Error: The handshake failed due to an unexpected packet format.

Jul 27, 2009 at 8:49 AM
Edited Jul 27, 2009 at 8:54 AM

Hi,

I am using your library to connect to an FTPS server with Implicit SSL.  It will let me connect and I can perform tasks such as getting the current directory, however when I try and get a directory list or download a file, I get the following error:

The handshake failed due to an unexpected packet format.

The error occurs on the following line in the CreateSSLStream method:

sslStream.AuthenticateAsClient(hostname, clientCertColl, SslProtocols.Default, sslCheckCertRevocation);

My code is as follows:

FTPSClient client = new FTPSClient();

client.Connect(this.HostName, new NetworkCredential(this.Username, this.Password), ESSLSupportMode.Implicit | ESSLSupportMode.DataChannelRequested, myCertificateValidation);

IList<AlexPilotti.FTPS.Common.DirectoryListItem> files = client.GetDirectoryList();

Any help would be much appreciated, many thanks.  Rob J

Coordinator
Aug 3, 2009 at 12:51 PM

Hi,

for implicit SSL support "ESSLSupportMode.Implicit" is enough. This error refers to invalid SSL protocol support, usually due to the server answering inclear text. Could you please provide some details about the FTPS server you are connecting to?

 

Cheers,

Alessandro

Aug 26, 2009 at 6:45 PM

I am also experiencing the same issue.

I can put files to the remote server, but I'm unable to retrieve a directory listing. It fails with

"The handshake failed due to an unexpected packet format."

I'm using FileZilla Server 0.9.32

It seems to be related to the Implicit connection because I can retrieve a directory listing from another server running FileZilla and connecting with ESSLSupportMode.All

 

 

Aug 27, 2009 at 10:17 AM

Hi,

Unfortunately I am unable to provide any details of the FTPS Server as it belongs to a customer.

I did however manage to resolve this problem in the following way:

In the method GetDataStream() I added an additional IF clause that checks if the current mode is Implicit and if so sets the current stream to the existing data client stream, e.g.

private Stream GetDataStream()
{
    Stream s = null;

    if (SslSupportCurrentMode == ESSLSupportMode.Implicit)
    {
        s = dataClient.GetStream();
    }
    else if ((sslSupportCurrentMode & ESSLSupportMode.DataChannelRequested) == ESSLSupportMode.DataChannelRequested)
    {
        if (dataSslStream == null)
            dataSslStream = CreateSSlStream(dataClient.GetStream(), false);
        s = dataSslStream;
    }
    else
    {
        s = dataClient.GetStream();
    }

    return s;
}

I am not sure if this is entirely correct but it does seem to work for me in all circumstances.

Hope this helps.

Aug 27, 2009 at 2:43 PM
Thanks!

I ended up working around it by getting the server to accept explicit tsl connections. For some reason the server was giving me a handshake error, but when I changed the server port to a random high port it worked.

I suspect that issue was the data center doing dome weird ftp port mapping.

Thanks again,

Scott

On Thu, Aug 27, 2009 at 4:19 AM, robjohnson <notifications@codeplex.com> wrote:

From: robjohnson

Hi,

Unfortunately I am unable to provide any details of the FTPS Server as it belongs to a customer.

I did however manage to resolve this problem in the following way:

In the method GetDataStream() I added an additional IF clause that checks if the current mode is Implicit and if so sets the current stream to the existing data client stream, e.g.

private Stream GetDataStream()
{
    Stream s = null;

    if (SslSupportCurrentMode == ESSLSupportMode.Implicit)
    {
        s = dataClient.GetStream();
    }
    else if ((sslSupportCurrentMode & ESSLSupportMode.DataChannelRequested) == ESSLSupportMode.DataChannelRequested)
    {
        if (dataSslStream == null)
            dataSslStream = CreateSSlStream(dataClient.GetStream(), false);
        s = dataSslStream;
    }
    else
    {
        s = dataClient.GetStream();
    }

    return s;
}

I am not sure if this is entirely correct but it does seem to work for me in all circumstances.

Hope this helps.

Read the full discussion online.

To add a post to this discussion, reply to this email (ftps@discussions.codeplex.com)

To start a new discussion for this project, email ftps@discussions.codeplex.com

You are receiving this email because you subscribed to this discussion on CodePlex. You can unsubscribe on codePlex.com.

