Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TrustAllCertificatesCallback is ignored

Given a url or server name, how can i use powershell or a .net library to download the (expired) certificate the web server is using and then save it to file or import it into my certificate store?

Thanks!

I have made progress, i got this far on this problem:

static class Program
    {
        static void Main()
        {
            ServicePointManager.ServerCertificateValidationCallback = TrustAllCertificatesCallback;
            var tcpclient = new TcpClient("remote.example.com", 443);
            var tcpstream = tcpclient.GetStream();
            var sslstream = new SslStream(tcpstream);
            sslstream.AuthenticateAsClient("remote.example.com");
            X509Certificate rc = sslstream.RemoteCertificate;
            Console.WriteLine(rc.ToString());
            Console.ReadLine();
        }

        public static bool TrustAllCertificatesCallback(
            object sender, X509Certificate cert,
            X509Chain chain, System.Net.Security.SslPolicyErrors errors)
        {
            return true;
        }
    }

Now, when i run this program i get an AuthenticationException on the AuthenticateAsClient line and it says "The remote certificate is invalid according to the validation procedure." I ran it with a breakpoint on return true; and it never called the TrustAllCertificatesCallback. I think there is a permission or configuration problem with the assembly, does anyone know how to fix it?

like image 305
Segfault Avatar asked Jan 22 '23 17:01

Segfault


1 Answers

I haven't done something like this, but looking at the examples I think I can see what is wrong. Try this code:

static class Program
{
    static void Main()
    {
        var tcpclient = new TcpClient("remote.example.com", 443);
        var tcpstream = tcpclient.GetStream();
        var sslstream = new SslStream(tcpstream, false, new RemoteCertificateValidationCallback (TrustAllCertificatesCallback));
        sslstream.AuthenticateAsClient("remote.example.com");
        X509Certificate rc = sslstream.RemoteCertificate;
        Console.WriteLine(rc.ToString());
        Console.ReadLine();
    }

    public static bool TrustAllCertificatesCallback(
        object sender, X509Certificate cert,
        X509Chain chain, System.Net.Security.SslPolicyErrors errors)
    {
        return true;
    }
}
like image 153
JasonMArcher Avatar answered Feb 07 '23 16:02

JasonMArcher