简体   繁体   中英

c#- HTTPS proxy

I was trying to create an HTTPS proxy server in c#. Someone here posted a solution:

        string host = "encrypted.google.com";
        string proxy = "127.0.0.1";//host;
        int proxyPort = 8888;//443;

        byte[] buffer = new byte[2048];
        int bytes;

        // Connect socket
        TcpClient client = new TcpClient(proxy, proxyPort);
        NetworkStream stream = client.GetStream();

        // Establish Tcp tunnel
        byte[] tunnelRequest = Encoding.UTF8.GetBytes(String.Format("CONNECT {0}:443  HTTP/1.1\r\nHost: {0}\r\n\r\n", host));
        stream.Write(tunnelRequest , 0, tunnelRequest.Length);
        stream.Flush();

        // Read response to CONNECT request
        // There should be loop that reads multiple packets
        bytes = stream.Read(buffer, 0, buffer.Length);
        Console.Write(Encoding.UTF8.GetString(buffer, 0, bytes));

        // Wrap in SSL stream
        SslStream sslStream = new SslStream(stream);
        sslStream.AuthenticateAsClient(host);

        // Send request
        byte[] request = Encoding.UTF8.GetBytes(String.Format("GET https://{0}/  HTTP/1.1\r\nHost: {0}\r\n\r\n", host));
        sslStream.Write(request, 0, request.Length);
        sslStream.Flush();

        // Read response
        do
        {
            bytes = sslStream.Read(buffer, 0, buffer.Length);
            Console.Write(Encoding.UTF8.GetString(buffer, 0, bytes));
        } while (bytes != 0);

        client.Close();
        Console.ReadKey();

However, this is not a server's code. It prints the response (as plain text), but the client socket (the browser) doesn't get the response.

Appreciate your help, Thanks.

I'm no C# expert, but wouldn't replacing Console.Write with a write operation back to the TCP connection that the original CONNECT request came from solve this problem?

Looks like there's some missing code, like before all this occurs you have to be listening to the client with a TCP connection. So you're listening on ip address 192.168.1.1 port 8080 for example. Then the client sends something like

HTTP/1.1 www.example.com:443

And then you go and do all this stuff, then instead of Console.write, you want to do (192.168.1.1:8080).write() or the C# equivalent of that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM