Microsoft MVP성태의 닷넷 이야기
오류 유형 : 95. WCF 인증서 설정 관련 오류 정리 [링크 복사], [링크+제목 복사]
조회: 20617
글쓴 사람
정성태 (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]

[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13607정성태4/25/2024185닷넷: 2248.C# - 인터페이스 타입의 다중 포인터를 인자로 갖는 C/C++ 함수 연동
13606정성태4/24/2024200닷넷: 2247. C# - tensorflow 연동 (MNIST 예제)파일 다운로드1
13605정성태4/23/2024366닷넷: 2246. C# - Python.NET을 이용한 파이썬 소스코드 연동파일 다운로드1
13604정성태4/22/2024400오류 유형: 901. Visual Studio - Unable to set the next statement. Set next statement cannot be used in '[Exception]' call stack frames.
13603정성태4/21/2024703닷넷: 2245. C# - IronPython을 이용한 파이썬 소스코드 연동파일 다운로드1
13602정성태4/20/2024801닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
13601정성태4/19/2024850닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/2024877닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024869닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024889닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드2
13597정성태4/15/2024878닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/20241067닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/20241051닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241069닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241084닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241219C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241198닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241079Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241154닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241268닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신 [2]파일 다운로드1
13587정성태3/27/20241170오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241335Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241131Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241249개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241471Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...