예제 #1
0
        /// <summary>
        /// Removes one of the attestation policy management certificates.
        /// </summary>
        /// <param name="certificateToRemove">The certificate to remove.</param>
        /// <param name="existingSigningKey">An existing key corresponding to the existing certificate.</param>
        /// <param name="cancellationToken">Cancellation token used to cancel this operation.</param>
        /// <returns>An <see cref="AttestationResponse{PolicyCertificatesModificationResult}"/> with the policy for the specified attestation type.</returns>
        public virtual async Task <AttestationResponse <PolicyCertificatesModificationResult> > RemovePolicyManagementCertificateAsync(
            X509Certificate2 certificateToRemove,
            AttestationTokenSigningKey existingSigningKey,
            CancellationToken cancellationToken = default)
        {
            using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(AttestationAdministrationClient)}.{nameof(RemovePolicyManagementCertificate)}");
            scope.Start();
            try
            {
                var tokenToRemove = new AttestationToken(
                    BinaryData.FromObjectAsJson(new PolicyCertificateModification(certificateToRemove)),
                    existingSigningKey);

                var result = await _policyManagementClient.RemoveAsync(tokenToRemove.Serialize(), cancellationToken).ConfigureAwait(false);

                var token = AttestationToken.Deserialize(result.Value.Token, _clientDiagnostics);
                if (_options.TokenOptions.ValidateToken)
                {
                    var signers = await GetSignersAsync(true, cancellationToken).ConfigureAwait(false);

                    if (!await token.ValidateTokenAsync(_options.TokenOptions, signers, cancellationToken).ConfigureAwait(false))
                    {
                        AttestationTokenValidationFailedException.ThrowFailure(signers, token);
                    }
                }
                return(new AttestationResponse <PolicyCertificatesModificationResult>(result.GetRawResponse(), token));
            }
            catch (Exception ex)
            {
                scope.Failed(ex);
                throw;
            }
        }
예제 #2
0
        /// <summary>
        /// Adds the specified new signing certificate to the set of policy management certificates.
        /// </summary>
        /// <param name="newSigningCertificate">The new certificate to add.</param>
        /// <param name="existingSigningKey">An existing key corresponding to the existing certificate.</param>
        /// <param name="cancellationToken">Cancellation token used to cancel this operation.</param>
        /// <returns>An <see cref="AttestationResponse{PolicyCertificatesModificationResult}"/> with the policy for the specified attestation type.</returns>
        /// <remarks>
        /// </remarks>
        public virtual AttestationResponse <PolicyCertificatesModificationResult> AddPolicyManagementCertificate(
            X509Certificate2 newSigningCertificate,
            AttestationTokenSigningKey existingSigningKey,
            CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(existingSigningKey, nameof(existingSigningKey));
            Argument.AssertNotNull(newSigningCertificate, nameof(newSigningCertificate));

            using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(AttestationAdministrationClient)}.{nameof(AddPolicyManagementCertificate)}");
            scope.Start();
            try
            {
                var tokenToAdd = new AttestationToken(
                    BinaryData.FromObjectAsJson(new PolicyCertificateModification(newSigningCertificate)),
                    existingSigningKey);
                var result = _policyManagementClient.Add(tokenToAdd.Serialize(), cancellationToken);
                var token  = AttestationToken.Deserialize(result.Value.Token, _clientDiagnostics);
                if (_options.TokenOptions.ValidateToken)
                {
                    var signers = GetSignersAsync(false, cancellationToken).EnsureCompleted();
                    if (!token.ValidateTokenInternal(_options.TokenOptions, signers, false, cancellationToken).EnsureCompleted())
                    {
                        AttestationTokenValidationFailedException.ThrowFailure(signers, token);
                    }
                }
                return(new AttestationResponse <PolicyCertificatesModificationResult>(result.GetRawResponse(), token));
            }
            catch (Exception ex)
            {
                scope.Failed(ex);
                throw;
            }
        }
예제 #3
0
        /// <summary>
        /// Resets the policy for the specified <see cref="AttestationType"/> to the default value.
        /// </summary>
        /// <param name="attestationType"><see cref="AttestationType"/> whose policy should be reset.</param>
        /// <param name="signingKey">If provided, specifies the signing key used to sign the request to the attestation service.</param>
        /// <param name="cancellationToken">Cancellation token used to cancel this operation.</param>
        /// <returns>An <see cref="AttestationResponse{PolicyResult}"/> with the policy for the specified attestation type.</returns>
        /// <remarks>
        /// If the <paramref name="signingKey"/> parameter is not provided, then the policy document sent to the
        /// attestation service will be unsigned. Unsigned attestation policies are only allowed when the attestation instance is running in AAD mode - if the
        /// attestation instance is running in Isolated mode, then a signing key and signing certificate MUST be provided to ensure that the caller of the API is authorized to change policy.
        /// The <see cref="AttestationTokenSigningKey.Certificate"/> parameter MUST be one of the certificates returned by the <see cref="GetPolicyManagementCertificates(CancellationToken)"/> API.
        /// <para/>
        /// </remarks>
        public virtual async Task <AttestationResponse <PolicyModificationResult> > ResetPolicyAsync(
            AttestationType attestationType,
            AttestationTokenSigningKey signingKey = default,
            CancellationToken cancellationToken   = default)
        {
            using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(AttestationAdministrationClient)}.{nameof(ResetPolicy)}");
            scope.Start();
            try
            {
                AttestationToken tokenToSet = new AttestationToken(null, signingKey);

                var result = await _policyClient.ResetAsync(attestationType, tokenToSet.Serialize(), cancellationToken).ConfigureAwait(false);

                var token = AttestationToken.Deserialize(result.Value.Token, _clientDiagnostics);
                if (_options.TokenOptions.ValidateToken)
                {
                    var signers = await GetSignersAsync(true, cancellationToken).ConfigureAwait(false);

                    if (!await token.ValidateTokenAsync(_options.TokenOptions, signers, cancellationToken).ConfigureAwait(false))
                    {
                        AttestationTokenValidationFailedException.ThrowFailure(signers, token);
                    }
                }
                return(new AttestationResponse <PolicyModificationResult>(result.GetRawResponse(), token));
            }
            catch (Exception ex)
            {
                scope.Failed(ex);
                throw;
            }
        }
예제 #4
0
        /// <summary>
        /// Sets the attesttion policy for the specified <see cref="AttestationType"/>.
        /// </summary>
        /// <param name="attestationType"><see cref="AttestationType"/> whose policy should be set.</param>
        /// <param name="policyToSet">Specifies the attestation policy to set.</param>
        /// <param name="signingKey">If provided, specifies the signing key used to sign the request to the attestation service.</param>
        /// <param name="cancellationToken">Cancellation token used to cancel this operation.</param>
        /// <returns>An <see cref="AttestationResponse{PolicyResult}"/> with the policy for the specified attestation type.</returns>
        /// <remarks>
        /// If the <paramref name="signingKey"/> parameter is not provided, then the policy document sent to the
        /// attestation service will be unsigned. Unsigned attestation policies are only allowed when the attestation instance is running in AAD mode - if the
        /// attestation instance is running in Isolated mode, then a signing key and signing certificate MUST be provided to ensure that the caller of the API is authorized to change policy.
        /// The <see cref="AttestationTokenSigningKey.Certificate"/> field MUST be one of the certificates returned by the <see cref="GetPolicyManagementCertificates(CancellationToken)"/> API.
        /// <para/>
        /// 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][attestation_policy_result] that can be used to verify that the service received the policy document:
        /// <list type="bullet">
        /// <item>
        /// <description><see cref="PolicyModificationResult.PolicySigner"/> - if the <see cref="SetPolicy(AttestationType, string, AttestationTokenSigningKey, CancellationToken)"/> call included a signing certificate, this will be the certificate provided at the time of the `SetPolicy` call. If no policy signer was set, this will be null. </description>
        /// </item>
        /// <item>
        /// <description><see cref="PolicyModificationResult.PolicyTokenHash"/> - this is the hash of the [JSON Web Token][json_web_token] sent to the service</description>
        /// </item>
        /// </list>
        /// To verify the hash, clients can generate an attestation token and verify the hash generated from that token:
        /// <code snippet="Snippet:VerifySigningHash">
        /// // The SetPolicyAsync API will create an AttestationToken signed with the TokenSigningKey to transmit the policy.
        /// // To verify that the policy specified by the caller was received by the service inside the enclave, we
        /// // verify that the hash of the policy document returned from the Attestation Service matches the hash
        /// // of an attestation token created locally.
        /// TokenSigningKey signingKey = new TokenSigningKey(&lt;Customer provided signing key&gt;, &lt;Customer provided certificate&gt;)
        /// var policySetToken = new AttestationToken(
        ///     BinaryData.FromObjectAsJson(new StoredAttestationPolicy { AttestationPolicy = attestationPolicy }),
        ///     signingKey);
        ///
        /// using var shaHasher = SHA256Managed.Create();
        /// byte[] attestationPolicyHash = shaHasher.ComputeHash(Encoding.UTF8.GetBytes(policySetToken.Serialize()));
        ///
        /// Debug.Assert(attestationPolicyHash.SequenceEqual(setResult.Value.PolicyTokenHash.ToArray()));
        /// </code>
        ///
        /// If the signing key and certificate are not provided, then the SetPolicyAsync API will create an unsecured attestation token
        /// wrapping the attestation policy. To validate the <see cref="PolicyModificationResult.PolicyTokenHash"/> return value, a developer
        /// can create their own <see cref="AttestationToken"/> and create the hash of that.
        /// <code>
        /// using var shaHasher = SHA256Managed.Create();
        /// var policySetToken = new UnsecuredAttestationToken(new StoredAttestationPolicy { AttestationPolicy = disallowDebugging });
        /// disallowDebuggingHash = shaHasher.ComputeHash(Encoding.UTF8.GetBytes(policySetToken.Serialize()));
        /// </code>
        /// </remarks>
        public virtual AttestationResponse <PolicyModificationResult> SetPolicy(
            AttestationType attestationType,
            string policyToSet,
            AttestationTokenSigningKey signingKey = default,
            CancellationToken cancellationToken   = default)
        {
            Argument.AssertNotNullOrWhiteSpace(policyToSet, nameof(policyToSet));

            using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(AttestationAdministrationClient)}.{nameof(SetPolicy)}");
            scope.Start();
            try
            {
                AttestationToken tokenToSet = new AttestationToken(
                    BinaryData.FromObjectAsJson(new StoredAttestationPolicy {
                    AttestationPolicy = policyToSet,
                }),
                    signingKey);
                var result = _policyClient.Set(attestationType, tokenToSet.Serialize(), cancellationToken);
                var token  = AttestationToken.Deserialize(result.Value.Token);
                if (_options.TokenOptions.ValidateToken)
                {
                    var signers = GetSignersAsync(false, cancellationToken).EnsureCompleted();
                    if (!token.ValidateToken(_options.TokenOptions, signers, cancellationToken))
                    {
                        AttestationTokenValidationFailedException.ThrowFailure(signers, token);
                    }
                }
                return(new AttestationResponse <PolicyModificationResult>(result.GetRawResponse(), token));
            }
            catch (Exception ex)
            {
                scope.Failed(ex);
                throw;
            }
        }
