Search code examples
.netwindowssftpopensshssh.net

Error "Bad message" when accessing a file on Windows OpenSSH SFTP server


I need to transfer large files via SFTP from a web site. I cannot store these files (even temporarily) on the web server so I am streaming the file in chunks to the SFTP server.

I've installed OpenSSH (version 5_30_2016) on another Windows machine and am attempting to connect to it using SSH.NET (version 2016.0.0).

This example code gives causes an exception to be thrown on my machine:

const string PATH = "/D:/sftp/test.xml";
var Client = new SftpClient("host", 22, "username", "password");

Client.Connect();   

if(!Client.Exists(PATH))
{                       
    var s = Client.Create(PATH, 1024 * 4);
    s.Dispose();        
}   

var Data = File.ReadAllBytes(@"D:\Temp\TestFile.xml");  
using(var w = Client.Open(PATH, FileMode.Append, FileAccess.ReadWrite)) // this line throws an exception
{
    w.Write(Data, 0, Data.Length);
}

Client.Disconnect();

I am getting an SSH exception coming whenever I try to connect my client to append or open - basically any operation that returns a Stream or a StreamWriter.

The error I get back through the SFTP client is "Bad Message" which isn't very descriptive. I'm just hoping I've missed something obvious in my approach...!

I've also tried looking at using other SFTP libraries but they all seem to rely on passing a physical local file to the remote location which isn't what I want to do. It appears that SSH.NET is the best suited to my needs as it provides methods for passing byte arrays and streams to the SFTP server

Stack trace, with message "Bad Message":

   at Renci.SshNet.Sftp.SftpSession.RequestOpen(String path, Flags flags, Boolean nullOnError)
   at Renci.SshNet.Sftp.SftpFileStream..ctor(ISftpSession session, String path, FileMode mode, FileAccess access, Int32 bufferSize, Boolean useAsync)
   at Renci.SshNet.Sftp.SftpFileStream..ctor(ISftpSession session, String path, FileMode mode, FileAccess access, Int32 bufferSize)
   at Renci.SshNet.SftpClient.Open(String path, FileMode mode, FileAccess access)

Solution

  • This turned out to be an issue with OpenSSH on Windows and an issue was raised on Github.

    https://github.com/PowerShell/Win32-OpenSSH/issues/310