def getUserFromRequest(request): ''' This function first tries to get the user from * a DigestAuth and otherwise from * basic auth and otherwise from * the client certificate ''' d_auth = {'login': ''} param = request.params try: # Do BasicAuth if request.environ.has_key('REMOTE_USER'): d_auth['login'] = request.environ['REMOTE_USER'] log.debug("[getUserFromRequest] BasicAuth: found the " "REMOTE_USER: %r" % d_auth) # Do DigestAuth elif request.environ.has_key('HTTP_AUTHORIZATION'): a_auth = request.environ['HTTP_AUTHORIZATION'].split(",") for field in a_auth: (key, _delimiter, value) = field.partition("=") d_auth[key.lstrip(' ')] = value.strip('"') if d_auth.has_key('Digest username'): d_auth['login'] = d_auth['Digest username'] log.debug("[getUserFromRequest] DigestAuth: found " "this HTTP_AUTHORIZATION: %r" % d_auth) # Do SSL Client Cert elif request.environ.has_key('SSL_CLIENT_S_DN_CN'): d_auth['login'] = request.environ.get('SSL_CLIENT_S_DN_CN') log.debug("[getUserFromRequest] SSLClientCert Auth: found " "this SSL_CLIENT_S_DN_CN: %r" % d_auth) # In case of selftest log.debug("[getUserFromRequest] Doing selftest!: %r" % isSelfTest()) if isSelfTest(): log.debug("[getUserFromRequest] Doing selftest!") param = request.params d_auth['login'] = getParam(param, "selftest_admin", True) log.debug( "[getUserFromRequest] Found the user: %r in the request." % d_auth) except Exception as e: log.error( "[getUserFromRequest] An error occurred when trying to fetch " "the user from the request: %r" % e) pass return d_auth
def authenticate(self, environ, identity): log.info("[authenticate] entering repoze authenticate function.") # log.debug( identity ) username = None realm = None authUser = None try: if isSelfTest(): if ('login' not in identity and 'repoze.who.plugins.auth_tkt.userid' in identity): uid = identity.get('repoze.who.plugins.auth_tkt.userid') identity['login'] = uid identity['password'] = uid if getRealmBox(): username = identity['login'] realm = identity['realm'] else: log.info("[authenticate] no realmbox") if '@' in identity['login']: if getSplitAtSign(): log.debug("trying to split the loginname") username, _at_, realm = identity['login'].rpartition( '@') else: log.debug("no split for the @ of the loginname") username = identity['login'] realm = identity.get('realm', getDefaultRealm()) else: username = identity['login'] realm = getDefaultRealm() log.info("[authenticate]: username: %r, realm: %r" % (username, realm)) password = identity['password'] except KeyError as e: log.error("[authenticate] Keyerror in identity: %r." % e) log.error("[authenticate] %s" % traceback.format_exc()) return None # as repoze does not run through the std pylons middleware, we have to # convert the input which might be UTF8 to unicode username = str2unicode(username) password = str2unicode(password) # check username/realm, password if isSelfTest(): authUser = "******" % (username, realm) else: authUser = get_authenticated_user(username, realm, password) return authUser
def getUserFromRequest(request): ''' This function first tries to get the user from * a DigestAuth and otherwise from * basic auth and otherwise from * the client certificate ''' d_auth = { 'login' : '' } param = request.params try: # Do BasicAuth if request.environ.has_key('REMOTE_USER'): d_auth['login'] = request.environ['REMOTE_USER'] log.debug("[getUserFromRequest] BasicAuth: found the " "REMOTE_USER: %r" % d_auth) # Do DigestAuth elif request.environ.has_key('HTTP_AUTHORIZATION'): a_auth = request.environ['HTTP_AUTHORIZATION'].split(",") for field in a_auth: (key, _delimiter, value) = field.partition("=") d_auth[key.lstrip(' ')] = value.strip('"') if d_auth.has_key('Digest username'): d_auth['login'] = d_auth['Digest username'] log.debug("[getUserFromRequest] DigestAuth: found " "this HTTP_AUTHORIZATION: %r" % d_auth) # Do SSL Client Cert elif request.environ.has_key('SSL_CLIENT_S_DN_CN'): d_auth['login'] = request.environ.get('SSL_CLIENT_S_DN_CN') log.debug("[getUserFromRequest] SSLClientCert Auth: found " "this SSL_CLIENT_S_DN_CN: %r" % d_auth) # In case of selftest log.debug("[getUserFromRequest] Doing selftest!: %r" % isSelfTest()) if isSelfTest(): log.debug("[getUserFromRequest] Doing selftest!") param = request.params d_auth['login'] = getParam(param, "selftest_admin", True) log.debug("[getUserFromRequest] Found the user: %r in the request." % d_auth) except Exception as e: log.exception("[getUserFromRequest] An error occurred when trying to fetch " "the user from the request: %r" % e) pass return d_auth
def authenticate(self, environ, identity): log.info("[authenticate] entering repoze authenticate function.") # log.debug( identity ) username = None realm = None authUser = None try: if isSelfTest(): if ('login' not in identity and 'repoze.who.plugins.auth_tkt.userid' in identity): uid = identity.get('repoze.who.plugins.auth_tkt.userid') identity['login'] = uid identity['password'] = uid if getRealmBox(): username = identity['login'] realm = identity['realm'] else: log.info("[authenticate] no realmbox") if '@' in identity['login']: if getSplitAtSign(): log.debug("trying to split the loginname") username, _at_, realm = identity['login'].rpartition('@') else: log.debug("no split for the @ of the loginname") username = identity['login'] realm = identity.get('realm', getDefaultRealm()) else: username = identity['login'] realm = getDefaultRealm() log.info("[authenticate]: username: %r, realm: %r" % (username, realm)) password = identity['password'] except KeyError as e: log.error("[authenticate] Keyerror in identity: %r." % e) log.error("[authenticate] %s" % traceback.format_exc()) return None # as repoze does not run through the std pylons middleware, we have to # convert the input which might be UTF8 to unicode username = str2unicode(username) password = str2unicode(password) # check username/realm, password if isSelfTest(): authUser = "******" % (username, realm) else: authUser = get_authenticated_user(username, realm, password) return authUser
def authenticate(self, environ, identity): log.info("[authenticate] entering repoze authenticate function.") # log.debug( identity ) username = None realm = None options = {} realmbox = "False" authenticate = True if isSelfTest(): authenticate = False try: if isSelfTest(): if ('login' not in identity and 'repoze.who.plugins.auth_tkt.userid' in identity): u = identity.get('repoze.who.plugins.auth_tkt.userid') identity['login'] = u identity['password'] = u username = identity['login'] realm = identity['realm'] password = identity['password'] options.update(identity) realmbox = options.get("realmbox", "False") except KeyError as e: log.exception("[authenticate] Keyerror in identity: %r." % e) return None # convert string to boolean realm_mbox = False if realmbox.lower() == 'true': realm_mbox = True # check username/realm, password with request_context_safety(): linotp_config = getLinotpConfig() request_context['Config'] = linotp_config user = get_authenticated_user(username, realm, password, realm_box=realm_mbox, authenticate=authenticate, options=options) if not user: return None authUser = "******" % (user.login, user.realm) return authUser
def authenticate(self, environ, identity): log.info("[authenticate] entering repoze authenticate function.") #log.debug( identity ) username = None realm = None success = None try: if isSelfTest(): if identity.has_key('login') == False and identity.has_key( 'repoze.who.plugins.auth_tkt.userid') == True: u = identity.get('repoze.who.plugins.auth_tkt.userid') identity['login'] = u identity['password'] = u if getRealmBox(): username = identity['login'] realm = identity['realm'] else: log.info( "[authenticate] no realmbox, so we are trying to split the loginname" ) m = re.match("(.*)\@(.*)", identity['login']) if m: if 2 == len(m.groups()): username = m.groups()[0] realm = m.groups()[1] log.info( "[authenticate] found @: username: %r, realm: %r" % (username, realm)) else: username = identity['login'] realm = getDefaultRealm() log.info( "[authenticate] using default Realm: username: %r, realm: %r" % (username, realm)) password = identity['password'] except KeyError as e: log.error("[authenticate] Keyerror in identity: %r." % e) log.error("[authenticate] %s" % traceback.format_exc()) return None # check username/realm, password if isSelfTest(): success = "%s@%s" % (unicode(username), unicode(realm)) else: success = check_user_password(username, realm, password) return success
def getUserFromRequest(request, config=None): ''' This function first tries to get the user from * a DigestAuth and otherwise from * basic auth and otherwise from * the client certificate ''' d_auth = {'login': ''} param = request.params try: # Do BasicAuth if 'REMOTE_USER' in request.environ: d_auth['login'] = request.environ['REMOTE_USER'] log.debug( "[getUserFromRequest] BasicAuth: found the " "REMOTE_USER: %r", d_auth) # Do DigestAuth elif 'HTTP_AUTHORIZATION' in request.environ: a_auth = request.environ['HTTP_AUTHORIZATION'].split(",") for field in a_auth: (key, _delimiter, value) = field.partition("=") d_auth[key.lstrip(' ')] = value.strip('"') d_auth['login'] = d_auth.get('Digest username', '') or '' log.debug( "[getUserFromRequest] DigestAuth: found " "this HTTP_AUTHORIZATION: %r", d_auth) # Do SSL Client Cert elif 'SSL_CLIENT_S_DN_CN' in request.environ: d_auth['login'] = request.environ.get('SSL_CLIENT_S_DN_CN', '') log.debug( "[getUserFromRequest] SSLClientCert Auth: found " "this SSL_CLIENT_S_DN_CN: %r", d_auth) # In case of selftest self_test = isSelfTest(config=config) log.debug("[getUserFromRequest] Doing selftest!: %r", self_test) if self_test: log.debug("[getUserFromRequest] Doing selftest!") param = request.params login = getParam(param, "selftest_admin", True) if login: d_auth['login'] = login log.debug( "[getUserFromRequest] Found selfservice user: %r in " "the request.", d_auth) except Exception as exx: log.exception( "[getUserFromRequest] An error occurred when trying" " to fetch the user from the request: %r", exx) return d_auth
def check_session(): ''' This function checks the session cookie for management API and compares it to the session parameter ''' if isSelfTest(): return # check if the client is in the allowed IP range no_session_clients = [c.strip() for c in config.get("linotpNoSessionCheck", "").split(",")] client = request.environ.get('REMOTE_ADDR', None) log.debug("[check_session] checking %s in %s" % (client, no_session_clients)) for network in no_session_clients: if not network: continue try: if IPAddress(client) in IPNetwork(network): log.debug("[check_session] skipping session check since client %s in allowed: %s" % (client, no_session_clients)) return except Exception as ex: log.warning("[check_session] misconfiguration in linotpNoSessionCheck: %r - %r" % (network, ex)) if request.path.lower() == '/admin/getsession': log.debug('[check_session] requesting a new session cookie') else: cookie = request.cookies.get('admin_session') session = request.params.get('session') # doing any other request, we need to check the session! log.debug("[check_session]: session: %s" % session) log.debug("[check_session]: cookie: %s" % cookie) if session is None or session == "" or session != cookie: log.error("[check_session] The request did not pass a valid session!") abort(401, "You have no valid session!") pass
def check_session(): ''' This function checks the session cookie for management API and compares it to the session parameter ''' if isSelfTest(): return # check if the client is in the allowed IP range no_session_clients = [c.strip() for c in config.get("linotpNoSessionCheck", "").split(",")] client = request.environ.get('REMOTE_ADDR', None) log.debug("[check_session] checking %s in %s" % (client, no_session_clients)) for network in no_session_clients: if not network: continue try: if netaddr.IPAddress(client) in netaddr.IPNetwork(network): log.debug("[check_session] skipping session check since client %s in allowed: %s" % (client, no_session_clients)) return except Exception as ex: log.warning("[check_session] misconfiguration in linotpNoSessionCheck: %r - %r" % (network, ex)) if request.path.lower() == '/admin/getsession': log.debug('[check_session] requesting a new session cookie') else: cookie = request.cookies.get('admin_session') session = request.params.get('session') # doing any other request, we need to check the session! log.debug("[check_session]: session: %s" % session) log.debug("[check_session]: cookie: %s" % cookie) if session is None or session == "" or session != cookie: log.error("[check_session] The request did not pass a valid session!") abort(401, "You have no valid session!") pass
def __after__(response): ''' __after__ is called after every action :param response: the previously created response - for modification :return: return the response ''' if request_context.get('reponse_redirect', False): # FIXME: does this really do a redirect??? return response param = request.params action = request_context['action'] try: if c.audit['action'] in ['selfservice/index']: if isSelfTest(): log.debug("[__after__] Doing selftest!") if "selftest_user" in param: (c.user, _foo, c.realm) = param["selftest_user"].rpartition('@') else: c.realm = "" c.user = "******" env = request.environ uuser = env.get('REMOTE_USER') if uuser is not None: (c.user, _foo, c.realm) = uuser.rpartition('@') log.debug("[__after__] authenticating as %s in realm %s!" % (c.user, c.realm)) c.audit['user'] = c.user c.audit['realm'] = c.realm c.audit['success'] = True if 'serial' in param: c.audit['serial'] = param['serial'] c.audit['token_type'] = getTokenType(param['serial']) audit = config.get('audit') audit.log(c.audit) return response except flap.HTTPUnauthorized as acc: # the exception, when an abort() is called if forwarded log.exception("[__after__::%r] webob.exception %r" % (action, acc)) Session.rollback() Session.close() # FIXME: verify that this really works raise acc except Exception as e: log.exception("[__after__] failed with error: %r" % e) Session.rollback() Session.close() return sendError(response, e, context='after')
def __after__( self, action, ): ''' ''' param = request.params try: if c.audit['action'] in ['selfservice/index']: if isSelfTest(): log.debug("[__after__] Doing selftest!") suser = getParam(param, "selftest_user", True) if suser is not None: (c.user, _foo, c.realm) = getParam(param, "selftest_user", True)\ .rpartition('@') else: c.realm = "" c.user = "******" env = request.environ uuser = env.get('REMOTE_USER') if uuser is not None: (c.user, _foo, c.realm) = uuser.rpartition('@') log.debug("[__after__] authenticating as %s in realm %s!" % (c.user, c.realm)) c.audit['user'] = c.user c.audit['realm'] = c.realm c.audit['success'] = True if 'serial' in param: c.audit['serial'] = param['serial'] c.audit['token_type'] = getTokenType(param['serial']) audit.log(c.audit) return response except webob.exc.HTTPUnauthorized as acc: # the exception, when an abort() is called if forwarded log.exception("[__after__::%r] webob.exception %r" % (action, acc)) Session.rollback() Session.close() raise acc except Exception as e: log.exception("[__after__] failed with error: %r" % e) Session.rollback() Session.close() return sendError(response, e, context='after') finally: log.debug('[__after__] done')
def __after__(self, action,): ''' ''' param = request.params try: if c.audit['action'] in ['selfservice/index']: if isSelfTest(): log.debug("[__after__] Doing selftest!") suser = getParam(param, "selftest_user", True) if suser is not None: (c.user, _foo, c.realm) = getParam(param, "selftest_user", True)\ .rpartition('@') else: c.realm = "" c.user = "******" env = request.environ uuser = env.get('REMOTE_USER') if uuser is not None: (c.user, _foo, c.realm) = uuser.rpartition('@') log.debug("[__after__] authenticating as %s in realm %s!" % (c.user, c.realm)) c.audit['user'] = c.user c.audit['realm'] = c.realm c.audit['success'] = True if 'serial' in param: c.audit['serial'] = param['serial'] c.audit['token_type'] = getTokenType(param['serial']) audit.log(c.audit) return response except webob.exc.HTTPUnauthorized as acc: # the exception, when an abort() is called if forwarded log.error("[__after__::%r] webob.exception %r" % (action, acc)) log.error("[__after__] %s" % traceback.format_exc()) Session.rollback() Session.close() raise acc except Exception as e: log.error("[__after__] failed with error: %r" % e) log.error("[__after__] %s" % traceback.format_exc()) Session.rollback() Session.close() return sendError(response, e, context='after') finally: log.debug('[__after__] done')
def getUserFromRequest(request, config=None): ''' This function first tries to get the user from * a DigestAuth and otherwise from * basic auth and otherwise from * the client certificate ''' d_auth = {'login': ''} param = request.params try: # Do BasicAuth if 'REMOTE_USER' in request.environ: d_auth['login'] = request.environ['REMOTE_USER'] log.debug("[getUserFromRequest] BasicAuth: found the " "REMOTE_USER: %r", d_auth) # Do DigestAuth elif 'HTTP_AUTHORIZATION' in request.environ: a_auth = request.environ['HTTP_AUTHORIZATION'].split(",") for field in a_auth: (key, _delimiter, value) = field.partition("=") d_auth[key.lstrip(' ')] = value.strip('"') d_auth['login'] = d_auth.get('Digest username', '') or '' log.debug("[getUserFromRequest] DigestAuth: found " "this HTTP_AUTHORIZATION: %r", d_auth) # Do SSL Client Cert elif 'SSL_CLIENT_S_DN_CN' in request.environ: d_auth['login'] = request.environ.get('SSL_CLIENT_S_DN_CN', '') log.debug("[getUserFromRequest] SSLClientCert Auth: found " "this SSL_CLIENT_S_DN_CN: %r", d_auth) # In case of selftest self_test = isSelfTest(config=config) log.debug("[getUserFromRequest] Doing selftest!: %r", self_test) if self_test: log.debug("[getUserFromRequest] Doing selftest!") param = request.params login = getParam(param, "selftest_admin", True) if login: d_auth['login'] = login log.debug("[getUserFromRequest] Found selfservice user: %r in " "the request.", d_auth) except Exception as exx: log.exception("[getUserFromRequest] An error occurred when trying" " to fetch the user from the request: %r", exx) return d_auth
def authenticate(self, environ, identity): log.info("[authenticate] entering repoze authenticate function.") #log.debug( identity ) username = None realm = None success = None try: if isSelfTest(): if identity.has_key('login') == False and identity.has_key('repoze.who.plugins.auth_tkt.userid') == True: u = identity.get('repoze.who.plugins.auth_tkt.userid') identity['login'] = u identity['password'] = u if getRealmBox(): username = identity['login'] realm = identity['realm'] else: log.info("[authenticate] no realmbox, so we are trying to split the loginname") m = re.match("(.*)\@(.*)", identity['login']) if m: if 2 == len(m.groups()): username = m.groups()[0] realm = m.groups()[1] log.info("[authenticate] found @: username: %r, realm: %r" % (username, realm)) else: username = identity['login'] realm = getDefaultRealm() log.info("[authenticate] using default Realm: username: %r, realm: %r" % (username, realm)) password = identity['password'] except KeyError as e: log.error("[authenticate] Keyerror in identity: %r." % e) log.error("[authenticate] %s" % traceback.format_exc()) return None # check username/realm, password if isSelfTest(): success = "%s@%s" % (unicode(username), unicode(realm)) else: success = check_user_password(username, realm, password) return success
def check_session(request, scope='admin'): ''' This function checks the session cookie and compares it to the session parameter :param request: the request object :param scope: by default the admin scope, but used to as well for the scope helpdesk with the helpdesk_session cookie name :return: boolean ''' if isSelfTest(): return # check if the client is in the allowed IP range no_session_clients = [] for no_session_client in config.get("linotpNoSessionCheck", "").split(","): no_session_clients.append(no_session_client.strip()) client = request.environ.get('REMOTE_ADDR', None) log.debug("[check_session] checking %s in %s" % (client, no_session_clients)) for network in no_session_clients: if not network: continue try: if netaddr.IPAddress(client) in netaddr.IPNetwork(network): log.debug("skipping session check since client" " %s in allowed: %s" % (client, no_session_clients)) return except Exception as ex: log.warning("misconfiguration in linotpNoSessionCheck: " "%r - %r" % (network, ex)) cookie = request.cookies.get(scope + '_session') session = get_request_param(request, 'session') # doing any other request, we need to check the session! log.debug("[check_session]: session: %s" % session) log.debug("[check_session]: cookie: %s" % cookie) if session is None or session == "" or session != cookie: log.error("The request did not pass a valid session!") abort(401, "You have no valid session!") cookie = request.cookies.get(scope + '_session') session = get_request_param(request, 'session') # doing any other request, we need to check the session! log.debug("[check_session]: session: %s" % session) log.debug("[check_session]: cookie: %s" % cookie) if session is None or session == "" or session != cookie: log.error("The request did not pass a valid session!") abort(401, "You have no valid session!")
def autosms(self): ''' This function is used to test the autosms policy method: testing/autosms arguments: user - username / loginname realm - additional realm to match the user to a useridresolver returns: JSON response ''' log.debug('[autosms]') param = request.params try: if isSelfTest() == False: Session.rollback() return sendError( response, "The testing controller can only be used in SelfTest mode!", 0) user = getUserFromParam(param, required) ok = get_auth_AutoSMSPolicy() Session.commit() return sendResult(response, ok, 0) except Exception as e: log.error("[autosms] validate/check failed: %r", e) log.error("[autosms] %s" % traceback.format_exc()) Session.rollback() return sendError(response, "validate/check failed:" + unicode(e), 0) finally: Session.close() log.debug('[autosms] done')
def autosms(self): ''' This function is used to test the autosms policy method: testing/autosms arguments: user - username / loginname realm - additional realm to match the user to a useridresolver returns: JSON response ''' param = request.params try: if isSelfTest() is False: Session.rollback() return sendError( response, "The testing controller can only be used in SelfTest mode!", 0) if "user" not in param: raise ParameterError("Missing parameter: 'user'") ok = get_auth_AutoSMSPolicy() Session.commit() return sendResult(response, ok, 0) except Exception as e: log.exception("[autosms] validate/check failed: %r", e) Session.rollback() return sendError(response, "validate/check failed:" + unicode(e), 0) finally: Session.close()
def autosms(self): ''' This function is used to test the autosms policy method: testing/autosms arguments: user - username / loginname realm - additional realm to match the user to a useridresolver returns: JSON response ''' log.debug('[autosms]') param = request.params try: if isSelfTest() == False: Session.rollback() return sendError(response, "The testing controller can only be used in SelfTest mode!", 0) user = getUserFromParam(param, required) ok = get_auth_AutoSMSPolicy() Session.commit() return sendResult(response, ok, 0) except Exception as e: log.error("[autosms] validate/check failed: %r", e) log.error("[autosms] %s" % traceback.format_exc()) Session.rollback() return sendError(response, "validate/check failed:" + unicode(e), 0) finally: Session.close() log.debug('[autosms] done')
def autosms(self): ''' This function is used to test the autosms policy method: testing/autosms arguments: user - username / loginname realm - additional realm to match the user to a useridresolver returns: JSON response ''' try: if isSelfTest() is False: Session.rollback() return sendError(response, "The testing controller can only" " be used in SelfTest mode!", 0) if "user" not in self.request_params: raise ParameterError("Missing parameter: 'user'") ok = get_auth_AutoSMSPolicy() Session.commit() return sendResult(response, ok, 0) except Exception as exx: log.exception("[autosms] validate/check failed: %r", exx) Session.rollback() return sendError(response, ("validate/check failed: %r", exx), 0) finally: Session.close()
def _check(self, param): ''' basic check function, that can be used by different controllers :param param: dict of all caller parameters :type param: dict :return: Tuple of True or False and opt :rtype: Tuple(boolean, opt) ''' opt = None options = {} # put everything in the options but the user, pass, init options.update(param) for para in ["pass", "user", "init"]: if options.has_key(para): del options[para] passw = param.get("pass") user = getUserFromParam(param) # support for ocra application challenge verification challenge = param.get("challenge") if challenge is not None: options = {} options['challenge'] = challenge c.audit['user'] = user.login realm = user.realm or getDefaultRealm() c.audit['realm'] = realm # AUTHORIZATION Pre Check # we need to overwrite the user.realm in case the # user does not exist in the original realm (setrealm-policy) user.realm = set_realm(user.login, realm, exception=True) check_user_authorization(user.login, user.realm, exception=True) if isSelfTest() is True: initTime = param.get("init") if initTime is not None: if options is None: options = {} options['initTime'] = initTime vh = ValidationHandler() (ok, opt) = vh.checkUserPass(user, passw, options=options) c.audit.update(request_context.get('audit')) c.audit['success'] = ok if ok: # AUTHORIZATION post check check_auth_tokentype(c.audit['serial'], exception=True, user=user) check_auth_serial(c.audit['serial'], exception=True, user=user) # add additional details if is_auth_return(ok, user=user): if opt is None: opt = {} if ok: opt['realm'] = c.audit.get('realm') opt['user'] = c.audit.get('user') opt['tokentype'] = c.audit.get('token_type') opt['serial'] = c.audit.get('serial') else: opt['error'] = c.audit.get('action_detail') return (ok, opt)
def __after__(self, action,): ''' ''' param = request.params try: if c.audit['action'] in ['selfservice/index']: if isSelfTest(): log.debug("[__after__] Doing selftest!") suser = getParam(param, "selftest_user", True) if suser is not None: (c.user, _foo, c.realm) = getParam(param, "selftest_user", True)\ .rpartition('@') else: c.realm = "" c.user = "******" env = request.environ uuser = env.get('REMOTE_USER') realms = getAllUserRealms(User(uuser, "", "")) if (realms): c.user = uuser c.realm = realms[0] ### This makes no sense... # c.audit['user'] = c.user # c.audit['realm'] = c.realm # else: # user = getUserFromRequest(request).get("login") # c.audit['user'] ,c.audit['realm'] = user.split('@') # uc = user.split('@') # c.audit['realm'] = uc[-1] # c.audit['user'] = '******'.join(uc[:-1]) log.debug("[__after__] authenticating as %s in realm %s!" % (c.user, c.realm)) c.audit['user'] = c.user c.audit['realm'] = c.realm c.audit['success'] = True if 'serial' in param: c.audit['serial'] = param['serial'] c.audit['token_type'] = getTokenType(param['serial']) audit.log(c.audit) return response except webob.exc.HTTPUnauthorized as acc: # the exception, when an abort() is called if forwarded log.error("[__after__::%r] webob.exception %r" % (action, acc)) log.error("[__after__] %s" % traceback.format_exc()) Session.rollback() Session.close() raise acc except Exception as e: log.error("[__after__] failed with error: %r" % e) log.error("[__after__] %s" % traceback.format_exc()) Session.rollback() Session.close() return sendError(response, e, context='after') finally: log.debug('[__after__] done')
def getUserFromRequest(request, config=None): ''' This function first tries to get the user from * already authenticated systems (REMOTE_USER) * a Basic / DigestAuth and * otherwise from the client certificate :param request: the pylons request :param config: the LinOTP configuration :return: the authentication dict :remark: the function catches all exceptions which are only logged :remark: the selfservice authentication should be removed!! ''' d_auth = {'login': ''} param = request.params try: # ------------------------------------------------------------------ -- # accept remote authenticated users if 'REMOTE_USER' in request.environ: d_auth['login'] = request.environ['REMOTE_USER'] log.debug( "[getUserFromRequest] BasicAuth: found the " "REMOTE_USER: %r", d_auth) # ------------------------------------------------------------------ -- # Find user name from HTTP_AUTHORIZATION (Basic or Digest auth) elif 'HTTP_AUTHORIZATION' in request.environ: hdr = request.environ['HTTP_AUTHORIZATION'] # -------------------------------------------------------------- -- # Basic Authentication if hdr.startswith('Basic '): a_auth = b64decode(hdr[5:].strip()) d_auth['login'], _junk, _junk = a_auth.partition(':') log.debug( "[getUserFromRequest] BasicAuth: found " "this HTTP_AUTHORIZATION: %r", d_auth) # -------------------------------------------------------------- -- # Digest authentication else: for field in hdr.split(","): (key, _delimiter, value) = field.partition("=") d_auth[key.lstrip(' ')] = value.strip('"') d_auth['login'] = d_auth.get('Digest username', '') or '' log.debug( "[getUserFromRequest] DigestAuth: found " "this HTTP_AUTHORIZATION: %r", d_auth) # ------------------------------------------------------------------ -- # Do SSL Client Cert elif 'SSL_CLIENT_S_DN_CN' in request.environ: d_auth['login'] = request.environ.get('SSL_CLIENT_S_DN_CN', '') log.debug( "[getUserFromRequest] SSLClientCert Auth: found " "this SSL_CLIENT_S_DN_CN: %r", d_auth) # ------------------------------------------------------------------ -- # In case of selftest if isSelfTest(config=config): log.debug("[getUserFromRequest] Doing selftest!") login = param.get("selftest_admin") if login: d_auth['login'] = login log.debug( "[getUserFromRequest] Found selfservice user: %r in " "the request.", d_auth) # ------------------------------------------------------------------ -- except Exception as exx: log.exception( "[getUserFromRequest] An error occurred when trying" " to fetch the user from the request: %r", exx) return d_auth
def check_s(self): ''' This function is used to validate the serial and the otp value/password. method: validate/check_s arguments: * serial: the serial number of the token * pass: the password that consists of a possible fixes password component and the OTP value returns: JSON response ''' param = {} param.update(request.params) options = {} options.update(param) for k in ['user', 'serial', "pass", "init"]: if k in options: del options[k] if 'init' in param: if isSelfTest() is True: options['initTime'] = param.get('init') try: passw = getParam(param, "pass", optional) serial = getParam(param, 'serial', optional) if serial is None: user = getParam(param, 'user', optional) if user is not None: user = getUserFromParam(param, optional) toks = getTokens4UserOrSerial(user=user) if len(toks) == 0: raise Exception("No token found!") elif len(toks) > 1: raise Exception("More than one token found!") else: tok = toks[0].token desc = tok.get() realms = desc.get('LinOtp.RealmNames') if realms is None or len(realms) == 0: realm = getDefaultRealm() elif len(realms) > 0: realm = realms[0] userInfo = getUserInfo(tok.LinOtpUserid, tok.LinOtpIdResolver, tok.LinOtpIdResClass) user = User(login=userInfo.get('username'), realm=realm) serial = tok.getSerial() c.audit['serial'] = serial if isSelfTest() is True: initTime = getParam(param, "init", optional) if initTime is not None: if options is None: options = {} options['initTime'] = initTime options['scope'] = {"check_s": True} vh = ValidationHandler() (ok, opt) = vh.checkSerialPass(serial, passw, options=options) c.audit['success'] = ok Session.commit() qr = param.get('qr', None) if qr and opt and 'message' in opt: try: dataobj = opt.get('message') param['alt'] = "%s" % opt if 'transactionid' in opt: param['transactionid'] = opt['transactionid'] return sendQRImageResult(response, dataobj, param) except Exception as exc: log.warning("failed to send QRImage: %r " % exc) return sendQRImageResult(response, opt, param) else: return sendResult(response, ok, 0, opt=opt) except Exception as exx: log.exception("[check_s] validate/check_s failed: %r" % exx) c.audit['info'] = unicode(exx) Session.rollback() return sendResult(response, False, id=0, status=False) finally: Session.close() log.debug('[check_s] done')
def authenticate(self, environ, identity): log.debug("Authentication through repoze.") username = None realm = None options = {} realmbox = "False" authenticate = True if isSelfTest(): authenticate = False try: if isSelfTest(): if ('login' not in identity and 'repoze.who.plugins.auth_tkt.userid' in identity): u = identity.get('repoze.who.plugins.auth_tkt.userid') identity['login'] = u identity['password'] = u username = identity['login'] realm = identity['realm'] password = identity['password'] options.update(identity) realmbox = options.get("realmbox", "False") except KeyError as e: log.exception("Keyerror in repoze identity: %r." % e) return None # convert string to boolean realm_mbox = False if realmbox.lower() == 'true': realm_mbox = True # check username/realm, password with request_context_safety(): linotp_config = getLinotpConfig() request_context['Config'] = linotp_config # add the cache manager to the context glo = getGlobalObject() cache_manager = glo.cache_manager request_context['CacheManager'] = cache_manager # and also add the hsm - enables us to do otp validation :-) sep = glo.security_provider hsm = sep.getSecurityModule() request_context['hsm'] = hsm # initialize the base context # - copied for the dumb repoze middleware cache_dir = config.get("app_conf", {}).get("cache_dir", None) setupResolvers(config=linotp_config, cache_dir=cache_dir) resolver_context = initResolvers() request_context.update(resolver_context) # prepare the request local user cache if 'UserLookup' not in request_context: request_context['UserLookup'] = {} user = get_authenticated_user(username, realm, password, realm_box=realm_mbox, authenticate=authenticate, options=options) if not user: return None authUser = "******" % (user.login, user.realm) return authUser
def _check(self, param): ''' basic check function, that can be used by different controllers :param param: dict of all caller parameters :type param: dict :return: Tuple of True or False and opt :rtype: Tuple(boolean, opt) ''' opt = None options = {} ## put everythin in the options but the user, pass, init options.update(param) for para in ["pass", "user", "init"]: if options.has_key(para): del options[para] passw = getParam(param, "pass", optional) user = getUserFromParam(param, optional) # support for ocra application challenge verification challenge = getParam(param, "challenge", optional) if challenge is not None: options = {} options['challenge'] = challenge c.audit['user'] = user.login realm = user.realm or getDefaultRealm() c.audit['realm'] = realm # AUTHORIZATION Pre Check # we need to overwrite the user.realm in case the user does not exist in the original realm (setrealm-policy) user.realm = set_realm(user.login, realm, exception=True) check_user_authorization(user.login, user.realm, exception=True) if isSelfTest() is True: initTime = getParam(param, "init", optional) if initTime is not None: if options is None: options = {} options['initTime'] = initTime vh = ValidationHandler() (ok, opt) = vh.checkUserPass(user, passw, options=options) c.audit.update(request_context.get('audit')) c.audit['success'] = ok if ok: # AUTHORIZATION post check check_auth_tokentype(c.audit['serial'], exception=True, user=user) check_auth_serial(c.audit['serial'], exception=True, user=user) # add additional details if is_auth_return(ok, user=user): if opt is None: opt = {} if ok: opt['realm'] = c.audit.get('realm') opt['user'] = c.audit.get('user') opt['tokentype'] = c.audit.get('token_type') opt['serial'] = c.audit.get('serial') else: opt['error'] = c.audit.get('action_detail') return (ok, opt)
def check_s(self): """ This function is used to validate the serial and the otp value/password. method: validate/check_s arguments: * serial: the serial number of the token * pass: the password that consists of a possible fixes password component and the OTP value returns: JSON response """ param = {} param.update(request.params) options = {} options.update(param) for k in ["user", "serial", "pass", "init"]: if k in options: del options[k] if "init" in param: if isSelfTest() == True: options["initTime"] = param.get("init") try: passw = getParam(param, "pass", optional) serial = getParam(param, "serial", optional) if serial is None: user = getParam(param, "user", optional) if user is not None: user = getUserFromParam(param, optional) toks = getTokens4UserOrSerial(user=user) if len(toks) == 0: raise Exception("No token found!") elif len(toks) > 1: raise Exception("More than one token found!") else: tok = toks[0].token desc = tok.get() realms = desc.get("LinOtp.RealmNames") if realms is None or len(realms) == 0: realm = getDefaultRealm() elif len(realms) > 0: realm = realms[0] userInfo = getUserInfo(tok.LinOtpUserid, tok.LinOtpIdResolver, tok.LinOtpIdResClass) user = User(login=userInfo.get("username"), realm=realm) serial = tok.getSerial() c.audit["serial"] = serial if isSelfTest() == True: initTime = getParam(param, "init", optional) if initTime is not None: if options is None: options = {} options["initTime"] = initTime (ok, opt) = checkSerialPass(serial, passw, options=options) c.audit["success"] = ok Session.commit() qr = getParam(param, "qr", optional) if qr is not None and opt is not None and opt.has_key("message"): try: dataobj = opt.get("message") param["alt"] = "%s" % opt return sendQRImageResult(response, dataobj, param) except Exception as exc: log.warning("failed to send QRImage: %r " % exc) return sendQRImageResult(response, opt, param) else: return sendResult(response, ok, 0, opt=opt) except Exception as exx: log.error("[check_s] validate/check_s failed: %r" % exx) log.error("[check_s] %s" % traceback.format_exc()) c.audit["info"] = unicode(exx) Session.rollback() return sendError(response, "validate/check_s failed: %s" % unicode(exx), 0) finally: Session.close() log.debug("[check_s] done")
def __before__(self, action): ''' This is the authentication to self service If you want to do ANYTHING with selfservice, you need to be authenticated. The _before_ is executed before any other function in this controller. ''' try: param = request.params audit.initialize() c.audit['success'] = False c.audit['client'] = get_client() c.version = get_version() c.licenseinfo = get_copyright_info() if isSelfTest(): log.debug("[__before__] Doing selftest!") uuser = getParam(param, "selftest_user", True) if uuser is not None: (c.user, _foo, c.realm) = uuser.rpartition('@') else: c.realm = "" c.user = "******" env = request.environ uuser = env.get('REMOTE_USER') if uuser is not None: (c.user, _foo, c.realm) = uuser.rpartition('@') self.authUser = User(c.user, c.realm, '') log.debug("[__before__] authenticating as %s in realm %s!" % (c.user, c.realm)) else: # Use WebAuth instead of LinOTP auth. identity = request.environ.get('REMOTE_USER') if identity is None: abort(401, "You are not authenticated") c.user = identity # Put their current realm as the first one we find them in. # Doesn't really matter since tokens are realm-independent. realms = getAllUserRealms(User(identity, "", "")) if (realms): c.realm = realms[0] self.authUser = User(c.user, c.realm, '') # Check token expiry. age = int(request.environ.get('WEBAUTH_TOKEN_EXPIRATION')) - time.time() # Set selfservice cookie response.set_cookie('linotp_selfservice', 'REMOTE_USER', max_age = int(age)) # Set userservice auth cookie self.client = get_client() authcookie = create_auth_cookie(config, identity, self.client) response.set_cookie('userauthcookie', authcookie, max_age=360*24) log.debug("[__before__] set the self.authUser to: %s, %s " % (self.authUser.login, self.authUser.realm)) log.debug('[__before__] param for action %s: %s' % (action, param)) # checking the session if (False == check_selfservice_session(request.url, request.path, request.cookies, request.params)): c.audit['action'] = request.path[1:] c.audit['info'] = "session expired" audit.log(c.audit) abort(401, "No valid session") c.imprint = get_imprint(c.realm) c.tokenArray = [] c.user = self.authUser.login c.realm = self.authUser.realm c.tokenArray = getTokenForUser(self.authUser) # only the defined actions should be displayed # - remark: the generic actions like enrollTT are allready approved # to have a rendering section and included actions = getSelfserviceActions(self.authUser) c.actions = actions for policy in actions: if "=" in policy: (name, val) = policy.split('=') val = val.strip() # try if val is a simple numeric - # w.r.t. javascript evaluation try: nval = int(val) except: nval = val c.__setattr__(name.strip(), nval) c.dynamic_actions = add_dynamic_selfservice_enrollment(config, c.actions) # we require to establish all token local defined # policies to be initialiezd additional_policies = add_dynamic_selfservice_policies(config, actions) for policy in additional_policies: c.__setattr__(policy, -1) c.otplen = -1 c.totp_len = -1 return response except webob.exc.HTTPUnauthorized as acc: # the exception, when an abort() is called if forwarded log.info("[__before__::%r] webob.exception %r" % (action, acc)) log.info("[__before__] %s" % traceback.format_exc()) Session.rollback() Session.close() raise acc except Exception as e: log.error("[__before__] failed with error: %r" % e) log.error("[__before__] %s" % traceback.format_exc()) Session.rollback() Session.close() return sendError(response, e, context='before') finally: log.debug('[__before__] done')
def check_s(self): ''' This function is used to validate the serial and the otp value/password. method: validate/check_s arguments: * serial: the serial number of the token * pass: the password that consists of a possible fixes password component and the OTP value returns: JSON response ''' param = self.request_params options = {} options.update(param) for k in ['user', 'serial', "pass", "init"]: if k in options: del options[k] if 'init' in param: if isSelfTest() is True: options['initTime'] = param.get('init') try: passw = param.get("pass") serial = param.get('serial') if serial is None: user = param.get('user') if user is not None: user = getUserFromParam(param) toks = getTokens4UserOrSerial(user=user) if len(toks) == 0: raise Exception("No token found!") elif len(toks) > 1: raise Exception("More than one token found!") else: tok = toks[0].token desc = tok.get() realms = desc.get('LinOtp.RealmNames') if realms is None or len(realms) == 0: realm = getDefaultRealm() elif len(realms) > 0: realm = realms[0] userInfo = getUserInfo(tok.LinOtpUserid, tok.LinOtpIdResolver, tok.LinOtpIdResClass) user = User(login=userInfo.get('username'), realm=realm) serial = tok.getSerial() c.audit['serial'] = serial if isSelfTest() is True: initTime = param.get("init") if initTime is not None: if options is None: options = {} options['initTime'] = initTime options['scope'] = {"check_s": True} vh = ValidationHandler() (ok, opt) = vh.checkSerialPass(serial, passw, options=options) c.audit['success'] = ok Session.commit() qr = param.get('qr', None) if qr and opt and 'message' in opt: try: dataobj = opt.get('message') param['alt'] = "%s" % opt if 'transactionid' in opt: param['transactionid'] = opt['transactionid'] return sendQRImageResult(response, dataobj, param) except Exception as exc: log.warning("failed to send QRImage: %r " % exc) return sendQRImageResult(response, opt, param) else: return sendResult(response, ok, 0, opt=opt) except Exception as exx: log.exception("[check_s] validate/check_s failed: %r" % exx) c.audit['info'] = unicode(exx) Session.rollback() return sendResult(response, False, id=0, status=False) finally: Session.close()
def __before__(self, action): ''' This is the authentication to self service If you want to do ANYTHING with selfservice, you need to be authenticated. The _before_ is executed before any other function in this controller. ''' try: param = request.params audit.initialize() c.audit['success'] = False c.audit['client'] = get_client() c.version = get_version() c.licenseinfo = get_copyright_info() if isSelfTest(): log.debug("[__before__] Doing selftest!") uuser = getParam(param, "selftest_user", True) if uuser is not None: (c.user, _foo, c.realm) = uuser.rpartition('@') else: c.realm = "" c.user = "******" env = request.environ uuser = env.get('REMOTE_USER') if uuser is not None: (c.user, _foo, c.realm) = uuser.rpartition('@') if c.user in ['--u--']: abort(401, "No valid session") self.authUser = User(c.user, c.realm, '') log.debug("[__before__] authenticating as %s in realm %s!" % (c.user, c.realm)) else: identity = request.environ.get('repoze.who.identity') if identity is None: abort(401, "You are not authenticated") log.debug("[__before__] doing getAuthFromIdentity in action %s" % action) user_id = request.environ.get('repoze.who.identity')\ .get('repoze.who.userid') if type(user_id) == unicode: user_id = user_id.encode(ENCODING) identity = user_id.decode(ENCODING) log.debug("[__before__] getting identity from repoze.who: %r" % identity) (c.user, _foo, c.realm) = identity.rpartition('@') self.authUser = User(c.user, c.realm, '') log.debug("[__before__] set the self.authUser to: %s, %s " % (self.authUser.login, self.authUser.realm)) log.debug('[__before__] param for action %s: %s' % (action, param)) # checking the session if (False == check_selfservice_session(request.url, request.path, request.cookies, request.params )): c.audit['action'] = request.path[1:] c.audit['info'] = "session expired" audit.log(c.audit) abort(401, "No valid session") c.imprint = get_imprint(c.realm) c.tokenArray = [] c.user = self.authUser.login c.realm = self.authUser.realm c.tokenArray = getTokenForUser(self.authUser) # only the defined actions should be displayed # - remark: the generic actions like enrollTT are allready approved # to have a rendering section and included actions = getSelfserviceActions(self.authUser) c.actions = actions for policy in actions: if "=" in policy: (name, val) = policy.split('=') val = val.strip() # try if val is a simple numeric - # w.r.t. javascript evaluation try: nval = int(val) except: nval = val c.__setattr__(name.strip(), nval) c.dynamic_actions = add_dynamic_selfservice_enrollment(config, c.actions) # we require to establish all token local defined # policies to be initialiezd additional_policies = add_dynamic_selfservice_policies(config, actions) for policy in additional_policies: c.__setattr__(policy, -1) c.otplen = -1 c.totp_len = -1 return response except webob.exc.HTTPUnauthorized as acc: # the exception, when an abort() is called if forwarded log.info("[__before__::%r] webob.exception %r" % (action, acc)) log.info("[__before__] %s" % traceback.format_exc()) Session.rollback() Session.close() raise acc except Exception as e: log.error("[__before__] failed with error: %r" % e) log.error("[__before__] %s" % traceback.format_exc()) Session.rollback() Session.close() return sendError(response, e, context='before') finally: log.debug('[__after__] done')
def authenticate(self, environ, identity): log.info("[authenticate] entering repoze authenticate function.") # log.debug( identity ) username = None realm = None options = {} realmbox = "False" authenticate = True if isSelfTest(): authenticate = False try: if isSelfTest(): if ('login' not in identity and 'repoze.who.plugins.auth_tkt.userid' in identity): u = identity.get('repoze.who.plugins.auth_tkt.userid') identity['login'] = u identity['password'] = u username = identity['login'] realm = identity['realm'] password = identity['password'] options.update(identity) realmbox = options.get("realmbox", "False") except KeyError as e: log.exception("[authenticate] Keyerror in identity: %r." % e) return None # convert string to boolean realm_mbox = False if realmbox.lower() == 'true': realm_mbox = True # check username/realm, password with request_context_safety(): linotp_config = getLinotpConfig() request_context['Config'] = linotp_config # add the cache manager to the context glo = getGlobalObject() cache_manager = glo.cache_manager request_context['CacheManager'] = cache_manager # and also add the hsm - enables us to do otp validation :-) sep = glo.security_provider hsm = sep.getSecurityModule() request_context['hsm'] = hsm resolver_context = initResolvers() request_context.update(resolver_context) user = get_authenticated_user(username, realm, password, realm_box=realm_mbox, authenticate=authenticate, options=options) if not user: return None authUser = "******" % (user.login, user.realm) return authUser
def check_s(self): ''' This function is used to validate the serial and the otp value/password. method: validate/check_s arguments: * serial: the serial number of the token * pass: the password that consists of a possible fixes password component and the OTP value returns: JSON response ''' param = {} param.update(request.params) options = {} options.update(param) for k in ['user', 'serial', "pass", "init"]: if k in options: del options[k] if 'init' in param: if isSelfTest() == True: options['initTime'] = param.get('init') try: passw = getParam(param, "pass", optional) serial = getParam(param, 'serial', optional) if serial is None: user = getParam(param, 'user', optional) if user is not None: user = getUserFromParam(param, optional) toks = getTokens4UserOrSerial(user=user) if len(toks) == 0: raise Exception("No token found!") elif len(toks) > 1: raise Exception("More than one token found!") else: tok = toks[0].token desc = tok.get() realms = desc.get('LinOtp.RealmNames') if realms is None or len(realms) == 0: realm = getDefaultRealm() elif len(realms) > 0: realm = realms[0] userInfo = getUserInfo(tok.LinOtpUserid, tok.LinOtpIdResolver, tok.LinOtpIdResClass) user = User(login=userInfo.get('username'), realm=realm) serial = tok.getSerial() c.audit['serial'] = serial if isSelfTest() == True: initTime = getParam(param, "init", optional) if initTime is not None: if options is None: options = {} options['initTime'] = initTime (ok, opt) = checkSerialPass(serial, passw, options=options) c.audit['success'] = ok Session.commit() qr = getParam(param, 'qr', optional) if qr is not None and opt is not None and opt.has_key('message'): try: dataobj = opt.get('message') param['alt'] = "%s" % opt return sendQRImageResult(response, dataobj, param) except Exception as exc: log.warning("failed to send QRImage: %r " % exc) return sendQRImageResult(response, opt, param) else: return sendResult(response, ok, 0, opt=opt) except Exception as exx: log.error("[check_s] validate/check_s failed: %r" % exx) log.error("[check_s] %s" % traceback.format_exc()) c.audit['info'] = unicode(exx) Session.rollback() return sendError(response, "validate/check_s failed: %s" % unicode(exx), 0) finally: Session.close() log.debug('[check_s] done')