I.T. Consulting
How RAID Works What's a RAID? Hardware vs Software RAID Striping and Mirroring RAID 2 and 3 RAID 4 and 5 Conclusion
Software RAID on Linux RAID: Quick Recap Software Tools Creating & Using an Array Monitoring an Array Removing & Re-Assembling an Array The mdadm.conf File Deleting an Array Summary & Cheat-Sheet
Network Security
Squid Proxy Server Basic Configuration Controlling Traffic Blocking Access Monitoring Traffic
SSH: Secure Shell Overview Using SSH Encryption Authentication Keys Configuring SSH Advanced Tricks
Implementing HTTPS What Is HTTPS? Setting Up The Server
Linux Skills
The ed Line Editor First Things First Navigating Entering Text Changing Text Line Maneuvers Text Searches Using ed in Real Life Summary
Regular Expressions Text Patterns Extended Expressions
The vi Editor Introduction Operating Modes Navigation Editing Summary
Intermediate vi Power Editing Cut-and-Paste Modifying Text Searches Tips & Tricks The vi Prompt Indenting
Creating an eBook Introduction Create an ePub Create a MOBI Create a PDF

SSH: Secure Shell

SSH (Secure Shell) is a secure substitute for telnet. With SSH, your entire session is encrypted, including logins and passwords. But that's just the beginning; you can do some pretty amazing things with SSH if you know how to configure it and use it. This tutorial shows you how.

What can SSH do?

SSH stands for "Secure Shell" and is primarily a communications program for character-based sessions. This means that, in its simplest form, SSH works like Telnet to connect you to a command prompt or character-based application on a remote system. However, the main difference between Telnet and SSH is that SSH encrypts the entire session, so that it's impossible for someone to spy on your session even if they find a way to intercept your data stream on the network.

That, by itself, is an amazing benefit, but that's only the beginning. SSH also supports authentication keys, which makes it possible to secure passwordless sessions. This can be extremely useful for unattended system tasks such as remote printing, overnight system backups, or periodic system polling for any purpose.

In addition, the SSH suite of programs includes scp and sftp, two secure file transfer protocols that can be used to download or upload sensitive data with complete confidentiality.

And finally, SSH supports port forwarding, which makes it possible to relay an entire protocol stream (like X Window or HTTP, for instance) from one machine to another. For instance, I frequently use this feature to display an X Window graphical application (such as a word processor or Web browser) from a client's machine to my own screen for trouble-shooting purposes using nothing more than a plain old SSH connection.

Similarly, I can use this feature to point my browser to a client's router or printer to access their Web-based configuration menu, and I can even get through a client's firewall protection (with their permission, of course) by using the port-forwarding features of SSH to piggy-back over a connection I've allowed them to establish from their machine to my own.

That's a lot to absorb right now, but the point is that you can do some pretty amazing things with SSH if you know how to use it. In this tutorial, we will first examine how to use the most basic features of this software, such as connecting to a remote system and transferring files. Next, we will see how to configure the software to implement various desirable features, such as passwordless connections with authentication keys. And finally, we will cover some advanced tips and tricks, including how to use port forwarding as just mentioned.



Simple Tasks

To get started, let's pretend that someone else has installed and configured SSH on your system and that you are simply going to use it. Here is what you would need to know.

Using ssh to connect to a server

The command to connect to a remote server is ssh. In its simplest form, the ssh command can be invoked with the name of the server you are trying to access, like this:

ssh some_server.example.com

Of course, if the server is on your local network, you don't need to specify a full domain name. For instance, if you have a system on your network named pluto, you can simply invoke:

ssh pluto

And of course, you can use the numeric IP address of the system you are calling, as in:


Without any additional options, ssh will attempt to login to the remote server with the same login ID you are using on the calling system. For instance, if you are currently logged in as johndoe, ssh will assume you are trying to login as that user on the remote system.

If your account on the remote system is different, then you need to specify it with the -l option (for "login"), as in:

ssh -l johnny myserver