Please note: Images and attachments will be removed from emails. Any posts to this discussion will also be available online at codeplex.com


Coordinator
Aug 27, 2009 at 7:57 PM

Hi,

thanks for your contribution!

I will do more tests with implicit settings against a FileZilla server.

 

Cheers,

Alessandro 

 

Aug 27, 2009 at 9:03 PM
Thanks for putting the FTPS client code together. It's great!

One other clue, before you knock yourself out on this one....

I was attempting an Implicit connection because I couldn't get an Explicit connection to work on the server. I verified with the data center that they were not filtering any of the FileZilla ports. I know my router from home is fine because I can make Explicit connections to a FileZilla Server in another data center.

I then decided to change the port from port 21 to port 30001. Then Explicit worked!

My assumption is that the data center is doing some sort of weird port forwarding on Port 21. That's my guess as to why the implicit connection didn't work - but it's just a guess.

Cheers,

Scott

On Thu, Aug 27, 2009 at 1:58 PM, alexp <notifications@codeplex.com> wrote:

From: alexp

Hi,

thanks for your contribution!

I will do more tests with implicit settings against a FileZilla server.

 

Cheers,

Alessandro 

 

Read the full discussion online.

To add a post to this discussion, reply to this email (ftps@discussions.codeplex.com)

To start a new discussion for this project, email ftps@discussions.codeplex.com

You are receiving this email because you subscribed to this discussion on CodePlex. You can unsubscribe on codePlex.com.

Please note: Images and attachments will be removed from emails. Any posts to this discussion will also be available online at codeplex.com


Feb 10, 2010 at 6:07 PM
Edited Feb 10, 2010 at 6:23 PM

Hi, i work in BI area and i'm using de FTPS Library in a Script Task.

I trying connect to FTPS server with Implicit SSL - Port 2121. And i was getting the error: "No Connection could be made because the target machine actively refused it". So, looking the source, i see that is not default port on ESSLSupportMode.Implict. I change the code to port 2121, just for see if it works.

Here is the code changed: int port = (sslSupportMode & ESSLSupportMode.Implicit) == ESSLSupportMode.Implicit ? 2121 : 21;

Now, the error is: "The handshake failed due to an unexpected packet format". So i try the approach that robjohnson. Putting a additional If in the method GetDataStream().

Here is the entire description of the error:

   em System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)

   em System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)

   em System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)

   em System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)

   em System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)

   em System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)

   em System.Net.Security.SslStream.AuthenticateAsClient(String targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, Boolean checkCertificateRevocation)

   em AlexPilotti.FTPS.Client.FTPSClient.CreateSSlStream(Stream s, Boolean leaveInnerStreamOpen)

   em AlexPilotti.FTPS.Client.FTPSClient.SwitchCtrlToSSLMode()

   em AlexPilotti.FTPS.Client.FTPSClient.Connect(String hostname, Int32 port, NetworkCredential credential, ESSLSupportMode sslSupportMode, RemoteCertificateValidationCallback userValidateServerCertificate, X509Certificate x509ClientCert, Int32 sslMinKeyExchangeAlgStrength, Int32 sslMinCipherAlgStrength, Int32 sslMinHashAlgStrength, Nullable`1 timeout, Boolean useCtrlEndPointAddressForData)

   em AlexPilotti.FTPS.Client.FTPSClient.Connect(String hostname, Int32 port, NetworkCredential credential, ESSLSupportMode sslSupportMode, RemoteCertificateValidationCallback userValidateServerCertificate, X509Certificate x509ClientCert, Int32 sslMinKeyExchangeAlgStrength, Int32 sslMinCipherAlgStrength, Int32 sslMinHashAlgStrength, Nullable`1 timeout)

   em AlexPilotti.FTPS.Client.FTPSClient.Connect(String hostname, NetworkCredential credential, ESSLSupportMode sslSupportMode, RemoteCertificateValidationCallback userValidateServerCertificate)

   em AlexPilotti.FTPS.Client.FTPSClient.Connect(String hostname, NetworkCredential credential, ESSLSupportMode sslSupportMode)

   em ScriptTask_a274746f83144e22af02375b4125685d.ScriptMain.Main()

I just can't figure it out, why or where is the error. Im not a pro in C# and .NET plataform, so it's complicate.

Any help would be much appreciated. Thanks, Rodrigo Carvalho.

P.S.: Sorry some english language mistakes. I'm a brazillian and my english it's terrible.

Coordinator
Feb 10, 2010 at 6:48 PM
Edited Feb 10, 2010 at 6:49 PM

Rodrigo,

> P.S.: Sorry some english language mistakes. I'm a brazillian and my english it's terrible.

Nao se preocupe, Voce escribe in Ingleis muito bem! .... much better than how I'd write in Portugues :-) 

 

> Here is the code changed: int port = (sslSupportMode & ESSLSupportMode.Implicit) == ESSLSupportMode.Implicit ? 2121 : 21

That's ok, BTW there's also an overload of the "Connect" method where you can explicitly set the port number.

 

Your error look like an SSL handshake error. Are you sure that you are dealing with an implicit FTPS server connection instead of explicit?

Could you please post a log obtained by connecting with a client like FileZilla?

 

Até logo,

Alessandro

[ MVP / IIS ]

Feb 10, 2010 at 7:27 PM

Sorry Alessandro, i receive a wrong information. I'm not dealing with an implicit FTPS server. It's explicit. Thanks for my Secure Area that said that to me.

So, i change my code. But now i get nothing. Either an error or a response.

Here is my code:

Dim client As FTPSClient = New FTPSClient()

Dim dirs As New AlexPilotti.FTPS.Common.DirectoryListItem

Dim MyCred As New NetworkCredential

        MyCred.UserName = "xxxx"

        MyCred.Password = "xxxx"

        MyCred.Domain = "xxxxxx.xxxxxx.com"

        Try

            client.Connect("xxxxxx.xxxxxx.com", 2121, MyCred, ESSLSupportMode.CredentialsRequired Or ESSLSupportMode.DataChannelRequested)

             MsgBox("connected")

            client.Close()

        Catch ex As Exception

            MsgBox("Error")

            MsgBox(ex.ToString())

        End Try

        Dts.TaskResult = Dts.Results.Success

    End Sub

Here is the log of FTP Client:

Status:           Conectando a 200.143.0.202:2121...

Status:           Estabelish Connection, waiting for welcome message....

Resposta:      220 Welcome to Freeddom FTP service.

Comando:      AUTH TLS

Resposta:      234 Proceed with negotiation.

Status:           Initializating  TLS...

Comando:      USER xxxxxxxx

Status:           Verifying certificate

Status:           Conexão TLS/SSL estabelecida.

Resposta:      331 Please specify the password.

Comando:      PASS *************

Resposta:      230 Login successful.

Comando:      SYST

Resposta:      215 UNIX Type: L8

Comando:      FEAT

Resposta:      211-Features:

Resposta:      AUTH SSL

Resposta:      AUTH TLS

Resposta:      EPRT

Resposta:      EPSV

Resposta:      MDTM

Resposta:      PASV

Resposta:      PBSZ

Resposta:      PROT

Resposta:      REST STREAM

Resposta:      SIZE

Resposta:      TVFS

Resposta:      211 End

Comando:      PBSZ 0

Resposta:      200 PBSZ set to 0.

Comando:      PROT P

Resposta:      200 PROT now Private.

Status:           Conectado

Status:           Recuperando a listagem de pastas...

Comando:      PWD

Resposta:      257 "/"

Comando:      TYPE I

Resposta:      200 Switching to Binary mode.

Comando:      PASV

Resposta:      227 Entering Passive Mode (192,168,31,161,58,153)

Status:           O servidor enviou uma resposta passiva com um endereço não-roteável. Usando o endereço do servidor em vez deste.

Comando:      LIST

Resposta:      150 Here comes the directory listing.

Resposta:      226 Directory send OK.

Status:           Calculando o offset do fuso horário do servidor...

Comando:      MDTM teste Fabiano Marketdata.txt

Resposta:      213 20100208132718

Status:           Fuso horários: Servidor: 0 segundos. Local: -7200 segundos. Diferença: -7200 segundos.

Status:           Listagem de diretórios bem sucedida

Coordinator
Feb 11, 2010 at 11:59 AM
Edited Feb 11, 2010 at 12:00 PM

Rodrigo,

Connect(...) does not return anything, it just performs the connection. It throws an exception in case of errors of course.

After getting connected you probably need to issue some commands like, e.g.:

IList<DirectoryListItem> l = client.GetDirectoryList();

// Just a sample
foreach(DirectoryListItem i in l)
{
    Console.WriteLine(i.Name);
}

the object model follows the FTP command set: GetFile(...), PutFile(...), etc.

Cheers,

Alessandro

[ MVP / IIS ]

 

 

 

 

Feb 11, 2010 at 4:15 PM

Hi Alessandro,

Thank's for help.

But after the method connect, i put a dialog box to show me that the console pass the method.

I create a project with Visual C# 2008 to work on that:

namespace testeFTP
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("Start Connect");

            FTPSClient client = new FTPSClient();
            NetworkCredential mycred = new NetworkCredential();

            mycred.UserName = "xxxx";
            mycred.Password = "xxxx";

            client.Connect("xxxxxxxxx.com", mycred);

            /* or client.Connect("xxxxxxxx.com, mycred, ESSLSupportMode.CredentialsRequired);

                or client.Connect("homolog.freeddom.com", mycred, ESSLSupportMode.CredentialsRequired | ESSLSupportMode.DataChannelRequested);

                But the error is the same.

            */
                        
            Console.WriteLine("Conecting");

            client.GetFile("//remote_folder//archive.txt", "\\server\\folder");

            Consolen.WriteLine("Downloaded");

            client.Dispose();

            Console.ReadKey();

        }
    }
}

Running that, i get the error on this line: "//sslStream.AuthenticateAsClient(hostname);
                                                                            sslStream.AuthenticateAsClient(hostname, clientCertColl, SslProtocols.Default, sslCheckCertRevocation);"

"The Remote certificate is invalid"

I wanna thank you for all support.

Thanks,

Rodrigo Carvalho

Coordinator
Feb 12, 2010 at 12:50 AM

Rodrigo,

the certificate sent by your FTPS server is probably invalid: maybe self signed or with a non-matching CN.

Look at this thread for how to accept invalid X509 server certificates (you need just a couple of code lines).

http://ftps.codeplex.com/Thread/View.aspx?ThreadId=64472

 

Cheers,

Alessandro Pilotti

[MVP / IIS]

 

Feb 12, 2010 at 3:37 PM

Alessandro,

Just for say some few words. FTPSClient it's working perfect on on SQL Server Integration Services.

Thanks for sharing this lib. It's a great job!!

I wanna thank you, and i think that i'm saying for all that use the FTPSClient, the great suport that you give and the quickly reply's.It's something hard to find.

Cheers,

Rodrigo Carvalho

Coordinator
Feb 12, 2010 at 10:03 PM

Rodrigo,

thanks for your words! :-)

 

Cheers,

Alessandro Pilotti

[ MVP / IIS ]

 

May 9, 2012 at 7:31 PM

Guys,

I'm probably way late int he game here, but where are you guys finding the "FTPSClient" from?  I just downloaded the source code and I don't see any class called "FTPSClient".

I'm also running into the same situation and trying to figure out how to go about correcting this error.  Anyone else has the latest source code that is running in the same issue as mine and how did you go about solving it?

Thanks a bunch.

Khan 

May 9, 2012 at 7:31 PM

Thank you for your recent email. Rob Johnson no longer works for ESP Systex Limited.

Emails to this address are being monitored and will be responded to where appropriate

Alternatively, please forward your email to info@espsystex.co.uk.

ESP Systex Ltd,
Registered office: 68–74 Holderness Road, Hull, HU9 1ED, Registered in England No. 1599791

The contents of this e-mail and any transmitted files are confidential and intended solely for the use of the individual or entity for whom they were intended. ESP Systex Limited hereby excludes any warranty and any liability as to the quality or accuracy of the contents of this e-mail and any attached transmitted files. The views expressed in this e-mail are not necessarily the views of ESP Systex Ltd. This e-mail is not legally binding, contractual or legally binding agreements will only be entered into on company letterhead. If you are not the intended recipient, be advised that you have received this e-mail in error and that any use, dissemination, forwarding, printing or copying of this e-mail is strictly prohibited.

If you are not the intended recipient and have received this e-mail in error please notify us on info@espsystex.co.uk.
Warning: Although ESP Systex Limited has taken reasonable precautions to ensure no viruses are present in this e-mail, ESP Systex Limited cannot accept responsibility for any loss or damage arising from the use of this e-mail or attachments.

Think about the environment, do you really need to print this e-mail?