SSH Tunneling - Poor Techie's VPN

"If we see light at the end of the tunnel, it is the light of the oncoming train" ~ Robert Lowell. Oh yes, another good quote. This post is on SSH tunneling, or as I like to call it 'Poor Man's VPN'. Contrary to the sysadmin's popular belief, SSH tunneling actually can be very valuable use for both techies and home users. I say contrary to popular belief because 'reverse tunneling' and tunneling http traffic through SSH can bypass firewalls and content filters. But this article isn't about how to violate your corporate internet use policy, it's about how to create SSH tunnels to make your life just a little bit easier.

Why SSH Tunnels instead of VPN? Well, I actually use both at home. If you have followed any of my posts on jaysonbroughton.com, I use a 3-factor authentication with OpenVPN (user name, certificate & One-Time-Password). But if I want to check on one of my servers from the house via my Android, or a computer where I don't have administrative rights (required of my custom portable OpenVPN client), or even tunnel vnc over ssh to fix a problem on my better half's Linux laptop then SSH is my backup to using VPN.

What I'll cover here today is just your basics: how to create tunnels, what the syntax means, examples of reverse tunnels and why would you use each one of them. I'll briefly go over ssh_config, but a more in-depth post on custom ssh_config's will be at a later date.

So as always, time to dispense with the necessities. I use Debian in a virtual environment so your results may vary. In this case I am using OpenSSH_5.3p1 as a Server and a mix of OpenSSH 5.X ssh clients with my examples. Before I get too far into tunneling I'll say this: If you feel the need to use SSH tunneling via http or reverse SSH tunnels to bypass your corporate firewall make sure you are not violating any of your companies Internet Acceptable Use Policy. This goes without saying, your System Administrators will hunt you down and fry you when they find that you're bypassing the content filter or setting a reverse tunnel in order to tunnel back into a server at work. As a System Administrator myself, I take immense pleasure in locating such individuals. At the very least check with your Network/System Administrator so they are not caught off-guard. LinuxJournal.com and myself are not liable for your blatant violations of your corporate policy :-) With that said, let's have some fun shall we?

Creating an SSH tunnel is actually quite easy. Figuring out what to do with it once you have learned how to create a tunnel might be slightly more difficult. So I'll give you a few use cases to get your mind churning before we get into the details of creating a tunnel. I used to travel quite a bit before kids and with a previous IT job. When I traveled I would end up in the strangest of hotel rooms (you know the kind) with even stranger wireless access points. Do you really want to connect to a wireless access point where the SSID of the hotel is missspelled? Or the airport where there appears to be quite a few open WAP's? When I'm out and about I will tunnel my http traffic through ssh on my rooted droid to my home server. If I'm on my laptop/netbook I'll open an ssh tunnel and route http traffic via socks5 so that all of my traffic is encrypted via ssh then back out to me. I wouldn't trust an open WAP as far as I can throw it. What about anything else in plain text? I've tunneled SMTP traffic on my computer back to the house when certain places I've been block outbound SMTP. Same thing goes with pop3 (of which I've recently changed over to imap-s). Other examples of ssh tunneling include X11 applications tunneled via SSH, and VNC sessions. One of the things I brought up earlier is reverse tunneling, which is..well you got it, the reverse of tunneling. In this case you create a tunnel from a server that is behind a firewall with no SSH servers to an SSH server. Then when you log into that SSH server you can re-establish the connection. What good is that you say? Well if your corporate VPN is down, or requires Windows only VPN clients but you really don't want to lug your laptop home to check on a process running when you get home you can reverse tunnel. In this case you would establish a connection from server X to your home machine. Once you arrived at the house you would re-establish the connection to server X, thus bypassing the firewall/VPN and checking on the process without having to establish a VPN connection. I do this very rarely as I feel this is bad juju, bypassing all the rules setup on my firewall and VPN is usually a last resort.

So there are your examples for SSH tunneling, now let's show you how to get 'er done.

Before we get too carried away on the client side of things there are a few things that need to be edited on the server-side of sshd.config. in /etc/ssh/sshd_config I tend to make the following changes. Before you get too carried away, make a copy of /etc/ssh/sshd_config origional file so you have a reference in case something goes horribly wrong. cp /etc/ssh/sshd_config /etc/ssh/sshd_config.orig


# Force SSH Protocol 2
Protocol 2

#Turn on Privileged Separation for security
UsePrivilegeSeparation yes

#Deny root login
PermitRootLogin no

#Do not allow empty passwords
PermitEmptyPasswords no

# Forward my X Sessions
X11Forwarding yes
X11DisplayOffset 10

# I hate Motd displays
PrintMotd no

# It's alliivee
TCPKeepAlive yes

Don't forget if you do make any changes to your sshd_config file, you need to restart your sshd service in order to make the necessary changes.

All right, lets get into switches. No no, not the switches your 'pa made you pull off the tree branch when you broke ma's favorite vase, SSH switches.

A typical SSH tunnel (without tunneling X) looks like this:


ssh -N -p 22 bob@mylinuxserver.xxx -L 2110:localhost:110
Where:
-N
= Do not execute a remote command
-p 22
= External SSH port 22. I tend to use other external SSH ports to keep skript kiddies from hitting my home SSH server
bob@mylinuxserver.xxx
= username@hostname(or ip address)
-L 2110/localhost/110
= Bind information. Broken down as such: client-port:hostname:hostport - In this example your binding POP3 on the server to your localhost port 2110

So how about some examples?

Forward pop3 and smtp through SSH:


ssh -N -p 2022 bob@mylinuxserver.xxx -L 2110:localhost:110 -L 2025:localhost:25

Forward google Talk through SSH:
(-g Allows remote hosts to connect to local forwarding ports)


ssh -g -p 2022 -N bob@mylinuxserver.xxx 5223:talk.google.com:5223 

Basically anything that is sent in plain-text can be secured via SSH tunneling. Once you have established the tunnel, on the client-side you would configure your settings for the hostname as localhost and the port as your 'client-port', be it 2110,2020,5223, or any other port that you have selected to forward through.

Encrypt your HTTP Traffic

This is another one that goes without saying. If you work for a company that has an 'IT Acceptable Use Policy' check before you do this. This is one that I use whenever I'm out of town or in a place that I don't trust the wifi. On an android I'll use my SSHTunnel app, but if I'm on my laptop I use the following SSH command

ssh -D 5222 bob@mylinuxserver.xxx -N

After you make a connection, then set your browser of choice (or any application that allows proxy) to localhost:5222. This will create a dynamic port forward and tunnel all the application traffic through your SSH server, both encrypting your data and bypassing content filters.

Tunneling X and VNC Sessions

Remember when you added 'X11Forwarding yes' to your sshd_config? This is where tunneling X comes in.

ssh -X -p 2022 bob@mylinuxserver.xxx

You guessed it, -X tunnels X. Remember though, this will tunnel X apps from your remote machine to your client machine running Linux. If you somehow find you're on a Microsoft Windows machine and want to tunnel, just install Cygwin/X (http://x.cygwin.com/) on your guest OS. I haven't personally tried this but from what I understand it gives you an X windowing system that should allow you to run your remote X apps in Windows.

When it comes to tunneling VNC sessions, you have to be careful. If the client you're tunneling from has a vnc server running on say 5900, make sure you don't decide to put your local forwarding port at 5900 or you will just connect right back to yourself. Connecting via VNC is as straight forward as any of the other services:

ssh -p 2022 bob@mylinuxserver.xxx -L 5900:localhost:5900

In this example your connecting to ssh external port 2022 as user bob to mylinuxserver.com. Your local forwarding port is 5900, the port you want to forward is mylinxuserver.com's 5900 vnc. Once you setup the forward you can open up your vnc client of choice and type: localhost:0 at which point you should be connected via vnc to your remote desktop. If you used 5901, then it would be localhost:1, and so on and so forth.

Reverse SSH Tunnels

Oh yes it's time for my favorite part of SSH tunneling. Sure, getting access to a service from behind SSH is nice, so is tunneling your web traffic through encrypted SSH tunnels. But the real surprise comes when you can reverse the tunnel. As I've outlined earlier, a reverse tunnel is when you are behind a firewall that has no SSH server, but need to access it at a later date (be it minutes/hours/days later) but don't want or have the ability to VPN in. You would connect to your SSH server from that machine, then reverse the tunnel by connecting to that open connection. What do I use it for? From time to time against a server, or even with friends and family with reverse VNC sessions via SSH tunnels. In this case they execute a putty saved session that logs into my ssh server as a certain user with no rights. Once the tunnel is established, I can vnc to their machine in order to remote to them. No more having them setup their firewall, or figure out log-me-in, or any of those other websites.

So the steps to create a reverse SSH tunnel are as follows:

  1. From client machine: ssh -R remoteport:localhost:22 username@servername
    ex: ssh -R 2048:localhost:22 bob@mylinuxserver.xxx
  2. From server side (to re-establish the tunnel): ssh -p 2048 localhost

And there you have it, a reverse tunnel. Yay!

For you visual learners out there, daddoo and nerdboy4200 from #linuxjournal got together and whipped up a message sequence chart using mscgen (http://www.mcternan.me.uk/mscgen/). Yes it's opensource, and really awesome. I tried my hand at creating the mscgen chart for this article but what daddoo and nerdboy did in just a few short hours put my little image to shame.

Conclusion

An there you have it, a primer to SSH tunneling. Keep in mind that this was just a primer, what you can do with tunneling is limited only by your imagination. Later on I'll go over setting up ssh_config on the client side so that all of these settings that I have described above can be saved as individual settings on your client-side ssh. But that's a post for another time.

______________________

www.jaysonbroughton.com

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Tunnelig

jogos's picture

a test with SSH, I legaç well, but had a problem with the configuration. Custodian of resolved never changed. News send pro site, already grateful!

SSH

Jhunne's picture

I did a test with SSH, I legaç well, but had a problem with the configuration. Custodian of resolved never changed. News send pro site, already grateful! jogos

Tarih

tarih's picture

No pb with the network admin... It's me.
I'm trying to find a way to remote help a client in another network with a linux server that I manage but a dslbox that I do not manage.

HOW TO COOK SALMON

shairalopez1's picture

I'm using ssh, but I never

alfonserz's picture

I'm using ssh, but I never dug into what you can actually do with it. I'd suggest name "SSH tunelling - _wise_ techie's VPN" :-D
waterproof camera

I use ssh a lot and > vnc spc

decop's picture

I use ssh a lot and > vnc spc serasa. Always use ssh for security. This article has greatly increased my knowledge.

I use ssh a lot and > vnc

decop's picture

I use ssh a lot and > vnc limpar o
nome
. Always use ssh for security. This article has greatly increased my knowledge.

Good One..

satyajeet's picture

Thank you for your post, I’ve got started reading that will right after couple min, I uncovered it worth it to read. Only want to say thanks… linkkei

shh and vnp

Santiado's picture

Thanks to your explanations, I understand how to create a tunnel between Aserver and Bserver without routing anything on ADSL or BDSL.
Aserver > SSH reversible tunnel > Bserver spc serasa

Is there any way I can make this a VNC reversible tunnel so that I can then use VNC from Bwin to Awin

ssh tunneling poor techies vpn

Roy mattias's picture

As stated in the main article, doing this will get you into a heap of trouble if you don't have approval from the right people. Some boss who just wants to do this for whatever reason isn't good enough. Spc serasa When in doubt talk to the network admins. It will get noticed by the network admins when questions about why "the Internet" seems slow. VNP is a powerful tool for virtual machines, but have to be very careful with their security

Awsome Post

Anonymous's picture

I have read all the comments and suggestions posted by the visitors for this article are very good,We will wait for your next article soonly.Thanks!!Buy Backlinks,High Page Rank Backlinks,Buy Backlinks

Thanks for this

Anonymous's picture

There is an option in firefox to make sure name resolving also goes through your proxy, but it is only on the about:config page (network.proxy.socks_remote_dns).
I think you need to restart firefox after doing this modification.
Can I implement this? Ultimate Demon Tool

berzan

Anonymous's picture

Very useful! It’s always interesting to spot what others are tagging.
chat

Nice article, though you are

estani's picture

Nice article, though you are missing a very important fact that can be very confusing at first, the target machine.

The tunnel is not open to the ssh-server but through the ssh-server to a target machine. if the target happen to be localhost, like in your example, then it ends in the same machine, but the article might confuse people into thinking that the target machine is the source one or something.

so from node1:
ssh -L 1111:node3:3333 node2

will tunnel the traffic going into port 1111 from node1 via port 22 of node2 to port 3333 of node 3.

And this:

Basically anything that is sent in plain-text can be secured via SSH tunneling

Makes no sense. It's a TCP connection, you can send any stream, does not have to be text oriented. (even your X server explanation goes against this)

Besides that, nice article :-)

Using SSH tunel every day

ericzqma's picture

Good article! I am a big fan of SSH tunneling and VNC---actually I use it almost every day (VNC over SSH tunnel). I have a PC in at home, and I connect to it from every where, library, laboritary, etc. No matter whether the client is a Mac or a Windows, I always connect to my own Linux environment with VNC to check email etc. SSH ensures the security for me. With tunneling, only 22 port is needed to open for my PC at home, and the connection is encrypted.

SSH with OpenVPN

jhansonxi's picture

I use SSH to connect to client systems for administration. But this doesn't work if the client is behind a firewall that isn't under my or their control. Allowing them to connect to my system over SSH is a security hole since they can reverse-forward ports and block services on my system (like NFS on 2049). OpenSSH doesn't have the ability to restrict port access in that direction (only forwarded ports). To work around this I configured a "remote tech support VPN" on their systems for them to use to connect to my system. I block VPN access to everything with iptables and OpenVPN has many scripting options that allow me to set up a notification on my system when they connect. I then can use SSH to connect back through the VPN.

If you're going to use SSH,

Anonymous's picture

If you're going to use SSH, stay away from putty... even though it's the most commonly used emulator, SecureCRT is way better and it's not that expensive.

Dave
http://carinsurancecomparisonshelp.com

tunnels

