# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2014 IBM Corporation # # 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. # authentication and authorization routines for confluent # authentication scheme caches passphrase values to help HTTP Basic auth # the PBKDF2 transform is skipped unless a user has been idle for sufficient # time import confluentd.config.configmanager as configmanager import eventlet import eventlet.tpool import Crypto.Protocol.KDF as KDF import hashlib import hmac import multiprocessing try: import PAM except ImportError: pass import time _pamservice = 'confluent' _passcache = {} _passchecking = {} authworkers = None class Credentials(object): def __init__(self, username, passphrase): self.username = username self.passphrase = passphrase self.haspam = False def pam_conv(self, auth, query_list): # use stored credentials in a pam conversation self.haspam = True resp = [] for query_entry in query_list: query, pamtype = query_entry if query.startswith('Password'): resp.append((self.passphrase, 0)) else: return None return resp def _prune_passcache(): # This function makes sure we don't remember a passphrase in memory more # than 10 seconds while True: curtime = time.time() for passent in _passcache.iterkeys(): if passent[2] < curtime - 10: del _passcache[passent] eventlet.sleep(10) def _get_usertenant(name, tenant=False): """_get_usertenant Convenience function to parse name into username and tenant. If tenant is explicitly passed in, then name must be the username tenant name with '/' is forbidden. If '/' is seen in name, tenant is assumed to preface the /. If the username is a tenant name, then it is to be the implied administrator account a tenant gets. Otherwise, just assume a user in the default tenant """ if not isinstance(tenant, bool): # if not boolean, it must be explicit tenant user = name elif '/' in name: # tenant scoped name tenant, user = name.split('/', 1) elif configmanager.is_tenant(name): # the account is the implicit tenant owner account user = name tenant = name else: # assume it is a non-tenant user account user = name tenant = None yield user yield tenant def authorize(name, element, tenant=False, operation='create', skipuserobj=False): #TODO: actually use the element to ascertain if this user is good enough """Determine whether the given authenticated name is authorized. :param name: The shortname authenticated by the authentication scheme :param element: The path being examined. :param tenant: The tenant under which the account exists (defaults to detect from name) :param operation: Defaults to checking for 'create' level access returns None if authorization fails or a tuple of the user object and the relevant ConfigManager object for the context of the request. """ if operation not in ('create', 'start', 'update', 'retrieve', 'delete'): return None user, tenant = _get_usertenant(name, tenant) if tenant is not None and not configmanager.is_tenant(tenant): return None manager = configmanager.ConfigManager(tenant) if skipuserobj: return None, manager, user, tenant, skipuserobj userobj = manager.get_user(user) if userobj: # returning return userobj, manager, user, tenant, skipuserobj return None def check_user_passphrase(name, passphrase, element=None, tenant=False): """Check a a login name and passphrase for authenticity and authorization The function combines authentication and authorization into one function. It is highly recommended for a session layer to provide some secure means of protecting a session once this function works once and calling authorize() in order to provide best performance regardless of circumstance. The function makes effort to provide good performance in repeated invocation, but that facility will slow down to deter detected passphrase guessing activity when such activity is detected. :param name: The login name provided by client :param passphrase: The passphrase provided by client :param element: Optional specification of a particular destination :param tenant: Optional explicit indication of tenant (defaults to embedded in name) """ # The reason why tenant is 'False' instead of 'None': # None means explicitly not a tenant. False means check # the username for signs of being a tenant # If there is any sign of guessing on a user, all valid and # invalid attempts are equally slowed to no more than 20 per second # for that particular user. # similarly, guessing usernames is throttled to 20/sec user, tenant = _get_usertenant(name, tenant) while (user, tenant) in _passchecking: # Want to serialize passphrase checking activity # by a user, which might be malicious # would normally make an event and wait # but here there's no need for that eventlet.sleep(0.5) credobj = Credentials(user, passphrase) try: pammy = PAM.pam() pammy.start(_pamservice, user, credobj.pam_conv) pammy.authenticate() pammy.acct_mgmt() del pammy return authorize(user, element, tenant, skipuserobj=False) except NameError: pass except PAM.error: if credobj.haspam: return None if (user, tenant) in _passcache: if passphrase == _passcache[(user, tenant)]: return authorize(user, element, tenant) else: # In case of someone trying to guess, # while someone is legitimately logged in # invalidate cache and force the slower check del _passcache[(user, tenant)] return None cfm = configmanager.ConfigManager(tenant) ucfg = cfm.get_user(user) if ucfg is None or 'cryptpass' not in ucfg: eventlet.sleep(0.05) # stall even on test for existence of a username return None _passchecking[(user, tenant)] = True # TODO(jbjohnso): WORKERPOOL # PBKDF2 is, by design, cpu intensive # throw it at the worker pool when implemented # maybe a distinct worker pool, wondering about starving out non-auth stuff salt, crypt = ucfg['cryptpass'] # execute inside tpool to get greenthreads to give it a special thread # world #TODO(jbjohnso): util function to generically offload a call #such a beast could be passed into pyghmi as a way for pyghmi to #magically get offload of the crypto functions without having #to explicitly get into the eventlet tpool game crypted = eventlet.tpool.execute(_do_pbkdf, passphrase, salt) del _passchecking[(user, tenant)] eventlet.sleep(0.05) # either way, we want to stall so that client can't # determine failure because there is a delay, valid response will # delay as well if crypt == crypted: _passcache[(user, tenant)] = passphrase return authorize(user, element, tenant) return None def _apply_pbkdf(passphrase, salt): return KDF.PBKDF2(passphrase, salt, 32, 10000, lambda p, s: hmac.new(p, s, hashlib.sha256).digest()) def _do_pbkdf(passphrase, salt): # we must get it over to the authworkers pool or else get blocked in # compute. However, we do want to wait for result, so we have # one of the exceedingly rare sort of circumstances where 'apply' # actually makes sense return authworkers.apply(_apply_pbkdf, [passphrase, salt]) def init_auth(): # have a some auth workers available. Keep them distinct from # the general populace of workers to avoid unauthorized users # starving out productive work global authworkers # for now we'll just have one auth worker and see if there is any # demand for more. I personally doubt it. authworkers = multiprocessing.Pool(processes=1)