Esempio n. 1
0
def decrypt_token(token, _from):
    '''
    Decrypt a token.
    '''
    try:
        token_key = '{0}{1}'.format(hashlib.sha256(token).hexdigest(), _from)
    except Exception:
        raise TokenDecryptionError('Authentication error.')
    if token_key not in TOKENS:
        try:
            token = base64.b64decode(token)
            with stats.timer('kms_decrypt_token'):
                data = kms.decrypt(
                    CiphertextBlob=token,
                    EncryptionContext={
                        # This key is sent to us.
                        'to': app.config['AUTH_CONTEXT'],
                        # From a service.
                        'from': _from
                    })
            # Decrypt doesn't take KeyId as an argument. We need to verify the
            # correct key was used to do the decryption.
            # Annoyingly, the KeyId from the data is actually an arn.
            key_arn = data['KeyId']
            if key_arn != get_key_arn(app.config['AUTH_KEY']):
                raise TokenDecryptionError('Authentication error.')
            plaintext = data['Plaintext']
            payload = json.loads(plaintext)
        # We don't care what exception is thrown. For paranoia's sake, fail
        # here.
        except Exception:
            log.exception('Failed to validate token.')
            raise TokenDecryptionError('Authentication error.')
    else:
        payload = TOKENS[token_key]
    time_format = "%Y%m%dT%H%M%SZ"
    now = datetime.datetime.utcnow()
    try:
        not_before = datetime.datetime.strptime(payload['not_before'],
                                                time_format)
        not_after = datetime.datetime.strptime(payload['not_after'],
                                               time_format)
    except Exception:
        log.exception(
            'Failed to get not_before and not_after from token payload.')
        raise TokenDecryptionError('Authentication error.')
    delta = (not_after - not_before).seconds / 60
    if delta > app.config['AUTH_TOKEN_MAX_LIFETIME']:
        log.warning('Token used which exceeds max token lifetime.')
        raise TokenDecryptionError('Authentication error.')
    if not (now >= not_before) and (now <= not_after):
        log.warning('Expired token used.')
        raise TokenDecryptionError('Authentication error.')
    TOKENS[token_key] = payload
    return payload
Esempio n. 2
0
def decrypt_key(data_key, encryption_context=None):
    '''
    Decrypt a datakey.
    '''
    # Disabled encryption is dangerous, so we don't use falsiness here.
    if app.config['USE_ENCRYPTION'] is False:
        log.warning('Decypting a mock data key in keymanager.decrypt_key.'
                    ' If you are not running in a development or test'
                    ' environment, this should not be happening!')
        return _decrypt_mock_datakey(data_key)
    sha = hashlib.sha256(data_key).hexdigest()
    if sha not in DATAKEYS:
        plaintext = kms.decrypt(
            CiphertextBlob=data_key,
            EncryptionContext=encryption_context)['Plaintext']
        DATAKEYS[sha] = plaintext
    return DATAKEYS[sha]
Esempio n. 3
0
def decrypt_key(data_key, encryption_context=None):
    '''
    Decrypt a datakey.
    '''
    # Disabled encryption is dangerous, so we don't use falsiness here.
    if app.config['USE_ENCRYPTION'] is False:
        log.warning('Decypting a mock data key in keymanager.decrypt_key.'
                    ' If you are not running in a development or test'
                    ' environment, this should not be happening!')
        return _decrypt_mock_datakey(data_key)
    sha = hashlib.sha256(data_key).hexdigest()
    if sha not in DATAKEYS:
        plaintext = kms.decrypt(
            CiphertextBlob=data_key,
            EncryptionContext=encryption_context
        )['Plaintext']
        DATAKEYS[sha] = plaintext
    return DATAKEYS[sha]
Esempio n. 4
0
def decrypt_token(token, _from):
    '''
    Decrypt a token.
    '''
    try:
        token_key = '{0}{1}'.format(
            hashlib.sha256(token).hexdigest(),
            _from
        )
    except Exception:
        raise TokenDecryptionError('Authentication error.')
    if token_key not in TOKENS:
        try:
            token = base64.b64decode(token)
            with stats.timer('kms_decrypt_token'):
                data = kms.decrypt(
                    CiphertextBlob=token,
                    EncryptionContext={
                        # This key is sent to us.
                        'to': app.config['AUTH_CONTEXT'],
                        # From a service.
                        'from': _from
                    }
                )
            # Decrypt doesn't take KeyId as an argument. We need to verify the
            # correct key was used to do the decryption.
            # Annoyingly, the KeyId from the data is actually an arn.
            key_arn = data['KeyId']
            if key_arn != get_key_arn(app.config['AUTH_KEY']):
                raise TokenDecryptionError('Authentication error.')
            plaintext = data['Plaintext']
            payload = json.loads(plaintext)
        # We don't care what exception is thrown. For paranoia's sake, fail
        # here.
        except Exception:
            log.exception('Failed to validate token.')
            raise TokenDecryptionError('Authentication error.')
    else:
        payload = TOKENS[token_key]
    time_format = "%Y%m%dT%H%M%SZ"
    now = datetime.datetime.utcnow()
    try:
        not_before = datetime.datetime.strptime(
            payload['not_before'],
            time_format
        )
        not_after = datetime.datetime.strptime(
            payload['not_after'],
            time_format
        )
    except Exception:
        log.exception(
            'Failed to get not_before and not_after from token payload.'
        )
        raise TokenDecryptionError('Authentication error.')
    delta = (not_after - not_before).seconds / 60
    if delta > app.config['AUTH_TOKEN_MAX_LIFETIME']:
        log.warning('Token used which exceeds max token lifetime.')
        raise TokenDecryptionError('Authentication error.')
    if not (now >= not_before) and (now <= not_after):
        log.warning('Expired token used.')
        raise TokenDecryptionError('Authentication error.')
    TOKENS[token_key] = payload
    return payload