public SecureConnection(TcpClient client, SslStream stream, MessageExchangeProtocol protocol) { this.client = client; this.stream = stream; this.protocol = protocol; lastUsed = DateTimeOffset.UtcNow; }
void ExchangeMessages(TcpClient client, SslStream stream) { if (stream.RemoteCertificate == null) { log.Write(EventType.ClientDenied, "A client at {0} connected, and attempted a message exchange, but did not present a client certificate", client.Client.RemoteEndPoint); stream.Close(); client.Close(); return; } var thumbprint = new X509Certificate2(stream.RemoteCertificate).Thumbprint; var verified = verifyClientThumbprint(thumbprint); if (!verified) { log.Write(EventType.ClientDenied, "A client at {0} connected, and attempted a message exchange, but it presented a client certificate with the thumbprint '{1}' which is not in the list of thumbprints that we trust", client.Client.RemoteEndPoint, thumbprint); stream.Close(); client.Close(); return; } log.Write(EventType.Security, "Client authenticated as {0}", thumbprint); var protocol = new MessageExchangeProtocol(stream, log); protocolHandler(protocol); }
SecureConnection EstablishNewConnection() { log.Write(EventType.OpeningNewConnection, "Opening a new connection"); var remoteUri = serviceEndpoint.BaseUri; var certificateValidator = new ClientCertificateValidator(serviceEndpoint.RemoteThumbprint); var client = CreateTcpClient(); client.ConnectWithTimeout(remoteUri, HalibutLimits.TcpClientConnectTimeout); log.Write(EventType.Diagnostic, "Connection established"); var stream = client.GetStream(); log.Write(EventType.Security, "Performing TLS handshake"); var ssl = new SslStream(stream, false, certificateValidator.Validate, UserCertificateSelectionCallback); ssl.AuthenticateAsClient(remoteUri.Host, new X509Certificate2Collection(clientCertificate), SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, false); ssl.Write(MxLine, 0, MxLine.Length); ssl.Flush(); log.Write(EventType.Security, "Secure connection established. Server at {0} identified by thumbprint: {1}, using protocol {2}", client.Client.RemoteEndPoint, serviceEndpoint.RemoteThumbprint, ssl.SslProtocol.ToString()); var protocol = new MessageExchangeProtocol(ssl, log); return new SecureConnection(client, ssl, protocol); }