Example #1
0
    def test_getUserInfo_fallback(self, mock_lookup_user_in_resolver):
        """
        verify that the fallback is an empty dict for
        - lookup result is None
        - no userid as input is provided
        """

        mock_lookup_user_in_resolver.return_value = None, None, None

        assert {} == getUserInfo('userId', 'resolver', 'resolver_conf')
        assert {} == getUserInfo(None, 'resolver', 'resolver_conf')
Example #2
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 = self.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()
Example #3
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()
Example #4
0
def get_userinfo(user):

    (uid, resolver, resolver_class) = getUserId(user)
    uinfo = getUserInfo(uid, resolver, resolver_class)
    if 'cryptpass' in uinfo:
        del uinfo['cryptpass']

    return uinfo
Example #5
0
def get_userinfo(user):

    (uid, resolver, resolver_class) = getUserId(user)
    uinfo = getUserInfo(uid, resolver, resolver_class)
    if 'cryptpass' in uinfo:
        del uinfo['cryptpass']

    return uinfo
Example #6
0
    def getUserDetail(self, tok):
        userInfo = {}
        uInfo = {}

        userInfo["User.description"] = u''
        userInfo["User.userid"] = u''
        userInfo["User.username"] = u''
        for field in self.user_fields:
            userInfo["User.%s" % field] = u''

        if tok.LinOtpUserid:
            # userInfo["User.description"]    = u'/:no user info:/'
            userInfo["User.userid"] = u'/:no user info:/'
            userInfo["User.username"] = u'/:no user info:/'

            uInfo = None

            try:

                uInfo = getUserInfo(tok.LinOtpUserid, tok.LinOtpIdResolver,
                                    tok.LinOtpIdResClass)

            except NoResolverFound:
                log.error("no user info found!")

            if uInfo is not None and len(uInfo) > 0:
                if uInfo.has_key("description"):
                    description = uInfo.get("description")
                    if isinstance(description, str):
                        userInfo["User.description"] = description.decode(
                            ENCODING)
                    else:
                        userInfo["User.description"] = description

                if uInfo.has_key("userid"):
                    userid = uInfo.get("userid")
                    if isinstance(userid, str):
                        userInfo["User.userid"] = userid.decode(ENCODING)
                    else:
                        userInfo["User.userid"] = userid

                if uInfo.has_key("username"):
                    username = uInfo.get("username")
                    if isinstance(username, str):
                        userInfo["User.username"] = username.decode(ENCODING)
                    else:
                        userInfo["User.username"] = username

                for field in self.user_fields:
                    fieldvalue = uInfo.get(field, "")
                    if isinstance(fieldvalue, str):
                        userInfo["User.%s" %
                                 field] = fieldvalue.decode(ENCODING)
                    else:
                        userInfo["User.%s" % field] = fieldvalue

        return (userInfo, uInfo)
Example #7
0
def get_userinfo(user):

    (uid, resolver, resolver_class) = getUserId(user)
    uinfo = getUserInfo(uid, resolver, resolver_class)
    if "cryptpass" in uinfo:
        del uinfo["cryptpass"]
    uinfo["realm"] = user.realm

    return uinfo
Example #8
0
    def getUserDetail(self, tok):
        userInfo = {}
        uInfo = {}

        userInfo["User.description"] = u''
        userInfo["User.userid"] = u''
        userInfo["User.username"] = u''
        for field in self.user_fields:
            userInfo["User.%s" % field] = u''

        if tok.LinOtpUserid:
            # userInfo["User.description"]    = u'/:no user info:/'
            userInfo["User.userid"] = u'/:no user info:/'
            userInfo["User.username"] = u'/:no user info:/'

            uInfo = None

            try:

                uInfo = getUserInfo(
                                tok.LinOtpUserid,
                                tok.LinOtpIdResolver,
                                tok.LinOtpIdResClass)

            except NoResolverFound:
                log.error("no user info found!")

            if uInfo is not None and len(uInfo) > 0:
                if uInfo.has_key("description"):
                    description = uInfo.get("description")
                    if isinstance(description, str):
                        userInfo["User.description"] = description.decode(ENCODING)
                    else:
                        userInfo["User.description"] = description

                if uInfo.has_key("userid"):
                    userid = uInfo.get("userid")
                    if isinstance(userid, str):
                        userInfo["User.userid"] = userid.decode(ENCODING)
                    else:
                        userInfo["User.userid"] = userid

                if uInfo.has_key("username"):
                    username = uInfo.get("username")
                    if isinstance(username, str):
                        userInfo["User.username"] = username.decode(ENCODING)
                    else:
                        userInfo["User.username"] = username

                for field in self.user_fields:
                    fieldvalue = uInfo.get(field, "")
                    if isinstance(fieldvalue, str):
                        userInfo["User.%s" % field] = fieldvalue.decode(ENCODING)
                    else:
                        userInfo["User.%s" % field] = fieldvalue

        return (userInfo, uInfo)
Example #9
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")
Example #10
0
    def checkSerialPass(self, serial, passw, options=None, user=None):
        """
        This function checks the otp for a given serial

        :attention: the parameter user must be set, as the pin policy==1 will
                    verify the user pin
        """

        token_type = options.get("token_type", None)

        tokenList = getTokens4UserOrSerial(None,
                                           serial,
                                           token_type=token_type,
                                           read_for_update=True)

        if passw is None:
            # other than zero or one token should not happen, as serial is
            # unique
            if len(tokenList) == 1:
                theToken = tokenList[0]
                tok = theToken.token
                realms = tok.getRealmNames()
                if realms is None or len(realms) == 0:
                    realm = getDefaultRealm()
                elif len(realms) > 0:
                    realm = realms[0]
                userInfo = getUserInfo(
                    tok.LinOtpUserid,
                    tok.LinOtpIdResolver,
                    tok.LinOtpIdResClass,
                )
                user = User(login=userInfo.get("username"), realm=realm)
                user.info = userInfo

                if theToken.is_challenge_request(passw, user, options=options):
                    (res, opt) = Challenges.create_challenge(theToken, options)
                    res = False
                else:
                    raise ParameterError("Missing parameter: pass", id=905)

            else:
                raise Exception("No token found: "
                                "unable to create challenge for %s" % serial)

        else:
            (res, opt) = self.checkTokenList(tokenList,
                                             passw,
                                             user=user,
                                             options=options)

        return (res, opt)
Example #11
0
    def test_getUserInfo_good(self, mock_lookup_user_in_resolver):
        """
        verify that the lookup result is forwarded
        """

        mock_lookup_user_in_resolver.return_value = '1223', 'myResolver', {
            'login': '******',
            'email': '*****@*****.**'
        }

        userInfo = getUserInfo('userId', 'resolver', 'resolver_conf')

        assert userInfo['login'] == 'heinz'

        return
Example #12
0
    def checkSerialPass(self, serial, passw, options=None, user=None):
        """
        This function checks the otp for a given serial

        :attention: the parameter user must be set, as the pin policy==1 will
                    verify the user pin
        """

        log.debug('checking for serial %r' % serial)
        tokenList = linotp.lib.token.getTokens4UserOrSerial(None, serial)

        if passw is None:
            # other than zero or one token should not happen, as serial is
            # unique
            if len(tokenList) == 1:
                theToken = tokenList[0]
                tok = theToken.token
                realms = tok.getRealmNames()
                if realms is None or len(realms) == 0:
                    realm = getDefaultRealm()
                elif len(realms) > 0:
                    realm = realms[0]
                userInfo = getUserInfo(tok.LinOtpUserid, tok.LinOtpIdResolver,
                                       tok.LinOtpIdResClass)
                user = User(login=userInfo.get('username'), realm=realm)
                user.info = userInfo

                if theToken.is_challenge_request(passw, user, options=options):
                    (res, opt) = Challenges.create_challenge(theToken, options)
                    res = False
                else:
                    raise ParameterError('Missing parameter: pass', id=905)

            else:
                raise Exception('No token found: '
                                'unable to create challenge for %s' % serial)

        else:
            log.debug('checking len(pass)=%r for serial %r' %
                      (len(passw), serial))

            (res, opt) = self.checkTokenList(tokenList,
                                             passw,
                                             user=user,
                                             options=options)

        return (res, opt)
Example #13
0
    def checkSerialPass(self, serial, passw, options=None, user=None):
        """
        This function checks the otp for a given serial

        :attention: the parameter user must be set, as the pin policy==1 will
                    verify the user pin
        """

        log.debug('checking for serial %r' % serial)
        tokenList = linotp.lib.token.getTokens4UserOrSerial(
            None, serial)

        if passw is None:
            # other than zero or one token should not happen, as serial is
            # unique
            if len(tokenList) == 1:
                theToken = tokenList[0]
                tok = theToken.token
                realms = tok.getRealmNames()
                if realms is None or len(realms) == 0:
                    realm = getDefaultRealm()
                elif len(realms) > 0:
                    realm = realms[0]
                userInfo = getUserInfo(tok.LinOtpUserid, tok.LinOtpIdResolver,
                                       tok.LinOtpIdResClass)
                user = User(login=userInfo.get('username'), realm=realm)
                user.info = userInfo

                if theToken.is_challenge_request(passw, user, options=options):
                    (res, opt) = Challenges.create_challenge(
                        theToken, options)
                    res = False
                else:
                    raise ParameterError('Missing parameter: pass', id=905)

            else:
                raise Exception('No token found: '
                                'unable to create challenge for %s' % serial)

        else:
            log.debug('checking len(pass)=%r for serial %r' %
                      (len(passw), serial))

            (res, opt) = self.checkTokenList(
                tokenList, passw, user=user, options=options)

        return (res, opt)
Example #14
0
    def getUserDetail(self, tok):
        userInfo = {}
        uInfo = {}

        userInfo["User.description"] = u""
        userInfo["User.userid"] = u""
        userInfo["User.username"] = u""
        for field in self.user_fields:
            userInfo["User.%s" % field] = u""

        if tok.LinOtpUserid:
            # userInfo["User.description"]    = u'/:no user info:/'
            userInfo["User.userid"] = u"/:no user info:/"
            userInfo["User.username"] = u"/:no user info:/"

            uInfo = getUserInfo(tok.LinOtpUserid, tok.LinOtpIdResolver, tok.LinOtpIdResClass)
            if uInfo is not None and len(uInfo) > 0:
                if "description" in uInfo:
                    description = uInfo.get("description")
                    if isinstance(description, str):
                        userInfo["User.description"] = description.decode(ENCODING)
                    else:
                        userInfo["User.description"] = description

                if "userid" in uInfo:
                    userid = uInfo.get("userid")
                    if isinstance(userid, str):
                        userInfo["User.userid"] = userid.decode(ENCODING)
                    else:
                        userInfo["User.userid"] = userid

                if "username" in uInfo:
                    username = uInfo.get("username")
                    if isinstance(username, str):
                        userInfo["User.username"] = username.decode(ENCODING)
                    else:
                        userInfo["User.username"] = username

                for field in self.user_fields:
                    fieldvalue = uInfo.get(field, "")
                    if isinstance(fieldvalue, str):
                        userInfo["User.%s" % field] = fieldvalue.decode(ENCODING)
                    else:
                        userInfo["User.%s" % field] = fieldvalue

        return (userInfo, uInfo)
