コード例 #1
0
        public async Task AuthenticateRequestTestX509IgnoresAuthorizationHeader_Success()
        {
            string iothubHostName = "TestHub.azure-devices.net";
            string deviceId       = "device_2";
            string moduleId       = "module_1";
            var    httpContext    = new DefaultHttpContext();

            httpContext.Connection.LocalPort = Constants.ApiProxyPort;
            var clientCert = CertificateHelper.GenerateSelfSignedCert($"test_cert");

            httpContext.Request.Headers.Add(HeaderNames.Authorization, new StringValues("blah"));
            httpContext.Request.QueryString          = new QueryString("?api-version=2017-10-20");
            httpContext.Connection.ClientCertificate = clientCert;
            var authenticator = new Mock <IAuthenticator>();

            authenticator.Setup(a => a.AuthenticateAsync(It.IsAny <IClientCredentials>())).ReturnsAsync(true);

            var identityFactory = new ClientCredentialsFactory(new IdentityProvider(iothubHostName));

            var            httpRequestAuthenticator = new HttpRequestAuthenticator(authenticator.Object, identityFactory, iothubHostName);
            HttpAuthResult result = await httpRequestAuthenticator.AuthenticateAsync(deviceId, Option.Some(moduleId), Option.None <string>(), httpContext);

            Assert.True(result.Authenticated);
            Assert.Equal(string.Empty, result.ErrorMessage);
        }
コード例 #2
0
        public async Task TestAsyncAuthentionReturnsFalse_FailsAsync()
        {
            var certificate = TestCertificateHelper.GenerateSelfSignedCert("test moi");
            var chain       = new List <X509Certificate2>()
            {
                certificate
            };
            var    identity                 = new X509CertificateIdentity(certificate, true);
            var    authenticator            = Mock.Of <IAuthenticator>();
            var    clientCredentialsFactory = Mock.Of <IClientCredentialsFactory>();
            var    clientCredentials        = Mock.Of <IClientCredentials>();
            var    principal                = new EdgeX509Principal(identity, chain, authenticator, clientCredentialsFactory);
            string deviceId                 = "myDid";
            string moduleId                 = "myMid";

            Mock.Get(clientCredentialsFactory).Setup(f => f.GetWithX509Cert(deviceId,
                                                                            moduleId,
                                                                            string.Empty,
                                                                            certificate,
                                                                            chain))
            .Returns(clientCredentials);
            Mock.Get(authenticator).Setup(a => a.AuthenticateAsync(clientCredentials)).ReturnsAsync(false);

            Assert.False(await principal.AuthenticateAsync($"{deviceId}/{moduleId}"));
        }
コード例 #3
0
        public async Task AuthenticateRequestTestX509ApiProxyForward_ProxyAuthSuccess_ShouldReturnCertificate()
        {
            string iothubHostName = "TestHub.azure-devices.net";
            string deviceId       = "device_2";
            string apiProxyId     = "iotedgeApiProxy";
            var    httpContext    = new DefaultHttpContext();

            httpContext.Connection.RemoteIpAddress = new IPAddress(0);
            var    certContentBytes  = CertificateHelper.GenerateSelfSignedCert($"test_cert").Export(X509ContentType.Cert);
            string certContentBase64 = Convert.ToBase64String(certContentBytes);
            string clientCertString  = $"-----BEGIN CERTIFICATE-----\n{certContentBase64}\n-----END CERTIFICATE-----\n";

            clientCertString = WebUtility.UrlEncode(clientCertString);
            httpContext.Request.Headers.Add(Constants.ClientCertificateHeaderKey, new StringValues(clientCertString));
            string sasToken = TokenHelper.CreateSasToken($"{iothubHostName}/devices/{deviceId}/modules/{apiProxyId}");

            httpContext.Request.Headers.Add(HeaderNames.Authorization, new StringValues(sasToken));
            httpContext.Request.QueryString = new QueryString("?api-version=2017-10-20");
            var authenticator = new Mock <IAuthenticator>();

            authenticator.Setup(a => a.AuthenticateAsync(It.Is <IClientCredentials>(c => c.Identity.Id == "device_2/iotedgeApiProxy"))).ReturnsAsync(true);

            var identityFactory = new ClientCredentialsFactory(new IdentityProvider(iothubHostName));

            var httpRequestAuthenticator = new HttpProxiedCertificateExtractor(authenticator.Object, identityFactory, iothubHostName, deviceId, apiProxyId);
            var cert = await httpRequestAuthenticator.GetClientCertificate(httpContext);

            Assert.True(cert.HasValue);
            authenticator.VerifyAll();
        }
コード例 #4
0
        public async Task AuthenticateRequestTestX509ApiProxyForward_NoProxyAuthorization_AuthFailed()
        {
            string iothubHostName = "TestHub.azure-devices.net";
            string deviceId       = "device_2";
            string moduleId       = "module_1";
            string apiProxyId     = "iotedgeApiProxy";
            var    httpContext    = new DefaultHttpContext();

            httpContext.Connection.RemoteIpAddress = new IPAddress(0);
            var    certContentBytes  = CertificateHelper.GenerateSelfSignedCert($"test_cert").Export(X509ContentType.Cert);
            string certContentBase64 = Convert.ToBase64String(certContentBytes);
            string clientCertString  = $"-----BEGIN CERTIFICATE-----\n{certContentBase64}\n-----END CERTIFICATE-----\n";

            clientCertString = WebUtility.UrlEncode(clientCertString);
            httpContext.Request.Headers.Add(Constants.ClientCertificateHeaderKey, new StringValues(clientCertString));
            httpContext.Request.QueryString = new QueryString("?api-version=2017-10-20");
            var authenticator = new Mock <IAuthenticator>();

            authenticator.Setup(a => a.AuthenticateAsync(It.IsAny <IClientCredentials>())).ReturnsAsync(true);

            var identityFactory = new ClientCredentialsFactory(new IdentityProvider(iothubHostName));
            var httpProxiedCertificateExtractor = new Mock <IHttpProxiedCertificateExtractor>();

            httpProxiedCertificateExtractor.Setup(p => p.GetClientCertificate(httpContext)).ThrowsAsync(new AuthenticationException($"Unable to authorize proxy {apiProxyId} to forward device certificate - Authorization header missing"));

            var            httpRequestAuthenticator = new HttpRequestAuthenticator(authenticator.Object, identityFactory, iothubHostName, httpProxiedCertificateExtractor.Object);
            HttpAuthResult result = await httpRequestAuthenticator.AuthenticateAsync(deviceId, Option.Some(moduleId), Option.None <string>(), httpContext);

            Assert.False(result.Authenticated);
            Assert.Equal($"Unable to authenticate device with Id device_2/module_1 - Unable to authorize proxy {apiProxyId} to forward device certificate - Authorization header missing", result.ErrorMessage);
        }
コード例 #5
0
        public async Task AuthenticateRequestTestX509ApiProxyForward_NoSasToken_ShouldThrow()
        {
            string iothubHostName = "TestHub.azure-devices.net";
            string deviceId       = "device_2";
            string apiProxyId     = "iotedgeApiProxy";
            var    httpContext    = new DefaultHttpContext();

            httpContext.Connection.RemoteIpAddress = new IPAddress(0);
            var    certContentBytes  = CertificateHelper.GenerateSelfSignedCert($"test_cert").Export(X509ContentType.Cert);
            string certContentBase64 = Convert.ToBase64String(certContentBytes);
            string clientCertString  = $"-----BEGIN CERTIFICATE-----\n{certContentBase64}\n-----END CERTIFICATE-----\n";

            clientCertString = WebUtility.UrlEncode(clientCertString);
            httpContext.Request.Headers.Add(Constants.ClientCertificateHeaderKey, new StringValues(clientCertString));
            httpContext.Request.QueryString = new QueryString("?api-version=2017-10-20");
            var authenticator = new Mock <IAuthenticator>();

            var identityFactory = new ClientCredentialsFactory(new IdentityProvider(iothubHostName));

            var httpRequestAuthenticator = new HttpProxiedCertificateExtractor(authenticator.Object, identityFactory, iothubHostName, deviceId, apiProxyId);
            var ex = await Assert.ThrowsAsync <AuthenticationException>(() => httpRequestAuthenticator.GetClientCertificate(httpContext));

            Assert.Equal($"Unable to authorize proxy iotedgeApiProxy to forward device certificate - Authorization header missing", ex.Message);
            authenticator.VerifyAll();
        }
