Fatskills
Practice. Master. Repeat.
Study Guide: CompTIA Linux+ Certification: Overseeing Linux Firewalls
Source: https://www.fatskills.com/comptia-linux-/chapter/comptia-linux-certification-overseeing-linux-firewalls

CompTIA Linux+ Certification: Overseeing Linux Firewalls

By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.

⏱️ ~34 min read

Key Topics:
Providing Access Control
Looking at Firewall Technologies
Forwarding IP Packets
Dynamically Setting Rules
 

Objective 2.3: Given a scenario, implement and configure firewalls
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 a software application, network-based or host-based, and a network-layer or application-layer filter. In this guide, we'll take a look at software application firewalls that are host-based and that 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.

Note: “Applying Ownership and Permissions.” 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.

Real World Scenario
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 the Health Insurance Portability and Accountability Act (HIPAA) or the 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. The NIST Special Publication 800-92, Guide to Computer Security Log Management, is a helpful publication that can guide your organization's analysis requirements and determine what appropriate steps to take.
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.

Note: /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. For Red Hat–based distributions, if you configure your network environment during the installation it will install the firewalld service by default.
Debian-based distributions use yet another firewall service that utilizes netfilter: the Uncomplicated Firewall (UFW). This firewall configuration tool is an interface to the netfilter firewall that provides easier rule management.
Although firewalld and UFW services provide easy-to-use interfaces to the netfilter firewall, they have an additional layer that can slow down the packet filtering process. While this is fine for most server environments, if you're using Linux as a dedicated network firewall, speed is of the essence. The nftable service provides low-level access to the netfilter firewall similar to iptables but is not quite as complicated as iptables.
The following sections discuss each of these four firewall services.

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 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.

Note: 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 The predefined firewalld zones

The zones are listed in the order of the least trusted to the most trusted network connections.

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-prohibited message back.
public Accepts only selected incoming network connections. Typically used in a public setting, where other systems on the 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 below.

List: 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

Tip: 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 using the firewall-cmd utility.

You can view the system's current default zone as shown below.

List: 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 below.

List: Viewing the active zones with the firewall-cmd command
$ firewall-cmd ––get-active-zones
interfaces: enp0s8

Note: 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 GUI's 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.

List: 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 below

List: Assigning the DNS service to the dmz zone
# firewall-cmd --add-service=dns --zone=dmz
success
# firewall-cmd --list-services --zone=dmz
ssh dns

Tip: 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 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.

Note: iptables service should not run alongside firewalld. This is easily shown on a systemd system. Use super user privileges and type 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.

Different chains are involved with processing network packets on a Linux system. (See below)
Notice below 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.


Schematic illustration of the packet processing chain
Figure: The packet processing chain

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: 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 below.

List: 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)
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.

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!
 

The list below 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.

List: 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
64 bytes from 192.168.0.105: icmp_seq=1 ttl=64 time=0.062 ms

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

Note: 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 below table.

TABLE: 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 the above table 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:
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 list shown, 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.

List: 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
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 in the snipped List shown.

List: Blocking a ping to a remote system that blocks the packets
$ ping -c 1 192.168.0.105
From 192.168.0.105 icmp_seq=1 Destination Port Unreachable
1 packets transmitted, 0 received, +1 errors, 100% packet loss, time 0ms

Note: 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.
Although 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.
As long as the iptables service is enabled to start at system boot, Red Hat and Red Hat–based distributions, such as Fedora and Rocky Linux, 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

Note: 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.

Exploring nftables
You may have noticed that the format to create rules in iptables can often get somewhat complicated, especially compared to tools like firewalld. A good compromise is the nftables service.
The nftables service provides low-level access to the netfilter chains similar to iptables, making it extremely efficient and fast. However, the command syntax for building rules in nftables has been simplified, making it easier to work with.
The nftables service utilizes the same concept of tables, chains, policies, and rules as iptables. You can list the existing tables defined by using the list option of the nft command, as shown in below.

List: List tables in nftables
$ sudo nft list tables
table ip filter
table ip6 filter
table bridge filter
table ip security
table ip raw
table ip mangle
table ip nat
table ip6 security
table ip6 raw
table ip6 mangle
table ip6 nat
table bridge nat
table inet firewalld
table ip firewalld
table ip6 firewalld

Notice in this list that in a Red Hat system the firewalld service creates its own tables in netfilter, which nftables detects. To create a new table, use the add table option in nft, as shown in below

List: Creating a new table using nftables
$ sudo nft add table ip rich
$ sudo nft list tables ip
table ip rich
$ sudo nft list table ip rich
table ip rich {
The add command created the table rich, but as
List: shows, the table is empty by default.

After you create a table, the next step is to create chains, which will contain the rules you define for the firewall definitions. As you would expect, the add chain option does this.

The basic format for the add chain option looks like this:
nft add chain [family] table_name chain_name { type type hook
hook priority value \; [policy policy \;] [comment \"text
comment\" \;] }

The type value can be filter, router, or nat (the same as in iptables), and the hook value can be prerouting, input, forward, output, or postrouting (again the same as in iptables). The priority value determines the order in which the chain is processed; lower priority values are processed first. The policy value can be either accept or drop.
List: shows an example of creating a chain.

List: Creating a new chain using nftables
$ sudo nft 'add chain ip rich test { type filter hook input
priority 0; policy drop; }'
chain test {
type filter hook input priority filter; policy drop;
}

As seen in the above list, you must place single quotes around the add chain command. The default policy for this chain is set to drop, so all incoming packets will be dropped, unless they match a rule that says otherwise.
Once you have a chain created, you can define rules to apply to the chain using the add rule option. The format for rules is one of the selling points of nftables. The format uses simple syntax, similar to that used by the popular tcpdump monitoring program.


List: Adding a new rule using nftables
$ sudo nft 'add rule ip rich test tcp dport ssh accept'
tcp dport 22 accept
 

This list shows that the rule has been added to the test chain. You can then create additional rules in the same chain, or create additional chains with different priorities to contain additional rules.

To remove a rule from a table, use the flush table option:
$ sudo nft flush table rich
To remove a chain from a table use the delete chain option. To remove an entire table, use the delete table option:
$ sudo nft delete table ip rich
iptables, firewalld, or ufw. Since they all use the same netfilter service, the rules in each firewall configuration could conflict—or at least make things extremely complicated when trying to sort out why things are being blocked or allowed.

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.

Note: 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 the firewalld service can be running.
There are several UFW commands that let you control the firewall's state as well as view its status. These commands are shown below. Each one requires super user privileges.

TABLE: 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 below.

List: 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 common arguments are shown below

TABLE:  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 below.

List: Using ufw simple syntax to add an ACL rule
$ sudo ufw allow 22/tcp
Rule added
Rule added (v6)
$ sudo ufw status
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 below.

TABLE: 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




Note: 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 List 18.16. 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.

List: Using ufw full syntax to add an ACL rule
$ sudo ufw deny from 192.168.0.0/24 to any port 80
$ 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. 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 below.

List: 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 so by the rule number. First view the rules via their numbers and then employ the ufw delete command, as shown below.

List: Deleting a rule via its number
$ sudo ufw status numbered
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 below.

List: 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. The profiles not only provide application documentation but also allow you to modify the ports and protocols used by the applications as well as create nontypical application profiles for your system's needs.
/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 in 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 -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 below list, and if it is disabled, the files will contain the number 0.

List: Viewing the packet forwarding files
$ cat /proc/sys/net/ipv4/ip_forward
$ cat /proc/sys/net/ipv6/conf/all/forwarding

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 “Configuring Network Connections.”

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.

Warning: - 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.

Tip: - 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 Rocky Linux distribution is shown below.

List: 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 handiwork. Just employ the ipset list command as shown snipped below.

List: 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.

Note: 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 need to either create an ipset.service file or obtain one from a reliable source.

You can delete a single item from your named IPset by using the ipset del command. To remove the entire IPset, you'll need to destroy it, as shown below.

List: Deleting a subnet IPset
# ipset destroy BadGuyNets
# ipset list

Note: 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.

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 it to block malicious network traffic. Using the correct products and properly configuring them not only helps to keep systems secure but makes your job easier as well.

Important exam questions

1. 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.

2. 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.

3. 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.

4. 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.

5. 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.

 

 



ADVERTISEMENT