Chapter 25

Securing Linux on a Network

In This Chapter
Managing network services
Controlling access to network services
Implementing firewalls

Setting up your Linux system on a network, especially a public network, creates a whole new set of challenges when it comes to security. The best way to secure your Linux system is to keep it off all networks. However, that is rarely a feasible option.

Entire books have been filled with information on how to go about securing a computer system on a network. Many organizations hire full-time computer security administrators to watch over their network-attached Linux systems. Therefore, think of this chapter as a brief introduction to securing Linux on a network.

A starting point for learning network security is to understand the OSI model. Every network operates in a series of layers, called the Open Systems Interconnection (OSI) reference model (see Figure 25.1). The model consists of seven layers, each representing the process of moving the data packets from a sender to/from a receiver.

The OSI model is a conceptual depiction. Many actual network protocols operate over several layers as opposed to moving in a straight line from one phase to the next. However, this model is very useful for security purposes. You can get an overall view of the various phases of network communications that must be secured for your Linux server.

Figure 25.1 The OSI reference model.

25.1

Auditing Network Services

Your Linux system's primary job is to offer services. A network service is any task that the computer performs requiring it to send and receive information over the network using some predefined set of rules. Routing e-mail is a network service and so is serving web pages.

A Linux server has the potential to provide thousands of services. Many of them are listed in the /etc/services file. Consider the following sections from the /etc/services file:

$ cat /etc/services
# /etc/services:
# $Id: services,v 1.53 2011/06/13 15:00:06 ovasik Exp $
#
# Network services, Internet style
# IANA services version: last updated 2011-06-10
#
# Note that it is presently the policy of IANA to assign
 a single well-known
# port number for both TCP and UDP; hence, most entries 
here have two entries
# even if the protocol doesn't support UDP operations.
# Updated from RFC 1700, "Assigned Numbers" (October 1994).
  Not all ports
# are included, only the more common ones.
#
# The latest IANA port assignments can be gotten from
#       http://www.iana.org/assignments/port-numbers
# The Well Known Ports are those from 0 through 1023.
# The Registered Ports are those from 1024 through 49151
# The Dynamic and/or Private Ports are those from 49152
 through 65535
#
# Each line describes one service, and is of the form:
#
# service-name  port/protocol  [aliases ...]   [# comment]
...
echo            7/tcp
echo            7/udp
discard         9/tcp           sink null
discard         9/udp           sink null
systat          11/tcp          users
systat          11/udp          users
daytime         13/tcp
daytime         13/udp
qotd            17/tcp          quote
qotd            17/udp          quote
...
chargen         19/tcp          ttytst source
chargen         19/udp          ttytst source
ftp-data        20/tcp
ftp-data        20/udp
# 21 is registered to ftp, but also used by fsp
ftp             21/tcp
...
http            80/tcp          www www-http    # WorldWideWeb HTTP
http            80/udp          www www-http    # HyperText Transfer Protocol
http            80/sctp                         # HyperText Transfer Protocol
kerberos        88/tcp          kerberos5 krb5  # Kerberos v5
kerberos        88/udp          kerberos5 krb5  # Kerberos v5
...
blp5            48129/udp               # Bloomberg locator
com-bardac-dw   48556/tcp               # com-bardac-dw
com-bardac-dw   48556/udp               # com-bardac-dw
iqobject        48619/tcp               # iqobject
iqobject        48619/udp               # iqobject

After the comment lines, you will notice three columns of information. The left column contains the name of each service. The middle column defines the port number and protocol type used for that service. The rightmost column contains an optional alias or list of aliases for the service.

Many Linux distributions come with unneeded network services running. An unnecessary service exposes your Linux system to malicious attacks. For example, if your Linux server is a print server, then it should only be offering printing services. It should not also offer Apache Web services. This would only unnecessarily expose your print server to any malicious attacks that take advantage of web service vulnerabilities.

Evaluating access to network services

One of the outcomes from the Security Lifecycle Planning phase is a “Needed Software and Services Checklist” (see Chapter 22, “Understanding Basic Linux Security,” for a description). Using this checklist, you need to review and remove services from a host standpoint (see Chapter 15, “Starting and Stopping Services”) and from a network standpoint.

Also, you must review how the needed network services are being “advertised.” If your Linux server needs to offer a network service like Secure Shell, only those authorized by your organization need to know it is there.

Using nmap to create a network services list

A wonderful tool to help you review your network services from a network standpoint is the nmap security scanner. The nmap utility is available in most Linux distribution repositories and has a web page full of information at http://nmap.org.

To install nmap on a Fedora or RHEL distribution, use the yum command (using root privileges), as shown in the example that follows.

# yum install nmap 
Loaded plugins: langpacks, presto, refresh-packagekit 
...
Setting up Install Process 
Resolving Dependencies 
--> Running transaction check 
---> Package nmap.i686 2:5.51-1.fc16 will be installed 
--> Finished Dependency Resolution 
Dependencies Resolved 
...
Install       1 Package 
...
Installing : 2:nmap-5.51-1.fc16.i686   1/1  
Installed: 
  nmap.i686 2:5.51-1.fc16 
Complete!

To install the nmap utility on an Ubuntu distribution, type sudo apt-get install nmap at the command line.

The nmap utility's full name is “Network Mapper.” It has a variety of uses for security audits and network exploration. The nmap's various port scans allow you to see what services are running on all the servers on your local network, and if they are advertising their availability.


