Nice programing

포트에 바인딩 할 때 SSL 인증서 추가에 실패했습니다.

nicepro 2020. 12. 6. 22:07
반응형

포트에 바인딩 할 때 SSL 인증서 추가에 실패했습니다.


WCF를 사용하여 WebService를 만들었습니다. 셀프 호스팅을하고 있으며 HTTPS를 활성화하고 싶습니다. 이런 일이 발생하기 위해서는 인증서를 생성하고 사용하려는 포트에 바인딩해야합니다.

이를 처리하기 위해 수행 한 단계는 다음과 같습니다.

  1. 루트 인증 기관 역할을하는 내 로컬 컴퓨터에 인증서를 생성했습니다.
    • makecert -n "CN = 내 루트 인증 기관"-r -sv RootCATest.pvk RootCATest.cer
  2. MMC.exe를 열고 저장된 .cer 파일을 "Trusted Root Certificate \ Certificates \ 폴더로 가져 왔습니다.
    • makecert -sk MyKeyName -iv RootCATest.pvk -n "CN = MyMachineName"-ic RootCATest.cer -sr localmachine -ss my -sky exchange -pe MyMachineName.cer
  3. 서명 된 루트 인증 기관에서 임시 서비스 인증서를 생성했습니다.

    • makecert -sk MyKeyName -iv RootCATest.pvk -n "CN = MyMachineName"-ic RootCATest.cer -sr localmachine -ss my -sky exchange -pe MyMachineName.cer
  4. 인증서를 포트 번호 (이 경우 443)에 바인딩하려고했습니다.

    • netsh http add sslcert ipport = 0.0.0.0 : 443 certhash = 2c5ba85bcbca412a74fece02878a44b285c63981 appid = {646937c0-1042-4e81-a3b6-47d678d68ba9}

4 단계의 결과는 다음 오류입니다.

SSL 인증서 추가 실패, 오류 1312

지정된 로그온 세션이 없습니다. 이미 종료되었을 수 있습니다.

아무도 내가 왜이 오류가 발생할 수 있는지 단서가 있습니까?


나는 같은 오류가 있었다. 처음 발생했을 때 Micheal이 말했듯이 인증서 (로컬 컴퓨터)-> 개인-> 인증서 폴더 아래로 인증서를 이동해야했습니다. 다른 컴퓨터에서 동일한 인증서를 가져올 때 동일한 오류가 발생했습니다. 그 이유는 인증서를 가져 오기 위해 certmgr.msc를 사용했기 때문입니다. . 따라서 열린 창에 "인증서 – 현재 사용자"가 표시됩니다. 이 창을 사용하여 가져온 인증서로 인해 netsh가 1312 오류와 함께 실패합니다. 인증서를 가져 오려면 MMC에서 인증서 스냅인을 사용해야합니다. MMC의 인증서 스냅인에 "인증서 (로컬 컴퓨터)"가 표시됩니다. 이렇게하면 netsh 실행이 진행됩니다.


SSL Certificate add failed, Error 1312

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

나는 똑같은 문제를 가지고 있었고 그 이유가 무엇인지 알아 내려고 며칠을 보냈습니다.

간단히 말해서 문제는 winrmPRIVATE KEY가없는 서버에 인증서를 설치했다는 것 입니다.

나는 이것을 여러 번 확인했다. http://blogs.technet.com/b/jhoward/archive/2005/02/02/365323.aspx에makecert 완벽하게 설명 된대로 예를 들어 사용하여 인증서를 삭제하고 다시 작성해야 합니다.

인증서가 너무로의 사설 키가 있는지 쉽게 확인할 수 있습니다 : mmc- certificates- local machine- personal. 인증서 아이콘을보십시오. 아이콘에 키 기호가 있어야합니다.


이 문제를 다루고 있었고 자체 호스팅 WCF 서비스를 사용하고 있습니다. 방금 돌파구를 만들었습니다.

