Search the Catalog
Linux Network Administrator's Guide, 2nd Edition

Linux Network Administrator's Guide, 2nd Edition

By Olaf Kirch & Terry Dawson
2nd Edition June 2000
1-56592-400-2, Order Number: 4002
506 pages, $34.95

Chapter 12
Important Network Features

Contents:
The inetd Super Server
The tcpd Access Control Facility
The Services and Protocols Files
Remote Procedure Call
Configuring Remote Login and Execution

After successfully setting up IP and the resolver, you then must look at the services you want to provide over the network. This chapter covers the configuration of a few simple network applications, including the inetd server and the programs from the rlogin family. We'll also deal briefly with the Remote Procedure Call interface, upon which services like the Network File System (NFS) and the Network Information System (NIS) are based. The configuration of NFS and NIS, however, is more complex and are described in separate chapters, as are electronic mail and network news.

Of course, we can't cover all network applications in this book. If you want to install one that's not discussed here, like talk, gopher, or http, please refer to the manual pages of the server for details.

The inetd Super Server

Programs that provide application services via the network are called network daemons. A daemon is a program that opens a port, most commonly a well-known service port, and waits for incoming connections on it. If one occurs, the daemon creates a child process that accepts the connection, while the parent continues to listen for further requests. This mechanism works well, but has a few disadvantages; at least one instance of every possible service you wish to provide must be active in memory at all times. In addition, the software routines that do the listening and port handling must be replicated in every network daemon.

To overcome these inefficiencies, most Unix installations run a special network daemon, what you might consider a "super server." This daemon creates sockets on behalf of a number of services and listens on all of them simultaneously. When an incoming connection is received on any of these sockets, the super server accepts the connection and spawns the server specified for this port, passing the socket across to the child to manage. The server then returns to listening.

The most common super server is called inetd, the Internet Daemon. It is started at system boot time and takes the list of services it is to manage from a startup file named /etc/inetd.conf. In addition to those servers, there are a number of trivial services performed by inetd itself called internal services. They include chargen, which simply generates a string of characters, and daytime, which returns the system's idea of the time of day.

An entry in this file consists of a single line made up of the following fields:

service type protocol wait user server cmdline

Each of the fields is described in the following list:

service

Gives the service name. The service name has to be translated to a port number by looking it up in the /etc/services file. This file will be described later in this chapter in the section "The Services and Protocols Files".

type

Specifies a socket type, either stream (for connection-oriented protocols) or dgram (for datagram protocols). TCP-based services should therefore always use stream, while UDP-based services should always use dgram.

protocol

Names the transport protocol used by the service. This must be a valid protocol name found in the protocols file, explained later.

wait

This option applies only to dgram sockets. It can be either wait or nowait. If wait is specified, inetd executes only one server for the specified port at any time. Otherwise, it immediately continues to listen on the port after executing the server.

This is useful for "single-threaded" servers that read all incoming datagrams until no more arrive, and then exit. Most RPC servers are of this type and should therefore specify wait. The opposite type, "multi-threaded" servers, allow an unlimited number of instances to run concurrently. These servers should specify nowait.

stream sockets should always use nowait.

user

This is the login ID of the user who will own the process when it is executing. This will frequently be the root user, but some services may use different accounts. It is a very good idea to apply the principle of least privilege here, which states that you shouldn't run a command under a privileged account if the program doesn't require this for proper functioning. For example, the NNTP news server runs as news, while services that may pose a security risk (such as tftp or finger) are often run as nobody.

server

Gives the full pathname of the server program to be executed. Internal services are marked by the keyword internal.

cmdline

This is the command line to be passed to the server. It starts with the name of the server to be executed and can include any arguments that need to be passed to it. If you are using the TCP wrapper, you specify the full pathname to the server here. If not, then you just specify the server name as you'd like it to appear in a process list. We'll talk about the TCP wrapper shortly.

This field is empty for internal services.

A sample inetd.conf file is shown in Example 12.1. The finger service is commented out so that it is not available. This is often done for security reasons, because it can be used by attackers to obtain names and other details of users on your system.

Example 12.1: A Sample /etc/inetd.conf File

# 
# inetd services
ftp      stream tcp nowait root  /usr/sbin/ftpd    in.ftpd -l
telnet   stream tcp nowait root  /usr/sbin/telnetd in.telnetd -b/etc/issue
#finger  stream tcp nowait bin   /usr/sbin/fingerd in.fingerd
#tftp    dgram  udp wait  nobody /usr/sbin/tftpd   in.tftpd
#tftp    dgram  udp wait  nobody /usr/sbin/tftpd   in.tftpd /boot/diskless
#login   stream tcp nowait root  /usr/sbin/rlogind in.rlogind
#shell   stream tcp nowait root  /usr/sbin/rshd    in.rshd
#exec    stream tcp nowait root  /usr/sbin/rexecd  in.rexecd
#
#       inetd internal services
#
daytime  stream tcp nowait root internal
daytime  dgram  udp nowait root internal
time     stream tcp nowait root internal
time     dgram  udp nowait root internal
echo     stream tcp nowait root internal
echo     dgram  udp nowait root internal
discard  stream tcp nowait root internal
discard  dgram  udp nowait root internal
chargen  stream tcp nowait root internal
chargen  dgram  udp nowait root internal

The tftp daemon is shown commented out as well. tftp implements the Trivial File Transfer Protocol (TFTP), which allows someone to transfer any world-readable files from your system without password checking. This is especially harmful with the /etc/passwd file, and even more so when you don't use shadow passwords.

TFTP is commonly used by diskless clients and Xterminals to download their code from a boot server. If you need to run tftpd for this reason, make sure to limit its scope to those directories from which clients will retrieve files; you will need to add those directory names to tftpd's command line. This is shown in the second tftp line in the example.

The tcpd Access Control Facility

Since opening a computer to network access involves many security risks, applications are designed to guard against several types of attacks. Some security features, however, may be flawed (most drastically demonstrated by the RTM Internet worm, which exploited a hole in a number of programs, including old versions of the sendmail mail daemon), or do not distinguish between secure hosts from which requests for a particular service will be accepted and insecure hosts whose requests should be rejected. We've already briefly discussed the finger and tftp services. Network Administrator would want to limit access to these services to "trusted hosts" only, which is impossible with the usual setup, for which inetd provides this service either to all clients or not at all.

A useful tool for managing host-specific access is tcpd, often called the daemon "wrapper."[1] For TCP services you want to monitor or protect, it is invoked instead of the server program. tcpd checks if the remote host is allowed to use that service, and only if this succeeds will it execute the real server program. tcpd also logs the request to the syslog daemon. Note that this does not work with UDP-based services.

[1] Written by Wietse Venema, wietse@wzv.win.tue.nl.

For example, to wrap the finger daemon, you have to change the corresponding line in inetd.conf from this:

# unwrapped finger daemon
finger    stream tcp nowait bin    /usr/sbin/fingerd in.fingerd
to this:
# wrap finger daemon
finger  stream  tcp     nowait  root    /usr/sbin/tcpd   in.fingerd

Without adding any access control, this will appear to the client as the usual finger setup, except that any requests are logged to syslog's auth facility.

Two files called /etc/hosts.allow and /etc/hosts.deny implement access control. They contain entries that allow and deny access to certain services and hosts. When tcpd handles a request for a service such as finger from a client host named biff.foobar.com, it scans hosts.allow and hosts.deny (in this order) for an entry matching both the service and client host. If a matching entry is found in hosts.allow, access is granted and tcpd doesn't consult the hosts.deny file. If no match is found in the hosts.allow file, but a match is found in hosts.deny, the request is rejected by closing down the connection. The request is accepted if no match is found at all.

Entries in the access files look like this:

servicelist: hostlist [:shellcmd]

servicelist is a list of service names from /etc/services, or the keyword ALL. To match all services except finger and tftp, use ALL EXCEPT finger, tftp.

hostlist is a list of hostnames, IP addresses, or the keywords ALL, LOCAL, UNKNOWN or PARANOID. ALL matches any host, while LOCAL matches hostnames that don't contain a dot.[2] UNKNOWN matches any hosts whose name or address lookup failed. PARANOID matches any host whose hostname does not resolve back to its IP address.[3] A name starting with a dot matches all hosts whose domain is equal to this name. For example, .foobar.com matches biff.foobar.com, but not nurks.fredsville.com. A pattern that ends with a dot matches any host whose IP address begins with the supplied pattern, so 172.16. matches 172.16.32.0, but not 172.15.9.1. A pattern of the form n.n.n.n/m.m.m.m is treated as an IP address and network mask, so we could specify our previous example as 172.16.0.0/255.255.0.0 instead. Lastly, any pattern beginning with a "/" character allows you to specify a file that is presumed to contain a list of hostname or IP address patterns, any of which are allowed to match. So a pattern that looked like /var/access/trustedhosts would cause the tcpd daemon to read that file, testing if any of the lines in it matched the connecting host.

[2] Usually only local hostnames obtained from lookups in /etc/hosts contain no dots.

[3] While its name suggests it is an extreme measure, the PARANOID keyword is a good default, as it protects you against mailicious hosts pretending to be someone they are not. Not all tcpd are supplied with PARANOID compiled in; if yours is not, you need to recompile tcpd to use it.

To deny access to the finger and tftp services to all but the local hosts, put the following in /etc/hosts.deny and leave /etc/hosts.allow empty:

in.tftpd, in.fingerd: ALL EXCEPT LOCAL, .your.domain

The optional shellcmd field may contain a shell command to be invoked when the entry is matched. This is useful to set up traps that may expose potential attackers. The following example creates a log file listing the user and host connecting, and if the host is not vlager.vbrew.com it will append the output of a finger to that host:

in.ftpd: ALL EXCEPT LOCAL, .vbrew.com : \
      echo "request from %d@%h: >> /var/log/finger.log; \
      if [ %h != "vlager.vbrew.com:" ]; then \ 
          finger -l @%h >> /var/log/finger.log \
      fi

The %h and %d arguments are expanded by tcpd to the client hostname and service name, respectively. Please refer to the hosts_access(5) manual page for details.

The Services and Protocols Files

The port numbers on which certain "standard" services are offered are defined in the Assigned Numbers RFC. To enable server and client programs to convert service names to these numbers, at least part of the list is kept on each host; it is stored in a file called /etc/services. An entry is made up like this:

service port/protocol   [aliases]

Here, service specifies the service name, port defines the port the service is offered on, and protocol defines which transport protocol is used. Commonly, the latter field is either udp or tcp. It is possible for a service to be offered for more than one protocol, as well as offering different services on the same port as long as the protocols are different. The aliases field allows you to specify alternative names for the same service.

Usually, you don't have to change the services file that comes along with the network software on your Linux system. Nevertheless, we give a small excerpt from that file in Example 12.2.

Example 12.2: A Sample /etc/services File

# The services file:
#
# well-known services
echo           7/tcp                 # Echo
echo           7/udp                 #
discard        9/tcp  sink null      # Discard
discard        9/udp  sink null      #
daytime       13/tcp                 # Daytime
daytime       13/udp                 #
chargen       19/tcp  ttytst source  # Character Generator
chargen       19/udp  ttytst source  #
ftp-data      20/tcp                 # File Transfer Protocol (Data)
ftp           21/tcp                 # File Transfer Protocol (Control)
telnet        23/tcp                 # Virtual Terminal Protocol
smtp          25/tcp                 # Simple Mail Transfer Protocol
nntp         119/tcp  readnews       # Network News Transfer Protocol
#
# UNIX services
exec         512/tcp                 # BSD rexecd
biff         512/udp  comsat         # mail notification
login        513/tcp                 # remote login
who          513/udp  whod           # remote who and uptime
shell        514/tcp  cmd            # remote command, no passwd used
syslog       514/udp                 # remote system logging
printer      515/tcp  spooler        # remote print spooling
route        520/udp  router routed  # routing information protocol

