internal static int Decrypt(IntPtr sslContextPtr, IntPtr outBufferPtr, int count, out libssl.SslErrorCode errorCode) { errorCode = libssl.SslErrorCode.SSL_ERROR_NONE; SslContext context = Marshal.PtrToStructure <SslContext>(sslContextPtr); int retVal = BioWrite(context.readBioPtr, outBufferPtr, count); if (retVal == count) { retVal = libssl.SSL_read(context.sslPtr, outBufferPtr, retVal); if (retVal > 0) { count = retVal; } } if (retVal != count) { errorCode = GetSslError(context.sslPtr, retVal); retVal = 0; switch (errorCode) { // indicate end-of-file case libssl.SslErrorCode.SSL_ERROR_ZERO_RETURN: break; case libssl.SslErrorCode.SSL_ERROR_WANT_READ: // update error code to renegotiate if renegotiate is pending, otherwise make it SSL_ERROR_WANT_READ errorCode = libssl.SSL_renegotiate_pending(context.sslPtr) == 1 ? libssl.SslErrorCode.SSL_ERROR_RENEGOTIATE : libssl.SslErrorCode.SSL_ERROR_WANT_READ; break; default: throw CreateSslException("OpenSsl::Decrypt failed"); } } return(retVal); }
internal static int Encrypt(IntPtr handlePtr, IntPtr buffer, int offset, int count, int bufferCapacity, out libssl.SslErrorCode errorCode) { errorCode = libssl.SslErrorCode.SSL_ERROR_NONE; SslContext context = Marshal.PtrToStructure <SslContext>(handlePtr); var retVal = libssl.SSL_write(context.sslPtr, new IntPtr(buffer.ToInt64() + offset), count); if (retVal != count) { errorCode = GetSslError(context.sslPtr, retVal); retVal = 0; switch (errorCode) { // indicate end-of-file case libssl.SslErrorCode.SSL_ERROR_ZERO_RETURN: case libssl.SslErrorCode.SSL_ERROR_WANT_READ: break; default: throw CreateSslException("OpenSsl::Encrypt failed"); } } else { int capacityNeeded = libssl.BIO_ctrl_pending(context.writeBioPtr); if (capacityNeeded > bufferCapacity) { throw CreateSslException("OpenSsl::Encrypt capacity needed is more than buffer capacity. capacityNeeded = " + capacityNeeded + "," + "bufferCapacity = " + bufferCapacity); } retVal = BioRead(context.writeBioPtr, buffer, capacityNeeded); if (retVal < 0) { throw CreateSslException("OpenSsl::Encrypt failed"); } } return(retVal); }
internal static bool DoSslHandshake(IntPtr sslContextPtr, IntPtr recvPtr, int recvCount, out IntPtr sendPtr, out int sendCount) { sendPtr = IntPtr.Zero; sendCount = 0; SslContext context = Marshal.PtrToStructure <SslContext>(sslContextPtr); bool isServer = context.isServer; if ((IntPtr.Zero != recvPtr) && (recvCount > 0)) { BioWrite(context.readBioPtr, recvPtr, recvCount); } int retVal = libssl.SSL_do_handshake(context.sslPtr); if (retVal != 1) { libssl.SslErrorCode error = GetSslError(context.sslPtr, retVal); if ((retVal != -1) || (error != libssl.SslErrorCode.SSL_ERROR_WANT_READ)) { throw CreateSslException(context.sslPtr, "SSL Handshake failed: ", retVal); } } sendCount = libssl.BIO_ctrl_pending(context.writeBioPtr); if (sendCount > 0) { sendPtr = Marshal.AllocHGlobal(sendCount); sendCount = BioRead(context.writeBioPtr, sendPtr, sendCount); if (sendCount <= 0) { int errorCode = sendCount; Marshal.FreeHGlobal(sendPtr); sendPtr = IntPtr.Zero; sendCount = 0; throw CreateSslException(context.sslPtr, "Read Bio failed: ", errorCode); } } return((libssl.SSL_state(context.sslPtr) == (int)libssl.SslState.SSL_ST_OK)); }
public void StreamDefaults() { using (var ssl = new SslContext(SslProtocolSide.Client, SslConnectionType.Stream)) { Assert.That(ssl.BufferedReadSize, Is.EqualTo((nint)0), "BufferedReadSize"); Assert.That(ssl.ClientCertificateState, Is.EqualTo(SslClientCertificateState.None), "ClientCertificateState"); Assert.Null(ssl.Connection, "Connection"); Assert.That(ssl.DatagramWriteSize, Is.EqualTo((nint)0), "DatagramWriteSize"); Assert.That(ssl.Handle, Is.Not.EqualTo(IntPtr.Zero), "Handle"); Assert.That(ssl.MaxDatagramRecordSize, Is.EqualTo((nint)0), "MaxDatagramRecordSize"); Assert.That(ssl.MaxProtocol, Is.EqualTo(SslProtocol.Tls_1_2), "MaxProtocol"); Assert.That(ssl.MinProtocol, Is.EqualTo(SslProtocol.Ssl_3_0), "MinProtocol"); Assert.That(ssl.NegotiatedCipher, Is.EqualTo(SslCipherSuite.SSL_NULL_WITH_NULL_NULL), "NegotiatedCipher"); Assert.That(ssl.NegotiatedProtocol, Is.EqualTo(SslProtocol.Unknown), "NegotiatedProtocol"); Assert.That(ssl.PeerDomainName, Is.Empty, "PeerDomainName"); ssl.PeerDomainName = "google.ca"; Assert.That(ssl.PeerDomainName, Is.EqualTo("google.ca"), "PeerDomainName-2"); ssl.PeerDomainName = null; Assert.That(ssl.PeerDomainName, Is.Empty, "PeerDomainName"); Assert.Null(ssl.PeerId, "PeerId"); ssl.PeerId = new byte [] { 0xff }; Assert.That(ssl.PeerId.Length, Is.EqualTo(1), "1a"); // note: SSLSetPeerID (see Apple open source code) does not accept a null/zero-length value ssl.PeerId = new byte [0]; Assert.That((int)ssl.GetLastStatus(), Is.EqualTo(errSecParam), "set_PeerId/empty"); Assert.That(ssl.PeerId.Length, Is.EqualTo(1), "1b"); ssl.PeerId = new byte [] { 0x01, 0x02 }; Assert.That(ssl.PeerId.Length, Is.EqualTo(2), "2"); Assert.Null(ssl.PeerTrust, "PeerTrust"); Assert.That(ssl.SessionState, Is.EqualTo(SslSessionState.Idle), "SessionState"); Assert.That((int)ssl.SetDatagramHelloCookie(new byte [32]), Is.EqualTo(-50), "no cookie in stream"); // Assert.Null (ssl.GetDistinguishedNames<string> (), "GetDistinguishedNames"); } }
public void SslSupportedCiphers() { TestRuntime.AssertSystemVersion(PlatformName.MacOSX, 10, 8, throwIfOtherPlatform: false); int ssl_client_ciphers = -1; using (var client = new SslContext(SslProtocolSide.Client, SslConnectionType.Stream)) { // maximum downgrade client.MaxProtocol = client.MinProtocol; var ciphers = client.GetSupportedCiphers(); ssl_client_ciphers = ciphers.Count; Assert.That(ssl_client_ciphers, Is.AtLeast(1), "GetSupportedCiphers"); // we can't really scan for SSL_* since (some of) the values are identical to TLS_ // useful the other way around } int ssl_server_ciphers = -1; using (var server = new SslContext(SslProtocolSide.Server, SslConnectionType.Stream)) { // no downgrade, shows that the ciphers are not really restriced var ciphers = server.GetSupportedCiphers(); ssl_server_ciphers = ciphers.Count; Assert.That(ssl_server_ciphers, Is.AtLeast(1), "GetSupportedCiphers"); // we can't really scan for SSL_* since (some of) the values are identical to TLS_ // useful the other way around // make sure we have names for all ciphers - except old export ones (that we do not want to promote) // e.g. iOS 5.1 still supports them foreach (var cipher in ciphers) { string s = cipher.ToString(); if (s.Length < 8) { Console.WriteLine(s); } Assert.True(s.StartsWith("SSL_", StringComparison.Ordinal) || s.StartsWith("TLS_", StringComparison.Ordinal), s); } } Assert.That(ssl_client_ciphers, Is.EqualTo(ssl_server_ciphers), "same"); }
/// <summary></summary> public DtlsOverlord(RSACryptoServiceProvider private_key, CertificateHandler ch, PType ptype) : base(private_key, ch) { _osch = ch as OpenSslCertificateHandler; if (_osch == null) { throw new Exception("CertificateHandler is invalid type: " + ch.GetType()); } _it = new IdentifierTable(); _sas_helper = new IdentifierTableAsDtlsAssociation(_it); _rwl = new ReaderWriterLock(); _sender_to_sa = new Dictionary <ISender, DtlsAssociation>(); PType = ptype; _ptype_mb = ptype.ToMemBlock(); _ctx = new SslContext(SslMethod.DTLSv1_method); _ctx.SetCertificateStore(_osch.Store); _ctx.SetVerify(VerifyMode.SSL_VERIFY_PEER | VerifyMode.SSL_VERIFY_FAIL_IF_NO_PEER_CERT, RemoteCertificateValidation); _ctx.UsePrivateKey(AsymmetricKeyToOpenSslFormat(_private_key)); _ctx.UseCertificate(_osch.LocalCertificate); _ctx.CheckPrivateKey(); _ctx.Options = SslOptions.SSL_OP_SINGLE_DH_USE; var rng = new RNGCryptoServiceProvider(); byte[] sid = new byte[4]; rng.GetBytes(sid); _ctx.SetSessionIdContext(sid); _ctx.SetCookieGenerateCallback(GenerateCookie); _ctx.SetCookieVerifyCallback(VerifyCookie); _ctx.Options = SslOptions.SSL_OP_COOKIE_EXCHANGE; UpdateCookie(); }
internal static int Encrypt(IntPtr handlePtr, IntPtr buffer, int offset, int count, int bufferCapacity) { SslContext context = Marshal.PtrToStructure <SslContext>(handlePtr); var retVal = libssl.SSL_write(context.sslPtr, new IntPtr(buffer.ToInt64() + offset), count); if (retVal != count) { int error = GetSslError(context.sslPtr, retVal); if (libssl.SslErrorCode.SSL_ERROR_ZERO_RETURN == error) { return(0); // indicate end-of-file } throw CreateSslException("OpenSsl::Encrypt failed"); } int capacityNeeded = libssl.BIO_ctrl_pending(context.writeBioPtr); if (retVal == count) { if (capacityNeeded > bufferCapacity) { throw CreateSslException("OpenSsl::Encrypt capacity needed is more than buffer capacity. capacityNeeded = " + capacityNeeded + "," + "bufferCapacity = " + bufferCapacity); } IntPtr outBufferPtr = buffer; retVal = BioRead(context.writeBioPtr, outBufferPtr, capacityNeeded); if (retVal < 0) { throw CreateSslException("OpenSsl::Encrypt failed"); } } return(retVal); }
public void DatagramDefaults() { TestRuntime.AssertSystemVersion(ApplePlatform.MacOSX, 10, 8, throwIfOtherPlatform: false); #if __MACOS__ nint dsize = TestRuntime.CheckSystemVersion(ApplePlatform.MacOSX, 10, 10) ? 1327 : 1387; #else nint dsize = TestRuntime.CheckXcodeVersion(6, 0) ? 1327 : 1387; #endif using (var ssl = new SslContext(SslProtocolSide.Client, SslConnectionType.Datagram)) { Assert.That(ssl.BufferedReadSize, Is.EqualTo((nint)0), "BufferedReadSize"); Assert.Null(ssl.Connection, "Connection"); Assert.That(ssl.DatagramWriteSize, Is.EqualTo(dsize), "DatagramWriteSize"); Assert.That(ssl.Handle, Is.Not.EqualTo(IntPtr.Zero), "Handle"); Assert.That(ssl.MaxDatagramRecordSize, Is.EqualTo((nint)1400), "MaxDatagramRecordSize"); Assert.That(ssl.MaxProtocol, Is.EqualTo(SslProtocol.Dtls_1_0), "MaxProtocol"); Assert.That(ssl.MinProtocol, Is.EqualTo(SslProtocol.Dtls_1_0), "MinProtocol"); #if !NET Assert.That(ssl.NegotiatedCipher, Is.EqualTo(SslCipherSuite.SSL_NULL_WITH_NULL_NULL), "NegotiatedCipher"); #endif Assert.That(ssl.NegotiatedProtocol, Is.EqualTo(SslProtocol.Unknown), "NegotiatedProtocol"); Assert.Null(ssl.PeerId, "PeerId"); Assert.That(ssl.SessionState, Is.EqualTo(SslSessionState.Idle), "SessionState"); ssl.PeerId = new byte [] { 0xff }; Assert.That(ssl.PeerId.Length, Is.EqualTo(1), "1"); // note: SSLSetPeerID (see Apple open source code) does not accept a null/zero-length value ssl.PeerId = null; Assert.That((int)ssl.GetLastStatus(), Is.EqualTo(errSecParam), "set_PeerId/null"); Assert.That((int)ssl.SetDatagramHelloCookie(new byte [33]), Is.EqualTo(-50), "cookie to long"); Assert.That(ssl.SetDatagramHelloCookie(new byte [32]), Is.EqualTo(SslStatus.Success), "tasty cookie");; Assert.That(ssl.SetDatagramHelloCookie(new byte [1]), Is.EqualTo(SslStatus.Success), "fat free cookie"); Assert.That(ssl.SetDatagramHelloCookie(null), Is.EqualTo(SslStatus.Success), "no more cookies"); } }
public void StreamDefaults() { TestRuntime.AssertSystemVersion(PlatformName.MacOSX, 10, 8, throwIfOtherPlatform: false); using (var ssl = new SslContext(SslProtocolSide.Client, SslConnectionType.Stream)) { Assert.That(ssl.BufferedReadSize, Is.EqualTo((nint)0), "BufferedReadSize"); Assert.That(ssl.ClientCertificateState, Is.EqualTo(SslClientCertificateState.None), "ClientCertificateState"); Assert.Null(ssl.Connection, "Connection"); Assert.That(ssl.DatagramWriteSize, Is.EqualTo((nint)0), "DatagramWriteSize"); Assert.That(ssl.Handle, Is.Not.EqualTo(IntPtr.Zero), "Handle"); Assert.That(ssl.MaxDatagramRecordSize, Is.EqualTo((nint)0), "MaxDatagramRecordSize"); Assert.That(ssl.MaxProtocol, Is.EqualTo(SslProtocol.Tls_1_2), "MaxProtocol"); if (TestRuntime.CheckXcodeVersion(8, 0)) { Assert.That(ssl.MinProtocol, Is.EqualTo(SslProtocol.Tls_1_0), "MinProtocol"); } else { Assert.That(ssl.MinProtocol, Is.EqualTo(SslProtocol.Ssl_3_0), "MinProtocol"); } Assert.That(ssl.NegotiatedCipher, Is.EqualTo(SslCipherSuite.SSL_NULL_WITH_NULL_NULL), "NegotiatedCipher"); Assert.That(ssl.NegotiatedProtocol, Is.EqualTo(SslProtocol.Unknown), "NegotiatedProtocol"); Assert.That(ssl.PeerDomainName, Is.Empty, "PeerDomainName"); ssl.PeerDomainName = "google.ca"; Assert.That(ssl.PeerDomainName, Is.EqualTo("google.ca"), "PeerDomainName-2"); ssl.PeerDomainName = null; Assert.That(ssl.PeerDomainName, Is.Empty, "PeerDomainName"); Assert.Null(ssl.PeerId, "PeerId"); ssl.PeerId = new byte [] { 0xff }; Assert.That(ssl.PeerId.Length, Is.EqualTo(1), "1a"); // note: SSLSetPeerID (see Apple open source code) does not accept a null/zero-length value ssl.PeerId = new byte [0]; Assert.That((int)ssl.GetLastStatus(), Is.EqualTo(errSecParam), "set_PeerId/empty"); Assert.That(ssl.PeerId.Length, Is.EqualTo(1), "1b"); ssl.PeerId = new byte [] { 0x01, 0x02 }; Assert.That(ssl.PeerId.Length, Is.EqualTo(2), "2"); Assert.Null(ssl.PeerTrust, "PeerTrust"); Assert.That(ssl.SessionState, Is.EqualTo(SslSessionState.Idle), "SessionState"); Assert.That((int)ssl.SetDatagramHelloCookie(new byte [32]), Is.EqualTo(-50), "no cookie in stream"); // Assert.Null (ssl.GetDistinguishedNames<string> (), "GetDistinguishedNames"); if (TestRuntime.CheckXcodeVersion(9, 0)) { Assert.That(ssl.SetSessionTickets(false), Is.EqualTo(0), "SetSessionTickets"); Assert.That(ssl.SetError(SecStatusCode.Success), Is.EqualTo(0), "SetError"); Assert.Throws <ArgumentNullException> (() => ssl.SetOcspResponse(null), "SetOcspResponse/null"); using (var data = new NSData()) Assert.That(ssl.SetOcspResponse(data), Is.EqualTo(0), "SetOcspResponse/empty"); #if MONOMAC if (TestRuntime.CheckXcodeVersion(9, 3)) { #endif int error; var alpn = ssl.GetAlpnProtocols(out error); Assert.That(alpn, Is.Empty, "alpn"); Assert.That(error, Is.EqualTo((int)SecStatusCode.Param), "GetAlpnProtocols"); var protocols = new [] { "HTTP/1.1", "SPDY/1" } ; Assert.That(ssl.SetAlpnProtocols(protocols), Is.EqualTo(0), "SetAlpnProtocols"); #if MONOMAC } #endif } } }
public EchoWssClient(SslContext context, string address, int port) : base(context, address, port) { }
private void InitializeServerContext( X509Certificate serverCertificate, bool clientCertificateRequired, X509Chain caCerts, SslProtocols enabledSslProtocols, SslStrength sslStrength, bool checkCertificateRevocation) { if (serverCertificate == null) { throw new ArgumentNullException("serverCertificate", "Server certificate cannot be null"); } if (!serverCertificate.HasPrivateKey) { throw new ArgumentException("Server certificate must have a private key", "serverCertificate"); } // Initialize the context with specified TLS version sslContext = new SslContext(SslMethod.TLSv12_server_method, ConnectionEnd.Server, new[] { Protocols.Http2, Protocols.Http1 }); var options = sslContext.Options; // Remove support for protocols not specified in the enabledSslProtocols if (!EnumExtensions.HasFlag(enabledSslProtocols, SslProtocols.Ssl2)) { options |= SslOptions.SSL_OP_NO_SSLv2; } if (!EnumExtensions.HasFlag(enabledSslProtocols, SslProtocols.Ssl3)) { options |= SslOptions.SSL_OP_NO_SSLv3; } if (!EnumExtensions.HasFlag(enabledSslProtocols, SslProtocols.Tls)) { options |= SslOptions.SSL_OP_NO_TLSv1; } // Set the workaround options sslContext.Options = options | SslOptions.SSL_OP_ALL; // Set the context mode sslContext.Mode = SslMode.SSL_MODE_AUTO_RETRY; // Set the client certificate verification callback if we are requiring client certs if (clientCertificateRequired) { sslContext.SetVerify(VerifyMode.SSL_VERIFY_PEER | VerifyMode.SSL_VERIFY_FAIL_IF_NO_PEER_CERT, OnRemoteCertificate); } else { sslContext.SetVerify(VerifyMode.SSL_VERIFY_NONE, null); } // Set the client certificate max verification depth sslContext.SetVerifyDepth(10); // Set the certificate store and ca list if (caCerts != null) { // Don't take ownership of the X509Store IntPtr. When we // SetCertificateStore, the context takes ownership of the store pointer. sslContext.SetCertificateStore(new X509Store(caCerts, false)); var name_stack = new Core.Stack<X509Name>(); foreach (var cert in caCerts) { var subject = cert.Subject; name_stack.Add(subject); } // Assign the stack to the context sslContext.CAList = name_stack; } // Set the cipher string sslContext.SetCipherList(SslCipher.MakeString(enabledSslProtocols, sslStrength)); // Set the certificate sslContext.UseCertificate(serverCertificate); // Set the private key sslContext.UsePrivateKey(serverCertificate.PrivateKey); // Set the session id context sslContext.SetSessionIdContext(Encoding.ASCII.GetBytes(AppDomain.CurrentDomain.FriendlyName)); }
private ChannelHandler NettyServerHandler(Channel channel, SslContext sslContext) { SSLEngine sslEngine = sslContext.newEngine(channel.alloc()); return(new SslHandler(sslEngine)); }
internal virtual ChannelHandler NettyClientHandler(Channel channel, SslContext sslContext) { return(new ClientSideOnConnectSslHandler(channel, sslContext, _verifyHostname, _tlsVersions)); }
//TODO (Issue #3362) Set remote certificate options internal static IntPtr AllocateSslContext(long options, SafeX509Handle certHandle, SafeEvpPKeyHandle certKeyHandle, bool isServer, bool remoteCertRequired) { SslContext sslContext = new SslContext { isServer = isServer, }; try { IntPtr method = GetSslMethod(isServer, options); IntPtr contextPtr = libssl.SSL_CTX_new(method); if (IntPtr.Zero == contextPtr) { throw CreateSslException("Failed to allocate SSL/TLS context"); } libssl.SSL_CTX_ctrl(contextPtr, libssl.SSL_CTRL_OPTIONS, options, IntPtr.Zero); libssl.SSL_CTX_set_quiet_shutdown(contextPtr, 1); if (certHandle != null && certKeyHandle != null) { SetSslCertificate(contextPtr, certHandle, certKeyHandle); } sslContext.sslPtr = libssl.SSL_new(contextPtr); libssl.SSL_CTX_free(contextPtr); if (IntPtr.Zero == sslContext.sslPtr) { throw CreateSslException("Failed to create SSSL object from SSL context"); } IntPtr memMethod = libcrypto.BIO_s_mem(); if (IntPtr.Zero == memMethod) { throw CreateSslException("Failed to return memory BIO method function"); } sslContext.readBioPtr = libssl.BIO_new(memMethod); sslContext.writeBioPtr = libssl.BIO_new(memMethod); if ((IntPtr.Zero == sslContext.readBioPtr) || (IntPtr.Zero == sslContext.writeBioPtr)) { FreeBio(sslContext); throw CreateSslException("Failed to retun new BIO for a given method type"); } if (isServer) { libssl.SSL_set_accept_state(sslContext.sslPtr); } else { libssl.SSL_set_connect_state(sslContext.sslPtr); } libssl.SSL_set_bio(sslContext.sslPtr, sslContext.readBioPtr, sslContext.writeBioPtr); } catch { Disconnect(sslContext.sslPtr); throw; } IntPtr sslContextPtr = Marshal.AllocHGlobal(Marshal.SizeOf<SslContext>()); Marshal.StructureToPtr(sslContext, sslContextPtr, false); return sslContextPtr; }
static void Main(string[] args) { bool help = false; string address = "127.0.0.1"; int port = 2222; int threads = Environment.ProcessorCount; int clients = 100; int messages = 1000000; int size = 32; var options = new OptionSet() { { "h|?|help", v => help = v != null }, { "a|address=", v => address = v }, { "p|port=", v => port = int.Parse(v) }, { "t|threads=", v => threads = int.Parse(v) }, { "c|clients=", v => clients = int.Parse(v) }, { "m|messages=", v => messages = int.Parse(v) }, { "s|size=", v => size = int.Parse(v) } }; try { options.Parse(args); } catch (OptionException e) { Console.Write("Command line error: "); Console.WriteLine(e.Message); Console.WriteLine("Try `--help' to get usage information."); return; } if (help) { Console.WriteLine("Usage:"); options.WriteOptionDescriptions(Console.Out); return; } Console.WriteLine($"Server address: {address}"); Console.WriteLine($"Server port: {port}"); Console.WriteLine($"Working threads: {threads}"); Console.WriteLine($"Working clients: {clients}"); Console.WriteLine($"Messages to send: {messages}"); Console.WriteLine($"Message size: {size}"); // Prepare a message to send MessageToSend = new byte[size]; // Create a new service var service = new Service(threads); // Start the service Console.Write("Service starting..."); service.Start(); Console.WriteLine("Done!"); // Create and prepare a new SSL client context var context = new SslContext(SslMethod.TLSV12); context.SetVerifyMode(SslVerifyMode.VerifyPeer); context.LoadVerifyFile("ca.pem"); // Create echo clients var echoClients = new List <EchoClient>(); for (int i = 0; i < clients; ++i) { var client = new EchoClient(service, context, address, port, messages / clients); // client.SetupNoDelay(true); echoClients.Add(client); } TimestampStart = DateTime.UtcNow; // Connect clients Console.Write("Clients connecting..."); foreach (var client in echoClients) { client.ConnectAsync(); } Console.WriteLine("Done!"); foreach (var client in echoClients) { while (!client.Handshaked) { Thread.Yield(); } } Console.WriteLine("All clients connected!"); // Wait for processing all messages Console.Write("Processing..."); foreach (var client in echoClients) { while (client.IsConnected) { Thread.Sleep(100); } } Console.WriteLine("Done!"); // Stop the service Console.Write("Service stopping..."); service.Stop(); Console.WriteLine("Done!"); Console.WriteLine(); Console.WriteLine($"Errors: {TotalErrors}"); Console.WriteLine(); TotalMessages = TotalBytes / size; Console.WriteLine($"Round-trip time: {Service.GenerateTimePeriod((TimestampStop - TimestampStart).TotalMilliseconds)}"); Console.WriteLine($"Total data: {Service.GenerateDataSize(TotalBytes)}"); Console.WriteLine($"Total messages: {TotalMessages}"); Console.WriteLine($"Data throughput: {Service.GenerateDataSize((long)(TotalBytes / (TimestampStop - TimestampStart).TotalSeconds))}/s"); if (TotalMessages > 0) { Console.WriteLine($"Message latency: {Service.GenerateTimePeriod((TimestampStop - TimestampStart).TotalMilliseconds / TotalMessages)}"); Console.WriteLine($"Message throughput: {(long)(TotalMessages / (TimestampStop - TimestampStart).TotalSeconds)} msg/s"); } }
public EchoServer(SslContext context, IPAddress address, int port) : base(context, address, port) { }
public MulticastServer(Service service, SslContext context, int port, InternetProtocol protocol) : base(service, context, port, protocol) { }
static void Main(string[] args) { // WebSocket server port int port = 8443; if (args.Length > 0) { port = int.Parse(args[0]); } // WebSocket server content path string www = "../../../../../www/wss"; if (args.Length > 1) { www = args[1]; } Console.WriteLine($"WebSocket server port: {port}"); Console.WriteLine($"WebSocket server static content path: {www}"); Console.WriteLine($"WebSocket server website: https://localhost:{port}/chat/index.html"); Console.WriteLine(); // Create and prepare a new SSL server context var context = new SslContext(SslProtocols.Tls12, new X509Certificate2("server.pfx", "qwerty")); // Create a new WebSocket server var server = new ChatServer(context, IPAddress.Any, port); server.AddStaticContent(www, "/chat"); // Start the server Console.Write("Server starting..."); server.Start(); Console.WriteLine("Done!"); Console.WriteLine("Press Enter to stop the server or '!' to restart the server..."); // Perform text input for (;;) { string line = Console.ReadLine(); if (string.IsNullOrEmpty(line)) { break; } // Restart the server if (line == "!") { Console.Write("Server restarting..."); server.Restart(); Console.WriteLine("Done!"); } // Multicast admin message to all sessions line = "(admin) " + line; server.MulticastText(line); } // Stop the server Console.Write("Server stopping..."); server.Stop(); Console.WriteLine("Done!"); }
public MulticastClient(SslContext context, string address, int port) : base(context, address, port) { }
static void Main(string[] args) { bool help = false; int port = 2222; int messagesRate = 1000000; int messageSize = 32; var options = new OptionSet() { { "h|?|help", v => help = v != null }, { "p|port=", v => port = int.Parse(v) }, { "m|messages=", v => messagesRate = int.Parse(v) }, { "s|size=", v => messageSize = int.Parse(v) } }; try { options.Parse(args); } catch (OptionException e) { Console.Write("Command line error: "); Console.WriteLine(e.Message); Console.WriteLine("Try `--help' to get usage information."); return; } if (help) { Console.WriteLine("Usage:"); options.WriteOptionDescriptions(Console.Out); return; } Console.WriteLine($"Server port: {port}"); Console.WriteLine($"Messages rate: {messagesRate}"); Console.WriteLine($"Message size: {messageSize}"); // Create and prepare a new SSL server context var context = new SslContext(SslProtocols.Tls12, new X509Certificate2("server.pfx", "qwerty")); // Create a new echo server var server = new MulticastServer(context, IPAddress.Any, port); // server.OptionNoDelay = true; server.OptionReuseAddress = true; server.OptionReusePort = true; // Start the server Console.Write("Server starting..."); server.Start(); Console.WriteLine("Done!"); // Start the multicasting thread bool multicasting = true; var multicaster = Task.Factory.StartNew(() => { // Prepare message to multicast byte[] message = new byte[messageSize]; // Multicasting loop while (multicasting) { var start = DateTime.UtcNow; for (int i = 0; i < messagesRate; ++i) { server.Multicast(message); } var end = DateTime.UtcNow; // Sleep for remaining time or yield var milliseconds = (int)(end - start).TotalMilliseconds; if (milliseconds < 1000) { Thread.Sleep(milliseconds); } else { Thread.Yield(); } } }); Console.WriteLine("Press Enter to stop the server or '!' to restart the server..."); // Perform text input for (;;) { string line = Console.ReadLine(); if (line == string.Empty) { break; } // Restart the server if (line == "!") { Console.Write("Server restarting..."); server.Restart(); Console.WriteLine("Done!"); } } // Stop the multicasting thread multicasting = false; multicaster.Wait(); // Stop the server Console.Write("Server stopping..."); server.Stop(); Console.WriteLine("Done!"); }
public MulticastServer(SslContext context, IPAddress address, int port) : base(context, address, port) { }
static void Main(string[] args) { bool help = false; int port = 2222; int threads = Environment.ProcessorCount; var options = new OptionSet() { { "h|?|help", v => help = v != null }, { "p|port=", v => port = int.Parse(v) }, { "t|threads=", v => threads = int.Parse(v) } }; try { options.Parse(args); } catch (OptionException e) { Console.Write("Command line error: "); Console.WriteLine(e.Message); Console.WriteLine("Try `--help' to get usage information."); return; } if (help) { Console.WriteLine("Usage:"); options.WriteOptionDescriptions(Console.Out); return; } Console.WriteLine($"Server port: {port}"); Console.WriteLine($"Working threads: {threads}"); // Create a new service var service = new Service(threads); // Start the service Console.Write("Service starting..."); service.Start(); Console.WriteLine("Done!"); // Create and prepare a new SSL server context var context = new SslContext(SslMethod.TLSV12); context.SetPassword("qwerty"); context.UseCertificateChainFile("server.pem"); context.UsePrivateKeyFile("server.pem", SslFileFormat.PEM); context.UseTmpDHFile("dh4096.pem"); // Create a new echo server var server = new EchoServer(service, context, InternetProtocol.IPv4, port); // server.SetupNoDelay(true); server.SetupReuseAddress(true); server.SetupReusePort(true); // Start the server Console.Write("Server starting..."); server.Start(); Console.WriteLine("Done!"); Console.WriteLine("Press Enter to stop the server or '!' to restart the server..."); // Perform text input for (;;) { string line = Console.ReadLine(); if (line == string.Empty) { break; } // Restart the server if (line == "!") { Console.Write("Server restarting..."); server.Restart(); Console.WriteLine("Done!"); } } // Stop the server Console.Write("Server stopping..."); server.Stop(); Console.WriteLine("Done!"); // Stop the service Console.Write("Service stopping..."); service.Stop(); Console.WriteLine("Done!"); }
static void Main(string[] args) { // SSL server address string address = "127.0.0.1"; if (args.Length > 0) { address = args[0]; } // SSL server port int port = 2222; if (args.Length > 1) { port = int.Parse(args[1]); } Console.WriteLine($"SSL server address: {address}"); Console.WriteLine($"SSL server port: {port}"); // Create and prepare a new SSL client context var context = new SslContext(SslProtocols.Tls12, new X509Certificate2("ca.pem")); // Create a new SSL chat client var client = new ChatClient(context, address, port); // Connect the client Console.Write("Client connecting..."); client.Connect(); Console.WriteLine("Done!"); Console.WriteLine("Press Enter to stop the client or '!' to reconnect the client..."); // Perform text input for (;;) { string line = Console.ReadLine(); if (line == string.Empty) { break; } // Disconnect the client if (line == "!") { Console.Write("Client disconnecting..."); client.Disconnect(); Console.WriteLine("Done!"); continue; } // Send the entered text to the chat server client.Send(line); } // Disconnect the client Console.Write("Client disconnecting..."); client.DisconnectAndStop(); Console.WriteLine("Done!"); }
protected void InitializeClientContext( X509List certificates, SslProtocols enabledSslProtocols, SslStrength sslStrength, bool checkCertificateRevocation) { // Initialize the context with specified TLS version sslContext = new SslContext(SslMethod.TLSv12_client_method, ConnectionEnd.Client, new[] { Protocols.Http2, Protocols.Http1 }); var options = sslContext.Options; // Remove support for protocols not specified in the enabledSslProtocols if (!EnumExtensions.HasFlag(enabledSslProtocols, SslProtocols.Ssl2)) { options |= SslOptions.SSL_OP_NO_SSLv2; } if (!EnumExtensions.HasFlag(enabledSslProtocols, SslProtocols.Ssl3)) { options |= SslOptions.SSL_OP_NO_SSLv3; } if (!EnumExtensions.HasFlag(enabledSslProtocols, SslProtocols.Tls)) { options |= SslOptions.SSL_OP_NO_TLSv1; } sslContext.Options = options; // Set the Local certificate selection callback sslContext.SetClientCertCallback(OnClientCertificate); // Set the enabled cipher list sslContext.SetCipherList(SslCipher.MakeString(enabledSslProtocols, sslStrength)); // Set the callbacks for remote cert verification and local cert selection if (OnRemoteCertificate != null) { sslContext.SetVerify( VerifyMode.SSL_VERIFY_PEER | VerifyMode.SSL_VERIFY_FAIL_IF_NO_PEER_CERT, OnRemoteCertificate); } // Set the CA list into the store if (caCertificates != null) { var store = new X509Store(caCertificates); sslContext.SetCertificateStore(store); } // Set up the read/write bio's read_bio = BIO.MemoryBuffer(false); write_bio = BIO.MemoryBuffer(false); ssl = new Ssl(sslContext); sniCb = sniExt.ClientSniCb; sniExt.AttachSniExtensionClient(ssl.Handle, sslContext.Handle, sniCb); ssl.SetBIO(read_bio, write_bio); read_bio.SetClose(BIO.CloseOption.Close); write_bio.SetClose(BIO.CloseOption.Close); // Set the Ssl object into Client mode ssl.SetConnectState(); }
public HttpsCacheServer(SslContext context, IPAddress address, int port) : base(context, address, port) { }
private static void FreeBio(SslContext sslContext) { if (IntPtr.Zero != sslContext.readBioPtr) { Interop.libcrypto.BIO_free(sslContext.readBioPtr); } if (IntPtr.Zero != sslContext.writeBioPtr) { Interop.libcrypto.BIO_free(sslContext.writeBioPtr); } }
public EchoClient(SslContext context, string address, int port, int messages) : base(context, address, port) { _messages = messages; }
public ChatServer(Service service, SslContext context, InternetProtocol protocol, int port) : base(service, context, protocol, port) { }
static void Main(string[] args) { bool help = false; string address = "127.0.0.1"; int port = 2222; int clients = 100; int size = 32; int seconds = 10; var options = new OptionSet() { { "h|?|help", v => help = v != null }, { "a|address=", v => address = v }, { "p|port=", v => port = int.Parse(v) }, { "c|clients=", v => clients = int.Parse(v) }, { "s|size=", v => size = int.Parse(v) }, { "z|seconds=", v => seconds = int.Parse(v) } }; try { options.Parse(args); } catch (OptionException e) { Console.Write("Command line error: "); Console.WriteLine(e.Message); Console.WriteLine("Try `--help' to get usage information."); return; } if (help) { Console.WriteLine("Usage:"); options.WriteOptionDescriptions(Console.Out); return; } Console.WriteLine($"Server address: {address}"); Console.WriteLine($"Server port: {port}"); Console.WriteLine($"Working clients: {clients}"); Console.WriteLine($"Message size: {size}"); Console.WriteLine($"Seconds to benchmarking: {seconds}"); Console.WriteLine(); // Prepare a message to send MessageToSend = new byte[size]; // Create and prepare a new SSL client context var context = new SslContext(SslProtocols.Tls12, new X509Certificate2("client.pfx", "qwerty"), (sender, certificate, chain, sslPolicyErrors) => true); // Create multicast clients var multicastClients = new List <MulticastClient>(); for (int i = 0; i < clients; ++i) { var client = new MulticastClient(context, address, port); // client.OptionNoDelay = true; multicastClients.Add(client); } TimestampStart = DateTime.UtcNow; // Connect clients Console.Write("Clients connecting..."); foreach (var client in multicastClients) { client.ConnectAsync(); } Console.WriteLine("Done!"); foreach (var client in multicastClients) { while (!client.IsHandshaked) { Thread.Yield(); } } Console.WriteLine("All clients connected!"); // Wait for benchmarking Console.Write("Benchmarking..."); Thread.Sleep(seconds * 1000); Console.WriteLine("Done!"); // Disconnect clients Console.Write("Clients disconnecting..."); foreach (var client in multicastClients) { client.DisconnectAsync(); } Console.WriteLine("Done!"); foreach (var client in multicastClients) { while (client.IsConnected) { Thread.Yield(); } } Console.WriteLine("All clients disconnected!"); TimestampStop = DateTime.UtcNow; Console.WriteLine(); Console.WriteLine($"Errors: {TotalErrors}"); Console.WriteLine(); TotalMessages = TotalBytes / size; Console.WriteLine($"Total time: {Utilities.GenerateTimePeriod((TimestampStop - TimestampStart).TotalMilliseconds)}"); Console.WriteLine($"Total data: {Utilities.GenerateDataSize(TotalBytes)}"); Console.WriteLine($"Total messages: {TotalMessages}"); Console.WriteLine($"Data throughput: {Utilities.GenerateDataSize((long)(TotalBytes / (TimestampStop - TimestampStart).TotalSeconds))}/s"); if (TotalMessages > 0) { Console.WriteLine($"Message latency: {Utilities.GenerateTimePeriod((TimestampStop - TimestampStart).TotalMilliseconds / TotalMessages)}"); Console.WriteLine($"Message throughput: {(long)(TotalMessages / (TimestampStop - TimestampStart).TotalSeconds)} msg/s"); } }
static void Main(string[] args) { // SSL server port int port = 2222; if (args.Length > 0) { port = int.Parse(args[0]); } Console.WriteLine($"SSL server port: {port}"); // Create a new service var service = new Service(); // Start the service Console.Write("Service starting..."); service.Start(); Console.WriteLine("Done!"); // Create and prepare a new SSL server context var context = new SslContext(SslMethod.TLSV12); context.SetPassword("qwerty"); context.UseCertificateChainFile("server.pem"); context.UsePrivateKeyFile("server.pem", SslFileFormat.PEM); context.UseTmpDHFile("dh4096.pem"); // Create a new SSL chat server var server = new ChatServer(service, context, InternetProtocol.IPv4, port); // Start the server Console.Write("Server starting..."); server.Start(); Console.WriteLine("Done!"); Console.WriteLine("Press Enter to stop the server or '!' to restart the server..."); // Perform text input for (;;) { string line = Console.ReadLine(); if (line == string.Empty) { break; } // Restart the server if (line == "!") { Console.Write("Server restarting..."); server.Restart(); Console.WriteLine("Done!"); continue; } // Multicast admin message to all sessions line = "(admin) " + line; server.Multicast(line); } // Stop the server Console.Write("Server stopping..."); server.Stop(); Console.WriteLine("Done!"); // Stop the service Console.Write("Service stopping..."); service.Stop(); Console.WriteLine("Done!"); }
static void Main(string[] args) { bool help = false; int port = 2222; var options = new OptionSet() { { "h|?|help", v => help = v != null }, { "p|port=", v => port = int.Parse(v) } }; try { options.Parse(args); } catch (OptionException e) { Console.Write("Command line error: "); Console.WriteLine(e.Message); Console.WriteLine("Try `--help' to get usage information."); return; } if (help) { Console.WriteLine("Usage:"); options.WriteOptionDescriptions(Console.Out); return; } Console.WriteLine($"Server port: {port}"); Console.WriteLine(); // Create and prepare a new SSL server context var context = new SslContext(SslProtocols.Tls12, new X509Certificate2("server.pfx", "qwerty")); // Create a new echo server var server = new EchoServer(context, IPAddress.Any, port); // server.OptionNoDelay = true; server.OptionReuseAddress = true; server.OptionReusePort = true; // Start the server Console.Write("Server starting..."); server.Start(); Console.WriteLine("Done!"); Console.WriteLine("Press Enter to stop the server or '!' to restart the server..."); // Perform text input for (;;) { string line = Console.ReadLine(); if (line == string.Empty) { break; } // Restart the server if (line == "!") { Console.Write("Server restarting..."); server.Restart(); Console.WriteLine("Done!"); } } // Stop the server Console.Write("Server stopping..."); server.Stop(); Console.WriteLine("Done!"); }
public NATP_SSL_Server(SslContext context, IPAddress address, int port) : base(context, address, port) { }
static void Main(string[] args) { bool help = false; int port = 2222; int threads = Environment.ProcessorCount; int messagesRate = 1000000; int messageSize = 32; var options = new OptionSet() { { "h|?|help", v => help = v != null }, { "p|port=", v => port = int.Parse(v) }, { "t|threads=", v => threads = int.Parse(v) }, { "m|messages=", v => messagesRate = int.Parse(v) }, { "s|size=", v => messageSize = int.Parse(v) } }; try { options.Parse(args); } catch (OptionException e) { Console.Write("Command line error: "); Console.WriteLine(e.Message); Console.WriteLine("Try `--help' to get usage information."); return; } if (help) { Console.WriteLine("Usage:"); options.WriteOptionDescriptions(Console.Out); return; } Console.WriteLine($"Server port: {port}"); Console.WriteLine($"Working threads: {threads}"); Console.WriteLine($"Messages rate: {messagesRate}"); Console.WriteLine($"Message size: {messageSize}"); Console.WriteLine(); // Create a new service var service = new Service(threads); // Start the service Console.Write("Service starting..."); service.Start(); Console.WriteLine("Done!"); // Create and prepare a new SSL server context var context = new SslContext(SslMethod.TLSV12); context.SetPassword("qwerty"); context.UseCertificateChainFile("server.pem"); context.UsePrivateKeyFile("server.pem", SslFileFormat.PEM); context.UseTmpDHFile("dh4096.pem"); // Create a new echo server var server = new MulticastServer(service, context, port, InternetProtocol.IPv4); // server.SetupNoDelay(true); server.SetupReuseAddress(true); server.SetupReusePort(true); // Start the server Console.Write("Server starting..."); server.Start(); Console.WriteLine("Done!"); // Start the multicasting thread bool multicasting = true; var multicaster = Task.Factory.StartNew(() => { // Prepare message to multicast byte[] message = new byte[messageSize]; // Multicasting loop while (multicasting) { var start = DateTime.UtcNow; for (int i = 0; i < messagesRate; ++i) { server.Multicast(message); } var end = DateTime.UtcNow; // Sleep for remaining time or yield var milliseconds = (int)(end - start).TotalMilliseconds; if (milliseconds < 1000) { Thread.Sleep(1000 - milliseconds); } else { Thread.Yield(); } } }); Console.WriteLine("Press Enter to stop the server or '!' to restart the server..."); // Perform text input for (;;) { string line = Console.ReadLine(); if (line == string.Empty) { break; } // Restart the server if (line == "!") { Console.Write("Server restarting..."); server.Restart(); Console.WriteLine("Done!"); } } // Stop the multicasting thread multicasting = false; multicaster.Wait(); // Stop the server Console.Write("Server stopping..."); server.Stop(); Console.WriteLine("Done!"); // Stop the service Console.Write("Service stopping..."); service.Stop(); Console.WriteLine("Done!"); }
public EchoClient(Service service, SslContext context, string address, int port, int messages) : base(service, context, address, port) { _messagesOutput = messages; _messagesInput = messages; }