예제 #5
0
        /// <summary>
        /// Sets the attesttion policy for the specified <see cref="AttestationType"/>.
        /// </summary>
        /// <param name="attestationType"><see cref="AttestationType"/> whose policy should be set.</param>
        /// <param name="policyToSet">Specifies the attestation policy to set.</param>
        /// <param name="signingKey">If provided, specifies the signing key used to sign the request to the attestation service.</param>
        /// <param name="cancellationToken">Cancellation token used to cancel this operation.</param>
        /// <returns>An <see cref="AttestationResponse{PolicyResult}"/> with the policy for the specified attestation type.</returns>
        /// <remarks>
        /// If the <paramref name="signingKey"/> parameter is not provided, then the policy document sent to the
        /// attestation service will be unsigned. Unsigned attestation policies are only allowed when the attestation instance is running in AAD mode - if the
        /// attestation instance is running in Isolated mode, then a signing key and signing certificate MUST be provided to ensure that the caller of the API is authorized to change policy.
        /// The <see cref="AttestationTokenSigningKey.Certificate"/> field MUST be one of the certificates returned by the <see cref="GetPolicyManagementCertificates(CancellationToken)"/> API.
        /// <para/>
        /// 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][attestation_policy_result] that can be used to verify that the service received the policy document:
        /// <list type="bullet">
        /// <item>
        /// <description><see cref="PolicyModificationResult.PolicySigner"/> - if the <see cref="SetPolicy(AttestationType, string, AttestationTokenSigningKey, CancellationToken)"/> call included a signing certificate, this will be the certificate provided at the time of the `SetPolicy` call. If no policy signer was set, this will be null. </description>
        /// </item>
        /// <item>
        /// <description><see cref="PolicyModificationResult.PolicyTokenHash"/> - this is the hash of the [JSON Web Token][json_web_token] sent to the service</description>
        /// </item>
        /// </list>
        /// To verify the hash, clients can generate an attestation token and verify the hash generated from that token:
        /// <code snippet="Snippet:VerifySigningHash">
        /// // The SetPolicyAsync API will create an AttestationToken signed with the TokenSigningKey to transmit the policy.
        /// // To verify that the policy specified by the caller was received by the service inside the enclave, we
        /// // verify that the hash of the policy document returned from the Attestation Service matches the hash
        /// // of an attestation token created locally.
        /// TokenSigningKey signingKey = new TokenSigningKey(&lt;Customer provided signing key&gt;, &lt;Customer provided certificate&gt;)
        /// var policySetToken = new AttestationToken(
        ///     BinaryData.FromObjectAsJson(new StoredAttestationPolicy { AttestationPolicy = attestationPolicy }),
        ///     signingKey);
        ///
        /// using var shaHasher = SHA256Managed.Create();
        /// byte[] attestationPolicyHash = shaHasher.ComputeHash(Encoding.UTF8.GetBytes(policySetToken.Serialize()));
        ///
        /// Debug.Assert(attestationPolicyHash.SequenceEqual(setResult.Value.PolicyTokenHash.ToArray()));
        /// </code>
        ///
        /// If the signing key and certificate are not provided, then the SetPolicyAsync API will create an unsecured attestation token
        /// wrapping the attestation policy. To validate the <see cref="PolicyModificationResult.PolicyTokenHash"/> return value, a developer
        /// can create their own <see cref="AttestationToken"/> and create the hash of that.
        /// <code>
        /// using var shaHasher = SHA256Managed.Create();
        /// var policySetToken = new AttestationToken(new StoredAttestationPolicy { AttestationPolicy = disallowDebugging });
        /// disallowDebuggingHash = shaHasher.ComputeHash(Encoding.UTF8.GetBytes(policySetToken.ToString()));
        /// </code>
        /// </remarks>
        public virtual async Task <AttestationResponse <PolicyModificationResult> > SetPolicyAsync(
            AttestationType attestationType,
            string policyToSet,
            AttestationTokenSigningKey signingKey = default,
            CancellationToken cancellationToken   = default)
        {
            if (string.IsNullOrEmpty(policyToSet))
            {
                throw new ArgumentException($"'{nameof(policyToSet)}' cannot be null or empty.", nameof(policyToSet));
            }

            using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(AttestationAdministrationClient)}.{nameof(SetPolicy)}");
            scope.Start();
            try
            {
                AttestationToken tokenToSet = new AttestationToken(BinaryData.FromObjectAsJson(new StoredAttestationPolicy {
                    AttestationPolicy = policyToSet,
                }), signingKey);

                var result = await _policyClient.SetAsync(attestationType, tokenToSet.Serialize(), cancellationToken).ConfigureAwait(false);

                var token = AttestationToken.Deserialize(result.Value.Token, _clientDiagnostics);
                if (_options.TokenOptions.ValidateToken)
                {
                    var signers = await GetSignersAsync(true, cancellationToken).ConfigureAwait(false);

                    if (!await token.ValidateTokenAsync(_options.TokenOptions, signers, cancellationToken).ConfigureAwait(false))
                    {
                        AttestationTokenValidationFailedException.ThrowFailure(signers, token);
                    }
                }
                return(new AttestationResponse <PolicyModificationResult>(result.GetRawResponse(), token));
            }
            catch (Exception ex)
            {
                scope.Failed(ex);
                throw;
            }
        }
 /// <summary>
 /// Creates a new unsecured attestation token with an empty body. Used for the <see cref="AttestationAdministrationClient.ResetPolicy(AttestationType, AttestationTokenSigningKey, System.Threading.CancellationToken)"/> API.
 /// </summary>
 /// <param name="signingKey"><see cref="AttestationTokenSigningKey"/> which will be used to sign the generated token.</param>
 public AttestationToken(AttestationTokenSigningKey signingKey)
 {
     _token = signingKey != null?GenerateSecuredJsonWebToken(null, signingKey) : CreateUnsecuredJwt(null);
 }
        /// <summary>
        /// Creates a new attestation token based on the supplied body signed with the specified signing key.
        /// </summary>
        /// <param name="body">The body of the generated token, serialized as a byte array.</param>
        /// <param name="signingKey"><see cref="AttestationTokenSigningKey"/> which will be used to sign the generated token.</param>
        public AttestationToken(BinaryData body, AttestationTokenSigningKey signingKey)
        {
            _token = signingKey != null?GenerateSecuredJsonWebToken(body, signingKey) : CreateUnsecuredJwt(body);

            ConstructFromToken(_token);
        }