Beispiel #1
0
    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)
Beispiel #2
0
    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))
Beispiel #3
0
    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')
Beispiel #4
0
    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:
                vh = ValidationHandler()
                ok, opt = vh.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.exception("[check_yubikey] validate/check_yubikey failed: %r" %
                          exx)
            c.audit['info'] = unicode(exx)
            Session.rollback()
            return sendResult(response, False, 0)

        finally:
            Session.close()
Beispiel #5
0
    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()
Beispiel #6
0
    def pair(self):

        try:

            # ------------------------------------------------------------------

            params = dict(**request.params)

            enc_response = params.get('pairing_response')

            if enc_response is None:
                raise Exception('Parameter missing')

            # ------------------------------------------------------------------

            dec_response = decrypt_pairing_response(enc_response)
            token_type = dec_response.token_type
            pairing_data = dec_response.pairing_data

            if not hasattr(pairing_data, 'serial') or \
               pairing_data.serial is None:

                raise ValidateError(
                    'Pairing responses with no serial attached '
                    'are currently not implemented.')

            # ------------------------------------------------------------------

            # TODO: pairing policy
            tokens = getTokens4UserOrSerial(None, pairing_data.serial)

            if not tokens:
                raise Exception('Invalid serial in pairing response')

            if len(tokens) > 1:
                raise Exception('Multiple tokens found. Pairing not possible')

            token = tokens[0]

            # ------------------------------------------------------------------

            if token.type != token_type:
                raise Exception('Serial in pairing response doesn\'t match '
                                'supplied token_type')

            # ------------------------------------------------------------------

            token.pair(pairing_data)

            Session.commit()
            return sendResult(response, False)

        # ----------------------------------------------------------------------

        except Exception:
            Session.rollback()
            return sendResult(response, False, 0, status=False)

        finally:
            Session.close()
Beispiel #7
0
    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()
Beispiel #8
0
    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()
Beispiel #9
0
    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))
Beispiel #10
0
    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))
Beispiel #11
0
    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)
Beispiel #12
0
    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))
Beispiel #13
0
    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()
Beispiel #14
0
    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)
Beispiel #15
0
    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))
Beispiel #16
0
    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')
Beispiel #17
0
    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))
Beispiel #18
0
    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")
Beispiel #19
0
    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)
Beispiel #20
0
    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')
Beispiel #21
0
    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')
Beispiel #22
0
    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 is False.")
                if "True" == allowSAML:
                    ## Now we get the attributes of the user
                    user = getUserFromParam(param)
                    (uid, resId, resIdC) = getUserId(user)
                    userInfo = getUserInfo(uid, resId, resIdC)
                    log.debug("[samlcheck] getting attributes for: %s@%s"
                              % (user.login, user.realm))

                    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.exception("[samlcheck] validate/check failed: %r" % exx)
            Session.rollback()
            return sendResult(response, False, 0)

        finally:
            Session.close()
Beispiel #23
0
    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')
Beispiel #24
0
    def pair(self):

        try:

            params = dict(**request.params)
            enc_response = params.get('pairing_response')
            if enc_response is None:
                raise Exception('Parameter missing')

            dec_response = decrypt_pairing_response(enc_response)

            if not dec_response.serial:
                raise ValidateError(
                    'Pairing responses with no serial attached '
                    'are currently not implemented.')

            serial = dec_response.serial
            user_public_key = dec_response.user_public_key
            user_token_id = dec_response.user_token_id
            user = dec_response.user_login

            user = getUserFromParam(params, optional)

            # TODO: pairing policy
            tokens = getTokens4UserOrSerial(None, serial)

            if not tokens:
                raise Exception('Invalid serial in pairing response')

            if len(tokens) > 1:
                raise Exception('Multiple tokens found. Pairing not possible')

            token = tokens[0]

            if token.type != 'qr':
                raise Exception('Pairing is only implemented for the qrtoken')

            token.ensure_state('pairing_url_sent')
            token.addToTokenInfo('user_token_id', user_token_id)
            b64_user_public_key = b64encode(user_public_key)
            token.addToTokenInfo('user_public_key', b64_user_public_key)

            params['serial'] = serial
            params['user_public_key'] = user_public_key
            params['user_token_id'] = user_token_id
            params['user'] = user
            params['content_type'] = CONTENT_TYPE_PAIRING
            params['data'] = serial

            token.change_state('pairing_response_received')
            Session.commit()
            return sendResult(response, False)

        except Exception:
            Session.rollback()
            return sendResult(response, False, 0, status=False)

        finally:
            Session.close()
Beispiel #25
0
    def pair(self):

        try:

            params = dict(**request.params)
            enc_response = params.get('pairing_response')
            if enc_response is None:
                raise Exception('Parameter missing')

            dec_response = decrypt_pairing_response(enc_response)

            if not dec_response.serial:
                raise ValidateError('Pairing responses with no serial attached '
                                    'are currently not implemented.')

            serial = dec_response.serial
            user_public_key = dec_response.user_public_key
            user_token_id = dec_response.user_token_id
            user = dec_response.user_login

            user = getUserFromParam(params, optional)

            # TODO: pairing policy
            tokens = getTokens4UserOrSerial(None, serial)

            if not tokens:
                raise Exception('Invalid serial in pairing response')

            if len(tokens) > 1:
                raise Exception('Multiple tokens found. Pairing not possible')

            token = tokens[0]

            if token.type != 'qr':
                raise Exception('Pairing is only implemented for the qrtoken')

            token.ensure_state('pairing_url_sent')
            token.addToTokenInfo('user_token_id', user_token_id)
            b64_user_public_key = b64encode(user_public_key)
            token.addToTokenInfo('user_public_key', b64_user_public_key)

            params['serial'] = serial
            params['user_public_key'] = user_public_key
            params['user_token_id'] = user_token_id
            params['user'] = user
            params['content_type'] = CONTENT_TYPE_PAIRING
            params['data'] = serial

            token.change_state('pairing_response_received')
            Session.commit()
            return sendResult(response, False)

        except Exception:
            Session.rollback()
            return sendResult(response, False, 0, status=False)

        finally:
            Session.close()
Beispiel #26
0
    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')
Beispiel #27
0
    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')
Beispiel #28
0
    def check_status(self):
        """
        check the status of a transaction - for polling support
        """

        try:

            param = {}
            param.update(request.params)

            #
            # we require either state or transactionid as parameter

            transid = param.get('state', param.get('transactionid', None))
            if not transid:
                raise ParameterError(_('Missing required parameter "state" or '
                                     '"transactionid"!'))

            #
            # serial is an optional parameter

            serial = param.get('serial', None)

            #
            # but user is an required parameter

            if "user" not in param:
                raise ParameterError(_('Missing required parameter "serial"'
                                     ' or "user"!'))

            user = getUserFromParam(param)

            passw = param.get('pass', None)
            if passw is None:
                raise ParameterError(_('Missing required parameter "pass"!'))

            use_offline = param.get('use_offline', False)

            va = ValidationHandler()
            ok, opt = va.check_status(transid=transid, user=user,
                                      serial=serial, password=passw,
                                      use_offline=use_offline)

            c.audit['success'] = ok
            c.audit['info'] = unicode(opt)

            Session.commit()
            return sendResult(response, ok, 0, opt=opt)

        except Exception as exx:
            log.exception("check_status failed: %r" % exx)
            c.audit['info'] = unicode(exx)
            Session.rollback()
            return sendResult(response, False, 0)

        finally:
            Session.close()
Beispiel #29
0
    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")
Beispiel #30
0
    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')
Beispiel #31
0
    def check_t(self):

        param = {}
        value = {}
        ok = False
        opt = {}

        try:
            param.update(request.params)
            passw = getParam(param, "pass", required)

            transid = param.get('state', None)
            if transid is not None:
                param['transactionid'] = transid
                del param['state']

            if transid is None:
                transid = param.get('transactionid', None)

            if transid is None:
                raise Exception("missing parameter: state or transactionid!")

            vh = ValidationHandler()
            (ok, opt) = vh.check_by_transactionid(transid=transid,
                                                  passw=passw,
                                                  options=param)

            value['value'] = ok
            value['failcount'] = int(opt.get('failcount', 0))

            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, value, 1, opt=opt)

        except Exception as exx:
            log.exception("[check_t] validate/check_t failed: %r" % exx)
            c.audit['info'] = unicode(exx)
            Session.rollback()
            return sendResult(response, False, 0)

        finally:
            Session.close()
            log.debug('[check_t] done')
Beispiel #32
0
    def check_t(self):

        param = {}
        value = {}
        ok = False
        opt = None

        try:
            param.update(request.params)
            passw = getParam(param, "pass", required)

            transid = param.get('state', None)
            if transid is not  None:
                param['transactionid'] = transid
                del param['state']

            if transid is None:
                transid = param.get('transactionid', None)

            if transid is None:
                raise Exception("missing parameter: state or transactionid!")

            vh = ValidationHandler()
            (ok, reply) = vh.check_by_transactionid(transid=transid,
                                                    passw=passw,
                                                    options=param)

            value['value'] = ok
            value['failcount'] = int(reply.get('failcount', 0))

            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, value, 1, opt=opt)

        except Exception as exx:
            log.exception("[check_t] validate/check_t failed: %r" % exx)
            c.audit['info'] = unicode(exx)
            Session.rollback()
            return sendResult(response, False, 0)

        finally:
            Session.close()
            log.debug('[check_t] done')
Beispiel #33
0
    def webkdc_validate(self):
        # Called by WebAuth via the Elm remctld scripts.
        # Verifies a one-time passcode and indicates how long
        # the token should be considered valid.

        param = {}

        try:
            param.update(request.params)
            username = param["user"]
            code = param["code"]

            user = User(username, "", "")
            th = TokenHandler()

            if ('token' in param):
                serial = param["token"]
                (ok, opt) = th.checkSerialPass(serial,
                                               code,
                                               options=None,
                                               user=user)
            else:
                (ok, opt) = th.checkUserPass(user, code)

            ret = {
                "success": ok,
            }

            if (ok):
                ret['expiration'] = round(
                    time.time()) + 60 * 60,  # one hour from now
            else:
                if opt == None:
                    opt = {}
                ret['error'] = c.audit.get('info')
                log.error("[webkdc_validate] authorization failed: %s" %
                          ret['error'])
                ret['code'] = -310

            Session.commit()

            return sendResult(response, ret, 0, opt=opt)

        except Exception as exx:
            log.error("[webkdc_validate] validate/webkdc_validate failed: %r" %
                      exx)
            log.error("[webkdc_validate] %s" % traceback.format_exc())

            Session.rollback()
            return sendError(
                response,
                u"validate/webkdc_validate failed: %s" % unicode(exx), 0)

        finally:
            Session.close()
Beispiel #34
0
    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')
Beispiel #35
0
    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')
Beispiel #36
0
    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')
Beispiel #37
0
    def check_status(self):
        """
        check the status of a transaction - for polling support
        """
        param = {}
        ok = False
        opt = None

        try:
            param.update(request.params)

            transid = param.get('state', param.get('transactionid', None))
            if not transid:
                raise ParameterError(_('Missing required parameter "state" or '
                                     '"transactionid"!'))

            serial = param.get('serial', None)
            user = getUserFromParam(param, False)

            if not user and not serial:
                raise ParameterError(_('Missing required parameter "serial"'
                                     ' or "user"!'))

            passw = param.get('pass', None)
            if not passw:
                raise ParameterError(_('Missing required parameter "pass"!'))

            use_offline = param.get('use_offline', False)

            va = ValidationHandler()
            ok, opt = va.check_status(transid=transid, user=user,
                                      serial=serial, password=passw,
                                      use_offline=use_offline)

            c.audit['success'] = ok
            c.audit['info'] = unicode(opt)

            Session.commit()
            return sendResult(response, ok, 0, opt=opt)

        except Exception as exx:
            log.exception("check_status failed: %r" % exx)
            c.audit['info'] = unicode(exx)
            Session.rollback()
            return sendResult(response, False, 0)

        finally:
            Session.close()
            log.debug('[check] done')
Beispiel #38
0
    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')
Beispiel #39
0
    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')
Beispiel #40
0
    def webkdc_validate(self):
        # Called by WebAuth via the Elm remctld scripts.
        # Verifies a one-time passcode and indicates how long
        # the token should be considered valid.

        param = {}

        try:
            param.update(request.params)
            username = param["user"]
            code = param["code"]

            user = User(username, "", "")
            th = TokenHandler()
           
            if ('token' in param):
                serial = param["token"]
                (ok, opt) = th.checkSerialPass(serial, code, options = None, user=user)
            else:
                (ok, opt) = th.checkUserPass(user, code)

            ret = {
                "success" : ok,
            }

            if (ok):
                ret['expiration']  = round(time.time()) + 60 * 60, # one hour from now
            else:
                if opt == None:
                    opt = {}
                ret['error'] = c.audit.get('info')
                log.error("[webkdc_validate] authorization failed: %s" % ret['error'])
                ret['code'] = -310

            Session.commit()

            return sendResult(response, ret, 0, opt=opt)

        except Exception as exx:
            log.error("[webkdc_validate] validate/webkdc_validate failed: %r" % exx)
            log.error("[webkdc_validate] %s" % traceback.format_exc())

            Session.rollback()
            return sendError(response, u"validate/webkdc_validate failed: %s" % unicode(exx), 0)

        finally:
            Session.close()
Beispiel #41
0
    def check_url(self):
        '''
        This function works with pam_url.
        '''
        ok = False
        param = {}
        try:
            param.update(request.params)

            try:
                (ok, opt) = self._check(param)
            except AuthorizeException as acc:
                log.warning(
                    "[check_url] authorization failed for validate/check_url: %r"
                    % acc)
                c.audit['success'] = False
                c.audit['action_detail'] = unicode(acc)
                ok = False

            Session.commit()
            response.headers['blablafoo'] = 'application/json'

            ## TODO: this code seems not to be finished
            if not ok:
                abort(403)
            else:
                return "Preshared Key Todo"

        except webob.exc.HTTPUnauthorized as acc:
            ## the exception, when an abort() is called if forwarded
            log.error("[__before__::%r] webob.exception %r" % acc)
            log.error("[__before__] %s" % traceback.format_exc())
            Session.rollback()
            raise acc

        except Exception as exx:
            log.error("[check_url] validate/check_url failed: %r" % exx)
            log.error("[check_url] %s" % traceback.format_exc())
            Session.rollback()
            return sendError(response,
                             u"validate/check_url failed: %s" % unicode(exx),
                             0)

        finally:
            Session.close()
            log.debug("[check_url] done")
Beispiel #42
0
    def __before__(self, action):

        log.debug("[__before__]")

        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')

        finally:
            log.debug("[__before__::%r] done" % (action))
Beispiel #43
0
    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")
Beispiel #44
0
    def __after__(self, action):
        """
        """
        try:
            c.audit['administrator'] = getUserFromRequest(request).get('login')

            audit.log(c.audit)
            Session.commit()
            return request

        except Exception as exception:
            log.exception(exception)
            Session.rollback()
            return sendError(response, exception, context='after')

        finally:
            Session.close()
Beispiel #45
0
    def __before__(self, action):

        log.debug("[__before__]")

        try:
            audit.initialize()
            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')

        finally:
            log.debug("[__before__::%r] done" % (action))
Beispiel #46
0
    def __before__(self, action, **params):

        log.debug("[__before__::%r] %r" % (action, params))

        try:
            audit.initialize()
            c.audit['client'] = get_client()
            return response

        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))
Beispiel #47
0
    def __after__(self, action):
        """
        """
        try:
            c.audit['administrator'] = getUserFromRequest(request).get('login')

            audit.log(c.audit)
            Session.commit()
            return request

        except Exception as exception:
            log.exception(exception)
            Session.rollback()
            return sendError(response, exception, context='after')

        finally:
            Session.close()
Beispiel #48
0
    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))
            Session.rollback()
            return sendError(response, exx, context='after')

        finally:
            Session.close()
            log.debug("[__after__] done")
Beispiel #49
0
    def __before__(self, 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.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')
Beispiel #50
0
    def __before__(self, action, **params):

        log.debug("[__before__::%r] %r" % (action, params))

        try:
            audit.initialize()
            c.audit["client"] = get_client()
            return response

        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))
Beispiel #51
0
    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))
            Session.rollback()
            return sendError(response, exx, context='after')

        finally:
            Session.close()
            log.debug("[__after__] done")
Beispiel #52
0
    def __before__(self, action, **params):

        log.debug("[__before__]")

        try:

            c.version = get_version()
            c.licenseinfo = get_copyright_info()

        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))
Beispiel #53
0
    def __before__(self, action, **params):

        log.debug("[__before__]")

        try:

            c.version = get_version()
            c.licenseinfo = get_copyright_info()

        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))
Beispiel #54
0
    def __before__(self, action, **params):

        log.debug("[__before__::%r] %r" % (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')

        finally:
            log.debug("[__before__::%r] done" % (action))
Beispiel #55
0
    def __before__(self, action, **params):

        log.debug("[__before__]")

        try:
            audit.initialize()
            c.audit['client'] = get_client()
            check_session()

        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))
Beispiel #56
0
    def check_url(self):
        '''
        This function works with pam_url.
        '''
        ok = False
        param = {}
        try:
            param.update(request.params)

            try:
                (ok, opt) = self._check(param)
            except AuthorizeException as acc:
                log.warning("[check_url] authorization failed for validate/check_url: %r" % acc)
                c.audit['success'] = False
                c.audit['action_detail'] = unicode(acc)
                ok = False

            Session.commit()
            response.headers['blablafoo'] = 'application/json'

            ## TODO: this code seems not to be finished
            if not ok:
                abort(403)
            else:
                return "Preshared Key Todo"

        except webob.exc.HTTPUnauthorized as acc:
            ## the exception, when an abort() is called if forwarded
            log.error("[__before__::%r] webob.exception %r" % acc)
            log.error("[__before__] %s" % traceback.format_exc())
            Session.rollback()
            raise acc

        except Exception as exx:
            log.error("[check_url] validate/check_url failed: %r" % exx)
            log.error("[check_url] %s" % traceback.format_exc())
            Session.rollback()
            return sendError(response, u"validate/check_url failed: %s"
                             % unicode(exx), 0)

        finally:
            Session.close()
            log.debug("[check_url] done")
Beispiel #57
0
    def __before__(self, action, **params):

        log.debug("[__before__::%r] %r" % (action, params))

        try:
            c.audit = request_context['audit']
            c.audit['client'] = get_client(request)
            if request_context: # XXX why this check?
                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')

        finally:
            log.debug("[__before__::%r] done" % (action))
Beispiel #58
0
    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')
Beispiel #59
0
    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()
Beispiel #60
0
    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.error("[help] Error loading helpfile: %r" % e)
            log.error("[help] %s" % traceback.format_exc())
            Session.rollback()
            return sendError(response, e)

        finally:
            Session.close()
            log.debug("[help] done")