A SSH tunnel consists of an encrypted tunnel created through a SSH protocol connection. A SSH tunnel can be used to transfer unencrypted traffic over a network through an encrypted channel. For example we can use a ssh tunnel to securely transfer files between a FTP server and a client even though the FTP protocol itself is not encrypted. SSH tunnels also provide a means to bypass firewalls that prohibits or filter certain internet services. For example an organization will block certain sites using their proxy filter. But users may not wish to have their web traffic monitored or blocked by the organization proxy filter. If users can connect to an external SSH server, they can create a SSH tunnel to forward a given port on their local machine to port 80 on remote web-server via the external SSH server
Connecting to the internet from Wi-Fi hotspots, at work, or anywhere else away from home, exposes your data to unnecessary risks. You can easily configure your router to support a secure tunnel and shield your remote browser traffic
What is and Why Set Up a Secure Tunnel?
You might be curious why you would even want to set up a secure tunnel from your devices to your home router and what benefits you would reap from such a project. Let’s lay out a couple different scenarios that involve you using the internet to illustrate the benefits of secure tunneling.
Scenario one: You’re at a coffee shop using your laptop to browse the internet through their free Wi-Fi connection. Data leaves your Wi-Fi modem, travels through the air unencrypted to the Wi-Fi node in the coffee shop, and then is passed on to the greater internet. During the transmission from your computer to the greater internet your data is wide open. Anyone with a Wi-Fi device in the area can sniff your data. It’s so painfully easy that a motivated 12 year old with a laptop and a copy of Firesheep could snatch up your credentials for all manner of things. It’s as though you’re in a room filled with English-only speakers, talking into a phone speaking Mandarin Chinese. The moment somebody who speaks Mandarin Chinese comes in (the Wi-Fi sniffer) your pseudo-privacy is shattered.
Scenario two: You’re at a coffee shop using your laptop to browse the internet through their free Wi-Fi connection again. This time you’ve established an encrypted tunnel between your laptop and your home router using SSH. Your traffic is routed through this tunnel directly from your laptop to your home router which is functioning as a proxy server. This pipeline is impenetrable to Wi-Fi sniffers who would see nothing but a garbled stream of encrypted data. No matter how shifty the establishment, how insecure the Wi-Fi connection, your data stays in the encrypted tunnel and only leaves it once it has reached your home internet connection and exits to the greater internet.
In scenario one you’re surfing wide open; in scenario two you can login to your bank or other private web sites with the same confidence you would from your home computer.
Although we used Wi-Fi in our example you could use the SSH tunnel to secure a hardline connection to, say, launch a browser on a remote network and punch a hole through the firewall to surf as freely as you would on your home connection.
Sounds good doesn’t it? It’s incredibly easy to set up so there’s no time like the present—you can have your SSH tunnel up and running within the hour.
Down and Dirty
apt-get install openssh-server
Once you have installed an OpenSSH server, you will need to configure it by editing the sshd_config file in the /etc/ssh directory.
sshd_config is the configuration file for the OpenSSH server.
ssh_config is the configuration file for the OpenSSH client.
Make sure not to get them mixed up.
First, make a backup of your sshd_config file by copying it to your home directory, or by making a read-only copy in /etc/ssh by doing:
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.factory-defaults
sudo chmod a-w /etc/ssh/sshd_config.factory-defaults
Creating a read-only backup in /etc/ssh means you’ll always be able to find a known-good configuration when you need it.
Once you’ve backed up your sshd_config file, you can make changes with any text editor (gksudo gedit /etc/ssh/sshd_config runs the standard text editor). Once you’ve made your changes, you can apply them by saving the file then doing:
sudo restart ssh
Configuring OpenSSH means striking a balance between security and ease-of-use. Ubuntu’s default configuration tries to be as secure as possible without making it impossible to use in common use cases.
O P T I O N A L
Because a lot of people with SSH servers use weak passwords, many online attackers will look for an SSH server, then start guessing passwords at random. An attacker can try thousands of passwords in an hour, and guess even the strongest password given enough time. The recommended solution is to use SSH keys instead of passwords
If you disable password authentication, it will only be possible to connect from computers you have specifically approved. This massively improves your security, but makes it impossible for you to connect to your own computer from a friend’s PC without pre-approving the PC, or from your own laptop when you accidentally delete your key.
It’s recommended to disable password authentication unless you have a specific reason not to.
To disable password authentication, look for the following line in your sshd_config file:
replace it with a line that looks like this:
Once you have saved the file and restarted your SSH server, you shouldn’t even be asked for a password when you log in.
Key-Based SSH Logins
Key-based authentication is the most secure of several modes of authentication usable with OpenSSH, such as plain password (the default with Ubuntu) and Kerberos tickets. Key-based authentication has several advantages over password authentication, for example the key values are significantly more difficult to brute-force, or guess than plain passwords, provided an ample key length. Other authentication methods are only used in very specific situations.
SSH can use either “RSA” (Rivest-Shamir-Adleman) or “DSA” (“Digital Signature Algorithm”) keys. Both of these were considered state-of-the-art algorithms when SSH was invented, but DSA has come to be seen as less secure in recent years. RSA is the only recommended choice for new keys, so this guide uses “RSA key” and “SSH key” interchangeably.
Key-based authentication uses two keys, one “public” key that anyone is allowed to see, and another “private” key that only the owner is allowed to see. To securely communicate using key-based authentication, you need to create a public key for the computer you’re logging in from, and securely transmit it to the computer you’re logging in to. Wikipedia has a good explanation of the theory
Using key based logins with ssh is generally considered more secure than using plain password logins. This section of the guide will explain the process of generating a set of public/private RSA keys, and using them for logging into your Ubuntu computer(s) via OpenSSH.
Generating RSA Keys
The first step involves creating a set of RSA keys for use in authentication.
This should be done on the client.
To create your public and private SSH keys on the command-line:
chmod 700 ~/.ssh
ssh-keygen -t rsa
You will be prompted for a location to save the keys, and a passphrase for the keys. This passphrase will protect your private key while it’s stored on the hard drive and be required to use the keys every time you need to login to a key-based system:
Generating public/private rsa key pair.
Enter file in which to save the key (/home/b/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/b/.ssh/id_rsa.
Your public key has been saved in /home/b/.ssh/id_rsa.pub.
Your public key is now available as .ssh/id_rsa.pub in your home folder.
Congratulations! You now have a set of keys. Now it’s time to make your systems allow you to login with them
Choosing a good passphrase
Just like with physical keys, you need to change all your locks if your RSA key is stolen. Otherwise, your thief will be able to get access to all your stuff.
An SSH key passphrase is a secondary form of security that gives you a little time when your keys are stolen. If your RSA key has a strong passphrase, it might take your attacker a few hours to guess by brute force. That extra time should be enough to log in to any computers you have an account on, delete your old key from the .ssh/authorized_keys file, and add a new key.
Your SSH key passphrase is only used to protect your private key from thieves. It’s never transmitted over the Internet, and the strength of your key has nothing to do with the strength of your passphrase.
You have to choose for yourself whether to use a passphrase with your RSA key. Ultimately, it’s a choice between cursing the difficulty every time you have to type it in, or cursing your glibness when someone logs in to all your accounts and changes your password so you can’t get in any more.
If you choose to use a passphrase, pick something strong and write it down on a piece of paper that you keep in a safe place. If you choose not to use a password, just press the return key without typing a password – you’ll never be asked for one again.
Key Encryption Level
Note: The default is a 2048 bit key. You can increase this to 4096 bits with the -b flag (Increasing the bits makes it harder to crack the key by brute force methods).
ssh-keygen -t rsa -b 4096
The main problem with public key authentication is that you need a secure way of getting the public key onto a computer before you can log in with it. If you will only ever use an SSH key to log in to your own computer from a few other computers (such as logging in to your PC from your laptop), you should copy your SSH keys over on a memory stick, and disable password authentication altogether. If you would like to log in from other computers from time to time (such as a friend’s PC), make sure you have a strong password.
Transfer Client Key to Host
The key you need to transfer to the host is the public one. If you can log in to a computer over SSH using a password, you can transfer your RSA key by doing the following from your own computer:
Where <username> and <host> should be replaced by your username and the name of the computer you’re transferring your key to.
Due to this bug, you cannot specify a port other than the standard port 22. You can work around this by issuing the command like this: ssh-copy-id "<username>@<host> -p <port_nr>". If you are using the standard port 22, you can ignore this tip.
Another alternative is to copy the public key file to the server and concatenate it onto the authorized_keys file manually. It is wise to back that up first:
cp authorized_keys authorized_keys_Backup
cat id_rsa.pub >> authorized_keys
You can make sure this worked by doing:
You should be prompted for the passphrase for your key:
Enter passphrase for key ‘/home/<user>/.ssh/id_rsa’:
Enter your passphrase, and provided host is configured to allow key-based logins, you should then be logged in as usual.
Encrypted Home Directory
If you have an encrypted home directory, SSH cannot access your authorized_keys file because it is inside your encrypted home directory and won’t be available until after you are authenticated. Therefore, SSH will default to password authentication.
To solve this, create a folder outside your home named /etc/ssh/<username> (replace “<username>” with your actual username). This directory should have 755 permissions and be owned by the user. Move the authorized_keys file into it. The authorized_keys file should have 644 permissions and be owned by the user.
Then edit your /etc/ssh/sshd_config and add:
Finally, restart ssh with:
sudo service ssh restart
The next time you connect with SSH you should not have to enter your password.
If you are not prompted for the passphrase, and instead get just the
prompt as usual with password logins, then read on. There are a few things which could prevent this from working as easily as demonstrated above. On default Ubuntu installs however, the above examples should work. If not, then check the following condition, as it is the most frequent cause:
On the host computer, ensure that the /etc/ssh/sshd_config contains the following lines, and that they are uncommented;
If not, add them, or uncomment them, restart OpenSSH, and try logging in again. If you get the passphrase prompt now, then congratulations, you’re logging in with a key!
Permission denied (publickey)
If you’re sure you’ve correctly configured sshd_config, copied your ID, and have your private key in the .ssh directory, and still getting this error:
Permission denied (publickey).
Chances are, your /home/<user> or ~/.ssh/authorized_keys permissions are too open by OpenSSH standards. You can get rid of this problem by issuing the following commands:
chmod go-w ~/
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
Error: Agent admitted failure to sign using the key.
This error occurs when the ssh-agent on the client is not yet managing the key. Issue the following commands to fix:
This command should be entered after you have copied your public key to the host computer.
Debugging and sorting out further problems
The permissions of files and folders is crucial to this working. You can get debugging information from both the client and server.
if you think you have set it up correctly , yet still get asked for the password, try starting the server with debugging output to the terminal.
sudo /usr/sbin/sshd -d
To connect and send information to the client terminal
ssh -v ( or -vv) username@host's
Where to From Here?
No matter how your public key was generated, you can add it to your Ubuntu system by opening the file .ssh/authorized_keys in your favourite text editor and adding the key to the bottom of the file. You can also limit the SSH features that the key can use, such as disallowing port-forwarding or only allowing a specific command to be run. This is done by adding “options” before the SSH key, on the same line in theauthorized_keys file. For example, if you maintain a CVS repository, you could add a line like this:
command="/usr/bin/cvs server",no-agent-forwarding,no-port-forwarding,no-X11-forwarding,no-user-rc ssh-dss <string of nonsense>...
When the user with the specified key logged in, the server would automatically run /usr/bin/cvs server, ignoring any requests from the client to run another command such as a shell. For more information, see the sshd man page
END OF O P T I O N A L
Specify Which Accounts Can Use SSH
You can explicitly allow or deny access for certain users or groups. For example, if you have a family PC where most people have weak passwords, you might want to allow SSH access just for yourself.
Allowing or denying SSH access for specific users can significantly improve your security if users with poor security practices don’t need SSH access.
It’s recommended to specify which accounts can use SSH if only a few users want (not) to use SSH.
To allow only the users user1 and user2 to connect to your computer, add the following line to the bottom of the sshd_config file:
AllowUsers user1 user2
To allow everyone except the users user3 and user4 to connect to your computer, add the following line to the bottom of the sshd_configfile:
DenyUsers user3 user4
It’s possible to create very complex rules about who can use SSH – you can allow or deny specific groups of users, or users whose names match a specific pattern, or who are logging in from a specific location.
It is customary to switch:
Log More Information
By default, the OpenSSH server logs to the AUTH facility of syslog, at the INFO level. If you want to record more information – such as failed login attempts – you should increase the logging level to VERBOSE.
It’s recommended to log more information if you’re curious about malicious SSH traffic.
To increase the level, find the following line in your sshd_config:
and change it to this:
Now all the details of ssh login attempts will be saved in your /var/log/auth.log file
By default, you can tunnel network connections through an SSH session. For example, you could connect over the Internet to your PC, tunnel a remote desktop connection, and access your desktop. This is known as “port forwarding”.
By default, you can also tunnel specific graphical applications through an SSH session. For example, you could connect over the Internet to your PC and run nautilus "file://$HOME" to see your PC’s home folder. This is known as “X11 forwarding”.
So, What is SSH Tunnelling ?
SSH tunnels can be created in several ways using different kinds of port forwarding mechanisms. Ports can be forwarded in three ways.
- Local port forwarding
- Remote port forwarding
- Dynamic port forwarding
Tunnelling with Local port forwarding
Let’s say that yahoo.com is being blocked using a proxy filter in the company. A SSH tunnel can be used to bypass this restriction. Let’s name my machine at the university as ‘work’ and a home machine as ‘home’. ‘home’ needs to have a public IP for this to work. And we are running a SSH server on the home machine. Following diagram illustrates the scenario.
To create the SSH tunnel execute following from ‘work’ machine.
ssh -L 9001:yahoo.com:80 home
The ‘L’ switch indicates that a local port forward is need to be created. The switch syntax is as follows.
Now the SSH client at ‘work’ will connect to SSH server running at ‘home’ (usually running at port 22) binding port 9001 of ‘work’ to listen for local requests thus creating a SSH tunnel between ‘home’ and ’work’. At the ‘home’ end it will create a connection to ‘yahoo.com’ at port 80. So ‘work’ doesn’t need to know how to connect to yahoo.com. Only ‘home’ needs to worry about that. The channel between ‘work’ and ‘home’ will be encrypted while the connection between ‘home’ and ‘yahoo.com’ will be unencrypted.
Now it is possible to browse yahoo.com by visiting http://localhost:9001
in the web browser at ‘work’ computer. The ‘home’ computer will act as a gateway which would accept requests from ‘work’ machine and fetch data and tunnelling it back. So the syntax of the full command would be as follows.
ssh -L <local-port-to-listen>:<remote-host>:<remote-port> <gateway>
The image below describes the scenario.
Here the ‘host’ to ‘yahoo.com’ connection is only made when browser makes the request not at the tunnel setup time. It is also possible to specify a port in the ‘home’ computer itself instead of connecting to an external host. This is useful if I were to set up a VNC session between ‘work’ and ‘home’. Then the command line would be as follows.
ssh -L 5900:localhost:5900 home (Executed from 'work')
So here what does localhost refer to? Is it the ‘work’ since the command line is executed from ‘work’? Turns out that it is not. As explained earlier is relative not the machine from where the tunnel is initiated. So this will make a connection to port 5900 of the ‘home’ computer where the VNC client would be listening in.
The created tunnel can be used to transfer all kinds of data not limited to web browsing sessions. We can also tunnel SSH sessions from this as well. Let’s assume there is another computer (‘banned’) to which we need to SSH from work but the SSH access is being blocked. It is possible to tunnel a SSH session to this host using a local port forward. The setup would look like this.
As can be seen now the transferred data between ‘work’ and ‘banned’ are encrypted end to end. For this we need to create a local port forward as follows.
ssh -L 9001:banned:22 home
Now we need to create a SSH session to local port 9001 from where the session will get tunneled to ‘banned’ via ‘home’ computer.
ssh -p 9001 localhost
With that let’s move on to next type of SSH tunnelling method, reverse tunnelling.
Reverse Tunnelling with remote port forwarding
Let’s say it is required to connect to an internal work website from home.
The work firewall is blocking all incoming traffic. How can we connect from ‘home’ to internal network so that we can browse the internal site? A VPN setup is a good candidate here. However for this example let’s assume we don’t have this facility. Enter SSH reverse tunnelling..
As in the earlier case we will initiate the tunnel from ‘work’ computer behind the firewall. This is possible since only incoming traffic is blocked and outgoing traffic is allowed. However instead of the earlier case the client will now be at the ‘home’ computer. Instead of -L option we now define -R which specifies a reverse tunnel need to be created.
ssh -R 9001:intra-site.com:80 home (Executed from 'work')
Once executed the SSH client at ‘work’ will connect to SSH server running at home creating a SSH channel. Then the server will bind port 9001 on ‘home’ machine to listen for incoming requests which would subsequently be routed through the created SSH channel between ‘home’ and ‘work’. Now it’s possible to browse the internal site by visiting http://localhost:9001 in ‘home’ web browser. The ‘work’ will then create a connection to intra-site and relay back the response to ‘home’ via the created SSH channel.
As nice all of these would be still you need to create another tunnel if you need to connect to another site in both cases. Wouldn’t it be nice if it is possible to proxy traffic to any site using the SSH channel created? That’s what dynamic port forwarding is all about.
Dynamic Port Forwarding
Dynamic port forwarding allows to configure one local port for tunnelling data to all remote destinations. However to utilize this the client application connecting to local port should send their traffic using the SOCKS protocol. At the client side of the tunnel a SOCKS proxy would be created and the application (eg. browser) uses the SOCKS protocol to specify where the traffic should be sent when it leaves the other end of the ssh tunnel.
ssh -D 9001 home (Executed from 'work')
Here SSH will create a SOCKS proxy listening in for connections at local port 9001 and upon receiving a request would route the traffic via SSH channel created between ‘work’ and ‘home’. For this it is required to configure the browser to point to the SOCKS proxy at port 9001 at localhost.
To setup Firefox to use this tunnel to navigate the internet, we go to Edit>Preferences>Advance in the Network tab, we click on the ‘Settings…’ button. There we select “Manual Proxy Configuration” and leave everything blank, except for the field “SOCKS Host”, where we write down the ‘127.0.0.1’ and the port ‘9001’, that is the configuration of our tunnel. We select the SOCKS5 option and save our configuration.
As it stands, we now can use Firefox to navigate the web and our traffic will be forwarded through our tunnel, we can check that we are truly making use of our server, navigating a couple of pages and then kill our tunnel, with will result in broken browser connection With the current settings, even though our traffic is encrypted, our DNS request are still not being sent through our tunnel, to change this in firefox, we write in the address bar about:config, look for the key network.proxy.socks_remote_dns and change it to true.
Our SSH Tunnel, can be use with any program that can use a SOCKS proxy, such as Skype, messengers, etc.
Another Interesting application would be using someting like SSHTunnel which will tunnel your phone browser while you are using are untrusted wireless network
At the end I’ll leave you with a command to test and figure out for yourself
- ssh -c arcfour,blowfish-cbc -YCv user@host
Don’t forget to check man ssh