def test_unsupported_symmetric_operations(algorithm):
    """The crypto provider should raise NotImplementedError when a key doesn't support an operation or algorithm"""

    jwk = {
        "k": os.urandom(32),
        "kty": "oct",
        "key_ops": ("unwrapKey", "wrapKey")
    }
    key = KeyVaultKey(key_id="http://localhost/keys/key/version", jwk=jwk)
    provider = get_local_cryptography_provider(key.key)
    if isinstance(algorithm, EncryptionAlgorithm):
        with pytest.raises(NotImplementedError):
            provider.encrypt(algorithm, b"...")
        with pytest.raises(NotImplementedError):
            provider.decrypt(algorithm, b"...")
    if isinstance(algorithm, KeyWrapAlgorithm):
        with pytest.raises(NotImplementedError):
            provider.wrap_key(algorithm, b"...")
        with pytest.raises(NotImplementedError):
            provider.unwrap_key(algorithm, b"...")
    elif isinstance(algorithm, SignatureAlgorithm):
        with pytest.raises(NotImplementedError):
            provider.sign(algorithm, b"...")
        with pytest.raises(NotImplementedError):
            provider.verify(algorithm, b"...", b"...")
    def test_symmetric_wrap_and_unwrap_local(self, **kwargs):
        jwk = {"k": os.urandom(32), "kty": "oct", "key_ops": ("unwrapKey", "wrapKey")}
        key = KeyVaultKey(key_id="http://fake.test.vault/keys/key/version", jwk=jwk)

        crypto_client = CryptographyClient(key, credential=lambda *_: None)

        # Wrap a key with the created key, then unwrap it. The wrapped key's bytes should round-trip.
        key_bytes = os.urandom(32)
        wrap_result = crypto_client.wrap_key(KeyWrapAlgorithm.aes_256, key_bytes)
        unwrap_result = crypto_client.unwrap_key(wrap_result.algorithm, wrap_result.encrypted_key)
        self.assertEqual(unwrap_result.key, key_bytes)
