X509Certificate SelectClientCertificate( object sender, string targetHost, X509List localCerts, X509Certificate remoteCert, string[] acceptableIssuers) { Console.WriteLine("SelectClientCertificate> {0}", targetHost); foreach (var issuer in acceptableIssuers) { Console.WriteLine("SelectClientCertificate> issuer: {0}", issuer); using (var name = new X509Name(issuer)) { foreach (var cert in localCerts) { Console.WriteLine("SelectClientCertificate> local: {0}", cert.Subject); if (cert.Issuer.CompareTo(name) == 0) { return(cert); } cert.Dispose(); } } } return(null); }
/// <summary> /// /// </summary> /// <param name="targetHost"></param> /// <param name="clientCertificates"></param> /// <param name="caCertificates"></param> /// <param name="enabledSslProtocols"></param> /// <param name="sslStrength"></param> /// <param name="checkCertificateRevocation"></param> /// <param name="asyncCallback"></param> /// <param name="asyncState"></param> /// <returns></returns> public virtual IAsyncResult BeginAuthenticateAsClient( string targetHost, X509List clientCertificates, X509Chain caCertificates, SslProtocols enabledSslProtocols, SslStrength sslStrength, bool checkCertificateRevocation, AsyncCallback asyncCallback, Object asyncState) { if (IsAuthenticated) { throw new InvalidOperationException("SslStream is already authenticated"); } End = ConnectionEnd.Client; // Create the stream var client_stream = new SslStreamClient(InnerStream, false, targetHost, clientCertificates, caCertificates, enabledSslProtocols, sslStrength, checkCertificateRevocation, remoteCertificateValidationCallback, localCertificateSelectionCallback); // set the internal stream sslStream = client_stream; // start the write operation return(BeginWrite(new byte[0], 0, 0, asyncCallback, asyncState)); }
/// <summary> /// /// </summary> /// <param name="targetHost"></param> /// <param name="certificates"></param> /// <param name="caCertificates"></param> /// <param name="enabledSslProtocols"></param> /// <param name="sslStrength"></param> /// <param name="checkCertificateRevocation"></param> public virtual void AuthenticateAsClient( string targetHost, X509List certificates, X509Chain caCertificates, SslProtocols enabledSslProtocols, SslStrength sslStrength, bool checkCertificateRevocation) { EndAuthenticateAsClient(BeginAuthenticateAsClient(targetHost, certificates, caCertificates, enabledSslProtocols, sslStrength, checkCertificateRevocation, null, null)); }
//Bridge delegate to handle local certificate selection: private X509Certificate SelectionCallback( object sender, string targetHost, X509List localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers ) { return(localCertificates.Count > 0 ? localCertificates[0] : null); }
protected void InitializeClientContext(X509List certificates, SslProtocols enabledSslProtocols, SslStrength sslStrength, bool checkCertificateRevocation) { // Initialize the context with the specified SSL version // Initialize the context sslContext = new SslContext(SslMethod.SSLv23_client_method); // Remove support for protocols not specified in the enabledSslProtocols if ((enabledSslProtocols & SslProtocols.Ssl2) != SslProtocols.Ssl2) { sslContext.Options |= SslOptions.SSL_OP_NO_SSLv2; } if ((enabledSslProtocols & SslProtocols.Ssl3) != SslProtocols.Ssl3 && ((enabledSslProtocols & SslProtocols.Default) != SslProtocols.Default)) { // no SSLv3 support sslContext.Options |= SslOptions.SSL_OP_NO_SSLv3; } if ((enabledSslProtocols & SslProtocols.Tls) != SslProtocols.Tls && (enabledSslProtocols & SslProtocols.Default) != SslProtocols.Default) { sslContext.Options |= SslOptions.SSL_OP_NO_TLSv1; } // Set the Local certificate selection callback sslContext.SetClientCertCallback(internalCertificateSelectionCallback); // Set the enabled cipher list sslContext.SetCipherList(GetCipherString(false, enabledSslProtocols, sslStrength)); // Set the callbacks for remote cert verification and local cert selection if (remoteCertificateSelectionCallback != null) { sslContext.SetVerify(VerifyMode.SSL_VERIFY_PEER | VerifyMode.SSL_VERIFY_FAIL_IF_NO_PEER_CERT, remoteCertificateSelectionCallback); } // 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); 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(); }
protected void InitializeClientContext(X509List certificates, SslProtocols enabledSslProtocols, SslStrength sslStrength, bool checkCertificateRevocation) { // Initialize the context with the specified ssl version // Initialize the context sslContext = new SslContext(SslMethod.SSLv23_client_method); // Remove support for protocols not specified in the enabledSslProtocols if ((enabledSslProtocols & SslProtocols.Ssl2) != SslProtocols.Ssl2) { sslContext.Options |= SslOptions.SSL_OP_NO_SSLv2; } if ((enabledSslProtocols & SslProtocols.Ssl3) != SslProtocols.Ssl3 && ((enabledSslProtocols & SslProtocols.Default) != SslProtocols.Default)) { // no SSLv3 support sslContext.Options |= SslOptions.SSL_OP_NO_SSLv3; } if ((enabledSslProtocols & SslProtocols.Tls) != SslProtocols.Tls && (enabledSslProtocols & SslProtocols.Default) != SslProtocols.Default) { sslContext.Options |= SslOptions.SSL_OP_NO_TLSv1; } // Set the Local certificate selection callback sslContext.SetClientCertCallback(this.internalCertificateSelectionCallback); // Set the enabled cipher list sslContext.SetCipherList(GetCipherString(false, enabledSslProtocols, sslStrength)); // Set the callbacks for remote cert verification and local cert selection if (remoteCertificateSelectionCallback != null) { sslContext.SetVerify(VerifyMode.SSL_VERIFY_PEER | VerifyMode.SSL_VERIFY_FAIL_IF_NO_PEER_CERT, remoteCertificateSelectionCallback); } // Set the CA list into the store if (caCertificates != null) { X509Store 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); 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 void TestCase() { string serverCertPath = @"/certs/server.pfx"; string serverPrivateKeyPassword = "******"; string caFilePath = "/certs/ca_chain.pem"; string clientCertPath = "/certs/client.pfx"; string clientPrivateKeyPassword = "******"; string projDir = Directory.GetParent(Directory.GetParent(AppDomain.CurrentDomain.BaseDirectory).FullName).FullName; // Initialize OpenSSL for multithreaded use ThreadInitialization.InitializeThreads(); try { // Intitialize server certificates serverCAChain = LoadCACertificateChain(projDir + caFilePath); serverCertificate = LoadPKCS12Certificate(projDir + serverCertPath, serverPrivateKeyPassword); // Kick the server thread Thread serverThread = new Thread(new ThreadStart(ServerTestThreadProc)); serverThread.Start(); // Intialize the client certificates clientCAChain = LoadCACertificateChain(projDir + caFilePath); X509Certificate clientCert = LoadPKCS12Certificate(projDir + clientCertPath, clientPrivateKeyPassword); // Add the cert to the client certificate list clientCertificateList = new X509List(); clientCertificateList.Add(clientCert); // Kick the client thread Thread clientThread = new Thread(new ThreadStart(ClientTestThreadProc)); clientThread.Start(); // Wait for the threads to exit serverThread.Join(); clientThread.Join(); // Cleanup serverCertificate.Dispose(); serverCAChain.Dispose(); clientCAChain.Dispose(); clientCert.Dispose(); } catch (Exception ex) { Console.WriteLine("Server test failed with exception: {0}", ex.Message); } ThreadInitialization.UninitializeThreads(); }
public void Execute(string[] args) { string serverCertPath = @"../../test/certs/server.pfx"; string serverPrivateKeyPassword = "******"; string caFilePath = "../../test/certs/ca_chain.pem"; string clientCertPath = "../../test/certs/client.pfx"; string clientPrivateKeyPassword = "******"; // Initialize OpenSSL for multithreaded use ThreadInitialization.InitializeThreads(); try { // Intitialize server certificates serverCAChain = LoadCACertificateChain(caFilePath); serverCertificate = LoadPKCS12Certificate(serverCertPath, serverPrivateKeyPassword); // Kick the server thread Thread serverThread = new Thread(new ThreadStart(ServerTestThreadProc)); serverThread.Start(); // Intialize the client certificates clientCAChain = LoadCACertificateChain(caFilePath); X509Certificate clientCert = LoadPKCS12Certificate(clientCertPath, clientPrivateKeyPassword); // Add the cert to the client certificate list clientCertificateList = new X509List(); clientCertificateList.Add(clientCert); // Kick the client thread Thread clientThread = new Thread(new ThreadStart(ClientTestThreadProc)); clientThread.Start(); // Wait for the threads to exit serverThread.Join(); clientThread.Join(); // Cleanup serverCertificate.Dispose(); serverCAChain.Dispose(); clientCAChain.Dispose(); clientCert.Dispose(); } catch (Exception ex) { Console.WriteLine("Server test failed with exception: {0}", ex.Message); } ThreadInitialization.UninitializeThreads(); }
public MoagentClient(string host, int port, bool useSsl) { _server = host; _port = port; _useSsl = useSsl; _client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); if (_useSsl) { var certBio = BIO.File(@".\agentClientCert.p12", "r"); X509Certificate clientCert = X509Certificate.FromPKCS12(certBio, string.Empty); var serverBio = BIO.File(@".\ProactiveContactCA.cer", "r"); X509Certificate serverCert = X509Certificate.FromDER(serverBio); _xList = new X509List {clientCert}; _xChain = new X509Chain {serverCert}; } }
public SslStreamClient(Stream stream, bool ownStream, string targetHost, X509List clientCertificates, X509Chain caCertificates, SslProtocols enabledSslProtocols, SslStrength sslStrength, bool checkCertificateRevocationStatus, RemoteCertificateValidationHandler remoteCallback, LocalCertificateSelectionHandler localCallback) : base(stream, ownStream) { this.targetHost = targetHost; this.clientCertificates = clientCertificates; this.caCertificates = caCertificates; this.checkCertificateRevocationStatus = checkCertificateRevocationStatus; this.remoteCertificateSelectionCallback = remoteCallback; this.localCertificateSelectionCallback = localCallback; this.internalCertificateSelectionCallback = new ClientCertCallbackHandler(InternalClientCertificateSelectionCallback); InitializeClientContext(clientCertificates, enabledSslProtocols, sslStrength, checkCertificateRevocationStatus); }
protected X509Certificate clientCertificateSelectionCallback(object sender, string targetHost, X509List localCerts, X509Certificate remoteCert, string[] acceptableIssuers) { X509Certificate retCert = null; // check target host? for (int i = 0; i < acceptableIssuers.GetLength(0); i++) { X509Name name = new X509Name(acceptableIssuers[i]); foreach (X509Certificate cert in localCerts) { if (cert.Issuer.CompareTo(name) == 0) { retCert = cert; break; } cert.Dispose(); } name.Dispose(); } return(retCert); }
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(); }
X509Certificate SelectClientCertificate( object sender, string targetHost, X509List localCerts, X509Certificate remoteCert, string[] acceptableIssuers) { Console.WriteLine("SelectClientCertificate> {0}", targetHost); foreach (var issuer in acceptableIssuers) { Console.WriteLine("SelectClientCertificate> issuer: {0}", issuer); using (var name = new X509Name(issuer)) { foreach (var cert in localCerts) { Console.WriteLine("SelectClientCertificate> local: {0}", cert.Subject); if (cert.Issuer.CompareTo(name) == 0) { return cert; } cert.Dispose(); } } } return null; }
protected X509Certificate clientCertificateSelectionCallback(object sender, string targetHost, X509List localCerts, X509Certificate remoteCert, string[] acceptableIssuers) { X509Certificate retCert = null; // check target host? for (int i = 0; i < acceptableIssuers.GetLength(0); i++) { X509Name name = new X509Name(acceptableIssuers[i]); foreach (X509Certificate cert in localCerts) { if (cert.Issuer.CompareTo(name) == 0) { retCert = cert; break; } cert.Dispose(); } name.Dispose(); } return retCert; }
public void TestCase() { string serverCertPath = @"../../test/certs/server.pfx"; string serverPrivateKeyPassword = "******"; string caFilePath = "../../test/certs/ca_chain.pem"; string clientCertPath = "../../test/certs/client.pfx"; string clientPrivateKeyPassword = "******"; // Initialize OpenSSL for multithreaded use ThreadInitialization.InitializeThreads(); try { // Intitialize server certificates serverCAChain = LoadCACertificateChain(caFilePath); serverCertificate = LoadPKCS12Certificate(serverCertPath, serverPrivateKeyPassword); // Kick the server thread Thread serverThread = new Thread(new ThreadStart(ServerTestThreadProc)); serverThread.Start(); // Intialize the client certificates clientCAChain = LoadCACertificateChain(caFilePath); X509Certificate clientCert = LoadPKCS12Certificate(clientCertPath, clientPrivateKeyPassword); // Add the cert to the client certificate list clientCertificateList = new X509List(); clientCertificateList.Add(clientCert); // Kick the client thread Thread clientThread = new Thread(new ThreadStart(ClientTestThreadProc)); clientThread.Start(); // Wait for the threads to exit serverThread.Join(); clientThread.Join(); // Cleanup serverCertificate.Dispose(); serverCAChain.Dispose(); clientCAChain.Dispose(); clientCert.Dispose(); } catch (Exception ex) { Console.WriteLine("Server test failed with exception: {0}", ex.Message); } ThreadInitialization.UninitializeThreads(); }
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; } _isSecure = port == securePort; var tcpClnt = new TcpClient(connectUri.Host, port); _clientStream = tcpClnt.GetStream(); if (_useHandshake) { if (_isSecure) { _clientStream = new SslStream(_clientStream, false); _certificate = LoadPKCS12Certificate(AssemblyName + CertificatePath, String.Empty); _chain = new X509Chain {_certificate}; var certList = new X509List { _certificate }; (_clientStream as SslStream).AuthenticateAsClient(connectUri.AbsoluteUri, certList, _chain, SslProtocols.Tls, SslStrength.All, false); _selectedProtocol = (_clientStream as SslStream).AlpnSelectedProtocol; } if (!_isSecure || _selectedProtocol == Protocols.Http1) { MakeHandshakeEnvironment(); 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"); Protocol = _isSecure ? SslProtocols.Tls : SslProtocols.None; if (_useHttp20) { _sessionAdapter = new Http2ClientMessageHandler(_clientStream, ConnectionEnd.Client, _isSecure, 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; }
/// <summary> /// /// </summary> /// <param name="targetHost"></param> /// <param name="certificates"></param> /// <param name="caCertificates"></param> /// <param name="enabledSslProtocols"></param> /// <param name="sslStrength"></param> /// <param name="checkCertificateRevocation"></param> public virtual void AuthenticateAsClient( string targetHost, X509List certificates, X509Chain caCertificates, SslProtocols enabledSslProtocols, SslStrength sslStrength, bool checkCertificateRevocation) { EndAuthenticateAsClient(BeginAuthenticateAsClient( targetHost, certificates, caCertificates, enabledSslProtocols, sslStrength, checkCertificateRevocation, null, null)); }
/// <summary> /// /// </summary> /// <param name="targetHost"></param> /// <param name="clientCertificates"></param> /// <param name="caCertificates"></param> /// <param name="enabledSslProtocols"></param> /// <param name="sslStrength"></param> /// <param name="checkCertificateRevocation"></param> /// <param name="asyncCallback"></param> /// <param name="asyncState"></param> /// <returns></returns> public virtual IAsyncResult BeginAuthenticateAsClient( string targetHost, X509List clientCertificates, X509Chain caCertificates, SslProtocols enabledSslProtocols, SslStrength sslStrength, bool checkCertificateRevocation, AsyncCallback asyncCallback, Object asyncState) { if (IsAuthenticated) { throw new InvalidOperationException("SslStream is already authenticated"); } End = ConnectionEnd.Client; // Create the stream var client_stream = new SslStreamClient( InnerStream, targetHost, clientCertificates, caCertificates, enabledSslProtocols, sslStrength, checkCertificateRevocation, remoteCertificateValidationCallback, localCertificateSelectionCallback); // set the internal stream sslStream = client_stream; // start the write operation return BeginWrite(new byte[0], 0, 0, asyncCallback, asyncState); }
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); } _isSecure = port == securePort; var tcpClnt = new TcpClient(connectUri.Host, port); _clientStream = tcpClnt.GetStream(); if (_useHandshake) { if (_isSecure) { _clientStream = new SslStream(_clientStream, false); _certificate = LoadPKCS12Certificate(AssemblyName + CertificatePath, String.Empty); _chain = new X509Chain { _certificate }; var certList = new X509List { _certificate }; (_clientStream as SslStream).AuthenticateAsClient(connectUri.AbsoluteUri, certList, _chain, SslProtocols.Tls, SslStrength.All, false); _selectedProtocol = (_clientStream as SslStream).AlpnSelectedProtocol; } if (!_isSecure || _selectedProtocol == Protocols.Http1) { MakeHandshakeEnvironment(); 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"); Protocol = _isSecure ? SslProtocols.Tls : SslProtocols.None; if (_useHttp20) { _sessionAdapter = new Http2ClientMessageHandler(_clientStream, ConnectionEnd.Client, _isSecure, 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); }