Tag Archives: iptables

IPTables with IPSets

First thing is to ensure the correct options are set in the kernel.

IP sets support the following type of sets:

bitmap:ip The bitmap:ip set type uses a memory range, where each bit represents one IP address and can store up to 65535 (B-class network) entries. You can store same size network addresses in this kind of sets as well and an IP address will be in the set if the network address it belongs to can be found in the set.
bitmap:ip,mac The bitmap:ip,mac set type uses a memory range, where each 8 bytes represents one IP and a MAC addresses. A bitmap:ip,mac set type can store up to 65535 (B-class network) IP addresses with MAC.
bitmap:port The bitmap:port set type uses a memory range, where each bit represents one TCP/UDP port. A bitmap:port type of set can store up to 65535 ports.
hash:ip The hash:ip set type uses a hash to store IP addresses where clashing is resolved by storing the clashing elements in an array and, as a last resort, by dynamically growing the hash. Same size network addresses can be stored in an hash:ip type of set as well.
hash:net The hash:net set type also uses a hash to store CIDR netblocks, which may be of different sizes. The same techique is used to avoid clashes as at the hash:ip set type.
hash:ip,port The hash:ip,port is similar to hash:ip but you can store IP address and protocol-port pairs in it. TCP, SCTP, UDP, UDPLITE, ICMP and ICMPv6 are supported with port numbers/ICMP(v6) types and other protocol numbers without port information.
hash:ip,port,ip You can store IP address, port number, and IP address triples in an hash:ip,port,ip type of set.
hash:ip,port,net You can store IP address, port number and network address triples in this kind of set.
hash:net,port The set type supports to store network address and port number pairs.
hash:net,iface In this kind of set one can store network address and interface name pairs.
list:set In a list:set kind of set you can store other sets; it is like an ordered union of different sets.
-*- Networking support --->
    Networking options --->
        [*] Network packet filtering framework (Netfilter) --->
            <*> IP set support --->
                (256) Maximum number of IP sets  
                <*> bitmap:ip set support
                <*> bitmap:ip,mac set support
                <*> bitmap:port set support
                <*> hash:ip set support
                <*> hash:ip,mark set support
                <*> hash:ip,port set support
                <*> hash:ip,port,ip set support
                <*> hash:ip,port,net set support
                <*> hash:ip,mac set support
                <*> hash:mac set support
                <*> hash:net,port,net set support
                <*> hash:net set support
                <*> hash:net,net set support
                <*> hash:net,port set support
                <*> hash:net,iface set support
                <*> list:set set support

If you're having to now add this, you'll obviously need to reboot once you have built and installed the updated kernel.

Now let's install  ipset.

# emerge -av ipset

These are the packages that would be merged, in order:

Calculating dependencies... done!
[ebuild R ] net-firewall/ipset-6.29::gentoo USE="-modules"

Ipset has the modules flag set by default.  With the above kernel config, the build will fail as I haven't used modules DUH!  So just disable the flag.  If you've build the kernel with modules instead, just leave as is.

So on to the fun stuff.  Ipset has a pretty good help section and the manpage is detailed :)

I use systemd, so there is no service to restart for iptables or ipset.

Obviously you'll have iptables configured and running :)  By default I block everything and only have specific ports open to the world.  But that doesn't mean we don't need ipsets.  I'm going to use ipset to block spiders (crawlers) that I don't want or that bypass my robots.txt.  I could limit the blocking to specific ports eg 80 & 443, but I'm just going to block everything.  Just because I can ;) I've also set a timeout (optional) so the IP's can be rotated and the sets don't grow too big.

So let's create an ipset.  I only want to block CIDR, so I don't need to add port, mac etc etc.

ipset create netSpiders hash:net timeout 86400

You can add IPs in here also, but I like to keep things clean so I also have:

ipset create ipSpiders hash:ip timeout 86400

NOTE:  If you haven't rebooted into the ipset enabled kernel, you'll get the error:

ipset v6.29: Kernel error received: set type not supported

You can list the set and any rules within by executing:

# ipset list
Name: spiders
Type: hash:net
Revision: 6
Header: family inet hashsize 1024 maxelem 65536 timeout 86400
Size in memory: 368
References: 0
Number of entries: 0
Members:

As you can see, we have nothing defined yet.  So let's add some spiders.  Unfortunately it's per CIDR.

# ipset add netSpiders 123.151.148.0/22
# ipset add netSpiders 157.54.0.0/15
# ipset add netSpiders 157.56.0.0/14
# ipset add netSpiders 157.60.0.0/16
# ipset add netSpiders 65.52.0.0/14
# ipset add netSpiders 5.10.83.0/25
# ipset add netSpiders 208.115.113.80/28
# ipset add netSpiders 208.115.111.64/28
# ipset add netSpiders 198.27.64.0/18
# ipset add netSpiders 54.160.0.0/12
# ipset add netSpiders 54.224.0.0/12

We can then list our set to see the rules.

# ipset list netSpiders
Name: netSpiders
Type: hash:net
Revision: 6
Header: family inet hashsize 1024 maxelem 65536 timeout 86400
Size in memory: 1072
References: 0
Number of entries: 11
Members:
54.224.0.0/12
208.115.113.80/28
54.160.0.0/12
123.151.148.0/22
198.27.64.0/18
5.10.83.0/25
157.60.0.0/16
208.115.111.64/28
157.56.0.0/14
65.52.0.0/14
157.54.0.0/15

You can remove rules by executing:

# ipset del netSpiders 54.224.0.0/12

We then add the ipset to iptables.  I log dropped connections, but if you are just dropping, then just use DROP as the target instead.

iptables -A INPUT -m set --match-set netSpiders src -j LOGGING

Looking at my firewall log, I can see the ipset already working.

kernel: Incoming Dropped: IN=enp2s0 OUT= MAC=xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:08:00 SRC=54.227.98.207 DST=xxx.xxx.xxx.xxx LEN=60 TOS=0x00 PREC=0x00 TTL=43 ID=27451 DF PROTO=TCP SPT=56227 DPT=80 WINDOW=14600 RES=0x00 SYN URGP=0

If you check iptables, this is what you'll see for the ipset entry.

# iptables -L -n
...
LOGGING all -- 0.0.0.0/0 0.0.0.0/0 match-set netSpiders src
...

You can remove ipsets completely by executing:

ipset destroy netSpiders

not specifying the set will delete ALL sets.

If a set is in use by iptables, you will get the following error.

ipset v6.29: Set cannot be destroyed: it is in use by a kernel component

Also ipsets, like iptables, are not persistent from reboots.  You can save the sets by executing:

ipset save > ipset.save
# cat ipset.save 
create netSpiders hash:net family inet hashsize 1024 maxelem 65536 timeout 86400
add netSpiders 157.60.0.0/16
add netSpiders 65.52.0.0/14
add netSpiders 208.115.113.80/28
add netSpiders 123.151.148.0/22
add netSpiders 5.10.83.0/25
add netSpiders 157.56.0.0/14
add netSpiders 208.115.111.64/28
add netSpiders 54.144.0.0/12
add netSpiders 198.27.64.0/18
add netSpiders 54.224.0.0/12
add netSpiders 54.160.0.0/12
add netSpiders 157.54.0.0/15

Which will store all sets in the save file.  To restore, it's just the reverse.

# ipset restore < ipset.save

One thing to bare in mind is that iptables may fail to start if you restore rules that reference any ipsets that don't exist.

iptables v1.4.21: Set netSpiders doesn't exist.

Startup/Shutdown.

At the time of writing this, ipset does not support systemd.  So I knocked up a script and 2 systemd unit files which seem to do the job very nicely.

Script #### Ipset Startup #### Ipset Shutdown

Please save the script into /usr/sbin/ and both the unit files into /etc/systemd/system/.  Then enable them.

 # systemctl enable ipset-save
 # systemctl enable ipset

 

Block countries with IPTables

I get an absolute battering from China on a daily basis with the occasional attack from France, Germany or the US.  Time to block countries :)

First and foremost, make sure you have iptables installed, configured and working.
Next we'll install some additions:

emerge -av xtables-addons geoipupdate

You may need to remove some of the modules to allow xtables to install (depends on your setup).  This can be achieved by adding the following line to /etc/portage/make.conf:

XTABLES_ADDONS="=account =chaos =condition =delude =dhcpmac =fuzzy geoip =iface =ipmark =ipp2p =ipv4options =length2 =logmark =lscan =pknock =psd =quota2 =rawnat =steal =sysrq =tarpit =dnetmap =echo =gradm"

I'm only interested in geoip, so I removed everything else.

Make the directory where iptables will look for the database:

mkdir -p /usr/share/xt_geoip/

Execute the following to download the geoiplite databases:

If you have a paid account, you could potentially replace the URLs in the download script (untested)

cd /usr/share/xt_geoip/ && /lib64/xtables-addons/xt_geoip_dl && /lib64/xtables-addons/xt_geoip_build *.csv

You could cron this as a weekly update.

xt_geoip_dl: Downloads the CSV database files
xt_geoip_build: Processes the files into a format iptables can read.

/usr/share/xt_geoip/LE/<country abbreviation>.iv4 & .iv6

Now you can block countries using iptables

iptables -A INPUT -m geoip --src-cc CN -j DROP

An iptables -L -n will show

DROP all -- 0.0.0.0/0 0.0.0.0/0 -m geoip --source-country CN

 

25 Most Frequently Used Linux IPTables Rules Examples

I thought this was a very good article.  Credit to the original author.

by Ramesh Natarajan on June 14, 2011

At a first glance, IPTables rules might look cryptic.

In this article, I’ve given 25 practical IPTables rules that you can copy/paste and use it for your needs.

These examples will act as a basic templates for you to tweak these rules to suite your specific requirement.

1. Delete Existing Rules

Before you start building new set of rules, you might want to clean-up all the default rules, and existing rules. Use the iptables flush command as shown below to do this.

iptables -F
(or)
iptables --flush

2. Set Default Chain Policies

The default chain policy is ACCEPT. Change this to DROP for all INPUT, FORWARD, and OUTPUT chains as shown below.

iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT DROP

When you make both INPUT, and OUTPUT chain’s default policy as DROP, for every firewall rule requirement you have, you should define two rules. i.e one for incoming and one for outgoing.

In all our examples below, we have two rules for each scenario, as we’ve set DROP as default policy for both INPUT and OUTPUT chain.

If you trust your internal users, you can omit the last line above. i.e Do not DROP all outgoing packets by default. In that case, for every firewall rule requirement you have, you just have to define only one rule. i.e define rule only for incoming, as the outgoing is ACCEPT for all packets.

Note: If you don’t know what a chain means, you should first familiarize yourself with the IPTables fundamentals.

3. Block a Specific ip-address

Before we proceed further will other examples, if you want to block a specific ip-address, you should do that first as shown below. Change the “x.x.x.x” in the following example to the specific ip-address that you like to block.

BLOCK_THIS_IP="x.x.x.x"
iptables -A INPUT -s "$BLOCK_THIS_IP" -j DROP

This is helpful when you find some strange activities from a specific ip-address in your log files, and you want to temporarily block that ip-address while you do further research.

You can also use one of the following variations, which blocks only TCP traffic on eth0 connection for this ip-address.

iptables -A INPUT -i eth0 -s "$BLOCK_THIS_IP" -j DROP
iptables -A INPUT -i eth0 -p tcp -s "$BLOCK_THIS_IP" -j DROP

4. Allow ALL Incoming SSH

The following rules allow ALL incoming ssh connections on eth0 interface.

iptables -A INPUT -i eth0 -p tcp --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT

Note: If you like to understand exactly what each and every one of the arguments means, you should read How to Add IPTables Firewall Rules

5. Allow Incoming SSH only from a Sepcific Network

The following rules allow incoming ssh connections only from 192.168.100.X network.

iptables -A INPUT -i eth0 -p tcp -s 192.168.100.0/24 --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT

In the above example, instead of /24, you can also use the full subnet mask. i.e “192.168.100.0/255.255.255.0″.

6. Allow Incoming HTTP and HTTPS

The following rules allow all incoming web traffic. i.e HTTP traffic to port 80.

iptables -A INPUT -i eth0 -p tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 80 -m state --state ESTABLISHED -j ACCEPT

The following rules allow all incoming secure web traffic. i.e HTTPS traffic to port 443.

