private static void RunClientInSynchronousMode() { int timer = 1000; byte[] buffer = new byte[1024]; int receivedBytes; X509Certificate2 certificate = new X509Certificate2("./certs/client.pfx"); SecureSocket socket = SecureSocketFactory.CreateSecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, certificate); Console.WriteLine("Connecting to server in {0} seconds", timer / 1000D); Thread.Sleep(timer); socket.Connect("127.0.0.1", 9999); Console.WriteLine("Connected to server"); while (socket.Connected) { // Leitura Console.ForegroundColor = ConsoleColor.White; Console.Write("> "); string line = Console.ReadLine(); socket.Send(Encoding.UTF8.GetBytes(line)); // Escrita Console.ForegroundColor = ConsoleColor.Yellow; do { receivedBytes = socket.Receive(buffer); byte[] temp = new byte[receivedBytes]; Array.Copy(buffer, 0, temp, 0, receivedBytes); Console.WriteLine("< {0}", Encoding.UTF8.GetString(temp)); }while (receivedBytes < buffer.Length && socket.Available > 0); Thread.Sleep(50); } Console.WriteLine("Disconnected. Finishing..."); }
private void DownloadFile(Url url, int choice) { SecurityOptions options = new SecurityOptions(SecureProtocol.None);; m_Socket = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options); // connect to the FTP server using a normal TCP connection m_Socket.Connect(new IPEndPoint(Dns.Resolve(url.Host).AddressList[0], url.Port)); // wait for the server hello ReceiveReply(); // if the user selected to use the AUTH command.. if (choice == 2) { // ..send the command to the server and start the SSL handshake DoAuthCommand(url.Host); } // log on and quit if (!SendCommand("USER " + url.Username)) { return; } if (!SendCommand("PASS " + url.Password)) { return; } if (!SendCommand("QUIT")) { return; } // clean up m_Socket.Shutdown(SocketShutdown.Both); m_Socket.Close(); }
/// <summary> /// Connect to the Server in the Bookmark using the UserInfo from the /// bookmark as well. /// </summary> /// <param name="bookmark">The info about Server and /// UserInformation.</param> public void Connect(Bookmark bookmark) { commandSocket = new SecureSocket(); commands = new Commands(commandSocket); lagHandler = new LagHandler(); try { if (bookmark != null) { commandSocket.MessageReceived += messages.MessageReceived; commandSocket.Connect(bookmark.Server); commands.Hello(bookmark.Server.MachineName, bookmark.Server.ServerPort, bookmark.Server.ServerName); mCurrentBookmark = bookmark; messages.PingReplyEvent += lagHandler.OnPingReceived; commands.PingSentEvent += lagHandler.OnPingSent; } else { //TODO: Handle error Debug.WriteLine("CONNECTIONMANAGER -> Connect: Trying to connect to a null bookmark."); } } catch (ConnectionException ce) { ce.Bookmark = bookmark; throw (ce); } }
protected static SecureSocket GetHandshakedSocket(Uri uri) { string selectedProtocol = null; var extensions = new[] { ExtensionType.Renegotiation, ExtensionType.ALPN }; var options = _useSecurePort ? new SecurityOptions(SecureProtocol.Tls1, extensions, new[] { Protocols.Http2, Protocols.Http1 }, ConnectionEnd.Client) : new SecurityOptions(SecureProtocol.None, extensions, new[] { Protocols.Http2, Protocols.Http1 }, ConnectionEnd.Client); options.VerificationType = CredentialVerification.None; options.Certificate = Org.Mentalis.Security.Certificates.Certificate.CreateFromCerFile(@"certificate.pfx"); options.Flags = SecurityFlags.Default; options.AllowedAlgorithms = SslAlgorithms.RSA_AES_256_SHA | SslAlgorithms.NULL_COMPRESSION; var sessionSocket = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options); using (var monitor = new ALPNExtensionMonitor()) { monitor.OnProtocolSelected += (sender, args) => { selectedProtocol = args.SelectedProtocol; }; sessionSocket.Connect(new DnsEndPoint(uri.Host, uri.Port), monitor); if (_useHandshake) { var handshakeEnv = new Dictionary <string, object> { { ":method", "get" }, { ":version", Protocols.Http1 }, { ":path", uri.PathAndQuery }, { ":scheme", uri.Scheme }, { ":host", uri.Host }, { "securityOptions", options }, { "secureSocket", sessionSocket }, { "end", ConnectionEnd.Client } }; _handshakeResult = HandshakeManager.GetHandshakeAction(handshakeEnv).Invoke(); } } SendSessionHeader(sessionSocket); return(sessionSocket); }
public void UpgradeHandshakeSuccessful() { const string requestStr = @"http://*****:*****@"certificate.pfx"), Flags = SecurityFlags.Default, AllowedAlgorithms = SslAlgorithms.RSA_AES_256_SHA | SslAlgorithms.NULL_COMPRESSION }; var sessionSocket = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options); sessionSocket.Connect(new DnsEndPoint(uri.Host, uri.Port)); var handshakeEnv = new Dictionary <string, object> { { ":method", "get" }, { ":version", Protocols.Http1 }, { ":path", uri.PathAndQuery }, { ":scheme", uri.Scheme }, { ":host", uri.Host }, { "securityOptions", options }, { "secureSocket", sessionSocket }, { "end", ConnectionEnd.Client } }; bool gotFailedException = false; try { HandshakeManager.GetHandshakeAction(handshakeEnv).Invoke(); } catch (Http2HandshakeFailed) { gotFailedException = true; } sessionSocket.Close(); Assert.Equal(gotFailedException, false); }
public void AlpnSelectionHttp2Successful() { const string requestStr = @"https://*****:*****@"certificate.pfx"), Flags = SecurityFlags.Default, AllowedAlgorithms = SslAlgorithms.RSA_AES_256_SHA | SslAlgorithms.NULL_COMPRESSION }; var sessionSocket = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options); using (var monitor = new ALPNExtensionMonitor()) { monitor.OnProtocolSelected += (sender, args) => { selectedProtocol = args.SelectedProtocol; }; sessionSocket.Connect(new DnsEndPoint(uri.Host, uri.Port), monitor); var handshakeEnv = new Dictionary <string, object> { { ":method", "get" }, { ":version", Protocols.Http1 }, { ":path", uri.PathAndQuery }, { ":scheme", uri.Scheme }, { ":host", uri.Host }, { "securityOptions", options }, { "secureSocket", sessionSocket }, { "end", ConnectionEnd.Client } }; HandshakeManager.GetHandshakeAction(handshakeEnv).Invoke(); } sessionSocket.Close(); Assert.Equal(Protocols.Http2, selectedProtocol); }
private void Connect(SecureProtocol protocol) { try { GXLogging.Debug(log, "Connecting to host: " + host + ", port: " + port); SecurityOptions options = new SecurityOptions(protocol); options.AllowedAlgorithms = SslAlgorithms.ALL; options.Entity = ConnectionEnd.Client; options.VerificationType = CredentialVerification.Manual; options.Verifier = new CertVerifyEventHandler(OnCertificateVerify); options.Flags = SecurityFlags.Default; options.CommonName = host; connection = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options); IPHostEntry serverIPs = Dns.GetHostEntry(host.Trim()); IPAddress hostAddress = serverIPs.AddressList.First(a => (a.AddressFamily == connection.AddressFamily));; connection.Connect(new IPEndPoint(hostAddress, port)); string response = GetResponse(); GXLogging.Debug(log, "Connect Server response: " + response); if (!response.StartsWith("+OK")) { throw new IOException(response); } } catch (IOException exc) { GXLogging.Error(log, "Bad server response", exc); throw new GXMailException(exc.Message, MailConstants.MAIL_CantLogin); } catch (Exception exc) { GXLogging.Error(log, "Can't connect to host", exc); throw new GXMailException("Can't connect to host", MailConstants.MAIL_CantLogin); } }
public void Start() { try { // ask the user for SMTP server, port and the type of connection Console.Write("Host to connect to: "); string server = Console.ReadLine().Trim(); Console.Write("Port: "); string port = Console.ReadLine().Trim(); Console.Write("Connection type [0 = normal connection, 1 = direct TLS connection, 2 = indirect TLS connection (using STARTTLS command)]: "); string type = Console.ReadLine().Trim(); if (Array.IndexOf(new string[] { "0", "1", "2" }, type) == -1) { Console.WriteLine("Invalid connection type."); return; } Console.WriteLine("Please enter the email address you wish to send an email to:"); string address = Console.ReadLine().Trim(); // create a new SecurityOptions instance SecurityOptions options = new SecurityOptions(SecureProtocol.None); // allow only secure ciphers to be used. Currently, the seure ciphers are: // the AES algorithm [128 or 256 bit keys], the RC4 algorithm [128 bit keys] // or TipleDES [168 bit keys] options.AllowedAlgorithms = SslAlgorithms.SECURE_CIPHERS; // the SecureSocket should be a client socket options.Entity = ConnectionEnd.Client; // we will use manual verification of the server certificate options.VerificationType = CredentialVerification.Manual; // when the server certificate is receives, the SecureSocket should call // the OnVerify method options.Verifier = new CertVerifyEventHandler(OnVerify); // use the default flags options.Flags = SecurityFlags.Default; // the common name is the domain name or IP address of the server options.CommonName = server; // if the user chose a direct TLS connection, set the protocol to TLS1 if (type == "1") { options.Protocol = SecureProtocol.Tls1; } // create the new secure socket Connection = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options); // connect to the SMTP server Connection.Connect(new IPEndPoint(Dns.Resolve(server).AddressList[0], int.Parse(port))); // wait for the server hello message if (!IsReplyOK(Receive())) { Console.WriteLine("Server disallowed connection."); return; } // if the user selected an indirect TLS connection, issue // a EHLO command. Otherwise, stick to the standard HELO command. if (type == "2") // STARTTLS connection { Send("EHLO SmtpClient.Mentalis.org\r\n"); } else { Send("HELO SmtpClient.Mentalis.org\r\n"); } if (!IsReplyOK(Receive())) { Console.WriteLine("HELLO failed."); return; } // if the user selected an indirect TLS connection, issue // the STARTTLS command if (type == "2") { // send the STARTTLS command to the server Send("STARTTLS\r\n"); // make sure the server supports the STARTTLS command if (!IsReplyOK(Receive())) { Console.WriteLine("STARTTLS failed."); return; } // change the protocol from SecureProtocol.None // to SecureProtocol.Tls1 options.Protocol = SecureProtocol.Tls1; // start the TLS handshake Connection.ChangeSecurityProtocol(options); // after this line, we're using an encrypted TLS connection } // from here on, act as if the SecureSocket is a normal Socket Send("MAIL FROM: [email protected]\r\n"); // [email protected] is not a real email address if (!IsReplyOK(Receive())) { Console.WriteLine("MAIL FROM failed."); return; } Send("RCPT TO:" + address + "\r\n"); if (!IsReplyOK(Receive())) { Console.WriteLine("RCPT TO failed."); return; } Send("DATA\r\n"); if (!IsReplyOK(Receive())) { Console.WriteLine("DATA failed."); return; } Send(TestMail.Replace("#ADDRESS#", address) + "\r\n.\r\n"); if (!IsReplyOK(Receive())) { Console.WriteLine("Sending of e-mail failed."); return; } Send("QUIT\r\n"); if (!IsReplyOK(Receive())) { Console.WriteLine("QUIT failed."); } Connection.Shutdown(SocketShutdown.Both); } catch (Exception e) { Console.WriteLine("An error occurred [" + e.Message + "]"); Console.WriteLine(e); } finally { if (Connection != null) { Connection.Close(); } } }
public bool Connect(Uri connectUri) { _path = connectUri.PathAndQuery; _version = Protocols.Http2; _scheme = connectUri.Scheme; _host = connectUri.Host; _port = connectUri.Port; ServerUri = connectUri.Authority; if (_clientSession != null) { return(false); } try { int port = connectUri.Port; int securePort; if (!int.TryParse(ConfigurationManager.AppSettings["securePort"], out securePort)) { Http2Logger.LogError("Incorrect port in the config file!"); return(false); } //Connect alpn extension, set known protocols var extensions = new[] { ExtensionType.Renegotiation, ExtensionType.ALPN }; _options = port == securePort ? new SecurityOptions(SecureProtocol.Tls1, extensions, new[] { Protocols.Http1, Protocols.Http2 }, ConnectionEnd.Client) : new SecurityOptions(SecureProtocol.None, extensions, new[] { Protocols.Http1, Protocols.Http2 }, ConnectionEnd.Client); _options.VerificationType = CredentialVerification.None; _options.Certificate = Org.Mentalis.Security.Certificates.Certificate.CreateFromCerFile(CertificatePath); _options.Flags = SecurityFlags.Default; _options.AllowedAlgorithms = SslAlgorithms.RSA_AES_256_SHA | SslAlgorithms.NULL_COMPRESSION; _socket = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, _options); IDictionary <string, object> handshakeResult = null; using (var monitor = new ALPNExtensionMonitor()) { monitor.OnProtocolSelected += (o, args) => { _selectedProtocol = args.SelectedProtocol; }; _socket.Connect(new DnsEndPoint(connectUri.Host, connectUri.Port), monitor); if (_useHandshake) { var handshakeEnvironment = MakeHandshakeEnvironment(_socket); //Handshake manager determines what handshake must be used: upgrade or secure handshakeResult = HandshakeManager.GetHandshakeAction(handshakeEnvironment).Invoke(); Http2Logger.LogDebug("Handshake finished"); if (_selectedProtocol == Protocols.Http1) { _useHttp20 = false; return(true); } } } SendSessionHeader(); _useHttp20 = true; _clientSession = new Http2Session(_socket, ConnectionEnd.Client, _usePriorities, _useFlowControl, handshakeResult); //For saving incoming data _clientSession.OnFrameReceived += FrameReceivedHandler; _clientSession.OnRequestSent += RequestSentHandler; _clientSession.OnSessionDisposed += (sender, args) => Dispose(false); } catch (Http2HandshakeFailed ex) { if (ex.Reason == HandshakeFailureReason.InternalError) { _useHttp20 = false; } else { Http2Logger.LogError("Specified server did not respond"); Dispose(true); return(false); } } catch (SocketException) { Http2Logger.LogError("Check if any server listens port " + connectUri.Port); Dispose(true); return(false); } catch (Exception ex) { Http2Logger.LogError("Unknown connection exception was caught: " + ex.Message); Dispose(true); return(false); } return(true); }
private SecureSocket CreateSocketByUri(Uri uri) { if (!String.Equals(uri.Scheme, "http", StringComparison.OrdinalIgnoreCase) && !String.Equals(uri.Scheme, "https", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException("Unrecognized scheme: " + uri.Scheme); } SecurityOptions options; var extensions = new ExtensionType[] { ExtensionType.Renegotiation, ExtensionType.ALPN }; if (!String.Equals(uri.Scheme, "https", StringComparison.OrdinalIgnoreCase)) { options = new SecurityOptions(SecureProtocol.None, null, ConnectionEnd.Client); } else { options = new SecurityOptions(SecureProtocol.Tls1, extensions, ConnectionEnd.Client); } options.Entity = ConnectionEnd.Client; options.CommonName = uri.Host; options.VerificationType = CredentialVerification.None; options.Certificate = Org.Mentalis.Security.Certificates.Certificate.CreateFromCerFile(@"certificate.pfx"); options.Flags = SecurityFlags.Default; options.AllowedAlgorithms = SslAlgorithms.RSA_AES_128_SHA | SslAlgorithms.NULL_COMPRESSION; var s = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options); s.OnClose += SocketOnClose; try { if (String.Equals(uri.Scheme, "https", StringComparison.OrdinalIgnoreCase)) { s.OnHandshakeFinish += this.HandshakeFinishedHandler; } s.Connect(new Net.DnsEndPoint(uri.Host, uri.Port)); if (String.Equals(uri.Scheme, "https", StringComparison.OrdinalIgnoreCase)) { this.handshakeFinishedEventRaised.WaitOne(60000); if (!s.IsNegotiationCompleted) { throw new Exception("Handshake failed"); } if (!s.Connected) { throw new Exception("Connection was lost!"); } s.OnHandshakeFinish -= this.HandshakeFinishedHandler; this.ApplyProtocolSelectionResults(options.GetSelectedProtocol()); } } catch (Exception ex) { s.Close(); // Emitting protocol error. It will emit session OnError if (OnError != null) { this.OnError(this, new ProtocolErrorEventArgs(ex)); } throw; } return(s); }
/// <summary> /// Download a file using the synchronous Socket methods. /// </summary> /// <param name="url">The URL to download. /// </param> /// <param name="sp">The protocol to use.</param> protected void DownloadFile(Url url, SecureProtocol sp) { string request = GetHttpRequest(url); // holds the HTTP request for the given URL SecureSocket s; try { // First we create a new SecurityOptions instance // SecurityOptions objects hold information about the security // protocols the SecureSocket should use and how the SecureSocket // should react in certain situations. SecurityOptions options = new SecurityOptions(sp); // The Certificate field holds a certificate associated with // a client [you, for instance]. Because client certificates // are not often used for HTTP over SSL or TLS, we'll simply // set this field to a null reference. options.Certificate = null; // The Entity specifies whether the SecureSocket should act // as a client socket or as a server socket. In this case, // it should act as a client socket. options.Entity = ConnectionEnd.Client; // The CommonName field specifies the name of the remote // party we're connecting to. This is usually the domain name // of the remote host. options.CommonName = url.Host; // The VerificationType field specifies how we intend to verify // the certificate. In this case, we tell the SecureSocket that // we will manually verify the certificate. Look in the documentation // for other options. options.VerificationType = CredentialVerification.Manual; // When specifying the CredentialVerification.Manual option, we // must also specify a CertVerifyEventHandler delegate that will // be called when the SecureSocket receives the remote certificate. // The Verifier field holds this delegate. If no manual verification // is done, this field can be set to a null reference. options.Verifier = new CertVerifyEventHandler(OnVerify); // The Flags field specifies which flags should be used for the // connection. In this case, we will simply use the default behavior. options.Flags = SecurityFlags.Default; // Allow only secure ciphers to be used. If the server only supports // weak encryption, the connections will be shut down. options.AllowedAlgorithms = SslAlgorithms.SECURE_CIPHERS; // create a new SecureSocket instance and initialize it with // the security options we specified above. s = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options); // connect to the remote host s.Connect(new IPEndPoint(Dns.Resolve(url.Host).AddressList[0], url.Port)); } catch (Exception e) { Console.WriteLine("Exception occurred while connecting: " + e.ToString()); return; } // send the HTTP request to the remote host Console.Write("HTTP Query string:\r\n------------------\r\n" + request); try { byte[] reqBytes = Encoding.ASCII.GetBytes(request); int sent = s.Send(reqBytes, 0, reqBytes.Length, SocketFlags.None); while (sent != reqBytes.Length) { sent += s.Send(reqBytes, sent, reqBytes.Length - sent, SocketFlags.None); } } catch (Exception e) { Console.WriteLine("Exception occurred while sending: " + e.ToString()); return; } // receive the reply Console.WriteLine("HTTP Server reply:\r\n------------------"); try { byte[] buffer = new byte[4096]; int ret = s.Receive(buffer); while (ret != 0) { Console.Write(Encoding.ASCII.GetString(buffer, 0, ret)); ret = s.Receive(buffer); } } catch (Exception e) { Console.WriteLine("Exception occurred while receiving: " + e.ToString()); return; } try { s.Shutdown(SocketShutdown.Both); // shut down the TCP connection } catch (Exception e) { Console.WriteLine("Exception occurred while shutting the connection down: " + e.ToString()); return; } s.Close(); }
// ----------------------------- SecureConnect ----------------------------- // secure SSL connect to the remote socket. public void SecureConnect( ) { mSecureSocket = null; // make sure server name and port have been spcfd. if (Stringer.IsEmpty(mServerName) == true) { ThrowNetworkException("Connect error. Server name is empty."); } if (mServerPortNx == 0) { ThrowNetworkException("Connect error. Server port number is zero."); } // resolve and connect to the remote system. try { // resolve to the host server. IPHostEntry hostEntry = null; hostEntry = Dns.Resolve(mServerName); // I guess Resolve returns a list of IP addresses. ( something to do with // IPv6 ). This loop is standard stuff pulled from the MS documenation. // Try to connect to each address until successful. foreach (IPAddress address in hostEntry.AddressList) { IPEndPoint ep = new IPEndPoint(address, mServerPortNx); SecureSocket tempSocket = CreateSecureSocket( ); // Socket tempSocket = new Socket( // ep.AddressFamily, // SocketType.Stream, // ProtocolType.Tcp ) ; // connect to the SMTP server tempSocket.Connect(ep); if (tempSocket.Connected == true) { ConnectedSecureSocket = tempSocket; break; } } } catch (Exception e) { ThrowNetworkException( "Exception connecting to " + ServerPortCombo, e); } // throw exception if can't connect ... if (mSecureSocket == null) { ThrowNetworkException("Failed to connect to " + ServerPortCombo); } else { AddMessage(NetworkRole.Client, "Connected to " + ServerPortCombo); } }