Linux Bible 9th Ed (2015)
Part V. Learning Linux Security Techniques
Chapter 25. Securing Linux on a Network
IN THIS CHAPTER
1. Managing network services
2. Controlling access to network services
3. 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 secure 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.
Auditing Network Services
Most Linux systems used for large enterprises are configured as servers that, as the name implies, offer services to remote clients over a network. 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 email is a network service, as 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.55 2013/04/14 ovasik Exp $
#
# Network services, Internet style
# IANA services version: last updated 2013-04-10
#
# Note that it is presently the policy of IANA to assign ...
# 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, 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 right 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 with nmap
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 -y
Loaded plugins: langpacks, product-id, subscription-manager
...
Resolving Dependencies
--> Running transaction check
---> Package nmap.x86_64 2:6.40-4.el7 will be installed
--> Finished Dependency Resolution
Dependencies Resolved
...Installing:
nmap x86_64 2:6.47-1.fc21y rhel-7-server-rpms 4.0 M
...
Installed: nmap-6.47-1.fc21
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. Using nmap to do various port scans allows you to see what services are running on all the servers on your local network and whether they are advertising their availability.
NOTE
What is a port? Ports or, more correctly, network ports, are numeric values used by the TCP and UDP network protocols as access points to services on a system. Standard port numbers are assigned to services so a service knows to listen on a particular port number and a client knows to request the service on that port number.
For example, port 80 is the standard network port for unencrypted (HTTP) traffic to the Apache web service. So, if you ask for www.example.com from your Web browser, the browser assumes you mean to use TCP port 80 on the server that offers that Web content. 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.
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 to connect to ports using the Transmission Control Protocol (TCP) on the server. If a port is listening, the connect attempt succeeds.
TCP is a network protocol used in the TCP/IP network protocol suite. TCP is a connection-oriented protocol. Its primary purpose is to negotiate and initiate 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. Unlike TCP, however, UDP is a connectionless protocol. 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. Keep in mind that you should use tools like nmap only on your own systems, because scanning ports on other people's computers can give the impression that you are trying to break in.
When you run the nmap utility, it provides 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 as a sign on the door, “Come on in! We are here to help you.” Of course, if you are offering a public service, you want the port to be open.
· closed—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 to secure a port that you don't want anyone to access. It cannot be determined if a Linux server is actually at the scanned IP address. It is possible that a service could be listening on a particular port, but the firewall is blocking access to that port, effectively preventing any access to the service through the particular network interface.
· 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 2016-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 on the localhost (127.0.0.1) for requests to these ports:
· Simple Mail Transfer Protocol (SMTP) is listening at TCP port 25.
· Internet Printing Protocol (IPP) is listening at TCP 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 2016-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 on those ports:
· Dynamic Host Control Protocol client (dhcpc) is listening at port 68.
· Internet Printing Protocol (ipp) is listening at port 631.
Notice that 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.
Keep in mind that port numbers are associated with a particular protocol (TCP or UDP) and a particular network interface. For example, if you have one network interface card (NIC) on a computer that faces the Internet and another that faces a private network, you may want to offer a private service (like the CUPS service for printing) to the NIC on your private network. But you may want to filter that port (631) on the NIC that faces the Internet.
Using nmap to audit your network services advertisements
You probably want lots of people to visit your Web site (httpd service). You probably don't want everyone on the Internet able to access your SMB file shares (smb service). To make sure you are properly separating access to those two types of services, you want to be able to check what a malicious scanner can see of the services available on your public-facing network interfaces.
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 some network services are accessible that you intended to keep private, you can take steps to block access to them from external interfaces.
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.
Again, the nmap utility is a great help here. To get a proper view of how your Linux server's ports are seen, you need to conduct scans from several locations. For example, a simple audit would set up scans in these places:
· 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 2016-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 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 2016-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 stealthy 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.” 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 2016 10:57:24 -0400; 12s ago
Main PID: 1750 (sshd)
CGroup: name=systemd:/system/sshd.service
1750 /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 for a Fedora 21 or RHEL 7 system (for other systems, you probably need to disable the iptables service):
# systemctl stop firewalld.service
# systemctl status firewalld.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
# 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. 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: systemctl start firewalld.service.
You still need to implement controls for those services your Linux server should offer. One way to accomplish this is via TCP wrappers.
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 can be accomplished, via the /etc/hosts.allow and /etc/hosts.deny files, for selected services on Linux systems that incorporate TCP Wrapper support.
If it has TCP Wrapper support, a network service uses libwrap. To check for libwrap, you can run the ldd command on the network service daemon. The following example shows that the ssh daemon uses TCP Wrappers. If your Linux system's sshd does not use TCP Wrappers, then no output is 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 is 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 is199.170.177. This matches 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, are 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.
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 that prevents the spread of fire through the building. A firewall for a computer 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
Although 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. It's like putting a lettter inside an envelope at each stage as it moves down. 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 the packet as it traverses back up the OSI model at its destination (like taking off the outer envelope and handing the letter to the layer above).
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-based 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-layer filter 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 allows only 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.
Fedora, RHEL, and other Linux distributions have added the firewalld service on top of iptables, to provide a more dynamic way of managing firewall rules. The Firewall Configuration window (firewall-config command) provides an easy way to open ports on your firewall and do masquerading (routing private addresses to a public network) or port forwarding. The firewalld service can react to changes in conditions, which the static iptables service can't do as well on its own. By enabling access to a service, firewalld can also do things like load modules needed to allow access to a service.
TIP
The iptables utility manages the Linux firewall, called netfilter. Thus, you will often see the Linux firewall referred to as netfilter/iptables.
Starting with firewalld
The firewalld service may already be installed on your Linux system. If it's not, you can install the service and the associated graphical user interface, and then start the firewalld service as follows:
# yum install firewalld firewall-config
# systemctl start firewalld.service
# systemctl enable firewalld.service
To manage the firewalld service, you can start the Firewall Configuration window. Do this by typing:
# firewall-config &
Figure 25.1 shows an example of the Firewall Configuration window.
Figure 25.1 Firewall Configuration
If all you need to do is open some firewall ports to allow access to selected services, that's very easy to do from the Firewall Configuration window. With the public zone selected, just click the services you want to open. The port allowing access to that service is opened immediately (when you select the Runtime configuration) and opened permanently (when you select the Permanent configuration).
One nice feature of the Firewall Configuration window is that, when you select to allow access to a service, you do more than just open a port. For example, enabling the FTP service also causes connection tracking modules to be loaded that allow nonstandard ports to be accessed through the firewall when needed.
As mentioned earlier, underlying the firewalld service is the iptables facility. If you have a Linux system without the firewalld service (or with firewalld disabled), you can still use the iptables service. The next section describes how you can set iptables firewall rules manually and use the iptables service directly, without the firewalld service.
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 that 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 filtertable. 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, as follows:
· 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 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 |
After 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. These are a few of the ways:
· 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. After a network packet matches a particular rule or falls to the default policy, action on the packet can occur. The action taken depends upon what iptable target is set. Here are a couple of actions (targets) that can be taken:
· 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.
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 6 or earlier 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.
· RHEL 7 and recent Fedora systems netfilter/iptables firewall—The firewall interface service running on these distributions is firewalld. The iptables service is not run directly by default on these systems. To see if this firewall service is running, typesystemctl status firewalld.service at the command line.
· To enable the firewall, type systemctl start firewalld.service at the command line.
· To disable the firewall, type systemctl stop firewalld.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 -vnL at the command line. In the example that follows, this command is entered on a Linux Mint system.
# iptables -t filter -vnL
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)...
Note that on systems with firewalld enabled, there are many more iptables chains and rules listed by default than you might be used to on a system using iptables directly. This is done to offer more flexibility in building your firewalls by allowing your rules to be split into zones for different types of interfaces.
Only the first line of the iptables output is shown in the preceding example. That line shows that the INPUT chain's default policy is applied to all the network packets that don't match another rule. Currently, all the default INPUT, FORWARD and OUTPUT policies are set to ACCEPT. All network packets are allowed in, through, and out. A firewall in this state is essentially disabled until specific REJECT or DROP rules are added.
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 is 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 accomplish the following:
· 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 default policies of Host-A's firewall. In this example, the firewall is wide open with no restrictions implemented. No rules are set, and the policies are all set to ACCEPT.
# iptables -vnL
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? 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 -vnL
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 fails, and you receive the message “iptables: Bad policy name.” Use DROP as your policy instead.
Host-B attempts to ping Host-A and then attempts an 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 root@10.140.67.23
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 root@10.140.67.23
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 -vnL
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 root@10.140.67.23
root@10.140.67.23'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 root@10.140.67.23
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 sshconnections 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 -vnL
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 root@10.140.67.23
root@10.140.67.23's password:
Next, the new iptables rule is tested from Host-B to ensure that 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 root@10.140.67.23
ssh: connect to host 10.140.67.23 port 22: Connection timed out
Again, your organization's Access Control Matrix (see Chapter 22) helps 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 system's firewall.
Saving an iptables configuration
After 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 -vnL
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. After 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 -vnL
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 originalDROP rule for 10.140.67.22 is restored.
# iptables-restore < /etc/sysconfig/iptables
# iptables -vnL
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 athttps://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 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 after you determine and remove any unneeded network services. The nmap utility helps you here. Also, you can use nmap to audit your Linux server's advertising of network services. These audits 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.
Recent versions of Fedora and RHEL have added the firewalld service as a front-end to the iptables firewall facility that is built into the Linux kernel. Using the firewalld-config window, you can easily open ports in your firewall to allow access to selected services. The netfilter/iptables firewall facility 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.
At this point in the book, you should have a good grasp of what goes into setting up and securing Linux desktop and server systems. In the next two chapters, I'm going to help you extend that knowledge into cloud computing and virtualization.
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, you can often complete a task in multiple ways). 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 work on other Linux systems as well).
Please don't use a production system to try out the iptables commands in these exercises. Although the commands shown here do not permanently change your firewall (the old rules will return when the firewall service restarts), improperly modifying your firewall can result in unwanted access.
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.