我正在尝试连接到使用自签名SSL证书的API。我这样做是使用.NET的HttpWebRequest和HttpWebResponse对象。我得到一个例外:
基础连接已关闭:无法建立SSL / TLS安全通道的信任关系。
我明白这意味着什么。而且我明白为什么.NET认为它应该警告我并关闭连接。但是在这种情况下,无论如何,我还是想连接到API,以防中间人攻击。
那么,如何为该自签名证书添加例外?还是告诉HttpWebRequest / Response根本不验证证书的方法?我该怎么办?
我正在尝试连接到使用自签名SSL证书的API。我这样做是使用.NET的HttpWebRequest和HttpWebResponse对象。我得到一个例外:
基础连接已关闭:无法建立SSL / TLS安全通道的信任关系。
我明白这意味着什么。而且我明白为什么.NET认为它应该警告我并关闭连接。但是在这种情况下,无论如何,我还是想连接到API,以防中间人攻击。
那么,如何为该自签名证书添加例外?还是告诉HttpWebRequest / Response根本不验证证书的方法?我该怎么办?
Answers:
@Domster:可以,但是您可能想通过检查证书哈希是否符合您的期望来加强安全性。因此,扩展版本看起来像这样(基于我们正在使用的一些实时代码):
static readonly byte[] apiCertHash = { 0xZZ, 0xYY, ....};
/// <summary>
/// Somewhere in your application's startup/init sequence...
/// </summary>
void InitPhase()
{
// Override automatic validation of SSL server certificates.
ServicePointManager.ServerCertificateValidationCallback =
ValidateServerCertficate;
}
/// <summary>
/// Validates the SSL server certificate.
/// </summary>
/// <param name="sender">An object that contains state information for this
/// validation.</param>
/// <param name="cert">The certificate used to authenticate the remote party.</param>
/// <param name="chain">The chain of certificate authorities associated with the
/// remote certificate.</param>
/// <param name="sslPolicyErrors">One or more errors associated with the remote
/// certificate.</param>
/// <returns>Returns a boolean value that determines whether the specified
/// certificate is accepted for authentication; true to accept or false to
/// reject.</returns>
private static bool ValidateServerCertficate(
object sender,
X509Certificate cert,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
{
// Good certificate.
return true;
}
log.DebugFormat("SSL certificate error: {0}", sslPolicyErrors);
bool certMatch = false; // Assume failure
byte[] certHash = cert.GetCertHash();
if (certHash.Length == apiCertHash.Length)
{
certMatch = true; // Now assume success.
for (int idx = 0; idx < certHash.Length; idx++)
{
if (certHash[idx] != apiCertHash[idx])
{
certMatch = false; // No match
break;
}
}
}
// Return true => allow unauthenticated server,
// false => disallow unauthenticated server.
return certMatch;
}
事实证明,如果您只想完全禁用证书验证,则可以在ServicePointManager上更改ServerCertificateValidationCallback,如下所示:
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
这将验证所有证书(包括无效,过期或自签名的证书)。
请注意,在.NET 4.5中,您可以按HttpWebRequest本身覆盖SSL验证(而不是通过影响所有请求的全局委托):
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.ServerCertificateValidationCallback = delegate { return true; };
使用委托上的sender参数,可以将Domster答案中使用的验证回调的范围限制为特定的请求ServerCertificateValidationCallback
。以下简单的作用域类使用此技术临时连接仅对给定请求对象执行的验证回调。
public class ServerCertificateValidationScope : IDisposable
{
private readonly RemoteCertificateValidationCallback _callback;
public ServerCertificateValidationScope(object request,
RemoteCertificateValidationCallback callback)
{
var previous = ServicePointManager.ServerCertificateValidationCallback;
_callback = (sender, certificate, chain, errors) =>
{
if (sender == request)
{
return callback(sender, certificate, chain, errors);
}
if (previous != null)
{
return previous(sender, certificate, chain, errors);
}
return errors == SslPolicyErrors.None;
};
ServicePointManager.ServerCertificateValidationCallback += _callback;
}
public void Dispose()
{
ServicePointManager.ServerCertificateValidationCallback -= _callback;
}
}
上面的类可用于忽略特定请求的所有证书错误,如下所示:
var request = WebRequest.Create(uri);
using (new ServerCertificateValidationScope(request, delegate { return true; }))
{
request.GetResponse();
}
只是在devstuff的答案基础上,包括主题和发行者...欢迎发表评论...
public class SelfSignedCertificateValidator
{
private class CertificateAttributes
{
public string Subject { get; private set; }
public string Issuer { get; private set; }
public string Thumbprint { get; private set; }
public CertificateAttributes(string subject, string issuer, string thumbprint)
{
Subject = subject;
Issuer = issuer;
Thumbprint = thumbprint.Trim(
new char[] { '\u200e', '\u200f' } // strip any lrt and rlt markers from copy/paste
);
}
public bool IsMatch(X509Certificate cert)
{
bool subjectMatches = Subject.Replace(" ", "").Equals(cert.Subject.Replace(" ", ""), StringComparison.InvariantCulture);
bool issuerMatches = Issuer.Replace(" ", "").Equals(cert.Issuer.Replace(" ", ""), StringComparison.InvariantCulture);
bool thumbprintMatches = Thumbprint == String.Join(" ", cert.GetCertHash().Select(h => h.ToString("x2")));
return subjectMatches && issuerMatches && thumbprintMatches;
}
}
private readonly List<CertificateAttributes> __knownSelfSignedCertificates = new List<CertificateAttributes> {
new CertificateAttributes( // can paste values from "view cert" dialog
"CN = subject.company.int",
"CN = issuer.company.int",
"f6 23 16 3d 5a d8 e5 1e 13 58 85 0a 34 9f d6 d3 c8 23 a8 f4")
};
private static bool __createdSingleton = false;
public SelfSignedCertificateValidator()
{
lock (this)
{
if (__createdSingleton)
throw new Exception("Only a single instance can be instanciated.");
// Hook in validation of SSL server certificates.
ServicePointManager.ServerCertificateValidationCallback += ValidateServerCertficate;
__createdSingleton = true;
}
}
/// <summary>
/// Validates the SSL server certificate.
/// </summary>
/// <param name="sender">An object that contains state information for this
/// validation.</param>
/// <param name="cert">The certificate used to authenticate the remote party.</param>
/// <param name="chain">The chain of certificate authorities associated with the
/// remote certificate.</param>
/// <param name="sslPolicyErrors">One or more errors associated with the remote
/// certificate.</param>
/// <returns>Returns a boolean value that determines whether the specified
/// certificate is accepted for authentication; true to accept or false to
/// reject.</returns>
private bool ValidateServerCertficate(
object sender,
X509Certificate cert,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
return true; // Good certificate.
Dbg.WriteLine("SSL certificate error: {0}", sslPolicyErrors);
return __knownSelfSignedCertificates.Any(c => c.IsMatch(cert));
}
}
要向其他人添加可能的帮助...如果希望它提示用户安装自签名证书,则可以使用此代码(从上面进行修改)。
不需要管理员权限,将可信任的配置文件安装到本地用户:
private static bool ValidateServerCertficate(
object sender,
X509Certificate cert,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
{
// Good certificate.
return true;
}
Common.Helpers.Logger.Log.Error(string.Format("SSL certificate error: {0}", sslPolicyErrors));
try
{
using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
{
store.Open(OpenFlags.ReadWrite);
store.Add(new X509Certificate2(cert));
store.Close();
}
return true;
}
catch (Exception ex)
{
Common.Helpers.Logger.Log.Error(string.Format("SSL certificate add Error: {0}", ex.Message));
}
return false;
}
这对于我们的应用程序似乎效果很好,并且如果用户按no,则通信将无法进行。
更新:2015-12-11-将StoreName.Root更改为StoreName.My-我的我将安装到本地用户商店中,而不是Root。即使您“以管理员身份运行”,某些系统上的根也不起作用
我遇到了与OP相同的问题,其中Web请求将抛出该确切异常。我以为我已经正确设置了所有设置,安装了证书,可以在机器存储中找到它,并将其附加到Web请求,并且我已禁用了对请求上下文的证书验证。
原来,我使用用户帐户运行,并且证书已安装到计算机存储中。这导致Web请求引发此异常。为了解决该问题,我必须以管理员身份运行或将证书安装到用户存储中并从那里读取它。
即使C#不能与Web请求一起使用,似乎C#仍能够在计算机存储中找到证书,并且一旦Web请求发出,就会导致OP的异常被抛出。
首先-很抱歉,因为我使用了@devstuff描述的解决方案。但是,我发现了一些改进方法。
这是我的修改:
private static X509Certificate2 caCertificate2 = null;
/// <summary>
/// Validates the SSL server certificate.
/// </summary>
/// <param name="sender">An object that contains state information for this validation.</param>
/// <param name="cert">The certificate used to authenticate the remote party.</param>
/// <param name="chain">The chain of certificate authorities associated with the remote certificate.</param>
/// <param name="sslPolicyErrors">One or more errors associated with the remote certificate.</param>
/// <returns>Returns a boolean value that determines whether the specified certificate is accepted for authentication; true to accept or false to reject.</returns>
private static bool ValidateServerCertficate(
object sender,
X509Certificate cert,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
{
// Good certificate.
return true;
}
// If the following line is not added, then for the self-signed cert an error will be (not tested with let's encrypt!):
// "A certificate chain processed, but terminated in a root certificate which is not trusted by the trust provider. (UntrustedRoot)"
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
// convert old-style cert to new-style cert
var returnedServerCert2 = new X509Certificate2(cert);
// This part is very important. Adding known root here. It doesn't have to be in the computer store at all. Neither do certificates.
chain.ChainPolicy.ExtraStore.Add(caCertificate2);
// 1. Checks if ff the certs are OK (not expired/revoked/etc)
// 2. X509VerificationFlags.AllowUnknownCertificateAuthority will make sure that untrusted certs are OK
// 3. IMPORTANT: here, if the chain contains the wrong CA - the validation will fail, as the chain is wrong!
bool isChainValid = chain.Build(returnedServerCert2);
if (!isChainValid)
{
string[] errors = chain.ChainStatus
.Select(x => String.Format("{0} ({1})", x.StatusInformation.Trim(), x.Status))
.ToArray();
string certificateErrorsString = "Unknown errors.";
if (errors != null && errors.Length > 0)
{
certificateErrorsString = String.Join(", ", errors);
}
Log.Error("Trust chain did not complete to the known authority anchor. Errors: " + certificateErrorsString);
return false;
}
// This piece makes sure it actually matches your known root
bool isValid = chain.ChainElements
.Cast<X509ChainElement>()
.Any(x => x.Certificate.RawData.SequenceEqual(caCertificate2.GetRawCertData()));
if (!isValid)
{
Log.Error("Trust chain did not complete to the known authority anchor. Thumbprints did not match.");
}
return isValid;
}
设置证书:
caCertificate2 = new X509Certificate2("auth/ca.crt", "");
var clientCertificate2 = new X509Certificate2("auth/client.pfx", "");
传递委托方法
ServerCertificateValidationCallback(ValidateServerCertficate)
client.pfx
使用KEY和CERT生成,如下所示:
openssl pkcs12 -export -in client.crt -inkey client.key -out client.pfx