An alternate form for this syntax is to prefix the system name with the desired login ID and an "@" sign, email-style, like this:

ssh johnny@myserver

At this point, one of two things may happen, depending on how the server and your account have been configured: you might get prompted for a password, or you might get logged in immediately if authentication keys have been used (explained later).

The most common scenario is that you will be prompted for a password. Your session might look like this:

johndoe> ssh pluto
johndoe@pluto's password: _

If you have a shell account named johndoe on machine pluto, then simply enter your password and you're in. If you have an account of a different name on pluto, or you want to login as a different user (say, "maryjane") and know her password, you would simply specify this when calling the system, like this:

johndoe> ssh -l maryjane  pluto
maryjane@pluto's password: _

We will see later on that it is possible to exchange authentication keys between machines so that a user can connect to an account on another machine without being prompted for a password. At first glance, this might seem like a security risk since an intruder who might gain access to one account would automatically have access to a second account on another machine. That is quite right, and we will see that there are ways to mitigate this risk.

For now, I just want to mention that passwordless connections are possible, and they can be extremely useful for unattended tasks where no user is available to enter a password. For instance, you may want to system to automatically back up your home directory to a server at 2 AM every day. If you set things up right, there is no particular risk since an intruder would only have access to your backup files, which would be rather pointless if he has already gained access to your live files.

Similarly, you may want to set up automated tasks between systems to transfer print jobs to a remote site or periodically poll a directory for the presence of incoming orders. There are lots of scenarios where controlled and authorized passwordless connections can be useful without jeopardizing security. We will cover these scenarios later, after we are finished covering the basics.

Transferring files with scp

The scp command is very similar to the standard Unix cp command with the simple difference that you can prefix its arguments with a system name to indicate you are copying files over the network to a different machine.

For instance, to copy the file /home/john/memo to the /tmp directory on a Unix-type system (such as Linux, Mac OS X or Solaris), you would use the standard cp command like this:

cp /home/john/memo /tmp

Now, if you meant to transfer this file to the /tmp directory on another machine, say pluto, you would use scp instead of cp and would prefix the /tmp argument with the name of the desired target machine using a colon as the delimiter, like this:

scp /home/john/memo  pluto:/tmp

It's that simple.

