Chapter 18
Overseeing Linux Firewalls

  • images Objective 3.5: Given a scenario, implement and configure Linux firewalls.

images A firewall in a building is a fireproof wall that helps to prevent fire from spreading throughout the structure. In computer security, firewalls prevent the spread of unwanted, unauthorized, or malicious network traffic.

Firewalls are implemented in different forms. You can provide layered security by using multiple firewall structures. A firewall is either a hardware device or software application, network-based or host-based, and a network-layer or application-layer filter. In this chapter, we’ll take a look at software application firewalls that are host-based and operate at the Network layer.

Providing Access Control

Firewalls provide access control to your system or network. An access control list (ACL) implemented within a firewall identifies which network packets are allowed in or out. This is often referred to as packet filtering.

images Don’t confuse a firewall ACL with Linux file and directory ACLs, which were covered in Chapter 15. Commands such as setfacl and getfacl are not associated with firewalls.

A firewall ACL identifies a network packet by reviewing its control information along with other network data. This may include the following information:

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

Once a network packet is identified, the firewall’s ACL rules also determine what happens to that packet. The rules typically include the following actions:

  • Accept
  • Reject
  • Drop
  • Log

It’s important to distinguish between reject and drop. A reject action typically includes a message sent back to the application sending the packet, whereas a drop action does not. By dropping the network packet, the Linux system does not provide any information to a potentially malicious outside attacker.

images

Firewall Logs

Logging firewall traffic is critical. Your organization’s requirements dictate the amount of data to track. If your company must comply with regulations, such as Health Insurance Portability and Accountability Act (HIPAA) or Payment Card Industry Data Security Standard (PCI DSS), the log data volume increases.

Besides compliance issues, firewall logs can be monitored, provide alerts, and/or take needed actions to protect a system. These logs help determine if an attack is taking place. Software utilities, such as Graylog’s open-source product (www.graylog.com), allow you to process firewall logs in real time.

Managing your firewall logs is a complex issue. A helpful publication, which can guide your organization’s requirements analysis and determine what appropriate steps to take, is the NIST Special Publication 800-92, Guide to Computer Security Log Management.

On Linux, the /etc/services file documents the different standard application services names and their corresponding port numbers and protocols as well as any aliases. This information is standardized by the Internet Assigned Numbers Authority (IANA). This service catalog is used by various utilities such as the netstat network tool, and firewall applications, such as UFW, to determine the appropriate port and protocol information for a particular service.

Each non-comment record in the /etc/services file uses the following syntax:

ServiceName PortNumber/ProtocolName [Aliases]

By default port numbers 1 through 1023 are privileged ports. Only a super user can run a service on a privileged port. Therefore, these designated ports help prevent malicious users from setting up fake services on them.

images The /etc/services file is not a configuration file. Most services have configuration files, which allow you to change their default port if desired. For example, the OpenSSH configuration file, /etc/ssh/sshd_config, contains the Port directive, which is set to 22 by default, and you can modify it, if needed.

Firewalls can operate in either a stateful or stateless manner. There are pros and cons to both technologies.

Stateless This technology is the older of the two. In this mode, the firewall focuses only on individual packets. The firewall views each packet’s control information and decides what to do with the packet based on the defined ACL rules. This simplicity makes stateless firewalls fast.

However, because a stateless firewall does not track information such as active network connections, network status, data flows, and traffic patterns, it is vulnerable to certain malicious activity. This includes network attacks that spread themselves among multiple packets. In addition, a stateless firewall’s ACL rules are static. If an administrator changes them, the firewall software typically must be restarted.

Stateful This technology is the younger of the two. While it also employs packet filtering, it does not treat packets as individuals, but instead as a team. It tracks active network connections, such as TCP and UDP, and keeps an eye on network status. A stateful firewall determines if packets have fragmented. Thus, it is not vulnerable to attacks that spread themselves among multiple packets.

Stateful firewalls keep network information in memory. For example, when a TCP connection’s first packet comes into a stateful firewall’s view, the firewall monitors the connection process and tracks its states, such as SYN-SENT, SYN-RECEIVED, and ESTABLISHED. Once the connection is made, the firewall creates a record in its memory-based connection table. It uses this record for tracking the network connection. Thus, instead of just using ACL rules for that connection’s packets, it employs the connection table as well. This allows it to make faster decisions for established connections’ individual packets.

While the memory table allows faster access for established connections, building the table’s record for new connections is slower. In addition, this makes the stateful firewall more vulnerable to DDoS attacks than stateless ones.

Looking at Firewall Technologies

Embedded in the Linux kernel is netfilter. This software provides code hooks into the kernel, which allow other packages to implement firewall technologies. From a functionality standpoint, think of netfilter as a network sniffer that is planted in the Linux kernel and offers up packet filtering services.

The organization that maintains netfilter provides an informational website at https://netfilter.org. They also manage the iptables firewall software, which employs netfilter.

Another firewall technology that uses netfilter is firewalld. The newer firewalld service allows modified filter rules to be updated dynamically with no need to restart the service.

One more firewall technology covered by the certification is the Uncomplicated Firewall (UFW). This firewall configuration tool is an interface to the netfilter firewall that provides easier rule management.

Familiarizing Yourself with firewalld

The firewalld service provides packet filtering and user interfaces for the GUI environment and the command line. It offers support for IPv4 as well as IPv6, and much more. You can find additional details from the firewalld official website at https://www.firewalld.org/.

This firewall service is called the dynamic firewall daemon because you can change an ACL rule without needing to restart the service. The rules are loaded instantaneously via its D-Bus interface.

images D-Bus is the message bus daemon. It provides communication services between any two applications on a system-wide or per-session basis. It can also register to be notified of events, making it a powerful communication tool. The firewalld service employs a dbus Python library module to integrate D-Bus services.

A central part of firewalld is zones. Network traffic is grouped into a predefined rule set, or zone. Each zone has a configuration file that defines this rule set, also called a trust level. The traffic grouping can be a system’s network interface or a source address range, which identifies traffic from other systems. Each network connection can be a member of only one zone at a time.

By default, firewalld zone configuration files are stored in the /usr/lib/firewalld/ zones/ directory. Customized or user-created zone configuration files are stored in the /etc/firewalld/zones/ directory. Table 18.1 shows the predefined zones on a system employing firewalld. The zones are listed in the order of the least trusted to the most trusted network connections.

Table 18.1 The predefined firewalld zones

Name Description
drop Drops all incoming network packets. Allows only outbound network connections.
block Accepts only network connections that originated on the system. Rejects incoming network packets and sends an icmp-host-prohibited or icmp6-adm-prohibted message back.
public Accepts only selected incoming network connections. Typically used in a public setting, where other systems on network are not trusted.
external Performs similar to public but is typically used on external networks, when masquerading is enabled for the local systems.
dmz Performs similar to public but is used in a location’s demilitarized zone, which is publicly accessible and has limited access to the internal network.
work Accepts only selected incoming network connections. Typically used in a work setting, where other systems on the network are mostly trusted.
home Performs similar to work but is used in a home setting, where other systems on the network are mostly trusted.
internal Performs similar to work but is typically used on internal networks, where other systems on the network are mostly trusted.
trusted Accepts all network connections.

The firewall-cmd utility allows you to view and interact with various firewalld configuration settings. For example, to see all the predefined zones on a system, use the --get-zones option, as shown on a CentOS distribution in Listing 18.1.

Listing 18.1: Viewing the predefined zones with the firewall-cmd command

$ firewall-cmd ––get-zones
block dmz drop external home internal public trusted work
$
$ ls /usr/lib/firewalld/zones
block.xml  drop.xml      home.xml      public.xml   work.xml
dmz.xml    external.xml  internal.xml  trusted.xml
$

images The firewalld configuration files use Extensible Markup Language (XML). Though you may be tempted to edit these files directly, it is better to employ the firewalld utilities to modify and manage the firewall configuration.

NetworkManager is also integrated with firewalld. Thus, when a new network device is added via NetworkManager, firewalld automatically assigns it to the default zone. The default zone is typically preset to the public zone, but it can be customized via the firewall-cmd utility. You can view the system’s current default zone as shown in Listing 18.2.

Listing 18.2: Viewing the default zone with the firewall-cmd command

$ firewall-cmd --get-default-zone
public
$

If you need a different default zone, you can alter it. Just use super user privileges and employ the ––set-default-zone=zone option.

You can also view all the currently active zones as well as their traffic grouping. Just employ the ––get-active-zones switch as shown in Listing 18.3.

Listing 18.3: Viewing the active zones with the firewall-cmd command

$ firewall-cmd ––get-active-zones
public
  interfaces: enp0s8
$

images If desired, you can use the graphical firewalld configuration utility, firewall-config, instead of using the command-line utility. Typically it is easy to find this utility on firewalld systems by typing Firewall into the GUIs search box.

Besides zones, firewalld also employs services. A service is a predefined configuration set for a particular offered system service, such as DNS. The configuration information may contain items such as a list of ports, protocols, and so on. For example, the DNS service configuration set denotes that DNS uses both the TCP and UDP protocols on port number 53. Listing 18.4 shows a snipped listing of the various predefined services on a CentOS distro.

Listing 18.4: Viewing the predefined services with the firewall-cmd command

$ firewall-cmd ––get-services
[...]
amanda-client amanda-k5-client bacula bacula-client
[...]
dhcp dhcpv6 dhcpv6-client dns docker-registry
[...]
$
$ ls -1 /usr/lib/firewalld/services
amanda-client.xml
amanda-k5-client.xml
bacula-client.xml
bacula.xml
[...]
dhcp.xml
dns.xml
[...]
$

Using a firewalld service allows easier firewall configurations for a particular offered system service, because you can simply assign them to a zone. An example is shown in Listing 18.5.

Listing 18.5: Assigning the DNS service to the dmz zone

# firewall-cmd --add-service=dns --zone=dmz
success
#
# firewall-cmd --list-services --zone=dmz
ssh dns
#

images In an emergency situation, you can quickly disable all network traffic via firewalld. Use super user privileges and issue the command firewall-cmd ––panic-on at the command line. Once things have calmed down, you can re-enable network traffic by typing in firewall-cmd ––panic-off.

When you modify the firewalld configuration, by default you modify the runtime environment. The runtime environment is the configuration actively employed by the firewalld service.

The other firewalld environment is the permanent environment. This environment is the firewall configuration stored within the configuration files. It is loaded when the system boots (or when firewalld is restarted or reloaded) and becomes the active runtime environment.

Both of these firewalld environments have their place. The permanent environment is useful for production, whereas the runtime configuration is useful for testing firewall setting changes.

If you have tested firewall configuration changes in the runtime environment and wish to make them permanent, it is easily done. Just issue the firewall-cmd --runtime-to-permanent command using super user privileges. If you feel confident that your runtime environment configuration modifications are correct, you can tack on the --permanent option to the firewall-cmd command. This adds the changes to both the runtime and permanent environment at the same time. See the man pages for the firewall-cmd command for more information.

images The iptables service should not run alongside firewalld. This is easily shown on a systemd system. Use super user privileges and type in the systemctl show ––property=Conflicts firewalld command. You will see iptables.service listed in the output as a conflict. Also, while the iptables command is still available on many firewalld systems, it should not be employed. Instead of the iptables command, use either the firewall-cmd or firewall-config utility for setting up and managing your firewall configuration. If you just cannot give up the past, use the firewall-cmd command with its --direct switch. This allows you to employ the firewalld direct interface and use commands similar to iptables commands. Documentation notes that the direct interface should be used only as a last resort.

Investigating iptables

The iptables firewall service uses a series process called chains to handle network packets that enter the system. The chains determine the path each packet takes as it enters the Linux system to reach the appropriate application. As an application sends packets back out to the network to remote clients, these chains are also involved. Figure 18.1 shows different chains involved with processing network packets on a Linux system.

The diagram shows different chains involved with processing network packets on a Linux system.

Figure 18.1 The packet processing chain

Notice in Figure 18.1, that there are five separate chains to process packets:

  • PREROUTING handles packets before the routing decision process.
  • INPUT handles packets destined for the local system.
  • FORWARD handles packets being forwarded to a remote system.
  • POSTROUTING handles packets being sent to remote systems, after the forward filter.
  • OUTPUT handles packets output from the local system.

Each chain contains tables that define rules for handling the packets. There are five table types:

  • filter applies rules to allow or block packets from exiting the chain.
  • mangle applies rules to change features of the packets before they exit the chain.
  • nat applies rules to change the addresses of the packets before they exit the chain.
  • raw applies a NOTRACK setting on packets that are not to be tracked.
  • security applies mandatory access control rules.

Implementing network address translation (NAT) requires using the nat table to alter the packets’ address in the OUTPUT chain. Implementing a firewall is a little trickier, as you apply filter tables to the INPUT, OUTPUT, and FORWARD chains in the process. This provides multiple locations in the process to block packets.

Each chain also has a policy value. The policy entry defines how a packet is handled by default for the chain, when no rules apply to the packet. There are two different policy values:

  • ACCEPT: Pass the packet along to the next chain.
  • DROP: Don’t pass the packet to the next chain.

The tool you use to view and alter the chains and filters in the iptables service is the iptables command. Table 18.2 shows the commonly used iptables command-line options.

Table 18.2 The iptables command’s commonly used options

Option Description
-L [chain] Lists the rules in this chain. If chain is not specified, list all rules in all chains.
-S [chain] Lists the rules’ details in this chain. If chain is not specified, list all rules’ details in all chains.
[-t table] Applies the command to this table. If -t table is not specified, apply the command to the filter table.
-A chain rule Adds this new rule to this chain.
-I chain index rule Inserts this new rule to this chain at this index location.
-D chain rule Deletes this rule from this chain.
-R chain index rule Removes this rule from this chain at this index location.
-F [chain] Removes (flush) all rules from this chain. If chain is not specified, remove all rules from all chains.
-P chain policy Defines this default policy for this chain.

To quickly view the filter table’s chains and rules, use super user privileges and the -L option on the iptables command. A snipped example on a Fedora system is shown in Listing 18.6.

Listing 18.6: Viewing the filter table’s chains and rules

$ sudo iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     udp  ––  anywhere             anywhere             udp dpt:domain
[...]
Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     udp  ––  anywhere             anywhere             udp dpt:bootpc
OUTPUT_direct  all  ––  anywhere             anywhere
$

Notice that the -t filter option is not needed in this case. This is because the iptables command applies commands to the filter table by default.

images Keep in mind that you may see many more chains than the basic five listed back in Figure 18.1. This is especially true on a firewalld system. However, on a firewalld system, it is best to employ the firewall-cmd command instead for accurate and detailed information.

If you want to block all packets leaving your Linux system, you would just change the default OUTPUT chain to a DROP policy. Be careful here, because if you are using ssh to enter your system, this will cause your connection packets to be dropped as well! Listing 18.7 shows a snipped example of blocking all outbound packets on a Fedora system. Notice how the ping command operation is no longer permitted after this modification.

Listing 18.7: Employing the iptables command to drop all outbound packets

$ sudo iptables -P OUTPUT DROP
$
$ ping -c 3 192.168.0.105
PING 192.168.0.105 (192.168.0.105) 56(84) bytes of data.
ping: sendmsg: Operation not permitted
[...]
$ sudo iptables -P OUTPUT ACCEPT
$
$ ping -c 3 192.168.0.105
PING 192.168.0.105 (192.168.0.105) 56(84) bytes of data.
64 bytes from 192.168.0.105: icmp_seq=1 ttl=64 time=0.062 ms
[...]
$

In Listing 18.7, after the default OUTPUT chain is changed back to an ACCEPT policy, the ping packets are permitted.

images The iptables service firewall is managed by the iptables command only for IPv4 packets. If you have IPv6 packets traversing your network, you also have to employ the ip6tables command.

To change chain rules, you need to use some additional command-line options in the iptables command. These rule options are shown in Table 18.3.

Table 18.3 The iptables command’s commonly used chain options

Option Description
-d address Applies rule only to packets with this destination address
-s address Applies rule only to packets with this source address
-i name Applies rule only to packets coming in through the name network interface
-o name Applies rule only to packets going out through the name network interface
-p protocol Applies rule only to packets using this protocol, such as tcp, udp, or icmp
-j target Applies this target action (the rule) to the selected packets

The -j option in Table 18.3 needs a little more explanation. This is the actual rule applied to the identified packets. The most commonly used different target values are as follows:

  • ACCEPT: Pass the packet along to the next chain.
  • DROP: Don’t pass the packet to the next chain.
  • REJECT: Don’t pass the packet, and send a reject notice to the sender.

Putting a rule together and adding it to a chain is a little tricky, so an example will help. In snipped Listing 18.8, an Ubuntu system at IP address 192.168.0.104 is shown successfully sending a ping to a remote Fedora system, whose IP address is 192.168.0.105.

Listing 18.8: Sending a ping to a remote system successfully

$ ip addr show | grep 192.168.0.104
    inet 192.168.0.104/24 brd 192.168.0.255 [...] enp0s8
$
$ ping -c 1 192.168.0.105
PING 192.168.0.105 (192.168.0.105) 56(84) bytes of data.
64 bytes from 192.168.0.105: icmp_seq=1 ttl=64 time=0.305 ms
--- 192.168.0.105 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.305/0.305/0.305/0.000 ms
$

Now on the Fedora system, using super user privileges, the following command is issued:

sudo iptables -I INPUT 1 -s 192.168.0.104 -j REJECT

This new rule will be inserted (-I) into the INPUT chain’s filter table at index 1 (first rule in the chain). Any packets coming from the source (-s) address of 192.168.0.104 (the Ubuntu system) will be rejected (REJECT). Now that this rule is in place, when the Ubuntu system tries to ping the Fedora system, it will fail, as shown snipped Listing 18.9.

Listing 18.9: Blocking a ping to a remote system that blocks the packets

$ ping -c 1 192.168.0.105
PING 192.168.0.105 (192.168.0.105) 56(84) bytes of data.
From 192.168.0.105 icmp_seq=1 Destination Port Unreachable
--- 192.168.0.105 ping statistics ---
1 packets transmitted, 0 received, +1 errors, 100% packet loss, time 0ms
$

While you don’t need to reload the iptables service to have new or modified rules take effect, these rules have no persistency. In other words, if the system was rebooted or the iptables service restarted, you would lose all those new or modified ACL rules.

images You aren’t stuck with the iptables’ default chains. You can actually create your own. This is especially helpful, if you’d like to employ the LOG target to create log files of particular packets. Look in the man pages for iptables as well as iptables-extensions for more details.

As long as the iptables service is enabled to start at system boot, Red Hat and Red Hat–based distributions, such as Fedora and CentOS, will automatically load iptables rules stored in these files:

  • IPv4 rules: /etc/sysconfig/iptables
  • IPv6 rules: /etc/sysconfig/ip6tables

Debian and Debian-based distributions, such as Ubuntu, need an additional software package, iptables-persistent, installed and enabled. The files this package uses to load persistent rules are as follows:

  • IPv4 rules: /etc/iptables/rules.v4
  • IPv6 rules: /etc/iptables/rules.v6

images You won’t find these rule files for iptables service on the distribution versions recommended for this book because they use newer firewall technologies. If desired, you can use Fedora version 20 or older to play with these iptables’ files.

If you need to save the current iptables rules, employ the iptables-save command. This utility needs its output redirected to a file because by default, it sends the rules to STDOUT.

To restore saved iptables rules, employ the iptables-restore command. This utility needs its input redirected from a file. So, if you were testing an ACL change that was not working well, you could quickly restore the iptables’ original rules. On an older Fedora distribution, you use super user privileges and issue the iptables-restore < /etc/sysconfig/iptables command to restore all the original IPv4 rules.

Understanding UFW

The Uncomplicated Firewall (UFW) is the default firewall service on Ubuntu distributions. It is configured with the ufw command-line utility or Gufw for the GUI.

images By default, the UFW service is disabled. You start the service and set it to start at boot time by using the sudo ufw enable command, but do not use a system initialization tool, such as systemctl. This is because the firewall services covered here are not traditional SysV or systemd services but instead are interface services for the netfilter firewall. Thus, if you choose to start UFW, be aware that neither the iptables nor firewalld service can be running.

There are several UFW commands that control the firewall’s state as well as view its status. These commands are shown in Table 18.4. Each one requires super user privileges.

Table 18.4 The ufw commands to control state and view status

Command Description
ufw enable Starts the UFW firewall and enables it to start at system boot
ufw disable Stops the UFW firewall and disables it from starting at system boot
ufw reset Disables the UFW firewall and resets it to installation defaults
ufw reload Reloads the UFW firewall
ufw status Displays the UFW firewall’s current state

To view the current state of the UFW service, use sudo ufw status verbose, if you need more information than just status provides. Enabling the UFW firewall service and viewing its current state is shown snipped in Listing 18.10.

Listing 18.10: Enabling UFW and viewing its status

$ sudo ufw enable
[...]
Firewall is active and enabled on system startup
$
$ sudo ufw status verbose
Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)
New profiles: skip
$

Viewing the verbose status of the UFW firewall provides information that helps to explain its configuration:

  • Status: UFW service is running and will start on system boot (active), or the services stopped and a system boot does not change this (disabled).
  • Logging: The service’s logging feature can be set to off; log all blocked packets (low), which is the default; log all blocked, invalid, no-policy-match, and new connection packets (medium) with rate limiting; log medium-log-level packets and all other packets (high) with rate limiting; and log everything with no rate limits (full).
  • Default: Shows the default policy for incoming, outgoing, and routed packets, which can be set to either allow the packet, drop (deny) the packet, or reject the packet and send a rejection message back.
  • New profiles: Shows the default policy for automatically loading new profiles into the firewall, which can be set to ACCEPT, DROP, REJECT, or SKIP, where ACCEPT is considered a security risk.

The various default UFW policies are stored in the /etc/default/ufw configuration file. When first installed, these settings allow all outgoing connections and block all incoming connections. You can make modifications to the firewall as needed using the ufw command and its various arguments. A few of the more common arguments are shown in Table 18.5.

Table 18.5 The ufw command’s commonly used arguments

Argument Description
allow Identifiers Sets the rule identified by Identifiers to allow packets
deny Identifiers Sets the rule identified by Identifiers to deny (drop) packets
reject Identifiers Sets the rule identified by Identifiers to reject packets
delete RULE | NUM Deletes the rule identified by RULE or NUM
insert NUM RULE Inserts the RULE at index NUM
default POLICY DIRECTION Modifies the default DIRECTION policy, where POLICY is allow, deny, or reject, and direction is incoming, outgoing, or routed
logging LEVEL Sets the logging level, where LEVEL is on, off, low (default), medium, high, or full

When creating new UFW rules, you can use either simple or full syntax. Simple syntax involves designating the rule using only the port number or its service name. You can also add the protocol to the port number as shown in Listing 18.11.

Listing 18.11: Using ufw simple syntax to add an ACL rule

$ sudo ufw allow 22/tcp
Rule added
Rule added (v6)
$
$ sudo ufw status
Status: active
To                         Action      From
--                         ------      ----
22/tcp                     ALLOW       Anywhere
22/tcp (v6)                ALLOW       Anywhere (v6)
$

Notice that when the rule is added, that two rules were applied—one for IPv4 and one for IPv6 packets. With full syntax, there are many options. For example, you can employ settings such as those listed in Table 18.6.

Table 18.6 The ufw command’s full syntax common settings

Setting Description
comment "string" Displays this comment for rejected traffic
in Applies rule only to incoming traffic
out Applies rule only to outgoing traffic
proto protocol Applies rule to this protocol
port port# Applies rule to this port#
from source Applies rule to traffic from this source, which may be a single IP address, subnet, or any traffic
on interface Applies rule to traffic on this network interface
to destination Applies rule to traffic going to this destination, which may be a single IP address, subnet, or any traffic

images You do not need to issue the ufw reload command after you add, delete, or modify a rule. The change automatically takes effect.

You can specify a rule via a service name (e.g., telnet) with the ufw command. When doing this, ufw checks the /etc/services file to determine the appropriate port and protocol information for that service.

An example of using the UFW full syntax is shown in Listing 18.12. In this case, network packets coming from any systems in the 192.168.0.0 class C subnet will be denied access to port 80 on this system.

Listing 18.12: Using ufw full syntax to add an ACL rule

$ sudo ufw deny from 192.168.0.0/24 to any port 80
Rule added
$
$ sudo ufw show added
Added user rules (see 'ufw status' for running firewall):
ufw allow 22/tcp
ufw deny from 192.168.0.0/24 to any port 80
$$

View any user-added rules using the ufw show added command as shown in Listing 18.12. The UFW rules are stored in the /etc/ufw/ directory, and user-added rules are placed into the user.rules file within that directory, as shown in Listing 18.13.

Listing 18.13: Displaying the /etc/ufw/ directory’s contents

$ ls /etc/ufw/
after6.rules  applications.d  before.rules  user6.rules
after.init    before6.rules   sysctl.conf   user.rules
after.rules   before.init     ufw.conf
$

If you need to delete a rule, it’s easiest to do it by the rule number. First view the rules via their numbers and then employ the ufw delete command as shown in Listing 18.14.

Listing 18.14: Deleting a rule via its number

$ sudo ufw status numbered
Status: active
     To                         Action      From
     --                         ------      ----
[ 1] 22/tcp                     ALLOW IN    Anywhere
[ 2] 80                         DENY IN     192.168.0.0/24
[ 3] 22/tcp (v6)                ALLOW IN    Anywhere (v6)
$
$ sudo ufw delete 2
Deleting:
 deny from 192.168.0.0/24 to any port 80
Proceed with operation (y|n)? y
Rule deleted
$

UFW uses profiles for common applications and daemons. These profiles are stored in the /etc/ufw/applications.d/ directory. Use the ufw app list command to see the currently available UFW application profiles. An example is shown snipped in Listing 18.15.

Listing 18.15: Viewing the available UFW application profiles

$ sudo ufw app list
Available applications:
  CUPS
  OpenSSH
$
$ sudo ufw app info OpenSSH
Profile: OpenSSH
Title: Secure shell server, an rshd replacement
Description: OpenSSH is a free implementation[...]
Port:
  22/tcp
$

You can also view detailed information on these profiles as also shown in Listing 18.15. The profiles not only provide application documentation, they allow you to modify the ports and protocols used by the applications as well as create non-typical application profiles for your system’s needs.

images Do not modify the profiles in the /etc/ufw/applications.d/ directory. Instead, create a subdirectory there and name it custom.d. This will prevent your custom profiles from being overwritten during UFW software package updates. See the ufw man pages for more details on profile specifications.

Once you have created a new profile or updated an old one, use the ufw app update all command to update UFW on the profile changes. Also, when using a profile to specify a rule’s ports and protocols, you must employ app instead of port within your syntax for creating new rules.

Forwarding IP Packets

There is a packet forwarding feature in Linux. This feature is used for various purposes, such as allowing Linux to forward packets to a remote host or for IP masquerading. You must enable packet forwarding in the kernel prior to employing it. To enable that feature, just set the ip_forward entry for IPv4 or the forwarding entry for IPv6. You can do that with the sysctl command:

sudo sysctl &ndash;w net.ipv4.ip_forward=1
sudo sysctl -w net.ipv6.conf.all.forwarding=1

You can check the current kernel values by using the cat command in the /proc filesystem entries. If the files contain the number 1, the feature is enabled as shown in Listing 18.16, and if it is disabled, the files will contain the number 0.

Listing 18.16: Viewing the packet forwarding files

$ cat /proc/sys/net/ipv4/ip_forward
1
$ cat /proc/sys/net/ipv6/conf/all/forwarding
1
$

Once those kernel values are set, your Linux system is able to forward traffic from one network interface to another network interface. If there are multiple network interfaces on the Linux system, it knows which interface to use to send traffic to remote hosts via the routing table. Routing tables were covered in Chapter 7.

Dynamically Setting Rules

In protecting your system, it helps to have software that monitors the network and applications running on the system, looking for suspicious behavior. These applications are called intrusion detection systems (IDSs). Some IDS applications allow you to dynamically change rules so that these attacks are blocked. Two of those IDS programs are DenyHosts and Fail2Ban.

Another helpful utility in your firewall toolbelt is one that allows you to quickly change rules without having to type out long IP addresses or MAC addresses over and over again. An IPset can help with this issue.

DenyHosts

The DenyHosts application is a Python script, which helps protect against brute-force attacks coming through OpenSSH. The script can be run as a service or as a cron job. It monitors sshd log messages in the distribution’s authentication log files, such as /var/log/secure and /var/log/auth.log. If it sees repeated failed authentication attempts from the same host, it blocks the IP address via the /etc/hosts.deny file.

To configure DenyHosts you modify its /etc/denyhosts.conf file. You also need to have the TCP Wrappers files, /etc/hosts.allow and /etc/hosts.deny, ready to go.

images DenyHosts works only with IPv4 OpenSSH traffic. For all others, you’ll have to employ a different utility. Also, be aware that some distro repositories claim DenyHosts is no longer being developed. Therefore, install and use with caution.

Fail2ban

The Fail2ban service also monitors system logs, looking for repeated failures from the same host. If it detects a problem, Fail2ban can block the IP address of the offending host from accessing your system. While DenyHosts works only with TCP Wrappers, Fail2ban can work with TCP Wrappers, iptables, firewalld, and so on.

The fail2ban-client program monitors both system and application logs looking for problems. It monitors common system log files such as the /var/log/pwdfail and /var/log/auth.log log files, looking for multiple failed login attempts. When it detects a user account that has too many failed login attempts, it blocks access from the host the user account was attempting to log in from.

A great feature of Fail2ban is that it can also monitor individual application log files, such as the /var/log/apache/error.log log file for the Apache web server. Just as with the system log files, if Fail2ban detects too many connection attempts or errors coming from the same remote host, it will block access from that host.

The /etc/fail2ban/jail.conf file contains the Fail2ban configuration. It defines the applications to monitor, where their log files are located, and what actions to take if it detects a problem.

images The downside to using Fail2ban is that it can have false positives that detect a problem when there really isn’t one. This can cause it to block a valid client from accessing the system. Fortunately, Fail2ban is robust enough that you can configure it to release the block after a set time to allow the client to reconnect correctly.

IPset

An IPset is a named set of IP addresses, network interfaces, ports, MAC addresses, or subnets. By creating these sets, you can easily manage the groupings through your firewall and any other application that supports IPsets.

The ipset utility is used to manage IPsets and requires super user privileges. When you create an IPset, you need to first determine what name you will give it. After that, decide how you want the IPset to be stored. Your storage choices are bitmap, hash, or list. There are two ways to create an IPset via the ipset command:

ipset create IPset-Name  storage-method:set-type
ipset -N IPset-Name  storage-method:set-type

An example of creating a subnet IPset and adding members to it on a CentOS distribution is shown in Listing 18.17.

Listing 18.17: Creating and populating a subnet IPset

# ipset create BadGuyNets hash:net
#
# ipset add BadGuyNets 1.1.1.0/24
# ipset -A BadGuyNets 2.2.0.0/15
#

Once you have completed your IPset population, you can review your handy work. Just employ the ipset list command as shown snipped in Listing 18.18.

Listing 18.18: Viewing a subnet IPset

# ipset list
Name: BadGuyNets
Type: hash:net
[...]
Members:
1.1.1.0/24
2.2.0.0/15

Once it’s created and populated, block the IPset in either your iptables or firewalld ACL rules. To make the IPset persistent, you save it via the ipset save command and redirect its STDOUT to the /etc/ipset.conf file or use the -f option.

images After you create an IPset, you need to start the ipset service. However, you may not find a service file to start or enable on systemd systems. Therefore, if your distribution uses systemd, you will either need to create an ipset.service file or obtain one from a reliable source.

You can delete a single item from your named IPset via the ipset del command. To remove the entire IPset, you’ll need to destroy it as shown in Listing 18.19.

Listing 18.19: Deleting a subnet IPset

# ipset destroy BadGuyNets
#
# ipset list
#

images Only the firewalld and iptables service commands directly support IPset. However, you can use IPset with UFW, but it takes a little more work. You must modify the before.init and after.init scripts within the /etc/ufw/ directory. Find out more information about these scripts in the man pages for ufw-framework.

Summary

Properly managing your system’s firewall application and its packet filtering ACL is vital for securing your system. To do this, you must understand the underlying framework of the firewall software, how to modify its ACL rules, and what additional applications can be used alongside to block malicious network traffic. Using the correct products and properly configuring them not only helps to keep systems secure, it makes your job easier as well.

Exam Essentials

Summarize various firewall features. A firewall ACL identifies which network packets are allowed in or out. A stateless firewall views each packet’s control information and decides what to do with the packet based on the defined ACL rules. A stateful firewall tracks active network connections, such as TCP and UDP; keeps an eye on network status; and can determine if packets have fragmented. Firewalls employ the /etc/services file, which documents the different standard application services names and their corresponding port numbers, protocols, and aliases.

Describe firewalld and its commands. For the firewalld service, network traffic is grouped into a zone, which is a predefined rule set. Each zone has a configuration file that defines this rule set, also called trust levels. The firewalld zone configuration files are stored in the /usr/lib/firewalld/zones/ directory. Customized or user-created zone configuration files are stored in the /etc/firewalld/zones/ directory. For firewalld, a service is a predefined configuration set for a particular service, such as DNS. When you modify the firewalld configuration, by default you modify the runtime environment, which is the active situation. The permanent environment is the firewall settings within the configuration files. The firewall-cmd utility allows you to view and interact with firewalld.

Describe iptables and its commands. The iptables firewall service uses a series process called chains to handle network packets that enter the system. The chains determine the path each packet takes to the appropriate application as it enters the Linux system. Each chain has a policy value and contains tables that define rules for handling the packets. ACL rules in iptables have target values for identified packets, which determine the action taken on them. The iptables command allows you to view and interact with various iptables configuration settings.

Describe UFW and its commands. The Uncomplicated Firewall (UFW) is the default firewall service on Ubuntu distributions. It is configured with the ufw command-line utility or the Gufw for the GUI. Default UFW policies are stored in the /etc/default/ufw configuration file. When creating new UFW rules, you can use either simple or full syntax. User-added UFW rules are stored in the /etc/ufw/user.rules file. UFW uses profiles for common applications and daemons, and they are stored in the /etc/ufw/applications.d/ directory.

Explain how to dynamically change packet filtering. The DenyHosts application is a Python script, which helps protect against brute-force attacks coming through OpenSSH. It monitors sshd log messages and modifies the /etc/hosts.deny file to block an identified attack. The Fail2ban service also monitors system logs, looking for repeated failures from the same host. If it detects a problem, Fail2ban blocks the IP address of the offending host. An IPset is a named set of IP addresses, network interfaces, ports, MAC addresses, or subnets. By creating these sets, you can easily block the groupings through a firewall.

Review Questions

  1. Which of the following is true concerning firewalls on Linux that were covered in this chapter? (Choose all that apply.)

    1. They use ACLs for allowing packets.
    2. They detect malicious behavior.
    3. They inspect network packet control information.
    4. They use iptables embedded in the Linux kernel.
    5. They employ configuration files for persistency.
  2. Which of the following options best describes packet filtering?

    1. Identifying network packets via their control information, and allowing them into the system
    2. Identifying network packets via their control information, and determining what to do based upon ACL rules
    3. Identifying network packets via their payload, and determining what to do based upon ACL rules
    4. Identifying network packets by their source address, and determining what to do based upon ACL rules
    5. Identifying network packets by their payload, and determining what to do based upon their source address
  3. Which of the following are benefits of a stateful firewall over a stateless firewall? (Choose all that apply.)

    1. It operates faster.
    2. It is not as vulnerable to DDoS attacks.
    3. It determines if packets are fragmented.
    4. It operates faster for established connections.
    5. It is vulnerable to DDoS attacks.
  4. The firewalld service uses _____, which is a predefined rule set.

    1. netfilter
    2. firewall-cmd
    3. Services
    4. reject
    5. Zones
  5. Peter Quill, a Linux system administrator, has been testing a new firewalld configuration. The test was successful. What should Mr. Quill do next?

    1. Using super user privileges, issue the reboot command.
    2. Using super user privileges, issue the firewall-cmd --panic-on command.
    3. Nothing. If the test was successful, the runtime environment is the permanent environment.
    4. Issue the firewall-cmd --runtime-to-permanent command using super user privileges.
    5. Issue another firewall-cmd command, but add the --permanent option to it.
  6. Peter Quill is a Linux system administrator of a system using the iptables service. Mr. Quill wants to add a rule to block only incoming ping packets and not send a rejection message to the source. What command should he employ?

    1. sudo iptables -P INPUT DROP
    2. sudo iptables -A INPUT -p icmp -j REJECT
    3. sudo iptables -A INPUT -p icmp -j DROP
    4. sudo iptables -D INPUT -p icmp -j DROP
    5. sudo iptables -A OUTPUT -p icmp -j REJECT
  7. Which of the following commands will allow you to view the various rules in a UFW firewall with their associated numbers?

    1. sudo ufw show numeric
    2. sudo ufw status
    3. sudo ufw status verbose
    4. sudo ufw status numbered
    5. sudo ufw enable
  8. Which of the following is an example of UFW simple syntax for blocking all incoming and outgoing OpenSSH connections without providing a blocking message?

    1. sudo ufw deny 22/tcp
    2. sudo ufw drop 22/tcp
    3. sudo ufw reject 22/tcp
    4. sudo ufw accept 22/tcp
    5. sudo ufw block 22/tcp
  9. Which of the following are true concerning both DenyHosts and Fail2ban? (Choose all that apply.)

    1. It is an intrusion detection system (IDS)
    2. It modifies the /etc/hosts.deny file.
    3. It only handles OpenSSH traffic.
    4. Its configuration file is named jail.conf.
    5. It can work with TCP Wrappers, iptables, and firewalld.
  10. Virginia Potts is administering a Linux system with a firewall. She has already set up an IPset and named it BlockThem. A new attack has begun to occur from the 72.32.138.96 address. Along with super user privileges, what command should Ms. Potts issue to add this IPv4 address to the IPset?

    1. ipset create BlockThem hash:net
    2. ipset -n BlockThem hash:net
    3. ipset save -f /etc/ipset.conf
    4. ipset -A BlockThem 72.32.138.0/24
    5. ipset add BlockThem 72.32.138.96
..................Content has been hidden....................

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