Freigeben über


Using FtpWebRequest to do FTP over SSL

Last few weeks we were busy to get Whidbey Beta-2 bits ready for release.

If you are looking for some API where your application could talk to a FTP server, which supports SSL. FtpWebRequest under System.Net namespace is your solution. Here I will just point to SSL specific features of the class

Enabling FtpWebrequest to use Ssl is pretty simple, you just need to set EnableSsl flag before calling GetResponse() or GetRequestStream() on the FtpWebRequest object. 

FtpWebRequest request = WebRequest.Create(ftp://myftpserver/dir/filename);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.EnableSsl = true; // Here you enabled request to use ssl instead of clear text
WebResponse response = request.GetResponse();

Some people asked me why FtpWebRequest support "ftps:" protocol based uri similar to "https:", the reason is there is no standard "ftps" scheme specified (yet) and ftp-over-ssl mechanism actually does not demand dedicated port for ssl, you could do it on the same server port on which you are doing regular clear text ftp. It depends on server configuration choice to force the SSL or allow both.

Once you start doing Ftp over SSL there are two important things you will need to know

Validating Server Certificate

If you were old WebRequest user, you might already know about using ServicePointManager.CertificatePolicy for https server certificate validation. In whidbey you will notice the compiler warning saying ServicePointManager.CertificatePolicy is obsolete and replaced with ServicePointManager.ServerCertificateValidationCallback which is delegate of type RemoteCertificateValidationDelegate. New delegate provide better programming model with all certificate errors reported in a single callback and you will also get instance of X509Chain object, which allow you to make decision on certificate chain. 

     ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(myCertificateValidation);

Actual method will look as below
public bool myCertificateValidation(Object sender,
X509Certificate cert,
X509Chain chain,
SslPolicyErrors Errors)
{ return (certificate.GetName() == "my_trusted_name"); }; //Just an example, not real world scenaio

:) Another additional advantage you can take with delegate is from anonymous method support of C# 2.0, especially if you have very simple 1-2 line certificateplicy to implement, see follwing example.

ServicePointManager.ServerCertificateValidationCallback = delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{ return (certificate.GetName() == "my_trusted_name"); }; //Just an example, not real world scenaio

Using Client Certificate

Using Client certificate based authentication when connecting to FTP-SSL is no different then existing HttpWebRequest. You just need to assign appropriate X509Certificate instance to the request object before making GetResponse() or GetRequestStream() call.

 

This posting is provided "AS IS" with no warranties, and confers no rights

Comments

  • Anonymous
    January 23, 2006
    The comment has been removed

  • Anonymous
    June 22, 2006
    while using SSL(request.EnableSsl = True), the following error occurs: The remote server returned an error: (530) Not logged in

  • Anonymous
    September 11, 2006
    Hi,
    I'd like an information: enabling the EnableSsl, it'll make work the FTP connection as a SFTP connection
    http://en.wikipedia.org/wiki/SSH_file_transfer_protocol
    or not?
    If the answer is no, have you got some reference on how I might do it? ;)

  • Anonymous
    September 15, 2006
    Actually current SSL support on ftp does not include SSH FTP. Currently it is based on ftps mentioned in http://en.wikipedia.org/wiki/FTPS, which is basically FTP over SSL/TLS. Future versions of FtpWebRequest may support SSH/FTP.

  • Anonymous
    September 15, 2006
    I have looked at your sample code how do you implent this in a solution

  • Anonymous
    October 10, 2006
    What other options available to to SFTP using .Net? Thanks, Navneet

  • Anonymous
    October 25, 2006
    Until .net frameworks 3.0, there is no API available in .net frameworks. There may be some third party options available. (Ex. one I came across is http://www.jscape.com/articles/sftp_using_csharp.html). I could not get chance to try any of them, so can not recommend any from my side.

  • Anonymous
    November 08, 2006
    Hi,I'm using exactly the same code, but when I send a RETR to the FTP server the FTP server thinks its a GET instead.I've check the FTPWebRequest method and it thinks it's a RETR because of the URI.I've tried it with other ftp servers and still nothing.Help..pleaseSquish

  • Anonymous
    March 23, 2007
    The comment has been removed

  • Anonymous
    April 23, 2007
    The comment has been removed

  • Anonymous
    July 19, 2007
    I am trying to call a web service over https that has an invalid ssl cert. The .Net 2.0 framework throws an "unable to connect to remote host" error every time I try to call a method on the web service. How do I override this. Here is my code:ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate;        hew.apshealthcare.healtheweb_test.HealthEWebService webservice = new hew.apshealthcare.healtheweb_test.HealthEWebService();        DataSet ds = webservice.GetEligibleFamilyMembers(this.tbMemberId.Text);        this.GridView1.DataSource = ds;        this.GridView1.DataBind();   }   public static bool ValidateServerCertificate(     object sender,     X509Certificate certificate,     X509Chain chain,     SslPolicyErrors sslPolicyErrors)   {       return true;   }

  • Anonymous
    August 20, 2007
    after enabling Enablessl property it gives an exception on      request.GetResponse(); error(500): unrecognized command.

  • Anonymous
    September 19, 2007
    The comment has been removed

  • Anonymous
    November 02, 2007
    Does anyone know if this works with RaidenFTPD ftp server ssl connection?

  • Anonymous
    January 02, 2008
    I would like to know is there any way we can implement FTPS in implicit mode.

  • Anonymous
    February 21, 2008
    Hi,Does anybody have sample that works ?

  • Anonymous
    March 06, 2008
    If u don't want to answer why u create this blog

  • Anonymous
    April 23, 2008
    Perhaps you are trying to connect FTP port. FTPS port is different. Try putting correct SSL FTP port.

  • Anonymous
    May 05, 2008
    The comment has been removed

  • Anonymous
    July 25, 2008
    This is a current compile of the team's existing blogs on FtpWebRequest. I am going to update it periodically

  • Anonymous
    August 28, 2008
    This is an error when I call function reqFTP.GetRequestStream()"A call to SSPI failed, see inner exception."and this is innner exception message "The message received was unexpected or badly formatted"

  • Anonymous
    September 03, 2008
     try this .. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);                                    {               FtpWebResponse response =               (FtpWebResponse)reqFTP.GetResponse();}

  • Anonymous
    September 03, 2008
     try this ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);                                    {               FtpWebResponse response =               (FtpWebResponse)reqFTP.GetResponse();}

  • Anonymous
    November 18, 2008
    Thanks for the post. It helped me a lot!

  • Anonymous
    November 24, 2008
    hey I had the same issue, but i was able to get this solved using the content in following postinghttp://www.codeguru.com/csharp/.net/net_security/authentication/article.php/c15051

  • Anonymous
    November 24, 2008
    hey I had the same issue, but i was able to get this solved using the content in following postinghttp://www.codeguru.com/csharp/.net/net_security/authentication/article.php/c15051

  • Anonymous
    November 24, 2008
    http://www.codeguru.com/csharp/.net/net_security/authentication/article.php/c15051

  • Anonymous
    January 04, 2009
    Hm. im scratching my hair off. Why wont FtpWebRequest.EnableSsl=true; work? Anyone got some ideas why it wont work? It seems like its a big problem noone can sove.Regards

  • Anonymous
    January 21, 2009
    PingBack from http://www.keyongtech.com/679888-reg-ssl

  • Anonymous
    March 26, 2009
    I tried this and it worked, but the enablessl flag must be set to true right after you create the ftpwebrequest and before sending the network credential.

  • Anonymous
    June 13, 2009
    PingBack from http://hairgrowthproducts.info/story.php?id=2245