将证书注册到 SSL 端口

问题描述:

我有一个 Windows 服务(作为 LocalSystem 运行),它自托管一个 OWIN 服务(SignalR)并且需要通过 SSL 访问.

I have a windows service (running as LocalSystem) that is self-hosting an OWIN service (SignalR) and needs to be accessed over SSL.

我可以在我的本地开发机器上设置 SSL 绑定就好了 - 我可以在同一台机器上通过 SSL 访问我的服务.但是,当我转到另一台机器并尝试运行以下命令时,我收到一个错误:

I can set up the SSL binding on my local development machine just fine - and I can access my service over SSL on that same machine. However, when I go to another machine and try to run the following command I receive an error:

命令:

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

错误:

SSL 证书添加失败,错误:1312

SSL Certificate add failed, Error: 1312

指定的登录会话不存在.它可能已经被终止.

A specified logon session does not exist. It may have already been terminated.

我使用的证书是完全签名的证书(不是开发证书),可在我的本地开发设备上使用.这是我在做什么:

The certificate I am using is a fully signed cert (not a development cert) and works on my local dev box. Here's what I am doing:

Windows 服务启动并使用以下代码注册我的证书:

Windows service starts up 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();

然后我尝试使用 netsh 和以下代码将证书绑定到端口 9389:

I then attempt 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();

以上代码成功将证书安装到本地机器-证书受信任的根证书颁发机构证书";证书文件夹 - 但 netsh 命令无法运行,并出现我上面描述的错误.如果我使用 netsh 命令并在命令提示符中以管理员身份在该框中运行它,它也会抛出相同的错误 - 所以我不认为这是与代码相关的问题......

The code above successfully installs the certificate to the "Local Machine - CertificatesTrusted Root Certification AuthoritiesCertificates" certificate folder - but the netsh command fails to run with the error I described above. If I take the netsh command and run it in a command prompt as an administrator on that box it also throws out the same error - so I don't believe that it's a code related issue...

我不得不想象这是可以实现的——许多其他应用程序创建自托管服务并通过 ssl 托管它们——但我似乎根本无法让它工作......有人有什么建议吗?也许 netsh 的编程替代方案?

I have to imagine that this is possible to accomplish - plenty of other applications create self-hosted services and host them over ssl - but I cannot seem to get this to work at all...anyone have any suggestions? Perhaps programmatic alternatives to netsh?

好的,我找到了答案:

如果您从另一台机器引入证书,它将无法在新机器上运行.您必须在新机器上创建一个自签名证书并将其导入到本地计算机的受信任根证书中.

If you are bringing in a certificate from another machine it will NOT work on the new machine. You have to create a self-signed certificate on the new machine and import it into the Local Computer's Trusted Root Certificates.

答案来自这里:如何使用 C# 创建自签名证书?

为了后代,这是用于创建自签名证书的过程(来自上面引用的答案):

For posterity's sake this is the process used to create a self signed cert (from the above referenced answer):

从项目引用中的 COM 选项卡导入 CertEnroll 1.0 类型库

Import the CertEnroll 1.0 Type Library from the COM tab in your project's references

将以下方法添加到您的代码中:

Add the following method to your code:

//This method credit belongs to this * Answer:
//https://*.com/a/13806300/594354
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 for importing 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();