다음을 통해 공유


메시지 대기열을 통한 메시지 보안

MessageSecurity 샘플 클라이언트에 대해 X.509v3 인증서 인증으로 WS-Security 사용하고 MSMQ를 통해 서버의 X.509v3 인증서를 사용하여 서버 인증을 요구하는 애플리케이션을 구현하는 방법을 보여 줍니다. 메시지 보안은 MSMQ 저장소의 메시지가 암호화된 상태로 유지되고 애플리케이션이 메시지의 자체 인증을 수행할 수 있도록 하는 것이 더 바람직한 경우가 있습니다.

이 샘플은 거래된 MSMQ 바인딩 샘플을 기반으로 합니다. 메시지는 암호화되고 서명됩니다.

샘플을 설정, 빌드 및 실행하려면

  1. Windows Communication Foundation 샘플 에 대한One-Time 설정 절차를 수행했는지 확인합니다.

  2. 서비스가 먼저 실행되면 큐가 있는지 확인합니다. 큐가 존재하지 않으면 서비스가 큐를 생성합니다. 서비스를 먼저 실행하여 큐를 만들거나 MSMQ 큐 관리자를 통해 만들 수 있습니다. 다음 단계에 따라 Windows 2008에서 큐를 만듭니다.

    1. Visual Studio 2012에서 서버 관리자를 엽니다.

    2. 기능 탭을 확장합니다.

    3. 프라이빗 메시지 큐 마우스 오른쪽 단추로 클릭하고 새 프라이빗 큐선택합니다.

    4. 트랜잭션 체크박스를 선택하세요.

    5. 새 큐의 이름으로 ServiceModelSamplesTransacted 입력합니다.

  3. C# 또는 Visual Basic 버전의 솔루션을 빌드하려면 Windows Communication Foundation 샘플빌드의 지침을 따릅니다.

동일한 컴퓨터에서 샘플을 실행하려면

  1. 경로에 Makecert.exe 및 FindPrivateKey.exe포함된 폴더가 포함되어 있는지 확인합니다.

  2. 샘플 설치 폴더에서 Setup.bat 실행합니다. 그러면 샘플을 실행하는 데 필요한 모든 인증서가 설치됩니다.

    메모

    샘플을 마쳤을 때 Cleanup.bat 실행하여 인증서를 제거해야 합니다. 다른 보안 샘플은 동일한 인증서를 사용합니다.

  3. \service\bin에서 Service.exe 시작합니다.

  4. \client\bin에서 Client.exe 시작합니다. 클라이언트 활동은 클라이언트 콘솔 애플리케이션에 표시됩니다.

  5. 클라이언트와 서비스가 통신할 수 없는 경우 WCF 샘플대한 문제 해결 팁을 참조하세요.

컴퓨터에서 샘플을 실행하려면

  1. Setup.bat, Cleanup.bat및 ImportClientCert.bat 파일을 서비스 컴퓨터에 복사합니다.

  2. 클라이언트 컴퓨터에 클라이언트 이진 파일에 대한 디렉터리를 만듭니다.

  3. 클라이언트 프로그램 파일을 클라이언트 컴퓨터의 클라이언트 디렉터리에 복사합니다. 또한 Setup.bat, Cleanup.bat및 ImportServiceCert.bat 파일을 클라이언트에 복사합니다.

  4. 서버에서 setup.bat service실행합니다. service 인수를 사용하여 setup.bat 실행하면 컴퓨터의 정규화된 도메인 이름을 가진 서비스 인증서가 만들어지고 서비스 인증서를 Service.cer 파일로 내보냅니다.

  5. 서비스의 service.exe.config을 컴퓨터의 정규화된 도메인 이름과 동일한 새 인증서 이름으로 변경하여 (<serviceCertificate>findValue 특성에 반영) 수정합니다.

  6. 서비스 디렉터리에서 클라이언트 컴퓨터의 클라이언트 디렉터리로 Service.cer 파일을 복사합니다.

  7. 클라이언트에서 setup.bat client실행합니다. client 인수를 사용하여 setup.bat 실행하면 client.com 클라이언트 인증서가 만들어지고 클라이언트 인증서가 Client.cer 파일로 내보냅니다.

  8. 클라이언트 컴퓨터의 Client.exe.config 파일에서 엔드포인트의 주소 값을 서비스의 새 주소와 일치하도록 변경합니다. localhost를 서버의 정규화된 도메인 이름으로 바꿔서 이 작업을 수행합니다. 또한 서비스의 인증서 이름을 서비스 컴퓨터의 정규화된 도메인 이름과 동일하게 변경해야 합니다(clientCredentials아래 serviceCertificatedefaultCertificate 요소의 findValue 특성에서).

  9. 클라이언트 디렉터리에서 서버의 서비스 디렉터리로 Client.cer 파일을 복사합니다.

  10. 클라이언트에서 ImportServiceCert.bat실행합니다. 그러면 서비스 인증서가 Service.cer 파일에서 CurrentUser - TrustedPeople 저장소로 가져옵니다.

  11. 서버에서 ImportClientCert.bat실행합니다. 그러면 Client.cer 파일의 클라이언트 인증서를 LocalMachine - TrustedPeople 저장소로 가져옵니다.

  12. 서비스 컴퓨터의 명령 프롬프트에서 Service.exe 시작합니다.

  13. 클라이언트 컴퓨터의 명령 프롬프트에서 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.

요구 사항

이 샘플을 사용하려면 MSMQ를 설치하고 실행해야 합니다.

입증합니다

클라이언트는 서비스의 공개 키를 사용하여 메시지를 암호화하고 자체 인증서를 사용하여 메시지에 서명합니다. 큐에서 메시지를 읽는 서비스는 신뢰할 수 있는 사용자 저장소의 인증서를 사용하여 클라이언트 인증서를 인증합니다. 그런 다음, 메시지의 암호를 해독하고 메시지를 서비스 작업으로 전달합니다.

WCF(Windows Communication Foundation) 메시지는 MSMQ 메시지 본문에 페이로드로 전달되므로 본문은 MSMQ 저장소에서 암호화된 상태로 유지됩니다. 이렇게 하면 메시지의 원치 않는 공개로부터 메시지가 보호됩니다. MSMQ 자체는 전달하는 메시지가 암호화되었는지 여부를 인식하지 않습니다.

이 샘플에서는 메시지 수준에서 상호 인증을 MSMQ와 함께 사용하는 방법을 보여 줍니다. 인증서는 대역 외로 교환됩니다. 서비스와 클라이언트가 동시에 실행될 필요가 없으므로 큐에 대기 중인 애플리케이션의 경우는 항상 해당됩니다.

묘사

샘플 클라이언트 및 서비스 코드는 한 가지 차이점이 있는 거래된 MSMQ 바인딩 샘플과 동일합니다. 작업 계약에는 보호 수준으로 주석이 추가되어 메시지를 서명하고 암호화해야 한다는 것을 시사합니다.

// Define a service contract.
[ServiceContract(Namespace="http://Microsoft.ServiceModel.Samples")]
public interface IOrderProcessor
{
    [OperationContract(IsOneWay = true, ProtectionLevel=ProtectionLevel.EncryptAndSign)]
    void SubmitPurchaseOrder(PurchaseOrder po);
}

서비스 및 클라이언트를 식별하는 데 필요한 토큰을 사용하여 메시지를 보호하기 위해 App.config 자격 증명 정보를 포함합니다.