기계 저장소의 인사 폴더에 인증서가 있습니다. 만료되었고 관리자가 새 것을 발행했습니다. 이 오류로 인해 새 것이 실패했습니다. Google에서 많은 것을 시도했지만 결국 완전히 다른 솔루션을 사용하여 문제를 해결했습니다.

만료 된 인증서와 최신 인증서를 모두 설치했습니다. 그런 다음이 명령을 사용하여 목록을 가져 왔습니다.

certutil -store My

이 출력을 얻습니다 (정보는 가짜이고 다른 인증서는 나열되지 않음).

================ Certificate 1 ================
Serial Number: 6d
Issuer: E=operations@voicetrust.com, CN=VoiceTrust Server CA, OU=VoiceTrust Oper
ations, O=VoiceTrust
 NotBefore: 03-Jan-2013 3:33 PM
 NotAfter: 03-Mar-2013 3:33 PM
Subject: E=hgulzar@voicetrust.com, CN=hornet.voicetrust.com, OU=Software Develop
ment, O=VoiceTrust eServices MENA FZ LLC, L=Dubai, C=AE
Non-root Certificate
Cert Hash(sha1): 98 5f a0 d3 11 6a 4b 64 3b db 0a a4 11 66 fc 08 28 74 7e 53
  Key Container = {E5BC0912-7808-4B89-B457-31946DE5990E}
  Unique container name: dfedfcc149408fb990a3bacd6d31126b_3277b2c9-9894-46d0-9b6
4-30f0d6589239
  Provider = Microsoft Enhanced Cryptographic Provider v1.0
Private key is NOT exportable
Encryption test passed

================ Certificate 2 ================
Serial Number: 6d
Issuer: E=operations@voicetrust.com, CN=VoiceTrust Server CA, OU=VoiceTrust Oper
ations, O=VoiceTrust
 NotBefore: 03-Nov-2013 3:33 PM
 NotAfter: 03-Dec-2013 3:33 PM
Subject: E=hgulzar@voicetrust.com, CN=hornet.voicetrust.com, OU=Software Develop
ment, O=VoiceTrust eServices MENA FZ LLC, L=Dubai, C=AE
Non-root Certificate
Cert Hash(sha1): 30 5f a0 d3 11 6a 4b 64 3b db 0a a4 11 66 fc 08 28 74 7e 53
  Key Container = {E5BC0912-7808-4B89-B457-31946DE5960E}
  *Unique container name:* 55edfcc149408fb990a3bacd6d31126b_3277b2c9-9894-46d0-9b6
4-30f0d6589239
  Provider = Microsoft Enhanced Cryptographic Provider v1.0
Private key is NOT exportable
Encryption test passed

이제 모든 것이 정상인 것처럼 보이지만 인증서 1이 만료되어 포트에 바인딩하려고하면 작동하지만 인증서 2는 오류 1312로 실패합니다.

나를 당황하게 한 주요 차이점은 Unique container name 속성이었습니다. 하드 드라이브의 물리적 키 파일을 나타내야합니다.%ProgramData%\Microsoft\Crypto\RSA\MachineKeys\

인증서 1의 경우 파일이 있지만 인증서 2의 경우 해당 파일이 없습니다. 검색 후 폴더의 하위 폴더에서 인증서 2에 대한 파일을 찾았습니다 %AppData%\Microsoft\Crypto\. 이는 컴퓨터 수준 키가 아닌 사용자 별 키입니다. 인증서를 컴퓨터 저장소로 가져 오는 것은 놀랍지 만 항상 사용자 저장소의 컨테이너 키를 유지합니다.

AppData 폴더에서 '55edfcc149408fb990a3bacd6d31126b_3277b2c9-9894-46d0-9b64-30f0d6589239'파일을 삭제하고 저장소에서 내 인증서 2에 대한 복구 명령을 실행했습니다.

certutil -repairstore My 2

이번에는 고유 컨테이너 이름이 '% ProgramData % \ Microsoft \ Crypto \'아래의 적절한 폴더에있는 파일을 반영하고 모든 것이 작동하기 시작했습니다.

