Ceci est une ancienne révision du document !


Version : 2020.01

Dernière mise-à-jour : 2020/02/21 06:06

LRF402 - Netfilter et Firewalld

Dans cette unité, vous allez apprendre :

  • Comment configurer Netfilter à l'aide de scripts,
  • Comment configurer Netfilter à l'aide de firewalld.

Les Problématiques

L'IP Spoofing

L'IP Spoofing consiste en faire croire à un serveur que sa machine possède une adresse IP autre que celle réellement attribuée. Le but de cette opération est de se placer en tant que point de passage obligatoire des paquets envoyés entre le serveur et le vrai propriétaire de l'adresse IP spoofée. Le mécanisme est la suivante :

  • L'attaquant change son adresse IP en prenant une à laquelle le serveur cible fera confiance,
  • L'attaquant envoie une requête au serveur en stipulant une route de communication qui passe par l'adresse IP réelle de l'attaquant,
  • L'attaquant reprend son adresse IP réelle,
  • Le serveur accepte la requête car elle provient d'une adresse IP à laquelle il peux faire confiance et renvoie une réponse en utilisant la route spécifiée par l'attaquant,
  • Le client utilise la route spécifiée par l'attaquant pour répondre au serveur.

Déni de Service (DoS)

Une attaque de déni de service consiste à rendre inopérable une machine en lui envoyant une grande quantité de données inutiles. Un exemple de ce type d'attaque s'appelle un ping flood :

  • L'attaquant prend l'adresse IP de sa cible,
  • Il envoie ensuite un ping à une machine de diffusion,
  • La machine de diffusion envoie ce même ping à un grand nombre de clients en spécifiant l'origine de la requête,
  • L'attaquant reprend son adresse IP d'origine,
  • Tous les clients renvoie une réponse au ping en même temps à la cible.

SYN Flooding

Le SYN Flooding, aussi appelé un SYN-ACK Attack, consiste à envoyer vers une cible de multiples paquets SYN très rapidement. La cible répond à chaque paquet reçu avec un paquet ACK et attend une réponse ACK de l'attaquant. A ce stade pour chaque ACK renvoyé par la cible, une connexion dite semi-ouverte existe entre les deux machines. La cible doit réserver une petite partie de sa mémoire pour chaque connexion semi-ouverte jusqu'au time-out de la dite semi-connexion. Si l'attaquant envoie très rapidement des paquets SYN, le système de time-out n'a pas la possibilité d'expirer les semi-connexions précédentes. Dans ce cas la mémoire de la cible se remplit et on obtient un buffer overflow.

Flood

Le Flood consiste à envoyer très rapidement des gros paquets ICMP vers la cible.

Le Contre-Mesure

Le contre-mesure est principalement l'utilisation d'un pare-feu.

Le Pare-feu Netfilter/iptables

Netfilter est composé de 5 hooks :

  • NF_IP_PRE_ROUTING
  • NF_IP_LOCAL_IN
  • NF_IP_LOCAL_OUT
  • NF_IP_FORWARD
  • NF_IP_POSTROUTING

Ces hooks sont utilisés par deux branches, la première est celle concernée par les paquets qui entrent vers des services locaux :

  • NF_IP_PRE_ROUTING > NF_IP_LOCAL_IN > NF_IP_LOCAL_OUT > NF_IP_POSTROUTING

tandis que la deuxième concerne les paquets qui traversent la passerelle:

  • NF_IP_PRE_ROUTING > NF_IP_FORWARD > NF_IP_POSTROUTING

Si IPTABLES a été compilé en tant que module, son utilisation nécessite le chargement de plusieurs modules supplémentaires en fonction de la situation:

  • iptable_filter
  • iptable_mangle
  • iptable_net
  • etc

Netfilter est organisé en tables. La commande iptables de netfilter permet d'insérer des policies dans les chaines:

  • La table FILTER
    • La chaîne INPUT
      • Concerne les paquets entrants
        • Policies: ACCEPT, DROP, REJECT
    • La chaîne OUTPUT
      • Concerne les paquets sortants
        • Policies: ACCEPT, DROP, REJECT
    • La chaîne FORWARD
      • Concerne les paquets traversant le par-feu.
        • Policies: ACCEPT, DROP, REJECT

Si aucune table n'est précisée, c'est la table FILTER qui s'applique par défaut.

  • La table NAT
    • La chaîne PREROUTING
      • Permet de faire la translation d'adresse de destination
        • Cibles: SNAT, DNAT, MASQUERADE
    • La chaîne POSTROUTING
      • Permet de faire la translation d'adresse de la source
        • Cibles: SNAT, DNAT, MASQUERADE
    • Le cas spécifique OUTPUT
      • Permet la modification de la destination des paquets générés localement
  • La table MANGLE
    • Permet le marquage de paquets générés localement (OUTPUT) et entrants (PREROUTING)

Les policies sont:

  • ACCEPT
    • Permet d'accepter le paquet concerné
  • DROP
    • Permet de rejeter le paquet concerné sans générer un message d'erreur
  • REJECT
    • Permet de rejeter le paquet concerné en générant une message d'erreur

Les cibles sont:

  • SNAT
    • Permet de modifier l'adresse source du paquet concerné
  • DNAT
    • Permet de modifier l'adresse de destination du paquet concerné
  • MASQUERADE
    • Permet de remplacer l'adresse IP privée de l'expéditeur par un socket public de la passerelle.

IPTABLES peut être configuré soit par des outils tels shorewall, soit en utilisant des lignes de commandes ou un script. Dans ce dernier cas, la ligne prend la forme:

# IPTABLES --action CHAINE --option1 --option2

Les actions sont:

Action Abréviation Déscription
- -append -A Ajouter une règle à la fin de la chaîne spécifiée
- -delete -D Supprimer une règle en spécifiant son numéro ou la règle à supprimer
- -replace -R Permet de remplacer la règle spécifée par son numéro
- -insert -I Permet d'insérer une règle à l'endroit spécifié
- -list -L Permet d'afficher des règles
- -flush -F Permet de vider toutes les règles d'une chaîne

Les options sont:

Option Abréviation Déscription
- -protocol -p Permet de spécifier un protocol - tcp, udp, icmp, all
- -source -s Permet de spécifier une adresse source
- -destination -d Permet de spécifier une adresse de destination
- -in-interface -i Permet de spécifier une interface réseau d'entrée
- -out-interface -o Permet de spécifier une interface réseau de sortie
- -fragment -f Permet de ne spécifier que les paquets fragmentés
- -source-port -sport Permet de spécifier un port source ou une plage de ports source
- -destination-port -dport Permet de spécifier un port de destination ou une plage de ports de destination
- -tcp-flags s/o Permet de spécifier un flag TCP à matcher - SYN, ACK, FIN, RST, URG, PSH, ALL, NONE
- -icmp-type s/o Permet de spécifier un type de paquet ICMP
- -mac-source s/o Permet de spécifier une adresse MAC

Les options spécifiques à NET sont:

- -to-destination s/o Permet de spécifier l'adresse de destination d'une translation
- -to-source s/o Permet spécifier l'adresse source d'une translation

Les options spécifiques aux LOGS sont:

- -log-level s/o Permet de spécifier le niveau de logs
- -log-prefix s/o Permet de spécifier un préfix pour les logs

L'option spécifique au STATEFUL est:

- -state s/o Permet de spécifier l'état du paquet à vérifier

Ce dernier cas fait référence au STATEFUL. Le STATEFUL est la capacité du par-feu à enregistrer dans une table spécifique, l'état des différentes connexions. Cette table s'appelle une table d'état. Le principe du fonctionnement de STATEFUL est simple, à savoir, si le paquet entrant appartient à une communication déjà établie, celui-ci n'est pas vérifié.

Il existe 4 états:

  • NEW
    • Le paquet concerne une nouvelle connexion et contient donc un flag SYN à 1
  • ESTABLISHED
    • Le paquet concerne une connexion déjà établie. Le paquet ne doit contenir ni flag SYN à 1, ni flag FIN à 1
  • RELATED
    • Le paquet est d'une connexion qui présente une relation avec une autre connexion
  • INVALID
    • La paquet provient d'une connexion anormale.

LAB #1 - Configuration par Scripts sous RHEL/CentOS 6 et versions Antérieures

Dans l'exemple suivant, expliquez le fonctionnement du script en détaillant les règles écrites :

#!/bin/bash
#####################################
# proxy server IP
PROXY_SERVER="192.168.1.2"
# Interface connected to Internet
INTERNET="eth1"
# Interface connected to LAN
LAN_IN="eth0"
# Local Interface
LOCAL="lo"
# Squid port
PROXY_PORT="8080"
# DO NOT MODIFY BELOW
# Clean old firewall
iptables -F
iptables -X
iptables -t nat -F
iptables -t nat -X
iptables -t mangle -F
iptables -t mangle -X
# Load IPTABLES modules for NAT and IP conntrack support
modprobe ip_conntrack
modprobe ip_conntrack_ftp
# For win xp ftp client
modprobe ip_nat_ftp
echo 1 > /proc/sys/net/ipv4/ip_forward
# Setting default filter policy
iptables -P INPUT DROP
iptables -P OUTPUT ACCEPT
# Unlimited access to loop back
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT
# Allow UDP, DNS and Passive FTP
iptables -A INPUT -i $INTERNET -m state --state ESTABLISHED,RELATED -j ACCEPT
# set this system as a router for Rest of LAN
iptables --table nat --append POSTROUTING --out-interface $INTERNET -j MASQUERADE
iptables --append FORWARD --in-interface $LAN_IN -j ACCEPT
# unlimited access to LAN
iptables -A INPUT -i $LAN_IN -j ACCEPT
iptables -A OUTPUT -o $LAN_IN -j ACCEPT
# DNAT port 80 request comming from LAN systems to squid 3128 ($SQUID_PORT) aka transparent proxy
iptables -t nat -A PREROUTING -i $LAN_IN -p tcp --dport 80 -j DNAT --to $PROXY_SERVER:$PROXY_PORT
# iptables -t nat -A PREROUTING -i br0 -p tcp --dport 80 -j REDIRECT --to-port 3128
# if it is same system
iptables -t nat -A PREROUTING -i $INTERNET -p tcp --dport 80 -j REDIRECT --to-port $PROXY_PORT
# DROP everything and Log it
iptables -A INPUT -j LOG
iptables -A INPUT -j DROP

Dans l'exemple suivant, expliquez le fonctionnement du script en détaillant les règles écrites :

#!/bin/sh
#
# Generated iptables firewall script for the Linux 2.4 kernel
# Script generated by Easy Firewall Generator for IPTables 1.15
# copyright 2002 Timothy Scott Morizot
# 
# Redhat chkconfig comments - firewall applied early,
#                             removed late
# chkconfig: 2345 08 92
# description: This script applies or removes iptables firewall rules
# 
# This generator is primarily designed for RedHat installations,
# although it should be adaptable for others.
#
# It can be executed with the typical start and stop arguments.
# If used with stop, it will stop after flushing the firewall.
# The save and restore arguments will save or restore the rules
# from the /etc/sysconfig/iptables file.  The save and restore
# arguments are included to preserve compatibility with
# Redhat's or Fedora's init.d script if you prefer to use it.

# Redhat/Fedora installation instructions
#
# 1. Have the system link the iptables init.d startup script into run states
#    2, 3, and 5.
#    chkconfig --level 235 iptables on
#
# 2. Save this script and execute it to load the ruleset from this file.
#    You may need to run the dos2unix command on it to remove carraige returns.
#
# 3. To have it applied at startup, copy this script to
#    /etc/init.d/iptables.  It accepts stop, start, save, and restore
#    arguments.  (You may wish to save the existing one first.)
#    Alternatively, if you issue the 'service iptables save' command
#    the init.d script should save the rules and reload them at runtime.
#
# 4. For non-Redhat systems (or Redhat systems if you have a problem), you
#    may want to append the command to execute this script to rc.local.
#    rc.local is typically located in /etc and /etc/rc.d and is usually
#    the last thing executed on startup.  Simply add /path/to/script/script_name
#    on its own line in the rc.local file.

###############################################################################
# 
# Local Settings
#

# sysctl location.  If set, it will use sysctl to adjust the kernel parameters.
# If this is set to the empty string (or is unset), the use of sysctl
# is disabled.

SYSCTL="/sbin/sysctl -w" 

# To echo the value directly to the /proc file instead
# SYSCTL=""

# IPTables Location - adjust if needed

IPT="/sbin/iptables"
IPTS="/sbin/iptables-save"
IPTR="/sbin/iptables-restore"

# Internet Interface
INET_IFACE="eth1"

# Local Interface Information
LOCAL_IFACE="eth0"
LOCAL_IP="192.168.1.1"
LOCAL_NET="192.168.1.0/24"
LOCAL_BCAST="192.168.1.255"

# Localhost Interface

LO_IFACE="lo"
LO_IP="127.0.0.1"

# Save and Restore arguments handled here
if [ "$1" = "save" ]
then
	echo -n "Saving firewall to /etc/sysconfig/iptables ... "
	$IPTS > /etc/sysconfig/iptables
	echo "done"
	exit 0
elif [ "$1" = "restore" ]
then
	echo -n "Restoring firewall from /etc/sysconfig/iptables ... "
	$IPTR < /etc/sysconfig/iptables
	echo "done"
	exit 0
fi

###############################################################################
#
# Load Modules
#

echo "Loading kernel modules ..."

# You should uncomment the line below and run it the first time just to
# ensure all kernel module dependencies are OK.  There is no need to run
# every time, however.

# /sbin/depmod -a

# Unless you have kernel module auto-loading disabled, you should not
# need to manually load each of these modules.  Other than ip_tables,
# ip_conntrack, and some of the optional modules, I've left these
# commented by default.  Uncomment if you have any problems or if
# you have disabled module autoload.  Note that some modules must
# be loaded by another kernel module.

# core netfilter module
/sbin/modprobe ip_tables

# the stateful connection tracking module
/sbin/modprobe ip_conntrack

# filter table module
# /sbin/modprobe iptable_filter

# mangle table module
# /sbin/modprobe iptable_mangle

# nat table module
# /sbin/modprobe iptable_nat

# LOG target module
# /sbin/modprobe ipt_LOG

# This is used to limit the number of packets per sec/min/hr
# /sbin/modprobe ipt_limit

# masquerade target module
# /sbin/modprobe ipt_MASQUERADE

# filter using owner as part of the match
# /sbin/modprobe ipt_owner

# REJECT target drops the packet and returns an ICMP response.
# The response is configurable.  By default, connection refused.
# /sbin/modprobe ipt_REJECT

# This target allows packets to be marked in the mangle table
# /sbin/modprobe ipt_mark

# This target affects the TCP MSS
# /sbin/modprobe ipt_tcpmss

# This match allows multiple ports instead of a single port or range
# /sbin/modprobe multiport

# This match checks against the TCP flags
# /sbin/modprobe ipt_state

# This match catches packets with invalid flags
# /sbin/modprobe ipt_unclean

# The ftp nat module is required for non-PASV ftp support
/sbin/modprobe ip_nat_ftp

# the module for full ftp connection tracking
/sbin/modprobe ip_conntrack_ftp

# the module for full irc connection tracking
/sbin/modprobe ip_conntrack_irc


###############################################################################
#
# Kernel Parameter Configuration
#
# See http://ipsysctl-tutorial.frozentux.net/chunkyhtml/index.html
# for a detailed tutorial on sysctl and the various settings
# available.

# Required to enable IPv4 forwarding.
# Redhat users can try setting FORWARD_IPV4 in /etc/sysconfig/network to true
# Alternatively, it can be set in /etc/sysctl.conf
if [ "$SYSCTL" = "" ]
then
    echo "1" > /proc/sys/net/ipv4/ip_forward
else
    $SYSCTL net.ipv4.ip_forward="1"
fi

# This enables dynamic address hacking.
# This may help if you have a dynamic IP address \(e.g. slip, ppp, dhcp\).
#if [ "$SYSCTL" = "" ]
#then
#    echo "1" > /proc/sys/net/ipv4/ip_dynaddr
#else
#    $SYSCTL net.ipv4.ip_dynaddr="1"
#fi

# This enables SYN flood protection.
# The SYN cookies activation allows your system to accept an unlimited
# number of TCP connections while still trying to give reasonable
# service during a denial of service attack.
if [ "$SYSCTL" = "" ]
then
    echo "1" > /proc/sys/net/ipv4/tcp_syncookies
else
    $SYSCTL net.ipv4.tcp_syncookies="1"
fi

# This enables source validation by reversed path according to RFC1812.
# In other words, did the response packet originate from the same interface
# through which the source packet was sent?  It's recommended for single-homed
# systems and routers on stub networks.  Since those are the configurations
# this firewall is designed to support, I turn it on by default.
# Turn it off if you use multiple NICs connected to the same network.
if [ "$SYSCTL" = "" ]
then
    echo "1" > /proc/sys/net/ipv4/conf/all/rp_filter
else
    $SYSCTL net.ipv4.conf.all.rp_filter="1"
fi

# This option allows a subnet to be firewalled with a single IP address.
# It's used to build a DMZ.  Since that's not a focus of this firewall
# script, it's not enabled by default, but is included for reference.
# See: http://www.sjdjweis.com/linux/proxyarp/ 
#if [ "$SYSCTL" = "" ]
#then
#    echo "1" > /proc/sys/net/ipv4/conf/all/proxy_arp
#else
#    $SYSCTL net.ipv4.conf.all.proxy_arp="1"
#fi

# The following kernel settings were suggested by Alex Weeks. Thanks!

# This kernel parameter instructs the kernel to ignore all ICMP
# echo requests sent to the broadcast address.  This prevents
# a number of smurfs and similar DoS nasty attacks.
if [ "$SYSCTL" = "" ]
then
    echo "1" > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts
else
    $SYSCTL net.ipv4.icmp_echo_ignore_broadcasts="1"
fi

# This option can be used to accept or refuse source routed
# packets.  It is usually on by default, but is generally
# considered a security risk.  This option turns it off.
if [ "$SYSCTL" = "" ]
then
    echo "0" > /proc/sys/net/ipv4/conf/all/accept_source_route
else
    $SYSCTL net.ipv4.conf.all.accept_source_route="0"
fi

# This option can disable ICMP redirects.  ICMP redirects
# are generally considered a security risk and shouldn't be
# needed by most systems using this generator.
#if [ "$SYSCTL" = "" ]
#then
#    echo "0" > /proc/sys/net/ipv4/conf/all/accept_redirects
#else
#    $SYSCTL net.ipv4.conf.all.accept_redirects="0"
#fi

# However, we'll ensure the secure_redirects option is on instead.
# This option accepts only from gateways in the default gateways list.
if [ "$SYSCTL" = "" ]
then
    echo "1" > /proc/sys/net/ipv4/conf/all/secure_redirects
else
    $SYSCTL net.ipv4.conf.all.secure_redirects="1"
fi

# This option logs packets from impossible addresses.
if [ "$SYSCTL" = "" ]
then
    echo "1" > /proc/sys/net/ipv4/conf/all/log_martians
else
    $SYSCTL net.ipv4.conf.all.log_martians="1"
fi


###############################################################################
#
# Flush Any Existing Rules or Chains
#

echo "Flushing Tables ..."

# Reset Default Policies
$IPT -P INPUT ACCEPT
$IPT -P FORWARD ACCEPT
$IPT -P OUTPUT ACCEPT
$IPT -t nat -P PREROUTING ACCEPT
$IPT -t nat -P POSTROUTING ACCEPT
$IPT -t nat -P OUTPUT ACCEPT
$IPT -t mangle -P PREROUTING ACCEPT
$IPT -t mangle -P OUTPUT ACCEPT

# Flush all rules
$IPT -F
$IPT -t nat -F
$IPT -t mangle -F

# Erase all non-default chains
$IPT -X
$IPT -t nat -X
$IPT -t mangle -X

if [ "$1" = "stop" ]
then
	echo "Firewall completely flushed!  Now running with no firewall."
	exit 0
fi

###############################################################################
#
# Rules Configuration
#

###############################################################################
#
# Filter Table
#
###############################################################################

# Set Policies

$IPT -P INPUT DROP
$IPT -P OUTPUT DROP
$IPT -P FORWARD DROP

###############################################################################
#
# User-Specified Chains
#
# Create user chains to reduce the number of rules each packet
# must traverse.

echo "Create and populate custom rule chains ..."

# Create a chain to filter INVALID packets

$IPT -N bad_packets

# Create another chain to filter bad tcp packets

$IPT -N bad_tcp_packets

# Create separate chains for icmp, tcp (incoming and outgoing),
# and incoming udp packets.

$IPT -N icmp_packets

# Used for UDP packets inbound from the Internet
$IPT -N udp_inbound

# Used to block outbound UDP services from internal network
# Default to allow all
$IPT -N udp_outbound

# Used to allow inbound services if desired
# Default fail except for established sessions
$IPT -N tcp_inbound

# Used to block outbound services from internal network
# Default to allow all
$IPT -N tcp_outbound

###############################################################################
#
# Populate User Chains
#

# bad_packets chain
#

# Drop packets received on the external interface
# claiming a source of the local network
$IPT -A bad_packets -p ALL -i $INET_IFACE -s $LOCAL_NET -j LOG \
    --log-prefix "fp=bad_packets:2 a=DROP "
$IPT -A bad_packets -p ALL -i $INET_IFACE -s $LOCAL_NET -j DROP

# Drop INVALID packets immediately
$IPT -A bad_packets -p ALL -m state --state INVALID -j LOG \
    --log-prefix "fp=bad_packets:1 a=DROP "

$IPT -A bad_packets -p ALL -m state --state INVALID -j DROP

# Then check the tcp packets for additional problems
$IPT -A bad_packets -p tcp -j bad_tcp_packets

# All good, so return
$IPT -A bad_packets -p ALL -j RETURN

# bad_tcp_packets chain
#
# All tcp packets will traverse this chain.
# Every new connection attempt should begin with
# a syn packet.  If it doesn't, it is likely a
# port scan.  This drops packets in state
# NEW that are not flagged as syn packets.

# Return to the calling chain if the bad packets originate
# from the local interface. This maintains the approach
# throughout this firewall of a largely trusted internal
# network.
$IPT -A bad_tcp_packets -p tcp -i $LOCAL_IFACE -j RETURN

# However, I originally did apply this filter to the forward chain
# for packets originating from the internal network.  While I have
# not conclusively determined its effect, it appears to have the
# interesting side effect of blocking some of the ad systems.
# Apparently some ad systems have the browser initiate a NEW
# connection that is not flagged as a syn packet to retrieve
# the ad image.  If you wish to experiment further comment the
# rule above. If you try it, you may also wish to uncomment the
# rule below.  It will keep those packets from being logged.
# There are a lot of them.
# $IPT -A bad_tcp_packets -p tcp -i $LOCAL_IFACE ! --syn -m state \
#     --state NEW -j DROP

$IPT -A bad_tcp_packets -p tcp ! --syn -m state --state NEW -j LOG \
    --log-prefix "fp=bad_tcp_packets:1 a=DROP "
$IPT -A bad_tcp_packets -p tcp ! --syn -m state --state NEW -j DROP

$IPT -A bad_tcp_packets -p tcp --tcp-flags ALL NONE -j LOG \
    --log-prefix "fp=bad_tcp_packets:2 a=DROP "
$IPT -A bad_tcp_packets -p tcp --tcp-flags ALL NONE -j DROP

$IPT -A bad_tcp_packets -p tcp --tcp-flags ALL ALL -j LOG \
    --log-prefix "fp=bad_tcp_packets:3 a=DROP "
$IPT -A bad_tcp_packets -p tcp --tcp-flags ALL ALL -j DROP

$IPT -A bad_tcp_packets -p tcp --tcp-flags ALL FIN,URG,PSH -j LOG \
    --log-prefix "fp=bad_tcp_packets:4 a=DROP "
$IPT -A bad_tcp_packets -p tcp --tcp-flags ALL FIN,URG,PSH -j DROP

$IPT -A bad_tcp_packets -p tcp --tcp-flags ALL SYN,RST,ACK,FIN,URG -j LOG \
    --log-prefix "fp=bad_tcp_packets:5 a=DROP "
$IPT -A bad_tcp_packets -p tcp --tcp-flags ALL SYN,RST,ACK,FIN,URG -j DROP

$IPT -A bad_tcp_packets -p tcp --tcp-flags SYN,RST SYN,RST -j LOG \
    --log-prefix "fp=bad_tcp_packets:6 a=DROP "
$IPT -A bad_tcp_packets -p tcp --tcp-flags SYN,RST SYN,RST -j DROP

$IPT -A bad_tcp_packets -p tcp --tcp-flags SYN,FIN SYN,FIN -j LOG \
    --log-prefix "fp=bad_tcp_packets:7 a=DROP "
$IPT -A bad_tcp_packets -p tcp --tcp-flags SYN,FIN SYN,FIN -j DROP

# All good, so return
$IPT -A bad_tcp_packets -p tcp -j RETURN

# icmp_packets chain
#
# This chain is for inbound (from the Internet) icmp packets only.
# Type 8 (Echo Request) is not accepted by default
# Enable it if you want remote hosts to be able to reach you.
# 11 (Time Exceeded) is the only one accepted
# that would not already be covered by the established
# connection rule.  Applied to INPUT on the external interface.
# 
# See: http://www.ee.siue.edu/~rwalden/networking/icmp.html
# for more info on ICMP types.
#
# Note that the stateful settings allow replies to ICMP packets.
# These rules allow new packets of the specified types.

# ICMP packets should fit in a Layer 2 frame, thus they should
# never be fragmented.  Fragmented ICMP packets are a typical sign
# of a denial of service attack.
$IPT -A icmp_packets --fragment -p ICMP -j LOG \
    --log-prefix "fp=icmp_packets:1 a=DROP "
$IPT -A icmp_packets --fragment -p ICMP -j DROP

# Echo - uncomment to allow your system to be pinged.
# Uncomment the LOG command if you also want to log PING attempts
# 
# $IPT -A icmp_packets -p ICMP -s 0/0 --icmp-type 8 -j LOG \
#    --log-prefix "fp=icmp_packets:2 a=ACCEPT "
# $IPT -A icmp_packets -p ICMP -s 0/0 --icmp-type 8 -j ACCEPT

# By default, however, drop pings without logging. Blaster
# and other worms have infected systems blasting pings.
# Comment the line below if you want pings logged, but it
# will likely fill your logs.
$IPT -A icmp_packets -p ICMP -s 0/0 --icmp-type 8 -j DROP

# Time Exceeded
$IPT -A icmp_packets -p ICMP -s 0/0 --icmp-type 11 -j ACCEPT

# Not matched, so return so it will be logged
$IPT -A icmp_packets -p ICMP -j RETURN

# TCP & UDP
# Identify ports at:
#    http://www.chebucto.ns.ca/~rakerman/port-table.html
#    http://www.iana.org/assignments/port-numbers

# udp_inbound chain
#
# This chain describes the inbound UDP packets it will accept.
# It's applied to INPUT on the external or Internet interface.
# Note that the stateful settings allow replies.
# These rules are for new requests.
# It drops netbios packets (windows) immediately without logging.

# Drop netbios calls
# Please note that these rules do not really change the way the firewall
# treats netbios connections.  Connections from the localhost and
# internal interface (if one exists) are accepted by default.
# Responses from the Internet to requests initiated by or through
# the firewall are also accepted by default.  To get here, the
# packets would have to be part of a new request received by the
# Internet interface.  You would have to manually add rules to
# accept these.  I added these rules because some network connections,
# such as those via cable modems, tend to be filled with noise from
# unprotected Windows machines.  These rules drop those packets
# quickly and without logging them.  This prevents them from traversing
# the whole chain and keeps the log from getting cluttered with
# chatter from Windows systems.
$IPT -A udp_inbound -p UDP -s 0/0 --destination-port 137 -j DROP
$IPT -A udp_inbound -p UDP -s 0/0 --destination-port 138 -j DROP

# Ident requests (Port 113) must have a REJECT rule rather than the
# default DROP rule.  This is the minimum requirement to avoid
# long delays while connecting.  Also see the tcp_inbound rule.
$IPT -A udp_inbound -p UDP -s 0/0 --destination-port 113 -j REJECT

# A more sophisticated configuration could accept the ident requests.
# $IPT -A udp_inbound -p UDP -s 0/0 --destination-port 113 -j ACCEPT

# However, if this is a gateway system that masquerades/nats for internal systems
# and the internal systems wish to chat, a simple changing these rules to
# ACCEPT won't work.  The ident daemon on the gateway will need to know how
# to handle the requests.  The stock daemon in most linux distributions
# can't do that.   oidentd is one package that can.
# See: http://dev.ojnk.net/

# Network Time Protocol (NTP) Server
$IPT -A udp_inbound -p UDP -s 0/0 --destination-port 123 -j ACCEPT

# Dynamic Address
# If DHCP, the initial request is a broadcast. The response
# doesn't exactly match the outbound packet.  This explicitly
# allow the DHCP ports to alleviate this problem.
# If you receive your dynamic address by a different means, you
# can probably comment this line.
$IPT -A udp_inbound -p UDP -s 0/0 --source-port 67 --destination-port 68 \
     -j ACCEPT


# Not matched, so return for logging
$IPT -A udp_inbound -p UDP -j RETURN

# udp_outbound chain
#
# This chain is used with a private network to prevent forwarding for
# UDP requests on specific protocols.  Applied to the FORWARD rule from
# the internal network.  Ends with an ACCEPT


# No match, so ACCEPT
$IPT -A udp_outbound -p UDP -s 0/0 -j ACCEPT

# tcp_inbound chain
#
# This chain is used to allow inbound connections to the
# system/gateway.  Use with care.  It defaults to none.
# It's applied on INPUT from the external or Internet interface.

# Ident requests (Port 113) must have a REJECT rule rather than the
# default DROP rule.  This is the minimum requirement to avoid
# long delays while connecting.  Also see the tcp_inbound rule.
$IPT -A tcp_inbound -p TCP -s 0/0 --destination-port 113 -j REJECT

# A more sophisticated configuration could accept the ident requests.
# $IPT -A tcp_inbound -p TCP -s 0/0 --destination-port 113 -j ACCEPT

# However, if this is a gateway system that masquerades/nats for internal systems
# and the internal systems wish to chat, a simple changing these rules to
# ACCEPT won't work.  The ident daemon on the gateway will need to know how
# to handle the requests.  The stock daemon in most linux distributions
# can't do that.   oidentd is one package that can.
# See: http://dev.ojnk.net/

# Web Server

# HTTP
$IPT -A tcp_inbound -p TCP -s 0/0 --destination-port 80 -j ACCEPT

# HTTPS (Secure Web Server)
$IPT -A tcp_inbound -p TCP -s 0/0 --destination-port 443 -j ACCEPT

# FTP Server (Control)
$IPT -A tcp_inbound -p TCP -s 0/0 --destination-port 21 -j ACCEPT

# FTP Client (Data Port for non-PASV transfers)
$IPT -A tcp_inbound -p TCP -s 0/0 --source-port 20 -j ACCEPT

# Passive FTP
# 
# With passive FTP, the server provides a port to the client
# and allows the client to initiate the connection rather
# than initiating the connection with the client from the data port.
# Web browsers and clients operating behind a firewall generally
# use passive ftp transfers.  A general purpose FTP server
# will need to support them.
# 
# However, by default an FTP server will select a port from the entire
# range of high ports.  It is not particularly safe to open all
# high ports.  Fortunately, that range can be restricted.  This
# firewall presumes that the range has been restricted to a specific
# selected range.  That range must also be configured in the ftp server.
# 
# Instructions for specifying the port range for the wu-ftpd server
# can be found here:
# http://www.wu-ftpd.org/man/ftpaccess.html
# (See the passive ports option.)
# 
# Instructions for the ProFTPD server can be found here:
# http://proftpd.linux.co.uk/localsite/Userguide/linked/x861.html

$IPT -A tcp_inbound -p TCP -s 0/0 --destination-port 62000:64000 -j ACCEPT

# Email Server (SMTP)
$IPT -A tcp_inbound -p TCP -s 0/0 --destination-port 25 -j ACCEPT

# Email Server (POP3)
$IPT -A tcp_inbound -p TCP -s 0/0 --destination-port 110 -j ACCEPT

# Email Server (IMAP4)
$IPT -A tcp_inbound -p TCP -s 0/0 --destination-port 143 -j ACCEPT

# SSL Email Server (POP3)
$IPT -A tcp_inbound -p TCP -s 0/0 --destination-port 995 -j ACCEPT

# SSL Email Server (IMAP4)
$IPT -A tcp_inbound -p TCP -s 0/0 --destination-port 993 -j ACCEPT

# sshd
$IPT -A tcp_inbound -p TCP -s 0/0 --destination-port 22 -j ACCEPT

# ICQ File Transfers & Other Advanced Features
# 
# ICQ supports a number of options beyond simple instant messaging.
# For those to function, the instant messaging system must allow
# new connections initiated from remote systems. This option will
# open a specified port range on the firewalled system.  The ICQ client
# on the firewalled system must also be configured to use the specified
# port range.

$IPT -A tcp_inbound -p TCP -s 0/0 --destination-port 5000:5100 -j ACCEPT

# MSN Messenger File Transfers
# 
# Messenger supports file transfers.  For transfers initiated by
# remote systems to function, the system must allow
# new connections initiated from remote systems a specific port range.
# This option defaults to the port range 6891 through 6900.
# Unless the MSN Messenger client can be configured to specify any
# port range, don't change the default.

$IPT -A tcp_inbound -p TCP -s 0/0 --destination-port 6891:6900 -j ACCEPT

# User specified allowed UDP protocol
$IPT -A tcp_inbound -p TCP -s 0/0 --destination-port 32500:36000 -j ACCEPT


# Not matched, so return so it will be logged
$IPT -A tcp_inbound -p TCP -j RETURN

# tcp_outbound chain
#
# This chain is used with a private network to prevent forwarding for
# requests on specific protocols.  Applied to the FORWARD rule from
# the internal network.  Ends with an ACCEPT


# No match, so ACCEPT
$IPT -A tcp_outbound -p TCP -s 0/0 -j ACCEPT

###############################################################################
#
# INPUT Chain
#

echo "Process INPUT chain ..."

# Allow all on localhost interface
$IPT -A INPUT -p ALL -i $LO_IFACE -j ACCEPT

# Drop bad packets
$IPT -A INPUT -p ALL -j bad_packets

# DOCSIS compliant cable modems
# Some DOCSIS compliant cable modems send IGMP multicasts to find
# connected PCs.  The multicast packets have the destination address
# 224.0.0.1.  You can accept them.  If you choose to do so,
# Uncomment the rule to ACCEPT them and comment the rule to DROP
# them  The firewall will drop them here by default to avoid
# cluttering the log.  The firewall will drop all multicasts
# to the entire subnet (224.0.0.1) by default.  To only affect
# IGMP multicasts, change '-p ALL' to '-p 2'.  Of course,
# if they aren't accepted elsewhere, it will only ensure that
# multicasts on other protocols are logged.
# Drop them without logging.
$IPT -A INPUT -p ALL -d 224.0.0.1 -j DROP
# The rule to accept the packets.
# $IPT -A INPUT -p ALL -d 224.0.0.1 -j ACCEPT

# Rules for the private network (accessing gateway system itself)
$IPT -A INPUT -p ALL -i $LOCAL_IFACE -s $LOCAL_NET -j ACCEPT
$IPT -A INPUT -p ALL -i $LOCAL_IFACE -d $LOCAL_BCAST -j ACCEPT


# Inbound Internet Packet Rules

# Accept Established Connections
$IPT -A INPUT -p ALL -i $INET_IFACE -m state --state ESTABLISHED,RELATED \
     -j ACCEPT

# Route the rest to the appropriate user chain
$IPT -A INPUT -p TCP -i $INET_IFACE -j tcp_inbound
$IPT -A INPUT -p UDP -i $INET_IFACE -j udp_inbound
$IPT -A INPUT -p ICMP -i $INET_IFACE -j icmp_packets

# Drop without logging broadcasts that get this far.
# Cuts down on log clutter.
# Comment this line if testing new rules that impact
# broadcast protocols.
$IPT -A INPUT -m pkttype --pkt-type broadcast -j DROP

# Log packets that still don't match
$IPT -A INPUT -j LOG --log-prefix "fp=INPUT:99 a=DROP "

###############################################################################
#
# FORWARD Chain
#

echo "Process FORWARD chain ..."

# Used if forwarding for a private network

# Drop bad packets
$IPT -A FORWARD -p ALL -j bad_packets

# Accept TCP packets we want to forward from internal sources
$IPT -A FORWARD -p tcp -i $LOCAL_IFACE -j tcp_outbound

# Accept UDP packets we want to forward from internal sources
$IPT -A FORWARD -p udp -i $LOCAL_IFACE -j udp_outbound

# If not blocked, accept any other packets from the internal interface
$IPT -A FORWARD -p ALL -i $LOCAL_IFACE -j ACCEPT

# Deal with responses from the internet
$IPT -A FORWARD -i $INET_IFACE -m state --state ESTABLISHED,RELATED \
     -j ACCEPT

# Port Forwarding is enabled, so accept forwarded traffic
$IPT -A FORWARD -p tcp -i $INET_IFACE --destination-port 8080 \
     --destination 192.168.1.50 -j ACCEPT 

# Log packets that still don't match
$IPT -A FORWARD -j LOG --log-prefix "fp=FORWARD:99 a=DROP "

###############################################################################
#
# OUTPUT Chain
#

echo "Process OUTPUT chain ..."

# Generally trust the firewall on output

# However, invalid icmp packets need to be dropped
# to prevent a possible exploit.
$IPT -A OUTPUT -m state -p icmp --state INVALID -j DROP

# Localhost
$IPT -A OUTPUT -p ALL -s $LO_IP -j ACCEPT
$IPT -A OUTPUT -p ALL -o $LO_IFACE -j ACCEPT

# To internal network
$IPT -A OUTPUT -p ALL -s $LOCAL_IP -j ACCEPT
$IPT -A OUTPUT -p ALL -o $LOCAL_IFACE -j ACCEPT

# To internet
$IPT -A OUTPUT -p ALL -o $INET_IFACE -j ACCEPT

# Log packets that still don't match
$IPT -A OUTPUT -j LOG --log-prefix "fp=OUTPUT:99 a=DROP "

###############################################################################
#
# nat table
#
###############################################################################

# The nat table is where network address translation occurs if there
# is a private network.  If the gateway is connected to the Internet
# with a static IP, snat is used.  If the gateway has a dynamic address,
# masquerade must be used instead.  There is more overhead associated
# with masquerade, so snat is better when it can be used.
# The nat table has a builtin chain, PREROUTING, for dnat and redirects.
# Another, POSTROUTING, handles snat and masquerade.

echo "Load rules for nat table ..."

###############################################################################
#
# PREROUTING chain
#

# Port Forwarding
# 
# Port forwarding forwards all traffic on a port or ports from
# the firewall to a computer on the internal LAN.  This can
# be required to support special situations.  For instance,
# this is the only way to support file transfers with an ICQ
# client on an internal computer.  It's also required if an internal
# system hosts a service such as a web server.  However, it's also
# a dangerous option.  It allows Internet computers access to
# your internal network.  Use it carefully and only if you're
# certain you know what you're doing.

$IPT -t nat -A PREROUTING -p tcp -i $INET_IFACE --destination-port 80:80 \
     -j DNAT --to-destination 192.168.1.50:8080

# This is a sample that will exempt a specific host from the transparent proxy
#$IPT -t nat -A PREROUTING -p tcp -s 192.168.1.50 --destination-port 80 \
#     -j RETURN
#$IPT -t nat -A PREROUTING -p tcp -s 192.168.1.50 --destination-port 443 \
#     -j RETURN

# Redirect HTTP for a transparent proxy
$IPT -t nat -A PREROUTING -p tcp --destination-port 80 \
     -j REDIRECT --to-ports 3128
# Redirect HTTPS for a transparent proxy - commented by default
# $IPT -t nat -A PREROUTING -p tcp --destination-port 443 \
#     -j REDIRECT --to-ports 3128

###############################################################################
#
# POSTROUTING chain
#

$IPT -t nat -A POSTROUTING -o $INET_IFACE -j MASQUERADE

###############################################################################
#
# mangle table
#
###############################################################################

# The mangle table is used to alter packets.  It can alter or mangle them in
# several ways.  For the purposes of this generator, we only use its ability
# to alter the TTL in packets.  However, it can be used to set netfilter
# mark values on specific packets.  Those marks could then be used in another
# table like filter, to limit activities associated with a specific host, for
# instance.  The TOS target can be used to set the Type of Service field in
# the IP header.  Note that the TTL target might not be included in the
# distribution on your system.  If it is not and you require it, you will
# have to add it.  That may require that you build from source.

echo "Load rules for mangle table ..."

# Set the TTL in outbound packets to the same consistent value.
# A value around 128 is a good value.  Do not set this too high as
# it will adversely affect your network.  It is also considered bad
# form on the Internet.
$IPT -t mangle -A OUTPUT -o $INET_IFACE -j TTL --ttl-set 128

A Faire - Utilisez la commande system-config-firewall pour lancer l'outil graphique Configuration du pare-feu et constatez la configuration de netfilter.

LAB #2 - La Configuration par firewalld sous RHEL/CentOS 7

firewalld est à Netfilter ce que NetworkManager est au réseau. firewalld utilise des zones - des jeux de règles pré-définis dans lesquels sont placés les interfaces :

  • trusted - un réseau fiable. Dans ce cas tous les ports sont autorisés,
  • work, home, internal - un réseau partiellement fiable. Dans ce cas quelques ports sont autorisés,
  • dmz, public, external - un réseau non fiable. Dans ce cas peu de ports sont autorisés,
  • block, drop - tout est interdit. La zone drop n'envoie pas de messages d'erreurs.

Important - Une interface ne peut être que dans une zone à la fois tandis que plusieurs interfaces peuvent être dans la même zone.

Le service firewalld doit toujours être lancé :

[root@centos7 ~]# systemctl status firewalld.service
firewalld.service - firewalld - dynamic firewall daemon
   Loaded: loaded (/usr/lib/systemd/system/firewalld.service; enabled)
   Active: active (running) since Tue 2015-07-07 15:53:56 CEST; 1 day 21h ago
 Main PID: 493 (firewalld)
   CGroup: /system.slice/firewalld.service
           └─493 /usr/bin/python -Es /usr/sbin/firewalld --nofork --nopid

Jul 07 15:53:56 centos7.fenestros.loc systemd[1]: Started firewalld - dynamic firewall daemon.

La Configuration de Base de firewalld

La configuration par défaut de firewalld se trouve dans /usr/lib/firewalld :

[root@centos7 ~]# ls -l /usr/lib/firewalld/
total 12
drwxr-x---. 2 root root 4096 Jun  4 09:52 icmptypes
drwxr-x---. 2 root root 4096 Jun  4 09:52 services
drwxr-x---. 2 root root 4096 Jun  4 09:52 zones
[root@centos7 ~]# ls -l /usr/lib/firewalld/zones
total 36
-rw-r-----. 1 root root 299 Mar  6 00:35 block.xml
-rw-r-----. 1 root root 293 Mar  6 00:35 dmz.xml
-rw-r-----. 1 root root 291 Mar  6 00:35 drop.xml
-rw-r-----. 1 root root 304 Mar  6 00:35 external.xml
-rw-r-----. 1 root root 400 Mar  6 00:35 home.xml
-rw-r-----. 1 root root 415 Mar  6 00:35 internal.xml
-rw-r-----. 1 root root 315 Mar  6 00:35 public.xml
-rw-r-----. 1 root root 162 Mar  6 00:35 trusted.xml
-rw-r-----. 1 root root 342 Mar  6 00:35 work.xml
[root@centos7 ~]# ls -l /usr/lib/firewalld/services
total 192
-rw-r-----. 1 root root 412 Mar  6 00:35 amanda-client.xml
-rw-r-----. 1 root root 320 Mar  6 00:35 bacula-client.xml
-rw-r-----. 1 root root 346 Mar  6 00:35 bacula.xml
-rw-r-----. 1 root root 305 Mar  6 00:35 dhcpv6-client.xml
-rw-r-----. 1 root root 234 Mar  6 00:35 dhcpv6.xml
-rw-r-----. 1 root root 227 Mar  6 00:35 dhcp.xml
-rw-r-----. 1 root root 346 Mar  6 00:35 dns.xml
-rw-r-----. 1 root root 374 Mar  6 00:35 ftp.xml
-rw-r-----. 1 root root 476 Mar  6 00:35 high-availability.xml
-rw-r-----. 1 root root 448 Mar  6 00:35 https.xml
-rw-r-----. 1 root root 353 Mar  6 00:35 http.xml
-rw-r-----. 1 root root 372 Mar  6 00:35 imaps.xml
-rw-r-----. 1 root root 454 Mar  6 00:35 ipp-client.xml
-rw-r-----. 1 root root 427 Mar  6 00:35 ipp.xml
-rw-r-----. 1 root root 517 Mar  6 00:35 ipsec.xml
-rw-r-----. 1 root root 233 Mar  6 00:35 kerberos.xml
-rw-r-----. 1 root root 221 Mar  6 00:35 kpasswd.xml
-rw-r-----. 1 root root 232 Mar  6 00:35 ldaps.xml
-rw-r-----. 1 root root 199 Mar  6 00:35 ldap.xml
-rw-r-----. 1 root root 385 Mar  6 00:35 libvirt-tls.xml
-rw-r-----. 1 root root 389 Mar  6 00:35 libvirt.xml
-rw-r-----. 1 root root 424 Mar  6 00:35 mdns.xml
-rw-r-----. 1 root root 211 Mar  6 00:35 mountd.xml
-rw-r-----. 1 root root 190 Mar  6 00:35 ms-wbt.xml
-rw-r-----. 1 root root 171 Mar  6 00:35 mysql.xml
-rw-r-----. 1 root root 324 Mar  6 00:35 nfs.xml
-rw-r-----. 1 root root 389 Mar  6 00:35 ntp.xml
-rw-r-----. 1 root root 335 Mar  6 00:35 openvpn.xml
-rw-r-----. 1 root root 433 Mar  6 00:35 pmcd.xml
-rw-r-----. 1 root root 474 Mar  6 00:35 pmproxy.xml
-rw-r-----. 1 root root 544 Mar  6 00:35 pmwebapis.xml
-rw-r-----. 1 root root 460 Mar  6 00:35 pmwebapi.xml
-rw-r-----. 1 root root 357 Mar  6 00:35 pop3s.xml
-rw-r-----. 1 root root 181 Mar  6 00:35 postgresql.xml
-rw-r-----. 1 root root 261 Mar  6 00:35 proxy-dhcp.xml
-rw-r-----. 1 root root 446 Mar  6 00:35 radius.xml
-rw-r-----. 1 root root 517 Mar  6 00:35 RH-Satellite-6.xml
-rw-r-----. 1 root root 214 Mar  6 00:35 rpc-bind.xml
-rw-r-----. 1 root root 384 Mar  6 00:35 samba-client.xml
-rw-r-----. 1 root root 461 Mar  6 00:35 samba.xml
-rw-r-----. 1 root root 550 Mar  6 00:35 smtp.xml
-rw-r-----. 1 root root 463 Mar  6 00:35 ssh.xml
-rw-r-----. 1 root root 393 Mar  6 00:35 telnet.xml
-rw-r-----. 1 root root 301 Mar  6 00:35 tftp-client.xml
-rw-r-----. 1 root root 437 Mar  6 00:35 tftp.xml
-rw-r-----. 1 root root 211 Mar  6 00:35 transmission-client.xml
-rw-r-----. 1 root root 475 Mar  6 00:35 vnc-server.xml
-rw-r-----. 1 root root 310 Mar  6 00:35 wbem-https.xml
[root@centos7 ~]# ls -l /usr/lib/firewalld/icmptypes/
total 36
-rw-r-----. 1 root root 222 Mar  6 00:35 destination-unreachable.xml
-rw-r-----. 1 root root 173 Mar  6 00:35 echo-reply.xml
-rw-r-----. 1 root root 210 Mar  6 00:35 echo-request.xml
-rw-r-----. 1 root root 225 Mar  6 00:35 parameter-problem.xml
-rw-r-----. 1 root root 185 Mar  6 00:35 redirect.xml
-rw-r-----. 1 root root 227 Mar  6 00:35 router-advertisement.xml
-rw-r-----. 1 root root 223 Mar  6 00:35 router-solicitation.xml
-rw-r-----. 1 root root 248 Mar  6 00:35 source-quench.xml
-rw-r-----. 1 root root 253 Mar  6 00:35 time-exceeded.xml

Ces fichiers sont au format xml, par exemple :

[root@centos7 ~]# cat /usr/lib/firewalld/zones/home.xml 
<?xml version="1.0" encoding="utf-8"?>
<zone>
  <short>Home</short>
  <description>For use in home areas. You mostly trust the other computers on networks to not harm your computer. Only selected incoming connections are accepted.</description>
  <service name="ssh"/>
  <service name="ipp-client"/>
  <service name="mdns"/>
  <service name="samba-client"/>
  <service name="dhcpv6-client"/>
</zone>

La configuration de firewalld ainsi que les définitions et règles personnalisées se trouvent dans /etc/firewalld :

[root@centos7 ~]# ls -l /etc/firewalld/
total 8
-rw-r-----. 1 root root 1026 Mar  6 00:35 firewalld.conf
drwxr-x---. 2 root root    6 Mar  6 00:35 icmptypes
-rw-r-----. 1 root root  271 Mar  6 00:35 lockdown-whitelist.xml
drwxr-x---. 2 root root    6 Mar  6 00:35 services
drwxr-x---. 2 root root   23 Mar  6 00:35 zones
[root@centos7 ~]# ls -l /etc/firewalld/zones/
total 4
-rw-r--r--. 1 root root 315 Mar  8 14:05 public.xml
[root@centos7 ~]# ls -l /etc/firewalld/services/
total 0
[root@centos7 ~]# ls -l /etc/firewalld/icmptypes/
total 0

Le fichier de configuration de firewalld est /etc/firewalld/firewalld.conf :

[root@centos7 ~]# cat /etc/firewalld/firewalld.conf 
# firewalld config file

# default zone
# The default zone used if an empty zone string is used.
# Default: public
DefaultZone=public

# Minimal mark
# Marks up to this minimum are free for use for example in the direct 
# interface. If more free marks are needed, increase the minimum
# Default: 100
MinimalMark=100

# Clean up on exit
# If set to no or false the firewall configuration will not get cleaned up
# on exit or stop of firewalld
# Default: yes
CleanupOnExit=yes

# Lockdown
# If set to enabled, firewall changes with the D-Bus interface will be limited
# to applications that are listed in the lockdown whitelist.
# The lockdown whitelist file is lockdown-whitelist.xml
# Default: no
Lockdown=no

# IPv6_rpfilter
# Performs a reverse path filter test on a packet for IPv6. If a reply to the
# packet would be sent via the same interface that the packet arrived on, the 
# packet will match and be accepted, otherwise dropped.
# The rp_filter for IPv4 is controlled using sysctl.
# Default: yes
IPv6_rpfilter=yes

La Commande firewall-cmd

firewalld s'appuie sur netfilter. Pour cette raison, l'utilisation de firewall-cmd est incompatible avec l'utilisation des commandes iptables et system-config-firewall.

Important - firewall-cmd est le front-end de firewalld en ligne de commande. Il existe aussi la commande firewall-config qui lance un outi de configuration graphique.

Pour obtenir la liste de toutes les zones prédéfinies, utilisez la commande suivante :

[root@centos7 ~]# firewall-cmd --get-zones
block dmz drop external home internal public trusted work

Pour obtenir la liste de toutes les services prédéfinis, utilisez la commande suivante :

[root@centos7 ~]# firewall-cmd --get-services
RH-Satellite-6 amanda-client bacula bacula-client dhcp dhcpv6 dhcpv6-client dns ftp high-availability http https imaps ipp ipp-client ipsec kerberos kpasswd ldap ldaps libvirt libvirt-tls mdns mountd ms-wbt mysql nfs ntp openvpn pmcd pmproxy pmwebapi pmwebapis pop3s postgresql proxy-dhcp radius rpc-bind samba samba-client smtp ssh telnet tftp tftp-client transmission-client vnc-server wbem-https

Pour obtenir la liste de toutes les types ICMP prédéfinis, utilisez la commande suivante :

[root@centos7 ~]# firewall-cmd --get-icmptypes
destination-unreachable echo-reply echo-request parameter-problem redirect router-advertisement router-solicitation source-quench time-exceeded

Pour obtenir la liste des zones de la configuration courante, utilisez la commande suivante :

[root@centos7 ~]# firewall-cmd --get-active-zones
public
  interfaces: enp0s3

Pour obtenir la liste des zones de la configuration courante pour une interface spécifique, utilisez la commande suivante :

[root@centos7 ~]# firewall-cmd --get-zone-of-interface=enp0s3
public

Pour obtenir la liste des services autorisés pour la zone public, utilisez la commande suivante :

[root@centos7 ~]# firewall-cmd --zone=public --list-services
dhcpv6-client ssh

Pour obtenir toute la configuration pour la zone public, utilisez la commande suivante :

[root@centos7 ~]# firewall-cmd --zone=public --list-all
public (default, active)
  interfaces: enp0s3
  sources: 
  services: dhcpv6-client ssh
  ports: 
  masquerade: no
  forward-ports: 
  icmp-blocks: 
  rich rules: 
	

Pour obtenir la liste complète de toutes les zones et leurs configurations, utilisez la commande suivante :

[root@centos7 ~]# firewall-cmd --list-all-zones
block
  interfaces: 
  sources: 
  services: 
  ports: 
  masquerade: no
  forward-ports: 
  icmp-blocks: 
  rich rules: 
	
dmz
  interfaces: 
  sources: 
  services: ssh
  ports: 
  masquerade: no
  forward-ports: 
  icmp-blocks: 
  rich rules: 
	
drop
  interfaces: 
  sources: 
  services: 
  ports: 
  masquerade: no
  forward-ports: 
  icmp-blocks: 
  rich rules: 
	
external
  interfaces: 
  sources: 
  services: ssh
  ports: 
  masquerade: yes
  forward-ports: 
  icmp-blocks: 
  rich rules: 
	
home
  interfaces: 
  sources: 
  services: dhcpv6-client ipp-client mdns samba-client ssh
  ports: 
  masquerade: no
  forward-ports: 
  icmp-blocks: 
  rich rules: 
	
internal
  interfaces: 
  sources: 
  services: dhcpv6-client ipp-client mdns samba-client ssh
  ports: 
  masquerade: no
  forward-ports: 
  icmp-blocks: 
  rich rules: 
	
public (default, active)
  interfaces: enp0s3
  sources: 
  services: dhcpv6-client ssh
  ports: 
  masquerade: no
  forward-ports: 
  icmp-blocks: 
  rich rules: 
	
trusted
  interfaces: 
  sources: 
  services: 
  ports: 
  masquerade: no
  forward-ports: 
  icmp-blocks: 
  rich rules: 
	
work
  interfaces: 
  sources: 
  services: dhcpv6-client ipp-client ssh
  ports: 
  masquerade: no
  forward-ports: 
  icmp-blocks: 
  rich rules: 

Pour changer la zone par défaut de public à work, utilisez la commande suivante :

[root@centos7 ~]# firewall-cmd --set-default-zone=work
success
[root@centos7 ~]# firewall-cmd --get-active-zones
work
  interfaces: enp0s3

Pour ajouter l'interface ip_fixe à la zone work, utilisez la commande suivante :

[root@centos7 ~]# firewall-cmd --zone=work --add-interface=ip_fixe
success
[root@centos7 ~]# firewall-cmd --get-active-zones
work
  interfaces: enp0s3 ip_fixe

Pour supprimer l'interface ip_fixe à la zone work, utilisez la commande suivante :

[root@centos7 ~]# firewall-cmd --zone=work --remove-interface=ip_fixe
success
[root@centos7 ~]# firewall-cmd --get-active-zones
work
  interfaces: enp0s3

Pour ajouter le service http à la zone work, utilisez la commande suivante :

[root@centos7 ~]# firewall-cmd --zone=work --add-service=http
success
[root@centos7 ~]# firewall-cmd --zone=work --list-services
dhcpv6-client http ipp-client ssh

Pour supprimer le service http de la zone work, utilisez la commande suivante :

[root@centos7 ~]# firewall-cmd --zone=work --remove-service=http
success
[root@centos7 ~]# firewall-cmd --zone=work --list-services
dhcpv6-client ipp-client ssh

Pour ajouter un nouveau bloc ICMP, utilisez la commande suivante :

[root@centos7 ~]# firewall-cmd --zone=work --add-icmp-block=echo-reply
success
[root@centos7 ~]# firewall-cmd --zone=work --list-icmp-blocks
echo-reply

Pour supprimer un bloc ICMP, utilisez la commande suivante :

[root@centos7 ~]# firewall-cmd --zone=work --remove-icmp-block=echo-reply
success
[root@centos7 ~]# firewall-cmd --zone=work --list-icmp-blocks
[root@centos7 ~]# 

Pour ajouter le port 591/tcp à la zone work, utilisez la commande suivante :

[root@centos7 ~]# firewall-cmd --zone=work --add-port=591/tcp
success
[root@centos7 ~]# firewall-cmd --zone=work --list-ports
591/tcp

Pour supprimer le port 591/tcp à la zone work, utilisez la commande suivante :

[root@centos7 ~]# firewall-cmd --zone=work --remove-port=591/tcp
success
[root@centos7 ~]# firewall-cmd --zone=work --list-ports
[root@centos7 ~]#

Pour créer un nouveau service, il convient de :

  • copier un fichier existant se trouvant dans le répertoire /usr/lib/firewalld/services vers /etc/firewalld/services,
  • modifier le fichier,
  • recharger la configuration de firewalld,
  • vérifier que firewalld voit le nouveau service.

Par exemple :

[root@centos7 ~]# cp /usr/lib/firewalld/services/http.xml /etc/firewalld/services/filemaker.xml
[root@centos7 ~]#
[root@centos7 ~]# cat /etc/firewalld/services/filemaker.xml 
<?xml version="1.0" encoding="utf-8"?>
<service>
  <short>FileMakerPro</short>
  <description>fichier de service firewalld pour FileMaker Pro</description>
  <port protocol="tcp" port="591"/>
</service>
[root@centos7 ~]#
[root@centos7 ~]# firewall-cmd --reload
success
[root@centos7 ~]#
[root@centos7 ~]# firewall-cmd --get-services
RH-Satellite-6 amanda-client bacula bacula-client dhcp dhcpv6 dhcpv6-client dns filemaker ftp high-availability http https imaps ipp ipp-client ipsec kerberos kpasswd ldap ldaps libvirt libvirt-tls mdns mountd ms-wbt mysql nfs ntp openvpn pmcd pmproxy pmwebapi pmwebapis pop3s postgresql proxy-dhcp radius rpc-bind samba samba-client smtp ssh telnet tftp tftp-client transmission-client vnc-server wbem-https

La Configuration Avancée de firewalld

La configuration de base de firewalld ne permet que la configuration des zones, services, blocs ICMP et les ports non-standard. Cependant firewalld peut également être configuré avec des Rich Rules ou Règles Riches. Rich Rules ou Règles Riches évaluent des critères pour ensuite entreprendre une action.

Les Critères sont :

  • source address=“<adresse_IP>“
  • destination address=”<adresse_IP>“,
  • rule port port=”<numéro_du_port>“,
  • service name=<nom_d'un_sevice_prédéfini>.

Les Actions sont :

  • accept,
  • reject,
    • une Action reject peut être associée avec un message d'erreur spécifique par la clause type=”<type_d'erreur>,
  • drop.

Saisissez la commande suivante pour ouvrir le port 80 :

[root@centos7 ~]# firewall-cmd --add-rich-rule='rule port port="80" protocol="tcp" accept'
success

Important - Notez que la Rich Rule doit être entourée de caractères '.

Saisissez la commande suivante pour visualiser la règle iptables pour IPv4 :

[root@centos7 ~]# iptables -L -n | grep 80
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:80 ctstate NEW

Saisissez la commande suivante pour visualiser la règle iptables pour IPv6 :

[root@centos7 ~]# ip6tables -L -n | grep 80
ACCEPT     udp      ::/0                 fe80::/64            udp dpt:546 ctstate NEW
ACCEPT     tcp      ::/0                 ::/0                 tcp dpt:80 ctstate NEW

Important - Notez que la Rich Rule a créé deux règles, une pour IPv4 et une deuxième pour IPv6. Une règle peut être créée pour IPv4 seul en incluant le Critère family=ipv4. De la même façon, une règle peut être créée pour IPv6 seul en incluant le Critère family=ipv6.

Cette nouvelle règle est écrite en mémoire mais non pas sur disque. Pour l'écrire sur disque dans le fichier zone se trouvant dans /etc/firewalld, il faut ajouter l'option –permanent :

[root@centos7 ~]# firewall-cmd --add-rich-rule='rule port port="80" protocol="tcp" accept' --permanent
success
[root@centos7 ~]#
[root@centos7 ~]# cat /etc/firewalld/zones/work.xml 
<?xml version="1.0" encoding="utf-8"?>
<zone>
  <short>Work</short>
  <description>For use in work areas. You mostly trust the other computers on networks to not harm your computer. Only selected incoming connections are accepted.</description>
  <service name="ipp-client"/>
  <service name="dhcpv6-client"/>
  <service name="ssh"/>
  <rule>
    <port protocol="tcp" port="80"/>
    <accept/>
  </rule>
</zone>

Important - Attention ! La règle ajoutée avec l'option –permanent n'est pas prise en compte imédiatement mais uniquement au prochain redémmarge. Pour qu'une règle soit appliquée immédiatement et être écrite sur disque, il faut saisir la commande deux fois dont une avec l'option –permanent et l'autre sans l'option –permanent.

Pour visualiser cette règle dans la configuration de firewalld, il convient de saisir la commande suivante :

[root@centos7 ~]# firewall-cmd --list-all-zones
...	
work (default, active)
  interfaces: enp0s3
  sources: 
  services: dhcpv6-client ipp-client ssh
  ports: 
  masquerade: no
  forward-ports: 
  icmp-blocks: 
  rich rules: 
	rule port port="80" protocol="tcp" accept

Notez que la Rich Rule est créée dans la Zone par Défaut. Il est possible de créer une Rich Rule dans une autre zone en utilisant l'option –zone=<zone> de la commande firewall-cmd :

[root@centos7 ~]# firewall-cmd --zone=public --add-rich-rule='rule port port="80" protocol="tcp" accept'
success
[root@centos7 ~]# firewall-cmd --list-all-zones
...
public
  interfaces: 
  sources: 
  services: dhcpv6-client ssh
  ports: 
  masquerade: no
  forward-ports: 
  icmp-blocks: 
  rich rules: 
	rule port port="80" protocol="tcp" accept
trusted
  interfaces: 
  sources: 
  services: 
  ports: 
  masquerade: no
  forward-ports: 
  icmp-blocks: 
  rich rules: 
	
work (default, active)
  interfaces: enp0s3
  sources: 
  services: dhcpv6-client ipp-client ssh
  ports: 
  masquerade: no
  forward-ports: 
  icmp-blocks: 
  rich rules: 
	rule port port="80" protocol="tcp" accept

Pour supprimer une Rich Rule, il faut copier la ligne entière la concernant qui se trouve dans la sortie de la commande firewall-cmd –list-all-zones :

[root@centos7 ~]# firewall-cmd --zone=public --remove-rich-rule='rule port port="80" protocol="tcp" accept'
success

Le mode Panic de firewalld

Le mode Panic de firewalld permet de bloquer tout le trafic avec une seule commande. Pour connaître l'état du mode Panic, utilisez la commande suivante :

[root@centos7 ~]# firewall-cmd --query-panic
no

Pour activer le mode Panic, il convient de saisir la commande suivante :

[root@centos7 ~]# firewall-cmd --panic-on
success
[root@centos7 ~]# firewall-cmd --query-panic
yes

Pour désactiver le mode Panic, il convient de saisir la commande suivante :

[root@centos7 ~]# firewall-cmd --panic-off
success
[root@centos7 ~]# firewall-cmd --query-panic
no

<html>

Copyright © 2020 Hugh Norris.<br><br>

</html>

Menu