Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用c SslStream直接SSL/TLS(无连接消息)MITM代理_C#_Ssl_Proxy_Tcpclient - Fatal编程技术网

C# 使用c SslStream直接SSL/TLS(无连接消息)MITM代理

C# 使用c SslStream直接SSL/TLS(无连接消息)MITM代理,c#,ssl,proxy,tcpclient,C#,Ssl,Proxy,Tcpclient,我正在尝试使用C创建一个本地windows MITM代理,以处理一个现在不受支持的应用程序,该应用程序来自一家不再存在的公司 代理只需为一个HTTPS域提供服务,该域通过创建侦听本地地址的代理来完成:端口127.0.0.1:443 然后在主机文件中创建一个条目,即127.0.0.1 my.single.domain.com 当将域的条目直接添加到我的主机文件中时,我不会得到正常的连接类型的HTTP请求,而是在套接字上收到一个直接的客户机hello,我可以看到下一步是发起握手 但是,我不确定如何使

我正在尝试使用C创建一个本地windows MITM代理,以处理一个现在不受支持的应用程序,该应用程序来自一家不再存在的公司

代理只需为一个HTTPS域提供服务,该域通过创建侦听本地地址的代理来完成:端口127.0.0.1:443

然后在主机文件中创建一个条目,即127.0.0.1 my.single.domain.com

当将域的条目直接添加到我的主机文件中时,我不会得到正常的连接类型的HTTP请求,而是在套接字上收到一个直接的客户机hello,我可以看到下一步是发起握手

但是,我不确定如何使用csstream处理这个问题。可以找到的大多数示例,包括在MSDN之类的地方,都是针对CONNECT type proxys的


我是否需要创建两个SSL流来处理此问题。

回答我自己的问题,但可能会给其他人一些指导。这不是生产标准代码,但它可以工作

public sealed class SslTcpProxy
{
    static void Main(String[] args)
    {
        // Create a TCP/IP (IPv4) socket and listen for incoming connections.
        TcpListener tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 443);
        tcpListener.Start();

        Console.WriteLine("Server listening on 127.0.0.1:433  Press enter to exit.");
        Console.WriteLine();
        Console.WriteLine("Waiting for a client to connect...");
        Console.WriteLine();

        // Application blocks while waiting for an incoming connection.
        TcpClient tcpClient = tcpListener.AcceptTcpClient();
        AcceptConnection(tcpClient);

        Console.ReadLine();
        tcpListener.Stop();
    }

    private static void AcceptConnection(TcpClient client)
    {
        try
        {
            // Using a pre-created certificate.
            String certFilePath = Environment.CurrentDirectory + @"\certificates\server-cert.pfx";

            X509Certificate2 certificate;

            try
            {
                certificate = new X509Certificate2(certFilePath, "[CER_PASSWORD]");
            }
            catch (Exception ex)
            {
                throw new Exception($"Could not create the certificate from file from {certFilePath}", ex);
            }

            SslStream clientSslStream = new SslStream(client.GetStream(), false);
            clientSslStream.AuthenticateAsServer(certificate, false, SslProtocols.Default, false);

            // Display the properties and settings for the authenticated as server stream.
            Console.WriteLine("clientSslStream.AuthenticateAsServer");
            Console.WriteLine("------------------------------------");
            DisplaySecurityLevel(clientSslStream);
            DisplaySecurityServices(clientSslStream);
            DisplayCertificateInformation(clientSslStream);
            DisplayStreamProperties(clientSslStream);

            Console.WriteLine();

            // The Ip address of the server we are trying to connect to.
            // Dont use the URI as it will resolve from the host file.
            TcpClient server = new TcpClient("[SERVER_IP]", 443);
            SslStream serverSslStream = new SslStream(server.GetStream(), false, SslValidationCallback, null);
            serverSslStream.AuthenticateAsClient("[SERVER_NAME]");

            // Display the properties and settings for the authenticated as server stream.
            Console.WriteLine("serverSslStream.AuthenticateAsClient");
            Console.WriteLine("------------------------------------");
            DisplaySecurityLevel(serverSslStream);
            DisplaySecurityServices(serverSslStream);
            DisplayCertificateInformation(serverSslStream);
            DisplayStreamProperties(serverSslStream);

            new Task(() => ReadFromClient(client, clientSslStream, serverSslStream)).Start();
            new Task(() => ReadFromServer(serverSslStream, clientSslStream)).Start();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            throw;
        }

    }

    private static Boolean SslValidationCallback(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslpolicyerrors)
    {
        return true;
    }

    private static void ReadFromServer(Stream serverStream, Stream clientStream)
    {
        Byte[] message = new Byte[4096];

        Int32 serverBytes;

        try
        {
            while ((serverBytes = serverStream.Read(message, 0, message.Length)) > 0)
            {
                clientStream.Write(message, 0, serverBytes);
            }
        }
        catch
        {
            // Whatever
        }
    }

    private static void ReadFromClient(TcpClient client, Stream clientStream, Stream serverStream)
    {
        Byte[] message = new Byte[4096];

        FileInfo fileInfo = new FileInfo("client");

        if (!fileInfo.Exists)
        {
            fileInfo.Create().Dispose();
        }

        using (FileStream stream = fileInfo.OpenWrite())
        {
            while (true)
            {
                Int32 clientBytes;

                try
                {
                    clientBytes = clientStream.Read(message, 0, message.Length);
                }
                catch
                {
                    break;
                }

                if (clientBytes == 0)
                {
                    break;
                }

                serverStream.Write(message, 0, clientBytes);
                stream.Write(message, 0, clientBytes);
            }

            client.Close();
        }
    }

    static void DisplaySecurityLevel(SslStream stream)
    {
        Console.WriteLine("Cipher: {0} strength {1}", stream.CipherAlgorithm, stream.CipherStrength);
        Console.WriteLine("Hash: {0} strength {1}", stream.HashAlgorithm, stream.HashStrength);
        Console.WriteLine("Key exchange: {0} strength {1}", stream.KeyExchangeAlgorithm, stream.KeyExchangeStrength);
        Console.WriteLine("Protocol: {0}", stream.SslProtocol);
    }

    static void DisplaySecurityServices(SslStream stream)
    {
        Console.WriteLine("Is authenticated: {0} as server? {1}", stream.IsAuthenticated, stream.IsServer);
        Console.WriteLine("IsSigned: {0}", stream.IsSigned);
        Console.WriteLine("Is Encrypted: {0}", stream.IsEncrypted);
    }

    static void DisplayStreamProperties(SslStream stream)
    {
        Console.WriteLine($"Can read: {stream.CanRead}, write {stream.CanWrite}");
        Console.WriteLine($"Can timeout: {stream.CanTimeout}");
    }

    static void DisplayCertificateInformation(SslStream stream)
    {
        Console.WriteLine($"Certificate revocation list checked: {stream.CheckCertRevocationStatus}");

        X509Certificate localCertificate = stream.LocalCertificate;

        if (stream.LocalCertificate != null)
        {
            Console.WriteLine("Local cert was issued to {0} and is valid from {1} until {2}.",
                localCertificate.Subject,
                localCertificate.GetEffectiveDateString(),
                localCertificate.GetExpirationDateString());
        }
        else
        {
            Console.WriteLine("Local certificate is null.");
        }

        // Display the properties of the client's certificate.
        X509Certificate remoteCertificate = stream.RemoteCertificate;

        if (stream.RemoteCertificate != null)
        {
            if (remoteCertificate != null)
            {
                Console.WriteLine(
                    $"Remote cert was issued to {remoteCertificate.Subject} and is valid from {remoteCertificate.GetEffectiveDateString()} until {remoteCertificate.GetExpirationDateString()}.");
            }
        }
        else
        {
            Console.WriteLine("Remote certificate is null.");
        }

    }
}

我建议编辑你的问题,少问一些例子,用有效的技术问题直截了当地回答问题,否则人们会把它关闭。我对你的问题进行了大量编辑,试图使其有效并可回答。我不确定我是否成功,但仅供参考,如果您不同意编辑,请随时回滚。据我所知,您只希望代理服务器能够处理客户端Hello而不是CONNECT。您应该为我们提供更多关于代理服务器的信息,这样我们就知道它是如何处理请求的,比如它是否使用MVC?etcAt目前只是一个简单的控制台mitm代理。我猜它将需要一个客户端SSLStream和一个服务器SSLStream。我不需要为客户创建假证书,因为我有真实证书的副本。我真正的问题是我知道我想实现什么,但谷歌上的当前示例,甚至我自己的书,要么使用连接方法而不是直接ssl流,要么已经过时,要么根本不起作用。我喜欢.net,但微软一直在移动目标帖子,很难找到这些类型的最新例子,而不是一些常见的要求。@WilliamHumphreys当你说你有证书时,这些是什么类型的证书?他们将被绑定到一个域+IP。127.0.0.1绝对不会成为IP。需要更多信息。你可能应该从回答中删除抱怨,并添加一些实际的评论。发布一段代码没有多大用处。此外,我还编写了多个本地MITM程序,我考虑到了您的问题。我花了2年的时间写了我写的最后一个本地MITM软件,在你抱怨之前,你给了人们5个小时。我告诉你们这些并不是为了挑起一场争斗,我告诉你们是因为你们让一个,如果我敢说的话,是你们所问问题的专家的人,对回答完全不感兴趣。这是值得考虑的。它不起作用…范围中未定义BufferSize。这是很久以前一个更大的应用程序的片段。它不是一字不差的,而是一个指南。在这种情况下,它工作得很好。目前,只需将BufferSize替换为message.Length。