Note
What is a port? A port or, more correctly, a network port, is a numeric value used by the TCP/IP network protocol to identify services that can be available on a system. For example, port 80 is the standard network port for the Apache web service. Think of a network port as a door to your Linux server. Each door is numbered. And behind every door is a particular service waiting to help whoever knocks on that door. For security reasons, if your server should not offer that service, you want the knocker to find a brick wall behind that service's door.

To audit your server's ports, the nmap utility offers several useful scan types. The nmap site has an entire manual on all the port scanning techniques you can use at http://nmap.org/book/man-port-scanning-techniques.html. Here are two basic port scans to get you started on your service auditing:

  • TCP Connect port scan—For this scan, nmap attempts a Transmission Control Protocol (TCP) to connect to ports on the server. If a port is listening, the connect attempt will succeed.
TCP is a network protocol used in the TCP/IP network protocol suite. Its primary purpose is to negotiate a connection using what is called a “three-way handshake.” TCP sends a synchronize packet (SYN) to a remote server, specifying a specific port number in the packet. The remote server receives the SYN and replies with an acknowledgment packet (SYN-ACK) to the originating computer. The original server then acknowledges (ACK) the response and a TCP connection is officially established. This three-way handshake is often called a SYN-SYN-ACK or SYN, SYN-ACK, ACK.
If you select a TCP Connect port scan, the nmap utility uses this three-way handshake to do a little investigative activity on a remote server. Any services that use the TCP protocol will respond to the scan.
  • UDP port scan—For this scan, nmap sends a UDP packet to every port on the system being scanned. UDP is another popular protocol in the TCP/IP network protocol suite. If the port is listening and has a service that uses the UDP protocol, it responds to the scan.

Tip
Keep in mind that Free and Open Source Software (FOSS) utilities are also available to those with malicious intent. While you are doing these nmap scans, realize that the remote scan results you see for your Linux server are the same scan results others will see. This will help you evaluate your system's security settings in terms of how much information is being given out to port scans.

When you run the nmap utility, it will provide a handy little report with information on the system you are scanning and the ports it sees. The ports are given a “state” status. nmap reports six possible port states:

  • open—This is the most dangerous state an nmap scan can report for a port. An open port indicates that a server has a service handling requests on this port. Think of it a sign on the door, “Come on in! We are here to help you.”
  • closed—This is a better state than open. A closed port is accessible but there is no service waiting on the other side of this door. However, the scan status still indicates that there is a Linux server at this particular IP address.
  • filtered—This is the best state for a port. It cannot be determined if the port is open or even if a Linux server is actually at the scanned IP address. A malicious scanner would gain little information. It typically takes a firewall (covered in the “Working with Firewalls” section later in this chapter) to get this nmap reported status on a port.
  • unfiltered—The nmap scan sees the port but cannot determine if the port is open or closed.
  • open|filtered—The nmap scan sees the port but cannot determine if the port is open or filtered.
  • closed|filtered—The nmap scan sees the port but cannot determine if the port is closed or filtered.

To help you better understand how to use the nmap utility, review the following example. For the purposes of building a network services list, the example nmap scans are conducted on a Fedora system. The first scan is a TCP Connect scan from the command line, using the loop back address, 127.0.0.1.

# nmap -sT 127.0.0.1
Starting Nmap 5.51 ( http://nmap.org ) at 2015-03-22 10:33 EDT
Nmap scan report for localhost.localdomain (127.0.0.1)
Host is up (0.016s latency).
Not shown: 998 closed ports
PORT    STATE SERVICE
25/tcp  open  smtp
631/tcp open  ipp
Nmap done: 1 IP address (1 host up) scanned in 1.34 seconds

The TCP Connect nmap scan reports that two TCP ports are open and have services listening at the door:

  • Simple Mail Transfer Protocol (SMTP) is listening at port 25.
  • Internet Printing Protocol (IPP) is listening at port 631.

The next nmap scan is an UDP scan on the Fedora system's loopback address.

# nmap -sU 127.0.0.1
Starting Nmap 5.51 ( http://nmap.org ) at 2015-03-22 10:36 EDT
Nmap scan report for localhost.localdomain (127.0.0.1)
Host is up (0.00048s latency).
Not shown: 997 closed ports
PORT     STATE         SERVICE
68/udp   open|filtered dhcpc
631/udp  open|filtered ipp
Nmap done: 1 IP address (1 host up) scanned in 2.24 seconds

The UDP nmap scan reports that two UDP ports are open and have services listening at the door:

  • Dynamic Host Control Protocol client (dhcpc) is listening at port 68.
  • Internet Printing Protocol (ipp) is listening at port 631.

Notice port 631's IPP is listed under both nmap's TCP Connect scan and the UDP scan because the IPP protocol used both the TCP and the UDP protocol and thus is listed in both scans.

Using these two simple nmap scans, TCP Connect and UDP, on your loopback address, you can build a list of the network services offered by your Linux server. Once you build your list, compare it to the “Needed Software and Services Checklist” you created in Chapter 22. Any network services that are not on the “Needed Software and Services Checklist” should be shut down on your Linux server (see Chapter 15).

Using nmap to audit your network services advertisements

For some Linux network services, you want a lot of attention. For other network services, you want attention only from a select authorized few. You need to know how your network services are being advertised. In other words, you want to know if malicious scanners can see your Linux server's network ports and the services they offer.

The idea here is to compare what your Linux server looks like from the inside versus what it looks like from the outside. If you determine that too many vulnerable network services are being advertised, you can take steps to remove them from view.


Tip
You may be tempted to skip the scans from inside your organization's internal network. Don't. Malicious activity often occurs from a company's own employees or by someone who has already penetrated external defenses.

Once again, the nmap utility will be a great help here. To get a proper view of how your Linux server's ports are seen, you will need to conduct scans from several locations. For example, a simple audit would set up scans to take place

  • On the Linux server itself.
  • From another server on the organization's same network.
  • From outside the organization's network.

In the following examples, part of a simple audit is conducted. The nmap utility is run on a Fedora system, designated as “Host-A.” Host-A is the Linux server whose network services are to be protected. Host-B is a Linux server, using the Linux Mint distribution, and is on the same network as Host-A.


Tip
Security settings on various network components, such as the server's firewall and the company's routers, should all be considered when conducting audit scans.

For this audit example, a scan is run from Host-A, using not the loopback address, but the actual IP address. First, the IP address for Host-A is determined using the ifconfig command. The IP address is 10.140.67.23.

# ifconfig
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:4 errors:0 dropped:0 overruns:0 frame:0
    TX packets:4 errors:0 dropped:0 overruns:0 carrier:0
    collisions:0 txqueuelen:0 
    RX bytes:240 (240.0 b)  TX bytes:240 (240.0 b)
p2p1  Link encap:Ethernet  HWaddr 08:00:27:E5:89:5A  
      inet addr:10.140.67.23
  Bcast:10.140.67.255  Mask:255.255.255.0
      inet6 addr: fe80::a00:27ff:fee5:895a/64 Scope:Link
      UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
      RX packets:81 errors:0 dropped:0 overruns:0 frame:0
      TX packets:102 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:1000 
      RX bytes:50015 (48.8 KiB)  TX bytes:14721 (14.3 KiB)

Now, using the Host-A IP address, an nmap TCP Connect scan is issued from Host-A. The nmap scan goes out to the network to conduct the scan. All ports are reported as having a status of closed.

# nmap -sT 10.140.67.23
Starting Nmap 5.51 ( http://nmap.org ) at 2015-03-22 10:33 EDT
Nmap scan report for 10.140.67.23
Host is up (0.010s latency).
All 1000 scanned ports on 10.140.67.23 are closed
Nmap done: 1 IP address (1 host up) scanned in 1.48 seconds

The nmap scan is moved from originating at Host-A to originating on a Host-B. Now, the TCP Connect scan is attempted on Host-A's ports from Host-B's command line.

$ nmap -sT 10.140.67.23
Starting Nmap 5.21 ( http://nmap.org ) at 2015-03-22 05:34 HADT
Note: Host seems down. If it is really up,
 but blocking our ping probes, try -PN
Nmap done: 1 IP address (0 hosts up) scanned in 0.11 seconds

Here, nmap gives a helpful hint. Host-A appears to be down, or it could just be blocking the probes. So, another nmap scan is attempted from Host-B, using nmap's advice of disabling the scan's ping probes via the -PN option.

$ nmap -sT -PN 10.140.67.23
Starting Nmap 5.21 ( http://nmap.org ) at 2015-03-22 05:55 HADT
Nmap scan report for 10.140.67.23
Host is up (0.0015s latency).
All 1000 scanned ports on 10.140.67.23 are filtered
Nmap done: 1 IP address (1 host up) scanned in 5.54 seconds

You can see that Host-A (10.140.67.23) is up and running and all its ports have a status of filtered. This means there is a firewall in place on Host-A. These scans from Host-B give you a better idea of what a malicious scanner may see when scanning your Linux server. In this example, the malicious scanner would not see much.


Note
If you are familiar with nmap, you know that the TCP SYN scan is the default scan nmap uses. The TCP SYN scan does an excellent job of probing a remote system in a stealth manner. Because you are probing your own system for security auditing purposes, it makes sense to use the more “heavy duty” nmap utility scans. If you still want to use the TCP SYN scan, the command is nmap -sS ip_address.

The services currently running on Host-A are not that “juicy.” So in the example that follows, another service, ssh, is started on Host-A using the systemctl command (see Chapter 15). This should give the nmap utility a more interesting target to look for.

# systemctl start sshd.service
# 
# systemctl status sshd.service
sshd.service - OpenSSH server daemon
  Loaded: loaded (/lib/systemd/system/sshd.service; disabled)
  Active: active (running) since
 Thu, 22 Mar 2015 10:57:24 -0400; 12s ago
Main PID: 1750 (sshd)
  CGroup: name=systemd:/system/sshd.service
    UnFigure1750 /usr/sbin/sshd -D
# 

Also, because Host-A's firewall is blocking the nmap scans from Host-B, it would be interesting to see what an nmap scan can report when the firewall is down. The example that follows shows the firewall being disabled on Host-A:

# systemctl stop iptables.service
# 
# systemctl status iptables.service
iptables.service - IPv4 firewall with iptables
  Loaded: loaded (/lib/systemd/system/iptables.service; enabled)
  Active: inactive (dead) since
 Thu, 22 Mar 2015 11:21:28 -0400; 8s ago
 Process: 1806 ExecStop=/usr/libexec/iptables.init stop
 (code=exited, status=0/SUCCESS)
 Process: 656 ExecStart=/usr/libexec/iptables.init start
 (code=exited, status=0/SUCCESS)
  CGroup: name=systemd:/system/iptables.service

With a new service running and Host-A's firewall lowered, the nmap scans should find something. In the following, nmap scans are run again from Host-B. This time the nmap utility shows the ssh service running on open port 22. Notice with the firewall down on Host-A, both nmap scans pick up much more information. This really demonstrates the importance of your Linux server's firewall.

$ nmap -sT 10.140.67.23
Starting Nmap 5.21 ( http://nmap.org ) at 2012-03-22 06:22 HADT
Nmap scan report for 10.140.67.23
Host is up (0.016s latency).
Not shown: 999 closed ports
PORT   STATE SERVICE
22/tcp open  ssh
Nmap done: 1 IP address (1 host up) scanned in 0.40 seconds
$ 
$ sudo nmap -sU 10.140.67.23
[sudo] password for johndoe: ***************
Starting Nmap 5.21 ( http://nmap.org ) at 2012-03-22 06:22 HADT
Nmap scan report for 10.140.67.23
Host is up (0.00072s latency).
Not shown: 997 closed ports
PORT     STATE         SERVICE
68/udp   open|filtered dhcpc
631/udp  open|filtered ipp
...
Nmap done: 1 IP address (1 host up) scanned in 1081.83 seconds

In order to conduct a thorough audit, be sure to include the UDP scan. Also, there are additional nmap scans that may be beneficial to your organization. Take a look at the nmap utility's website for additional suggestions.


Caution
If you have been following along and lowered your server's firewall to conduct these nmap scans, be sure to raise it again!

You still need to implement controls for those services your Linux server should offer. One way to accomplish this is via a wrapper.

Controlling access to network services

Completely disabling an unused service is fine, but for needed network services, you must set up access control. This needed access control is accomplished, via the /etc/hosts.allow and /etc/hosts.deny files, for Linux systems that incorporate TCP Wrapper support.

If it has TCP Wrapper support, a network service will use libwrap. To check for libwrap, you can run the ldd command on the network service daemon. The following example shows the ssh daemon uses TCP Wrappers. If your Linux system's sshd does not use TCP Wrappers, then no output will be shown.

$ ldd /usr/sbin/sshd | grep libwrap
libwrap.so.0 => /lib/libwrap.so.0 (0x0012f000)

When a network service that incorporates TCP Wrapper support is requested, the hosts.allow and hosts.deny files are scanned and checked for an entry that matches the address of the remote system making the request. The following steps occur when a remote system requests access to a TCP Wrapper–supported service:

1. The hosts.allow file is checked.
  • If the remote system's address is listed:
    • Access is allowed.
    • No further TCP Wrapper checks are made.
  • If the remote system's address is not listed, the TCP Wrapper check process continues on to the hosts.deny file.
2. The hosts.deny file is checked.
  • If the remote system's address is listed, access is denied.
  • If the remote system's address is not listed, access is allowed.

The order in which the hosts files are evaluated is important. For example, you cannot deny access to a host in the hosts.deny file that has already been given access in the hosts.allow file.

Listing every single address that may try to connect to your computer is not necessary. The hosts.allow and hosts.deny files enable you to specify entire subnets and groups of addresses. You can even use the keyword ALL to specify all possible IP addresses. Also, you can restrict specific entries in these files so they apply only to specific network services. Consider the following example of a typical pair of hosts.allow and hosts.deny files.

# cat /etc/hosts.allow
# hosts.allow This file describes the names of the hosts that are
#          allowed to use the local INET services, as decided
#          by the '/usr/sbin/tcpd' server.
#
sshd: 199.170.177.
vsftpd: ALL
# 
# cat /etc/hosts.deny
# hosts.deny This file describes names of the hosts which are
#          *not* allowed to use the local INET services, as
#          decided by the '/usr/sbin/tcpd' server.
#
ALL: ALL

In the hosts files, lines beginning with a # character are comments and are ignored. Other lines consist of a comma-separated list of service names followed by a colon (:) character and then a comma-separated list of client addresses to check. In this context, a client is any computer that attempts to access a network service on your system.

The preceding example is a rather restrictive configuration. The line:

sshd: 199.170.177.

in the hosts.allow file, allows connections to the sshd services from certain remote systems. The line:

vsftpd: ALL

allows all remote systems to connect to the FTP service, vsftpd. However, if the remote system is not requesting a connection to the sshd or vsftpd, it will be denied access by the line in the hosts.deny file:

ALL: ALL

A client entry can be a numeric IP address (such as 199.170.177.25) or a hostname (such as jukebox.linuxtoys.net). Often a wildcard variation is used that specifies an entire range of addresses. Notice in the example host.allow file, the sshd entry's allowed IP address is 199.170.177. This will match any IP address that begins with that string, such as 199.170.177.25. The ALL wildcard used in the hosts.deny file specifies that all remote systems reaching this file, requesting any TCP Wrapper–supported network services, will be denied.


Note
The ALL wildcard was also used in the example hosts.allow file for the vsftpd service, telling TCP Wrapper to permit absolutely any host to connect to the FTP service on the Linux system. This is appropriate for running an anonymous FTP server that anyone on the Internet can access. If you are not running an anonymous FTP site, you might not want to use the ALL flag here.

A good general rule is to make your hosts.deny file as restrictive as possible and then explicitly enable only those services that you really need. Grant access only to those systems that really need access according to your organization's Access Control Matrix (see Chapter 22).

Along with TCP Wrappers, firewalls control access to your Linux system's ports as well. In fact, firewalls do much more than just protect network services.

Working with Firewalls

A firewall in a building is a fireproof wall, which prevents the spread of fire through the building. A firewall for a computer does not prevent the spread of fire, but instead blocks the transmission of malicious or unwanted data into and out of a computer system or network. For example, a firewall can block malicious scans from your Linux server ports. A firewall can also allow desired software upgrades to download to the same server.

Understanding firewalls

While you may tend to think of a firewall as a complete barrier, a firewall is really just a filter that checks each network packet or application request coming into or out of a computer system or network.


Note
What is a network packet? A network packet is data that has been broken up into transmittable chunks. The chunks or packets have additional data added on to them as they traverse down the OSI model. One of the purposes of this additional data is to ensure the packet's safe and intact arrival at its destination. The additional data is stripped off of the packet as it traverses back up the OSI model at its destination.

Firewalls can be placed into different categories, depending upon their function. Each category has an important place in securing your server and network.

  • A firewall is either network- or host-based. A network-based firewall is one that is protecting the entire network or subnet. An example of a network firewall is in your workplace, where the network should be protected by a screening router's firewall.
A host-based firewall is one that is running on and protecting an individual host or server. You most likely have a firewall on your PC at home. This is a host-based firewall. Another example of a host-based firewall is the firestarter application. You can learn more about firestarter at http://www.fs-security.com.
  • A firewall is either a hardware or a software firewall. Firewalls can be located on network devices, such as routers. Their filters are configured in the router's firmware. In your home, your Internet service provider (ISP) may provide a DSL or cable modem to gain access to the Internet. The modem contains firewall firmware and is considered a hardware firewall.
Firewalls can be located on a computer system as an application. The application allows filtering rules to be set, which filter the incoming traffic. This is an example of a software firewall. A software firewall is also called a rule-based firewall.
  • A firewall is either a network- or application-layer filter. A firewall that examines individual network packets is also called a packet filter. A network-layer firewall allows only certain packets into and out of the system. It operates on the lower layers of the OSI reference model.
An application-layer firewall filters at the higher layers of the OSI reference model. This firewall will only allow certain applications access to/from the system.

You can see how these firewall categories overlap. The best firewall setup is a combination of all the categories. As with many security practices, the more layers you have, the harder it is for malicious activity to penetrate.

Implementing firewalls

On a Linux system, the firewall is a host-based, network-layer, software firewall managed by the iptables utility. With iptables, you can create a series of rules for every network packet coming through your Linux server. You can fine-tune the rules to allow network traffic from one location but not from another. These rules essentially make up a network access control list for your Linux server.


Tip
The iptables utility manages the Linux firewall, called netfilter. Thus, you will often see the Linux firewall referred to as netfilter/iptables.

Understanding the iptables utility

Before you start changing the firewall rules via the iptables utility, you need to understand netfilter/iptables basics, which include the following:

  • Tables
  • Chains
  • Policies
  • Rules

Each of these basics is critical to setting up and managing your Linux server firewall properly.

netfilter/iptables tables

The iptables firewall has the ability to do more than just low-level packet filtering. It defines what type of firewall functionality is taking place. There are four tables in the iptables utility, with an additional table added by SELinux. The tables offer the following functionalities:

  • filter—The filter table is the packet filtering feature of the firewall. In this table, access control decisions are made for packets traveling to, from and through your Linux system.
  • nat—The nat table is used for Network Address Translation (NAT). Firewalls can be set up for NAT, which is a different security feature than packet filtering.
  • mangle—As you suspect, packets are mangled (modified) according to the rules in the mangle table. Mangling packets is used in Network Address Translation.
  • raw—The raw table is used to exempt certain network packets from something called “connection tracking.” This feature is important when you are using Network Address Translation and Virtualization on your Linux server.
  • security—This table is available only on Linux distributions which have SELinux (see Chapter 24, “Enhancing Linux Security with SELinux”). The security table is used to filter network packets using MAC rules (see Chapter 22). This table is used with the filter table. The security table rules are applied only after the rules in the filter table are applied. This way the MAC rules are applied only after the DAC rules (see Chapter 22) are applied, which is consistent with SELinux implementation.

Of all the tables listed, three focus on Network Address Translation. Therefore, the filter table is the primary table to focus on for basic firewall packet filtering.

netfilter/iptables chains

The netfilter/iptables firewall categorizes network packets into categories, called chains. There are five chains (categories) that a network packet can be designated as:

  • INPUT—Network packets coming into the Linux server.
  • FORWARD—Network packets coming into the Linux server that are to be routed elsewhere.
  • OUTPUT—Network packets coming out of the Linux server.
  • PREROUTING—Used by NAT, for modifying network packets when they come into the Linux server.
  • POSTROUTING—Used by NAT, for modifying network packets before they come out of the Linux server.

Which netfilter/iptables table you choose to work with will determine what chains are available for categorizing network packets. Table 25.1 shows what chains are available for each table.

Table 25.1 Chains Available for Each netfilter/iptables Table

Table Chains Available
filter INPUT, FORWARD, OUTPUT
nat PREROUTING, OUTPUT, POSTROUTING
mangle INPUT, FORWARD, PREROUTING, OUTPUT, POSTROUTING
raw PREROUTING, OUTPUT
security INPUT, FORWARD, OUTPUT

Once a network packet is categorized into a specific chain, iptables can determine what policies or rules apply to that particular packet.

netfilter/iptables rules, policies, and targets

For each network packet, a rule can be set up defining what to do with that individual packet. Network packets can be identified many ways by the netfilter/iptables firewall. A few of these ways include:

  • Source IP address
  • Destination IP address
  • Network protocol
  • Inbound port
  • Outbound port
  • Network state

If no rule exists for a particular packet, then the overall policy is used. Each packet category or chain has a default policy.

Once a network packet matches a particular rule or falls to the default policy, then action on the packet can occur. The action taken depends upon what iptable target is set. A couple of actions (targets) that can be taken are:

  • ACCEPT—Network packet is accepted into the server.
  • REJECT—Network packet is dropped and not allowed into the server. A rejection message is sent.
  • DROP—Network packet is dropped and not allowed into the server. No rejection message is sent.

While REJECT gives a rejection message, DROP is quiet. You may consider using REJECT for internal employees, who should be told that you are rejecting their outbound network traffic and why. Consider using DROP for inbound traffic so that any malicious personnel are unaware that their traffic is being blocked.


Tip
There are a couple of additional more sophisticated targets for iptables, such as QUEUE. You can find out more about these targets via the man iptables command.

In Figure 25.1, an incoming network packet is followed through the netfilter/iptables firewall's filter table. In this example, no specific rules have been set for this incoming packet, so the policy's target, ACCEPT is used.

Figure 25.2 An iptables filter table example

25.1

The iptables utility implements a software firewall using the filter table via policies and rules. Now that you have a general understanding of the software firewall implementation, you can begin to dig deeper into the specific commands for implementing the firewall via the iptables utility.

Using the iptables utility

Your Linux server should come with the firewall up and running. However, it's a good idea to check and see if it really is enabled. Before you check, you first must understand that the netfilter/iptables firewall services are slightly different depending upon the Linux distribution:

  • RHEL netfilter/iptables firewall—The firewall interface service running on this distribution is iptables. To see if this firewall service is running, type service iptables status at the command line.
    • To enable the firewall, type service iptables start at the command line.
    • To disable the firewall, type service iptables stop at the command line.
  • Fedora netfilter/iptables firewall—The firewall interface service running on this distribution is iptables. To see if this firewall service is running, type systemctl status iptables.service at the command line.
    • To enable the firewall, type systemctl start iptables.service at the command line.
    • To disable the firewall, type systemctl stop iptables.service at the command line.
  • Ubuntu netfilter/iptables firewall—The firewall interface service running on this distribution is ufw. To see if the firewall service is running, type sudo ufw status at the command line. The ufw service is an interface to the iptables utility that does not run as a service on Ubuntu. You can use ufw commands to manipulate firewall rules. However, all the iptables utility commands are still valid for Ubuntu:
    • To enable the firewall, type sudo ufw enable at the command line.
    • To disable the firewall, type sudo ufw disable at the command line.

Thankfully, after you have checked the status and enabled or disabled the netfilter/iptables firewall, the differences between the distributions end.

To see what policies and rules are currently in place for the filter table, type iptables -t filter -L at the command line. In the example that follows, this command is entered on a Linux Mint system. Note that the sudo command is needed because the iptables utility requires root privileges.

$ sudo iptables -t filter -L
 [sudo] password for johndoe: ***************
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
Chain FORWARD (policy ACCEPT)
target     prot opt source               destination
Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

There are several things to notice in the preceding example. All the chains available to the filter table are listed: INPUT, FORWARD, and OUTPUT. For each chain, no rules are defined. Therefore, the chain's default policies will be applied to all the network packets. Currently all the default policies are set to ACCEPT. All network packets are allowed in, through, and out. A firewall in this state is essentially disabled.


Tip
If your Linux server is dealing with IP v6 network packets, you can use the ip6tables utility to manage your firewall for IPv6 addresses. The ip6tables utility is nearly identical to the iptables utility. For more information, type man ip6tables at the command line.

Modifying iptables policies and rules

Before you begin to modify the netfilter/iptables firewall, it is helpful to understand a few command options. Below are a few options for modifying the firewall:

  • -t table
The iptables command listed along with this switch is applied to the table. By default, the filter table is used. Example:
iptables -t filter -P OUTPUT DROP
  • -P chain target
Sets the overall policy for a particular chain. The rules in the chain are checked for matches. If no match occurs, then the chain's listed target is used. Example:
iptables -P INPUT ACCEPT
  • -A chain
Sets a rule, called an “appended rule,” which will be an exception to the overall policy for the chain designated. Example:
iptables -A OUTPUT -d 10.140.67.25 -j REJECT
  • -I rule# chain
Inserts an appended rule into a specific location, designated by the rule#, in the appended rule list for the chain designated. Example:
iptables -I 5 INPUT -s 10.140.67.23 -j DROP
  • -D chain rule#
Deletes a particular rule, designated by the rule#, from the chain designated. Example:
iptables -D INPUT 5
  • -j target
If the criteria in the rule are met, the firewall should jump to this designated target for processing. Example:
iptables -A INPUT -s 10.140.67.25 -j DROP
  • -d IP address
Assigns the rule listed to apply to the designated destination IP address. Example:
iptables -A OUTPUT -d 10.140.67.25 -j REJECT
  • -s IP address
Assigns the rule listed to apply to the designated source IP address. Example:
iptables -A INPUT -s 10.140.67.24 -j ACCEPT
  • -p protocol
Assigns the rule listed to apply to the protocol designated. Example:
iptables -A INPUT -p icmp -j DROP
  • --dport port#
Assigns the rule listed to apply to certain protocol packets coming into the designated port#. Example:
iptables -A INPUT -p tcp --dport 22 -j DROP
  • --sport port#
Assigns the rule listed to apply to certain protocol packets going out of the designated port#. Example:
iptables -A OUTPUT -p tcp --sport 22 -j ACCEPT
  • -m state --state network state
Assigns the rule listed to apply to the designated network state(s). Example:
iptables -A INPUT -m state --state RELATED,ESTABLISH -j ACCEPT

To see how the iptables options work, consider the following example. You have a Linux server (Host-A) at IP address 10.140.67.23. There are two other Linux servers on your network. One is Host-B at IP address 10.140.67.22 and the other is Host-C at IP address 10.140.67.25. Your goal is to:

  • Allow Host-C full access to Host-A
  • Block remote login connections using ssh from Host-B to Host-A

Setting a policy of Drop. The following code shows the current state of Host-A's firewall. The firewall is wide open with no restrictions implemented. No rules are set and the policies are all set to ACCEPT.

# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
Chain FORWARD (policy ACCEPT)
target     prot opt source               destination
Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

First, what would happen if the INPUT policy was changed from ACCEPT to DROP? Would that reach the goal? Take a look at what happens when this is tried. Remember that if no rules are listed for an incoming packet, then the chain's policy is followed. This change is made to Host-A's firewall in the example that follows.

# iptables -P INPUT DROP
# 
# iptables -L
Chain INPUT (policy DROP)
target     prot opt source               destination
Chain FORWARD (policy ACCEPT)
target     prot opt source               destination
Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Tip
For policies, you cannot set the target to REJECT. It will fail and you will receive the message, “iptables: Bad policy name.” Use DROP as your policy instead.

Host-B will attempt to try to ping Host-A and then attempt a ssh connection as shown in the example that follows. As you can see, both attempts fail. Because ping commands are blocked, this does not meet the objective to block only remote login connections using ssh from Host-B.

$ ping -c 2 10.140.67.23
PING 10.140.67.23 (10.140.67.23) 56(84) bytes of data.
--- 10.140.67.23 ping statistics ---
2 packets transmitted, 0 received, 100% packet loss, time 1007ms
$ 
$ ssh [email protected]
ssh: connect to host 10.140.67.23 port 22: Connection timed out

When Host-C attempts to ping Host-A and make an ssh connection, both attempts fail. Thus, it is confirmed that the firewall setting, INPUT policy equals DROP, is not what is needed to reach the goal.

$ ping -c 2 10.140.67.23
PING 10.140.67.23 (10.140.67.23) 56(84) bytes of data.
--- 10.140.67.23 ping statistics ---
2 packets transmitted, 0 received, 100% packet loss, time 1008ms
$ 
$ ssh [email protected]
ssh: connect to host 10.140.67.23 port 22: Connection timed out

Blocking a source IP address. What if instead only Host-B's IP address were blocked? That would allow Host-C to reach Host-A. Would this setting reach the desired goal?

In the example that follows, the policy of DROP must first be changed to ALLOW in Host-A's iptables. After that, a specific rule must be appended to block network packets from Host-B's IP address, 10.140.67.22, alone.

# iptables -P INPUT ACCEPT
# 
# iptables -A INPUT -s 10.140.67.22 -j DROP
# 
# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
DROP       all  --  10.140.67.22             anywhere
Chain FORWARD (policy ACCEPT)
target     prot opt source               destination
Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Host-C can now successfully ping and ssh into Host-A, meeting one of the set goals.

$ ping -c 2 10.140.67.23
PING 10.140.67.23 (10.140.67.23) 56(84) bytes of data.
64 bytes from 10.140.67.23: icmp_req=1 ttl=64 time=11.7 ms
64 bytes from 10.140.67.23: icmp_req=2 ttl=64 time=0.000 ms
--- 10.140.67.23 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1008ms
rtt min/avg/max/mdev = 0.000/5.824/11.648/5.824 ms
$ ssh [email protected]
[email protected]'s password: 

However, Host-B can neither ping nor ssh into Host-A. Thus, the appended rule is not quite what is needed to reach the entire goal.

$ ping -c 2 10.140.67.23
PING 10.140.67.23 (10.140.67.23) 56(84) bytes of data.
--- 10.140.67.23 ping statistics ---
2 packets transmitted, 0 received, 100% packet loss, time 1007ms
$ ssh [email protected]
ssh: connect to host 10.140.67.23 port 22: Connection timed out

Blocking a protocol and port. What if, instead of blocking Host-B's IP address entirely, only connections to the ssh port (port 22) from Host-B's IP address were blocked? Would that reach the goal of allowing Host-C full access to Host-A, and only blocking ssh connections from Host-B?

In the example that follows, the iptables rules for Host-A are modified to try blocking Host-B's IP address from port 22. Note that the --dport option must accompany a particular protocol, for example, -p tcp. Before the new rule is added, the rule from the previous example must be deleted using the -D option. Otherwise, the rule from the previous example would be used by the netfilter/iptables firewall for packets from 10.140.67.22 (Host-B).

# iptables -D INPUT 1
# 
# iptables -A INPUT -s 10.140.67.22 -p tcp --dport 22 -j DROP
# 
# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source      destination
DROP       tcp  --  10.140.67.22    anywhere     tcp dpt:ssh
Chain FORWARD (policy ACCEPT)
target     prot opt source      destination
Chain OUTPUT (policy ACCEPT)
target     prot opt source      destination

First, the new iptables rule is tested from Host-C to ensure both ping attempts and ssh connections remain unaffected. It works successfully.

$ ping -c 2 10.140.67.23
PING 10.140.67.23 (10.140.67.23) 56(84) bytes of data.
64 bytes from 10.140.67.23: icmp_req=1 ttl=64 time=1.04 ms
64 bytes from 10.140.67.23: icmp_req=2 ttl=64 time=0.740 ms
--- 10.140.67.23 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1000ms
rtt min/avg/max/mdev = 0.740/0.892/1.045/0.155 ms
$ ssh [email protected]
[email protected]'s password: 

Next, the new iptables rule is tested from Host-B to ensure ping works and ssh connections are blocked. It also works successfully!

$ ping -c 2 10.140.67.23
PING 10.140.67.23 (10.140.67.23) 56(84) bytes of data.
64 bytes from 10.140.67.23: icmp_req=1 ttl=64 time=1.10 ms
64 bytes from 10.140.67.23: icmp_req=2 ttl=64 time=0.781 ms
--- 10.140.67.23 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 0.781/0.942/1.104/0.164 ms
$ ssh [email protected]
ssh: connect to host 10.140.67.23 port 22: Connection timed out

Once again, your organization's Access Control Matrix (see Chapter 22) will help you in creating the necessary rules for the netfilter/iptables firewall on your Linux server. And each modification should be tested in a test or virtual environment before implementing it in your production Linux systems firewall.

Saving an iptables configuration

Once you have done all the hard work of creating your Linux server's firewall configuration policies and rules, you will want to save them. All modifications must be saved to the iptables configuration file, /etc/sysconfig/iptables, because this is the file used at system boot to load the firewall.

In the example that follows, the modifications made earlier are still in the firewall. Before they are saved to the configuration file, a backup copy of the original file is made. This is always a good idea. The modifications are then saved using the iptables-save command. Notice that the output is directed into the /etc/sysconfig/iptables file using a redirection symbol, > (see the last line of code in the example).

# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source     destination
DROP       tcp  --  10.140.67.22   anywhere  tcp dpt:ssh
Chain FORWARD (policy ACCEPT)
target     prot opt source     destination
Chain OUTPUT (policy ACCEPT)
target     prot opt source     destination
# cp /etc/sysconfig/iptables/etc/sysconfig/iptables.bck
# 
# iptables-save > /etc/sysconfig/iptables
# 

You can also remove all the modifications for the current netfilter/iptables firewall by using the flush option, iptables -F. Once this is completed, all the rules (but not the policies) are removed, as shown in the code that follows. This is useful for testing out individual policies and rules.

# iptables -F
# 
# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source     destination
Chain FORWARD (policy ACCEPT)
target     prot opt source     destination
Chain OUTPUT (policy ACCEPT)
target     prot opt source     destination

A flush of the rules does not affect the iptables configuration file. To restore the firewall to its original condition, use the iptables-restore command. In the example that follows, the iptables configuration file is redirected into the restore command and the original DROP rule for 10.140.67.22 is restored.

# iptables-restore < /etc/sysconfig/iptables
# 
# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source     destination
DROP       tcp  --  10.140.67.22   anywhere   tcp dpt:ssh
Chain FORWARD (policy ACCEPT)
target     prot opt source     destination
Chain OUTPUT (policy ACCEPT)
target     prot opt source     destination

Note
For an Ubuntu system, saving and restoring your netfilter/iptables modifications are very similar. You can still use the iptables-save command to create an iptables configuration file from the current iptables setting and use iptables-restore to restore it. However, having a saved iptables configuration load on boot is a little more complicated. There is no /etc/sysconfig/iptables file. There are several options for loading a configuration file on system boot. See the Ubuntu community website at https://help.ubuntu.com/community/IptablesHowTo for the various options.

You can also save your netfilter/iptables firewall rules to create an audit report. Reviewing these rules periodically should be part of your organization's System Life Cycle Audit/Review phase.

Summary

Securing your Linux server is critical on a network. Inherently, a majority of the malicious attacks will originate from a network, especially the Internet. This chapter covered some of the basics, such as the OSI model, that you need in order to get started on this process.

Protecting your network services can be simplified once you determine and remove any unneeded network services. The nmap utility will help you here. Also, you can use nmap to audit your Linux server's advertising of network services. These audits will assist in determining what firewall modifications are needed.

For needed network services, access control must be implemented. TCP wrappers can assist in this activity. On a per service basis, access can be allowed or denied, fine-tuning access to each network service.

Also, the firewall on a Linux server provides access control. The netfilter/iptables firewall is a host-based, network-layer, software firewall. It is managed by the iptables and ip6tables utilities. With these utilities, a series of policies and rules can be created for every network packet coming through your Linux server. These policies and rules essentially make up an access control list for your Linux server network.

Thanks for choosing the Linux Bible to learn more about the Linux operating system. But don't stop here. Continue learning about Linux and consider giving back as well. There are several Linux and free and open-source software (FOSS) communities online and around town, where you can share your new-found knowledge and stay in touch with advances in Linux. Enjoy the rest of your journey, and welcome to Linux!

Exercises

Refer to the material in this chapter to complete the tasks that follow. If you are stuck, solutions to the tasks are shown in Appendix B (although in Linux, there are often multiple ways to complete a task). Try each of the exercises before referring to the answers. These tasks assume you are running a Fedora or Red Hat Enterprise Linux system (although some tasks will work on other Linux systems as well).

1. Install the Network Mapper utility on your local Linux system.
2. Run a TCP Connect scan on your local loopback address. What ports have a service running on them?
3. Run a UDP Connect scan on your Linux system from a remote system.
4. Check to see if the ssh daemon on your Linux system uses TCP Wrapper support.
5. Using the TCP Wrapper files, allow access to the ssh tools on your Linux system from a designated remote system. Deny all other access.
6. Determine your Linux system's current netfilter/iptables firewall policies and rules.
7. Flush your Linux system's current firewall rules and then restore them.
8. For your Linux system's firewall, set a filter table policy for the input chain to reject.
9. Change your Linux system firewall's filter table policy back to accept for the input chain and then add a rule to drop all network packets from the IP address, 10.140.67.23.
10. Without flushing or restoring your Linux system firewall's rules, remove the rule you added above.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset