Пример #1
0
        public async Task VerifyNotAfterInvalid(bool trusted)
        {
            var cert = CertificateFactory.CreateCertificate(
                null, null, "CN=App Test Cert",
                null, CertificateFactory.DefaultKeySize,
                new DateTime(2010, 1, 1), 12,
                CertificateFactory.DefaultHashSize);

            TestContext.Out.WriteLine($"{cert}:");
            Assert.NotNull(cert);
            cert = new X509Certificate2(cert);
            Assert.NotNull(cert);
            Assert.True(X509Utils.CompareDistinguishedName("CN=App Test Cert", cert.Subject));
            CleanupValidatorAndStores();
            if (trusted)
            {
                await m_issuerStore.Add(cert);
            }
            else
            {
                await m_trustedStore.Add(cert);
            }
            var certValidator          = InitValidatorWithStores();
            var serviceResultException = Assert.Throws <ServiceResultException>(() => { certValidator.Validate(cert); });

            Assert.AreEqual(StatusCodes.BadCertificateTimeInvalid, serviceResultException.StatusCode, serviceResultException.Message);
        }
        public void VerifyCACerts(
            KeyHashPair keyHashPair
            )
        {
            var subject = "CN=CA Test Cert";
            int pathLengthConstraint = (keyHashPair.KeySize / 512) - 3;
            var cert = CertificateFactory.CreateCertificate(
                null, null, null,
                null, null, subject,
                null, keyHashPair.KeySize,
                DateTime.UtcNow, 25 * 12,
                keyHashPair.HashSize,
                isCA: true,
                pathLengthConstraint: pathLengthConstraint);

            Assert.NotNull(cert);
            Assert.NotNull(cert.RawData);
            Assert.True(cert.HasPrivateKey);
            var plainCert = new X509Certificate2(cert.RawData);

            Assert.NotNull(plainCert);
            VerifyCACert(plainCert, subject, pathLengthConstraint);
            CertificateFactory.VerifySelfSigned(cert);
            CertificateFactory.VerifyRSAKeyPair(cert, cert);
        }
Пример #3
0
        public virtual async Task <X509Certificate2> CreateCACertificateAsync(
            string subjectName
            )
        {
            DateTime         yesterday      = DateTime.UtcNow.AddDays(-1);
            X509Certificate2 newCertificate = CertificateFactory.CreateCertificate(
                m_authoritiesStoreType,
                m_authoritiesStorePath,
                null,
                null,
                null,
                subjectName,
                null,
                Configuration.CACertificateKeySize,
                yesterday,
                Configuration.CACertificateLifetime,
                Configuration.CACertificateHashSize,
                true,
                null,
                null);

            // save only public key
            Certificate = new X509Certificate2(newCertificate.RawData);

            // initialize revocation list
            await CertificateFactory.RevokeCertificateAsync(m_authoritiesStorePath, newCertificate, null);

            await UpdateAuthorityCertInTrustedList();

            return(Certificate);
        }
Пример #4
0
        /// <summary>
        /// Creates the application instance certificate.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        /// <param name="keySize">Size of the key.</param>
        /// <param name="lifeTimeInMonths">The lifetime in months.</param>
        /// <returns>The new certificate</returns>
        private static async Task <X509Certificate2> CreateApplicationInstanceCertificate(
            ApplicationConfiguration configuration,
            ushort keySize,
            ushort lifeTimeInMonths
            )
        {
            Utils.Trace(Utils.TraceMasks.Information, "Creating application instance certificate.");

            // delete any existing certificate.
            await DeleteApplicationInstanceCertificate(configuration).ConfigureAwait(false);

            CertificateIdentifier id = configuration.SecurityConfiguration.ApplicationCertificate;

            // get the domains from the configuration file.
            IList <string> serverDomainNames = configuration.GetServerDomainNames();

            if (serverDomainNames.Count == 0)
            {
                serverDomainNames.Add(Utils.GetHostName());
            }

            // ensure the certificate store directory exists.
            if (id.StoreType == CertificateStoreType.Directory)
            {
                Utils.GetAbsoluteDirectoryPath(id.StorePath, true, true, true);
            }

            X509Certificate2 certificate = CertificateFactory.CreateCertificate(
                configuration.ApplicationUri,
                configuration.ApplicationName,
                id.SubjectName,
                serverDomainNames)
                                           .SetLifeTime(lifeTimeInMonths)
                                           .SetRSAKeySize(keySize)
                                           .CreateForRSA();

            id.Certificate = certificate;
            var passwordProvider = configuration.SecurityConfiguration.CertificatePasswordProvider;

            certificate.AddToStore(
                id.StoreType,
                id.StorePath,
                passwordProvider?.GetPassword(id)
                );

            // ensure the certificate is trusted.
            if (configuration.SecurityConfiguration.AddAppCertToTrustedStore)
            {
                await AddToTrustedStore(configuration, certificate).ConfigureAwait(false);
            }

            await configuration.CertificateValidator.Update(configuration.SecurityConfiguration).ConfigureAwait(false);

            Utils.Trace(Utils.TraceMasks.Information, "Certificate created. Thumbprint={0}", certificate.Thumbprint);

            // reload the certificate from disk.
            await configuration.SecurityConfiguration.ApplicationCertificate.LoadPrivateKeyEx(passwordProvider).ConfigureAwait(false);

            return(certificate);
        }
        public void VerifySignedAppCerts(
            KeyHashPair keyHashPair
            )
        {
            X509Certificate2 issuerCertificate = GetIssuer(keyHashPair);

            Assert.NotNull(issuerCertificate);
            Assert.NotNull(issuerCertificate.RawData);
            Assert.True(issuerCertificate.HasPrivateKey);
            var appTestGenerator    = new ApplicationTestDataGenerator(keyHashPair.KeySize);
            ApplicationTestData app = appTestGenerator.ApplicationTestSet(1).First();
            var cert = CertificateFactory.CreateCertificate(
                app.ApplicationUri, app.ApplicationName, app.Subject, app.DomainNames)
                       .SetHashAlgorithm(keyHashPair.HashAlgorithmName)
                       .SetIssuer(issuerCertificate)
                       .SetRSAKeySize(keyHashPair.KeySize)
                       .CreateForRSA();

            Assert.NotNull(cert);
            Assert.NotNull(cert.RawData);
            Assert.True(cert.HasPrivateKey);
            using (var plainCert = new X509Certificate2(cert.RawData))
            {
                Assert.NotNull(plainCert);
                VerifyApplicationCert(app, plainCert, issuerCertificate);
                X509Utils.VerifyRSAKeyPair(plainCert, cert, true);
            }
        }
        public void VerifySelfSignedAppCerts(
            KeyHashPair keyHashPair
            )
        {
            var appTestGenerator    = new ApplicationTestDataGenerator(keyHashPair.KeySize);
            ApplicationTestData app = appTestGenerator
                                      .ApplicationTestSet(1)
                                      .First();
            var cert = CertificateFactory.CreateCertificate(app.ApplicationUri, app.ApplicationName, app.Subject, app.DomainNames)
                       .SetHashAlgorithm(keyHashPair.HashAlgorithmName)
                       .SetRSAKeySize(keyHashPair.KeySize)
                       .CreateForRSA();

            Assert.NotNull(cert);
            Assert.NotNull(cert.RawData);
            Assert.True(cert.HasPrivateKey);
            using (RSA rsa = cert.GetRSAPrivateKey())
            {
                rsa.ExportParameters(true);
            }
            using (RSA rsa = cert.GetRSAPublicKey())
            {
                rsa.ExportParameters(false);
            }
            var plainCert = new X509Certificate2(cert.RawData);

            Assert.NotNull(plainCert);
            VerifyApplicationCert(app, plainCert);
            X509Utils.VerifyRSAKeyPair(cert, cert, true);
            Assert.True(X509Utils.VerifySelfSigned(cert), "Verify Self signed.");
        }
Пример #7
0
        public virtual async Task <X509Certificate2> SigningRequestAsync(
            ApplicationRecordDataType application,
            string[] domainNames,
            byte[] certificateRequest)
        {
            Pkcs10CertificationRequest pkcs10CertificationRequest = new Pkcs10CertificationRequest(certificateRequest);
            CertificationRequestInfo   info = pkcs10CertificationRequest.GetCertificationRequestInfo();
            DateTime yesterday = DateTime.UtcNow.AddDays(-1);

            return(CertificateFactory.CreateCertificate(
                       null,
                       null,
                       null,
                       application.ApplicationUri ?? "urn:ApplicationURI",
                       application.ApplicationNames.Count > 0 ? application.ApplicationNames[0].Text : "ApplicationName",
                       info.Subject.ToString(),
                       domainNames,
                       Configuration.DefaultCertificateKeySize,
                       yesterday,
                       Configuration.DefaultCertificateLifetime,
                       Configuration.DefaultCertificateHashSize,
                       false,
                       await LoadSigningKeyAsync(Certificate, string.Empty),
                       info.SubjectPublicKeyInfo.GetEncoded()));
        }
Пример #8
0
        public async Task VerifyNotBeforeInvalid(bool trusted)
        {
            var cert = CertificateFactory.CreateCertificate(
                null, null, null,
                null, "App Test Cert", null,
                null, CertificateFactory.DefaultKeySize,
                DateTime.UtcNow + TimeSpan.FromDays(14), 12,
                CertificateFactory.DefaultHashSize);

            Assert.NotNull(cert);
            cert = new X509Certificate2(cert);
            Assert.NotNull(cert);
            Assert.True(Utils.CompareDistinguishedName("CN=App Test Cert", cert.Subject));
            CleanupValidatorAndStores();
            if (trusted)
            {
                await m_issuerStore.Add(cert);
            }
            else
            {
                await m_trustedStore.Add(cert);
            }
            var certValidator          = InitValidatorWithStores();
            var serviceResultException = Assert.Throws <ServiceResultException>(() => { certValidator.Validate(cert); });

            Assert.AreEqual(StatusCodes.BadCertificateTimeInvalid, serviceResultException.StatusCode, serviceResultException.Message);
        }
Пример #9
0
        /// <summary>
        /// Create CA test certificates.
        /// </summary>
        private void CreateCATestCerts(string tempStorePath)
        {
            Assert.IsTrue(EraseStore(tempStorePath));

            string           subjectName = "CN=CA Test Cert, O=OPC Foundation";
            X509Certificate2 newCACert   = CertificateFactory.CreateCertificate(
                CertificateStoreType.Directory,
                tempStorePath,
                null,
                null,
                null,
                subjectName,
                null,
                CertificateFactory.defaultKeySize,
                DateTime.UtcNow,
                CertificateFactory.defaultLifeTime,
                CertificateFactory.defaultHashSize,
                true,
                null,
                null);

            _caCert = newCACert;

            // initialize cert revocation list (CRL)
            X509CRL newCACrl = CertificateFactory.RevokeCertificateAsync(tempStorePath, newCACert).Result;

            _caCrl = newCACrl;
        }
