C #: sslStream и локальный прокси - PullRequest
0 голосов
/ 15 июня 2011

! [Введите описание изображения здесь] [1] Привет,

У нас есть сервер, который принимает соединение ssl.Скажите, если я запрашиваю https://gmail.com, тогда сервер сначала проверяет, вошел ли я в него, если да, то он подключается к gmail и отправляет ответ обратно.Если я не вошел в систему, то он перенаправляет на нашу страницу входа.Мое требование следующее:

Я должен написать TCPListener, который слушает локальный прокси (скажем, 127.0.0.1:13000).Когда приходит запрос от браузера, я должен создать ssl-соединение с нашим сервером и передать запрос на него.

Сервер ответит либо URL-адресом входа, либо успешным. Затем я должен сделать то же самое с браузером.

Код, который я написал, выглядит следующим образом:

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Collections.Generic;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

class MyTcpListener
{
    public static void Main()
    {
        TcpListener server = null;
        try
        {
            // Set the TcpListener on port 13000.
            Int32 port = 13000;
            IPAddress localAddr = IPAddress.Parse("127.0.0.1");

            // TcpListener server = new TcpListener(port);
            server = new TcpListener(localAddr, port);

            // Start listening for client requests.
            server.Start();

            // Buffer for reading data
            Byte[] bytes = new Byte[256];
            String data = null;

            // Buffer for reading data
            Byte[] bytes1 = new Byte[256];
            String data1 = null;

            string serverName = "xxxxxxxxxxxxxxxx";//This is the server of my company


            TcpClient sslClient = new TcpClient();
            sslClient.Connect(serverName, 8080);
            SslStream sslStream = new SslStream(sslClient.GetStream(), false, new RemoteCertificateValidationCallback(CertificateValidationCallback));
            sslStream.AuthenticateAsClient(serverName);

            // Enter the listening loop.
            while (true)
            {
                Console.Write("Waiting for a connection... ");

                // Perform a blocking call to accept requests.
                // You could also user server.AcceptSocket() here.
                TcpClient client = server.AcceptTcpClient();
                Console.WriteLine("Connected!");
                data = null;

                // Get a stream object for reading and writing
                NetworkStream stream = client.GetStream();

                int i;
                int j;
                bool firstTime = true;
                // Loop to receive all the data sent by the client.
                while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                {
                    // Translate data bytes to a ASCII string.
                    data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                    Console.WriteLine("Received: {0}", data);
                    Console.WriteLine("----------------------------------------------");
                    // Process the data sent by the client.
                    data = data.ToUpper();


                    byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
                    byte[] msg1 = null;
                    sslStream.Write(msg, 0, msg.Length);
                    Console.WriteLine("written to sslchannel: {0}", msg.Length);
                    if (firstTime)
                    {
                        j = sslStream.Read(bytes1, 0, bytes1.Length);

                        firstTime = false;
                        // Translate data bytes to a ASCII string.
                        data1 = System.Text.Encoding.ASCII.GetString(bytes1, 0, j);
                        Console.WriteLine("Received from ssl: {0}", data1);
                        Console.WriteLine("----------------------------------------------");
                        // Process the data sent by the client.


                        data1 = data1.ToUpper();
                        msg1 = System.Text.Encoding.ASCII.GetBytes(data1);
                        Console.WriteLine("Sent from ssl: {0}", data1);
                        Console.WriteLine("----------------------------------------------");
                        sslStream.Write(msg1, 0, msg1.Length);
                       // stream.Write(msg1, 0, msg1.Length);

                    }
                    // Send back a response.
                    stream.Write(msg1, 0, msg1.Length);
                    Console.WriteLine("Sent: {0}", data);
                    Console.WriteLine("----------------------------------------------");
                }

                Console.WriteLine("sslStream Block");

                // Shutdown and end connection
                client.Close();
            }
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: {0}", e);
        }


        finally
        {
            // Stop listening for new clients.
            server.Stop();
        }


        Console.WriteLine("\nHit enter to continue...");
        Console.Read();
    }

    static bool CertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        if (sslPolicyErrors != SslPolicyErrors.None)
        {
            Console.WriteLine("SSL Certificate Validation Error!");
            Console.WriteLine(sslPolicyErrors.ToString());
            return false;
        }
        else
            return true;
    }
}

Когда я запускаю код, я получаю вывод, который я прикрепил.(В заблокированном тексте указан логин моей компании)

Может кто-нибудь сказать мне, почему браузер не перенаправляет на страницу входа.

Спасибо, Ирфан

...