Iptables. Basic iptables commands. Actions on packages

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. There are good tutorials on the net on basic setting firewall 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 no longer enter it. This is especially true for cloud hosting. For example, if in AWS you close all ports from 1024 to 65536, after a reboot the machine for some reason turns out to be closed generally all ports. If you are hosting in the clouds, configure better firewall through the web-interface provided by the hosting.

A small 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 believe that the firewall is called iptables. This is not true. By saying something like "I am filtering packets with iptables", you show 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 know how to set up protection against DDoS and brute force, restrict network access to specific applications, users or groups, and do other crazy things;

I 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 consider the basic 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 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\u003e / 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.

Every computer on 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 to hackers who want to gain access to the computer they need. AND softwareinstalled on a 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. In the operating room linux system the very flexible and reliable iptables firewall is 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 disadvantage is that it is a little difficult to set up. This article will cover setting up iptables for dummies. After this I hope you can confidently use the basic iptables capabilities.

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 intended 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, a 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 were sent to this computer, outgoing are those 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 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.

The rules can check any matches, for example, by ip, by the 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 the ones 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 go here.

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

Ipatables tables

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 - designed to modify packages;
  • nat - makes nat 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 utility command line iptables, 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

And 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 look at the iptables parameters, the table indicates the table to work with, this parameter can be omitted, the action is the desired action, for example, create or delete a rule, and extra options describe an action and a rule to be performed.

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

  • -A - add a rule to the chain;
  • -FROM - 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 look at how 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 a 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 enable 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:

In this article, we will look at the order of traversing the tables and chains in each iptables table. The information will be useful when drafting rules and will give an understanding of the order in which the packet goes through all iptables tables and chains, especially when actions such as DNAT, SNAT, and TOS will be included in the rule sets.

The packet arriving at the firewall first goes to network device, is intercepted by the driver and passed to the system kernel. Then the packet goes through a number of tables and, depending on the rules in these tables, the further fate is decided.

Table 1. Order of FORWARD packets passing

Step Table Chain Note
1 Cable (i.e. Internet)
2
3 Mangle PREROUTING Usually this string is used to make changes to the packet header, for example, to change the TOS bits, etc.
4 Nat PREROUTING This chain is used for Destination Network Address Translation. Source Network Address Translation is done later in a different chain. Any kind of filtering in this chain can be performed only in exceptional cases.
5 Making a decision on further routing, i.e. at this point, it is decided where the packet will go - to a local application or to another node on the network.
6 Filter FORWARD Only those packets that go to another host get into the FORWARD chain. All transit traffic filtering should be performed here. Do not forget that traffic passes through this chain in both directions, be sure to take this circumstance into account when writing filtering rules.
7 Mangle FORWARD The packet then goes into the FORWARD\u003e chain of the mangle table, which should only be used in exceptional cases when it is necessary to make some changes to the packet header between two routing decision points.
8 Making a decision on further routing, i.e. at this point, for example, it is decided which interface the packet will go to.
9 Nat POSTROUTING This chain is primarily intended for Source Network Address Translation. Do not use it for filtering unnecessarily. Masquerading is also performed here.
10 Mangle POSTROUTING This chain is intended to make changes to the packet header after the last routing decision has been made.
11 Egress network interface (for example eth1).
12 Cable (let it be LAN).

As you can see, the packet goes through several stages before being passed on. At each of them, the packet can be stopped, be it the iptables chain or something else, but we are mainly interested in iptables. Note that there are no interface-specific chaining or anything similar. ALL packets that travel through our firewall / router pass through the FORWARD chain. Don't use the INPUT chain to filter transit packets, they just don't go there! Only those packets intended for this host move through this chain.

Table 2. The order of movement of INPUT packets

Step Table Chain Note
1 Cable (i.e. Internet)
2 Input network interface (e.g. eth0)
3 Mangle PREROUTING Usually used to make changes to the packet header, for example to set TOS bits, etc.
4 Nat PREROUTING Destination Network Address Translation Packet filtering is allowed here only in exceptional cases.
5 Deciding on routing.
6 Mangle INPUT The package goes into the INPUT chain of the mangle table. This is where the package header changes will be made before it is passed to the local application.
7 Filter INPUT This is where incoming traffic is filtered. Remember that all incoming packets addressed to us go through this chain, regardless of which interface they came from.
8 Local process / application

OUTPUT packets have the reverse order of traversing the tables. The order of passage is presented in table 3.

Table 3. Order of OUTPUT packets passing

Step Table Chain Note
1 Local process
2 Mangle OUTPUT This is where you make changes to the package header. Filtering done on this chain can have negative consequences.
3 Nat OUTPUT This chain is used for network address translation (NAT) in packets originating from local processes on the firewall.
4 Filter OUTPUT Outbound traffic is filtered here.
5 Deciding on routing. Here it is decided where the package will go next.
6 Nat POSTROUTING Source Network Address Translation (SNAT) is performed here. Avoid packet filtering along this chain to avoid unwanted side effects. However, you can stop packages here too, applying the default policy DROP.
7 Mangle POSTROUTING The POSTROUTING chain of the mangle table is mainly used for rules that must make changes to the packet header before it leaves the firewall, but after a routing decision has been made. This chain contains all packets, both transit and those created by local processes of the firewall.
8 Network interface (e.g. eth0)
9 Cable (i.e., Internet)

AND visual presentation passing packages:

This figure gives a pretty clear idea of \u200b\u200bthe order in which packets travel through the various chains. At the first routing decision point, all packets destined for a given host are directed to the INPUT chain, the rest to the FORWARD chain.

Note also the fact that packets with a destination address on the firewall may undergo broadcast network address (DNAT) in the PREROUTING chain of the nat table and, accordingly, further routing at the first point will be performed depending on the changes made.

steel, mink, beef, paper September 28, 2010 at 07:47 PM

The basics of iptables through the eyes of a baby in Debian

What will be discussed

Everything is very simple, once again explaining on the forum to beginners in linux world, that yes, how I understood that on the Internet it is impossible to find a put together article explaining not only the iptables settings, but also some network basics.
So for your attention, I present a small excursion on setting up a firewall in Linux. We will delve only into setting up netfilter / iptables, we will undoubtedly also touch on the rest of the applied questions, because we do not have enough complex answers to our questions ... And I will try to explain everything here as clearly as possible.

How it looks

We will consider a typical scheme for offices and apartments, yes, apartments! Few people have their own little server at home under the table, but most of the Internet at home is distributed through a router and most of them are also flashed with Linux.
This is a typical small office layout. When 1 computer (server) is connected to the Internet, and the rest are connected to the Internet through this server.

Let's go, little by little ...

And so what do we have:
  • server with 2 network cards and Debian Lenny installed on it
  • default on Debian Lenny firewall - netfilter / iptables
  • local network of N computers, all are connected through a switch, including the server
what is NAT
First, we need to understand that we will configure the most ordinary NAT (Network Address Translation). For those who are thirsty, at the end I will also mention the proxy server using squid as an example. As I said, we will chew on almost everything.
What is NAT? In fact, everything is simple, all computers have physical (MAC) and network (IP) addresses. We are currently interested in IP addresses. The IP address within the same network must be unique! And with the current IPv4 standard, only 4 294 967 296 (2 32) can be unique, which is not a lot and they are practically over. But do not worry, IPv6 is about to enter widespread use, and there are lots of addresses!
But here you can notice that there are much more computers than the number that allows IPv4, or you say that a friend's house has the same address as you! And this is where NAT comes in - it allows you to connect computer networks using a single IP address among themselves, the actions of the firewall are called SNAT (Source NAT or substitution of the source address). Those. in 99% of cases, your entire office goes online under 1 IP address, while inside the office everyone has their own. You can read about the classes of IP addresses on the Internet.

Now that we know what NAT is and what it is for, we can proceed directly to setting up the server.

transit traffic
All commands are executed as root (superuser). In Debian, so-called transit traffic is disabled by default, i.e. the default is to work only as a single machine. As you may have guessed, there is no NAT without transit traffic. To enable it, it is enough to change 1 digit - $ echo 1\u003e / proc / sys / net / ipv4 / ip_forwardbut this setting will crash after reboot, so it's better to fix the config - $ nano /etc/sysctl.conf then we are looking for a line # net.ipv4.ip_forward \u003d 1 and remove the hash (comment character) at the beginning of the line and check that the value is 1! Now you can start directly configuring iptables.
configure iptables
On the Internet, there are many articles on how to write rules in iptables and what can be done with them, it seemed to me the most complete and pleasant to read.
And so let's get started. First, let's clear the tables of unnecessary rules, suddenly there was something superfluous ...
$ iptables -F
$ iptables -t nat -F
$ iptables -t mangle -F

The excess was cleaned. It is very important to understand and remember that rules in iptables are applied hierarchically, i.e. the rule above will be executed earlier. All chains have ACCEPT policy by default - allow everything. which did not fall under the rules of this chain.
Let's agree that the interface looking to the local network is eth0, and to the Internet - eth1, the local network has addresses 192.168.0.0/24, and the provider gave us static address 10.188.106.33 (albeit not "white" - you can also look at the types of ip addresses on the Internet). And so we write:
$ iptables -A FORWARD -i eth0 -o eth1 -s 192.168.0.0/24 -j ACCEPT
$ iptables -A FORWARD -i eth1 -o eth0 -d 192.168.0.0/24 -j ACCEPT
$ iptables -P FORWARD DROP

thus we allowed transit packets to go through the firewall for our range of ip addresses, and we prohibit everything else.
Now NAT itself:
$ iptables -A POSTROUTING -s 192.168.0.0/24 -o eth1 -j SNAT --to-source 10.188.106.33
This is enough for NAT to work for you.
on trifles ...
On clients, we specify the ip from the selected range and specify the ip address of our server as the gateway (usually it is assigned the first from the subnet - I'll leave it up to you). All network settings on the server you can do it like this:
$ nano / etc / network / interfaces it specifies the settings for your network interfaces.
access to the bowels of the network through a gateway or DNAT
And then you realized that in the network you have Windows Server to which you have always had easy access via RDP, and then this annoying gateway on Debian got out! It's very simple - you just need to add a DNAT rule to our iptables.
What kind of beast is DNAT? DNAT (Destination NAT or Recipient Address Spoofing) - network cards work in such a mode that they only accept packets addressed to them, but if you log into our server if the ip under which it connects to the Internet there are a dozen more machines sitting in your office? How will the request reach him? In fact, all requests of this kind rest on our gateway. And all we need to do is set the rules for working with such packages.
$ iptables -A PREROUTING -i eth1 -p tcp -m tcp --dport 3389 -j DNAT --to-destination 192.168.0.2
This simple rule will redirect all packets coming to the gateway from the Internet to tCP port 3389 (this is what the RDP protocol uses) to your internal Windows Server. And voila, everything works for you.
so what's there with your favorite squid
And although everything works now, everyone has the Internet and everything works, some still need a proxy server. I will not talk about the squid setup, I will show a rule that will allow you to make it "transparent". In the squid, you just need to write the magic word transparent in the right place and it will begin to correctly process the requests that have fallen on it.
We write $ iptables -A PREROUTING -d! 192.168.0.0/24 -i eth0 -p tcp -m multiport --dports 80,443 -j REDIRECT --to-ports 3128.
And what does it give us? Now all requests for web pages from your workstations via the http ((80) and https (443) protocols will be redirected to the port that squid listens to.You receive content filtering, information about who was where and what was doing on the Internet, the user without suspecting anything works as before ...
a little safety
You should at least protect your gateway minimally, so let's add a couple more rules
$ iptables -A INPUT -i lo -j ACCEPT
$ iptables -A INPUT -i eth0 -s 192.168.0.0/24 -j ACCEPT
$ iptables -A INPUT -i eth1 -m conntrack --ctstate RELATED, ESTABLISHED -j ACCEPT
$ iptables -P INPUT DROP

Thus, they prohibited any communication directly with the gateway, except for the already established connections, i.e. those that were initiated by you and you just get answers to them. Do not be afraid our DNAT just does not get to these rules ...
why so few?
The article is not rubber and you still can't tell about everything ... I brought minimum a set of actions and concepts so that you can start to master such a colossus as a gateway on Linux. Here you can talk for a very, very long time, discussing many aspects and capabilities of netfilter.

Total

As we can see everything is really simple! The main thing is to understand the principle of the functioning of the network and are not afraid to set up and read large manuals.
I hope I managed to put together enough information to start your friendship with software routers based on Linux.

Tags: iptables, netfilter, NAT

Iptables is primarily responsible for packet filtering. Configuring iptables manually is a rather tricky task. Don't expect to figure out this snapshot. Fortunately, there are many tools that can help you if you have not figured out iptables yet, and you urgently need to secure the system: fwbuilder, firestarter, guarddog, arno firewall - in fact, this is a GUI for iptables. The unequivocal answer is that there is no better. It's up to you to choose. However, today's article is devoted specifically to iptables and is divided into two parts: theory and practice. The most impatient can do the practical part right away, although this approach is not recommended.

Attention! All actions with iptables are performed on behalf of the privileged user!

Theory

Record format iptables iptables [-t table] [command] [action] Example: iptables -t filter -A INPUT ACCEPT

Actions

  • ACCEPT - Accept package
  • DROP - Drop a packet
  • DNAT - Convert Destination Address
  • SNAT - Change outgoing IP address in packet header
  • LOG - Log packages and events
  • MARK - Place a mark on a package
  • MASQUERADE - Change the outgoing IP address in the packet header (different from SNAT - work with dynamic IP)
  • QUEUE - Queue a package for processing
  • REDIRECT - Redirect packet / stream to another port
  • REJECT - Drop the package + notify the remote system that. that her package was rejected
  • RETURN - Stop moving the packet along the current chain and return to the calling chain

Commands

  • -A - Add a rule to the chain
  • -D - Remove the rule from the chain
  • -R - Replace one rule with another
  • -I - Insert new rule
  • -L - List existing rules
  • -F - Reset rules
  • -Z - Zeroing counters in the specified chain
  • -N - Creates a new chain with the given name
  • -X - Delete chain
  • -P - Set the default policy for the selected chain
  • -E - Rename custom chain

Criteria (general)

  • -p - Specify protocol type
  • -s is the source IP of the packet
  • -d - IP address of the packet recipient
  • -j - Specify the action for the rule
  • -i - Interface from which the packet was received
  • -o - Specify the name of the output interface
  • -f - Expand the rule to all fragments of the package

TCP criteria:

  • –Tcp-flags - Specify packet mask and flags

UDP criteria:

  • –Sport - Port from which the packet was sent
  • –Dport - Port to which the packet is addressed

More in man iptables

Practice

Viewing the current configuration

$ sudo iptables -L Chain INPUT (policy ACCEPT) target prot opt \u200b\u200bsource destination Chain FORWARD (policy ACCEPT) target prot opt \u200b\u200bsource destination Chain OUTPUT (policy ACCEPT) target prot opt \u200b\u200bsource destination

If you see something like that, then your firewall is not configured yet and allows everything. Let's fix the situation.

Setting the default policy

  • iptables -P INPUT DROP - block incoming packets
  • iptables -P OUTPUT ACCEPT - allow outgoing packets
  • iptables -P FORWARD DROP - processing packets that got to the server from another machine and are awaiting further forwarding. The example is blocked. In this case, you will have to add rules for trusted machines.

Since incoming INPUT packets are blocked, let's write the rule:

$ sudo iptables -A INPUT -m state --state RELATED, ESTABLISHED -j ACCEPT

This will allow to receive packets from earlier established connection and accept new packets generated by this connection.

Or indicating the type of protocol:

$ sudo iptables -A INPUT -p TCP -m state --state ESTABLISHED, RELATED -j ACCEPT $ sudo iptables -A INPUT -p UDP -m state --state ESTABLISHED, RELATED -j ACCEPT

Now the local interface:

$ sudo iptables -A INPUT -i lo -j ACCEPT

  • NEW - data starting a new connection.
  • ESTABLISHED - a packet coming from an already established connection.
  • RELATED - new data packet, but generated by the old established connection
  • INVALID - so clear

$ sudo iptables-save\u003e /etc/iptables.up.rules

Enable these rules:

$ sudo iptables-restore< /etc/iptables.up.rules

And see the difference:

$ sudo iptables-L

Launching iptables at system startup:

In the /etc/init.d directory, create a file named iptables

$ sudo touch /etc/init.d/iptables

We write the following in it:

#! / bin / sh / sbin / iptables-restore< /etc/iptables.up.rules

Let's make the iptables file executable:

$ sudo chmod + x /etc/init.d/iptables

Add it to autorun

$ sudo update-rc.d -n iptables defaults

Running iptables when connected to a network:

$ sudo echo "#! / sbin / iptables-restore"\u003e /etc/network/if-up.d/iptables.up.rules $ sudo iptables-save \u003e\u003e /etc/network/if-up.d/iptables. up.rules $ sudo chmod + x /etc/network/if-up.d/iptables.up.rules

Note: at any time you can check if your rules are loaded by simply entering iptables-save from root

For archlinux, saving iptables rules is done with the command:

$ sudo rc.d save iptables

Did you like the article? To share with friends: