# Networking

When it comes to networking, Linux is your operating system of choice, not only because networking is tightly integrated with the OS itself and a wide variety of free tools and applications are available, but for the robustness under heavy loads that can only be achieved after years of debugging and testing in an Open Source project.

Bookshelves full of information have been written about Linux and networking, but we will try to give an overview in this chapter. After completing this, you will know more about

- Supported networking protocols

- Network configuration files

- Commands for configuring and probing the network

- Daemons and client programs enabling different network applications

- File sharing and printing

- Remote execution of commands and applications

- Basic network interconnection

- Secure execution of remote applications

- Firewalls and intrusion detection

## Networking Overview

### The OSI Model

A protocol is, simply put, a set of rules for communication.

networking protocols

In order to get data over the network, for instance an E-mail from your computer to some computer at the other end of the world, lots of different hard- and software needs to work together.

All these pieces of hardware and the different software programs speak different languages. Imagine your E-mail program: it is able to talk to the computer operating system, through a specific protocol, but it is not able to talk to the computer hardware. We need a special program in the operating system that performs this function. In turn, the computer needs to be able to communicate with the telephone line or other Internet hookup method. And behind the scenes, network connection hardware needs to be able to communicate in order to pass your E-mail from one appliance to the other, all the way to the destination computer.

All these different types of communication protocols are classified in 7 layers, which are known as the Open Systems Interconnection Reference Model, the OSI Model for short. For easy understanding, this model is reduced to a 4-layer protocol description, as described in the table below:

networking OSI Model
OSI Model

The simplified OSI Model

Layer name | Layer Protocols
--- | ---
Application layer | HTTP, DNS, SMTP, POP, ...
Transport layer | TCP, UDP
Network layer | IP, IPv6
Network access layer | PPP, PPPoE, Ethernet

Each layer can only use the functionality of the layer below; each layer can only export functionality to the layer above. In other words: layers communicate only with adjacent layers. Let's take the example of your E-mail message again: you enter it through the application layer. In your computer, it travels down the transport and network layer. Your computer puts it on the network through the network access layer. That is also the layer that will move the message around the world. At the destination, the receiving computer will accept the message through it's own network layer, and will display it to the recepient using the transport and application layer.

It's really much more complicated

The above and following sections are included because you will come across some networking terms sooner or later; they will give you some starting points, should you want to find out about the details.

### Some popular networking protocols

Linux supports many different networking protocols. We list only the most important:

networking protocol overview

#### TCP/IP

The Transport Control Protocol and the Internet Protocol are the two most popular ways of communicating on the Internet. A lot of applications, such as your browser and E-mail program, are built on top of this protocol suite.

Transport Control Protocol
Internet Protocol

Very simply put, IP provides a solution for sending packets of information from one machine to another, while TCP ensures that the packets are arranged in streams, so that packets from different applications don't get mixed up, and that the packets are sent and received in the correct order.

protocols TCP/IP

A good starting point for learning more about TCP and IP is in the following documents:

- `man `7` ip`: Describes the IPv4 protocol implementation on Linux (version 4 currently being the most wide-spread edition of the IP protocol).

- `man `7` tcp`: Implementation of the TCP protocol.

- RFC793, RFC1122, RFC2001 for TCP, and RFC791, RFC1122 and RFC1112 for IP.

  The Request For Comments documents contain the descriptions of networking standards, protocols, applications and implementation. These documents are managed by the Internet Engineering Task Force, an international community concerned with the smooth operation of the Internet and the evolution and development of the Internet architecture.

  networking IETF

  Your ISP usually has an RFC archive available, or you can browse the RFCs via .

#### TCP/IPv6

Nobody expected the Internet to grow as fast as it does. IP proved to have quite some disadvantages when a really large number of computers is in a network, the most important being the availability of unique addresses to assign to each machine participating. Thus, IP version 6 was deviced to meet the needs of today's Internet.

Unfortunately, not all applications and services support IPv6, yet. A migration is currently being set in motion in many environments that can benefit from an upgrade to IPv6. For some applications, the old protocol is still used, for applications that have been reworked the new version is already active. So when checking your network configuration, sometimes it might be a bit confusing since all kinds of measures can be taken to hide one protocol from the other so as the two don't mix up connections.

protocols IPv6

More information can be found in the following documents:

- `man `7` ipv6`: the Linux IPv6 protocol implementation.

- RFC1883 describing the IPv6 protocol.

#### PPP, SLIP, PLIP, PPPOE

The Linux kernel has built-in support for PPP (Point-to-Point-Protocol), SLIP (Serial Line IP), PLIP (Parallel Line IP) and PPPP Over EThernet. PPP is the most popular way individual users access their ISP (Internet Service Provider), although in densely populated areas it is often being replaced by PPPOE, the protocol used for ADSL (Asymmetric Digital Subscriber Line) connections.

protocols PPP

Most Linux distributions provide easy-to-use tools for setting up an Internet connection. The only thing you basically need is a username and password to connect to your Internet Service Provider (ISP), and a telephone number in the case of PPP. These data are entered in the graphical configuration tool, which will likely also allow for starting and stopping the connection to your provider.

#### ISDN

The Linux kernel has built-in ISDN capabilities. Isdn4linux controls ISDN PC cards and can emulate a modem with the Hayes command set (AT commands). The possibilities range from simply using a terminal program to full connection to the Internet.

protocols ISDN

Check your system documentation.

#### AppleTalk

Appletalk is the name of Apple's internetworking stack. It allows a peer-to-peer network model which provides basic functionality such as file and printer sharing. Each machine can simultaneously act as a client and a server, and the software and hardware necessary are included with every Apple computer.

protocols AppleTalk

Linux provides full AppleTalk networking. Netatalk is a kernel-level implementation of the AppleTalk Protocol Suite, originally for BSD-derived systems. It includes support for routing AppleTalk, serving UNIX and AFS file systems using AppleShare and serving UNIX printers and accessing AppleTalk printers.

#### SMB/NMB

For compatibility with MS Windows environments, the Samba suite, including support for the NMB and SMB protocols, can be installed on any UNIX-like system. The Server Message Block protocol (also called Session Message Block, NetBIOS or LanManager protocol) is used on MS Windows 3.11, NT, 95/98, 2K and XP to share disks and printers.

protocols SMB/NMB

The basic functions of the Samba suite are: sharing Linux drives with Windows machines, accessing SMB shares from Linux machines, sharing Linux printers with Windows machines and sharing Windows printers with Linux machines.

networking Samba

Most Linux distributions provide a samba package, which does most of the server setup and starts up `smbd`, the Samba server, and `nmbd`, the netbios name server, at boot time by default. Samba can be configured graphically, via a web interface or via the command line and text configuration files. The daemons make a Linux machine appear as an MS Windows host in an MS Windows My Network Places/Network Neighbourhood window; a share from a Linux machine will be indistinguishable from a share on any other host in an MS Windows environment.

More information can be found at the following locations:

- `man `smb.conf``: describes the format of the main Samba configuration file.

  smb.conf

- The Samba Project Documentation (or check your local samba.org mirror) contains an easy to read installation and testing guide, which also explains how to configure your Samba server as a Primary Domain Controller. All the man pages are also available here.

#### Miscellaneous protocols

Linux also has support for Amateur Radio, WAN internetworking (X25, Frame Relay, ATM), InfraRed and other wireless connections, but since these protocols usually require special hardware, we won't discuss them in this document.

## Network configuration and information

### Configuration of network interfaces

All the big, userfriendly Linux distributions come with various graphical tools, allowing for easy setup of the computer in a local network, for connecting it to an Internet Service Provider or for wireless access. These tools can be started up from the command line or from a menu:

network configuration graphical tools

- Ubuntu configuration is done selecting System Administration Networking.

- RedHat Linux comes with `redhat-config-network`, which has both a graphical and a text mode interface.

- Suse's YAST or YAST2 is an all-in-one configuration tool.

- Mandrake/Mandriva comes with a Network and Internet Configuration Wizard, which is preferably started up from Mandrake's Control Center.

- On Gnome systems: `gnome-network-preferences`.

- On KDE systems: `knetworkconf`.

Your system documentation provides plenty of advice and information about availability and use of tools.

Information that you will need to provide:

