Archive

Articles taggués ‘iptables’

Iptables Tutorial – Securing Ubuntu VPS with Linux Firewall

20/06/2024 Comments off

Are you looking for a complete iptables tutorial? Stay put. In this article, we will show you how to install and use iptables on the Ubuntu system. By learning about this Linux firewall tool, you can secure your Linux VPS using the command-line interface.

What is Iptables, and How Does It Work?

Simply put, iptables is a firewall program for Linux. It will monitor traffic from and to your server using tables. These tables contain sets of rules, called chains, that will filter incoming and outgoing data packets.

When a packet matches a rule, it is given a target, which can be another chain or one of these special values:

  • ACCEPT – will allow the packet to pass through.
  • DROP – will not let the packet pass through.
  • RETURN – stops the packet from traversing through a chain and tell it to go back to the previous chain.

In this iptables tutorial, we are going to work with one of the default tables, called filter. It consists of three chains:

  • INPUT –  controls incoming packets to the server.
  • FORWARD – filters incoming packets that will be forwarded somewhere else.
  • OUTPUT – filter packets that are going out from your server.

Before we begin this guide, make sure you have SSH root or sudo access to your machine that runs on Ubuntu 16.04 or up. You can establish the connection through PuTTY (Windows) or terminal shell (Linux, macOS). If you own Hostinger VPS, you can get the SSH login details on the Servers tab of hPanel.

iptables rules only apply to ipv4. If you want to set up a firewall for the ipv6 protocol, you will need to use ip6tables instead.

Lire la suite…

Categories: Réseau, Sécurité Tags: , ,

UFW: an Uncomplicated Firewall

19/06/2024 Comments off

Introduction

For an introduction to firewalls, please see Firewall.

UFW – Uncomplicated Firewall

The default firewall configuration tool for Ubuntu is ufw. Developed to easeiptables firewall configuration, ufw provides a user friendly way to create an IPv4 or IPv6 host-based firewall. By default UFW is disabled.

Gufw is a GUI that is available as a frontend.

Basic Syntax and Examples

Default rules are fine for the average home user

When you turn UFW on, it uses a default set of rules (profile) that should be fine for the average home user. That’s at least the goal of the Ubuntu developers. In short, all ‘incoming’ is being denied, with some exceptions to make things easier for home users.

Enable and Disable

Enable UFW

To turn UFW on with the default set of rules:

sudo ufw enable

To check the status of UFW:

sudo ufw status verbose

The output should be like this:

youruser@yourcomputer:~$ sudo ufw status verbose
[sudo] password for youruser:
Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing)
New profiles: skip
youruser@yourcomputer:~$

Note that by default, deny is being applied to incoming. There are exceptions, which can be found in the output of this command:

sudo ufw show raw

You can also read the rules files in /etc/ufw (the files whose names end with .rules).

Disable UFW

To disable ufw use:

sudo ufw disable

Lire la suite…

Iptables HowTo

19/06/2024 Comments off

Basic iptables howto

Iptables is a firewall, installed by default on all official Ubuntu distributions (Ubuntu, Kubuntu, Xubuntu). When you install Ubuntu, iptables is there, but it allows all traffic by default. Ubuntu 8.04 Comes with ufw – a program for managing the iptables firewall easily.

There is a wealth of information available about iptables, but much of it is fairly complex, and if you want to do a few basic things, this How To is for you.

Basic Commands

Typing

sudo iptables -L

lists your current rules in iptables. If you have just set up your server, you will have no rules, and you should see

Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Basic Iptables Options

Here are explanations for some of the iptables options you will see in this tutorial. Don’t worry about understanding everything here now, but remember to come back and look at this list as you encounter new options later on.

  1. -A – Append this rule to a rule chain. Valid chains for what we’re doing are INPUT, FORWARD and OUTPUT, but we mostly deal with INPUT in this tutorial, which affects only incoming traffic.
  2. -L – List the current filter rules.
  3. -m conntrack – Allow filter rules to match based on connection state. Permits the use of the --ctstate option.
  4. --ctstate – Define the list of states for the rule to match on. Valid states are:
    • NEW – The connection has not yet been seen.
    • RELATED – The connection is new, but is related to another connection already permitted.
    • ESTABLISHED – The connection is already established.
    • INVALID – The traffic couldn’t be identified for some reason.
  5. -m limit – Require the rule to match only a limited number of times. Allows the use of the --limit option. Useful for limiting logging rules.
    1. --limit – The maximum matching rate, given as a number followed by « /second« , « /minute« , « /hour« , or « /day » depending on how often you want the rule to match. If this option is not used and -m limit is used, the default is « 3/hour« .
  6. -p – The connection protocol used.
  7. --dport – The destination port(s) required for this rule. A single port may be given, or a range may be given as start:end, which will match all ports from start to end, inclusive.
  8. -j – Jump to the specified target. By default, iptables allows four targets:
    1. ACCEPT – Accept the packet and stop processing rules in this chain.
    2. REJECT – Reject the packet and notify the sender that we did so, and stop processing rules in this chain.
    3. DROP – Silently ignore the packet, and stop processing rules in this chain.
    4. LOG – Log the packet, and continue processing more rules in this chain. Allows the use of the --log-prefix and --log-level options.
  9. --log-prefix – When logging, put this text before the log message. Use double quotes around the text to use.
  10. --log-level – Log using the specified syslog level. 7 is a good choice unless you specifically need something else.
  11. -i – Only match if the packet is coming in on the specified interface.
  12. -I – Inserts a rule. Takes two options, the chain to insert the rule into, and the rule number it should be.
    1. -I INPUT 5 would insert the rule into the INPUT chain and make it the 5th rule in the list.
  13. -v – Display more information in the output. Useful for if you have rules that look similar without using -v.
  14. -s --source – address[/mask] source specification
  15. -d --destination – address[/mask] destination specification
  16. -o --out-interface – output name[ ] network interface name ([ ] for wildcard)

Allowing Established Sessions

We can allow established sessions to receive traffic:

sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
  1. The above rule has no spaces either side of the comma in ESTABLISHED,RELATED

If the line above doesn’t work, you may be on a castrated VPS whose provider has not made available the extension, in which case an inferior version can be used as last resort:

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

Allowing Incoming Traffic on Specific Ports

You could start by blocking traffic, but you might be working over SSH, where you would need to allow SSH before blocking everything else.

To allow incoming traffic on the default SSH port (22), you could tell iptables to allow all TCP traffic on that port to come in.

sudo iptables -A INPUT -p tcp --dport ssh -j ACCEPT

Referring back to the list above, you can see that this tells iptables:

  1. append this rule to the input chain (-A INPUT) so we look at incoming traffic
  2. check to see if it is TCP (-p tcp).
  3. if so, check to see if the input goes to the SSH port (–dport ssh).
  4. if so, accept the input (-j ACCEPT).

Lets check the rules: (only the first few lines shown, you will see more)

sudo iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:ssh

Now, let’s allow all incoming web traffic

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

Checking our rules, we have

sudo iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:ssh
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:www

We have specifically allowed tcp traffic to the ssh and web ports, but as we have not blocked anything, all traffic can still come in.

Lire la suite…

Categories: Réseau, Sécurité Tags: , ,

Limiter le nombre de connexions par IP

18/06/2024 Comments off

Source: petitchevalroux.net

Une journée de travail plus tard, j’ai enfin trouvé comment limiter le nombre de connexion par IP avec iptable sur le port 80. Pour se faire j’utilise l’extension match recent d’iptables qui permet de créer et de gérer des règles en fonction d’une liste d’adresses IP.

Limitation

Comme ces règles sont basées sur les adresses IP elles ne peuvent pas vous protéger contre des attaques DDOS(Distributed Denial Of Service).

Blocage simple

iptables -A INPUT -p tcp --dport 80 -m state --state NEW -m recent --name BLACKLIST --set
iptables -A INPUT -p tcp --dport 80 -m state --state NEW -m recent --name BLACKLIST --update --seconds 10 --hitcount 10 --rttl -j DROP

Avec les deux règles précédentes je refuse (DROP) les nouvelles (-m state –state NEW) connexions entrantes (-A INPUT) au port http (–dport 80) qui atteignent le taux de 10 connexions (–hitcount 10) sur une période de 10 secondes (–seconds 10) et qui utilisent le protocol tcp (-p tcp).

La première règle sert à mettre à jour l’adresse IP dans la liste BLACKLIST et la seconde règle permet de limiter les connexions.

Bloquer les attaquants sur une période plus grande que le taux

Le problème des règles précédentes est que l’adresse IP attaquante est bloquée sur une période glissante qui n’est que de 10 secondes.

Pour bloquer sur une période différentes que celle qui définit par le taux limite j’ai mis en place les règles suivantes :

Création d’une nouvelle chaine BLACKLIST :

iptables -N BLACKLIST

Lorsqu’un paquet arrive dans la chaine BLACKLIST on le drop et on ajoute son IP dans la liste BLACKLIST :

iptables -A BLACKLIST -m recent --name BLACKLIST --set -j DROP

On bloque les paquets pour une période de 60 secondes :

iptables -A INPUT -m recent --update --name BLACKLIST --seconds 60 --rttl -j DROP

Quand un paquet arrive en entrée sur le port 80 on met son IP dans la liste COUNTER :

iptables -A INPUT -p tcp --dport 80 -m state --state NEW -m recent --name COUNTER --set

Si un paquet arrive en entrée et qu’il dépasse le taux on le redirige dans la chaine BLACKLIST :

iptables -A INPUT -p tcp --dport 80 -m state --state NEW -m recent --name COUNTER --update --seconds 
10 --hitcount 10 --rttl -j BLACKLIST

Tuning de l’extension recent

Par défaut l’extension recent d’iptables garde 100 adresses IP différentes dans les listes et garde 20 paquets par IP. En faisant quelques tests je me suis rendu compte que ce n’était pas suffisant donc je vous donne les commandes qui vont bien.

Changer le nombre d’ip du mode recent

chmod u+w /sys/module/xt_recent/parameters/ip_list_tot
echo 200 > /sys/module/xt_recent/parameters/ip_list_tot
chmod u-w /sys/module/xt_recent/parameters/ip_list_tot

Changer le nombre de paquet par ip du mode recent

chmod u+w /sys/module/xt_recent/parameters/ip_pkt_list_tot
echo 200 > /sys/module/xt_recent/parameters/ip_pkt_list_tot
chmod u-w /sys/module/xt_recent/parameters/ip_pkt_list_tot

Surveiller les listes d’ip

Pour informations les listes d’IP de l’extension recent sont disponibles dans /proc/net/xt_recent/

root@home:~# ls /proc/net/xt_recent/* -alh
-rw-r--r-- 1 root root 0  4 juin  09:17 /proc/net/xt_recent/BLACKLIST
-rw-r--r-- 1 root root 0  4 juin  09:17 /proc/net/xt_recent/COUNTER

Un petit extrait du contenu de ma liste COUNTER :

src=81.245.XX.XXX ttl: 56 last_seen: 634716668 oldest_pkt: 7 634716652, 634716665, 634716666, 634716667, 634716667, 634716668, 634716668
src=67.xx.115.XXX ttl: 55 last_seen: 634719164 oldest_pkt: 1 634719164
src=2XX.46.X9X.XX ttl: 120 last_seen: 634831058 oldest_pkt: 1 634831058
src=6X.2XX.1XX.1X6 ttl: 60 last_seen: 634821958 oldest_pkt: 1 634821958
src=81.XX.143.3X ttl: 56 last_seen: 634806578 oldest_pkt: 1 634806578

Le format des listes est composé d’une ligne par adresse IP. Sur chaque ligne, en plus de l’adresse IP on trouve dans l’ordre :

  • Le time to live (ttl)
  • Le timestamp qui correspond au dernier paquet de cette adresse (last_seen)
  • Le nombre de paquets (oldest_pkt)
  • La liste des timestamps des derniers paquets
Categories: Réseau, Sécurité Tags: ,

Some iptables modules you probably don’t know about

18/06/2024 Comments off

I admit it, at the beginning of Rusty’s presentation on iptables years ago, I think it was at the Linux Expo or Raleigh back in the ’90s, I thought: “Just what we need, another network filtering system.” This was shortly after we made the change from ipfwadm to ipchains with little benefit (in fact, some lack of functionality, IIRC) and a re-learning. Rusty won me over pretty quickly though…

One of the big features that made it easy to swallow iptables was that it included backwards compatibility with both ipfwadm and ipchains. It also included, as the name suggests, tables, where you can branch off and handle packets by groups. For example, I have a table for detecting bogons (addresses like 192.168.0.0/24 and 10.0.0.0/8), and just have one rule in my main tables that jumps to the bogon check. In other systems, like FreeBSD’s ipfw, you can use gotos, which work about as well as they do in programming.

Another nice thing about iptables is that it has a plugin architecture for adding functionality. This has been used to great effect for things like firewalling weird application-specific protocols like FTP, marking packets or handing them off for shaping, etc… For example, one I mentioned yesterday was “hashlimit” to help protect from SSH attacks.

Let’s look at a few other interesting modules for iptables. Some of them are built-in to the stock kernel, others have to be patched in (requiring a rebuild of iptables in some cases as well as the kernel).

condition (patch?)

With condition, you can easily enable or disable a rule from a script by writing to a file under “/proc/net/ipt_condition”. For example: “iptables -I INPUT -m condition –condition killnet -j DROP”. Then if you “echo 1 >/proc/net/ipt_condition/killnet” the input chain will start dropping packets. Then “echo 0” will re-enable input packets.

connrate (patch?)

This includes a “–connrate min:max” and matches when a connection (managed by the conntrack module) is within the range. An optional “!” can appear before the rate to invert the sense of the match. You could, for example, start dropping packets if a particular connection is above a certain rate, for example.

iprange (built-in)

The iprange module allows you to specify source and/or destination addresses as ranges. While the built-in “-s” and “-d” will take a netmask, this can work with an arbitrary range of addresses, for example: “iptables -I INPUT -m iprange -s 192.168.1.5-192.168.1.100 -j ACCEPT”, that isn’t an address range that can be specified by “192.168.1.0/25” sort of syntax.

length (built-in)

Match a rule based on the packet length as a range.

limit (built-in)

Limit a match based on a rate and burst rate. For example, logging can be handy but also offers the opportunity for a denial of service by hitting your logs hard. “iptables -A INPUT -m limit –limit 10/min –limit-burst 30 -j LOG –log-prefix « Dropping:” would add a log target to the end of the input chain. This will log up to 10 messages a minute, with initial bursts of up to 30 messages. You’d normally use this at the end of an INPUT chain which has a default REJECT or DROP policy.

mac (built-in)

A rule which matches based on the MAC address the packet came from. For example, you could allow packets which have your name server’s IP on them, but come from another MAC address (one way of spoofing packets).

Lire la suite…