Archive

Archives pour 03/2019

iptables recent module usage by example

31/03/2019 Comments off

https://www.dbsysnet.com/wp-content/uploads/2016/06/iptables.jpgiptables recent module usage by example

icmp check: 2 packets per 10 seconds – rcheck

iptables -F
iptables -A INPUT -p icmp --icmp-type echo-request -m recent --rcheck --seconds 10 --hitcount 2 --name ICMPCHECK -j DROP
iptables -A INPUT -p icmp --icmp-type echo-request -m recent --set --name ICMPCHECK -j ACCEPT

icmp check: 2 packets per 10 seconds – update

iptables -F
iptables -A INPUT -p icmp --icmp-type echo-request -m recent --update --seconds 10 --hitcount 2 --name ICMPCHECK -j DROP
iptables -A INPUT -p icmp --icmp-type echo-request -m recent --set --name ICMPCHECK -j ACCEPT

SSH brute-force prevention : 3 connections per 60 seconds

SSHPORT=22
iptables -F
iptables -A INPUT -p tcp --dport ${SSHPORT} -m state --state NEW -m recent --update --seconds 60 --hitcount 3 --name BRUTEFORCE -j DROP 
iptables -A INPUT -p tcp --dport ${SSHPORT} -m state --state NEW -m recent --set --name BRUTEFORCE -j ACCEPT

SSH brute-force prevention : 3 connections per 60 seconds – separate chain

SSHPORT=22
iptables -F
iptables -X
iptables -N BRUTECHECK
iptables -A INPUT -p tcp --dport ${SSHPORT} -m state --state NEW -j BRUTECHECK
iptables -A BRUTECHECK -m recent --update --seconds 60 --hitcount 3 --name BRUTEFORCE -j DROP
iptables -A BRUTECHECK -m recent --set --name BRUTEFORCE -j ACCEPT

SSH port knocking : tcp/1000 , tcp/2000

SSHPORT=22
N1=1000
N2=2000
iptables -F
iptables -X
iptables -N KNOCK1
iptables -N KNOCK2
iptables -N OK

iptables -A KNOCK1 -m recent --set --name SEENFIRST
iptables -A KNOCK1 -m recent --remove --name KNOCKED
iptables -A KNOCK1 -j DROP

iptables -A KNOCK2 -m recent --rcheck --name SEENFIRST --seconds 5 -j OK
iptables -A KNOCK2 -m recent --remove --name SEENFIRST
iptables -A KNOCK2 -j DROP

iptables -A OK -m recent --set --name KNOCKED
iptables -A OK -j DROP

iptables -A INPUT -p tcp --dport ${N1} -j KNOCK1
iptables -A INPUT -p tcp --dport ${N2} -j KNOCK2
iptables -A INPUT -p tcp --dport ${SSHPORT} -m state --state NEW -m recent --seconds 10 --rcheck --name KNOCKED -j ACCEPT
iptables -A INPUT -p tcp --dport ${SSHPORT} -m state --state NEW -j DROP

SSH port knocker script

#!/bin/bash
HOST="172.16.20.2"
SSHPORT=22
KNOCKS="1000 2000"

for PORT in $KNOCKS; do
  echo "Knock: $PORT"
  telnet $HOST $PORT &> /dev/null &
  P=$(echo $!)
  echo "PID: ${P}"
  sleep 1
  kill -KILL ${P}
done
ssh -p${SSHPORT} ${HOST}

Source: Pejman Moghadam

How to Install and Configure UFW – An Un-complicated FireWall in Debian/Ubuntu

31/03/2019 Comments off

ufw debian ubuntuSince computers are connected to each other, services are growing fast. Email, Social Media, Online Shop, Chat until Web Conferencing are services that used by user. But on the other side this connectivity just likes a double-side knife. It’s also possible to send bad messages to those computers like Virus, malware, trojan-apps are one of them.

Install UFW Firewall

The Internet, as the biggest computer network is not always fill with good people. In order to make sure our computers / servers are safe, we need to protect it.

One of the must have component on your computer / servers is Firewall. From Wikipedia, a definition is:

In computing, a firewall is a software or hardware-based network security system that controls the incoming and outgoing network traffic by analysing the data packets and determining whether they should be allowed through or not, based on applied rule set.

Iptables is one of the firewall that widely used by servers. It is a program used to manage incoming and outgoing traffic in the server based on a set of rules. Generally, only trusted connection is allowed to enter the server. But IPTables is running at console mode and it’s complicated. Those who’re familiar with iptables rules and commands, they can read the following article that describes how to use iptables firewall.

Installation of UFW Firewall in Debian/Ubuntu

To reduce the complexity of how-to setting IPTables, there is a lot of fronted. If you’re running Ubuntu Linux, you will find ufw as a default firewall tool. Lets start to explore about ufw firewall.

What is ufw

The ufw (Uncomplicated Firewall) is an frontend for most widely used iptables firewall and it is well comfortable for host-based firewalls. ufw gives a framework for managing netfilter, as well as provides a command-line interface for controlling the firewall. It provides user friendly and easy to use interface for Linux newbies who are not much familiar with firewall concepts.

While, on the other side same complicated commands helps administrators it set complicated rules using command line interface. The ufw is an upstream for other distributions such as Debian, Ubuntu and Linux Mint.

Basic Usage ufw

First, check if ufw is installed using following command.

$ sudo dpkg --get-selections | grep ufw
ufw 		install

If it’s not installed, you can install it using apt command as shown below.

$ sudo apt-get install ufw

Before you use, you should check whether ufw is running or not. Use the following command to check it.

$ sudo ufw status

If you found Status: inactive, it mean it’s not active or disable.

NEW! An indispensable ebook for every Linux administrator!

Enabling / Disabling ufw

To enable it, you just need to type the following command at the terminal.

$ sudo ufw enable

Firewall is active and enabled on system startup

To disable it, just type.

$ sudo ufw disable

List the current ufw rules

After the firewall is activated you can add your rules into it. If you want to see what are the default rules, you can type.

$ sudo ufw status verbose
Sample Output
Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing)
New profiles: skip
$

Lire la suite…

UFW: an Uncomplicated Firewall

30/03/2019 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

30/03/2019 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 --destinationaddress[/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

29/03/2019 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: ,