Search code examples
c#.netvisual-studiosslstream

Stuck on AuthenticateAsServer method in mitm https proxy


I'm trying to write a simple https mitm proxy, and the problem arises when I handle the request:

public async Task Run(NetworkStream client, NetworkStream host) {
        try {
            //getting the cert
            var certificate = new X509Certificate(@"[PATH_TO_CERT]", "[PASSWORD]");
            //creating client's Ssl Stream
            var clientStream = new SslStream(client, false);
            //there the program freezes
            clientStream.AuthenticateAsServer(certificate, false, SslProtocols.Default, false);

            //creating server's Ssl Stream
            var serverSslStream = new SslStream(host, false, SslValidationCallback, null);
            serverSslStream.AuthenticateAsClient("[HOSTNAME]");

            //...

        } catch (Exception ex) {
            Console.WriteLine(ex.Message);
            throw;
        }

    }

After the request from client is sent, the program freezes at this line

clientStream.AuthenticateAsServer(certificate, false, SslProtocols.Default, false);

and it doesn't throw any exceptions. At first I thought that the problem is in the client's stream, so I tried to pass it's TcpClient as a method parameter, but nothing changed.

My self-signed certificate and .pfx file has been created like that:

makecert -n CN=*.[HOSTNAME].com -ic MyCA.cer -iv MyCA.pvk -a sha1 -sky exchange -pe -sr currentuser -ss my SslServer.cer 
makecert.exe -pe -n "CN=*.[HOSTNAME].com" -a sha1 -sky exchange -eku 1.3.6.1.5.5.7.3.1 -ic CA.cer -iv CA.pvk -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12 -sv server.pvk server.cer

pvk2pfx -pvk MyCA.pvk -pi [PASSWORD] -spc MyCA.cer -pfx MyPFX.pfx -f

So I thought the problem is in this line

var certificate = new X509Certificate(@"[path to the cert]", "[password]");

I replaced the cer path to the pfx path and I even downloaded the original crt file new X509Certificate(@"[path to the original cert]");, but none of this worked.

I don't know where the problem is, I tried different clients, the result is the same.

My Visual Studio version is 15.7.27703.2018 and .Net is 4.7.1.

Any tips, suggestions or links that could help me?


Solution

  • Turned out that i needed to use it with await.

    The final code looks like this:

    //getting the cert
    var certificate = new X509Certificate2(@"[PATH_TO_CERT]", "[PASSWORD]");
    //creating client's Ssl Stream
    var clientStream = new SslStream(client, false);
    await clientStream.AuthenticateAsServerAsync(certificate, false, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12 | SslProtocols.Ssl3, false);