Пример #1
0
    def test_bad_duration(self):
        """test: limits of human time delta format"""

        test_vector = {
            "24h 3m 4m 3s": 0,
            "1k 1h": 0,
        }

        for duration, _seconds in list(test_vector.items()):

            with pytest.raises(DurationParsingException):
                parse_duration(duration)

        return
Пример #2
0
    def test_ISO8601_duration(self):
        """test: parse ISO8601 time delta format"""

        test_vector = {
            "PT45S": 45.0,
            "PT5H10M": 18600.0,
            "P1DT12H": 129600.0,
            "P8W": 4838400.0,
            "P2YT3H10M": 63083400.0,
            "P0D": 0.0,
            "P23DT23H": 2070000.0,
            "P3Y6M4DT12H30M5S": 110550605.0,
            "PT5H": 18000.0,
            "PT36H": 129600.0,
            "P1M": 2592000.0,
            "P3D": 259200.0,
            "P7Y": 220752000.0,
            "PT0S": 0.0,
            "P5Y": 157680000.0,
            "P4Y": 126144000.0,
            "P2Y": 63072000.0,
            "P23M": 59616000.0,
            "PT10M": 600.0,
            "PT1M": 60.0,
        }
        for duration, seconds in list(test_vector.items()):

            timedelta = parse_duration(duration, time_delta_compliant=False)
            assert seconds == timedelta.total_seconds()
Пример #3
0
    def test_duration(self):
        """test: parse human time delta format"""

        test_vector = {
            "24h 3s": 86403.0,
            "1d 2h 1m": 93660.0,
        }

        for duration, seconds in list(test_vector.items()):
            timedelta = parse_duration(duration)
            assert seconds == timedelta.total_seconds()
Пример #4
0
def create_auth_cookie(user, client, state="authenticated", state_data=None):
    """
    create and auth_cookie value from the authenticated user and client

    :param user: the authenticated user
    :param client: the requesting client
    :param state: the state info for the authentication
    :return: the hmac256digest of the user data
             the expiration time as datetime
             the expiration time as string
    """

    secret = get_cookie_secret()
    key = binascii.unhexlify(secret)

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

    # handle expiration calculation

    expiry = get_cookie_expiry()

    if expiry is False:
        # default should be at max 1 hour
        delta = datetime.timedelta(seconds=1 * 60 * 60)
    else:
        delta = parse_duration(expiry)

    now = datetime.datetime.utcnow()
    expires = now + delta
    expiration = expires.strftime(TIMEFORMAT)

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

    # build the cache data
    if state_data is not None:
        state_data = copy.deepcopy(state_data)

    # we have to serialize the user object
    # - we do this currently in a very limited way where the resolver
    # specification is missing!

    user_dict = {"login": user.login, "realm": user.realm}

    data = [user_dict, client, expiration, state, state_data]
    hash_data = ("%r" % data).encode("utf-8")

    digest = hmac.new(key, hash_data, digestmod=hashlib.sha256).digest()
    auth_cookie = base64.urlsafe_b64encode(digest).decode().strip("=")

    Cookie_Cache[auth_cookie] = data

    return auth_cookie, expires, expiration
Пример #5
0
def create_auth_cookie(user, client, state='authenticated', state_data=None):
    """
    create and auth_cookie value from the authenticated user and client

    :param user: the authenticated user
    :param client: the requesting client
    :param state: the state info for the authentication
    :return: the hmac256digest of the user data
             the expiration time as datetime
             the expiration time as string
    """

    secret = get_cookie_secret()
    key = binascii.unhexlify(secret)

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

    # handle expiration calculation

    expiry = get_cookie_expiry()

    if expiry is False:
        # default should be at max 1 hour
        delta = datetime.timedelta(seconds=1 * 60 * 60)
    else:
        delta = parse_duration(expiry)

    now = datetime.datetime.utcnow()
    expires = now + delta
    expiration = expires.strftime(TIMEFORMAT)

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

    # build the cache data
    if state_data is not None:
        state_data = copy.deepcopy(state_data)

    data = [user, client, expiration, state, state_data]
    hash_data = ("%r" % data).encode('utf-8')

    digest = hmac.new(key, hash_data, digestmod=hashlib.sha256).digest()
    auth_cookie = base64.urlsafe_b64encode(digest).decode().strip("=")

    Cookie_Cache[auth_cookie] = data

    return auth_cookie, expires, expiration
Пример #6
0
def create_auth_cookie(user, client, state='authenticated', state_data=None):
    """
    create and auth_cookie value from the authenticated user and client

    :param user: the authenticated user
    :param client: the requesting client
    :param state: the state info for the authentication
    :return: the hmac256digest of the user data
             the expiration time as datetime
             the expiration time as string
    """

    secret = get_cookie_secret()
    key = binascii.unhexlify(secret)

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

    # handle expiration calculation

    expiry = get_cookie_expiry()

    if expiry is False:
        # default should be at max 1 hour
        delta = datetime.timedelta(seconds=1 * 60 * 60)
    else:
        delta = parse_duration(expiry)

    now = datetime.datetime.utcnow()
    expires = now + delta
    expiration = expires.strftime(TIMEFORMAT)

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

    # build the cache data

    data = [user, client, expiration, state, state_data]

    digest = hmac.new(key, "%r" % data, digestmod=hashlib.sha256).digest()
    auth_cookie = base64.urlsafe_b64encode(digest).decode().strip("=")

    Cookie_Cache[auth_cookie] = data

    return auth_cookie, expires, expiration
Пример #7
0
def create_auth_cookie(config, user, client):
    """
    create and auth_cookie value from the authenticated user and client

    :param user: the authenticated user
    :param client: the requesting client
    :return: the encrypted cookie value, the expires datetime object and
             the expiration time as string
    """

    secret = get_cookie_secret(config)
    expiry = get_cookie_expiry(config)

    if expiry:
        delta = parse_duration(expiry)
    else:
        # default should be at max 1 hour
        delta = datetime.timedelta(seconds=1 * 60 * 60)

    now = datetime.datetime.now()
    expires = now + delta
    expiration = expires.strftime(TIMEFORMAT)

    key = binascii.unhexlify(secret)

    username = "******" % user
    if type(user) == User:
        username = "******" % (user.login, user.realm)
    iv = os.urandom(SECRET_LEN)
    try:
        enc = aes_encrypt_data(username + "|" + client + '|' + expiration,
                               key, iv)
    except Exception as exx:
        log.exception("Failed to create encrypted cookie %r" % exx)
        raise exx

    auth_cookie = "%s%s" % (binascii.hexlify(iv), binascii.hexlify(enc))
    return auth_cookie, expires, expiration
Пример #8
0
    def get_otp_detail(self, otp, window='24h'):
        """
        provide information belonging to one otp

        :param otp: the otp for which the timestamp is searched
        :param window: string, in human readable '2h' or iso8601 format 'PT2H'
        """

        from linotp.lib.type_utils import parse_duration
        window = parse_duration(window).total_seconds()

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

        time_step = self.timeStepping

        T0 = time.time() + self.shift
        counter = time2counter(T0, timeStepping=time_step)

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

        # prepare the hmac operation

        secObj = self._get_secret_object()
        hmac2Otp = HmacOtp(
            secObj, counter, self.otplen, self.getHashlib(self.hashlibStr))
        matching_counter = hmac2Otp.checkOtp(
                                otp, int(window // time_step), symetric=True)


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

        # matching_counter =-1 : no otp found in the current time frame

        if matching_counter == -1:
            log.info('no matching otp found in window: %r', window)
            return False, None

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

        # do not provide information of otps in the future

        if matching_counter >= counter:
            log.info('otp is in future - no info for future otps')
            return False, None


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

        # all fine - now return the time stamp and the utc time format

        time_stamp = counter2time(
            matching_counter, timeStepping=time_step)

        time_info = datetime.datetime.utcfromtimestamp(time_stamp)

        return True, {
            'serial' : self.getSerial(),
            'otp': otp,
            'counter': matching_counter,
            'time': time_info.isoformat(),
            'seconds': int(time_stamp),
            'span': time_step,
        }