Configuring the Network - Beginning the Linux Command Line, Second edition (2015)

Beginning the Linux Command Line, Second edition (2015)

CHAPTER 11. Configuring the Network

Most Linux computers operate in a connected world. Therefore, configuring the network board is of highest importance. In this chapter, you’ll first learn how to give your computer an IP address and related information. You’ll also learn about some useful tools that will help you in analyzing and troubleshooting a failing network connection. The last part of this chapter is about Secure Shell (SSH), which helps you make secured connections to other computers.

A Quick Introduction to Computer Networking

Before looking at the specifics of network configuration, it’s important you first have a general understanding of what it is all about. This section explains basic networking for people who are new to the subject; it’s not a complete tutorial, but it tries to outline the most important concepts of networking for people who don’t have much knowledge on the subject.

All networking starts with an address. The most basic address, which is on the network card, is called a Media Access Control (MAC) address. Every network card has a MAC address. This goes not only for the wired network card in your computer, but also for the mobile phone that you use to browse the Internet. These MAC addresses are unique worldwide.

Although it is possible to communicate based solely on the MAC address, such a solution would not be ideal. This is because a MAC address contains no information about where a specific computer is on the network. The only way to have communication based on the MAC address is by broadcasting to all computers in the network, querying them to find out which has the MAC address you are looking for. This works for a small local network (referred to as a LAN), but it doesn’t work for a computer that is thousands of miles away over the Internet.

The solution for this problem is in the IP address. IP addresses make worldwide communication between computers possible, as each IP address contains information about the local computer (referred to as the node part of the IP address) as well as the network the computer is on. Since each IP address includes this network information, it is possible to address a computer at the other end of the world directly through an IP.

To connect different IP networks together, a router is used. This is a dedicated machine that knows how to reach other IP networks. Most routers just know a few other networks and contain a default route. This default route refers to all other IP network addresses. At the end, most routed network traffic is handled by one of the backbone routers on the Internet. These are huge machines that know how to find all IP network addresses.

As IP addresses are in a numeric format (such as 179.237.39.66), which is not easy to handle for humans, on the Internet, computers are addressed by their name instead of their IP address. This name is translated into an IP address by a Domain Name Service (DNS) server.

To make sure your computer can communicate with other computers on the Internet, your computer needs to have an IP address, and it needs to know where to find the default router and the DNS servers. You can enter all this information manually (which you’ll learn how to do later in this chapter), but in many cases, a DHCP server is used to hand out this information automatically. If you are working on a workstation, your computer will by default contact a DHCP server, and you’ll be fine. However, if you are an administrator who is responsible for having a server up and running in your network, you’ll probably need to set all this information yourself. The next sections teach you how.

Understanding Network Device Naming

When working with network cards in Linux, you need to know a bit about network device naming. Older Linux systems used names such as eth0 for the physical network card in a system and wlan0 for a WiFi network card. As on some servers multiple network cards are used, this way of addressing network device names isn’t efficient. For that reason the BIOS dependent network device names were introduced. When this feature is enabled, you’ll see network device names that say something about the physical location of a network card in the machine.

If BIOS devicenames are used, you will see the name em for embedded network cards (em1 for instance), and p<slot>p<ethernet_port> (p6p1 for instance) for cards that are inserted in a PCI slot. In virtual machines and for network cards whose firmware doesn’t support BIOS device names, you may still see the old eth<number> names.

For some administrators, using BIOS device names is a great improvement. Others sincerely hate it because it makes network device names inconsistent between machines. If you don’t want to use BIOS device names, but rather use the old naming instead, make sure that the GRUB2 boot loader starts your server with the boot options bios.devname=0 and net.ifnames=0.

Setting the IP Address

On installation, all Linux distributions work with DHCP to get an IP address. DHCP offers a very convenient way of configuring the network card, as even simple Internet routers for home usage have an embedded DHCP server. In some cases, however, you’ll need a fixed IP address. Let’s see how this works.

Before starting our discussion about IP address manipulation, you should know that there are two methods to manage IP addresses. There is the ifconfig command, a command that has been in use for a very long period. For modern Linux distributions however, this command isn’t efficient enough anymore, and therefore there is a new way of managing IP addresses, using the ip command. The ip command is the preferred way to manage IP addresses, and if you’ve never worked with ifconfig, I recommend skipping the section about ifconfig completely. As some administrators still like using this command, I’m including information on how to manage the IP stack with this command anyway.

Using the ip Tool

The ip tool is the default tool for managing IP address configuration. It has many options that allow you to manage virtually all aspects of the network connection. For example, you can use it to configure an IP address, but it manages routing as well. Other more advanced manipulations are supported through the ip tool as well.

The first option you use with the ip command determines exactly what you want to do with the tool. It is a reference to the so-called object; you can consider these objects the secondary command level that determines more precisely what you want to do. Each of the objects has different possibilities:

· link: Used to manage or display properties of a network device. Use this for monitoring the current state of a network interface.

· addr: Used to manage or display IPv4 or IPv6 network addresses on a device.

· route: Used to manage or display entries in the routing table.

· rule: Used to manage or display rules in the routing policy database.

· neigh: Used to manage or display entries in the ARP cache. ARP gives information about which IP address is used by which MAC address. By using this option, you can modify the ARP information or display it.

· netns: Used to manage IP network namespaces, a technology that is commonly used in cloud environment and which allows you to manage isolated network environments while using the same network interface.

· tunnel: Used to manage or display IP tunnels. This is something you’ll only need when setting up Virtual Private Network (VPN) connections over the Internet. VPN technology is quite popular in enterprise environments to set up secure connections, but will not be discussed any further in this book.

· maddr: Used to manage or display multicast addresses for interfaces. A multicast address is a group address that you can add to a network card. Using multicast makes it possible for a user or an application to address all nodes that provide the same functionality simultaneously.

· mroute: Used to manage or display multicast routing cache entries.

· monitor: Used to monitor what happens on a given device.

For each of the objects, you’ll have to use options. The easiest way to learn about these options is to use the ip command followed by the object followed by the keyword help. For example, ip address help provides information on how to use the ip address command, as shown in Listing 11-1.

Listing 11-1. The ip address help Command Gives Help on Configuring IP Addresses with the ip Tool

root@ZNA:~# ip address help
Usage: ip addr {add|del} IFADDR dev STRING
ip addr {show|flush} [ dev STRING ] [ scope SCOPE-ID ]
[ to PREFIX ] [ FLAG-LIST ] [ label PATTERN ]
IFADDR := PREFIX | ADDR peer PREFIX
[ broadcast ADDR ] [ anycast ADDR ]
[ label STRING ] [ scope SCOPE-ID ]
SCOPE-ID := [ host | link | global | NUMBER ]
FLAG-LIST := [ FLAG-LIST ] FLAG
FLAG := [ permanent | dynamic | secondary | primary |
tentative | deprecated ]

It can be quite a challenge to find out how the help for the ip tool works, so I’ll give you some pointers on this feature. To understand what you need to do, you must first analyze the Usage: lines. In the example in Listing 11-1, you see two of them: a usage line that starts with ip addr {add|del}, and another that starts with ip addr {show|flush}. Let’s have a look at the first one, which allows you to add or remove an IP address.

The complete usage line as described by ip address help is ip addr {add|del} IFADDR dev STRING. So you can add or delete an IP address that is referred to by IFADDR from a device (dev) that is referred to by STRING. Now, a string is just a string, and that can be anything (but normally will be something like eth0). The IFADDR part, which is the address that you’ll assign to the string, offers more options, which are described in the next part. You can find an explanation of that part in the next section of the help output: IFADDR := PREFIX | ADDR peer PREFIX [ broadcast ADDR ] [ anycast ADDR ] [ label STRING ] [ scope SCOPE-ID ]. In this line, the help explains that you have to use a PREFIX or an ADDR statement, which may be followed by several options like the broadcast address, the anycast address, a label, or a SCOPE-ID. But from the help also follows that you can just simply add an address. There is no further explanation of the other options, as this is information that you should know about when configuring IP addresses. This means ip address helpcan’t tell you which IP address you need on which Ethernet interface. Now that you understand how the help works, let’s have a look at some of the different ways you can use the ip command.

Tip! Using the ip command based on the help text alone is challenging. You might be better of just trying to remember the most important tasks that you can do with the ip command, and how you can accomplish them. Table 11-1 gives an overview of these commands.

Table 11-1. ip command important examples overview

Task

Command

show current configuration

ip addr show

add an IP address to eth0

ip addr add 10.0.0.10/24 dev eth0

show link statistics

ip link show

show the routing table

ip route show

add a default route

ip route add default via 10.0.0.1

Showing Ip addresses with ip

A common use of ip is to display information about the use of IP addresses for a given interface. The command to use is ip address show, or just ip address. Note that, if it is clear exactly what you want and there can be no confusion between options, you can specify the options used with the ip command in short form, such as ip a s, which accomplishes the same thing as ip address show. Listing 11-2 gives an example.

Listing 11-2. Showing ip Address Configuration with ip address show

root@ZNA:~# ip address show
1: lo: <LOOPBACK,UP,10000> 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 scope host lo
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,10000> mtu 1500 qdisc pfifo_fast qlen 1000
link/ether 00:0c:29:a0:a5:80 brd ff:ff:ff:ff:ff:ff
inet 192.168.1.33/24 brd 192.168.1.255 scope global eth0
inet 10.0.0.10/8 brd 10.255.255.255 scope global eth0:0
inet 10.0.0.20/8 brd 10.255.255.255 scope global secondary eth0:1
inet6 fe80::20c:29ff:fea0:a580/64 scope link
valid_lft forever preferred_lft forever

As you can see, the ip addr show command is quite complete in what it is showing. In particular the part about eth0 (normally your fixed network card) is interesting. First, you can see that broadcast and multicast are enabled on this device, and that the network card is up. Next, it shows some other properties of the network card that are interesting if you need to troubleshoot the way a network card is functioning. However, if you just need to assign an IP address, you typically wouldn’t care about these parameters. Last, the lines starting with inet show the addresses that are assigned to the network card, with their corresponding subnet masks.

Showing Device attributes

Another simple use of the ip tool is to show device attributes, which you can do with the ip link show command. This command shows usage statistics for the device you’ve specified but no address information, which is kind of obvious as well. ip link works on the link, ip address on the IP address. Listing 11-3 provides an example of its output.

Listing 11-3. Use the ip link show Command for an Overview of Link Attributes

root@ZNA:~# ip link show
1: lo: <LOOPBACK,UP,10000> mtu 16436 qdisc noqueue
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
2: eth0: <BROADCAST,MULTICAST,UP,10000> mtu 1500 qdisc pfifo_fast qlen 1000
link/ether 00:0c:29:a0:a5:80 brd ff:ff:ff:ff:ff:ff

