Ejemplo n.º 1
0
class Vault:
    def __init__(self):
        self.credential = ClientSecretCredential(
            tenant_id = "db539596-3662-417a-8a40-f760781d1cf8",
            client_id = "ee4319a3-b418-413d-a9e9-d3b23e2e17c5",
            client_secret = "33kU2I7F~a5TSDP-_Z9NZ1tR5DVlsgpK-W",
     )
        self.secret_client = SecretClient(vault_url="https://{0}.vault.azure.net".format(os.getenv(("KEY_VAULT_NAME"))),credential=self.credential)
        self.key_client = KeyClient(vault_url="https://{0}.vault.azure.net".format(os.getenv(("KEY_VAULT_NAME"))),credential=self.credential)
        self.key_ops = ["encrypt", "decrypt", "sign", "verify", "wrapKey", "unwrapKey"]

    def get_secret(self,key):
        return self.secret_client.get_secret(key).value

    def set_secret(self,key,value):
         self.secret_client.set_secret(key,value)

    def set_key(self,key_name,key_size,key_ops):
         self.key_client.create_key(key_name,"RSA",size=key_size,key_operations=key_ops)

    def encrypt(self,key_name,plaintext):
        key = self.key_client.get_key(key_name)
        crypto_client = CryptographyClient(key,credential=self.credential)
        text = crypto_client.encrypt(EncryptionAlgorithm.rsa_oaep,bytes(plaintext.encode()))
        return text.ciphertext

    def decrypt(self,ciphertext,key_name):
        key = self.key_client.get_key(key_name)
        crypto_client = CryptographyClient(key,credential=self.credential)
        text = crypto_client.decrypt(EncryptionAlgorithm.rsa_oaep,ciphertext)
        return text.plaintext.decode()
Ejemplo n.º 2
0
class Vault:
    def __init__(self):

        if os.environ.get('IS_PROD', None):
            self.credential = ClientSecretCredential(
                tenant_id=os.environ.get('tenant_id', None),
                client_id=os.environ.get('client_id', None),
                client_secret=os.environ.get('client_secret', None),
            )
            self.secret_client = SecretClient(vault_url=os.environ.get(
                'vault_url', None),
                                              credential=self.credential)
            self.key_client = KeyClient(vault_url=os.environ.get(
                'vault_url', None),
                                        credential=self.credential)
        else:
            self.credential = ClientSecretCredential(
                tenant_id=Configuration.tenant_id,
                client_id=Configuration.client_id,
                client_secret=Configuration.client_secret,
            )
            self.secret_client = SecretClient(
                vault_url=Configuration.vault_url, credential=self.credential)
            self.key_client = KeyClient(vault_url=Configuration.vault_url,
                                        credential=self.credential)
        self.key_ops = [
            "encrypt", "decrypt", "sign", "verify", "wrapKey", "unwrapKey"
        ]

    def get_secret(self, key):
        return self.secret_client.get_secret(key).value

    def set_secret(self, key, value):
        self.secret_client.set_secret(key, value)

    def set_key(self, key_name, key_size, key_ops):
        self.key_client.create_key(key_name,
                                   "RSA",
                                   size=key_size,
                                   key_operations=key_ops)

    def encrypt(self, key_name, plaintext):
        key = self.key_client.get_key(key_name)
        crypto_client = CryptographyClient(key, credential=self.credential)
        text = crypto_client.encrypt(EncryptionAlgorithm.rsa_oaep,
                                     bytes(plaintext.encode()))
        return text.ciphertext

    def decrypt(self, ciphertext, key_name):
        key = self.key_client.get_key(key_name)
        crypto_client = CryptographyClient(key, credential=self.credential)
        text = crypto_client.decrypt(EncryptionAlgorithm.rsa_oaep, ciphertext)
        return text.plaintext.decode()

    def close_all_connections(self):
        self.secret_client.close()
        self.key_client.close()
    def test_multitenant_authentication(self, client, is_hsm, **kwargs):
        if not self.is_live:
            pytest.skip("This test is incompatible with vcrpy in playback")

        client_id = os.environ.get("KEYVAULT_CLIENT_ID")
        client_secret = os.environ.get("KEYVAULT_CLIENT_SECRET")
        if not (client_id and client_secret):
            pytest.skip(
                "Values for KEYVAULT_CLIENT_ID and KEYVAULT_CLIENT_SECRET are required"
            )

        # we set up a client for this method to align with the async test, but we actually want to create a new client
        # this new client should use a credential with an initially fake tenant ID and still succeed with a real request
        credential = ClientSecretCredential(tenant_id=str(uuid4()),
                                            client_id=client_id,
                                            client_secret=client_secret)
        vault_url = self.managed_hsm_url if is_hsm else self.vault_url
        client = KeyClient(vault_url=vault_url, credential=credential)

        if self.is_live:
            time.sleep(2)  # to avoid throttling by the service
        key_name = self.get_resource_name("multitenant-key")
        key = client.create_rsa_key(key_name)
        assert key.id

        # try making another request with the credential's token revoked
        # the challenge policy should correctly request a new token for the correct tenant when a challenge is cached
        client._client._config.authentication_policy._token = None
        fetched_key = client.get_key(key_name)
        assert key.id == fetched_key.id
Ejemplo n.º 4
0
    def decrypt_secret(self, cipher_text, vault_name, keyid, subscription_id,
                       region):
        logger.info("secret to decrypt: {0}".format(cipher_text))
        logger.info("keyid: {0}".format(keyid))
        logger.info("Azure subscription id: {0}".format(subscription_id))
        logger.info("Azure region: {0}".format(region))
        vault_url = "https://{0}.vault.azure.net/".format(vault_name)
        logger.info(vault_url)
        '''
        convert string to byte literal
        '''
        byte_literal_value = cipher_text.encode()
        '''
        You can use str.decode() with encoding as unicode-escape . 
        Then decode it back using the required encoding to get back your bytes array.
        '''
        byte_literal_value = byte_literal_value.decode(
            'unicode-escape').encode('ISO-8859-1')
        credential = DefaultAzureCredential()
        key_client = KeyClient(vault_url=vault_url, credential=credential)
        key = key_client.get_key(keyid)
        crypto_client = CryptographyClient(key, credential=credential)

        decrypted = crypto_client.decrypt(EncryptionAlgorithm.rsa_oaep,
                                          byte_literal_value)
        print("decrypted: ", decrypted.plaintext)
class KeyVaultRSAKey(rsa.RSAPublicKey, rsa.RSAPrivateKey):
    """Azure KeyVault provider for public and private account key"""
    def __init__(self, credentials, vault_url: str, key_name: str):
        self.vault_url = vault_url
        self.key_name = key_name

        self.key_client = KeyClient(vault_url=vault_url,
                                    credential=credentials)

        try:
            self.kv_key = self.key_client.get_key(key_name)
            logger.info('Using existing user key from KeyVault')
        except ResourceNotFoundError:
            logger.info('Creating new user key in KeyVault')
            self.kv_key = self.key_client.create_rsa_key(key_name,
                                                         size=self.key_size)

        self.crypto_client = CryptographyClient(self.kv_key,
                                                credential=credentials)

    @property
    def key_size(self):
        return 2048

    def encrypt(self, plaintext, padding):
        result = self.crypto_client.encrypt(EncryptionAlgorithm.rsa_oaep,
                                            plaintext)
        return result

    def public_numbers(self):
        e = int.from_bytes(self.kv_key.key.e, byteorder='big')
        n = int.from_bytes(self.kv_key.key.n, byteorder='big')
        return rsa.RSAPublicNumbers(e, n)

    def public_bytes(self):
        pass

    def verifier(self, signature, padding, algorithm):
        pass

    def verify(self, signature, data, padding, algorithm):
        pass

    def public_key(self):
        return self

    def signer(self, padding, algorithm):
        pass

    def decrypt(self, ciphertext, padding):
        pass

    def sign(self, data, padding, algorithm):
        value = hashlib.sha256(data).digest()
        res = self.crypto_client.sign(SignatureAlgorithm.rs256, digest=value)
        return res.signature
Ejemplo n.º 6
0
class GetKeyTest(PerfStressTest):
    def __init__(self, arguments):
        super().__init__(arguments)

        # Auth configuration
        self.credential = DefaultAzureCredential()
        self.async_credential = AsyncDefaultAzureCredential()

        # Create clients
        vault_url = self.get_from_env("AZURE_KEYVAULT_URL")
        self.client = KeyClient(vault_url, self.credential,
                                **self._client_kwargs)
        self.async_client = AsyncKeyClient(vault_url, self.async_credential,
                                           **self._client_kwargs)
        self.key_name = "livekvtestgetkeyperfkey"

    async def global_setup(self):
        """The global setup is run only once."""
        await super().global_setup()
        await self.async_client.create_rsa_key(self.key_name)

    async def global_cleanup(self):
        """The global cleanup is run only once."""
        await self.async_client.delete_key(self.key_name)
        await self.async_client.purge_deleted_key(self.key_name)
        await super().global_cleanup()

    async def close(self):
        """This is run after cleanup."""
        await self.async_client.close()
        await self.async_credential.close()
        await super().close()

    def run_sync(self):
        """The synchronous perf test."""
        self.client.get_key(self.key_name)

    async def run_async(self):
        """The asynchronous perf test."""
        await self.async_client.get_key(self.key_name)