Note that the echo service is offered on port 7 for both TCP and UDP, and that port 512 is used for two different services: remote execution (rexec) using TCP, and the COMSAT daemon, which notifies users of new mail, over UDP (see xbiff(1x)).

Like the services file, the networking library needs a way to translate protocol names -- for example, those used in the services file -- to protocol numbers understood by the IP layer on other hosts. This is done by looking up the name in the /etc/protocols file. It contains one entry per line, each containing a protocol name, and the associated number. Having to touch this file is even more unlikely than having to meddle with /etc/services. A sample file is given in Example 12.3.

Example 12.3: A Sample /etc/protocols File

#
# Internet (IP) protocols
#
ip      0       IP              # internet protocol, pseudo protocol number
icmp    1       ICMP            # internet control message protocol
igmp    2       IGMP            # internet group multicast protocol
tcp     6       TCP             # transmission control protocol
udp     17      UDP             # user datagram protocol
raw     255     RAW             # RAW IP interface

Remote Procedure Call

The general mechanism for client-server applications is provided by the Remote Procedure Call (RPC) package. RPC was developed by Sun Microsystems and is a collection of tools and library functions. Important applications built on top of RPC are NIS, the Network Information System (described in Chapter 13, The Network Information System), and NFS, the Network File System (described in Chapter 14, The Network File System), which are both described in this book.

An RPC server consists of a collection of procedures that a client can call by sending an RPC request to the server along with the procedure parameters. The server will invoke the indicated procedure on behalf of the client, handing back the return value, if there is any. In order to be machine-independent, all data exchanged between client and server is converted to the External Data Representation format (XDR) by the sender, and converted back to the machine-local representation by the receiver. RPC relies on standard UDP and TCP sockets to transport the XDR formatted data to the remote host. Sun has graciously placed RPC in the public domain; it is described in a series of RFCs.

Sometimes improvements to an RPC application introduce incompatible changes in the procedure call interface. Of course, simply changing the server would crash all applications that still expect the original behavior. Therefore, RPC programs have version numbers assigned to them, usually starting with 1, and with each new version of the RPC interface, this counter will be bumped up. Often, a server may offer several versions simultaneously; clients then indicate by the version number in their requests which implementation of the service they want to use.

The communication between RPC servers and clients is somewhat peculiar. An RPC server offers one or more collections of procedures; each set is called a program and is uniquely identified by a program number. A list that maps service names to program numbers is usually kept in /etc/rpc, an excerpt of which is shown in Example 12.4.

Example 12.4: A Sample /etc/rpc File

#
# /etc/rpc - miscellaneous RPC-based services
#
portmapper      100000  portmap sunrpc
rstatd          100001  rstat rstat_svc rup perfmeter
rusersd         100002  rusers
nfs             100003  nfsprog
ypserv          100004  ypprog
mountd          100005  mount showmount
ypbind          100007
walld           100008  rwall shutdown
yppasswdd       100009  yppasswd
bootparam       100026
ypupdated       100028  ypupdate

In TCP/IP networks, the authors of RPC faced the problem of mapping program numbers to generic network services. They designed each server to provide both a TCP and a UDP port for each program and each version. Generally, RPC applications use UDP when sending data, and fall back to TCP only when the data to be transferred doesn't fit into a single UDP datagram.

Of course, client programs need to find out to which port a program number maps. Using a configuration file for this would be too unflexible; since RPC applications don't use reserved ports, there's no guarantee that a port originally meant to be used by our database application hasn't been taken by some other process. Therefore, RPC applications pick any port they can get and register it with a special program called the portmapper daemon. The portmapper acts as a service broker for all RPC servers running on its machine. A client that wishes to contact a service with a given program number first queries the portmapper on the server's host, which returns the TCP and UDP port numbers the service can be reached at.

This method introduces a single point of failure, much like the inetd daemon does for the standard Berkeley services. However, this case is even a little worse because when the portmapper dies, all RPC port information is lost; this usually means you have to restart all RPC servers manually or reboot the entire machine.

On Linux, the portmapper is called /sbin/portmap, or sometimes /usr/sbin/rpc.portmap. Other than making sure it is started from your network boot scripts, the portmapper doesn't require any configuration.

Configuring Remote Login and Execution

It's often very useful to execute a command on a remote host and have input or output from that command be read from, or written to, a network connection.

The traditional commands used for executing commands on remote hosts are rlogin, rsh and rcp. We saw an example of the rlogin command in Chapter 1, Introduction to Networking in the section "Introduction to TCP/IP Networks". We briefly discussed the security issues associated with it in "System Security" and suggested ssh as a replacement. The ssh package provides replacements called slogin, ssh, and scp.

Each of these commands spawns a shell on the remote host and allows the user to execute commands. Of course, the client needs to have an account on the remote host where the command is to be executed. Thus, all these commands use an authentication process. The r commands use a simple username and password exchange between the hosts with no encryption, so anyone listening could easily intercept the passwords. The ssh command suite provides a higher level of security: it uses a technique called Public Key Cryptography, which provides authentication and encryption between the hosts to ensure that neither passwords nor session data are easily intercepted by other hosts.

It is possible to relax authentication checks for certain users even further. For instance, if you frequently have to log into other machines on your LAN, you might want to be admitted without having to type your password every time. This was always possible with the r commands, but the ssh suite allows you to do this a little more easily. It's still not a great idea because it means that if an account on one machine is breached, access can be gained to all other accounts that user has configured for password-less login, but it is very convenient and people will use it.

Let's talk about removing the r commands and getting ssh to work instead.

Disabling the r; Commands

Start by removing the r commands if they're installed. The easiest way to disable the old r commands is to comment out (or remove) their entries in the /etc/inetd.conf file. The relevant entries will look something like this:

# Shell, login, exec and talk are BSD protocols.
shell    stream  tcp     nowait  root  /usr/sbin/tcpd /usr/sbin/in.rshd
login    stream  tcp     nowait  root  /usr/sbin/tcpd /usr/sbin/in.rlogind
exec     stream  tcp     nowait  root  /usr/sbin/tcpd /usr/sbin/in.rexecd
You can comment them by placing a # character at the start of each line, or delete the lines completely. Remember, you need to restart the inetd daemon for this change to take effect. Ideally, you should remove the daemon programs themselves, too.

Installing and Configuring ssh

OpenSSH is a free version of the ssh suite of programs; the Linux port can be found at http://violet.ibs.com.au/openssh/ and in most modern Linux distributions.[4] We won't describe compilation here; good instructions are included in the source. If you can install it from a precompiled package, then it's probably wise to do so.

[4] OpenSSH was developed by the OpenBSD project and is a fine example of the benefit of free software.

There are two parts to an ssh session. There is an ssh client that you need to configure and run on the local host and an ssh daemon that must be running on the remote host.

The ssh daemon

The sshd daemon is the program that listens for network connections from ssh clients, manages authentication, and executes the requested command. It has one main configuration file called /etc/ssh/sshd_config and a special file containing a key used by the authentication and encryption processes to represent the host end. Each host and each client has its own key.

A utility called ssh-keygen is supplied to generate a random key. This is usually used once at installation time to generate the host key, which the system administrator usually stores in a file called /etc/ssh/ssh_host_key. Keys can be of any length of 512 bits or greater. By default, ssh-keygen generates keys of 1024 bits in length, and most people use the default. To generate a random key, you would invoke the ssh-keygen command like this:

# ssh-keygen -f /etc/ssh/ssh_host_key

You will be prompted to enter a passphrase. However, host keys must not use a passphrase, so just press the return key to leave it blank. The program output will look something like:

Generating RSA keys:  ......oooooO...............................oooooO
Key generation complete.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /etc/ssh/ssh_host_key
Your public key has been saved in /etc/ssh/ssh_host_key.pub
The key fingerprint is:
1024 3a:14:78:8e:5a:a3:6b:bc:b0:69:10:23:b7:d8:56:82 root@moria

You will find at the end that two files have been created. The first is called the private key, which must be kept secret and will be in /etc/ssh/ssh_host_key. The second is called the public key and is one that you can share; it will be in /etc/ssh/ssh_host_key.pub.

Armed with the keys for ssh communication, you need to create a configuration file. The ssh suite is very powerful and the configuration file may contain many options. We'll present a simple example to get you started; you should refer to the ssh documentation to enable other features. The following code shows a safe and minimal sshd configuration file. The rest of the configuration options are detailed in the sshd(8) manpage:

# /etc/ssh/sshd_config
#

# The IP adddresses to listen for connections on. 0.0.0.0 means all
# local addresses.
ListenAddress 0.0.0.0

# The TCP port to listen for connections on. The default is 22.
Port 22

# The name of the host key file.
HostKey /etc/ssh/ssh_host_key

# The length of the key in bits.
ServerKeyBits 1024

# Should we allow root logins via ssh?
PermitRootLogin no

# Should the ssh daemon check users' home directory and files permissions?
# are safe before allowing login?
StrictModes yes

# Should we allow old ~/.rhosts and /etc/hosts.equiv authentication method?
RhostsAuthentication no
# Should we allow pure RSA authentication?
RSAAuthentication yes
# Should we allow password authentication?
PasswordAuthentication yes

# Should we allow /etc/hosts.equiv combined with RSA host authentication?
RhostsRSAAuthentication no
# Should we ignore ~/.rhosts files?
IgnoreRhosts yes
# Should we allow logins to accounts with empty passwords?
PermitEmptyPasswords no

It's important to make sure the permissions of the configuration files are correct to ensure that system security is maintained. Use the following commands:

# chown -R root:root /etc/ssh
# chmod 755 /etc/ssh
# chmod 600 /etc/ssh/ssh_host_key
# chmod 644 /etc/ssh/ssh_host_key.pub
# chmod 644 /etc/ssh/sshd_config

The final stage of sshd administration daemon is to run it. Normally you'd create an rc file for it or add it to an existing one, so that it is automatically executed at boot time. The daemon runs standalone and doesn't require any entry in the /etc/inetd.conf file. The daemon must be run as the root user. The syntax is very simple:

/usr/sbin/sshd
The sshd daemon will automatically place itself into the background when being run. You are now ready to accept ssh connections.

The ssh client

There are a number of ssh client programs: slogin, scp and ssh. They each read the same configuration file, usually called /etc/ssh/ssh_config. They each also read configuration files from the .ssh directory in the home directory of the user executing them. The most important of these files is the .ssh/config file, which may contain options that override those specified in the /etc/ssh/ssh_config file, the .ssh/identity file, which contains the user's own private key, and the corresponding .ssh/identity.pub file, containing the user's public key. Other important files are .ssh/known_hosts and .ssh/authorized_keys; we'll talk about those later in "Using ssh". First, let's create the global configuration file and the user key file.

/etc/ssh/ssh_config is very similar to the server configuration file. Again, there are lots of features you can configure, but a minimal configuration looks like that presented in Example 12.5. The rest of the configuration options are detailed in the sshd(8) manpage. You can add sections that match specific hosts or groups of hosts. The parameter to the "Host" statement may be either the full name of a host or a wildcard specification, as we've used in our example, to match all hosts. We could create an entry that used, for example, Host *.vbrew.com to match any host in the vbrew.com domain.

Example 12.5: Example ssh Client Configuration File

# /etc/ssh/ssh_config

# Default options to use when connecting to a remote host
Host *
  # Compress the session data?
  Compression yes
  # .. using which compression level? (1 - fast/poor, 9 - slow/good)
  CompressionLevel 6

  # Fall back to rsh if the secure connection fails?
  FallBackToRsh no

  # Should we send keep-alive messages? Useful if you use IP masquerade
  KeepAlive yes

  # Try RSA authentication?
  RSAAuthentication yes
  # Try RSA authentication in combination with .rhosts authentication?
  RhostsRSAAuthentication yes

We mentioned in the server configuration section that every host and user has a key. The user's key is stored in his or her ~/.ssh/indentity file. To generate the key, use the same ssh-keygen command as we used to generate the host key, except this time you do not need to specify the name of the file in which you save the key. The ssh-keygen defaults to the correct location, but it prompts you to enter a filename in case you'd like to save it elsewhere. It is sometimes useful to have multiple identity files, so ssh allows this. Just as before, ssh-keygen will prompt you to entry a passphrase. Passphrases add yet another level of security and are a good idea. Your passphrase won't be echoed on the screen when you type it.

WARNING: There is no way to recover a passphrase if you forget it. Make sure it is something you will remember, but as with all passwords, make it something that isn't obvious, like a proper noun or your name. For a passphrase to be truly effective, it should be between 10 and 30 characters long and not be plain English prose. Try to throw in some unusual characters. If you forget your passphrase, you will be forced to generate a new key.

You should ask each of your users to run the ssh-keygen command just once to ensure their key file is created correctly. The ssh-keygen will create their ~/.ssh/ directories for them with appropriate permissions and create their private and public keys in .ssh/identity and .ssh/identity.pub, respectively. A sample session should look like:
$ ssh-keygen
Generating RSA keys: .......oooooO.............................. Key generation complete. Enter file in which to save the key (/home/maggie/.ssh/identity): Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /home/maggie/.ssh/identity. Your public key has been saved in /home/maggie/.ssh/identity.pub. The key fingerprint is: 1024 85:49:53:f4:8a:d6:d9:05:d0:1f:23:c4:d7:2a:11:67 maggie@moria $

Now ssh is ready to run.

Using ssh

We should now have the ssh command and it's associated programs installed and ready to run. Let's now take a quick look at how to run them.

First, we'll try a remote login to a host. We can use the slogin program in much the same way as we used the rlogin program in our example earlier in the book. The first time you attempt a connection to a host, the ssh client will retrieve the public key of the host and ask you to confirm its identity by prompting you with a shortened version of the public key called a fingerprint.

The administrator at the remote host should have supplied you in advance with its public key fingerprint, which you should add to your .ssh/known_hosts file. If the remote administrator has not supplied you the appropriate key, you can connect to the remote host, but ssh will warn you that it does have a key and prompt you whether you wish to accept the one offered by the remote host. Assuming that you're sure no one is engaging in DNS spoofing and you are in fact talking to the correct host, answer yes to the prompt. The relevant key is then stored automatically in your .ssh/known_hosts and you will not be prompted for it again. If, on a future connection attempt, the public key retrieved from that host does not match the one that is stored, you will be warned, because this represents a potential security breach.

A first-time login to a remote host will look something like:

$ slogin vchianti.vbrew.com
The authenticity of host 'vchianti.vbrew.com' can't be established. Key fingerprint is 1024 7b:d4:a8:28:c5:19:52:53:3a:fe:8d:95:dd:14:93:f5. Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'vchianti.vbrew.com,172.16.2.3' to the list of/ known hosts. maggie@vchianti.vbrew.com's password: Last login: Tue Feb 1 23:28:58 2000 from vstout.vbrew.com $

You will be prompted for a password, which you should answer with the password belonging to the remote account, not the local one. This password is not echoed when you type it.

Without any special arguments, slogin will attempt to log in with the same userid used on the local machine. You can override this using the -l argument, supplying an alternate login name on the remote host. This is what we did in our example earlier in the book.

We can copy files to and from the remote host using the scp program. Its syntax is similar to the conventional cp with the exception that you may specify a hostname before a filename, meaning that the file path is on the specified host. The following example illustrates scp syntax by copying a local file called /tmp/fred to the /home/maggie/ of the remote host chianti.vbrew.com:

$ scp /tmp/fred vchianti.vbrew.com:/home/maggie/
maggie@vchianti.vbrew.com's password: fred 100% |*****************************| 50165 00:01 ETA

Again, you'll be prompted for a password. The scp command displays useful progress messages by default. You can copy a file from a remote host with the same ease; simply specify its hostname and filepath as the source and the local path as the destination. It's even possible to copy a file from a remote host to some other remote host, but it is something you wouldn't normally want to do, because all of the data travels via your host.

You can execute commands on remote hosts using the ssh command. Again, its syntax is very simple. Let's have our user maggie retrieve the root directory of the remote host vchianti.vbrew.com. She'd do this with:

$ ssh vchianti.vbrew.com ls -CF /
maggie@vchianti.vbrew.com's password: bin/ console@ dos/ home/ lost+found/ pub@ tmp/ vmlinuz@ boot/ dev/ etc/ initrd/ mnt/ root/ usr/ vmlinuz.old@ cdrom/ disk/ floppy/ lib/ proc/ sbin/ var/

You can place ssh in a command pipeline and pipe program input/output to or from it just like any other command, except that the input or output is directed to or from the remote host via the ssh connection. Here is an example of how you might use this capability in combination with the tar command to copy a whole directory with subdirectories and files from a remote host to the local host:

$ ssh vchianti.vbrew.com "tar cf - /etc/" | tar xvf -
maggie@vchianti.vbrew.com's password: etc/GNUstep etc/Muttrc etc/Net etc/X11 etc/adduser.conf .. ..

Here we surrounded the command we will execute with quotation marks to make it clear what is passed as an argument to ssh and what is used by the local shell. This command executes the tar command on the remote host to archive the /etc/ directory and write the output to standard output. We've piped to an instance of the tar command running on our local host in extract mode reading from standard input.

Again, we were prompted for the password. Now you can see why we encouraged you to configure ssh so that it doesn't prompt you for passwords all the time! Let's now configure our local ssh client so that it won't prompt for a password when connecting to the vchianti.vbrew.com host. We mentioned the .ssh/authorized_keys file earlier; this is where it is used. The .ssh/authorized_keys file contains the public keys on any remote user accounts that we wish to automatically log in to. You can set up automatic logins by copying the contents of the .ssh/identity.pub from the remote account into our local .ssh/authorized_keys file. It is vital that the file permissions of .ssh/authorized_keys allow only that you read and write it; anyone may steal and use the keys to log in to that remote account. To ensure the permissions are correct, change .ssh/authorized_keys, as shown:

$ chmod 600 ~/.ssh/authorized_keys

The public keys are a long single line of plain text. If you use copy and paste to duplicate the key into your local file, be sure to remove any end of line characters that might have been introduced along the way. The .ssh/authorized_keys file may contain many such keys, each on a line of its own.

The ssh suite of tools is very powerful and there are many other useful features and options that you will be interested in exploring. Please refer to the manual pages and other documentation that is supplied with the package for more information.

Back to: Sample Chapter Index

Back to: Linux Network Administrator's Guide, 2nd Edition


O'Reilly Home | O'Reilly Bookstores | How to Order | O'Reilly Contacts
International | About O'Reilly | Affiliated Companies

© 2001, O'Reilly & Associates, Inc.
webmaster@oreilly.com