Esempio n. 1
0
    async def attest_open_enclave_with_draft_policy(self):
        """
        Calls attest_open_enclave specifying a draft attestation policy.

        This functionality can be used to test attestation policies against real attestation
        collateral. This can be extremely helpful in debugging attestation policies.
        """
        write_banner("attest_open_enclave_with_draft_policy")
        oe_report = base64.urlsafe_b64decode(sample_open_enclave_report)
        runtime_data = base64.urlsafe_b64decode(sample_runtime_data)

        # [START attest_open_enclave_shared_draft]
        draft_policy = """
        version= 1.0;
        authorizationrules
        {
            [ type=="x-ms-sgx-is-debuggable", value==false ] &&
            [ type=="x-ms-sgx-product-id", value==1 ] &&
            [ type=="x-ms-sgx-svn", value>= 0 ] &&
            [ type=="x-ms-sgx-mrsigner", value=="2c1a44952ae8207135c6c29b75b8c029372ee94b677e15c20bd42340f10d41aa"]
                => permit();
        };
        issuancerules {
            c:[type=="x-ms-sgx-mrsigner"] => issue(type="My-MrSigner", value=c.value);
        };
        """
        print("Attest Open enclave using ", self.shared_url)
        print("Using draft policy:", draft_policy)
        async with DefaultAzureCredential() as credential, AttestationClient(
                self.shared_url, credential) as attest_client:
            response, token = await attest_client.attest_open_enclave(
                oe_report,
                runtime_data=runtime_data,
                draft_policy=draft_policy)

            print("Token algorithm", token.algorithm)
            print("Issuer of token is: ", response.issuer)
    def set_policy_isolated_secured(self):
        """
        Set a secured attestation policy on an Isolated mode instance.

        For an isolated attestation instance, the new attestation policy must
        be signed with one of the existing policy management certificates.

        """
        write_banner("set_policy_isolated_secured")
        print("Set Secured Policy on an AAD mode attestation instance.")
        with self._create_admin_client(self.isolated_url) as admin_client:
            set_result = admin_client.set_policy(
                AttestationType.SGX_ENCLAVE,
                """version= 1.0;authorizationrules{=> permit();};issuancerules {};""",
                signing_key=AttestationSigningKey(self.isolated_key,
                                                  self.isolated_certificate))
            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(self.isolated_certificate).decode('ascii'))

            print(
                "Reset the attestation policy to the default now to avoid side effects."
            )
            # Reset the policy now that we're done.
            admin_client.reset_policy(AttestationType.SGX_ENCLAVE,
                                      signing_key=AttestationSigningKey(
                                          self.isolated_key,
                                          self.isolated_certificate))
Esempio n. 3
0
    def attest_open_enclave_with_draft_failing_policy(self):
        """
        Set a policy which is guaranteed to fail attestation to show
        how to manage attestation failures.
        """
        write_banner("attest_open_enclave_with_draft_failing_policy")
        oe_report = base64.urlsafe_b64decode(sample_open_enclave_report)
        runtime_data = base64.urlsafe_b64decode(sample_runtime_data)

        draft_policy="""
version= 1.0;
authorizationrules
{
    [ type=="x-ms-sgx-is-debuggable", value == false] => deny();
    [ type=="x-ms-sgx-product-id", value==1 ] &&
    [ type=="x-ms-sgx-svn", value>= 0 ] &&
    [ type=="x-ms-sgx-mrsigner", value=="2c1a44952ae8207135c6c29b75b8c029372ee94b677e15c20bd42340f10d41aa"]
        => permit();
};
issuancerules {
    c:[type=="x-ms-sgx-mrsigner"] => issue(type="My-MrSigner", value=c.value);
};
"""

        print('Attest Open enclave using ', self.shared_url)
        print('Using draft policy which will fail.:', draft_policy)
        with self._create_client(self.shared_url) as attest_client:
            try:
                attest_client.attest_open_enclave(
                    oe_report, runtime_data=AttestationData(runtime_data, is_json=False),
                    draft_policy=draft_policy)
                print("Unexpectedly passed attestation.")
            except HttpResponseError as err:
                print("Caught expected exception: ", err.message)
                print("Error is:", err.error.code)
                pass
    def set_policy_isolated_secured(self):
        """
        Set a secured attestation policy on an Isolated mode instance.

        This sample sets the signing key on the admin client object directly, rather
        than providing the signing key to individual APIs.

        For an isolated attestation instance, the new attestation policy must
        be signed with one of the existing policy management certificates.

        """
        write_banner("set_policy_isolated_secured")
        print("Set Secured Policy on an AAD mode attestation instance.")
        endpoint = os.environ.get("ATTESTATION_ISOLATED_URL")
        with AttestationAdministrationClient(
                endpoint,
                DefaultAzureCredential(),
                signing_key=self.isolated_key,
                signing_certificate=self.isolated_certificate,
        ) as admin_client:
            set_result, _ = admin_client.set_policy(
                AttestationType.SGX_ENCLAVE,
                """version= 1.0;authorizationrules{=> permit();};issuancerules {};""",
                validation_slack=1.0,
            )
            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:   ", self.isolated_certificate)

            print(
                "Reset the attestation policy to the default now to avoid side effects."
            )
            # Reset the policy now that we're done.
            admin_client.reset_policy(AttestationType.SGX_ENCLAVE)
Esempio n. 5
0
    def attest_open_enclave_shared_with_options(self):
        """
        Demonstrates calling into the attest_open_enclave API using an attestation
        token validation callback to perform validation of the attestation collateral
        received from the server.
        """
        write_banner("attest_open_enclave_shared_with_options")

        oe_report = base64.urlsafe_b64decode(sample_open_enclave_report)
        runtime_data = base64.urlsafe_b64decode(sample_runtime_data)
        print()
        print("Attest Open enclave using ", self.shared_url)

        # [START attest_open_enclave_shared_with_options]
        def validate_token(token, signer):
            # type: (AttestationToken, AttestationSigner) -> bool
            """
            Perform minimal validation of the issued SGX token.
            The token validation logic will have checked the issuance_time
            and expiration_time, but this shows accessing those fields.

            The validation logic also checks the subject of the certificate to verify
            that the issuer of the certificate is the expected instance of the service.
            """
            print("In validation callback, checking token...")
            print("     Token issuer: ", token.issuer)
            print("     Token was issued at: ", token.issued)
            print("     Token expires at: ", token.expires)
            if token.issuer != self.shared_url:
                print(
                    "Token issuer {} does not match expected issuer {}".format(
                        token.issuer, self.shared_url))
                return False

            # Check the subject of the signing certificate used to validate the token.
            certificate = cryptography.x509.load_pem_x509_certificate(
                signer.certificates[0].encode("ascii"),
                backend=default_backend())
            if certificate.subject.rfc4514_string() != "CN=" + self.shared_url:
                print(
                    "Certificate subject {} does not match expected subject {}"
                    .format(certificate.subject, self.shared_url))
                return False

            print("Token passes validation checks.")
            return True

        with AttestationClient(
                self.shared_url,
                DefaultAzureCredential(),
                validation_callback=validate_token,
        ) as attest_client:
            response, token = attest_client.attest_open_enclave(
                oe_report, runtime_data=runtime_data)

            print("Issuer of token is: ", response.issuer)
            print("Expiration time: ", token.expires)

        # Repeat the same operation, this time specifying the callback options
        # on the attest_open_enclave call.
        with AttestationClient(self.shared_url,
                               DefaultAzureCredential()) as attest_client:
            response, token = attest_client.attest_open_enclave(
                oe_report,
                runtime_data=runtime_data,
                validation_callback=validate_token)

            print("Issuer of token is: ", response.issuer)
            print("Expiration time: ", token.expires)
    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!")