Skip to content
ImagineWorld

Networking in Linux

node_idnode-book_the-linux-devops-handbook_chapter-06-networking-in-linux
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num6
chapter_titleNetworking in Linux
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Networking is a complex topic no matter the operating system. Linux, in terms of its flexibility, can be very overwhelming regarding the multitude of possibilities of configuration, kernel features, and command-line tools that can help us configure those options. In this chapter, we will lay the foundation for this topic so that you can search for more information on a specific topic in other publications. In this chapter, we are going to cover the following topics:

  • Networking in Linux
  • ISO/OSI as a networking standard
  • Firewalls
  • Advanced topics

In Linux, networking is implemented in the kernel, which means that it is a part of the operating system. The kernel includes several components that work together to enable networking, including device drivers, protocol implementations, and system calls.

When a user wants to send or receive data over a network, they can do so using any of the networking applications available in Linux, such as ping, traceroute, telnet, or ssh. These applications use system calls to communicate with the kernel and request that data be sent or received over the network.

The kernel communicates with the network hardware using device drivers, which are software programs that allow the kernel to access and control the hardware. Different drivers are needed for different types of network hardware, such as Ethernet or Wi-Fi.

The kernel also implements several networking protocols, which are rules and standards that define how data is formatted and transmitted over the network. Common protocols used in Linux include TCP, UDP, and IP (version 4 and version 6).

The starting point of any discussion about networks always starts with the reference model defined by the International Organization for Standardization/Open Systems Interconnection (ISO/OSI). The ISO/OSI reference model is a conceptual model that defines a networking framework to implement protocols in seven layers. It is a framework that allows us to view communications between systems (computer or otherwise) as separate from the actual physical and software structure underlying it.

In Linux, the OSI model is implemented through a series of software components that are responsible for performing the functions of each layer. These components work together to enable networking capabilities in Linux.

The seven layers of the OSI model that are implemented in Linux are as follows:

  • Physical
  • Data link
  • Network
  • Transport
  • Session
  • Presentation
  • Application

In a system running in the cloud, you will have access to all the layers that are implemented in the Linux kernel. These layers are Network, Transport. Session, Presentation, and Application. To debug network connectivity, check statistics, and find any other possible issues, Linux has a console tool you can use. Let’s go through every layer one by one and investigate what command-line tools we can use in Linux to investigate each of them.

To learn more about the OSI model, you can refer to https://osi-model.com/. We are going to delve into the layers and explain them in the following subsections.

This layer is responsible for transmitting raw bits over a communication channel and is implemented through device drivers that control the network hardware, such as Ethernet standards such as 10BASE-T, 10BASE2, 10BASE5, 100BASE-TX, 100BASE-FX, 100BASE-T, 1000BASE-T, and others. We will not look at this layer in more detail here as we will focus on software implementation and how to interact with it on the Linux console. You can find plenty of information about cabling, hardware devices, and networking online.

The data link layer is responsible for providing a reliable link between devices on a network. It’s divided into the Logical Link Control (LLC) sublayer and the Media Access Control (MAC) sublayer.

The data link layer takes the raw data from the network layer (layer 3) and converts it into a format that can be transmitted over the physical link. It also provides error detection and correction, flow control, and MAC functions.

The LLC sublayer provides a consistent interface to the network layer, regardless of the type of physical network being used. It also provides flow control and error correction services.

The MAC sublayer controls access to the physical network and provides addressing services. It uses MAC addresses, which are unique identifiers that are assigned to each device on a network, to ensure that data is delivered to the correct destination.

The data link layer also includes the use of protocols such as Ethernet, PPP, and Frame Relay to provide communication between devices on a network. It also provides a mechanism for flow and error control – for example, it uses a cyclic redundancy check (CRC) for error detection and a sliding window for flow control.

Several Linux command-line tools can be used to debug data link layer problems. Here are a few examples:

  • ifconfig: This command can be used to view the status of network interfaces and their associated IP addresses, netmasks, and MAC addresses. It can also be used to configure network interfaces, such as setting an IP address or enabling or disabling an interface.
  • ping: This command can be used to test the reachability of a host on a network. It sends an Internet Control Message Protocol (ICMP) echo request packet to the specified host and waits for an echo reply. If the host responds, it indicates that the host is reachable and that the data link layer is functioning properly.
  • traceroute, tracepath, and mtr: These commands can be used to trace the route that packets take from the source to the destination. They can also be used to identify any network hops or devices that may be causing problems. Additionally, tracepath measures the Maximum Transmit Unit (MTU) you can use for this connection. mtr, on the other hand, provides more information about network health.
  • arp: This command can be used to view and manipulate the Address Resolution Protocol (ARP) cache. ARP is used to map an IP address to a MAC address on a local network. This command can be used to verify that the correct IP-MAC address mappings are in the ARP cache.
  • ethtool: This command can be used to view and configure advanced settings on Ethernet interfaces such as link speed, duplex mode, and auto-negotiation settings.
  • tcpdump: This command can be used to capture and analyze network packets in real time. It can be used to troubleshoot problems such as packet loss, delayed packets, and network congestion.

We will dive deeper into the preceding tools in the next sections of this chapter as most of them can be used to look into several different OSI layers at once.

Each device on a public (internet) or private (your office or home) network has a unique address that is used to identify it and connect to it. When you send a request to a website, your device sends a message to the destination server using its address. The server then responds by sending a message back to your device using its address. This process is how devices communicate with each other over the internet. There are two types of addresses we use: IPv6 and IPv4. IP stands for Internet Protocol and the main difference between v4 (version 4) and v6 (version 6) is the number of addresses you can use.

IPv4 is the most widely used version of IP and there are only about 4.3 billion unique addresses available. However, this is not enough to support the increasing number of devices that are being connected to the internet. To address this issue, a new version of IP called IPv6 was developed to provide a much larger address space.

IPv4 addresses are 32-bit numbers that are usually represented in a dotted decimal notation, with four octets ranging from 0 to 255. For example, 192.168.0.1 or 1.2.3.4 are valid IPv4 addresses.

IPv6 addresses are 128-bit numbers (between zero and FFFF in hexadecimal, which is equal to the decimal value 65535), represented in hexadecimal notation with eight groups of four hexadecimal digits separated by colons. An example of an IPv6 address is 2001:0db8:bad:f00d:0000:dead:beef:7331.

We’re mainly going to focus on IPv4 here as it’s generally easier to understand, but similar principles work for IPv6, so it’s going to be easier to reapply what we’ll learn later in this chapter to the IPv6 world.

Subnets are pieces of a network that are created by dividing a larger network into smaller networks. This is done for several reasons, including security, organization, and the efficient use of IP addresses. In public internet networks, every organization owns a piece of the network – a subnet.

When a network is subnetted, the host portion of the IP address (the part of the address that identifies a specific device on the network) is divided into two parts: one that identifies the subnet and one that identifies the host IPs within the subnet. The subnet mask, which is a binary representation that is applied to the IP address, is used to determine which part of the IP address identifies the subnet and which part identifies the host.

Imagine a network that uses the IP address range 192.168.11.0/24 (or 192.168.11.0/255.255.255.0 in decimal form). The /24 part is a Classless Inter-Domain Routing (CIDR) notation, which is a decimal representation of the number of bits used for the network (here, this is 24) and host.

This means that this particular network has 24 bits (or three numbers from the full address) for the network portion of the IP address and 8 bits (or one, last, number) for the host portion. So, for this network, you’ll have an available range of 192.168.11.0 - 192.168.11.255, where 192.168.11.0 is a network address and 192.168.11.255 is a broadcast address.

A broadcast network address is a special type of IP address that is used to send a message to all hosts on a particular network or subnet. The broadcast address is the highest in a network or subnet’s IP address range, and it is used in conjunction with the subnet mask to identify the broadcast domain. When a host sends a packet to a broadcast address, the packet is delivered to all hosts on the same network or subnet. It’s important to note that broadcast packets don’t leave the current subnet network – they only work within the local network or subnet.

Before standardizing CIDR, IP addresses were divided into classes (A, B, and C) based on the number of hosts that a network needed to support. These classes were defined by the leading bits of the IP address, and each class had a different number of bits for the network portion and host portion of the IP address. Right now, we’re mainly using CIDRs, but some network addressing remains. For example, 10.0.0.0, 12.0.0.0, or 15.0.0.0 usually have 255.0.0.0 or /8 network masks. Here are some other networks you could encounter:

  • Class A: 10.0.0.0/8, 12.0.0.0/8, and 15.0.0.0/8
  • Class B: 172.16.0.0/16, 172.17.0.0/16, and 172.18.0.0/16
  • Class C: 192.168.0.0/24, 192.168.1.0/24, and 192.168.2.0/24

These examples are not actual networks, but just a representation of how to identify the network class by looking at the leading bits of the IP address and the subnet mask – it’s not a rule and you could create smaller (or bigger) networks within your infrastructure.

You can find a lot of calculators online that will help you better understand how networks address work. Here are some examples:

Now that we have learned about subnets, classes, and network masks, let’s move on to the next subsection.

With the knowledge you’ve gained so far, you can easily check your Linux network configuration using some CLI tools that are available in every modern Linux environment.

Here are some basic console tools to use for network configuration:

  • The iproute2 package, replacing the ifconfig and route commands
  • ifconfig
  • route
  • ip
  • netplan

Let’s go through the syntax and what’s possible while using these tools.

One of the commands that’s usually available in Linux is ifconfig. This tool is used to configure network interfaces. It can be used to show the status of an interface, assign an IP address to an interface, set the netmask, and set the default gateway. ifconfig (from the net-tools package) was replaced in recent years with the iproute2 set of tools; the most well-known CLI command from this package is ip.

Here’s some example output of the ifconfig command:

admin@myhome:~$ ifconfig
eth0: flags=4163<UP,BRODCAST,RUNNING,MULTICAST> mtu 1500
inet 172.17.0.2 netmask 255.255.0.0 broadcast 172.17.255.255
ether 02:42:ac:11:00:02 txqueuelen 0 (Ethernet)
RX packets 17433 bytes 26244858 (26.2 MB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 8968 bytes 488744 (488.7 KB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
loop txqueuelen 1000 (Local Loopback)
RX packets 0 bytes 0 (0.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 0 bytes 0 (0.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

ifconfig, when invoked without any additional options, will list all available interfaces in our system with some basic information such as interface name (here, these are eth0 and lo), the MAC address of the network card (the physical address of your device), network configuration (IP address, network mask, and broadcast address), received and transmitted packets, and other information. This will allow you to check your network status at a glance.

The loopback device (named lo in the preceding example) is a virtual network interface that is used to send network packets to the same host that they were sent from. It is also known as the loopback interface and is represented by lo or lo0.

The primary purpose of the loopback device is to provide a stable and consistent way for the host to communicate with itself over the network stack, without having to rely on any physical network interface.

The loopback interface is typically used for testing, troubleshooting, and some system and application functions, as well as inter-process communication (IPC) between processes running on the same host.

Using ifconfig will also allow you to bring some interfaces up and down and configure their settings. To persist the configuration, you will need to save it to the / etc/network/interfaces file:

auto lo
iface lo inet loopback
# eth0 network device
auto eth0
iface eth0 inet static
address 172.17.0.2
netmask 255.255.0.0
gateway 172.17.0.1
dns-nameservers 8.8.8.8 4.4.4.4
auto eth1
allow-hotplug eth1
iface eth1 inet dhcp

In the preceding example, we’re setting an automatic loopback device with eth0 and eth1. The eth0 interface has a static network configuration and will be also configured, the same as lo, when your system boots. The eth1 interface has a dynamic network configuration that’s retrieved by the Dynamic Host Configuration Protocol (DHCP) server in the network it’s connected to. (DHCP is a widely used and de facto standard way to automatically and dynamically assign a system IP address; it is also possible to pass some other configuration parameters related to networking through DHCP.) Additional allow-hotplug configuration means that this device will be started upon detection by the Linux kernel.

It’s useful to know that after editing the /etc/network/interfaces file, you’ll need to use either ifup or ifdown tools on Debian Linux or Ubuntu Linux, or ifupdown tools in Alpine Linux. Alternatively, you can restart networking by using the systemctl restart network on Debian Linux, Ubuntu Linux, or RHEL/CentOS. You must use the rc-service networking restart command on Alpine Linux.

To manually configure a device using ifconfig, you’ll need to run the following commands:

admin@myhome:~$ ifconfig eth0 192.168.1.2 netmask 255.255.255.0
admin@myhome:~$ ifconfig eth0 up

This will configure the eth0 interface with a 192.168.1.2 IP address for the network with a netmask of 255.255.255.0 (or /24 in CIDR notation).

Instead of using the ifconfig up and ifconfig down commands, you can also use ifup and ifdown in Debian Linux and Ubuntu Linux systems, respectively, or ifupdown in Arch Linux systems.

The route command is used to view and manipulate the IP routing table. It’s used to determine where network packets are sent given the destination IP addresses.

Invoking the route command without any options will display the current route table in our system:

admin@myhome:~$ route
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
default 172.17.0.1 0.0.0.0 UG 0 0 0 eth0
172.17.0.0 0.0.0.0 255.255.0.0 U 0 0 0 eth0

To add a new entry to the routing table, use the following command:

admin@myhome:~$ sudo route add default gw 172.17.0.1 eth0

There can be only one default route. To add a custom route, do the following:

admin@myhome:~$ sudo route add -net 192.168.1.0 netmask 255.255.255.0 gw 192.168.1.1 dev eth0

The del command deletes an entry from the routing table, similar to the preceding example:

admin@myhome:~$ route del -net 192.168.1.0 gw 192.168.1.1 netmask 255.255.255.0 dev eth0

Finally, the flush command deletes all entries from the routing table, which means you will lose all network connections and if you are connected to a remote machine, you won’t be able to work on it anymore.

There are more possibilities while using the ifconfig and route commands, but as we’ve already stated, both commands got replaced by the iproute2 package (a successor of iproute), which includes the ip command.

A more advanced command to manipulate routes and the configuration of network devices is ip, which can be used to perform a wider range of tasks, such as creating and deleting interfaces, adding and removing routes, and displaying network statistics.

Let’s look at the most common commands you can perform using iproute2:

  • ip addr or ip a: This shows information about network interfaces and their IP addresses. It also supports subcommands; for instance, the ip addr add command can be used to add an IP address to an interface, and ip route add can be used to add a route to the routing table.
  • ip link or ip l: This shows information about network interfaces and their link-layer settings.
  • ip route or ip r: This shows the IP routing table.
  • ip -s link (or ip -s l): This shows statistics about network interfaces.

The following is the output of running the ip link and ip addr commands:

admin@myhome:~$ sudo ip link
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
2: tunl0@NONE: <NOARP> mtu 1480 qdisc noop state DOWN mode DEFAULT group default qlen 1000
link/ipip 0.0.0.0 brd 0.0.0.0
3: ip6tnl0@NONE: <NOARP> mtu 1452 qdisc noop state DOWN mode DEFAULT group default qlen 1000
link/tunnel6 :: brd :: permaddr 4ec4:2248:2903::
47: eth0@if48: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP mode DEFAULT group default
link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff link-netnsid 0
admin@myhome:~$ sudo ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
2: tunl0@NONE: <NOARP> mtu 1480 qdisc noop state DOWN group default qlen 1000
link/ipip 0.0.0.0 brd 0.0.0.0
3: ip6tnl0@NONE: <NOARP> mtu 1452 qdisc noop state DOWN group default qlen 1000
link/tunnel6 :: brd :: permaddr 4ec4:2248:2903::
47: eth0@if48: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff link-netnsid 0
inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
valid_lft forever preferred_lft forever

Both commands print out very similar information, but ip addr, apart from providing information about physical interfaces, adds information about network configuration. The ip link command is being used to control the interface status. Similar to how ifconfig up eth0 was enabling the interface, ip link set dev eth0 up will do the same.

To configure a network interface using iproute2, you will need to execute the following commands:

admin@myhome:~$ sudo ip addr add 172.17.0.2/255.255.0.0 dev eth0
admin@myhome:~$ sudo ip link set dev eth0 up

To set the interface as the default route, use the following command:

admin@myhome:~$ sudo ip route add default via 172.17.0.1 dev eth0

To check only the eth0 interface’s status, you’d execute the following command:

admin@myhome:~$ sudo ip addr show dev eth0
47: eth0@if48: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff link-netnsid
0
inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
valid_lft forever preferred_lft forever

This tool is a new network configuration tool that was introduced in Ubuntu and is supported in Debian. It is a YAML configuration file and can be used to manage network interfaces, IP addresses, and other network settings. It was first introduced in Ubuntu 17.10 as a replacement for the traditional /etc/network/interfaces file and has since been adopted by other distributions. such as Debian and Fedora. Ubuntu 18.04 and newer versions have netplan installed by default. Other distributions, such as Debian 10 and Fedora 29 onwards, have also included netplan by default.

To use Netplan, you will first need to create a configuration file in the /etc/netplan/ directory. The file should have a .yaml extension and should be named something descriptive, such as 01-eth0.yaml or homenetwork.yaml.

The sample configuration looks like this:

network:
version: 2
renderer: networkd
ethernets:
eth0:
dhcp4: true

This configuration defines a single network interface, eth0, that uses DHCP to obtain an IP address. The renderer key tells netplan which network manager to use (in this case, networkd). The version key is used to indicate the version of netplan being used. networkd is a network management daemon that is part of the systemd system and service manager.

A configuration with a static IP address for the eth0 interface would look like this:

network:
version: 2
renderer: networkd
ethernets:
eth0:
addresses: [192.168.0.2/24]
gateway4: 192.168.0.1
nameservers:
addresses: [8.8.8.8, 4.4.4.4]

This configuration file defines one ethernet interface (eth0) with a static IP address. This interface also has a gateway and DNS servers defined. Note that we’ve used a CIDR notation instead of a decimal one.

Once you saved your configuration, to apply the changes, you can run the following command:

admin@myhome:~$ sudo netplan apply

You can also use the following command to check the configuration for syntax errors:

admin@myhome:~$ sudo netplan --debug generate

You can check the current status of the network interfaces using the following command:

admin@myhome:~$ sudo netplan --debug try

Finally, if you want to check the network interface’s status without applying the configuration, use the following command:

admin@myhome:~$ sudo netplan --debug networkd try

To view logs regarding errors while bringing up network interfaces, you can use the dmesg command to view kernel messages, including those related to network interfaces. You can use dmesg | grep eth0 to filter logs related to the eth0 interface specifically. Other locations include the /var/log/messages file, journalctl (for example, the journalctl -u systemd-networkd.service command), and /var/log/netplan/, which contains logs generated by netplan.

In day-to-day operations, it’s much more likely you’ll edit the /etc/network/interfaces file or netplan configuration than configure the interface manually, but it’s very useful to know how to do it in case you need to temporarily change something in the network configuration for testing or debugging issues.

Next, we will cover the transport layer.

In the transport layer of the OSI model, we focus more on Transmission Control Protocol (TCP) and IP, which are the foundation of the modern internet. Additionally, we’ll look into the User Datagram Protocol (UDP). We talked about IP in the Network layer – IPv4 and IPv6 subsection of this chapter, so we’re only going to deepen our knowledge of this protocol a bit here.

TCP is used for communication and needs reliable two-way communication between services. UDP is a stateless protocol that does not need a constant connection.

A TCP connection is established using a three-way handshake:

  1. The client sends a SYN (synchronize) packet to the server, to initiate the connection.
  2. The server receives the SYN packet and sends back a SYN-ACK (synchronize-acknowledgment) packet to the client to confirm that the connection has been established.
  3. The client receives the SYN-ACK packet and sends back an ACK (acknowledgment) packet to the server to complete the three-way handshake.

Once the three-way handshake is completed, the devices can start sending data to each other over the established TCP connection.

The connection for TCP and UDP protocols is initiated by sending packets to a port on the server end of the connection. The port number is included in the IP packet header, along with the IP address, so that the destination device knows which process to send the data to.

A port is an integer ranging from 0 to 65535. It is used to identify a specific process running on a device and to differentiate it from other services. The port number is added to the IP address. Thus, if more than one program listens for a connection on one IP address, the other side can tell exactly which program it wants to talk to. Let’s assume that two processes are running and listening: a WWW server and an SSH server. The WWW server will typically listen on ports 80 or 443 and the SSH server will listen on port 22. Let’s assume the system has an IP address of 192.168.1.1. To connect to the SSH server, we would pair the IP address with the port address (commonly written as 192.168.1.1:22). The server will know that this incoming connection has to be handled by the SSH process. A UDP connection, unlike TCP, doesn’t establish a connection to a server machine. Instead, devices can start sending UDP datagrams (packets) to each other on known ports.

When a device sends a UDP datagram, it includes the destination IP address and port number in the packet header. The receiving device checks the destination IP address and port number in the packet header to determine which process to send the data to.

Because UDP is connectionless, there is no guarantee that the data will be received by the destination device or that it will be received in the order it was sent. There is also no error checking or retransmission of lost packets. UDP is typically used for services that require a low overhead and fast communication. The most well-known service that uses UDP for communication is Domain Name Service (DNS).

There are three types of port numbers:

  • Well-known ports, which you can typically find in your Linux system in the /etc/services file. These are port numbers that are reserved for specific services, such as HTTP traffic on port 80 or DNS traffic on port 53.
  • Privileged ports are ports that only root users can open a listening service on. Those ports are between 1 and 1024.
  • Ephemeral ports are port numbers that are used for temporary connections and are assigned dynamically by the operating system, such as for TCP connections.

There are various tools available for viewing details on TCP and UDP traffic on the machine you’re working on. You can also set up a firewall so that you can control access to your machine from the network.

To view all TCP connections made from your machine, you can use a netstat command. It can be used to view a list of open connections, as well as display statistics about the network traffic on your system.

To view a list of all open connections on your system, you can use the netstat -an command. This will display a list of all current connections, including the local and remote IP addresses and ports, as well as the status of the connection (for example, listening, established, and so on).

Using netstat -s, you can view statistics on each connection on your system. This will display a variety of statistics about the network traffic on your system, including the number of packets sent and received, the number of errors, and more.

To view only the UDP connections using netstat, you can use the netstat -an -u command. This will display a list of all current UDP connections, including the local and remote IP addresses and ports, as well as the status of the connection.

Alternatively, you can use the netstat -an -u | grep "udp" | grep "0.0.0.0:*" command to only show UDP connections that are in a listening state. This command filters the output of netstat -an -u to show only lines that contain "UDP" and "0.0.0.0:*", which indicates a listening UDP connection.

You can also use other options, such as -p to show the process ID and name of the process that owns each connection, -r to show the routing table, and -i to show the statistics for a particular interface.

tcpdump is a command-line packet analyzer that allows you to capture and analyze network traffic by displaying packets being transmitted or received over a network to which the computer is attached. tcpdump can be used to troubleshoot network issues, analyze network performance, and monitor network security. You can capture packets on a specific interface, filter packets based on various criteria, and save the captured packets to a file for later analysis.

To capture and display all network traffic on the eth0 interface, you can use the -i option, followed by the interface name. To capture and display all network traffic on the eth0 interface, you would need to run sudo tcpdump - i eth0.

You can also save the captured packets to a file for later analysis by using the -w option – for example, tcpdump -i eth0 -w all_traffic.pcap. This will save all the captured packets on the eth0 interface in the file.

By default, tcpdump captures packets indefinitely.

To capture packets for a specific amount of time, you can use the -c option, followed by the number of packets to capture – for example, sudo tcpdump -i eth0 -c 100. This command captures and displays 100 packets, then exits.

You can also filter the traffic by using filters such as port, ip, host, and so on – for example, sudo tcpdump -i eth0 'src host 192.168.1.2 and (tcp or udp)'. This filter captures all the packets on the eth0 interface with a source IP address of 192.168.1.2 and is either TCP or UDP.

To show more advanced use of tcpdump, let’s capture only SYN packets (see all connections being established). You can achieve this by using the tcp[tcpflags] & (tcp-syn) != 0 filter. This filter checks if the SYN flag is set in the TCP header of the packet.

Here is an example command that captures and displays all SYN packets on the eth0 interface:

sudo tcpdump -i eth0 'tcp[tcpflags] & (tcp-syn) != 0'

You can also save the captured packets to a file for later analysis by using the -w option, like this:

sudo tcpdump -i eth0 -w syn_packets.pcap 'tcp[tcpflags] & (tcp-syn) != 0'

This will save all the captured SYN packets in the syn_packets.pcap file.

You can also specify a filter with a more complex filter, like this:

sudo tcpdump -i eth0 'tcp[tcpflags] & (tcp-syn) != 0 and src host 192.168.1.2'

This filter captures only SYN packets that have a source IP address of 192.168.1.2.

Another popular tool that’s similar to tcpdump is Wireshark. It can be used both headless (only in a command line) and via a graphical interface:

  • To show all traffic on the eth0 interface using Wireshark, you can use the sudo wireshark -i eth0 command. This will start Wireshark and listen for traffic on the eth0 interface. You can also use the -k flag to start capturing immediately and the -w flag to write the captured traffic to a file: sudo wireshark -k -i eth0 - w output_file.pcap.
  • If you’d like to show only SYN packets, as we showed in the tcpdump example, you can run the sudo wireshark -i eth0 -f "tcp.flags.syn == 1" command. The preceding command uses a filter, "tcp.flags.syn == 1", which says that we want to see only TCP protocol flags marked as SYN. You can also use this filter in the GUI version of Wireshark by going to the Capture menu, selecting Options, then entering the filter in the Capture Filter field before starting the capture.

Alternatively, you can apply this filter after capturing the traffic by clicking on the filter button on the top-right corner of the Wireshark window, type "tcp.flags.syn==1" in the filter field, and press Enter.

The next very useful tool that’s similar to tcpdump and Wireshark is ngrep. What differentiates it from other tools we’ve been talking about is that it’s much simpler to use, and it allows you to (similar to grep) search for strings inside network packets.

For instance, to monitor GET HTTP requests, you can use the following command:

admin@myhome:~$ ngrep -d eth0 -q -W byline "GET" "tcp and port 80"
interface: en0 (192.168.1.0/255.255.255.0)
filter: ( tcp and port 80 ) and ((ip || ip6) || (vlan && (ip || ip6)))
match: GET
# Later output will contain actual GET requests, removed for readability

This command will listen on the eth0 interface and match only TCP packets on port 80 (the default port for HTTP). The -q option tells ngrep to be quiet and not display packet summary information, while -W tells ngrep to print each packet data in separate lines. At this point, we can move to the session layer.

The session layer, as we’ve already mentioned, is responsible for establishing, maintaining, and terminating connections between devices. This means it sets up, coordinates, and terminates conversations, exchanges, or connections between the applications. The session layer ensures that data is transmitted reliably and in the proper sequence by using techniques such as token management and checkpointing. It is also responsible for resolving any conflicts that may arise during a session, such as when two applications attempt to initiate a session at the same time. In a nutshell, the session layer establishes, maintains, and terminates the connections between the devices on a network.

In other words, the session layer is a glue between the lower layers we’ve already covered and the higher layers we will be covering in the next few sections of this chapter.

The best tools to figure out issues with sessions are logs tied to the service you’re working with. If you have a problem with an FTP connection, you might want to look into logs of your client and/or server running on the machine you manage. The tools we covered previously can also help if logs are not enough to understand the issue you’re trying to resolve.

The presentation layer is the sixth layer of the OSI model, and it is responsible for representing the data in a format that can be understood by the application layer. This includes converting data between different formats, such as the American Standard Code for Information Interchange (ASCII) and Extended Binary Coded Decimal Interchange Code (EBCDIC). Both are character encoding standards that represent characters using 7-bit (ASCII) or 8-bit (EBCDIC) integers. We also handle encryption and compression in this layer. The presentation layer also ensures that the data is in the correct format for the application to process. It acts as an intermediary between the application and the data, allowing the application to be independent of the specific format of the data being received.

For this layer, the most common encryption standards, Secure Sockets Layer (SSL) and Transport Layer Security (TLS) are the ones you might need to debug and fix issues with.

TLS is a widely used protocol for securing communications over a network. It is a successor to SSL and is used to encrypt and authenticate data transmitted over a network, such as the internet.

TLS works by establishing a secure tunnel between two devices, such as a web server and a web browser. This tunnel is used to transmit data between the two devices in an encrypted format, making it difficult for an attacker to intercept and read the data.

The process of establishing a TLS connection involves several steps:

  1. Handshake: The client and server exchange information to establish a shared understanding of the encryption method and keys that will be used to secure the connection.
  2. Authentication: The server authenticates itself to the client by providing a digital certificate that contains information about the server’s identity and public key. The client can then use this information to verify the server’s identity.
  3. Key exchange: The client and server exchange public keys to establish a shared secret key that will be used to encrypt and decrypt data.
  4. Data encryption: Once the shared secret key has been established, the client and server can start encrypting data using symmetric encryption algorithms.
  5. Data transfer: Data is then transferred over the secure connection, protected by the encryption established during the handshake.

TLS has multiple versions, among which the newest are considered more secure. However, older systems might not support the most recent versions. The available TLS versions are as follows:

  • TLS 1.0: This was the first version of the protocol, released in 1999.
  • TLS 1.1: This was released in 2006.
  • TLS 1.2: This was released in 2008. It added support for new cryptographic algorithms and made several other security enhancements.
  • TLS 1.3: This was released in 2018 and includes the use of forward secrecy, which makes it harder for attackers to decrypt captured data.

SSL is a security protocol that is widely used to secure communications over a network, such as the internet. It was developed by Netscape in the 1990s and was later succeeded by the TLS protocol.

Like TLS, SSL works by establishing a secure tunnel between two devices, such as a web server and a web browser. This tunnel is used to transmit data between the two devices in an encrypted format, making it difficult for an attacker to intercept and read the data. It’s not recommended to use SSL anymore and it’s better to use the latest version of TLS, but you might still encounter systems using it.

The best tool to debug issues with both SSL and TLS is the openssl command. You can use it to test a connection to a server using SSL. For example, you can use the following command to test a connection to a server on port (usually, it’s 443 as it’s a common port for HTTPS):

admin@myhome:~$ openssl s_client -connect myhome:443

You can use the openssl command to check the details of an SSL certificate, including the expiration date, the issuing authority, and the public key. For example, you can use the following command to check the details of a certificate:

admin@myhome:~$ openssl s_client -connect myhome:443 -showcerts

This will allow you to check if the certificates served by your server are valid and what you expect them to be. This is much faster than using a web browser.

Using the openssl command, you can also check which ciphers are supported by a server. For example, you can use the following command to check the ciphers supported by a server:

admin@myhome:~$ openssl s_client -connect myhome:443 -cipher 'ALL:eNULL'
# Cut most of the output for readability
SSL handshake has read 5368 bytes and written 415 bytes
---
New, TLSv1/SSLv3, Cipher is AEAD-AES256-GCM-SHA384
Server public key is 2048 bit
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
Protocol : TLSv1.3
Cipher : AEAD-AES256-GCM-SHA384
Session-ID:
Session-ID-ctx:
Master-Key:
Start Time: 1674075742
Timeout : 7200 (sec)
Verify return code: 0 (ok)
---
closed

Additionally, openssl has a built-in diagnostic that can detect known vulnerabilities that exist in your system:

admin@myhome:~$ openssl s_client -connect myhome:443 -tlsextdebug -status
CONNECTED(00000006)
140704621852864:error:1404B42E:SSL routines:ST_CONNECT:tlsv1 alert protocol version:/AppleInternal/Library/BuildRoots/aaefcfd1-5c95-11ed-8734-2e32217d8374/Library/Caches/com.apple.xbs/Sources/libressl/libressl-3.3/ssl/tls13_lib.c:151:
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 5 bytes and written 303 bytes
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
Protocol : TLSv1.3
Cipher : 0000
Session-ID:
Session-ID-ctx:
Master-Key:
Start Time: 1674075828
Timeout : 7200 (sec)
Verify return code: 0 (ok)
---

It’s also worth noting that both SSL and TLS use public key encryption. With this encryption method, we create two files: a private key and a public key. Together, they form a pair. The public key is designed to encrypt data, while the private key is designed to decrypt it. The private key should be kept private at all times, as its name implies. This method of encryption is based on the mathematical properties of large prime numbers, and it is considered to be very secure.

In the case of TLS, public key encryption is used during the handshake phase to establish a secure connection between the client and the server. The process works as follows:

  1. The server generates a public key and a private key. The public key is sent to the client as part of the server’s digital certificate.
  2. The client generates a session key, which is used to encrypt data that is sent to the server. The server’s public key is used to encrypt the session key. Once the server receives the encrypted data, it uses its private key to decrypt it and retrieve the session key.
  3. Once the session key has been decrypted, it is used to encrypt data that is sent between the client and the server.

The next and final layer is the top layer of the OSI model. In the next section, which covers the application layer, we’ll cover protocols such as HTTP and FTP, which are commonly used for browsing the web and sharing files.

The application layer is the seventh and highest layer of the OSI network model. It provides the interface between the software application and the network, allowing the application to access the network’s communication services. The application layer defines protocols and services that are specific to the application, such as file transfer (File Transfer Protocol (FTP)), email (Simple Mail Transfer Protocol (SMTP) and Internet Message Access Protocol (IMAP)), and well-known web services (Hypertext Transfer Protocol (HTTP)).

Let’s take a closer look at HTTP. This communication protocol is used for transferring data on the World Wide Web. It is based on a client-server model, where a web browser (the client) sends a request to a web server, and the server sends back a response.

When a user enters a Uniform Resource Locator (URL) in their web browser, the browser sends an HTTP request to the web server associated with that URL. A URL is something you can see in your browser address input field and is usually located at the top of the browser window – for example, https://google.com.

The request includes the method (such as GET, POST, PUT, PATCH, or DELETE), which indicates the type of action the browser wants the server to perform, as well as any additional information, such as data for a POST or PUT request.

The web server then processes the request, after which the server sends back an HTTP response, which includes a status code (such as 200 for success or 404 for not found) and any data requested by the browser, such as the HTML and CSS that make up the website.

Once the browser receives the response, it parses the HTML, CSS, and – very often – JavaScript to display the website to the user.

HTTP is a stateless protocol, which means that each request is independent and the server does not retain any information about previous requests. However, many web applications use cookies or other techniques to maintain state across multiple requests.

HTTP version 1.1 introduced new features such as persistent connections, a host header field, and byte-serving which, improved the overall performance of the protocol and made it more suitable for heavy usage scenarios. The most recent version of this protocol is 2.0 and is described in detail by RFC 7540 (https://www.rfc-editor.org/rfc/rfc7540.html), which was released in 2015, and updated by RFC 8740 (https://www.rfc-editor.org/rfc/rfc8740.html), which was released in 2020.

To resolve issues with HTTP, you can use any of the tools for debugging network problems, such as tcpdump or ngrep. There are several console and GUI tools available you can use for debugging HTTP. The most common are wget and curl for the console and Postman or Fiddler for the GUI. There will also be debugging tools built into your browser, such as Firefox or Chrome Developer Tools.

We’re going to focus on console tools right now, so let’s look into wget first. This tool is intended to download files, but we still can use it to debug HTTP. For the first example, we will show detailed information about the request and response:

admin@myhome:~$ wget -d https://google.com
DEBUG output created by Wget 1.21.3 on darwin22.1.0.
Reading HSTS entries from /home/admin/.wget-hsts
URI encoding = 'UTF-8'
Converted file name 'index.html' (UTF-8) -> 'index.html' (UTF-8)
--2023-01-20 14:11:02-- https://google.com/
Resolving google.com (google.com)... 216.58.215.78
Caching google.com => 216.58.215.78
Connecting to google.com (google.com)|216.58.215.78|:443... connected.
Created socket 5.
Releasing 0x0000600000d2dac0 (new refcount 1).
Initiating SSL handshake.
Handshake successful; connected socket 5 to SSL handle 0x00007fca4a008c00
certificate:
subject: CN=*.google.com
issuer: CN=GTS CA 1C3,O=Google Trust Services LLC,C=US
X509 certificate successfully verified and matches host google.com
---request begin---
GET / HTTP/1.1
Host: google.com
User-Agent: Wget/1.21.3
Accept: */*
Accept-Encoding: identity
Connection: Keep-Alive
---request end---
HTTP request sent, awaiting response...
# Rest of the output omitted

You might need to send an HTTP request with specific headers. To do so, you can use the -- header option:

admin@myhome:~$ wget --header='<header-name>: <header-value>' <url>

POST is a special HTTP request – it uses a URL, but it will also require some request data as it’s intended to send some data to your system, be it a username and password or files. To send an HTTP POST request with prepared data, you can use the --post-data option, like this:

admin@myhome:~$ wget --post-data=<data> <url>

A more powerful tool for debugging HTTP issues is curl. To send an HTTP GET request and display the response, you can use the following command:

admin@myhome:~$ curl linux.com
<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx</center>
</body>
</html>

To send an HTTP POST request and display the response, you can use the -X POST option and the - d option:

admin@myhome:~$ curl -X POST -d <data> <url>

Using the -X option, you can send other types of requests, such as PATCH or DELETE.

To send an HTTP request with specific headers, you can use the - H option:

admin@myhome:~$ curl -H '<header-name>: <header-value>' <url>

To display the response headers only, use the following code:

admin@myhome:~$ curl -I linux.com
HTTP/1.1 301 Moved Permanently
Connection: keep-alive
Content-Length: 162
Content-Type: text/html
Location: https://linux.com/
Server: nginx
X-Pantheon-Styx-Hostname: styx-fe3-b-7f84d5c76-q4hpv
X-Styx-Req-Id: f1409a84-9832-11ed-abcb-7611ac88195f
Cache-Control: public, max-age=86400
Date: Fri, 20 Jan 2023 13:14:42 GMT
X-Served-By: cache-chi-kigq8000084-CHI, cache-fra-eddf8230050-FRA
X-Cache: HIT, HIT
X-Cache-Hits: 37, 1
X-Timer: S1674220483.602573,VS0,VE1
Vary: Cookie, Cookie
Age: 62475
Accept-Ranges: bytes
Via: 1.1 varnish, 1.1 varnish

You can also show detailed information about the request and response by using the -v option, like this:

admin@myhome:~$ curl -v <url>

By sending different types of requests and analyzing the responses, you can use either wget or curl to debug various HTTP issues, such as connectivity problems, response errors, and performance issues. As usual, you can refer to the full documentation of both tools to deepen your understanding of how to use them.

In this section, we introduced several network layers, as defined by the ISO/OSI standard. Each of them standardizes the functions of different elements of networking communication. Next, we are going to discuss firewalls.

A firewall is a security measure that controls incoming and outgoing network traffic based on predefined rules and policies. It is typically placed between a protected network and the internet, and its main purpose is to block unauthorized access while allowing authorized communication. Firewalls can be hardware-based or software-based, and they can use a variety of techniques, such as packet filtering, stateful inspection, and application-level filtering, to control network traffic. In this section, we’re going to look into a firewall available on Linux systems.

To control a Linux firewall, you will need to use iptables, ufw, nftables, or firewalld. Packet filtering is built into the Linux kernel, so those CLI tools will interact with it.

iptables is the most verbose tool for controlling a firewall, meaning it does not have much abstraction built into it, but it’s important to understand the basic concepts so that we can move on to more user-friendly tools.

As mentioned previously, iptables allows you to create rules for filtering and manipulating network packets, and it can be used to control incoming and outgoing network traffic based on various criteria, such as IP or MAC addresses, ports, and protocols.

iptables uses several concepts to organize rules and divide them into functional parts: tables, chains, rules, and targets. The most general are tables to organize the rules.

There are three tables we can use: filter, nat, and mangle. The filter table is used to filter incoming and outgoing packets, the nat table is used for Network Address Translation (NAT), which we will get back to later, and the mangle table is used for advanced packet alteration.

Each table contains a set of chains, which are used to organize the rules. The filter table, for example, contains three predefined chains: INPUT, OUTPUT, and FORWARD. The INPUT chain is used for incoming packets, the OUTPUT chain is used for outgoing packets, and the FORWARD chain is used for packets that are being forwarded through the network.

Each chain contains a set of rules, which are used to match packets and decide what to do with them. Each rule has a match condition and an action. For example, a rule might match packets coming from a specific IP address and drop them, or it might match packets going to a specific port and accept them.

Each rule has a target, which is the action that should be taken when the rule’s match condition is met. The most common targets are ACCEPT, DROP, and REJECT. ACCEPT means to allow the packet through the firewall, DROP means to discard the packet without any feedback to the other end, and REJECT means to refuse the packet actively so that the remote end will know access is rejected to the said port.

The default table of iptables will add rules to the filter table and by default, each chain (INPUT, OUTPUT, and FORWARD) has a default policy set to ACCEPT. You can also create additional tables and direct packets to this table for later processing. It’s a good practice to set at least the FORWARD and INPUT policies to DROP:

admin@myhome:~$ sudo iptables -P INPUT DROP
admin@myhome:~$ sudo iptables -P FORWARD DROP

At the same time, we can allow all loopback interface access to ACCEPT:

admin@myhome:~$ sudo iptables -A INPUT -i lo -j ACCEPT

Additionally, all packets that are in the ESTABLISHED or RELATED state should be accepted; otherwise, we will lose all established connections or connections that are in the process of being established:

admin@myhome:~$ sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

To allow HTTP and HTTPS traffic, we can do the following:

admin@myhome:~$ sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
admin@myhome:~$ sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT

It’s a good idea to allow SSH traffic so that we can remotely log into this machine:

admin@myhome:~$ sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT

Here are some other more commonly used options you can use in iptables:

  • -A or --append: Appends a rule to the end of a chain
  • -I or --insert: Inserts a rule at a specific position in a chain
  • -D or --delete: Deletes a rule from a chain
  • -P or --policy: Sets the default policy for a chain
  • -j or --jump: Specifies the target for a rule
  • - s or --source: Matches packets based on the source IP address or network
  • -d or --destination: Matches packets based on the destination IP address or network
  • -p or --protocol: Matches packets based on the protocol (for example, TCP, UDP, or ICMP)
  • -i or --in-interface: Matches packets based on the incoming interface
  • -o or --out-interface: Matches packets based on the outgoing interface
  • --sport or --source-port: Matches packets based on the source port
  • --dport or --destination-port: Matches packets based on the destination port
  • -m or --match: Adds a match extension, which allows you to match packets based on additional criteria such as connection state, packet length, and more

There are many more features available when dealing with iptables, such as setting up NAT, interface bonding, TCP multipath, and many more. We will cover some of these in the Advanced topics section of this chapter.

nftables is a versatile tool for managing firewall configurations, offering a more streamlined and user-friendly approach compared to iptables, which is known for its verbosity and lack of built-in abstraction.

nftables employs a logical structure to organize rules that comprises tables, chains, rules, and verdicts. Tables serve as the top-level containers for rules and are instrumental in categorizing them. nftables offers several table types: ip, arp, ip6, bridge, inet, and netdev.

Within each table, there are chains, which help organize the rules further between categories: filter, route, and nat.

Each chain comprises individual rules, which serve as the criteria for matching packets and determining subsequent actions. A rule consists of both a matching condition and a verdict. For instance, a rule may match packets originating from a specific IP address and instruct the firewall to drop them, or it might match packets headed for a particular port and dictate acceptance.

Let’s set a default policy for incoming and forwarded packets to “drop” (stop processing the packet and don’t respond):

sudo nft add rule ip filter input drop
sudo nft add rule ip filter forward drop

Additionally, it’s common practice to allow all loopback interface access:

sudo nft add rule ip filter input iifname "lo" accept

To ensure established and related connections are permitted, you can run the following command:

sudo nft add rule ip filter input ct state established,related accept

You can run the following command to allow HTTP and HTTPS traffic:

sudo nft add rule ip filter input tcp dport {80, 443} accept

Finally, to enable SSH traffic for remote access, you can use the following command:

sudo nft add rule ip filter input tcp dport 22 accept

These are some frequently used options in nftables:

  • add: Appends a rule to the end of a chain
  • insert: Inserts a rule at a specific position in a chain
  • delete: Deletes a rule from a chain
  • chain: Specifies the target for a rule
  • ip saddr: Matches packets based on the source IP address or network
  • ip daddr: Matches packets based on the destination IP address or network
  • ip protocol: Matches packets based on the protocol (for example, TCP, UDP, or ICMP)
  • iifname: Matches packets based on the incoming interface
  • oifname: Matches packets based on the outgoing interface
  • tcp sport: Matches packets based on the source port
  • tcp dport: Matches packets based on the destination port
  • ct state: Adds a match extension, allowing packet matching based on additional criteria such as connection state, packet length, and more

nftables is set to be a replacement for iptables, but both are frequently used in modern systems. Let’s move on to other tools that are more abstract and by this, more user-friendly.

ufw is a frontend for the Linux iptables firewall and provides a simple and easy-to-use interface for managing it. ufw is designed to be easy to use, and it automatically sets up the iptables rules for you based on the configuration options you specify. It’s much more user-friendly and easier to use for more common tasks.

Before you start to use ufw, you will need to enable it so that all rules you add or remove will persist after system reboot. To do just that, run the following command:

admin@myhome:~$ sudo ufw enable

To open TCP ports 80 and 443 using ufw, you can use the following commands:

admin@myhome:~$ sudo ufw allow 80/tcp
admin@myhome:~$ sudo ufw allow 443/tcp

Alternatively, you can open both ports with one command:

admin@myhome:~$ sudo ufw allow 80,443/tcp

Once you have opened the ports, you can verify the changes by checking the status of ufw:

admin@myhome:~$ sudo ufw status

ufw is available on all major Linux distributions, including Debian Linux, Ubuntu Linux, Arch Linux, and Fedora Linux. However, in some cases, you will need to install it as it’s not part of the default system.

Another tool you can use to manage a firewall on Linux is firewalld. This is a program that was created to streamline the dynamic configuration of firewalls. One of the big features of firewalld is zones, which allow you to declare different levels of trust in interfaces and networks. It is included by default in many popular Linux distributions such as Red Hat Enterprise Linux, Fedora, CentOS, and Debian. Some other Linux distributions, such as Ubuntu, do not include firewalld by default but it can be installed and used on those systems as well.

To open TCP ports 80 and 443 using firewalld, you can use the firewall-cmd command-line tool. Here are the commands to open those ports:

admin@myhome:~$ sudo firewall-cmd --add-port=80/tcp --permanent
admin@myhome:~$ sudo firewall-cmd --add-port=443/tcp --permanent

You can open both ports with one command:

admin@myhome:~$ sudo firewall-cmd --add-port=80/tcp --add-port=443/tcp --permanent

After adding the ports, you need to reload the firewall for the changes to take effect:

admin@myhome:~$ sudo firewall-cmd --reload

You can also check the status of the ports using the following command:

admin@myhome:~$ sudo firewall-cmd --list-ports

Whatever tool you use to configure your firewall, it’s always a good idea to set default rule policies to DROP and only allow the traffic you expect to be handled by your system. There are some topics we don’t have much space for in this chapter, but it’s useful to know about possibilities when dealing with networking.

In this section, we will cover more advanced uses of network features. Some are very common (such as port forwarding or NAT), while some are less known. Let’s start with well-known features you will most likely encounter very often and then make our way down to more advanced and less-known features.

Network Address Translation (NAT) is a technique that involves mapping one network to another. The original reason for this was to simplify routing whole network segments without changing the address of every host in the packets.

Source NAT (SNAT) is a type of NAT that changes the source IP address of a packet. It is used to allow hosts on a private network to access the internet using a single public IP address.

Destination NAT (DNAT) is a type of NAT that changes the destination IP address of a packet. It is used to forward incoming traffic to a specific internal host based on the destination IP address. This is often used to allow external clients to access services running on internal hosts using a public IP address.

To set up NAT using iptables, you can use the following basic commands:

admin@myhome:~$ echo 1 > /proc/sys/net/ipv4/ip_forward

This will enable forwarding, which allows your machine to forward packets from one interface to another. This particular command updates the Linux kernel configuration on the fly by using the proc filesystem. You can achieve the same thing using the sysctl command:

admin@myhome:~$ sudo sysctl -w net.ipv4.ip_forward=1

To configure NAT for a local network such as 192.168.10.0/24, you will need to run the following commands as root user:

admin@myhome:~$ sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
admin@myhome:~$ sudo iptables -A FORWARD -i eth0 -o eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT
admin@myhome:~$ sudo iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT

Note that eth0 is the interface connected to the internet, and eth1 is the interface connected to the internal network.

The MASQUERADE target is used to implement NAT on a Linux router. When packets pass through the router and are sent out to the internet, the MASQUERADE target changes the source address of the packets to the router’s public IP address. This allows devices on the internal network to communicate with devices on the internet using the router’s public IP address as a source address, effectively hiding the internal network from the internet.

The MASQUERADE target is typically used in the POSTROUTING chain of the nat table and is commonly applied to the interface that is connected to the internet. It works only with dynamically assigned IP addresses (DHCP) and it’s mostly used in the case of a home router.

Port forwarding is a technique that’s used to direct network traffic from one network address and port to another. This can be useful for directing incoming traffic to a specific service or application running on a computer or network device. This helps with accessing services or applications on a private network from a remote location, or for making services or applications running on a private network accessible to the public.

Essentially, it’s another use of NAT as you will change the destination IP (and also port) of the packet that arrived on your machine.

To forward packets coming into TCP port 80 on the eth0 interface to internal IP 192.168.10.101 on port 8080 using iptables, you can use the following commands:

admin@myhome:~$ sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j DNAT --to-destination 192.168.10.101:8080
admin@myhome:~$ sudo iptables -t nat -A POSTROUTING -j MASQUERADE

We need MASQUERADE here as we want to hide the internal IP from the outside.

Network interface bonding is a feature in Linux that allows multiple network interfaces to be combined into a single bonded interface. This can provide increased bandwidth, redundancy, and failover capabilities. Several different bonding modes can be used, each with its benefits and drawbacks. Some common modes include active-backup, balance-rr, and 802.3ad. active-backup mode means that one of the two bonding interfaces is used as a backup when the primary device is down. balance-rr will use both interfaces simultaneously with a round-robin policy. The 802.3ad bonding creates aggregation groups that share the same technical specifications (speed and duplex settings). You can read more about modes and bonding settings on the official Linux kernel website: https://www.kernel.org/doc/Documentation/networking/bonding.txt

TCP multipath refers to using multiple paths to send and receive data between two points in a network, rather than just one. This can improve the reliability and performance of the network by allowing for failover if one of the paths becomes unavailable, and by allowing for load balancing across multiple paths. This can be achieved using various techniques, such as by using multiple interfaces on a device or by using multiple routing paths through the network.

Configuring multipath is quite easy with the use of the iproute2 package. To configure multipath on Linux using the eth0 and eth1 interfaces, you will need to run the following command:

admin@myhome:~$ ip route add default scope global nexthop via 192.168.1.1 dev eth0 nexthop via 192.168.2.1 dev eth1 weight 1

This command creates a new default route that uses both the eth0 and eth1 interfaces, with a weight of 1. The IP addresses used in this example (192.168.1.1 and 192.168.2.1) should be replaced with the actual IP addresses of the next hop routers on the eth0 and eth1 interfaces.

When running ip route show, you will see that a new multipath route is present. To start using it, you will need to change the default route:

admin@myhome:~$ ip route change default scope global nexthop via 192.168.1.1 dev eth0 nexthop via 192.168.2.1 dev eth1 weight 1

You can read more about multipath and how to use it at https://www.multipath-tcp.org/.

Border Gateway Protocol (BGP) is a routing protocol that’s used to distribute routing information within a single autonomous system (AS) or between multiple autonomous systems on the internet. BGP is used to build routing tables in routers in the internet backbone, as well as in enterprise networks.

BGP routers exchange routing information with their neighbors, which can be other BGP routers in the same AS or a different AS. When a BGP router receives routing information from its neighbors, it uses a set of rules and policies to decide which routes to add to its routing table and advertise to its neighbors. This allows BGP to support multiple paths to a destination, and to choose the best path based on various factors such as distance, cost, or preference.

BGP is considered a path vector protocol because it exchanges information about the complete path to a destination, rather than just the next hop. This allows BGP to support advanced features such as routing policy and traffic engineering.

There are several ways to use BGP on a Linux machine, depending on your specific use case and network environment.

BIRD is a routing daemon for Linux that supports BGP and other routing protocols. You can configure BIRD so that it acts as a BGP speaker and exchange routing information with other BGP routers. BIRD can be installed on most Linux distributions and can be configured using a simple configuration file.

Quagga is another open source routing software suite for Linux that supports BGP, OSPF, and other routing protocols. You can configure Quagga to act as a BGP speaker and exchange routing information with other BGP routers. Quagga can be installed on most Linux distributions and can be configured using a command-line interface or a configuration file.

Free Range Routing (FRR) is a routing software suite for Linux that supports BGP, OSPF, and other routing protocols; it’s a fork of Quagga.

You can read more about BGP and using BIRD in the following Linux Journal article: https://www.linuxjournal.com/content/linux-advanced-routing-tutorial.

In this chapter, we covered basic networking topics that you will probably encounter during your work in a DevOps team. This is a starting point and a base to help you understand network-related topics when dealing with services running inside a container. You will probably also want to expand your knowledge on this topic by reading about the IPv6 protocol, which is yet to replace IPv4.

In the next chapter, we will switch focus to a version control system (VCS) that is mainly used in modern organizations: Git.