Kali Linux: filtering traffic with netfilter

Original author: Collective of authors
  • Transfer
→ Part 1. Kali Linux: security policy, protecting computers and network services
→ Part 2. Kali Linux: filtering traffic using netfilter
→ Part 3. Kali Linux: monitoring and logging
→ Part 4. Kali Linux: exercises to protect and monitor the system

We present to your attention the continuation of the translation of Chapter 7 of Kali Linux Revealed . Last time, it was about security policies and the protection of computers and network services. This material includes a translation of section 7.4, which focuses on firewall and packet filtering.


7.4. Firewall or packet filtering

A firewall is computer equipment that can be represented as a software, hardware, or software-hardware complex. The firewall processes incoming and outgoing network packets (entering or leaving the local network) and passes only those that correspond to certain predefined rules.

A filtering network gateway is a type of firewall that protects the entire network. It is usually installed on a dedicated computer configured as a gateway to the network. As a result, this computer can process all packets that cross the boundary between the network and the outside world. Alternatively, a local firewall is a software service that runs on a particular machine in order to restrict access to certain services on that machine, or, possibly, to prevent outgoing connections initiated by unwanted software that a computer user may, intentionally or accidentally install.

Linux kernel has a built-in firewallnetfilter. The requirements of different networks and users are not the same, so there is no standard approach to setting up a firewall that allows you to get a ready-made solution for all occasions. You netfiltercan control the firewall from user space using the iptablesand commands ip6tables. The difference between the two teams is that the first is for IPv4 networks, the second is for IPv6 networks. Since both protocol stacks are likely to be in use for many more years, both tools should be used together. In addition, here you can apply an excellent program fwbuilderthat provides graphical tools for building and presenting traffic filtering rules.

No matter how you decide to configure netfilter — it, the standard Linux firewall, so take a closer look at how it works.

7.4.1. How netfilter works

Netfilter uses four tables that store rules governing three types of package operations:

  • filter: regarding filtering rules (accept, reject, or ignore the packet);
  • nat (Network Address Translation): concerns the translation of the source, receiver, or port addresses of a packet;
  • mangle: concerns other changes of IP packets (including fields and parameters of ToS - Type of Service);
  • raw: allows manual modification of packages before they reach the connection tracking system.

Each table contains lists of rules called chains. The firewall uses standard chains to process packets based on predefined conditions. The administrator can create other chains, which will be used only in cases when they, directly or indirectly, are referred to by one of the standard chains.

The table filtercontains three standard chains:

  • INPUT: applies to packets whose destination is the firewall itself;
  • OUTPUT: refers to packets that the firewall sends;
  • FORWARD: refers to packets that pass through the firewall (which is neither their source nor their destination).

The table natalso contains three standard chains:
  • PREROUTING: to modify arriving packages;
  • POSTROUTING: to modify packages when they are ready to go to their destination;
  • OUTPUT: to modify packages generated by the firewall itself.

The above chains are shown in the figure below.

Fig. 7.1. Netfilter chains

Each chain is a list of rules. Each rule is a set of conditions and actions that must be performed when the relevant conditions are met. In the process of processing the packet, the firewall scans the appropriate chain, rule by rule, and when the conditions for a certain rule are fulfilled, it “jumps” (hence the option -j — from the word “jump”) to the specified action to continue processing the packet.

The most common patterns of behavior are standardized, for them there are dedicated actions. Performing one of these standard actions interrupts the passage through the chain, since the fate of the package is already predetermined (this does not apply to the exceptions mentioned below). Here is a list of actions netfilter:

  • ACCEPT: allows the package to follow its own path.
  • REJECT: rejects the packet, generating an ICMP (Internet Control Message Protocol) error packet. The option iptables --reject-with typeallows you to specify the type of error generated.
  • DROP: delete (ignore) the package.
  • LOG: write a message (through syslogd) to the system log with the package description. Please note that this action does not interrupt the processing of the packet; the chain continues with the next rule. That is why logging rejected packets requires rules LOGand REJECT/DROP. Among the frequently used parameters related to logging, the following can be noted:
  • ULOG: Logs messages using ulogd. This approach may be more effective than syslogdwhen processing a large number of messages. Please note that this action, like LOG, does not interrupt the processing of the package.
  • chain_name: Go to the given chain and process its rules.
  • RETURN: Interrupts processing of the current chain and returns to the calling chain. In the event that the current chain is one of the standard ones, there is no calling chain, so instead the default action is performed (specified using the -Pcommand option iptables).
  • SNAT(table only nat): Applies Source Network Address Translation (SNAT). Additional options describe exactly what changes need to be made, including the - option -to-source address:port, which allows you to specify a new IP address for the packet source, and, if necessary, a port.
  • DNAT(table only nat): Applies Destination Network Address Translation (DNAT). Additional options describe exactly what changes need to be made, including an option --to-destination address:portthat allows you to set a new destination IP address, and, if necessary, a port.
  • MASQUERADE(only in the table nat): performs the so-called masquerading (a special case of Source NAT).
  • REDIRECT(only in the table nat): transparently redirects the packet to the specified port of the firewall itself. This action can be used to set up a transparent web proxy, which works without additional settings on the client side, since the client believes that it is connected to the recipient, while the data exchange, in fact, goes through the proxy. The option --to-ports port(s)allows you to specify the port or port range to which packets should be redirected.

