public void ValidateTokenCallback()
        {
            // Create a JWT whose body will become valid 5 seconds from now.
            object tokenBody = new JwtTestBody
            {
                StringField = "Foo",
                NotBefore   = DateTimeOffset.Now.AddSeconds(5).ToUnixTimeSeconds(),
                ExpiresAt   = DateTimeOffset.Now.AddSeconds(60).ToUnixTimeSeconds(),
            };

            X509Certificate2    fullCertificate = TestEnvironment.PolicyManagementCertificate;
            AsymmetricAlgorithm privateKey      = TestEnvironment.PolicyManagementKey;

            var    token           = new AttestationToken(BinaryData.FromObjectAsJson(tokenBody), new AttestationTokenSigningKey(privateKey, fullCertificate));
            string serializedToken = token.Serialize();

            var validationOptions = new AttestationTokenValidationOptions();

            validationOptions.TokenValidated += (args) =>
            {
                Assert.AreEqual(1, args.Signer.SigningCertificates.Count);
                Assert.IsNotNull(args.Signer.SigningCertificates[0]);
                CollectionAssert.AreEqual(fullCertificate.Export(X509ContentType.Cert), args.Signer.SigningCertificates[0].Export(X509ContentType.Cert));
                Assert.AreEqual(fullCertificate, args.Signer.SigningCertificates[0]);
                return(Task.CompletedTask);
            };

            // ValidateTokenAsync will throw an exception if a callback is specified outside of an attestation client.
            // Note that validation callbacks are tested elsewhere in the AttestationClient codebase.
            Assert.ThrowsAsync(typeof(Exception), async() => await ValidateSerializedToken(
                                   serializedToken,
                                   tokenBody,
                                   validationOptions));
        }
Пример #2
0
        public async Task SetPolicySecured(AttestationAdministrationClient adminClient, bool isIsolated)
        {
            // Reset the current attestation policy to a known state. Necessary if there were previous runs that failed.
            await ResetAttestationPolicy(adminClient, AttestationType.OpenEnclave, true, isIsolated);

            string originalPolicy = await adminClient.GetPolicyAsync(AttestationType.OpenEnclave);

            X509Certificate2 x509Certificate;
            RSA rsaKey;

            if (isIsolated)
            {
                x509Certificate = TestEnvironment.PolicyManagementCertificate;

                rsaKey = TestEnvironment.PolicyManagementKey;
            }
            else
            {
                x509Certificate = TestEnvironment.PolicyCertificate0;

                rsaKey = TestEnvironment.PolicySigningKey0;
            }

            byte[] disallowDebuggingHash;
            {
                var policySetResult = await adminClient.SetPolicyAsync(AttestationType.OpenEnclave, disallowDebugging, new AttestationTokenSigningKey(rsaKey, x509Certificate));

                var shaHasher = SHA256.Create();

                var policySetToken = new AttestationToken(
                    BinaryData.FromObjectAsJson(new StoredAttestationPolicy {
                    AttestationPolicy = disallowDebugging
                }), new AttestationTokenSigningKey(rsaKey, x509Certificate));
                disallowDebuggingHash = shaHasher.ComputeHash(Encoding.UTF8.GetBytes(policySetToken.Serialize()));

                Assert.AreEqual(200, policySetResult.GetRawResponse().Status);
                Assert.AreEqual(PolicyModification.Updated, policySetResult.Value.PolicyResolution);
                CollectionAssert.AreEqual(disallowDebuggingHash, policySetResult.Value.PolicyTokenHash.ToArray());
                Assert.AreEqual(x509Certificate, policySetResult.Value.PolicySigner.SigningCertificates[0]);
            }

            {
                var policyResult = await adminClient.GetPolicyAsync(AttestationType.OpenEnclave);

                Assert.AreEqual(disallowDebugging, policyResult.Value);
            }
            {
                var policySetResult = await adminClient.ResetPolicyAsync(AttestationType.OpenEnclave, new AttestationTokenSigningKey(rsaKey, x509Certificate));

                Assert.AreEqual(200, policySetResult.GetRawResponse().Status);
                Assert.AreEqual(PolicyModification.Removed, policySetResult.Value.PolicyResolution);
            }

            {
                var policyResult = await adminClient.GetPolicyAsync(AttestationType.OpenEnclave);

                // And when we're done, policy should be reset to the original value.
                Assert.AreEqual(originalPolicy, policyResult.Value);
            }
        }
        public async Task GetUnsecuredAttestationToken()
        {
            object tokenBody = new StoredAttestationPolicy {
                AttestationPolicy = "Foo",
            };

            var    token           = new AttestationToken(BinaryData.FromObjectAsJson(tokenBody));
            string serializedToken = token.Serialize();

            await ValidateSerializedToken(serializedToken, tokenBody);
        }
        public async Task GetSecuredAttestationToken()
        {
            X509Certificate2    fullCertificate = TestEnvironment.PolicyManagementCertificate;
            AsymmetricAlgorithm privateKey      = TestEnvironment.PolicyManagementKey;

            object tokenBody = new StoredAttestationPolicy {
                AttestationPolicy = "Foo",
            };

            var    token           = new AttestationToken(BinaryData.FromObjectAsJson(tokenBody), new AttestationTokenSigningKey(privateKey, fullCertificate));
            string serializedToken = token.Serialize();

            await ValidateSerializedToken(serializedToken, tokenBody);
        }
