Ftp and invalid host name in security certificate

I would like to start with a side note. Everybody should use secure connections for everything. Somebody could say: “But I don’t have anything important there, why should I bother?”. And I can tell you why you should bother. You see, most of the time you will start with something not important, but it will grow very quickly and in a very short time, there will be a lot of important stuff. But then, because it contains important stuff, it will be much harder to change because it “just works”. Usually, everybody starts to care about security only when it is too late. So, it is much easier to do it right from the beginning.

I wrote a small application that does backup of changed files for this web site over FTP protocol. From the beginning, I chose to use FTP over TLS. Read the first paragraph to understand why. But it looks like the company that hosts my web site was hacked again and they changed the whole infrastructure. As a result, the new FTP server is still secure, but the certificate’s hostname is invalid. I think they try to cut costs and use the same certificate for multiple hosts instead of using wildcard certificates. Or perhaps they will do it later because they rushed change. I don’t know their motives, but now I must deal with it as my app does not work anymore.

There is an obvious solution – disable certificate validation. But unfortunately, it disables validation of everything and not only host time. It is still better than not having a secure connection, but it is very crippled. I must note that it is possible to check everything else and allow only invalid host name, but it is quite advanced stuff, and most developers usually disable certificate validation completely.

So instead, I decided to just specify which certificate to use on the client side. Effectively it is saying to the FTP client: “Trust this particular certificate”. Because I know that it is a valid certificate used by a hosting company, I know I can trust it. But then I need to find a way, how to get a certificate from a FTP server. It is easy to view and download a certificate for web sites, but how to do it for FTP?

Well, as it turns out, it is very easy. I found this article that explains how to do it. You just need Openssl tool. And if you have a command line Git client, it has this tool. Then you need to run this command:

openssl s_client -connect YourFtpSite:21 -starttls ftp

And it will output a certificate. Then copy everything starting from -----BEGIN CERTIFICATE----- and finishing with  -----END CERTIFICATE-----. Resulting text should include both makers. Then save this text in some file and you get the server certificate. My application is written in C#, so I used following line to add it to my FTP client:

ftpClient.ClientCertificates.Add(new X509Certificate(@"Certificate.txt"));

After that my FTP client can connect to FTP server without errors.

I hope it helps someone