def set_policy_aad_secured(self):
        """
        Sets a minimal attestation policy for SGX enclaves with a customer
        specified signing key and certificate.
        """

        write_banner("set_policy_aad_secured")
        print("Set Secured Policy on an AAD mode attestation instance.")
        with self._create_admin_client(self.aad_url) as admin_client:
            # [START set_secured_policy]
            # Create an RSA Key and wrap an X.509 certificate around
            # the public key for that certificate.
            rsa_key = create_rsa_key()
            cert = create_x509_certificate(rsa_key, u'TestCertificate')

            # Set a minimal policy.
            set_result = admin_client.set_policy(
                AttestationType.SGX_ENCLAVE,
                """version= 1.0;authorizationrules{=> permit();};issuancerules {};""",
                signing_key=AttestationSigningKey(rsa_key, cert))
            print("Policy Set Resolution: ",
                  set_result.value.policy_resolution)
            print(
                "Resulting policy signer should match the input certificate:")
            print(
                "Policy Signer: ",
                base64.b64encode(
                    set_result.value.policy_signer.certificates[0]).decode(
                        'ascii'))
            print("Certificate:   ", base64.b64encode(cert).decode('ascii'))
            # [END set_secured_policy]

            # Reset the policy now that we're done.
            admin_client.reset_policy(AttestationType.SGX_ENCLAVE)
    def set_policy_aad_secured(self):
        """
        Sets a minimal attestation policy for SGX enclaves with a customer
        specified signing key and certificate.
        """

        write_banner("set_policy_aad_secured")
        print("Set Secured Policy on an AAD mode attestation instance.")
        # [START set_secured_policy]
        with AttestationAdministrationClient(
                os.environ.get("ATTESTATION_AAD_URL"),
                DefaultAzureCredential()) as admin_client:
            # Create an RSA Key and wrap an X.509 certificate around
            # the public key for that certificate.
            rsa_key = create_rsa_key()
            cert = create_x509_certificate(rsa_key, u"TestCertificate")

            # Set a minimal policy.
            set_result, _ = admin_client.set_policy(
                AttestationType.SGX_ENCLAVE,
                """version= 1.0;authorizationrules{=> permit();};issuancerules {};""",
                signing_key=rsa_key,
                signing_certificate=cert,
            )
            print("Policy Set Resolution: ", set_result.policy_resolution)
            print(
                "Resulting policy signer should match the input certificate:")
            print("Policy Signer: ", set_result.policy_signer.certificates[0])
            print("Certificate:   ", cert)
            # [END set_secured_policy]

            # Reset the policy now that we're done.
            admin_client.reset_policy(AttestationType.SGX_ENCLAVE)
    def set_policy_validate_hash(self):
        """
        Sets a signed attestation policy and validates the signing certificate and
        policy hash after the `set_policy` API returns.
        """

        # [START validate_policy_hash]
        from cryptography.hazmat.primitives import hashes

        write_banner("set_policy_aad_secured")
        print("Set Secured Policy on an AAD mode attestation instance.")
        with AttestationAdministrationClient(
                os.environ.get("ATTESTATION_AAD_URL"),
                DefaultAzureCredential()) as admin_client:
            # Create an RSA Key and wrap an X.509 certificate around
            # the public key for that certificate.
            rsa_key = create_rsa_key()
            cert = create_x509_certificate(rsa_key, u"TestCertificate")

            # Set a minimal policy.
            policy_to_set = """
version= 1.0;
authorizationrules{=> permit();};
issuancerules {};
"""
            set_result, _ = admin_client.set_policy(
                AttestationType.SGX_ENCLAVE,
                policy_to_set,
                signing_key=rsa_key,
                signing_certificate=cert,
            )
            print("Policy Set Resolution: ", set_result.policy_resolution)
            print(
                "Resulting policy signer should match the input certificate:")
            print("Policy Signer: ", set_result.policy_signer.certificates[0])
            print("Certificate:   ", cert)

            # Create an Attestation Token object representing the
            # attestation policy.
            expected_policy = AttestationPolicyToken(policy_to_set,
                                                     signing_key=rsa_key,
                                                     signing_certificate=cert)

            # Generate the Sha256 hash of the attestation token.
            hasher = hashes.Hash(hashes.SHA256(), backend=default_backend())
            hasher.update(expected_policy.to_jwt_string().encode("utf-8"))
            expected_hash = hasher.finalize()

            print("Expected hash should match returned hash.")
            print("Expected hash: ", expected_hash)
            print("Returned hash: ", set_result.policy_token_hash)

            # [END validate_policy_hash]

            # Reset the policy now that we're done.
            admin_client.reset_policy(AttestationType.SGX_ENCLAVE)
    def reset_policy_aad_secured(self):
        """ Set a secured attestation policy on an AAD mode instance"""
        write_banner("reset_policy_aad_secured")
        print("Set Secured Policy on an AAD mode attestation instance.")
        with self._create_admin_client(self.aad_url) as admin_client:
            rsa_key = create_rsa_key()
            cert = create_x509_certificate(rsa_key, u'TestCertificate')

            set_result = admin_client.reset_policy(
                AttestationType.SGX_ENCLAVE,
                signing_key=AttestationSigningKey(rsa_key, cert))
            print("Policy Set Resolution: ",
                  set_result.value.policy_resolution)
    def reset_policy_aad_secured(self):
        """Set a secured attestation policy on an AAD mode instance, specifying
        a default signing key and certificate to be used for all policy operations.
        """
        write_banner("reset_policy_aad_secured")
        # [BEGIN reset_aad_policy_secured]
        print("Set Secured Policy on an AAD mode attestation instance.")
        rsa_key = create_rsa_key()
        cert = create_x509_certificate(rsa_key, u"TestCertificate")

        # Create an administrative client, specifying a default key and certificate.
        # The key and certificate will be used for subsequent policy operations.
        with AttestationAdministrationClient(
                os.environ.get("ATTESTATION_AAD_URL"),
                DefaultAzureCredential(),
                signing_key=rsa_key,
                signing_certificate=cert,
        ) as admin_client:

            set_result, _ = admin_client.reset_policy(
                AttestationType.SGX_ENCLAVE)
            print("Policy Set Resolution: ", set_result.policy_resolution)
    def add_remove_policy_management_certificate(self):
        """
        Add and then remove a  policy management certificates for an Isolated
        mode attestation instance.

        """
        write_banner("add_remove_policy_management_certificate")
        print(
            "Get and set the policy management certificates for a isolated instance."
        )
        with self._create_admin_client(self.isolated_url) as admin_client:
            # [BEGIN add_policy_management_certificate]
            new_key = create_rsa_key()
            new_certificate = create_x509_certificate(new_key,
                                                      u'NewCertificateName')

            # Add the new certificate to the list.
            add_result = admin_client.add_policy_management_certificate(
                new_certificate,
                AttestationSigningKey(self.isolated_key,
                                      self.isolated_certificate))
            if add_result.value.certificate_resolution != CertificateModification.IS_PRESENT:
                raise Exception("Certificate was not added!")

            # [END add_policy_management_certificate]

            get_result = admin_client.get_policy_management_certificates()
            print("Isolated instance now has", len(get_result.value),
                  "certificates - should be 2")

            for cert_der in get_result.value:
                cert = load_der_x509_certificate(cert_der[0],
                                                 default_backend())
                print("certificate subject: ", cert.subject)

            # The signing certificate for the isolated instance should be
            # the configured isolated_signing_certificate.
            #
            # Note that the certificate list returned is an array of certificate chains.
            actual_cert0 = base64.b64encode(
                get_result.value[0][0]).decode('ascii')
            isolated_cert = base64.b64encode(
                self.isolated_certificate).decode('ascii')
            print("Actual Cert 0:   ", actual_cert0)
            print("Isolated Cert: ", isolated_cert)
            if actual_cert0 != isolated_cert:
                raise Exception("Unexpected certificate mismatch.")

            found_cert = False
            expected_cert = base64.b64encode(new_certificate).decode('ascii')
            for cert_der in get_result.value:
                actual_cert1 = base64.b64encode(cert_der[0]).decode('ascii')
                if actual_cert1 == expected_cert:
                    found_cert = True
            if not found_cert:
                raise Exception("Could not find new certificate!")

            # Now remove the certificate we just added.
            print("Remove the newly added certificate.")
            # [BEGIN remove_policy_management_certificate]
            remove_result = admin_client.remove_policy_management_certificate(
                new_certificate,
                AttestationSigningKey(self.isolated_key,
                                      self.isolated_certificate))

            if remove_result.value.certificate_resolution != CertificateModification.IS_ABSENT:
                raise Exception("Certificate was not removed!")
    def add_remove_policy_management_certificate(self):
        """
        Add and then remove a  policy management certificates for an Isolated
        mode attestation instance.

        """
        write_banner("add_remove_policy_management_certificate")
        print(
            "Get and set the policy management certificates for a isolated instance."
        )
        endpoint = os.environ.get("ATTESTATION_ISOLATED_URL")
        with AttestationAdministrationClient(
                endpoint, DefaultAzureCredential()) as admin_client:
            # [BEGIN add_policy_management_certificate]
            new_key = create_rsa_key()
            new_certificate = create_x509_certificate(new_key,
                                                      u"NewCertificateName")

            # Add the new certificate to the list. Specify a validation slack of
            # 1.0 to test passing in validation parameters to this method.
            add_result, _ = admin_client.add_policy_management_certificate(
                new_certificate,
                signing_key=self.isolated_key,
                signing_certificate=self.isolated_certificate,
                validation_slack=1.0,
            )
            if add_result.certificate_resolution != CertificateModification.IS_PRESENT:
                raise Exception("Certificate was not added!")

            # [END add_policy_management_certificate]

            certificates, _ = admin_client.get_policy_management_certificates()
            print("Isolated instance now has", len(certificates),
                  "certificates")

            for cert_pem in certificates:
                cert = load_pem_x509_certificate(cert_pem[0].encode("ascii"),
                                                 default_backend())
                print("certificate subject: ", cert.subject)

            # The signing certificate for the isolated instance should be
            # the configured isolated_signing_certificate.
            #
            # Note that the certificate list returned is an array of certificate chains.
            actual_cert0 = certificates[0][0]
            isolated_cert = self.isolated_certificate
            print("Actual Cert 0:   ", actual_cert0)
            print("Isolated Cert: ", isolated_cert)
            if actual_cert0 != isolated_cert:
                raise Exception("Unexpected certificate mismatch.")

            found_cert = False
            expected_cert = new_certificate
            for cert_pem in certificates:
                actual_cert1 = cert_pem[0]
                if actual_cert1 == expected_cert:
                    found_cert = True
            if not found_cert:
                raise Exception("Could not find new certificate!")

        # [BEGIN remove_policy_management_certificate]
        with AttestationAdministrationClient(
                endpoint, DefaultAzureCredential()) as admin_client:
            # Now remove the certificate we just added.
            print("Remove the newly added certificate.")
            remove_result, _ = admin_client.remove_policy_management_certificate(
                new_certificate,
                signing_key=self.isolated_key,
                signing_certificate=self.isolated_certificate,
            )

            if (remove_result.certificate_resolution !=
                    CertificateModification.IS_ABSENT):
                raise Exception("Certificate was not removed!")