Register certificate for SSL port

I have a Windows service (running LocalSystem) that is a self-service OWIN service (SignalR) and must be accessible via SSL.

I can configure SSL binding on my local development machine just fine - and I can access my service through SSL on the same computer. However, when I switch to another machine and try to run the following command, I get an error message:

Command:

netsh http add sslcert ipport=0.0.0.0:9389 appid={...guid here...} certhash=...cert hash here... 

Error:

SSL Certificate Error, Error: 1312

The specified login session does not exist. It may already be completed.

The certificate that I use is a fully signed certificate (not a development certificate) and works in my local dev block. That's what I'm doing:

The Windows service starts and registers my certificate using the following code:

 var store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); var path = AppDomain.CurrentDomain.BaseDirectory; var cert = new X509Certificate2(path + @"\mycert.cer"); var existingCert = store.Certificates.Find(X509FindType.FindByThumbprint, cert.Thumbprint, false); if (existingCert.Count == 0) store.Add(cert); store.Close(); 

Then I try to bind the certificate to port 9389 using netsh and the following code:

 var process = new Process { StartInfo = new ProcessStartInfo { WindowStyle = ProcessWindowStyle.Hidden, FileName = "cmd.exe", Arguments = "/c netsh http add sslcert ipport=0.0.0.0:9389 appid={12345678-db90-4b66-8b01-88f7af2e36bf} certhash=" + cert.thumbprint } }; process.Start(); 

The code above successfully installs the certificate in the certificate folder "Local machine - certificates \ Trusted root certification authorities \ Certificates", but the netsh command does not start with the error described above. If I take the netsh command and run it on the command line as an administrator in this field, it will also give the same error - so I don't think this is a problem with the code ...

I have to imagine that this can be done - many other applications create self-service services and host them on top of ssl - but I can't get this to work at all ... who has any suggestions? Perhaps software alternatives to netsh?

+6
source share
1 answer

Ok, I found the answer:

If you bring the certificate from another computer, it will not work on the new machine. You need to create a self-signed certificate on the new computer and import it into the trusted root certificates of the local computer.

The answer is from here: How to create a self-signed certificate using C #?

For posterity, this is the process used to create a self-signed certificate (from the answer above):

Import the CertEnroll 1.0 type library from the COM tab in the project links

Add the following code to your code:

 //This method credit belongs to this StackOverflow Answer: ///questions/139742/how-to-create-a-self-signed-certificate-using-c/829185#829185 using CERTENROLLLib; public static X509Certificate2 CreateSelfSignedCertificate(string subjectName) { // create DN for subject and issuer var dn = new CX500DistinguishedName(); dn.Encode("CN=" + subjectName, X500NameFlags.XCN_CERT_NAME_STR_NONE); // create a new private key for the certificate CX509PrivateKey privateKey = new CX509PrivateKey(); privateKey.ProviderName = "Microsoft Base Cryptographic Provider v1.0"; privateKey.MachineContext = true; privateKey.Length = 2048; privateKey.KeySpec = X509KeySpec.XCN_AT_SIGNATURE; // use is not limited privateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG; privateKey.Create(); // Use the stronger SHA512 hashing algorithm var hashobj = new CObjectId(); hashobj.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID, ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY, AlgorithmFlags.AlgorithmFlagsNone, "SHA512"); // add extended key usage if you want - look at MSDN for a list of possible OIDs var oid = new CObjectId(); oid.InitializeFromValue("1.3.6.1.5.5.7.3.1"); // SSL server var oidlist = new CObjectIds(); oidlist.Add(oid); var eku = new CX509ExtensionEnhancedKeyUsage(); eku.InitializeEncode(oidlist); // Create the self signing request var cert = new CX509CertificateRequestCertificate(); cert.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, privateKey, ""); cert.Subject = dn; cert.Issuer = dn; // the issuer and the subject are the same cert.NotBefore = DateTime.Now; // this cert expires immediately. Change to whatever makes sense for you cert.NotAfter = DateTime.Now; cert.X509Extensions.Add((CX509Extension)eku); // add the EKU cert.HashAlgorithm = hashobj; // Specify the hashing algorithm cert.Encode(); // encode the certificate // Do the final enrollment process var enroll = new CX509Enrollment(); enroll.InitializeFromRequest(cert); // load the certificate enroll.CertificateFriendlyName = subjectName; // Optional: add a friendly name string csr = enroll.CreateRequest(); // Output the request in base64 // and install it back as the response enroll.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedCertificate, csr, EncodingType.XCN_CRYPT_STRING_BASE64, ""); // no password // output a base64 encoded PKCS#12 so we can import it back to the .Net security classes var base64encoded = enroll.CreatePFX("", // no password, this is for internal consumption PFXExportOptions.PFXExportChainWithRoot); // instantiate the target class with the PKCS#12 data (and the empty password) return new System.Security.Cryptography.X509Certificates.X509Certificate2( System.Convert.FromBase64String(base64encoded), "", // mark the private key as exportable (this is usually what you want to do) System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable ); } 

For anyone else reading this answer - the code to import the certificate from the original question should now change to the following:

 var certName = "Your Cert Subject Name"; var store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); var existingCert = store.Certificates.Find(X509FindType.FindBySubjectName, certName, false); if (existingCert.Count == 0) { var cert = CreateSelfSignedCertificate(certName); store.Add(cert); RegisterCertForSSL(cert.Thumbprint); } store.Close(); 
+4
source

Source: https://habr.com/ru/post/977203/


All Articles