Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010-2012 OpenStack LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License.
TOKEN-BASED AUTH MIDDLEWARE
This WSGI component:
* Verifies that incoming client requests have valid tokens by validating tokens with the auth service. * Rejects unauthenticated requests UNLESS it is in 'delay_auth_decision' mode, which means the final decision is delegated to the downstream WSGI component (usually the OpenStack service) * Collects and forwards identity information based on a valid token such as user name, tenant, etc
Refer to: http://keystone.openstack.org/middlewarearchitecture.html
HEADERS -------
* Headers starting with HTTP\_ is a standard http header * Headers starting with HTTP_X is an extended http header
Coming in from initial call from client or customer ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
HTTP_X_AUTH_TOKEN The client token being passed in.
HTTP_X_STORAGE_TOKEN The client token being passed in (legacy Rackspace use) to support swift/cloud files
Used for communication between components ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
WWW-Authenticate HTTP header returned to a user indicating which endpoint to use to retrieve a new token
What we add to the request for use by the OpenStack service ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
HTTP_X_IDENTITY_STATUS 'Confirmed' or 'Invalid' The underlying service will only see a value of 'Invalid' if the Middleware is configured to run in 'delay_auth_decision' mode
HTTP_X_DOMAIN_ID Identity service managed unique identifier, string. Only present if this is a domain-scoped v3 token.
HTTP_X_DOMAIN_NAME Unique domain name, string. Only present if this is a domain-scoped v3 token.
HTTP_X_PROJECT_ID Identity service managed unique identifier, string. Only present if this is a project-scoped v3 token, or a tenant-scoped v2 token.
HTTP_X_PROJECT_NAME Project name, unique within owning domain, string. Only present if this is a project-scoped v3 token, or a tenant-scoped v2 token.
HTTP_X_PROJECT_DOMAIN_ID Identity service managed unique identifier of owning domain of project, string. Only present if this is a project-scoped v3 token. If this variable is set, this indicates that the PROJECT_NAME can only be assumed to be unique within this domain.
HTTP_X_PROJECT_DOMAIN_NAME Name of owning domain of project, string. Only present if this is a project-scoped v3 token. If this variable is set, this indicates that the PROJECT_NAME can only be assumed to be unique within this domain.
HTTP_X_USER_ID Identity-service managed unique identifier, string
HTTP_X_USER_NAME User identifier, unique within owning domain, string
HTTP_X_USER_DOMAIN_ID Identity service managed unique identifier of owning domain of user, string. If this variable is set, this indicates that the USER_NAME can only be assumed to be unique within this domain.
HTTP_X_USER_DOMAIN_NAME Name of owning domain of user, string. If this variable is set, this indicates that the USER_NAME can only be assumed to be unique within this domain.
HTTP_X_ROLES Comma delimited list of case-sensitive role names
HTTP_X_SERVICE_CATALOG json encoded keystone service catalog (optional).
HTTP_X_TENANT_ID *Deprecated* in favor of HTTP_X_PROJECT_ID Identity service managed unique identifier, string. For v3 tokens, this will be set to the same value as HTTP_X_PROJECT_ID
HTTP_X_TENANT_NAME *Deprecated* in favor of HTTP_X_PROJECT_NAME Project identifier, unique within owning domain, string. For v3 tokens, this will be set to the same value as HTTP_X_PROJECT_NAME
HTTP_X_TENANT *Deprecated* in favor of HTTP_X_TENANT_ID and HTTP_X_TENANT_NAME Keystone-assigned unique identifier, string. For v3 tokens, this will be set to the same value as HTTP_X_PROJECT_ID
HTTP_X_USER *Deprecated* in favor of HTTP_X_USER_ID and HTTP_X_USER_NAME User name, unique within owning domain, string
HTTP_X_ROLE *Deprecated* in favor of HTTP_X_ROLES Will contain the same values as HTTP_X_ROLES.
OTHER ENVIRONMENT VARIABLES ---------------------------
keystone.token_info Information about the token discovered in the process of validation. This may include extended information returned by the Keystone token validation call, as well as basic information about the tenant and user.
"""
# to pass gate before oslo-config is deployed everywhere, # try application copies first fromlist=['%s.openstack.common' % app]) # test which application middleware is running in if hasattr(cfg, 'CONF') and 'config_file' in cfg.CONF: CONF = cfg.CONF break
# alternative middleware configuration in the main application's # configuration file e.g. in nova.conf # [keystone_authtoken] # auth_host = 127.0.0.1 # auth_port = 35357 # auth_protocol = http # admin_tenant_name = admin # admin_user = admin # admin_password = badpassword
# when deploy Keystone auth_token middleware with Swift, user may elect # to use Swift memcache instead of the local Keystone memcache. Swift memcache # is passed in from the request environment and its identified by the # 'swift.cache' key. However it could be different, depending on deployment. # To use Swift memcache, you must set the 'cache' option to the environment # key where the Swift cache object is stored. cfg.StrOpt('auth_admin_prefix', default=''), cfg.StrOpt('auth_host', default='127.0.0.1'), cfg.IntOpt('auth_port', default=35357), cfg.StrOpt('auth_protocol', default='https'), cfg.StrOpt('auth_uri', default=None), cfg.StrOpt('auth_version', default=None), cfg.BoolOpt('delay_auth_decision', default=False), cfg.BoolOpt('http_connect_timeout', default=None), cfg.StrOpt('http_handler', default=None), cfg.StrOpt('admin_token', secret=True), cfg.StrOpt('admin_user'), cfg.StrOpt('admin_password', secret=True), cfg.StrOpt('admin_tenant_name', default='admin'), cfg.StrOpt('cache', default=None), # env key for the swift cache cfg.StrOpt('certfile'), cfg.StrOpt('keyfile'), cfg.StrOpt('signing_dir'), cfg.ListOpt('memcache_servers'), cfg.IntOpt('token_cache_time', default=300), cfg.IntOpt('revocation_cache_time', default=1), cfg.StrOpt('memcache_security_strategy', default=None), cfg.StrOpt('memcache_secret_key', default=None, secret=True) ]
""" Determines if expiration is about to occur.
:param expiry: a datetime of the expected expiration :returns: boolean : true if expiration is within 30 seconds """
"""URL-encode strings that are not already URL-encoded."""
"""Auth Middleware that handles authenticating client calls."""
# delay_auth_decision means we still allow unauthenticated requests # through and we let the downstream service make the final decision (True, 'true', 't', '1', 'on', 'yes', 'y'))
# where to find the auth service (we use this to validate tokens) self.http_client_class = httplib.HTTPConnection else: else: # Really only used for unit testing, since we need to # have a fake handler set up before we issue an http # request to get the list of versions supported by the # server at the end of this initialization
self.auth_host, self.auth_port)
# SSL
# signing self.signing_dirname) raise ConfigurationError( 'unable to access signing_dir %s' % self.signing_dirname) self.LOG.warning( 'signing_dir is not owned by %s' % os.getlogin()) self.LOG.warning( 'signing_dir mode is %s instead of %s' % (oct(current_mode), oct(stat.S_IRWXU))) else: os.makedirs(self.signing_dirname, stat.S_IRWXU)
# Credentials used to verify this component with the Auth service since # validating tokens is a privileged call
# Token caching via memcache # memcache value treatment, ENCRYPT or MAC self._conf_get('memcache_security_strategy') self._memcache_security_strategy.upper() self._conf_get('memcache_secret_key') # By default the token will be cached for 5 minutes seconds=self._conf_get('revocation_cache_time')) int(http_connect_timeout_cfg))
raise Exception('memcache_security_strategy must be ' 'ENCRYPT or MAC') raise Exception('mecmache_secret_key must be defined when ' 'a memcache_security_strategy is defined')
# use the cache from the upstream filter else: # use Keystone memcache
# try config from paste-deploy first else:
""" Determine the api version that we should use."""
# If the configuration specifies an auth_version we will just # assume that is correct and use it. We could, of course, check # that this version is supported by the server, but in case # there are some problems in the field, we want as little code # as possible in the way of letting auth_token talk to the # server. version_to_use) else: version_to_use) else: self.LOG.error( 'Attempted versions [%s] not in list supported by ' 'server [%s]', ', '.join(LIST_OF_VERSIONS_TO_ATTEMPT), ', '.join(versions_supported_by_server)) raise ServiceError('No compatible apis supported by server')
self.LOG.error('Unable to get version info from keystone: %s' % response.status) raise ServiceError('Unable to get version info from keystone') else: except KeyError: self.LOG.error( 'Invalid version response format from server', data) raise ServiceError('Unable to parse version response ' 'from keystone')
', '.join(versions))
"""Handle incoming request.
Authenticate send downstream on success. Reject request if we can't authenticate.
"""
# initialize memcache if we haven't done so
self.LOG.info( 'Invalid user token - deferring reject downstream') self._add_headers(env, {'X-Identity-Status': 'Invalid'}) return self.app(env, start_response) else:
except ServiceError as e: self.LOG.critical('Unable to obtain admin token: %s' % e) resp = webob.exc.HTTPServiceUnavailable() return resp(env, start_response)
"""Remove headers so a user can't fake authentication.
:param env: wsgi request environment
""" 'X-Identity-Status', 'X-Domain-Id', 'X-Domain-Name', 'X-Project-Id', 'X-Project-Name', 'X-Project-Domain-Id', 'X-Project-Domain-Name', 'X-User-Id', 'X-User-Name', 'X-User-Domain-Id', 'X-User-Domain-Name', 'X-Roles', 'X-Service-Catalog', # Deprecated 'X-User', 'X-Tenant-Id', 'X-Tenant-Name', 'X-Tenant', 'X-Role', ) ','.join(auth_headers))
"""Get token id from request.
:param env: wsgi request environment :return token id :raises InvalidUserToken if no token is provided in request
""" self._get_header(env, 'X-Storage-Token')) else: " in headers")
"""Redirect client to auth server.
:param env: wsgi request environment :param start_response: wsgi response callback :returns HTTPUnauthorized http response
"""
"""Return admin token, possibly fetching a new one.
if self.admin_token_expiry is set from fetching an admin token, check it for expiration, and request a new token is the existing token is about to expire.
:return admin token id :raise ServiceError when unable to retrieve token from keystone
""" if will_expire_soon(self.admin_token_expiry): self.admin_token = None
self.admin_token_expiry) = self._request_admin_token()
return self.http_client_class(self.auth_host, self.auth_port, timeout=self.http_connect_timeout) else: self.auth_port, self.key_file, self.cert_file, timeout=self.http_connect_timeout)
"""HTTP request helper used to make unspecified content type requests.
:param method: http method :param path: relative request url :return (http response object, response body) :raise ServerError when unable to communicate with keystone
"""
except Exception as e: if retry == RETRIES: self.LOG.error('HTTP connection exception: %s' % e) raise ServiceError('Unable to communicate with keystone') # NOTE(vish): sleep 0.5, 1, 2 self.LOG.warn('Retrying on HTTP connection exception: %s' % e) time.sleep(2.0 ** retry / 2) retry += 1 finally:
"""HTTP request helper used to make json requests.
:param method: http method :param path: relative request url :param body: dict to encode to json as request body. Optional. :param additional_headers: dict of additional headers to send with http request. Optional. :return (http response object, response body parsed as json) :raise ServerError when unable to communicate with keystone
""" 'headers': { 'Content-type': 'application/json', 'Accept': 'application/json', }, }
"""Retrieve new token as admin user from keystone.
:return token id upon success :raises ServerError when unable to communicate with keystone
Irrespective of the auth version we are going to use for the user token, for simplicity we always use a v2 admin token to validate the user token.
""" 'auth': { 'passwordCredentials': { 'username': self.admin_user, 'password': self.admin_password, }, 'tenantName': self.admin_tenant_name, } }
'/v2.0/tokens', body=params)
except (AssertionError, KeyError): self.LOG.warn( "Unexpected response from keystone service: %s", data) raise ServiceError('invalid json response') except (ValueError): self.LOG.warn( "Unable to parse expiration time from token: %s", data) raise ServiceError('invalid json response')
"""Authenticate user using PKI
:param user_token: user's token id :param retry: Ignored, as it is not longer relevant :return uncrypted body of the token if the token is valid :raise InvalidUserToken if token is rejected :no longer raises ServiceError since it no longer makes RPC
""" return cached else:
"""Convert token object into headers.
Build headers that represent authenticated user - see main doc info at start of file for details of headers to be defined.
:param token_info: token object returned by keystone on authentication :raise InvalidUserToken when unable to parse token object
""" """Returns a (tenant_id, tenant_name) tuple from context.""" """Essex puts the tenant ID and name on the token."""
"""Pre-diablo, Keystone only provided tenantId."""
"""Pre-grizzly, assume the user's default tenant."""
# For clarity. set all those attributes that are optional in # either a v2 or v3 token to None first
else: #v3 token for role in token.get('roles', [])])) # For v3, the server will put in the default project if there is # one, so no need for us to add it here (like we do for a v2 token)
'X-Identity-Status': 'Confirmed', 'X-Domain-Id': domain_id, 'X-Domain-Name': domain_name, 'X-Project-Id': project_id, 'X-Project-Name': project_name, 'X-Project-Domain-Id': project_domain_id, 'X-Project-Domain-Name': project_domain_name, 'X-User-Id': user_id, 'X-User-Name': user_name, 'X-User-Domain-Id': user_domain_id, 'X-User-Domain-Name': user_domain_name, 'X-Roles': roles, # Deprecated 'X-User': user_name, 'X-Tenant-Id': project_id, 'X-Tenant-Name': project_name, 'X-Tenant': project_name, 'X-Role': roles, }
"""Convert header to wsgi env variable.
:param key: http header name (ex. 'X-Auth-Token') :return wsgi env variable name (ex. 'HTTP_X_AUTH_TOKEN')
"""
"""Add http headers to environment."""
"""Remove http headers from environment."""
"""Get http header from environment."""
""" Encrypt or sign data if necessary. """ self._memcache_secret_key, data) else: except: msg = 'Failed to encrypt/sign cache data.' self.LOG.exception(msg) return data
""" Decrypt or verify signed data if necessary. """
self._memcache_secret_key, data) else: # this should have the same effect as data not found in cache
""" Return the cache key.
Do not use clear token as key if memcache protection is on.
"""
"""Return token information from cache.
If token is invalid raise InvalidUserToken return token only if fresh (not expired). """ self.LOG.debug('Cached Token %s is marked unauthorized', token) raise InvalidUserToken('Token authorization failed') data, expires = cached if time.time() < float(expires): self.LOG.debug('Returning cached token %s', token) return data else: self.LOG.debug('Cached Token %s seems expired', token)
""" Store value into memcache. """ # we need to special-case set() because of the incompatibility between # Swift MemcacheRing and python-memcached. See # https://bugs.launchpad.net/swift/+bug/1095730 data_to_store, time=self.token_cache_time) else: self._cache.set(key, data_to_store, timeout=self.token_cache_time)
raise InvalidUserToken('Token authorization failed') else: raise InvalidUserToken('Token authorization failed')
""" Put token data into the cache.
Stores the parsed expire date in cache allowing quick check of token freshness on retrieval.
"""
"""Store invalid token in cache.""" 'Marking token %s as unauthorized in memcache', token)
"""Authenticate user token with keystone.
:param user_token: user's token id :param retry: flag that forces the middleware to retry user authentication when an indeterminate response is received. Optional. :return token object received from keystone on success :raise InvalidUserToken if token is rejected :raise ServiceError if unable to authenticate token
""" # Determine the highest api version we can use.
'X-Subject-Token': safe_quote(user_token)} 'GET', '/v3/auth/tokens', additional_headers=headers) else: 'GET', '/v2.0/tokens/%s' % safe_quote(user_token), additional_headers=headers)
if response.status == 401: self.LOG.info( 'Keystone rejected admin token %s, resetting', headers) self.admin_token = None else: self.LOG.error('Bad response code while validating token: %s' % response.status) if retry: self.LOG.info('Retrying validation') return self._validate_user_token(user_token, False) else: self.LOG.warn("Invalid user token: %s. Keystone response: %s.", user_token, data)
raise InvalidUserToken()
"""Indicate whether the token appears in the revocation list.""" token_id)
"""Verifies the signature of the provided data's IAW CMS syntax.
If either of the certificate files are missing, fetch them and retry. """ self.ca_file_name) except cms.subprocess.CalledProcessError as err: if self.cert_file_missing(err.output, self.signing_cert_file_name): self.fetch_signing_cert() continue if self.cert_file_missing(err.output, self.ca_file_name): self.fetch_ca_cert() continue raise err
"""Check that the token is unrevoked and has a valid signature."""
def token_revocation_list_fetched_time(self): # If the fetched list has been written to disk, use its # modification time. # Otherwise the list will need to be fetched. else:
def token_revocation_list_fetched_time(self, value):
def token_revocation_list(self): self.token_revocation_list_cache_timeout)
# Load the list from disk if required else:
def token_revocation_list(self, value): """Save a revocation list to memory and to disk.
:param value: A json-encoded revocation list
"""
additional_headers=headers) if retry: self.LOG.info( 'Keystone rejected admin token %s, resetting admin token', headers) self.admin_token = None return self.fetch_revocation_list(retry=False) raise ServiceError('Unable to fetch token revocation list.')
response, data = self._http_request('GET', '/v2.0/certificates/signing') try: #todo check response certfile = open(self.signing_cert_file_name, 'w') certfile.write(data) certfile.close() except (AssertionError, KeyError): self.LOG.warn( "Unexpected response from keystone service: %s", data) raise ServiceError('invalid json response')
response, data = self._http_request('GET', '/v2.0/certificates/ca') try: #todo check response certfile = open(self.ca_file_name, 'w') certfile.write(data) certfile.close() except (AssertionError, KeyError): self.LOG.warn( "Unexpected response from keystone service: %s", data) raise ServiceError('invalid json response')
"""Returns a WSGI filter app for use with paste.deploy.""" conf = global_conf.copy() conf.update(local_conf)
def auth_filter(app): return AuthProtocol(app, conf) return auth_filter
conf = global_conf.copy() conf.update(local_conf) return AuthProtocol(None, conf) |