- For connecting to the local network, for instance with your home computers, or at work: hostname, domainname and IP address. If you want to set up your own network, best do some more reading first. At work, this information is likely to be given to your computer automatically when you boot it up. When in doubt, it is better not to specify any information than making it up.

- For connecting to the Internet: username and password for your ISP, telephone number when using a modem. Your ISP usually automatically assigns you an IP address and all the other things necessary for your Internet applications to work.

### Network configuration files

The graphical helper tools edit a specific set of network configuration files, using a couple of basic commands. The exact names of the configuration files and their location in the file system is largely dependent on your Linux distribution and version. However, a couple of network configuration files are common on all UNIX systems:

network configuration files

#### /etc/hosts

The `/etc/hosts` file always contains the localhost IP address, 127.0.0.1, which is used for interprocess communication. Never remove this line! Sometimes contains addresses of additional hosts, which can be contacted without using an external naming service such as DNS (the Domain Name Server).

hosts
localhost

A sample `hosts` file for a small home network:

    # Do not remove the following line, or various programs
    # that require network functionality will fail.
    127.0.0.1       localhost.localdomain   localhost
    192.168.52.10	tux.mylan.com		tux
    192.168.52.11	winxp.mylan.com		winxp

Read more in `man `hosts``.

#### /etc/resolv.conf

The `/etc/resolv.conf` file configures access to a DNS server, see . This file contains your domain name and the name server(s) to contact:

resolv.conf

    search mylan.com
    nameserver 193.134.20.4

Read more in the `resolv.conf` man page.

#### /etc/nsswitch.conf

The `/etc/nsswitch.conf` file defines the order in which to contact different name services. For Internet use, it is important that dns shows up in the hosts line:

nsswitch.conf

    [bob@tux ~] grep hosts /etc/nsswitch.conf
    hosts:	files dns

This instructs your computer to look up hostnames and IP addresses first in the `/etc/hosts` file, and to contact the DNS server if a given host does not occur in the local `hosts` file. Other possible name services to contact are LDAP, NIS and NIS+.

More in `man `nsswitch.conf``.

### Network configuration commands

#### The ip command

The distribution-specific scripts and graphical tools are front-ends to `ip` (or `ifconfig` and `route` on older systems) to display and configure the kernel's networking configuration.

ip
ifconfig
route

The `ip` command is used for assigning IP addresses to interfaces, for setting up routes to the Internet and to other networks, for displaying TCP/IP configurations etcetera.

The following commands show IP address and routing information:

networking display IP address
networking display routes

    benny@home benny> ip addr show
    1: lo: <LOOPBACK,UP> mtu 16436 qdisc noqueue
        link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
        inet 127.0.0.1/8 brd 127.255.255.255 scope host lo
        inet6 ::1/128 scope host
    2: eth0: <BROADCAST,MULTICAST,UP> mtu 1500 qdisc pfifo_fast qlen 100
        link/ether 00:50:bf:7e:54:9a brd ff:ff:ff:ff:ff:ff
        inet 192.168.42.15/24 brd 192.168.42.255 scope global eth0
        inet6 fe80::250:bfff:fe7e:549a/10 scope link

    benny@home benny> ip route show
    192.168.42.0/24 dev eth0  scope link
    127.0.0.0/8 dev lo  scope link
    default via 192.168.42.1 dev eth0

Things to note:

- two network interfaces, even on a system that has only one network interface card: lo is the local loop, used for internal network communication; eth0 is a common name for a real interface. Do not ever change the local loop configuration, or your machine will start mallfunctioning! Wireless interfaces are usually defined as wlan0; modem interfaces as ppp0, but there might be other names as well.

  networking device names

- IP addresses, marked with inet: the local loop always has 127.0.0.1, the physical interface can have any other combination.

  networking local loop

- The hardware address of your interface, which might be required as part of the authentication procedure to connect to a network, is marked with ether. The local loop has 6 pairs of all zeros, the physical loop has 6 pairs of hexadecimal characters, of which the first 3 pairs are vendor-specific.

#### The ifconfig command

While `ip` is the most novel way to configure a Linux system, `ifconfig` is still very popular. Use it without option for displaying network interface information:

networking show IP address

    els@asus:~$ /sbin/ifconfig
    eth0      Link encap:Ethernet  HWaddr 00:50:70:31:2C:14
              inet addr:60.138.67.31  Bcast:66.255.255.255  Mask:255.255.255.192
              inet6 addr: fe80::250:70ff:fe31:2c14/64 Scope:Link
              UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
              RX packets:31977764 errors:0 dropped:0 overruns:0 frame:0
              TX packets:51896866 errors:0 dropped:0 overruns:0 carrier:0
              collisions:802207 txqueuelen:1000
              RX bytes:2806974916 (2.6 GiB)  TX bytes:2874632613 (2.6 GiB)
              Interrupt:11 Base address:0xec00
    										lo        Link encap:Local Loopback
    	  inet addr:127.0.0.1  Mask:255.0.0.0
    	  inet6 addr: ::1/128 Scope:Host
    	  UP LOOPBACK RUNNING  MTU:16436  Metric:1
    	  RX packets:765762 errors:0 dropped:0 overruns:0 frame:0
    	  TX packets:765762 errors:0 dropped:0 overruns:0 carrier:0
    	  collisions:0 txqueuelen:0
    	  RX bytes:624214573 (595.2 MiB)  TX bytes:624214573 (595.2 MiB)

Here, too, we note the most important aspects of the interface configuration:

- The IP address is marked with inet addr.

- The hardware address follows the HWaddr tag.

Both `ifconfig` and `ip` display more detailed configuration information and a number of statistics about each interface and, maybe most important, whether it is UP and RUNNING.

#### PCMCIA commands

On your laptop which you usually connect to the company network using the onboard Ethernet connection, but which you are now to configure for dial-in at home or in a hotel, you might need to activate the PCMCIA card. This is done using the `cardctl` control utility, or the `pccardctl` on newer distributions.

networking PCMCIA
cardctl
pccardctl

A usage example:

`cardctl insert`

Now the card can be configured, either using the graphical or the command line interface. Prior to taking the card out, use this command:

`cardctl eject`

However, a good distribution should provide PCMCIA support in the network configuration tools, preventing users from having to execute PCMCIA commands manually.

#### More information

Further discussion of network configuration is out of the scope of this document. Your primary source for extra information is the man pages for the services you want to set up. Additional reading:

- The Modem-HOWTO: Help with selecting, connecting, configuring, trouble-shooting, and understanding analog modems for a PC.

- LDP HOWTO Index, section 4.4: categorized list of HOWTOs about general networking, protocols, dial-up, DNS, VPNs, bridging, routinfg, security and more.

- Most systems have a version of the `ip-cref` file (locate it using the `locate` command); the PS format of this file is viewable with for instance `gv`.

### Network interface names

On a Linux machine, the device name lo or the local loop is linked with the internal 127.0.0.1 address. The computer will have a hard time making your applications work if this device is not present; it is always there, even on computers which are not networked.

networking device names

The first ethernet device, eth0 in the case of a standard network interface card, points to your local LAN IP address. Normal client machines only have one network interface card. Routers, connecting networks together, have one network device for each network they serve.

If you use a modem to connect to the Internet, your network device will probably be named ppp0.

There are many more names, for instance for Virtual Private Network interfaces (VPNs), and multiple interfaces can be active simultaneously, so that the output of the `ifconfig` or `ip` commands might become quite extensive when no options are used. Even multiple interfaces of the same type can be active. In that case, they are numbered sequentially: the first will get the number 0, the second will get a suffix of 1, the third will get 2, and so on. This is the case on many application servers, on machines which have a failover configuration, on routers, firewalls and many more.

### Checking the host configuration with netstat

Apart from the `ip` command for displaying the network configuration, there's the common `netstat` command which has a lot of options and is generally useful on any UNIX system.

networking display routes

Routing information can be displayed with the `-nr` option to the `netstat` command:

    bob:~> netstat -nr
    Kernel IP routing table
    Destination  Gateway      Genmask       Flags MSS Window irtt Iface
    192.168.42.0 0.0.0.0      255.255.255.0 U      40 0         0 eth0
    127.0.0.0    0.0.0.0      255.0.0.0     U      40 0         0 lo
    0.0.0.0      192.168.42.1 0.0.0.0       UG     40 0         0 eth0

This is a typical client machine in an IP network. It only has one network device, eth0. The lo interface is the local loop.

