domain registration

SSH tunneling in your application

by terhunetech on April 16, 2011


This article is dedicated towards the job of securing MySQL client-server connection using performance supplied by the Secure Shell (SSH) protocol. To be exact, the SSH tunneling idea is used. We’ll evaluation the actions needed to build secure MySQL consumer apps and implement a sample 1 ourselves.

MySQL traffic is not the only type of information that can be tunneled by the Safe Shell. SSH can be utilized to safe any application-layer TCP-based protocol, such as HTTP, SMTP and POP3. If your application needs to safe this type of protocol by tunneling it through a protected SSH connection, this article will probably be helpful for you.

Track record

Let’s envision that we are creating an enterprise application that requirements to deliver requests to a number of SQL servers all over the world and get responses from them (let us envision that it is a super-powerful financial institution system that stores info about millions of accounts).

All the information in between the application and SQL servers are transferred via the internet “as is”. As most protocols utilized by SQL servers do not provide data integrity and confidentiality (and those that do, do it in a really nontransparent way), all of the transferred requests and responses may (and be sure, they’ll!) turn out to be visible to a passive adversary. An energetic adversary can trigger much much more severe problems – he can alter the information and no one will detect it!

SSH (Secure Shell) is a protocol that might assist in solving this problem. One of its outstanding functions is its ability to tunnel different kinds of connections through a single, assured and integrity-protected connection.

Now you don’t need to be concerned about securing the information transferred more than the web – SSH will deal with this for you personally. In specific, SSH will take care of the following safety elements:

Strong information encryption according to the latest industry-standard algorithms (AES, Twofish)
Authentication of each consumer and server computer systems
Data integrity protection
Stability regarding various sorts of network attacks
Compression of the information becoming tunneled
Complete independence of the running system and network specifics

Tunneling (or forwarding) functions within the following way:

SSH client opens a listening port on some local network interface and tells the SSH server that he wishes to ahead all connections accepted on this port to some remote host.
When another connection is accepted on the listening port, the SSH client informs the SSH server about this reality plus they together set up a logical tunnel for it. In the same time, the SSH server establishes a new TCP connection to the remote host agreed upon in stage 1.
The SSH client encrypts all the information it receives from the accepted connection and sends it to the SSH server. The SSH server decrypts the data received from the SSH client and sends it to the remote host.

Please be aware, the SSH consumer acts as being a TCP server for that connections it accepts, and the SSH server acts as a TCP consumer for the connections it establishes towards the remote host.

Just one SSH connection can tunnel as many application layer connections as needed. This indicates that you simply can defend your server by moving all the listening ports (e.g., database and application server ports) to a nearby network, leaving only the SSH port open. It is a lot simpler to look after just one port, rather than a dozen different listening ports.

Into the Fire!

Let us develop a little software that illustrates the use of SSH forwarding capabilities. We’ll think about an essential task of securing a connection in between a MySQL client application along with a MySQL server. Imagine that we need to obtain information from the database server, which is located a thousand miles absent from us, inside a safe way.

SecureMySQLClient will be the software we are planning to put into action. It includes the following modules:

SSH client-side module with forwarding abilities
MySQL client-side module
User interface for configuring software settings and displaying query outcomes.

The SSH server runs in a remote network and is visible from the web. The database (MySQL) server runs within the same network as the SSH server and might not be visible from the web.

The process of performing secure information exchange between SecureMySQLClient and the Database server goes as follows:

The SSH consumer module negotiates a safe connection to the SSH server and establishes forwarding from some nearby port to the remote MySQL server.
The MySQL consumer module connects towards the listening port opened by the SSH consumer module.
The SSH client and server setup a logical tunnel for that accepted connection.
The MySQL client sends Select towards the port opened through the SSH client module, which encrypts it and sends it towards the SSH server. The SSH server decrypts the request and sends it to the MySQL server.
The SSH server gets a response through the MySQL server, encrypts it and sends it back again towards the SSH consumer, which decrypts it and passes it towards the MySQL consumer module.

Appears too complicated? Implementing this really is easier than you believe.So, let us go and do it.

We will need the following goods set up on the pc prior to creating the software:

Microsoft Visual Studio .Net 2003, 2005 or 2008.
EldoS SecureBlackbox (.Net edition). Could be downloaded from

MySQL .Internet Connector. Can be downloaded from

Let’s now open Microsoft Visual Studio .Net (we will use the 2005 version) and attempt to develop such an software from scratch.

After the GUI design continues to be completed, we can go on with the business logic code by itself. First, including references to the following assemblies to our undertaking:

SecureBlackbox.PKI (only in SecureBlackbox 5. SecureBlackbox 6 does not have this assembly)

SSHForwarding notifies us about certain situations by way of its occasions, so we need to create handlers for a number of them:

OnAuthenticationSuccess – Is fired when the consumer authentication procedure has been completed.
OnAuthenticationFailed – Is fired in the event the client was unable to authenticate using particular authentication technique. In general, this doesn’t imply that the authentication procedure completely failed – the consumer may attempt several authentication methods consequently and 1 of them may succeed.
OnError – Is fired if some protocol error occurs throughout the session. Generally this leads to a connection closure. The exact error can be detected via the error code passed to it.
OnKeyValidate – Is utilized to pass the received server key towards the application. Please be aware that incorrect handling of this event may result in a serious security breach. The handler of this event ought to verify that the passed key corresponds to the remote server (and alert the consumer if it does not). In the event the key is valid, the handler ought to set the Validate parameter to accurate. The sample doesn’t perform key checkup for that sake of simplicity.
OnOpen – Is fired once the SSH connection is established and also the element is prepared to tunnel information. We’ll use the handler of this occasion to kick the MySQL client element.
OnClose – Is fired once the SSH connection is closed.
OnConnectionOpen – Is fired when a new tunnel is created. The corresponding tunneled connection object is passed as parameter.
OnConnectionClose – Is fired when an existing tunnel is closed.