이것이 누군가에게 도움이되기를 바랍니다.


인터넷 서버의 특정 포트를 통해 자체 호스팅 (콘솔 애플리케이션) 웹 서비스를 보호하기 위해 공식 Thawte 인증서구입했습니다 . 그런 다음 Thawte 인증서를 받고이를 인터넷 서버에 mmc로 설치했습니다 (인증서는 "신뢰할 수있는 루트 인증 기관"아래에서 볼 수있었습니다 (이미지의 키 아이콘으로 인증서에 필수 항목 인 개인 키가 포함되어 있음을 보여줍니다). btw) 포트에 바인딩 할 수 있습니다.

다음 단계는 <port>https 대해 활성화하는 것 입니다.

netsh http add urlacl url=https://+:<port>/ user=everyone

(문제 없었던 것)

다음 단계는 https에 대한 포트 ()를 활성화하는 것입니다.

netsh http add sslcert ipport=0.0.0.0:<port> certhash=<thumbprint to certificate> appid={<guid to application>}

다음 오류 메시지와 함께 실패했습니다.
SSL 인증서 추가 실패, 오류 : 1312 지정된 로그온 세션이 없습니다. 이미 종료되었을 수 있습니다.

그런 다음 인터넷을 검색하고 다양한 제안 된 해결 방법을 시도했습니다 (성공하지 않음).

제 경우에 대한 해결책은 netsh 명령에 certstorename = Root를 추가하는 것입니다.

netsh http add sslcert ipport=0.0.0.0:<port *1)> certstorename=Root certhash=<thumbprint to certificate *2)> appid={<guid to application *3)>}

참고 : net netsh 명령에 certstorename이 적용 되지 않은
경우 netsh는 기본값 인 MY를 사용합니다 (인증서 저장소 대상 : 자체 서명 된 인증서가 정상적으로 저장 되는 " 개인 " ). 루트 는 인증서 저장소를 대상으로합니다. "신뢰할 수있는 루트 인증 기관"

* 1) : 연결을 사용하려는 포트
* 2) : 인증서를 열면 인증서에 지문을 추출 할 수 있습니다 (Windows 시스템에서는 탐색기에서 인증서를 두 번 클릭하기 만하면 됨).- "세부 정보"탭을 선택합니다. "Thumbprint"를 클릭합니다. 그러면 "지문"이 표시되고 복사 할 수 있습니다. 지문을 복사하고 모든 공백을 제거합니다 ...
* 3) : APPID는 정보 용일 뿐이므로 {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} 형식의 모든 ID를 사용할 수 있습니다. "netsh http show sslcert"명령을 사용하면 전체 시스템에서 바인딩 된 인증서를 쿼리 할 수 ​​있으며 어떤 appid가 어떤 인증서에 바인딩되어 있는지 정보를 볼 수 있습니다 (실제로는 실제로 도움이되지 않음 btw). 제 경우에는 VS 생성) 내 웹 서비스 응용 프로그램에 대한 GUID


나는 하루 종일 오류 1312와 싸우고 있는데, 나를 위해 수정 된 것은 .crt 대신 .p12 파일로 mmc의 인증서를 가져 오는 것입니다. OpenSSL로 작성하는 경우 .crt를 작성한 후 다음을 수행하십시오.

pkcs12 -export -in server.crt -inkey server.key -name “Your Name” -out server.p12

설명대로 . mmc로 가져 오면 "개인 정보 교환"파일이됩니다 (그리고 분명히 .pfx 파일도 작동합니다).

나는 서버를 작성하고 SSL을 다루는 것이 처음이고 이것이 왜 작동하는지 모르겠지만 도움이되기를 바랍니다.


내 경우 문제는 CER 파일에 개인 키가 첨부되어 있지 않다는 것입니다.

OpenSSL 명령을 사용하여 PK를 첨부했습니다.

openssl x509 -in server.der -inform DER -out server.pem -outform PEM
openssl pkcs12 -export -in server.pem -inkey serverkey.pem -out server.p12

CER / DER 파일에서 작동합니다.


문제는 4 단계에있었습니다. certhash의 값에 대해 루트 인증서의 지문을 사용하고있었습니다. 이를 해결하기 위해 MMC로 돌아가 인증서 (로컬 컴퓨터)-> 개인-> 인증서 폴더를 새로 고쳐야했습니다. 그런 다음 루트 인증 기관에서 "발급 한"인증서의 지문을 사용합니다.


이 오류를 수신하는 방법에는 여러 가지가 있습니다 (다른 답변은 위 참조).

이 특정 오류를 수신하는 또 다른 방법은 인증서가 적절한 저장소에 없을 때 인증서를 포트에 바인딩하는 것입니다.

인증서가 localMachine 루트 저장소에 저장되어 있는지 확인합니다 (명령 줄에서 certutil 또는 certmgr.exe를 사용하여 올바르게 덤프 할 수 있음).

업데이트 된 문법 :)


나는 같은 문제가 있었고 다음 명령을 사용하여 인증서 가져 오기를 해결했습니다.

c:> certutil -importPFX certname.pfx

이제 다음 명령을 사용하여 인증서가 나타납니다.

c:> certutil -store my

이 명령 전에 인증서가 나타나지 않습니다.


이것은 명백해 보일 수 있습니다. 그러나 나는 그것이 누군가의 머리를 긁는 시간을 절약 할 수 있다고 생각합니다. 내 개인 인증서 폴더 (개인용 컴퓨터 계정 용) 아래에 확장자가 .cer 인 파일을 가져 왔습니다. 잠시 후 * .pfx 확장자로 파일을 가져와야한다는 것을 깨달았습니다. 그것을 고치고 voilà! 문제 해결됨!


만약:

  1. 컴퓨터에 IIS가 없었으며 (자체 호스팅 WCF로 작업한다고 가정 해 보겠습니다)
  2. IIS 관리자를 사용하여 다른 컴퓨터에서 인증서를 요청했습니다 (개인 키가 인증서 요청에 포함 된 암호에서 나온다는 것을 이해하지 못했기 때문에 나중에 발급 된 .pb7).

그때:

  1. .pb7인증서 요청 (로컬 머신 / 개인 / 인증서-mmc 사용)을 만드는 데 사용한 IIS 머신에를 설치하십시오 .
  2. 개인 키 (암호 할당)를 포함하여 해당 컴퓨터에서 인증서를 내 보냅니다.
  3. WCF 서버에서 mmc를 사용하여 설치합니다 (로컬 컴퓨터 / 개인 / 인증서-mmc 사용).

그런 다음 netsh포트 443에 바인딩 할 수 있습니다. 더 이상 1312 오류가 없습니다.


링에 또 다른 대답을 던지기 위해 이것이 내가 가진 문제입니다.

인증서를 (Local Computer)\...인증서 저장소 로 가져 왔지만 Trusted Root Certification Authorities섹션 으로 가져 왔습니다 . Personal섹션 으로 가져와야 했습니다. 그렇지 않으면이 오류가 발생했습니다.


If anyone else runs into this problem and the answers in here do not clearly answer it, the underlying core problem is the private key needs to be imported. If you do not mark the certificate as exportable when you import it, the private key is not imported and you cannot bind it. If you delete it and re-import it and mark it as exportable, then it will work.

It also needs to be the local machine store as others have pointed out.


I had exact same problem eventhough my .pfx file had private key. Adding of certificate with MMC console was successful, but adding programatically using .Net X509Store.Add(X509Certificate2) method failed every time with error 1312. Certificate even had a key sign on the icon.
After several days finaly decided to make new certificate using makecert.exe as suggested in posts here. After that everything was fine. Key appeared in %ProgramData%\Microsoft\Crypto\RSA\MachineKeys. For some reason my earlier pfx file was not compatible.

In my experience, as long as your key in not appearing in %ProgramData%\Microsoft\Crypto\RSA\MachineKeys\, binding with 'netsh http add sslcert ....' will fail.


The certstorename argument should be the string value of the StoreName enumeration from the .net framework namespace System.Security.Cryptography.X509Certificates.


I've being working on this for hours, and basically read through what @DoomerDGR8 said above, but my fix was a lot more simple. I ran

 C:\Windows\system32> certutil -store TRUSTEDPUBLISHER

This listed several certificates I have installed, I then ran repair store on the certificate that I was having a problem installing with netsh.

C:\Windows\system32> certutil -repairstore TRUSTEDPUBLISHER 6

The number 6 at the end represents the index of your certificate, found at in the store, hope this helps


In my case while creating the certificate I chose a different name than My for my Cert Store name. The default name is MY. So if yours is different append certstorename=Your provided store name to the command.


I had the same error when creating self signed certificate with OpenSSL(BouncyCastle) I resolved it with help from this post: Cannot export generated certificate with private key to byte array in .net 4.0/4.5

I had to add:

        RsaPrivateKeyStructure rsa = RsaPrivateKeyStructure.GetInstance(seq); //new RsaPrivateKeyStructure(seq);
        RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(
            rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

        var rsaPriv = DotNetUtilities.ToRSA(rsaparams);

        var cspParams = new CspParameters
        {
            KeyContainerName = Guid.NewGuid().ToString(),
            KeyNumber = (int)KeyNumber.Exchange,
            Flags = CspProviderFlags.UseMachineKeyStore
        };

        var rsaPrivate = new RSACryptoServiceProvider(cspParams);**

        // Import private key from BouncyCastle's rsa
        rsaPrivate.ImportParameters(rsaPriv.ExportParameters(true));

        // Set private key on our X509Certificate2
        x509.PrivateKey = rsaPrivate;

So to add (yet) fix/situation.

I had C# code that used BouncyCastle to create self-signed certificates.

<packages>
  <package id="BouncyCastle" version="1.8.1" targetFramework="net45" />

So my code created the certificates AND placed them in the correct locations in the Cert-Store.

Using the hints here, my install of On Premise Service Bus 1.1 was failing...and that led me here.

I ended up DELETING both certificates my BouncyCastle code had created (from the cert store) and reimporting them (with private keys)....and it all worked. I imported FIRST to the

Certificates (Local Computer) / Personal / Certificates

then I copied pasted (in the mmc) to any other places (stores) I needed them.

My "before" and "after" looked exactly the same from my eyes in MMC, BUT it fixed the issue. Go figure.


I just had yet another error. I renewed an expired cert for our WorkFolders service from our CA using the same private key. Then I always got Error 1312. Even if Certificate Management shows I have a private key.
I could only solve the problem by re-issuing a new certificate (without the renew option). Then it worked on the first try.
Maybe this will help someone who also tried the renew option.


In my case, i have missing the certificate private key.


IF you imported the certificate using .NET, specific import flags must be used:

/// <summary>
/// Imports X.509 certificate from file to certificate store.
/// </summary>
/// <param name="fileName">Certificate file.</param>
/// <param name="password">Password.</param>
/// <param name="storeName">Store name.</param>
/// <param name="storeLocation">Store location.</param>
public static void ImportCertificate(string fileName, string password, StoreName storeName, StoreLocation storeLocation) {
    var keyStorageFlags =
        X509KeyStorageFlags.PersistKeySet
        | (storeLocation == StoreLocation.LocalMachine ? X509KeyStorageFlags.MachineKeySet : X509KeyStorageFlags.UserKeySet);
    var cert = new X509Certificate2(fileName, password, keyStorageFlags);
    var store = new X509Store(storeName, storeLocation);
    store.Open(OpenFlags.MaxAllowed);
    store.Add(cert);
    store.Close();
}

The ImportCertificate method is a part of the Woof.Security package created by me.

참고URL : https://stackoverflow.com/questions/13076915/ssl-certificate-add-failed-when-binding-to-port

반응형