Beispiel #1
0
    def incOtpFailCounter(self):

        self.token.LinOtpFailCount = self.token.LinOtpFailCount + 1

        try:
            self.token.storeToken()
        except BaseException:
            log.error("Token fail counter update failed")
            raise TokenAdminError("Token Fail Counter update failed", id=1106)

        return self.token.LinOtpFailCount
Beispiel #2
0
    def get_multi_otp(self, count=0, epoch_start=0, epoch_end=0, curTime=None):
        '''
        This returns a dictionary of multiple future OTP values of the Tagespasswort token

        parameter
            count    - how many otp values should be returned
            epoch_start    - time based tokens: start when
            epoch_end      - time based tokens: stop when

        return
            True/False
            error text
            OTP dictionary
        '''
        otp_dict = {"type": "DPW", "otp": {}}
        ret = False
        error = "No count specified"
        try:
            otplen = int(self.token.LinOtpOtpLen)
        except ValueError as ex:
            log.error("[get_multi_otp] %r" % ex)
            return (False, unicode(ex), otp_dict)

        secretHOtp = self.token.getHOtpKey()
        dpw = dpwOtp(secretHOtp, otplen)
        log.debug("[get_multi_otp] retrieving %i OTP values for token %s" %
                  (count, dpw))

        if count > 0:
            now = datetime.datetime.now()
            if curTime:
                if type(curTime) == datetime.datetime:
                    now = curTime
                elif type(curTime) == unicode:
                    now = datetime.datetime.strptime(curTime,
                                                     "%Y-%m-%d %H:%M:%S.%f")
                else:
                    log.error("[get_multi_otp] wrong curTime type: %s" %
                              type(curTime))
                    raise TokenAdminError(
                        "[get_multi_otp] wrong curTime type: %s (%s)" %
                        (type(curTime), curTime),
                        id=2001)
            for i in range(count):
                delta = datetime.timedelta(days=i)
                date_string = (now + delta).strftime("%d%m%y")
                otpval = dpw.getOtp(date_string=date_string)
                otp_dict["otp"][(now + delta).strftime("%y-%m-%d")] = otpval
            ret = True

        log.debug("[get_multi_otp] %s" % otp_dict)
        return (ret, error, otp_dict)
Beispiel #3
0
    def get_multi_otp(self, count=0, epoch_start=0, epoch_end=0, curTime=None):
        """
        This returns a dictionary of multiple future OTP values of
        the Tagespasswort token

        parameter
            count    - how many otp values should be returned
            epoch_start    - time based tokens: start when
            epoch_end      - time based tokens: stop when

        return
            True/False
            error text
            OTP dictionary
        """

        otp_dict = {"type": "DPW", "otp": {}}
        ret = False
        error = "No count specified"
        try:
            otplen = int(self.token.LinOtpOtpLen)
        except ValueError as ex:
            log.error("[get_multi_otp] %r", ex)
            return (False, str(ex), otp_dict)

        if count > 0:
            now = datetime.now()
            if curTime:
                if isinstance(curTime, datetime):
                    now = curTime
                elif isinstance(curTime, str):
                    now = datetime.strptime(curTime, "%Y-%m-%d %H:%M:%S.%f")
                else:
                    raise TokenAdminError(
                        "[get_multi_otp] wrong curTime type:"
                        " %s (%s)" % (type(curTime), curTime),
                        id=2001,
                    )

            secObj = self._get_secret_object()
            with dpwOtp(secObj, otplen) as dpw:

                for i in range(count):
                    delta = timedelta(days=i)
                    date_string = (now + delta).strftime("%d%m%y")
                    otpval = dpw.getOtp(date_string=date_string)
                    otp_dict["otp"][
                        (now + delta).strftime("%y-%m-%d")
                    ] = otpval
                ret = True

        return (ret, error, otp_dict)
