이 샘플에서는 사용자 지정 X.509 인증서 유효성 검사기를 구현하는 방법을 보여 줍니다. 이는 기본 제공 X.509 인증서 유효성 검사 모드가 애플리케이션 요구 사항에 적합하지 않은 경우에 유용합니다. 이 샘플에서는 자체 발급된 인증서를 허용하는 사용자 지정 유효성 검사기가 있는 서비스를 보여 줍니다. 클라이언트는 이러한 인증서를 사용하여 서비스에 인증합니다.
참고: 누구나 자체 발급 인증서를 생성할 수 있으므로 서비스에서 사용하는 사용자 지정 유효성 검사기는 ChainTrust X509CertificateValidationMode에서 제공하는 기본 동작보다 안전하지 않습니다. 프로덕션 코드에서 이 유효성 검사 논리를 사용하기 전에 이러한 보안 영향을 신중하게 고려해야 합니다.
요약하면 이 샘플은 다음 방법을 보여 줍니다.
X.509 인증서를 사용하여 클라이언트를 인증할 수 있습니다.
서버는 사용자 지정 X509CertificateValidator에 대해 클라이언트 자격 증명의 유효성을 검사합니다.
서버는 서버의 X.509 인증서를 사용하여 인증됩니다.
이 서비스는 구성 파일 App.config사용하여 정의된 서비스와 통신하기 위한 단일 엔드포인트를 노출합니다. 엔드포인트는 주소, 바인딩 및 계약으로 구성됩니다. 바인딩은 표준 wsHttpBinding
으로 구성되며, 기본적으로 WSSecurity
과 클라이언트 인증서 인증을 사용하도록 설정됩니다. 서비스 동작은 유효성 검사기 클래스의 유형과 함께 클라이언트 X.509 인증서의 유효성을 검사하기 위한 사용자 지정 모드를 지정합니다. 또한 이 동작은 serviceCertificate 요소를 사용하여 서버 인증서를 지정합니다. 서버 인증서는 serviceCertificate의 SubjectName
값과 findValue
동일한 값을 포함해야 합니다<>.
<system.serviceModel>
<services>
<service name="Microsoft.ServiceModel.Samples.CalculatorService"
behaviorConfiguration="CalculatorServiceBehavior">
<!-- use host/baseAddresses to configure base address -->
<!-- provided by host -->
<host>
<baseAddresses>
<add baseAddress =
"http://localhost:8001/servicemodelsamples/service" />
</baseAddresses>
</host>
<!-- use base address specified above, provide one endpoint -->
<endpoint address="certificate"
binding="wsHttpBinding"
bindingConfiguration="Binding"
contract="Microsoft.ServiceModel.Samples.ICalculator" />
</service>
</services>
<bindings>
<wsHttpBinding>
<!-- X509 certificate binding -->
<binding name="Binding">
<security mode="Message">
<message clientCredentialType="Certificate" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="CalculatorServiceBehavior">
<serviceDebug includeExceptionDetailInFaults ="true"/>
<serviceCredentials>
<!-- The serviceCredentials behavior allows one -->
<!-- to specify authentication constraints on -->
<!-- client certificates. -->
<clientCertificate>
<!-- Setting the certificateValidationMode to -->
<!-- Custom means that if the custom -->
<!-- X509CertificateValidator does NOT throw -->
<!-- an exception, then the provided certificate -->
<!-- will be trusted without performing any -->
<!-- validation beyond that performed by the custom -->
<!-- validator. The security implications of this -->
<!-- setting should be carefully considered before -->
<!-- using Custom in production code. -->
<authentication
certificateValidationMode="Custom"
customCertificateValidatorType =
"Microsoft.ServiceModel.Samples.CustomX509CertificateValidator, service" />
</clientCertificate>
<!-- The serviceCredentials behavior allows one to -->
<!-- define a service certificate. -->
<!-- A service certificate is used by a client to -->
<!-- authenticate the service and provide message -->
<!-- protection. This configuration references the -->
<!-- "localhost" certificate installed during the setup -->
<!-- instructions. -->
<serviceCertificate findValue="localhost"
storeLocation="LocalMachine"
storeName="My" x509FindType="FindBySubjectName" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
클라이언트 엔드포인트 구성은 구성 이름, 서비스 엔드포인트의 절대 주소, 바인딩 및 계약으로 구성됩니다. 클라이언트 바인딩은 적절한 모드 및 메시지 clientCredentialType
로 구성됩니다.
<system.serviceModel>
<client>
<!-- X509 certificate based endpoint -->
<endpoint name="Certificate"
address=
"http://localhost:8001/servicemodelsamples/service/certificate"
binding="wsHttpBinding"
bindingConfiguration="Binding"
behaviorConfiguration="ClientCertificateBehavior"
contract="Microsoft.ServiceModel.Samples.ICalculator">
</endpoint>
</client>
<bindings>
<wsHttpBinding>
<!-- X509 certificate binding -->
<binding name="Binding">
<security mode="Message">
<message clientCredentialType="Certificate" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="ClientCertificateBehavior">
<clientCredentials>
<serviceCertificate>
<!-- Setting the certificateValidationMode to -->
<!-- PeerOrChainTrust means that if the certificate -->
<!-- is in the user's Trusted People store, then it -->
<!-- is trusted without performing a validation of -->
<!-- the certificate's issuer chain. -->
<!-- This setting is used here for convenience so -->
<!-- that the sample can be run without having to -->
<!-- have certificates issued by a certification -->
<!-- authority (CA). This setting is less secure -->
<!-- than the default, ChainTrust. The security -->
<!-- implications of this setting should be -->
<!-- carefully considered before using -->
<!-- PeerOrChainTrust in production code.-->
<authentication
certificateValidationMode="PeerOrChainTrust" />
</serviceCertificate>
</clientCredentials>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
클라이언트 구현은 사용할 클라이언트 인증서를 설정합니다.
// Create a client with Certificate endpoint configuration
CalculatorClient client = new CalculatorClient("Certificate");
try
{
client.ClientCredentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindBySubjectName, "test1");
// Call the Add service operation.
double value1 = 100.00D;
double value2 = 15.99D;
double result = client.Add(value1, value2);
Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result);
// Call the Subtract service operation.
value1 = 145.00D;
value2 = 76.54D;
result = client.Subtract(value1, value2);
Console.WriteLine("Subtract({0},{1}) = {2}", value1, value2, result);
// Call the Multiply service operation.
value1 = 9.00D;
value2 = 81.25D;
result = client.Multiply(value1, value2);
Console.WriteLine("Multiply({0},{1}) = {2}", value1, value2, result);
// Call the Divide service operation.
value1 = 22.00D;
value2 = 7.00D;
result = client.Divide(value1, value2);
Console.WriteLine("Divide({0},{1}) = {2}", value1, value2, result);
client.Close();
}
catch (TimeoutException e)
{
Console.WriteLine("Call timed out : {0}", e.Message);
client.Abort();
}
catch (CommunicationException e)
{
Console.WriteLine("Call failed : {0}", e.Message);
client.Abort();
}
catch (Exception e)
{
Console.WriteLine("Call failed : {0}", e.Message);
client.Abort();
}
이 샘플에서는 사용자 지정 X509CertificateValidator를 사용하여 인증서의 유효성을 검사합니다. 이 샘플은 X509CertificateValidator에서 파생된 CustomX509CertificateValidator를 구현합니다. 자세한 내용은 설명서를 X509CertificateValidator 참조하세요. 이 특정 사용자 지정 유효성 검사기 샘플은 다음 코드와 같이 자체 발급된 X.509 인증서를 수락하는 Validate 메서드를 구현합니다.
public class CustomX509CertificateValidator : X509CertificateValidator
{
public override void Validate ( X509Certificate2 certificate )
{
// Only accept self-issued certificates
if (certificate.Subject != certificate.Issuer)
throw new Exception("Certificate is not self-issued");
}
}
유효성 검사기가 서비스 코드에서 구현되면 서비스 호스트에 사용할 유효성 검사기 인스턴스에 대해 알려야 합니다. 이 작업은 다음 코드를 사용하여 수행됩니다.
serviceHost.Credentials.ClientCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.Custom;
serviceHost.Credentials.ClientCertificate.Authentication.CustomCertificateValidator = new CustomX509CertificateValidator();
또는 다음과 같이 구성에서 동일한 작업을 수행할 수 있습니다.
<behaviors>
<serviceBehaviors>
<behavior name="CalculatorServiceBehavior">
...
<serviceCredentials>
<!--The serviceCredentials behavior allows one to specify -->
<!--authentication constraints on client certificates.-->
<clientCertificate>
<!-- Setting the certificateValidationMode to Custom means -->
<!--that if the custom X509CertificateValidator does NOT -->
<!--throw an exception, then the provided certificate will -->
<!--be trusted without performing any validation beyond that -->
<!--performed by the custom validator. The security -->
<!--implications of this setting should be carefully -->
<!--considered before using Custom in production code. -->
<authentication certificateValidationMode="Custom"
customCertificateValidatorType =
"Microsoft.ServiceModel.Samples. CustomX509CertificateValidator, service" />
</clientCertificate>
</serviceCredentials>
...
</behavior>
</serviceBehaviors>
</behaviors>
샘플을 실행하면 작업 요청 및 응답이 클라이언트 콘솔 창에 표시됩니다. 클라이언트는 모든 메서드를 성공적으로 호출해야 합니다. 클라이언트 창에서 Enter 키를 눌러 클라이언트를 종료합니다.
Batch 파일 설정
이 샘플에 포함된 Setup.bat 일괄 처리 파일을 사용하면 서버 인증서 기반 보안이 필요한 자체 호스팅 애플리케이션을 실행하도록 관련 인증서를 사용하여 서버를 구성할 수 있습니다. 이 일괄 처리 파일은 컴퓨터 간 작동하거나 비호스팅 환경에서 작동하도록 수정해야 합니다.
다음은 적절한 구성에서 실행되도록 수정할 수 있도록 일괄 처리 파일의 여러 섹션에 대한 간략한 개요를 제공합니다.
서버 인증서 만들기:
Setup.bat 일괄 처리 파일의 다음 줄은 사용할 서버 인증서를 만듭니다. %SERVER_NAME% 변수는 서버 이름을 지정합니다. 이 변수를 변경하여 사용자 고유의 서버 이름을 지정합니다. 기본값은 localhost입니다.
echo ************ echo Server cert setup starting echo %SERVER_NAME% echo ************ echo making server cert echo ************ makecert.exe -sr LocalMachine -ss MY -a sha1 -n CN=%SERVER_NAME% -sky exchange -pe
클라이언트의 신뢰할 수 있는 인증서 저장소에 서버 인증서 설치:
Setup.bat 일괄 처리 파일의 다음 줄은 서버 인증서를 클라이언트에서 신뢰할 수 있는 사용자 저장소에 복사합니다. Makecert.exe 생성된 인증서는 클라이언트 시스템에서 암시적으로 신뢰할 수 없으므로 이 단계가 필요합니다. 클라이언트에서 신뢰할 수 있는 루트 인증서(예: Microsoft 발급 인증서)에 루트된 인증서가 이미 있는 경우 클라이언트 인증서 저장소를 서버 인증서로 채우는 이 단계는 필요하지 않습니다.
certmgr.exe -add -r LocalMachine -s My -c -n %SERVER_NAME% -r CurrentUser -s TrustedPeople
클라이언트 인증서 만들기:
Setup.bat 일괄 처리 파일의 다음 줄은 사용할 클라이언트 인증서를 만듭니다. %USER_NAME% 변수는 클라이언트 이름을 지정합니다. 이 값은 클라이언트 코드에서 찾는 이름이기 때문에 "test1"로 설정됩니다. %USER_NAME% 값을 변경하는 경우 Client.cs 원본 파일에서 해당 값을 변경하고 클라이언트를 다시 빌드해야 합니다.
인증서는 CurrentUser 저장소 위치 아래의 내(개인) 저장소에 저장됩니다.
echo ************ echo Client cert setup starting echo %USER_NAME% echo ************ echo making client cert echo ************ makecert.exe -sr CurrentUser -ss MY -a sha1 -n CN=%USER_NAME% -sky exchange -pe
서버의 신뢰할 수 있는 인증서 저장소에 클라이언트 인증서 설치:
Setup.bat 일괄 처리 파일의 다음 줄은 클라이언트 인증서를 신뢰할 수 있는 사용자 저장소에 복사합니다. Makecert.exe 생성된 인증서는 서버 시스템에서 암시적으로 신뢰할 수 없으므로 이 단계가 필요합니다. 신뢰할 수 있는 루트 인증서(예: Microsoft 발급 인증서)에 루트된 인증서가 이미 있는 경우 서버 인증서 저장소를 클라이언트 인증서로 채우는 이 단계는 필요하지 않습니다.
certmgr.exe -add -r CurrentUser -s My -c -n %USER_NAME% -r LocalMachine -s TrustedPeople
샘플을 설정하고 빌드하려면
솔루션을 빌드하려면 Windows Communication Foundation 샘플 빌드의 지침을 따릅니다.
단일 또는 컴퓨터 간 구성에서 샘플을 실행하려면 다음 지침을 사용합니다.
동일한 컴퓨터에서 샘플을 실행하려면
관리자 권한으로 열린 Visual Studio 명령 프롬프트 내의 샘플 설치 폴더에서 Setup.bat 실행합니다. 그러면 샘플을 실행하는 데 필요한 모든 인증서가 설치됩니다.
중요합니다
Setup.bat 배치 파일은 Visual Studio 명령 프롬프트에서 실행되도록 설계되었습니다. Visual Studio 명령 프롬프트 내에 설정된 PATH 환경 변수는 Setup.bat 스크립트에 필요한 실행 파일이 포함된 디렉터리를 가리킵니다.
service\bin에서 Service.exe 시작합니다.
\client\bin에서 Client.exe 시작합니다. 클라이언트 활동은 클라이언트 콘솔 애플리케이션에 표시됩니다.
클라이언트와 서비스가 통신할 수 없는 경우 WCF 샘플대한 문제 해결 팁을 참조하세요.
컴퓨터에서 샘플을 실행하려면
서비스 컴퓨터에서 디렉터리를 만듭니다.
서비스 프로그램 파일을 \service\bin에서 서비스 컴퓨터의 가상 디렉터리로 복사합니다. 또한 Setup.bat, Cleanup.bat, GetComputerName.vbs 및 ImportClientCert.bat 파일을 서비스 컴퓨터에 복사합니다.
클라이언트 컴퓨터에 클라이언트 이진 파일에 대한 디렉터리를 만듭니다.
클라이언트 프로그램 파일을 클라이언트 컴퓨터의 클라이언트 디렉터리에 복사합니다. 또한 Setup.bat, Cleanup.bat및 ImportServiceCert.bat 파일을 클라이언트에 복사합니다.
서버에서 관리자 권한으로 열린 Visual Studio용 개발자 명령 프롬프트에서 실행
setup.bat service
합니다.setup.bat
인수를 사용하여service
실행하면 컴퓨터의 정규화된 도메인 이름을 가진 서비스 인증서가 만들어지고 서비스 인증서를 Service.cer 파일로 내보냅니다.Service.exe.config을 컴퓨터의 정규화된 도메인 이름과 동일한 새 인증서 이름으로 편집합니다 (
findValue
속성<serviceCertificate>). 또한 service</>baseAddresses< 요소의 >컴퓨터 이름을 localhost에서 서비스 컴퓨터의 정규화된 이름으로 변경합니다.서비스 디렉터리에서 클라이언트 컴퓨터의 클라이언트 디렉터리로 Service.cer 파일을 복사합니다.
클라이언트에서 관리자 권한으로 열린 Visual Studio용 개발자 명령 프롬프트에서 실행
setup.bat client
합니다.setup.bat
인수를 사용하여client
실행하면 client.com 클라이언트 인증서가 만들어지고 클라이언트 인증서가 Client.cer 파일로 내보냅니다.클라이언트 컴퓨터의 Client.exe.config 파일에서 엔드포인트의 주소 값을 서비스의 새 주소와 일치하도록 변경합니다. localhost를 서버의 정규화된 도메인 이름으로 바꿔서 이 작업을 수행합니다.
클라이언트 디렉터리에서 서버의 서비스 디렉터리로 Client.cer 파일을 복사합니다.
클라이언트에서 관리자 권한으로 열린 Visual Studio용 개발자 명령 프롬프트에서 ImportServiceCert.bat 실행합니다. 그러면 서비스 인증서가 Service.cer 파일에서 CurrentUser - TrustedPeople 저장소로 가져옵니다.
서버에서 관리자 권한으로 열린 Visual Studio용 개발자 명령 프롬프트에서 ImportClientCert.bat 실행합니다. 그러면 클라이언트 인증서가 Client.cer 파일에서 LocalMachine - TrustedPeople 저장소로 가져옵니다.
서버 컴퓨터의 명령 프롬프트 창에서 Service.exe 시작합니다.
클라이언트 컴퓨터의 명령 프롬프트 창에서 Client.exe 시작합니다. 클라이언트와 서비스가 통신할 수 없는 경우 WCF 샘플대한 문제 해결 팁을 참조하세요.
샘플 후에 정리하기
- 샘플 실행이 완료되면 샘플 폴더에서 Cleanup.bat 실행합니다. 그러면 인증서 저장소에서 서버 및 클라이언트 인증서가 제거됩니다.
비고
이 스크립트는 컴퓨터에서 이 샘플을 실행할 때 클라이언트에서 서비스 인증서를 제거하지 않습니다. 컴퓨터에서 인증서를 사용하는 WCF(Windows Communication Foundation) 샘플을 실행한 경우 CurrentUser - TrustedPeople 저장소에 설치된 서비스 인증서를 지워야 합니다. 이렇게 하려면 다음 명령을 사용합니다. certmgr -del -r CurrentUser -s TrustedPeople -c -n <Fully Qualified Server Machine Name>
예를 들면 certmgr -del -r CurrentUser -s TrustedPeople -c -n server1.contoso.com
.