コード例 #6
0
        public async Task AuthenticateAsyncWithModuleCAX509InScopeCacheFails()
        {
            var notBefore = DateTime.Now.Subtract(TimeSpan.FromDays(2));
            var notAfter  = DateTime.Now.AddYears(1);

            var(caCert, caKeyPair) = TestCertificateHelper.GenerateSelfSignedCert("MyTestCA", notBefore, notAfter, true);
            var(issuedClientCert, issuedClientKeyPair) = TestCertificateHelper.GenerateCertificate("MyIssuedTestClient", notBefore, notAfter, caCert, caKeyPair, false, null, null);
            IList <X509Certificate2> issuedClientCertChain = new List <X509Certificate2>()
            {
                caCert
            };
            IList <X509Certificate2> trustBundle = new List <X509Certificate2>()
            {
                caCert
            };
            string deviceId = "d1";
            string moduleId = "MyIssuedTestClient";
            string identity = FormattableString.Invariant($"{deviceId}/{moduleId}");

            var deviceScopeIdentitiesCache = new Mock <IDeviceScopeIdentitiesCache>();
            var clientCredentials          = Mock.Of <ICertificateCredentials>(c =>
                                                                               c.Identity == Mock.Of <IModuleIdentity>(i => i.DeviceId == deviceId && i.ModuleId == moduleId &&
                                                                                                                       i.Id == identity) &&
                                                                               c.AuthenticationType == AuthenticationType.X509Cert &&
                                                                               c.ClientCertificate == issuedClientCert && c.ClientCertificateChain == issuedClientCertChain);

            var serviceIdentity = new ServiceIdentity(deviceId, moduleId, "1234", new string[0],
                                                      new ServiceAuthentication(ServiceAuthenticationType.CertificateAuthority), ServiceIdentityStatus.Enabled);
            var authenticator = new DeviceScopeCertificateAuthenticator(deviceScopeIdentitiesCache.Object, UnderlyingAuthenticator, trustBundle, true);

            deviceScopeIdentitiesCache.Setup(d => d.GetServiceIdentity(It.Is <string>(i => i == identity), false)).ReturnsAsync(Option.Some(serviceIdentity));


            Assert.False(await authenticator.AuthenticateAsync(clientCredentials));
        }
コード例 #7
0
        public async Task AuthenticateRequestTestX509ApiProxyIgnoresAuthorizationHeader_Success()
        {
            string iothubHostName    = "TestHub.azure-devices.net";
            string deviceId          = "device_2";
            string moduleId          = "module_1";
            var    httpContext       = new DefaultHttpContext();
            var    certContentBytes  = CertificateHelper.GenerateSelfSignedCert($"test_cert").Export(X509ContentType.Cert);
            string certContentBase64 = Convert.ToBase64String(certContentBytes);
            string clientCertString  = $"-----BEGIN CERTIFICATE-----\n{certContentBase64}\n-----END CERTIFICATE-----\n";

            clientCertString = WebUtility.UrlEncode(clientCertString);
            httpContext.Request.Headers.Add(Constants.ClientCertificateHeaderKey, new StringValues(clientCertString));
            httpContext.Request.Headers.Add(HeaderNames.Authorization, new StringValues("blah"));
            httpContext.Request.QueryString = new QueryString("?api-version=2017-10-20");
            var authenticator = new Mock <IAuthenticator>();

            authenticator.Setup(a => a.AuthenticateAsync(It.IsAny <IClientCredentials>())).ReturnsAsync(true);

            var identityFactory = new ClientCredentialsFactory(new IdentityProvider(iothubHostName));

            var            httpRequestAuthenticator = new HttpRequestAuthenticator(authenticator.Object, identityFactory, iothubHostName);
            HttpAuthResult result = await httpRequestAuthenticator.AuthenticateAsync(deviceId, Option.Some(moduleId), Option.None <string>(), httpContext);

            Assert.True(result.Authenticated);
            Assert.Equal(string.Empty, result.ErrorMessage);
        }
コード例 #8
0
        public async Task TestAuthenticateAsyncWithInvalidId_FailsAsync()
        {
            var certificate = TestCertificateHelper.GenerateSelfSignedCert("test moi");
            var chain       = new List <X509Certificate2>()
            {
                certificate
            };
            var identity = new X509CertificateIdentity(certificate, true);
            var auth     = Mock.Of <IAuthenticator>();
            var cf       = Mock.Of <IClientCredentialsFactory>();

            var principal = new EdgeX509Principal(identity, chain, auth, cf);
            await Assert.ThrowsAsync <ArgumentException>(() => principal.AuthenticateAsync(null));

            await Assert.ThrowsAsync <ArgumentException>(() => principal.AuthenticateAsync(""));

            await Assert.ThrowsAsync <ArgumentException>(() => principal.AuthenticateAsync("   "));

            Assert.False(await principal.AuthenticateAsync("/   "));
            Assert.False(await principal.AuthenticateAsync("   /"));
            Assert.False(await principal.AuthenticateAsync("   /   "));
            Assert.False(await principal.AuthenticateAsync("did/"));
            Assert.False(await principal.AuthenticateAsync("did/   "));
            Assert.False(await principal.AuthenticateAsync("/mid"));
            Assert.False(await principal.AuthenticateAsync("   /mid"));
            Assert.False(await principal.AuthenticateAsync("did/mid/blah"));
        }
コード例 #9
0
        public void ClientCertCallbackNoCaCertsFails()
        {
            X509Certificate2 cert = TestCertificateHelper.GenerateSelfSignedCert("top secret");

            Assert.False(CertificateHelper.ValidateClientCert(cert, new X509Chain(),
                                                              Option.None <IList <X509Certificate2> >(), Logger.Factory.CreateLogger("something")));
        }
コード例 #10
0
        public async Task AuthenticateAsyncWithEmptyChainDeviceCAX509InScopeCacheFails()
        {
            var notBefore        = DateTime.Now.Subtract(TimeSpan.FromDays(2));
            var notAfter         = DateTime.Now.AddYears(1);
            var caCert           = TestCertificateHelper.GenerateSelfSignedCert("MyTestCA", notBefore, notAfter, true);
            var issuedClientCert = TestCertificateHelper.GenerateCertificate("MyIssuedTestClient", notBefore, notAfter, caCert, false, null, null);
            IList <X509Certificate2> issuedClientCertChain = new List <X509Certificate2>()
            {
            };                                                                                // empty chain supplied
            IList <X509Certificate2> trustBundle = new List <X509Certificate2>()
            {
                caCert
            };
            string deviceId = "different from CN";

            var deviceScopeIdentitiesCache = new Mock <IDeviceScopeIdentitiesCache>();
            var clientCredentials          = Mock.Of <ICertificateCredentials>(
                c =>
                c.Identity == Mock.Of <IDeviceIdentity>(i => i.DeviceId == deviceId && i.Id == deviceId) &&
                c.AuthenticationType == AuthenticationType.X509Cert &&
                c.ClientCertificate == issuedClientCert && c.ClientCertificateChain == issuedClientCertChain);

            var serviceIdentity = new ServiceIdentity(
                deviceId,
                "1234",
                new string[0],
                new ServiceAuthentication(ServiceAuthenticationType.CertificateAuthority),
                ServiceIdentityStatus.Enabled);
            var authenticator = new DeviceScopeCertificateAuthenticator(deviceScopeIdentitiesCache.Object, UnderlyingAuthenticator, trustBundle, true);

            deviceScopeIdentitiesCache.Setup(d => d.GetServiceIdentity(It.Is <string>(i => i == deviceId))).ReturnsAsync(Option.Some(serviceIdentity));

            Assert.False(await authenticator.AuthenticateAsync(clientCredentials));
        }
コード例 #11
0
        public void ClientCertCallbackNoCaCertsFails()
        {
            X509Certificate2         cert = TestCertificateHelper.GenerateSelfSignedCert("top secret");
            IList <X509Certificate2> ca   = new List <X509Certificate2>();
            var trustedCACerts            = Option.Some(ca);

            Assert.False(CertificateHelper.ValidateClientCert(cert, new List <X509Certificate2>(), trustedCACerts, Logger.Factory.CreateLogger("something")));
        }
コード例 #12
0
        public void ValidateCertSuccess()
        {
            X509Certificate2 cert = TestCertificateHelper.GenerateSelfSignedCert("top secret");

            (bool validated, Option <string> errors) = CertificateHelper.ValidateCert(cert, new[] { cert }, new[] { cert });
            Assert.True(validated);
            Assert.False(errors.HasValue);
        }
コード例 #13
0
        public void BuildCertificateListSuccess()
        {
            X509Certificate2 cert = TestCertificateHelper.GenerateSelfSignedCert("top secret");

            (IList <X509Certificate2> certs, Option <string> errors) = CertificateHelper.BuildCertificateList(cert, Option.None <IList <X509Certificate2> >());
            Assert.True(certs.Count == 1);
            Assert.False(errors.HasValue);
        }
コード例 #14
0
        public void ValidateCertNullArgumentsThrows()
        {
            var trustedCACerts    = Option.None <IList <X509Certificate2> >();
            X509Certificate2 cert = TestCertificateHelper.GenerateSelfSignedCert("top secret");

            Assert.Throws <ArgumentNullException>(() => CertificateHelper.ValidateCert(null, Array.Empty <X509Certificate2>(), trustedCACerts));
            Assert.Throws <ArgumentNullException>(() => CertificateHelper.ValidateCert(cert, null, trustedCACerts));
        }
コード例 #15
0
        public void TestValidateCertificateWithCAExtentionFails()
        {
            var caCert = TestCertificateHelper.GenerateSelfSignedCert("MyTestCA", true);

            Assert.False(CertificateHelper.ValidateClientCert(caCert, new List <X509Certificate2>()
            {
                caCert
            }, Option.None <IList <X509Certificate2> >(), Logger.Factory.CreateLogger("something")));
        }
コード例 #16
0
        public void ValidateCertSuccess()
        {
            var trustedCACerts    = Option.None <IList <X509Certificate2> >();
            X509Certificate2 cert = TestCertificateHelper.GenerateSelfSignedCert("top secret");

            (bool validated, Option <string> errors) = CertificateHelper.ValidateCert(cert, new[] { cert }, trustedCACerts);
            Assert.True(validated);
            Assert.False(errors.HasValue);
        }
コード例 #17
0
        public void HttpsExtensionConnectionAdapterTestValidCertWithNoEku_Succeeds()
        {
            var cert    = TestCertificateHelper.GenerateSelfSignedCert("no eku");
            var options = new HttpsConnectionAdapterOptions()
            {
                ServerCertificate = cert
            };

            Assert.NotNull(new HttpsExtensionConnectionAdapter(options));
        }
コード例 #18
0
        public void HttpsExtensionConnectionAdapterTestValidCertWithEkuServer_Succeeds()
        {
            var(cert, key) = TestCertificateHelper.GenerateServerCert("eku server auth", DateTime.Now.Subtract(TimeSpan.FromDays(2)), DateTime.Now.AddYears(1));
            var options = new HttpsConnectionAdapterOptions()
            {
                ServerCertificate = cert
            };

            Assert.NotNull(new HttpsExtensionConnectionAdapter(options));
        }
コード例 #19
0
        public void HttpsExtensionConnectionAdapterTestValidCertWithEkuClient_Fails()
        {
            var(cert, key) = TestCertificateHelper.GenerateClientert("eku client auth", DateTime.Now.Subtract(TimeSpan.FromDays(2)), DateTime.Now.AddYears(1));
            var options = new HttpsConnectionAdapterOptions()
            {
                ServerCertificate = cert
            };

            Assert.Throws <InvalidOperationException>(() => new HttpsExtensionConnectionAdapter(options));
        }
コード例 #20
0
        public void TestValidateCertificateWithFutureValidityFails()
        {
            var notBefore  = DateTime.Now.AddYears(1);
            var notAfter   = DateTime.Now.AddYears(2);
            var clientCert = TestCertificateHelper.GenerateSelfSignedCert("MyTestClient", notBefore, notAfter, false);

            Assert.False(CertificateHelper.ValidateClientCert(clientCert, new List <X509Certificate2>()
            {
                clientCert
            }, Option.None <IList <X509Certificate2> >(), Logger.Factory.CreateLogger("something")));
        }
コード例 #21
0
        public void TestValidateCertificateWithExpiredValidityFails()
        {
            var notBefore = DateTime.Now.Subtract(TimeSpan.FromDays(2));
            var notAfter  = DateTime.Now.Subtract(TimeSpan.FromDays(1));

            var(clientCert, clientKeyPair) = TestCertificateHelper.GenerateSelfSignedCert("MyTestClient", notBefore, notAfter, false);
            Assert.False(CertificateHelper.ValidateClientCert(clientCert, new List <X509Certificate2>()
            {
                clientCert
            }, Option.None <IList <X509Certificate2> >(), Logger.Factory.CreateLogger("something")));
        }
コード例 #22
0
        public void ParseRSACertificateAndKeyShouldReturnCertAndKey()
        {
            TestCertificateHelper.GenerateSelfSignedCert("top secret").Export(X509ContentType.Cert);
            (X509Certificate2 cert, IEnumerable <X509Certificate2> chain) = CertificateHelper.ParseCertificateAndKey(TestCertificateHelper.CertificatePem, TestCertificateHelper.PrivateKeyPem);

            var expected = new X509Certificate2(Encoding.UTF8.GetBytes(TestCertificateHelper.CertificatePem));

            Assert.Equal(expected, cert);
            Assert.True(cert.HasPrivateKey);
            Assert.Empty(chain);
        }
コード例 #23
0
        public void IsHttpsAlwaysTrue()
        {
            var server  = TestCertificateHelper.GenerateSelfSignedCert("test server");
            var options = new HttpsConnectionAdapterOptions()
            {
                ServerCertificate = server
            };
            var ext = new HttpsExtensionConnectionAdapter(options);

            Assert.True(ext.IsHttps);
        }
コード例 #24
0
        public void TestValidateCertificateAndChainSucceeds()
        {
            var notBefore        = DateTime.Now.Subtract(TimeSpan.FromDays(2));
            var notAfter         = DateTime.Now.AddYears(1);
            var caCert           = TestCertificateHelper.GenerateSelfSignedCert("MyTestCA", notBefore, notAfter, true);
            var issuedClientCert = TestCertificateHelper.GenerateCertificate("MyIssuedTestClient", notBefore, notAfter, caCert, false, null, null);

            Assert.True(CertificateHelper.ValidateClientCert(issuedClientCert, new List <X509Certificate2>()
            {
                caCert
            }, Option.None <IList <X509Certificate2> >(), Logger.Factory.CreateLogger("something")));
        }
コード例 #25
0
        public void ClientCertCallbackNullArgumentThrows()
        {
            var trustedCACerts    = Option.None <IList <X509Certificate2> >();
            X509Certificate2 cert = TestCertificateHelper.GenerateSelfSignedCert("top secret");

            Assert.Throws <ArgumentNullException>(
                () =>
                CertificateHelper.ValidateClientCert(null, new List <X509Certificate2>(), trustedCACerts, Logger.Factory.CreateLogger("something")));
            Assert.Throws <ArgumentNullException>(
                () =>
                CertificateHelper.ValidateClientCert(cert, null, trustedCACerts, Logger.Factory.CreateLogger("something")));
        }
コード例 #26
0
        public void TestValidConstructorInputs_Succeeds()
        {
            var certificate = TestCertificateHelper.GenerateSelfSignedCert("test moi");
            var chain       = new List <X509Certificate2>()
            {
                certificate
            };
            var identity = new X509CertificateIdentity(certificate, true);
            var auth     = Mock.Of <IAuthenticator>();
            var cf       = Mock.Of <IClientCredentialsFactory>();

            Assert.NotNull(new EdgeX509Principal(identity, chain, auth, cf));
        }
コード例 #27
0
        public void ValidateCertNoMatchFailure()
        {
            X509Certificate2         cert = TestCertificateHelper.GenerateSelfSignedCert("top secret");
            X509Certificate2         root = TestCertificateHelper.GenerateSelfSignedCert("root");
            IList <X509Certificate2> ca   = new List <X509Certificate2>()
            {
                root
            };

            (bool validated, Option <string> errors) = CertificateHelper.ValidateCert(cert, new[] { cert }, Option.Some(ca));
            Assert.False(validated);
            Assert.True(errors.HasValue);
        }
コード例 #28
0
        public async Task AuthenticateAsyncWithModuleThumbprintX509InScopeCacheFails()
        {
            string deviceId               = "d1";
            string moduleId               = "m1";
            string identity               = FormattableString.Invariant($"{deviceId}/{moduleId}");
            var    primaryCertificate     = TestCertificateHelper.GenerateSelfSignedCert("primo");
            var    primaryClientCertChain = new List <X509Certificate2>()
            {
                primaryCertificate
            };
            var secondaryCertificate     = TestCertificateHelper.GenerateSelfSignedCert("secondo");
            var secondaryClientCertChain = new List <X509Certificate2>()
            {
                secondaryCertificate
            };

            var deviceScopeIdentitiesCache       = new Mock <IDeviceScopeIdentitiesCache>();
            IList <X509Certificate2> trustBundle = new List <X509Certificate2>();
            var primaryCredentials = Mock.Of <ICertificateCredentials>(
                c =>
                c.Identity == Mock.Of <IModuleIdentity>(
                    i => i.DeviceId == deviceId && i.ModuleId == moduleId &&
                    i.Id == identity) &&
                c.AuthenticationType == AuthenticationType.X509Cert &&
                c.ClientCertificate == primaryCertificate && c.ClientCertificateChain == primaryClientCertChain);

            var secondaryCredentials = Mock.Of <ICertificateCredentials>(
                c =>
                c.Identity == Mock.Of <IModuleIdentity>(
                    i => i.DeviceId == deviceId && i.ModuleId == moduleId &&
                    i.Id == identity) &&
                c.AuthenticationType == AuthenticationType.X509Cert &&
                c.ClientCertificate == secondaryCertificate && c.ClientCertificateChain == secondaryClientCertChain);

            var serviceIdentity = new ServiceIdentity(
                deviceId,
                moduleId,
                "e1",
                new List <string>(),
                "1234",
                new string[0],
                new ServiceAuthentication(new X509ThumbprintAuthentication(primaryCertificate.Thumbprint, secondaryCertificate.Thumbprint)),
                ServiceIdentityStatus.Enabled);
            var authenticator = new DeviceScopeCertificateAuthenticator(deviceScopeIdentitiesCache.Object, UnderlyingAuthenticator, trustBundle, true);

            deviceScopeIdentitiesCache.Setup(d => d.GetServiceIdentity(It.Is <string>(i => i == identity))).ReturnsAsync(Option.Some(serviceIdentity));

            // Assert
            Assert.False(await authenticator.AuthenticateAsync(primaryCredentials));
            Assert.False(await authenticator.AuthenticateAsync(secondaryCredentials));
        }
コード例 #29
0
        public void ParseMultipleCertificateAndKeyShouldReturnCertAndKey()
        {
            TestCertificateHelper.GenerateSelfSignedCert("top secret").Export(X509ContentType.Cert);
            string certificate = $"{TestCertificateHelper.CertificatePem}\n{TestCertificateHelper.CertificatePem}";

            (X509Certificate2 cert, IEnumerable <X509Certificate2> chain) = CertificateHelper.ParseCertificateAndKey(certificate, TestCertificateHelper.PrivateKeyPemPkcs8);

            var expected = new X509Certificate2(Encoding.UTF8.GetBytes(TestCertificateHelper.CertificatePem));

            Assert.Equal(expected, cert);
            Assert.True(cert.HasPrivateKey);
            Assert.Single(chain);
            Assert.Equal(expected, chain.First());
        }
コード例 #30
0
        public void TestIfCACertificate()
        {
            var notBefore = DateTime.Now.Subtract(TimeSpan.FromDays(2));
            var notAfter  = DateTime.Now.AddYears(1);

            var(caCert, caKeyPair) = TestCertificateHelper.GenerateSelfSignedCert("MyTestCA", notBefore, notAfter, true);
            Assert.True(CertificateHelper.IsCACertificate(caCert));

            var(clientCert, clientKeyPair) = TestCertificateHelper.GenerateSelfSignedCert("MyTestClient", notBefore, notAfter, false);
            Assert.False(CertificateHelper.IsCACertificate(clientCert));

            var(issuedClientCert, issuedClientKeyPair) = TestCertificateHelper.GenerateCertificate("MyIssuedTestClient", notBefore, notAfter, caCert, caKeyPair, false, null, null);
            Assert.False(CertificateHelper.IsCACertificate(issuedClientCert));
        }