Example #15
0
    def getUserDetail(self, tok):
        userInfo = {}
        uInfo = {}

        userInfo["User.description"] = ""
        userInfo["User.userid"] = ""
        userInfo["User.username"] = ""
        for field in self.user_fields:
            userInfo["User.%s" % field] = ""

        if tok.LinOtpUserid:
            # userInfo["User.description"]    = u'/:no user info:/'
            userInfo["User.userid"] = "/:no user info:/"
            userInfo["User.username"] = "******"

            uInfo = None

            try:

                uInfo = getUserInfo(
                    tok.LinOtpUserid,
                    tok.LinOtpIdResolver,
                    tok.LinOtpIdResClass,
                )

            except NoResolverFound:
                log.error("no user info found!")

            if uInfo is not None and len(uInfo) > 0:
                if "description" in uInfo:
                    description = uInfo.get("description")
                    userInfo["User.description"] = description

                if "userid" in uInfo:
                    userid = uInfo.get("userid")
                    userInfo["User.userid"] = userid

                if "username" in uInfo:
                    username = uInfo.get("username")
                    userInfo["User.username"] = username

                for field in self.user_fields:
                    fieldvalue = uInfo.get(field, "")
                    userInfo["User.%s" % field] = fieldvalue

        return (userInfo, uInfo)
Example #16
0
    def test_getUserInfo_good(self, mock_lookup_user_in_resolver):
        """
        verify that the lookup result is forwarded
        """

        mock_lookup_user_in_resolver.return_value = (
            "1223",
            "myResolver",
            {
                "login": "******",
                "email": "*****@*****.**"
            },
        )

        userInfo = getUserInfo("userId", "resolver", "resolver_conf")

        assert userInfo["login"] == "heinz"

        return
Example #17
0
def get_userinfo(login):

    uinfo = {}

    if '@' in login:
        uuser, rrealm = login.split("@")
        user = User(uuser, rrealm)
    else:
        realm = getDefaultRealm()
        user = User(login, realm)

    (uid, resolver, resolver_class) = getUserId(user)
    uinfo = getUserInfo(uid, resolver, resolver_class)

    # the passwd resolver should not expose the crypted/hasehd password
    if 'cryptpass' in uinfo:
        del uinfo['cryptpass']

    return uinfo
Example #18
0
def get_userinfo(login):

    uinfo = {}

    if "@" in login:
        uuser, rrealm = login.split("@")
        user = User(uuser, rrealm)
    else:
        realm = getDefaultRealm()
        user = User(login, realm)

    (uid, resolver, resolver_class) = getUserId(user)
    uinfo = getUserInfo(uid, resolver, resolver_class)

    # the passwd resolver should not expose the crypted/hasehd password
    if "cryptpass" in uinfo:
        del uinfo["cryptpass"]

    return uinfo
Example #19
0
    def get_user_detail(self):
        """
        get detail info about openid cookie owner

        :return: tuple of (email,firstname,lastname,fullname)
        """

        email = ""
        fullname = ""
        firstname = ""
        lastname = ""

        ## search in userresolvers for user detail
        user = self.user
        if "@" not in user:
            user = "******" % (user, getDefaultRealm())
        login, realm = user.split('@')

        usr = User(login, realm)
        (userid, res_id, res_conf) = getUserId(usr)
        usr_detail = getUserInfo(userid, res_id, res_conf)

        if "email" in usr_detail:
            email = usr_detail["email"]

        if "givenname" in usr_detail:
            firstname = usr_detail["givenname"]

        if "surname" in usr_detail:
            lastname = usr_detail["surname"]

        if firstname and lastname:
            fullname = "%s %s" % (firstname, lastname)
        elif firstname:
            fullname = "%s" % firstname
        elif lastname:
            fullname = "%s" % lastname

        return (email, firstname, lastname, fullname)
Example #20
0
    def get_user_detail(self):
        """
        get detail info about openid cookie owner

        :return: tuple of (email,firstname,lastname,fullname)
        """

        email = ""
        fullname = ""
        firstname = ""
        lastname = ""

        ## search in userresolvers for user detail
        user = self.user
        if "@" not in user:
            user = "******" % (user, getDefaultRealm())
        login, realm = user.split('@')

        usr = User(login, realm)
        (userid, res_id, res_conf) = getUserId(usr)
        usr_detail = getUserInfo(userid, res_id, res_conf)

        if "email" in usr_detail:
            email = usr_detail["email"]

        if "givenname" in usr_detail:
            firstname = usr_detail["givenname"]

        if "surname" in usr_detail:
            lastname = usr_detail["surname"]

        if firstname and lastname:
            fullname = "%s %s" % (firstname, lastname)
        elif firstname:
            fullname = "%s" % firstname
        elif lastname:
            fullname = "%s" % lastname

        return (email, firstname, lastname, fullname)