Пример #5
0
        public async Task SetPolicyUnsecuredAad()
        {
            var adminclient = TestEnvironment.GetAadAdministrationClient(this);

            // Reset the current attestation policy to a known state. Necessary if there were previous runs that failed.
            await ResetAttestationPolicy(adminclient, AttestationType.OpenEnclave, false, false);

            string originalPolicy;

            {
                originalPolicy = await adminclient.GetPolicyAsync(AttestationType.OpenEnclave);
            }

            byte[] disallowDebuggingHash;
            {
                var policySetResult = await adminclient.SetPolicyAsync(AttestationType.OpenEnclave, disallowDebugging);

                // The SetPolicyAsync API will create an UnsecuredAttestationToken to transmit the policy.
                var shaHasher      = SHA256.Create();
                var policySetToken = new AttestationToken(BinaryData.FromObjectAsJson(new StoredAttestationPolicy {
                    AttestationPolicy = disallowDebugging
                }));

                disallowDebuggingHash = shaHasher.ComputeHash(Encoding.UTF8.GetBytes(policySetToken.Serialize()));

                Assert.AreEqual(200, policySetResult.GetRawResponse().Status);
                Assert.AreEqual(PolicyModification.Updated, policySetResult.Value.PolicyResolution);
                CollectionAssert.AreEqual(disallowDebuggingHash, policySetResult.Value.PolicyTokenHash.ToArray());
            }

            {
                string policyResult = await adminclient.GetPolicyAsync(AttestationType.OpenEnclave);

                Assert.AreEqual(disallowDebugging, policyResult);
            }
            {
                var policySetResult = await adminclient.ResetPolicyAsync(AttestationType.OpenEnclave);

                Assert.AreEqual(200, policySetResult.GetRawResponse().Status);
                Assert.AreEqual(PolicyModification.Removed, policySetResult.Value.PolicyResolution);
            }

            {
                var policyResult = await adminclient.GetPolicyAsync(AttestationType.OpenEnclave);

                // And when we're done, policy should be reset to the original value.
                Assert.AreEqual(originalPolicy, policyResult.Value);
            }
        }
        public async Task GetSecuredAttestationTokenWithPrivateKey()
        {
            X509Certificate2 fullCertificate = TestEnvironment.PolicyManagementCertificate;

            fullCertificate.PrivateKey = TestEnvironment.PolicyManagementKey;

            // The body of attestation token MUST be a JSON object.
            TestBody body = new TestBody {
                StringField = "Foo",
            };

            var    token           = new AttestationToken(BinaryData.FromObjectAsJson(body), new AttestationTokenSigningKey(fullCertificate));
            string serializedToken = token.Serialize();

            await ValidateSerializedToken(serializedToken, body);
        }
        public async Task ValidateJustExpiredAttestationToken()
        {
            // Create a JWT whose body has just expired.
            object tokenBody = new JwtTestBody {
                StringField = "Foo",
                ExpiresAt   = DateTimeOffset.Now.Subtract(TimeSpan.FromSeconds(5)).ToUnixTimeSeconds(),
            };

            var    token           = new AttestationToken(BinaryData.FromObjectAsJson(tokenBody));
            string serializedToken = token.Serialize();

            // This check should fail since the token expired 5 seconds ago.
            Assert.ThrowsAsync(typeof(Exception), async() => await ValidateSerializedToken(serializedToken, tokenBody));

            // This check should succeed since the token slack is greater than the 5 second expiration time.
            await ValidateSerializedToken(serializedToken, tokenBody, new AttestationTokenValidationOptions { TimeValidationSlack = 10 });
        }
        public async Task ValidateTooEarlyAttestationToken()
        {
            // Create a JWT whose body will become valid 5 seconds from now.
            object tokenBody = new JwtTestBody
            {
                StringField = "Foo",
                NotBefore   = DateTimeOffset.Now.AddSeconds(5).ToUnixTimeSeconds(),
                ExpiresAt   = DateTimeOffset.Now.AddSeconds(60).ToUnixTimeSeconds(),
            };

            X509Certificate2    fullCertificate = TestEnvironment.PolicyManagementCertificate;
            AsymmetricAlgorithm privateKey      = TestEnvironment.PolicyManagementKey;

            var    token           = new AttestationToken(BinaryData.FromObjectAsJson(tokenBody), new AttestationTokenSigningKey(privateKey, fullCertificate));
            string serializedToken = token.Serialize();

            // This check should fail since the token won't be valid for another 5 seconds.
            Assert.ThrowsAsync(typeof(Exception), async() => await ValidateSerializedToken(serializedToken, tokenBody));

            // This check should succeed since the token slack is greater than the 10 seconds before it becomes valid.
            await ValidateSerializedToken(serializedToken, tokenBody, new AttestationTokenValidationOptions { TimeValidationSlack = 10 });
        }
Пример #9
0
        public async Task SettingAttestationPolicy()
        {
            var endpoint = TestEnvironment.AadAttestationUrl;

            #region Snippet:GetPolicy
            var client = new AttestationAdministrationClient(new Uri(endpoint), new DefaultAzureCredential());

            AttestationResponse <string> policyResult = await client.GetPolicyAsync(AttestationType.SgxEnclave);

            string result = policyResult.Value;
            #endregion

            #region Snippet:SetPolicy
            string attestationPolicy = "version=1.0; authorizationrules{=> permit();}; issuancerules{};";

            //@@ X509Certificate2 policyTokenCertificate = new X509Certificate2(<Attestation Policy Signing Certificate>);
            //@@ AsymmetricAlgorithm policyTokenKey = <Attestation Policy Signing Key>;
            /*@@*/ var policyTokenCertificate = TestEnvironment.PolicyCertificate0;
            /*@@*/ var policyTokenKey         = TestEnvironment.PolicySigningKey0;

            var setResult = client.SetPolicy(AttestationType.SgxEnclave, attestationPolicy, new AttestationTokenSigningKey(policyTokenKey, policyTokenCertificate));
            #endregion

            #region 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(<Customer provided signing key>, <Customer provided certificate>)
            /*@@*/ AttestationTokenSigningKey signingKey = new AttestationTokenSigningKey(policyTokenKey, policyTokenCertificate);
            var policySetToken = new AttestationToken(
                BinaryData.FromObjectAsJson(new StoredAttestationPolicy {
                AttestationPolicy = attestationPolicy
            }),
                signingKey);

            using var shaHasher = SHA256.Create();
            byte[] attestationPolicyHash = shaHasher.ComputeHash(Encoding.UTF8.GetBytes(policySetToken.Serialize()));

            Debug.Assert(attestationPolicyHash.SequenceEqual(setResult.Value.PolicyTokenHash.ToArray()));
            #endregion
            var resetResult = client.ResetPolicy(AttestationType.SgxEnclave);

            // When the attestation instance is in Isolated mode, the ResetPolicy API requires using a signing key/certificate to authorize the user.
            var resetResult2 = client.ResetPolicy(
                AttestationType.SgxEnclave,
                new AttestationTokenSigningKey(TestEnvironment.PolicySigningKey0, policyTokenCertificate));
            return;
        }