I'm trying to establish a TCP connection to a remote server using SslStream and TLS 1.2 protocol. The code is as follows:
_tcpClient.Connect(endPoint);
var certificate = new X509Certificate2(_settings.CertificateFilePath, _settings.CertificatePassword, X509KeyStorageFlags.MachineKeySet);
var certificates = new X509CertificateCollection { certificate };
_nStream = _tcpClient.GetStream();
_sslStream = new SslStream(_nStream, false,
(o, x509Certificate, chain, errors) => true,
(o, s, collection, x509Certificate, issuers) =>
{ return collection[0]; }
);
_sslStream.AuthenticateAsClient(_settings.HostIpAddress, certificates, SslProtocols.Tls12, true);
_sslStream.Write(someData, 0, someData.Length);
However, I'm getting an exception:
System.Security.Authentication.AuthenticationException: A call to SSPI failed, see inner exception. ---> System.ComponentModel.Win32Exception: An unknown error occurred while processing the certificate
--- End of inner exception stack trace
at System.Net.Security.SslState.CheckThrow(Boolean authSucessCheck) at System.Net.Security.SslStream.Write(Byte[] buffer, Int32 offset, Int32 count)
I enabled SChannel logging and found this in Windows event log:
The remote server has requested SSL client authentication, but no suitable client certificate could be found. An anonymous connection will be attempted.
Then I enabled System.Net loggiing as described here and got this log (I removed some certificate data from it). It looks like the client certificate is OK but for some reason the log says Remote certificate: null
although there is clearly some data sent back from the remote server that looks very much like a certificate. And at the very end the log says returned code=CertUnknown
. I've no idea where the problem might be (remote server certificate? my code? remote/local server settings?) and would appreciate any help.
Note:
If I change my code to use SSL 3 by specifying SslProtocols.Ssl3
instead of SslProtocols.Tls12
everything works fine. But I really need to use TLS because that's what the remote server owner asks to do.