The information displayed by ip link show is related to the activity on the network board. Of particular interest are the device attributes returned for each of the devices (they’re displayed in brackets right after the name of the device). You can see for instance the attributesBROADCAST,MULTICAST,UP for a normal network interface card. The BROADCAST attribute indicates that the device is capable of sending broadcasts to other nodes in the network, the MULTICAST attribute indicates that the device can also send multicast packets (a feature that is disabled in some networks), and the UP attribute indicates that the device is working. The command also shows all IP protocol attributes, such as the maximum transmission unit (mtu) that is used on the interface.

Setting the IP address

You can also use the ip tool to assign an IP address to a device. To do this, you could use a command like ip address add 10.0.0.10/16 dev eth0. This command sets the IP address for eth0 to 10.0.0.10. With this IP address, a 16-bit subnet mask is used, which is indicated by the CIDR notation of the subnetmask 255.255.0.0 (/16) directly behind the IP address. The broadcast address is calculated automatically, which you can specify by adding brd + to the command. Once you have set the IP address with the ip tool, you can use the following command to check if it’s set correctly: ip address show dev eth0 (or just use ip a, which gives you the address configuration for all network cards).

You can add more than one IP address to a network interface when using the ip tool as well. And it isn’t hard: just use ip address add 10.0.0.20/16 dev eth0, and 10.0.0.20 with its specified properties is added as a second IP address to eth0 (assuming that some other IP address was already defined for this network card). There is a difference between secondary IP addresses that are added with ifconfig and the IP addresses that are added with the ip tool. An address added with ip won’t show up when you use ifconfig. So when using secondary IP addresses, make sure you use the right tool to check their properties, you might miss them when using the legacy ifconfig tool.

Using ifconfig

You can use ifconfig to manage and monitor a network interface card. The command has been around for years; although it’s not the most flexible command, it’ll still do the job. And the biggest advantage: it’s a relatively easy command to use. If you use the ifconfig command without any parameters, you’ll see information about the current configuration of the network cards in your computer. An example of this is in Listing 11-4.

Listing 11-4. The ifconfig Command Can Show Your Current Network Configuration Parameter

eth0 Link encap:Ethernet HWaddr 00:0C:29:A0:A5:80
inet addr:192.168.1.33 Bcast:192.168.1.255 Mask:255.255.255.0
inet6 addr: fe80::20c:29ff:fea0:a580/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:3035 errors:0 dropped:0 overruns:0 frame:0
TX packets:199 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:240695 (235.0 KiB) TX bytes:19035 (18.5 KiB)
Interrupt:18 Base address:0x1400
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:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 b) TX bytes:0 (0.0 b)

Displaying Information with ifconfig

As you have seen in Listing 11-4, the ifconfig command provides different kinds of information about a network card. It starts with the name of the protocol used on the network card. The protocol is indicated by (for example) Link encap: Ethernet, which states that it is an Ethernet network board. Almost all modern LAN interfaces will show you Ethernet as the link encapsulation type, but on a WAN connection you may see other protocols such as PPP instead. Then the MAC address is given as the HWaddr (hardware address). This address is followed first by the IPv4-related address information (inet addr) and then the IPv6 address information, if IPv6 hasn’t been disabled (inet6 addr). Then several statistics about the network board are given. Pay special attention to the RX packets (received packets) and TX packets (transmitted packets) because you can see from these statistics what the network board is doing and if any errors have occurred. Typically, there should be no errors here.

Image Note Currently, most computers use IP version 4 IP addresses. In version 4, approximately 4 billion IP addresses can be addressed. However, since the protocol specification is inefficient, there are almost no more free IPv4 addresses available. Therefore, IPv6 was developed (seewww.ipv6.org). The most important purpose of IPv6 is to make (many) more IP addresses available. Migration to IPv6 goes slowly, however, as it requires quite a lot of work on the network infrastructure of companies that want to migrate. Linux offers full support for IPv6, and most distributions even enable it by default. An IPv6 address is represented in hexadecimal way, as in this example: feb0:ff66:ab08:0963:badc:afe0:3796:0012. Compare this to the typical IPv4 address, which looks like 129.13.57.192.

Apart from the information about the physical network boards that are present in your computer, you’ll also always see information about the loopback device (lo), which is the network interface that’s used for internal purposes on your computer. Your computer needs this loopback device because some IP-related services depend on it; for example, the graphical environment that’s used on Linux is written on top of the IP stack offered by the loopback interface.

Configuring a Network Card with ifconfig

Although your system is provided with an IP address upon installation, it’s important for you to be able to manage IP address configuration on the fly, using the ifconfig command. Fortunately, it’s relatively easy to configure a network board in this way: just add the name of the network board you want to configure followed by the IP address you want to use on that network board (for example, ifconfig eth0 192.168.1.125). This command will configure eth0 with a default class C subnet mask of 255.255.255.0, which indicates that the first three bytes of the IP address are a part of the network address and that the last byte is the unique host identifier within that network.

Image Tip Not sure what eth device number is used? You can manage this via the udev mechanism. In the file /etc/udev/rules.d/nn-persistent-net.rules a mapping is made between the MAC address and interface number of your network boards. So if you want the eth1device to be presented as eth0, this is the place where you can change it. Just change the current name (e.g., eth1) in the name you want it to be, and restart your computer to make the change effective.

If you need a custom subnet mask, add an extra parameter to ifconfig, as in the command ifconfig eth0 172.16.18.18 netmask 255.255.255.0 broadcast 172.16.18.255, which configures the eth0 device with the given IP address and a 24-bit subnet mask. If you work with a nondefault subnet mask, you have to specify the broadcast address that’s used to address all nodes in the same network as well; the ifconfig command just isn’t smart enough to realize that you’re using a nondefault IP address and to calculate the right broadcast address accordingly.

Image Note In the IP protocol, subnet masks are used to distinguish the network part from the node part of the IP address. All IP addresses must have a subnet mask. To make working with IP easier, IP addresses do have a default subnetmask; for instance, IP addresses starting with 192, such as 192.1.2.3, have the default subnet mask 255.255.255.0, which tells the IP stack that the first three bytes are used to address the network, and the last byte only is used to address the node. In some situations, an administrator may choose to use nondefault subnet masks, for instance, if he or she needs to address more than one network but doesn’t have enough network addresses available. There are two ways to write the subnet mask that is to be used: in the so-called dotted method (e.g., 255.255.255.0) or in the CIDR method. The latter uses a slash, followed by the number of bytes that are in the subnet mask. Consult http://en.wikipedia.org/wiki/Subnetwork for a more detailed explanation of subnet masks.

Bringing Interfaces Up and Down with ifconfig

Apart from adding an IP address to a network board, you can use the ifconfig command to bring a specific network board up or down. For example, ifconfig eth0 down shuts down the interface, and ifconfig eth0 up brings it up again with its default settings. This is useful if you want to test a new configuration, but you’re not sure whether it’s really going to work properly.

Instead of using ifconfig to bring the network card up and down, you can also use ifup and ifdown. These commands allow you to bring a network card up or down easily, without changing the configuration of a given network board. For example, to bring a network board down, use ifdown eth0; to bring it up again, use ifup eth0. In both cases, the default configuration for the network card is applied.

Using Virtual Ip addresses with ifconfig

In some cases, one network card may need multiple IP addresses. These are called virtual IP addresses, and you can set them with ifconfig. Using virtual IP addresses is useful if you are configuring services on your computer that all need their own IP address. Think, for example, of different virtual Apache web servers that are all reachable on their own IP address.

Image Note This doesn’t mean that to run multiple instances of Apache, you’ll always need a virtual IP address configuration. Using virtual IP addresses is just one way of doing this.

You can use the virtual IP address either within the same IP address range or on a different one. To add a virtual IP address, add :n where n is a number after the name of the network interface. For example, ifconfig eth0:0 10.0.0.10 adds the address 10.0.0.10 as a virtual IP address to eth0. The number after the colon must be unique, so you can add a second virtual IP address with ifconfig eth0:1 10.0.0.20, and so on. When you use the ifconfig tool to display the current configuration of your computer, you’ll see all virtual IP addresses that are configured, as shown in Listing 11-5.

Listing 11-5. The ifconfig Tool Shows Virtual IP Addresses As Well

root@ZNA:~# ifconfig eth0:0 10.0.0.10
root@ZNA:~# ifconfig eth0:1 10.0.0.20
root@ZNA:~# ifconfig
eth0 Link encap:Ethernet HWaddr 00:0C:29:A0:A5:80
inet addr:192.168.1.33 Bcast:192.168.1.255 Mask:255.255.255.0
inet6 addr: fe80::20c:29ff:fea0:a580/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:3035 errors:0 dropped:0 overruns:0 frame:0
TX packets:199 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:240695 (235.0 KiB) TX bytes:19035 (18.5 KiB)
Interrupt:18 Base address:0x1400
eth0:0 Link encap:Ethernet HWaddr 00:0C:29:A0:A5:80
inet addr:10.0.0.10 Bcast:10.255.255.255 Mask:255.0.0.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
Interrupt:18 Base address:0x1400
eth0:1 Link encap:Ethernet HWaddr 00:0C:29:A0:A5:80
inet addr:10.0.0.20 Bcast:10.255.255.255 Mask:255.0.0.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
Interrupt:18 Base address:0x1400
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:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 b) TX bytes:0 (0.0 b)

EXERCISE 11-1: MANAGING IP ADDRESSES

In this exercise you’ll learn how to manage IP addresses. You’ll work with the ip command and also will see why you shouldn’t use the ifconfig command anymore.

1. Open a root shell on your machine. If you’re working on Ubuntu, you can do so by using the sudo su command.

2. Type ip addr show. Look up the name of the network card in your machine. In the remainder of this exercise I’ll assume it is eth0, make sure to replace that name with the name that is used in your configuration.

3. Type ip link show to show link statistics for your network card.

4. Type ip addr add dev eth0 10.11.12.13/24 to add a secondary IP address.

5. Use ping 10.11.12.13 to verify that this IP address is operational.

6. Type ifconfig. You won’t see the secondary IP address that you have assigned. This is why you should not use ifconfig anymore.

Storing Address Configuration

When your computer boots, it normally loads its IP address configuration automatically. In the next sections you’ll read how this works on the most important Linux distributions.

Storing IP Address Configuration on Ubuntu

When your computer boots, it starts the networking script from /etc/init.d. The script reads the configuration that is stored in the /etc/network directory or using the systemd script if you’re on a newer version, paying particular attention to the /etc/network/interfacesfile. This configuration file stores the entire configuration of the network board. Listing 11-6 shows an example configuration for a computer that has two Ethernet network cards.

Listing 11-6. Example Contents of the interfaces File on Ubuntu

root@ZNA:~# cat /etc/network/interfaces
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).
# The loopback network interface
auto lo
iface lo inet loopback

# The primary network interface
auto eth0
iface eth0 inet static
address 192.168.1.33
netmask 255.255.255.0
network 192.168.1.0
broadcast 192.168.1.255
gateway 192.168.1.254
# dns-* options are implemented by the resolvconf package, if installed
dns-nameservers 193.79.237.39
dns-search lan

#The second network board
auto eth1
iface eth1 inet static
address 10.0.0.10
netmask 255.255.255.0
network 10.0.0.0
broadcast 10.0.0.255

As you can see from the configuration file, the computer has activated three network interfaces. The first is lo, and this is the loopback interface. It’s required for many services to function, even if your computer has no network connection at all. For instance, the X server that takes care of the graphical display on your computer uses the loopback interface to handle internal communication. The loopback interface always uses the IP address 127.0.0.1.

In most cases, an Ethernet network card is used to connect with the rest of the world. This network card is represented by the name eth0 if it’s the first, and names like eth1 and so on for the next cards. The definition of each of the network boards starts with auto ethn, in which n is the number of the network interface. This line is used to start the network card automatically when your computer boots. You can omit this line, but if you do so, you’ll need to use the ifup or ifconfig commands as described earlier to start the network card by hand. In most situations you don’t want to do that, so make sure that the line that starts with auto is used at all times.

Following the auto line, there is a definition of the interface itself. In this example, a computer is configured with two static IP addresses. If you need DHCP on an interface, make sure the iface line reads iface ethn inet dynamic. Following that, there is the rest of the configuration for the network card. You’ll need address, netmask, network, and broadcast in all cases. The other options are optional.

Storing IP Address Configuration on Red Hat

On Red Hat, fixed IP address configuration is stored in the /etc/sysconfig/network-scripts/ ifcfg-ethn file. One file is created for each Ethernet interface. In Listing 11-7, you can see what this file looks like.

Listing 11-7. Network Configuration As Stored on Red Hat

[root@workstation ~]# cat /etc/sysconfig/network-scripts/ifcfg-eno16777736
TYPE="Ethernet"
BOOTPROTO="none"
DEFROUTE="yes"
IPV4_FAILURE_FATAL="no"
IPV6INIT="yes"
IPV6_AUTOCONF="yes"
IPV6_DEFROUTE="yes"
IPV6_FAILURE_FATAL="no"
NAME="eno16777736"
UUID="67ef89fc-cf5f-449b-b92d-7f980951eace"
ONBOOT="yes"
HWADDR="00:0C:29:25:D0:71"
IPADDR0="192.168.4.9"
PREFIX0="24"
GATEWAY0="192.168.4.2"
DNS1="8.8.8.8"
IPV6_PEERDNS="yes"
IPV6_PEERROUTES="yes"

In this example configuration file, you can see several parameters. You can change them as needed and deactivate and activate the device after applying the changes with ifdown ethn, followed by ifup ethn. The following parameters are in the ifcfg-ethn file:

· DEVICE: The device name. This should be the eth name of the hardware device.

· HWADDR: The MAC address of the device. Make sure that it is unique for all devices you are using.

· ONBOOT: Whether or not the device must be activated when your computer boots. You normally want to set this parameter to yes.

· SEARCH: The default DNS search domain. If an incomplete DNS name is used (e.g., ping linda), the default DNS search domain is appended.

· BOOTPROTO: The specific boot protocol used, if any. Set this to DHCP if you want the network card to obtain an IP address automatically from a DHCP server when activated.

· NETMASK: The netmask that you are using with the IP address on this interface.

· IPADDR: The IP address used by this interface.

· USERCTL: Whether or not an end user is allowed to activate and deactivate this interface.

· PEERDNS: DNS information for the peer in a point-to-point setup.

· IPV6INIT: Whether or not you want to initialize the IPv6 protocol.

· NMCONTROL: As an alternative to manual device configuration, you can configure a network device with the network manager application. This parameter tells your system whether this applet should be used.

· GATEWAY: The IP address of the default router that is needed to connect to computers on other networks.

· TYPE: The protocol used by this network card.

Storing IP Address Configuration on SUSE

On SUSE Linux, the network information is stored in more or less the same way as on Fedora. The name of the configuration file is /etc/sysconfig/network/ifcfg-nnn, in which nnn represents the MAC address the network card uses. Listing 11-8 shows what the SUSE configuration file looks like. In this listing, you can see that the contents of the file ifcfg-eth- id-00:0c:29:ae:e6:e5 is requested. In the file name, backslashes are used to make sure that the next character is not interpreted by the shell. You can change the SUSE configuration file by hand, or by using the YaST configuration tool.

Listing 11-8. Network Card Configuration As Stored on SUSE

nuuk:/etc/sysconfig/network # cat ifcfg-eth-id-00\:0c\:29\:ae\:e6\:e5
BOOTPROTO='dhcp'
BROADCAST=''
ETHTOOL_OPTIONS=''
IPADDR=''
MTU=''
NAME='AMD PCnet - Fast 79C971'
NETMASK='255.255.255.0'
NETWORK=''
REMOTE_IPADDR=''
STARTMODE='auto'
UNIQUE='rBUF.weGuQ9ywYPF'
USERCONTROL='no'
_nm_name='bus-pci-0000:02:00.0'

In the SUSE configuration file, multiple parameters are stored. A short explanation of each of them follows:

· BOOTPROTO: Indicates whether DHCP should be used or whether the interface has a static IP address assignment. Use either DHCP or STATIC.

· BROADCAST: Specifies the broadcast address of the network.

· ETHTOOL_OPTIONS: Specifies ethtool command arguments that will be interpreted by the ethtool utility. ethtool lets you set specific parameters, such as the link speed, duplex mode, or receive buffer size of your network card. You can read more about this utility in the section “Tuning the Network Card with ethtool” later in this chapter.

· IPADDR: Specifies which IP address is to be used.

· MTU: Specifies the maximum transmission unit. By default on Ethernet, it is 1500; set it to 9000 to enable jumbo frames, which are useful on links that work with large packets.

· NAME: Specifies a name for the interface. Enter a unique name here. * NETMASK: Indicates the netmask in dotted notation (255.255.255.0 and not /24).

· NETWORK: Allows you to specify the address of the network. This field is optional.

· REMOTE_IPADDR: Specifies the IP address of the remote node in a peer-to-peer connection.

· STARTMODE: Indicates whether this interface must be started automatically or manually.

· UNIQUE: Contains a unique ID that is used by the YaST management utility.

· USERCONTROL: Indicates whether or not an end user is allowed to stop and start this interface.

· _nm_name: Contains a reference to the hardware location of the NIC.

Configuring Routing

You’ve read about how a network interface is provided with an IP address. But, to be completely functional on the network, you have to specify some routes as well. These routes allow you to communicate with computers on other networks, and, conversely, they allow computers on other networks to communicate with your computer.

As a minimal requirement, you need a default route. This entry specifies where to send packets that don’t have a destination on the local network. The router used as the default route is always on the same network as your computer; just consider it to be the door that helps you get out of the local network. Your computer typically gets the information about the default router that it should use from the /etc/network/interfaces Ubuntu file, /etc/sysconfig/network-scripts/ifcfg-eth0 on Fedora, or /etc/sysconfig/network/routes on SUSE. To set the default route yourself, two tools can be used: the ip tool and the route utility. In the next two sections, you’ll read how to do this. The ip tool is the preferred utility to manage routes.

Managing the Default Route with route

The old command to set the default route is route. If no options are used, it will display a list of all routes that are currently defined on this host. Listing 11-9 provides an example. When using the route command without options, it will always try to resolve the name for a given IP address, which takes some time. If you don’t want any name resolution to be performed, use the option -n, which makes the command a lot faster.

Listing 11-9. Use the route Command to Get an Overview of All Routes That Are Currently Configured

root@ZNA:~# route
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface

localnet * 255.255.255.0 U 0 0 0 eth0
10.0.0.0 * 255.0.0.0 U 0 0 0 eth0
default 192.168.1.254 0.0.0.0 UG 0 0 0 eth0

In the output of the route command all information necessary for the routing process is provided, as you can see in Listing 11-9. The first column provides the destination, which is the network or host that a route is defined for. Typically, these are networks that your computer is connected to with its local interfaces and the default route. Next is the gateway, which is the router that needs to be contacted to reach the specified destination. An asterisk (*) in this field indicates that the local computer is the gateway for that destination. If an external router is used as the destination, you’ll see the IP address (or name) of that router. Next is the genmask, which is the subnet mask used on the specified destination. Then come the flags, metric, ref, and use columns, all of which reveal more detailed information about this route. Finally, the ifacecolumn reveals what network interface is used to route packets.

To specify a route, you need to provide a minimum of two pieces of information: the IP address or name of the network you want to add, and the IP address of the default gateway. All the other information is added automatically. For example, if you want to specify that the router with IP address 192.168.1.254 should be used as the default gateway, use the command route add default gw 192.168.1.254.

If you need to change the default gateway, you should be aware that you first have to remove the old entry for this default gateway. Use the route del command to do this. For example, to remove the current setting for the default gateway, use route del default gw.

Managing the Default Route with the ip Tool

If you know what information to enter when defining a route, it’s easy to do it with either the ifconfig or the ip tool. Only the syntax is different. To set the default gateway to 192.168.1.254 using the ip tool, use the ip route add default via 192.168.1.254 command. This command makes sure that all packets sent to nonlocal destinations are sent through 192.168.1.254. Likewise, you can delete the default route with ip route del default.

Storing Routing Information

To make sure that your computer still knows the default route after a reboot, you should store it somewhere. In the next three sections, you’ll read how to do this for the three main distributions.

Ubuntu

When you enter information, such as the default gateway, from the command line, it will be lost the next time you reboot your computer. To make sure that the information remains after a reboot, store it in the /etc/network/interfaces file on Ubuntu. This file is read every time the network is activated. The entry used in this file to store the default route isn’t complex:

gateway 192.168.1.254

If you have more than one network card in your computer, it is enough to specify the information about the default route once only.

Red Hat

On Red Hat also, you specify the address of the default route in the file that stores the configuration of your network interface. See Listing 11-7 earlier in this chapter for an example. If you have more than one network card in your computer, you do not need to enter this information in the configuration file of each network card.

Resolving DNS Names to IP Addresses

If you want to manually configure a network connection as the last part, you need to specify what DNS name server to use. The DNS Server makes sure that names that are used on your local network and the Internet can be translated to the IP addresses your computer needs to make a connection.

To store the DNS information, you use the so-called DNS resolver. This DNS resolver is stored in the /etc/resolv.conf file; there is no command-line utility to configure it. Typically, the /etc/resolv.conf file will contain the IP address of at least two DNS name servers and a search domain. The name server specifications indicate what DNS name computer should be contacted to translate DNS names to IP addresses and vice versa. Typically, your Internet provider will get you this information. Specify at least two name servers so that if the first one cannot be reached, the second one can do the job.

The search domain specifies what domain name should be appended if an incomplete host name is used. It makes sense to use the name of your default DNS domain as the search domain. So if you computer’s name is computer.example.com, set the search domain name to example.com.Listing 11-10 is an example of the content of the /etc/resolv.conf file.

Listing 11-10. Example of the /etc/resolv.conf File

nameserver 192.168.1.10
nameserver 193.79.237.39
search example.com

In this example, you see that name server 192.168.1.10 is used as the default name server, and all DNS requests will be sent to it. If this server cannot be reached, only then will the second server in the list (193.79.237.39) be contacted. The third line of the Listing 11-10 example specifies the search domain. For example, if a user uses the command ping ftp, which includes an incomplete host name, the name of the domain specified with the search option in resolv.conf is added automatically to it, so in this case the packet would be sent to ftp. example.com.

Notice that on none of the three major Linux distributions the /etc/resol.conf file should be edited directly. You’ll have to include the DNS server configuration in the network card configuration file (/etc/sysconfig/network-scripts/ifcfg-eth0 on Red Hat or /etc/network/interfaces on Ubuntu). From there, the DNS name server will be written to the /etc/resolv.conf file. Any modification you make manually to the /etc/resolv.conf file risks getting lost after a restart of the network service.

The Role of the /etc/nsswitch.conf File

Most people take it for granted that DNS resolves host names to IP addresses, but this isn’t necessarily so. Every Linux computer has the /etc/nsswitch.conf file that determines what exactly should happen when translating a host name to an IP address and vice versa. This file specifies many things (such as user configuration, which you read about in Chapter 6), but only the following lines are important for resolving host names:

hosts: files dns
networks: files

These two lines specify that, when resolving host names as well as network names, the (local) files should be searched first, and that the DNS subsystem should be used only if the files have no information about the given host. Thus, an administrator can make sure that frequently accessed host names are resolved locally, where the DNS is contacted only when the files don’t have information about a particular host. The most important file used for resolving names to IP addresses is the /etc/hosts file, which is the file referred to by files on the hosts line in/etc/nsswitch.conf.

Using the /etc/hosts File

One of the oldest ways to resolve host names to IP addresses (and vice versa) is to use the /etc/hosts file. It’s rather primitive because you have to maintain the file on every single computer where you need it, and no synchronization of entries in this file is established between computers. But it’s also a very efficient way to supply information that needs to be available locally.

Image Note To resolve the problem of decentralized management, the Network Information Service (NIS, formerly known as Yellow Pages) was invented by Sun Microsystems. Nowadays, it’s hardly ever used anymore, because most companies keep their hosts-related information in DNS.

Using the /etc/hosts file makes resolving names faster and reduces Internet traffic, and you can use it to add any host names that need to be available only locally. Listing 11-11 shows example contents of this file.

Listing 11-11. Example of the /etc/hosts File

[root@workstation ~]# cat /etc/hosts
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.4.9 workstation workstation.example.com
192.168.4.10 server1 server1.example.com
192.168.4.20 server2 server2.example.com

As you can see, the contents of this file is rather simple. First, you specify the IP address of the host, which can be an IPv4 or an IPv6 address. Next, the fully qualified host name of the host is specified. This is the name of the host itself followed by its DNS suffix. Last, the short host name is used. Alternatively, you can just provide the IP address followed by the name of the host you want to add, such as in the following line:

192.168.1.180 RNA

On a modern Linux computer, it’s often not necessary to set up /etc/hosts except for local name resolving. Network name resolving is typically managed in DNS. So you’ll always need your own host name and IP address in this file. This is configured automatically when installing your computer.

Tuning the Network Card with ethtool

At this point you know how to configure IP-related parameters. The network card itself also has settings that you may need to modify, and you’ll use the ethtool command to do this. With this utility, you can change network board properties like link speed and duplex mode. Don’t overestimate this tool though. Some Ethernet cards are not supported, and the only way to change settings on those may be through the network board’s BIOS settings. Let’s start by displaying some information: issue ethtool -i eth0 to see an overview of driver properties that are currently used, as shown in Listing 11-12.

Listing 11-12. The ethtool -i Command Provides an Overview of Driver Properties

[root@lab ~]# ethtool -i eno1
driver: e1000e
version: 2.3.2-k
firmware-version: 0.6-4
bus-info: 0000:00:19.0
supports-statistics: yes
supports-test: yes
supports-eeprom-access: yes
supports-register-dump: yes
supports-priv-flags: no

To change duplex settings and link speed on your network board, you’ll use the -s option, followed by one of these arguments:

· speed: This option changes the speed. Valid options are 10, 100, and 1000.

· duplex: This option changes the duplex settings. Set it to half or full.

· port: This specifies what port to use. This option is used for network interfaces with different ports available (which is not very common). Valid choices are tp, aui, bnc, mii, and fibre.

· autoneg: This option indicates whether you want to use autonegotiation to discover the settings that are used on the network.

So, for example, if you want to change the settings of your network card to full duplex and a link speed of 1000 Mbps, use ethtool -s eth0 speed 1000 duplex full. Now there is a problem when using ethtool like this: you need to enter these settings again the next time you start your computer. Only SUSE offers a solution for this problem; on SUSE you can store the ethtool configuration parameters in the configuration file for your network card. You have seen this in Listing 11-8. On other distributions that don’t offer such a solution, you can include the ethtool command with all the parameters you need in the /etc/ init.d/boot.local script. Doing this, you’ll make sure that ethtool settings are applied after a reboot as well.

In addition to the -i option with ethtool, which gives you a brief summary about your network board, are some other useful options. For instance, you can get some very detailed statistics about your network board when using ethtool -S as you can see in Listing 11-13.

Listing 11-13. ethtool -S Gives You Very Detailed Statistics About Your Network Card

[root@lab ~]# ethtool -S eno1
NIC statistics:
rx_packets: 4423965
tx_packets: 5086934
rx_bytes: 2789043235
tx_bytes: 4708139801
rx_broadcast: 81778
tx_broadcast: 4
rx_multicast: 5044
tx_multicast: 64
rx_errors: 0
tx_errors: 0
tx_dropped: 0
multicast: 5044
collisions: 0
rx_length_errors: 0
rx_over_errors: 0
rx_crc_errors: 0
rx_frame_errors: 0
rx_no_buffer_count: 0
rx_missed_errors: 0
tx_aborted_errors: 0
tx_carrier_errors: 0
tx_fifo_errors: 0
tx_heartbeat_errors: 0
tx_window_errors: 0
tx_abort_late_coll: 0
tx_deferred_ok: 0
tx_single_coll_ok: 0
tx_multi_coll_ok: 0
tx_timeout_count: 0
tx_restart_queue: 0
rx_long_length_errors: 0
rx_short_length_errors: 0
rx_align_errors: 0
tx_tcp_seg_good: 718842
tx_tcp_seg_failed: 0
rx_flow_control_xon: 0
rx_flow_control_xoff: 0
tx_flow_control_xon: 0
tx_flow_control_xoff: 0
rx_csum_offload_good: 4325815
rx_csum_offload_errors: 3
rx_header_split: 0
alloc_rx_buff_failed: 0
tx_smbus: 0
rx_smbus: 0
dropped_smbus: 0
rx_dma_failed: 0
tx_dma_failed: 0
rx_hwtstamp_cleared: 0
uncorr_ecc_errors: 0
corr_ecc_errors: 0
tx_hwtstamp_timeouts: 0

Analyzing Network Connections

Once you have finished the setup tasks I’ve just described, you should have a working network connection. But, even if it’s working fine right now, you may at some point need to perform some tuning and troubleshooting, and that’s exactly what this section is about. Here, you’ll learn how to test that everything is working the way it should and how to monitor what is happening on the network itself, as well as on the network interface. The tools I’m talking about in this section are the top-notch troubleshooting tools.

Testing Connectivity

After configuring a network card, you want to make sure it’s working correctly. For this, the ping command is your friend, and more so because it’s easy to use: enter the command followed by the name or address of the host you want to test connectivity to, such as pingwww.ubuntu.com. This forces ping to start continuous output, which you can interrupt by using the Ctrl+C key sequence. You can also send a limited number of packets; for example, the command ping -c 3 192.168.1.254 sends just three packets to the specified host. If you use ping in a clever way, you can test a lot of things with it. I recommend using it in the following order:

1. Ping the localhost. If you pass this test, you’ve verified that the IP stack on your local machine is working properly.

2. Ping a machine on the local network by using its IP address: if this works, you’ve verified that IP is properly bound to the network board of your computer and that it can make a connection to other nodes on the network. If it fails, you need to check the information you’ve entered with the ifconfig or ip commands; you may have made an error entering the subnet mask for your network interface.

3. Ping a machine on the Internet using its IP address. A good bet is 8.8.8.8, which is a DNS server that hasn’t failed me in the last 15 years. Of course, you can use any other host as long as you know its IP address. If the ping is successful, you’ve verified that the routers between the localhost and the destination are all working. If it fails, there’s an error somewhere in the routing chain. Check route -n or ip route show on your localhost to see if the default route is defined.

4. Ping a machine on the Internet using its DNS name. If this succeeds, everything is working. If this step fails (but test 3 was successful), make sure you’ve entered the name of the DNS server that should be used in /etc/resolv.conf. If this is okay, check to see whether your DNS server is working.

In many cases, you’ll use the ping command without options. But some options can be useful, and these are listed in Table 11-2.

Table 11-2. Useful ping Options

Option

Description

-c count

Specifies the number of packets to be sent. The ping command terminates automatically after reaching this number.

-l device

Specifies the name of the network device that should be used. Useful on a computer with several network devices.

-i seconds

Specifies the number of seconds to wait between individual ping packets. The default setting is 1 second.

-f

Sends packets as fast as possible, but only after a reply comes in.

-l

Sends packets without waiting for a reply. If used with the -f option, this may cause a denial-of-service attack on the target host, and the host may stop functioning properly or even crash. Apart from the unknown harm that this may do to the target computer, you may find yourself blacklisted or even charged with a criminal offense. Because this is such a very dangerous option, only the user root is allowed to use it.

-t ttl

Sets the time to live (TTL) for packets that are sent. This indicates the maximum number of routers that each packet may pass through on its way to a destination. The TTL is decremented by one by each router it passes until the TTL becomes 0, which means that the packet won’t be routed any more.

-b

Sends packets to the broadcast address of the network. This prompts a reply from every host that’s up and allowed to answer to ping packets. Don’t use this unless you have a very good reason to use it, as this command generates large numbers of packets on your network.

Image Note To protect against a denial-of-service attack, many hosts are configured not to answer a ping request. Therefore, when testing connectivity, make sure that you use a host that’s allowed to answer.

The ping command is not just used to test that a connection can be established; you can also use it to check the round-trip delay between your computer and a given host. The elapsed time is an important indication of the quality of the network connection. To check the round-trip delay, have a look at the time parameter that’s listed in the result of the ping command. Listing 11-14 provides an example in which ping is used to send four packets to www.ubuntu.com.

Listing 11-14. Testing Connectivity to www.ubuntu.com

root@ZNA:~# ping -c 4 www.ubuntu.com
PING www.ubuntu.com (82.211.81.158) 56(84) bytes of data.
64 bytes from arctowski.ubuntu.com (82.211.81.158): icmp_seq=1 ttl=51 time=22.0 ms
64 bytes from arctowski.ubuntu.com (82.211.81.158): icmp_seq=2 ttl=51 time=10.7 ms
64 bytes from arctowski.ubuntu.com (82.211.81.158): icmp_seq=3 ttl=51 time=18.6 ms
64 bytes from arctowski.ubuntu.com (82.211.81.158): icmp_seq=4 ttl=51 time=20.8 ms

--- www.ubuntu.com ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3015ms
rtt min/avg/max/mdev = 10.741/18.092/22.057/4.417 ms

Testing Routing

If you can ping your default router but you can’t ping a given host on the Internet, it’s probably obvious that something is wrong with one of the routers between your network and the destination host. You can use the traceroute command to find out exactly where things are going wrong. The traceroute command uses the TTL value of the UDP datagrams it sends out.

Image Note A datagram is a packet sent over the OSI model network layer.

The idea is that, when the TTL value reaches 0, the packet is discarded by the router, and a message is sent back to the sender. When starting, traceroute uses a TTL value of 0, which causes the packet to be discarded by the very first router. This is how traceroute identifies the first router. Next, it sends the packet to the target destination again, but with a TTL of 1, which, as you can see, causes the packet to be discarded by the second router. Things continue in this manner until the packet reaches its final destination.

To use traceroute, you normally put the host name as the argument, such as traceroute www.ubuntu.com. It’s possible as well to use the IP address of a host, which will produce a result as shown in Listing 11-15.

Listing 11-15. Testing a Network’s Route with traceroute

root@ZNA:~# traceroute www.ubuntu.com
traceroute to www.ubuntu.com (82.211.81.158), 30 hops max, 40 byte packets
1 192.168.1.254 (192.168.1.254) 72.668 ms 10.361 ms 176.306 ms
2 195.190.249.90 (195.190.249.90) 3.353 ms 9.199 ms 10.351 ms
3 42.ge-4-0-0.xr1.3d12.xs4all.net (194.109.5.49) 6.386 ms 7.237 ms 16.421 ms
4 0.so-6-0-0.xr1.tc2.xs4all.net (194.109.5.10) 11.407 ms 11.447 ms 9.599 ms
5 217.149.46.21 (217.149.46.21) 31.989 ms 29.321 ms 22.756 ms
6 sl-bb21-ams-11-0.sprintlink.net (217.149.32.41) 13.415 ms 13.244 ms 12.569 ms
7 213.206.131.46 (213.206.131.46) 11.147 ms 12.282 ms 11.222 ms
8 ae-0-56.mp2.Amsterdam1.Level3.net (4.68.120.162) 7.862 ms ae-0-54.mp2.Amster\
dam1.Level3.net (4.68.120.98) 11.796 ms ae-0-52.mp2.Amsterdam1.Level3.net\
(4.68.120.34) 11.000 ms
9 as-0-0.bbr2.London2.Level3.net (4.68.128.110) 21.047 ms ae-1-0.bbr1.London2.\
Level3.net (212.187.128.46) 35.125 ms as-0-0.bbr2.London2.Level3.net\
(4.68.128.110) 17.183 ms
10 ae-15-53.car1.London2.Level3.net (4.68.117.79) 18.917 ms 17.388 ms ae-25-52.\
car1.London2.Level3.net (4.68.117.47) 18.992 ms
11 tge9-3-146.core-r-1.lon2.\
mnet.net.uk (212.187.196.82) 14.699 ms 17.381 ms 15.293 ms
12 85.133.32.134 (85.133.32.134) 27.130 ms 33.310 ms 37.576 ms
13 82.211.81.76 (82.211.81.76) 16.784 ms 20.140 ms 17.556 ms
14 * * *
15 * * *
16 * * *
17 * * *

With the traceroute command, you’ll see every router that’s passed. For each router, the name of the router is displayed, followed by its IP address and then the round-trip times of the three packets that were sent to that router. You’ll often see that a router replies with only a string of three asterisks (* * *), which indicates that the router forwards packets normally but is configured not to reply to ping packets for security reasons.

Testing Availability of Services

When the ping and traceroute commands show that everything is working, you’re the proud owner of a working network interface. Next you can test the availability of two kinds of services: those on your computer itself and those on external computers. Because so many tools are available to test service availability, I won’t try to cover them all, but I do want to discuss two of the most popular. First is the netstat tool, which you can use to test for the availability of services on the host where you run the command. And second is nmap, which is used to test availability on other hosts.

Image Caution Some administrators consider any use of nmap on their hosts or their network as an attack against their security, and therefore won’t allow it. I once used it in a hotel room in the United States to see if my server in Amsterdam was still offering all its services, and the hotel network shut me off immediately. In these circumstances, it can be a real pain to get your connection back, so be careful.

Using netstat for Services on Your Computer

If you want to know what services are available on your computer and what these services are doing, the netstat command is an excellent choice. However, because many of its options require you to be root, I recommend that you use netstat as root only. To see the most useful information offered by netstat, use the -platune options, which make sure that you see information about programs connected to ports (-p) and what ports are actually listening (-l).

Other options show you everything there is to show (-a), do that for TCP (-t) as well as UDP (-u), without translating IP addresses to DNS names (-n), or with extended information (-e).

If you think that netstat -platune offers too much information, use netstat -tulp instead. The results are slightly less verbose, which makes it easier to get the data you really need. Listing 11-16 shows the first screen of output generated by netstat -platune.

Listing 11-16. The netstat -platune Command Provides an Exhaustive Overview of Everything Happening on Your Computer

root@ZNA:~# netstat -platune
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State User\ Inode PID/Program name
tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN 103\ 12937 3839/mysqld

tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 0\ 13209 3965/apache2

tcp 0 0 10.0.0.20:53 0.0.0.0:* LISTEN 104\ 13737 3737/named

tcp 0 0 10.0.0.30:53 0.0.0.0:* LISTEN 104\ 13735 3737/named

tcp 0 0 10.0.0.10:53 0.0.0.0:* LISTEN 104\ 13733 3737/named

tcp 0 0 192.168.1.33:53 0.0.0.0:* LISTEN 104\ 12821 3737/named

tcp 0 0 127.0.0.1:53 0.0.0.0:* LISTEN 104\ 12819 3737/named

tcp 0 0 127.0.0.1:953 0.0.0.0:* LISTEN 104\ 12824 3737/named

tcp6 0 0 :::53 :::* LISTEN\ 104 12816 3737/named

tcp6 0 0 :::22 :::* LISTEN\ 0 13585 4150/sshd

tcp6 0 0 ::1:953 :::* LISTEN\ 104 12825 3737/named

tcp6 0 0 ::ffff:192.168.1.33:22 ::ffff:192.168.1.6:4197 ESTABLISHED0\ 13761 4229/1

tcp6 0 164 ::ffff:192.168.1.33:22 ::ffff:192.168.1.7:9688 ESTABLISHED0\ 13609 4158/0

udp 0 0 0.0.0.0:1024 0.0.0.0:* 104\ 12822 3737/named

udp 0 0 10.0.0.20:53 0.0.0.0:* 104\ 13736 3737/named

udp 0 0 10.0.0.30:53 0.0.0.0:* 104\ 13734 3737/named

udp 0 0 10.0.0.10:53 0.0.0.0:* 104\ 13732 3737/named

udp 0 0 192.168.1.33:53 0.0.0.0:* 104\ 12820 3737/named

udp 0 0 127.0.0.1:53 0.0.0.0:* 104\ 12818 3737/named

udp6 0 0 :::1025 :::* 104\ 12823 3737/named

udp6 0 0 :::53 :::* 104\ 12815 3737/named

As you can see, the netstat command yields a lot of information when used with the -platune options. Table 11-3 explains the information displayed in Listing 11-16.

Table 11-3. Information Offered by netstat -platune

Item

Explanation

Proto

The protocol that’s used. Can be TCP or UDP.

Recv-Q

The number of packets waiting in the receive queue for this port at the moment that netstat was used.

Send-Q

The number of packets waiting to be sent from this port at the moment that netstat was used.

Local Address

The local socket address (the local IP address followed by the port number that’s used).

Foreign Address

The address of the foreign host (if any) that currently has an open connection to this host.

State

The current state of the protocol connected to the mentioned port.

User

The numeric user ID of the user with whose permissions the process was started.

Inode

The inode(s) of files that currently are opened by the process.

PID/Program name

The PID and name of the program that has currently claimed the mentioned port.

As you can see, netstat provides a complete overview of what’s happening on your computer. It’s especially useful if you get error messages like “port already in use.” In combination with the grep utility, it’s easy to learn what port program is currently holding a port open and, if required, to terminate that program. For example, to find out what program is currently occupying port 80, use netstat -platune | grep 80. This returns a line like

root@ZNA:~# netstat -platune | grep 80

tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 0\
13209 3965/apache2

From this line, you can see that an Apache web server with a PID of 3965 is currently listening on port 80. Want to remove it and you don’t know how to do that in a normal way? Use kill 3965 and it’s gone.

Using nmap to Check Services on remote Computers

The netstat command is a useful tool, but it works only on the host where you run it. Sometimes, when you cannot connect to a given service on a given host, you’d like to know if the service is available at all. You can do this with the nmap command. Like most powerful network tools,nmap also works best if you are root.

The nmap command is an expert tool that helps you find out exactly what’s happening at another host. If you use it properly, the owner of that host will never even know that you were there. However, you should be aware that running a so-called port scan to monitor open ports on a given host is considered an intrusion by many administrators, so be careful what you’re doing with it because you may run into trouble if you use nmap on a host that isn’t yours, and you haven’t notified its owner.

If you really want to keep things simple, just use nmap without arguments. For example, nmap 192.168.1.69 performs a basic scan on host 192.168.1.69 to find what common ports are open on it. This gives good results for day-to-day use; see Listing 11-17 for an example.

Listing 11-17. The nmap Command Shows You What Services Are Offered by a Host

root@ZNA:~# nmap 192.168.1.69

Starting Nmap 4.20 ( http://insecure.org ) at 2007-011-01 11:08 EDT
Interesting ports on 192.168.1.69:
Not shown: 1693 closed ports
PORT STATE SERVICE
22/tcp open ssh
111/tcp open rpcbind
139/tcp open netbios-ssn
445/tcp open microsoft-ds
MAC Address: 00:18:8B:AC:C9:54 (Dell)
Nmap finished: 1 IP address (1 host up) scanned in 0.626 seconds

A very common reason why the test shown in Listing 11-17 could fail is that nmap normally tries to ping its targets first. On many hosts, ping commands are administratively prohibited, dropped, or ignored. And these hosts won’t reveal anything when you issue nmap on them. To make sure that they’re working even when you cannot ping, use the -P0 option to disable ping. Another useful option is -O, which tries to guess the operating system that is on the target host. And, if you want to make sure that both TCP and UDP ports are scanned, you should include -sT and -sU as well. So the command becomes somewhat longer: nmap -sT -sU -P0 -O 192.168.1.69 would scan the target host with all those options. You’ll notice that, because nmap has to do a lot more work with these options, it takes considerably longer for the command to complete. Listing 11-18 shows the result of this scan.

Listing 11-18. You Have Lots of Options to Specify How nmap Should Do Its Work

root@ZNA:~# nmap -sT -sU -P0 -O 192.168.1.69

Starting Nmap 4.20 ( http://insecure.org ) at 2007-011-01 11:11 EDT
Interesting ports on 192.168.1.69:
Not shown: 3176 closed ports
PORT STATE SERVICE
22/tcp open ssh
111/tcp open rpcbind
139/tcp open netbios-ssn
445/tcp open microsoft-ds
68/udp open|filtered dhcpc
111/udp open|filtered rpcbind
631/udp open|filtered unknown
5353/udp open|filtered zeroconf
32768/udp open|filtered omad
MAC Address: 00:18:8B:AC:C9:54 (Dell)
Device type: general purpose
Running: Linux 2.6.X
OS details: Linux 2.6.14 - 2.6.17
Uptime: 0.176 days (since Wed Aug 1 07:23:05 2007)
Network Distance: 1 hop

OS detection performed. Please report any incorrect results at http://insecure.org/nmap/submit/.
Nmap finished: 1 IP address (1 host up) scanned in 1482.860 seconds

In the last command, you’ll most likely get a better result, but there’s still a problem: the scan is rather noisy, and so the target host may log messages to tell its owner that you’re using nmap on it. There’s nothing wrong with this in most cases, but if you really want to put nmap through a thorough security test, you should use some stealth options like -sF (FINscan), -sX (X-mas tree scan), or -sN (NULL-scan). All of these use specific properties of the IP protocol to perform a stealth scan so that the target host never knows you were there. The disadvantage of these scan options is that they don’t always work! On many modern operating systems, you’ll find that the operating system ignores them, so you’ll end up waiting a long time without a result.

EXERCISE 11-2: ANALYZING NETWORKING

In this exercise you’ll analyze the current configuration of network in your network.

1. Type ip route show. This will show you the IP address of your router.

2. Ping the router, using ping <router>. (Replace <router> with the IP address you’ve just found.

3. Note the network address of your current configuration. Normally, the network address is the same as your IP address, but with a 0 in the last byte. So if your IP address is 192.168.1.10, the network address is 192.168.1.0. In this example I’ll use 192.168.1.0 as the example network, replace this IP so that it matches your configuration. Use nmap -sP 192.168.1.0/24 to scan your network for IP addresses.

4. Type nmap <router> (replace <router> with the IP address of your router. This shows all services that are currently being offered on your router.

5. Type netstat -tulpen. This gives a list of all services that are being offered on your local machine.

Connecting Remotely with Secure Shell

If you’re in a network with multiple Linux computers, you’ll occasionally need to make a shell connection to another computer. Secure Shell is just made for that. It also replaces the older telnet utility, which was used in the days that security was not the issue it is today. The essence of SSH is its security, and public and private keys naturally play an important role in it. On first making contact, the client and the host exchange public and private keys. In this communication, the host creates a key based on its private key—the so-called host key—and uses this as its proof of identity. When connecting, the host sends its public key to the client. If this is the first time the client has connected to this host, the host replies with the message that shown in Listing 11-19.

Listing 11-19. Establishing an SSH Session with an Unknown Host

root@ZNA:~# ssh 192.168.1.70
The authenticity of host '192.168.1.70 (192.168.1.70)' can’t be established.
RSA key fingerprint is fd:07:f6:ce:5d:df:6f:a2:84:38:c7:89:f1:3a:a6:34.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.1.70' (RSA) to the list of known hosts.
Password:
Last login: Tue Jul 31 15:34:15 2007 from ida.lan

If the client trusts that this is really the intended host, it should answer yes to the request, in which case the host is then added to the .ssh/known_hosts file in the home directory of the user who initiated the SSH session. The next time the client connects to the host, this file is checked to see whether the host is already known. The check is based on the public key fingerprint of the host, which is a unique checksum related to the public key of the host. The connection is established only if this check matches the name and public key of the host that the client is connecting to. If these two pieces of data don’t match, it’s very likely that the host the client is trying to connect to isn’t the intended host, and the connection is refused.

Once the identity of the host you want to connect to is established, a secured channel is set up between the client and host. These secured channels are established by a session key, which is an encryption key that’s the same on both the host and the client and that encrypts all data sent between the two machines. The client and the host negotiate this session key based on their public keys. One of the things determined in this negotiation is the protocol that should be used. For example, session keys can use different encryption protocols like 3DES, Blowfish, or IDEA.

After establishing the secured channel, the user on the client is asked for credentials: if nothing is configured, a prompt asks the user to enter his or her username and password. Alternatively, the user can authenticate with his or her public/private key pair, thus proving he or she really is that user, but some more things have to be configured before that can happen.

All this may sound pretty complicated, but the nice thing is that the user doesn’t notice any of it. The user just has to enter a username and a password. If, however, you want to move beyond simple password-based authentication, it’s necessary to understand what’s happening.

Working with Public/Private Key Pairs

The security of SSH relies on the use of public/private key pairs. By default, the client tries to authenticate using RSA or DSA key pairs. To make this work, the host must have the client’s public key, which is something that you have to configure by hand, as you’ll see later. When the client has a public/private key pair, it generates an encrypted string with its private key. If the host is able to decrypt this string using the client’s public key, the client’s identity is authenticated.

When using public/private key pairs, you can configure different things. First, the user needs to determine what cryptographic algorithm he or she wants to use. For this purpose, he or she can choose between RSA and DSA (of which DSA is considered stronger). Next, the user has to decide whether to protect his or her private key with a passphrase.

Using a passphrase is important because the private key really is used as the identity of the user. Should anyone steal this private key, it would be possible to forge the identity of the key’s owner, and, for that reason, it’s a very good idea to secure private keys with a passphrase.

Working with Secure Shell

Basically, Secure Shell is a suite of tools that consists of three main programs and a daemon, sshd. On Fedora/Red Hat and SUSE, SSH is installed by default. On Ubuntu, you’ll need to install it first, using apt-get install openssh-server.

In SSH, three tools are available: ssh, scp, and sftp. The first, ssh, is used to establish a secured remote session. Let’s say that it’s like telnet but cryptographically secured. The second, scp, is a very useful command that’s used to copy files to and from another computer where the SSH process is running. The third, sftp, is a secure FTP client interface. Using it establishes a secured FTP session to a computer that’s running the sshd.

Two of the best things of all of these tools are that they can be used without any preparation or setup, and you can set them up to work entirely according to your needs. They are at once easy-to-use and very specialized tools.

Using the ssh Command

The simplest way to work with SSH is to just enter the ssh command, followed by the name of the host you want to connect to. For example, to connect to the host AMS.sandervanvugt.com, use ssh AMS.sandervanvugt.com.

Depending on whether you’ve connected to that host before, it may check the host credentials or just ask for your password. The ssh command doesn’t ask for a username because it assumes that you want to connect to the other host with the same identity that you’re logged in with locally. If you’d rather log in with another user account, you can indicate this intention in one of two ways: you can specify the username and follow it with an ampersand when establishing the connection to the remote host, or you can use the -l option followed by the name of the user account you want to use to connect to the other host. So, basically, ssh linda@AMS.sandervanvugt.com and ssh -l linda AMS.sandervanvugt.com accomplish the same thing. After establishing a session, use the exit command (or Ctrl+D) to close the session and return to your own machine.

Now, it seems a lot of trouble to log in to a remote host if you just need to enter one or two commands. If you face this situation often, it’s good to know that you can just specify the name of the command at the end of the ssh command: ssh -l linda@AMS.sandervanvugt.comls -l provides a long listing of files that user linda has in her home directory at the other host. Of course, this isn’t the most realistic example of how to use “one command only” sessions to a host, but you probably can see its value when working from shell scripts.

Using scp to Copy Files Securely

The scp command is another part of the SSH suite that you’ll definitely like. It’s used to copy files securely. If you know how the cp command works, you’ll know how to handle scp. The only difference is that it requires a complete network path name including the names of the host and the file you want to copy. Also, if you don’t want to use the name of the user you are currently logged in as, a username should be included as well. Consider the following example:

scp /some/file linda@AMS.sandervanvugt.com:/some/file

This easy command copies /some/file to AMS.sandervanvugt.com and places it with the name file in the directory /some on that host. Of course, it’s possible to do the opposite as well: scp root@SFO.sandervanvugt.com:/some/file /some/file copies/some/file from a remote host with the name SFO.sandervanvugt.com to the localhost. You’re going to like the -r option as well, because it allows you to copy a complete subdirectory structure.

Using sftp for Secured Ftp Sessions

As an alternative to copying files with scp, you can use the sftp command. This command is used to connect to computers running the sshd program and to establish a secured FTP session with it. From the sftp command, you have an interface that really looks a lot like the normal FTP client interface. All the standard FTP commands work here as well, with the only difference that, in this case, it’s secure. For example, you can use the ls and cd commands to browse to a directory and see what files are available and, from there, use the get command to copy a file to the current local directory. Once you’ve opened the sftp interface, you can use the following FTP commands to copy files to and from your computer:

· put: Copies a file from your computer to another computer

· mput: Copies multiple files from your computer to another computer

· get: Copies a file from another computer to your computer

· mget: Copies multiple files from another computer to your computer

Before establishing an FTP session to another computer, use the cd command on your local computer to change to the directory you want to copy files to or from. Your home directory might be a decent location. When using put, mput, get, and mget to transfer files, this directory is used as the default local directory. To establish an sftp session to the computer named nuuk, you would first use the following command:

sftp nuuk

This command assumes that you want to connect to the remote host using the same user account. If you want to connect with another user account, put it in front of the name of the remote server, as in the following command:

sftp sander@nuuk

You’ll now see an SFTP prompt and will be in the root directory that was provided for the user on the remote host. Here, you can use standard Linux commands such as ls to show a list of files, pwd to print your working directory, and cd to change to another directory. You can now transfer files between your computer and the remote computer. For instance, the following command would use sftp to copy the /etc/hosts file to the current directory on your local computer:

get /etc/hosts

When finished copying files, use the quit or the exit command to terminate the sftp session.

Configuring SSH

In an SSH environment, a node can be client and server simultaneously. This means that your computer can provide SSH services to others, and use SSH to connect to others at the same time. So, as you can imagine, there’s a configuration file for both of these aspects. The client is configured in /etc/ssh/ssh_config, and the host uses /etc/ssh/sshd_config. Setting options for the host isn’t hard to understand: just put them in the configuration file for the daemon /etc/ssh/sshd_config. For the client settings, however, the situation is more complicated, because there are several ways of overwriting the default client settings:

· The generic /etc/ssh/ssh_config file is applied to all users initiating an SSH session. An individual user can overwrite these if he or she creates a .ssh_config file in the .ssh directory of his or her home directory.

· An option in /etc/ssh/ssh_config has to be supported by the sshd_config file on the host you are connecting to. For example, if you’re allowing password-based authentication from the client side but the computer doesn’t allow it, it won’t work.

· Options in both files can be overwritten with command-line options.

Table 11-4 is an overview of some of the most useful options that you can use to configure the client in ssh_config.

Table 11-4. Useful Options in ssh_config

Option

Description

Host

This option restricts the following declarations (up to the next Host keyword) to a specific host. Therefore, this option is applied on a host that a user is connecting to. The host name is taken as specified on the command line. Use this parameter to add some extra security to specific hosts. You can also use wildcards such as * and ? to refer to more than one host name.

CheckHostIP

If this option is set to yes (the default value), SSH will check the host IP address in the known_hosts file. Use this as a protection against DNS or IP address spoofing.

Ciphers

This option, which takes multiple arguments, is used to specify the order in which the different encryption algorithms should be tried to use in an SSHv2 session (version 2 is the default SSH version nowadays).

Compression

The yes/no values for this option specify whether to use compression in your SSH session. The default is no.

ForwardX11

This very useful option specifies whether X11 connections will be forwarded. If set to yes, graphical screens from an SSH session can be forwarded through a secure tunnel. The result is that the DISPLAY environment variable that determines where to draw graphical screens is set correctly. If you don’t want to enable X forwarding by default, use the -X option on the command line when establishing an SSH session.

LocalForward

This option specifies that a TCP/IP port on the local machine is forwarded over SSH to the specified port on a remote machine. (See “Generic TCP Port Forwarding” later in this chapter for more details.)

LogLevel

Use this option to specify the level of verbosity for log messages. The default value is INFO. If this doesn’t go deep enough, VERBOSE, DEBUG, DEBUG1, DEBUG2, and DEBUG3 provide progressively more information.

PasswordAuthentication

Use this option to specify whether or not you want to use password authentication. By default, password authentication is used. In a secure environment in which keys are used for authentication, you can safely set this option to no to disable password authentication completely.

Protocol

This option specifies the protocol version that SSH should use. The default value is set to 2,1 (which indicates that version 2 should be used first and, if that doesn’t work, version 1 is tried). It’s a good idea to disable version 1 completely because it has some known security issues.

PubkeyAuthentication

Use this option to specify whether you want to use public key–based authentication. This option should always be set to the default value (yes) because public key–base authentication is the safest way of authenticating.

The counterpart of ssh_config on the client computer is the sshd_config file on the host. Many options that you can use in the ssh_config file are also available in the sshd_config file. However, some options are specific to the host side of SSH. Table 11-5 gives an overview of some of these options.

Table 11-5. Important Options in sshd_config

Option

Description

AllowTcpForwarding

Use this option to specify whether you want to allow clients to do TCP port forwarding. This is a very useful feature, and you’ll probably want to leave it at its default value (yes).

Port

Use this option to specify the port that the SSH process is listening on. By default, sshd is listening on port 22. If the SSH process is connected directly to the Internet, this will cause many people to try a brute-force attack on your host. Consider running the SSH process on some other port for increased security.

PermitRootLogin

Use this option to specify whether you want to allow root logins. To add additional security to your host, consider setting this option to the no value. If set to no, the root user has to establish a connection as a normal user and from there use su to become root or use sudo to perform certain tasks with root permissions.

PermitEmptyPasswords

Use this option to specify whether you want to allow users to log in with an empty password. From a security perspective, this isn’t a very good idea, and so the default no value is suitable in most cases. If, however, you want to run SSH from a script and establish a connection without entering a password, it can be useful to change the value of this parameter to yes.

ChallengeResponseAuthentication

This option specifies whether users are allowed to log in using passwords. If you want to add additional security to your host by forcing users to log in with public/private key pairs only, give this parameter the value no.

X11Forwarding

Use this option to specify whether you want to allow clients to use X11 forwarding. On most Linux distributions, the default value for this parameter is yes.

Using SSH Key-Based Authentication

Now that you know all about the basics of SSH, let’s look at some of the more advanced options. One of the most important is key-based authentication, which SSH uses via public/ private key–based authentication. Before diving into the configuration of key-based authentication, let’s first have a look on how these keys are used.

A Short Introduction To Cryptography

In general, you can use two methods for encryption: symmetric and asymmetric. Symmetric encryption is faster but less secure, and asymmetric encryption is slower but more secure. In a symmetric key environment, both parties use the same key to encrypt and decrypt messages. With asymmetric keys, a public and a private key are used, and this is the important technique that’s used for SSH.

If asymmetric keys are used, every user needs his or her own public/private key pair, and every computer needs a pair of them as well. Of these keys, the private key must be protected at all times: if the private key is compromised, the identity of the owner of the private key is compromised as well. In short, stealing a user’s private key is like stealing that user’s identity.

Therefore, a private key is normally stored in a very secure place where no one other than its owner can access it; typically this is in ~/.ssh. The public key, on the other hand, is available to everyone.

Public/private keys are generally used for three purposes: encryption, authentication, and nonrepudiation.

To send an encrypted message, the sender encrypts the message with the public key of the receiver who can decrypt it with the matching private key. This scenario requires that, before sending an encrypted message, you have the public key of the person you want to send the message to.

The other options are to use public/private keys for authentication or to prove that a message has not changed since it was created. This method is known as nonrepudiation. In the example of authentication, the private key is used to generate an encrypted token, the salt. If this salt can be decrypted with the public key of the person who wants to authenticate, that proves the host really is dealing with the right person, and access can be granted. However, this technique requires the public key to be copied to the host before any authentication can occur, which is also the case when keys are used to prove that a message hasn’t been tampered with.

Using Public/Private Key–Based Authentication in an SSh Environment

When SSH key-based authentication is used, you must make sure that, for all users who need to use this technology, the public key is available on the hosts they want to log in to. When logging in, the user creates an authentication request that’s signed with the user’s private key. This authentication request is matched to the public key of the same user on the computer where that user wants to be authenticated. If it matches, the user is allowed access; if it doesn’t, user access is denied.

Public/private key–based authentication is enabled by default on all major Linux distributions, so it’s only when no keys are present that the computer prompts users for a password. The following steps provide a summary of what happens when a user tries to establish an SSH session with a host:

1. If public key authentication is enabled (the default), SSH checks the .ssh directory in the user’s home directory to see whether a private key is present.

2. If a private key is found, SSH creates a packet with some data in it (the salt), encrypts that packet with the private key, and sends it to the host. The public key is also sent with this packet.

3. The host now checks whether a file with the name authorized_keys exists in the home directory of the user. If it doesn’t, the user can’t be authenticated with his or her keys. If the file does exist and the public key is an allowed key (and also is identical to the key that was previously stored on the host), the host uses this key to check the signature.

4. If the signature is verified, the user is granted access. If the signature can’t be verified, the host prompts the user for a password instead.

All this sounds pretty complicated, but it really isn’t. Everything happens transparently, if it has been set up right. Also, there’s hardly any noticeable delay when establishing a connection. It normally takes no more than a second.

Setting Up SSh for Key-Based Authentication

The best way to explain how to set up SSH for key-based authentication is by working through an example. In the following procedure, key-based authentication is enabled for the user root.

1. On the desktop where root is working, use the command ssh-keygen -t dsa -b 1024. This generates a public/private key pair of 1,024 bits. Listing 11-20 shows what happens.

Listing 11-20. Generating a Public/Private Key Pair with ssh-keygen

workstation # ssh-keygen -t dsa -b 1024
Generating public/private dsa key pair.
Enter file in which to save the key (/root/.ssh/id_dsa) :
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_dsa.
Your public key has been saved in /root/.ssh/id_dsa.pub.
The key fingerprint is:
59:63:b5:a0:c5:2c:b5:b8:2f:99:80:5b:43:77:3c:dd root@workstation

I’ll explain what happens. The user in this example uses the ssh-keygen command to generate a public and a private key. The encryption algorithm used to generate this key is DSA, which is considered more secure than its alternative, RSA. The option -b 1024specifies that 1024-bit encryption should be used for the key. You’re possibly aware that the longer this number, the more secure it is. Notice, however, that a many-bits encryption algorithm also requires more system resources to use it. After generating the keys, the command prompts you to save it somewhere. By default, a directory with the name .ssh is created in your home directory and, within this directory, a file with the name id_dsa. This file contains the private key.

Next, you’re prompted to enter a passphrase, which is an important extra layer of protection that can be added to the key. Because anyone who has access to your private key (which isn’t that easy) can forge your identity, your private key should always be protected with a passphrase. After entering the same passphrase twice, the private key is saved, and the related public key is generated and saved in the file /root/.ssh/id_dsa.pub. Also, a key fingerprint is generated. This fingerprint is a summary of your key, a checksum that’s calculated on the key to alert you if the key has been changed. Make sure that your passphrase is not too easy to guess; a weak passphrase makes a strong key useless.

2. After creating the public/private key pair, you must transfer the public key to the host. The ultimate goal is to place the contents of the id_dsa.pub file in the /root/.shh/ authorized_keys file on the host. But you can’t simply copy the file to the destination file authorized_keys because other keys may already be stored there. Therefore, first use scp to copy the file to a temporary location. The command scp /root/.ssh/id_dsa. pub root@host:/root/from_workstation_key.pubwould do the job.

3. Now that the public key is on the host, you have to put it in the authorized_keys file. Before doing this, though, make sure that the .ssh directory exists on the host in the home directory of the user root, and that it has user and group root as its owner and permission mode 700. Then, on the host with the directory /root as your current directory, use cat from_workstation_key.pub >> .ssh/authorized_keys. This command appends the content of the public key file to the authorized_keys file, thus not overwriting any file that may have been there already.

4. Hopefully, no errors have occurred, and you’ve been successful. Go back to your workstation and start an SSH session to the host where you just copied your public key to the authorized_keys file. You’ll notice that you are no longer prompted for a password, but for a passphrase instead. This proves that everything worked. Do notice, however, that you need to repeat this procedure for every key-secured host with which you want to be able to establish a session.

Working with keys as described in these steps is an excellent way to make SSH authentication more secure. But there’s a drawback: if you need to establish an SSH session automatically from a shell script or cron job, it’s not very handy if you’re first prompted for a key. Therefore, some method is needed to execute such jobs automatically. One solution is to create a special user account with limited permissions and without a passphrase on its private key. Another solution is to run ssh-agent, which caches the keys before they are used, and you’ll learn how to do this in the next section.

Caching Keys with ssh- ssh-agent

You can use ssh-agent to save yourself from constantly having to enter private keys. With this program, you can cache keys for a given shell environment. After starting ssh-agent from a shell prompt, you need to add the passphrase for the private key that belongs to it. This is something that you’ll do for a specific shell, so after you close that specific shell or load another shell, you’ll need to add the passphrase to that shell again.

After adding a passphrase to ssh-agent, the passphrase is stored in RAM, and only the user who added the key to RAM is able to read it from there. Also, ssh-agent listens only to ssh and scp commands that you’ve started locally, so there’s no way that you can access a key that is kept by ssh-agent over the network. So you can be sure that using ssh-agent is pretty secure. Apart from being secure, it’s pretty easy as well. Enabling ssh-agent and adding a passphrase to it is a simple two-step procedure:

1. From the shell prompt, use ssh-agent followed by the name of the shell you want to use it from. For example, use ssh-agent /bin/bash to activate ssh-agent for the Bash shell.

2. Now type ssh-add. You’ll be prompted for the passphrase of your current private key, and you’ll then see the message identity added, followed by the private key whose passphrase is added to ssh-agent.

Image Tip Secure Shell is a great way of accessing other hosts. But did you know that you can also use it to mount a file system on a remote host? All modern versions of SSH support this feature: just use sshfs for access to all the files and directories on the remote host, just like a local user on that host. If you know how to mount a directory with the mount command, working with sshfs is easy. For example, the command sshfs linda@AMS:/data /mnt allows access to the /data directory on the remote host and connects that directory to /mnt on the local computer. Secure Shell is not installed by default, so use apt-get install sshfs to install it on your computer.

Tunneling Traffic with SSH

Apart from establishing remote login sessions, copying files, and executing commands on remote hosts, you can also use SSH for TCP port forwarding. When used like this, SSH is a simple VPN solution with the capability of tunneling to almost any unsecured protocol over a secured connection. In this section, I’ll first talk about X forwarding, and then you’ll see how to forward almost any protocol using SSH.

X Forwarding

Wouldn’t it be useful if you could start an application on a host, where all the workload is performed by the host, while you control the application from your client? Well, you can with SSH X forwarding. To use X forwarding, you first must establish an SSH session to the host you want to connect to. Next, from this SSH session, you start the graphical application, which will draw its screen on your workstation while doing all the work on the host itself.

Sounds good? Establishing such an environment has only two requirements:

· Make sure the X11Forwarding option is set to yes in /etc/ssh/sshd_config on the host.

· Connect to the host with the ssh -X command from your client. Alternatively, you can set the X11Forwarding option in the client configuration file /etc/ssh/ssh_config, which allows you to forward graphical sessions by default. This poses a minor security problem, however, and so this setting is not enabled by default on most Linux distributions.

Now that you have established the SSH session with your host, start your favorite graphical program. The program itself will be executed at the remote host, and you’ll see the screen locally.

Image Note X-forwarding sessions with SSH is really cool, but there is a limitation: you need an X server on the client from which you are establishing the SSH session. This X server is used as the driver for your graphical hardware, and the application that you want to run on your client needs it to display its screens. On Linux, UNIX, or Macintosh machines, this won’t be a problem because an X server is present by default. It’s a problem on Windows, however. The most common SSH client for Windows is PuTTY, which, although very useful, doesn’t contain an X server. A good X server for Windows is Xming, which is a free X server that you can download from the Internet.

Generic tCp port Forwarding

X is the only service for which port forwarding is hard-coded in the SSH software. For everything else, you need to do port forwarding by hand, using the -L (local forwarding) or the -R (remote port forwarding) options. Let’s have a look at the example in Figure 11-1.

Figure 11-1. Example network

This example network has three nodes: AMS is the node where the administrator is working, ATL is the node in the middle, and AMS has a direct connection to ATL, but not to SLC, which is behind a firewall. ATL does have a direct connection to SLC and is not obstructed by any firewall.

The following command illustrates a simple case of port forwarding:

linda@AMS:~> ssh -L 4444:ATL:110 linda@ATL

In this example, user linda forwards connections to port 4444 on her localhost to port 110 on the host ATL as user linda on that host. This is how you would establish a secure session to the insecure POP service on that host, for example. The localhost first establishes a connection to the SSH host running on ATL. This SSH host connects to port 110 at ATL, whereas ssh binds to port 4444 on the localhost. Now an encrypted session is established between local port 4444 and host port 110: everything sent to port 4444 on the localhost really goes to port 110 at the host. If, for example, you configured your POP mail client to get its mail from local port 4444, it would really get it from port 110 at ATL.

Notice that a nonprivileged port is used in this example. Only user root can connect to a privileged port with a port number lower than 1024. No matter what port you are connecting to, you should always check in the services configuration file /etc/services, where port numbers are matched to names of services indicating what the port is normally used for (if anything), and use netstat -platune | grep <your-intended-port> to make sure that the port is not already in use.

A little variation on local port forwarding is remote port forwarding, which involves forwarding all connections on a remote port at a remote host to a local port on your machine.

To do this, use the -R option as in the following example:

linda@AMS:~> ssh -R 4444:AMS:110 linda@ATL

In this example, user linda connects to host ATL (see the last part of the command). On this remote host, port 4444 is addressed by using the construction -R 4444. This remote port is redirected to port 110 on the localhost. As a result, anything going to port 4444 on ATL is redirected to port 110 on AMS. This example would be useful if ATL is the client and AMS is the host running a POP mail server that user linda wants to connect to. Another instance when port forwarding proves useful is when the host you want to forward to cannot be reached directly, perhaps because it is behind a firewall. In this case, you can establish a tunnel to another host that is reachable with SSH. Imagine that, in Listing 11-6, the host SLC is running a POP mail server that our user linda wants to connect to. This user would use the following command:

linda@AMS:~> ssh -L 4444:SLC:110 linda@ATL

In this example, linda forwards connections to port 4444 on her localhost to host ATL, which is running SSH. This host, in turn, forwards the connection to port 110 on host SLC. Note that in this scenario, the only requirement is that ATL has the SSH service activated; no sshd is needed on SLC for this to work. Also note that there is no need for host AMS to get in direct contact with SLC, as that’s what ATL is used for.

In these examples, you’ve learned how to use the ssh command to accomplish port forwarding, but this isn’t the only way of doing it. If a port-forwarding connection needs to be available all the time, you can put it in the ssh configuration file at the client computer. Put it in.ssh/config in your home directory if you want it to work for your user account only, or in /etc/ssh/ssh_config if you want it to apply to all users on your machine. The parameter that should be used as an alternative to ssh -L 4444:ATL:110 would be LocalForward 4444 ATL:110.

EXERCISE 11-3: USING SSH

In this exercise you’ll configure SSH. Make sure to change back the configuration if this doesn’t match your operational needs.

1. Open a root shell.

2. Open the configuration file /etc/ssh/sshd_config with an editor and find the line that reads Port 22. Below this line, add the line Port 2222. This tells your server to offer services on two different ports.

3. Type systemctl restart sshd to restart the ssh server.

4. Type ssh -p 2222 localhost to connect as root to port 2222 on the server that is listening on localhost. We’re using localhost here, because that allows you to do this exercise without the need of configuring an additional server.

5. Type exit. This closes the current SSH session.

6. Type ssh-keygen. This generates a pair of SSH keys.

7. Type ssh-copy-id localhost to copy the public key to the authorized_keys file on the target server.

8. Type ssh -p 2222 localhost again. This will now connect you to localhost without asking for a password.

Summary

In this chapter, you’ve learned how to set up a network connection. First, we explored how an IP address is assigned to a network interface card. We covered IPv4 addresses as well as IPv6 addresses. Following that, you read how to troubleshoot a network connection using basic commands such as ping and traceroute, or advanced tools like nmap. In the last part of this chapter, you’ve learned how to create a remote session with SSH. You have read about the following commands:

· ifconfig: Legacy command to monitor and set IP address and other network card– related information

· ip: Newer command to monitor and set IP address and other network card–related information

· route: Command that displays and sets routing information

· ethtool: Command that displays and sets settings related to the physical capabilities of a network card, such as duplex mode and speed

· ping: Tool to test connectivity to other computers

· traceroute: Utility that helps you analyzing reachability of hosts on the network

· nmap: Utility that helps you check which services are offered by an other host

· netstat: Utility that helps you find out which services are offered by the local host

· ssh: Command that helps you to establish a shell connection to a remote computer, secured wit cryptography

· scp: Command that securely copies files between hosts

· sftp: Secure FTP client

· ssh-keygen: Command that generates public/private keys you can use for automatic SSH connection establishments where keys are used for authentication

· ssh-agent: Command that caches the passphrase associated to a private key used by SSH

In the next chapter, you’ll find out how to set up file services like Samba and NFS on your computer.