Microsoft MVP성태의 닷넷 이야기
오류 유형 : 95. WCF 인증서 설정 관련 오류 정리 [링크 복사], [링크+제목 복사],
조회: 28112
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 2개 있습니다.)
WCF 인증서 설정 관련 오류 정리


WCF 사용자 정의 인증 구현 예제는, 사실 구현보다는 문제가 발생했을 때 오류에 대한 대응이 더 어렵습니다. 설정이 조금이라도 틀리면 오류가 발생하게 되고, 추상화가 워낙 잘 되어 있다보니 도대체 어느 설정에서 잘못되었는지 알 수 없을 때가 많기 때문입니다.

이번 회에서는 대표적인 오류 유형에 따른 원인을 살펴보겠습니다. 즉, 여기 나오는 예외들은 아래의 글을 실습하면서 만날 수 있는 유형들입니다.

WCF 사용자 정의 인증 구현 예제
; https://www.sysnet.pe.kr/2/0/864



System.InvalidOperationException:
The ChannelDispatcher at 'net.tcp://localhost:9001/myservice' with contract(s) '"IHelloWorld"' is unable to open its IChannelListener. ---> System.InvalidOperationException: The ChannelDispatcher at 'net.tcp://localhost:9001/myservice' with contract(s) '"IssueAndRenewSession"' is unable to open its IChannelListener. ---> System.InvalidOperationException: The service certificate is not provided. Specify a service certificate in ServiceCredentials.




위와 같은 오류는 그래도 양반입니다. ^^ "The service certificate is not provided. Specify a service certificate in ServiceCredentials."과 같이 메시지에 해답이 있기 때문입니다. 해당 서비스가 clientCredentialType="UserName" 설정을 포함하기 때문에 보안을 위해 인증서를 필요로 하는데 <serviceCertificate /> 구성이 없기 때문에 발생한다는 것을 알 수 있습니다. 해결하기 위해서는 다음과 같은 식의 구성을 포함해야 겠지요.

<serviceCertificate
        findValue="myserver"
        x509FindType="FindBySubjectName"
        storeLocation="LocalMachine"
        storeName="Root" />




System.InvalidOperationException:
Cannot find the X.509 certificate using the following search criteria: StoreName 'Root', StoreLocation 'LocalMachine', FindType 'FindBySubjectName', FindValue 'myserver'.



역시 메시지에서 보는 것처럼 <serviceCertificate />에 지정된 인증서를 찾을 수 없기 때문에 발생한다는 것을 알 수 있습니다. 위의 예에서는 StoreLocation == "LocalMachine"인데 이 위치는 "인증서 관리자"에서 보면 "Local Computer" 영역이고 StoreName == "Root"는 "Trusted Root Certification Authorities"이므로 "SubjectName"이 "myserver"이라면 다음과 같은 영역에 인증서가 위치해 있어야 합니다.

wcf_username_auth_config_error_1.png




System.ArgumentException:
The certificate 'CN=myserver' must have a private key that is capable of key exchange. The process must have access rights for the private key.



이렇게 오류나는 경우는 해당 인증서가 "key exchange" 용으로 생성되지 않아서입니다. makecert를 이용해서 생성한 경우라면 다음과 같이 반드시 exchange 옵션을 주어야 합니다.

makecert -n "CN=myserver" -r -sky exchange -sv mycert.pvk mycert.cer




System.ServiceModel.AddressAccessDeniedException: HTTP could not register URL http://+:9000/. Your process does not have access rights to this namespace (see http://go.microsoft.com/fwlink/?LinkId=70353 for details). ---> System.Net.HttpListenerException: Access is denied


이 오류는 뭐... 워낙 유명해서. ^^
대부분 Vista/7 이상의 운영체제에서 "관리자 권한"으로 실행되지 않은 응용 프로그램 내부에 WCF 서비스를 호스팅 할 때 발생합니다. (XP인 경우에도 비관리자 계정으로 로그한 경우 발생합니다.) 사용하려는 포트(위의 예에서는 9000번)를 미리 등록해 주어야 하는데 일반 사용자 권한으로는 등록할 수 없기 때문에 위와 같은 오류가 발생하는 것입니다.

물론, 방법은 간단합니다. "관리자 권한"으로 실행한 명령행에서 다음과 같이 포트를 등록해 주면 됩니다.

netsh http add urlacl url=http://+:9000/ user="[계정]"

(엄밀히는 포트가 아닌 URL 단위인데, 자세한 설명은 생략합니다.)




System.ServiceModel.AddressAlreadyInUseException:
HTTP could not register URL http://+:9000/. Another application has already registered this URL with HTTP.SYS. ---> System.Net.HttpListenerException: Failed to listen on prefix 'http://+:9000/' because it conflicts with an existing registration on the machine.



"netsh http add urlacl"을 많이 사용하다 보면 이런 오류를 만날 가능성이 쪼끔 있습니다. ^^ 같은 포트로 이미 등록되어 있기 때문에 사용할 수 없다는 것입니다. 그런데... 가만 생각해 보면 이미 등록되어 있다면 그걸 사용하면 될 텐데 왜... 이런 오류가 발생했느냐는 것입니다.

이유는 "netsh http show urlacl"을 이용해서 현재 등록된 URL을 확인해 봐야 합니다. 위와 같은 오류가 발생했다면 아마도 같은 포트에 다음과 같은 식으로 스키마가 다른 체로 이미 등록되어 있는 경우입니다.

Reserved URL            : https://+:9000/
    User: TEST\mytestAccount
        Listen: Yes
        Delegate: No
        SDDL: D:(A;;GX;;;S-...[생략]...-1000)

보시는 것처럼, 현재 사용하려는 URL은 "http://+:9000/"인데, 이미 그 포트로 등록된 스키마는 "https://+:9000/"으로 충돌이 발생한 것입니다. 관리자 계정으로 실행한 "명령행"에서 "netsh http delete urlacl url=https://+:9000/"와 같은 식으로 기존 등록된 URL을 삭제해 주고 다시 http 스키마로 등록해 주면 됩니다.




잠시 오류 정리를 벗어나서. 사용자 정의 인증 모듈에서 Validate 메서드 안에서 인증을 허용하지 않는다면 예외를 발생하면 된다고 했는데요. 이에 대해서 다음의 블로그에서,

Silverlight 3: Securing your WCF service with a custom username / password authentication mechanism 
; http://blogs.infosupport.com/blogs/alexb/archive/2009/10/02/silverlight-3-securing-your-wcf-service-with-a-custom-username-and-password-authentication-mechanism.aspx

아래와 같은 언급이 있습니다.

If validation fails, throw a SecurityTokenException if you want a non informative message or a FaultException if you want a informative message. If validation succeeds, just do nothing.



실제로 각각 아래와 같은 코드로 테스트를 해보면,

throw new FaultException("Test account can be authenticated ONLY.");
throw new SecurityTokenException("Test account can be authenticated ONLY.");

SecurityTokenException으로 한 경우, 인자에 지정된 문자열이 다음과 같이 예외 메시지에서 나타나지 않습니다.

System.ServiceModel.Security.MessageSecurityException:
An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail. ---> System.ServiceModel.FaultException: An error occurred when processing the security tokens in the message.



대신 FaultException으로 한 경우에는 정상적으로 문자열 정보가 넘어오게 됩니다.

System.ServiceModel.Security.MessageSecurityException:
An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail. ---> System.ServiceModel.FaultException: Test account can be authenticated ONLY.



어느 쪽을 선택하실 건가요? ^^




인증서까지 정상적으로 설치했는데 다음과 같은 오류가 발생하는 경우가 있습니다.

System.ArgumentException:
The certificate 'CN=myserver' must have a private key that is capable of key exchange. The process must have access rights for the private key. ---> System.Security.Cryptography.CryptographicException: Keyset does not exist



얼핏 보면, 이전에 "key exchange" 유형으로 인증서를 만들지 않았을 때와 오류 메시지가 비슷한데요. 한가지 차이점은 "Keyset does not exist" 메시지가 있다는 정도입니다. 이런 경우에는 해당 인증서의 개인키에 대한 "파일 접근 권한"이 없어서입니다.

FindPrivateKey 유틸리티를 이용해서 해당 인증서의 개인키 물리 파일 위치를 알아내고 cacls.exe를 이용해서 권한을 적절하게 부여해 주면 됩니다. 자세한 내용은 다음에서 참조하세요.

인증서의 개인키를 담은 물리 파일 위치 알아내는 방법
; https://www.sysnet.pe.kr/2/0/865




이번 오류는 클라이언트를 실행할 때 발생할 수 있습니다.

System.ServiceModel.Security.MessageSecurityException:
Identity check failed for outgoing message. The expected DNS identity of the remote endpoint was '192.168.1.2' but the remote endpoint provided DNS claim 'myserver'. If this is a legitimate remote endpoint, you can fix the problem by explicitly specifying DNS identity 'myserver' as the Identity property of EndpointAddress when creating channel proxy.



다행히 위의 경우에도 오류 메시지에 답이 있습니다. 이런 상황은 인증서를 생성할 때 지정한 "CN=" 값이 WCF 클라이언트에서 endpoint에 지정한 주소와 다른 경우에 발생합니다.

예를 들어, 서버 측에서 사용한 인증서는 "CN=myserver"로 생성했는데, WCF 클라이언트 측에서는 endpoint 설정을 다음과 같이 한 경우입니다.

<endpoint name="TcpNetConf"
    address="net.tcp://192.168.1.2:9001/myservice"
    binding="netTcpBinding"
    bindingConfiguration="netTcpBindingConf"
    behaviorConfiguration="netTcpBehavior"
    contract="WcfLibrary.IHelloWorld">
</endpoint>

이런 경우에는 해결 방법이 다양합니다.

  1. 인증서를 CN=192.168.1.2로 해서 다시 받는다.
  2. 또는, 접근 주소를 CN=myserver에 지정된 것처럼 "net.tcp://myserver:9001/myservice"로 변경한다.
  3. 또는, identity 설정을 이용한다.

2번의 경우, myserver 이름에 대한 IP가 정상적으로 풀이되지 않는다면 임시적으로 HOSTS 파일을 이용해서 지정해 주는 것으로 우회할 수 있습니다.

3번의 경우를 자세히 살펴봐야 할텐데요. 위와 같이 CN=myserver로 지정된 인증서를 유효하게 받아들이고 싶다면 다음과 같이 endpoint에 identity 설정을 해주는 것으로 해결할 수 있습니다

<endpoint name="TcpNetConf"
    address="net.tcp://192.168.1.2:9001/myservice"
    ...[생략]...
    contract="WcfLibrary.IHelloWorld">

    <identity>
        <dns value="myserver"/>
    </identity>

</endpoint>




[이 토픽에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 6/12/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2012-06-19 08시53분
[수강생] WCF Service를 wsHttpBinding 으로 구현작업 중에 있습니다.
인증서 관련해서 문의 드립니다.
위의 순서대로 진행을 햇는데 FindPrivateKey 유틸리티 가 존재 자지 않았습니다.
제 PC의 경로는 C:\Program Files\Microsoft SDKs\Windows\v7.1\Samples 폴더안에 FindPrivateKey 존재하지 않더라구요
다른 설치파일들이 피요한건가요?
그리고 위의 방법대로 하면 인증서 검사를 Web.config 에서 인증서 유무를 검사할수 있는건가요?

아차 그리고 makecert 를 통해 인증서를 만들었습니다. 인증서의 확장자가 .cer / .pvk 이러한 종류들이 있는데 어떤 확장자의 인증서로 인증을 해야하나요?

제가 잘 몰라서요 답변 부탁드리겠습니다.
[guest]
2012-06-20 12시24분
일단, findprivatekey는 다음의 파일에 포함되어 있습니다.

Windows Communication Foundation (WCF) and Windows Workflow Foundation (WF) Samples for .NET Framework 4
; (broken) http://www.microsoft.com/en-us/download/details.aspx?id=21459

Windows Communication Foundation (WCF) samples
; https://docs.microsoft.com/en-us/dotnet/framework/wcf/samples/

그 외의 질문들은 다음의 글을 읽어보시고 다시 모르는 부분에 대해서 질문해 주세요. ^^

인증서 관련(CER, PVK, SPC, PFX) 파일 만드는 방법
; http://www.sysnet.pe.kr/2/0/863

WCF 사용자 정의 인증 구현 예제
; http://www.sysnet.pe.kr/2/0/864
정성태
2012-06-20 11시37분
[수강생] 답변 감사드립니다.
걸어주신 링크 참고해서 인증서도 만들고 findprivatekey 를 사용해서 인증서를 찾고 또한 Icacls.exe 를 통해 권한도 주었습니다.
Cacls.exe 가 아니랑 Icacls.exe 더라구요. windosw 7 환경입니다.
위의 절차대로 잘 되고 있는데. 오류가 발생하더군요
"키 세트가 없습니다." 왜 발생하는지 모르겠습니다.

구성파일쪽에 다른 추가되어야 하는 부분이 있는건가요??
[guest]
2012-06-20 04시15분
[수강생] 제가 질문 드린 "키 세트가 없습니다." 오류 문제 해결했습니다.

C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys

MachineKeys 폴더의 권한이 없어서 발생한 오류였습니다.
감사합니다.
[guest]

... 136  137  [138]  139  140  141  142  143  144  145  146  147  148  149  150  ...
NoWriterDateCnt.TitleFile(s)
1637정성태2/14/201426849Windows: 89. 컴퓨터를 껐는데도 어느 순간 자동으로 켜진다면? - 두 번째 이야기
1636정성태2/14/201422906Windows: 88. Hyper-V가 설치된 컴퓨터의 윈도우 백업 설정
1635정성태2/14/201423695오류 유형: 221. SharePoint - System.InvalidOperationException: The farm is unavailable.
1634정성태2/14/201423906.NET Framework: 424. C# - CSharpCodeProvider로 컴파일한 메서드의 실행이 일반 메서드보다 더 빠르다? [1]파일 다운로드1
1633정성태2/13/201426786오류 유형: 220. 2014년 2월 13일 이후로 Visual Studio 2010 Macro가 동작하지 않는다면? [3]
1632정성태2/12/201444777.NET Framework: 423. C#에서 DirectShow를 이용한 미디어 재생 [2]파일 다운로드1
1631정성태2/11/201423557개발 환경 구성: 217. Realtek 사운드 장치에서 재생되는 오디오를 GraphEditor로 녹음하는 방법
1630정성태2/5/201424044개발 환경 구성: 216. Hyper-V에 올려진 윈도우 XP VM에서 24bit 컬러 및 ClearType 활성화하는 방법
1629정성태2/5/201433807개발 환경 구성: 215. DOS batch - 하나의 .bat 파일에서 다중 .bat 파일을 (비동기로) 실행하는 방법 [1]
1628정성태2/4/201435178Windows: 87. 윈도우 8.1에서 .NET 3.5 설치가 안된다면? [2]
1627정성태2/4/201430290개발 환경 구성: 214. SQL Server Reporting Services를 이용해 간단한 리포트 제작하는 방법
1626정성태2/4/201422313Windows: 86. 윈도우 8.1의 Skydrive 내용이 동기화가 안된다면?
1625정성태2/2/201429403.NET Framework: 422. C++과 C#의 Event 공유파일 다운로드1
1624정성태2/2/201425092.NET Framework: 421. ASP.NET에서 Server.CreateObject와 COM Interop 클래스 생성의 차이점
1623정성태2/1/201429819개발 환경 구성: 213. x86/x64별로 나뉘어진 어셈블리를 한 프로젝트에서 참조하는 방법 [1]파일 다운로드1
1622정성태1/31/201430100VC++: 74. 어떤 것을 쓰면 좋을까요? wvnsprintf, _vsnwprintf_s, StringCbVPrintfW [4]
1621정성태1/31/201421931.NET Framework: 420. 베트남의 11학년(한국의 고2)이 45분만에 푼다는 알고리즘 문제파일 다운로드1
1620정성태1/30/201431992.NET Framework: 419. C# - BigDecimal파일 다운로드1
1619정성태1/30/201428669VS.NET IDE: 85. T4를 이용한 INotifyPropertyChanged 코드 자동 생성파일 다운로드1
1618정성태1/29/201444323Linux: 2. 우분투에서 Active Directory 계정을 이용한 파일 공유
1617정성태1/29/201425608.NET Framework: 418. Thread.Abort 호출의 hang 현상 [1]
1616정성태1/29/201426158디버깅 기술: 63. windbg 디버깅 사례: AppDomain 간의 static 변수 사용으로 인한 crash
1615정성태1/29/201427991.NET Framework: 417. WPF WebBrowser 컨트롤에서 SHDocVw.IWebBrowser2 인터페이스를 구하는 방법 및 순수 WPF 웹 브라우저 컨트롤 소개
1614정성태1/29/201425048.NET Framework: 416. System.Net.Sockets.NetworkStream이 Thread-safe할까?파일 다운로드1
1613정성태1/29/201426924.NET Framework: 415. IIS 작업자 프로세스 재생(recycle)하는 방법 [1]
1612정성태1/29/201423683오류 유형: 219. IIS 500 Internal Server Error - Skydrive에 공유된 경우
... 136  137  [138]  139  140  141  142  143  144  145  146  147  148  149  150  ...