Exemplo n.º 1
0
 def test_generate_key_data_error(self):
     kms_client = boto3.client('kms')
     key_id = "test"
     encryption_context = {}
     with Stubber(kms_client) as stubber:
         stubber.add_client_error(
             'generate_key_data',
             'KeyUnavailableException',
             'The request was rejected because the specified CMK was not available. The request can be retried.',
             500,
             expected_params={
                 'KeyId': key_id,
                 'EncryptionContext': encryption_context,
                 'NumberOfBytes': 1
             })
         key_service = KeyService(kms_client, key_id, encryption_context)
         with self.assertRaises(KmsError) as e:
             key_service.generate_key_data(1)
             self.assertEqual(
                 e,
                 KmsError(
                     "Could not generate key using KMS key %s (Details: %s)"
                     %
                     (key_id,
                      'The request was rejected because the specified CMK was not available. The request can be retried.'
                      )))
Exemplo n.º 2
0
 def test_decrypt_success(self):
     kms_client = boto3.client('kms')
     key_id = "test"
     encryption_context = {}
     with Stubber(kms_client) as stubber:
         stubber.add_response('decrypt', {
             'KeyId': 'key_id',
             'Plaintext': b'plaintext'
         },
                              expected_params={
                                  'CiphertextBlob': 'encoded_key',
                                  'EncryptionContext': encryption_context
                              })
         key_service = KeyService(kms_client, key_id, encryption_context)
         response = key_service.decrypt('encoded_key')
     self.assertEqual(response, b'plaintext')
Exemplo n.º 3
0
 def test_generate_key_data_success(self):
     kms_client = boto3.client('kms')
     key_id = "test"
     encryption_context = {}
     with Stubber(kms_client) as stubber:
         stubber.add_response('generate_data_key', {
             'CiphertextBlob': b'ciphertext',
             'Plaintext': b'plaintext',
             'KeyId': 'string'
         },
                              expected_params={
                                  'KeyId': key_id,
                                  'EncryptionContext': encryption_context,
                                  'NumberOfBytes': 1
                              })
         key_service = KeyService(kms_client, key_id, encryption_context)
         response = key_service.generate_key_data(1)
     self.assertEqual(response[0], b'plaintext')
     self.assertEqual(response[1], b'ciphertext')
Exemplo n.º 4
0
 def test_decrypt_invalid_ciphertext_error_with_context(self):
     kms_client = boto3.client('kms')
     key_id = "test"
     encryption_context = {'key': 'value'}
     with Stubber(kms_client) as stubber:
         stubber.add_client_error(
             'decrypt',
             'InvalidCiphertextException',
             'The request was rejected because the specified ciphertext, or additional authenticated data incorporated into the ciphertext, such as the encryption context, is corrupted, missing, or otherwise invalid.',
             400,
             expected_params={
                 'CiphertextBlob': 'encoded_key',
                 'EncryptionContext': encryption_context
             })
         key_service = KeyService(kms_client, key_id, encryption_context)
         with self.assertRaises(KmsError) as e:
             msg = ("Could not decrypt hmac key with KMS. The encryption "
                    "context provided may not match the one used when the "
                    "credential was stored.")
             response = key_service.decrypt('encoded_key')
             self.assertEqual(e, KmsError(msg))
Exemplo n.º 5
0
 def test_decrypt_error(self):
     kms_client = boto3.client('kms')
     key_id = "test"
     encryption_context = {}
     with Stubber(kms_client) as stubber:
         stubber.add_client_error(
             'decrypt',
             'NotFoundException',
             'The request was rejected because the specified entity or resource could not be found.',
             400,
             expected_params={
                 'CiphertextBlob': 'encoded_key',
                 'EncryptionContext': encryption_context
             })
         key_service = KeyService(kms_client, key_id, encryption_context)
         with self.assertRaises(KmsError) as e:
             response = key_service.decrypt('encoded_key')
             self.assertEqual(
                 e,
                 KmsError(
                     "Decryption error The request was rejected because the specified entity or resource could not be found."
                 ))
Exemplo n.º 6
0
def putSecret(name, secret, version="", kms_key="alias/creds3",
              region=None, location=None, context=None,
              digest=DEFAULT_DIGEST, **kwargs):
    '''
    put a secret called `name` into the secret-store,
    protected by the key kms_key
    '''
    if not context:
        context = {}
    session = get_session(**kwargs)
    kms = session.client('kms', region_name=region)
    key_service = KeyService(kms, kms_key, context)
    sealed = seal_aes_ctr_legacy(
        key_service,
        secret,
        digest_method=digest,
    )

    client = session.client('s3', region_name=region)
    (bucket, prefix) = get_s3_bucket_prefix(location)
    version_exists = True
    try:
        obj = client.get_object(Bucket = bucket,
            Key = prefix + name + "/" + version)
    except botocore.exceptions.ClientError as e:
        if e.response["Error"]["Code"] == "NoSuchKey":
            client.put_object(Bucket = bucket,
                  Key = prefix + name + "/" + version,
                  Metadata = sealed[1],
                  Body = sealed[0]
                )
            version_exists = False
        else:
            fatal(e)

    if version_exists:
        latestVersion = getHighestVersion(name, region,
                                            location,
                                            **kwargs)
        fatal("%s version %s is already in the credential store. "
                "Use the -v flag to specify a new version" %
                (name, latestVersion))

    return True
Exemplo n.º 7
0
def getSecret(name, version="", region=None,
              location=None, context=None,
              client=None, kms=None, **kwargs):
    '''
    fetch and decrypt the secret called `name`
    '''
    if not context:
        context = {}

    # Can we cache
    if client is None or kms is None:
        session = get_session(**kwargs)
        if client is None:
            client = session.client('s3', region_name=region)
        if kms is None:
            kms = session.client('kms', region_name=region)

    (bucket, prefix) = get_s3_bucket_prefix(location)

    if version == "":
        secrets = listSecrets(region, bucket + "/" + prefix + name,
                True, **kwargs)
        # do a consistent fetch of the credential with the highest version
        if secrets:
            obj = client.get_object(Bucket = bucket,
                    Key = prefix + name + "/" + secrets[0]["version"])
        else:
            raise ItemNotFound("Item {'name': '%s'} couldn't be found in %s" %
                    name, location)
    else:
        obj = client.get_object(Bucket = bucket,
                    Key = prefix + name + "/" + version)
    material = { "contents": obj["Body"].read() }
    material.update(obj["Metadata"])

    key_service = KeyService(kms, None, context)

    return open_aes_ctr_legacy(key_service, material)