protected override void CreateFrondEndConnection(Socket socket) { X509Certificate2 serverCertificate = new X509Certificate2(_certificateFile); SslServerStream secureStream = new SslServerStream( new NetworkStream(socket, true), serverCertificate, true, true, SecurityProtocolType.Tls); secureStream.CheckCertRevocationStatus = true; secureStream.PrivateKeyCertSelectionDelegate += delegate(X509Certificate cert, string targetHost) { X509Certificate2 cert2 = serverCertificate as X509Certificate2 ?? new X509Certificate2(serverCertificate); return(cert2 != null ? cert2.PrivateKey : null); }; SslConnection connection = null; try { secureStream.ClientCertValidationDelegate += ValidateRemoteCertificate; secureStream.Read(new byte [0], 0, 0); connection = new SslConnection(socket, secureStream); } catch (Exception e) { _logger.FatalFormat("Error negotiating ssl connection: {0}", e); return; } RaiseClientConnectedEvent(connection); }
public void Test_Authenticate(bool isAuthenticated, bool isEncrypted, bool isSigned) { var endpoint = IPEndPointExtensions.GetEndPoint(TestConfiguration.Settings.Hostname, 11207); var bootstrapUri = new Uri($@"https://{endpoint.Address}:8091/pools"); var socket = new Socket(SocketType.Stream, ProtocolType.Tcp); socket.Connect(endpoint); var poolConfig = new PoolConfiguration { UseSsl = true, Uri = bootstrapUri, ClientConfiguration = new ClientConfiguration() }; var sslStream = new Mock <SslStream>(new MemoryStream(), true, new RemoteCertificateValidationCallback(ServerCertificateValidationCallback)); sslStream.Setup(x => x.IsAuthenticated).Returns(isAuthenticated); sslStream.Setup(x => x.IsEncrypted).Returns(isEncrypted); sslStream.Setup(x => x.IsSigned).Returns(isSigned); var connPool = new Mock <IConnectionPool <IConnection> >(); connPool.Setup(x => x.Configuration).Returns(poolConfig); var conn = new SslConnection(connPool.Object, socket, sslStream.Object, new DefaultConverter(), new BufferAllocator(1024, 1024)); if (isAuthenticated && isEncrypted && isSigned) { Assert.DoesNotThrow(conn.Authenticate); } else { Assert.Throws <AuthenticationException>(conn.Authenticate); } }
public override void Authenticate(RequestContext <AuthenticateRequest, AuthenticateResponse> requestContext) { SslConnection connection = _context.Connection as SslConnection; X509Certificate cert = connection.ClientCertificate; string certHashString = cert.GetCertHashString(); foreach (User user in ServerContext.AccessControlList.Users) { SslAuthenticationParameters auth = (SslAuthenticationParameters)user.GetAuthentication("ssl_auth"); if (auth != null && auth.CertificateHash.Equals(certHashString)) { ServerContext.ServerAuthenticationContext.AuthenticatedPermissionMember = user; AuthenticateResponse response = requestContext.CreateResponse(); response.Succeeded = true; response.Execute(); return; } } _log.WarnFormat("Could not find user associated with certificate '{0}'", certHashString); AuthenticateResponse errorResponse = requestContext.CreateResponse(); errorResponse.Succeeded = false; errorResponse.CustomErrorMessage = "No client associated with specified certificate!"; errorResponse.Execute(); }
private async Task <bool> ConnectToServer(X509Certificate[] clientCertificates, X509Certificate[] serverCertificates, int port, TimeSpan timeout, CancellationToken cancellationToken) { using (var client = new TcpClient()) { await client.ConnectAsync(IPAddress.Loopback, port); var configuration = new SslConnection.Configuration() { ClientCertificates = clientCertificates, ServerCertificates = serverCertificates, }; var clientPolicy = new SslConnection(0, configuration); try { using (Stream clientStream = await clientPolicy.AuthenticateAsClient("localhost", client, timeout, cancellationToken)) { Trace.TraceInformation("AuthenticateAsClient succeeded"); var message = new byte[1]; await clientStream.WriteAsync(message, 0, 1); return(true); } } catch (AuthenticationException ex) { Trace.TraceError($"AuthenticateAsClient failed. exception={ex}"); return(false); } } }
public async Task When_Packet_Exceeds_MaxDocSize_ThrowValueTooLargeException() { var conn = new SslConnection(new SslStream(new MemoryStream()), new IPEndPoint(0, 0), new IPEndPoint(0, 0), new Logger <SslConnection>(new LoggerFactory()), new Logger <MultiplexingConnection>(new LoggerFactory())); var json = JsonConvert.SerializeObject(new string[1024 * 6145]); var bytes = Encoding.UTF8.GetBytes(json); await Assert.ThrowsAsync <ValueToolargeException>(() => conn.SendAsync(bytes, Mock.Of <IOperation>()).AsTask()).ConfigureAwait(false); }
/// <summary> /// Validates the certificate of the remote host /// </summary> public bool ValidateRemoteCertificate(X509Certificate certificate, int[] certificateErrors) { if (certificateErrors.Length == 0) { return(true); } foreach (int certErr in certificateErrors) { _logger.Fatal(SslConnection.CertificateErrorCodeToMessage(certErr)); } return(false); }
static ConnectionExtensions() { //TODO .NET5 GC.AllocateUninitializedArray _Provider = Provider<Memory<byte>>.CreateFromProcessor(() => new UnmanagedMemory<byte>(8192).Memory, 1024);//reset? _UseSsl = (client, options) => new SslClient(client, options); _UseSslAsync = async (connection, options) => { var ssl = new SslConnection(connection); try { await ssl.AuthenticateAsync(options); } catch { ssl.Close(); throw; } return ssl; }; }
public void When_Custom_KvServerCertificateValidationCallback_Provided_It_Is_Used(SslPolicyErrors sslPolicyErrors, bool success) { var config = new ClientConfiguration { KvServerCertificateValidationCallback = OnCertificateValidation }; var mockConnection = new Mock <IConnection>(); mockConnection.Setup(x => x.IsConnected).Returns(false); var mockConnectionPool = new Mock <IConnectionPool>(); mockConnectionPool.Setup(x => x.Acquire()).Returns(mockConnection.Object); mockConnectionPool.SetupGet(x => x.Configuration).Returns(config.PoolConfiguration); Socket socket = null; try { socket = new Socket(SocketType.Stream, ProtocolType.Tcp); socket.Connect(IPAddress.Parse(TestConfiguration.Settings.Hostname), 11207); var conn = new SslConnection(mockConnectionPool.Object, socket, new DefaultConverter(), new BufferAllocator(0, 0)); var sslStream = typeof(SslConnection) .GetField("_sslStream", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(conn); var remoteCertificateValidationCallback = (RemoteCertificateValidationCallback)typeof(SslStream) .GetField("_userCertificateValidationCallback", BindingFlags.Instance | BindingFlags.NonPublic) .GetValue(sslStream); Assert.AreEqual(success, remoteCertificateValidationCallback(null, null, null, sslPolicyErrors)); } finally { socket?.Dispose(); } }
private async Task <bool> AcceptClient(X509Certificate[] clientCertificates, X509Certificate[] serverCertificates, int port, TimeSpan timeout, CancellationToken cancellationToken) { TcpListener listener = new TcpListener(IPAddress.Loopback, port); listener.Start(); var configuration = new SslConnection.Configuration() { ClientCertificates = clientCertificates, ServerCertificates = serverCertificates, }; var serverPolicy = new SslConnection(0, configuration); try { using (TcpClient connection = await listener.AcceptTcpClientAsync()) using (Stream stream = await serverPolicy.AuthenticateAsServer(connection, timeout, cancellationToken)) { var message = new byte[1]; await stream.ReadAsync(message, 0, message.Length); Trace.TraceInformation("AuthenticateAsServer succeeded"); return(true); } } catch (AuthenticationException ex) { Trace.TraceError($"AuthenticateAsServer failed. exception={ex}"); return(false); } finally { listener.Stop(); } }
private void OnClientAccepted(IAsyncResult ar) { var listener = (TcpListener)ar.AsyncState; Socket socket = null; TcpSession session = null; SslConnection sslConnection = null; try { socket = listener.EndAcceptSocket(ar); if (SecureServer) { sslConnection = new SslConnection { Socket = socket, }; sslConnection.SslStream = new SslStream( new NetworkStream(socket, true), false, CertificateValidationCallback); sslConnection.SslStream.BeginAuthenticateAsServer( ServerCertificate, ClientCertificateReqired, SslProtocols.Tls, true, OnClientAutenticated, sslConnection); } else { session = new TcpSession(socket, new NetworkStream(socket, true)); try { if (OnClientConnected != null) { OnClientConnected(session); } } catch (Exception e) { Console.WriteLine(e); // ignored } session.Start(); } } catch (Exception e) { try { if (OnError != null) { OnError(e); } } catch (Exception) { // ignored } if (session != null) { session.Close(); } else if (sslConnection != null) { if (sslConnection.SslStream != null) { sslConnection.SslStream.Close(); } else { sslConnection.Socket.Close(); } } else if (socket != null) { socket.Close(); } } listener.BeginAcceptTcpClient(OnClientAccepted, listener); }