OpenSSH: Secure Network Communication - Using Clients and Setting Up Servers - A practical guide to Fedora and Red Hat Enterprise Linux, 7th Edition (2014)

A practical guide to Fedora and Red Hat Enterprise Linux, 7th Edition (2014)

Part IV: Using Clients and Setting Up Servers

Chapter 18 OpenSSH: Secure Network Communication

Chapter 19 FTP: Transferring Files Across a Network

Chapter 20 sendmail: Setting Up Mail Servers, Clients, and More

Chapter 21 NIS and LDAP

Chapter 22 NFS: Sharing Directory Hierarchies

Chapter 23 Samba: Linux and Windows File and Printer Sharing

Chapter 24 DNS/BIND: Tracking Domain Names and Addresses

Chapter 25 firewalld and iptables: Setting Up a Firewall

Chapter 26 Apache (httpd): Setting Up a Web Server

Chapter 18. OpenSSH: Secure Network Communication

In This Chapter

Introduction to OpenSSH

Running the ssh, scp, and sftp OpenSSH Clients

JumpStart I: Using ssh and scp to Connect to an OpenSSH Server

Setting Up an OpenSSH Server (sshd)

Authorized Keys: Automatic Login

Troubleshooting

Tunneling/Port Forwarding


Objectives

After reading this chapter you should be able to:

Image Explain the need for encrypted services

Image Log in on a remote OpenSSH server system using ssh

Image Copy files and directories to and from a remote system securely

Image Set up an OpenSSH server

Image Configure OpenSSH server options

Image Set up a client/server so you do not need to use a password to log in using ssh or scp

Image Enable trusted X11 tunneling between the client and the OpenSSH server

Image Remove a known host record from the ~/.ssh/known_hosts file

Image Enable trusted X11 forwarding

Image List the uses of ssh tunneling (port forwarding)

OpenSSH is a suite of secure network connectivity tools that replaces telnet/telnetd, rcp, rsh/rshd, rlogin/rlogind, and ftp/ftpd. Unlike the tools they replace, OpenSSH tools encrypt all traffic, including passwords. In this way they can thwart malicious users who attempt to eavesdrop, hijack connections, and steal passwords.

This chapter covers the following OpenSSH tools:

• scp—Copies files to and from a remote system

• sftp—Copies files to and from a remote system (a secure replacement for ftp)

• ssh—Runs a command on or logs in on a remote system

sshd—The OpenSSH daemon (runs on the server)

• ssh-keygen—Creates, manages, and converts RSA or DSA host/user authentication keys

Introduction to OpenSSH

Using public key encryption (page 1157), OpenSSH provides two levels of authentication: server and client/user. First the client verifies it is connected to the correct server. Then OpenSSH encrypts communication between the systems. When a secure, encrypted connection has been established, OpenSSH makes sure the user is authorized to log in on or copy files to and from the server. After verifying the system and user, OpenSSH allows different services to be passed through the connection. These services include interactive shell sessions (ssh), remote command execution (ssh), file copying (scp), FTP services (sftp), X11 client/server connections, and TCP/IP port tunneling.

SSH1 versus SSH2

SSH protocol version 2 (SSH2) is a complete rewrite of SSH protocol version 1 (SSH1) that offers improved security, performance, and portability. The two protocols are not compatible. Because SSH1 is being rapidly supplanted by SSH2 and because SSH1 is vulnerable to a man-in-the-middle attack (page 1160), this chapter does not discuss SSH1. Because version 2 is floating-point intensive, version 1 does have a place on systems without FPUs (floating-point units or accelerators), such as old 486SX systems. As installed, the OpenSSH tools supplied with Fedora/RHEL support both protocols; you need run only one server to communicate with systems using either protocol.

ssh

The ssh utility allows you to log in on a remote system over a network. You might choose to use a remote system to access a special-purpose application or to take advantage of a device that is available only on that system, or you might use a remote system because you know it is faster or less busy than the local system. While traveling, many businesspeople use ssh on a laptop to log in on a system at company headquarters. From a GUI you can use several systems simultaneously by logging in on each one from a different terminal emulator window.

X11 forwarding

When you turn on trusted X11 forwarding on an ssh client, it is a simple matter to run a graphical program over an ssh connection to a server that has X11 forwarding enabled: Run ssh from a terminal emulator running on an X11 server and give an X11 command such as gnome-calculator; the graphical output appears on the local display. For more information refer to “Forwarding X11” on page 707.

Image How OpenSSH Works

When OpenSSH starts, it first establishes an encrypted connection and then authenticates the user. When these two tasks are complete, OpenSSH allows the two systems to send information back and forth.

keys

OpenSSH uses a host key pair and a session key to negotiate an encrypted session. The host key pair is a set of public/private keys that is established the first time the server system runs sshd (page 700). The session key is a symmetric key that the server and client share. For more information on keys see “Encryption” on page 1156.

The first time an OpenSSH client connects with an OpenSSH server, OpenSSH asks you to verify the client is connected to the correct server (see “First-time authentication” on page 691). This verification helps prevent a man-in-the-middle attack (page 1160). After verification, the client makes a copy of the server’s public host key. On subsequent connections, the client compares the key provided by the server with the original key it stored. Although this test is not foolproof, the next one is quite secure.

The client then generates a random key, which it encrypts with both the server’s public host key and the session key. The client sends this encrypted key to the server. The server, in turn, uses its private keys to decrypt the encrypted key. This process creates the session key, a key that is known only to the client and the server and is used to encrypt the rest of the session.

Files

OpenSSH clients and servers rely on many files. Global files are kept in /etc/ssh and user files in ~/.ssh. In this section, the first word in the description of each file indicates whether the client or the server uses the file.


Security: rhost authentication is a security risk

Although OpenSSH can get authentication information from /etc/hosts.equiv, /etc/shosts.equiv, ~/.rhosts, and ~/.shosts, this chapter does not cover the use of these files because they present security risks. The default settings in the /etc/ssh/sshd_config configuration file prevent their use.


/etc/ssh: Global Files

Global files listed in this section appear in the /etc/ssh directory. They affect all users, but a user can override them with files in her ~/.ssh directory.

moduli

client and server Contains key exchange information that OpenSSH uses to establish a secure connection. Do not modify this file.

ssh_config

client The global OpenSSH configuration file (page 698). Entries here can be overridden by entries in a user’s ~/.ssh/config file.

sshd_config

server The configuration file for sshd (page 704).

Image ssh_host_dsa_key, ssh_host_dsa_key.pub

server SSH protocol version 2 DSA host keys. Both files should be owned by root. The ssh_host_dsa_key.pub public file should be readable by anyone but writable only by its owner (644 permissions). The ssh_host_dsa_key private file should not be readable or writable by anyone except its owner (600 permissions).

ssh_host_key, ssh_host_key.pub

server SSH protocol version 1 host keys. Both files should be owned by root. The ssh_host_key.pub public file should be readable by anyone but writable only by its owner (644 permissions). The ssh_host_key private file should not be readable or writable by anyone except its owner (600 permissions).

Image ssh_host_rsa_key, ssh_host_rsa_key.pub

server SSH protocol version 2 RSA host keys. Both files should be owned by root. The ssh_host_rsa_key.pub public file should be readable by anyone but writable only by its owner (644 permissions). The ssh_host_rsa_key private file should not be readable or writable by anyone except its owner (600 permissions).

ssh_known_hosts

client Contains public RSA (by default) keys of hosts that users on the local system can connect to. This file contains information similar to that found in ~/.ssh/known_hosts but is set up by the administrator and is available to all users. This file should be owned by root and should be readable by anyone but writable only by its owner (644 permissions).

~/.ssh: User Files

OpenSSH creates the ~/.ssh directory and the known_hosts file therein automatically when a user connects to a remote system.

Image authorized_keys

server Enables a user to log in on or copy files to and from another system without supplying a user login password (page 700). However, the user might need to supply a passphrase, depending on how the key was set up. No one except the owner should be able to write to this file.

config

client A user’s private OpenSSH configuration file (page 698). Entries here override those in /etc/ssh/ssh_config.

environment

server Contains assignment statements that define environment variables on a server when a user logs in using ssh.

Image id_dsa id_dsa.pub

client User authentication DSA keys generated by ssh-keygen (page 701). Both files should be owned by the user in whose home directory they appear. The id_dsa.pub public file should be readable by anyone but writable only by its owner (644 permissions). The id_dsa private file should not be readable or writable by anyone except its owner (600 permissions).

Image id_rsa id_rsa.pub

client User authentication RSA keys generated by ssh-keygen (page 701). Both files should be owned by the user in whose home directory they appear. The id_rsa.pub public file should be readable by anyone but writable only by its owner (644 permissions). The id_rsa private file should not be readable or writable by anyone except its owner (600 permissions).

known_hosts

client Contains public RSA keys (by default) of hosts the user has connected to. OpenSSH automatically adds entries each time the user connects to a new server (page 690). Refer to “HostKeyAlgorithms” (page 699) for information on using DSA keys. If HashKnownHosts (page 699) is set to yes, the hostnames and addresses in this file are hashed to improve security.

More Information

Local

man pages: ssh, scp, sftp, ssh-keygen, ssh_config, sshd, sshd_config

Web

OpenSSH home page: www.openssh.com

Search on ssh to find various HOWTOs and other documents: tldp.org

Books

Implementing SSH: Strategies for Optimizing the Secure Shell by Dwivedi; John Wiley & Sons (October 2003)

SSH, The Secure Shell: The Definitive Guide by Barrett, Silverman, & Byrnes; O’Reilly Media (May 2005)

Image Running the ssh, scp, and sftp OpenSSH Clients

This section covers setting up and using the ssh, scp, and sftp clients.

Prerequisites

Install the following package (both are installed by default):

openssh

openssh-clients

OpenSSH clients do not run a daemon so there is no service to set up.

JumpStart I: Using ssh and scp to Connect to an OpenSSH Server

The ssh and scp clients do not require setup beyond installing the requisite packages, although you can create and edit files that facilitate their use. To run a secure shell on or securely copy a file to or from a remote system, the following criteria must be met: The remote system must be running the OpenSSH daemon (sshd), you must have an account on the remote system, and the server must positively identify itself to the client.

ssh

The following example shows Zach using ssh to log in on the remote host named plum, running who, and finally giving an exit command to return to the shell on the local system. The who utility displays the hostname of the system Zach logged in from.

[zach@guava ~]$ ssh zach@plum
zach@plum's password:
Last login: Wed Jun 12 16:34:10 2013 from guava
[zach@plum ~]$ who am i
zach pts/1 2013-06-12 16:38 (guava)
[zach@plum ~]$ exit
logout
Connection to plum closed.
[zach@guava ~]$

You can omit user@ (zach@ in the preceding example) from the command line if you want to log in as yourself and you have the same username on both systems. The first time you connect to a remote OpenSSH server, ssh or scp asks you to confirm that you are connected to the right system. Refer to “First-time authentication” on page 691.

scp

The following example uses scp to copy ty1 from the working directory on the local system to Zach’s home directory on plum:

$ scp ty1 zach@plum:
zach@plum's password:
ty1 100% 97KB 96.8KB/s 00:00

Remember to follow the system name with a colon (:). If you omit the colon, scp copies the file locally; in the example you would end up with a copy of ty1 named zach@plum.

Image Configuring OpenSSH Clients

This section describes how to set up OpenSSH on the client side.

Recommended Settings

X11 forwarding

The configuration files provided by Fedora/RHEL establish a mostly secure system that might or might not meet your needs. One OpenSSH parameter you might want to change is ForwardX11Trusted, which is set to yes in the /etc/ssh/ssh_config configuration file (page 698). To increase security, and in some cases reduce usability, set ForwardX11Trusted to no. See page 707 for more information on X11 forwarding.

Server Authentication/Known Hosts

Two files list the hosts the local system has connected to and positively identified: ~/.ssh/known_hosts (user) and /etc/ssh/ssh_known_hosts (global). No one except the owner (root in the case of the second file) should be able to write to either of these files. No one except the owner should have any access to a ~/.ssh directory.

First-time authentication

When you connect to an OpenSSH server for the first time, the OpenSSH client prompts you to confirm that you are connected to the right system. This behavior is controlled by StrictHostKeyChecking (page 699). This check can help prevent a man-in-the-middle attack (page 1160):

The authenticity of host 'plum (192.168.206.181)' can't be established.
RSA key fingerprint is d1:9d:1b:5b:97:5c:80:e9:4b:41:9a:b7:bc:1a:ea:a1.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'plum,192.168.206.181' (RSA) to the list of
known hosts.

Before you respond to the preceding query, make sure you are logging in on the correct system and not on an imposter. If you are not sure, a telephone call to someone who logs in on that system locally can help verify that you are on the intended system. When you answer yes (you must spell it out), the client appends the server’s public host key (the single line in the /etc/ssh/ssh_host_rsa_key.pub or /etc/ssh/ssh_host_dsa_key.pub file on the server) to the user’s ~/.ssh/known_hosts file on the local system, creating the ~/.ssh directory if necessary. So that it can keep track of which line in known_hosts applies to which server, OpenSSH prepends the name of the server and the server’s IP address to the line.

When you subsequently use OpenSSH to connect to that server, the client verifies it is connected to the correct server by comparing this key to the one supplied by the server.

known_hosts

The ~/.ssh/known_hosts file uses one or two very long lines to identify each host it keeps track of. Each line starts with the hostname and IP address of the system the line corresponds to, followed by the type of encryption being used and the server’s public host key. WhenHashKnownHosts (page 699) is set to yes (the default is no), OpenSSH hashes the system name and address to improve security. Because HashKnownHosts hashes the hostname and IP address separately, OpenSSH puts two lines in known_hosts for each host. The following line (it is one logical line that wraps on to several physical lines) from known_hosts is used to connect to plum at 192.168.206.181 using RSA (page 1271) encryption:

