OpenStack Identity (Keystone) Middleware
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

__init__.py 40KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002
  1. # Copyright 2010-2012 OpenStack Foundation
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  12. # implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. r"""
  16. Token-based Authentication Middleware.
  17. This WSGI component:
  18. * Verifies that incoming client requests have valid tokens by validating
  19. tokens with the auth service.
  20. * Rejects unauthenticated requests unless the auth_token middleware is in
  21. ``delay_auth_decision`` mode, which means the final decision is delegated to
  22. the downstream WSGI component (usually the OpenStack service).
  23. * Collects and forwards identity information based on a valid token
  24. such as user name, domain, project, etc.
  25. Refer to: https://docs.openstack.org/keystonemiddleware/latest/\
  26. middlewarearchitecture.html
  27. Headers
  28. -------
  29. The auth_token middleware uses headers sent in by the client on the request
  30. and sets headers and environment variables for the downstream WSGI component.
  31. Coming in from initial call from client or customer
  32. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  33. HTTP_X_AUTH_TOKEN
  34. The client token being passed in.
  35. HTTP_X_SERVICE_TOKEN
  36. A service token being passed in.
  37. Used for communication between components
  38. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  39. WWW-Authenticate
  40. HTTP header returned to a user indicating which endpoint to use
  41. to retrieve a new token.
  42. What auth_token adds to the request for use by the OpenStack service
  43. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  44. When using composite authentication (a user and service token are
  45. present) additional service headers relating to the service user
  46. will be added. They take the same form as the standard headers but add
  47. ``_SERVICE_``. These headers will not exist in the environment if no
  48. service token is present.
  49. HTTP_X_IDENTITY_STATUS, HTTP_X_SERVICE_IDENTITY_STATUS
  50. Will be set to either ``Confirmed`` or ``Invalid``.
  51. The underlying service will only see a value of 'Invalid' if the middleware
  52. is configured to run in ``delay_auth_decision`` mode. As with all such
  53. headers, ``HTTP_X_SERVICE_IDENTITY_STATUS`` will only exist in the
  54. environment if a service token is presented. This is different than
  55. ``HTTP_X_IDENTITY_STATUS`` which is always set even if no user token is
  56. presented. This allows the underlying service to determine if a
  57. denial should use ``401 Unauthenticated`` or ``403 Forbidden``.
  58. HTTP_OPENSTACK_SYSTEM_SCOPE
  59. A string relaying system information about the token's scope. This
  60. attribute is only present if the token is system-scoped. The string ``all``
  61. means the token is scoped to the entire deployment system.
  62. HTTP_X_DOMAIN_ID, HTTP_X_SERVICE_DOMAIN_ID
  63. Identity service managed unique identifier, string. Only present if
  64. this is a domain-scoped token.
  65. HTTP_X_DOMAIN_NAME, HTTP_X_SERVICE_DOMAIN_NAME
  66. Unique domain name, string. Only present if this is a domain-scoped
  67. token.
  68. HTTP_X_PROJECT_ID, HTTP_X_SERVICE_PROJECT_ID
  69. Identity service managed unique identifier, string. Only present if
  70. this is a project-scoped token.
  71. HTTP_X_PROJECT_NAME, HTTP_X_SERVICE_PROJECT_NAME
  72. Project name, unique within owning domain, string. Only present if
  73. this is a project-scoped token.
  74. HTTP_X_PROJECT_DOMAIN_ID, HTTP_X_SERVICE_PROJECT_DOMAIN_ID
  75. Identity service managed unique identifier of owning domain of
  76. project, string. Only present if this is a project-scoped v3 token. If
  77. this variable is set, this indicates that the PROJECT_NAME can only
  78. be assumed to be unique within this domain.
  79. HTTP_X_PROJECT_DOMAIN_NAME, HTTP_X_SERVICE_PROJECT_DOMAIN_NAME
  80. Name of owning domain of project, string. Only present if this is a
  81. project-scoped v3 token. If this variable is set, this indicates that
  82. the PROJECT_NAME can only be assumed to be unique within this domain.
  83. HTTP_X_USER_ID, HTTP_X_SERVICE_USER_ID
  84. Identity-service managed unique identifier, string.
  85. HTTP_X_USER_NAME, HTTP_X_SERVICE_USER_NAME
  86. User identifier, unique within owning domain, string.
  87. HTTP_X_USER_DOMAIN_ID, HTTP_X_SERVICE_USER_DOMAIN_ID
  88. Identity service managed unique identifier of owning domain of
  89. user, string. If this variable is set, this indicates that the USER_NAME
  90. can only be assumed to be unique within this domain.
  91. HTTP_X_USER_DOMAIN_NAME, HTTP_X_SERVICE_USER_DOMAIN_NAME
  92. Name of owning domain of user, string. If this variable is set, this
  93. indicates that the USER_NAME can only be assumed to be unique within
  94. this domain.
  95. HTTP_X_ROLES, HTTP_X_SERVICE_ROLES
  96. Comma delimited list of case-sensitive role names.
  97. HTTP_X_IS_ADMIN_PROJECT
  98. The string value 'True' or 'False' representing whether the user's token is
  99. scoped to the admin project. As historically there was no admin project
  100. this will default to True for tokens without this information to be
  101. backwards with existing policy files.
  102. HTTP_X_SERVICE_CATALOG
  103. service catalog (optional, JSON string).
  104. For compatibility reasons this catalog will always be in the V2 catalog
  105. format even if it is a v3 token.
  106. .. note:: This is an exception in that it contains 'SERVICE' but relates to
  107. a user token, not a service token. The existing user's catalog can be
  108. very large; it was decided not to present a catalog relating to the
  109. service token to avoid using more HTTP header space.
  110. HTTP_X_TENANT_ID
  111. *Deprecated* in favor of HTTP_X_PROJECT_ID.
  112. Identity service managed unique identifier, string. For v3 tokens, this
  113. will be set to the same value as HTTP_X_PROJECT_ID.
  114. HTTP_X_TENANT_NAME
  115. *Deprecated* in favor of HTTP_X_PROJECT_NAME.
  116. Project identifier, unique within owning domain, string. For v3 tokens,
  117. this will be set to the same value as HTTP_X_PROJECT_NAME.
  118. HTTP_X_TENANT
  119. *Deprecated* in favor of HTTP_X_TENANT_ID and HTTP_X_TENANT_NAME.
  120. Identity server-assigned unique identifier, string. For v3 tokens, this
  121. will be set to the same value as HTTP_X_PROJECT_ID.
  122. HTTP_X_USER
  123. *Deprecated* in favor of HTTP_X_USER_ID and HTTP_X_USER_NAME.
  124. User name, unique within owning domain, string.
  125. HTTP_X_ROLE
  126. *Deprecated* in favor of HTTP_X_ROLES.
  127. Will contain the same values as HTTP_X_ROLES.
  128. Environment Variables
  129. ^^^^^^^^^^^^^^^^^^^^^
  130. These variables are set in the request environment for use by the downstream
  131. WSGI component.
  132. keystone.token_info
  133. Information about the token discovered in the process of validation. This
  134. may include extended information returned by the token validation call, as
  135. well as basic information about the project and user.
  136. keystone.token_auth
  137. A keystoneauth1 auth plugin that may be used with a
  138. :py:class:`keystoneauth1.session.Session`. This plugin will load the
  139. authentication data provided to auth_token middleware.
  140. Configuration
  141. -------------
  142. auth_token middleware configuration can be in the main application's
  143. configuration file, e.g. in ``nova.conf``:
  144. .. code-block:: ini
  145. [keystone_authtoken]
  146. auth_plugin = password
  147. auth_url = http://keystone:35357/
  148. username = nova
  149. user_domain_id = default
  150. password = whyarewestillusingpasswords
  151. project_name = service
  152. project_domain_id = default
  153. Configuration can also be in the ``api-paste.ini`` file with the same options,
  154. but this is discouraged.
  155. Swift
  156. -----
  157. When deploy auth_token middleware with Swift, user may elect to use Swift
  158. memcache instead of the local auth_token memcache. Swift memcache is passed in
  159. from the request environment and it's identified by the ``swift.cache`` key.
  160. However it could be different, depending on deployment. To use Swift memcache,
  161. you must set the ``cache`` option to the environment key where the Swift cache
  162. object is stored.
  163. """
  164. import binascii
  165. import copy
  166. import datetime
  167. from keystoneauth1 import access
  168. from keystoneauth1 import adapter
  169. from keystoneauth1 import discover
  170. from keystoneauth1 import exceptions as ksa_exceptions
  171. from keystoneauth1 import loading
  172. from keystoneauth1.loading import session as session_loading
  173. from keystoneclient.common import cms
  174. from keystoneclient import exceptions as ksc_exceptions
  175. import oslo_cache
  176. from oslo_config import cfg
  177. from oslo_log import log as logging
  178. from oslo_serialization import jsonutils
  179. import webob.dec
  180. from keystonemiddleware._common import config
  181. from keystonemiddleware.auth_token import _auth
  182. from keystonemiddleware.auth_token import _base
  183. from keystonemiddleware.auth_token import _cache
  184. from keystonemiddleware.auth_token import _exceptions as ksm_exceptions
  185. from keystonemiddleware.auth_token import _identity
  186. from keystonemiddleware.auth_token import _opts
  187. from keystonemiddleware.auth_token import _request
  188. from keystonemiddleware.auth_token import _revocations
  189. from keystonemiddleware.auth_token import _signing_dir
  190. from keystonemiddleware.auth_token import _user_plugin
  191. from keystonemiddleware.i18n import _
  192. _LOG = logging.getLogger(__name__)
  193. _CACHE_INVALID_INDICATOR = 'invalid'
  194. oslo_cache.configure(cfg.CONF)
  195. AUTH_TOKEN_OPTS = [
  196. (_base.AUTHTOKEN_GROUP,
  197. _opts._OPTS + _auth.OPTS + loading.get_auth_common_conf_options())
  198. ]
  199. def list_opts():
  200. """Return a list of oslo_config options available in auth_token middleware.
  201. The returned list includes all oslo_config options which may be registered
  202. at runtime by the project.
  203. Each element of the list is a tuple. The first element is the name of the
  204. group under which the list of elements in the second element will be
  205. registered. A group name of None corresponds to the [DEFAULT] group in
  206. config files.
  207. NOTE: This function is no longer used for oslo_config sample generation.
  208. Some services rely on this function for listing ALL (including deprecated)
  209. options and registering them into their own config objects which we do not
  210. want for sample config files.
  211. See: :py:func:`keystonemiddleware.auth_token._opts.list_opts` for sample
  212. config files.
  213. :returns: a list of (group_name, opts) tuples
  214. """
  215. return [(g, copy.deepcopy(o)) for g, o in AUTH_TOKEN_OPTS]
  216. class _BIND_MODE(object):
  217. DISABLED = 'disabled'
  218. PERMISSIVE = 'permissive'
  219. STRICT = 'strict'
  220. REQUIRED = 'required'
  221. KERBEROS = 'kerberos'
  222. def _uncompress_pkiz(token):
  223. # TypeError If the signed_text is not zlib compressed binascii.Error if
  224. # signed_text has incorrect base64 padding (py34)
  225. try:
  226. return cms.pkiz_uncompress(token)
  227. except (TypeError, binascii.Error):
  228. raise ksm_exceptions.InvalidToken(token)
  229. class BaseAuthProtocol(object):
  230. """A base class for AuthProtocol token checking implementations.
  231. :param Callable app: The next application to call after middleware.
  232. :param logging.Logger log: The logging object to use for output. By default
  233. it will use a logger in the
  234. keystonemiddleware.auth_token namespace.
  235. :param str enforce_token_bind: The style of token binding enforcement to
  236. perform.
  237. """
  238. def __init__(self,
  239. app,
  240. log=_LOG,
  241. enforce_token_bind=_BIND_MODE.PERMISSIVE,
  242. service_token_roles=None,
  243. service_token_roles_required=False):
  244. self.log = log
  245. self._app = app
  246. self._enforce_token_bind = enforce_token_bind
  247. self._service_token_roles = set(service_token_roles or [])
  248. self._service_token_roles_required = service_token_roles_required
  249. self._service_token_warning_emitted = False
  250. @webob.dec.wsgify(RequestClass=_request._AuthTokenRequest)
  251. def __call__(self, req):
  252. """Handle incoming request."""
  253. response = self.process_request(req)
  254. if response:
  255. return response
  256. response = req.get_response(self._app)
  257. return self.process_response(response)
  258. def process_request(self, request):
  259. """Process request.
  260. If this method returns a value then that value will be used as the
  261. response. The next application down the stack will not be executed and
  262. process_response will not be called.
  263. Otherwise, the next application down the stack will be executed and
  264. process_response will be called with the generated response.
  265. By default this method does not return a value.
  266. :param request: Incoming request
  267. :type request: _request.AuthTokenRequest
  268. """
  269. user_auth_ref = None
  270. serv_auth_ref = None
  271. allow_expired = False
  272. if request.service_token:
  273. self.log.debug('Authenticating service token')
  274. try:
  275. _, serv_auth_ref = self._do_fetch_token(request.service_token)
  276. self._validate_token(serv_auth_ref)
  277. self._confirm_token_bind(serv_auth_ref, request)
  278. except ksm_exceptions.InvalidToken:
  279. self.log.info('Invalid service token')
  280. request.service_token_valid = False
  281. else:
  282. # FIXME(jamielennox): The new behaviour for service tokens is
  283. # that they have to pass the policy check to be allowed.
  284. # Previously any token was accepted here. For now we will
  285. # continue to mark service tokens as valid if they are valid
  286. # but we will only allow service role tokens to do
  287. # allow_expired. In future we should reject any token that
  288. # isn't a service token here.
  289. role_names = set(serv_auth_ref.role_names)
  290. check = self._service_token_roles.intersection(role_names)
  291. role_check_passed = bool(check)
  292. # if service_token_role_required then the service token is only
  293. # valid if the roles check out. Otherwise at this point it is
  294. # true because keystone has already validated it.
  295. if self._service_token_roles_required:
  296. request.service_token_valid = role_check_passed
  297. else:
  298. if not self._service_token_warning_emitted:
  299. self.log.warning('A valid token was submitted as '
  300. 'a service token, but it was not '
  301. 'a valid service token. This is '
  302. 'incorrect but backwards '
  303. 'compatible behaviour. This will '
  304. 'be removed in future releases.')
  305. # prevent log spam on every single request
  306. self._service_token_warning_emitted = True
  307. request.service_token_valid = True
  308. # allow_expired always requires passing the role check.
  309. allow_expired = role_check_passed
  310. if request.user_token:
  311. self.log.debug('Authenticating user token')
  312. try:
  313. data, user_auth_ref = self._do_fetch_token(
  314. request.user_token,
  315. allow_expired=allow_expired)
  316. self._validate_token(user_auth_ref,
  317. allow_expired=allow_expired)
  318. if not request.service_token:
  319. self._confirm_token_bind(user_auth_ref, request)
  320. except ksm_exceptions.InvalidToken:
  321. self.log.info('Invalid user token')
  322. request.user_token_valid = False
  323. else:
  324. request.user_token_valid = True
  325. request.token_info = data
  326. request.token_auth = _user_plugin.UserAuthPlugin(user_auth_ref,
  327. serv_auth_ref)
  328. def _validate_token(self, auth_ref, allow_expired=False):
  329. """Perform the validation steps on the token.
  330. :param auth_ref: The token data
  331. :type auth_ref: keystoneauth1.access.AccessInfo
  332. :raises exc.InvalidToken: if token is rejected
  333. """
  334. # 0 seconds of validity means it is invalid right now
  335. if (not allow_expired) and auth_ref.will_expire_soon(stale_duration=0):
  336. raise ksm_exceptions.InvalidToken(_('Token authorization failed'))
  337. def _do_fetch_token(self, token, **kwargs):
  338. """Helper method to fetch a token and convert it into an AccessInfo."""
  339. # NOTE(edmondsw): strip the token to remove any whitespace that may
  340. # have been passed along in the header per bug 1689468
  341. token = token.strip()
  342. data = self.fetch_token(token, **kwargs)
  343. try:
  344. return data, access.create(body=data, auth_token=token)
  345. except Exception:
  346. self.log.warning('Invalid token contents.', exc_info=True)
  347. raise ksm_exceptions.InvalidToken(_('Token authorization failed'))
  348. def fetch_token(self, token, **kwargs):
  349. """Fetch the token data based on the value in the header.
  350. Retrieve the data associated with the token value that was in the
  351. header. This can be from PKI, contacting the identity server or
  352. whatever is required.
  353. :param str token: The token present in the request header.
  354. :param dict kwargs: Additional keyword arguments may be passed through
  355. here to support new features. If an implementation
  356. is not aware of how to use these arguments it
  357. should ignore them.
  358. :raises exc.InvalidToken: if token is invalid.
  359. :returns: The token data
  360. :rtype: dict
  361. """
  362. raise NotImplementedError()
  363. def process_response(self, response):
  364. """Do whatever you'd like to the response.
  365. By default the response is returned unmodified.
  366. :param response: Response object
  367. :type response: ._request._AuthTokenResponse
  368. """
  369. return response
  370. def _invalid_user_token(self, msg=False):
  371. # NOTE(jamielennox): use False as the default so that None is valid
  372. if msg is False:
  373. msg = _('Token authorization failed')
  374. raise ksm_exceptions.InvalidToken(msg)
  375. def _confirm_token_bind(self, auth_ref, req):
  376. if self._enforce_token_bind == _BIND_MODE.DISABLED:
  377. return
  378. # permissive and strict modes don't require there to be a bind
  379. permissive = self._enforce_token_bind in (_BIND_MODE.PERMISSIVE,
  380. _BIND_MODE.STRICT)
  381. if not auth_ref.bind:
  382. if permissive:
  383. # no bind provided and none required
  384. return
  385. else:
  386. self.log.info('No bind information present in token.')
  387. self._invalid_user_token()
  388. # get the named mode if bind_mode is not one of the predefined
  389. if permissive or self._enforce_token_bind == _BIND_MODE.REQUIRED:
  390. name = None
  391. else:
  392. name = self._enforce_token_bind
  393. if name and name not in auth_ref.bind:
  394. self.log.info('Named bind mode %s not in bind information',
  395. name)
  396. self._invalid_user_token()
  397. for bind_type, identifier in auth_ref.bind.items():
  398. if bind_type == _BIND_MODE.KERBEROS:
  399. if req.auth_type != 'negotiate':
  400. self.log.info('Kerberos credentials required and '
  401. 'not present.')
  402. self._invalid_user_token()
  403. if req.remote_user != identifier:
  404. self.log.info('Kerberos credentials do not match '
  405. 'those in bind.')
  406. self._invalid_user_token()
  407. self.log.debug('Kerberos bind authentication successful.')
  408. elif self._enforce_token_bind == _BIND_MODE.PERMISSIVE:
  409. self.log.debug('Ignoring Unknown bind for permissive mode: '
  410. '%(bind_type)s: %(identifier)s.',
  411. {'bind_type': bind_type,
  412. 'identifier': identifier})
  413. else:
  414. self.log.info(
  415. 'Couldn`t verify unknown bind: %(bind_type)s: '
  416. '%(identifier)s.',
  417. {'bind_type': bind_type, 'identifier': identifier})
  418. self._invalid_user_token()
  419. class AuthProtocol(BaseAuthProtocol):
  420. """Middleware that handles authenticating client calls."""
  421. _SIGNING_CERT_FILE_NAME = 'signing_cert.pem'
  422. _SIGNING_CA_FILE_NAME = 'cacert.pem'
  423. def __init__(self, app, conf):
  424. log = logging.getLogger(conf.get('log_name', __name__))
  425. log.info('Starting Keystone auth_token middleware')
  426. self._conf = config.Config('auth_token',
  427. _base.AUTHTOKEN_GROUP,
  428. list_opts(),
  429. conf)
  430. if self._conf.oslo_conf_obj != cfg.CONF:
  431. oslo_cache.configure(self._conf.oslo_conf_obj)
  432. token_roles_required = self._conf.get('service_token_roles_required')
  433. if not token_roles_required:
  434. log.warning('AuthToken middleware is set with '
  435. 'keystone_authtoken.service_token_roles_required '
  436. 'set to False. This is backwards compatible but '
  437. 'deprecated behaviour. Please set this to True.')
  438. super(AuthProtocol, self).__init__(
  439. app,
  440. log=log,
  441. enforce_token_bind=self._conf.get('enforce_token_bind'),
  442. service_token_roles=self._conf.get('service_token_roles'),
  443. service_token_roles_required=token_roles_required)
  444. # delay_auth_decision means we still allow unauthenticated requests
  445. # through and we let the downstream service make the final decision
  446. self._delay_auth_decision = self._conf.get('delay_auth_decision')
  447. self._include_service_catalog = self._conf.get(
  448. 'include_service_catalog')
  449. self._hash_algorithms = self._conf.get('hash_algorithms')
  450. self._auth = self._create_auth_plugin()
  451. self._session = self._create_session()
  452. self._identity_server = self._create_identity_server()
  453. self._www_authenticate_uri = self._conf.get('www_authenticate_uri')
  454. if not self._www_authenticate_uri:
  455. self._www_authenticate_uri = self._conf.get('auth_uri')
  456. if not self._www_authenticate_uri:
  457. self.log.warning(
  458. 'Configuring www_authenticate_uri to point to the public '
  459. 'identity endpoint is required; clients may not be able to '
  460. 'authenticate against an admin endpoint')
  461. # FIXME(dolph): drop support for this fallback behavior as
  462. # documented in bug 1207517.
  463. self._www_authenticate_uri = \
  464. self._identity_server.www_authenticate_uri
  465. self._signing_directory = _signing_dir.SigningDirectory(
  466. directory_name=self._conf.get('signing_dir'), log=self.log)
  467. self._token_cache = self._token_cache_factory()
  468. revocation_cache_timeout = datetime.timedelta(
  469. seconds=self._conf.get('revocation_cache_time'))
  470. self._revocations = _revocations.Revocations(revocation_cache_timeout,
  471. self._signing_directory,
  472. self._identity_server,
  473. self._cms_verify,
  474. self.log)
  475. self._check_revocations_for_cached = self._conf.get(
  476. 'check_revocations_for_cached')
  477. def process_request(self, request):
  478. """Process request.
  479. Evaluate the headers in a request and attempt to authenticate the
  480. request. If authenticated then additional headers are added to the
  481. request for use by applications. If not authenticated the request will
  482. be rejected or marked unauthenticated depending on configuration.
  483. """
  484. request.remove_auth_headers()
  485. self._token_cache.initialize(request.environ)
  486. resp = super(AuthProtocol, self).process_request(request)
  487. if resp:
  488. return resp
  489. if not request.user_token:
  490. # if no user token is present then that's an invalid request
  491. request.user_token_valid = False
  492. # NOTE(jamielennox): The service status is allowed to be missing if a
  493. # service token is not passed. If the service status is missing that's
  494. # a valid request. We should find a better way to expose this from the
  495. # request object.
  496. user_status = request.user_token and request.user_token_valid
  497. service_status = request.headers.get('X-Service-Identity-Status',
  498. 'Confirmed')
  499. if not (user_status and service_status == 'Confirmed'):
  500. if self._delay_auth_decision:
  501. self.log.debug('Deferring reject downstream')
  502. else:
  503. self.log.info('Rejecting request')
  504. message = _('The request you have made requires '
  505. 'authentication.')
  506. body = {'error': {
  507. 'code': 401,
  508. 'title': 'Unauthorized',
  509. 'message': message,
  510. }}
  511. raise webob.exc.HTTPUnauthorized(
  512. body=jsonutils.dumps(body),
  513. headers=self._reject_auth_headers,
  514. charset='UTF-8',
  515. content_type='application/json')
  516. if request.user_token_valid:
  517. request.set_user_headers(request.token_auth.user)
  518. if self._include_service_catalog:
  519. request.set_service_catalog_headers(request.token_auth.user)
  520. if request.token_auth:
  521. request.token_auth._auth = self._auth
  522. request.token_auth._session = self._session
  523. if request.service_token and request.service_token_valid:
  524. request.set_service_headers(request.token_auth.service)
  525. if self.log.isEnabledFor(logging.DEBUG):
  526. self.log.debug('Received request from %s',
  527. request.token_auth._log_format)
  528. def process_response(self, response):
  529. """Process Response.
  530. Add ``WWW-Authenticate`` headers to requests that failed with
  531. ``401 Unauthenticated`` so users know where to authenticate for future
  532. requests.
  533. """
  534. if response.status_int == 401:
  535. response.headers.extend(self._reject_auth_headers)
  536. return response
  537. @property
  538. def _reject_auth_headers(self):
  539. header_val = 'Keystone uri="%s"' % self._www_authenticate_uri
  540. return [('WWW-Authenticate', header_val)]
  541. def _token_hashes(self, token):
  542. """Generate a list of hashes that the current token may be cached as.
  543. With PKI tokens we have multiple hashing algorithms that we test with
  544. revocations. This generates that whole list.
  545. The first element of this list is the preferred algorithm and is what
  546. new cache values should be saved as.
  547. :param str token: The token being presented by a user.
  548. :returns: list of str token hashes.
  549. """
  550. if cms.is_asn1_token(token) or cms.is_pkiz(token):
  551. return list(cms.cms_hash_token(token, mode=algo)
  552. for algo in self._hash_algorithms)
  553. else:
  554. return [token]
  555. def _cache_get_hashes(self, token_hashes):
  556. """Check if the token is cached already.
  557. Functions takes a list of hashes that might be in the cache and matches
  558. the first one that is present. If nothing is found in the cache it
  559. returns None.
  560. :returns: token data if found else None.
  561. """
  562. for token in token_hashes:
  563. cached = self._token_cache.get(token)
  564. if cached:
  565. return cached
  566. def fetch_token(self, token, allow_expired=False):
  567. """Retrieve a token from either a PKI bundle or the identity server.
  568. :param str token: token id
  569. :raises exc.InvalidToken: if token is rejected
  570. """
  571. data = None
  572. token_hashes = None
  573. try:
  574. token_hashes = self._token_hashes(token)
  575. cached = self._cache_get_hashes(token_hashes)
  576. if cached:
  577. if cached == _CACHE_INVALID_INDICATOR:
  578. self.log.debug('Cached token is marked unauthorized')
  579. raise ksm_exceptions.InvalidToken()
  580. if self._check_revocations_for_cached:
  581. # A token might have been revoked, regardless of initial
  582. # mechanism used to validate it, and needs to be checked.
  583. self._revocations.check(token_hashes)
  584. # NOTE(jamielennox): Cached values used to be stored as a tuple
  585. # of data and expiry time. They no longer are but we have to
  586. # allow some time to transition the old format so if it's a
  587. # tuple just use the data.
  588. if len(cached) == 2:
  589. cached = cached[0]
  590. data = cached
  591. else:
  592. data = self._validate_offline(token, token_hashes)
  593. if not data:
  594. data = self._identity_server.verify_token(
  595. token,
  596. allow_expired=allow_expired)
  597. self._token_cache.set(token_hashes[0], data)
  598. except (ksa_exceptions.ConnectFailure,
  599. ksa_exceptions.RequestTimeout,
  600. ksm_exceptions.RevocationListError,
  601. ksm_exceptions.ServiceError) as e:
  602. self.log.critical('Unable to validate token: %s', e)
  603. raise webob.exc.HTTPServiceUnavailable(
  604. 'The Keystone service is temporarily unavailable.')
  605. except ksm_exceptions.InvalidToken:
  606. self.log.debug('Token validation failure.', exc_info=True)
  607. if token_hashes:
  608. self._token_cache.set(token_hashes[0],
  609. _CACHE_INVALID_INDICATOR)
  610. self.log.warning('Authorization failed for token')
  611. raise
  612. return data
  613. def _validate_offline(self, token, token_hashes):
  614. if cms.is_pkiz(token):
  615. token_data = _uncompress_pkiz(token)
  616. inform = cms.PKIZ_CMS_FORM
  617. elif cms.is_asn1_token(token):
  618. token_data = cms.token_to_cms(token)
  619. inform = cms.PKI_ASN1_FORM
  620. else:
  621. # Can't do offline validation for this type of token.
  622. return
  623. try:
  624. self._revocations.check(token_hashes)
  625. verified = self._cms_verify(token_data, inform)
  626. except ksc_exceptions.CertificateConfigError:
  627. self.log.warning('Fetch certificate config failed, '
  628. 'fallback to online validation.')
  629. except ksm_exceptions.RevocationListError:
  630. self.log.warning('Fetch revocation list failed, '
  631. 'fallback to online validation.')
  632. else:
  633. self.log.warning('auth_token middleware received a PKI/Z token. '
  634. 'This form of token is deprecated and has been '
  635. 'removed from keystone server and will be '
  636. 'removed from auth_token middleware in the Rocky '
  637. 'release. Please contact your administrator '
  638. 'about upgrading keystone and the token format.')
  639. data = jsonutils.loads(verified)
  640. audit_ids = None
  641. if 'access' in data:
  642. # It's a v2 token.
  643. audit_ids = data['access']['token'].get('audit_ids')
  644. else:
  645. # It's a v3 token
  646. audit_ids = data['token'].get('audit_ids')
  647. if audit_ids:
  648. self._revocations.check_by_audit_id(audit_ids)
  649. return data
  650. def _validate_token(self, auth_ref, **kwargs):
  651. super(AuthProtocol, self)._validate_token(auth_ref, **kwargs)
  652. if auth_ref.version == 'v2.0' and not auth_ref.project_id:
  653. msg = _('Unable to determine service tenancy.')
  654. raise ksm_exceptions.InvalidToken(msg)
  655. def _cms_verify(self, data, inform=cms.PKI_ASN1_FORM):
  656. """Verify the signature of the provided data's IAW CMS syntax.
  657. If either of the certificate files might be missing, fetch them and
  658. retry.
  659. """
  660. def verify():
  661. try:
  662. signing_cert_path = self._signing_directory.calc_path(
  663. self._SIGNING_CERT_FILE_NAME)
  664. signing_ca_path = self._signing_directory.calc_path(
  665. self._SIGNING_CA_FILE_NAME)
  666. return cms.cms_verify(data, signing_cert_path,
  667. signing_ca_path,
  668. inform=inform).decode('utf-8')
  669. except (ksc_exceptions.CMSError,
  670. cms.subprocess.CalledProcessError) as err:
  671. self.log.warning('Verify error: %s', err)
  672. msg = _('Token authorization failed')
  673. raise ksm_exceptions.InvalidToken(msg)
  674. try:
  675. return verify()
  676. except ksc_exceptions.CertificateConfigError:
  677. # the certs might be missing; unconditionally fetch to avoid racing
  678. self._fetch_signing_cert()
  679. self._fetch_ca_cert()
  680. try:
  681. # retry with certs in place
  682. return verify()
  683. except ksc_exceptions.CertificateConfigError as err:
  684. # if this is still occurring, something else is wrong and we
  685. # need err.output to identify the problem
  686. self.log.error('CMS Verify output: %s', err.output)
  687. raise
  688. def _fetch_signing_cert(self):
  689. self._signing_directory.write_file(
  690. self._SIGNING_CERT_FILE_NAME,
  691. self._identity_server.fetch_signing_cert())
  692. def _fetch_ca_cert(self):
  693. self._signing_directory.write_file(
  694. self._SIGNING_CA_FILE_NAME,
  695. self._identity_server.fetch_ca_cert())
  696. def _create_auth_plugin(self):
  697. # NOTE(jamielennox): Ideally this would use load_from_conf_options
  698. # however that is not possible because we have to support the override
  699. # pattern we use in _conf.get. This function therefore does a manual
  700. # version of load_from_conf_options with the fallback plugin inline.
  701. group = self._conf.get('auth_section') or _base.AUTHTOKEN_GROUP
  702. # NOTE(jamielennox): auth_plugin was deprecated to auth_type. _conf.get
  703. # doesn't handle that deprecation in the case of conf dict options so
  704. # we have to manually check the value
  705. plugin_name = (self._conf.get('auth_type', group=group)
  706. or self._conf.paste_overrides.get('auth_plugin'))
  707. if not plugin_name:
  708. return _auth.AuthTokenPlugin(
  709. log=self.log,
  710. auth_admin_prefix=self._conf.get('auth_admin_prefix',
  711. group=group),
  712. auth_host=self._conf.get('auth_host', group=group),
  713. auth_port=self._conf.get('auth_port', group=group),
  714. auth_protocol=self._conf.get('auth_protocol', group=group),
  715. identity_uri=self._conf.get('identity_uri', group=group),
  716. admin_token=self._conf.get('admin_token', group=group),
  717. admin_user=self._conf.get('admin_user', group=group),
  718. admin_password=self._conf.get('admin_password', group=group),
  719. admin_tenant_name=self._conf.get('admin_tenant_name',
  720. group=group)
  721. )
  722. # Plugin option registration is normally done as part of the load_from
  723. # function rather than the register function so copy here.
  724. plugin_loader = loading.get_plugin_loader(plugin_name)
  725. plugin_opts = loading.get_auth_plugin_conf_options(plugin_loader)
  726. self._conf.oslo_conf_obj.register_opts(plugin_opts, group=group)
  727. getter = lambda opt: self._conf.get(opt.dest, group=group)
  728. return plugin_loader.load_from_options_getter(getter)
  729. def _create_session(self, **kwargs):
  730. # NOTE(jamielennox): Loading Session here should be exactly the
  731. # same as calling Session.load_from_conf_options(CONF, GROUP)
  732. # however we can't do that because we have to use _conf.get to
  733. # support the paste.ini options.
  734. kwargs.setdefault('cert', self._conf.get('certfile'))
  735. kwargs.setdefault('key', self._conf.get('keyfile'))
  736. kwargs.setdefault('cacert', self._conf.get('cafile'))
  737. kwargs.setdefault('insecure', self._conf.get('insecure'))
  738. kwargs.setdefault('timeout', self._conf.get('http_connect_timeout'))
  739. kwargs.setdefault('user_agent', self._conf.user_agent)
  740. return session_loading.Session().load_from_options(**kwargs)
  741. def _create_identity_server(self):
  742. adap = adapter.Adapter(
  743. self._session,
  744. auth=self._auth,
  745. service_type='identity',
  746. interface='admin',
  747. region_name=self._conf.get('region_name'),
  748. connect_retries=self._conf.get('http_request_max_retries'))
  749. auth_version = self._conf.get('auth_version')
  750. if auth_version is not None:
  751. auth_version = discover.normalize_version_number(auth_version)
  752. return _identity.IdentityServer(
  753. self.log,
  754. adap,
  755. include_service_catalog=self._include_service_catalog,
  756. requested_auth_version=auth_version)
  757. def _create_oslo_cache(self):
  758. # having this as a function makes test mocking easier
  759. region = oslo_cache.create_region()
  760. oslo_cache.configure_cache_region(self._conf.oslo_conf_obj, region)
  761. return region
  762. def _token_cache_factory(self):
  763. security_strategy = self._conf.get('memcache_security_strategy')
  764. cache_kwargs = dict(
  765. cache_time=int(self._conf.get('token_cache_time')),
  766. env_cache_name=self._conf.get('cache'),
  767. memcached_servers=self._conf.get('memcached_servers'),
  768. use_advanced_pool=self._conf.get('memcache_use_advanced_pool'),
  769. dead_retry=self._conf.get('memcache_pool_dead_retry'),
  770. maxsize=self._conf.get('memcache_pool_maxsize'),
  771. unused_timeout=self._conf.get('memcache_pool_unused_timeout'),
  772. conn_get_timeout=self._conf.get('memcache_pool_conn_get_timeout'),
  773. socket_timeout=self._conf.get('memcache_pool_socket_timeout'),
  774. )
  775. if security_strategy.lower() != 'none':
  776. secret_key = self._conf.get('memcache_secret_key')
  777. return _cache.SecureTokenCache(self.log,
  778. security_strategy,
  779. secret_key,
  780. **cache_kwargs)
  781. else:
  782. return _cache.TokenCache(self.log, **cache_kwargs)
  783. def filter_factory(global_conf, **local_conf):
  784. """Return a WSGI filter app for use with paste.deploy."""
  785. conf = global_conf.copy()
  786. conf.update(local_conf)
  787. def auth_filter(app):
  788. return AuthProtocol(app, conf)
  789. return auth_filter
  790. def app_factory(global_conf, **local_conf):
  791. conf = global_conf.copy()
  792. conf.update(local_conf)
  793. return AuthProtocol(None, conf)
  794. # NOTE(jamielennox): Maintained here for public API compatibility.
  795. InvalidToken = ksm_exceptions.InvalidToken
  796. ServiceError = ksm_exceptions.ServiceError
  797. ConfigurationError = ksm_exceptions.ConfigurationError
  798. RevocationListError = ksm_exceptions.RevocationListError