public Connect ( |
||
remoteEP | An |
|
return | void |
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.GetHostEntry(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(); }
public bool Connect(Uri connectUri) { _path = connectUri.PathAndQuery; _version = Protocols.Http2; _scheme = connectUri.Scheme; _host = connectUri.Host; _port = connectUri.Port; ServerUri = connectUri.Authority; if (_sessionAdapter != 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; var socket = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, Options); using (var monitor = new ALPNExtensionMonitor()) { monitor.OnProtocolSelected += (o, args) => { _selectedProtocol = args.SelectedProtocol; }; socket.Connect(new DnsEndPoint(connectUri.Host, connectUri.Port), monitor); _clientStream = new DuplexStream(socket, true); if (_useHandshake) { MakeHandshakeEnvironment(); //Handshake manager determines what handshake must be used: upgrade or secure if (socket.SecureProtocol != SecureProtocol.None) { socket.MakeSecureHandshake(Options); _selectedProtocol = socket.SelectedProtocol; } if (socket.SecureProtocol == SecureProtocol.None || _selectedProtocol == Protocols.Http1) { try { var handshakeResult = new UpgradeHandshaker(_environment).Handshake(); _environment.Add(HandshakeKeys.Result, handshakeResult); _useHttp20 = handshakeResult[HandshakeKeys.Successful] as string == HandshakeKeys.True; if (!_useHttp20) { Dispose(false); return true; } } catch (Http2HandshakeFailed ex) { if (ex.Reason == HandshakeFailureReason.InternalError) { _useHttp20 = false; } else { Http2Logger.LogError("Specified server did not respond"); Dispose(true); return false; } } } } } Http2Logger.LogDebug("Handshake finished"); if (_useHttp20) { //TODO provide transport info _sessionAdapter = new Http2ClientMessageHandler(_clientStream, ConnectionEnd.Client, default(TransportInformation), CancellationToken.None); } } 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; }
//sendraw SSL public string sendraw (string ipRaw, string portRaw, string payloadRaw, int size, int TimeOut, int retry, bool useSSL) { IPHostEntry IPHost = Dns.Resolve(ipRaw); string []aliases = IPHost.Aliases; IPAddress[] addr = IPHost.AddressList; IPEndPoint iep ; SecureProtocol sp; sp=SecureProtocol.Ssl3; SecureSocket s=null; SecurityOptions options = new SecurityOptions(sp); options.Certificate = null; options.Protocol=SecureProtocol.Ssl3; options.Entity = ConnectionEnd.Client; options.CommonName = ipRaw; options.VerificationType = CredentialVerification.None; options.Flags = SecurityFlags.IgnoreMaxProtocol; options.AllowedAlgorithms = SslAlgorithms.ALL; while (retry>0){ try { s = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options); s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 4000); s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 4000); iep = new IPEndPoint(addr[0],Convert.ToInt32(portRaw)); s.Connect(iep); ASCIIEncoding asen= new ASCIIEncoding(); byte[] ba=asen.GetBytes(payloadRaw); s.Send(ba,ba.Length,System.Net.Sockets.SocketFlags.None); byte[] bb=new byte[size]; int k=1; string response=""; while (k>0){ k=s.Receive(bb,size,System.Net.Sockets.SocketFlags.None); response+=Encoding.Default.GetString(bb,0,k); } s.Close(); GC.Collect(); GC.WaitForPendingFinalizers(); return response; } catch(Exception ex) { retry--; Thread.Sleep(1000); } } return "Timeout or retry count exceeded"; }
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; }
public string sendraw(string ipRaw, string portRaw, string payloadRaw, int size, int TimeOut, bool useSSL) { int retry = (int)updownRetryTCP.Value; IPHostEntry IPHost = Dns.GetHostEntry(ipRaw); //IPHostEntry IPHost = Dns.Resolve(ipRaw); string[] aliases = IPHost.Aliases; IPAddress[] addr = IPHost.AddressList; IPEndPoint iep; SecureProtocol sp; sp = SecureProtocol.Ssl3; SecureSocket s = null; SecurityOptions options = new SecurityOptions(sp); options.Certificate = null; options.Protocol = SecureProtocol.Ssl3; options.Entity = ConnectionEnd.Client; options.CommonName = ipRaw; options.VerificationType = CredentialVerification.None; options.Flags = SecurityFlags.IgnoreMaxProtocol; options.AllowedAlgorithms = SslAlgorithms.ALL; while (retry > 0) { try { s = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options); s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 4000); s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 4000); iep = new IPEndPoint(addr[0], Convert.ToInt32(portRaw)); s.Connect(iep); ASCIIEncoding asen = new ASCIIEncoding(); byte[] ba = asen.GetBytes(payloadRaw); s.Send(ba, ba.Length, System.Net.Sockets.SocketFlags.None); byte[] bb = new byte[size]; string response = ""; int k = 1; while (k > 0) { k = s.Receive(bb, size, System.Net.Sockets.SocketFlags.None); for (int i = 0; i < k; i++) { response += Convert.ToChar(bb[i]); } } s.Close(); GC.Collect(); GC.WaitForPendingFinalizers(); return response; } catch { retry--; lblStatus.Text = "Network problem - retrying\r\n"; lblNiktoAI.Text = "Network problem - retrying\r\n"; Thread.Sleep(1000); } } return "Retry count (" + updownRetryTCP.Value.ToString() + ") exceeded"; }
public static DuplexStream GetHandshakedDuplexStream(string address, bool allowHttp2Communication = true, bool useMock = false) { string selectedProtocol = null; var extensions = new[] { ExtensionType.Renegotiation, ExtensionType.ALPN }; var useHandshake = ConfigurationManager.AppSettings["handshakeOptions"] != "no-handshake"; var protocols = new List<string> { Protocols.Http1 }; if (allowHttp2Communication) { protocols.Add(Protocols.Http2); } var options = UseSecurePort ? new SecurityOptions(SecureProtocol.Tls1, extensions, protocols, ConnectionEnd.Client) : new SecurityOptions(SecureProtocol.None, extensions, protocols, 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; }; var uri = new Uri(GetAddress() + address); sessionSocket.Connect(new DnsEndPoint(uri.Host, uri.Port), monitor); if (useHandshake) { sessionSocket.MakeSecureHandshake(options); } } //SendSessionHeader(sessionSocket); return useMock ? new Mock<DuplexStream>(sessionSocket, true).Object : new DuplexStream(sessionSocket, 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; }
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.GetHostEntry(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(); } } }
/// <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.GetHostEntry(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(); }