$ cat ~/.ssh/known_hosts
plum,192.168.206.181 ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDbhLRVTfI
v9gy7oP+5T3HjZmrKt2q6ydyKmLlHNUjZFXM4hCdkJlpTfJ4wy260UAZBWvrBLP6N9k
...

You can use ssh-keygen with the –R option followed by the hostname to remove an entry, even a hashed one. Alternately, you can use a text editor to remove an entry. The –F option to ssh-keygen displays a line in a known_hosts file that corresponds to a specified system, even if the entry is hashed:

$ ssh-keygen -F plum
# Host plum found: line 1 type RSA
plum ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDbhLRVTfIv9gy7oP+5T3HjZmr
Kt2q6ydyKmLlHNUjZFXM4hCdkJlpTfJ4wy260UAZBWvrBLP6N9kYA+KRG1FyuwROUwXQ
...

Image ssh_known_hosts

OpenSSH automatically stores keys from servers it has connected to in user-private files (~/.ssh/known_hosts). These files work only for the user whose directory they appear in. Working with root privileges and using a text editor, you can copy nonhashed lines from a user’s private list of known hosts to the public list in /etc/ssh/ssh_known_hosts to make a server known globally on the local system.

The following example shows how Sam puts the hashed entry from his known_hosts file into the global ssh_known_hosts file. First, working as himself, Sam sends the output of ssh-keygen through tail to strip off the Host plum found line and redirects the output to a file namedtmp_known_hosts in his home directory. Next, working with root privileges, Sam appends the contents of the file he just created to /etc/ssh/ssh_known_hosts. This command creates this file if it does not exist. Finally, Sam returns to working as himself and removes the temporary file he created.

$ ssh-keygen -F plum | tail -1 > ~sam/tmp_known_hosts
$ su
Password:
# cat ~sam/tmp_known_hosts >> /etc/ssh/ssh_known_hosts
# exit
exit
$ rm ~/tmp_known_hosts

If, after a remote system’s public key is stored in one of the known-hosts files, the remote system supplies a different fingerprint when the systems connect, OpenSSH displays the following message and does not complete the connection:

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that the RSA host key has just been changed.
The fingerprint for the RSA key sent by the remote host is
f1:6f:ea:87:bb:1b:df:cd:e3:45:24:60:d3:25:b1:0a.
Please contact your system administrator.
Add correct host key in /home/sam/.ssh/known_hosts to get rid of this message.
Offending key in /home/sam/.ssh/known_hosts:1
RSA host key for plum has changed and you have requested strict checking.
Host key verification failed.

If you see this message, you might be the subject of a man-in-the-middle attack. More likely, however, something on the remote system has changed, causing it to supply a new fingerprint. Check with the remote system’s administrator. If all is well, remove the offending key from the specified file (the third line from the bottom in the preceding message points to the line you need to remove) and try connecting again. You can use ssh-keygen with the –R option followed by the name of a host to remove a hashed entry. You will be subject to first-time authentication (page691) again as OpenSSH verifies you are connecting to the correct system. Follow the same steps as when you initially connected to the remote host.

Image ssh: Logs in or Executes Commands on a Remote System

The format of an ssh command line is

ssh [options] [user@]host [command]

where host, the name of the OpenSSH server (the remote system) you want to connect to, is the only required argument. The host can be a local system name, the FQDN (page 1250) of a system on the Internet, or an IP address.

With the command ssh host, you log in on the remote system host with the same username you are using on the local system. The remote system displays a shell prompt, and you can run commands on host. Enter the command exit to close the connection to host and return to the local system’s prompt. Include user@ when you want to log in with a username other than the one you are using on the local system. Depending on how the server is set up, you might need to supply the password you use on the remote system.

When you include command, ssh logs in on host, executes command, closes the connection to host, and returns control to the local system. The remote system never displays a shell prompt.

Opening a remote shell

In the following example, Sam, who is logged in on guava, uses ssh to log in on plum, gives a uname command that shows the name and type of the system, and uses exit to close the connection to plum and return to the local system’s prompt:

[sam@guava ~]$ ssh plum
sam@plum's password:
Last login: Wed Jun 12 16:55:47 2013 from guava
[sam@plum ~]$ uname -nm
plum x86_64
[sam@plum ~]$ exit
logout
Connection to plum closed.
[sam@guava ~]$

Running commands remotely

The following example uses ls to display a listing of the files in the memos directory on the remote system plum. The example assumes the user running the command (Sam) has a login on plum and that the memos directory is in Sam’s home directory on plum:

$ ssh plum ls memos
sam@plum's password:
memo.0921
memo.draft
$

When you run ssh, standard output of the command run on the remote system is passed to the local shell as though the command had been run on the local system. As with all shell commands, you must quote special characters you do not want the local shell to interpret.

In the next example, standard output of the ls command, which is run on the remote system, is sent to ls.out on the local system.

$ ssh plum ls memos > ls.out
sam@plum's password:
$ cat ls.out
memo.0921
memo.draft

In the preceding ssh command the redirect symbol (>) is not quoted, so it is interpreted by the local shell and creates the ls.out file on the local system.

The next command is similar, but the redirect symbol is quoted, so the local shell does not interpret it but passes it to the remote shell. The first command creates the ls.out2 file on the remote system, and the second command displays the file.

$ ssh plum 'ls memos > ls.out2'
sam@plum's password:
$ ssh plum cat ls.out2
sam@plum's password:
memo.0921
memo.draft

For the next example, assume the working directory on the local system holds a file named memo.new. You cannot remember whether this file contains certain changes or whether you made these changes to the file named memo.draft in the memos directory on plum. You could copymemo.draft to the local system and run diff (page 227) on the two files, but then you would have three similar copies of the file spread across two systems. If you are not careful about removing the old copies when you are done, you might just become confused again in a few days. Instead of copying the file, you can use ssh. This example shows that only the date line differs between the two files:

$ ssh plum cat memos/memo.draft | diff memo.new -
sam@plum's password:
1c1
< Wed Jun 14 12:22:14 PDT 2013
---
> Wed Jun 12 17:05:51 PDT 2013

In the preceding example, the output of the cat command on plum is sent through a pipeline on the local system to diff (running on the local system), which compares the local file memos.new to standard input (). The following command line has the same effect but causes diff to run on the remote system:

$ cat memo.new | ssh plum diff - memos/memo.draft
sam@plum's password:
1c1
< Wed Jun 14 12:22:14 PDT 2013
---
> Wed Jun 12 17:05:51 PDT 2013

Standard output from diff on the remote system is sent to the local shell, which displays it on the screen (because it is not redirected).

Options

This section describes some of the options you can use with ssh.

–C

(compression) Enables compression (page 710). In the commercial version of ssh, –C disables compression and +C enables compression.

