如何使用TLS上的FTP(FTPS)验证X.509证书? [英] How to validate X.509 certificate using FTP over TLS (FTPS)?
问题描述
以下代码能够使用TLS连接到FTP服务器:
The following code is able to connect to a FTP server using TLS:
private FtpClient getFtpsClient(System.Uri uri) {
if (uri.Scheme != "ftps") {
throw new NotImplementedException("Only ftps is implementent");
}
var userInfo = uri.UserInfo.Split(":");
FtpClient client = new FtpClient(uri.Host, userInfo[0], userInfo[1]);
client.EncryptionMode = FtpEncryptionMode.Explicit;
client.SslProtocols = SslProtocols.Tls;
client.ValidateCertificate += new FtpSslValidation(OnValidateCertificate);
client.Connect();
void OnValidateCertificate(FtpClient control, FtpSslValidationEventArgs e) {
var cert2 = new X509Certificate2(e.Certificate);
e.Accept = cert2.Verify();
}
return client;
}
作为库,我使用FluentFTP。我想知道,方法 X509Certificate2.Verify()
是否足以防止安全问题。
As library I use FluentFTP. I wonder, if the method X509Certificate2.Verify()
is enough to prevent security issues.
<< a href = https://docs.microsoft.com/zh-cn/dotnet/api/system.security.cryptography.x509certificates.x509certificate2.verify?view=netcore-2.2 rel = nofollow noreferrer> X509Certificate2.Verify()
可以吗?所引用的文档信息非常匮乏。
What exactly does X509Certificate2.Verify()
do? The referenced documentation is very short on information.
如果中间人攻击?
推荐答案
文档已于3个月前更新,现在又提了问题。
The documentation got updated 3 month ago and now anwers the question.
方法1:如果SSL证书没有错误,则进行连接。
client.ValidateCertificate += new FtpSslValidation(delegate (FtpClient c, FtpSslValidationEventArgs e) {
if (e.PolicyErrors != System.Net.Security.SslPolicyErrors.None){
e.Accept = false;
}else{
e.Accept = true;
}
});
方法2:如果证书与白名单证书匹配,则连接。
首先,您必须找到有效证书的字符串。使用以下代码将有效的证书字符串保存到文件中:
First you must discover the string of the valid certificate. Use this code to save the valid certificate string to a file:
client.ValidateCertificate += new FtpSslValidation(delegate (FtpClient c, FtpSslValidationEventArgs e) {
File.WriteAllText(@"C:\cert.txt", e.Certificate.GetRawCertDataString());
});
然后最后使用此代码检查收到的证书是否与您信任的证书匹配:
Then finally use this code to check if the received certificate matches the one you trust:
string ValidCert = "<insert contents of cert.txt>";
client.ValidateCertificate += new FtpSslValidation(delegate (FtpClient c, FtpSslValidationEventArgs e) {
if (e.PolicyErrors == SslPolicyErrors.None || e.Certificate.GetRawCertDataString() == ValidCert) {
e.Accept = true;
}else{
throw new Exception("Invalid certificate : " + e.PolicyErrors);
}
});
这篇关于如何使用TLS上的FTP(FTPS)验证X.509证书?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!