Procedimiento para configurar un puerto con un certificado SSL

Cuando se crea un servicio de Windows Communication Foundation (WCF) autohospedado con la clase WSHttpBinding que utiliza la seguridad de transporte, también debe configurarse un puerto con un certificado X.509. Si no está creando un servicio autohospedado, puede hospedar su servicio en Servicios de Internet Information Server (IIS). Para obtener más información, consulte Seguridad de transporte HTTP.

La herramienta que se usa para configurar un puerto depende del sistema operativo que se esté ejecutando en el equipo.

Si ejecuta Windows Server 2003, use la herramienta HttpCfg.exe. En Windows Server 2003, esta herramienta está instalada. Para obtener más información, consulte Información general de Httpcfg. En la documentación de las Herramientas de soporte de Windows, se explica la sintaxis de la herramienta Httpcfg.exe.

Si ejecuta Windows Vista, use la herramienta Netsh.exe, que ya está instalada.

Nota

Para modificar los certificados almacenados en el equipo, se requieren privilegios de administrador.

Determinación de cómo se configuran los puertos

  1. En Windows Server 2003 o Windows XP, use la herramienta HttpCfg.exe para ver la configuración de puerto actual con los modificadores query y ssl, como se muestra en el ejemplo siguiente.

    httpcfg query ssl  
    
  2. En Windows Vista, use la herramienta Netsh.exe para ver la configuración de puerto actual, como se muestra en el ejemplo siguiente.

    netsh http show sslcert  
    

Obtención de la huella digital de un certificado

  1. Use el complemento de certificados de MMC para buscar un certificado X.509 que tenga como finalidad la autenticación del cliente. Para más información, consulte Visualización de certificados con el complemento MMC.

  2. Obtenga acceso a la huella digital del certificado. Para más información, consulte Cómo recuperar la huella digital de un certificado.

  3. Copie la huella digital del certificado en un editor de texto, como por ejemplo Bloc de notas.

  4. Quite todos los espacios entre los caracteres hexadecimales. Una manera de llevarlo a cabo es utilizar la característica del editor de texto buscar y reemplazar y reemplazar todos los espacios con un carácter nulo.

Enlace de un certificado SSL a un número de puerto

  1. En Windows Server 2003 o Windows XP, use la herramienta HttpCfg.exe en modo "set" en el almacén SSL (Capa de sockets seguros) para enlazar el certificado a un número de puerto. La herramienta utiliza la huella digital para identificar el certificado, tal y como se muestra en el ejemplo siguiente.

    httpcfg set ssl -i 0.0.0.0:8012 -h 0000000000003ed9cd0c315bbb6dc1c08da5e6  
    
    • El modificador -i tiene la sintaxis IP:port y le indica a la herramienta que establezca el certificado en el puerto 8012 del equipo. De forma opcional, también se pueden reemplazar los cuatro ceros que preceden el número por la dirección IP real del equipo.

    • El modificador -h especifica la huella digital del certificado.

  2. En Windows Vista, use la herramienta Netsh.exe, como se muestra en el siguiente ejemplo.

    netsh http add sslcert ipport=0.0.0.0:8000 certhash=0000000000003ed9cd0c315bbb6dc1c08da5e6 appid={00112233-4455-6677-8899-AABBCCDDEEFF}
    
    • El parámetro certhash especifica la huella digital del certificado.

    • El parámetro ipport especifica el puerto y la dirección IP, y funciona como el modificador -i de la herramienta Httpcfg.exe descrita.

    • El parámetro appid es un GUID que se puede usar para identificar la aplicación propietaria.

Enlace de un certificado SSL a un número de puerto y compatibilidad con certificados de cliente

  1. En Windows Server 2003 o Windows XP, para admitir clientes que se autentican con certificados X.509 en el nivel de transporte, siga el procedimiento anterior pero pase un parámetro de la línea de comandos adicional a HttpCfg.exe, como se muestra en el ejemplo siguiente.

    httpcfg set ssl -i 0.0.0.0:8012 -h 0000000000003ed9cd0c315bbb6dc1c08da5e6 -f 2  
    

    El modificador -f tiene la sintaxis n, donde n es un número del 1 al 7. El valor 2, como se mostraba en el ejemplo anterior, habilita los certificados de cliente en el nivel de transporte. El valor 3 habilita los certificados de cliente y los asigna a una cuenta de Windows. Consulte la Ayuda HttpCfg.exe para el comportamiento de otros valores.

  2. En Windows Vista, para admitir los clientes que se autentican con certificados X.509 en el nivel de transporte, siga el procedimiento anterior pero pase un parámetro de la línea de comandos adicional a HttpCfg.exe, como se muestra en el ejemplo siguiente.

    netsh http add sslcert ipport=0.0.0.0:8000 certhash=0000000000003ed9cd0c315bbb6dc1c08da5e6 appid={00112233-4455-6677-8899-AABBCCDDEEFF} clientcertnegotiation=enable  
    

Eliminación de un certificado SSL de un número de puerto

  1. Use la herramienta HttpCfg.exe o Netsh.exe para ver los puertos y huellas digitales de todos los enlaces del equipo. Para imprimir la información en el disco, use el carácter de redireccionamiento ">", como se muestra en el ejemplo siguiente.

    httpcfg query ssl>myMachinePorts.txt  
    
  2. En Windows Server 2003 o Windows XP, use la herramienta HttpCfg.exe con las palabras clave delete y ssl. Use el modificador -i para especificar el número IP:port y el modificador -h para especificar la huella digital.

    httpcfg delete ssl -i 0.0.0.0:8005 -h 0000000000003ed9cd0c315bbb6dc1c08da5e6  
    
  3. En Windows Vista, use la herramienta Netsh.exe, como se muestra en el siguiente ejemplo.

    Netsh http delete sslcert ipport=0.0.0.0:8005  
    

Ejemplo

El código siguiente muestra cómo crear un servicio autohospedado utilizando la clase WSHttpBinding establezca para seguridad de transporte. Cuando cree una aplicación, especifique el número de puerto en la dirección.

// This string uses a function to prepend the computer name at run time.
string addressHttp = String.Format(
    "http://{0}:8080/Calculator",
    System.Net.Dns.GetHostEntry("").HostName);

WSHttpBinding b = new WSHttpBinding();
b.Security.Mode = SecurityMode.Transport;
b.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;

// You must create an array of URI objects to have a base address.
Uri a = new Uri(addressHttp);
Uri[] baseAddresses = new Uri[] { a };

// Create the ServiceHost. The service type (Calculator) is not
// shown here.
ServiceHost sh = new ServiceHost(typeof(Calculator), baseAddresses);

// Add an endpoint to the service. Insert the thumbprint of an X.509
// certificate found on your computer.
Type c = typeof(ICalculator);
sh.AddServiceEndpoint(c, b, "MyCalculator");
sh.Credentials.ServiceCertificate.SetCertificate(
    StoreLocation.LocalMachine,
    StoreName.My,
    X509FindType.FindBySubjectName,
    "contoso.com");

// This next line is optional. It specifies that the client's certificate
// does not have to be issued by a trusted authority, but can be issued
// by a peer if it is in the Trusted People store. Do not use this setting
// for production code. The default is PeerTrust, which specifies that
// the certificate must originate from a trusted certificate authority.

// sh.Credentials.ClientCertificate.Authentication.CertificateValidationMode =
// X509CertificateValidationMode.PeerOrChainTrust;
try
{
    sh.Open();

    string address = sh.Description.Endpoints[0].ListenUri.AbsoluteUri;
    Console.WriteLine("Listening @ {0}", address);
    Console.WriteLine("Press enter to close the service");
    Console.ReadLine();
    sh.Close();
}
catch (CommunicationException ce)
{
    Console.WriteLine("A communication error occurred: {0}", ce.Message);
    Console.WriteLine();
}
catch (System.Exception exc)
{
    Console.WriteLine("An unforeseen error occurred: {0}", exc.Message);
    Console.ReadLine();
}
' This string uses a function to prepend the computer name at run time.
Dim addressHttp As String = String.Format("http://{0}:8080/Calculator", _
System.Net.Dns.GetHostEntry("").HostName)

Dim b As New WSHttpBinding()
b.Security.Mode = SecurityMode.Transport
b.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate

' You must create an array of URI objects to have a base address.
Dim a As New Uri(addressHttp)
Dim baseAddresses() As Uri = {a}

' Create the ServiceHost. The service type (Calculator) is not
' shown here.
Dim sh As New ServiceHost(GetType(Calculator), baseAddresses)

' Add an endpoint to the service. Insert the thumbprint of an X.509 
' certificate found on your computer. 
Dim c As Type = GetType(ICalculator)
sh.AddServiceEndpoint(c, b, "MyCalculator")
sh.Credentials.ServiceCertificate.SetCertificate( _
                StoreLocation.LocalMachine, _
                StoreName.My, _
                X509FindType.FindBySubjectName, _
                "contoso.com")

' This next line is optional. It specifies that the client's certificate
' does not have to be issued by a trusted authority, but can be issued
' by a peer if it is in the Trusted People store. Do not use this setting
' for production code. The default is PeerTrust, which specifies that 
' the certificate must originate from a trusted certificate authority.
' sh.Credentials.ClientCertificate.Authentication.CertificateValidationMode =
' X509CertificateValidationMode.PeerOrChainTrust
Try
    sh.Open()

    Dim address As String = sh.Description.Endpoints(0).ListenUri.AbsoluteUri
    Console.WriteLine("Listening @ {0}", address)
    Console.WriteLine("Press enter to close the service")
    Console.ReadLine()
    sh.Close()
Catch ce As CommunicationException
    Console.WriteLine("A communication error occurred: {0}", ce.Message)
    Console.WriteLine()
Catch exc As System.Exception
    Console.WriteLine("An unforeseen error occurred: {0}", exc.Message)
    Console.ReadLine()
End Try

Consulte también