Tag Archives: ssh port forwarding

OpenSSH (server and client) | A complete guide | UBUNTU

20 Feb

SSH, or Secure Shell, is a popular network protocol that allows for the exchange of data using cryptography for additional security. It is most commonly used to log into a remote machine, such as a server, and execute commands via the command line. SSH operates on port 22 on the server by default. So, how is this useful to you, someone who I assume is not familiar with SSH? In the case that you may own a VPS or dedicated server, it will allow you to possess a greater control over your account, some highlights including the ability to modify configuration files which may not be available to you otherwise such as httpd.conf – this customization could allow for better optimization, increased performance, and as a result, a better bang for your buck.

So, what will you get out of this tutorial? You will learn how to connect to your server using PuTTY, a great and free SSH client, and will be introduced to some basic commands and various other useful commands. So, let us begin.

To start things off, you’ll need to use/download an SSH client. If you are using a *Nix system, chances are you can launch an SSH Session from the terminal without installing any software. Windows, however, requires a client. I’d like to recommend PuTTY, although you could try a variety of clients, as found at
http://en.wikipedia.org/wiki/Comparison_of_SSH_clients
. But, for the purpose of this guide, you can download PuTTY at
http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html
. The windows executable installer should be good enough for any Windows user.

Once downloaded, which shouldn’t take too long by the way as the installer is under 2MB, run it and install the client. The default values for the installer should be good enough, although you can change things if needed.

So now that PuTTY has been installed, start the client up by using the created shortcuts or going to Start->All Programs->PuTTY->PuTTY if installed with default settings. On start, the PuTTY configuration window will appear.

Here you’ll need to specify the IP address of your server (ex: 192.168.100.1) You can also specify a port other than the 22 if need be, although most servers listen to it by default. After specifying these things, you may want to save the information for quicker access by clicking on Save, under “Load, save or delete a stored session”. And now that you’ve done this, you can click on open to connect. At this point, a warning may come up saying that the server’s host key is not cached in the registry. In most cases, simply press Yes to trust the host and continue.

Here it is evident that you’ll need to specify a user to log in as. In many cases you’ll be able to use the same user information as those made available to you for logging into your control panels such as plesk or cpanel. After typing in your username, press enter. It will then ask for a password. At this point, you should note that the password will not be displayed as you type. Nope, not even the usual *** asterisks. So, just input your password carefully as to avoid any typos and press enter to login.

Now you’re in. Congratulations, you just opened up an SSH connection! From here on in you’ll be able to input various commands using your keyboard. In order to input a command, simply type it and press enter. You should also note that the standard right click function has been replaced by the paste function, and so should be used if you want to copy-paste. When done using PuTTY, simply enter exit to log out and exit the client.

Installing an OpenSSH Server

Type the following two command to install both ssh client and server on an Ubuntu Server Installation :

# sudo apt-get install openssh-server openssh-client

This will install the OpenSSH server (daemon) and start it on port 22. The SSH Server has a configuration file located in /etc/ssh/sshd_config. There is a heap of config changes that can be applied by changing parameters in this config file. The main ones that i usually use are :

Port :- default listening port for ssh daemon

PermitRootLogin :- allow root to login via ssh (disabled is recommended)

What about configuring the OpenSSH Server (SSHD) daemon?

Now that we’ve install the SSH Server and had a look at the config file we can test it from your home computer or from same system with the command:

# ssh localhost

OR

# ssh user@your-server-ip-address

Assuming that your server hostname is userver.mydomain.com and username is vivek, you need to type the following command:

# ssh vivek@userver.mydomain.com

To stop ssh server, enter:

# sudo /etc/init.d/ssh stop

To start sshs server, enter:

# sudo /etc/init.d/ssh start

To restart ssh server, enter:

# sudo /etc/init.d/ssh restart,

The log’s for checking ssh logins is located in /var/log/auth.log by default and should look like this :

Feb 20 10:02:49 bomber sshd[14113]: Accepted password for vivek from 1.155.23.110 port 39508 ssh2

Configuring SSH using ~/.ssh/config

For system and network administrators or other users who frequently deal with sessions on multiple machines, SSH ends up being one of the most oft-used Unix tools. SSH usually works so well that until you use it for something slightly more complex than starting a terminal session on a remote machine, you tend to use it fairly automatically. However, the ~/.ssh/config file bears mentioning for a few ways it can make using the ssh a client a little easier.

:- Abbreviating Hostnames

If you often have to SSH into a machine with a long host and/or network name, it can get irritating to type it every time. For example, consider the following command:

$ ssh web0911.colo.sta.solutionnetworkgroup.com

If you interact with the web0911 machine a lot, you could include a stanza like this in your ~/.ssh/config:

Host web0911
    HostName web0911.colo.sta.solutionnetworkgroup.com

This would allow you to just type the following for the same result:

$ ssh web0911

Of course, if you have root access on the system, you could also do this by adding the hostname to your/etc/hosts file, or by adding the domain to your /etc/resolv.conf to search it, but I prefer the above solution as it’s cleaner and doesn’t apply system-wide.

:- Fixing Alternative Ports

If any of the hosts with which you interact have SSH processes listening on alternative ports, it can be a pain to both remember the port number and to type it in every time:

# ssh webserver.example.com -p 5331

You can affix this port permanently into your .ssh/config file instead:

Host webserver.example.com
    Port 5331

This will allow you to leave out the port definition when you call ssh on that host:

# ssh webserver.example.com
:- Custom Identity Files

If you have a private/public key setup working between your client machine and the server, but for whatever reason you need to use a different key from your normal one, you’ll be using the -i flag to specify the key pair that should be used for the connection:

# ssh -i ~/.ssh/id_dsa.mail srv1.mail.example.com
# ssh -i ~/.ssh/id_dsa.mail srv2.mail.example.com

You can specify a fixed identity file in .ssh/config just for these hosts instead, using an asterisk to match everything in that domain:

Host *.mail.example.com
    IdentityFile ~/.ssh/id_dsa.mail

I need to do this for Mikrotik’s RouterOS connections, as my own private key structure is 2048-bit RSA which RouterOS doesn’t support, so I keep a DSA key as well just for that purpose.

:- Logging in as a different user

By default, if you omit a username, SSH assumes the username on the remote machine is the same as the local one, so for servers on which I’m called tom, I can just type:

tom@conan:$ ssh server.network

However, on some machines I might be known as a different username, and hence need to remember to connect with one of the following:

tom@conan:$ ssh -l tomryder server.anothernetwork
tom@conan:$ ssh tomryder@server.anothernetwork

If I always connect as the same user, it makes sense to put that into my .ssh/config instead, so I can leave it out of the command entirely:

Host server.anothernetwork
    User tomryder
:- SSH Proxies

If you have an SSH server that’s only accessible to you via an SSH session on an intermediate machine, which is a very common situation when dealing with remote networks using private RFC1918 addresses through network address translation, you can automate that in .ssh/config too. Say you can’t reach the hostnathost directly, but you can reach some other SSH server on the same private subnet that is publically accessible, publichost.example.com:

Host nathost
    ProxyCommand ssh -q -W %h:%p public.example.com

This will allow you to just type:

# ssh nathost
:- More Information

The above are the .ssh/config settings most useful to me, but there are plenty more available; check man ssh_config for a complete list.

SSH Tunnels

Quite apart from replacing Telnet and other insecure protocols as the primary means of choice for contacting and administrating services, the OpenSSH implementation of the SSH protocol has developed into a general-purpose toolbox for all kinds of well-secured communication, whether using both simple challenge-response authentication in the form of user and password logins, or for more complex public key authentication.

SSH is useful in a general sense for tunnelling pretty much any kind of TCP traffic, and doing so securely and with appropriate authentication. This can be used both for ad-hoc purposes such as talking to a process on a remote host that’s only listening locally or within a secured network, or for bypassing restrictive firewall rules, to more stable implementations such as setting up a persistent SSH tunnel between two machines to ensure sensitive traffic that might otherwise be sent in cleartext is not only encrypted but authenticated. I’ll discuss a couple of simple examples here, in addition to talking about the SSH escape sequences, about which I don’t seem to have seen very much information online.

:- SSH Tunnelling and Port Forwarding

Suppose you’re at work or on a client site and you need some information off a webserver on your network at home, perhaps a private wiki you run, or a bug tracker or version control repository. This being private information, and your HTTP daemon perhaps not the most secure in the world, the server only listens on its local address of 192.168.1.1, and HTTP traffic is not allowed through your firewall anyway. However, SSH traffic is, so all you need to do is set up a tunnel to port forward a local port on your client machine to a local port on the remote machine. Assuming your SSH-accessible firewall was listening on firewall.yourdomain.com, one possible syntax would be:

# ssh user@firewall.yourdomain.com -L5080:192.168.1.1:80

If you then pointed your browser to localhost:5080, your traffic would be transparently tunnelled to your webserver by your firewall, and you could act more or less as if you were actually at home on your office network with the webserver happily trusting all of your requests. This will work as long as the SSH session is open, and there are means to background it instead if you prefer — see man ssh and look for the -f and -Noptions. As you can see by the use of the 192.168.1.1 address here, this also works through NAT.

