Microsoft Azure Attestation Client Library for Python
Project description
Azure Attestation client library for Python
The Microsoft Azure Attestation (MAA) service is a unified solution for remotely verifying the trustworthiness of a platform and integrity of the binaries running inside it. The service supports attestation of the platforms backed by Trusted Platform Modules (TPMs) alongside the ability to attest to the state of Trusted Execution Environments (TEEs) such as Intel(tm) Software Guard Extensions (SGX) enclaves and Virtualization-based Security (VBS) enclaves.
Attestation is a process for demonstrating that software binaries were properly instantiated on a trusted platform. Remote relying parties can then gain confidence that only such intended software is running on trusted hardware. Azure Attestation is a unified customer-facing service and framework for attestation.
Azure Attestation enables cutting-edge security paradigms such as Azure Confidential computing and Intelligent Edge protection. Customers have been requesting the ability to independently verify the location of a machine, the posture of a virtual machine (VM) on that machine, and the environment within which enclaves are running on that VM. Azure Attestation will empower these and many additional customer requests.
Azure Attestation receives evidence from compute entities, turns them into a set of claims, validates them against configurable policies, and produces cryptographic proofs for claims-based applications (for example, relying parties and auditing authorities).
This package has been tested with Python 2.7, 3.6 to 3.9.
For a more complete view of Azure libraries, see the Azure SDK for Python release page.
Source code | Package (PyPI) | API reference documentation | Product documentation
Getting started
Prerequisites
- An Azure subscription. To use Azure services, including the Azure Attestation service, you'll need a subscription. If you do not have an existing Azure account, you may sign up for a free trial or use your Visual Studio Subscription benefits when you create an account.
- An existing Azure Attestation Instance, or you can use the "shared provider" available in each Azure region. If you need to create an Azure Attestation service instance, you can use the Azure Portal or Azure CLI.
Install the package
Install the Azure Attestation client library for Python with PyPI:
pip install azure-security-attestation
Authenticate the client
In order to interact with the Azure Attestation service, you'll need to create an instance of the Attestation Client or Attestation Administration Client class. You need an attestation endpoint, which you may see as "Attest URI" in the portal, and client credentials (client id, client secret, tenant id) to instantiate a client object.
Client secret credential authentication is being used in this getting started section but you can find more ways to authenticate with the Azure identity package. To use the DefaultAzureCredential provider shown below, or other credential providers provided with the Azure SDK, you should install the azure-identity package:
pip install azure-identity
Create/Get credentials
Use the Azure CLI snippet below to create/get client secret credentials.
-
Create a service principal and configure its access to Azure resources:
az ad sp create-for-rbac -n <your-application-name> --skip-assignment
Output:
{ "appId": "generated-app-ID", "displayName": "dummy-app-name", "name": "http://dummy-app-name", "password": "random-password", "tenant": "tenant-ID" }
-
Take note of the service principal objectId
az ad sp show --id <appId> --query objectId
Output:
"<your-service-principal-object-id>"
-
Use the returned credentials above to set AZURE_CLIENT_ID (appId), AZURE_CLIENT_SECRET (password), and AZURE_TENANT_ID (tenant) environment variables. The following example shows a way to do this in Powershell:
$Env:AZURE_CLIENT_ID="generated-app-ID" $Env:AZURE_CLIENT_SECRET="random-password" $Env:AZURE_TENANT_ID="tenant-ID"
For more information about the Azure Identity APIs and how to use them, see Azure Identity client library
Key concepts
There are four major families of functionality provided in this preview SDK:
- SGX and TPM enclave attestation.
- MAA Attestation Token signing certificate discovery and validation.
- Attestation Policy management.
- Attestation policy management certificate management (yes, policy management management).
The Microsoft Azure Attestation service runs in two separate modes: "Isolated" and "AAD". When the service is running in "Isolated" mode, the customer needs to provide additional information beyond their authentication credentials to verify that they are authorized to modify the state of an attestation instance.
Finally, each region in which the Azure Attestation service is available supports a "shared" instance, which can be used to attest SGX enclaves which only need verification against the azure baseline (there are no policies applied to the shared instance). TPM attestation is not available in the shared instance. While the shared instance requires AAD authentication, it does not have any RBAC policies - any customer with a valid AAD bearer token can attest using the shared instance.
Attestation
SGX or TPM attestation is the process of validating evidence collected from a trusted execution environment to ensure that it meets both the Azure baseline for that environment and customer defined policies applied to that environment.
Attestation service token signing certificate discovery and validation
One of the core operational guarantees of the Azure Attestation Service is that the service operates "operationally out of the TCB". In other words, there is no way that a Microsoft operator could tamper with the operation of the service, or corrupt data sent from the client. To ensure this guarantee, the core of the attestation service runs in an Intel(tm) SGX enclave.
To allow customers to verify that operations were actually performed inside the enclave, most responses from the Attestation Service are encoded in a JSON Web Token, which is signed by a key held within the attestation service's enclave.
This token will be signed by a signing certificate issued by the MAA service for the specified instance.
If the MAA service instance is running in a region where the service runs in an SGX enclave, then the certificate issued by the server can be verified using the oe_verify_attestation_certificate API.
Policy Management
Each attestation service instance has a policy applied to it which defines additional criteria which the customer has defined.
For more information on attestation policies, see Attestation Policy
Policy Management certificate management
When an attestation instance is running in "Isolated" mode, the customer who created the instance will have provided a policy management certificate at the time the instance is created. All policy modification operations require that the customer sign the policy data with one of the existing policy management certificates. The Policy Management Certificate Management APIs enable clients to "roll" the policy management certificates.
Isolated Mode and AAD Mode
Each Microsoft Azure Attestation service instance operates in either "AAD" mode or "Isolated" mode. When an MAA instance is operating in AAD mode, it means that the customer which created the attestation instance allows Azure Active Directory and Azure Role Based Access control policies to verify access to the attestation instance.
AttestationType
The Azure Attestation service supports attesting different types of evidence depending on the environment. Currently, MAA supports the following Trusted Execution environments:
- OpenEnclave - An Intel(tm) Processor running code in an SGX Enclave where the attestation evidence was collected using the OpenEnclave oe_get_report or oe_get_evidence API.
- SgxEnclave - An Intel(tm) Processor running code in an SGX Enclave where the attestation evidence was collected using the Intel SGX SDK.
- Tpm - A Virtualization Based Security environment where the Trusted Platform Module of the processor is used to provide the attestation evidence.
Runtime Data and Inittime Data
RuntimeData refers to data which is presented to the Intel SGX Quote generation logic or the oe_get_report
/oe_get_evidence
APIs. If the caller to the attest API provided a runtime_data
attribute, The Azure Attestation service will validate that the first 32 bytes of the report_data
field in the SGX Quote/OE Report/OE Evidence matches the SHA256 hash of the runtime_data
.
InitTime data refers to data which is used to configure the SGX enclave being attested.
Note that InitTime data is not supported on Azure DCsv2-Series virtual machines.
Additional concepts
Examples
- Create an attestation client instance
- Attest an SGX enclave
- Get attestation policy
- Retrieve token validation certificates
- Create an attestation client instance
Create client instance
Creates an instance of the Attestation Client at uri endpoint
.
attest_client = AttestationClient(
endpoint=base_uri,
credential=DefaultAzureCredential())
Get attestation policy
The set_policy
method retrieves the attestation policy from the service.
Attestation Policies are instanced on a per-attestation type basis, the AttestationType
parameter defines the type to retrieve.
policy, token = attest_client.get_policy(AttestationType.SGX_ENCLAVE)
print('Instance SGX policy: ', policy)
print('Token: ', token)
Set an attestation policy for a specified attestation type
If the attestation service instance is running in Isolated mode, the set_policy API needs to provide a signing certificate (and private key) which can be used to validate that the caller is authorized to modify policy on the attestation instance. If the service instance is running in AAD mode, then the signing certificate and key are optional.
Under the covers, the SetPolicy APIs create a JSON Web Token based on the policy document and signing information which is sent to the attestation service.
policy_set_response = attest_client.set_policy(AttestationType.SGX_ENCLAVE,
attestation_policy,
signing_key=key,
signing_certificate=signing_certificate)
new_policy, _ = attest_client.get_policy(AttestationType.SGX_ENCLAVE)
# `new_policy` will equal `attestation_policy`.
If the service instance is running in AAD mode, the call to set_policy can be simplified:
policy_set_response = attest_client.set_policy(AttestationType.SGX_ENCLAVE,
attestation_policy)
# Now retrieve the policy which was just set.
new_policy, _ = attest_client.get_policy(AttestationType.SGX_ENCLAVE)
Clients need to be able to verify that the attestation policy document was not modified before the policy document was received by the attestation service's enclave.
There are two properties provided in the PolicyResult that can be used to verify that the service received the policy document:
- policy_signer - if the
set_policy
call included a signing certificate, this will be the certificate provided at the time of theset_policy
call. If no policy signer was set, this will be null. - policy_token_hash - this is the hash of the JSON Web Token sent to the service.
To verify the hash, clients can generate an attestation policy token and verify the hash generated from that token:
from cryptography.hazmat.primitives import hashes
expected_policy = AttestationPolicyToken(
attestation_policy,
signing_key=key,
signing_certificate=signing_certificate)
hasher = hashes.Hash(hashes.SHA256())
hasher.update(expected_policy.serialize().encode('utf-8'))
expected_hash = hasher.finalize()
# `expected_hash` will exactly match `policy_set_response.policy_token_hash`
Attest SGX Enclave
Use the attest_sgx_enclave method to attest an SGX enclave.
One of the core challenges customers have interacting with encrypted environments is how to ensure that you can securely communicate with the code running in the environment ("enclave code").
One solution to this problem is what is known as "Secure Key Release", which is a pattern that enables secure communication with enclave code.
To implement the "Secure Key Release" pattern, the enclave code generates an ephemeral asymmetric key. It then serializes the public portion of the key to some format (possibly a JSON Web Key, or PEM, or some other serialization format).
The enclave code then calculates the SHA256 value of the public key and passes it as an input to code which generates an SGX Quote (for OpenEnclave, that would be the oe_get_evidence or oe_get_report).
The client then sends the SGX quote and the serialized key to the attestation service. The attestation service will validate the quote and ensure that the hash of the key is present in the quote and will issue an "Attestation Token".
The client can then send that Attestation Token (which contains the serialized key) to a 3rd party "relying party". The relying party then validates that the attestation token was created by the attestation service, and thus the serialized key can be used to encrypt some data held by the "relying party" to send to the service.
This example shows one common pattern of calling into the attestation service to retrieve an attestation token associated with a request.
This example assumes that you have an existing AttestationClient
object which is configured with the base URI for your endpoint. It also assumes that you have an SGX Quote (quote
) generated from within the SGX enclave you are attesting, and "Runtime Data" (runtime_data
) which is referenced in the SGX Quote.
response, token = attest_client.attest_sgx_enclave(quote, runtime_data=runtime_data)
At this point, the enclave_held_data attribute in the attestationResult will hold the input binary runtime_data.
The token is now passed to the "relying party". The relying party will validate that the token was issued by the Attestation Service. It then extracts the asymmetric key from the EnclaveHeldData field. The relying party will then Encrypt its "key" data using the asymmetric key and transmits it back to the enclave.
encrypted_data = send_token_to_relying_party(attestationResult.Token)
Now the encrypted data can be passed into the enclave which can decrypt that data.
Additional information on how to perform attestation token validation can be found in the MAA Service Attestation Sample.
Retrieve Token Certificates
Use get_signing_certificates
to retrieve the certificates which can be used to validate the token returned from the attestation service.
signers = attest_client.get_signing_certificates()
for signer in signers:
from cryptography.hazmat.backends import default_backend
cert = cryptography.x509.load_pem_x509_certificate(signer.certificates[0].encode('ascii'), backend=default_backend())
print('Cert iss:', cert.issuer, '; subject:', cert.subject)
Troubleshooting
Most Attestation service operations will raise exceptions defined in Azure Core. The attestation service APIs will throw a HttpResponseError
on failure with helpful error codes. Many of these errors are recoverable.
try:
response, _ = attest_client.attest_sgx_enclave(
quote,
runtime_data=AttestationData(runtime_data, is_json=False))
except HttpResponseError as ex:
# Ignore invalid quote errors.
if ex.error == "InvalidParameter":
pass
}
Additional troubleshooting information for the MAA service can be found here
Next steps
For more information about the Microsoft Azure Attestation service, please see our documentation page.
Contributing
This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit the Contributor License Agreement site.
When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.
This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.
See CONTRIBUTING.md for details on building, testing, and contributing to these libraries.
Provide Feedback
If you encounter any bugs or have suggestions, please file an issue in the Issues section of the project.
Release History
1.0.0 (2021-07-06)
Features Added
Sample cleanup - instead of using ClientSecretCredentials
, the samples now use
DefaultAzureCredential.
Breaking Changes
- TPM attestation takes a JSON string parameter and returns a JSON string parameter.
TPMAttestationRequest
andTPMAttestationResponse
type were removed.
confirmation
attribute removed fromAttestationResult
type.- The
AttestationSigningKey
type was removed, replaced with asigning_key
andsigning_certificate
kwargs parameter. - All certificates and keys accepted and returned by the SDK are now PEM encoded strings instead of DER encoded arrays of bytes for easier manipulation and interoperability.
- Removed
AttestationResponse
type, token value merged intoAttestationResult
,PolicyResult
, etc. - Removed
TokenValidationOptions
type and merged the validation options into keyword arguments on the APIs which validate returned tokens. Those keyword arguments can also be specified on the Client classes to simplify individual API invocations. - Renamed
instance_url
parameter to the constructors toendpoint
. - Many optional fields in
AttestationResult
were made non-optional. AttestationToken._validate_token
is made internal-only, and now returnsNone
.- The caller provided
validation_callback
now must throw exceptions on invalid tokens rather than returningFalse
.
- The caller provided
- Removed the
AttestationData
type, instead theattest_xxx
APIs take two sets of parameters:inittime_data
andinittime_json
andruntime_data
andruntime_json
. if the_json
value is set, the value of the parameter is an array of UTF8 encoded JSON values, if the_data
value is set, the value of the parameter is an array of bytes. - The
get_policy
API now returns aTuple[str, AttestationToken]
to simplify the consumption experience. - The
get_policy_management_certificates
API also returns aTuple[list[list[string]], AttestationToken]
to simplify the consumption experience. Note that each of the entries in the list is a PEM encoded X.509 certificate.
To call into the attest APIs if you care about the attestation policy and token, you can write:
policy, token = attest_client.get_policy(AttestationType.SGX_ENCLAVE)
If you only care about the policy, you can write any of the following:
policy, _ = attest_client.get_policy(AttestationType.SGX_ENCLAVE)
or
policy = attest_client.get_policy(AttestationType.SGX_ENCLAVE)[0]
or
response = attest_client.get_policy(AttestationType.SGX_ENCLAVE)
policy = response[0]
- The
AttestationToken
class no longer inherits fromGeneric
. - The
attest_sgx_enclave
, andattest_openenclave
APIs now return a tuple ofAttestationResult
,AttestationToken
, similar to theget_policy
API. - The
set_policy
,reset_policy
,add_policy_management_certificate
, andremove_policy_management_certificate
APIs all return a tuple. - The
AttestationToken.get_body()
API was renamedAttestationToken.body()
- Several time related properties were renamed to be consistent with the usage from
keyvault:
- The
expiration_time
property onAttestationToken
was renamed toexpires
. - The
issuance_time
property onAttestationToken
was renamed toissued_on
. - The
not_before_time
property onAttestationToken
was renamed tonot_before
.
- The
- The
StoredAttestationPolicy
model type has been removed. To validate the attestation policy hash, use theAttestationPolicyToken
model object instead. - The
get_openidmetadata
API has been renamedget_open_id_metadata
.
1.0.0b4 (2021-06-08)
Features Added
- Added reset_policy API.
- Added models.
- Documentation cleanup.
Breaking Changes
- Creating the
StoredAttestationPolicy
model type means that theattestation_policy
kwargs parameter for the constructor has been replaced with a positionalpolicy
parameter. As a result of this change, this code:
StoredAttestationPolicy(attestation_policy=str(attestation_policy).encode('utf-8')))
changes to:
StoredAttestationPolicy(attestation_policy)
-
Several parameters for the
AttestationResult
type have been renamed, and several parameters which were shared withAttestationToken
have been removed. In general, the naming changes removed some protocol specific elements and replaced them with friendlier names. Finally, the deprecated attributes have been removed from theAttestationResult
Full set of changes:
iss
renamed toissuer
cnf
renamed toconfirmation
jti
renamed tounique_identifier
iat
removedexp
removednbf
removeddeprecated_version
removeddeprecated_is_debuggable
removeddeprecated_sgx_collateral
removeddeprecated_enclave_held_data
removeddeprecated_enclave_held_data2
removeddeprecated_product_id
removeddeprecated_mr_enclave
removeddeprecated_mr_signer
removeddeprecated_svn
removeddeprecated_tee
removeddeprecated_policy_signer
removeddeprecated_policy_hash
removeddeprecated_rp_data
removed
If customers need to access the removed or renamed fields directly, they can use the
get_body
method of theAttestationResponse
object:if response.token.get_body().deprecated_tee != 'sgx': print("Unexpected tee claim in token")
1.0.0b2 (2021-05-11)
Features Added
- Preliminary implementation of a Track 2 SDK for the attestation service.
Breaking Changes
- Complete reimplementation of the API surface, follows the API patterns already established for the attestation service.
1.0.0b1 (2021-01-15)
Initial early preview release for MAA Data Plane SDK Demonstrates use of the machine generated MAA APIs.
- Initial Release
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for azure-security-attestation-1.0.0.zip
Algorithm | Hash digest | |
---|---|---|
SHA256 | 0bf814db4225d418b3332f2226537142849c0a45a638a5da380fd3f7c241a2da |
|
MD5 | 1b4ff2db263229eee2d8314edcf21b10 |
|
BLAKE2b-256 | c1309c728aff4e671de3bce4a56e0ba6c1b53da6a7df83970ee01bab3100ea76 |
Hashes for azure_security_attestation-1.0.0-py2.py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 9a1042cdc2f3fc20a2e006f3541b3b32666c284fb2427ddb900cf8e0e786dd3f |
|
MD5 | cb5b03bbbbff3da875f7af4e95949639 |
|
BLAKE2b-256 | 0fa2b64f1876588883169a591b9b1038473eb06cfbe29d3e7ebd29cb98f80521 |