private async ValueTask <TlsStream> EstablishSslConnection(string host, HttpRequestMessage request, Stream stream, CancellationToken cancellationToken)
        {
            logger.Trace("HTTP connection handler: Establish TLS connection");

            var secParams = new SecurityParameters();

            secParams.CipherSuiteIDs.Add(CipherSuiteId.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256);
            secParams.CipherSuiteIDs.Add(CipherSuiteId.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384);
            secParams.CipherSuiteIDs.Add(CipherSuiteId.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256);
            secParams.CipherSuiteIDs.Add(CipherSuiteId.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384);
            secParams.MinimumVersion = ProtocolVersion.TLS1_2;
            secParams.MaximumVersion = ProtocolVersion.TLS1_2;

            if (this._settings._clientCertificate != null)
            {
                var pluginManager = new IVU.Common.Tls.Plugin.CipherSuitePluginInterface.CipherSuitePluginManager();
                var privateKey    = pluginManager.GetPrivateKey(this._settings._clientCertificate.Key);
                secParams.AddCertificate(new X509CertificateCollection {
                    this._settings._clientCertificate.Certificate
                }, privateKey);
            }

            secParams.ClientCertificateSelectionCallback += (client, server) =>
            {
                return(0);
            };

            secParams.ServerCertificateValidationCallback = certificates =>
            {
                if (this._settings?._serverCertificateCustomValidationCallback == null)
                {
                    logger.Error("No server certificate validation callback provided!");
                    return(false);
                }

                return(this._settings?._serverCertificateCustomValidationCallback(
                           request,
                           new X509Certificate2(certificates[0]),
                           null,
                           SslPolicyErrors.None) == true);
            };

            var tlsSession = new SecureSession(stream, secParams);

            try
            {
                await tlsSession.PerformClientHandshake(cancellationToken);

                logger.Trace("HTTP connection handler: TLS connection successfull establish");
            }
            catch (Exception ex)
            {
                tlsSession.Close();
                logger.ErrorException("Failed to establish TLS connection: {0}", ex, ex.Message);
                throw new TlsConnectFailed("Failed to establish TLS connection", ex);
            }

            return(new TlsStream(tlsSession));
        }
Exemplo n.º 2
0
        public static void Main(string[] args)
        {
            SecurityParameters securityParameters = new SecurityParameters();

            securityParameters.CipherSuiteIDs.Add(0x000a);
            securityParameters.ServerCertificateValidationCallback = new ServerCertificateValidationCallback(CertificateValidationCallback);
            securityParameters.ClientCertificateSelectionCallback  = new ClientCertificateSelectionCallback(CertificateSelectionCallback);

            if (args.Length >= 2)
            {
                X509CertificateCollection certs = new X509CertificateCollection();
                for (int i = 0; i < args.Length - 1; i++)
                {
                    certs.Add(new X509Certificate(args[i]));
                }

                // Get plugin manager for importing the private key
                string path      = System.Reflection.Assembly.GetAssembly(typeof(AaltoTLS.HandshakeLayer.HandshakeSession)).Location;
                string directory = Path.GetDirectoryName(path);
                CipherSuitePluginManager pluginManager = new CipherSuitePluginManager(directory);

                // Import the private key into asymmetric algorithm
                byte[] privateKeyData            = File.ReadAllBytes(args[args.Length - 1]);
                CertificatePrivateKey privateKey = pluginManager.GetPrivateKey(privateKeyData);

                securityParameters.AddCertificate(certs, privateKey);
            }

            string host = "www.mikestoolbox.net";
            int    port = 443;

            string request = "GET / HTTP/1.1\r\nHost: " + host + "\r\n\r\n";

            try {
                TcpClient     tcpClient = new TcpClient(host, port);
                NetworkStream ns        = tcpClient.GetStream();
                SecureSession session   = new SecureSession(ns, securityParameters);
                session.PerformClientHandshake(host);
                session.Send(Encoding.UTF8.GetBytes(request));
                byte[] received = session.Receive();
                Console.WriteLine("Received data: " + Encoding.UTF8.GetString(received));
                session.Close();
            } catch (SocketException) {
                Console.WriteLine("Unable to connect to server");
                return;
            }
        }
        public void Handle()
        {
            NetworkStream networkStream  = null;

            try
            {
                bool loop = true;

                IPEndPoint ipep = (IPEndPoint)Socket.RemoteEndPoint;
                IPAddress = ipep.Address;

                networkStream = new NetworkStream(Socket);

                try
                {
                    Session = new SecureSession(networkStream, Certificates.SecurityParameters);
                    Session.PerformServerHandshake(Certificates.Certificate);
                }
                catch
                {
                    loop = false;
                }


                while (loop)
                {
                    HydraRequest request = null;
                    try
                    {
                        request = new HydraRequest(this);
                    }
                    catch
                    {
                        break;
                    }

                    Modules.IModule module = null;

                    switch (request.Module)
                    {
                        case "feed":
                            {
                                module = new Modules.FeedModule(this);
                                break;
                            }
                        case "profile":
                            {
                                module = new Modules.ProfileModule(this);
                                break;
                            }
                        case "onesite_proxy":
                            {
                                module = new Modules.OnesiteProxyModule(this);
                                break;
                            }
                        case "ugc":
                            {
                                module = new Modules.UgcModule(this);
                                break;
                            }

                        default:
                            {
                                HydraResponse response = new HydraResponse(this);
                                response.StatusCode = 404;
                                response.Status = "File Not Found";
                                response.Payload = new byte[0];
                                response.Send();
                                break;
                            }
                    }

                    if (module != null)
                        module.HandleRequest(request);
                }
            }
            catch (Exception ex)
            {
            }

            try
            {
                Session.Close();
                networkStream.Flush();
                networkStream.Close();
                Socket.Disconnect(false);
                Socket.Dispose();
            }
            catch
            {
            }
        }