如何使用 FTP over TLS (FTPS) 验证 X.509 证书? [英] How to validate X.509 certificate using FTP over TLS (FTPS)?

查看:43
本文介绍了如何使用 FTP over TLS (FTPS) 验证 X.509 证书?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码可以使用 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.

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);
    }
});

这篇关于如何使用 FTP over TLS (FTPS) 验证 X.509 证书?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