Пример #10
0
        public virtual async Task <X509Certificate2> CreateCACertificateAsync(
            string subjectName
            )
        {
            DateTime         yesterday      = DateTime.Today.AddDays(-1);
            X509Certificate2 newCertificate = CertificateFactory.CreateCertificate(subjectName)
                                              .SetNotBefore(yesterday)
                                              .SetLifeTime(Configuration.CACertificateLifetime)
                                              .SetHashAlgorithm(X509Utils.GetRSAHashAlgorithmName(Configuration.CACertificateHashSize))
                                              .SetCAConstraint()
                                              .SetRSAKeySize(Configuration.CACertificateKeySize)
                                              .CreateForRSA()
                                              .AddToStore(
                AuthoritiesStoreType,
                AuthoritiesStorePath);

            // save only public key
            Certificate = new X509Certificate2(newCertificate.RawData);

            // initialize revocation list
            await RevokeCertificateAsync(AuthoritiesStorePath, newCertificate, null).ConfigureAwait(false);

            await UpdateAuthorityCertInTrustedList().ConfigureAwait(false);

            return(Certificate);
        }
        /// <summary>
        /// Synchronous helper implementation of CheckApplicationInstanceCertificate for C++ Proxy
        /// </summary>
        public static void CheckApplicationInstanceCertificate(ApplicationConfiguration configuration)
        {
            // create a default certificate id none specified.
            CertificateIdentifier id = configuration.SecurityConfiguration.ApplicationCertificate;

            if (id == null)
            {
                id             = new CertificateIdentifier();
                id.StoreType   = Utils.DefaultStoreType;
                id.StorePath   = Utils.DefaultStorePath;
                id.SubjectName = configuration.ApplicationName;
            }

            // check for certificate with a private key.
            X509Certificate2 certificate = id.Find(true).Result;

            if (certificate != null)
            {
                return;
            }

            // construct the subject name from the
            List <string> hostNames = new List <string>();

            hostNames.Add(Utils.GetHostName());

            string commonName  = Utils.Format("CN={0}", configuration.ApplicationName);
            string domainName  = Utils.Format("DC={0}", hostNames[0]);
            string subjectName = Utils.Format("{0}, {1}", commonName, domainName);

            // create a new certificate with a new public key pair.
            certificate = CertificateFactory.CreateCertificate(
                configuration.ApplicationUri,
                configuration.ApplicationName,
                subjectName,
                hostNames)
                          .CreateForRSA()
                          .AddToStore(
                id.StoreType,
                id.StorePath);

            id.Certificate = certificate;

            // update and save the configuration file.
            configuration.SaveToFile(configuration.SourceFilePath);

            // add certificate to the trusted peer store so other applications will trust it.
            using (ICertificateStore store = configuration.SecurityConfiguration.TrustedPeerCertificates.OpenStore())
            {
                X509Certificate2Collection certificateCollection = store.FindByThumbprint(certificate.Thumbprint).Result;
                if (certificateCollection != null)
                {
                    store.Add(certificateCollection[0]).Wait();
                }
            }

            // tell the certificate validator about the new certificate.
            configuration.CertificateValidator.Update(configuration.SecurityConfiguration).Wait();
        }
        public async Task <X509CertificateCollection> KeyVaultSigningRequestAsync()
        {
            Skip.If(!_fixture.KeyVaultInitOk);
            var certCollection = new X509CertificateCollection();
            var groups         = await _registry.ListGroupIdsAsync(null, null);

            foreach (var group in groups.Groups)
            {
                var certificateGroupConfiguration = await _registry.GetGroupInfoAsync(group);

                var randomApp      = _fixture.RandomGenerator.RandomApplicationTestData();
                var csrCertificate = CertificateFactory.CreateCertificate(
                    null, null, null,
                    randomApp.ApplicationRecord.ApplicationUri,
                    null,
                    randomApp.Subject,
                    randomApp.DomainNames.ToArray(),
                    certificateGroupConfiguration.DefaultCertificateKeySize,
                    DateTime.UtcNow.AddDays(-10),
                    certificateGroupConfiguration.DefaultCertificateLifetime,
                    certificateGroupConfiguration.DefaultCertificateHashSize
                    );
                var certificateRequest = CertificateFactory.CreateSigningRequest(
                    csrCertificate, randomApp.DomainNames);

                var newCert = await _services.ProcessSigningRequestAsync(
                    "cert",
                    new Registry.Models.ApplicationInfoModel {
                    ApplicationUri = randomApp.ApplicationRecord.ApplicationUri,
                },
                    certificateRequest);

                // get issuer cert used for signing
                var issuerCerts = await _services.GetIssuerCACertificateChainAsync(group);

#if WRITECERT
                // save cert for debugging
                using (var store = Opc.Ua.CertificateStoreIdentifier.CreateStore(
                           Opc.Ua.CertificateStoreType.Directory)) {
                    Assert.NotNull(store);
                    store.Open("d:\\unittest");
                    await store.Add(newCert.ToStackModel());

                    foreach (var cert in issuerCerts.ToStackModel())
                    {
                        await store.Add(cert);
                    }
                }
#endif
                Assert.NotNull(issuerCerts);
                Assert.True(issuerCerts.Chain.Count >= 1);
                X509TestUtils.VerifySignedApplicationCert(
                    randomApp, newCert.ToStackModel(), issuerCerts.ToStackModel());
                certCollection.Add(newCert.ToStackModel());
            }
            return(certCollection);
        }
