public HttpConnection(Uri m2mUrl, X509Certificate?certificate = null) { _iotApiUrl = m2mUrl; var handler = new HttpClientHandler { #if false //enable this code if using proxy Proxy = new System.Net.WebProxy("http://localhost.:8888") { BypassProxyOnLocal = false, }, #endif ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true }; if (certificate != null) { this.ClientCertificate = certificate; handler.ClientCertificates.Add(certificate); } #if DEBUG var loggingHandler = new TraceMessageHandler(handler); _pnClient = new HttpClient(loggingHandler); #else _pnClient = new HttpClient(handler); #endif _pnClient.Timeout = TimeSpan.FromSeconds(300); _pnClient.DefaultRequestHeaders.Add("Accept", OneM2MResponseContentType); }
static bool CertificateValidationCallback( object sender, X509Certificate?certificate, X509Chain?chain, SslPolicyErrors sslPolicyErrors) { Assert.NotNull(certificate); using (SafeCertContextHandle ctx = new SafeCertContextHandle(certificate.Handle, ownsHandle: false)) { bool hasStapledOcsp = ctx.CertHasProperty(Interop.Crypt32.CertContextPropId.CERT_OCSP_RESPONSE_PROP_ID); if (((SslStream)sender).CheckCertRevocationStatus) { Assert.True(hasStapledOcsp, "Cert has stapled OCSP data"); } else { Assert.False(hasStapledOcsp, "Cert has stapled OCSP data"); } } return(true); }
internal static bool ValidatorWithIgnoreNameMismatch(object sender, X509Certificate?certificate, X509Chain?chain, SslPolicyErrors sslPolicyErrors) { sslPolicyErrors &= ~SslPolicyErrors.RemoteCertificateNameMismatch; sslPolicyErrors &= ~SslPolicyErrors.RemoteCertificateChainErrors; return(sslPolicyErrors == SslPolicyErrors.None); }
public virtual bool Equals(X509Certificate?other) { if (other == null) { return(false); } if (Pal == null) { return(other.Pal == null); } if (!Issuer.Equals(other.Issuer)) { return(false); } byte[] thisSerialNumber = GetRawSerialNumber(); byte[] otherSerialNumber = other.GetRawSerialNumber(); if (thisSerialNumber.Length != otherSerialNumber.Length) { return(false); } for (int i = 0; i < thisSerialNumber.Length; i++) { if (thisSerialNumber[i] != otherSerialNumber[i]) { return(false); } } return(true); }
public override bool Equals([NotNullWhen(true)] object? obj) { X509Certificate? other = obj as X509Certificate; if (other == null) return false; return Equals(other); }
public static SafeMsQuicConfigurationHandle Create(QuicOptions options, SslServerAuthenticationOptions?serverAuthenticationOptions, string?targetHost = null) { QUIC_CREDENTIAL_FLAGS flags = QUIC_CREDENTIAL_FLAGS.NONE; X509Certificate? certificate = serverAuthenticationOptions?.ServerCertificate; if (serverAuthenticationOptions != null) { if (serverAuthenticationOptions.CipherSuitesPolicy != null) { throw new PlatformNotSupportedException(SR.Format(SR.net_quic_ssl_option, nameof(serverAuthenticationOptions.CipherSuitesPolicy))); } if (serverAuthenticationOptions.EncryptionPolicy == EncryptionPolicy.NoEncryption) { throw new PlatformNotSupportedException(SR.Format(SR.net_quic_ssl_option, nameof(serverAuthenticationOptions.EncryptionPolicy))); } if (serverAuthenticationOptions.ClientCertificateRequired) { flags |= QUIC_CREDENTIAL_FLAGS.REQUIRE_CLIENT_AUTHENTICATION | QUIC_CREDENTIAL_FLAGS.INDICATE_CERTIFICATE_RECEIVED | QUIC_CREDENTIAL_FLAGS.NO_CERTIFICATE_VALIDATION; } if (certificate == null && serverAuthenticationOptions?.ServerCertificateSelectionCallback != null && targetHost != null) { certificate = serverAuthenticationOptions.ServerCertificateSelectionCallback(options, targetHost); } } return(Create(options, flags, certificate, serverAuthenticationOptions?.ServerCertificateContext, serverAuthenticationOptions?.ApplicationProtocols)); }
#pragma warning restore IDE0052 // Remove unread private members /// <summary> /// Initializes a new instance of the <see cref="MllpServer"/> class. /// </summary> /// <param name="endPoint">The <see cref="IPEndPoint"/> the server will listen on.</param> /// <param name="messageLog">The <see cref="IMessageLog"/> to use for logging incoming messages.</param> /// <param name="middleware">The message handling middleware.</param> /// <param name="cleanupInterval">The interval between cleaning up client connections.</param> /// <param name="parser">The <see cref="PipeParser"/> to use for parsing and encoding.</param> /// <param name="encoding">The <see cref="Encoding"/> to use for network transfers.</param> /// <param name="serverCertificate">The certificates to use for secure connections.</param> /// <param name="userCertificateValidationCallback">Optional certificate validation callback.</param> public MllpServer( IPEndPoint endPoint, IMessageLog messageLog, IHl7MessageMiddleware middleware, TimeSpan cleanupInterval = default, PipeParser?parser = null, Encoding?encoding = null, X509Certificate?serverCertificate = null, RemoteCertificateValidationCallback?userCertificateValidationCallback = null) { _messageLog = messageLog; _middleware = middleware; _parser = parser; _encoding = encoding ?? Encoding.ASCII; _serverCertificate = serverCertificate; _userCertificateValidationCallback = userCertificateValidationCallback; _listener = new TcpListener(endPoint); cleanupInterval = cleanupInterval == default ? TimeSpan.FromSeconds(5) : cleanupInterval; _timer = new Timer( CleanConnections, null, cleanupInterval, cleanupInterval); }
public void RemoteCertificate(X509Certificate?remoteCertificate) { if (IsEnabled()) { RemoteCertificate(remoteCertificate?.ToString(true)); } }
// TODO: consider moving the static code from here to keep all the handle classes small and simple. public static SafeMsQuicConfigurationHandle Create(QuicClientConnectionOptions options) { X509Certificate?certificate = null; if (options.ClientAuthenticationOptions != null) { #pragma warning disable SYSLIB0040 // NoEncryption and AllowNoEncryption are obsolete if (options.ClientAuthenticationOptions.EncryptionPolicy == EncryptionPolicy.NoEncryption) { throw new PlatformNotSupportedException(SR.Format(SR.net_quic_ssl_option, nameof(options.ClientAuthenticationOptions.EncryptionPolicy))); } #pragma warning restore SYSLIB0040 if (options.ClientAuthenticationOptions.ClientCertificates != null) { foreach (var cert in options.ClientAuthenticationOptions.ClientCertificates) { try { if (((X509Certificate2)cert).HasPrivateKey) { // Pick first certificate with private key. certificate = cert; break; } } catch { } } } } return(Create(options, QUIC_CREDENTIAL_FLAGS.CLIENT, certificate: certificate, certificateContext: null, options.ClientAuthenticationOptions?.ApplicationProtocols, options.ClientAuthenticationOptions?.CipherSuitesPolicy)); }
public void AttemptingRestartUsingCert(X509Certificate?clientCertificate, SecureChannel secureChannel) { if (IsEnabled()) { AttemptingRestartUsingCert(clientCertificate?.ToString(true), GetHashCode(secureChannel)); } }
public async Task CertificateCallbackThrowPropagates() { using CancellationTokenSource cts = new CancellationTokenSource(PassingTestTimeout); X509Certificate?receivedCertificate = null; var listenerOptions = new QuicListenerOptions(); listenerOptions.ListenEndPoint = new IPEndPoint(Socket.OSSupportsIPv6 ? IPAddress.IPv6Loopback : IPAddress.Loopback, 0); listenerOptions.ServerAuthenticationOptions = GetSslServerAuthenticationOptions(); using QuicListener listener = new QuicListener(QuicImplementationProviders.MsQuic, listenerOptions); QuicClientConnectionOptions clientOptions = CreateQuicClientOptions(); clientOptions.RemoteEndPoint = listener.ListenEndPoint; clientOptions.ClientAuthenticationOptions.RemoteCertificateValidationCallback = (sender, cert, chain, errors) => { receivedCertificate = cert; throw new ArithmeticException("foobar"); }; clientOptions.ClientAuthenticationOptions.TargetHost = "foobar1"; QuicConnection clientConnection = new QuicConnection(QuicImplementationProviders.MsQuic, clientOptions); Task <QuicConnection> serverTask = listener.AcceptConnectionAsync(cts.Token).AsTask(); await Assert.ThrowsAsync <ArithmeticException>(() => clientConnection.ConnectAsync(cts.Token).AsTask()); QuicConnection serverConnection = await serverTask; Assert.Equal(listenerOptions.ServerAuthenticationOptions.ServerCertificate, receivedCertificate); clientConnection.Dispose(); serverConnection.Dispose(); }
public void AttemptingRestartUsingCert(X509Certificate?clientCertificate, SslStream SslStream) { if (IsEnabled()) { AttemptingRestartUsingCert(clientCertificate?.ToString(true), GetHashCode(SslStream)); } }
/// <summary> /// Initializes a new instance of the <see cref="HttpListener" /> class. /// </summary> /// <param name="certificate">The certificate.</param> public HttpListener(X509Certificate?certificate = null) { Certificate = certificate; _prefixes = new HttpListenerPrefixCollection(this); _connections = new ConcurrentDictionary <HttpConnection, object>(); _ctxQueue = new ConcurrentDictionary <string, HttpListenerContext>(); }
private static X509Certificate2?ConvertToX509Certificate2(X509Certificate?certificate) { return(certificate switch { null => null, X509Certificate2 cert2 => cert2, _ => new X509Certificate2(certificate), });
private static bool DangerousCertificationValidation( object sender, X509Certificate?certificate, X509Chain?chain, SslPolicyErrors sslPolicyErrors) { return(true); }
public CoapConnection(Uri m2mUrl, X509Certificate?certificate = null) { _iotApiUrl = m2mUrl; // TODO: certificate _pnClient = new CoapClient(m2mUrl); _pnClient.Timeout = 300 * 1000; }
static partial void AdditionalCustomizedToString <T>(T value, ref string?result) { X509Certificate?cert = value as X509Certificate; if (cert != null) { result = cert.ToString(fVerbose: true); } }
/// <summary> /// Initializes a new instance of the <see cref="TlsEnableServerCommandHandler"/> class. /// </summary> /// <param name="connectionAccessor">The FTP connection accessor.</param> /// <param name="options">Options for the AUTH TLS command.</param> /// <param name="logger">The logger.</param> public TlsEnableServerCommandHandler( IFtpConnectionAccessor connectionAccessor, IOptions <AuthTlsOptions> options, ILogger <TlsEnableServerCommandHandler>?logger = null) { _connectionAccessor = connectionAccessor; _logger = logger; _serverCertificate = options.Value.ServerCertificate; }
public override bool Equals(object?obj) { X509Certificate?other = obj as X509Certificate; if (other == null) { return(false); } return(Equals(other)); }
public ServiceSslSetter(IServiceProvider container) : base(container) { var ssloption = container.GetRequiredService <IOptions <SslOption> >().Value; if (ssloption.IsUse && ssloption.Certificate != null) { Certificate = ssloption.Certificate; is_use_ssl = true; } }
public void AddCertificate(byte[] input) { var reader = new X509Reader(_publicKeyReaderRegistry, input); var cert = reader.ReadCertificate(); if (_certificates.Count == 0) { _defaultCertificate = cert; } _certificates.Add(cert); }
/// <summary> /// Creates a gRPC client using the specified address. /// </summary> /// <typeparam name="TClient">The type of the gRPC client. This type will typically be defined using generated code from a *.proto file.</typeparam> /// <param name="baseAddress">The base address to use when making gRPC requests.</param> /// <param name="certificate">The client certificate to use when making gRPC requests.</param> /// <param name="loggerFactory">The <see cref="ILoggerFactory"/>.</param> /// <returns>A gRPC client.</returns> public static TClient Create <TClient>(string baseAddress, X509Certificate?certificate = null, ILoggerFactory?loggerFactory = null) where TClient : ClientBase <TClient> { var httpClientHandler = new HttpClientHandler(); httpClientHandler.ServerCertificateCustomValidationCallback = (httpRequestMessage, cert, cetChain, policyErrors) => true; if (certificate != null) { httpClientHandler.ClientCertificates.Add(certificate); } return(CreateCore <TClient>(baseAddress, httpClientHandler, loggerFactory)); }
static bool CertificateValidationCallback( object sender, X509Certificate?certificate, X509Chain?chain, SslPolicyErrors sslPolicyErrors) { Assert.NotNull(certificate); Assert.NotNull(chain); sslPolicyErrors &= ~SslPolicyErrors.RemoteCertificateChainErrors; chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust; chain.ChainPolicy.CustomTrustStore.Add(chain.ChainElements[^ 1].Certificate);
public ServiceDecodeSetter(IServiceProvider container) : base(container) { var ssloption = container.GetRequiredService <IOptions <SslOption> >().Value; if (ssloption.IsUse && ssloption.Certificate != null) { Certificate = ssloption.Certificate; is_use_ssl = true; } var compresstion = container.GetRequiredService <IOptions <CompressOption> >().Value; decodeType = compresstion.Mode; }
// TODO: consider moving the static code from here to keep all the handle classes small and simple. public static SafeMsQuicConfigurationHandle Create(QuicClientConnectionOptions options) { X509Certificate?certificate = null; if (options.ClientAuthenticationOptions != null) { SslClientAuthenticationOptions clientAuthenticationOptions = options.ClientAuthenticationOptions; #pragma warning disable SYSLIB0040 // NoEncryption and AllowNoEncryption are obsolete if (clientAuthenticationOptions.EncryptionPolicy == EncryptionPolicy.NoEncryption) { throw new PlatformNotSupportedException(SR.Format(SR.net_quic_ssl_option, nameof(clientAuthenticationOptions.EncryptionPolicy))); } #pragma warning restore SYSLIB0040 if (clientAuthenticationOptions.LocalCertificateSelectionCallback != null) { X509Certificate?cert = clientAuthenticationOptions.LocalCertificateSelectionCallback( options, clientAuthenticationOptions.TargetHost ?? string.Empty, clientAuthenticationOptions.ClientCertificates ?? new X509CertificateCollection(), null, Array.Empty <string>()); if (cert is X509Certificate2 cert2 && cert2.Handle != IntPtr.Zero && cert2.HasPrivateKey) { certificate = cert; } } else if (clientAuthenticationOptions.ClientCertificates != null) { foreach (X509Certificate cert in clientAuthenticationOptions.ClientCertificates) { if (cert is X509Certificate2 cert2 && cert2.Handle != IntPtr.Zero && cert2.HasPrivateKey) { // Pick first certificate with private key. certificate = cert; break; } } } } QUIC_CREDENTIAL_FLAGS flags = QUIC_CREDENTIAL_FLAGS.CLIENT; if (OperatingSystem.IsWindows()) { flags |= QUIC_CREDENTIAL_FLAGS.USE_SUPPLIED_CREDENTIALS; } return(Create(options, flags, certificate: certificate, certificateContext: null, options.ClientAuthenticationOptions?.ApplicationProtocols, options.ClientAuthenticationOptions?.CipherSuitesPolicy)); }
private static X509Certificate2?ConvertToX509Certificate2(X509Certificate?certificate) { if (certificate == null) { return(null); } if (certificate is X509Certificate2 cert2) { return(cert2); } return(new X509Certificate2(certificate)); }
public bool CheckValidationCallback(object sender, X509Certificate?certificate, X509Chain?chain, SslPolicyErrors sslPolicyErrors) { try { this.CheckCertificate(certificate); } catch (Exception ex) { ex._Error(); return(false); } return(true); }
public SafeFreeSslCredentials(X509Certificate?certificate, SslProtocols protocols, EncryptionPolicy policy) : base(IntPtr.Zero, true) { Debug.Assert( certificate == null || certificate is X509Certificate2, "Only X509Certificate2 certificates are supported at this time"); X509Certificate2?cert = (X509Certificate2?)certificate; if (cert != null) { Debug.Assert(cert.HasPrivateKey, "cert.HasPrivateKey"); using (RSAOpenSsl? rsa = (RSAOpenSsl?)cert.GetRSAPrivateKey()) { if (rsa != null) { _certKeyHandle = rsa.DuplicateKeyHandle(); Interop.Crypto.CheckValidOpenSslHandle(_certKeyHandle); } } if (_certKeyHandle == null) { using (ECDsaOpenSsl? ecdsa = (ECDsaOpenSsl?)cert.GetECDsaPrivateKey()) { if (ecdsa != null) { _certKeyHandle = ecdsa.DuplicateKeyHandle(); Interop.Crypto.CheckValidOpenSslHandle(_certKeyHandle); } } } if (_certKeyHandle == null) { throw new NotSupportedException(SR.net_ssl_io_no_server_cert); } _certHandle = Interop.Crypto.X509UpRef(cert.Handle); Interop.Crypto.CheckValidOpenSslHandle(_certHandle); } _protocols = protocols; _policy = policy; }
/// <summary> /// Call back to select client certificate used for mutual authentication /// </summary> /// <param name="sender">The sender.</param> /// <param name="targetHost">The remote hostname.</param> /// <param name="localCertificates">Selected local certificates by SslStream.</param> /// <param name="remoteCertificate">The remote certificate of server.</param> /// <param name="acceptableIssuers">The acceptable issues for client certificate as listed by server.</param> /// <returns></returns> internal X509Certificate?SelectClientCertificate(object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers) { X509Certificate?clientCertificate = null; if (acceptableIssuers != null && acceptableIssuers.Length > 0 && localCertificates != null && localCertificates.Count > 0) { foreach (var certificate in localCertificates) { string issuer = certificate.Issuer; if (Array.IndexOf(acceptableIssuers, issuer) != -1) { clientCertificate = certificate; } } } if (localCertificates != null && localCertificates.Count > 0) { clientCertificate = localCertificates[0]; } // If user call back is registered if (ClientCertificateSelectionCallback != null) { var args = new CertificateSelectionEventArgs { TargetHost = targetHost, LocalCertificates = localCertificates, RemoteCertificate = remoteCertificate, AcceptableIssuers = acceptableIssuers, ClientCertificate = clientCertificate }; // why is the sender null? ClientCertificateSelectionCallback.InvokeAsync(this, args, exceptionFunc).Wait(); return(args.ClientCertificate); } return(clientCertificate); }
public async Task CertificateCallbackThrowPropagates() { using CancellationTokenSource cts = new CancellationTokenSource(PassingTestTimeout); X509Certificate?receivedCertificate = null; bool validationResult = false; var listenerOptions = new QuicListenerOptions(); listenerOptions.ListenEndPoint = new IPEndPoint(Socket.OSSupportsIPv6 ? IPAddress.IPv6Loopback : IPAddress.Loopback, 0); listenerOptions.ServerAuthenticationOptions = GetSslServerAuthenticationOptions(); using QuicListener listener = new QuicListener(QuicImplementationProviders.MsQuic, listenerOptions); QuicClientConnectionOptions clientOptions = CreateQuicClientOptions(); clientOptions.RemoteEndPoint = listener.ListenEndPoint; clientOptions.ClientAuthenticationOptions.RemoteCertificateValidationCallback = (sender, cert, chain, errors) => { receivedCertificate = cert; if (validationResult) { return(validationResult); } throw new ArithmeticException("foobar"); }; clientOptions.ClientAuthenticationOptions.TargetHost = "foobar1"; QuicConnection clientConnection = new QuicConnection(QuicImplementationProviders.MsQuic, clientOptions); await Assert.ThrowsAsync <ArithmeticException>(() => clientConnection.ConnectAsync(cts.Token).AsTask()); Assert.Equal(listenerOptions.ServerAuthenticationOptions.ServerCertificate, receivedCertificate); clientConnection.Dispose(); // Make sure the listner is still usable and there is no lingering bad conenction validationResult = true; (clientConnection, QuicConnection serverConnection) = await CreateConnectedQuicConnection(listener); await PingPong(clientConnection, serverConnection); clientConnection.Dispose(); serverConnection.Dispose(); }