Example #21
0
    def migrate_resolver(self, src=None, target=None, filter_serials=None):
        """
        support the migration of owned tokens from one resolver to a new one

        the idea is:
        - get all tokens from one resolver
        - for each token, the the owner
        - from the owner get the login name
        - with the login name get the uid from the target resolver
        - update the new_id in the token

        """

        ret = {}

        if not src or not target:
            raise Exception("Missing src or target resolver defintion!")

        now = datetime.now()
        stime = now.strftime("%s")

        g.audit["action_detail"] = "migration from %s to %s" % (
            src["resolvername"],
            target["resolvername"],
        )

        ret["src"] = src
        ret["target"] = target
        ret["value"] = False
        ret["message"] = ""

        search = getResolverClassName(src["type"], src["resolvername"])
        target_resolver = getResolverClassName(target["type"],
                                               target["resolvername"])

        # get all tokens of src resolver
        tokens = self._get_tokens_for_resolver(search, serials=filter_serials)

        num_migration = 0
        serials = set()
        for token in tokens:
            serial = token.get("LinOtpTokenSerialnumber")
            userid = token.get("LinOtpUserid")
            resolverC = token.get("LinOtpIdResClass")
            # now do the lookup of the uid in the
            # src resolver to get the login
            uInfo = getUserInfo(userid, "", resolverC)

            login = uInfo.get("username")
            try:
                y = getResolverObject(target_resolver)
                uid = y.getUserId(login)
                if not uid:
                    log.warning(
                        "User %s not found in target resolver %r",
                        login,
                        target_resolver,
                    )
                    continue

                token.LinOtpIdResClass = target_resolver
                token.LinOtpUserid = uid
                # TODO: adjust
                token.LinOtpIdResolver = target["type"]
                db.session.add(token)

                num_migration += 1
                serials.add(serial)

            except Exception as exx:
                log.error(
                    "Faild to set new resolver data for token %s: %r",
                    serial,
                    exx,
                )

        ret["value"] = True
        ret["message"] = _("%d tokens of %d migrated") % (
            num_migration,
            len(tokens),
        )
        g.audit["info"] = "[%s] %s" % (stime, ret["message"])
        g.audit["serial"] = ",".join(list(serials))
        g.audit["success"] = True

        return ret
Example #22
0
    def check_s(self):
        '''
        This function is used to validate the serial and the otp value/password.

        method:
            validate/check_s

        arguments:
            * serial:  the serial number of the token
            * pass:    the password that consists of a possible fixes password component
                        and the OTP value

        returns:
            JSON response
        '''
        param = self.request_params

        options = {}
        options.update(param)
        for k in ['user', 'serial', "pass", "init"]:
            if k in options:
                del options[k]

        if 'init' in param:
            if isSelfTest() is True:
                options['initTime'] = param.get('init')

        try:
            passw = param.get("pass")
            serial = param.get('serial')
            if serial is None:
                user = param.get('user')
                if user is not None:
                    user = getUserFromParam(param)
                    toks = getTokens4UserOrSerial(user=user)
                    if len(toks) == 0:
                        raise Exception("No token found!")
                    elif len(toks) > 1:
                        raise Exception("More than one token found!")
                    else:
                        tok = toks[0].token
                        desc = tok.get()
                        realms = desc.get('LinOtp.RealmNames')
                        if realms is None or len(realms) == 0:
                            realm = getDefaultRealm()
                        elif len(realms) > 0:
                            realm = realms[0]

                        userInfo = getUserInfo(tok.LinOtpUserid,
                                               tok.LinOtpIdResolver,
                                               tok.LinOtpIdResClass)
                        user = User(login=userInfo.get('username'),
                                    realm=realm)

                        serial = tok.getSerial()

            c.audit['serial'] = serial

            if isSelfTest() is True:
                initTime = param.get("init")
                if initTime is not None:
                    if options is None:
                        options = {}
                    options['initTime'] = initTime

            options['scope'] = {"check_s": True}
            vh = ValidationHandler()
            (ok, opt) = vh.checkSerialPass(serial, passw, options=options)
            c.audit['success'] = ok
            Session.commit()

            qr = param.get('qr', None)
            if qr and opt and 'message' in opt:
                try:
                    dataobj = opt.get('message')
                    param['alt'] = "%s" % opt
                    if 'transactionid' in opt:
                        param['transactionid'] = opt['transactionid']
                    return sendQRImageResult(response, dataobj, param)
                except Exception as exc:
                    log.warning("failed to send QRImage: %r " % exc)
                    return sendQRImageResult(response, opt, param)
            else:
                return sendResult(response, ok, 0, opt=opt)

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

        finally:
            Session.close()
Example #23
0
    def check_s(self):
        '''
        This function is used to validate the serial and the otp value/password.

        method:
            validate/check_s

        arguments:
            * serial:  the serial number of the token
            * pass:    the password that consists of a possible fixes password component
                        and the OTP value

        returns:
            JSON response
        '''
        param = {}
        param.update(request.params)

        options = {}
        options.update(param)
        for k in ['user', 'serial', "pass", "init"]:
            if k in options:
                del options[k]

        if 'init' in param:
            if isSelfTest() == True:
                options['initTime'] = param.get('init')

        try:
            passw = getParam(param, "pass", optional)
            serial = getParam(param, 'serial', optional)
            if serial is None:
                user = getParam(param, 'user', optional)
                if user is not None:
                    user = getUserFromParam(param, optional)
                    toks = getTokens4UserOrSerial(user=user)
                    if len(toks) == 0:
                        raise Exception("No token found!")
                    elif len(toks) > 1:
                        raise Exception("More than one token found!")
                    else:
                        tok = toks[0].token
                        desc = tok.get()
                        realms = desc.get('LinOtp.RealmNames')
                        if realms is None or len(realms) == 0:
                            realm = getDefaultRealm()
                        elif len(realms) > 0:
                            realm = realms[0]

                        userInfo = getUserInfo(tok.LinOtpUserid,
                                               tok.LinOtpIdResolver,
                                               tok.LinOtpIdResClass)
                        user = User(login=userInfo.get('username'),
                                    realm=realm)

                        serial = tok.getSerial()

            c.audit['serial'] = serial

            if isSelfTest() == True:
                initTime = getParam(param, "init", optional)
                if initTime is not None:
                    if options is None:
                        options = {}
                    options['initTime'] = initTime

            (ok, opt) = checkSerialPass(serial, passw, options=options)

            c.audit['success'] = ok
            Session.commit()

            qr = getParam(param, 'qr', optional)
            if qr is not None and opt is not None and opt.has_key('message'):
                try:
                    dataobj = opt.get('message')
                    param['alt'] = "%s" % opt
                    return sendQRImageResult(response, dataobj, param)
                except Exception as exc:
                    log.warning("failed to send QRImage: %r " % exc)
                    return sendQRImageResult(response, opt, param)
            else:
                return sendResult(response, ok, 0, opt=opt)

        except Exception as exx:
            log.error("[check_s] validate/check_s failed: %r" % exx)
            log.error("[check_s] %s" % traceback.format_exc())
            c.audit['info'] = unicode(exx)
            Session.rollback()
            return sendError(response,
                             "validate/check_s failed: %s" % unicode(exx), 0)

        finally:
            Session.close()
            log.debug('[check_s] done')
Example #24
0
    def check_s(self):
        """
        This function is used to validate the serial and the otp value/password.

        method:
            validate/check_s

        arguments:
            * serial:  the serial number of the token
            * pass:    the password that consists of a possible fixes password component
                        and the OTP value

        returns:
            JSON response
        """
        param = {}
        param.update(request.params)

        options = {}
        options.update(param)
        for k in ["user", "serial", "pass", "init"]:
            if k in options:
                del options[k]

        if "init" in param:
            if isSelfTest() == True:
                options["initTime"] = param.get("init")

        try:
            passw = getParam(param, "pass", optional)
            serial = getParam(param, "serial", optional)
            if serial is None:
                user = getParam(param, "user", optional)
                if user is not None:
                    user = getUserFromParam(param, optional)
                    toks = getTokens4UserOrSerial(user=user)
                    if len(toks) == 0:
                        raise Exception("No token found!")
                    elif len(toks) > 1:
                        raise Exception("More than one token found!")
                    else:
                        tok = toks[0].token
                        desc = tok.get()
                        realms = desc.get("LinOtp.RealmNames")
                        if realms is None or len(realms) == 0:
                            realm = getDefaultRealm()
                        elif len(realms) > 0:
                            realm = realms[0]

                        userInfo = getUserInfo(tok.LinOtpUserid, tok.LinOtpIdResolver, tok.LinOtpIdResClass)
                        user = User(login=userInfo.get("username"), realm=realm)

                        serial = tok.getSerial()

            c.audit["serial"] = serial

            if isSelfTest() == True:
                initTime = getParam(param, "init", optional)
                if initTime is not None:
                    if options is None:
                        options = {}
                    options["initTime"] = initTime

            (ok, opt) = checkSerialPass(serial, passw, options=options)

            c.audit["success"] = ok
            Session.commit()

            qr = getParam(param, "qr", optional)
            if qr is not None and opt is not None and opt.has_key("message"):
                try:
                    dataobj = opt.get("message")
                    param["alt"] = "%s" % opt
                    return sendQRImageResult(response, dataobj, param)
                except Exception as exc:
                    log.warning("failed to send QRImage: %r " % exc)
                    return sendQRImageResult(response, opt, param)
            else:
                return sendResult(response, ok, 0, opt=opt)

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

        finally:
            Session.close()
            log.debug("[check_s] done")
Example #25
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!")

            serial = get_tokenserial_of_transaction(transId=transid)
            if serial is None:
                value['value'] = False
                value['failure'] = 'No challenge for transaction %r found'\
                                    % transid

            else:
                param['serial'] = serial

                tokens = getTokens4UserOrSerial(serial=serial)
                if len(tokens) == 0 or len(tokens) > 1:
                    raise Exception('tokenmismatch for token serial: %s' %
                                    (unicode(serial)))

                theToken = tokens[0]
                tok = theToken.token
                realms = tok.getRealmNames()
                if realms is None or len(realms) == 0:
                    realm = getDefaultRealm()
                elif len(realms) > 0:
                    realm = realms[0]

                userInfo = getUserInfo(tok.LinOtpUserid, tok.LinOtpIdResolver,
                                       tok.LinOtpIdResClass)
                user = User(login=userInfo.get('username'), realm=realm)

                (ok, opt) = checkSerialPass(serial,
                                            passw,
                                            user=user,
                                            options=param)

                value['value'] = ok
                failcount = theToken.getFailCount()
                value['failcount'] = int(failcount)

            c.audit['success'] = ok
            #c.audit['info'] += "%s=%s, " % (k, value)
            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.error("[check_t] validate/check_t failed: %r" % exx)
            log.error("[check_t] %s" % traceback.format_exc())
            c.audit['info'] = unicode(exx)
            Session.rollback()
            return sendError(response,
                             "validate/check_t failed: %s" % unicode(exx), 0)

        finally:
            Session.close()
            log.debug('[check_t] done')
Example #26
0
    def check_t(self):
        """
        method:
            ocra/check_t

        description:
            verify the response of the ocra token

        arguments:
            * transactionid:  (required - string)
                    Dies ist eine Transaktions-ID, die bei der Challenge ausgegeben wurde.

            * pass:   (required - string)
                    die response, die der OCRA Token auf Grund der Challenge berechnet hat

        returns:

            A JSON response::

                {
                 "version": "LinOTP 2.4",
                 "jsonrpc": "2.0",
                 "result": {
                     "status": true,
                     "value": {
                         "failcount" : 3,
                         "result": false
                        }
                    },
                 "id": 0
                }

        exception:

        """
        res = {}
        description = 'ocra/check_t: validate a token request.'

        try:
            param = getLowerParams(request.params)
            log.info("[check_t] check OCRA token: %r" % param)

            #checkPolicyPre('ocra', "check_t")

            passw = getParam(param, 'pass'  , optional)
            if passw is None:
                ## raise exception'''
                log.exception("[check_t] missing pass ")
                raise ParameterError("Usage: %s Missing parameter 'pass'." % description, id=77)

            transid = getParam(param, 'transactionid', optional)
            if transid is None:
                ## raise exception'''
                log.exception("[check_t] missing transactionid, user or serial number of token")
                raise ParameterError("Usage: %s Missing parameter 'transactionid'." % description, id=77)

            ## if we have a transaction, get serial from this challenge
            value = {}
            ocraChallenge = OcraTokenClass.getTransaction(transid)
            if ocraChallenge is not None:
                serial = ocraChallenge.tokenserial

                tokens = getTokens4UserOrSerial(serial=serial)
                if len(tokens) == 0 or len(tokens) > 1:
                    raise Exception('tokenmismatch for token serial: %s'
                                    % (unicode(serial)))

                theToken = tokens[0]
                tok = theToken.token
                desc = tok.get()
                realms = desc.get('LinOtp.RealmNames')
                if realms is None or len(realms) == 0:
                    realm = getDefaultRealm()
                elif len(realms) > 0:
                    realm = realms[0]

                userInfo = getUserInfo(tok.LinOtpUserid, tok.LinOtpIdResolver, tok.LinOtpIdResClass)
                user = User(login=userInfo.get('username'), realm=realm)

                vh = ValidationHandler()
                (ok, opt) = vh.checkSerialPass(serial, passw, user=user,
                                            options={'transactionid': transid})

                failcount = theToken.getFailCount()
                value['result'] = ok
                value['failcount'] = int(failcount)

            else:
                ## no challenge found for this transid
                value['result'] = False
                value['failure'] = 'No challenge for transaction %r found'\
                                    % transid

            c.audit['success'] = res
            #c.audit['info'] += "%s=%s, " % (k, value)

            Session.commit()
            return sendResult(response, value, 1)

        except Exception as e :
            log.exception("[check_t] failed: %r" % e)
            Session.rollback()
            return sendResult(response, unicode(e), 0)

        finally:
            Session.close()
            log.debug("[check_t] done")
Example #27
0
    def migrate_resolver(self, src=None, target=None, filter_serials=None):
        """
        support the migration of owned tokens from one resolver to a new one

        the idea is:
        - get all tokens from one resolver
        - for each token, the the owner
        - from the owner get the login name
        - with the login name get the uid from the target resolver
        - update the new_id in the token

        """

        _ = context['translate']

        ret = {}

        if not src or not target:
            raise Exception("Missing src or target resolver defintion!")

        audit = context.get('audit')
        now = datetime.now()
        stime = now.strftime("%s")

        audit['action_detail'] = (
            "migration from %s to %s" %
            (src['resolvername'], target['resolvername']))

        ret['src'] = src
        ret['target'] = target
        ret['value'] = False
        ret['message'] = ''

        search = getResolverClassName(src['type'], src['resolvername'])
        target_resolver = getResolverClassName(target['type'],
                                               target['resolvername'])

        # get all tokens of src resolver
        tokens = self._get_tokens_for_resolver(search, serials=filter_serials)

        num_migration = 0
        serials = set()
        for token in tokens:
            serial = token.get('LinOtpTokenSerialnumber')
            userid = token.get('LinOtpUserid')
            resolverC = token.get('LinOtpIdResClass')
            # now do the lookup of the uid in the
            # src resolver to get the login
            uInfo = getUserInfo(userid, '', resolverC)

            login = uInfo.get('username')
            try:
                y = getResolverObject(target_resolver)
                uid = y.getUserId(login)
                if not uid:
                    log.warning("User %s not found in target resolver %r",
                                login, target_resolver)
                    continue

                token.LinOtpIdResClass = target_resolver
                token.LinOtpUserid = uid
                # TODO: adjust
                token.LinOtpIdResolver = target['type']
                Session.add(token)

                num_migration += 1
                serials.add(serial)

            except Exception as exx:
                log.exception(
                    "Faild to set new resolver data for token %s: %r" %
                    (serial, exx))

        ret['value'] = True
        ret['message'] = (_("%d tokens of %d migrated") %
                          (num_migration, len(tokens)))
        log.info(ret['message'])
        audit['info'] = "[%s] %s" % (stime, ret['message'])
        audit['serial'] = ",".join(list(serials))
        audit['success'] = True
        context['audit'] = audit

        return ret
    def migrate_resolver(self, src=None, target=None, filter_serials=None):
        """
        support the migration of owned tokens from one resolver to a new one

        the idea is:
        - get all tokens from one resolver
        - for each token, the the owner
        - from the owner get the login name
        - with the login name get the uid from the target resolver
        - update the new_id in the token

        """

        _ = context['translate']

        ret = {}

        if not src or not target:
            raise Exception("Missing src or target resolver defintion!")

        audit = context.get('audit')
        now = datetime.now()
        stime = now.strftime("%s")

        audit['action_detail'] = ("migration from %s to %s"
                                  % (src['resolvername'],
                                     target['resolvername']))

        ret['src'] = src
        ret['target'] = target
        ret['value'] = False
        ret['message'] = ''

        search = getResolverClassName(src['type'], src['resolvername'])
        target_resolver = getResolverClassName(target['type'],
                                               target['resolvername'])

        # get all tokens of src resolver
        tokens = self._get_tokens_for_resolver(search, serials=filter_serials)

        num_migration = 0
        serials = set()
        for token in tokens:
            serial = token.get('LinOtpTokenSerialnumber')
            userid = token.get('LinOtpUserid')
            resolverC = token.get('LinOtpIdResClass')
            # now do the lookup of the uid in the
            # src resolver to get the login
            uInfo = getUserInfo(userid, '', resolverC)

            login = uInfo.get('username')
            try:
                y = getResolverObject(target_resolver)
                uid = y.getUserId(login)
                if not uid:
                    log.warning("User %s not found in target resolver %r",
                                login, target_resolver)
                    continue

                token.LinOtpIdResClass = target_resolver
                token.LinOtpUserid = uid
                # TODO: adjust
                token.LinOtpIdResolver = target['type']
                Session.add(token)

                num_migration += 1
                serials.add(serial)

            except Exception as exx:
                log.exception("Faild to set new resolver data for token %s: %r"
                              % (serial, exx))

        ret['value'] = True
        ret['message'] = (_("%d tokens of %d migrated")
                            % (num_migration, len(tokens)))
        log.info(ret['message'])
        audit['info'] = "[%s] %s" % (stime, ret['message'])
        audit['serial'] = ",".join(list(serials))
        audit['success'] = True
        context['audit'] = audit

        return ret
Example #29
0
    def check_s(self):
        '''
        This function is used to validate the serial and the otp value/password.

        method:
            validate/check_s

        arguments:
            * serial:  the serial number of the token
            * pass:    the password that consists of a possible fixes password component
                        and the OTP value

        returns:
            JSON response
        '''
        param = {}
        param.update(request.params)

        options = {}
        options.update(param)
        for k in ['user', 'serial', "pass", "init"]:
            if k in options:
                del options[k]

        if 'init' in param:
            if isSelfTest() is True:
                options['initTime'] = param.get('init')

        try:
            passw = getParam(param, "pass", optional)
            serial = getParam(param, 'serial', optional)
            if serial is None:
                user = getParam(param, 'user', optional)
                if user is not None:
                    user = getUserFromParam(param, optional)
                    toks = getTokens4UserOrSerial(user=user)
                    if len(toks) == 0:
                        raise Exception("No token found!")
                    elif len(toks) > 1:
                        raise Exception("More than one token found!")
                    else:
                        tok = toks[0].token
                        desc = tok.get()
                        realms = desc.get('LinOtp.RealmNames')
                        if realms is None or len(realms) == 0:
                            realm = getDefaultRealm()
                        elif len(realms) > 0:
                            realm = realms[0]

                        userInfo = getUserInfo(tok.LinOtpUserid, tok.LinOtpIdResolver, tok.LinOtpIdResClass)
                        user = User(login=userInfo.get('username'), realm=realm)

                        serial = tok.getSerial()

            c.audit['serial'] = serial

            if isSelfTest() is True:
                initTime = getParam(param, "init", optional)
                if initTime is not None:
                    if options is None:
                        options = {}
                    options['initTime'] = initTime

            options['scope'] = {"check_s": True}
            vh = ValidationHandler()
            (ok, opt) = vh.checkSerialPass(serial, passw, options=options)
            c.audit['success'] = ok
            Session.commit()

            qr = param.get('qr', None)
            if qr and opt and 'message' in opt:
                try:
                    dataobj = opt.get('message')
                    param['alt'] = "%s" % opt
                    if 'transactionid' in opt:
                        param['transactionid'] = opt['transactionid']
                    return sendQRImageResult(response, dataobj, param)
                except Exception as exc:
                    log.warning("failed to send QRImage: %r " % exc)
                    return sendQRImageResult(response, opt, param)
            else:
                return sendResult(response, ok, 0, opt=opt)

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

        finally:
            Session.close()
            log.debug('[check_s] done')
Example #30
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!")

            serial = get_tokenserial_of_transaction(transId=transid)
            if serial is None:
                value['value'] = False
                value['failure'] = 'No challenge for transaction %r found'\
                                    % transid


            else:
                param['serial'] = serial

                tokens = getTokens4UserOrSerial(serial=serial)
                if len(tokens) == 0 or len(tokens) > 1:
                    raise Exception('tokenmismatch for token serial: %s'
                                    % (unicode(serial)))

                theToken = tokens[0]
                tok = theToken.token
                realms = tok.getRealmNames()
                if realms is None or len(realms) == 0:
                    realm = getDefaultRealm()
                elif len(realms) > 0:
                    realm = realms[0]

                userInfo = getUserInfo(tok.LinOtpUserid, tok.LinOtpIdResolver, tok.LinOtpIdResClass)
                user = User(login=userInfo.get('username'), realm=realm)

                (ok, opt) = checkSerialPass(serial, passw, user=user,
                                     options=param)

                value['value'] = ok
                failcount = theToken.getFailCount()
                value['failcount'] = int(failcount)

            c.audit['success'] = ok
            #c.audit['info'] += "%s=%s, " % (k, value)
            Session.commit()

            qr = getParam(param, 'qr', optional)
            if qr is not None and opt is not None and opt.has_key('message'):
                try:
                    dataobj = opt.get('message')
                    param['alt'] = "%s" % opt
                    return sendQRImageResult(response, dataobj, param)
                except Exception as exc:
                    log.warning("failed to send QRImage: %r " % exc)
                    return sendQRImageResult(response, opt, param)
            else:
                return sendResult(response, value, 1, opt=opt)

        except Exception as exx:
            log.error("[check_t] validate/check_t failed: %r" % exx)
            log.error("[check_t] %s" % traceback.format_exc())
            c.audit['info'] = unicode(exx)
            Session.rollback()
            return sendError(response, "validate/check_t failed: %s"
                             % unicode(exx), 0)

        finally:
            Session.close()
            log.debug('[check_t] done')
Example #31
0
    def check_t(self):
        """
        method:
            ocra/check_t

        description:
            verify the response of the ocra token

        arguments:
            * transactionid:  (required - string)
                    Dies ist eine Transaktions-ID, die bei der Challenge
                    ausgegeben wurde.

            * pass:   (required - string)
                    die response, die der OCRA Token auf Grund der Challenge
                    berechnet hat

        returns:

            A JSON response::

                {
                 "version": "LinOTP 2.4",
                 "jsonrpc": "2.0",
                 "result": {
                     "status": true,
                     "value": {
                         "failcount" : 3,
                         "result": false
                        }
                    },
                 "id": 0
                }

        exception:

        """
        res = {}
        description = 'ocra/check_t: validate a token request.'

        try:
            param = getLowerParams(request.params)
            log.info("[check_t] check OCRA token: %r" % param)

            # TODO: checkPolicyPre('ocra', "check_t")

            passw = param.get('pass')
            if passw is None:
                # raise exception'''
                log.exception("[check_t] missing pass ")
                raise ParameterError("Usage: %s Missing parameter "
                                     "'pass'." % description, id=77)

            transid = param.get('transactionid')
            if not transid:
                # raise exception
                log.exception("[check_t] missing transactionid, user or "
                              "serial number of token")
                raise ParameterError("Usage: %s Missing parameter "
                                     "'transactionid'." % description, id=77)

            # if we have a transaction, get serial from this challenge

            value = {}
            ocraChallenge = OcraTokenClass.getTransaction(transid)
            if ocraChallenge is not None:
                serial = ocraChallenge.tokenserial

                tokens = getTokens4UserOrSerial(serial=serial)
                if len(tokens) == 0 or len(tokens) > 1:
                    raise Exception('tokenmismatch for token serial: %s'
                                    % (unicode(serial)))

                theToken = tokens[0]
                tok = theToken.token
                desc = tok.get()
                realms = desc.get('LinOtp.RealmNames')
                if realms is None or len(realms) == 0:
                    realm = getDefaultRealm()
                elif len(realms) > 0:
                    realm = realms[0]

                userInfo = getUserInfo(tok.LinOtpUserid,
                                       tok.LinOtpIdResolver,
                                       tok.LinOtpIdResClass)

                user = User(login=userInfo.get('username'), realm=realm)

                vh = ValidationHandler()
                (ok, _opt) = vh.checkSerialPass(
                                       serial,
                                       passw,
                                       user=user,
                                       options={'transactionid': transid})

                failcount = theToken.getFailCount()
                value['result'] = ok
                value['failcount'] = int(failcount)

            else:

                # no challenge found for this transid

                value['result'] = False
                value['failure'] = ('No challenge for transaction %r found'
                                    % transid)

            c.audit['success'] = res

            Session.commit()
            return sendResult(response, value, 1)

        except Exception as exx:
            log.exception("[check_t] failed: %r", exx)
            Session.rollback()
            return sendResult(response, unicode(exx), 0)

        finally:
            Session.close()
Example #32
0
    def check_s(self):
        """
        This function is used to validate the serial and the otp value/password.
        If the otppin policy is set, the endpoint /validate/check_s does not work.

        method:
            validate/check_s

        arguments:
            * serial:  the serial number of the token
            * pass:    the password that consists of a possible fixes password component
                        and the OTP value

        returns:
            JSON response
        """
        param = self.request_params

        options = {}
        options.update(param)
        for k in ["user", "serial", "pass", "init"]:
            if k in options:
                del options[k]

        try:
            passw = param.get("pass")
            serial = param.get("serial")
            if serial is None:
                user = param.get("user")
                if user is not None:
                    user = getUserFromParam(param)
                    toks = getTokens4UserOrSerial(user=user)
                    if len(toks) == 0:
                        raise Exception("No token found!")
                    elif len(toks) > 1:
                        raise Exception("More than one token found!")
                    else:
                        tok = toks[0].token
                        desc = tok.get()
                        realms = desc.get("LinOtp.RealmNames")
                        if realms is None or len(realms) == 0:
                            realm = getDefaultRealm()
                        elif len(realms) > 0:
                            realm = realms[0]

                        userInfo = getUserInfo(
                            tok.LinOtpUserid,
                            tok.LinOtpIdResolver,
                            tok.LinOtpIdResClass,
                        )
                        user = User(
                            login=userInfo.get("username"), realm=realm
                        )

                        serial = tok.getSerial()

            g.audit["serial"] = serial

            options["scope"] = {"check_s": True}
            vh = ValidationHandler()
            (ok, opt) = vh.checkSerialPass(serial, passw, options=options)
            g.audit["success"] = ok
            db.session.commit()

            qr = param.get("qr", None)
            if qr and opt and "message" in opt:
                try:
                    dataobj = opt.get("message")
                    param["alt"] = "%s" % opt
                    if "transactionid" in opt:
                        param["transactionid"] = opt["transactionid"]
                    return sendQRImageResult(response, dataobj, param)
                except Exception as exc:
                    log.warning("failed to send QRImage: %r ", exc)
                    return sendQRImageResult(response, opt, param)
            else:
                return sendResult(response, ok, 0, opt=opt)

        except Exception as exx:
            log.error("[check_s] validate/check_s failed: %r", exx)
            g.audit["info"] = str(exx)
            db.session.rollback()
            return sendResult(response, False, id=0, status=False)