當前位置: 首頁>>代碼示例>>Python>>正文


Python challenges.Challenges類代碼示例

本文整理匯總了Python中linotp.lib.challenges.Challenges的典型用法代碼示例。如果您正苦於以下問題:Python Challenges類的具體用法?Python Challenges怎麽用?Python Challenges使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了Challenges類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: finish_challenge_token

    def finish_challenge_token(self):
        """
        processing of the challenge tokens
        """
        challenge_tokens = self.challenge_tokens
        options = self.options
        if not options:
            options = {}

        action_detail = 'challenge created'

        if len(challenge_tokens) == 1:
            challenge_token = challenge_tokens[0]
            _res, reply = Challenges.create_challenge(
                                challenge_token, options=options)
            return (False, reply, action_detail)

        # processing of multiple challenges
        else:
            # for each token, who can submit a challenge, we have to
            # create the challenge. To mark the challenges as depending
            # the transaction id will have an id that all sub transaction share
            # and a postfix with their enumaration. Finally the result is
            # composed by the top level transaction id and the message
            # and below in a dict for each token a challenge description -
            # the key is the token type combined with its token serial number
            all_reply = {'challenges': {}}
            challenge_count = 0
            transactionid = ''
            challenge_id = ""
            for challenge_token in challenge_tokens:
                challenge_count += 1
                id_postfix = ".%02d" % challenge_count
                if transactionid:
                    challenge_id = "%s%s" % (transactionid, id_postfix)

                (_res, reply) = Challenges.create_challenge(
                    challenge_token,
                    options=options,
                    challenge_id=challenge_id,
                    id_postfix=id_postfix
                )
                transactionid = reply.get('transactionid').rsplit('.')[0]

                # add token type and serial to ease the type specific processing
                reply['linotp_tokentype'] = challenge_token.type
                reply['linotp_tokenserial'] = challenge_token.getSerial()
                key = challenge_token.getSerial()
                all_reply['challenges'][key] = reply

            # finally add the root challenge response with top transaction id
            # and message, that indicates that 'multiple challenges have been
            # submitted
            all_reply['transactionid'] = transactionid
            all_reply['message'] = "Multiple challenges submitted."

            log.debug("Multiple challenges submitted: %d",
                      len(challenge_tokens))

            return (False, all_reply, action_detail)
開發者ID:linearregression,項目名稱:LinOTP,代碼行數:60,代碼來源:finishtokens.py

示例2: finish_valid_tokens

    def finish_valid_tokens(self):
        """
        processing of the valid tokens
        """
        valid_tokens = self.valid_tokens
        validation_results = self.validation_results
        user = self.user

        if len(valid_tokens) == 1:
            token = valid_tokens[0]
            if user:
                action_detail = ("user %[email protected]%r successfully authenticated."
                                 % (user.login, user.realm))
            else:
                action_detail = ("serial %r successfully authenticated."
                                 % token.getSerial())

            log.info(action_detail)

            # there could be a match in the window ahead,
            # so we need the last valid counter here
            (counter, _reply) = validation_results[token.getSerial()]
            token.setOtpCount(counter + 1)
            token.statusValidationSuccess()
            # finish as well related open challenges
            Challenges.finish_challenges(token, success=True)

            if token.getFromTokenInfo('count_auth_success_max', default=None):
                auth_count = token.get_count_auth_success()
                token.set_count_auth_success(auth_count + 1)

            detail = None
            auth_info = self.options.get('auth_info', 'False')
            if auth_info.lower() == "true":
                detail = token.getAuthDetail()
            return (True, detail, action_detail)

        else:
            # we have to set the matching counter to prevent replay one one
            # single token
            for token in valid_tokens:
                (res, _reply) = validation_results[token.getSerial()]
                token.setOtpCount(res)

            context['audit']['action_detail'] = "Multiple valid tokens found!"
            if user:
                log.error("[__checkTokenList] multiple token match error: "
                          "Several Tokens matching with the same OTP PIN "
                          "and OTP for user %r. Not sure how to auth",
                          user.login)
            raise UserError("multiple token match error", id=-33)
開發者ID:MuhamadYULIANTO,項目名稱:LinOTP,代碼行數:51,代碼來源:finishtokens.py

示例3: finish_pin_matching_tokens

    def finish_pin_matching_tokens(self):
        """
            check, if there have been some tokens
            where the pin matched (but OTP failed
            and increment only these
        """
        pin_matching_tokens = self.pin_matching_tokens
        action_detail = "wrong otp value"

        for tok in pin_matching_tokens:
            tok.statusValidationFail()
            tok.inc_count_auth()
            Challenges.finish_challenges(tok, success=False)

        return (False, None, action_detail)
開發者ID:,項目名稱:,代碼行數:15,代碼來源:

示例4: checkResponse4Challenge

    def checkResponse4Challenge(self, user, passw, options=None, challenges=None):
        '''
        verify the response of a previous challenge

        :param user:     the requesting user
        :param passw:    the to be checked pass (pin+otp)
        :param options:  options an additional argument, which could be token
                          specific
        :param challenges: the list of challenges, where each challenge is
                            described as dict
        :return: tuple of (otpcounter and the list of matching challenges)

        '''
        otp_counter = -1
        transid = None
        matching = None
        matchin_challenges = []

        if 'transactionid' in options or 'state' in options:
            ## fetch the transactionid
            transid = options.get('transactionid', options.get('state', None))

        # check if the transactionid is in the list of challenges
        if transid is not None:
            for challenge in challenges:
                if Challenges.is_same_transaction(challenge, transid):
                    matching = challenge
                    break
            if matching is not None:
                otp_counter = check_otp(self, passw, options=options)
                if otp_counter >= 0:
                    matchin_challenges.append(matching)

        return (otp_counter, matchin_challenges)
開發者ID:rogerwangzy,項目名稱:LinOTP,代碼行數:34,代碼來源:hmactoken.py

示例5: finish_invalid_tokens

    def finish_invalid_tokens(self):
        """
        """
        invalid_tokens = self.invalid_tokens
        user = self.user

        for tok in invalid_tokens:
            tok.statusValidationFail()
            Challenges.finish_challenges(tok, success=False)

        import linotp.lib.policy
        pin_policies = linotp.lib.policy.get_pin_policies(user) or []

        if 1 in pin_policies:
            action_detail = "wrong user password -1"
        else:
            action_detail = "wrong otp pin -1"

        return (False, None, action_detail)
開發者ID:MuhamadYULIANTO,項目名稱:LinOTP,代碼行數:19,代碼來源:finishtokens.py

示例6: test_transactionid_length

    def test_transactionid_length(self):

        with patch('linotp.lib.challenges.context') as mock_context:
            mock_context.get.return_value = {}
            transid_length = Challenges.get_tranactionid_length()
            self.assertAlmostEqual(
                transid_length, Challenges.DefaultTransactionIdLength)

            with self.assertRaises(Exception) as wrong_range:
                too_short_length = 7

                wrong_range_message = \
                    "TransactionIdLength must be between 12 and 17, " \
                    "was %d" % too_short_length
                mock_context.get.return_value = {
                    'TransactionIdLength': too_short_length
                }
                Challenges.get_tranactionid_length()

            self.assertEqual(wrong_range.exception.message, wrong_range_message)
開發者ID:,項目名稱:,代碼行數:20,代碼來源:

示例7: check_by_transactionid

    def check_by_transactionid(self, transid, passw, options=None):
        """
        check the passw against the open transaction

        :param transid: the transaction id
        :param passw: the pass parameter
        :param options: the additional optional parameters

        :return: tuple of boolean and detail dict
        """

        reply = {}

        serials = []
        challenges = Challenges.lookup_challenges(transid=transid)

        for challenge in challenges:
            serials.append(challenge.tokenserial)

        if not serials:
            reply['value'] = False
            reply['failure'] = ('No challenge for transaction %r found'
                                % transid)

            return False, reply

        reply['failcount'] = 0
        reply['value'] = False
        reply['token_type'] = ''

        for serial in serials:

            tokens = getTokens4UserOrSerial(serial=serial)
            if not tokens:
                raise Exception('tokenmismatch for token serial: %s'
                                % (unicode(serial)))

            # there could be only one
            token = tokens[0]
            owner = linotp.lib.token.get_token_owner(token)

            (ok, opt) = self.checkTokenList(tokens, passw, user=owner,
                                            options=options)
            if opt:
                reply.update(opt)

            reply['token_type'] = token.getType()
            reply['failcount'] = token.getFailCount()
            reply['value'] = ok

            if ok:
                break

        return ok, reply
開發者ID:kuffz,項目名稱:LinOTP,代碼行數:54,代碼來源:validate.py

示例8: checkResponse4Challenge

    def checkResponse4Challenge(self, user, passw, options=None, challenges=None):
        """
        This method verifies if the given ``passw`` matches any existing ``challenge``
        of the token.

        It then returns the new otp_counter of the token and the
        list of the matching challenges.

        In case of success the otp_counter needs to be > 0.
        The matching_challenges is passed to the method
        :py:meth:`~linotp.tokens.base.TokenClass.challenge_janitor`
        to clean up challenges.

        :param user: the requesting user
        :type user: User object
        :param passw: the password (pin+otp)
        :type passw: string
        :param options:  additional arguments from the request, which could be token specific
        :type options: dict
        :param challenges: A sorted list of valid challenges for this token.
        :type challenges: list
        :return: tuple of (otpcounter and the list of matching challenges)
        """
        otp_counter = -1
        transid = None
        matching = None
        matching_challenges = []

        # fetch the transactionid
        if 'transactionid' in options:
            transid = options.get('transactionid', None)

        # check if the transactionid is in the list of challenges
        if transid is not None:
            for challenge in challenges:
                if Challenges.is_same_transaction(challenge, transid):
                    matching = challenge
                    break
            if matching is not None:
                # Split pin from otp and check the resulting pin and otpval
                (pin, otpval) = self.splitPinPass(passw)
                if not check_pin(self, pin, user=user, options=options):
                    otpval = passw
                # The U2F checkOtp functions needs to know the saved challenge
                # to compare the received challenge value to the saved one,
                # thus we add the transactionid to the options
                options['transactionid'] = transid
                options['challenges'] = challenges
                otp_counter = check_otp(self, otpval, options=options)
                if otp_counter >= 0:
                    matching_challenges.append(matching)

        return (otp_counter, matching_challenges)
開發者ID:,項目名稱:,代碼行數:53,代碼來源:

示例9: finish_invalid_tokens

    def finish_invalid_tokens(self):
        """
        """
        invalid_tokens = self.invalid_tokens
        user = self.user

        for tok in invalid_tokens:

            # count all token accesses
            if tok.count_auth_max > 0:
                tok.inc_count_auth()

            tok.statusValidationFail()

            Challenges.finish_challenges(tok, success=False)

        pin_policies = get_pin_policies(user) or []

        if 1 in pin_policies:
            action_detail = "wrong user password -1"
        else:
            action_detail = "wrong otp pin -1"

        return (False, None, action_detail)
開發者ID:,項目名稱:,代碼行數:24,代碼來源:

示例10: statusValidationFail

    def statusValidationFail(self):
        '''
        statusValidationFail - callback to enable a status change,

        will be called if the token verification has failed

        :return - nothing

        '''
        log.debug('[statusValidationFail]')
        challenge = None

        if self.transId == 0 :
            return
        try:

            challenges = Challenges.lookup_challenges(self.context, self.getSerial(),
                                                      transid=self.transId)
            if len(challenges) == 1:
                challenge = challenges[0]
                challenge.setTanStatus(received=True, valid=False)


            ##  still in rollout state??
            rolloutState = self.getFromTokenInfo('rollout', '0')

            if rolloutState == '1':
                log.info('rollout state 1 for token %r not completed' % (self.getSerial()))

            elif rolloutState == '2':
                if challenge.received_count >= int(getFromConfig("OcraMaxChallengeRequests", '3')):
                    ##  after 3 fails in rollout state 2 - reset to rescan
                    self.addToTokenInfo('rollout', '1')
                    log.info('rollout for token %r reset to phase 1:' % (self.getSerial()))

                log.info('rollout for token %r not completed' % (self.getSerial()))

        except Exception as ex:
            log.exception('[Ocra2TokenClass:statusValidationFail] Error during validation finalisation for token %r :%r' % (self.getSerial(), ex))
            raise Exception(ex)

        finally:
            if challenge is not None:
                challenge.save()

        log.debug('[statusValidationFail]')
        return
開發者ID:choth02,項目名稱:LinOTP,代碼行數:47,代碼來源:ocra2token.py

示例11: checkSerialPass

    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)
開發者ID:hekate2639,項目名稱:LinOTP,代碼行數:47,代碼來源:validate.py

示例12: check_challenge_response

    def check_challenge_response(self, challenges, user, passw, options=None):
        """
        This function checks, if the given response (passw) matches
        any of the open challenges

        to prevent the token author to deal with the database layer, the
        token.checkResponse4Challenge will recieve only the dictionary of the
        challenge data

        :param challenges: the list of database challenges
        :param user: the requesting use
        :param passw: the to password of the request, which must be pin+otp
        :param options: the addtional request parameters
        :return: tuple of otpcount (as result of an internal token.checkOtp)
                 and additional optional reply
        """
        # challenge reply will stay None as we are in the challenge response
        # mode
        reply = None
        if options is None:
            options = {}

        otp = passw
        self.transId = options.get('transactionid', options.get('state', None))

        # only check those challenges, which currently have not been verified
        check_challenges = []
        for ch in challenges:
            if Challenges.verify_checksum(ch) and ch.is_open():
                check_challenges.append(ch)

        (otpcount, matching_challenges) = self.checkResponse4Challenge(
            user, otp, options=options, challenges=check_challenges)

        if otpcount >= 0:
            self.matching_challenges = matching_challenges
            self.valid_token.append(self)
            if len(self.invalid_token) > 0:
                del self.invalid_token[0]
        else:
            self.invalid_token.append(self)

        return (otpcount, reply)
開發者ID:,項目名稱:,代碼行數:43,代碼來源:

示例13: statusValidationSuccess

    def statusValidationSuccess(self):
        '''
        statusValidationSuccess - callback to enable a status change,

        remark: will be called if the token has been succesfull verified

        :return: - nothing

        '''
        log.debug('[statusValidationSuccess]')

        if self.transId == 0 :
            return

        challenges = Challenges.lookup_challenges(self.context, self.getSerial(),
                                                  transid=self.transId)
        if len(challenges) == 1:
            challenge = challenges[0]
            challenge.setTanStatus(True, True)
            challenge.save()

        ##  still in rollout state??
        rolloutState = self.getFromTokenInfo('rollout', '0')

        if rolloutState == '2':
            t_info = self.getTokenInfo()
            if t_info.has_key('rollout'):
                del t_info['rollout']
            if t_info.has_key('sharedSecret'):
                del t_info['sharedSecret']
            if t_info.has_key('nonce'):
                del t_info['nonce']
            self.setTokenInfo(t_info)

            log.info('rollout for token %r completed' % (self.getSerial()))

        elif rolloutState == '1':
            raise Exception('unable to complete the rollout ')

        log.debug('[statusValidationSuccess]:')
        return
開發者ID:choth02,項目名稱:LinOTP,代碼行數:41,代碼來源:ocra2token.py

示例14: getStatus

    def getStatus(self, transactionId):
        '''
        getStatus - assembles the status of a transaction / challenge in a dict

        {   "serial": SERIENNUMMER1,
            "transactionid": TRANSACTIONID1,
            "received_tan": true,
            "valid_tan": true,
            "failcount": 0
        }

        :param transactionId:    the transaction / challenge id
        :type transactionId:    string

        :return:    status dict
        :rtype:       dict
        '''

        log.debug('[getStatus] %r' % (transactionId))

        statusDict = {}
        challenge = Challenges.lookup_challenges(self.context, self.getSerial(),
                                                 transid=transactionId)
        if challenge is not None:
            statusDict['serial'] = challenge.tokenserial
            statusDict['transactionid'] = challenge.transid
            statusDict['received_tan'] = challenge.received_tan
            statusDict['valid_tan'] = challenge.valid_tan
            statusDict['failcount'] = self.getFailCount()
            statusDict['id'] = challenge.id
            statusDict['timestamp'] = unicode(challenge.timestamp)
            statusDict['active'] = unicode(self.isActive())


        log.debug('[getStatus]: %r' % (statusDict))
        return statusDict
開發者ID:choth02,項目名稱:LinOTP,代碼行數:36,代碼來源:ocra2token.py

示例15: update

    def update(self, params):

        param_keys = set(params.keys())
        init_rollout_state_keys = set(['type', 'hashlib', 'serial',
                                       'key_size', 'user.login',
                                       'user.realm', 'session'])

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

        if param_keys.issubset(init_rollout_state_keys):

            # if param keys are in {'type', 'hashlib'} the token is
            # initialized for the first time. this is e.g. done on the
            # manage web ui. since the token doesn't exist in the database
            # yet, its rollout state must be None (that is: they data for
            # the rollout state doesn't exist yet)

            self.ensure_state(None)

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

            # collect data used for generating the pairing url

            serial = params.get('serial')
            hash_algorithm = params.get('hashlib')
            pub_key = get_qrtoken_public_key()

            cb_url = get_single_auth_policy('qrtoken_pairing_callback_url')
            cb_sms = get_single_auth_policy('qrtoken_pairing_callback_sms')

            # TODO: read from config
            otp_pin_length = None

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

            pairing_url = generate_pairing_url('qrtoken',
                                          server_public_key=pub_key,
                                          serial=serial,
                                          callback_url=cb_url,
                                          callback_sms_number=cb_sms,
                                          otp_pin_length=otp_pin_length,
                                          hash_algorithm=hash_algorithm)

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

            self.addToInfo('pairing_url', pairing_url)

            # we set the the active state of the token to False, because
            # it should not be allowed to use it for validation before the
            # pairing process is done

            self.token.LinOtpIsactive = False

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

            self.change_state('pairing_url_sent')

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

        elif 'pairing_response' in params:

            # if a pairing response is in the parameters, we guess,
            # that the request refers to a token in the state
            # 'pairing_url_sent'

            self.ensure_state('pairing_url_sent')

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

            # adding the user's public key to the token info
            # as well as the user_token_id, which is used to
            # identify the token on the user's side

            self.addToTokenInfo('user_token_id', params['user_token_id'])

            # user public key arrives in the bytes format.
            # we must convert to a string in order to be
            # able to dump it as json in the db

            b64_user_public_key = b64encode(params['user_public_key'])
            self.addToTokenInfo('user_public_key', b64_user_public_key)

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

            # create challenge through the challenge factory

            # add the content type and the challenge data to the params
            # (needed in the createChallenge method)

            params['content_type'] = CONTENT_TYPE_PAIRING
            params['data'] = self.getSerial()

            self.change_state('pairing_response_received')

            success, challenge_dict = Challenges.create_challenge(self, params)

            if not success:
                raise Exception('Unable to create challenge from '
                                'pairing response %s' %
                                params['pairing_response'])
#.........這裏部分代碼省略.........
開發者ID:kuffz,項目名稱:LinOTP,代碼行數:101,代碼來源:qrtoken.py


注:本文中的linotp.lib.challenges.Challenges類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。