Example #1
0
        public void X509CertificateCreationParametersDefaultPropertiesTest()
        {
            X500DistinguishedName dn = new X500DistinguishedName("CN=Test");

            DateTime preCreationTime = DateTime.UtcNow;
            X509CertificateCreationParameters creationParams = new X509CertificateCreationParameters(dn);
            DateTime postCreationTime = DateTime.UtcNow;

            Assert.AreEqual(dn.Name, creationParams.SubjectName.Name);
            Assert.AreEqual(X509CertificateCreationOptions.None, creationParams.CertificateCreationOptions);
            Assert.AreEqual(X509CertificateSignatureAlgorithm.RsaSha1, creationParams.SignatureAlgorithm);

            // The cert should be valid for 1 year (allowing for leap years, so 366 days could be valid as well)
            int validDays = (creationParams.EndTime - creationParams.StartTime).Days;

            Assert.IsTrue(validDays == 365 || validDays == 366);

            // In theory we could have rolled over a day while since the parameters were created, so we'll
            // accept either the date before or after the parameters were created
            Assert.IsTrue(creationParams.StartTime.Day == preCreationTime.Day ||
                          creationParams.StartTime.Day == postCreationTime.Day);
            Assert.IsTrue(creationParams.StartTime.Month == preCreationTime.Month ||
                          creationParams.StartTime.Month == postCreationTime.Month);
            Assert.IsTrue(creationParams.StartTime.Year == preCreationTime.Year ||
                          creationParams.StartTime.Year == postCreationTime.Year);

            Assert.AreEqual(0, creationParams.Extensions.Count);

            Assert.IsTrue(creationParams.TakeOwnershipOfKey);
        }
Example #2
0
        public void X509CertificateCreationParametersPropertiesTest()
        {
            X500DistinguishedName             dn             = new X500DistinguishedName("CN=Test");
            X509CertificateCreationParameters creationParams = new X509CertificateCreationParameters(dn);

            creationParams.SubjectName = new X500DistinguishedName("CN=Test2");
            Assert.AreEqual(new X500DistinguishedName("CN=Test2").Name, creationParams.SubjectName.Name);

            creationParams.CertificateCreationOptions = X509CertificateCreationOptions.DoNotLinkKeyInformation |
                                                        X509CertificateCreationOptions.DoNotSignCertificate;
            Assert.AreEqual(X509CertificateCreationOptions.DoNotLinkKeyInformation | X509CertificateCreationOptions.DoNotSignCertificate,
                            creationParams.CertificateCreationOptions);

            DateTime newStart = new DateTime(2006, 08, 12);

            creationParams.StartTime = newStart;
            Assert.AreEqual(newStart, creationParams.StartTime);

            DateTime newEnd = new DateTime(2008, 09, 15);

            creationParams.EndTime = newEnd;
            Assert.AreEqual(newEnd, creationParams.EndTime);

            creationParams.SignatureAlgorithm = X509CertificateSignatureAlgorithm.RsaSha256;
            Assert.AreEqual(X509CertificateSignatureAlgorithm.RsaSha256, creationParams.SignatureAlgorithm);

            X509KeyUsageExtension keyUsage = new X509KeyUsageExtension(X509KeyUsageFlags.KeyAgreement, true);

            creationParams.Extensions.Add(keyUsage);

            Assert.AreEqual(1, creationParams.Extensions.Count);
            Assert.IsInstanceOfType(creationParams.Extensions[0], typeof(X509KeyUsageExtension));
            Assert.AreEqual(X509KeyUsageFlags.KeyAgreement,
                            ((X509KeyUsageExtension)creationParams.Extensions[0]).KeyUsages);
        }
Example #3
0
        public void X509CertificateCreationParametersSetNullNameTest()
        {
            X500DistinguishedName             name           = new X500DistinguishedName("CN=");
            X509CertificateCreationParameters creationParams = new X509CertificateCreationParameters(name);

            creationParams.SubjectName = null;
        }
Example #4
0
        private void WritePrivateKey()
        {
            if (false == Options.ExportPrivateKey)
            {
                return;
            }

            var creationParams =
                new X509CertificateCreationParameters(new X500DistinguishedName("CN=" + Key.KeyName))
            {
                CertificateCreationOptions = X509CertificateCreationOptions.None,
                SignatureAlgorithm         = X509CertificateSignatureAlgorithm.ECDsaSha512,
                TakeOwnershipOfKey         = false,
                EndTime = DateTime.Now.AddDays(Options.ExpiryDays)
            };

            var cert = Key.CreateSelfSignedCertificate(creationParams);

            byte[] pfx = string.IsNullOrEmpty(Options.Password) ?
                         cert.Export(X509ContentType.Pfx) :
                         cert.Export(X509ContentType.Pfx, Options.Password);

            using (var fs = File.OpenWrite(Options.KeyName + ".key.pfx"))
            {
                fs.Write(pfx, 0, pfx.Length);
            }
        }
Example #5
0
        public void CreateECDsaCertificate()
        {
            byte[] pfx = null;

            CngKeyCreationParameters keyCreationParameters = new CngKeyCreationParameters();

            keyCreationParameters.ExportPolicy = CngExportPolicies.AllowExport;
            keyCreationParameters.KeyUsage     = CngKeyUsages.Signing;

            using (CngKey key = CngKey.Create(CngAlgorithm.ECDsaP256, null, keyCreationParameters))
            {
                X509CertificateCreationParameters creationParams = new X509CertificateCreationParameters(new X500DistinguishedName("CN=TestECDSACert"));
                creationParams.SignatureAlgorithm = X509CertificateSignatureAlgorithm.ECDsaSha256;

                X509Certificate2 cert = key.CreateSelfSignedCertificate(creationParams);
                pfx = cert.Export(X509ContentType.Pfx, "TestPassword");

                Assert.IsTrue(cert.HasPrivateKey);
                Assert.IsTrue(cert.HasCngKey());
            }

            X509Certificate2 rtCert = new X509Certificate2(pfx, "TestPassword");

            Assert.IsTrue(rtCert.HasPrivateKey);
            Assert.IsTrue(rtCert.HasCngKey());

            using (CngKey rtKey = rtCert.GetCngPrivateKey())
            {
                Assert.AreEqual(CngAlgorithmGroup.ECDsa, rtKey.AlgorithmGroup);
                Assert.AreEqual(256, rtKey.KeySize);
            }
        }
Example #6
0
        /// <summary>
        ///     Method to generate a self signed certificate
        /// </summary>
        /// <param name="validForHours">number of hours for which the certificate is valid.</param>
        /// <param name="subscriptionId">subscriptionId in question</param>
        /// <param name="certificateNamePrefix">prefix for the certificate name</param>
        /// <param name="issuer">issuer for the certificate</param>
        /// <param name="password">certificate password</param>
        /// <returns>certificate as an object</returns>
        public static X509Certificate2 CreateSelfSignedCertificate(
            int validForHours,
            string subscriptionId,
            string certificateNamePrefix,
            string issuer   = DefaultIssuer,
            string password = DefaultPassword)
        {
            var friendlyName = GenerateCertFriendlyName(
                subscriptionId,
                certificateNamePrefix);
            var startTime = DateTime.UtcNow.AddMinutes(-10);
            var endTime   = DateTime.UtcNow.AddHours(validForHours);

            var key = Create2048RsaKey();

            var creationParams =
                new X509CertificateCreationParameters(new X500DistinguishedName(issuer))
            {
                TakeOwnershipOfKey = true,
                StartTime          = startTime,
                EndTime            = endTime
            };

            //// adding client authentication, -eku = 1.3.6.1.5.5.7.3.2,
            //// This is mandatory for the upload to be successful
            var oidCollection = new OidCollection();

            oidCollection.Add(
                new Oid(
                    OIDClientAuthValue,
                    OIDClientAuthFriendlyName));
            creationParams.Extensions.Add(
                new X509EnhancedKeyUsageExtension(
                    oidCollection,
                    false));

            // Documentation of CreateSelfSignedCertificate states:
            // If creationParameters have TakeOwnershipOfKey set to true, the certificate
            // generated will own the key and the input CngKey will be disposed to ensure
            // that the caller doesn't accidentally use it beyond its lifetime (which is
            // now controlled by the certificate object).
            // We don't dispose it ourselves in this case.
            var cert = key.CreateSelfSignedCertificate(creationParams);

            key = null;
            cert.FriendlyName = friendlyName;

            // X509 certificate needs PersistKeySet flag set.
            // Reload a new X509Certificate2 instance from exported bytes in order to set the PersistKeySet flag.
            var bytes = cert.Export(
                X509ContentType.Pfx,
                password);

            // PfxValidation is not done here because these are newly created certs and assumed valid.
            return(NewX509Certificate2(
                       bytes,
                       password,
                       X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable,
                       false));
        }
        public static X509Certificate2 CreateCertificate(string password, string issuer = "CN=Microsoft Azure Powershell Test", string friendlyName = "PSTest")
        {
            var keyCreationParameters = new CngKeyCreationParameters
            {
                ExportPolicy       = CngExportPolicies.AllowExport,
                KeyCreationOptions = CngKeyCreationOptions.None,
                KeyUsage           = CngKeyUsages.AllUsages,
                Provider           = CngProvider.MicrosoftSoftwareKeyStorageProvider
            };

            keyCreationParameters.Parameters.Add(new CngProperty("Length", BitConverter.GetBytes(2048), CngPropertyOptions.None));

            CngKey key = CngKey.Create(CngAlgorithm2.Rsa, null, keyCreationParameters);

            var creationParams = new X509CertificateCreationParameters(new X500DistinguishedName(issuer))
            {
                TakeOwnershipOfKey = true
            };

            X509Certificate2 cert = key.CreateSelfSignedCertificate(creationParams);

            key = null;
            cert.FriendlyName = friendlyName;

            byte[]           bytes      = cert.Export(X509ContentType.Pfx, password);
            X509Certificate2 returnCert = new X509Certificate2();

            returnCert.Import(bytes, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
            return(returnCert);
        }
Example #8
0
        public static X509Certificate2 CreateSelfSignedCertificate(this CngKey key,
                                                                   X509CertificateCreationParameters creationParameters)
        {
            if (creationParameters == null)
            {
                throw new ArgumentNullException("creationParameters");
            }

            // If we are not being asked to hand ownership of the key over to the certificate, then we need
            // ensure that we are running in a trusted context as we have no way to ensure that the caller
            // will not force the key to be cleaned up and then continue to use the dangling handle left in
            // the certificate.
            if (!creationParameters.TakeOwnershipOfKey)
            {
                new PermissionSet(PermissionState.Unrestricted).Demand();
            }

            using (SafeCertContextHandle selfSignedCertHandle =
                       X509Native.CreateSelfSignedCertificate(key,
                                                              creationParameters.TakeOwnershipOfKey,
                                                              creationParameters.SubjectName.RawData,
                                                              creationParameters.CertificateCreationOptions,
                                                              X509Native.MapCertificateSignatureAlgorithm(creationParameters.SignatureAlgorithm),
                                                              creationParameters.StartTime,
                                                              creationParameters.EndTime,
                                                              creationParameters.ExtensionsNoDemand))
            {
                // We need to get the raw handle out of the safe handle because X509Certificate2 only
                // exposes an IntPtr constructor.  To do that we'll temporarially bump the ref count on
                // the handle.
                //
                // X509Certificate2 will duplicate the handle value in the .ctor, so once we've created
                // the certificate object, we can safely drop the ref count and dispose of our handle.
                X509Certificate2 certificate = null;
                bool             addedRef    = false;
                RuntimeHelpers.PrepareConstrainedRegions();
                try
                {
                    selfSignedCertHandle.DangerousAddRef(ref addedRef);
                    certificate = new X509Certificate2(selfSignedCertHandle.DangerousGetHandle());
                }
                finally
                {
                    if (addedRef)
                    {
                        selfSignedCertHandle.DangerousRelease();
                    }
                }

                // If we passed ownership of the key to the certificate, than destroy the key
                // now so that we don't continue to use it beyond the liftime of the cert.
                if (creationParameters.TakeOwnershipOfKey)
                {
                    key.Dispose();
                }

                return(certificate);
            }
        }
        /// <summary>
        ///     <para>
        ///         CreateSelfSignedCertificate creates a new self signed certificate issued to the specified
        ///         subject. The certificate will contain the key used to create the self signed certificate.
        ///         Since the certificate needs to be signed, the CngKey used must be usable for signing, which
        ///         means it must also contain a private key. If there is no private key, the operation will fail
        ///         with a CryptographicException indicating that "The key does not exist."
        ///     </para>
        ///     <para>
        ///         This overload creates a certificate which does take ownership of the underlying key - which
        ///         means that the input CngKey will be disposed before this method exits and should no longer
        ///         be used by the caller.
        ///     </para>
        /// </summary>
        /// <param name="key">key to wrap in a self signed certificate</param>
        /// <param name="subjectName">the name of hte subject the self-signed certificate will be issued to</param>
        /// <exception cref="ArgumentNullException">if <paramref name="subjectName" /> is null</exception>
        /// <exception cref="CryptographicException">if the certificate cannot be created</exception>
        public static X509Certificate2 CreateSelfSignedCertificate(this CngKey key,
                                                                   X500DistinguishedName subjectName)
        {
            X509CertificateCreationParameters creationParameters = new X509CertificateCreationParameters(subjectName);

            creationParameters.TakeOwnershipOfKey = true;
            return(CreateSelfSignedCertificate(key, creationParameters));
        }
        public X509Certificate2 CreateNamedKeyCertificate(CertData data)
        {
            try
            {
                CngKeyCreationParameters keyCreationParameters
                    = new CngKeyCreationParameters
                    {
                    ExportPolicy =
                        CngExportPolicies.AllowExport |
                        CngExportPolicies.AllowPlaintextExport |
                        CngExportPolicies.AllowPlaintextArchiving |
                        CngExportPolicies.AllowArchiving,
                    KeyUsage = CngKeyUsages.AllUsages
                    };

                X509Certificate2 cert;
                X509CertificateCreationParameters configCreate
                    = new X509CertificateCreationParameters(new X500DistinguishedName(data.DistinguishedName))
                    {
                    EndTime =
                        DateTime.Parse("01/01/2020",
                                       System.Globalization.
                                       DateTimeFormatInfo.
                                       InvariantInfo),
                    StartTime =
                        DateTime.Parse("01/01/2010",
                                       System.Globalization.
                                       DateTimeFormatInfo.
                                       InvariantInfo)
                    };

                using (CngKey namedKey = CngKey.Create(CngAlgorithm2.Rsa, data.Key, keyCreationParameters))
                {
                    cert = namedKey.CreateSelfSignedCertificate(configCreate);
                    cert.FriendlyName = data.Friendlyname;
                    Assert.True(cert.HasPrivateKey);
                    Assert.True(cert.HasCngKey());
                    using (CngKey certKey = cert.GetCngPrivateKey())
                    {
                        Assert.Equal(CngAlgorithm2.Rsa, certKey.Algorithm);
                    }
                }
                return(cert);
            }
            finally
            {
                if (CngKey.Exists(data.Key))
                {
                    using (CngKey key = CngKey.Open(data.Key))
                    {
                        key.Delete();
                    }
                }
            }
        }
Example #11
0
        private X509Certificate2 _GetSelfSignedCert(string subjectName)
        {
            var keyParam = new CngKeyCreationParameters
            {
                ExportPolicy       = CngExportPolicies.AllowExport,
                KeyCreationOptions = CngKeyCreationOptions.MachineKey | CngKeyCreationOptions.OverwriteExistingKey,
                KeyUsage           = CngKeyUsages.AllUsages,
                Provider           = CngProvider.MicrosoftSoftwareKeyStorageProvider,
            };

            keyParam.Parameters.Add(new CngProperty("Length", BitConverter.GetBytes(2048), CngPropertyOptions.None));

            CngKey key;

            try
            {
                key = CngKey.Create(CngAlgorithm2.Rsa, Guid.NewGuid().ToString(), keyParam);
            }
            catch (PlatformNotSupportedException)
            {
                try
                {
                    key = CngKey.Create(CngAlgorithm2.Aes, Guid.NewGuid().ToString(), keyParam);
                }
                catch (PlatformNotSupportedException)
                {
                    return(null);
                }
            }

            X509CertificateCreationParameters param = new X509CertificateCreationParameters(new X500DistinguishedName(subjectName))
            {
                SubjectName = new X500DistinguishedName(subjectName),
                EndTime     = DateTime.Today.AddYears(20) //,SignatureAlgorithm = X509CertificateSignatureAlgorithm.RsaSha512
            };

            OidCollection oc = new OidCollection {
                new Oid("1.3.6.1.5.5.7.3.1")
            };
            X509Extension eku = new X509EnhancedKeyUsageExtension(oc, true);

            param.Extensions.Add(eku);

            param.TakeOwnershipOfKey = true;

            byte[] rawData = key.CreateSelfSignedCertificate(param).Export(X509ContentType.Pfx, "");
            var    cert    = new X509Certificate2(rawData, "", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet)
            {
                FriendlyName = _RuleName + " Server Certificate"
            };

            return(cert);
        }
        public void OpenSubscriber()
        {
            try
            {
                if (IsListening())
                {
                    return;
                }

                log.InfoFormat("Opening subscriber endpoint at {0}", netTcpAddress);

                log.InfoFormat("Opening http subscriber endpoint at {0}", httpAddress);

                NotificationSubscriber notificationSubscriber = new NotificationSubscriber();
                notificationSubscriber.IndicationReceived += OnIndication;

                CngKeyCreationParameters keyCreationParameters = new CngKeyCreationParameters();
                keyCreationParameters.ExportPolicy = CngExportPolicies.AllowExport | CngExportPolicies.AllowPlaintextExport | CngExportPolicies.AllowPlaintextArchiving | CngExportPolicies.AllowArchiving;
                keyCreationParameters.KeyUsage     = CngKeyUsages.AllUsages;

                X509CertificateCreationParameters configCreate = new X509CertificateCreationParameters(new X500DistinguishedName("CN=SolarWinds-SwqlStudio"));
                configCreate.EndTime   = DateTime.Now.AddYears(1);
                configCreate.StartTime = DateTime.Now;

                using (CngKey cngKey = CngKey.Create(CngAlgorithm2.Rsa))
                {
                    X509Certificate2 certificate = cngKey.CreateSelfSignedCertificate(configCreate);
                    ServiceHost      host        = new ServiceHost(notificationSubscriber, new Uri(netTcpAddress), new Uri(httpAddress));
                    host.Credentials.ServiceCertificate.Certificate = certificate;
                    // SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectDistinguishedName, "CN=SolarWinds-Orion");
                    host.Open();
                    subscriberHosts.Add(host);
                }

                log.Info("Http Subscriber endpoint opened");
            }
            catch (Exception ex)
            {
                log.ErrorFormat("Exception opening subscriber host with address {0}.\n{1}", httpAddress, ex);
            }

            foreach (ServiceHost serviceHost in subscriberHosts)
            {
                foreach (ChannelDispatcherBase channelDispatcher in serviceHost.ChannelDispatchers)
                {
                    log.InfoFormat("Listening on {0}", channelDispatcher.Listener.Uri.AbsoluteUri);
                }
            }

            ListenerOpened?.Invoke();
        }
Example #13
0
        /// <summary>
        /// This will load Certificate and private key for the server from a file. If File doesn't exist a dummy file will be created.
        /// </summary>
        private void LoadCertificateAndPrivatekeyFromFile(String certfile = "ServerCert.der", String privkeyfile = "ServerKey.pem")
        {
            try
            {
                // Try to load existing (public key) and associated private key
                this.appCertificate  = new X509Certificate2(certfile);
                this.cryptPrivateKey = new RSACryptoServiceProvider();

                var rsaPrivParams = UASecurity.ImportRSAPrivateKey(File.ReadAllText(privkeyfile));
                this.cryptPrivateKey.ImportParameters(rsaPrivParams);
            }
            catch
            {
                // If existing certificate could not be loaded:
                // Make a new certificate (public key) and associated private key
                var dn = new X500DistinguishedName("CN=Client certificate;OU=Demo organization", X500DistinguishedNameFlags.UseSemicolons);

                var keyCreationParameters = new CngKeyCreationParameters()
                {
                    KeyUsage           = CngKeyUsages.AllUsages,
                    KeyCreationOptions = CngKeyCreationOptions.OverwriteExistingKey,
                    ExportPolicy       = CngExportPolicies.AllowPlaintextExport
                };

                keyCreationParameters.Parameters.Add(new CngProperty("Length", BitConverter.GetBytes(1024), CngPropertyOptions.None));
                var cngKey = CngKey.Create(CngAlgorithm2.Rsa, "KeyName", keyCreationParameters);

                var certParams = new X509CertificateCreationParameters(dn)
                {
                    StartTime          = DateTime.Now,
                    EndTime            = DateTime.Now.AddYears(10),
                    SignatureAlgorithm = X509CertificateSignatureAlgorithm.RsaSha1,
                    TakeOwnershipOfKey = true
                };

                appCertificate = cngKey.CreateSelfSignedCertificate(certParams);

                var certPrivateCNG    = new RSACng(appCertificate.GetCngPrivateKey());
                var certPrivateParams = certPrivateCNG.ExportParameters(true);

                File.WriteAllText(certfile, UASecurity.ExportPEM(appCertificate));
                File.WriteAllText(privkeyfile, UASecurity.ExportRSAPrivateKey(certPrivateParams));

                cryptPrivateKey = new RSACryptoServiceProvider();
                cryptPrivateKey.ImportParameters(certPrivateParams);
            }
        }
Example #14
0
        public void GetCngPrivateKeyTest()
        {
            // The known Microsoft cert does not have a CNG private key
            Assert.IsNull(s_microsoftCert.GetCngPrivateKey());

            const string keyName = "Microsoft.Security.Cryptography.X509Certificates.Test.X509Certificate2Tests.GetCngPrivateKeyTest.RSA1";

            try
            {
                // Create a cert for a persisted CNG key
                CngKeyCreationParameters keyCreationParams = new CngKeyCreationParameters();
                keyCreationParams.ExportPolicy = CngExportPolicies.AllowExport | CngExportPolicies.AllowPlaintextExport;
                using (CngKey key = CngKey.Create(CngAlgorithm2.Rsa, keyName, keyCreationParams))
                {
                    X509CertificateCreationParameters creationParams =
                        new X509CertificateCreationParameters(new X500DistinguishedName("CN=CngCert"));
                    creationParams.CertificateCreationOptions = X509CertificateCreationOptions.None;
                    creationParams.TakeOwnershipOfKey         = false;

                    // A CNG certificate using a named key which is linked to the cert itself should return true
                    X509Certificate2 cngFullCert = key.CreateSelfSignedCertificate(creationParams);
                    using (CngKey certKey = cngFullCert.GetCngPrivateKey())
                    {
                        Assert.AreEqual(keyName, certKey.KeyName);
                    }

                    // Create a cert with just the public key - there should be no access to the private key
                    byte[]           publicCertData = cngFullCert.Export(X509ContentType.Cert);
                    X509Certificate2 cngPublicCert  = new X509Certificate2(publicCertData);
                    Assert.IsFalse(cngPublicCert.HasPrivateKey);
                    Assert.IsNull(cngPublicCert.GetCngPrivateKey());

                    key.Delete();
                }
            }
            finally
            {
                // Make sure to delete the persisted key so we're clean for the next run.
                if (CngKey.Exists(keyName))
                {
                    using (CngKey key = CngKey.Open(keyName))
                    {
                        key.Delete();
                    }
                }
            }
        }
Example #15
0
        public void HasCngKeyTestCngCertTest()
        {
            const string keyName = "Microsoft.Security.Cryptography.X509Certificates.Test.X509Certificate2Tests.HasCngKeyTest.RSA1";

            try
            {
                // Create a cert for a persisted CNG key
                CngKeyCreationParameters keyCreationParams = new CngKeyCreationParameters();
                keyCreationParams.ExportPolicy = CngExportPolicies.AllowExport | CngExportPolicies.AllowPlaintextExport;
                using (CngKey key = CngKey.Create(CngAlgorithm2.Rsa, keyName, keyCreationParams))
                {
                    X509CertificateCreationParameters creationParams =
                        new X509CertificateCreationParameters(new X500DistinguishedName("CN=CngCert"));
                    creationParams.CertificateCreationOptions = X509CertificateCreationOptions.None;
                    creationParams.TakeOwnershipOfKey         = false;

                    // A CNG certificate using a named key which is linked to the cert itself should return true
                    X509Certificate2 cngCert = key.CreateSelfSignedCertificate(creationParams);
                    Assert.IsTrue(cngCert.HasCngKey());

                    // A CNG cert exported and then re-imported should also return true
                    byte[]           pfx           = cngCert.Export(X509ContentType.Pfx, "CngCertPassword");
                    X509Certificate2 cngCertImport = new X509Certificate2(pfx, "CngCertPassword");
                    Assert.IsTrue(cngCertImport.HasCngKey());

                    key.Delete();
                }

                using (CngKey key = CngKey.Create(CngAlgorithm2.Rsa))
                {
                    X509Certificate2 ephemeralCert = key.CreateSelfSignedCertificate(new X500DistinguishedName("CN=EphemeralCngCert"));
                    Assert.IsTrue(ephemeralCert.HasCngKey());
                }
            }
            finally
            {
                // Make sure to delete the persisted key so we're clean for the next run.
                if (CngKey.Exists(keyName))
                {
                    using (CngKey key = CngKey.Open(keyName))
                    {
                        key.Delete();
                    }
                }
            }
        }
        /// <summary>
        /// Method to generate a self signed certificate
        /// </summary>
        /// <param name="validForHours">number of hours for which the certificate is valid.</param>
        /// <param name="subscriptionId">subscriptionId in question</param>
        /// <param name="certificateNamePrefix">prefix for the certificate name</param>
        /// <param name="issuer">issuer for the certificate</param>
        /// <param name="password">certificate password</param>
        /// <returns>certificate as an object</returns>
        public static X509Certificate2 CreateSelfSignedCertificate(
            int validForHours,
            string subscriptionId,
            string certificateNamePrefix,
            string issuer = DefaultIssuer,
            string password = DefaultPassword)
        {
            string friendlyName = GenerateCertFriendlyName(subscriptionId, certificateNamePrefix);
            DateTime startTime = DateTime.UtcNow.AddMinutes(-10);
            DateTime endTime = DateTime.UtcNow.AddHours(validForHours);

            var key = Create2048RsaKey();

            var creationParams = new X509CertificateCreationParameters(new X500DistinguishedName(issuer))
            {
                TakeOwnershipOfKey = true,
                StartTime = startTime,
                EndTime = endTime
            };

            //// adding client authentication, -eku = 1.3.6.1.5.5.7.3.2, 
            //// This is mandatory for the upload to be successful
            OidCollection oidCollection = new OidCollection();
            oidCollection.Add(new Oid(OIDClientAuthValue, OIDClientAuthFriendlyName));
            creationParams.Extensions.Add(new X509EnhancedKeyUsageExtension(oidCollection, false));

            // Documentation of CreateSelfSignedCertificate states:
            // If creationParameters have TakeOwnershipOfKey set to true, the certificate
            // generated will own the key and the input CngKey will be disposed to ensure
            // that the caller doesn't accidentally use it beyond its lifetime (which is
            // now controlled by the certificate object).
            // We don't dispose it ourselves in this case.
            var cert = key.CreateSelfSignedCertificate(creationParams);
            key = null;
            cert.FriendlyName = friendlyName;

            // X509 certificate needs PersistKeySet flag set.  
            // Reload a new X509Certificate2 instance from exported bytes in order to set the PersistKeySet flag.
            var bytes = cert.Export(X509ContentType.Pfx, password);

            // PfxValidation is not done here because these are newly created certs and assumed valid.
            return NewX509Certificate2(bytes, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable, shouldValidatePfx: false);
        }
Example #17
0
        private void WritePrivateKey(CngKey key)
        {
            var creationParams =
                new X509CertificateCreationParameters(new X500DistinguishedName("CN=" + key.KeyName))
            {
                CertificateCreationOptions = X509CertificateCreationOptions.None,
                SignatureAlgorithm         = X509CertificateSignatureAlgorithm.ECDsaSha512,
                TakeOwnershipOfKey         = false
            };

            var cert = key.CreateSelfSignedCertificate(creationParams);

            byte[] pfx = string.IsNullOrEmpty(Password) ? cert.Export(X509ContentType.Pfx) : cert.Export(X509ContentType.Pfx, Password);

            using (var fs = File.OpenWrite(OutputPath))
            {
                fs.Write(pfx, 0, pfx.Length);
            }
        }
Example #18
0
        public static X509Certificate2 CreateSelfSignedCertificate(this CngKey key,
                                                                   X509CertificateCreationParameters creationParameters)
        {
            if (creationParameters == null)
            {
                throw new ArgumentNullException("creationParameters");
            }

            using (SafeNCryptKeyHandle keyHandle = key.Handle)
            {
                using (SafeCertificateContextHandle selfSignedCertHandle =
                           X509Native.CreateSelfSignedCertificate(keyHandle,
                                                                  creationParameters.SubjectName.RawData,
                                                                  creationParameters.CertificateCreationOptions,
                                                                  X509Native.MapCertificateSignatureAlgorithm(creationParameters.SignatureAlgorithm),
                                                                  creationParameters.StartTime,
                                                                  creationParameters.EndTime,
                                                                  creationParameters.ExtensionsNoDemand))
                {
                    // We need to get the raw handle out of the safe handle because X509Certificate2 only
                    // exposes an IntPtr constructor.  To do that we'll temporarially bump the ref count on
                    // the handle.
                    //
                    // X509Certificate2 will duplicate the handle value in the .ctor, so once we've created
                    // the certificate object, we can safely drop the ref count and dispose of our handle.
                    bool addedRef = false;
                    RuntimeHelpers.PrepareConstrainedRegions();
                    try
                    {
                        selfSignedCertHandle.DangerousAddRef(ref addedRef);
                        return(new X509Certificate2(selfSignedCertHandle.DangerousGetHandle()));
                    }
                    finally
                    {
                        if (addedRef)
                        {
                            selfSignedCertHandle.DangerousRelease();
                        }
                    }
                }
            }
        }
Example #19
0
        public static X509Certificate2 CreateSelfSignedCertificate(this CngKey key,
                                                                   X509CertificateCreationParameters creationParameters)
        {
            if (creationParameters == null)
                throw new ArgumentNullException("creationParameters");

            using (SafeNCryptKeyHandle keyHandle = key.Handle)
            {
                using (SafeCertificateContextHandle selfSignedCertHandle =
                    X509Native.CreateSelfSignedCertificate(keyHandle,
                                                           creationParameters.SubjectName.RawData,
                                                           creationParameters.CertificateCreationOptions,
                                                           X509Native.MapCertificateSignatureAlgorithm(creationParameters.SignatureAlgorithm),
                                                           creationParameters.StartTime,
                                                           creationParameters.EndTime,
                                                           creationParameters.ExtensionsNoDemand))
                {
                    // We need to get the raw handle out of the safe handle because X509Certificate2 only
                    // exposes an IntPtr constructor.  To do that we'll temporarially bump the ref count on
                    // the handle.
                    //
                    // X509Certificate2 will duplicate the handle value in the .ctor, so once we've created
                    // the certificate object, we can safely drop the ref count and dispose of our handle.
                    bool addedRef = false;
                    RuntimeHelpers.PrepareConstrainedRegions();
                    try
                    {
                        selfSignedCertHandle.DangerousAddRef(ref addedRef);
                        return new X509Certificate2(selfSignedCertHandle.DangerousGetHandle());
                    }
                    finally
                    {
                        if (addedRef)
                        {
                            selfSignedCertHandle.DangerousRelease();
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Creates a new self-signed X509 certificate
        /// </summary>
        /// <param name="issuer">The certificate issuer</param>
        /// <param name="friendlyName">Human readable name</param>
        /// <param name="password">The certificate's password</param>
        /// <param name="startTime">Certificate creation date & time</param>
        /// <param name="endTime">Certificate expiry date & time</param>
        /// <returns>An X509Certificate2</returns>
        public static X509Certificate2 CreateSelfSignedCert(string issuer, string friendlyName, string password, DateTime startTime, DateTime endTime)
        {
            string distinguishedNameString = issuer;
            var    key = Create2048RsaKey();

            var creationParams = new X509CertificateCreationParameters(new X500DistinguishedName(distinguishedNameString))
            {
                TakeOwnershipOfKey = true,
                StartTime          = startTime,
                EndTime            = endTime
            };

            // adding client authentication, -eku = 1.3.6.1.5.5.7.3.2,
            // This is mandatory for the upload to be successful
            OidCollection oidCollection = new OidCollection();

            oidCollection.Add(new Oid(OIDClientAuthValue, OIDClientAuthFriendlyName));
            creationParams.Extensions.Add(new X509EnhancedKeyUsageExtension(oidCollection, false));

            // Documentation of CreateSelfSignedCertificate states:
            // If creationParameters have TakeOwnershipOfKey set to true, the certificate
            // generated will own the key and the input CngKey will be disposed to ensure
            // that the caller doesn't accidentally use it beyond its lifetime (which is
            // now controlled by the certificate object).
            // We don't dispose it ourselves in this case.
            var cert = key.CreateSelfSignedCertificate(creationParams);

            key = null;
            cert.FriendlyName = friendlyName;

            // X509 certificate needs PersistKeySet flag set.
            // Reload a new X509Certificate2 instance from exported bytes in order to set the PersistKeySet flag.
            var bytes = cert.Export(X509ContentType.Pfx, password);

            // NOTE: PfxValidation is not done here because these are newly created certs and assumed valid.

            ICommonEventSource evtSource = null;

            return(X509Certificate2Helper.NewX509Certificate2(bytes, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable, evtSource, doPfxValidation: false));
        }
Example #21
0
        public void CreateCertificateNoOwnershipChangeReuseKey()
        {
            CngKeyCreationParameters keyCreationParameters = new CngKeyCreationParameters();

            keyCreationParameters.ExportPolicy = CngExportPolicies.AllowExport;

            using (CngKey key = CngKey.Create(CngAlgorithm2.Rsa, null, keyCreationParameters))
            {
                X509CertificateCreationParameters certCreationParameters =
                    new X509CertificateCreationParameters(new X500DistinguishedName("CN=TestCert"));
                certCreationParameters.TakeOwnershipOfKey = false;

                key.CreateSelfSignedCertificate(certCreationParameters);

                // Make sure the X509Certificate has been destroyed
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();

                Assert.AreEqual(CngAlgorithm2.Rsa, key.Algorithm);
            }
        }
Example #22
0
        /// <summary>
        /// Create a RSA based certificate (to be used with encryption) with the given options
        /// </summary>
        /// <param name="buildOptions">Allows for more advanced configuration</param>
        /// <returns>An exportable X509Certificate2 object (with private key)</returns>
        public static X509Certificate2 CreateNewCertificate(RSACertificateBuilderOptions buildOptions)
        {
            if (buildOptions == null)
            {
                throw new ArgumentNullException("buildOptions");
            }

            string keyName = buildOptions.RSAKeyName ?? "RSAKey";

            CngKey objCngKey = null;

            if (CngKey.Exists(keyName))
            {
                objCngKey = CngKey.Open(keyName);
                objCngKey.Delete();
            }

            var creationParameters = new CngKeyCreationParameters();

            creationParameters.ExportPolicy = CngExportPolicies.AllowExport;
            creationParameters.KeyUsage     = CngKeyUsages.AllUsages;
            creationParameters.Provider     = CngProvider.MicrosoftSoftwareKeyStorageProvider;
            var keySizeProperty = new CngProperty("Length", BitConverter.GetBytes(buildOptions.KeySize ?? 4096), CngPropertyOptions.None);

            creationParameters.Parameters.Add(keySizeProperty);

            objCngKey = CngKey.Create(CngAlgorithm2.Rsa, keyName, creationParameters);

            var name = new X500DistinguishedName(buildOptions.FullSubjectName);

            X509CertificateSignatureAlgorithm certAlg;

            switch (buildOptions.HashingMethod ?? HashingMethods.Sha256)
            {
            case HashingMethods.Sha1:
                certAlg = X509CertificateSignatureAlgorithm.RsaSha1;
                break;

            case HashingMethods.Sha256:
                certAlg = X509CertificateSignatureAlgorithm.RsaSha256;
                break;

            case HashingMethods.Sha384:
                certAlg = X509CertificateSignatureAlgorithm.RsaSha384;
                break;

            case HashingMethods.Sha512:
                certAlg = X509CertificateSignatureAlgorithm.RsaSha512;
                break;

            default:
                throw new InvalidOperationException("Selected hashing method is not supported");
            }

            var options = new X509CertificateCreationParameters(name)
            {
                SignatureAlgorithm = certAlg,
                TakeOwnershipOfKey = true
            };

            return(objCngKey.CreateSelfSignedCertificate(options));
        }
        /// <summary>
        /// Create a ECDSA based certificate with the given options
        /// </summary>
        /// <param name="buildOptions">Allows for more advanced configuration</param>
        /// <returns>An exportable X509Certificate2 object (with private key)</returns>
        public static X509Certificate2 CreateNewSigningCertificate(ECCertificateBuilderOptions buildOptions)
        {
            if (buildOptions == null)
            {
                throw new ArgumentNullException("buildOptions");
            }

            string keyName = buildOptions.ECKeyName ?? "ECDSAKey";

            CngKey objCngKey = null;

            if (CngKey.Exists(keyName))
            {
                objCngKey = CngKey.Open(keyName);
                objCngKey.Delete();
            }

            var creationParameters = new CngKeyCreationParameters();

            creationParameters.ExportPolicy = CngExportPolicies.AllowExport;
            creationParameters.KeyUsage     = CngKeyUsages.Signing;

            CngAlgorithm keyAlg;

            switch (buildOptions.ECCurve ?? ECNamedCurves.P521)
            {
            case ECNamedCurves.P521:
                keyAlg = CngAlgorithm.ECDsaP521;
                break;

            case ECNamedCurves.P384:
                keyAlg = CngAlgorithm.ECDsaP384;
                break;

            case ECNamedCurves.P256:
                keyAlg = CngAlgorithm.ECDsaP256;
                break;

            default:
                throw new InvalidOperationException("Selected curve is not supported");
            }

            objCngKey = CngKey.Create(keyAlg, keyName, creationParameters);

            var name = new X500DistinguishedName(buildOptions.FullSubjectName);

            X509CertificateSignatureAlgorithm certAlg;

            switch (buildOptions.HashingMethod ?? HashingMethods.Sha256)
            {
            case HashingMethods.Sha1:
                certAlg = X509CertificateSignatureAlgorithm.ECDsaSha1;
                break;

            case HashingMethods.Sha256:
                certAlg = X509CertificateSignatureAlgorithm.ECDsaSha256;
                break;

            case HashingMethods.Sha384:
                certAlg = X509CertificateSignatureAlgorithm.ECDsaSha384;
                break;

            case HashingMethods.Sha512:
                certAlg = X509CertificateSignatureAlgorithm.ECDsaSha512;
                break;

            default:
                throw new InvalidOperationException("Selected hashing method is not supported");
            }

            var options = new X509CertificateCreationParameters(name)
            {
                SignatureAlgorithm = certAlg,
                TakeOwnershipOfKey = true
            };

            return(objCngKey.CreateSelfSignedCertificate(options));
        }
        public async Task TestSslTermination()
        {
            ILoadBalancerService provider = CreateProvider();
            using (CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(TestTimeout(TimeSpan.FromSeconds(240))))
            {
                IEnumerable<LoadBalancingProtocol> protocols = await provider.ListProtocolsAsync(cancellationTokenSource.Token);
                LoadBalancingProtocol httpProtocol = protocols.First(i => i.Name.Equals("HTTP", StringComparison.OrdinalIgnoreCase));

                string loadBalancerName = CreateRandomLoadBalancerName();

                LoadBalancerConfiguration configuration = new LoadBalancerConfiguration(
                    name: loadBalancerName,
                    nodes: null,
                    protocol: httpProtocol,
                    virtualAddresses: new[] { new LoadBalancerVirtualAddress(LoadBalancerVirtualAddressType.ServiceNet) },
                    algorithm: LoadBalancingAlgorithm.RoundRobin);
                LoadBalancer tempLoadBalancer = await provider.CreateLoadBalancerAsync(configuration, AsyncCompletionOption.RequestCompleted, cancellationTokenSource.Token, null);

                string privateKey;
                string certificate;

                CngKeyCreationParameters keyParams = new CngKeyCreationParameters();
                keyParams.ExportPolicy = CngExportPolicies.AllowExport | CngExportPolicies.AllowPlaintextExport;
                keyParams.KeyUsage = CngKeyUsages.AllUsages;
                keyParams.Provider = CngProvider.MicrosoftSoftwareKeyStorageProvider;
                using (CngKey key = CngKey.Create(CngAlgorithm2.Rsa, Guid.NewGuid().ToString(), keyParams))
                {
                    byte[] exported = key.Export(CngKeyBlobFormat.Pkcs8PrivateBlob);

                    StringBuilder formatted = new StringBuilder();
                    formatted.AppendLine("-----BEGIN RSA PRIVATE KEY-----");
                    formatted.AppendLine(Convert.ToBase64String(exported, Base64FormattingOptions.InsertLineBreaks));
                    formatted.Append("-----END RSA PRIVATE KEY-----");
                    Console.WriteLine(formatted.ToString());
                    privateKey = formatted.ToString();

                    X509CertificateCreationParameters certParams = new X509CertificateCreationParameters(new X500DistinguishedName(string.Format("CN={0}, OU=Integration Testing, O=openstacknetsdk, L=San Antonio, S=Texas, C=US", loadBalancerName)));
                    certParams.SignatureAlgorithm = X509CertificateSignatureAlgorithm.RsaSha1;
                    certParams.StartTime = DateTime.Now;
                    certParams.EndTime = DateTime.Now.AddYears(10);
                    certParams.TakeOwnershipOfKey = true;

                    X509Certificate signed = key.CreateSelfSignedCertificate(certParams);
                    exported = signed.Export(X509ContentType.Cert);

                    formatted = new StringBuilder();
                    formatted.AppendLine("-----BEGIN CERTIFICATE-----");
                    formatted.AppendLine(Convert.ToBase64String(exported, Base64FormattingOptions.InsertLineBreaks));
                    formatted.Append("-----END CERTIFICATE-----");
                    Console.WriteLine(formatted.ToString());
                    certificate = formatted.ToString();
                }

                string intermediateCertificate = null;
                LoadBalancerSslConfiguration sslConfiguration = new LoadBalancerSslConfiguration(true, false, 443, privateKey, certificate, intermediateCertificate);

                await provider.UpdateSslConfigurationAsync(tempLoadBalancer.Id, sslConfiguration, AsyncCompletionOption.RequestCompleted, cancellationTokenSource.Token, null);

                LoadBalancerSslConfiguration updatedConfiguration = new LoadBalancerSslConfiguration(true, true, 443);
                await provider.UpdateSslConfigurationAsync(tempLoadBalancer.Id, updatedConfiguration, AsyncCompletionOption.RequestCompleted, cancellationTokenSource.Token, null);

                await provider.RemoveSslConfigurationAsync(tempLoadBalancer.Id, AsyncCompletionOption.RequestCompleted, cancellationTokenSource.Token, null);

                /* Cleanup
                 */

                await provider.RemoveLoadBalancerAsync(tempLoadBalancer.Id, AsyncCompletionOption.RequestCompleted, cancellationTokenSource.Token, null);
            }
        }
Example #25
0
        public X509Certificate2  CreateNamedKeyCertificate(CertData data)
        {
            try
            {
                CngKeyCreationParameters keyCreationParameters
                    = new CngKeyCreationParameters
                          {
                              ExportPolicy =
                                  CngExportPolicies.AllowExport |
                                  CngExportPolicies.AllowPlaintextExport |
                                  CngExportPolicies.AllowPlaintextArchiving |
                                  CngExportPolicies.AllowArchiving,
                              KeyUsage = CngKeyUsages.AllUsages
                          };

                X509Certificate2 cert;
                X509CertificateCreationParameters configCreate
                    = new X509CertificateCreationParameters(new X500DistinguishedName(data.DistinguishedName))
                          {
                              EndTime =
                                  DateTime.Parse("01/01/2020",
                                                 System.Globalization.
                                                     DateTimeFormatInfo.
                                                     InvariantInfo),
                              StartTime =
                                  DateTime.Parse("01/01/2010",
                                                 System.Globalization.
                                                     DateTimeFormatInfo.
                                                     InvariantInfo)
                          };

                using (CngKey namedKey = CngKey.Create(CngAlgorithm2.Rsa, data.Key, keyCreationParameters))
                {
                    cert = namedKey.CreateSelfSignedCertificate(configCreate);
                    cert.FriendlyName = data.Friendlyname;
                    Assert.True(cert.HasPrivateKey);
                    Assert.True(cert.HasCngKey());
                    using (CngKey certKey = cert.GetCngPrivateKey())
                    {
                        Assert.Equal(CngAlgorithm2.Rsa, certKey.Algorithm);
                    }
                }
                return cert;
            }
            finally
            {
                if (CngKey.Exists(data.Key))
                {
                    using (CngKey key = CngKey.Open(data.Key))
                    {
                        key.Delete();
                    }
                }
            }
        }
        /// <summary>
        /// Create a RSA based certificate (to be used with encryption) with the given options
        /// </summary>
        /// <param name="buildOptions">Allows for more advanced configuration</param>
        /// <returns>An exportable X509Certificate2 object (with private key)</returns>
        public static X509Certificate2 CreateNewCertificate(RSACertificateBuilderOptions buildOptions)
        {
            if (buildOptions == null)
            {
                throw new ArgumentNullException("buildOptions");
            }

            string keyName = buildOptions.RSAKeyName ?? "RSAKey";

            CngKey objCngKey = null;
            if (CngKey.Exists(keyName))
            {
                objCngKey = CngKey.Open(keyName);
                objCngKey.Delete();
            }

            var creationParameters = new CngKeyCreationParameters();
            creationParameters.ExportPolicy = CngExportPolicies.AllowExport;
            creationParameters.KeyUsage = CngKeyUsages.AllUsages;
            creationParameters.Provider = CngProvider.MicrosoftSoftwareKeyStorageProvider;
            var keySizeProperty = new CngProperty("Length", BitConverter.GetBytes(buildOptions.KeySize ?? 4096), CngPropertyOptions.None);
            creationParameters.Parameters.Add(keySizeProperty);

            objCngKey = CngKey.Create(CngAlgorithm2.Rsa, keyName, creationParameters);

            var name = new X500DistinguishedName(buildOptions.FullSubjectName);

            X509CertificateSignatureAlgorithm certAlg;
            switch (buildOptions.HashingMethod ?? HashingMethods.Sha256)
            {
                case HashingMethods.Sha1:
                    certAlg = X509CertificateSignatureAlgorithm.RsaSha1;
                    break;
                case HashingMethods.Sha256:
                    certAlg = X509CertificateSignatureAlgorithm.RsaSha256;
                    break;
                case HashingMethods.Sha384:
                    certAlg = X509CertificateSignatureAlgorithm.RsaSha384;
                    break;
                case HashingMethods.Sha512:
                    certAlg = X509CertificateSignatureAlgorithm.RsaSha512;
                    break;
                default:
                    throw new InvalidOperationException("Selected hashing method is not supported");
            }

            var options = new X509CertificateCreationParameters(name)
            {
                SignatureAlgorithm = certAlg,
                TakeOwnershipOfKey = true
            };

            return objCngKey.CreateSelfSignedCertificate(options);
        }
        public void OpenSubscriber()
        {
            try
            {

                if (IsListening())
                    return;

                log.InfoFormat("Opening subscriber endpoint at {0}", netTcpAddress);

                log.InfoFormat("Opening http subscriber endpoint at {0}", httpAddress);

                NotificationSubscriber notificationSubscriber = new NotificationSubscriber();
                notificationSubscriber.IndicationReceived += OnIndication;

                CngKeyCreationParameters keyCreationParameters = new CngKeyCreationParameters();
                keyCreationParameters.ExportPolicy = CngExportPolicies.AllowExport | CngExportPolicies.AllowPlaintextExport | CngExportPolicies.AllowPlaintextArchiving | CngExportPolicies.AllowArchiving;
                keyCreationParameters.KeyUsage = CngKeyUsages.AllUsages;

                X509CertificateCreationParameters configCreate = new X509CertificateCreationParameters(new X500DistinguishedName("CN=SolarWinds-SwqlStudio"));
                configCreate.EndTime = DateTime.Now.AddYears(1);
                configCreate.StartTime = DateTime.Now;

                using (CngKey cngKey = CngKey.Create(CngAlgorithm2.Rsa))
                {
                    X509Certificate2 certificate = cngKey.CreateSelfSignedCertificate(configCreate);
                    ServiceHost host = new ServiceHost(notificationSubscriber, new Uri(netTcpAddress), new Uri(httpAddress));
                    host.Credentials.ServiceCertificate.Certificate = certificate;
                    // SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectDistinguishedName, "CN=SolarWinds-Orion");
                    host.Open();
                    subscriberHosts.Add(host);
                }

                log.Info("Http Subscriber endpoint opened");
            }
            catch (Exception ex)
            {
                log.ErrorFormat("Exception opening subscriber host with address {0}.\n{1}", httpAddress, ex);
            }

            foreach (ServiceHost serviceHost in subscriberHosts)
            {
                foreach (ChannelDispatcherBase channelDispatcher in serviceHost.ChannelDispatchers)
                {
                    log.InfoFormat("Listening on {0}", channelDispatcher.Listener.Uri.AbsoluteUri);
                }
            }

            ListenerOpened?.Invoke();
        }
Example #28
0
        private void OpenSubscriber()
        {
            string ipAddress;

            try
            {
                // Instance should run on a different machine (i.e. where the additional poller is), so in that case must be subscription done via IP instead of relative localhost
                ipAddress = ResolveLocalIPAddress();
            }
            catch (Exception ex)
            {
                log.ErrorFormat("Unable to retrieve ip address", ex);
                return;
            }

            string address = string.Format("net.tcp://{0}:17777/SolarWinds/SwqlStudio/{1}/Subscriber", ipAddress, Process.GetCurrentProcess().Id);

            try
            {
                log.InfoFormat("Opening subscriber endpoint at {0}", address);

                ServiceHost host = new ServiceHost(this);
                host.AddServiceEndpoint(typeof(INotificationSubscriber), new NetTcpBinding("NotificationSubscriber"), address);
                host.Open();
                subscriberHosts.Add(host);

                log.Info("Subscriber endpoint opened");

                subscriberInfo = new SubscriberInfo {
                    EndpointAddress = address, OpenedSuccessfully = true, Binding = "NetTcp", DataFormat = "Xml", CredentialType = "Certificate"
                };
            }
            catch (Exception ex)
            {
                log.ErrorFormat("Exception opening subscriber host with address {0}.\n{1}", address, ex);
                subscriberInfo = new SubscriberInfo {
                    OpenedSuccessfully = false, ErrorMessage = ex.Message
                };
            }

            string httpAddress = string.Format("https://{0}:17778/SolarWinds/SwqlStudio/{1}", Utility.GetFqdn(), Process.GetCurrentProcess().Id);

            try
            {
                log.InfoFormat("Opening http subscriber endpoint at {0}", httpAddress);

                NotificationSubscriber notificationSubscriber = new NotificationSubscriber();
                notificationSubscriber.IndicationReceived += OnIndication;

                CngKeyCreationParameters keyCreationParameters = new CngKeyCreationParameters();
                keyCreationParameters.ExportPolicy = CngExportPolicies.AllowExport | CngExportPolicies.AllowPlaintextExport | CngExportPolicies.AllowPlaintextArchiving | CngExportPolicies.AllowArchiving;
                keyCreationParameters.KeyUsage     = CngKeyUsages.AllUsages;

                X509CertificateCreationParameters configCreate = new X509CertificateCreationParameters(new X500DistinguishedName("CN=SolarWinds-SwqlStudio"));
                configCreate.EndTime   = DateTime.Now.AddYears(1);
                configCreate.StartTime = DateTime.Now;

                using (CngKey cngKey = CngKey.Create(CngAlgorithm2.Rsa))
                {
                    X509Certificate2 certificate = cngKey.CreateSelfSignedCertificate(configCreate);
                    ServiceHost      host        = new ServiceHost(notificationSubscriber, new Uri(httpAddress));
                    host.Credentials.ServiceCertificate.Certificate = certificate;
                    // SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectDistinguishedName, "CN=SolarWinds-Orion");
                    host.Open();
                    subscriberHosts.Add(host);
                }

                log.Info("Http Subscriber endpoint opened");

                httpSubscriberInfo = new SubscriberInfo {
                    EndpointAddress = httpAddress + "/Subscriber", OpenedSuccessfully = true, DataFormat = "Xml", Binding = "Soap1_1", CredentialType = "Username"
                };
            }
            catch (Exception ex)
            {
                log.ErrorFormat("Exception opening subscriber host with address {0}.\n{1}", address, ex);
                httpSubscriberInfo = new SubscriberInfo {
                    OpenedSuccessfully = false, ErrorMessage = ex.Message
                };
            }

            foreach (ServiceHost serviceHost in subscriberHosts)
            {
                foreach (ChannelDispatcherBase channelDispatcher in serviceHost.ChannelDispatchers)
                {
                    log.InfoFormat("Listening on {0}", channelDispatcher.Listener.Uri.AbsoluteUri);
                }
            }

            subscriberHostOpened.Set();
        }
Example #29
0
        public void X509CertificateCreationParametersSetBadAlgorithmTest1()
        {
            X509CertificateCreationParameters creationParams = new X509CertificateCreationParameters(new X500DistinguishedName("CN="));

            creationParams.SignatureAlgorithm = (X509CertificateSignatureAlgorithm)(-1);
        }
Example #30
0
        public void CreateCertificateWithExtensions()
        {
            byte[] pfx = null;

            X509CertificateCreationParameters creationParams = new X509CertificateCreationParameters(new X500DistinguishedName("CN=TestCertWithExtensions"));

            creationParams.SignatureAlgorithm = X509CertificateSignatureAlgorithm.RsaSha512;

            creationParams.Extensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, true));
            creationParams.Extensions.Add(new X509BasicConstraintsExtension(false, true, 5, false));

            CngKeyCreationParameters keyCreationParameters = new CngKeyCreationParameters();

            keyCreationParameters.ExportPolicy = CngExportPolicies.AllowExport;
            using (CngKey key = CngKey.Create(CngAlgorithm2.Rsa, null, keyCreationParameters))
            {
                X509Certificate2 cert = key.CreateSelfSignedCertificate(creationParams);

                bool foundKeyUsageExtension        = false;
                bool foundBasicConstraintExtension = false;

                foreach (X509Extension extension in cert.Extensions)
                {
                    X509KeyUsageExtension         keyUsageExtension         = extension as X509KeyUsageExtension;
                    X509BasicConstraintsExtension basicConstraintsExtension = extension as X509BasicConstraintsExtension;

                    if (keyUsageExtension != null)
                    {
                        foundKeyUsageExtension = true;
                        Assert.AreEqual(X509KeyUsageFlags.DigitalSignature, keyUsageExtension.KeyUsages);
                        Assert.IsTrue(keyUsageExtension.Critical);
                    }
                    else if (basicConstraintsExtension != null)
                    {
                        foundBasicConstraintExtension = true;
                        Assert.IsFalse(basicConstraintsExtension.CertificateAuthority);
                        Assert.IsTrue(basicConstraintsExtension.HasPathLengthConstraint);
                        Assert.AreEqual(5, basicConstraintsExtension.PathLengthConstraint);
                        Assert.IsFalse(basicConstraintsExtension.Critical);
                    }
                }

                Assert.IsTrue(foundKeyUsageExtension);
                Assert.IsTrue(foundBasicConstraintExtension);

                pfx = cert.Export(X509ContentType.Pfx, "TestPassword");
            }

            X509Certificate2 rtCert = new X509Certificate2(pfx, "TestPassword");

            bool foundRTKeyUsageExtension        = false;
            bool foundRTBasicConstraintExtension = false;

            foreach (X509Extension extension in rtCert.Extensions)
            {
                X509KeyUsageExtension         keyUsageExtension         = extension as X509KeyUsageExtension;
                X509BasicConstraintsExtension basicConstraintsExtension = extension as X509BasicConstraintsExtension;

                if (keyUsageExtension != null)
                {
                    foundRTKeyUsageExtension = true;
                    Assert.AreEqual(X509KeyUsageFlags.DigitalSignature, keyUsageExtension.KeyUsages);
                    Assert.IsTrue(keyUsageExtension.Critical);
                }
                else if (basicConstraintsExtension != null)
                {
                    foundRTBasicConstraintExtension = true;
                    Assert.IsFalse(basicConstraintsExtension.CertificateAuthority);
                    Assert.IsTrue(basicConstraintsExtension.HasPathLengthConstraint);
                    Assert.AreEqual(5, basicConstraintsExtension.PathLengthConstraint);
                    Assert.IsFalse(basicConstraintsExtension.Critical);
                }
            }

            Assert.IsTrue(foundRTKeyUsageExtension);
            Assert.IsTrue(foundRTBasicConstraintExtension);
        }
Example #31
0
        private void WritePrivateKey()
        {
            if (false == Options.ExportPrivateKey)
                return;

            var creationParams =
                new X509CertificateCreationParameters(new X500DistinguishedName("CN="+Key.KeyName))
                    {
                        CertificateCreationOptions = X509CertificateCreationOptions.None,
                        SignatureAlgorithm = X509CertificateSignatureAlgorithm.ECDsaSha512,
                        TakeOwnershipOfKey = false,
                        EndTime = DateTime.Now.AddDays(Options.ExpiryDays)
                    };

            var cert = Key.CreateSelfSignedCertificate(creationParams);

            byte[] pfx = string.IsNullOrEmpty(Options.Password) ?
                                                                    cert.Export(X509ContentType.Pfx) :
                                                                                                         cert.Export(X509ContentType.Pfx, Options.Password);

            using(var fs  = File.OpenWrite(Options.KeyName+".key.pfx"))
            {
                fs.Write(pfx, 0, pfx.Length);
            }
        }
        /// <summary>
        /// Create a ECDSA based certificate with the given options
        /// </summary>
        /// <param name="buildOptions">Allows for more advanced configuration</param>
        /// <returns>An exportable X509Certificate2 object (with private key)</returns>
        public static X509Certificate2 CreateNewSigningCertificate(ECCertificateBuilderOptions buildOptions)
        {
            if(buildOptions == null)
            {
                throw new ArgumentNullException("buildOptions");
            }

            string keyName = buildOptions.ECKeyName ?? "ECDSAKey";

            CngKey objCngKey = null;
            if (CngKey.Exists(keyName))
            {
                objCngKey = CngKey.Open(keyName);
                objCngKey.Delete();
            }

            var creationParameters = new CngKeyCreationParameters();
            creationParameters.ExportPolicy = CngExportPolicies.AllowExport;
            creationParameters.KeyUsage = CngKeyUsages.Signing;

            CngAlgorithm keyAlg;
            switch(buildOptions.ECCurve ?? ECNamedCurves.P521)
            {
                case ECNamedCurves.P521:
                    keyAlg = CngAlgorithm.ECDsaP521;
                    break;
                case ECNamedCurves.P384:
                    keyAlg = CngAlgorithm.ECDsaP384;
                    break;
                case ECNamedCurves.P256:
                    keyAlg = CngAlgorithm.ECDsaP256;
                    break;
                default:
                    throw new InvalidOperationException("Selected curve is not supported");
            }

            objCngKey = CngKey.Create(keyAlg, keyName, creationParameters);

            var name = new X500DistinguishedName(buildOptions.FullSubjectName);

            X509CertificateSignatureAlgorithm certAlg;
            switch(buildOptions.HashingMethod ?? HashingMethods.Sha256)
            {
                case HashingMethods.Sha1:
                    certAlg = X509CertificateSignatureAlgorithm.ECDsaSha1;
                    break;
                case HashingMethods.Sha256:
                    certAlg = X509CertificateSignatureAlgorithm.ECDsaSha256;
                    break;
                case HashingMethods.Sha384:
                    certAlg = X509CertificateSignatureAlgorithm.ECDsaSha384;
                    break;
                case HashingMethods.Sha512:
                    certAlg = X509CertificateSignatureAlgorithm.ECDsaSha512;
                    break;
                default:
                    throw new InvalidOperationException("Selected hashing method is not supported");
            }

            var options = new X509CertificateCreationParameters(name)
            {
                SignatureAlgorithm = certAlg,
                TakeOwnershipOfKey = true
            };

            return objCngKey.CreateSelfSignedCertificate(options);
        }