–f

(not foreground) Sends ssh to the background after asking for a password and before executing the command. Useful when you want to run the command in the background but must supply a password. Implies –n.

–i filename

(identity) Instructs ssh to read the private key from filename instead of ~/.ssh/id_dsa or ~/.ssh/id_rsa for automatic login (page 700). See page 680 for an example.

–L

Forwards a port on the local system to a remote system. For more information refer to “Tunneling/Port Forwarding” on page 707.

–l user

(login) Attempts to log in as user.

–n

(null) Redirects standard input to ssh to come from /dev/null. Required when running ssh in the background (–f option).

–o option

(option) Specifies option in the format used in configuration files (page 698).

–p

(port) Specifies the port on the remote host that the connection is made to. Using the host declaration (page 699) in the configuration file, you can specify a different port for each system you connect to.

–R

Forwards a port on the remote system to the local client. For more information refer to “Tunneling/Port Forwarding” on page 707.

–t

(tty) Allocates a pseudo-tty (terminal) to the ssh process on the remote system. Without this option, when you run a command on a remote system, ssh does not allocate a tty (terminal) to the process. Instead, it attaches standard input and standard output of the remote process to the sshsession—which is normally, but not always, what you want. This option forces ssh to allocate a tty on the remote system so programs that require a tty will work.

–v

(verbose) Displays debugging messages about the connection and transfer. Useful if things are not going as expected. Repeat this option up to a total of three times to increase verbosity.

–X

(X11) Turns on nontrusted X11 forwarding. This option is not necessary if you turn on nontrusted X11 forwarding in the configuration file. For more information refer to “Forwarding X11” on page 707.

–x

(X11) Turns off X11 forwarding.

–Y

(X11trusted) Turns on trusted X11 forwarding. This option is not necessary if you turn on trusted X11 forwarding in the configuration file. For more information refer to “Forwarding X11” on page 707.

scp: Copies Files to and from a Remote System

The scp (secure copy) utility copies an ordinary or directory file from one system to another over a network; both systems can be remote. This utility uses ssh to transfer files and employs the same authentication mechanism as ssh; thus it provides the same security as ssh. The scp utility asks for a password when one is required. The format of an scp command is

scp [[user@]from-host:]source-file [[user@]to-host:][destination-file]

where from-host is the name of the system you are copying files from and to-host is the system you are copying to. The from-host and to-host arguments can be local system names, FQDNs (page 1250) of systems on the Internet, or IP addresses. When you do not specify a host, scp assumes the local system. The user on either system defaults to the user on the local system who is giving the command; you can specify a different user with user@.

The source-file is the file you are copying, and the destination-file is the resulting copy. Make sure you have read permission for the file you are copying and write permission for the directory you are copying it into. You can specify plain or directory files as relative or absolute pathnames. (A relative pathname is relative to the specified directory or to the implicit user’s home directory.) When the source-file is a directory, you must use the –r option to copy its contents. When the destination-file is a directory, each of the source files maintains its simple filename. When thedestination-file is missing, scp assumes the user’s home directory.

Suppose Sam has an alternate username, sls, on plum. In the following example, Sam uses scp to copy memo.txt from the home directory of his sls account on plum to the allmemos directory in the working directory on the local system. If allmemos were not the name of a directory,memo.txt would be copied to a file named allmemos in the working directory.

[sam@guava ~]$ scp sls@plum:memo.txt allmemos
sls@plum's password:
memo.txt 100% 12KB 12.3KB/s 00:00

As the transfer progresses, the percentage and number of bytes transferred increase, and the time remaining decreases.


Tip: rsync is much more versatile than scp

The rsync utility is more configurable than scp and uses OpenSSH security by default. It has many options; the most commonly used are –a and –v. The –a option causes rsync to copy ordinary files and directories, preserving the ownership, group, permissions, and modification times associated with the files. It usually does no harm to specify the –a option and frequently helps. The –v option causes rsync to list files as it copies them. For example, Sam could have given the preceding command as

$ rsync -av sls@plum:memo.txt allmemos
sls@plum's password:
receiving incremental file list
memo.txt

sent 30 bytes received 87495 bytes 19450.00 bytes/sec
total size is 87395 speedup is 1.00

The rsync utility is also smarter than scp. If the source and destination files exist, rsync copies only the parts of the source file that are different from the destination file. This feature can save a lot of time when copying large files with few changes, such as when making backups. The number following speedup in the output indicates how much rsync’s algorithm has speeded up the process of copying a file.


In the next example, Sam, while working from guava, copies the same file as in the previous example to the directory named old in his home directory on speedy. For this example to work, Sam must be able to use ssh to log in on speedy from plum without using a password. For more information refer to “Authorized Keys: Automatic Login” on page 700.

[sam@guava ~]$ scp sls@plum:memo.txt speedy:old
sls@plum's password:

Options

This section describes some of the options you can use with scp.

–C

(compression) Enables compression (page 710).

–o option

(option) Specifies option in the format used in configuration files (discussed shortly).

–P port

(port) Connects to port port on the remote host. This option is uppercase for scp and in lowercase for ssh.

–p

(preserve) Preserves the modification and access times as well as the modes of the original file.

–q

(quiet) Does not display the progress information as scp copies a file.

–r

(recursive) Recursively copies a directory hierarchy (follows symbolic links).

–v

(verbose) Displays debugging messages about the connection and transfer. Useful if things are not going as expected.

sftp: A Secure FTP Client

As part of OpenSSH, Fedora/RHEL provides sftp, a secure alternative to ftp (page 713). Functionally the same as ftp, sftp maps ftp commands to OpenSSH commands. You can replace ftp with sftp when you are logging in on a server that is running the OpenSSH daemon, sshd. When you are connected to a system with sftp, enter the command ? to display a list of commands. For secure communication, use sftp or scp to perform all file transfers requiring authentication. Refer to the sftp man page for more information.

lftp

Fedora/RHEL also offers lftp, which is more sophisticated than sftp and supports sftp. The lftp utility provides a shell-like command syntax that has many features, including support for tab completion and the ability to run jobs in the background. Place the following .lftprc file in your home directory to ensure lftp uses OpenSSH to connect to a server.

$ cat ~/.lftprc
set default-protocol sftp

You can also use /etc/lftp.conf to configure lftp; see the lftp man page for more information.

~/.ssh/config and /etc/ssh/ssh_config Configuration Files

It is rarely necessary to modify OpenSSH client configuration files. For a given user there might be two configuration files: ~/.ssh/config (user) and /etc/ssh/ssh_config (global). These files are read in this order and, for a given parameter, the first one found is the one OpenSSH uses. A user can override a global parameter setting by setting the same parameter in her user configuration file. Parameters given on the ssh or scp command line take precedence over parameters set in either of these files.

For security, a user’s ~/.ssh/config file should be owned by the user in whose home directory it appears and should not be writable by anyone except the owner. This file is typically set to mode 600 as there is no reason for anyone except its owner to be able to read it.

Lines in the configuration files contain declarations. Each of these declarations starts with a keyword that is not case sensitive. Some keywords must be followed by whitespace and one or more case-sensitive arguments. You can use the Host keyword to cause declarations to apply to a specific system. A Host declaration applies to all the lines between it and the next Host declaration.

Following are some of the keywords and arguments you can specify:

CheckHostIP yes | no

Identifies a remote system using the IP address in addition to a hostname from the known_hosts file when set to yes. Set it to no to use a hostname only. Setting CheckHostIP to yes can improve system security. Default is yes.

ForwardX11 yes | no

When set to yes, automatically forwards X11 connections over a secure channel in nontrusted mode and sets the DISPLAY shell variable. Fedora/RHEL allows this keyword to default to no so X11 forwarding is not initially enabled. If ForwardX11Trusted is also set to yes, the connections are made in trusted mode. Alternately, you can use –X on the command line to redirect X11 connections in nontrusted mode. For X11 forwarding to work, you must also set X11Forwarding to yes in the /etc/sshd_config file on the server (page 706). For more information refer to “Forwarding X11” on page 707.

ForwardX11Trusted yes | no

Works in conjunction with ForwardX11, which must be set to yes for this keyword to have any effect. When this keyword is set to yes (as it is under Fedora/RHEL) and ForwardX11 is set to yes, this keyword gives remote X11 clients full access to the original (server) X11 display. Alternately, you can use –Y on the command line to redirect X11 connections in trusted mode. For X11 forwarding to work, X11Forwarding must also be set to yes in the /etc/sshd_config file on the server (page 706). Default value is no, but Fedora/RHEL sets this keyword to yes. For more information refer to “Forwarding X11” on page 707.

HashKnownHosts

Causes OpenSSH to hash hostnames and addresses in the ~/.ssh/known_hosts file when set to yes. When set to no, the hostnames and addresses are written in cleartext. Default is no. See page 691 for more information on the known_hosts file.

Host hostnames

Specifies that the following declarations, until the next Host declaration, apply only to hosts that hostnames matches. The hostnames is a whitespace-separated list that can include ? and * wildcards. A single * specifies all hosts. Without this keyword, all declarations apply to all hosts.

HostbasedAuthentication yes | no

Tries rhosts authentication when set to yes. For a more secure system, set to no. Default is no.

HostKeyAlgorithms algorithms

The algorithms is a comma-separated list of algorithms the client uses in order of preference. Choose algorithms from ssh-rsa or ssh-dss. Default is ssh-rsa,ssh-dss.

Port num

Causes OpenSSH to connect to the remote system on port num. Default is 22.

StrictHostKeyChecking yes | no | ask

Determines whether and how OpenSSH adds host keys to a user’s known_hosts file. Set this option to ask to ask whether to add a host key when connecting to a new system, set it to no to add a host key automatically, and set it to yes to require host keys to be added manually. The yes andask arguments cause OpenSSH to refuse to connect to a system whose host key has changed. For a more secure system, set to yes or ask. Default is ask.

TCPKeepAlive yes | no

Periodically checks whether a connection is alive when set to yes. Checking causes the ssh or scp connection to be dropped when the server crashes or the connection dies for another reason, even if it is only temporary. This option tests the connection at the transport (TCP) layer (page 291). Setting this parameter to no causes the client not to check whether the connection is alive. Default is yes.

This declaration uses the TCP keepalive option, which is not encrypted and is susceptible to IP spoofing (page 1256). Refer to ClientAliveInterval on page 704 for a server-based nonspoofable alternative.

User name

Specifies a username to use when logging in on a system. You can specify a system with the Host declaration. This option means you do not have to enter a username on the command line when you are using a username that differs from your username on the local system.

VisualHostKey yes | no

Displays an ASCII art representation of the key of the remote system in addition to displaying the hexadecimal representation of the key when set to yes. When set to no, this declaration displays the hexadecimal key only. For more information refer to “Randomart” on page 702. Default isno.

Setting Up an OpenSSH Server (sshd)

This section describes how to set up an OpenSSH server.

Prerequisites

Install the following packages (both are installed by default):

openssh

openssh-server

Check sshd is running

A new Fedora/RHEL system boots with sshd installed and running. Use the systemctl status command to make sure the service is running.

# systemctl status sshd.service

After modifying sshd configuration files, give the second command again, replacing status with restart to cause sshd to reread those files.

When the system is booted just after it is installed, the sshd daemon is started and automatically creates host key files (page 687) in /etc/ssh. OpenSSH uses the files it creates to identify the server.

Notes

Firewall

An OpenSSH server normally uses TCP port 22. Under Fedora/RHEL, this port is open when the system is installed. If the OpenSSH server system is running a firewall, this port must be open.

SELinux

When SELinux is set to use a targeted policy, sshd is protected by SELinux. You can disable this protection if necessary. For more information refer to “Setting the Targeted Policy with system-config-selinux” on page 475.

JumpStart II: Starting an OpenSSH Server

By default, the sshd server is installed and running when you first boot a Fedora/RHEL system (page 700). You can look in /var/log/secure and /var/log/messages or give the command systemctl status httpd to make sure everything is working properly.

Recommended Settings

The configuration files provided by Fedora/RHEL establish a mostly secure system that might or might not meet your needs. The Fedora/RHEL /etc/ssh/sshd_config file turns on X11 forwarding (page 707). It is important to set PermitRootLogin (page 705) to no, which prevents a known-name, privileged account from being exposed to the outside world with only password protection.

Image Authorized Keys: Automatic Login

You can configure OpenSSH so you do not have to enter a password each time you connect to a server (remote system). To set up this feature, you need to generate a personal authentication key on the client (local system), place the public part of the key on the server, and keep the private part of the key on the client. When you connect to the server, it issues a challenge based on the public part of the key. OpenSSH then uses the private part of the key to respond to this challenge. If the client provides the appropriate response, the server logs you in.

The first step in setting up an automatic login is to generate your personal authentication keys. First check whether these authentication keys already exist on the local system (client) by looking in ~/.ssh for either id_dsa and id_dsa.pub or id_rsa and id_rsa.pub. If one of these pairs of files is present, skip the next step (do not create a new key).

Image ssh-keygen

On the client, the ssh-keygen utility creates the public and private parts of an RSA key. The key’s randomart image is a visual representation of the public key; see page 702.

$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/sam/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/sam/.ssh/id_rsa.
Your public key has been saved in /home/sam/.ssh/id_rsa.pub.
The key fingerprint is:
23:8f:99:2e:43:36:93:ed:c6:38:fe:4d:04:61:27:28 sam@guava
The key's randomart image is:
+--[ RSA 2048]----+
| .+ . |
| E .. + |
| . . |
| . |
| o. S |
| * .B . |
| o *+ o |
| =.+o |
| ..*o . |
+-----------------+

