Click here to Skip to main content
15,887,485 members
Articles / Programming Languages / C#
Article

sharpSsh - A Secure Shell (SSH) library for .NET

Rate me:
Please Sign up or sign in to vote.
4.91/5 (125 votes)
29 Oct 2005BSD5 min read 10.4M   87.7K   261   1.1K
A C# implementation of the SSH2 protocol.

Image 1

Introduction

Recently there was a need to connect to a SSH server from my C# code. I needed to perform a simple task: login to a remote Linux device, execute a command and read the response. I knew there were a number of free Java SSH libraries out there and I hoped to find a free .NET one that will allow me to do just that, but all I could find were commercial components. After experimenting with an open source Java SSH library called JSch I decided to try and port it to C# just for the sake of exercise. The result is the attached sharpSsh library and this article which explains how to use it.

Background

SSH (Secure Shell) is a protocol to log into another computer over a network, to execute commands in a remote machine, and to move files from one machine to another. It provides strong authentication and secure communications over unsecured channels. The JSch library is a pure Java implementation of the SSH2 protocol suite; It contains many features such as port forwarding, X11 forwarding, secure file transfer and supports numerous cipher and MAC algorithms. JSch is licensed under BSD style license.

My C# version is not a full port of JSch. I ported only the minimal required features in order to complete my simple task. The following list summarizes the supported features of the library:

  • Key exchange: diffie-hellman-group-exchange-sha1, diffie-hellman-group1-sha1.
  • Cipher: 3des-cbc
  • MAC: hmac-md5
  • Host key type: ssh-rsa and partial ssh-dss.
  • Userauth: password, publickey (RSA)
  • Generating RSA key pairs.
  • Changing the passphrase for a private key.
  • SCP and SFTP

Please check my homepage for the latest version and feature list of SharpSSH.

Using the code

Let me begin with a small disclaimer. The code isn't fully tested, and I cannot guarantee any level of performance, security or quality. The purpose of this library and article is to educate myself (and maybe you) about the SSH protocol and the differences between C# and Java.

In order to provide the simplest API for SSH communication, I created two wrapper classes under the Tamir.SharpSsh namespace that encapsulates JSch's internal structures:

  • SshStream - A stream based class for reading and writing over the SSH channel.
  • Scp - A class for handling file transfers over the SSH channel.

Reading and writing data over the SSH channel

The SshStream class makes reading and writing of data over an SSH channel as easy as any I/O read/write task. Its constructor gets three parameters: The remote hostname or IP address, a username and a password. It connects to the remote server as soon as it is constructed.

C#
//Create a new SSH stream
SshStream ssh = new SshStream("remoteHost", "username", "password");

//..The SshStream has successfully established the connection.

Now, we can set some properties:

C#
//Set the end of response matcher character
ssh.Prompt = "#";
//Remove terminal emulation characters
ssh.RemoveTerminalEmulationCharacters = true;

The Prompt property is a string that matches the end of a response. Setting this property is useful when using the ReadResponse() method which keeps reading and buffering data from the SSH channel until the Prompt string is matched in the response, only then will it return the result string. For example, a Linux shell prompt usually ends with '#' or '$', so after executing a command it will be useful to match these characters to detect the end of the command response (this property actually gets any regular expression pattern and matches it with the response, so it's possible to match more complex patterns such as "\[[^@]*@[^]]*]#\s" which matches the bash shell prompt [user@host dir]# of a Linux host). The default value of the Prompt property is "\n", which simply tells the ReadResponse() method to return one line of response.

The response string will typically contain escape sequence characters which are terminal emulation signals that instruct the connected SSH client how to display the response. However, if we are only interested in the 'clean' response content we can omit these characters by setting the RemoveTerminalEmulationCharacters property to true.

Now, reading and writing to/from the SSH stream will be done as follows:

C#
//Writing to the SSH channel
ssh.Write( command );

//Reading from the SSH channel
string response = ssh.ReadResponse();

Of course, it's still possible to use the SshStream's standard Read/Write I/O methods available in the System.IO.Stream API.

Transferring files using SCP

Transferring files to and from an SSH server is pretty straightforward with the Scp class. The following snippet demonstrates how it's done:

C#
//Create a new SCP instance
Scp scp = new Scp();

//Copy a file from local machine to remote SSH server
scp.To("C:\fileName", "remoteHost", 
             "/pub/fileName", "username", "password");

//Copy a file from remote SSH server to local machine
scp.From("remoteHost", "/pub/fileName", 
               "username", "password", "C:\fileName");

The Scp class also has some events for tracking the progress of file transfer:

  • Scp.OnConnecting - Triggered on SSH connection initialization.
  • Scp.OnStart - Triggered on file transfer start.
  • Scp.OnEnd - Triggered on file transfer end.
  • Scp.OnProgress - Triggered on file transfer progress update (The ProgressUpdateInterval property can be set to modify the progress update interval time in milliseconds).

Running the examples

The demo project is a simple console application demonstrating the use of SshStream and Scp classes. It asks the user for the hostname, username and password for a remote SSH server and shows examples of a simple SSH session, and file transfers to/from a remote SSH machine.

Here is a screen shot of an SSH connection to a Linux shell:

Image 2

And here is a file transfer from a Linux machine to my PC using SCP:

Image 3

In the demo project zip file you will also find an examples directory containing some classes showing the use of the original JSch API. These examples were translated directly from the Java examples posted with the original JSch library and show the use of advanced options such as public key authentication, known hosts files, key generation, SFTP and others.

References

  • SharpSSH Homepage - New versions and bug fixes will be posted here, so please check this page for the latest updates.
  • JSch - JSch is a pure Java implementation of the SSH2 protocol suite. My C# library is based on this project.
  • Mentalis.org - Mentalis.org contains some great .NET projects for security and networking. I used their HMAC and Diffie Hellman classes as part of my SSH implementation.
  • Granados - A full featured open source SSH1 and SSH2 implementation in C#. I found this project after finishing my own library.

History

  • 2005-Oct-16
    • Initial version.
  • 2005-Oct-22
    • Fixed two bugs in Scp class.
  • 2005-Oct-29
    • Added the option to use DSA signatures ('ssh-dss') for authenticating the server during the key-exchange phase.
  • 2005-Oct-29
    • All future updates will be posted in my homepage.

License

This article, along with any associated source code and files, is licensed under The BSD License


Written By
Software Developer
Israel Israel
Works as a Network Engineer for a leading networking company.

Comments and Discussions

 
QuestionSshShell and ViaHTTP Proxy - is it implemented? Pin
Darked1-Apr-08 0:46
Darked1-Apr-08 0:46 
GeneralExpect Timeout Pin
Member 16326725-Mar-08 4:45
Member 16326725-Mar-08 4:45 
GeneralSCP Pin
Mike Rabtok25-Feb-08 7:56
Mike Rabtok25-Feb-08 7:56 
Generaltrouble in virtualbox Pin
esa18-Feb-08 23:29
esa18-Feb-08 23:29 
Questionhow to turn on ignore permision Pin
nndq2910198318-Feb-08 17:43
nndq2910198318-Feb-08 17:43 
GeneralSession wont disconnect Pin
tcaduto9-Feb-08 15:51
tcaduto9-Feb-08 15:51 
GeneralRe: Session wont disconnect Pin
Ross Korsky6-Mar-08 5:36
Ross Korsky6-Mar-08 5:36 
GeneralRe: Session wont disconnect Pin
pbarrette12-Nov-08 21:38
pbarrette12-Nov-08 21:38 
The problem seems to be higher up the food chain than JStream. What I have seen is this:

When you call the close method, that thread sends Message-ID 97 to the remote server. Then it wanders off to the Session.disconnect() method. In the mean time, your (separate) connection thread receives a reply back from the server containing Message-ID 97. The connection thread (which was instantiated using the Session.run() method) jumps through a bunch of cases until it hits SSH_MSG_CHANNEL_CLOSE. That's where it gets tricky, because suddenly it wants to close the channel and call on Session.disconnect() as well.

So you can end up in a condition where both the main thread and the connection thread are contending for the disconnection, and it's just a matter of dumb luck and timing as to whether the session gets disconnected, or the main thread invalidates the channel that the connection thread is reading from before the channel_close message is returned by the server.

If the latter happens, and it often seems to, the connection thread is stuck reading from a stream whose underlying connection variables have been invalidated by the main thread. When that happens, the connection thread will keep the connection open, but there is no way for it to read data out of that stream, so the stream will be kept open until the server times out from inactivity or the client process is forcibly terminated.

My current fix is to put a lock around the entire Session.disconnect() method. That way the main thread can't go about killing off the session variables while the connection thread is trying to either read from the stream or kill itself off. With the entire method locked, my testing shows that the connection thread reaches Session.disconnect before the main thread about 70% of the time. The other 30%, it is blocked by the main thread until the connection is properly closed. Either way, my sessions now exit 100% of the time.
GeneralRe: Session wont disconnect Pin
TheSimon25-Jul-10 3:28
TheSimon25-Jul-10 3:28 
QuestionHow about using Mono.Security instead of Mentalis security dll? Pin
tcaduto9-Feb-08 15:49
tcaduto9-Feb-08 15:49 
GeneralNew Developer Pin
Clemdogu9-Feb-08 4:42
Clemdogu9-Feb-08 4:42 
GeneralSharpSSH 2.0 Pin
m1ke c24-Jan-08 21:32
m1ke c24-Jan-08 21:32 
GeneralRe: SharpSSH 2.0 Pin
Clemdogu9-Feb-08 5:02
Clemdogu9-Feb-08 5:02 
GeneralA friendly warning... PinPopular
DeepT16-Jan-08 11:55
DeepT16-Jan-08 11:55 
GeneralRe: A friendly warning... Pin
shawn_liang24-Nov-08 21:36
shawn_liang24-Nov-08 21:36 
GeneralRe: A friendly warning... Pin
dandy726-Apr-11 8:29
dandy726-Apr-11 8:29 
GeneralDistinguish Files from directories in Sftp Pin
m1ke c16-Jan-08 0:22
m1ke c16-Jan-08 0:22 
GeneralRe: Distinguish Files from directories in Sftp Pin
Clemdogu9-Feb-08 5:13
Clemdogu9-Feb-08 5:13 
GeneralRe: Distinguish Files from directories in Sftp Pin
m1ke c13-Feb-08 0:50
m1ke c13-Feb-08 0:50 
AnswerRe: Distinguish Files from directories in Sftp Pin
Edw14-Aug-08 6:45
Edw14-Aug-08 6:45 
GeneralSystem.NullReferenceException on oSFTP.Close(); [modified] Pin
m1ke c16-Jan-08 0:03
m1ke c16-Jan-08 0:03 
GeneralRe: System.NullReferenceException on oSFTP.Close(); Pin
Clemdogu9-Feb-08 5:16
Clemdogu9-Feb-08 5:16 
GeneralChecking for connection Pin
websmurf12310-Jan-08 23:51
websmurf12310-Jan-08 23:51 
QuestionCisco SSH - invalid server's version string Pin
pavlosd7-Jan-08 21:06
pavlosd7-Jan-08 21:06 
GeneralRe: Cisco SSH - invalid server's version string Pin
Mr Nutts22-Feb-08 0:29
Mr Nutts22-Feb-08 0:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.