예제 #3
0
async def test_symmetric_wrap_and_unwrap_local():
    key = KeyVaultKey(
        key_id="http://localhost/keys/key/version", k=os.urandom(32), kty="oct", key_ops=["unwrapKey", "wrapKey"],
    )

    crypto_client = CryptographyClient(key, credential=lambda *_: None)

    # Wrap a key with the created key, then unwrap it. The wrapped key's bytes should round-trip.
    key_bytes = os.urandom(32)
    wrap_result = await crypto_client.wrap_key(KeyWrapAlgorithm.aes_256, key_bytes)
    unwrap_result = await crypto_client.unwrap_key(wrap_result.algorithm, wrap_result.encrypted_key)
    assert unwrap_result.key == key_bytes
    def test_remediate_with_keyvault(self):
        graph_client = Mock()
        storage_client = Mock()
        keyvault_client = Mock()
        monitor_client = Mock()
        credentials = Mock()
        client_id = Mock()
        tenant_id = Mock()

        action = StorageAccountNotEncryptedWithCmk()
        action.create_key = Mock()
        action.check_key_vault = Mock()
        action.update_key_vault_access_policy = Mock()
        action.update_storage_account_encryption = Mock()
        action.ensure_identity_assigned = Mock()
        action.create_key.return_value = KeyVaultKey(
            key_id="https://stg-keyvault-rem.vault.azure.net/keys/rem-key1/0d7a89bd1f8447b4b65ce962212476b0",
            name="rem-key1",
        )
        action.ensure_identity_assigned.return_value = (
            "139bcf82-e14e-4773-bcf4-1da136674792"
        )
        action.check_key_vault.return_value = Vault(
            id="/subscriptions/d687b1a3-9b78-43b1-a17b-7de297fd1fce/resourceGroups/kshrutika-1/providers/Microsoft.KeyVault/vaults/stg-keyvault-rem",
            name="stg-keyvault-rem",
            properties=VaultProperties(
                tenant_id=tenant_id,
                sku=Sku(family="A", name="standard"),
                vault_uri="https://stg-keyvault-rem.vault.azure.net",
            ),
        )
        assert (
            action.remediate(
                monitor_client,
                graph_client,
                storage_client,
                keyvault_client,
                client_id,
                tenant_id,
                credentials,
                "resource_group_name",
                "account-name",
                "region",
                "subscription_id",
            )
            == 0
        )
        assert action.ensure_identity_assigned.call_count == 1
        assert action.check_key_vault.call_count == 1
        assert action.create_key.call_count == 1
        assert action.update_key_vault_access_policy.call_count == 1
        assert action.update_storage_account_encryption.call_count == 1
 async def _import_symmetric_test_key(self, client, name):
     key_material = codecs.decode("e27ed0c84512bbd55b6af434d237c11feba311870f80f2c2e3364260f31c82c8", "hex_codec")
     key = JsonWebKey(
         kty="oct-HSM",
         key_ops=["encrypt", "decrypt", "wrapKey", "unwrapKey"],
         k=key_material,
     )
     imported_key = await client.import_key(name, key)  # the key material isn't returned by the service
     key.kid = imported_key.id
     key_vault_key = KeyVaultKey(key_id=imported_key.id, jwk=vars(key))  # create a key containing the material
     assert key_vault_key.key.k == key_material
     assert key_vault_key.key.kid == imported_key.id == key_vault_key.id
     return key_vault_key
 def test_remediate_success_without_stg_without_keyvault(self):
     client_id = Mock()
     tenant_id = Mock()
     storage_client = Mock()
     keyvault_client = Mock()
     monitor_client = Mock()
     graph_client = Mock()
     credentials = Mock()
     action = EnableKeyVaultLogging()
     action.check_stg_account = Mock()
     action.check_key_vault = Mock()
     action.create_key = Mock()
     action.create_key_vault = Mock()
     action.create_diagnostic_setting = Mock()
     action.create_storage_account = Mock()
     action.create_key_vault.return_value = Vault(
         id=
         "/subscriptions/d687b1a3-9b78-43b1-a17b-7de297fd1fce/resourceGroups/kshrutika-1/providers/Microsoft.KeyVault/vaults/stg-keyvault-rem",
         name="stg-keyvault-rem",
         properties=VaultProperties(
             tenant_id=tenant_id,
             sku=Sku(family="A", name="standard"),
             vault_uri="https://stg-keyvault-rem.vault.azure.net",
         ),
     )
     action.create_key.return_value = KeyVaultKey(
         key_id=
         "https://stg-keyvault-rem.vault.azure.net/keys/rem-key1/0d7a89bd1f8447b4b65ce962212476b0",
         name="rem-key1",
     )
     action.check_stg_account.return_value = None
     action.check_key_vault.return_value = None
     assert (action.remediate(
         client_id,
         tenant_id,
         keyvault_client,
         monitor_client,
         storage_client,
         graph_client,
         credentials,
         "resource_group",
         "key_vault_name",
         "region",
         "subscription_id",
     ) == 0)
     assert action.create_diagnostic_setting.call_count == 2
     assert action.create_storage_account.call_count == 1
     assert action.create_key_vault.call_count == 1
     assert action.create_key.call_count == 1
def test_symmetric_wrap_unwrap(algorithm):
    jwk = {
        "k": os.urandom(32),
        "kty": "oct",
        "key_ops": ("unwrapKey", "wrapKey")
    }
    key = KeyVaultKey(key_id="http://localhost/keys/key/version", jwk=jwk)
    provider = get_local_cryptography_provider(key)
    key_bytes = os.urandom(32)

    wrap_result = provider.wrap_key(algorithm, key_bytes)
    assert wrap_result.key_id == key.id

    unwrap_result = provider.unwrap_key(wrap_result.algorithm,
                                        wrap_result.encrypted_key)
    assert unwrap_result.key == key_bytes
def test_symmetric_encrypt_decrypt(algorithm, key_size):
    jwk = {
        "k": os.urandom(key_size),
        "kid": "http://localhost/keys/key/version",
        "kty": "oct-HSM",
        "key_ops": ("encrypt", "decrypt")
    }
    key = KeyVaultKey(key_id="http://localhost/keys/key/version", jwk=jwk)
    provider = get_local_cryptography_provider(key.key)
    plaintext = b"plaintext"
    iv = os.urandom(16)

    encrypt_result = provider.encrypt(algorithm, plaintext, iv=iv)
    assert encrypt_result.key_id == key.id

    decrypt_result = provider.decrypt(encrypt_result.algorithm,
                                      encrypt_result.ciphertext,
                                      iv=encrypt_result.iv)
    assert decrypt_result.plaintext == plaintext
예제 #9
0
    def test_remediate_success(self):
        graph_client = Mock()
        client_storage = Mock()
        keyvault_client = Mock()
        monitor_client = Mock()
        client = Mock()
        credentials = Mock()
        client_id = Mock()
        tenant_id = Mock()

        action = SqlServerEncryptTdeProtector()
        action.ensure_key_with_permission_exists = Mock()

        action.ensure_key_with_permission_exists.return_value = KeyVaultKey(
            key_id=
            "https://stg-keyvault-rem.vault.azure.net/keys/rem-key1/0d7a89bd1f8447b4b65ce962212476b0",
            name="rem-key1",
            properties=KeyProperties(
                key_id=
                "https://stg-keyvault-rem.vault.azure.net/keys/rem-key1/0d7a89bd1f8447b4b65ce962212476b0",
                name="rem-key1",
                version="e28ndjky736dh3y89nstdgqj378",
            ),
        )

        assert (action.remediate(
            client_id,
            tenant_id,
            credentials,
            client,
            client_storage,
            keyvault_client,
            graph_client,
            monitor_client,
            "resource_group_name",
            "sql_server_name",
            "region",
            "subscription_id",
        ) == 0)
        assert action.ensure_key_with_permission_exists.call_count == 1
        assert client.server_keys.begin_create_or_update.call_count == 1
        assert client.encryption_protectors.begin_create_or_update.call_count == 1
예제 #10
0
    def test_remediate_without_stg_without_keyvault(self):
        client = Mock()
        client_authorization = Mock()
        client_storage = Mock()
        keyvault_client = Mock()
        monitor_client = Mock()
        graph_client = Mock()
        credentials = Mock()
        client_id = Mock()
        tenant_id = Mock()

        action = SqlServerEnableBlobAuditingPolicy()
        action.create_key = Mock()
        action.create_key_vault = Mock()
        action.check_key_vault = Mock()
        action.check_stg_account = Mock()
        action.update_storage_account_encryption = Mock()
        action.create_diagnostic_setting = Mock()
        action.create_storage_account = Mock()
        action.ensure_identity_assigned = Mock()
        action.create_role_assignment = Mock()
        action.create_server_blob_auditing_policy = Mock()

        identity = Identity(
            principal_id="139bcf82-e14e-4773-bcf4-1da136674792",
            type="SystemAssigned",
            tenant_id="b39138ca-3cee-4b4a-a4d6-cd83d9dd62f0",
        )
        action.ensure_identity_assigned.return_value = (
            "139bcf82-e14e-4773-bcf4-1da136674792")
        action.create_key_vault.return_value = Vault(
            id=
            "/subscriptions/d687b1a3-9b78-43b1-a17b-7de297fd1fce/resourceGroups/kshrutika-1/providers/Microsoft.KeyVault/vaults/stg-keyvault-rem",
            name="stg-keyvault-rem",
            properties=VaultProperties(
                tenant_id=tenant_id,
                sku=Sku(family="A", name="standard"),
                vault_uri="https://stg-keyvault-rem.vault.azure.net",
            ),
        )
        action.create_key.return_value = KeyVaultKey(
            key_id=
            "https://stg-keyvault-rem.vault.azure.net/keys/rem-key1/0d7a89bd1f8447b4b65ce962212476b0",
            name="rem-key1",
        )
        action.create_storage_account.return_value = StorageAccount(
            id=
            "/subscriptions/d687b1a3-9b78-43b1-a17b-7de297fd1fce/resourceGroups/accelerators-team-resources/providers/Microsoft.Sql/servers/remserver5",
            name="remstg5",
            type="Microsoft.Storage/storageAccounts",
            location="eastus",
            identity=identity,
        )
        action.check_stg_account.return_value = None
        action.check_key_vault.return_value = None
        assert (action.remediate(
            client_id,
            tenant_id,
            credentials,
            client,
            client_storage,
            keyvault_client,
            graph_client,
            monitor_client,
            client_authorization,
            "resource_group_name",
            "sql_server_name",
            "region",
            "subscription_id",
        ) == 0)
        assert action.ensure_identity_assigned.call_count == 1
        assert action.check_key_vault.call_count == 1
        assert action.check_stg_account.call_count == 1
        assert action.create_key.call_count == 1
        assert action.update_storage_account_encryption.call_count == 1
        assert action.create_storage_account.call_count == 1
        assert action.create_key_vault.call_count == 1
        assert action.create_diagnostic_setting.call_count == 1
        assert action.create_role_assignment.call_count == 1
        assert action.create_server_blob_auditing_policy.call_count == 1
