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)
class GetCertificateTest(PerfStressTest):
    def __init__(self, arguments):
        super().__init__(arguments)

        # Auth configuration
        self.credential = EnvironmentCredential()
        self.async_credential = AsyncEnvironmentCredential()

        # Create clients
        vault_url = self.get_from_env("AZURE_KEYVAULT_URL")
        self.client = CertificateClient(vault_url, self.credential)
        self.async_client = AsyncCertificateClient(vault_url,
                                                   self.async_credential)

    async def global_setup(self):
        """The global setup is run only once."""
        await super().global_setup()
        await self.async_client.create_certificate(
            "livekvtestperfcert", CertificatePolicy.get_default())

    async def global_cleanup(self):
        """The global cleanup is run only once."""
        await self.async_client.delete_certificate("livekvtestperfcert")
        await self.async_client.purge_deleted_certificate("livekvtestperfcert")
        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_certificate("livekvtestperfcert")

    async def run_async(self):
        """The asynchronous perf test."""
        await self.async_client.get_certificate("livekvtestperfcert")
Example #3
0
class KeyVaultCertificates:
    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.certificate_client = CertificateClient(
            vault_url=os.environ["AZURE_PROJECT_URL"], credential=credential
        )

        self.certificate_name = "cert-name-" + uuid.uuid1().hex

    def create_certificate(self):
        print("Creating certificate (name: {})".format(self.certificate_name))
        create_poller = self.certificate_client.begin_create_certificate(
            certificate_name=self.certificate_name,
            policy=CertificatePolicy.get_default())
        print("\twaiting...")
        create_poller.result()
        print("\tdone")

    def get_certificate(self):
        print("Getting a certificate...")
        certificate = self.certificate_client.get_certificate(certificate_name=self.certificate_name)
        print("\tdone, certificate: {}.".format(certificate.name))

    def delete_certificate(self):
        print("Deleting a certificate...")
        poller = self.certificate_client.begin_delete_certificate(certificate_name=self.certificate_name)
        deleted_certificate = poller.result()
        print("\tdone: " + deleted_certificate.name)

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

        try:
            self.create_certificate()
            self.get_certificate()
        finally:
            self.delete_certificate()
def get_certdate():

    credential = DefaultAzureCredential()
    certificate_client = CertificateClient(vault_url=(os.environ.get('kvurl')),
                                           credential=credential)
    certificate = certificate_client.get_certificate(
        certificate_name=(os.environ.get('certname')))
    cert_date = certificate.properties.expires_on.strftime("%d/%m/%Y")
    limit_date = (datetime.now() + timedelta(days=7)).strftime("%d/%m/%Y")
    slack_token = os.environ.get('slacktoken')

    if cert_date == limit_date:
        queue_build()
        slack_message('O certificate vai expirar')
    else:
        slack_message('O certificate não vai expirar')
Example #5
0
class KeyVaultCertificates(KeyVaultBase):
    def __init__(self):

        credential = self.get_default_credential()
        self.certificate_client = CertificateClient(
            vault_url=os.environ["AZURE_PROJECT_URL"], credential=credential)

        self.certificate_name = "cert-name-" + uuid.uuid1().hex

    def create_certificate(self):
        print("Creating certificate (name: {})".format(self.certificate_name))
        create_poller = self.certificate_client.begin_create_certificate(
            certificate_name=self.certificate_name,
            policy=CertificatePolicy.get_default())
        print("\twaiting...")
        create_poller.result()
        print("\tdone")

    def get_certificate(self):
        print("Getting a certificate...")
        certificate = self.certificate_client.get_certificate(
            certificate_name=self.certificate_name)
        print("\tdone, certificate: {}.".format(certificate.name))

    def delete_certificate(self):
        print("Deleting a certificate...")
        poller = self.certificate_client.begin_delete_certificate(
            certificate_name=self.certificate_name)
        deleted_certificate = poller.result()
        print("\tdone: " + deleted_certificate.name)

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

        try:
            self.create_certificate()
            self.get_certificate()
        finally:
            self.delete_certificate()
Example #6
0
class KeyVaultCertificates:
    def __init__(self):
        # DefaultAzureCredential() expects the following environment variables:
        # * AZURE_CLIENT_ID
        # * AZURE_CLIENT_SECRET
        # * AZURE_TENANT_ID
        credential = DefaultAzureCredential()
        self.certificate_client = CertificateClient(
            vault_url=os.environ["AZURE_PROJECT_URL"], credential=credential)

        self.certificate_name = "cert-name-" + uuid.uuid1().hex

    def create_certificate(self):
        self.certificate_client.begin_create_certificate(
            name=self.certificate_name,
            policy=CertificatePolicy.get_default()).wait()
        print("\tdone")

    def get_certificate(self):
        print("Getting a certificate...")
        certificate = self.certificate_client.get_certificate(
            name=self.certificate_name)
        print(f"\tdone, certificate: {certificate.name}.")

    def delete_certificate(self):
        print("Deleting a certificate...")
        deleted_certificate = self.certificate_client.delete_certificate(
            name=self.certificate_name)
        print("\tdone: " + deleted_certificate.name)

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

        try:
            self.create_certificate()
            self.get_certificate()
        finally:
            self.delete_certificate()
Example #7
0
        reuse_key=False,
        content_type=CertificateContentType.pkcs12,
        validity_in_months=24,
    )
    cert_name = "HelloWorldCertificate"

    # begin_create_certificate returns a poller. Calling result() on the poller will return the certificate
    # as a KeyVaultCertificate if creation is successful, and the CertificateOperation if not. The wait()
    # call on the poller will wait until the long running operation is complete.
    certificate = client.begin_create_certificate(certificate_name=cert_name,
                                                  policy=cert_policy).result()
    print("Certificate with name '{0}' created".format(certificate.name))

    # Let's get the bank certificate using its name
    print("\n.. Get a certificate by name")
    bank_certificate = client.get_certificate(cert_name)
    print("Certificate with name '{0}' was found'.".format(
        bank_certificate.name))

    # After one year, the bank account is still active, and we have decided to update the tags.
    print("\n.. Update a certificate by name")
    tags = {"a": "b"}
    updated_certificate = client.update_certificate_properties(
        certificate_name=bank_certificate.name, tags=tags)
    print("Certificate with name '{0}' was updated on date '{1}'".format(
        bank_certificate.name, updated_certificate.properties.updated_on))
    print("Certificate with name '{0}' was updated with tags '{1}'".format(
        bank_certificate.name, updated_certificate.properties.tags))

    # The bank account was closed, need to delete its credentials from the Key Vault.
    print("\n.. Delete certificate")
Example #8
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')