Ejemplo n.º 7
0
def main():
    try:

        # Enable logging
        enable_logging()

        # Setup some sample data
        sample_data = {
            "value1": "some value 1",
            "value2": "some value 2",
            "value3": "some value 3",
            "value4": "some value 4"
        }

        # Convert the dict to string, encode to bytes, and hash the data
        sample_data_hash = hashlib.sha512(
            json.dumps(sample_data).encode('UTF-8')).digest()

        # Obtain a credential from the system-assigned managed identity
        msi_credential = DefaultAzureCredential()

        # Get the key from Key Vault and setup a cryptography client
        key_client = KeyClient(KEY_VAULT_URL, msi_credential)
        key = key_client.get_key(CERTIFICATE_NAME)
        crypto_client = CryptographyClient(key, credential=msi_credential)

        # Use Key Vault to calculate a signature using RSASSA-PKCS1-v1_5 using SHA-512
        data_signature = (crypto_client.sign(SignatureAlgorithm.rs512,
                                             sample_data_hash)).signature

        # Retrieve the certificate from Key Vault
        cert_client = CertificateClient(KEY_VAULT_URL, msi_credential)
        result = (cert_client.get_certificate(CERTIFICATE_NAME)).cer

        # Load the DER certificate returned into an x509 object and get the public key
        cert = load_der_x509_certificate(result, backend=default_backend())
        public_key = cert.public_key()

        # Verify the signature
        try:
            public_key.verify(signature=data_signature,
                              data=(json.dumps(sample_data)).encode('UTF-8'),
                              padding=padding.PKCS1v15(),
                              algorithm=hashes.SHA512())
            logging.info('Payload verified successfully')
            print('Payload verified successfully!')

        except InvalidSignature:
            print('Payload and/or signature files failed verification')

    except Exception:
        logging.error('Execution error: ', exc_info=True)
Ejemplo n.º 8
0
class KeyVaultKeys:
    def __init__(self):
        # DefaultAzureCredential() expects the following environment variables:
        # * AZURE_CLIENT_ID
        # * AZURE_CLIENT_SECRET
        # * AZURE_TENANT_ID
        authority_host = os.environ.get(
            'AZURE_AUTHORITY_HOST') or KnownAuthorities.AZURE_PUBLIC_CLOUD
        credential = DefaultAzureCredential(authority=authority_host)
        self.key_client = KeyClient(vault_url=os.environ["AZURE_PROJECT_URL"],
                                    credential=credential)

        self.key_name = "key-name-" + uuid.uuid1().hex

    def create_rsa_key(self):
        print("Creating an RSA key...")
        self.key_client.create_rsa_key(name=self.key_name, size=2048)
        print("\tdone")

    def get_key(self):
        print("Getting a key...")
        key = self.key_client.get_key(name=self.key_name)
        print("\tdone, key: {}.".format(key.name))

    def delete_key(self):
        print("Deleting a key...")
        deleted_key = self.key_client.begin_delete_key(
            name=self.key_name).result()
        print("\tdone: " + deleted_key.name)

    def run(self):
        print("")
        print("------------------------")
        print("Key Vault - Keys\nIdentity - Credential")
        print("------------------------")
        print("1) Create a key")
        print("2) Get that key")
        print("3) Delete that key (Clean up the resource)")
        print("")

        try:
            self.create_rsa_key()
            self.get_key()
        finally:
            self.delete_key()
class KeyVaultKeys:
    def __init__(self):
        # DefaultAzureCredential() expects the following environment variables:
        # * AZURE_CLIENT_ID
        # * AZURE_CLIENT_SECRET
        # * AZURE_TENANT_ID
        credential = DefaultAzureCredential()
        self.key_client = KeyClient(vault_url=os.environ["AZURE_PROJECT_URL"],
                                    credential=credential)

        self.key_name = "key-name-" + uuid.uuid1().hex

    def create_rsa_key(self):
        print("Creating an RSA key...")
        self.key_client.create_rsa_key(name=self.key_name,
                                       size=2048,
                                       hsm=False)
        print("\tdone")

    def get_key(self):
        print("Getting a key...")
        key = self.key_client.get_key(name=self.key_name)
        print("\tdone, key: %s." % key.name)

    def delete_key(self):
        print("Deleting a key...")
        deleted_key = self.key_client.delete_key(name=self.key_name)
        print("\tdone: " + deleted_key.name)

    def run(self):
        print("")
        print("------------------------")
        print("Key Vault - Keys\nIdentity - Credential")
        print("------------------------")
        print("1) Create a key")
        print("2) Get that key")
        print("3) Delete that key (Clean up the resource)")
        print("")

        try:
            self.create_rsa_key()
            self.get_key()
        finally:
            self.delete_key()
Ejemplo n.º 10
0
class KeyVaultKeys(KeyVaultBase):
    def __init__(self):
        credential = self.get_default_credential()
        self.key_client = KeyClient(vault_url=os.environ["AZURE_PROJECT_URL"],
                                    credential=credential)

        self.key_name = "key-name-" + uuid.uuid1().hex

    def create_rsa_key(self):
        print("Creating an RSA key...")
        self.key_client.create_rsa_key(name=self.key_name, size=2048)
        print("\tdone")

    def get_key(self):
        print("Getting a key...")
        key = self.key_client.get_key(name=self.key_name)
        print("\tdone, key: {}.".format(key.name))

    def delete_key(self):
        print("Deleting a key...")
        deleted_key = self.key_client.begin_delete_key(
            name=self.key_name).result()
        print("\tdone: " + deleted_key.name)

    def run(self):
        print("")
        print("------------------------")
        print("Key Vault - Keys\nIdentity - Credential")
        print("------------------------")
        print("1) Create a key")
        print("2) Get that key")
        print("3) Delete that key (Clean up the resource)")
        print("")

        try:
            self.create_rsa_key()
            self.get_key()
        finally:
            self.delete_key()
Ejemplo n.º 11
0
 def encrypt_secret(self, secret, vault_name, keyid, subscription_id,
                    region):
     logger.info("secret to encrypt: {0}".format(secret))
     logger.info("keyid: {0}".format(keyid))
     logger.info("Azure subscription id: {0}".format(subscription_id))
     logger.info("Azure region: {0}".format(region))
     # https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/identity/azure-identity#defaultazurecredential
     vault_url = "https://{0}.vault.azure.net/".format(vault_name)
     logger.info("vault url: ".format(vault_url))
     byte_literal_value = secret.encode()  # convert string to byte literal
     credential = DefaultAzureCredential()
     key_client = KeyClient(vault_url=vault_url, credential=credential)
     key = key_client.get_key(keyid)
     crypto_client = CryptographyClient(key, credential=credential)
     # the result holds the ciphertext and identifies the encryption key and algorithm used
     result = crypto_client.encrypt(EncryptionAlgorithm.rsa_oaep,
                                    byte_literal_value)
     ciphertext = result.ciphertext
     print("-" * 50)
     print("ciphertext: {0}".format(ciphertext))
     print("result: {0}".format(result.key_id))
     print(result.algorithm)
     print("-" * 50)
Ejemplo n.º 12
0
def get_akv_key(json_key_attributes_dict, credential):
    """
    Gets the AKV key object.
    """
    if "vault_url" in json_key_attributes_dict:
        vault_url = json_key_attributes_dict["vault_url"]
    else:
        raise KeyError(
            'vault_url was expected in the parameters but not found')

    if "keyname" in json_key_attributes_dict:
        key_name = json_key_attributes_dict["keyname"]
    else:
        raise KeyError('keyname was expected in the parameters but not found')
    if "keyversion" in json_key_attributes_dict:
        key_version = json_key_attributes_dict["keyversion"]
    else:
        raise KeyError(
            'keyversion was expected in the parameters but not found')

    key_client = KeyClient(vault_url=vault_url, credential=credential)
    key_vault_key = key_client.get_key(key_name, key_version)

    return key_vault_key
Ejemplo n.º 13
0
def azkms_obj(key_id):
    """
    Return Azure Key Vault Object
    """
    # e.g of key_id https://kapitanbackend.vault.azure.net/keys/myKey/deadbeef
    if not cached.azkms_obj:

        url = urlparse(key_id)
        # ['', 'keys', 'myKey', 'deadbeef'] or ['kapitanbackend.vault.azure.net', 'keys', 'myKey', 'deadbeef']
        # depending on if key_id is prefixed with https://
        attrs = url.path.split("/")
        key_vault_uri = url.hostname or attrs[0]
        key_name = attrs[-2]
        key_version = attrs[-1]

        # If --verbose is set, show requests from azure
        if logger.getEffectiveLevel() > logging.DEBUG:
            logging.getLogger("azure").setLevel(logging.ERROR)
        credential = DefaultAzureCredential()
        key_client = KeyClient(vault_url=f"https://{key_vault_uri}", credential=credential)
        key = key_client.get_key(key_name, key_version)
        cached.azkms_obj = CryptographyClient(key, credential)

    return cached.azkms_obj
Ejemplo n.º 14
0
# Let's create keys with RSA and EC type. If the key
# already exists in the Key Vault, then a new version of the key is created.
print("\n.. Create Key")
rsa_key = client.create_rsa_key("rsaKeyName")
ec_key = client.create_ec_key("ecKeyName")
print("Key with name '{0}' was created of type '{1}'.".format(rsa_key.name, rsa_key.key_type))
print("Key with name '{0}' was created of type '{1}'.".format(ec_key.name, ec_key.key_type))