A description of other actions, in particular those related to the table mangle, is beyond the scope of this material. Help can be found on the maniptables(8)and pages ip6tables(8).

▍ What is ICMP?

ICMP (Internet Control Message Protocol) is used to transmit additional information about network connections. It allows you to test network connections using a command pingthat sends ICMP pings to which a recipient is expected to receive ICMP pings. This protocol is used to issue messages about packets rejected by the firewall, to indicate that the receive buffer is full, to suggest a better route for the next packets in the connection, and so on. This protocol is defined by several RFC documents. The first were RFC777 and RFC792 , however, many other documents extend or revise the protocol.

For example, a receive buffer is a small area of ​​memory designed to store data after it is received from the network and before processing by the kernel. If this memory is full, new data cannot be received and ICMP signals a problem. As a result, the source can reduce the data transfer rate (which, after some time, ideally, should reach a level that provides a balance between the source and receiver).

Please note that although an IPv4 network can work without ICMP, ICMP v6 protocol support is absolutely necessary for IPv6 networks, as this protocol combines several functions that, in IPv4 networks, were distributed between ICMPv4, Internet Group Membership Protocol (IGMP ), and Address Resolution Protocol (ARP). ICMPv6 is dedicated to the RFC4443 standard .

7.4.2. Syntax for iptables and ip6tables commands

Commands iptablesand ip6tablesare used to work with tables, chains and rules. Their option - t tableallows you to specify the table with which you plan to work (by default this is a table filter).

▍ Teams

Here are the main options for working with chains:

  • -L chain: Displays the rules in the chain. Usually this option is used with the option -nto disable name resolution (for example, the command iptables -n -L INPUTwill display the rules related to incoming packets).
  • -N chain: creates a new chain. New chains are created, pursuing many goals, including - to test new network services and to prevent network attacks.
  • -X chain: Deletes an empty or unused chain (for example - iptables -X ddos-attack).
  • -A chain rule: Adds a rule to the specified chain. Remember that rules are processed starting from the head of the chain, keep this in mind when adding new rules to chains.
  • -I chain rule_num rule: Inserts a rule before the rule specified by the argument rule_num. As with the option -A, remember the rules processing order by adding a new rule to the chain.
  • -D chain rule_num(or -D chain rule): removes the rule from the chain. The first use case identifies the rule to be deleted by number (the command iptables -L --line-numbersallows you to display these numbers). The second option allows you to identify the rule by its contents.
  • -F chain: resets the chain (removes all rules from it). For example, in order to remove all the rules associated with outgoing packages, you can use the command iptables -F OUTPUT. If no specific chains are specified using this option, all rules in the table will be deleted.
  • -P chain action: allows you to set a default action, or “policy” for a given chain. Please note that only standard conversations can have a policy. For example, in order to discard all incoming traffic by default, you can use the command iptables -P INPUT DROP.

▍ rules

Each rule is expressed as conditions -j action action_options. If several conditions are described in the same rule, then the final criterion is the combination of these conditions (according to the rules of logical AND). The result of the union, at a minimum, imposes the same restrictions on the rule as each individual condition.

The condition -p protocolcorresponds to the IP packet protocol field. The most commonly used values for this condition - tcp, udp, icmp, and icmpv6. This condition can be supplemented with conditions regarding TCP ports using expressions of the form --source-port portand --destination-port port.

▍Logical denial of conditions

If you put an exclamation mark before the condition, this will lead to its transformation into the opposite condition. For example, an exclamation mark in an option condition -pallows you to build an expression of the following form: "any packet with a protocol that differs from the specified one." This mechanism of logical negation can be applied to any other conditions.

A condition of the form -s addressor -s network/maskallows you to filter packets by their source address. Accordingly, conditions -d addressor -d network/maskallow the system to respond to packet destination addresses.

The view condition -i interfaceresponds to packets that come from the specified network interface. The condition -o interfaceallows you to select packets that go to the specified interface.

The condition --state statefilters packets according to their state in the connection (applying this condition requires a kernel module ipt_conntrackto monitor connections). So, the state NEWdescribes a packet requesting a new connection, a ESTABLISHED — packet belonging to an existing connection,RELATED- describes a packet initiating a new connection, which is part of an existing connection (analysis of this state is useful for connections ftp-datain the “active” mode of the FTP protocol).

The teams iptablesand ip6tablesthere are plenty of options, mastering them requires a serious approach to their study and experience. However, one of the options that you will use most often is the one that is designed to block unwanted network traffic from a certain host or range of hosts. For example, in order to "silently" block incoming traffic from an IP address and a subnet of class C, you need to do the following:

# iptables -A INPUT -s -j DROP
# iptables -A INPUT -s -j DROP
# iptables -n -L INPUT
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
DROP       all  --   
DROP       all  --

Another commonly used command iptablesis to allow network traffic from a service or port. For example, to allow users to connect via SSH, HTTP, and IMAP, you can use the following commands:

# iptables -A INPUT -m state --state NEW -p tcp --dport 22 -j ACCEPT
# iptables -A INPUT -m state --state NEW -p tcp --dport 80 -j ACCEPT
# iptables -A INPUT -m state --state NEW -p tcp --dport 143 -j ACCEPT
# iptables -n -L INPUT
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
DROP       all  --   
DROP       all  --
ACCEPT     tcp  --              state NEW tcp dpt:22
ACCEPT     tcp  --              state NEW tcp dpt:80
ACCEPT     tcp  --              state NEW tcp dpt:143

It is considered useful, to maintain a healthy atmosphere in the system, to remove old or unused rules. The easiest way to delete rules iptablesis to access the rules by line number, which can be obtained using the option --line-numbers. However, you should be careful here, since deleting a rule will lead to a change in the numbers of all the rules located below it in the chain:

# iptables -n -L INPUT --line-numbers
Chain INPUT (policy ACCEPT)
num  target     prot opt source               destination
1    DROP       all  --   
2    DROP       all  --
3    ACCEPT     tcp  --              state NEW tcp dpt:22
4    ACCEPT     tcp  --              state NEW tcp dpt:80
5    ACCEPT     tcp  --              state NEW tcp dpt:143
# iptables -D INPUT 2
# iptables -D INPUT 1
# iptables -n -L INPUT --line-numbers
Chain INPUT (policy ACCEPT)
num  target     prot opt source               destination
1    ACCEPT     tcp  --              state NEW tcp dpt:22
2    ACCEPT     tcp  --              state NEW tcp dpt:80
3    ACCEPT     tcp  --              state NEW tcp dpt:143

There are more specific conditions that depend on the general conditions described above. More information about this can be found in man( iptables(8)and ip6tables(8)).

7.4.3. Create rules

Each rule creation operation requires one invocation of the iptablesor command ip6tables. Entering these commands manually can be a time-consuming task, so usually these commands are executed in the form of scripts that allow you to automatically configure the system as needed, each time you boot the computer. Such scripts can be written manually, but there is a more advanced way, which is to use the program fwbuilder. To install it, use the following command:

# apt install fwbuilder

The principles for creating rules in a program are simple. First, describe all the elements of the system to which the rules that you want to create will be extended. Among these elements, the following can be noted:

  • The firewall itself with its network interfaces.
  • The network and its corresponding IP address ranges.
  • Servers.
  • Ports owned by services running on servers.

Next, create the rules using the graphical interface and dragging the corresponding elements with the mouse. Context menus can be used to change conditions (for example, to create conditions that are opposite to those specified). Then you need to select and configure actions.

Since IPv6 is also taken into account, you can either create two separate sets of rules, for IPv4 and IPv6, or create only one set and allow you to fwbuildertranslate the rules according to the addresses assigned to the objects.

Fig. 7.2. The main window of fwbuilder The

result of work with fwbuilderwill be a script to configure the firewall in accordance with the specified rules. The modular architecture of the program makes it possible to create scripts designed for various systems, including iptablesfor Linux,ipffor FreeBSD and pffor OpenBSD.

7.4.4. Applying rules at every system boot

In order to apply the firewall rules every time the system boots, you need to register the configuration script in the upfile directive /etc/network/interfaces. In the following example, the script is stored at /usr/local/etc/arrakis.fw.

auto eth0
iface eth0 inet static
    up /usr/local/etc/arrakis.fw

This example assumes that you are using to configure network interfaces ifupdown. If you use other tools (like NetworkManageror systemd-networkd), refer to their documentation in order to find out how to execute the script after turning on the interface.


Today we talked about working with the firewall built into the Linux kernel netfilter, discussed the features of IPv4 and IPv6 traffic management using the iptablesand commands ip6tables. We looked at a graphical tool for creating rules fwbuilderand showed how to automatically set rules when the system boots. Next time we will share with you the translation of section 7.5, which is devoted to monitoring Kali Linux.

Dear readers! How do you solve traffic filtering problems on Linux?

Also popular now: