Microsoft MVP성태의 닷넷 이야기
오류 유형 : 95. WCF 인증서 설정 관련 오류 정리 [링크 복사], [링크+제목 복사],
조회: 20646
글쓴 사람
정성태 (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)
13541정성태1/29/20241980VS.NET IDE: 188. launchSettings.json의 useSSL 옵션
13540정성태1/29/20242116Linux: 69. 리눅스 - "Docker Desktop for Windows" Container 환경에서 IPv6 Loopback Address 바인딩 오류
13539정성태1/26/20242372개발 환경 구성: 703. Visual Studio - launchSettings.json을 이용한 HTTP/HTTPS 포트 바인딩
13538정성태1/25/20242428닷넷: 2211. C# - NonGC(FOH) 영역에 .NET 개체를 생성파일 다운로드1
13537정성태1/24/20242540닷넷: 2210. C# - Native 메모리에 .NET 개체를 생성파일 다운로드1
13536정성태1/23/20242603닷넷: 2209. .NET 8 - NonGC Heap / FOH (Frozen Object Heap) [1]
13535정성태1/22/20242485닷넷: 2208. C# - GCHandle 구조체의 메모리 분석
13534정성태1/21/20242261닷넷: 2207. C# - SQL Server DB를 bacpac으로 Export/Import파일 다운로드1
13533정성태1/18/20242490닷넷: 2206. C# - TCP KeepAlive의 서버 측 구현파일 다운로드1
13532정성태1/17/20242368닷넷: 2205. C# - SuperSimpleTcp 사용 시 주의할 점파일 다운로드1
13531정성태1/16/20242289닷넷: 2204. C# - TCP KeepAlive에 새로 추가된 Retry 옵션파일 다운로드1
13530정성태1/15/20242213닷넷: 2203. C# - Python과의 AES 암호화 연동파일 다운로드1
13529정성태1/15/20242096닷넷: 2202. C# - PublishAot의 glibc에 대한 정적 링킹하는 방법
13528정성태1/14/20242235Linux: 68. busybox 컨테이너에서 실행 가능한 C++, Go 프로그램 빌드
13527정성태1/14/20242158오류 유형: 892. Visual Studio - Failed to launch debug adapter. Additional information may be available in the output window.
13526정성태1/14/20242245닷넷: 2201. C# - Facebook 연동 / 사용자 탈퇴 처리 방법
13525정성태1/13/20242211오류 유형: 891. Visual Studio - Web Application을 실행하지 못하는 IISExpress
13524정성태1/12/20242300오류 유형: 890. 한국투자증권 KIS Developers OpenAPI - GW라우팅 중 오류가 발생했습니다.
13523정성태1/12/20242100오류 유형: 889. Visual Studio - error : A project with that name is already opened in the solution.
13522정성태1/11/20242242닷넷: 2200. C# - HttpClient.PostAsJsonAsync 호출 시 "Transfer-Encoding: chunked" 대신 "Content-Length" 헤더 처리
13521정성태1/11/20242305닷넷: 2199. C# - 한국투자증권 KIS Developers OpenAPI의 WebSocket Ping, Pong 처리
13520정성태1/10/20242077오류 유형: 888. C# - Unable to resolve service for type 'Microsoft.Extensions.ObjectPool.ObjectPool`....'
13519정성태1/10/20242135닷넷: 2198. C# - Reflection을 이용한 ClientWebSocket의 Ping 호출파일 다운로드1
13518정성태1/9/20242386닷넷: 2197. C# - ClientWebSocket의 Ping, Pong 처리
13517정성태1/8/20242219스크립트: 63. Python - 공개 패키지를 이용한 위성 이미지 생성 (pystac_client, odc.stac)
13516정성태1/7/20242343닷넷: 2196. IIS - AppPool의 "Disable Overlapped Recycle" 옵션의 부작용
1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...