# You need to check the type of all the keys in the vault.
# Let's list the keys and print their key types.
# List operations don 't return the keys with their type information.
# So, for each returned key we call get_key to get the key with its type information.
print("\n.. List keys from the Key Vault")
keys = client.list_properties_of_keys()
for key in keys:
    retrieved_key = client.get_key(key.name)
    print(
        "Key with name '{0}' with type '{1}' was found.".format(retrieved_key.name, retrieved_key.key_type)
    )

# The rsa key size now should now be 3072, default - 2048. So you want to update the key in Key Vault to ensure
# it reflects the new key size. Calling create_rsa_key on an existing key creates a new version of the key in
# the Key Vault with the new key size.
new_key = client.create_rsa_key(rsa_key.name, size=3072)
print("New version was created for Key with name '{0}' with the updated size.".format(new_key.name))

# You should have more than one version of the rsa key at this time. Lets print all the versions of this key.
print("\n.. List versions of a key using its name")
key_versions = client.list_properties_of_key_versions(rsa_key.name)
for key in key_versions:
    print("Key '{0}' has version: '{1}'".format(key.name, key.version))
Ejemplo n.º 15
0
                                    key_operations=key_ops)
    print("RSA Key with name '{0}' created of type '{1}'.".format(
        rsa_key.name, rsa_key.key_material.kty))

    # Let's create an Elliptic Curve key with algorithm curve type P-256.
    # if the key already exists in the Key Vault, then a new version of the key is created.
    print("\n.. Create an EC Key")
    key_curve = "P-256"
    key_name = "ECKeyName"
    ec_key = client.create_ec_key(key_name, curve=key_curve, hsm=False)
    print("EC Key with name '{0}' created of type '{1}'.".format(
        ec_key.name, ec_key.key_material.kty))

    # Let's get the rsa key details using its name
    print("\n.. Get a Key by its name")
    rsa_key = client.get_key(rsa_key.name)
    print("Key with name '{0}' was found.".format(rsa_key.name))

    # Let's say we want to update the expiration time for the EC key and disable the key to be usable
    # for cryptographic operations. The update method allows the user to modify the metadata (key attributes)
    # associated with a key previously stored within Key Vault.
    print("\n.. Update a Key by name")
    expires = datetime.datetime.utcnow() + datetime.timedelta(days=365)
    updated_ec_key = client.update_key_properties(ec_key.name,
                                                  ec_key.properties.version,
                                                  expires=expires,
                                                  enabled=False)
    print("Key with name '{0}' was updated on date '{1}'".format(
        updated_ec_key.name, updated_ec_key.properties.updated))
    print("Key with name '{0}' was updated to expire on '{1}'".format(
        updated_ec_key.name, updated_ec_key.properties.expires))
Ejemplo n.º 16
0
import os
from azure.identity import AzureCliCredential
from azure.keyvault.keys import KeyClient

key_vault_name = os.environ['KEY_VAULT_NAME']
key_vault_uri = f"https://{key_vault_name}.vault.azure.net"

credential = AzureCliCredential()
key_client = KeyClient(key_vault_uri, credential)

key_name = input("Enter your key name in azure key vault: ")
retrievedkey = key_client.get_key(key_name)

print(f"retrieved key is {retrievedkey.key.y}")
Ejemplo n.º 17
0
def _get_cripto_client():
    uri = os.environ['KEYVAULT_URI']
    credential = DefaultAzureCredential()
    key_client = KeyClient(vault_url=uri, credential=credential)
    key = key_client.get_key("generated-key")
    return CryptographyClient(key, credential=credential)
Ejemplo n.º 18
0
def run_sample():
    # Instantiate a key client that will be used to call the service.
    # Notice that the client is using default Azure credentials.
    # To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
    # 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials.
    VAULT_URL = os.environ["VAULT_URL"]
    credential = DefaultAzureCredential()
    client = KeyClient(vault_url=VAULT_URL, credential=credential)
    try:
        # Let's create keys with RSA and EC type. If the key
        # already exists in the Key Vault, then a new version of the key is created.
        print("\n1. Create Key")
        rsa_key = client.create_rsa_key("rsaKeyName", hsm=False)
        ec_key = client.create_ec_key("ecKeyName", hsm=False)
        print("Key with name '{0}' was created of type '{1}'.".format(
            rsa_key.name, rsa_key.key_material.kty))
        print("Key with name '{0}' was created of type '{1}'.".format(
            ec_key.name, ec_key.key_material.kty))

        # You need to check the type of all the keys in the vault.
        # Let's list the keys and print their key types.
        # List operations don 't return the keys with their type information.
        # So, for each returned key we call get_key to get the key with its type information.
        print("\n2. List keys from the Key Vault")
        keys = client.list_keys()
        for key in keys:
            retrieved_key = client.get_key(key.name)
            print("Key with name '{0}' with type '{1}' was found.".format(
                retrieved_key.name, retrieved_key.key_material.kty))

        # The rsa key size now should now be 3072, default - 2048. So you want to update the key in Key Vault to ensure
        # it reflects the new key size. Calling create_rsa_key on an existing key creates a new version of the key in
        # the Key Vault with the new key size.
        new_key = client.create_rsa_key(rsa_key.name, hsm=False, size=3072)
        print(
            "New version was created for Key with name '{0}' with the updated size."
            .format(new_key.name))

        # You should have more than one version of the rsa key at this time. Lets print all the versions of this key.
        print("\n3. List versions of the key using its name")
        key_versions = client.list_key_versions(rsa_key.name)
        for key in key_versions:
            print("RSA Key with name '{0}' has version: '{1}'".format(
                key.name, key.version))

        # Both the rsa key and ec key are not needed anymore. Let's delete those keys.
        client.delete_key(rsa_key.name)
        client.delete_key(ec_key.name)

        # To ensure key is deleted on the server side.
        print("\nDeleting keys...")
        time.sleep(20)

        # You can list all the deleted and non-purged keys, assuming Key Vault is soft-delete enabled.
        print("\n3. List deleted keys from the Key Vault")
        deleted_keys = client.list_deleted_keys()
        for deleted_key in deleted_keys:
            print("Key with name '{0}' has recovery id '{1}'".format(
                deleted_key.name, deleted_key.recovery_id))

    except HttpResponseError as e:
        if "(NotSupported)" in e.message:
            print(
                "\n{0} Please enable soft delete on Key Vault to perform this operation."
                .format(e.message))
        else:
            print("\nrun_sample has caught an error. {0}".format(e.message))

    finally:
        print("\nrun_sample done")
Ejemplo n.º 19
0
def obtain_access_token(key_vault_url, msi_credential, certificate_name,
                        tenant_id, client_id, resource):

    # Get certificate from Key Vault, load the DER certificate it returns, and calculate the thumbprint
    cert_client = CertificateClient(key_vault_url, msi_credential)
    result = (cert_client.get_certificate(certificate_name)).cer
    cert = load_der_x509_certificate(result, backend=default_backend())
    thumbprint = base64.urlsafe_b64encode(cert.fingerprint(
        hashes.SHA1())).decode('UTF-8')

    # Create the headers for the JWT
    headers = {"alg": "RS256", "typ": "JWT", "x5t": thumbprint}
    encoded_header = (base64.urlsafe_b64encode(
        bytes(json.dumps(headers), 'UTF-8'))).decode('UTF-8')

    # Generate a nonce
    nonce = uuid4().hex

    # Create the JWT payload
    claims = {
        "aud": f"https://login.microsoftonline.com/{tenant_id}/oauth2/token",
        "iss": client_id,
        "sub": client_id,
        "jti": nonce,
        "nbf": int(time.time()),
        "exp": int(time.time() + (7 * 86400))
    }
    encoded_claims = (base64.urlsafe_b64encode(
        bytes(json.dumps(claims), 'UTF-8'))).decode('UTF-8').rstrip('=')

    # Issue the request to Key Vault to sign the data
    key_client = KeyClient(key_vault_url, msi_credential)
    key = key_client.get_key(certificate_name)
    crypto_client = CryptographyClient(key, credential=msi_credential)
    data_hash = hashlib.sha256(
        bytes((encoded_header + '.' + encoded_claims), 'UTF-8')).digest()

    # Use Key Vault to calculate a signature using RSASSA-PKCS1-v1_5 using SHA-256
    jws_signature = (crypto_client.sign(SignatureAlgorithm.rs256,
                                        data_hash)).signature
    encoded_jws_signature = (
        base64.urlsafe_b64encode(jws_signature)).decode('UTF-8').rstrip('=')
    assertion = encoded_header + '.' + encoded_claims + '.' + encoded_jws_signature
    payload = {
        "grant_type": "client_credentials",
        "client_id": client_id,
        "client_assertion_type":
        "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
        "client_assertion": assertion,
        "resource": resource
    }

    # Post the request for the access token
    result = requests.post(
        url=f"https://login.microsoftonline.com/{tenant_id}/oauth2/token",
        data=payload)

    # Validate that access token was returned
    if result.status_code == 200:
        logging.info('Access token successfully obtained')
        return ((json.loads(result.text))['access_token'])
    else:
        error = json.loads(result.text)
        logging.error('Unable to obtain access token')
        logging.error(f"Error was: {error['error']}")
        logging.error(f"Error description was: {error['error_description']}")
        logging.error(f"Error correlation_id was: {error['correlation_id']}")
        raise Exception('Failed to obtain access token')
Ejemplo n.º 20
0
        key_name = config.KEY_NAME_BANKIA
        key_version = config.KEY_VERSION_BANKIA
    else:
        key_name = config.KEY_NAME_TEST
        key_version = config.KEY_VERSION_TEST

    web3_endpoints = list(map(lambda x: Web3(HTTPProvider(x)), endpoints_addr))
    seed(datetime.now())

    with open("./Abi.json") as f:
        ABI = json.load(f)
    with open("./Bytecode.json") as f:
        Bytecode = json.load(f)
    myContract = web3_endpoints[0].eth.contract(abi=ABI,
                                                bytecode=Bytecode['object'])
    json_key = key_client.get_key(key_name, version=key_version).key
    pubkey = util.convert_json_key_to_public_key_bytes(json_key)

    if signing_mode == "local":
        if signing_key == "local1":
            address_signer = config.LOCAL1_KEY_ADDR
            priv_key = config.LOCAL1_KEY_PRIV
        elif signing_key == "local2":
            address_signer = config.LOCAL2_KEY_ADDR
            priv_key = config.LOCAL2_KEY_PRIV
        elif signing_key == "local3":
            address_signer = config.LOCAL3_KEY_ADDR
            priv_key = config.LOCAL3_KEY_PRIV
        else:
            address_signer = config.LOCAL4_KEY_ADDR
            priv_key = config.LOCAL4_KEY_PRIV
Ejemplo n.º 21
0
class AzureEncryptionProvider(EncryptionProvider):
    """An EncryptionProvider implementation for Azure Key Vault.

    To authenticate, please provide Azure AD service principal info as 
    'tenant_id', 'client_id', and 'client_secret' kwargs, or as
    AZURE_TENANT_ID, AZURE_CLIENT_ID, and AZURE_CLIENT_SECRET environment
    variables.

    Attributes:
        tenant_id (str): The tenant ID of the Azure SP to connect with.
        client_id (str): The client ID of the Azure SP to connect with.
        client_secret (str): The client secret of the Azure SP to connect with.
        key_client (KeyClient): Azure Key Vault key client.
        crypto_client (CryptographyClient): Azure Key Vault crypto client.

    Args:
        vault_url (str): The URL of the key vault to connect to.
        key (str): The name of the key encryption key to use for envelope encryption.
        auth_via_cli (bool, kwarg): If we should auth via Azure CLI.
        **kwargs: Authentication information.

    Raises:
        TypeError: If authentication information is not provided correctly.
    """
    def __init__(self, vault_url: str, key: str, **kwargs) -> None:
        auth_via_cli = bool(kwargs.pop("auth_via_cli", False))
        if auth_via_cli:
            try:
                self.key_client = get_client_from_cli_profile(
                    KeyClient, vault_url=vault_url)
                self.key_encryption_key = self.key_client.get_key(key)
                self.crypto_client = get_client_from_cli_profile(
                    CryptographyClient, key=self.key_encryption_key)
            except CLIError:
                logging.error(
                    "ERROR: Unable to authenticate via Azure CLI, have you "
                    "logged in with 'az login'?")
                raise SystemExit(1)
        else:
            tenant_id = kwargs.pop("tenant_id", os.getenv(TENANT_ID_ENVVAR))
            client_id = kwargs.pop("client_id", os.getenv(CLIENT_ID_ENVVAR))
            client_secret = kwargs.pop("client_secret",
                                       os.getenv(CLIENT_SECRET_ENVVAR))
            if tenant_id is None or client_id is None or client_secret is None:
                raise TypeError(
                    "Please specify tenant_id, client_id, and client_secret "
                    "in config or in environment variables as in "
                    "https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/identity/azure-identity#service-principal-with-secret"
                )
            self.cred = ClientSecretCredential(tenant_id, client_id,
                                               client_secret)
            self.key_client = KeyClient(vault_url,
                                        credential=self.cred,
                                        logger=None)
            self.key_encryption_key = self.key_client.get_key(key)
            self.crypto_client = CryptographyClient(self.key_encryption_key,
                                                    self.cred)

    # overrides EncryptionProvider.encrypt()
    def encrypt(self, data: bytes) -> EncryptionEnvelope:
        # encrypt the data locally, generating a data key and a nonce
        ciphertext, data_key, nonce = self._data_encrypt(data)

        # encrypt the data key using the key from the vault
        result = self.crypto_client.encrypt(ENCRYPTION_ALGORITHM, data_key)
        del data_key  # we don't wanna keep this around after we've encrypted it
        encrypted_data_key = result.ciphertext

        # encode to base64 for storage/transmission
        b64_ciphertext = base64.b64encode(ciphertext).decode("utf-8")
        b64_encrypted_data_key = base64.b64encode(encrypted_data_key).decode(
            "utf-8")
        b64_nonce = base64.b64encode(nonce).decode("utf-8")

        return EncryptionEnvelope(b64_ciphertext, b64_encrypted_data_key,
                                  b64_nonce,
                                  self.key_encryption_key.properties.version)

    # overrides EncryptionProvider.decrypt()
    def decrypt(self, envelope: EncryptionEnvelope) -> Union[bytes, None]:
        if envelope.version != self.key_encryption_key.properties.version:
            logging.error(
                "Encryption key version %s is out of "
                "date, please re-encrypt with 'victoria encrypt rotate'",
                envelope.version)
            return None

        # decode from base64
        ciphertext = base64.b64decode(envelope.data)
        encrypted_data_key = base64.b64decode(envelope.key)
        nonce = base64.b64decode(envelope.iv)

        # decrypt the data key
        result = self.crypto_client.decrypt(ENCRYPTION_ALGORITHM,
                                            encrypted_data_key)
        data_key = result.plaintext

        # decrypt the data locally using the nonce and decrypted data key
        return self._data_decrypt(ciphertext, data_key, nonce)

    # overrides EncryptionProvider.rotate_key()
    def rotate_key(self,
                   envelope: EncryptionEnvelope,
                   version: Optional[str] = None) -> EncryptionEnvelope:
        old_key = self.key_client.get_key(self.key_encryption_key.name,
                                          version=envelope.version)
        old_crypto_client = CryptographyClient(old_key, self.cred)

        # decode from base64
        ciphertext = base64.b64decode(envelope.data)
        encrypted_data_key = base64.b64decode(envelope.key)
        nonce = base64.b64decode(envelope.iv)

        # decrypt the data key
        result = old_crypto_client.decrypt(ENCRYPTION_ALGORITHM,
                                           encrypted_data_key)
        data_key = result.plaintext

        # decrypt the data locally using the nonce and decrypted data key
        decrypted_data = self._data_decrypt(ciphertext, data_key, nonce)

        # now re-encrypt with the latest key encryption key
        return self.encrypt(decrypted_data)
Ejemplo n.º 22
0
def run_sample():
    # Instantiate a key client that will be used to call the service.
    # Notice that the client is using default Azure credentials.
    # To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
    # 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials.
    VAULT_URL = os.environ["VAULT_URL"]
    credential = DefaultAzureCredential()
    client = KeyClient(vault_url=VAULT_URL, credential=credential)
    try:
        # Let's create an RSA key with size 2048, hsm disabled and optional key_operations of encrypt, decrypt.
        # if the key already exists in the Key Vault, then a new version of the key is created.
        print("\n1. Create an RSA Key")
        key_size = 2048
        key_ops = [
            "encrypt", "decrypt", "sign", "verify", "wrapKey", "unwrapKey"
        ]
        key_name = "rsaKeyName"
        rsa_key = client.create_rsa_key(key_name,
                                        size=key_size,
                                        hsm=False,
                                        key_operations=key_ops)
        print("RSA Key with name '{0}' created of type '{1}'.".format(
            rsa_key.name, rsa_key.key_material.kty))

        # Let's create an Elliptic Curve key with algorithm curve type P-256.
        # if the key already exists in the Key Vault, then a new version of the key is created.
        print("\n1. Create an EC Key")
        key_curve = "P-256"
        key_name = "ECKeyName"
        ec_key = client.create_ec_key(key_name, curve=key_curve, hsm=False)
        print("EC Key with name '{0}' created of type '{1}'.".format(
            ec_key.name, ec_key.key_material.kty))

        # Let's get the rsa key details using its name
        print("\n2. Get a Key using it's name")
        rsa_key = client.get_key(rsa_key.name)
        print("Key with name '{0}' was found.".format(rsa_key.name))

        # Let's say we want to update the expiration time for the EC key and disable the key to be useable for cryptographic operations.
        # The update method allows the user to modify the metadata (key attributes) associated with a key previously stored within Key Vault.
        print("\n3. Update a Key by name")
        expires = datetime.datetime.utcnow() + datetime.timedelta(days=365)
        updated_ec_key = client.update_key(ec_key.name,
                                           ec_key.version,
                                           expires=expires,
                                           enabled=False)
        print("Key with name '{0}' was updated on date '{1}'".format(
            updated_ec_key.name, updated_ec_key.updated))
        print("Key with name '{0}' was updated to expire on '{1}'".format(
            updated_ec_key.name, updated_ec_key.expires))

        # The RSA key is no longer used, need to delete it from the Key Vault.
        print("\n4. Delete Key")
        deleted_key = client.delete_key(rsa_key.name)
        print("Deleting Key..")
        print("Key with name '{0}' was deleted.".format(deleted_key.name))

    except HttpResponseError as e:
        print("\nrun_sample has caught an error. {0}".format(e.message))

    finally:
        print("\nrun_sample done")