iptables -A INPUT -i eth0 -p tcp --dport 443 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 443 -m state --state ESTABLISHED -j ACCEPT

7. Combine Multiple Rules Together using MultiPorts

When you are allowing incoming connections from outside world to multiple ports, instead of writing individual rules for each and every port, you can combine them together using the multiport extension as shown below.

The following example allows all incoming SSH, HTTP and HTTPS traffic.

iptables -A INPUT -i eth0 -p tcp -m multiport --dports 22,80,443 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp -m multiport --sports 22,80,443 -m state --state ESTABLISHED -j ACCEPT

8. Allow Outgoing SSH

The following rules allow outgoing ssh connection. i.e When you ssh from inside to an outside server.

iptables -A OUTPUT -o eth0 -p tcp --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -i eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT

Please note that this is slightly different than the incoming rule. i.e We allow both the NEW and ESTABLISHED state on the OUTPUT chain, and only ESTABLISHED state on the INPUT chain. For the incoming rule, it is vice versa.

9. Allow Outgoing SSH only to a Specific Network

The following rules allow outgoing ssh connection only to a specific network. i.e You an ssh only to 192.168.100.0/24 network from the inside.

iptables -A OUTPUT -o eth0 -p tcp -d 192.168.100.0/24 --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -i eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT

10. Allow Outgoing HTTPS

The following rules allow outgoing secure web traffic. This is helpful when you want to allow internet traffic for your users. On servers, these rules are also helpful when you want to use wget to download some files from outside.

iptables -A OUTPUT -o eth0 -p tcp --dport 443 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -i eth0 -p tcp --sport 443 -m state --state ESTABLISHED -j ACCEPT

Note: For outgoing HTTP web traffic, add two additional rules like the above, and change 443 to 80.

11. Load Balance Incoming Web Traffic

You can also load balance your incoming web traffic using iptables firewall rules.

This uses the iptables nth extension. The following example load balances the HTTPS traffic to three different ip-address. For every 3th packet, it is load balanced to the appropriate server (using the counter 0).

iptables -A PREROUTING -i eth0 -p tcp --dport 443 -m state --state NEW -m nth --counter 0 --every 3 --packet 0 -j DNAT --to-destination 192.168.1.101:443
iptables -A PREROUTING -i eth0 -p tcp --dport 443 -m state --state NEW -m nth --counter 0 --every 3 --packet 1 -j DNAT --to-destination 192.168.1.102:443
iptables -A PREROUTING -i eth0 -p tcp --dport 443 -m state --state NEW -m nth --counter 0 --every 3 --packet 2 -j DNAT --to-destination 192.168.1.103:443

12. Allow Ping from Outside to Inside

The following rules allow outside users to be able to ping your servers.

iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT
iptables -A OUTPUT -p icmp --icmp-type echo-reply -j ACCEPT

13. Allow Ping from Inside to Outside

The following rules allow you to ping from inside to any of the outside servers.

iptables -A OUTPUT -p icmp --icmp-type echo-request -j ACCEPT
iptables -A INPUT -p icmp --icmp-type echo-reply -j ACCEPT

14. Allow Loopback Access

You should allow full loopback access on your servers. i.e access using 127.0.0.1

iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT

15. Allow Internal Network to External network.

On the firewall server where one ethernet card is connected to the external, and another ethernet card connected to the internal servers, use the following rules to allow internal network talk to external network.

In this example, eth1 is connected to external network (internet), and eth0 is connected to internal network (For example: 192.168.1.x).

iptables -A FORWARD -i eth0 -o eth1 -j ACCEPT

16. Allow outbound DNS

The following rules allow outgoing DNS connections.

iptables -A OUTPUT -p udp -o eth0 --dport 53 -j ACCEPT
iptables -A INPUT -p udp -i eth0 --sport 53 -j ACCEPT

17. Allow NIS Connections

If you are running NIS to manage your user accounts, you should allow the NIS connections. Even when the SSH connection is allowed, if you don’t allow the NIS related ypbind connections, users will not be able to login.

The NIS ports are dynamic. i.e When the ypbind starts it allocates the ports.

First do a rpcinfo -p as shown below and get the port numbers. In this example, it was using port 853 and 850.

rpcinfo -p | grep ypbind

Now allow incoming connection to the port 111, and the ports that were used by ypbind.

iptables -A INPUT -p tcp --dport 111 -j ACCEPT
iptables -A INPUT -p udp --dport 111 -j ACCEPT
iptables -A INPUT -p tcp --dport 853 -j ACCEPT
iptables -A INPUT -p udp --dport 853 -j ACCEPT
iptables -A INPUT -p tcp --dport 850 -j ACCEPT
iptables -A INPUT -p udp --dport 850 -j ACCEPT

The above will not work when you restart the ypbind, as it will have different port numbers that time.

There are two solutions to this: 1) Use static ip-address for your NIS, or 2) Use some clever shell scripting techniques to automatically grab the dynamic port number from the “rpcinfo -p” command output, and use those in the above iptables rules.

18. Allow Rsync From a Specific Network

The following rules allows rsync only from a specific network.

iptables -A INPUT -i eth0 -p tcp -s 192.168.101.0/24 --dport 873 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 873 -m state --state ESTABLISHED -j ACCEPT

19. Allow MySQL connection only from a specific network

If you are running MySQL, typically you don’t want to allow direct connection from outside. In most cases, you might have web server running on the same server where the MySQL database runs.

However DBA and developers might need to login directly to the MySQL from their laptop and desktop using MySQL client. In those case, you might want to allow your internal network to talk to the MySQL directly as shown below.

iptables -A INPUT -i eth0 -p tcp -s 192.168.100.0/24 --dport 3306 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 3306 -m state --state ESTABLISHED -j ACCEPT

20. Allow Sendmail or Postfix Traffic

The following rules allow mail traffic. It may be sendmail or postfix.

iptables -A INPUT -i eth0 -p tcp --dport 25 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 25 -m state --state ESTABLISHED -j ACCEPT

21. Allow IMAP and IMAPS

The following rules allow IMAP/IMAP2 traffic.

iptables -A INPUT -i eth0 -p tcp --dport 143 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 143 -m state --state ESTABLISHED -j ACCEPT

The following rules allow IMAPS traffic.

iptables -A INPUT -i eth0 -p tcp --dport 993 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 993 -m state --state ESTABLISHED -j ACCEPT

22. Allow POP3 and POP3S

The following rules allow POP3 access.

iptables -A INPUT -i eth0 -p tcp --dport 110 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 110 -m state --state ESTABLISHED -j ACCEPT

The following rules allow POP3S access.

iptables -A INPUT -i eth0 -p tcp --dport 995 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 995 -m state --state ESTABLISHED -j ACCEPT

23. Prevent DoS Attack

The following iptables rule will help you prevent the Denial of Service (DoS) attack on your webserver.

iptables -A INPUT -p tcp --dport 80 -m limit --limit 25/minute --limit-burst 100 -j ACCEPT

In the above example:

  • -m limit: This uses the limit iptables extension
  • –limit 25/minute: This limits only maximum of 25 connection per minute. Change this value based on your specific requirement
  • –limit-burst 100: This value indicates that the limit/minute will be enforced only after the total number of connection have reached the limit-burst level.

24. Port Forwarding

The following example routes all traffic that comes to the port 442 to 22. This means that the incoming ssh connection can come from both port 22 and 422.

iptables -t nat -A PREROUTING -p tcp -d 192.168.102.37 --dport 422 -j DNAT --to 192.168.102.37:22

If you do the above, you also need to explicitly allow incoming connection on the port 422.

iptables -A INPUT -i eth0 -p tcp --dport 422 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 422 -m state --state ESTABLISHED -j ACCEPT

25. Log Dropped Packets

You might also want to log all the dropped packets. These rules should be at the bottom.

First, create a new chain called LOGGING.

iptables -N LOGGING

Next, make sure all the remaining incoming connections jump to the LOGGING chain as shown below.

iptables -A INPUT -j LOGGING

Next, log these packets by specifying a custom “log-prefix”.

iptables -A LOGGING -m limit --limit 2/min -j LOG --log-prefix "IPTables Packet Dropped: " --log-level 7

Finally, drop these packets.

iptables -A LOGGING -j DROP