What happens next depends on how SSH has been configured on those two systems. In the simplest case, you would have a user account of the same name on the target machine and you would be prompted for your password, like this (assuming you are logged in as user johndoe:

$ scp /home/john/memo  pluto:/tmp
johndoe@pluto's password: (enter your password)
memo       100% 2564     2.5KB/s 00:02
$ _

The scp command will produce some feedback regarding this transfer, including the name of the file, the size, and the time it took to transfer it.

If your user ID on the remote machine is different from that on the source system, you will have to specify it using the "name@" syntax we used for ssh earlier, like this:

scp /home/john/memo  johnny@pluto:/tmp

As mentioned before, it is possible for the system administrator to configure your account for passwordless access. If this has been done, then the scp process would be the same as the standard cp process: you would simply enter your command, the transfer would take place, and you would then be returned to your prompt. It's remarkably convenient.

sftp: Secure FTP

Secure FTP is a less convenient file transfer utility patterned after the old FTP interface. It provides a familiar user interface for those who are used to FTP but does not provide any other advantage.

If you are a fan of the FTP command set, then this is the utility for you. The standard FTP commands such as put, get, and dir are all available. The only difference is that all transfers, including your login ID and password, will be encrypted to make the session secure.

Here is what a typical session might look like (the text in bold is what you would type in):

$ sftp pluto
johndoe@pluto's password: (enter your password)
Connected to pluto.
sftp> dir
Documents        Downloads    Examples                  
wallpaper.html    Mail         Music                     
sftp> get wallpaper.html
Fetching /home/johndoe/wallpaper.html
wallpaper.html      100%    91675     1.6KB/s  00:01    
sftp> bye
$ _


That's it for the basics. There are 3 main communication tools in the SSH family of utilities:

  • ssh: Connect to another system
  • scp: Copy files to or from another system
  • sftp: Copy files using an FTP-style interface and command set

On most systems, your access will be protected with a standard password, which makes it vulnerable to password-guessing. In the next section, we will see how SSH can use authentication keys to impove both convenience and security.



How Does Encryption Work?

The Challenge

In the old days, if you wanted to send a secret message to someone, you would encode it using the most clever method you could come up with, and send it in this encrypted form to your correspondent. That person would then use some sort of password or secret key to decode your message.

The challenge, of course, was to communicate this secret decoding key to your cohort in such a way that nobody else would intercept it in transit. In times of war, some extremely elaborate systems were devised to send these keys to their destination in a secure manner so that subsequent correspondence could be sent in encrypted form without as much security. The trouble was, you could never be absolutely sure that your key had not been somehow copied by the enemy, so you were never completely sure whether your encrypted messages were actually secure.

The New and Improved Way

SSH turns the whole problem on its head in such a clever way that you have to wonder why no-one thought of it earlier.

The SSH protocols use two separate keys to implement encryption: one key is used to encode the message while a separate and totally different key is used to decode it.

Now, here is where it gets clever: If you want to exchange encrypted messages with a pal, you give him your encryption key and you keep the corresponding decryption key to yourself. Your buddy uses your encryption key to encode his message to you and then sends it along by the most convenient means at his disposal. It doesn't have to be secure since the message is encoded. For instance, he could send you the message by email and he wouldn't care if someone intercepts it in transit.

When you receive his message, you use your decryption key to break the code and read the text.

The beauty of this system is that you never had to expose your decryption key; it never had to leave your office, so it was never in danger of being intercepted. Not only that, but you didn't have to protect the encryption key either when you sent it to your buddy; you don't care if the whole world sees it because it can only be used to encrypt messages addressed to you, not decrypt them. This key allow anyone to send you encrypted messages if they want, but only you can decrypt them.

Meanwhile, your buddy would have sent you his own encryption key so that you can respond to his message with the same level of security. You would encode your response using his key and then send it to him, without any particular security measures. When he receives your encrypted message, he would use his decryption key, which has never left his computer, to read your response.

SSH provides a simple tool to generate unique key pairs. The encryption key, which you want to hand out freely to anyone who wants to communicate with you, is called the "public key," because you don't mind if the public at large gets to see it. The other half of this pair, the decryption key, is called the "private key" because you want to take great care to keep it to yourself.

If, for some reason, you ever have reason to believe your private key has been compromised (i.e. someone has obtained a copy), you can simply delete it and create a new pair, and send the public key from that pair to everybody you need to communicate with.

It's a beautiful system.



Using Authentication Keys

Host Keys

So, how do these public keys get exchanged anyway? After all, you may have used SSH to connect to a remote system before and you certainly don't remember sending them a special key in advance, right?

The answer is quite simple: When SSH is installed on a system, a pair of "host keys" are created as part of the process. These keys typically reside in /etc/ssh on a Linux system and have names like ssh_host_rsa.pub (public key, as indicated by the .pub extension) and ssh_host_rsa (private key, no filename extension).

When a user on system "A" calls system "B" over SSH, the two systems exchange public keys and then proceed to accept the login ID and password (or other authentication method). As a result, even this information (your user name and password) are encrypted, along with the rest of your entire login session.

Using Keys for Authentication

In addition to providing encryption for entire sessions, SSH keys may also be used for a totally different purpose: authentication. After all, each file in a pair of SSH keys matches the other one in a way that is virtually impossible to replicate, so this situation can be leveraged to provide a much more secure authentication method than the traditional login ID and password.

Specifically, you would generate a pair of SSH keys (we'll see in a minute how to do this) and you would place the public key in your account on the remote machine and keep the private key in your account on the source machine. When an SSH connection is initiated, the process would look for the presend of that public key on the remote account and, if found, would compare it with your private key to see if they match. If they do, you're in; otherwise, SSH will fall back to password logins, assuming you have not disabled them. Generally, if you take the trouble to set up authentication keys, you will also disable password logins to prevent password-guessing attacks. (We will see how to disable password logins further down.)

Generating Authentication Keys

So, how would you go about generating your own pair of authentication keys? Very simple: SSH comes with a utility to do just that. The ssh-keygen command will generate a pair of keys and place them in the .ssh subdirectory of your home directory. In its simplest form, the command is invoked without arguments, like this:

$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/rey/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
$ _

If you just press ENTER when prompted for the location and name of your key, ssh-keygen will accept the default pathname specified in parentheses. That's a perfectly acceptable value and there is no particular reason you would want anything else in most situations.

In fact, ssh-keygen will create two keys: one by the name specified as the default ("id_rsa" in our example) and a second one with the same name but with a .pub extension added to it, i.e. "id_rsa.pub" in our example. As expected, the .pub file is the public key that you will upload to remote accounts you wish to SSH to, while the file without a filename extension is the private key that you will keep on your system and guard very carefully, making sure it does not have read or write access for the group or other users so that nobody can make a copy of it or modify it.

Encrypting the Private Key

The second prompt is interesting: you are being prompted for a "passphrase." What is this all about?

Quite simply, this allows you to put a password on the private key itself for added protection. For instance, what if someone were to get a copy of your private key, install it on their own computer and then try to use it to login as you or transfer files under your ID? Without a password, there would be nothing to stop this intruder. However, by protecting the key itself with a password, the intruder would be prompted for that password and would not get any further.

In fact, the reason this password is called a passphrase is that you can include spaces and make it as long as you wish. For instance, a typical password might be something like 2hard4U2guess while a passphrase could be somthing like " You'll never guess this in 1000 years!". As a general rule, the longer your passphrase, the less likely it is to be guessable.

Now, the obvious question that probably comes up in your mind is, "Doesn't this defeat the purpose of using keys to begin with? After all, we were trying to eliminate passwords and here we are again, getting prompted for one!"

Valid objection. And there are two perfectly good responses to that.

First, even though you are being prompted to enter a password, the password is on your authentication key, not on your login account. Password-based logins should still be disabled if you are using authentication keys.

You see, the danger with allowing password-based logins is that any stranger, anywhere in the world, can try to guess your password by trying every word in the dictionary or common combinations of letters and numbers until they get in. And I can assure you, a lot of people are trying. I know this from looking at access logs on my clients' systems: I see brute-force attacks all the time, and they all fail because I don't allow password-based SSH logins on the systems I manage.

Conversely, if you disable password-based logins (we'll see how to do this shortly) and put a passphrase on your authentication key instead, you are still being prompted for a password but you are the only person in the world who can enter it because the program that is prompting you is running on your own computer, not on the server. This means brute-force attacks will not work in this scenario; they can't possibly work because no combination of login ID and password will let anyone into your account; only your authentication key can allow this.

The second answer is that the SSH family of programs includes a utility to keep your authentication key in memory for added convenience. It's called an "SSH Agent" and runs as a background process. On Linux, you would invoke it with the command ssh-add, like this:

$ ssh-add
Enter passphrase for /home/johndoe/.ssh/id_rsa: 
Identity added: /home/rey/.ssh/id_rsa (/home/rey/.ssh/id_rsa)

From this point on, your passphrase is saved in RAM and will be fed to any program that requires it, such as ssh, scp or sftp. Is that safe? Well, it's as safe as your own login session. If you walk away from your desk and don't log out and don't lock your screen, then yes, someone could sit at your desk while you're away and access remote sites as you. Of course, that person could also access all your local files such as email, documents and your job applications to your employer's competitors.

However, assuming you exercise common sense, your passphrase is as safe in memory as it would be in your head because no standard user has access to it. In addition, this value disappears from RAM as soon as you terminate your login session. For this reason, it may be wise to add the "ssh-add" command to your .profile file so that you will automatically be prompted for it when you log in.

On most modern X Window-based systems, SSH will invoke the "agent" automatically the first time you enter your passphrase and will memorize it for the rest of your session, so you may not even have to invoke ssh-add manually. In other environments such as Windows, you may have to click on an icon to start the SSH Agent.

Installing the Public Key

Now, what? You have generated a pair of authentication keys and have protected your private key with a passphrase. What happens next?

At this time, the authentication keys are most likely located in the .ssh subdirectory of your home directory. To be consistent with our previous examples, we will assume your user ID is johndoe and that your home directory is /home/johndoe on a Linux system. Consequently, you should have a subdirectory named /home/johndoe/.ssh containing the files id_rsa and id_rsa.pub if you have accepted the defaults.

What you need to do next is transfer the public key, id_rsa.pub, to the .ssh subdirectory of your account on the remote system and rename it authorized_keys2 on that system.

Again, using our previous examples, we will assume the remote system is named pluto and that your account on that machine is johnny. Using the method of your choice (ftp, scp, cut-and-paste between two windows, USB flashdrive, etc.), get that file to machine pluto and save it as /home/johnny/.ssh/authorized_keys2. If the .ssh directory does not exist in your account on pluto, just create it.

Important: If anyone can modify, replace or overwrite the authorized_keys2 file on the target system, they could replace it with their own key and access the system as you. For this reason, permissions and ownership must be correct on both the file and the .ssh directory. Specifically, permissions on .ssh should be 755, and 644 on authorized_keys2. In addition, both must belong to the correct user (johnny in this example). If this is not the case, SSH will deny the connection for your own protection.

Note that authorized_keys2 can contain multiple keys, allowing more than one account to connect remotely as this user. To make this possible, simply append as many additional public keys as you wish to this file. After all, these public keys as just text files and can be appended to authorized_keys2 using the ">>" shell construct, or inserted with a cut-and-paste operation in a standard text editor.

Explaining the Strange Names

When SSH was originally designed (what we call today "SSH-1"), the authentication keys were called identity and identity.pub, and the file containing those keys on the remote site was called authorized_keys, a logical name for it.

Over time, a new and improved version of SSH was designed, which is referred to as "SSH-2". This is the default protocol on most modern systems.

Since the two protocols are quite different, the default filenames were changed to avoid potential configuration errors such as attempting to use an SSH-1 key on an SSH-2 server. This is why the file containing the authorized keys on a remote server that uses SSH-2 is now called authorized_keys2.

In addition, SSH-2 supports two types of authentication: RSA and DSA. For this reason, the default filename for authentication keys under SSH-2 is now id_rsa or id_dsa, depending on the chosen protocol.

As mentioned before, either protocol will do the job, so you can simply accept whatever ssh-keygen defaults to when generating your keys. However, if you prefer or need a specific protocol, say DSA, you can inform ssh-keygen of your preference using the -t option (for "type"), like this:

$ ssh-keygen -t dsa
Generating public/private dsa key pair.
Enter file in which to save the key (/home/johndoe/.ssh/id_dsa): _


We can use SSH keys as a method of authentication to replace password-based logins. The keys are generated using the command ssh-keygen and should be assigned a passphrase under normal conditions.

By default, the keys will be created in the .ssh subdirectory of your home directory. To complete the process, you need to copy the public key (the .pub file) from the source system to the target machine in a .ssh subdirectory of your home directory on that machine, and you must name that file authorized_keys2.

Finally, it is critical that your .ssh subdirectories and their contents on both systems be suitably protected against tampering. Specifically, this means directories and files must belong to the appropriate user and not be writable by members of the group or the general public.



Configuration Files

In a Nutshell

There are three configuration files you need to know about:

  • /etc/ssh_config: System-wide defaults for all outgoing calls.
  • /etc/sshd_config: System-wide defaults for all incoming calls.
  • ~/.ssh/config: Individual user preferences for outgoing calls.

The first two are host settings, configured by the system administrator, while the last one is an optional set of personal SSH settings and can be modified by each individual user.

ssh_config: Outgoing Defaults

The file /etc/ssh_config contains default settings for any outgoing SSH transmission (which includes ssh, scp and sftp) initiated on the host where this file resides.

Generally, you will not need to modify this file as the system defaults are usually suitable for most people. Entries in this file can be commented out using the octothorpe ("#"). In fact, the file is usually delivered with default settings indicated by commented-out entries, like this:

#   CheckHostIP yes
#   StrictHostKeyChecking ask
#   Port 22
#   Protocol 2,1
# (etc.)

For example, in this segment, we see that the default port is set to 22 and the default protocol is "2" but will fall back to "1" if needed. You will not usually want to modify these defaults.

One possible exception is the "StrictHostKeyChecking" setting. The first time you call a system, the host key for that system is saved in your "known_hosts" file in your .ssh subdirectory. On subsequent calls, SSH will compare the remote machine's host key with the one you have on file and will warn you if it has changed. This is in case an impostor has managed to hijack the IP address of the remote system and is attempting to pose as that machine and trick you into logging in to the wrong system.

While this is a worthwhile safeguard, you may have reason to disable this feature in cases where you know the remote system's host key has changed for a valid reason, such as after reinstalling SSH or the OS, and the unwanted prompt might disrupt some automated transfers you have set up.

In this scenario, you would create an entry in /etc/ssh_config with the desired setting, like this:

#   CheckHostIP yes
#   StrictHostKeyChecking ask
StrictHostKeyChecking no
#   Port 22
#   Protocol 2,1

Note that we did not replace the commented-out entry but rather added a new line with the value we wanted. I recommend this approach when modifying any settings in order to preserve the original default value for reference purposes. You may want to return to that previous value some day and it is helpful to leave evidence of what it was prior to your changes.

sshd_config: Incoming Defaults

The term sshd stands for "SSH Daemon," which is the process that listens for connection requests on the network and determines whether they will be allowed. The file /etc/sshd_config is the configuration file for this daemon and is therefore critical to the security of your SSH service.

When the SSH daemon is started, it reads this file and adopts the settings you specified in it. For instance, if you wanted to disable password-based SSH logins, this is where you would do it. Similarly, if you needed your SSH daemon to monitor a different port than the standard port (22), this is the file you would edit to make that change.

As a general rule, the defaults in this file are reasonable and you should not modify them unless you understand what you are doing. Just like the ssh_config file we examined in the previous section, this file also includes commented-out entries for the most common parameters, indicating their default values.

Here is a sample segment from a typical sshd_config file:

# Port 22
# Protocol 2
PermitRootLogin yes
StrictModes yes
PermitEmptyPasswords no
PasswordAuthentication yes
ChallengeResponseAuthentication yes
# X11Forwarding yes
AllowUsers johndoe maryjane

In this example, I have shown the lines you are most likely to want to modify on your system. Here is a quick explanation of their purpose:

  • Port: Indicates the port number that SSH will listen on.
  • Protocol: Indicates which protocol your server will support. Valid values are either 2 for SSH-2, or 1 for SSH-1, or both "2,1" if you want your server to accept connections over either protocol. Most modern systems support protocol 2 by default. If your configuration file indicates only one supported protocol, clients attempting to connect using the other protocol will not get a connection.
  • PermitRootLogin: Do you want to allow remote users to SSH into your system directly as root? Generally, this is considered poor security policy because root is an anonymous user; you can't really tell who logged in as that user. However, on a trusted system such as your own LAN, you may find it convenient to login directly as root without the hassle of using su or sudo.
  • StrictModes: The first time you access a system over SSH, an entry is created in your known_hosts file to save the host key from that system. Every time you connect to that system again, SSH will check your known_hosts file to make sure the host key on the remote system is indeed what you have on file. If it isn't, SSH will assume an impostor is posing as this host and will deny the connection. This is called "strict host key checking," or "strict mode." This is usually a desirable feature but you may want to disable it if you have just changed your host key and don't want a bunch of users to be denied access to your system, especially if these involve automated processes such as system backups or remote printing.
  • PasswordAuthentication: If you want to disable password-based logins and force users to use authentication keys (recommended), set this parameter to "no." Note that you may also need to set ChallengeResponseAuthentication to "no" on PAM-enabled systems for this to work.
  • ChallengeResponseAuthentication: This setting is equivalent to PasswordAuthentication for systems that use PAM, the "Pluggable Authentication Module" interface. Since most modern systems use PAM, you should set this parameter to "no," along with PasswordAuthencation, if you don't want to allow password-based logins.
  • PermitEmptyPasswords: It's difficult to image a scenario where you would want to allow password-based logins and allow users to login without a password. Normally, if you want to allow paswordless logins, you will usually implement this with authentication keys, which are actually more secure than passwords. However, your might be in a special situation where you may want to allow users to get into a system without a password, possibly to allow potential customers to try out a piece of software for demonstration purposes. If this is the case, set this parameter to "yes" and be sure to allow password-based logins. In all other cases, you should make sure this parameter is set to "no."
  • AllowUsers: This is a handy parameter for password-enabled system. The AllowUsers parameter lets the system administrator specify a list of users who will be allowed to access the system; all others will be denied. For instance, the line AllowUsers john mary will restrict access to the login IDs john and mary only. Note that it only makes sense to use this parameter when password-based logins are enabled. If password-based logins are not allowed, access is already restricted to those users who have a valid authentication key installed in their account, so there is no need to also specify their names here.

For the full list of parameters, check out the man page for sshd_config.

NOTE: After you modify this file, you will have to restart your SSH daemon if it was already running. The command to do this will vary with the flavour of Linux or Unix you are running. For instance, on Ubuntu, you would enter the command service ssh restart. On OpenSuSE, you would enter rcsshd restart. On Mac OS X, you wouldn't need to restart the SSH daemon because it is invoked on demand rather than running in the background. Refer to your system documentation for the appropriate method for your environment.

Individual config file

While system defaults for outgoing SSH calls are saved in /etc/ssh_config, users may wish to set their own personal preferences different from the system defaults. This is done by simply adding the desired lines to the file config in the user's .ssh subdirectory.

For instance, if user john prefers to disable strict host checking when calling any system and wants to enable data compression, he would create a config file in his .ssh subdirectory containing the following lines:

StrictHostKeyChecking no
Compression yes

TIP: You can also specify options to ssh directly on the command line using the -o option, like this:
    ssh -o "Compression yes" some_system
This can be particularly useful when creating automated SSH transfers in shell scripts, for instance.



Port Forwarding


Port forwarding is one of the most mysterious, yet most useful, features of SSH. Using port forwarding, you can get a different type of connection (HTTP, telnet, X Window, SMB, printing, etc.) to "piggy-back" over your own SSH session in either direction. This is often called "tunnelling" as well.

For instance, let's say you need to reconfigure a client's router or printer. If you were sitting in their office, you would simply start up a Web browser and access the Web-based administrative tool on the device. However, since you are sitting in your own office, perhaps even in a different city, you don't have this option. Or do you?

If you have access to this system over SSH, you do have that option. Using the appropriate options to ssh, you would ask SSH to forward any HTTP packets originating from your system to the IP address of the device you are trying to configure on your client's LAN. And as if by magic, you can now access the configuration page on that device, right from your office!

Similarly, what if you wanted the remote host to send traffic back to your system, such as perhaps sending a print job to the printer sitting on your desk? The classic challenge with this is that your system is usually protected by a firewall, so the remote host cannot initiate a connection to send that print jobs. Using port forwarding, however, you can allow the remote host to "piggy-back" over your existing SSH connection to send this traffic back to your system, right through your firewall.

Finally, another common use of port forwarding is to allow an X Window application running on the server to display on your own monitor, again without having to open any ports on your firewall.

Let's have a look at each one of these examples in detail.

Forwarding a Local Port to the Remote Host

The -L option (for "Local port") allows you to forward a port from your local system to the remote host. Conceptually, it's like creating an alias that transforms a resource located on the remote system into one that resides on your own LAN.

For instance, let's say you would like to configure a router on a remote system, and let's also assume this router is not enabled for remote administration. Normally, you would have to be inside the network (i.e. sitting in the remote office) to access the administrative Web page on that router from inside the LAN. However, if you have an SSH connection to that remote host, you can relay your HTTP packets from your local machine to the target device using your SSH connection as the middle-man.

For instance, let's assume the router is at IP address on the remote LAN. To connect directly to it over port 80 (HTTP), simply invoke SSH like this to make your connection:

ssh -L 1234:  target_system 
In this example, we picked an arbitrary unused port (1234 in this case) and told SSH to map it to port 80 on device (the router) on the remote system. From this point forward, if you point your browser to port 1234 on your local system, your packets will automatically get forwarded to port 80 on the remote device. Specifically, you would simply enter the following URL in your Web browser and the admin page from the remote router would immediately appear on your screen:


Note that there is no particular significance to port number 1234; we simply picked any number that was not already being used on our system. The only restriction is that you cannot use port numbers below 1024 unless you are root; any other valid port number (1024-65535) is fair game.

Note also that the IP address we specified to the -L option represents the device we are attempting to connect to, not the IP address of the system we are calling.

Forwarding a Remote Port to the Local System

Just as we are able to "tunnel" packets for any port from our system to the remote host over an SSH connection, we can also do the exact opposite and relay packets from the remote system to our own.

For instance, let's assume you are sitting at home and accessing an application running on your office server. What if you would like this application to send print jobs directly to the printer sitting on your desk at home? If this printer is accessible over the network, you can fool the remote host into thinking your printer is a local device on its own network using port forwarding.

The -R option, for "Remote," tells SSH to redirect a given port on the remote site to a particular port and IP address on your local network.

For instance, let's assume your printer at home is sitting at IP address and uses the standard port 9100 for communications. You could map this device to an arbitrary unused port number on the remote system, say 3000, by invoking SSH like this:

ssh -R3000:  target_system

From that point on, anything the remote host sends to itself over port 3000 is automatically relayed to your network, care of IP address, port 9100.

The exact mechanism to configure print services to take advantage of this feature will depend on the operating system and type of print services used on the remote. For instance, if your office server uses lpd, you would need an entry like this in the /etc/printcap file:

mylaser: lp=localhost%3000:sd=/var/spool/lpd/mylaser:

This entry would create a printer destination named "mylaser," corresponding to your printer at home. On the other hand, if your office server uses CUPS, you would create this "mylaser" printer with the following command:

lpadmin -E -p mylaser -v socket://localhost:3000

The topic of printer configuration is outside the scope of this tutorial, but the above examples should be sufficient to point you in the right direction if you are already familiar with configuring printers under Linux.

Running X Window Applications

One very common and useful application of SSH's port-forwarding features is to run X Window applications remotely. For instance, if someone calls you with a problem they are having configuring their Web browser on their Linux system, it would be nice to be able to login under their ID on their system using SSH and start up the browser and have it show up on your own screen.

Fortunately, this can be done without using the complicated port-forwarding syntax we have just covered. To forward X Window packets to your own screen, simply invoke ssh with the -X option, like this:

ssh -X  user_name@system_name 

Once the SSH connection is established, you can then start the X Window application of your choice and the X packets will be relayed to your own X Window server, i.e. your own screen.

Of course, for this to work, you must be running X Window on your own system, which usually means you would be doing this from a Linux system at your end. While it is true that there are X Window servers available for Microsoft Windows and Mac OS X, these are not their native display system, so the -X option will not readily work under Windows and Mac OS X unless you have specifically arranged for an X server to be running.



Did you find an error on this page or do you have a comment?