Beispiel #4
0
    def incOtpCounter(self, counter=None, reset=True):
        """
        method
            incOtpCounter(aToken, counter)

        parameters:
            token - a token object
            counter - the new counter
            reset - optional -

        exception:
            in case of an transaction fail an exception is thrown

        side effects:
            default of reset will reset the failCounter

        """

        resetCounter = False

        if counter is None:
            counter = self.token.LinOtpCount

        self.token.LinOtpCount = counter + 1

        if reset is True:
            if getFromConfig("DefaultResetFailCount") == "True":
                resetCounter = True

        if resetCounter is True:
            if (self.token.LinOtpFailCount < self.token.LinOtpMaxFail
                    and self.token.LinOtpIsactive is True):
                self.token.LinOtpFailCount = 0

        try:
            self.token.storeToken()

        except Exception as ex:
            log.error("Token Counter update failed: %r", ex)
            raise TokenAdminError("Token Counter update failed: %r" % (ex),
                                  id=1106)

        return self.token.LinOtpCount
Beispiel #5
0
    def enroll(self):
        """
        method:
            api/helpdesk/enroll

        description:
            method to enroll a token as helpdesk

        arguments:
            * type: the token type, currently only 'email'
            * user: the new token owner
            * realm: (optional) the realm the user belongs to - used to identify the user

        returns:
            success as boolean

        """

        ret = False
        response_detail = {}

        params = self.request_params

        try:

            if 'user' not in params:
                raise ParameterError('missing parameter: user!')

            if 'type' not in params:
                raise ParameterError('missing parameter: type!')

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

            # determine token class

            token_cls_alias = params.get("type")
            lower_alias = token_cls_alias.lower()

            if lower_alias not in tokenclass_registry:
                raise TokenAdminError('admin/init failed: unknown token '
                                      'type %r' % token_cls_alias, id=1610)

            token_cls = tokenclass_registry.get(lower_alias)

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

            # call the token class hook in order to enrich/overwrite the
            # parameters

            helper_params = token_cls.get_helper_params_pre(params)
            params.update(helper_params)

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

            # fetch user from parameters.

            user = getUserFromParam(params)

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

            # create a new pin according to the policies

            if 'pin' not in params:
                params['pin'] = createRandomPin(user, min_pin_length=6)

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

            if 'otpkey' not in params:
                params['genkey'] = '1'

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

            # check admin authorization

            res = checkPolicyPre('admin', 'init', params, user=user)

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

            helper_params = token_cls.get_helper_params_post(params, user=user)
            params.update(helper_params)

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

            # create new serial

            th = TokenHandler()

            serial = th.genSerial(token_cls_alias)
            params['serial'] = serial

            log.info("[init] initialize token. user: %s, serial: %s"
                     % (user.login, serial))

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

            # scope_extension: we are in scope helpdesk
            # this is eg required to notify the emailtoken to use the
            # email from user if none is given as param

            params['::scope::'] = {
                'helpdesk': True,
                'user': user
            }

            (ret, token) = th.initToken(params, user)

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

            # different token types return different information on
            # initialization (e.g. otpkey, pairing_url, etc)

            initDetail = token.getInitDetail(params, user)
            response_detail.update(initDetail)

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

            # prepare data for audit

            if token is not None and ret is True:
                c.audit['serial'] = token.getSerial()
                c.audit['token_type'] = token.type

            c.audit['success'] = ret
            c.audit['user'] = user.login
            c.audit['realm'] = user.realm

            c.audit['action_detail'] += get_token_num_info()

            res = checkPolicyPost('admin', 'init', params, user=user)
            pin = res.get('new_pin', params['pin'])

            message = ("A new ${tokentype} token (${serial}) "
                       "with pin '${Pin}' "
                       "for ${givenname} ${surname} has been enrolled.")
            info = {
                'message': message,
                'Subject': 'New %s token enrolled' % token.type,
                'Pin': pin,
                'tokentype': token.type
            }
            info.update(response_detail)

            notify_user(user, 'enrollment', info, required=True)

            c.audit['action_detail'] += get_token_num_info()

            c.audit['success'] = ret

            return sendResult(response, ret)

        except PolicyException as pex:
            log.exception("Policy Exception while enrolling token")
            Session.rollback()
            return sendError(response, pex, 1)

        except Exception as exx:
            log.exception("Exception while enrolling token")
            Session.rollback()
            return sendError(response, exx, 1)