Cómo ignorar la comprobación del certificado cuando ssl


Estoy tratando de encontrar una manera de ignorar la comprobación del certificado cuando solicite un recurso Https, hasta ahora, he encontrado un artículo útil en Internet.

Pero todavía tengo algún problema. Por favor revise mi código. Simplemente no entiendo qué significa el código ServicePointManager.ServerCertificateValidationCallback.

¿Cuándo se llamará a este método delegado? Y una pregunta más, ¿en qué lugar debo escribir este código? Antes de ServicePointManager.ServerCertificateValidationCallback ejecutar o antes de Stream stream = request.GetRequestStream()?

public HttpWebRequest GetRequest()
{
    CookieContainer cookieContainer = new CookieContainer();

    // Create a request to the server
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_remoteUrl);

    #region Set request parameters

    request.Method = _context.Request.HttpMethod;
    request.UserAgent = _context.Request.UserAgent;
    request.KeepAlive = true;
    request.CookieContainer = cookieContainer;
    request.PreAuthenticate = true;
    request.AllowAutoRedirect = false;

    #endregion

    // For POST, write the post data extracted from the incoming request
    if (request.Method == "POST")
    {
        Stream clientStream = _context.Request.InputStream;
        request.ContentType = _context.Request.ContentType;
        request.ContentLength = clientStream.Length;

        ServicePointManager.ServerCertificateValidationCallback = delegate(
            Object obj, X509Certificate certificate, X509Chain chain, 
            SslPolicyErrors errors)
            {
                return (true);
            };

            Stream stream = request.GetRequestStream();

            ....
        }

        ....

        return request;
    }
}   
Author: Luke Girvin, 2012-09-20

10 answers

Ya que solo hay un ServicePointManager global, configurando ServicePointManager.ServerCertificateValidationCallback producirá el resultado de que todas las solicitudes posteriores heredarán esta política. Dado que es un "ajuste" global, sería preferible establecerlo en el método Application_Start en Global.asax .

Establecer la devolución de llamada anula el comportamiento predeterminado y usted mismo puede crear una rutina de validación personalizada.

 60
Author: Sani Singh Huttunen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-20 06:26:31

Para cualquier persona interesada en aplicar esta solución por solicitud, esta es una opción y utiliza una expresión Lambda. La misma expresión Lambda también se puede aplicar al filtro global mencionado por blak3r. Este método parece requerir. NET 4.5.

String url = "https://www.stackoverflow.com";
HttpWebRequest request = HttpWebRequest.CreateHttp(url);
request.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;

En. NET 4.0, la expresión Lambda se puede aplicar al filtro global como tal

ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
 139
Author: Adam Venezia,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-16 21:22:18

Esto funcionó para mí:

System.Net.ServicePointManager.ServerCertificateValidationCallback +=
delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                        System.Security.Cryptography.X509Certificates.X509Chain chain,
                        System.Net.Security.SslPolicyErrors sslPolicyErrors)
    {
        return true; // **** Always accept
    };

Fragmento de aquí: http://www.west-wind.com/weblog/posts/2011/Feb/11/HttpWebRequest-and-Ignoring-SSL-Certificate-Errors

 48
Author: blak3r,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-29 22:38:35

También está la solución de delegado corto:

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; 
 18
Author: Andrej Rommel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-13 12:57:27

Se ha mencionado que antes de.NET 4.5 la propiedad en la solicitud de acceso a su ServicePointManager no estaba disponible.

Aquí está el código.NET 4.0 que le dará acceso a ServicePoint por solicitud. No le da acceso a la devolución de llamada por solicitud, pero debería permitirle obtener más detalles sobre el problema. Simplemente acceda a las propiedades scvPoint.Certificate (o ClientCertificate si lo prefiere).

WebRequest request = WebRequest.Create(uri);

// oddity: these two .Address values are not necessarily the same!
//  The service point appears to be related to the .Host, not the Uri itself.
//  So, check the .Host vlaues before fussing in the debugger.
//
ServicePoint svcPoint = ServicePointManager.FindServicePoint(uri);
if (null != svcPoint)
{
    if (!request.RequestUri.Host.Equals(svcPoint.Address.Host, StringComparison.OrdinalIgnoreCase))
    {
        Debug.WriteLine(".Address              == " + request.RequestUri.ToString());
        Debug.WriteLine(".ServicePoint.Address == " + svcPoint.Address.ToString());
    }
    Debug.WriteLine(".IssuerName           == " + svcPoint.Certificate.GetIssuerName());
}
 5
Author: Jesse Chisholm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-06 17:43:37

Basado en la respuesta de Adam y el comentario de Rob usé esto:

ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => certificate.Issuer == "CN=localhost";

Que filtra el "ignorar" un poco. Se pueden añadir otros emisores según sea necesario, por supuesto. Esto se probó en. NET 2.0, ya que necesitamos admitir código heredado.

 2
Author: Andrej,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-08 07:12:03

Por cierto, esta es la forma menos detallada de desactivar toda la validación de certificados en una aplicación determinada que conozco:

ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => true;
 2
Author: Melbourne Developer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-23 16:06:52

Añadiendo a las respuestas de Sani y blak3r, he añadido lo siguiente al código de inicio de mi aplicación, pero en VB:

'** Overriding the certificate validation check.
Net.ServicePointManager.ServerCertificateValidationCallback = Function(sender, certificate, chain, sslPolicyErrors) True

Parece hacer el truco.

 0
Author: MCattle,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-05 22:15:35

Tuve el mismo problema, así que creé una clase que help con mis códigos. Pero use un HttpClient:

Https://github.com/PicolotoLF/IgnoresSSL

Ejemplo:

public async Task DoRequest()
{
    IgnoreSSL Client = new IgnoreSSL();

    var client = Client.IgnoreSSLA();

    //NOTE(picoloto): Use how a HttpClient
    var response = await client.GetAsync(URL)
}
 0
Author: Lucas Picoloto,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-30 22:48:31

Consejo: También puede usar este método para rastrear certificados que caducarán pronto. Esto puede salvar su tocino si descubre un certificado que está a punto de caducar y puede arreglarlo a tiempo. Bueno también para las compañías de terceros - para nosotros esto es DHL / FedEx. DHL acaba de dejar expirar un certificado que nos está jodiendo 3 días antes de Acción de Gracias. Afortunadamente estoy aquí para arreglarlo ... esta vez!

    private static DateTime? _nextCertWarning;
    private static bool ValidateRemoteCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
    {
        if (error == SslPolicyErrors.None)
        {
            var cert2 = cert as X509Certificate2;
            if (cert2 != null)
            { 
                // If cert expires within 2 days send an alert every 2 hours
                if (cert2.NotAfter.AddDays(-2) < DateTime.Now)
                {
                    if (_nextCertWarning == null || _nextCertWarning < DateTime.Now)
                    {
                        _nextCertWarning = DateTime.Now.AddHours(2);

                        ProwlUtil.StepReached("CERT EXPIRING WITHIN 2 DAYS " + cert, cert.GetCertHashString());   // this is my own function
                    }
                }
            }

            return true;
        }
        else
        {
            switch (cert.GetCertHashString())
            {
                // Machine certs - SELF SIGNED
                case "066CF9CAD814DE2097D367F22D3A7E398B87C4D6":    

                    return true;

                default:
                    ProwlUtil.StepReached("UNTRUSTED CERT " + cert, cert.GetCertHashString());
                    return false;
            }
        }
    }
 0
Author: Simon_Weaver,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-21 20:35:34