Implementing two core methods, SetupSSHConnection() and RunQuery(). The first 1 initializes the SSHForwarding object and establishes an SSH session towards the remote server by calling its Open() technique, and the 2nd one sends the query towards the MySQL server.

The code of the SetupSSHConnection() technique is pretty easy:

personal void SetupSSHConnection()

// Specifying address and port of SSH server

Forwarding.Address = tbSSHAddress.Text;

Forwarding.Port = Convert.ToInt32(tbSSHPort.Text);

// Setting credentials for authentication on SSH server

Forwarding.Username = tbUsername.Text;

Forwarding.Password = tbPassword.Text;

// Specifying network interface and port number to be opened locally

Forwarding.ForwardedHost = “”;

Forwarding.ForwardedPort = Convert.ToInt32(tbFwdPort.Text);

// Specifying destination host where the server should forward the data to.

// Please be aware, the location should be specified based on

// SSH servers viewpoint. E.g., will stand for

// SSH servers localhost, not SSH customers 1.

Forwarding.DestHost = tbDBAddress.Text;

Forwarding.DestPort = Convert.ToInt32(tbDBPort.Text);

// Opening SSH connection


A little more complex will be the code of the RunQuery() technique (to become exact, the code of RunQueryThreadFunc() method, that is invoked in a separate thread by the RunQuery() method):

private void RunQueryThreadFunc()

MySqlConnection MySQLConnection = new MySqlConnection();

// forming connection string

string connString = “database=” tbDBName.Text “;Connect Timeout=30;user id=” tbDBUsername.Text “; pwd=” tbDBPassword.Text “;”;

if (cbUseTunnelling.Checked)

// specifying local destination if forwarding is enabled

connString = connString “server=; port=” tbFwdPort.Text;


// specifying real MySQL server location if forwarding is not used

connString = connString “server=” tbDBAddress.Text “; port=” tbDBPort.Text;

MySQLConnection.ConnectionString = connString;


// opening MySQL connection

MySqlCommand cmd = new MySqlCommand(tbQuery.Text, MySQLConnection);

Log(“Connecting to MySQL server…”);


Log(“Connection to MySQL server established. Version: ” MySQLConnection.ServerVersion “.”);

// reading query results

MySqlDataReader reader = cmd.ExecuteReader();


for (int i = 0; i < reader.FieldCount; i )


while (reader.Read())

string[] values = new string[reader.FieldCount];

for (int i = 0; i < reader.FieldCount; i )

values[i] = reader.GetString(i);



// closing both MySQL and SSH connections

Log(“Closing MySQL connection”);




catch (Exception ex)

Log(“MySQL connection failed (” ex.Message “)”);

And, that’s all!
But there is 1 more thing I require to draw your attention to. As both SSH and MySQL protocols run in separate threads and access GUI controls from those threads, we need to deal with the GUI access in a special way to prevent a cross-thread issues. I will illustrate this using the example of the Log() technique:

delegate void LogFunc(string S);

personal void Log(string S)

if (lvLog.InvokeRequired)

LogFunc d = new LogFunc(Log);

Invoke(d, new object[] S );


ListViewItem item = new ListViewItem();

item.Text = DateTime.Now.ToShortTimeString();



Finally, the application is completed, and we may attempt it in work. So clicking F5 and specifying the following settings in the text fields from the software form:

SSH server place, username and password used to authenticate to it.
Database server deal with, port, username, password, database name and query. Remember that database server address should be specified as it’s visible from the SSH server.
Turning on the “Use tunneling” checkbox.

Now click the Start button and wait for the query results. If all the parameters have been specified correctly, we should get something like this:

Features and requirements

SSH protocol provides (and SecureBlackbox implements) the following functions:

Strong data encryption utilizing AES, Twofish, Triple DES, Serpent and numerous other symmetric algorithms with key lengths up to 256 bits
Client authentication utilizing 1 or multiple authentication types (password-based, public key-based, X.509 certificate-based, interactive challenge-response authentication)
Server authentication
Strong key exchange according to DH or RSA public key algorithms
Data integrity safety
Compression of tunneled data
Multiplexing a number of tunneled connections via just one SSH connection

SecureBlackbox provides the following functionality as well:

Comprehensive standards-compliant implementation from the SSH protocol (each consumer and server sides)
Support for cryptographic tokens as storage for keys and certificates
Windows system certificate shops support
Professional and fast customer support

SecureBlackbox is available in .Net, VCL and ActiveX editions. This indicates that you simply can use the components in projects implemented in C#, VB.Net, Object Pascal (Delphi and Kylix), FreePascal, VB6 and C languages.

SecureBlackbox (.Net edition) is available for Microsoft .Net Framework 1.1, 2.0, 3.0 and 3.5, and .Internet Compact Framework.

Related posts:

  1. Internet Servers and Firewall software Zones
  2. Career Paths For Comptia A Licensed Technician
  3. Virtualization Software program
  4. Twelve Important Completely New Functions of Office
  5. Microsoft Windows Server 2003 Active Directory and Networking System

Leave a Comment

Previous post:

Next post: