Search code examples
c#.netsshsftpwinscp

How to perform "double hop" via SFTP/SSH in .NET?


In my scenario i am trying to go from Local App Server -> Middle Server (DMZ) -> Client Server

I need to move files from the Local App Server to the Client Server and back.

So my question is what is the most widely used standard for doing this?

I am currently using WinSCP to connect to the Middle Server via SFTP, and then invoking a command on the Middle Server to download and upload files to the Client Server. I'm not really a fan of this, as i feel like its prone to error as i am manually entering a command, rather than using the WinSCP's library to upload and download. It also leaves me stuck when i try to list all files on the Client Server with a command, as the function returns void

I have looked at SSH.NET which seems like its more widely used, however i cant see any real way of performing a "double hop" with that library either.


Solution

  • With WinSCP .NET assembly, it's easy:

    SessionOptions sessionOptions = new SessionOptions
    {
        Protocol = Protocol.Sftp,
        HostName = "example.com",
        UserName = "username",
        Password = "password",
        SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx...=",
    };
    
    sessionOptions.AddRawSettings("Tunnel", "on");
    sessionOptions.AddRawSettings("TunnelHostName", "tunnel.example.com");
    sessionOptions.AddRawSettings("TunnelUserName", "username");
    sessionOptions.AddRawSettings("TunnelPasswordPlain", "password");
    sessionOptions.AddRawSettings("TunnelHostKey", "ssh-rsa 2048 xxxxxxxxxxx...=");
    
    using (Session session = new Session())
    {
        session.Open(sessionOptions);
    
        // Your code
    }
    

    WinSCP GUI can generate a code template to connect through tunnel, like the one above, for you (except for the TunnelHostKey).


    With SSH.NET you can implement a port forwarding explicitly by:

    • opening connection to the "Middle Server";
    • creating a forwarded port;
    • opening a second connection to the forwarded port.

    For some example, see Connection to MySQL from .NET using SSH.NET Library.


    Another hackish solution is to execute ssh on the "Middle Server" to facilitate the second "hop".