클라이언트 구성은 서비스를 인증할 서비스 인증서를 지정합니다. LocalMachine 저장소를 신뢰할 수 있는 저장소로 사용하여 서비스의 유효성에 의존합니다. 또한 클라이언트의 서비스 인증을 위해 메시지와 함께 연결된 클라이언트 인증서를 지정합니다.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <system.serviceModel>

    <client>
      <!-- Define NetMsmqEndpoint -->
      <endpoint address="net.msmq://localhost/private/ServiceModelSamplesMessageSecurity"
                binding="netMsmqBinding"
                bindingConfiguration="messageSecurityBinding"
                contract="Microsoft.ServiceModel.Samples.IOrderProcessor"
                behaviorConfiguration="ClientCertificateBehavior" />
    </client>

    <bindings>
        <netMsmqBinding>
            <binding name="messageSecurityBinding">
                <security mode="Message">
                    <message clientCredentialType="Certificate"/>
                </security>
            </binding>
        </netMsmqBinding>
    </bindings>

    <behaviors>
      <endpointBehaviors>
        <behavior name="ClientCertificateBehavior">
          <!--
        The clientCredentials behavior allows one to define a certificate to present to a service.
        A certificate is used by a client to authenticate itself to the service and provide message integrity.
        This configuration references the "client.com" certificate installed during the setup instructions.
        -->
          <clientCredentials>
            <clientCertificate findValue="client.com" storeLocation="CurrentUser" storeName="My" x509FindType="FindBySubjectName" />
            <serviceCertificate>
                <defaultCertificate findValue="localhost" storeLocation="CurrentUser" storeName="TrustedPeople" x509FindType="FindBySubjectName"/>
              <!--
            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>
</configuration>

보안 모드는 Message로 설정되고 ClientCredentialType은 인증서로 설정됩니다.

서비스 구성에는 클라이언트가 서비스를 인증할 때 사용되는 서비스의 자격 증명을 지정하는 서비스 동작이 포함됩니다. 서버 인증서 주체 이름은 <serviceCredentials>findValue 특성에 지정됩니다.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <appSettings>
    <!-- Use appSetting to configure MSMQ queue name. -->
    <add key="queueName" value=".\private$\ServiceModelSamplesMessageSecurity" />
  </appSettings>

  <system.serviceModel>
    <services>
      <service
          name="Microsoft.ServiceModel.Samples.OrderProcessorService"
          behaviorConfiguration="PurchaseOrderServiceBehavior">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8000/ServiceModelSamples/service"/>
          </baseAddresses>
        </host>
        <!-- Define NetMsmqEndpoint -->
        <endpoint address="net.msmq://localhost/private/ServiceModelSamplesMessageSecurity"
                  binding="netMsmqBinding"
                  bindingConfiguration="messageSecurityBinding"
                  contract="Microsoft.ServiceModel.Samples.IOrderProcessor" />
        <!-- The mex endpoint is exposed at http://localhost:8000/ServiceModelSamples/service/mex. -->
        <endpoint address="mex"
                  binding="mexHttpBinding"
                  contract="IMetadataExchange" />
      </service>
    </services>

    <bindings>
        <netMsmqBinding>
            <binding name="messageSecurityBinding">
                <security mode="Message">
                    <message clientCredentialType="Certificate" />
                </security>
            </binding>
        </netMsmqBinding>
    </bindings>

    <behaviors>
      <serviceBehaviors>
        <behavior name="PurchaseOrderServiceBehavior">
          <serviceMetadata httpGetEnabled="True"/>
          <!--
               The serviceCredentials behavior allows one to define a service certificate.
               A service certificate is used by the service to authenticate itself to its clients and to provide message protection.
               This configuration references the "localhost" certificate installed during the setup instructions.
          -->
          <serviceCredentials>
            <serviceCertificate findValue="localhost" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />
            <clientCertificate>
                <certificate findValue="client.com" storeLocation="LocalMachine" storeName="TrustedPeople" x509FindType="FindBySubjectName"/>
              <!--
            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" />
            </clientCertificate>
          </serviceCredentials>
        </behavior>
      </serviceBehaviors>
    </behaviors>

  </system.serviceModel>

</configuration>

이 샘플에서는 다음 샘플 코드와 같이 구성을 사용하여 인증을 제어하고 보안 컨텍스트에서 호출자의 ID를 가져오는 방법을 보여 줍니다.

// Service class which implements the service contract.
// Added code to write output to the console window.
public class OrderProcessorService : IOrderProcessor
{
    private string GetCallerIdentity()
    {
        // The client certificate is not mapped to a Windows identity by default.
        // ServiceSecurityContext.PrimaryIdentity is populated based on the information
        // in the certificate that the client used to authenticate itself to the service.
        return ServiceSecurityContext.Current.PrimaryIdentity.Name;
    }

    [OperationBehavior(TransactionScopeRequired = true, TransactionAutoComplete = true)]
    public void SubmitPurchaseOrder(PurchaseOrder po)
    {
        Console.WriteLine("Client's Identity {0} ", GetCallerIdentity());
        Orders.Add(po);
        Console.WriteLine("Processing {0} ", po);
    }
  //…
}

실행하면 서비스 코드에 클라이언트 ID가 표시됩니다. 다음은 서비스 코드의 샘플 출력입니다.

The service is ready.
Press <ENTER> to terminate service.

Client's Identity CN=client.com; ECA6629A3C695D01832D77EEE836E04891DE9D3C
Processing Purchase Order: 6536e097-da96-4773-9da3-77bab4345b5d
        Customer: somecustomer.com
        OrderDetails
                Order LineItem: 54 of Blue Widget @unit price: $29.99
                Order LineItem: 890 of Red Widget @unit price: $45.89
        Total cost of this order: $42461.56
        Order status: Pending

코멘트

  • 클라이언트 인증서 만들기

    일괄 처리 파일의 다음 줄은 클라이언트 인증서를 만듭니다. 지정된 클라이언트 이름은 만든 인증서의 주체 이름에 사용됩니다. 인증서는 My 저장소에 CurrentUser 저장소 위치에 저장됩니다.

    echo ************
    echo making client cert
    echo ************
    makecert.exe -sr CurrentUser -ss MY -a sha1 -n CN=%CLIENT_NAME% -sky exchange -pe
    
  • 서버의 신뢰할 수 있는 인증서 저장소에 클라이언트 인증서 설치

    일괄 처리 파일의 다음 줄은 서버가 관련 신뢰 또는 신뢰 없음 결정을 내릴 수 있도록 클라이언트 인증서를 서버의 TrustedPeople 저장소에 복사합니다. TrustedPeople 저장소에 설치된 인증서가 WCF(Windows Communication Foundation) 서비스에서 신뢰할 수 있도록 하려면 클라이언트 인증서 유효성 검사 모드를 PeerOrChainTrust 또는 PeerTrust 값으로 설정해야 합니다. 구성 파일을 사용하여 이 작업을 수행하는 방법을 알아보려면 이전 서비스 구성 샘플을 참조하세요.

    echo ************
    echo copying client cert to server's LocalMachine store
    echo ************
    certmgr.exe -add -r CurrentUser -s My -c -n %CLIENT_NAME% -r LocalMachine -s TrustedPeople
    
  • 서버 인증서 만들기

    Setup.bat 일괄 처리 파일의 다음 줄은 사용할 서버 인증서를 만듭니다.

    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
    

    %SERVER_NAME% 변수는 서버 이름을 지정합니다. 인증서는 LocalMachine 저장소에 저장됩니다. 설치 일괄 처리 파일이 서비스 인수(예: setup.bat service)로 실행되는 경우 %SERVER_NAME% 컴퓨터의 정규화된 도메인 이름을 포함합니다. 그렇지 않으면 기본적으로 localhost로 설정됩니다.

  • 클라이언트의 신뢰할 수 있는 인증서 저장소에 서버 인증서 설치

    다음 줄은 서버 인증서를 클라이언트에서 신뢰할 수 있는 사용자 저장소에 복사합니다. Makecert.exe 생성된 인증서는 클라이언트 시스템에서 암시적으로 신뢰할 수 없으므로 이 단계가 필요합니다. 클라이언트에서 신뢰할 수 있는 루트 인증서(예: Microsoft 발급 인증서)에 루트된 인증서가 이미 있는 경우 클라이언트 인증서 저장소를 서버 인증서로 채우는 이 단계는 필요하지 않습니다.

    certmgr.exe -add -r LocalMachine -s My -c -n %SERVER_NAME% -r CurrentUser -s TrustedPeople
    

    메모

    미국 이외의 영어 버전을 사용하는 경우 Microsoft Windows에서는 Setup.bat 파일을 편집하고 "NT AUTHORITY\NETWORK SERVICE" 계정 이름을 해당 지역의 이름으로 바꿔야 합니다.