Microsoft MVP성태의 닷넷 이야기
오류 유형 : 95. WCF 인증서 설정 관련 오류 정리 [링크 복사], [링크+제목 복사],
조회: 20657
글쓴 사람
정성태 (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)
13338정성태5/6/20234407닷넷: 2112. C# 12 - 기본 람다 매개 변수파일 다운로드1
13337정성태5/5/20234917Linux: 59. dockerfile - docker exec로 container에 접속 시 자동으로 실행되는 코드 적용
13336정성태5/4/20234740.NET Framework: 2111. C# - 바이너리 출력 디렉터리와 연관된 csproj 설정
13335정성태4/30/20234772.NET Framework: 2110. C# - FFmpeg.AutoGen 라이브러리를 이용한 기본 프로젝트 구성 - Windows Forms파일 다운로드1
13334정성태4/29/20234428Windows: 250. Win32 C/C++ - Modal 메시지 루프 내에서 SetWindowsHookEx를 이용한 Thread 메시지 처리 방법
13333정성태4/28/20233836Windows: 249. Win32 C/C++ - 대화창 템플릿을 런타임에 코딩해서 사용파일 다운로드1
13332정성태4/27/20233910Windows: 248. Win32 C/C++ - 대화창을 위한 메시지 루프 사용자 정의파일 다운로드1
13331정성태4/27/20233943오류 유형: 856. dockerfile - 구 버전의 .NET Core 이미지 사용 시 apt update 오류
13330정성태4/26/20233584Windows: 247. Win32 C/C++ - CS_GLOBALCLASS 설명
13329정성태4/24/20233795Windows: 246. Win32 C/C++ - 직접 띄운 대화창 템플릿을 위한 Modal 메시지 루프 생성파일 다운로드1
13328정성태4/19/20233465VS.NET IDE: 184. Visual Studio - Fine Code Coverage에서 동작하지 않는 Fake/Shim 테스트
13327정성태4/19/20233871VS.NET IDE: 183. C# - .NET Core/5+ 환경에서 Fakes를 이용한 단위 테스트 방법
13326정성태4/18/20235350.NET Framework: 2109. C# - 닷넷 응용 프로그램에서 SQLite 사용 (System.Data.SQLite) [1]파일 다운로드1
13325정성태4/18/20234627스크립트: 48. 파이썬 - PostgreSQL의 with 문을 사용한 경우 연결 개체 누수
13324정성태4/17/20234447.NET Framework: 2108. C# - Octave의 "save -binary ..."로 생성한 바이너리 파일 분석파일 다운로드1
13323정성태4/16/20234384개발 환경 구성: 677. Octave에서 Excel read/write를 위한 io 패키지 설치
13322정성태4/15/20235203VS.NET IDE: 182. Visual Studio - 32비트로만 빌드된 ActiveX와 작업해야 한다면?
13321정성태4/14/20234003개발 환경 구성: 676. WSL/Linux Octave - Python 스크립트 연동
13320정성태4/13/20233914개발 환경 구성: 675. Windows Octave 8.1.0 - Python 스크립트 연동
13319정성태4/12/20234403개발 환경 구성: 674. WSL 2 환경에서 GNU Octave 설치
13318정성태4/11/20234276개발 환경 구성: 673. JetBrains IDE에서 "Squash Commits..." 메뉴가 비활성화된 경우
13317정성태4/11/20234338오류 유형: 855. WSL 2 Ubuntu 20.04 - error: cannot communicate with server: Post http://localhost/v2/snaps/...
13316정성태4/10/20233597오류 유형: 854. docker-compose 시 "json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)" 오류 발생
13315정성태4/10/20233838Windows: 245. Win32 - 시간 만료를 갖는 컨텍스트 메뉴와 윈도우 메시지의 영역별 정의파일 다운로드1
13314정성태4/9/20234000개발 환경 구성: 672. DosBox를 이용한 Turbo C, Windows 3.1 설치
13313정성태4/9/20234035개발 환경 구성: 671. Hyper-V VM에 Turbo C 2.0 설치 [2]
1  2  3  4  5  6  7  8  9  10  11  [12]  13  14  15  ...