I have a powershell script using WinScp that allows me to authenticate the server cert against a fingerprint stored as a string "a1:ec:72:18:8b:c3:dc:12:9b:77:b0:6d:f4:c1:a6:cf:db:47:8f:66:66:15:14:39:c4:62:85:a7:b2:73:f7:93"
I am attempting to implement FluentFtp inside the main data processing app so we no longer need the script. _ftpsOptions
is an object containing various ftps relevant settings from Configuration. I've read that I need to implement a callback handler to ValidateCertificate
so, in my ftps method:
client.Config.ValidateAnyCertificate = _ftpsOptions.IgnoreCertificateErrors;
client.ValidateCertificate += new FtpSslValidation(OnValidateCertificate); //this is ignored if ValidateAnyCertificate is true
and then.
/// <summary>
/// Callback handler for FtpSslValidation
/// </summary>
/// <param name="control"><see cref="BaseFtpClient"/> A base Ftp Client</param>
/// <param name="e"><see cref="FtpSslValidationEventArgs"/> options</param>
private void OnValidateCertificate(BaseFtpClient control, FtpSslValidationEventArgs e)
{
X509Certificate2 serverCert = (X509Certificate2)e.Certificate;
if (serverCert.Thumbprint == _ftpsOptions.FingerPrint)
{
e.PolicyErrors = SslPolicyErrors.None;
}
else
{
e.PolicyErrors = SslPolicyErrors.RemoteCertificateNameMismatch;
}
if (e.PolicyErrors != System.Net.Security.SslPolicyErrors.None)
{
// invalid cert, do you want to accept it?
e.Accept = false;
}
else
{
e.Accept = true;
}
}
To access the Thumbprint property I have to cast to X509Certificate2
as mentioned in several blog posts. There is no 'bad server cert' option in the SslPolicyErrors enum, so picking the closest.
Problem is: check is failing. I can't see the Thumbprint value in VS because its being optimized away. Tried adding [MethodImpl(MethodImplOptions.NoOptimization]
to the method, but it didn't help. I think it would need adding to the X509Certificate2 class. Added a Log.Debug and that worked.
[10:50:49 DBG] [FtpsFluent.OnValidateCertificate] Server Thumbprint: 679B8B251C541FA0CCF3734B25A7C523635B9360
[10:50:49 DBG] [FtpsFluent.OnValidateCertificate] Validate Against: a1:ec:72:18:8b:c3:dc:12:9b:77:b0:6d:f4:c1:a6:cf:db:47:8f:66:66:15:14:39:c4:62:85:a7:b2:73:f7:93
These look different enough that I don't think I'm comparing the same thing. Should I change my config to store the 679B... value? Should I be going about this differently?