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 verifyLevel1Authentication(SecureSocket socket, Certificate cert, CertificateChain chain, VerifyEventArgs e ) { if (cert == null) { if ((Adk.Debug & AdkDebugFlags.Messaging_Detailed) != 0) { log.Warn("Client Certificate is missing and fails SIF Level 1 Authentication"); } e.Valid = false; } else if (!cert.IsCurrent) { if ((Adk.Debug & AdkDebugFlags.Messaging_Detailed) != 0) { log.Warn("Client Certificate is invalid and fails SIF Level 1 Authentication"); } e.Valid = false; } else { e.Valid = true; } }
public UpgradeHandshaker(IDictionary <string, object> handshakeEnvironment) { InternalSocket = (SecureSocket)handshakeEnvironment["secureSocket"]; _end = (ConnectionEnd)handshakeEnvironment["end"]; _responseReceivedRaised = new ManualResetEvent(false); _handshakeResult = new Dictionary <string, object>(); if (_end == ConnectionEnd.Client) { if (handshakeEnvironment.ContainsKey(":host") || (handshakeEnvironment[":host"] is string) || handshakeEnvironment.ContainsKey(":version") || (handshakeEnvironment[":version"] is string)) { _headers = new Dictionary <string, string> { { ":path", (string)handshakeEnvironment[":path"] }, { ":host", (string)handshakeEnvironment[":host"] }, { ":version", (string)handshakeEnvironment[":version"] } }; } else { throw new InvalidConstraintException("Incorrect header for upgrade handshake"); } } }
private void verifyLevel2Authentication(SecureSocket socket, Certificate cert, CertificateChain chain, VerifyEventArgs e ) { // Verify level 1 first verifyLevel1Authentication(socket, cert, chain, e); if (!e.Valid) { return; } CertificateStatus certStatus = chain.VerifyChain(null, AuthType.Client, VerificationFlags.IgnoreInvalidName); if (certStatus != CertificateStatus.ValidCertificate) { if ((Adk.Debug & AdkDebugFlags.Messaging_Detailed) != 0) { log.Warn ("Client Certificate is not trusted and fails SIF Level 2 Authentication: " + certStatus.ToString()); } e.Valid = false; } else { e.Valid = true; } }
/// <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); } }
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(); }
static void Main(string[] args) { byte[] buffer = new byte[1024]; int receivedBytes; X509Certificate2 certificate = new X509Certificate2("./certs/server.pfx"); SecureSocket socket = SecureSocketFactory.CreateSecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, certificate); socket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999)); socket.Listen(10); Console.WriteLine("Socket started"); Console.WriteLine("Waiting connections..."); while (true) { var scli = socket.Accept(); Console.WriteLine("Connection received."); while (scli.Connected) { Console.WriteLine("Reading data..."); do { receivedBytes = scli.Receive(buffer); byte[] temp = new byte[receivedBytes]; Array.Copy(buffer, 0, temp, 0, receivedBytes); Console.WriteLine("Data read: \"{0}\"", Encoding.UTF8.GetString(temp)); scli.Send(Encoding.UTF8.GetBytes(string.Format("ACK: \"{0}\"", Encoding.UTF8.GetString(temp)))); }while (receivedBytes < buffer.Length && scli.Available > 0); Thread.Sleep(50); } Console.WriteLine("Disconnected. Waiting new connection..."); } }
// --------------------------- OpenInBox ----------------------------- public SocketExchange OpenInbox( ) { // connect to the mail server. SocketExchange sockEx = new SocketExchange( m_credential.Server, Port, Logger); if (UseSecureConnection == true) { sockEx.SecureConnect( ); mSecureSocket = sockEx.ConnectedSecureSocket; } else { sockEx.Connect( ); m_socket = sockEx.ConnectedSocket; } SignalConnectedEvent(new MailEventArgs(MailEvent.Connected)); // receive initial connection response from mail server. sockEx.ExpectedResponseCodes = new ExpectedResponseCodes(PopConstants.Ok); sockEx.Receive( ); sockEx.ThrowIfUnexpectedResponse( ); // send login details ... MailServerLogin(sockEx); return(sockEx); }
public void Start() { // create a new ManualResetEvent. This will be used to make the main application // thread wait until the full server reply has been received. m_ResetEvent = new ManualResetEvent(false); // initialize the security options SecurityOptions options = new SecurityOptions( SecureProtocol.Ssl3 | SecureProtocol.Tls1, // use SSL3 or TLS1 null, // do not use client authentication ConnectionEnd.Client, // this is the client side CredentialVerification.None, // do not check the certificate -- this should not be used in a real-life application :-) null, // not used with automatic certificate verification "www.microsoft.com", // this is the common name of the Microsoft web server SecurityFlags.Default, // use the default security flags SslAlgorithms.SECURE_CIPHERS, // only use secure ciphers null); // do not process certificate requests. try { // create the securesocket with the specified security options m_Socket = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options); // resolve www.microsoft.com IPEndPoint endpoint = new IPEndPoint(Dns.Resolve("www.microsoft.com").AddressList[0], 443); // start connecting to www.microsoft.com m_Socket.BeginConnect(endpoint, new AsyncCallback(this.OnConnect), null); // wait until the entire web page has been received m_ResetEvent.WaitOne(); // close the SecureSocket m_Socket.Close(); } catch { OnError("Could not connect to the website"); } }
public Smtp() { Login = string.Empty; Server = string.Empty; Password = string.Empty; SecureSocket = SecureSocket.Auto; }
// ---------------------- CreateSecureSocket --------------------------- private SecureSocket CreateSecureSocket( ) { SecureSocket socket; // Connection type. // 0 = normal connection, 1 = direct TLS connection, // 2 = indirect TLS connection (using STARTTLS command)] mSecureSocketType = "1"; // create a new SecurityOptions instance SecurityOptions options = new SecurityOptions(SecureProtocol.None); options.AllowedAlgorithms = SslAlgorithms.SECURE_CIPHERS; options.Entity = ConnectionEnd.Client; options.VerificationType = CredentialVerification.Manual; options.Verifier = new CertVerifyEventHandler(OnVerify); options.Flags = SecurityFlags.Default; options.CommonName = ServerName; if (mSecureSocketType == "1") { options.Protocol = SecureProtocol.Tls1; } // create the new secure socket socket = new SecureSocket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options); return(socket); }
public SocketController(SecureSocket parent, Socket socket, SecurityOptions options) { m_Parent = parent; m_Socket = socket; m_IsDisposed = false; m_ActiveSend = null; m_ActiveReceive = null; m_DecryptedBuffer = new XBuffer(); m_ToSendList = new ArrayList(2); m_SentList = new ArrayList(2); m_ReceiveBuffer = new byte[m_ReceiveBufferLength]; m_Compatibility = new CompatibilityLayer(this, options); // m_RecordLayer = new RecordLayer(this, options); try { m_Socket.BeginReceive(m_ReceiveBuffer, 0, m_ReceiveBufferLength, SocketFlags.None, new AsyncCallback(this.OnReceive), null); } catch (Exception e) { CloseConnection(e); } if (options.Entity == ConnectionEnd.Client) { // byte[] hello = m_RecordLayer.GetControlBytes(ControlType.ClientHello); byte[] hello = m_Compatibility.GetClientHello(); BeginSend(hello, 0, hello.Length, null, DataType.ProtocolData); } }
public override void Attach(SecureSocket socket) { this.Socket = socket; this.AlpnExtension = this.Socket.m_Options.ExtensionList.GetExtesionOfType <ALPNExtension>(); AttachToExtension(this.AlpnExtension); }
public void Close() { if (fAcceptSocket != null) { fAcceptSocket.Close(); fAcceptSocket = null; } }
///<summary>Starts connecting to the remote host.</summary> override public void StartHandshake() { try { DestinationSocket = new SecureSocket(MapTo.AddressFamily, SocketType.Stream, ProtocolType.Tcp); DestinationSocket.BeginConnect(MapTo, new AsyncCallback(this.OnConnected), DestinationSocket); } catch { Dispose(); } }
///<summary>Initializes a new instance of the SocksHandler class.</summary> ///<param name="ClientConnection">The connection with the client.</param> ///<param name="Callback">The method to call when the SOCKS negotiation is complete.</param> ///<exception cref="ArgumentNullException"><c>Callback</c> is null.</exception> public SocksHandler(SecureSocket ClientConnection, NegotiationCompleteDelegate Callback) { if (Callback == null) { throw new ArgumentNullException(); } Connection = ClientConnection; Signaler = Callback; }
/// <summary> /// Verifies a certificate received from the remote host. /// </summary> /// <param name="socket">The SecureSocket that received the certificate.</param> /// <param name="remote">The received certificate.</param> /// <param name="e">The event parameters.</param> protected void OnVerify(SecureSocket socket, Certificate remote, CertificateChain chain, VerifyEventArgs e) { CertificateChain cc = new CertificateChain(remote); Console.WriteLine("\r\nServer Certificate:\r\n-------------------"); Console.WriteLine(remote.ToString(true)); Console.Write("\r\nServer Certificate Verification:\r\n--------------------------------\r\n -> "); Console.WriteLine(cc.VerifyChain(socket.CommonName, AuthType.Server).ToString() + "\r\n"); }
///<summary>Processes a PASV reply from the server.</summary> ///<param name="Reply">The reply to process.</param> private void ProcessPasvReply(string Reply) { try { IPEndPoint ConnectTo = ParsePasvIP(Reply); DestinationSocket = new SecureSocket(ConnectTo.AddressFamily, SocketType.Stream, ProtocolType.Tcp); DestinationSocket.BeginConnect(ConnectTo, new AsyncCallback(this.OnPasvConnected), DestinationSocket); } catch { Dispose(); } }
///<summary>Processes a received query.</summary> ///<param name="Query">The query to process.</param> private void ProcessQuery(byte [] Query) { try { switch (Query[1]) { case 1: //CONNECT IPAddress RemoteIP = null; int RemotePort = 0; if (Query[3] == 1) { RemoteIP = IPAddress.Parse(Query[4].ToString() + "." + Query[5].ToString() + "." + Query[6].ToString() + "." + Query[7].ToString()); RemotePort = Query[8] * 256 + Query[9]; } else if (Query[3] == 3) { RemoteIP = Dns.Resolve(Encoding.ASCII.GetString(Query, 5, Query[4])).AddressList[0]; RemotePort = Query[4] + 5; RemotePort = Query[RemotePort] * 256 + Query[RemotePort + 1]; } RemoteConnection = new SecureSocket(RemoteIP.AddressFamily, SocketType.Stream, ProtocolType.Tcp); RemoteConnection.BeginConnect(new IPEndPoint(RemoteIP, RemotePort), new AsyncCallback(this.OnConnected), RemoteConnection); break; case 2: //BIND byte [] Reply = new byte[10]; long LocalIP = Listener.GetLocalExternalIP().Address; AcceptSocket = new SecureSocket(IPAddress.Any.AddressFamily, SocketType.Stream, ProtocolType.Tcp); AcceptSocket.Bind(new IPEndPoint(IPAddress.Any, 0)); AcceptSocket.Listen(50); Reply[0] = 5; //Version 5 Reply[1] = 0; //Everything is ok :) Reply[2] = 0; //Reserved Reply[3] = 1; //We're going to send a IPv4 address Reply[4] = (byte)(Math.Floor((LocalIP % 256))); //IP Address/1 Reply[5] = (byte)(Math.Floor((LocalIP % 65536) / 256)); //IP Address/2 Reply[6] = (byte)(Math.Floor((LocalIP % 16777216) / 65536)); //IP Address/3 Reply[7] = (byte)(Math.Floor(LocalIP / 16777216)); //IP Address/4 Reply[8] = (byte)(Math.Floor(((IPEndPoint)AcceptSocket.LocalEndPoint).Port / 256)); //Port/1 Reply[9] = (byte)(((IPEndPoint)AcceptSocket.LocalEndPoint).Port % 256); //Port/2 Connection.BeginSend(Reply, 0, Reply.Length, SocketFlags.None, new AsyncCallback(this.OnStartAccept), Connection); break; case 3: //ASSOCIATE //ASSOCIATE is not implemented (yet?) Dispose(7); break; default: Dispose(7); break; } } catch { Dispose(1); } }
private IDictionary <string, object> MakeHandshakeEnvironment(SecureSocket incomingClient) { var result = new Dictionary <string, object> { { "securityOptions", _options }, { "secureSocket", incomingClient }, { "end", ConnectionEnd.Server } }; return(result); }
public void Bind(IPEndPoint endPoint) { if (fAcceptSocket != null) { throw new InvalidOperationException("Socket is already bound"); } fAcceptSocket = new SecureSocket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, fOptions); fAcceptSocket.Bind(endPoint); fAcceptSocket.Listen(10); }
///<summary>Starts the authentication process.</summary> ///<param name="Connection">The connection with the SOCKS client.</param> ///<param name="Callback">The method to call when the authentication is complete.</param> internal override void StartAuthentication(SecureSocket Connection, AuthenticationCompleteDelegate Callback) { this.Connection = Connection; this.Callback = Callback; try { Bytes = null; Connection.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(this.OnRecvRequest), Connection); } catch { Callback(false); } }
internal Http2Protocol(SecureSocket socket, IStreamStore streamsStore, ProtocolOptions options) { this.options = options; this.streamsStore = streamsStore; this.serializer = new FrameSerializer(this.options); this.builder = new FrameBuilder(); this.socket = socket; this.isServer = true; this.handshakeFinishedEventRaised = new ManualResetEvent(false); }
//TODO must be reworked public static void SendHeaders(SecureSocket socket, Dictionary <string, string> headers, int contentLength = 0) { var headersString = new StringBuilder(); foreach (var header in headers) { headersString.AppendFormat("{0}: {1}\r\n", header.Key, header.Value); } headersString.AppendFormat("Content-Length: {0}\r\n" + "\r\n", contentLength); byte[] headersBytes = Encoding.UTF8.GetBytes(headersString.ToString()); socket.Send(headersBytes); }
/// <summary> /// This method is called when the SecureSocket received the remote /// certificate and when the certificate validation type is set to Manual. /// </summary> /// <param name="socket">The <see cref="SecureSocket"/> that received the certificate to verify.</param> /// <param name="remote">The <see cref="Certificate"/> of the remote party to verify.</param> /// <param name="chain">The <see cref="CertificateChain"/> associated with the remote certificate.</param> /// <param name="e">A <see cref="VerifyEventArgs"/> instance used to (in)validate the certificate.</param> /// <remarks>If an error is thrown by the code in the delegate, the SecureSocket will close the connection.</remarks> protected void OnVerify(SecureSocket socket, Certificate remote, CertificateChain chain, VerifyEventArgs e) { // get all the certificates from the certificate chain .. Certificate[] certs = chain.GetCertificates(); // .. and print them out in the console for (int i = 0; i < certs.Length; i++) { Console.WriteLine(certs[i].ToString(true)); } // print out the result of the chain verification Console.WriteLine(chain.VerifyChain(socket.CommonName, AuthType.Server)); }
///<summary>Starts listening on the selected IP address and port.</summary> ///<exception cref="SocketException">There was an error while creating the listening socket.</exception> public void Start() { try { ListenSocket = new SecureSocket(Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp); ListenSocket.Bind(new IPEndPoint(Address, Port)); ListenSocket.Listen(50); ListenSocket.BeginAccept(new AsyncCallback(this.OnAccept), ListenSocket); } catch { ListenSocket = null; throw new SocketException(); } }
///<summary>Called when the SOCKS protocol has ended. We can no start relaying data, if the SOCKS authentication was successful.</summary> ///<param name="Success">Specifies whether the SOCKS negotiation was successful or not.</param> ///<param name="Remote">The connection with the remote server.</param> private void OnEndSocksProtocol(bool Success, SecureSocket Remote) { DestinationSocket = Remote; if (Success) { StartRelay(); } else { Dispose(); } }
private bool GetSessionHeaderAndVerifyIt(SecureSocket incomingClient) { var sessionHeaderBuffer = new byte[ClientSessionHeader.Length]; int received = incomingClient.Receive(sessionHeaderBuffer, 0, sessionHeaderBuffer.Length, SocketFlags.None); var receivedHeader = Encoding.UTF8.GetString(sessionHeaderBuffer); return(string.Equals(receivedHeader, ClientSessionHeader, StringComparison.OrdinalIgnoreCase)); }
///<summary>Called when we're connected to the data port of the remote FTP server.</summary> ///<param name="ar">The result of the asynchronous operation.</param> private void OnPasvConnected(IAsyncResult ar) { try { DestinationSocket.EndConnect(ar); ListenSocket = new SecureSocket(IPAddress.Any.AddressFamily, SocketType.Stream, ProtocolType.Tcp); ListenSocket.Bind(new IPEndPoint(IPAddress.Any, 0)); ListenSocket.Listen(1); ListenSocket.BeginAccept(new AsyncCallback(this.OnPasvAccept), ListenSocket); Parent.SendCommand("227 Entering Passive Mode (" + Listener.GetLocalInternalIP().ToString().Replace('.', ',') + "," + Math.Floor(((IPEndPoint)ListenSocket.LocalEndPoint).Port / 256).ToString() + "," + (((IPEndPoint)ListenSocket.LocalEndPoint).Port % 256).ToString() + ").\r\n"); } catch { Dispose(); } }
public SecureHandshaker(IDictionary <string, object> handshakeEnvironment) { InternalSocket = (SecureSocket)handshakeEnvironment["secureSocket"]; InternalSocket.OnHandshakeFinish += HandshakeFinishedHandler; Options = (SecurityOptions)handshakeEnvironment["securityOptions"]; _handshakeFinishedEventRaised = new ManualResetEvent(false); if (Options.Protocol == SecureProtocol.None) { HandshakeFinishedHandler(this, null); } }
public SocketController(SecureSocket parent, Socket socket, SecurityOptions options) { this.m_Parent = parent; this.m_Socket = socket; this.m_IsDisposed = false; this.m_ActiveSend = null; this.m_ActiveReceive = null; this.m_DecryptedBuffer = new XBuffer(); this.m_ToSendList = new ArrayList(2); this.m_SentList = new ArrayList(2); this.m_ReceiveBuffer = new byte[m_ReceiveBufferLength]; this.m_End = options.Entity; this.OnConnectionClose += parent.ConnectionCloseHandler; this.m_Compatibility = new CompatibilityLayer(this, options); }