How to set up smartphones and PCs. Informational portal

The key concepts in iptables are.

IPTables is a utility used to manage firewalls in Linux. It is a powerful and handy tool for unwanted connections. The whole process is wrapped up in iptables rules, which can be edited and viewed. For more information, see the article.

History of creation

Before IPTables on Linux used the IPFW firewall, borrowed from BSD. Then, with the 2.4 Linux kernel, it came with the Netfilter firewall and the IPTables utility to manage it. In the methodology of her work, all aspects have been preserved and functionally slightly expanded.

Structure and structure of IPTables

When a packet enters the firewall, it goes through several checks. This can be a checksum or any other kernel-level analysis. Then it is the turn to go through the PREROUTING chain. Next, it is checked according to which the redirection to the next chain occurs. If the packet does not have an address, as, for example, in TCP, then it is directed to the FORWARD chain. In cases where there is a specific address, the INPUT chain follows, and then the daemons or services for which it is intended. The response from them must also go through several chains, for example OUTPUT. The final link in this process is the POSTROUTING chain.

Now a little about chains. Each of them contains several tables. Their names can be repeated, but this does not affect the work in any way, since they are not interconnected.

The tables, in turn, contain several rules. In fact, a rule is a certain condition that must be met by the package being checked. Depending on the outcome, a certain action is performed on the package.

Thus, going through all the stages of the network, the packet sequentially visits all chains and in each is checked for compliance with the condition of a certain rule. If the table is not generated by the user, then the default action is performed, basically, it is ACCEPT, which allows you to continue moving further, or DROP, which stops the packet.

The preset chains come in the following categories:

  • PREROUTING... Initial processing of all incoming packets.
  • INPUT... This includes those packages that are sent directly to the local computer.
  • FORWARD... Used for "transit packets" that follow the routing table.
  • OUTPUT... Used for outgoing packets.
  • POSTROUTING... The last stage in the passage of all chains by the outgoing packet.

In addition to the built-in chains, users can create or delete their own.

Viewing and Managing IPTables Rules

As mentioned earlier, all chains contain certain conditions for packages. The IPTables utility is used to view and manage IPTables rules. Each individual rule is a line with a set of conditions for packages, as well as actions on them, depending on the outcome.

The command format looks like this: iptables [-t name of the table being processed] the command being invoked [criteria] [action to be performed].

Anything that is contained in can be omitted. If this is a parameter specifying a table, then filter will be used. To use a specific name, you need to add the -t switch. The invoked command allows you to invoke the required action, for example, add or remove an IPTables rule. The "criteria" specifies the parameters by which the selection will take place. And in the "action" the action is applied, which must be performed if the condition is met.

Commands for creating and viewing IPTables rules

  • Append (-A). When using the command, you specify the chain and table to which you want to add the required rule. The value of the team is that it does it at the bottom of the entire list.
  • Delete (-D). As the name implies, it removes the rule. As parameters, you can specify both the full name and the numbers assigned to them.
  • Rename-chain (-E). Changes the name of the chain. The command specifies the old name, then the new name.
  • Flush (-F). Clearing absolutely all the rules of a specific table.
  • Insert (-I). This command inserts the required rule into the place indicated by the number.
  • List (- L). Viewing iptables rules. If no table is specified, then the default filter will be used.
  • Policy (-P). The default policy for the specified chain is used.
  • Replace (-R). Changes the rule under the specified number to the required one.
  • Delete-chain (-X). This command deletes all created chains. Only the pre-installed ones will remain.
  • Zero (-Z). Will reset the counters of the transmitted data in the specified chain.

A little about the package selection parameters

They can be roughly divided into three types:

  • General criteria... They can be specified for any rules. They do not require the connection of special extensions and modules, and also do not depend on which protocol will be used.
  • Not general criteria. They are made available using general criteria.
  • Explicit. In order to use this type, you need to connect special plugins for netfilter. In addition, the command must use the -m switch.

It is worth talking a little about the frequently encountered parameters used in packet analysis:

  • Protocol (-p). Indicates protocol.
  • Source (-s). This parameter defines the IP address of the source from which the packet came. It can be specified in several ways. A specific host, address, or an entire subnet.
  • Destination (-d). The destination address of the packet. Also, like the previous one, it can be described in several ways.
  • In-interface (-i). Specifies the inbound interface of the package. Mostly used for NAT or on systems with multiple interfaces.
  • Out-interface (-o). Outgoing interface.

A few examples

To view IPTables nat rules? you need to use the command - "iptables -L -t nat". Check the general status of the firewall - "iptables -L -n -v". In addition, this command allows you to see the IPTables rules that are available in the entire system. Insert a rule at a specific place in the table, for example, between the first and second lines - "iptables -I INPUT 2 -s 202.54.1.2 -j DROP". Then see if it was added - "iptables -L INPUT -n --line-numbers".

To block a specific address, for example 12.12.12.12 - "iptables -A INPUT -s 12.12.12.12 -j DROP".

Iptables reference - "man iptables". If you need information on a specific command - "iptables -j DROP -h".

Finally

Use IPTables commands with caution, as incorrect configuration (unknowingly) can lead to network failures or complete failure. Therefore, it is worthwhile to study the manuals and instructions in detail before configuring. In the right hands, IPTables can be turned into a reliable protector of network connections. System administrators actively use the utility to create connections isolated from unauthorized access.

Several times I have come across the fact that even people who are not stupid in general make absolutely unforgivable mistakes. For example, they open the port on which the database is running to the entire Internet. This is often the case for DevOps beginners who have been coding all their lives and now their responsibilities include setting up servers as well. There are good tutorials on the net on basic firewall setup in Linux and other * nix, but often these are sheets for many screens. So, hopefully someone will find this more concise tutorial useful.

Important! It is very easy to mistakenly fire a car in such a way that you will not enter it again. This is especially true for cloud hosting. For example, if in AWS you close all ports from 1024 to 65536, for some reason the machine is closed after a reboot. generally all ports. If you're hosting in the clouds, it's best to configure your firewall through the hosted web interface.

A quick note on terminology. The firewall built into the Linux kernel is called Netfilter, and iptables is the utility for managing this firewall. Many people mistakenly think that the firewall is called iptables. This is not true. Saying something like "I am filtering packets with iptables" shows others that you are illiterate.

In general, what tasks can be solved using Netfilter:

  • Allow / deny incoming traffic to specific ports using specific protocols (IPv4 / IPv6, TCP / UDP) from specified addresses (IP, MAC) or subnets;
  • Everything is the same for outgoing traffic;
  • You can, for example, completely ignore all ICMP packets;
  • Configuring NAT, see the article on a Raspberry Pi router;
  • I heard that real gurus can set up protection against DDoS and brute force, restrict network access to specific applications, users or groups, and do other crazy things;

Note that the iptables utility seemed to me at first extremely inconvenient compared to ipfw in FreeBSD. Fortunately, after working with it for a while, all this many flags like -A, -D, -j and others become familiar, so be patient. Let's take a look at the main commands.

Show all rules:

iptables -L -n

You may notice that Netfilter has some kind of "chains" - at least INPUT, OUTPUT and FORWARD. I personally also have a Docker chain on my car. For the first time, you can think of the first two as all incoming and outgoing traffic, respectively, and temporarily forget about the rest. Chances are good that you will never need them at all.

Remove all rules:

iptables -F

Change policy (default behavior) chaining:

iptables -P INPUT DROP
iptables -P INPUT ACCEPT

Deny access from host / subnet:

iptables -A INPUT -s 123.45.67.89 -j DROP
iptables -A INPUT -s 123.45.0.0/ 16 -j DROP

You can also use domain names:

iptables -A INPUT -s example.com -j DROP

Barring outgoing connections:

iptables -A OUTPUT -d 123.45.67.89 -j DROP

Negatives can be used in rules:

iptables -A INPUT! -s 123.45.67.89 -j DROP

Deleting a rule by its number in the chain:

iptables -D INPUT 1

Removing a rule based on what it does:

iptables -D INPUT -s 123.45.67.89 -j DROP

The -p option indicates the protocol. You can use all, icmp, tcp, udp, or the protocol number from / etc / protocols. Flag - -sport indicates the port from which the packet was sent, and - -dport specifies the destination port:

iptables -A INPUT -p tcp --sport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -j ACCEPT

Insert a rule at the beginning of a chain:

iptables -I INPUT ...

Or you can specify a specific position:

iptables -I INPUT 3 ...

iptables-save> / etc / iptables.rules

Restore rules:

iptables-restore< / etc/ iptables.rules

Now let's look at some practical examples. This is, for example, the emulation of a net split in a test that checks the behavior of an application that uses Akka Cluster:

run (node1, s "iptables -A INPUT -s $ node2 -j DROP")
run (node1, s "iptables -A INPUT -s $ node3 -j DROP")
run (node1, s "iptables -A OUTPUT -d $ node2 -j DROP")
run (node1, s "iptables -A OUTPUT -d $ node3 -j DROP")

Recovery is exactly the same, except that the -A flag is replaced with the -D flag.

Another example. It is required to find out which ports are listening on the machine and close the extra ones. We go to the car and say:

netstat -tuwpln

Output example:

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID / Prog name
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 3210 / nginx
tcp 0 0 0.0.0.0:4369 0.0.0.0:* LISTEN 1789 / epmd
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 797 / sshd
tcp 0 0 127.0.0.1:5432 0.0.0.0:* LISTEN 990 / postgres

Nginx and SSHd are browsing the internet, that's fine. PostgreSQL only listens to the local interface, so there is no problem with it either. But the epmd sticks out (you can check it with telnet from another machine), and this is no good. You can only close port 4369. How to do this was shown above. Or you can go even further and deny all connections from the outside to port 81 and older.

Introduction and history

Netfilter- a firewall (aka firewall, aka firewall, aka firewall ...) has been built into the Linux kernel since version 2.4. Netfilter is controlled by a utility iptables(For IPv6 - ip6tables). Before netfilter / iptables was Ipchains which was part of the Linux 2.2 kernels. Prior to ipchains, Linux had the so-called ipfw (IPV4 firewal) ported from BSD. The management utility is ipfwadm. The netfilter / iptables project was founded in 1998 by Rusty Russell (who has also led past developments). In 1999, the Netfilter Core Team (abbreviated as coreteam) was formed. The developed firewall was officially named netfilter. In August 2003, Harald Welte became the head of coreteam.

Projects ipchains and ipfwadm changed how the Linux kernel protocol stack works, since before netfilter there was no way in the kernel architecture to include additional package management modules. iptables kept the main idea ipfwadm- a list of rules, consisting of criteria and an action that is performed if the package matches the criteria. V ipchains a new concept was introduced - the ability to create new chains of rules and the transition of packets between chains, and in iptables the concept was expanded to four tables (in modern netfilters - more than four), delimiting the chains of rules by task: filtering, NAT, and packet modification... Iptables also extended the statefulness of Linux by allowing the creation of session-level firewalls.

Netfilter / iptables architecture

Prerequisites ()

As mentioned above, Netfilter requires a 2.6 kernel (or at least 2.3.15). In addition, if you need the CONFIG_NETFILTER settings, CONFIG_IP_NF_IPTABLES, CONFIG_IP_NF_FILTER (filter table), CONFIG_IP_NF_NAT (nat table), CONFIG_BRIDGE_NETFILTER, as well as numerous additional modules: CONFIG_NIP_NF_IPTABLES, CONFIG_NIP_NF_FIGIP connection tracking module) additional types of packet matching patterns: LIMIT, MAC, MARK, MULTIPORT, TOS, TCPMSS, STATE, UNCLEAN, OWNER), CONFIG_IP_NF_TARGET_ * (additional actions in the rules: REJECT, MASQUERADE, REDIRECT, LOG, TCPMSS), CONFIG_IPAT_NFIPCHACOMPchains CONFIG_BRIDGE_NF_EBTABLES and CONFIG_BRIDGE_EBT_ * for bridge mode, others are CONFIG_IP_NF_ * and CONFIG_IP6_NF_ *. It is also useful to specify CONFIG_PACKET.

As seen, nat table and mangle can modify the recipient or sender of a network packet. This is why the network packet is checked against the routing table several times.

State detection engine (conntrack)

Above in the text, the concept of "determining states" was indicated several times, it deserves a separate topic for discussion, but nevertheless, I will briefly touch on this issue in the current post. In general, the mechanism for determining states (aka state machine, aka conn ection track ing, he is conntrack) is part of the packet filter and allows you to determine which connection / session the packet belongs to. Conntrack analyzes the status of all packets except those marked as NOTRACK on raw table... Based on this state, the package belongs new connection (state NEW), already established connection (state ESTABLISHED), additional to the existing one ( RELATED), or to " to another"(undefined) connection (state INVALID). The state of the packet is determined based on the analysis of the headers of the transmitted TCP packet. Conntrack module allows you to implement a session layer (fifth) firewall. The utility is used to control this mechanism. conntrack, as well as the parameter of the iptables utility: -m conntrack or -m state(deprecated). The conntrack stores the state of the current connections in the kernel. They can be viewed in / proc / net / nf_conntrack (or / proc / net / ip_conntrack).

So that thoughts do not turn into a mess, I think this brief information will be enough to understand further material.

Managing Netfilter Network Filtering Rules (Using the iptables Command)

Iptables utility is the interface for managing netfilter firewall... This command allows you to edit the rules of tables, tables and chains. As I already said - every rule is a record / line containing the selection of network packets and above the packets that match the specified rule. Iptables command requires root rights for its work.

In general, the command format is as follows:

Iptables [-t]

All parameters in square brackets - optional... The default is filter table, if you need to specify another table, then you should use the key -t indicating name... The name of the table is followed by the defining action ( For example: insert a rule, or add a rule to the end of the chain, or delete a rule). sets the selection parameters. indicates what action should be performed if the selection criteria in the rule ( For example: transfer the packet to another chain of rules, "discard" the packet, issue an error message to the source ...).

Below are the commands and parameters for the iptables utility:

Parameter Description Example
Commands
--append (-A) Add the specified rule to the specified chain and specified table to the END of the list. iptables -A FORWARD criteria -j action
--delete (-D) Deletes the rule (s) specified by the number (s) or rule (s). The first example removes all rules numbered 10,12 in all chains in the filter tables, the second example removes the given rule from the mangle table in the PREROUTING chain. iptables -D 10.12
iptables -t mangle -D PREROUTING criteria -j action
--rename-chain (-E) Change the name of the chain. iptables -E OLD_CHAIN ​​NEW_CHAIN
--flush (-F) Clears all rules of the current table. For all packets that refer to already established connections, apply the terminal action ACCEPT - skip iptables -F
--insert (-I) Inserts the specified rule at the location specified by the number. iptables -I FORWARD 5 criteria -j action
--list (abbreviated -L) Viewing existing rules (without explicitly specifying the table - the filter table of all chains is displayed). iptables -L
--policy (-P) Sets the default policy for the given chain. iptables -t mangle -P PREROUTING DROP
--replace (-R) Replaces the rule specified by the number with the one specified in the criteria. iptables -R POSROUTING 7 | criteria -j action
--delete-chain (-X) Delete ALL manually created chains (leave only the standard INPUT, OUTPUT, FORWARD, PREROUTING and POSTROUTING). iptables -X
--zero (-Z) Resets the transmitted data counters in the chain. iptables -Z INPUT
Options
--numeric (-n) Doesn't resolve addresses and protocols when outputting.
--line-numbers Specify rule numbers in output (can be used in conjunction with -L). iptables -L --line-numbers
--help (-h) where without her
-t table Specifies the name of the table on which to perform the action. The example dumps the nat table in all chains. iptables -t nat -F
--verbose (-v) Detailed conclusion. iptables -L -v

Criteria (parameters) for selecting network packets of the iptables command

Network packet selection criteria tacitly divided into several groups: General criteria, Implicit criteria, Explicit criteria. can be used in any rules, they do not depend on the type of protocol and do not require loading of extension modules. (I would call uncommon), those criteria that are loaded implicitly and become available, for example, when specifying a general criterion --protocol tcp | udp | icmp... Before use, you need to connect additional extension(these are peculiar plugins for netfilter). Additional extensions loaded using the parameter -m or --match... So, for example, if we are going to use the criteria state, then we must explicitly indicate this in the rule line: -m state to the left of the used criterion. The difference between explicit and implicit non-general criteria is that the explicit ones need to be loaded explicitly, and the implicit ones are loaded automatically.

All criteria can be used sign! before the criterion value. This will mean that this rule applies to all packages that do not match this parameter. for instance: criterion --protocol! tcp will denote that all packages that not are the TCP protocol fit the rule. However, the latest versions of iptables (in particular, 1.4.3.2 and higher) no longer support this syntax and do not require the use of --protocol! tcp, a ! --protocol tcp giving the following error:

Using intrapositioned negation (`--option! This`) is deprecated in favor of extrapositioned (`! --Option this`).

Below in the form of a table are commonly used packet selection parameters:

Parameter Description Example
Common parameters
--protocol
(abbreviation -p)
Defines the protocol. Options tcp, udp, icmp, all or any other protocol defined in / etc / protocols iptables -A INPUT -p tcp
--source
(-s, --src)
Source IP address of the packet. It can be defined in several ways:
  • Single host: host.domain.tld, or IP address: 10.10.10.3
  • Pool addresses (subnet): 10.10.10.3/24 or 10.10.10.3/255.255.255.0

It is strongly discouraged to use domain names that require DNS queries to be resolved (resolved), since at the configuration stage, netfilter DNS may not work correctly. Also, note that names are resolved only once - when adding a rule to a chain. Subsequently, the IP address corresponding to this name may change, but this will not affect the rules already written down (the old address will remain in them). If you specify a domain name that resolves into several IP addresses, then a separate rule will be added for each address.

iptables -A INPUT -s 10.10.10.3
--destination
(-d)
The destination IP address of the packet. It can be defined in several ways (see --source). iptables -A INPUT --destination 192.168.1.0/24
--in-interface
(-i)
Defines the interface on which the packet arrived. Useful for NAT and machines with multiple network interfaces. Used in the INPUT, FORWARD and PREROUTING chains. It is possible to use the "+" sign, then all interfaces starting with the name + are assumed (eg eth + - all eth interfaces). iptables -t nat -A PREROUTING --in-interface eth0
--out-interface
(-o)
Defines the interface from which the packet will leave. Useful for NAT and machines with multiple network interfaces. Used in the OUTPUT, FORWARD, and POSTROUTING chains. It is possible to use the "+" sign. iptables -t nat -A POSTROUTING --in-interface eth1
Implicit (non-generic) parameters
-p proto -h displays help on implicit parameters of the proto protocol. iptables -p icmp -h
--source-port
(--sport)
Source port, only possible for --protocol tcp, or --protocol udp iptables -A INPUT --protocol tcp --source-port 25
--destination-port
(--dport)
Destination port, possible only for protocols --protocol tcp, or --protemocol udp iptables -A INPUT --protocol udp --destination-port 67
Explicit parameters
-m state --state (deprecated)
he is
-m conntrack --ctstate

Connection status. Available options:

  • NEW(All packages establish a new connection)
  • ESTABLISHED(All packages belonging to the established connection)
  • RELATED(Packages that do not belong to the established connection, but are associated with it. For example - FTP in active mode uses different connections for data transfer. These connections are related.)
  • INVALID(Packets that cannot be identified for one reason or another. For example, ICMP errors that do not belong to existing connections)
  • etc. (in more detail in the documentation)
iptables -A INPUT -m state --state NEW, ESTABLISHED iptables -A INPUT -m conntrack --ctstate NEW, ESTABLISHED
-m mac --mac-source Specifies the MAC address of the network node that sent the packet. The MAC address must be in the form XX: XX: XX: XX: XX: XX. -m mac --mac-source 00: 00: 00: 00: 00: 0

Actions on packages

This heading would be more correctly rephrased in " Actions on packages that match the selection criteria". So, to commit any actions on packages, you need to set the key -j (--jump) and indicate what specific action to perform.

Actions on packages can take the following values:

  • ACCEPT- the packet leaves this chain and is transmitted to the next one (literally - ACCEPT).
  • DROP- discard a packet that meets the condition, while the packet is not transferred to other tables / chains.
  • REJECT- drop the packet by sending an ICMP message to the sender, while the packet is not transferred to other tables / chains.
  • RETURN- return the packet to the previous chain and continue its passage starting from the next rule.
  • SNAT source in the package. Can only be used in chains POSTROUTING and OUTPUT in the nat tables.
  • DNAT- apply broadcast address destination in the package. Can be used in a chain PREROUTING in the nat table. (in exceptional cases - in the OUTPUT chain)
  • LOG- log the packet (sent to the daemon) and process it with the rest of the rules.
  • MASQUERADE- used instead of SNAT if there is a dynamic IP connection (it is allowed to specify only in the chain POSTROUTING nat tables).
  • MARK- used to set labels on packets, passed for processing to further rules.
  • and etc.

In addition to these actions, there are others that can be found in the documentation (perhaps soon I will supplement the article in the course of mastering the topic). Some actions have additional parameters.

The table below shows examples and descriptions of additional parameters:

Parameter Description Example
DNAT (Destination Network Address Translation)
--to-destination specifies which IP address should be substituted for the destination address. In the example, in all packets of the tcp protocol arriving at the address 1.2.3.4, this address will be replaced by 4.3.2.1. iptables -t nat -A PREROUTING -p tcp -d 1.2.3.4 -j DNAT --to-destination 4.3.2.1
LOG
--log-level Used to set the logging level (). The example sets the maximum logging level for all tcp packets in the filter table of the FORWARD chain. iptables -A FORWARD -p tcp -j LOG --log-level debug
--log-prefix Sets the text (prefix) that will be used before all messages iptables... (very convenient for what follows) The prefix can contain up to 29 characters, including spaces. In the example, all tcp packets in the filter table of the INPUT chain with the INRUT-filter prefix are sent to syslog. iptables -A INPUT -p tcp -j LOG --log-prefix "INRUT-filter"
--log-ip-options Allows to enter into various information from the IP packet header. iptables -A FORWARD -p tcp -j LOG --log-ip-options
and etc...

This concludes the theory about the netfilter / iptables network filter. In the next article, I will provide practical examples for assimilating this theory.

Summary

In this article, we have covered very briefly the basic concepts of a network filter in Linux. So, the netfilter / iptables subsystem is part of the Linux kernel and is used to organize various filtering schemes and manipulate network packets. At the same time, each packet passes from the network interface to which it arrived and further along a certain chain route, depending on whether it is intended for a local system or "non-local". Each chain consists of a set of tables containing a sequential set of rules. Each rule consists of a certain criterion / criteria for selecting a network packet and some action with a packet that matches these criteria. In accordance with the specified rules, any action can be performed on the packet (For example, transfer to the next / another chain, discard the packet, modify the content or headers, etc.). Each chain and each table has its own purpose, functionality, and place in the package path. For example, to filter packets, the filter table is used, which is contained in three standard chains and can be contained in user-defined chains. The packet path is terminated either on the outgoing network interface or delivered to the local process / application.

Literature

Quite a lot of interesting information in Russian is contained here:

  • http://www.opennet.ru/docs/RUS/iptables/
  • http://ru.wikibooks.org/wiki/Iptables

More in-depth material is available in bourgeois here:

  • http://www.frozentux.net/documents/ipsysctl-tutorial/
  • http://www.netfilter.org/documentation/index.html

Regards, Mc.Sim!

A reliable firewall is one of the most important aspects of protecting any modern OS. Most Linux distributions contain several different firewall tools. This tutorial is dedicated to one of the most popular - iptables.

So iptables is the default firewall included with most Linux distributions by default (nftables is being developed to replace it). In fact, iptables is the user interface for managing the netfilter system, which in turn manages the Linux networking stack. iptables compares each incoming packet against a set of established rules, and then decides what to do with it next.

I talked about how iptables works. This article focuses on practical examples showing how to create a basic ruleset for an Ubuntu 14.04 server.

Basic iptables commands

This section contains basic commands that can be used to create a complex set of rules and control the iptables interface as a whole.

Remember: iptables commands must be run with root privileges. This means that you need to do one of the following:

  • log in as root user;
  • use su or sudo -i to expand the root shell;
  • start all commands with sudo (recommended on Ubuntu).

This guide applies the latter option.

So, first you need to look at the list of current iptables rules. The -L flag is used for this:

sudo iptables -L
Chain INPUT (policy ACCEPT)


target prot opt ​​source destination
Chain OUTPUT (policy ACCEPT)
target prot opt ​​source destination

As you can see, the list contains three default chains (INPUT, OUTPUT and FORWARD), each of which has a default policy (currently ACCEPT). You can also see the names of the columns. But this list does not include the rules themselves, as Ubuntu does not come with a default set of rules.

Using the -S flag, this list can be viewed in a different format that reflects the commands required to activate rules and policies:

sudo iptables -S
-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT

To replicate configurations, all you need to do is enter sudo iptables at the beginning of each result line. (Depending on your configurations, this procedure can be a little more complicated when connecting remotely; if the rules to allow the current connection are not already in place, you should not set the DROP policy.)

To reset the current rules (if any), type:

sudo iptables -F

Again, the default policy is very important at this point because it will not be changed with the previous command even though all rules will be removed from the chains.

Before you reset the rules on a remote connection, you must make sure that the ACCEPT policy is set in the INPUT and OUTPUT chains. This is done like this:

sudo iptables -P INPUT ACCEPT
sudo iptables -P OUTPUT ACCEPT
sudo iptables -F

Once you have created the rules to allow remote connections, you can set the DROP policy. So, let's move on directly to creating rules.

Creating iptables rules

As mentioned above, this tutorial focuses on working with the INPUT chain, since it is responsible for incoming traffic. First, you need to consider the already mentioned rule - the rule that allows the current SSH connection.

It looks like this:

sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED, RELATED -j ACCEPT

Of course, it may seem incredibly difficult at first; to understand this rule, check out its components:

  • -A INPUT: the -A flag adds ( append) rule at the end of the chain. This part of the command tells iptables to append the rule to the end of the INPUT chain.
  • -m conntrack: in addition to a set of basic functions, iptables also has a set of extensions, or modules, which are responsible for additional features of the firewall. This part of the command says that the user needs access to the functions of the conntrack module. This module allows you to use commands to decide what to do with a package based on its relationship to previous connections.
  • —Ctstate: one of the commands available when calling the conntrack module. This command allows you to track the relationship of packages to other packages previously viewed. It is set to ESTABLISHED (which allows it to accept packets that are part of an existing connection) and RELATED (accepts packets that are associated with an already established connection). It is this part of the rule that is responsible for the current SSH session.
  • jACCEPT: indicates the action (target) to be performed on the package that matches the rule. In this case, iptables will accept packets that meet the previous criteria.

This rule should be placed at the beginning to ensure that existing connections match the rules, are accepted, and exit the chain without reaching the DROP rules.

By requesting the list of rules, you can see the changes:

sudo iptables -L
Chain INPUT (policy ACCEPT)
target prot opt ​​source destination
ACCEPT all - anywhere anywhere ctstate RELATED, ESTABLISHED
Chain FORWARD (policy ACCEPT)
target prot opt ​​source destination
Chain OUTPUT (policy ACCEPT)
target prot opt ​​source destination

Now that you are familiar with the basic syntax, create a few more rules that accept a join.

Accepting other important connections

Previously, iptables received the command not to drop all current connections, and also to accept all connections related to them. Now you need to create rules that accept connections that do not meet the above criteria.

Leave two ports open: the SSH port (this tutorial uses the default port 22; if this value has been changed, do not forget to enter the new value); in addition, assume that this computer is running a web server on port 80 by default (do not add this rule if it is not).

So, the lines that need to be used to create such rules look like this:

sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT

As you can see, they are very similar to the first rule; perhaps they have an even simpler structure. New options:

  • ptcp: This option allows packets using TCP (a stream-oriented protocol that is used by most applications because it allows reliable communication).
  • dport: This option is available using the -p tcp flag. It specifies the inbound port to match the packet port on. The first rule allows TCP packets directed to port 22 to pass through, and the second rule accepts TCP traffic directed to port 80.

Now we need to create another ACCEPT rule to make sure the server is working as expected. Typically, services interact by exchanging packages; to do this, they use a pseudo-ring network interface called a loopback device, which routes traffic back to its source and not to other computers.

That is, if service 1 needs to establish a connection with service 2 listening for connections on port 4555, then service 1 sends a packet to port 4555 using a loopback device. This behavior must be allowed because it is essential for many programs to function properly.

To do this, add the following rule:

sudo iptables -I INPUT 1 -i lo -j ACCEPT

It differs slightly from the previous rules; consider it in more detail:

  • IINPUT 1: The -I flag tells iptables to insert the rule. This flag is different from the -A flag (which simply adds the rule to the end of the chain); it indicates the chain in which the rule should be inserted and the location of the rule in it. In this case, the rule needs to be inserted at the very beginning of the INPUT chain, as a result of which all rules will move one position. This rule should be placed at the beginning of the chain, since it is one of the main rules and should not depend on others.
  • ilo: This rule component allows packets that use the lo interface to pass (“lo” is another name for a loopback device). This means that any packet using this interface must be accepted.

To view the current rules, use the -S flag, since the -L flag does not display some information (for example, the interface to which the rule is bound, which is very important in the case of the last rule):

sudo iptables -S
-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m conntrack --ctstate RELATED, ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT

Creating DROP Rules

So, at the moment, 4 rules have been created that accept packets based on certain criteria. However, the server is not currently blocking any other packets.

If a packet traverses the INPUT chain and does not meet any of the four rules, the default policy (ACCEPT) will be executed, which will somehow accept this packet. Now it needs to be changed.

This can be done in two ways, which have significant differences.

The first way is to edit the default INPUT chain; to do this, type:

sudo iptables -P INPUT DROP

This policy will monitor and discard all packets that do not match any of the rules in the INPUT chain. One of the consequences of this type of construct is that it will drop packets even after the rules themselves are flushed.

Of course, this increases the security level of the server; however, this can have serious consequences if the user has no other way to connect to the server. More often than not, hosting providers provide a web console to connect to the server in case of such problems. This console works like a virtual local connection, so iptables will not respond to it.

You can have the server automatically drop the connection if the rules are removed. This will make the server more secure and more difficult to access. It also means that you can add rules to the end of the chain, and all unwanted packets will be dropped.

An alternative approach is to add a rule at the end of the chain to discard all non-matching packets while maintaining the ACCEPT policy.

To return the ACCEPT policy to the INPUT chain, type:

sudo iptables -P INPUT ACCEPT

Now you can add a rule to the end of this chain that will drop all non-matching packets:

sudo iptables -A INPUT -j DROP

Under normal operating conditions, the result will be exactly the same as using the DROP policy. This rule discards every packet that reaches it, which prevents packets that do not match the specified rules from reaching the server.

Basically, the second approach is used when it is necessary to preserve the ACCEPT policy that accepts traffic. That is, even if all the rules are cleared, the user can still access the machine on the network. This approach allows the default actions to be taken without having to change the policy that will be applied to the empty chain.

Of course, this also means that any rule that needs to be inserted at the end of the chain must come before the discard rule. This can be done either by temporarily removing the reset rule:

sudo iptables -D INPUT -j DROP
sudo iptables -A INPUT new_rule
sudo iptables -A INPUT -j DROP

or by inserting a new rule at the end of the rung (but before the reset rule), specifying the line number. To add a rule to line 4, type:

sudo iptables -I INPUT 4 new_rule

If there are many rules, calculating the line number manually is rather problematic; in this case iptables can number the lines:

sudo iptables -L --line-numbers
Chain INPUT (policy DROP)

1 ACCEPT all - anywhere anywhere
2 ACCEPT all - anywhere anywhere ctstate RELATED, ESTABLISHED
3 ACCEPT tcp - anywhere anywhere tcp dpt: ssh
4 ACCEPT tcp - anywhere anywhere tcp dpt: http
Chain FORWARD (policy ACCEPT)
num target prot opt ​​source destination
Chain OUTPUT (policy ACCEPT)
num target prot opt ​​source destination

This ensures that the rule has been entered on the correct line.

Saving iptables settings

By default, all unsaved rules remain in effect until the next server restart; unsaved rules will be lost immediately upon reboot.

In some cases, this is useful because it allows users who have accidentally locked themselves out to gain access to the server. However, in most cases it is more convenient to save the rules and load them when the server starts.

This can be done in several ways; the simplest one is to use the iptables-persistent package, which can be downloaded from the default Ubuntu repository:

sudo apt-get update
sudo apt-get install iptables-persistent

During installation, the package will specify whether you want to save the current rules for further automatic loading; if the current rules have been tested (allow you to create SSH connections) and meet all the requirements, you can save them.

When the installation is complete, a new service called iptables-persistent will appear that will start when the server is rebooted and resume the set rules.

Outcomes

This guide will help you configure the firewall according to the user's requirements. Of course, there are many more such utilities, and some of them may be easier to use; however, iptables is one of the best tools out there, if only because it demonstrates some of the basic structures of netfilter and is included in many systems.

Tags:,

Every computer connected to the network is in potential danger. There are a lot of threats on the network, ranging from programs that will try to penetrate the system in any way and ending with hackers who want to gain access to the computer they need. And the software installed on the computer may contain not yet known and unpatched vulnerabilities, which may become a security hole.

If for home computers this is not very relevant, since they are connected to the network through routers and NAT, which hide them from the external network, then for servers it is more relevant than ever. The Linux operating system has a very flexible and reliable iptables firewall built into the kernel.

It is with the help of this program that the system is protected from external intrusions, port forwarding, as well as many more actions with traffic. But its downside is that it is a little tricky to set up. This article will cover setting up iptables for dummies. I hope that after that you can confidently use the basic capabilities of iptables.

The iptables and Netfilter subsystem have been built into the Linux kernel for quite some time. All network packets that pass through the computer, are sent by the computer, or are destined for the computer, the kernel directs through the iptables filter. There, these packages are amenable to checks and then for each check, if it is passed, the specified action is performed. For example, the packet is passed on to the kernel to be sent to the target program, or discarded.

Types of packages

All packets are divided into three types: incoming, outgoing and passing. Inbox are those that have been sent to this computer, outgoing are those that have been sent from this computer to the network. And passing ones are packets that just have to be forwarded further, for example, if your computer acts as a router.

Accordingly, in the iptables filter, all packets are divided into three similar chains:

  • Input- processes incoming packets and connections. For example, if some external user tries to connect to your computer via ssh or any website sends you its content when requested by the browser. All of these packages will end up in this chain;
  • forward- this chain is used for passing connections. This includes packets that are sent to your computer, but are not intended for it, they are simply forwarded over the network to their destination. As I said, this is observed on routers or, for example, if your computer distributes wifi;
  • output- this chain is used for outgoing packets and connections. This includes packages that were generated when you try to ping a site or when you launch your browser and try to open any site.

But if you think that you can just completely close the Input chain to increase security, then you are very much mistaken. The network uses both input and output chains. For example, you try to ping, data is sent through output, but the response comes through input. The same happens when browsing sites and other activities. But the forward chain may not be used at all if your computer is not a router. So the iptables configuration must be done very carefully.

Rules and actions

Before moving on to creating a list of iptables rules, you need to consider how they work and what they are. For each type of package, you can set a set of rules that will be checked in turn for compliance with the package, and if the package matches, then apply the action specified in the rule to it. Rules form a chain, so input, output and forward are called chains, or rule chains. There can be several actions:

  • ACCEPT- allow the packet to pass further along the chain of rules;
  • DROP- remove the package;
  • REJECT- reject the package, a message will be sent to the sender that the package was rejected;
  • LOG- make a record about the package in the log file;
  • QUEUE- send a package to a custom application.

Rules can check any matches, for example, by ip, by recipient or sender port, packet headers, and much more. If a packet does not match any of the rules, then the default action is applied to it, usually ACCEPT.

When we have figured out the rules, we can go back to the chains. In addition to those listed above, there are two additional chains of rules:

  • prerouting- the packet enters this chain before being processed by iptables, the system does not yet know where it will be sent, to input, output or forward;
  • postrouting- all passing packets that have already passed the forward chain are included here.

But that's not all. We also have iptables tables, with which it is also desirable to understand.

Ipatables

There is another level of abstraction above the chains of rules in iptables, and that's tables. There are several tables in the system, and they all have a standard set of input, forward and output chains. Tables are used to perform various actions on packets, for example, for modification or filtering. Now this is not so important for you and it will be enough to know that the filtering of iptables packets is carried out in the filter table. But we'll cover them all:

  • raw- designed to work with raw bags, while they have not yet been processed;
  • mangle- intended for modifying packages;
  • nat- Provides nat to work if you want to use your computer as a router;
  • filter- the main table for packet filtering, used by default.

With almost everything in theory, now let's look at the iptables command line utility, which is used to manage the iptables system.

Iptables utility

The iptables and netfilter subsystem are built into the kernel, but a set of utilities for managing all of this is not always supplied with the system. To install the utility on Ubuntu, type:

sudo apt install iptables

On Fedora-based distributions, the iptables installation is slightly different:

sudo yum install iptables

Once the iptables installation is complete, you can move on to configuration, but let's first look at the utility's syntax. Usually the command looks like this:

-t table action chain Extra options

Now let's take a look at the iptables parameters, the table indicates the table with which to work, this parameter can be omitted, the action is the desired action, for example, create or delete a rule, and the additional parameters describe the action and the rule to be performed.

It remains to consider the main actions that iptables allows you to perform:

  • -A- add a rule to the chain;
  • -WITH- check all the rules;
  • -D- remove the rule;
  • -I- insert a rule with the required number;
  • -L- display all the rules in the current chain;
  • -S- display all the rules;
  • -F- clear all rules;
  • -N- create a chain;
  • -X- delete the chain;
  • -P- set the default action.

Additional options for rules:

  • -p- specify the protocol, one of tcp, udp, udplite, icmp, icmpv6, esp, ah, sctp,
    mh;
  • -s- specify the ip address of the device sending the packet;
  • -d- specify the recipient's ip address;
  • -i- input network interface;
  • -o- outgoing network interface;
  • -j- select an action if the rule matches.

Now you can go on to look at examples of how iptables is configured.

Iptables Configuration Examples

We'll go over a few basic examples so you can consolidate what you read above.

List of rules

First, let's see how the iptables rules lookup is performed, the -L option is enough for this:

You can also specify the desired chain to display rules only for it:

iptables -L INPUT

Clearing rules

You cannot just disable iptables by stopping the iptables rule update service through systemd or even removing the set of configuration utilities. The subsystem works at the kernel level and does not depend on what you have installed there. Therefore, if you do something wrong, you will need to clear the rules. To do this, run:

Or just for a specific chain:

sudo iptables -F Input

Let me remind you that all these actions are performed for the default table - filter.

Default rules

As I already said, if no rule is suitable for a package, then the default action is applied to it. It can be set using the -p option:

sudo iptables -p INPUT ACCEPT
$ sudo iptables -p OUTPUT ACCEPT
$ sudo iptables -p FORWARD DROP

In this example, we allow INPUT and OUTPUT chains, but disallow FORWARD.

Blocking packages

To block packets, we can use the DROP action, we can filter packets that need to be blocked by many criteria, for example, protocol, ip address, netmask, port and much more.

This is how the command will look like, which allows you to add an iptables rule to block all incoming packets from 10.10.10.10:

sudo iptables -A INPUT -s 10.10.10.10 -j DROP

And now outgoing packets to the same address:

IP range locking is done in a similar way. To do this, you need to use the network mask 10.10.10.0/24. These will be all addresses from 10.10.10.0 to 10.10.10.255:

sudo iptables -A INPUT -s 10.10.10.0/24 -j DROP

Or an extended version of the mask:

sudo iptables -A INPUT -s 10.10.10.0/255.255.255.0 -j DROP

Also you can block all incoming ssh connections:

sudo iptables -A INPUT -p tcp --dport ssh -s 10.10.10.10 -j DROP

As you can see, adding an iptables rule is very easy.

Removing rules

Deleting iptables rules is performed in the same way as creating new ones, only instead of option A, you need to use option D. First, look at the list of rules:

For example, this is how you can delete the iptables rule that was created the second:

sudo iptables -A OUTPUT -s 10.10.10.10 -j DROP

You can also clear iptables completely by running the command with the -F option:

Top related articles