def tokeninfo(self): ''' this returns the contents of /admin/show?serial=xyz in a html format ''' param = request.params try: serial = getParam(param, 'serial', required) filterRealm = "" # check admin authorization res = checkPolicyPre('admin', 'show', param) filterRealm = res['realms'] # check if policies are active at all # If they are not active, we are allowed to SHOW any tokens. pol = getAdminPolicies("show") if not pol['active']: filterRealm = ["*"] log.info("[tokeninfo] admin >%s< may display the following realms: %s" % (res['admin'], filterRealm)) log.info("[tokeninfo] displaying tokens: serial: %s", serial) toks = TokenIterator(User("", "", ""), serial, filterRealm=filterRealm) ### now row by row lines = [] for tok in toks: lines.append(tok) if len(lines) > 0: c.tokeninfo = lines[0] else: c.tokeninfo = {} for k in c.tokeninfo: if "LinOtp.TokenInfo" == k: try: # Try to convert string to Dictionary c.tokeninfo['LinOtp.TokenInfo'] = json.loads(c.tokeninfo['LinOtp.TokenInfo']) except: pass return render('/manage/tokeninfo.mako') except PolicyException as pe: log.error("[tokeninfo] Error during checking policies: %r" % pe) log.error("[tokeninfo] %s" % traceback.format_exc()) Session.rollback() return sendError(response, unicode(pe), 1) except Exception as e: log.error("[tokeninfo] failed! %r" % e) log.error("[tokeninfo] %s" % traceback.format_exc()) Session.rollback() return sendError(response, e) finally: Session.close() log.debug('[tokeninfo] done')
def delete_all(self): """ method: reporting/delete_all description: delete the reporting database table returns: dict in which value is the number of deleted rows exception: if an error occurs an exception is serialized and returned """ try: result = delete_reporting() Session.commit() return sendResult(response, result) except PolicyException as policy_exception: log.exception(policy_exception) Session.rollback() return sendError(response, unicode(policy_exception), 1) except Exception as exc: log.exception(exc) Session.rollback() return sendError(response, exc) finally: Session.close() log.debug('[delete_all] done')
def activeUsers(self): """ method: monitoring/activeUsers description: for each realm, display the resolvers and the number of users which have at least one assigned active token per resolver the 'total' gives the number of all users, which are in an allowed realm and own an active token users are conted per resolver (not per realm), so if resolver is in multiple realms and one user ons tokens in 2 realms, the user will be counted only once arguments: * realms - optional: takes realms, only information on these realms will be displayed """ result = {} try: param = request.params request_realms = param.get('realms', '').split(',') monit_handl = MonitorHandler() policies = getAdminPolicies('activeUsers', scope='monitoring') realm_whitelist = [] if policies['active'] and policies['realms']: realm_whitelist = policies.get('realms') # if there are no policies for us, we are allowed to see all realms if not realm_whitelist or '*' in realm_whitelist: realm_whitelist = request_context['Realms'].keys() realms = match_realms(request_realms, realm_whitelist) realm_info = {} for a_realm in realms: realm_info[a_realm] = monit_handl.active_users_per_realm(a_realm) result['Realms'] = realm_info result['total'] = monit_handl.active_users_total(realms) return sendResult(response, result) except PolicyException as policy_exception: log.exception(policy_exception) Session.rollback() return sendError(response, unicode(policy_exception), 1) except Exception as exc: log.exception(exc) Session.rollback() return sendError(response, exc) finally: Session.close() log.debug('[resolvers] done')
def tokeninfo(self): ''' this returns the contents of /admin/show?serial=xyz in an html format ''' param = self.request_params try: try: serial = param['serial'] except KeyError: raise ParameterError("Missing parameter: 'serial'") filterRealm = "" # check admin authorization res = checkPolicyPre('admin', 'show', param) # check if policies are active at all # If they are not active, we are allowed to SHOW any tokens. filterRealm = ["*"] if res['active'] and res['realms']: filterRealm = res['realms'] log.info("[tokeninfo] admin >%s< may display the following realms:" " %s" % (res['admin'], filterRealm)) log.info("[tokeninfo] displaying tokens: serial: %s", serial) toks = TokenIterator(User("", "", ""), serial, filterRealm=filterRealm) # now row by row lines = [] for tok in toks: lines.append(tok) if len(lines) > 0: c.tokeninfo = lines[0] else: c.tokeninfo = {} for k in c.tokeninfo: if "LinOtp.TokenInfo" == k: try: # Try to convert string to Dictionary c.tokeninfo['LinOtp.TokenInfo'] = json.loads( c.tokeninfo['LinOtp.TokenInfo']) except: pass return render('/manage/tokeninfo.mako').decode('utf-8') except PolicyException as pe: log.exception("[tokeninfo] Error during checking policies: %r" % pe) db.session.rollback() return sendError(response, str(pe), 1) except Exception as e: log.exception("[tokeninfo] failed! %r" % e) db.session.rollback() return sendError(response, e)
def activeUsers(self): """ method: monitoring/activeUsers description: for each realm, display the resolvers and the number of users which have at least one assigned active token per resolver the 'total' gives the number of all users, which are in an allowed realm and own an active token users are conted per resolver (not per realm), so if resolver is in multiple realms and one user ons tokens in 2 realms, the user will be counted only once arguments: * realms - optional: takes realms, only information on these realms will be displayed """ result = {} try: param = request.params request_realms = param.get('realms', '').split(',') monit_handl = MonitorHandler() policies = getAdminPolicies('activeUsers', scope='monitoring') realm_whitelist = [] if policies['active'] and policies['realms']: realm_whitelist = policies.get('realms') # if there are no policies for us, we are allowed to see all realms if not realm_whitelist or '*' in realm_whitelist: realm_whitelist = request_context['Realms'].keys() realms = match_realms(request_realms, realm_whitelist) realm_info = {} for a_realm in realms: realm_info[a_realm] = monit_handl.active_users_per_realm( a_realm) result['Realms'] = realm_info result['total'] = monit_handl.active_users_total(realms) return sendResult(response, result) except PolicyException as policy_exception: log.exception(policy_exception) Session.rollback() return sendError(response, unicode(policy_exception), 1) except Exception as exc: log.exception(exc) Session.rollback() return sendError(response, exc) finally: Session.close()
def tokeninfo(self): """ this returns the contents of /admin/show?serial=xyz in a html format """ param = request.params try: serial = getParam(param, "serial", required) filterRealm = "" # check admin authorization res = checkPolicyPre("admin", "show", param) filterRealm = res["realms"] # check if policies are active at all # If they are not active, we are allowed to SHOW any tokens. pol = getAdminPolicies("show") if not pol["active"]: filterRealm = ["*"] log.info("[tokeninfo] admin >%s< may display the following realms: %s" % (res["admin"], filterRealm)) log.info("[tokeninfo] displaying tokens: serial: %s", serial) toks = TokenIterator(User("", "", ""), serial, filterRealm=filterRealm) ### now row by row lines = [] for tok in toks: lines.append(tok) if len(lines) > 0: c.tokeninfo = lines[0] else: c.tokeninfo = {} for k in c.tokeninfo: if "LinOtp.TokenInfo" == k: try: # Try to convert string to Dictionary c.tokeninfo["LinOtp.TokenInfo"] = json.loads(c.tokeninfo["LinOtp.TokenInfo"]) except: pass return render("/manage/tokeninfo.mako") except PolicyException as pe: log.error("[tokeninfo] Error during checking policies: %r" % pe) log.error("[tokeninfo] %s" % traceback.format_exc()) Session.rollback() return sendError(response, unicode(pe), 1) except Exception as e: log.error("[tokeninfo] failed! %r" % e) log.error("[tokeninfo] %s" % traceback.format_exc()) Session.rollback() return sendError(response, e) finally: Session.close() log.debug("[tokeninfo] done")
def __before__(self, action, **params): """ """ try: log.debug("[__before__::%r] %r" % (action, params)) # Session handling check_session(request) checkToolsAuthorisation(action, params) c.audit = request_context['audit'] return request except PolicyException as exx: log.exception("policy failed %r" % exx) Session.rollback() Session.close() return sendError(response, exx, context='before') except Exception as exx: log.exception("[__before__::%r] exception %r" % (action, exx)) Session.rollback() Session.close() return sendError(response, exx, context='before') finally: log.debug("[__before__::%r] done" % (action))
def __before__(self, **params): """ __before__ is called before every action :param params: list of named arguments :return: -nothing- or in case of an error a Response created by sendError with the context info 'before' """ action = request_context['action'] try: # Session handling check_session(request) checkToolsAuthorisation(action, params) c.audit = request_context['audit'] return except PolicyException as exx: log.exception("policy failed %r" % exx) Session.rollback() Session.close() return sendError(response, exx, context='before') except Exception as exx: log.exception("[__before__::%r] exception %r" % (action, exx)) Session.rollback() Session.close() return sendError(response, exx, context='before')
def userinfo(self): """ method: monitoring/userinfo description: for each realm, display the resolvers and the number of users per resolver arguments: * realms - optional: takes a realm, only information on this realm will be displayed returns: a json result with: { "head": [], "data": [ [row1], [row2] .. ] } """ result = {} try: request_realms = self.request_params.get("realms", "").split(",") monit_handler = MonitorHandler() policies = getAdminPolicies("userinfo", scope="monitoring") realm_whitelist = [] if policies["active"] and policies["realms"]: realm_whitelist = policies.get("realms") # if there are no policies for us, we are allowed to see all realms if not realm_whitelist or "*" in realm_whitelist: realm_whitelist = list(request_context["Realms"].keys()) realms = match_realms(request_realms, realm_whitelist) if "/:no realm:/" in realms: realms.remove("/:no realm:/") realm_info = {} for a_realm in realms: realm_info[a_realm] = monit_handler.resolverinfo(a_realm) result["Realms"] = realm_info db.session.commit() return sendResult(response, result) except PolicyException as policy_exception: log.error(policy_exception) db.session.rollback() return sendError(response, policy_exception, 1) except Exception as exc: log.error(exc) db.session.rollback() return sendError(response, exc)
def tokeninfo(self): ''' this returns the contents of /admin/show?serial=xyz in an html format ''' param = request.params try: serial = getParam(param, 'serial', required) filterRealm = "" # check admin authorization res = checkPolicyPre('admin', 'show', param) # check if policies are active at all # If they are not active, we are allowed to SHOW any tokens. filterRealm = ["*"] if res['active'] and res['realms']: filterRealm = res['realms'] log.info("[tokeninfo] admin >%s< may display the following realms:" " %s" % (res['admin'], filterRealm)) log.info("[tokeninfo] displaying tokens: serial: %s", serial) toks = TokenIterator(User("", "", ""), serial, filterRealm=filterRealm) # now row by row lines = [] for tok in toks: lines.append(tok) if len(lines) > 0: c.tokeninfo = lines[0] else: c.tokeninfo = {} for k in c.tokeninfo: if "LinOtp.TokenInfo" == k: try: # Try to convert string to Dictionary c.tokeninfo['LinOtp.TokenInfo'] = json.loads( c.tokeninfo['LinOtp.TokenInfo']) except: pass return render('/manage/tokeninfo.mako') except PolicyException as pe: log.exception("[tokeninfo] Error during checking policies: %r" % pe) Session.rollback() return sendError(response, unicode(pe), 1) except Exception as e: log.exception("[tokeninfo] failed! %r" % e) Session.rollback() return sendError(response, e) finally: Session.close() log.debug('[tokeninfo] done')
def activeUsers(self): """ method: monitoring/activeUsers description: for each realm, display the resolvers and the number of users which have at least one assigned active token per resolver the 'total' gives the number of all users, which are in an allowed realm and own an active token users are conted per resolver (not per realm), so if resolver is in multiple realms and one user ons tokens in 2 realms, the user will be counted only once arguments: * realms - optional: takes realms, only information on these realms will be displayed """ result = {} try: request_realms = self.request_params.get("realms", "").split(",") monit_handl = MonitorHandler() policies = getAdminPolicies("activeUsers", scope="monitoring") realm_whitelist = [] if policies["active"] and policies["realms"]: realm_whitelist = policies.get("realms") # if there are no policies for us, we are allowed to see all realms if not realm_whitelist or "*" in realm_whitelist: realm_whitelist = list(request_context["Realms"].keys()) realms = match_realms(request_realms, realm_whitelist) realm_info = {} for a_realm in realms: realm_info[a_realm] = monit_handl.active_users_per_realm( a_realm ) result["Realms"] = realm_info result["total"] = monit_handl.active_users_total(realms) return sendResult(response, result) except PolicyException as policy_exception: log.error(policy_exception) db.session.rollback() return sendError(response, policy_exception, 1) except Exception as exc: log.error(exc) db.session.rollback() return sendError(response, exc)
def delete_all(self): """ method: reporting/delete_all description: delete the reporting database table returns: dict in which value is the number of deleted rows exception: if an error occurs an exception is serialized and returned """ try: param = request.params request_realms = param.get('realms', '').split(',') status = param.get('status', ['total']) if status != ['total']: status = status.split(',') realm_whitelist = [] policies = getAdminPolicies('tokens', scope='monitoring') if policies['active'] and policies['realms']: realm_whitelist = policies.get('realms') # if there are no policies for us, we are allowed to see all realms if not realm_whitelist or '*' in realm_whitelist: realm_whitelist = request_context['Realms'].keys() realms = match_realms(request_realms, realm_whitelist) if '*' in status: status.remove('*') status.extend(['active', 'inactive', 'assigned', 'unassigned', 'active&assigned', 'active&unassigned', 'inactive&assigned', 'inactive&unassigned', 'total']) result = delete(realms=realms, status=status) Session.commit() return sendResult(response, result) except PolicyException as policy_exception: log.exception(policy_exception) Session.rollback() return sendError(response, unicode(policy_exception), 1) except Exception as exc: log.exception(exc) Session.rollback() return sendError(response, exc) finally: Session.close() log.debug('[delete_all] done')
def getActivationCode(self): ''' method: orcra/getActivationCode description: returns an valid example activcation code arguments: ./. returns: JSON with "activationcode": "JZXW4ZI=2A" ''' from linotp.lib.crypt import createActivationCode res = {} #description = 'ocra/getActivationCode' try: params = getLowerParams(request.params) log.debug("[getActivationCode]: %r" % params) checkPolicyPre('ocra', "activationcode") ac = str(params.get('activationcode')) activationCode = createActivationCode(acode=ac) res = {'activationcode': activationCode} Session.commit() return sendResult(response, res, 1) except PolicyException as pe: log.error("[getActivationCode] policy failed: %r" % pe) log.error("[getActivationCode] %s" % traceback.format_exc()) Session.rollback() return sendError(response, unicode(pe)) except Exception as exx: log.error("[getActivationCode] failed: %r" % exx) log.error("[getActivationCode] %s" % traceback.format_exc()) Session.rollback() return sendError(response, unicode(exx), 0) finally: Session.close() log.debug('[getActivationCode] done')
def getActivationCode(self): ''' method: ocra/getActivationCode description: returns an valid example activcation code arguments: ./. returns: JSON with "activationcode": "JZXW4ZI=2A" ''' from linotp.lib.crypt import createActivationCode res = {} #description = 'ocra/getActivationCode' try: params = getLowerParams(request.params) log.debug("[getActivationCode]: %r" % params) checkPolicyPre('ocra', "activationcode") ac = str(params.get('activationcode')) activationCode = createActivationCode(acode=ac) res = {'activationcode':activationCode} Session.commit() return sendResult(response, res, 1) except PolicyException as pe: log.error("[getActivationCode] policy failed: %r" % pe) log.error("[getActivationCode] %s" % traceback.format_exc()) Session.rollback() return sendError(response, unicode(pe)) except Exception as exx: log.error("[getActivationCode] failed: %r" % exx) log.error("[getActivationCode] %s" % traceback.format_exc()) Session.rollback() return sendError(response, unicode(exx), 0) finally: Session.close() log.debug('[getActivationCode] done')
def __before__(self, **params): """ __before__ is called before every action :param params: list of named arguments :return: -nothing- or in case of an error a Response created by sendError with the context info 'before' """ action = request_context['action'] try: c.audit = request_context['audit'] c.audit['success'] = False c.audit['client'] = get_client(request) c.version = get_version() c.version_ref = base64.encodebytes(c.version.encode())[:6] c.licenseinfo = get_copyright_info() c.polDefs = getPolicyDefinitions() c.display_provider = boolean( request_context['Config'].get('display_provider', True)) # -------------------------------------------------------------- -- # check for support of setting admin password c.admin_can_change_password = False if ('linotpadmin.user' in config and 'linotpadmin.password' in config): c.admin_can_change_password = True # -------------------------------------------------------------- -- # Session handling for the functions, that show data: # Also exclude custom-style.css, since the CSRF check # will always fail and return a HTTP 401 anyway. # A HTTP 404 makes more sense. if request.path.lower() in ['/manage/', '/manage', '/manage/logout', '/manage/audittrail', '/manage/policies', '/manage/tokenview', '/manage/userview', '/manage/help', '/manage/custom-style.css']: pass else: check_session(request) except Exception as exx: log.exception("[__before__::%r] exception %r" % (action, exx)) Session.rollback() Session.close() return sendError(response, exx, context='before') finally: log.debug("[__before__::%r] done" % (action))
def __before__(self, action, **params): """ """ try: log.debug('[__before__::%r] %r', action, params) audit.initialize() c.audit['success'] = False c.audit['client'] = get_client(request) # Session handling check_session(request) self.request_context['Audit'] = audit return request except Exception as exception: log.exception(exception) Session.rollback() Session.close() return sendError(response, exception, context='before') finally: log.debug('[__before__::%r] done', action)
def login(self): log.debug("[login] selfservice login screen") identity = request.environ.get('repoze.who.identity') if identity is not None: # After login We always redirect to the start page redirect("/") res = {} try: c.defaultRealm = getDefaultRealm() res = getRealms() c.realmArray = [] #log.debug("[login] %s" % str(res) ) for (k, v) in res.items(): c.realmArray.append(k) c.realmbox = getRealmBox() log.debug("[login] displaying realmbox: %i" % int(c.realmbox)) Session.commit() response.status = '%i Logout from LinOTP selfservice' % LOGIN_CODE return render('/selfservice/login.mako') except Exception as e: log.exception('[login] failed %r' % e) Session.rollback() return sendError(response, e) finally: Session.close()
def __before__(self, action, **params): """ Here we see, what action is to be called and check the authorization """ log.debug("[__before__::%r] %r" % (action, params)) try: audit.initialize() c.audit["success"] = False c.audit["client"] = get_client() if action != "check_t": check_session() return response except webob.exc.HTTPUnauthorized as acc: ## the exception, when an abort() is called if forwarded log.exception("[__before__::%r] webob.exception %r" % (action, acc)) Session.rollback() Session.close() raise acc except Exception as exx: log.exception("[__before__::%r] exception %r" % (action, exx)) Session.rollback() Session.close() return sendError(response, exx, context="before") finally: log.debug("[__before__::%r] done" % (action))
def check_yubikey(self): ''' This function is used to validate the output of a yubikey method: validate/check_yubikey :param pass: The password that consist of the static yubikey prefix and the otp :type pass: string :return: JSON Object returns: JSON response:: { "version": "LinOTP 2.4", "jsonrpc": "2.0", "result": { "status": true, "value": false }, "detail" : { "username": username, "realm": realm }, "id": 0 } ''' param = request.params passw = getParam(param, "pass", required) try: ok = False try: ok, opt = checkYubikeyPass(passw) c.audit['success'] = ok except AuthorizeException as exx: log.warning("[check_yubikey] authorization failed for validate/check_yubikey: %r" % exx) c.audit['success'] = False c.audit['info'] = unicode(exx) ok = False Session.commit() return sendResult(response, ok, 0, opt=opt) except Exception as exx: log.error("[check_yubikey] validate/check_yubikey failed: %r" % exx) log.error("[check_yubikey] %s" % traceback.format_exc()) c.audit['info'] = unicode(exx) Session.rollback() return sendError(response, u"validate/check_yubikey failed: %s" % unicode(exx), 0) finally: Session.close() log.debug('[check_yubikey] done')
def jwt_check(self): """Check whether the current request needs to be authenticated using JWT, and if so, whether it contains a valid JWT access token. The login name from the access token is stored in the request_context['AuthUser'] via quering the jwt identity with get_jwt_identiy for the benefit of `lib.user.getUserFromRequest()`. """ method = request.url_rule.endpoint[request.url_rule.endpoint. rfind(".") + 1:] if method in self.jwt_exempt_methods: log.debug("jwt_check: operation is exempt from JWT check") return None try: verify_jwt_in_request() except ( NoAuthorizationError, ExpiredSignatureError, InvalidSignatureError, CSRFError, ): log.error("jwt_check: Failed JWT authentication") response = sendError(None, "Not authenticated") response.status_code = 401 return response
def __before__(self, action, **params): """ """ try: log.debug('[__before__::%r] %r', action, params) c.audit = request_context['audit'] c.audit['success'] = False c.audit['client'] = get_client(request) # Session handling check_session(request) request_context['Audit'] = audit checkAuthorisation(scope='monitoring', method=action) return request except Exception as exception: log.exception(exception) Session.rollback() Session.close() return sendError(response, exception, context='before') finally: log.debug('[__before__::%r] done', action)
def __before__(self, action, **params): log.debug("[__before__::%r] %r" % (action, params)) try: c.version = get_version() c.licenseinfo = get_copyright_info() except webob.exc.HTTPUnauthorized as acc: ## the exception, when an abort() is called if forwarded log.error("[__before__::%r] webob.exception %r" % (action, acc)) log.error("[__before__] %s" % traceback.format_exc()) Session.rollback() Session.close() raise acc except Exception as exx: log.error("[__before__::%r] exception %r" % (action, exx)) log.error("[__before__] %s" % traceback.format_exc()) Session.rollback() Session.close() return sendError(response, exx, context='before') finally: log.debug("[__before__::%r] done" % (action))
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 "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 migrate_resolver(self): from linotp.lib.tools.migrate_resolver import MigrateResolverHandler ret = {} try: src = self.request_params["from"] target = self.request_params["to"] from linotp.lib.resolver import getResolverList resolvers = getResolverList() src_resolver = resolvers.get(src, None) target_resolver = resolvers.get(target, None) if not target_resolver or not src_resolver: raise Exception("Src or Target resolver is undefined!") mg = MigrateResolverHandler() ret = mg.migrate_resolver(src=src_resolver, target=target_resolver) db.session.commit() return sendResult(response, ret) except Exception as e: log.error("migrate resolver failed") db.session.rollback() return sendError(response, e, 1)
def __before__(self, action, **params): ''' Here we see, what action is to be called and check the authorization ''' log.debug("[__before__::%r] %r" % (action, params)) try: audit.initialize() c.audit['success'] = False c.audit['client'] = get_client() if action != "check_t": check_session() return response except webob.exc.HTTPUnauthorized as acc: ## the exception, when an abort() is called if forwarded log.error("[__before__::%r] webob.exception %r" % (action, acc)) log.error("[__before__] %s" % traceback.format_exc()) Session.rollback() Session.close() raise acc except Exception as exx: log.error("[__before__::%r] exception %r" % (action, exx)) log.error("[__before__] %s" % traceback.format_exc()) Session.rollback() Session.close() return sendError(response, exx, context='before') finally: log.debug("[__before__::%r] done" % (action))
def __before__(self, **params): """ __before__ is called before every action :param params: list of named arguments :return: -nothing- or in case of an error a Response created by sendError with the context info 'before' """ action = request_context['action'] try: c.audit = request_context['audit'] c.audit['success'] = False c.audit['client'] = get_client(request) # Session handling check_session(request) audit = config.get('audit') request_context['Audit'] = audit checkAuthorisation(scope='monitoring', method=action) return except Exception as exception: log.exception(exception) Session.rollback() Session.close() return sendError(response, exception, context='before')
def help(self): ''' This downloads the Manual The filename will be the 3. part,ID https://172.16.200.6/manage/help/somehelp.pdf The file is downloaded through pylons! ''' try: directory = config.get("linotpManual.Directory", "/usr/share/doc/linotp") default_filename = config.get("linotpManual.File", "LinOTP_Manual-en.pdf") headers = [] route_dict = request.environ.get('pylons.routes_dict') filename = route_dict.get('id') if not filename: filename = default_filename + ".gz" headers = [('content-Disposition', 'attachment; filename=\"' + default_filename + '\"'), ('content-Type', 'application/x-gzip') ] from paste.fileapp import FileApp wsgi_app = FileApp("%s/%s" % (directory, filename), headers=headers) Session.commit() return wsgi_app(request.environ, self.start_response) except Exception as e: log.exception("[help] Error loading helpfile: %r" % e) Session.rollback() return sendError(response, e) finally: Session.close()
def __before__(self, **params): """ __before__ is called before every action :param params: list of named arguments :return: -nothing- or in case of an error a Response created by sendError with the context info 'before' """ action = request_context["action"] try: g.audit["success"] = False g.audit["client"] = get_client(request) # Session handling check_session(request) audit = config.get("audit") request_context["Audit"] = audit checkAuthorisation(scope="monitoring", method=action) return except Exception as exception: log.error(exception) db.session.rollback() return sendError(response, exception, context="before")
def webkdc_userinfo(self): # Called by WebAuth via the Elm remctld scripts. # Returns information about whether the user owns any tokens. # TODO: Require some sort of session token. param = {} try: param.update(request.params) user = getUserFromParam(param, optionalOrRequired = True) if (user is not None and user.isEmpty() == False): (userid, idResolver, idResolverClass) = getUserId(user) sqlQuery = Session.query(model.Token).with_lockmode("update").filter( model.Token.LinOtpUserid == userid).filter( model.Token.LinOtpIdResClass == idResolverClass).filter( model.Token.LinOtpIsactive == 1) tokenList = [] for token in sqlQuery: tokenList.append(token.LinOtpTokenSerialnumber) Session.commit() return sendResult(response, tokenList, 0) except Exception as exx: log.error("[webkdc_userinfo] validate/webkdc_userinfo failed: %r" % exx) log.error("[webkdc_userinfo] %s" % traceback.format_exc()) Session.rollback() return sendError(response, u"validate/webkdc_userinfo failed: %s" % unicode(exx), 0) finally: Session.close()
def __after__(response): ''' __after__ is called after every action :param response: the previously created response - for modification :return: return the response ''' try: # finally create the audit entry Audit = request_context['Audit'] audit = request_context.get('audit') c.audit.update(audit) Audit.log(c.audit) Session.commit() return response except Exception as exx: log.exception(exx) Session.rollback() return sendError(response, exx, context='after') finally: Session.close()
def migrate_resolver(self): from linotp.lib.tools.migrate_resolver import MigrateResolverHandler ret = {} try: src = self.request_params['from'] target = self.request_params['to'] from linotp.lib.resolver import getResolverList resolvers = getResolverList() src_resolver = resolvers.get(src, None) target_resolver = resolvers.get(target, None) if not target_resolver or not src_resolver: raise Exception('Src or Target resolver is undefined!') mg = MigrateResolverHandler() ret = mg.migrate_resolver(src=src_resolver, target=target_resolver) Session.commit() return sendResult(response, ret) except Exception as e: log.exception("failed: %r" % e) Session.rollback() return sendError(response, e, 1) finally: Session.close()
def __before__(self, action, **params): log.debug("[__before__::%r] %r" % (action, params)) try: audit.initialize() c.audit['success'] = False c.audit['client'] = get_client(request) c.version = get_version() c.licenseinfo = get_copyright_info() c.polDefs = getPolicyDefinitions() # Session handling for the functions, that show data: # Also exclude custom-style.css, since the CSRF check # will always fail and return a HTTP 401 anyway. # A HTTP 404 makes more sense. if request.path.lower() in [ '/manage/', '/manage', '/manage/logout', '/manage/audittrail', '/manage/policies', '/manage/tokenview', '/manage/userview', '/manage/help', '/manage/custom-style.css' ]: pass else: check_session(request) except Exception as exx: log.exception("[__before__::%r] exception %r" % (action, exx)) Session.rollback() Session.close() return sendError(response, exx, context='before') finally: log.debug("[__before__::%r] done" % (action))
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 __before__(self, action, **params): ''' Here we see, what action is to be called and check the authorization ''' log.debug("[__before__::%r] %r" % (action, params)) try: c.audit = request_context['audit'] c.audit['success'] = False c.audit['client'] = get_client(request) if action != "check_t": check_session(request) request_context['Audit'] = audit return response except webob.exc.HTTPUnauthorized as acc: ## the exception, when an abort() is called if forwarded log.exception("[__before__::%r] webob.exception %r" % (action, acc)) Session.rollback() Session.close() raise acc except Exception as exx: log.exception("[__before__::%r] exception %r" % (action, exx)) Session.rollback() Session.close() return sendError(response, exx, context='before') finally: log.debug("[__before__::%r] done" % (action))
def storageEncryption(self): """ check if hsm/enckey encrypts value before storing it to config db :return: true if a new value gets encryptet before beeing stored in db """ try: if hasattr(c, 'hsm') is False or isinstance(c.hsm, dict) is False: raise HSMException('no hsm defined in execution context!') hsm = c.hsm.get('obj') if hsm is None or hsm.isReady() is False: raise HSMException('hsm not ready!') hsm_class = str(type(hsm)) enc_type = hsm_class.split('.')[-1] enc_type = enc_type.strip("'>") enc_name = hsm.name res = {'cryptmodul_type': enc_type, 'cryptmodul_name': enc_name} monit_handler = MonitorHandler() res['encryption'] = monit_handler.check_encryption() return sendResult(response, res, 1) except Exception as exception: log.exception(exception) return sendError(response, exception) finally: Session.close()
def __before__(self, action, **params): log.debug("[__before__::%r] %r" % (action, params)) try: self.set_language() c.version = get_version() c.licenseinfo = get_copyright_info() except webob.exc.HTTPUnauthorized as acc: ## the exception, when an abort() is called if forwarded log.error("[__before__::%r] webob.exception %r" % (action, acc)) log.error("[__before__] %s" % traceback.format_exc()) Session.rollback() Session.close() raise acc except Exception as exx: log.error("[__before__::%r] exception %r" % (action, exx)) log.error("[__before__] %s" % traceback.format_exc()) Session.rollback() Session.close() return sendError(response, exx, context='before') finally: log.debug("[__before__::%r] done" % (action))
def storageEncryption(self): """ check if hsm/enckey encrypts value before storing it to config db :return: true if a new value gets encryptet before beeing stored in db """ try: if hasattr(c, 'hsm') == False or isinstance(c.hsm, dict) == False: raise HSMException('no hsm defined in execution context!') hsm = c.hsm.get('obj') if hsm is None or hsm.isReady() == False: raise HSMException('hsm not ready!') hsm_class = str(type(hsm)) enc_type = hsm_class.split('.')[-1] enc_type = enc_type.strip("'>") enc_name = hsm.name res = {'cryptmodul_type': enc_type, 'cryptmodul_name': enc_name} monit_handler = MonitorHandler() res['encryption'] = monit_handler.check_encryption() return sendResult(response, res, 1) except Exception as exception: log.exception(exception) return sendError(response, exception) finally: Session.close() log.debug('[encryption] done')
def storageEncryption(self): """ check if hsm/enckey encrypts value before storing it to config db :return: true if a new value gets encryptet before beeing stored in db """ try: if hasattr(c, "hsm") is False or isinstance(c.hsm, dict) is False: raise HSMException("no hsm defined in execution context!") hsm = c.hsm.get("obj") if hsm is None or hsm.isReady() is False: raise HSMException("hsm not ready!") hsm_class = str(type(hsm)) enc_type = hsm_class.split(".")[-1] enc_type = enc_type.strip("'>") enc_name = hsm.name res = {"cryptmodul_type": enc_type, "cryptmodul_name": enc_name} monit_handler = MonitorHandler() res["encryption"] = monit_handler.check_encryption() return sendResult(response, res, 1) except Exception as exception: log.error(exception) return sendError(response, exception)
def __before__(self, action, **params): ''' Here we see, what action is to be called and check the authorization ''' try: c.audit = request_context['audit'] c.audit['success'] = False c.audit['client'] = get_client(request) if action != "check_t": check_session(request) request_context['Audit'] = audit return response except webob.exc.HTTPUnauthorized as acc: # the exception, when an abort() is called if forwarded log.exception("[__before__::%r] webob.exception %r" % (action, acc)) Session.rollback() Session.close() raise acc except Exception as exx: log.exception("[__before__::%r] exception %r" % (action, exx)) Session.rollback() Session.close() return sendError(response, exx, context='before')
def getActivationCode(self): """ method: ocra/getActivationCode description: returns an valid example activcation code arguments: ./. returns: JSON with "activationcode": "JZXW4ZI=2A" """ from linotp.lib.crypt import createActivationCode res = {} # description = 'ocra/getActivationCode' try: params = getLowerParams(request.params) log.debug("[getActivationCode]: %r" % params) checkPolicyPre("ocra", "activationcode", context=self.request_context) ac = str(params.get("activationcode")) activationCode = createActivationCode(acode=ac) res = {"activationcode": activationCode} Session.commit() return sendResult(response, res, 1) except PolicyException as pe: log.exception("[getActivationCode] policy failed: %r" % pe) Session.rollback() return sendError(response, unicode(pe)) except Exception as exx: log.exception("[getActivationCode] failed: %r" % exx) Session.rollback() return sendError(response, unicode(exx), 0) finally: Session.close() log.debug("[getActivationCode] 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.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 delete_before(self): """ method: reporting/delete_before description: delete all entries from reporting database which are older than date date must be given in format: 'yyyy-mm-dd' returns: dict in which value is the number of deleted rows exception: if an error occurs an exception is serialized and returned """ try: param = request.params border_day = param.get('date') # this may throw ValueError if date is in wrong format datetime.strptime(border_day, "%Y-%m-%d") result = delete_before(border_day) Session.commit() return sendResult(response, result) except PolicyException as policy_exception: log.exception(policy_exception) Session.rollback() return sendError(response, unicode(policy_exception), 1) except ValueError as value_error: log.exception(value_error) Session.rollback() return sendError(response, unicode(value_error), 1) except Exception as exc: log.exception(exc) Session.rollback() return sendError(response, exc) finally: Session.close() log.debug('[tokens] 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 samlcheck(self): """ This function is used to validate the username and the otp value/password in a SAML environment. If ``linotp.allowSamlAttributes = True`` then the attributes of the authenticated users are also contained in the response. method: validate/samlcheck arguments: * user: username / loginname * pass: the password that consists of a possible fixes password component and the OTP value * realm: optional realm to match the user to a useridresolver returns: JSON response """ try: opt = None param = request.params (ok, opt) = self._check(param) attributes = {} if True == ok: allowSAML = False try: allowSAML = getFromConfig("allowSamlAttributes") except: log.warning("[samlcheck] Calling controller samlcheck. But allowSamlAttributes == False.") if "True" == allowSAML: ## Now we get the attributes of the user user = getUserFromParam(param, optional) (uid, resId, resIdC) = getUserId(user) userInfo = getUserInfo(uid, resId, resIdC) # users = getUserList({ 'username':user.getUser()} , user) log.debug("[samlcheck] getting attributes for: %s@%s" % (user.getUser(), user.getRealm())) res = userInfo for key in ["username", "surname", "mobile", "phone", "givenname", "email"]: if key in res: attributes[key] = res[key] Session.commit() return sendResult(response, {"auth": ok, "attributes": attributes}, 0, opt) except Exception as exx: log.error("[samlcheck] validate/check failed: %r" % exx) log.error("[samlcheck] %s" % traceback.format_exc()) Session.rollback() return sendError(response, "validate/samlcheck failed: %s" % unicode(exx), 0) finally: Session.close() log.debug("[samlcheck] 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 ''' 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 __before__(self, action,): try: c.version = get_version() c.licenseinfo = get_copyright_info() except Exception as exx: log.exception("[__before__::%r] exception %r" % (action, exx)) Session.rollback() Session.close() return sendError(response, exx, context='before')
def __before__(self, action): try: c.audit = request_context['audit'] c.audit['client'] = get_client(request) check_session(request) except Exception as exx: log.exception("[__before__::%r] exception %r", action, exx) Session.rollback() Session.close() return sendError(response, exx, context='before')
def __before__(self, action, **params): try: c.audit = request_context['audit'] c.audit['client'] = get_client(request) request_context['Audit'] = audit return response except Exception as exx: log.exception("[__before__::%r] exception %r" % (action, exx)) Session.rollback() Session.close() return sendError(response, exx, context='before')
def __after__(self): ''' __after is called after every action :return: return the response :rtype: pylons response ''' try: return response except Exception as exx: log.exception("[__after__] exception %r" % (exx)) return sendError(response, exx, context='after')
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 __before__(self, action, **params): try: c.audit = request_context['audit'] c.audit['success'] = False c.audit['client'] = get_client(request) c.version = get_version() c.version_ref = base64.encodestring(c.version)[:6] c.licenseinfo = get_copyright_info() c.polDefs = getPolicyDefinitions() c.display_provider = boolean( request_context['Config'].get('display_provider', True)) # -------------------------------------------------------------- -- # check for support of setting admin password c.admin_can_change_password = False if ('linotpadmin.user' in config and 'linotpadmin.password' in config): c.admin_can_change_password = True # -------------------------------------------------------------- -- # Session handling for the functions, that show data: # Also exclude custom-style.css, since the CSRF check # will always fail and return a HTTP 401 anyway. # A HTTP 404 makes more sense. if request.path.lower() in ['/manage/', '/manage', '/manage/logout', '/manage/audittrail', '/manage/policies', '/manage/tokenview', '/manage/userview', '/manage/help', '/manage/custom-style.css']: pass else: check_session(request) except Exception as exx: log.exception("[__before__::%r] exception %r" % (action, exx)) Session.rollback() Session.close() return sendError(response, exx, context='before') finally: log.debug("[__before__::%r] done" % (action))
def webprovisiongoogletoken(self): ''' This is the form for an google token to do web provisioning. ''' try: c.actions = getSelfserviceActions(self.authUser) return render('/selfservice/webprovisiongoogle.mako') except Exception as exx: log.error("[webprovisiongoogletoken] failed with error: %r" % exx) log.error("[webprovisiongoogletoken] %s" % traceback.format_exc()) return sendError(response, exx) finally: log.debug('[webprovisiongoogletoken] done')
def __after__(self): try: audit.log(c.audit) self.storage.session.commit() ## default return for the __before__ and __after__ return response except Exception as exx: log.exception("[__after__] exception %r" % (exx)) self.storage.session.rollback() return sendError(response, exx, context='after') finally: self.storage.session.close()