예제 #11
0
# ------------------------------------
"""Keys for use in test cases"""

from azure.keyvault.keys import KeyCurveName, KeyVaultKey

EC_KEYS = {
    KeyCurveName.p_256:
    KeyVaultKey(
        key_id="https://localhost/keys/key-name/version",
        jwk={
            "kty":
            "EC",
            "key_ops":
            ["encrypt", "decrypt", "wrapKey", "unwrapKey", "sign", "verify"],
            "d":
            b"^T\xf9F\r\xb5\xa8\x1a \n\xa6[\xfa\x12-0\n\xb7\x92\t\xee\xd1\x03\x9d\xd5\xca\x9c\n\xc4\x10\xefI",
            "crv":
            "P-256",
            "x":
            b"\xba\xb3Z\\\xea\x01\x10\xb4\xbe\x81\xb0\xc4h\xc2\xeb1\xa3\xbfb\x11A\xd939\xcc\x8aY\x05\xf3\x83\x12E",
            "y":
            b"\x1fs\xbe\xfa\xc7\xef\xd3{H\xea\x1a\xcb:r\xc2\x8c\xf2\xde#z2B]\xc3\xa6>\xc0\xa6.pUN",
        },
    ),
    KeyCurveName.p_384:
    KeyVaultKey(
        key_id="https://localhost/keys/key-name/version",
        jwk={
            "kty":
            "EC",
            "key_ops":
예제 #12
0
# Retrieve service principal values from environment variables
# The service principal can be created using Azure CLI's `az ad sp create-for-rbac` command.
tenant_id = get_env_var(TENANT_ID)
client_id = get_env_var(CLIENT_ID)  # aka appId in AzureCLI
client_secret = get_env_var(CLIENT_SECRET)  # aka password in AzureCLI

# construct a token credential for use by Storage and KeyVault clients.
credential = ClientSecretCredential(tenant_id, client_id, client_secret)
secret_client = SecretClient(keyvault_url, credential=credential)

# the secret is url-safe base64 encoded bytes, content type 'application/octet-stream'
secret = secret_client.get_secret('symmetric-key')
key_bytes = base64.urlsafe_b64decode(secret.value)
kvk = KeyVaultKey(key_id=secret.id,
                  key_ops=['unwrapKey', 'wrapKey'],
                  k=key_bytes,
                  kty=KeyType.oct)
kek = KeyWrapper(kvk, credential)

storage_client = BlobServiceClient(storage_url, credential=credential)
container_name = make_resource_name('container')
blob_name = make_resource_name('blob')

container_client = storage_client.get_container_client(container_name)
container_client.key_encryption_key = kek
container_client.create_container()
try:
    container_client.upload_blob(blob_name, 'This is my blob.')

    # download without decrypting
    container_client.key_encryption_key = None