This can work in reverse, too; if you need to be able to access a service on your local network that might be behind a restrictive firewall from a remote machine, a perhaps less typical but still useful case, you could set up a tunnel to listen for SSH connections on the network you’re on from your remote firewall:

# ssh user@firewall.yourdomain.com -R5022:localhost:22 -f -N

As long as this TCP session stays active on the machine, you’ll be able to point an SSH client on your firewall to localhost on port 5022, and it will open an SSH session as normal:

# ssh localhost -p 5022

I have used this as an ad-hoc VPN back into a remote site when the established VPN system was being replaced, and it worked very well. With appropriate settings for sshd, you can even allow other machines on that network to use the forward through the firewall, by allowing GatewayPorts and providing abind_address to the SSH invocation. This is also in the manual.

SSH’s practicality and transparency in this regard has meant it’s quite typical for advanced or particularly cautious administrators to make the SSH daemon the only process on appropriate servers that listens on a network interface other than localhost, or as the only port left open on a private network firewall, since an available SSH service proffers full connectivity for any legitimate user with a basic knowledge of SSH tunnelling anyway. This has the added bonus of transparent encryption when working on any sort of insecure network. This would be a necessity, for example, if you needed to pass sensitive information to another network while on a public WiFi network at a café or library; it’s the same rationale for using HTTPS rather than HTTP wherever possible on public networks.

:- Escape Sequences

If you use these often, however, you’ll probably find it’s a bit inconvenient to be working on a remote machine through an SSH session, and then have to start a new SSH session or restart your current one just to forward a local port to some resource that you discovered you need on the remote machine. Fortunately, the OpenSSH client provides a shortcut in the form of its escape sequence, ~C.

Typed on its own at a fresh Bash prompt in an ssh session, before any other character has been inserted or deleted, this will drop you to an ssh> prompt. You can type ? and press Enter here to get a list of the commands available:

$ ~C
ssh> ?
Commands:
    -L[bind_address:]port:host:hostport  Request local forward
    -R[bind_address:]port:host:hostport  Request remote forward
    -D[bind_address:]port                Request dynamic forward
    -KR[bind_address:]port               Cancel remote forward

The syntax for the -L and -R commands is the same as when used as a parameter for SSH. So to return to our earlier example, if you had an established SSH session to the firewall of your local network, to forward a port you could drop to the ssh> prompt and type -L5080:localhost:80 to get the same port forward rule working.

SSH Keys (Passwordless login)

SSH keys allow authentication between two hosts without the need of a password. SSH key authentication uses two keys aprivate key and a public key.

To generate the keys, from a terminal prompt enter:

#   ssh-keygen -t dsa

This will generate the keys using a DSA authentication (use -t RSA for RSA authentication) identity of the user. During the process you will be prompted for a password. Simply hit Enter when prompted to create the key. If you specify a password during the key creation, it will always require this password during login and thus avert the purpose of “passwordless” loggin.

By default the public key is saved in the file ~/.ssh/id_dsa.pub, while ~/.ssh/id_dsa is the private key. Now copy the id_dsa.pub file to the remote host and appended it to ~/.ssh/authorized_keys:

#   cat id_dsa.pub >> .ssh/authorized_keys

OR
The ssh client has a built in tool to perform this task, called ssh-copy-id. The one drawback is that this tool only works if your default port for SSH has not changed.
#   ssh-copy-id -i id_dsa.pub user@remotehost

Finally, double check the permissions on the authorized_keys2 file, only the authenticated user should have read and write permissions. If the permissions are not correct change them by:

#   chmod 644 .ssh/authorized_keys

You should now be able to SSH to the host without being prompted for a password.

Block SSH Bruteforce Attempts

If you running your SSH Server on port 22 and you have the machine connected to the internet, within a couple minutes you will see a range of attempted bruteforce attempts on your server. This is considered normal as there are a wide range of attacks taking place at any given second on the internet. The below iptable rules, allow a maximum of 3 connections per minute from host. This is usually enough to tharwt the most basic of Bruteforce attacks and free up some of your bandwidth.

iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set --name SSH -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -m recent --update --seconds 60 --hitcount 4 --rttl --name SSH -j LOG --log-prefix "SSH_brute_fo ce "
iptables -A INPUT -p tcp --dport 22 -m recent --update --seconds 60 --hitcount 4 --rttl --name SSH -j DROP

Hope you enjoyed this guide to setting up and using SSH.