The modern way

The novel way to get this info from your system is by using the `ip` command:

`ip route show`

When this machine tries to contact a host that is on another network than its own, indicated by the line starting with 0.0.0.0, it will send the connection requests to the machine (router) with IP address 192.168.42.1, and it will use its primary interface, eth0, to do this.

Hosts that are on the same network, the line starting with 192.168.42.0, will also be contacted through the primary network interface, but no router is necessary, the data are just put on the network.

Machines can have much more complicated routing tables than this one, with lots of different Destination-Gateway pairs to connect to different networks. If you have the occasion to connect to an application server, for instance at work, it is most educating to check the routing information.

### Other hosts

An impressive amount of tools is focused on network management and remote administration of Linux machines. Your local Linux software mirror will offer plenty of those. It would lead us too far to discuss them in this document, so please refer to the program-specific documentation.

We will only discuss some common UNIX/Linux text tools in this section.

#### The host command

To display information on hosts or domains, use the `host` command:

networking host lookup
host

    [emmy@pc10 emmy]$ host www.eunet.be
    www.eunet.be. has address 193.74.208.177

    [emmy@pc10 emmy]$ host -t any eunet.be
    eunet.be. SOA dns.eunet.be. hostmaster.Belgium.EU.net.
      2002021300 28800 7200 604800 86400
    eunet.be. mail is handled by 50 pophost.eunet.be.
    eunet.be. name server ns.EU.net.
    eunet.be. name server dns.eunet.be.

Similar information can be displayed using the `dig` command, which gives additional information about how records are stored in the name server.

dig

#### The ping command

To check if a host is alive, use `ping`. If your system is configured to send more than one packet, interrupt `ping` with the Ctrl+C key combination:

ping
networking check other hosts

    [emmy@pc10 emmy]$ ping a.host.be
    PING a.host.be (1.2.8.3) from 80.20.84.26: 56(84) bytes of data.
    64 bytes from a.host.be(1.2.8.3):icmp_seq=0 ttl=244 time=99.977msec
    --- a.host.be ping statistics ---
    1 packets transmitted, 1 packets received, 0% packet loss
    round-trip min/avg/max/mdev = 99.977/99.977/99.977/0.000 ms

#### The traceroute command

To check the route that packets follow to a network host, use the `traceroute` command:

traceroute
networking trace hosts

    [emmy@pc10 emmy]$ /usr/sbin/traceroute www.eunet.be
    traceroute to www.eunet.be(193.74.208.177),30 hops max,38b packets
    1 blob (10.0.0.1)
           0.297ms  0.257ms  0.174ms
    2 adsl-65.myprovider.be (217.136.111.1)
           12.120ms 13.058ms 13.009ms
    3 194.78.255.177 (194.78.255.177)
           13.845ms 14.308ms 12.756ms
    4 gigabitethernet2-2.intl2.gam.brussels.skynet.be (195.238.2.226)
           13.123ms 13.164ms 12.527ms
    5 pecbru2.car.belbone.be (194.78.255.118)
           16.336ms 13.889ms 13.028ms
    6 ser-2-1-110-ias-be-vil-ar01.kpnbelgium.be (194.119.224.9)
           14.602ms 15.546ms 15.959ms
    7 unknown-195-207-939.eunet.be (195.207.93.49)
           16.514ms 17.661ms 18.889ms
    8 S0-1-0.Leuven.Belgium.EU.net (195.207.129.1)
           22.714ms 19.193ms 18.432ms
    9 dukat.Belgium.EU.net (193.74.208.178) 22.758ms * 25.263ms

On some systems, `traceroute` has been renamed to `tracepath`.

#### The whois command

Specific domain name information can be queried using the `whois` command, as is explained by many `whois` servers, like the one below:

whois
networking info on hosts

    [emmy@pc10 emmy]$ whois cnn.com
    [whois.crsnic.net]

    Whois Server Version 1.3

    	$<--snap server message-->

       Domain Name: CNN.COM
       Registrar: NETWORK SOLUTIONS, INC.
       Whois Server: whois.networksolutions.com
       Referral URL: http://www.networksolutions.com
       Name Server: TWDNS-01.NS.AOL.COM
       Name Server: TWDNS-02.NS.AOL.COM
       Name Server: TWDNS-03.NS.AOL.COM
       Name Server: TWDNS-04.NS.AOL.COM
       Updated Date: 12-mar-2002
    >>> Last update of whois database: Fri, 5 Apr 2002 05:04:55 EST <<<

    The Registry database contains ONLY .COM, .NET, .ORG, .EDU domains
    and Registrars.

    [whois.networksolutions.com]

            $<--snap server message-->

    Registrant:
    Turner Broadcasting (CNN-DOM)
       1 CNN Center
       Atlanta, GA 30303

       Domain Name: CNN.COM

       Administrative Contact:
            $<--snap contactinfo-->
       Technical Contact:
            $<--snap contactinfo-->
       Billing Contact:
    	$<--snap contactinfo-->
       Record last updated on 12-Mar-2002.
       Record expires on 23-Sep-2009.
       Record created on 22-Sep-1993.
       Database last updated on 4-Apr-2002 20:10:00 EST.

       Domain servers in listed order:

       TWDNS-01.NS.AOL.COM		149.174.213.151
       TWDNS-02.NS.AOL.COM		152.163.239.216
       TWDNS-03.NS.AOL.COM		205.188.146.88
       TWDNS-04.NS.AOL.COM		64.12.147.120

For other domain names than .com, .net, .org and .edu, you might need to specify the whois server, such as this one for .be domains:

`whois domain.be@whois.dns.be`

## Internet/Intranet applications

The Linux system is a great platform for offering networking services. In this section, we will try to give an overview of most common network servers and applications.

### Server types

#### Standalone server

Offering a service to users can be approached in two ways. A daemon or service can run in standalone mode, or it can be dependent on another service to be activated.

Network services that are heavily and/or continuously used, usually run in the standalone mode: they are independent program daemons that are always running. They are most likely started up at system boot time, and they wait for requests on the specific connection points or ports for which they are set up to listen. When a request comes, it is processed, and the listening continues until the next request. A web server is a typical example: you want it to be available 24 hours a day, and if it is too busy it should create more listening instances to serve simultaneous users. Other examples are the large software archives such as Sourceforge or your Tucows mirror, which must handle thousands of FTP requests per day.

server types standalone

An example of a standalone network service on your home computer might be the `named` (name daemon), a caching name server. Standalone services have their own processes running, you can check any time using `ps`:

    bob:~> ps auxw | grep named
    named   908  0.0  1.0 14876 5108 ?   S  Mar14  0:07 named -u named

However, there are some services that you can use on your PC, even if there is no server process running for that services. Examples could be the FTP service, the secure copy service or the finger service. Those services have the Internet Daemon (`inetd`) listening in their place.

#### (x)inetd

On your home PC, things are usually a bit calmer. You may have a small network, for instance, and you may have to transfer files from one PC to another from time to time, using FTP or Samba (for connectivity with MS Windows machines). In those cases, starting all the services which you only need occasionally and having them run all the time would be a waste of resources. So in smaller setups, you will find the necessary daemons dependent on a central program, that listen on all the ports of the services for which it is responsible.

server types managed services

This super-server, the Internet services daemon, is started up at system initialization time. There are two common implementations: `inetd` and `xinetd` (the extended Internet services daemon). One or the other is usually running on every Linux system:

daemons inetd
inetd
xinetd

    bob:~> ps -ef | grep inet
    root  926   1 0 Mar14 ?   00:00:00 xinetd-ipv6 -stayalive -reuse \
    -pidfile /var/run/xinetd.pid

The services for which the Internet daemon is responsible, are listed in its configuration file, `/etc/inetd.conf`, for `inetd`, and in the directory `/etc/xinetd.d` for `xinetd`. Commonly managed services include file share and print services, SSH, FTP, telnet, the Samba configuration daemon, talk and time services.

inetd.conf
xinetd.d

As soon as a connection request is received, the central server will start an instance of the required server. Thus, in the example below, when user bob starts an FTP session to the local host, an FTP daemon is running as long as the session is active:

    bob:~> ps auxw | grep ftp
    bob     793  0.1  0.2  3960 1076 pts/6    S    16:44   0:00 ncftp localhost
    ftp     794  0.7  0.5  5588 2608 ?        SN   16:44   0:00 ftpd:
    localhost.localdomain: anonymous/bob@his.server.com: IDLE

Of course, the same happens when you open connections to remote hosts: either a daemon answers directly, or a remote `(x)inetd` starts the service you need and stops it when you quit.

### Mail

#### Servers

Sendmail is the standard mail server program or Mail Transport Agent for UNIX platforms. It is robust, scalable, and when properly configured with appropriate hardware, handles thousands of users without blinking. More information about how to configure Sendmail is included with the sendmail and sendmail-cf packages, you may want to read the `README` and `README.cf` files in `/usr/share/doc/sendmail`. The `man sendmail` and `man aliases` are also useful.

Sendmail
mail servers overview
servers mail

Qmail is another mail server, gaining popularity because it claims to be more secure than Sendmail. While Sendmail is a monolithic program, Qmail consists of smaller interacting program parts that can be better secured. Postfix is another mail server which is gaining popularity.

Qmail
Postfix

These servers handle mailing lists, filtering, virus scanning and much more. Free and commercial scanners are available for use with Linux. Examples of mailing list software are Mailman, Listserv, Majordomo and EZmlm. See the web page of your favorite virus scanner for information on Linux client and server support. Amavis and Spamassassin are free implementations of a virus scanner and a spam scanner.

mail mailing lists
mail anti-spam/anti-virus

#### Remote mail servers

The most popular protocols to access mail remotely are POP3 and IMAP4. IMAP and POP both allow offline operation, remote access to new mail and they both rely on an SMTP server to send mail.

mail protocols
POP3
IMAP

While POP is a simple protocol, easy to implement and supported by almost any mail client, IMAP is to be preferred because:

- It can manipulate persistent message status flags.

- It can store as well as fetch mail messages.

- It can access and manage multiple mailboxes.

- It supports concurrent updates and shared mailboxes.

- It is also suitable for accessing Usenet messages and other documents.

- IMAP works both on-line and off-line.

- it is optimized for on-line performance, especially over low-speed links.

#### Mail user-agents

There are plenty of both text and graphical E-mail clients, we'll just name a few of the common ones. Pick your favorite.

mail client applications

The UNIX `mail` command has been around for years, even before networking existed. It is a simple interface to send messages and small files to other users, who can then save the message, redirect it, reply to it etcetera.

While it is not commonly used as a client anymore, the `mail` program is still useful, for example to mail the output of a command to somebody:

`mail future.employer@whereIwant2work.com < `cv.txt``

The `elm` mail reader is a much needed improvement to `mail`, and so is `pine` (Pine Is Not ELM). The `mutt` mail reader is even more recent and offers features like threading.

For those users who prefer a graphical interface to their mail (and a tennis elbow or a mouse arm), there are hundreds of options. The most popular for new users are Mozilla Mail/Thunderbird, which has easy anti-spam configuring options, and Evolution, the MS Outlook clone. Kmail is popular among KDE users.

Evolution mail and news reader

Evolution E-mail client looks just like MS Outlook.

There are also tens of web mail applications available, such as Squirrelmail, Yahoo! mail, gmail from Google and Hotmail.

An overview is available via the Linux Mail User HOWTO.

Most Linux distributions include `fetchmail`, a mail-retrieval and forwarding utility. It fetches mail from remote mail servers (POP, IMAP and some others) and forwards it to your local delivery system. You can then handle the retrieved mail using normal mail clients. It can be run in daemon mode to repeatedly poll one or more systems at a specified interval. Information and usage examples can be found in the Info pages; the directory `/usr/share/doc/fetchmail[-<version>]` contains a full list of features and a FAQ for beginners.

fetchmail

The `procmail` filter can be used for filtering incoming mail, to create mailing lists, to pre-process mail, to selectively forward mail and more. The accompanying `formail` program, among others, enables generation of auto-replies and splitting up mailboxes. Procmail has been around for years on UNIX and Linux machines and is a very robust system, designed to work even in the worst circumstances. More information may be found in the `/usr/share/doc/procmail[-<version>]` directory and in the man pages.

procmail
formail

A note on E-mail Etiquette

Some people these days seem to think that an E-mail message shouldn't be too formal. That depends, of course. If you are writing to someone you don't know, best to keep some distance, just like you would do in a traditional letter. And don't forget: people you don't know might be male or female...

### Web

#### The Apache Web Server

Apache is by far the most popular web server, used on more than half of all Internet web servers. Most Linux distributions include Apache. Apache's advantages include its modular design, SSL support, stability and speed. Given the appropriate hardware and configuration it can support the highest loads.

Apache
servers web

On Linux systems, the server configuration is usually done in the `/etc/httpd` directory. The most important configuration file is `httpd.conf`; it is rather self-explanatory. Should you need help, you can find it in the `httpd` man page or on the Apache website.

#### Web browsers

A number of web browsers, both free and commercial, exist for the Linux platform. Netscape Navigator as the only decent option has long been a thing of the past, as Mozilla/Firefox offers a competitive alternative running on many other operating systems, like MS Windows and MacOS X as well.

web browsers overview

Amaya is the W3C browser. Opera is a commercial browser, compact and fast. Many desktop managers offer web browsing features in their file manager, like `nautilus`.

Among the popular text based browsers are `lynx` and `links`. You may need to define proxy servers in your shell, by setting the appropriate variables. Text browsers are fast and handy when no graphical environment is available, such as when used in scripts.

#### Proxy servers

##### What is a proxy server?

Companies and organizations often want their users to use a proxy server. Especially in environments with lots of users, a proxy server can enable faster downloads of web pages. The proxy server stores web pages. When a user asks for a web page that has already been requested previously, the proxy server will give that page to the user directly, so that s/he does not need to get it from the Internet, which would take longer. Of course, measures can be taken so that the proxy server does a quick check and always serves the most recent version of a page. In some environments, usage of the proxy server is compulsory, in other environments you may have the choice whether or not to use it.

servers proxy

##### Proxy configuration

If you have the proxy server name and port, it should be rather obvious to feed that information into your browser. However, many (command line) applications depend on the variables `http_proxy` and `ftp_proxy` for correct functioning. For your convenience, you might want to add a line like the following to your `~/.bashrc`:

proxy configuration
http_proxy
ftp_proxy
.bashrc
`export `http_proxy`=http://username:password@proxy_server_name:port_number`

For instance:

`export `http_proxy`=http://willy:Appelsi3ntj3@proxy:80`

If you do not need to give a username and password, simply leave out everything before the @ sign, this sign included.

### File Transfer Protocol

#### FTP servers

On a Linux system, an FTP server is typically run from `xinetd`, using the WU-ftpd server, although the FTP server may be configured as a stand-alone server on systems with heavy FTP traffic. See the exercises.

servers FTP
FTP servers

Other FTP servers include among others vsftpd, Ncftpd and Proftpd.

Most Linux distributions contain the anonftp package, which sets up an anonymous FTP server tree and accompanying configuration files.

#### FTP clients

Most Linux distributions include `ncftp`, an improved version of the common UNIX `ftp` command, which you may also know from the Windows command line. The `ncftp` program offers extra features such as a nicer and more comprehensible user interface, file name completion, append and resume functions, bookmarking, session management and more:

FTP clients
ncftp
ftp

    thomas:~> ncftp blob
    NcFTP 3.0.3 (April 15, 2001) by Mike Gleason (ncftp@ncftp.com).
    Connecting to blob...
    blob.some.net FTP server (Version wu-2.6.1-20) ready.
    Logging in...
    Guest login ok, access restrictions apply.
    Logged in to blob.
    ncftp / > help
    Commands may be abbreviated.  'help showall' shows hidden and
    unsupported commands.
    'help <command>' gives a brief description of <command>.

    ascii      cat      help      lpage     open     quote    site
    bgget      cd       jobs      lpwd      page     rename   type
    bgput      chmod    lcd       lrename   pdir     rhelp    umask
    bgstart    close    lchmod    lrm       pls      rm       version
    binary     debug    lls       lrmdir    put      rmdir
    bookmark   dir      lmkdir    ls        pwd      set
    bookmarks  get      lookup    mkdir     quit     show
    ncftp / >

Excellent help with lot of examples can be found in the man pages. And again, a number of GUI applications are available.

FTP is insecure!

Don't use the File Transfer Protocol for non-anonymous login unless you know what you are doing. Your user name and password might be captured by malevolent fellow network users! Use secure FTP instead; the `sftp` program comes with the Secure SHell suite, see .

FTP secure FTP
sftp

### Chatting and conferencing

Various clients and systems are available in each distribution, replacing the old-style IRC text-based chat. A short and incomplete list of the most popular programs:

networking chatting and conferencing

- `gaim`: multi-protocol instant messaging client for Linux, Windows and Mac, compatible with MSN Messenger, ICQ, IRC and much more; see the Info pages or the Gaim site for more.

- `xchat`: IRC client for the X window system:

  X-Chat

  The home page is at SourceForge.

- aMSN: an MSN clone.

- `Konversation`, `kopete`, `KVIrc` and many other K-tools from the KDE suite.

- `gnomemeeting`: videoconferencing program for UNIX (now Ekiga).

- `jabber`: Open Source Instant Messenging platform, compatible with ICQ, AIM, Yahoo, MSN, IRC, SMTP and much more.

- `psi`: jabber client, see the PSI Jabber Client Homepage.

- `skype`: program for making telephone-like calls over the Internet to other Skype users, see for more info. Skype is free but not open.

- Gizmo: a free (but not open) phone for your computer, see .

### News services

Running a Usenet server involves a lot of expertise and fine-tuning, so refer to the INN homepage for more information.

servers news

There are a couple of interesting newsgroups in the comp.* hierarchy, which can be accessed using a variety of text and graphical clients. A lot of mail clients support newsgroup browsing as well, check your program or see your local Open Source software mirror for text clients such as `tin`, `slrnn` and `mutt`, or download Mozilla or one of a number of other graphical clients.

Deja.com keeps a searchable archive of all newsgroups, powered by Google. This is a very powerful instrument for getting help: chances are very high that somebody has encountered your problem, found a solution and posted it in one of the newsgroups.

### The Domain Name System

All these applications need DNS services to match IP addresses to host names and vice versa. A DNS server does not know all the IP addresses in the world, but networks with other DNS servers which it can query to find an unknown address. Most UNIX systems can run `named`, which is part of the BIND (Berkeley Internet Name Domain) package distributed by the Internet Software Consortium. It can run as a stand-alone caching nameserver, which is often done on Linux systems in order to speed up network access.

servers DNS
named
ISC
nameserver

Your main client configuration file is `/etc/resolv.conf`, which determines the order in which Domain Name Servers are contacted:

resolv.conf

    search somewhere.org
    nameserver 192.168.42.1
    nameserver 193.74.208.137

More information can be found in the Info pages on `named`, in the `/usr/share/doc/bind[-<version>]` files and on the Bind project homepage. The DNS HOWTO covers the use of BIND as a DNS server.

### DHCP

DHCP is the Dynamic Host Configuration Protocol, which is gradually replacing good old `bootp` in larger environments. It is used to control vital networking parameters such as IP addresses and name servers of hosts. DHCP is backward compatible with `bootp`. For configuring the server, you will need to read the HOWTO.

protocols DHCP
DHCP
servers DHCP

DHCP client machines will usually be configured using a GUI that configures the `dhcpcd`, the DHCP client daemon. Check your system documentation if you need to configure your machine as a DHCP client.

dhcpcd

### Authentication services

#### Traditional

Traditionally, users are authenticated locally, using the information stored in `/etc/passwd` and `/etc/shadow` on each system. But even when using a network service for authenticating, the local files will always be present to configure system accounts for administrative use, such as the root account, the daemon accounts and often accounts for additional programs and purposes.

passwd
shadow
servers authentication

These files are often the first candidates for being examined by hackers, so make sure the permissions and ownerships are strictly set as should be:

    bob:~> ls -l /etc/passwd /etc/shadow
    -rw-r--r--    1 root     root         1803 Mar 10 13:08 /etc/passwd
    -r--------    1 root     root         1116 Mar 10 13:08 /etc/shadow

#### PAM

Linux can use PAM, the Pluggable Authentication Module, a flexible method of UNIX authentication. Advantages of PAM:

PAM

- A common authentication scheme that can be used with a wide variety of applications.

- PAM can be implemented with various applications without having to recompile the applications to specifically support PAM.

- Great flexibility and control over authentication for the administrator and application developer.

- Application developers do not need to develop their program to use a particular authentication scheme. Instead, they can focus purely on the details of their program.

The directory `/etc/pam.d` contains the PAM configuration files (used to be `/etc/pam.conf`). Each application or service has its own file. Each line in the file has four elements:

- Module:

  - `auth`: provides the actual authentication (perhaps asking for and checking a password) and sets credentials, such as group membership or Kerberos tickets.

  - `account`: checks to make sure that access is allowed for the user (the account has not expired, the user is allowed to log in at this time of day, and so on).

  - `password`: used to set passwords.

  - `session`: used after a user has been authenticated. This module performs additional tasks which are needed to allow access (for example, mounting the user's home directory or making their mailbox available).

  The order in which modules are stacked, so that multiple modules can be used, is very important.

- Control Flags: tell PAM which actions to take upon failure or success. Values can be `required`, `requisite`, `sufficient` or `optional`.

- Module Path: path to the pluggable module to be used, usually in `/lib/security`.

- Arguments: information for the modules

Shadow password files are automatically detected by PAM.

More information can be found in the `pam` man pages or at the Linux-PAM project homepage.

#### LDAP

The Lightweight Directory Access Protocol is a client-server system for accessing global or local directory services over a network. On Linux, the OpenLDAP implementation is used. It includes `slapd`, a stand-alone server; `slurpd`, a stand-alone LDAP replication server; libraries implementing the LDAP protocol and a series of utilities, tools and sample clients.

protocols LDAP
LDAP
slapd

The main benefit of using LDAP is the consolidation of certain types of information within your organization. For example, all of the different lists of users within your organization can be merged into one LDAP directory. This directory can be queried by any LDAP-enabled applications that need this information. It can also be accessed by users who need directory information.

Other LDAP or X.500 Lite benefits include its ease of implementation (compared to X.500) and its well-defined Application Programming Interface (API), which means that the number of LDAP-enabled applications and LDAP gateways should increase in the future.

On the negative side, if you want to use LDAP, you will need LDAP-enabled applications or the ability to use LDAP gateways. While LDAP usage should only increase, currently there are not very many LDAP-enabled applications available for Linux. Also, while LDAP does support some access control, it does not possess as many security features as X.500.

Since LDAP is an open and configurable protocol, it can be used to store almost any type of information relating to a particular organizational structure. Common examples are mail address lookups, central authentication in combination with PAM, telephone directories and machine configuration databases.

See your system specific information and the man pages for related commands such as `ldapmodify` and `ldapsearch` for details. More information can be found in the LDAP Linux HOWTO, which discusses installation, configuration, running and maintenance of an LDAP server on Linux. The author of this Introduction to Linux document also wrote an LDAP Operations HOWTO, describing the basics everyone should know about when dealing with LDAP management, operations and integration of services.

## Remote execution of applications

### Introduction

There are a couple of different ways to execute commands or run programs on a remote machine and have the output, be it text or graphics, sent to your workstation. The connections can be secure or insecure. While it is of course advised to use secure connections instead of transporting your password over the network unencrypted, we will discuss some practical applications of the older (unsafe) mechanisms, as they are still useful in a modern networked environment, such as for troubleshooting or running exotic programs.

commands remote execution
networking remote execution

### Rsh, rlogin and telnet

The `rlogin` and `rsh` commands for remote login and remote execution of commands are inherited from UNIX. While seldom used because they are blatantly insecure, they still come with almost every Linux distribution for backward compatibility with UNIX programs.

rlogin
rsh
remote execution security

Telnet, on the other hand, is still commonly used, often by system and network administrators. Telnet is one of the most powerful tools for remote access to files and remote administration, allowing connections from anywhere on the Internet. Combined with an X server, remote graphical applications can be displayed locally. There is no difference between working on the local machine and using the remote machine.

Because the entire connection is unencrypted, allowing `telnet` connections involves taking high security risks. For normal remote execution of programs, Secure SHell or `ssh` is advised. We will discuss the secure method later in this section.

security remote commands
telnet
ssh

However, `telnet` is still used in many cases. Below are some examples in which a mail server and a web server are tested for replies:

telnet examples

Checking that a mail server works:

    [jimmy@blob ~] telnet mailserver 25
    Trying 192.168.42.1...
    Connected to mailserver.
    Escape character is '^]'.
    220 m1.some.net ESMTP Sendmail 8.11.6/8.11.6; 200302281626
    ehlo some.net
    250-m1.some.net Hello blob.some.net [10.0.0.1], pleased to meet you
    250-ENHANCEDSTATUSCODES
    250-8BITMIME
    250-SIZE
    250-DSN
    250-ONEX
    250-ETRN
    250-XUSR
    250 HELP
    mail from: jimmy@some.net
    250 2.1.0 jimmy@some.net... Sender ok
    rcpt to: davy@some.net
    250 2.1.5 davy@some.net... Recipient ok
    data
    354 Enter mail, end with "." on a line by itself
    test
    .
    250 2.0.0 g2MA1R619237 Message accepted for delivery
    quit
    221 2.0.0 m1.some.net closing connection
    Connection closed by foreign host.

Checking that a web server answers to basic requests:

    [jimmy@blob ~] telnet www.some.net 80
    Trying 64.39.151.23...
    Connected to www.some.net.
    Escape character is '^]'.
    HEAD / ;HTTP/1.1

    HTTP/1.1 200 OK
    Date: Fri, 22 Mar 2002 10:05:14 GMT
    Server: Apache/1.3.22 (UNIX) (Red-Hat/Linux)
     mod_ssl/2.8.5 OpenSSL/0.9.6
     DAV/1.0.2 PHP/4.0.6 mod_perl/1.24_01
    Last-Modified: Fri, 04 Jan 2002 08:21:00 GMT
    ETag: "70061-68-3c3565ec"
    Accept-Ranges: bytes
    Content-Length: 104
    Connection: close
    Content-Type: text/html

    Connection closed by foreign host.

    [jimmy@blob ~]

This is perfectly safe, because you never have to give a username and/or password for getting the data you want, so nobody can snoop that important information off the cable.

### The X Window System

#### X features

As we already explained in Chapter 7 (see ), the X Window system comes with an X server which serves graphics to clients that need a display.

X Window features

It is important to realize the distinction between the X server and the X client application(s). The X server controls the display directly and is responsible for all input and output via keyboard, mouse and display. The X client, on the other hand, does not access the input and output devices directly. It communicates with the X server which handles input and output. It is the X client which does the real work, like computing values, running applications and so forth. The X server only opens windows to handle input and output for the specified client.

In normal operation (graphical mode), every Linux workstation is an X server to itself, even if it only runs client applications. All the applications you are running (for example, Gimp, a terminal window, your browser, your office application, your CD playing tool, and so on) are clients to your X server. Server and client are running on the same machine in this case.

This client/server nature of the X system makes it an ideal environment for remote execution of applications and programs. Because the process is actually being executed on the remote machine, very little CPU power is needed on the local host. Such machines, purely acting as servers for X, are called X terminals and were once very popular. More information may be found in the Remote X applications mini-HOWTO.

#### Telnet and X

If you would want to use `telnet` to display graphical applications running on a remote machine, you first need to give the remote machine access to your display (to your X server!) using the `xhost` command, by typing a command similar to the one below in a terminal window on your local machine:

remote execution X Window
xhost

    davy:~> xhost +remote.machine.com

After that, connect to the remote host and tell it to display graphics on the local machine by setting the environment variable `DISPLAY`:

DISPLAY

    [davy@remote ~] export DISPLAY="local.host.com:0.0"

After completing this step, any application started in this terminal window will be displayed on your local desktop, using remote resources for computing, but your local graphical resources (your X server) for displaying the application.

This procedure assumes that you have some sort of X server (XFree86, X.org, Exceed, Cygwin) already set up on the machine where you want to display images. The architecture and operating system of the client machine are not important as long as they allow you to run an X server on it.

Mind that displaying a terminal window from the remote machine is also considered to be a display of an image.

### The SSH suite

#### Introduction

Most UNIX and Linux systems now run Secure SHell in order to leave out the security risks that came with `telnet`. Most Linux systems will run a version of OpenSSH, an Open Source implementation of the SSH protocol, providing secure encrypted communications between untrusted hosts over an untrusted network. In the standard setup X connections are automatically forwarded, but arbitrary TCP/IP ports may also be forwarded using a secure channel.

Secure SHell
security Secure SHell

The `ssh` client connects and logs into the specified host name. The user must provide his identity to the remote machine as specified in the `sshd_config` file, which can usually be found in `/etc/ssh`. The configuration file is rather self-explanatory and by defaults enables most common features. Should you need help, you can find it in the `sshd` man pages.

ssh
sshd_config

When the user's identity has been accepted by the server, the server either executes the given command, or logs into the machine and gives the user a normal shell on the remote machine. All communication with the remote command or shell will be automatically encrypted.

The session terminates when the command or shell on the remote machine exits and all X11 and TCP/IP connections have been closed.

When connecting to a host for the first time, using any of the programs that are included in the SSH collection, you need to establish the authenticity of that host and acknowledge that you want to connect:

Secure SHell example

    lenny ~> ssh blob
    The authenticity of host 'blob (10.0.0.1)' can't be established.
    RSA fingerprint is 18:30:50:46:ac:98:3c:93:1a:56:35:09:8d:97:e3:1d.
    Are you sure you want to continue connecting (yes/no)? yes
    Warning: Permanently added 'blob,192.168.30.2' (RSA) to the list of
    known hosts.
    Last login: Sat Dec 28 13:29:19 2002 from octarine
    This space for rent.

    lenny is in ~

It is important that you type yes, in three characters, not just y. This edits your `~/.ssh/known_hosts` file, see .

If you just want to check something on a remote machine and then get your prompt back on the local host, you can give the commands that you want to execute remotely as arguments to `ssh`:

    lenny ~> ssh blob who
    jenny@blob's password:
    root     tty2         Jul 24 07:19
    lena	 tty3         Jul 23 22:24
    lena     0:	      Jul 25 22:03

    lenny ~> uname -n
    magrat.example.com

#### X11 and TCP forwarding

If the `X11Forwarding` entry is set to yes on the target machine and the user is using X applications, the `DISPLAY` environment variable is set, the connection to the X11 display is automatically forwarded to the remote side in such a way that any X11 programs started from the shell will go through the encrypted channel, and the connection to the real X server will be made from the local machine. The user should not manually set `DISPLAY`. Forwarding of X11 connections can be configured on the command line or in the `sshd` configuration file.

Secure SHell X11Forwarding
DISPLAY

The value for `DISPLAY` set by `ssh` will point to the server machine, but with a display number greater than zero. This is normal, and happens because `ssh` creates a proxy X server on the server machine (that runs the X client application) for forwarding the connections over the encrypted channel.

This is all done automatically, so when you type in the name of a graphical application, it is displayed on your local machine and not on the remote host. We use `xclock` in the example, since it is a small program which is generally installed and ideal for testing:

SSH X11 forwarding

SSH will also automatically set up Xauthority data on the server machine. For this purpose, it will generate a random authorization cookie, store it in `Xauthority` on the server, and verify that any forwarded connections carry this cookie and replace it by the real cookie when the connection is opened. The real authentication cookie is never sent to the server machine (and no cookies are sent in the plain).

Xauthority

Forwarding of arbitrary TCP/IP connections over the secure channel can be specified either on the command line or in a configuration file.

The X server

This procedure assumes that you have a running X server on the client where you want to display the application from the remote host. The client may be of different architecture and operating system than the remote host, as long as it can run an X server, such as Cygwin (which implements an X.org server for MS Windows clients and others) or Exceed, it should be possible to set up a remote connection with any Linux or UNIX machine.

#### Server authentication

The `ssh` client/server system automatically maintains and checks a database containing identifications for all hosts it has ever been used with. Host keys are stored in `$HOME/.ssh/known_hosts` in the user's home directory. Additionally, the file `/etc/ssh/ssh_known_hosts` is automatically checked for known hosts. Any new hosts are automatically added to the user's file. If a host's identification ever changes, `ssh` warns about this and disables password authentication to prevent a Trojan horse from getting the user's password. Another purpose of this mechanism is to prevent man-in-the-middle attacks which could otherwise be used to circumvent the encryption. In environments where high security is needed, `sshd` can even be configured to prevent logins to machines whose host keys have changed or are unknown.

Secure SHell server authentication

#### Secure remote copying

The SSH suite provides `scp` as a secure alternative to the `rcp` command that used to be popular when only `rsh` existed. `scp` uses `ssh` for data transfer, uses the same authentication and provides the same security as `ssh`. Unlike `rcp`, `scp` will ask for passwords or passphrases if they are needed for authentication:

Secure SHell secure copy
scp
scp example

    lenny /var/tmp> scp Schedule.sdc.gz blob:/var/tmp/
    lenny@blob's password:
    Schedule.sdc.gz  100% |*****************************| 100 KB 00:00

    lenny /var/tmp>

Any file name may contain a host and user specification to indicate that the file is to be copied to/from that host. Copies between two remote hosts are permitted. See the Info pages for more information.

If you would rather use an FTP-like interface, use `sftp`:

sftp example

    lenny /var/tmp> sftp blob
    Connecting to blob...
    lenny@blob's password:

    sftp> cd /var/tmp

    sftp> get Sch*
    Fetching /var/tmp/Schedule.sdc.gz to Schedule.sdc.gz

    sftp> bye

    lenny /var/tmp>

Secure copy or FTP GUIs

Don't feel comfortable with the command line yet? Try Konqueror's capabilities for secure remote copy, or install Putty.

#### Authentication keys

The `ssh-keygen` command generates, manages and converts authentication keys for `ssh`. It can create RSA keys for use by SSH protocol version 1 and RSA or DSA keys for use by SSH protocol version 2.

ssh-keygen
Secure SHell authentication keys

Normally each user wishing to use SSH with RSA or DSA authentication runs this once to create the authentication key in `$HOME/.ssh/identity`, `id_dsa` or `id_rsa`. Additionally, the system administrator may use this to generate host keys for the system.

Normally this program generates the key and asks for a file in which to store the private key. The public key is stored in a file with the same name but .pub appended. The program also asks for a passphrase. The passphrase may be empty to indicate no passphrase (host keys must have an empty passphrase), or it may be a string of arbitrary length.

There is no way to recover a lost passphrase. If the passphrase is lost or forgotten, a new key must be generated and copied to the corresponding public keys.

We will study SSH keys in the exercises. All information can be found in the man or Info pages.

### VNC

VNC or Virtual Network Computing is in fact a remote display system which allows viewing a desktop environment not only on the local machine on which it is running, but from anywhere on the Internet and from a wide variety of machines and architectures, including MS Windows and several UNIX distributions. You could, for example, run MS Word on a Windows NT machine and display the output on your Linux desktop. VNC provides servers as well as clients, so the opposite also works and it may thus be used to display Linux programs on Windows clients. VNC is probably the easiest way to have X connections on a PC. The following features make VNC different from a normal X server or commercial implementations:

VNC
remote execution VNC

- No state is stored at the viewer side: you can leave your desk and resume from another machine, continuing where you left. When you are running a PC X server, and the PC crashes or is restarted, all remote applications that you were running will die. With VNC, they keep on running.

- It is small and simple, no installation needed, can be run from a floppy if needed.

- Platform independent with the Java client, runs on virtually everything that supports X.

- Sharable: one desktop may be displayed on multiple viewers.

- Free.

More information can be found in the VNC client man pages (`man vncviewer`) or on the VNC website.

### The rdesktop protocol

In order to ease management of MS Windows hosts, recent Linux distributions support the Remote Desktop Protocol (RDP), which is implemented in the `rdesktop` client. The protocol is used in a number of Microsoft products, including Windows NT Terminal Server, Windows 2000 Server, Windows XP and Windows 2003 Server.

protocols RDP
rdesktop
remote execution RDP

Surprise your friends (or management) with the fullscreen mode, multiple types of keyboard layouts and single application mode, just like the real thing. The `man rdesktop` manual provides more information. The project's homepage is at .

### Cygwin

Cygwin provides substantial UNIX functionality on MS Windows systems. Apart from providing UNIX command line tools and graphical applications, it can also be used to display a Linux desktop on an MS Windows machine, using remote X. From a Cygwin Bash shell, type the command

remote execution Cygwin
Cygwin
`/usr/X11R6/bin/XWin.exe `-query` your_linux_machine_name_or_IP`

The connection is by default denied. You need to change the X Display Manager (XDM) configuration and possibly the X Font Server (XFS) configuration to enable this type of connection, where you get a login screen on the remote machine. Depending on your desktop manager (Gnome, KDE, other), you might have to change some configurations there, too.

If you do not need to display the entire desktop, you can use SSH in Cygwin, just like explained in . without all the fuss of editing configuration files.

## Security

### Introduction

As soon as a computer is connected to the network, all kinds of abuse becomes possible, be it a UNIX-based or any other system. Admittedly, mountains of papers have been spilled on this subject and it would lead us too far to discuss the subject of security in detail. There are, however, a couple of fairly logical things even a novice user can do to obtain a very secure system, because most break-ins are the result of ignorant or careless users.

security considerations

Maybe you are asking yourself if this all applies to you, using your computer at home or working at your office on a desktop in a fairly protected environment. The questions you should be asking yourself, however, are more on the lines of:

- Do you want to be in control of your own system?

- Do you want to (unwittingly) participate in criminal activities?

- Do you want your equipment to be used by someone else?

- Do you want to take risks on losing your Internet connection?

- Do you want to rebuild your system every time it has been hacked?

- Do you want to risk personal or other data loss?

Presuming you don't, we will quickly list the steps you can take to secure your machine. Extended information can be found in the Linux Security HOWTO.

### Services

The goal is to run as few services as possible. If the number of ports that are open for the outside world are kept to a minimum, this is all the better to keep an overview. If services can't be turned off for the local network, try to at least disable them for outside connections.

security disable services

A rule of thumb is that if you don't recognize a particular service, you probably won't need it anyway. Also keep in mind that some services are not really meant to be used over the Internet. Don't rely on what should be running, check which services are listening on what TCP ports using the `netstat` command:

security check open ports
netstat

    [elly@mars ~] netstat -l | grep tcp
    tcp     0      0 *:32769                 *:*      LISTEN
    tcp     0      0 *:32771                 *:*      LISTEN
    tcp     0      0 *:printer               *:*      LISTEN
    tcp     0      0 *:kerberos_master       *:*      LISTEN
    tcp     0      0 *:sunrpc                *:*      LISTEN
    tcp     0      0 *:6001                  *:*      LISTEN
    tcp     0      0 *:785                   *:*      LISTEN
    tcp     0      0 localhost.localdom:smtp *:*      LISTEN
    tcp     0      0 *:ftp                   *:*      LISTEN
    tcp     0      0 *:ssh                   *:*      LISTEN
    tcp     0      0 ::1:x11-ssh-offset      *:*      LISTEN

Things to avoid:

- `exec`, `rlogin` and `rsh`, and `telnet` just to be on the safe side.

  exec
  rlogin
  rsh
  telnet

- X11 on server machines.

- No lp if no printer is physically attached.

- No MS Windows hosts in the network, no Samba required.

- Don't allow FTP unless an FTP server is required.

- Don't allow NFS and NIS over the Internet, disable all related services on a stand-alone installation.

- Don't run an MTA if you're not actually on a mail server.

- ...

Stop running services using the `chkconfig` command, the initscripts or by editing the `(x)inetd` configuration files.

### Update regularly

Its ability to adapt quickly in an ever changing environment is what makes Linux thrive. But it also creates a possibility that security updates have been released even while you are installing a brand new version, so the first thing you should do (and this goes for about any OS you can think of) after installing is getting the updates as soon as possible. After that, update all the packages you use regularly.

security updates

Some updates may require new configuration files, and old files may be replaced. Check the documentation, and ensure that everything runs normal after updating.

Most Linux distributions provide mailing list services for security update announcements, and tools for applying updates to the system. General Linux only security issues are reported among others at Linuxsecurity.com.

Updating is an ongoing process, so it should be an almost daily habit.

### Firewalls and access policies

#### What is a firewall?

In the previous section we already mentioned firewall capabilities in Linux. While firewall administration is one of the tasks of your network admin, you should know a couple of things about firewalls.

security firewall

Firewall is a vague term that can mean anything that acts as a protective barrier between us and the outside world, generally the Internet. A firewall can be a dedicated system or a specific application that provides this functionality. Or it can be a combination of components, including various combinations of hardware and software. Firewalls are built from rules that are used to define what is allowed to enter and/or exit a given system or network.

After disabling unnecessary services, we now want to restrict accepted services as to allow only the minimum required connections. A fine example is working from home: only the specific connection between your office and your home should be allowed, connections from other machines on the Internet should be blocked.

#### Packet filters

The first line of defense is a packet filter, which can look inside IP packets and make decisions based on the content. Most common is the Netfilter package, providing the `iptables` command, a next generation packet filter for Linux.

security packet filters

One of the most noteworthy enhancements in the newer kernels is the stateful inspection feature, which not only tells what is inside a packet, but also detects if a packet belongs or is related to a new or existing connection.

The Shoreline Firewall or Shorewall for short is a front-end for the standard firewall functionality in Linux.

More information can be found at the Netfilter/iptables project page.

#### TCP wrappers

TCP wrapping provides much the same results as the packet filters, but works differently. The wrapper actually accepts the connection attempt, then examines configuration files and decides whether to accept or reject the connection request. It controls connections at the application level rather than at the network level.

security TCP wrappers

TCP wrappers are typically used with `xinetd` to provide host name and IP-address-based access control. In addition, these tools include logging and utilization management capabilities that are easy to configure.

The advantages of TCP wrappers are that the connecting client is unaware that wrappers are used, and that they operate separately from the applications they protect.

The host based access is controlled in the `hosts.allow` and `hosts.deny` files. More information can be found in the TCP wrapper documentation files in `/usr/share/doc/tcp_wrappers[-<version>/]` or `/usr/share/doc/tcp` and in the man pages for the host based access control files, which contain examples.

#### Proxies

Proxies can perform various duties, not all of which have much to do with security. But the fact that they are an intermediary make proxies a good place to enforce access control policies, limit direct connections through a firewall, and control how the network behind the proxy looks to the Internet.

servers proxy
security proxies

Usually in combination with a packet filter, but sometimes all by themselves, proxies provide an extra level of control. More information can be found in the Firewall HOWTO or on the Squid website.

#### Access to individual applications

Some servers may have their own access control features. Common examples include Samba, X Window, Bind, Apache and CUPS. For every service you want to offer check which configuration files apply.

#### Log files

If anything, the UNIX way of logging all kinds of activities into all kinds of files confirms that it is doing something. Of course, log files should be checked regularly, manually or automatically. Firewalls and other means of access control tend to create huge amounts of log files, so the trick is to try and only log abnormal activities.

files logging
security logs

### Intrusion detection

Intrusion Detection Systems are designed to catch what might have gotten past the firewall. They can either be designed to catch an active break-in attempt in progress, or to detect a successful break-in after the fact. In the latter case, it is too late to prevent any damage, but at least we have early awareness of a problem. There are two basic types of IDS: those protecting networks, and those protecting individual hosts.

security intrusion detection

For host based IDS, this is done with utilities that monitor the file system for changes. System files that have changed in some way, but should not change, are a dead give-away that something is amiss. Anyone who gets in and gets root access will presumably make changes to the system somewhere. This is usually the very first thing done, either so he can get back in through a backdoor, or to launch an attack against someone else, in which case, he has to change or add files to the system. Some systems come with the `tripwire` monitoring system, which is documented at the Tripwire Open Source Project website.

Network intrusion detection is handled by a system that sees all the traffic that passes the firewall (not by portscanners, which advertise usable ports). Snort is an Open Source example of such a program. Whitehats.com features an open Intrusion detection database, arachNIDS.

### More tips

Some general things you should keep in mind:

security tips

- Do not allow root logins. UNIX developers came up with the `su` over two decades ago for extra security.

- Direct root access is always dangerous and susceptible to human errors, be it by allowing root login or by using the `su `-`` command. Rather than using `su`, it is even better to use `sudo` to only execute the command that you need extra permissions for, and to return afterwards to your own environment.

- Take passwords seriously. Use shadow passwords. Change your passwords regularly.

- Try to always use SSH or SSL. Avoid `telnet`, FTP and E-mail clients and other client programs which send unencrypted passwords over the network. Security is not only about securing your computer, it is also about securing your passwords.

- Limit resources using `quota` and/or `ulimit`.

- The mail for root should be delivered to, or at least read by, an actual person.

- The SANS institute has more tips and tricks, sorted per distribution, with mailing list service.

- Check the origin of new software, get it from a trusted place/site. Verify new packages before installing.

- When using a non-permanent Internet connection, shut it down as soon as you don't need it anymore.

- Run private services on odd ports instead of the ones expected by possible hackers.

- Know your system. After a while, you can almost feel when something is happening.

### Have I been hacked?

How can you tell? This is a checklist of suspicious events:

security intrusion detection

- Mysterious open ports, strange processes.

- System utilities (common commands) behaving strange.

- Login problems.

- Unexplained bandwidth usage.

- Damaged or missing log files, syslog daemon behaving strange.

- Interfaces in unusual modes.

- Unexpectedly modified configuration files.

- Strange entries in shell history files.

- Unidentified temporary files.

### Recovering from intrusion

In short, stay calm. Then take the following actions in this order:

security recovery

- Disconnect the machine from the network.

- Try to find out as much as you can about how your security was breached.

- Backup important non-system data. If possible, check these data against existing backups, made before the system was compromised, to ensure data integrity.

- Re-install the system.

- Use new passwords.

- Restore from system and data backups.

- Apply all available updates.

- Re-examine the system: block off unnecessary services, check firewall rules and other access policies.

- Reconnect.

## Summary

Linux and networking go hand in hand. The Linux kernel has support for all common and most uncommon network protocols. The standard UNIX networking tools are provided in each distribution. Next to those, most distributions offer tools for easy network installation and management.

Linux is well known as a stable platform for running various Internet services, the amount of Internet software is endless. Like UNIX, Linux can be just as well used and administered from a remote location, using one of several solutions for remote execution of programs.

We briefly touched the subject of security. Linux is an ideal firewall system, light and cheap, but can be used in several other network functions such as routers and proxy servers.

Increasing network security is mainly done by applying frequent updates and common sense.

Here is an overview of network related commands:

New commands in chapter 10: Networking

Command | Meaning
--- | ---
`ftp` | Transfer files to another host (insecure).
`host` | Get information about networked hosts.
`ifconfig` | Display IP address information.
`ip` | Display IP address information.
`netstat` | Display routing information and network statistics.
`ping` | Send answer requests to other hosts.
`rdesktop` | Display and MS Windows desktop on your Linux system.
`route` | Show routing information.
`scp` | Secure copy files to and from other hosts.
`sftp` | Secure FTP files to and from other hosts.
`ssh` | Make an encrypted connection to another host.
`ssh-keygen` | Generate authentication keys for Secure SHell.
`telnet` | Make an insecure connection to another hosts.
`tracepath/traceroute` | Print the route that packets follow to another host.
`whois` | Get information abotu a domain name.
`xclock` | X Window clock application, handy for testing remote display.
`xhost` | X Window access control tool.

## Exercises

### General networking

- Display network information for your workstation: IP address, routes, name servers.

- Suppose no DNS is available. What would you do to reach your neighbour's machine without typing the IP address all the time?

- How would you permanently store proxy information for a text mode browser such as `links`?

- Which name servers handle the redhat.com domain?

- Send an E-mail to your local account. Try two different ways to send and read it. How can you check that it really arrived?

- Does your machine accept anonymous FTP connections? How do you use the `ncftp` program to authenticate with your user name and password?

- Does your machine run a web server? If not, make it do so. Check the log files!

### Remote connections

- From your local workstation, display a graphical application, such as `xclock` on your neighbour's screen. The necessary accounts will have to be set up. Use a secure connection!

- Set up SSH keys so you can connect to your neighbour's machine without having to enter a password.

- Make a backup copy of your home directory in `/var/tmp` on your neighbour's backup server, using `scp`. Archive and compress before starting the data transfer! Connect to the remote host using `ssh`, unpack the backup, and put one file back on the original machine using `sftp`.

### Security

- Make a list of open (listening) ports on your machine.

- Supposing you want to run a web server. Which services would you deactivate? How would you do that?

- Install available updates.

- How can you see who connected to your system?

- Make a repetitive job that reminds you to change your password every month, and preferably the root password as well.