Replace rsa with dsa to generate DSA keys. In this example, the user pressed RETURN in response to each query. You have the option of specifying a passphrase (10–30 characters is a good length) to encrypt the private part of the key. There is no way to recover a lost passphrase. See the security tip on page 703 for more information about the passphrase.

Image id_rsa and id_rsa.pub

The ssh-keygen utility generates two keys: a private key or identification in ~/.ssh/id_rsa and a public key in ~/.ssh/id_rsa.pub. No one except the owner should be able to write to either of these files, and only the owner should be able to read from the private key file.

You can display the local server’s RSA key fingerprint using ssh-keygen:

$ ssh-keygen -lf /etc/ssh/ssh_host_rsa_key.pub
2048 d1:9d:1b:5b:97:5c:80:e9:4b:41:9a:b7:bc:1a:ea:a1 /etc/ssh/ssh_host_rsa_key.pub (RSA)

Or you can display the fingerprint of the public key you just created:

$ ssh-keygen -lf ~/.ssh/id_rsa.pub
2048 23:8f:99:2e:43:36:93:ed:c6:38:fe:4d:04:61:27:28 /home/sam/.ssh/id_rsa.pub sam@plum (RSA)

ssh-copy-id

To log in on or copy files to and from another system without supplying a password, you must copy the ~/.ssh/id_rsa.pub from the client (local system) to a file named ~/.ssh/authorized_keys on the server (remote system). The ssh-copy-id utility creates the ~/.ssh directory on the server if necessary, copies id_rsa.pub, and makes sure permissions are correct. The following example shows Sam setting up automatic login on the system named plum:

$ ssh-copy-id sam@plum
sam@plum's password:
...
Number of key(s) added: 1

Now try logging into the machine, with: "ssh 'sam@plum'"
and check to make sure that only the key(s) you wanted were added.

$ ssh sam@plum
$

Sam must supply his password to copy the file to plum. After running ssh-copy-id, Sam can log in on plum without providing a password. To make the server even more secure, disable password authentication (see the adjacent tip).


Security: Use a personal authentication key instead of a password

Using a personal authentication key is more secure than using a password. When you turn off password authentication, brute force authentication attacks become very unlikely.

Disable password authentication by setting PasswordAuthentication to no in /etc/ssh/sshd_config (remove the # from the beginning of the PasswordAuthentication line and change the yes to no; page 705).


Randomart

The randomart image of a system is an experimental OpenSSH ASCII visualization of the system’s host key. This image is displayed by OpenSSH utilities, including ssh, scp, and ssh-keygen. Its display is controlled by the VisualHostKey keyword in the ssh_config file (page 699). With this keyword set to yes, OpenSSH displays a system’s randomart image when you connect:

$ ssh plum
Host key fingerprint is 0b:90:12:02:97:fb:93:6e:d4:14:f8:e0:ac:f3:26:36
+--[ RSA 2048]----+
|+ o. . |
| o..o.. |
| .+oo . |
| ..o.o |
| o +. S |
| o = .. . |
| = . . |
| E = |
| . = |
+-----------------+

sam@plum's password:
...

The randomart image renders a system’s host key in a visual format that can be easier to recall than a host key fingerprint (see the preceding example). Making it easier for a user to detect a change in the fingerprint can mean that a user will be aware when he is connecting to a system other than the one he intended to connect to.

Image ssh-agent: Holds Your Private Keys


Security: Personal key encryption, passphrase, and ssh-agent

The private part of your personal authentication key is kept in a file that only you can read. When you set up automatic login on a remote system, any user who has access to your account on the local system also has access to your account on the remote system because that user can read the private part of your personal key. Thus, if a malicious user compromises your account or the root account on the local system, that user then has access to your account on the remote system.

Encrypting the private part of your personal key protects the key and, therefore, restricts access to the remote system should someone compromise your local account. However, if you encrypt your personal key, you must supply the passphrase you used to encrypt the key each time you use the key, negating the benefit of not having to type a password when logging in on the remote system.

You can use ssh-agent to remember the private part of your personal key for the duration of a session; you supply your passphrase once, at the beginning of the session.



Security: Storing private keys on a removable medium

You can store the private keys on a removable medium, such as a USB flash drive, and use your ~/.ssh directory as the mount point for the filesystem stored on this drive. You might want to encrypt these keys with a passphrase in case you lose the flash drive.


When you use ssh-keygen to generate a public/private key pair, you have the option of specifying a passphrase. If you specify a passphrase, you must supply that passphrase each time you use the key. The result is, when you set up a key pair to avoid specifying your password when you log in on a remote system using ssh, you end up supplying the passphrase instead.

The ssh-agent utility allows you to use a passphrase with your personal key while entering the key one time, at the beginning of each session. When you log out, ssh-agent forgets the key. Because Fedora/RHEL is set up with ssh-agent enabled for X sessions, it is very easy to use in a graphical environment. It is also easy to set up in a textual environment.

If you are running a textual session (not within a terminal emulator window), you must give the following command to enable ssh-agent. If you are running a graphical session, skip this step (ssh-agent is set up in the files in /etc/X11/xinit/xinitrc).

$ eval $(ssh-agent -s)
Agent pid 9882

Image ssh-add

Once ssh-agent is enabled, use ssh-add to specify the passphrase for a key pair:

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

If you omit the argument to ssh-add, it adds a passphrase for each of the ~/.ssh/id_rsa, ~/.ssh/id_dsa, and ~/.ssh/identity files that exist.

With this setup, you can use ssh to work on a remote system without supplying a login password and by supplying your passphrase one time per session.

Command-Line Options

Command-line options override declarations in the configuration files. Following are descriptions of some of the more useful sshd options.

–D

(noDetach) Keeps sshd in the foreground. Useful for debugging; implied by –d.

–d

(debug) Sets debug mode so that sshd sends debugging messages to the system log and the server stays in the foreground (implies –D). You can specify this option a maximum of three times to increase the verbosity of the output. See also –e. (The ssh client uses –v for debugging; page 695.)

–e

(error) Sends output to standard error, not to the system log. Useful with –d.

–f file

Specifies file as the configuration file instead of /etc/ssh/sshd_config.

–t

(test) Checks the configuration file syntax and the sanity of the key files.

/etc/ssh/sshd_config Configuration File

Lines in the /etc/ssh/sshd_config configuration file contain declarations. Each of these declarations starts with a keyword that is not case sensitive. Some keywords must be followed by whitespace and one or more case-sensitive arguments. You must reload the sshd server before these changes will take effect.

AllowUsers userlist

The userlist is a SPACE-separated list of usernames that specifies which users are allowed to log in using sshd. This list can include * and ? wildcards. You can specify a user as user or user@host. If you use the second format, make sure you specify the host as returned by hostname. Without this declaration, any user who can log in locally can log in using an OpenSSH client. Does not work with numeric user IDs.

ClientAliveCountMax n

The n specifies the number of client-alive messages that can be sent without receiving a response before sshd disconnects from the client. See ClientAliveInterval. Default is 3.

ClientAliveInterval n

Sends a message through the encrypted channel after n seconds of not receiving a message from the client. See ClientAliveCountMax. The default is 0, meaning that no messages are sent.

This declaration passes messages over the encrypted channel (application layer; page 291) and is not susceptible to IP spoofing (page 1256). It differs from TCPKeepAlive, which uses the TCP keepalive option (transport layer; page 291) and is susceptible to IP spoofing.

DenyUsers userlist

The userlist is a SPACE-separated list of usernames that specifies users who are not allowed to log in using sshd. This list can include * and ? wildcards. You can specify a user as user or user@host. If you use the second format, make sure you specify the host as returned by hostname. Does not work with numeric user IDs.

ForceCommand command

Executes command, ignoring commands specified by the client and commands in the optional ~/.ssh/ssh/rc file.

HostbasedAuthentication yes | no

Tries rhosts and /etc/hosts.equiv authentication when set to yes. For a more secure system, set this declaration to no. Default is no.

IgnoreRhosts yes | no

Ignores .rhosts and .shosts files for authentication. Does not affect the use of /etc/hosts.equiv and /etc/ssh/shosts.equiv files for authentication. For a more secure system, set this declaration to yes. Default is yes.

LoginGraceTime n

Waits n seconds for a user to log in on the server before disconnecting. A value of 0 means there is no time limit. Default is 120 seconds.

LogLevel val

Specifies how detailed the log messages are. Choose val from QUIET, FATAL, ERROR, INFO, and VERBOSE. Default is INFO.

PasswordAuthentication yes | no

Permits a user to use a password for authentication. For a more secure system, set up automatic login (page 700) and set this declaration to no. Default is yes.

PermitEmptyPasswords yes | no

Permits a user to log in on an account that has an empty password. Default is no.

PermitRootLogin yes | without-password | forced-commands-only | no

Permits root to log in using an OpenSSH client. Default is yes.

Setting this declaration to yes allows a user to log in as a privileged user by suppling the root password. This setup allows the root password to be sent over the network, although it is encrypted, so it is not a big security risk. It also requires all users connecting as a privileged user to know theroot password.

Setting this declaration to no does not allow root to authenticate directly; privilege must come from sudo or su after a user has logged in. Given the number of brute-force attacks on a typical system connected to the Internet, this is a good choice.

Setting this declaration to without-password means the only way for a user to authenticate as root is by using an authorized key (page 700). This choice eliminates the need for a group of people to know the root password. However, one user must be able to run with root privileges so new keys can be added as needed.

Setting this declaration to forced-commands works with an authorized key but forces a specific command after authentication instead of starting an interactive shell. The command is specified by ForceCommand (above).

PermitUserEnvironment yes | no

Permits a user to modify the environment he logs in to on the remote system. Default is no. See environment on page 688.

Port num

Specifies that the sshd server listen on port num. It might improve security to change num to a nonstandard port. Default is 22.

StrictModes yes | no

Checks modes and ownership of the user’s home directory and files. Login fails for users other than the owner if the directories and/or files can be written to by anyone other than the owner. For a more secure system, set this declaration to yes. Default is yes.

SyslogFacility val

Specifies the facility name (page 620) sshd uses when logging messages. Set val to daemon, user, auth, authpriv, local0, local1, local2, local3, local4, local5, local6, or local7. Default is auth.

TCPKeepAlive yes | no

Periodically checks whether a connection is alive when set to yes. Checking causes the ssh or scp connection to be dropped when the client crashes or the connection dies for another reason, even if it is only temporary. Setting this parameter to no causes the server not to check whether the connection is alive. Default is yes.

This declaration tests the connection at the transport (TCP) layer (page 291). It uses the TCP keepalive option, which is not encrypted and is susceptible to IP spoofing (page 1256). Refer to ClientAliveInterval (page 704) for a nonspoofable alternative.

X11Forwarding yes | no

Allows X11 forwarding when set to yes. For trusted X11 forwarding to work, the ForwardX11 or the ForwardX11Trusted declaration must also be set to yes in either the ~/.ssh/config or /etc/ssh/ssh_config client configuration file (page 698). The default is no, but Fedora/RHEL sets X11Forwarding to yes. For more information refer to “Forwarding X11” on page 707.

Troubleshooting

Log files

There are several places to look for clues when you have a problem connecting with ssh or scp. First look for sshd entries in /var/log/secure and /var/log/messages on the server. Following are messages you might see when you are using an AllowUsers declaration but have not included the user who is trying to log in (page 704). The messages that are marked pam_unix originate with PAM (page 476).

# grep sshd /var/log/secure | tail -6
guava sshd[10244]: Server listening on :: port 22.
guava sshd[10248]: User sam from 172.16.192.150 not allowed because not listed in AllowUsers
guava sshd[10249]: input_userauth_request: invalid user sam
guava sshd[10248]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser=
rhost=192.168.206.181 user=sam
guava sshd[10248]: Failed password for invalid user sam from 192.168.206.181 port 59088 ssh2
guava sshd[10249]: Connection closed by 192.168.206.181

Check the configuration file

You can use the sshd –t option to check the syntax of the server configuration file.

Debug the client

If entries in these files do not help solve the problem, try connecting with the –v option (either ssh or scp—the results should be the same). OpenSSH displays a lot of debugging messages, one of which might help you figure out what the problem is. You can use a maximum of three –voptions to increase the number of messages that OpenSSH displays.

$ ssh -v plum
OpenSSH_6.2p1, OpenSSL 1.0.1e-fips 11 Feb 2013
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 50: Applying options for *
debug1: Connecting to plum [192.168.206.181] port 22.
debug1: Connection established.
debug1: identity file /home/sam/.ssh/id_rsa type 1
debug1: identity file /home/sam/.ssh/id_rsa-cert type -1

...
debug1: Host 'plum' is known and matches the RSA host key.
debug1: Found key in /home/sam/.ssh/known_hosts:1
debug1: ssh_rsa_verify: signature correct
...
debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,password
...
debug1: Next authentication method: publickey
debug1: Offering public key: /home/sam/.ssh/id_rsa
debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,password
debug1: Trying private key: /home/sam/.ssh/id_dsa
debug1: Next authentication method: password
sam@plum's password:

Debug the server

You can debug from the server side by giving the command /usr/sbin/sshd –de while working with root privileges. The server will run in the foreground, and its display might help you solve the problem.

Image Tunneling/Port Forwarding

The ssh utility can forward a port (port forwarding; page 1266) through the encrypted connection it establishes. Because the data sent across the forwarded port uses the encrypted ssh connection as its data link layer (page 291), the term tunneling (page 1278) is applied to this type of connection: “The connection is tunneled through ssh.” You can secure protocols—including POP, X, IMAP, VNC, and WWW—by tunneling them through ssh.

Forwarding X11

The ssh utility makes it easy to tunnel the X11 protocol. For X11 tunneling to work, you must enable it on both the server and the client, and the client must be running the X Window System.

Server

On the ssh server, enable X11 forwarding by setting the X11Forwarding declaration (page 706) to yes (the default) in the /etc/ssh/sshd_config file.

Trusted Client

On a client, enable trusted X11 forwarding by setting the ForwardX11 (default is no; page 698) and ForwardX11Trusted (default is no, but set to yes as installed; page 698) declarations to yes in the /etc/ssh/ssh_config or ~/.ssh/config file. Alternately, you can specify the –Y option (page695) on the command line to start the client in trusted mode.

When you enable X11 forwarding on a client, the client connects as a trusted client, which means the client trusts the server and is given full access to the X11 display. With full access to the X11 display, in some situations a client might be able to modify other clients of the X11 display. Make a trusted connection only when you trust the remote system. (You do not want someone tampering with your client.) If this concept is confusing, see the tip “The roles of X client and server might be counterintuitive” on page 459.

Nontrusted Client

On a client, enable nontrusted X11 forwarding by setting the ForwardX11 (default is no; page 698) declaration to yes and the ForwardX11Trusted (default is no, but set to yes as installed; page 698) declaration to no in the /etc/ssh/ssh_config or ~/.ssh/config file. Alternately, you can specify the –X option (page 695) on the command line to start the client in nontrusted mode.

A nontrusted client is given limited access to the X11 display and cannot modify other clients of the X11 display. Few clients work properly when they are run in nontrusted mode. If you are running an X11 client in nontrusted mode and encounter problems, try running in trusted mode (assuming you trust the remote system). Fedora/RHEL sets up ssh clients to run in trusted mode.

Running ssh

With X11 forwarding turned on, ssh tunnels the X11 protocol, setting the DISPLAY environment variable on the system it connects to and forwarding the required port. Typically you will be running from a GUI, which usually means that you are using ssh in a terminal emulator window to connect to a remote system. When you give an X11 command from an ssh prompt, OpenSSH creates a new secure channel that carries the X11 data, and the graphical output from the X11 program appears on the screen. Typically you will need to start the client in trusted mode.

[sam@guava ~]$ ssh plum
[sam@plum ~]$ echo $DISPLAY
localhost:10.0

By default, ssh uses X Window System display numbers 10 and higher (port numbers 6010 and higher) for forwarded X sessions. After you connect to a remote system using ssh, you can give a command to run an X application. The application will then run on the remote system with its display appearing on the local system, such that it appears to run locally.

Port Forwarding

You can forward arbitrary ports using the –L and –R options. The –L option forwards a local port to a remote system, so a program that tries to connect to the forwarded port on the local system transparently connects to the remote system. The –R option does the reverse: It forwards remote ports to the local system. The –N option, which prevents ssh from executing remote commands, is generally used with –L and –R. When you specify –N, ssh works only as a private network to forward ports. An ssh command line using the –L or –R option has the following format:

$ ssh –N –L | –R local-port:remote-host:remote-port target

where local-port is the number of the local port that is being forwarded to or from remote-host, remote-host is the name or IP address of the system that local-port gets forwarded to or from, remote-port is the number of the port on remote-host that is being forwarded from or to the local system, and target is the name or IP address of the system ssh connects to.

As an example, assume there is a POP mail client on the local system and that the POP server is on a remote network, on a system named pophost. POP is not a secure protocol; passwords are sent in cleartext each time the client connects to the server. You can make it more secure by tunneling POP through ssh (POP-3 connects on port 110; port 1550 is an arbitrary port on the local system):

$ ssh -N -L 1550:pophost:110 pophost

After giving the preceding command, you can point the POP client at localhost:1550. The connection between the client and the server will then be encrypted. (When you set up an account on the POP client, specify the location of the server as localhost, port 1550; details vary with different mail clients.)

Firewalls

In the preceding example, remote-host and target were the same system. However, the system specified for port forwarding (remote-host) does not have to be the same as the destination of the ssh connection (target). As an example, assume the POP server is behind a firewall and you cannot connect to it via ssh. If you can connect to the firewall via the Internet using ssh, you can encrypt the part of the connection over the Internet:

$ ssh -N -L 1550:pophost:110 firewall

Here remote-host (the system receiving the port forwarding) is pophost, and target (the system that ssh connects to) is firewall.

You can also use ssh when you are behind a firewall (that is running sshd) and want to forward a port into your system without modifying the firewall settings:

$ ssh -R 1678:localhost:80 firewall

The preceding command forwards connections from the outside to port 1678 on the firewall to the local Web server. Forwarding connections in this manner allows you to use a Web browser to connect to port 1678 on the firewall when you connect to the Web server on the local system. This setup would be useful if you ran a Webmail program (page 758) on the local system because it would allow you to check your mail from anywhere using an Internet connection.

Compression

Compression, which is enabled with the –C option, can speed up communication over a low-bandwidth connection. This option is commonly used with port forwarding. Compression can increase latency to an extent that might not be desirable for an X session forwarded over a high-bandwidth connection.

Chapter Summary

OpenSSH is a suite of secure network connectivity tools that encrypts all traffic, including passwords, thereby helping to thwart malicious users who might otherwise eavesdrop, hijack connections, and steal passwords. The sshd server daemon accepts connections from clients including ssh(runs a command on or logs in on another system), scp (copies files to and from another system), and sftp (securely replaces ftp). Helper programs including ssh-keygen (creates, manages, and converts authentication keys), ssh-agent (manages keys during a session), and ssh-add (works with ssh-agent) create and manage authentication keys.

To ensure secure communications, when an OpenSSH client opens a connection, it verifies that it is connected to the correct server. Then OpenSSH encrypts communication between the systems. Finally, OpenSSH makes sure the user is authorized to log in on or copy files to and from the server. You can secure many protocols—including POP, X, IMAP, VNC, and WWW—by tunneling them through ssh.

When it is properly set up, OpenSSH also enables secure X11 forwarding. With this feature, you can run securely a graphical program on a remote system and have the display appear on the local system.

Exercises

1. What is the difference between the scp and sftp utilities?

2. How can you use ssh to find out who is logged in on a remote system?

3. How would you use scp to copy your ~/.bashrc file from the system named plum to the local system?

4. How would you use ssh to run xterm on plum and show the display on the local system?

5. What problem can enabling compression present when you are using ssh to run remote X applications on a local display?

6. When you try to connect to a remote system using an OpenSSH client and you see a message warning you that the remote host identification has changed, what has happened? What should you do?

Advanced Exercises

7. Which scp command would you use to copy your home directory from plum to the local system?

8. Which single command could you give to log in as root on the remote system named plum, if plum has remote root logins disabled?

9. How could you use ssh to compare the contents of the ~/memos directories on plum and the local system?

10. How would you use rsync with OpenSSH authentication to copy the memos12 file from the working directory on the local system to your home directory on plum? How would you copy the memos directory from the working directory on the local system to your home directory onplum and cause rsync to display each file as it copied the file?