tacra's picture

Great article. I frequently combine netcat with the tunnels to bypass using scp to transfer files. Why go through authenticating twice when you don't have too? There is even a version of netcat for windows which will happily converse over the same tunnels with the versions found on Linux or the BSDs.

scp authorizes twice? Why do

estani's picture

scp authorizes twice? Why do you say so?
scp = ssh + cp
It uses ssh unless you define a different ssh client.

Actually netcat over ssh might be redundant if used just for moving files, ssh opens a pipe just like netcat.

cat file | ssh bob@somewhere ">file"

For example this is more typical: tar cz blah | ssh bob@somewhere "tar xz"

Brute force attacks on OpenSSH

Anonymous's picture

One of the problems encountered with exposing OpenSSH to the Internet is brute force attacks on it.

There is a FOSS product called Taferno (http://taferno.sourceforge.net) that prevents brute force attacks on OpenSSH while also providing frugal TFA (Two-Factor Authentication) for OpenVPN and Web Single Sign On.

This is FYI.

Other assists

Rick's picture

knockd (only opening ports after a sequence of ports) or fail2ban (monitoring logs and blocking incoming IPs that are attempting brute force) are also helpful here.

Brute Force attacks prevention with FWKNOP client

Charles Hewson's picture

Single packet authentication can be used open or manage IP/Port from your USB stick and pass phrase.

http://www.cipherdyne.org/fwknop/

report link useful

Fionna's picture

I tried to use this site to see some settings on my usb, but this site i does not report anything good for evaluation. There is another site more useful Ver Tv Online

VNC over SSH on a reversible tunnel

Santiago DIEZ's picture

Hi there,

Is there any way one can use a tunnel between 2 linux servers to connect 2 windows clients. I'll try and explain:

  • On network A we have
    • ADSL : the internet box. NOT routable.
    • Aserver : a Debian server connecting to the internet through ADSL.
    • Awin : a Windows machine connecting to the internet through ADSL.
  • On network B we have
    • BDSL : the internet box (routable with DMZ on Bserver).
    • Bserver : a Debian server connecting to the internet through BDSL.
    • Bwin : a Windows machine connecting to the internet through BDSL.

Thanks to your explanations, I understand how to create a tunnel between Aserver and Bserver without routing anything on ADSL or BDSL.
Aserver > SSH reversible tunnel > Bserver

Is there any way I can make this a VNC reversible tunnel so that I can then use VNC from Bwin to Awin

  • I'm working on Bwin, open up TightVNC and call an address like Bserver:5900.
  • With Bserver then routing the request through the tunnel back to Aserver.
  • And finally Aserver routing the request on port 5900 to Awin.

Here is what I think I know :

  • Create a VNC reversible tunnel from Aserver to Bserver with ssh santiago@BDSL 5900:foo:5900 (because of how I configured BDSL, the request is directly forwarded to Bserver).
  • forward any request made to Bserver on port 5900 to foo on the same port with iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 5900 -j DNAT --to foo:5900 (although I'm not sure iptable will know that foo is the name of the tunnel)
  • But what I'm definitely missing is how to forward the request from Aserver to Awin. I don't think iptable can work here because the request is virtually on port 5900 but it actually arrives on port 22 (the ssh tunnel)

Any help would be greatly appreciated.

Santiago

To create a tunnel to AServer

gcamp0730's picture

To create a tunnel to AServer on the B network and allow connections from BWin (or any other machine on the B network), run a command like this on BServer:
ssh -L *:5900:AWin:5900 santiago@ADSL

The '*:' before the first 5900 allows the port to be accessible from other machines, i.e. BWin. So to connect to AWin from BWin tell VNC to connect to BServer:0

Also, I normally use the -f parameter to put the session in the background, like this:
ssh -f -L *:5900:AWin:5900 santiago@ADSL sleep 10h

That will keep the session open for 10 hours.

pppd+ssh

tacra's picture

You might take a look at using pppd with ssh. SSH supplies the tunnel. Encrypted of course. PPPD setups a network interface and routes to push the traffic through the tunnel. While ppp was originally created to establish ip based connections over the old modem tech of 20 odd years ago, it still works well and doesn't have to have a modem. Many ADSLs use PPP over Ethernet today. And yes, you could also use SLIP but why subject yourself to more pain than necessary.

As stated in the main article, doing this will get you into a heap of trouble if you don't have approval from the right people. Some boss who just wants to do this for whatever reason isn't good enough. When in doubt talk to the network admins. It will get noticed by the network admins when questions about why "the Internet" seems slow.

No pb with the network

Santiago DIEZ's picture

No pb with the network admin... It's me.
I'm trying to find a way to remote help a client in another network with a linux server that I manage but a dslbox that I do not manage.

ssh is ...

Przemo's picture

Very good article - I'm using ssh, but I never dug into what you can actually do with it. I'd suggest name "SSH tunelling - _wise_ techie's VPN" :-D
regards,
Przemo

Dynamic forwarding issue

Stian Berger's picture

When using ssh user@site -D5222
you might want to note that DNS resolving is normally done outside the applications. They will therefore not be tunneled or encrypted. So if you are on a non trusted wifi, you could still be a victim of rouge dns (unless you have specified a fixed dns, like opendns, but will still be unencrypted).

There is an option in firefox to make sure name resolving also goes through your proxy, but it is only on the about:config page (network.proxy.socks_remote_dns).
I think you need to restart firefox after doing this modification.

Dynamic forwarding issue

Stian Berger's picture

When using ssh user@site -D5222
you might want to note that DNS resolving is normally done outside the applications. They will therefore not be tunneled or encrypted. So if you are on a non trusted wifi, you could still be a victim of rouge dns (unless you have specified a fixed dns, like opendns, but will still be unencrypted).

There is an option in firefox to make sure name resolving also goes through your proxy, but it is only on the about:config page (network.proxy.socks_remote_dns).
I think you need to restart firefox after doing this modification.

sshuttle

Charles Hewson's picture

This makes most of what you suggest academic. I expect better research !

https://github.com/apenwarr/sshuttle

Forwarding a remote remote address

Steeve McCauley's picture

I use this to access services running on my "desktop" at work, which are behind a firewall at "server",

ssh -LNNNN:desktop:MMMM server -N

so this maps the remote port on desktop:MMMM (internal to the server network) to localhost:NNNN.

You can also save some typeing by creating ssh configs (in ~/.ssh/config) that pre-configure the portforwarding for you, for one or more services,

Host foo_cdb
Hostname companyserver.net
Port 2229
Compression yes
LocalForward 5984 foo:5984
LocalForward 3306 foo:3306

so when I need to setup this particular port forward, I can just type,

ssh foo_cdb

Bobbies

Dizon's picture

Most bobbies are busted not by bypassing company firewalling rules but actually by the traffic itself they make downloading whole isos. Administratoris focus even more on bandwidth violations than trafficking policies themselves.

Webinar
One Click, Universal Protection: Implementing Centralized Security Policies on Linux Systems

As Linux continues to play an ever increasing role in corporate data centers and institutions, ensuring the integrity and protection of these systems must be a priority. With 60% of the world's websites and an increasing share of organization's mission-critical workloads running on Linux, failing to stop malware and other advanced threats on Linux can increasingly impact an organization's reputation and bottom line.

Learn More

Sponsored by Bit9

Webinar
Linux Backup and Recovery Webinar

Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.

In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.

Learn More

Sponsored by Storix