Пример #13
0
        /// <summary>
        /// Create application configuration
        /// </summary>
        /// <param name="opcConfig"></param>
        /// <param name="handler"></param>
        /// <param name="createSelfSignedCertIfNone"></param>
        /// <returns></returns>
        public static ApplicationConfiguration ToApplicationConfiguration(
            this IClientServicesConfig2 opcConfig, bool createSelfSignedCertIfNone,
            CertificateValidationEventHandler handler)
        {
            if (string.IsNullOrWhiteSpace(opcConfig.ApplicationName))
            {
                throw new ArgumentNullException(nameof(opcConfig.ApplicationName));
            }

            var applicationConfiguration = new ApplicationConfiguration {
                ApplicationName       = opcConfig.ApplicationName,
                ApplicationUri        = opcConfig.ApplicationUri,
                ProductUri            = opcConfig.ProductUri,
                ApplicationType       = ApplicationType.Client,
                TransportQuotas       = opcConfig.ToTransportQuotas(),
                SecurityConfiguration = opcConfig.ToSecurityConfiguration(),
                ClientConfiguration   = new ClientConfiguration(),
                CertificateValidator  = new CertificateValidator()
            };

            applicationConfiguration.CertificateValidator.CertificateValidation += handler;

            X509Certificate2 certificate = null;

            // use existing certificate, if it is there
            certificate = applicationConfiguration.SecurityConfiguration.ApplicationCertificate.Find(true).Result;

            // create a self signed certificate if there is none
            if (certificate == null && createSelfSignedCertIfNone)
            {
                certificate = CertificateFactory.CreateCertificate(
                    applicationConfiguration.SecurityConfiguration.ApplicationCertificate.StoreType,
                    applicationConfiguration.SecurityConfiguration.ApplicationCertificate.StorePath,
                    null,
                    applicationConfiguration.ApplicationUri,
                    applicationConfiguration.ApplicationName,
                    applicationConfiguration.ApplicationName,
                    null,
                    CertificateFactory.defaultKeySize,
                    DateTime.UtcNow - TimeSpan.FromDays(1),
                    CertificateFactory.defaultLifeTime,
                    CertificateFactory.defaultHashSize
                    );

                // update security information
                applicationConfiguration.SecurityConfiguration.ApplicationCertificate.Certificate =
                    certificate ??
                    throw new Exception(
                              "OPC UA application certificate can not be created! Cannot continue without it!");
                //await applicationConfiguration.CertificateValidator.UpdateCertificate(
                //applicationConfiguration.SecurityConfiguration).ConfigureAwait(false);
            }

            applicationConfiguration.ApplicationUri = Utils.GetApplicationUriFromCertificate(certificate);

            return(applicationConfiguration);
        }
Пример #14
0
        private async Task SigningRequestAllApplications()
        {
            Skip.If(!_fixture.RegistrationOk);
            int count = 0;

            foreach (var application in _applicationTestSet)
            {
                string[] groups = await _certificateGroup.GetCertificateGroupIds();

                foreach (var group in groups)
                {
                    var applicationId = application.Model.ApplicationId.ToString();
                    var certificateGroupConfiguration = await _certificateGroup.GetCertificateGroupConfiguration(group);

                    X509Certificate2 csrCertificate = CertificateFactory.CreateCertificate(
                        null, null, null,
                        application.ApplicationRecord.ApplicationUri,
                        null,
                        application.Subject,
                        application.DomainNames.ToArray(),
                        certificateGroupConfiguration.DefaultCertificateKeySize,
                        DateTime.UtcNow.AddDays(-20),
                        certificateGroupConfiguration.DefaultCertificateLifetime,
                        certificateGroupConfiguration.DefaultCertificateHashSize
                        );
                    byte[] csr = CertificateFactory.CreateSigningRequest(
                        csrCertificate,
                        application.DomainNames);
                    string requestId = await _certificateRequest.StartSigningRequestAsync(
                        applicationId,
                        group,
                        null,
                        csr,
                        "*****@*****.**");

                    Assert.NotNull(requestId);
                    // read request
                    var request = await _certificateRequest.ReadAsync(requestId);

                    Assert.Equal(CertificateRequestState.New, request.State);
                    Assert.Null(request.PrivateKeyFormat);
                    Assert.True(request.SigningRequest);
                    Assert.Equal(requestId, request.RequestId);
                    Assert.Equal(applicationId, request.ApplicationId);
                    Assert.Null(request.SubjectName);
                    Assert.Equal(group, request.CertificateGroupId);
                    //Assert.Equal(null, fullRequest.CertificateTypeId);
                    //Assert.Equal(application.DomainNames.ToArray(), fullRequest.DomainNames);
                    Assert.Null(request.PrivateKeyFormat);
                    // add to list
                    application.RequestIds.Add(requestId);
                    count++;
                }
            }
            Assert.True(count > 0);
        }
        public async Task <X509CertificateCollection> KeyVaultSigningRequestAsync()
        {
            Skip.If(!_fixture.KeyVaultInitOk);
            X509CertificateCollection certCollection = new X509CertificateCollection();

            string[] groups = await _keyVault.GetCertificateGroupIds();

            foreach (string group in groups)
            {
                var certificateGroupConfiguration = await _keyVault.GetCertificateGroupConfiguration(group);

                ApplicationTestData randomApp      = _fixture.RandomGenerator.RandomApplicationTestData();
                X509Certificate2    csrCertificate = CertificateFactory.CreateCertificate(
                    null, null, null,
                    randomApp.ApplicationRecord.ApplicationUri,
                    null,
                    randomApp.Subject,
                    randomApp.DomainNames.ToArray(),
                    certificateGroupConfiguration.DefaultCertificateKeySize,
                    DateTime.UtcNow.AddDays(-10),
                    certificateGroupConfiguration.DefaultCertificateLifetime,
                    certificateGroupConfiguration.DefaultCertificateHashSize
                    );
                byte[] certificateRequest = CertificateFactory.CreateSigningRequest(csrCertificate, randomApp.DomainNames);

                X509Certificate2 newCert = await _keyVault.SigningRequestAsync(
                    group,
                    randomApp.ApplicationRecord.ApplicationUri,
                    certificateRequest);

                // get issuer cert used for signing
                X509Certificate2Collection issuerCerts = await _keyVault.GetIssuerCACertificateChainAsync(group);

#if WRITECERT
                // save cert for debugging
                using (ICertificateStore store = CertificateStoreIdentifier.CreateStore(CertificateStoreType.Directory))
                {
                    Assert.NotNull(store);
                    store.Open("d:\\unittest");
                    await store.Add(newCert);

                    foreach (var cert in issuerCerts)
                    {
                        await store.Add(cert);
                    }
                }
#endif
                Assert.NotNull(issuerCerts);
                Assert.True(issuerCerts.Count >= 1);
                X509TestUtils.VerifySignedApplicationCert(randomApp, newCert, issuerCerts);
                certCollection.Add(newCert);
            }
            return(certCollection);
        }
Пример #16
0
        public void UpdateCertificateSelfSigned(string keyFormat)
        {
            ConnectPushClient(true);
            var keyFormats = _pushClient.PushClient.GetSupportedKeyFormats();

            if (!keyFormats.Contains(keyFormat))
            {
                Assert.Ignore("Push server doesn't support {0} key update", keyFormat);
            }

            X509Certificate2 newCert = CertificateFactory.CreateCertificate(
                null,
                null,
                null,
                _applicationRecord.ApplicationUri,
                _applicationRecord.ApplicationNames[0].Text,
                _selfSignedServerCert.Subject,
                null,
                CertificateFactory.defaultKeySize,
                DateTime.UtcNow,
                CertificateFactory.defaultLifeTime,
                CertificateFactory.defaultHashSize);

            byte[] privateKey = null;
            if (keyFormat == "PFX")
            {
                Assert.IsTrue(newCert.HasPrivateKey);
                privateKey = newCert.Export(X509ContentType.Pfx);
            }
            else if (keyFormat == "PEM")
            {
                Assert.IsTrue(newCert.HasPrivateKey);
                privateKey = CertificateFactory.ExportPrivateKeyAsPEM(newCert);
            }
            else
            {
                Assert.Fail("Testing unsupported key format {0}.", keyFormat);
            }

            var success = _pushClient.PushClient.UpdateCertificate(
                _pushClient.PushClient.DefaultApplicationGroup,
                _pushClient.PushClient.ApplicationCertificateType,
                newCert.RawData,
                keyFormat,
                privateKey,
                null);

            if (success)
            {
                _pushClient.PushClient.ApplyChanges();
            }
            VerifyNewPushServerCert(newCert.RawData);
        }
Пример #17
0
        public async Task SigningRequestAllApplications()
        {
            Skip.If(!_fixture.RegistrationOk);
            var count = 0;

            foreach (var application in _applicationTestSet)
            {
                var groups = await _groupRegistry.ListGroupIdsAsync();

                foreach (var group in groups.Groups)
                {
                    var applicationId = application.Model.ApplicationId;
                    var certificateGroupConfiguration = await _groupRegistry.GetGroupAsync(group);

                    var csrCertificate = CertificateFactory.CreateCertificate(
                        null, null, null,
                        application.ApplicationRecord.ApplicationUri,
                        null,
                        application.Subject,
                        application.DomainNames.ToArray(),
                        /* certificateGroupConfiguration.Policy.IssuedKeySize ?? */ 2048,
                        DateTime.UtcNow.AddDays(-20), 1, 256);
                    //  certificateGroupConfiguration.Policy.IssuedLifetime,
                    //certificateGroupConfiguration.Policy.IssuedSignatureAlgorithm
                    // );
                    var csr = CertificateFactory.CreateSigningRequest(
                        csrCertificate,
                        application.DomainNames);
                    var requestId = await _ca.StartSigningRequestAsync(new StartSigningRequestModel {
                        EntityId           = applicationId,
                        GroupId            = group,
                        CertificateRequest = csr,
                    }, "*****@*****.**");

                    Assert.NotNull(requestId);
                    // read request
                    var request = await _requests.GetRequestAsync(requestId);

                    Assert.Equal(CertificateRequestState.New, request.State);
                    Assert.True(request.SigningRequest);
                    Assert.Equal(requestId, request.RequestId);
                    Assert.Equal(applicationId, request.ApplicationId);
                    Assert.Null(request.SubjectName);
                    Assert.Equal(group, request.GroupId);
                    //Assert.Equal(null, fullRequest.CertificateType);
                    //Assert.Equal(application.DomainNames.ToArray(), fullRequest.DomainNames);
                    // add to list
                    application.RequestIds.Add(requestId);
                    count++;
                }
            }
            Assert.True(count > 0);
        }
Пример #18
0
        // Create a certificate store for the Akri Broker
        static void CreateClientCertificate(string storeType, string storePath, X509Certificate2 caCert, string caStorePath)
        {
            Console.WriteLine("Creating a certificate for the Akri Broker");
            ushort   keySize          = 2048;
            DateTime startTime        = DateTime.UtcNow - TimeSpan.FromDays(1);
            ushort   lifetimeInMonths = 6;
            ushort   hashSizeInBits   = CertificateFactory.DefaultHashSize;
            bool     isCA             = false;
            string   applicationUri   = "urn:AkriBroker";
            string   applicationName  = "AkriBroker";
            string   clientStorePath  = Path.Combine(storePath, applicationName);

            CertificateFactory.CreateCertificate(storeType, clientStorePath, null, applicationUri, applicationName, null, null, keySize, startTime, lifetimeInMonths, hashSizeInBits, isCA, caCert);
            RearrangeCertificateStore(clientStorePath, caStorePath);
        }
Пример #19
0
        // Create a CA cert
        static X509Certificate2 CreateCACert(string storeType, string storePath)
        {
            string applicationUri  = "urn:SomeCA";
            string applicationName = "SomeCA";

            Console.WriteLine("Creating a CA with name " + applicationName);
            ushort           keySize                  = 2048;
            DateTime         startTime                = DateTime.UtcNow - TimeSpan.FromDays(1);
            ushort           lifetimeInMonths         = 6;
            ushort           hashSizeInBits           = CertificateFactory.DefaultHashSize;
            bool             isCA                     = true;
            X509Certificate2 certificateAuthorityCert = CertificateFactory.CreateCertificate(storeType, storePath, null, applicationUri, applicationName, null, null, keySize, startTime, lifetimeInMonths, hashSizeInBits, isCA, null);

            return(certificateAuthorityCert);
        }
Пример #20
0
        // Create a certificate store for a Server
        static void CreateServerCertificate(string storeType, string storePath, X509Certificate2 caCert, string caStorePath, int serverNumber, string ipAddress)
        {
            ushort         keySize          = 2048;
            DateTime       startTime        = DateTime.UtcNow - TimeSpan.FromDays(1);
            ushort         lifetimeInMonths = 6;
            ushort         hashSizeInBits   = CertificateFactory.DefaultHashSize;
            bool           isCA             = false;
            IList <String> domainNames      = new[] { ipAddress };
            string         applicationUri   = "urn:SomeServer" + serverNumber;
            string         applicationName  = "SomeServer" + serverNumber;
            string         serverStorePath  = Path.Combine(storePath, applicationName);

            Console.WriteLine("Creating a certificate for server {0} with IP address {1}", applicationName, ipAddress);
            X509Certificate2 certificateAuthorityCert = CertificateFactory.CreateCertificate(storeType, serverStorePath, null, applicationUri, applicationName, null, domainNames, keySize, startTime, lifetimeInMonths, hashSizeInBits, isCA, caCert);

            RearrangeCertificateStore(serverStorePath, caStorePath);
        }
        private X509Certificate2 CreateCertificateIn(StoreName storeName, StoreLocation storeLocation)
        {
            var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);

            store.Open(OpenFlags.ReadWrite);
            var certificate = CertificateFactory.CreateCertificate();

            store.Add(certificate);

            RegisterDisposable(() =>
            {
                store.Remove(certificate);
                store.Close();
            });

            return(certificate);
        }
Пример #22
0
        /// <summary>
        /// Creates the application instance certificate.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        /// <param name="keySize">Size of the key.</param>
        /// <param name="lifetimeInMonths">The lifetime in months.</param>
        /// <returns>The new certificate</returns>
        private static X509Certificate2 CreateApplicationInstanceCertificate(
            ApplicationConfiguration configuration,
            ushort keySize,
            ushort lifetimeInMonths)
        {
            Utils.Trace(Utils.TraceMasks.Information, "Creating application instance certificate. KeySize={0}, Lifetime={1}", keySize, lifetimeInMonths);

            // Delete existing certificate
            DeleteApplicationInstanceCertificate(configuration);

            CertificateIdentifier id = configuration.SecurityConfiguration.ApplicationCertificate;

            // Get the domains from the configuration file.
            IList <string> serverDomainNames = configuration.GetServerDomainNames();

            if (serverDomainNames.Count == 0)
            {
                GetLocalIpAddressAndDns().ForEach(x => serverDomainNames.Add(x));
            }

            // ensure the certificate store directory exists.
            if (id.StoreType == CertificateStoreType.Directory)
            {
                Utils.GetAbsoluteDirectoryPath(id.StorePath, true, true, true);
            }

            X509Certificate2 certificate = CertificateFactory.CreateCertificate(
                id.StoreType,
                id.StorePath,
                configuration.ApplicationUri,
                configuration.ApplicationName,
                null,
                serverDomainNames,
                keySize,
                lifetimeInMonths);

            id.Certificate = certificate;
            AddToTrustedStore(configuration, certificate);

            configuration.CertificateValidator.Update(configuration.SecurityConfiguration);

            Utils.Trace(Utils.TraceMasks.Information, "Certificate created. Thumbprint={0}", certificate.Thumbprint);

            // reload the certificate from disk.
            return(configuration.SecurityConfiguration.ApplicationCertificate.LoadPrivateKey(null));
        }
        /// <summary>
        /// Create issuer CA cert and default Crl offline, then import in KeyVault.
        /// Note: Sample only for reference, importing the private key is unsecure!
        /// </summary>
        public async Task <bool> CreateImportedIssuerCACertificateAsync()
        {
            await _semaphoreSlim.WaitAsync();

            try
            {
                DateTime notBefore = TrimmedNotBeforeDate();
                using (var caCert = CertificateFactory.CreateCertificate(
                           null,
                           null,
                           null,
                           null,
                           null,
                           Configuration.SubjectName,
                           null,
                           Configuration.CACertificateKeySize,
                           notBefore,
                           Configuration.CACertificateLifetime,
                           Configuration.CACertificateHashSize,
                           true,
                           null,
                           null))
                {
                    // save only public key
                    Certificate = new X509Certificate2(caCert.RawData);

                    // initialize revocation list
                    Crl = CertificateFactory.RevokeCertificate(caCert, null, null);
                    if (Crl == null)
                    {
                        return(false);
                    }

                    // upload ca cert with private key
                    await _keyVaultServiceClient.ImportIssuerCACertificate(Configuration.Id, new X509Certificate2Collection(caCert), true).ConfigureAwait(false);

                    await _keyVaultServiceClient.ImportIssuerCACrl(Configuration.Id, Certificate, Crl).ConfigureAwait(false);
                }
                return(true);
            }
            finally
            {
                _semaphoreSlim.Release();
            }
        }
Пример #24
0
        /// <summary>
        /// Create a certificate with a new key pair signed by the CA of the cert group.
        /// </summary>
        /// <param name="application">The application record.</param>
        /// <param name="subjectName">The subject of the certificate.</param>
        /// <param name="domainNames">The domain names for the subject alt name extension.</param>
        /// <param name="privateKeyFormat">The private key format as PFX or PEM.</param>
        /// <param name="privateKeyPassword">A password for the private key.</param>
        public virtual async Task <X509Certificate2KeyPair> NewKeyPairRequestAsync(
            ApplicationRecordDataType application,
            string subjectName,
            string[] domainNames,
            string privateKeyFormat,
            string privateKeyPassword)
        {
            if (application == null)
            {
                throw new ArgumentNullException(nameof(application));
            }
            if (application.ApplicationUri == null)
            {
                throw new ArgumentNullException(nameof(application.ApplicationUri));
            }
            if (application.ApplicationNames == null)
            {
                throw new ArgumentNullException(nameof(application.ApplicationNames));
            }

            using (var signingKey = await LoadSigningKeyAsync(Certificate, string.Empty).ConfigureAwait(false))
                using (var certificate = CertificateFactory.CreateCertificate(
                           application.ApplicationUri,
                           application.ApplicationNames.Count > 0 ? application.ApplicationNames[0].Text : "ApplicationName",
                           subjectName,
                           domainNames)
                                         .SetIssuer(signingKey)
                                         .CreateForRSA())
                {
                    byte[] privateKey;
                    if (privateKeyFormat == "PFX")
                    {
                        privateKey = certificate.Export(X509ContentType.Pfx, privateKeyPassword);
                    }
                    else if (privateKeyFormat == "PEM")
                    {
                        privateKey = PEMWriter.ExportPrivateKeyAsPEM(certificate, privateKeyPassword);
                    }
                    else
                    {
                        throw new ServiceResultException(StatusCodes.BadInvalidArgument, "Invalid private key format");
                    }
                    return(new X509Certificate2KeyPair(new X509Certificate2(certificate.RawData), privateKeyFormat, privateKey));
                }
        }
Пример #25
0
        /// <summary>
        /// Create CA test certificates.
        /// </summary>
        private async Task CreateCATestCerts(string tempStorePath)
        {
            Assert.IsTrue(EraseStore(tempStorePath));

            string           subjectName = "CN=CA Test Cert, O=OPC Foundation";
            X509Certificate2 newCACert   = CertificateFactory.CreateCertificate(
                null, null, subjectName, null)
                                           .SetCAConstraint()
                                           .CreateForRSA()
                                           .AddToStore(CertificateStoreType.Directory, tempStorePath);

            _caCert = newCACert;

            // initialize cert revocation list (CRL)
            X509CRL newCACrl = await CertificateGroup.RevokeCertificateAsync(tempStorePath, newCACert);

            _caCrl = newCACrl;
        }
Пример #26
0
 /// <summary>
 /// Create client host services
 /// </summary>
 /// <param name="logger"></param>
 /// <param name="maxOpTimeout"></param>
 public ClientServices(ILogger logger, TimeSpan?maxOpTimeout = null)
 {
     _logger = logger ?? throw new ArgumentNullException(nameof(logger));
     // Create discovery config and client certificate
     _maxOpTimeout = maxOpTimeout;
     _config       = CreateApplicationConfiguration(TimeSpan.FromMinutes(2),
                                                    TimeSpan.FromMinutes(2));
     Certificate = CertificateFactory.CreateCertificate(
         _config.SecurityConfiguration.ApplicationCertificate.StoreType,
         _config.SecurityConfiguration.ApplicationCertificate.StorePath, null,
         _config.ApplicationUri, _config.ApplicationName,
         _config.SecurityConfiguration.ApplicationCertificate.SubjectName, null,
         CertificateFactory.defaultKeySize, DateTime.UtcNow - TimeSpan.FromDays(1),
         CertificateFactory.defaultLifeTime, CertificateFactory.defaultHashSize,
         false, null, null);
     _timer = new Timer(_ => OnTimer(), null, kEvictionCheck,
                        Timeout.InfiniteTimeSpan);
 }
Пример #27
0
 public void AddRemoveCert()
 {
     using (X509Certificate2 trustedCert = CertificateFactory.CreateCertificate(null, null, null, "uri:x:y:z", "TrustedCert", "CN=Push Server Test", null, 2048, DateTime.UtcNow, 1, 256))
         using (X509Certificate2 issuerCert = CertificateFactory.CreateCertificate(null, null, null, "uri:x:y:z", "IssuerCert", "CN=Push Server Test", null, 2048, DateTime.UtcNow, 1, 256))
         {
             ConnectPushClient(true);
             TrustListDataType beforeTrustList = _pushClient.PushClient.ReadTrustList();
             _pushClient.PushClient.AddCertificate(trustedCert, true);
             _pushClient.PushClient.AddCertificate(issuerCert, false);
             TrustListDataType afterAddTrustList = _pushClient.PushClient.ReadTrustList();
             Assert.Greater(afterAddTrustList.TrustedCertificates.Count, beforeTrustList.TrustedCertificates.Count);
             Assert.Greater(afterAddTrustList.IssuerCertificates.Count, beforeTrustList.IssuerCertificates.Count);
             Assert.IsFalse(Utils.IsEqual(beforeTrustList, afterAddTrustList));
             _pushClient.PushClient.RemoveCertificate(trustedCert.Thumbprint, true);
             _pushClient.PushClient.RemoveCertificate(issuerCert.Thumbprint, false);
             TrustListDataType afterRemoveTrustList = _pushClient.PushClient.ReadTrustList();
             Assert.IsTrue(Utils.IsEqual(beforeTrustList, afterRemoveTrustList));
         }
 }
        private X509Certificate2 CreateInvalidCert(InvalidCertType certType)
        {
            // reasonable defaults
            DateTime notBefore = DateTime.Today.AddDays(-30);
            DateTime notAfter  = DateTime.Today.AddDays(30);
            ushort   keySize   = CertificateFactory.DefaultKeySize;

            string[] domainNames = new string[] { Utils.GetHostName() };
            switch (certType)
            {
            case InvalidCertType.Expired:
                notBefore = DateTime.Today.AddMonths(-12);
                notAfter  = DateTime.Today.AddDays(-7);
                break;

            case InvalidCertType.NotYetValid:
                notBefore = DateTime.Today.AddDays(7);
                notAfter  = notBefore.AddMonths(12);
                break;

            case InvalidCertType.KeySize1024:
                keySize = 1024;
                break;

            case InvalidCertType.HostName:
                domainNames = new string[] { "myhost", "1.2.3.4" };
                break;

            default:
                break;
            }

            return(CertificateFactory.CreateCertificate(
                       ApplicationUri,
                       ApplicationName,
                       SubjectName,
                       domainNames)
                   .SetNotBefore(notBefore)
                   .SetNotAfter(notAfter)
                   .SetRSAKeySize(keySize)
                   .CreateForRSA());
        }
Пример #29
0
 public void UpdateCertificateSelfSignedNoPrivateKey()
 {
     ConnectPushClient(true);
     using (X509Certificate2 invalidCert = CertificateFactory.CreateCertificate(null, null, null, "uri:x:y:z", "TestApp", "CN=Push Server Test", null, 2048, DateTime.UtcNow, 1, 256))
         using (X509Certificate2 serverCert = new X509Certificate2(_pushClient.PushClient.Session.ConfiguredEndpoint.Description.ServerCertificate))
         {
             if (!Utils.CompareDistinguishedName(serverCert.Subject, serverCert.Issuer))
             {
                 Assert.Ignore("Server has no self signed cert in use.");
             }
             byte[] invalidRawCert = { 0xba, 0xd0, 0xbe, 0xef, 3 };
             // negative test all parameter combinations
             NodeId invalidCertGroup = new NodeId(333);
             NodeId invalidCertType  = new NodeId(Guid.NewGuid());
             Assert.That(() => { _pushClient.PushClient.UpdateCertificate(null, null, null, null, null, null); }, Throws.Exception);
             Assert.That(() => { _pushClient.PushClient.UpdateCertificate(invalidCertGroup, null, serverCert.RawData, null, null, null); }, Throws.Exception);
             Assert.That(() => { _pushClient.PushClient.UpdateCertificate(null, invalidCertType, serverCert.RawData, null, null, null); }, Throws.Exception);
             Assert.That(() => { _pushClient.PushClient.UpdateCertificate(invalidCertGroup, invalidCertType, serverCert.RawData, null, null, null); }, Throws.Exception);
             Assert.That(() => { _pushClient.PushClient.UpdateCertificate(null, null, invalidRawCert, null, null, null); }, Throws.Exception);
             Assert.That(() => { _pushClient.PushClient.UpdateCertificate(null, null, invalidCert.RawData, null, null, null); }, Throws.Exception);
             Assert.That(() => { _pushClient.PushClient.UpdateCertificate(null, null, serverCert.RawData, "XYZ", null, null); }, Throws.Exception);
             Assert.That(() => { _pushClient.PushClient.UpdateCertificate(null, null, serverCert.RawData, "XYZ", invalidCert.RawData, null); }, Throws.Exception);
             Assert.That(() => { _pushClient.PushClient.UpdateCertificate(null, null, invalidCert.RawData, null, null, new byte[][] { serverCert.RawData, invalidCert.RawData }); }, Throws.Exception);
             Assert.That(() => { _pushClient.PushClient.UpdateCertificate(null, null, null, null, null, new byte[][] { serverCert.RawData, invalidCert.RawData }); }, Throws.Exception);
             Assert.That(() => { _pushClient.PushClient.UpdateCertificate(null, null, invalidRawCert, null, null, new byte[][] { serverCert.RawData, invalidCert.RawData }); }, Throws.Exception);
             Assert.That(() => { _pushClient.PushClient.UpdateCertificate(null, null, serverCert.RawData, null, null, new byte[][] { serverCert.RawData, invalidRawCert }); }, Throws.Exception);
             Assert.That(() => { _pushClient.PushClient.UpdateCertificate(null, null, serverCert.RawData, null, null, null); }, Throws.Exception);
             var success = _pushClient.PushClient.UpdateCertificate(
                 null,
                 _pushClient.PushClient.ApplicationCertificateType,
                 serverCert.RawData,
                 null,
                 null,
                 null);
             if (success)
             {
                 _pushClient.PushClient.ApplyChanges();
             }
             VerifyNewPushServerCert(serverCert.RawData);
         }
 }
        public void VerifySelfSignedAppCerts(
            KeyHashPair keyHashPair
            )
        {
            var appTestGenerator    = new ApplicationTestDataGenerator(keyHashPair.KeySize);
            ApplicationTestData app = appTestGenerator.ApplicationTestSet(1).First();
            var cert = CertificateFactory.CreateCertificate(null, null, null,
                                                            app.ApplicationUri, app.ApplicationName, app.Subject,
                                                            app.DomainNames, keyHashPair.KeySize, DateTime.UtcNow,
                                                            CertificateFactory.DefaultLifeTime, keyHashPair.HashSize);

            Assert.NotNull(cert);
            Assert.NotNull(cert.RawData);
            Assert.True(cert.HasPrivateKey);
            var plainCert = new X509Certificate2(cert.RawData);

            Assert.NotNull(plainCert);
            VerifySelfSignedApplicationCert(app, plainCert);
            CertificateFactory.VerifySelfSigned(cert);
            CertificateFactory.VerifyRSAKeyPair(cert, cert);
        }