Notes de laboratoiresUE Système d’exploitation
AAs Administration UNIX 1 & 22èmes Master Ingénieurs Industriels en Informatique (M28)
Haute Ecole de la Province de Liège (HEPL)
Ludovic Kuty <[email protected]>Mounawar Madani <[email protected]>
2016–2017Version du 13 septembre 2016 à 19:44
HEPL 2016–2017 Table des matières L. Kuty & M. Madani
Table des matières
1 Introduction 21.1 Machines à disposition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.2 Configuration initiale . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2 Labo 1 : accès distant sécurisé à l’intranet 42.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42.2 SSH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.2.1 Scénario 1 : accès à Internet depuis l’intranet . . . . . . . . . . . . . . . . . . . . . . . 42.2.2 Scénario 2 : accès SSH à un serveur de I . . . . . . . . . . . . . . . . . . . . . . . . . . 42.2.3 Scénario 3 : accès à I par un serveur de I . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.3 OpenVPN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
3 iptables 73.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73.2 Netfilter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73.3 Iptables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.3.1 Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93.3.2 Chains . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93.3.3 Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123.3.4 Policies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123.3.5 User-defined chains . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123.3.6 Filter table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
3.4 iptables command tool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143.4.1 Add a new rule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143.4.2 List the existing rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143.4.3 Removing a rule, flushing a chain or removing a chain . . . . . . . . . . . . . . . . . . 153.4.4 Creating or renaming a chain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.5 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153.6 Extended modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
3.6.1 tcp module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173.6.2 comment module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173.6.3 connbytes module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
3.7 Fail2ban . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173.8 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
13 septembre 2016 19:44 Administration UNIX 1 & 2 1
HEPL 2016–2017 1. Introduction L. Kuty & M. Madani
Chapitre 1
Introduction
Ce document constitue le document de référence des activités d’apprentissages (AA) ”Administration UNIX1” et ”Administration UNIX 2” de l’unité d’enseignement (UE) ”Système d’exploitation” pour l’année 2015-2016. Le système d’exploitation utilisé est Ubuntu Server 14.04.3 LTS. Lorsqu’on utilise le terme ”cours”dans le cadre de ce document, on fait référence aux deux AAs précitées.Le cours est organisé en laboratoires à réaliser par les étudiants en se basant sur les indications fourniesainsi que des ressources extérieures (livres, Web, …). Pour réaliser un des laboratoire, il peut être nécessairede consulter d’autres chapitres de ce document.Vous pouvez obtenir la dernière version de ce document sur le Web1.Nous utilisons indifféremment des lettres minuscules et majuscules en italique ou pas pour désigner leséquipements présents sur les topologie ainsi que les entités plus génériques telle ques les entreprises, lesréseaux, etc. Par exemple, on peut représenter une entreprise par la lettre E ou E.
1.1 Machines à disposition
Un certain nombre de machines sont mises à votre disposition sur Internet. Chaque équipe d’étudiant disposede plusieurs serveurs faisant tous partie d’une entreprise E hypothétique. On identifie une équipe par unnombre, soit X. Par conséquent l’équipe d’étudiants X possède l’entreprise EX ou plus simplement entrepriseX et son intranet IX ou plus simplement intranet X.Chaque entreprise X possède 3 machines tel qu’on peut le voir sur la figure 1.1.
• Une machine publique qui fait office de passerelle (routeur) pour l’intranet avec une IP publique surInternet et une IP privée sur l’intranet (192.168.0.254). Cette machine est nommée RE pour ”routeurentreprise” ou vmX-gw où le X doit être remplacé par un nombre étant donné que les vrais nom dedomaine de ces machines sont du type vm1-gw.khi.be.
• Deux machines vmX-1 et vmX-2 dans l’intranet de l’entreprise dont l’adresse est 192.168.0.0/24.Les informations pratiques de connexion aux machines vont seront données pendant le cours. Notez quechaque machine est une machine virtuelle (VM) de type VMWare dont un snapshot permettant de revenirà l’état initial a été réalisé.
1https://cours.khi.be/isil/unix/administration_unix_1_2.pdf
13 septembre 2016 19:44 Administration UNIX 1 & 2 2
HEPL 2016–2017 1. Introduction L. Kuty & M. Madani
Fig. 1.1: Topologie de l’entreprise X
vmX-1
vmX-gw.khi.be
Enterprise X
vmX-2
intranetLAN 192.168.0.0/24
1.2 Configuration initiale
On vous demande de générer une paire de clés RSA (publique/privée) pour SSH à l’aide de PuTTY ou dela commande ssh-keygen avec les options -b et -t pour accéder à votre machine vmX-gw. Protégez votreclé privée à l’aide d’un mot de passe. Vous pourrez utiliser pageant avec PuTTY ou ssh-agent et ssh-addsous Unix.On vous demande également d’acheter un nom de domaine dont le ccTLD (country code top-level domain)est be chez le registrar Gandi2. Cela vous permettra également de bénéficier d’un certificat SSL lorsque nousen aurons besoin. Le prix demandé est modeste puisqu’il est actuellement de 12 euros.
2https://www.gandi.net/
13 septembre 2016 19:44 Administration UNIX 1 & 2 3
HEPL 2016–2017 2. Labo 1 : accès distant sécurisé à l’intranet L. Kuty & M. Madani
Chapitre 2
Labo 1 : accès distant sécurisé à l’intranet
2.1 Introduction
Une entreprise désire donner la possibilité à ses travailleurs distants (remote workers) qui disposent d’unordinateur sur Internet, c’est-à-dire à l’extérieur de l’intranet, d’accéder de manière sécurisée aux ressourcesde l’entreprise. Dans notre cas, l’intranet sera simplement un LAN et les ressources de l’entreprise sont desserveurs sur ce LAN.Dans toutes les manipulations qui suivent, nous vous invitons à utiliser régulièrement la commande netstatavec ses options comme -nltp par exemple.
2.2 SSH
2.2.1 Scénario 1 : accès à Internet depuis l’intranet
Dans un premier temps, on souhaite que les serveurs de l’intranet puissent accéder à Internet. Cela estreprésenté à la figure 2.1. On peut voir que serveur vmX-gw fait office de routeur (RE) entre Internet etl’intranet (adresses IP privées) et de ce fait il doit NAT-er le trafic sortant de l’intranet avec iptables.De plus on souhaite l’intranet soit protégé, c’est-à-dire que le trafic entrant venant d’Internet soit filtré pourne laisser passer que l’essentiel. Vous réaliserez également cela avec iptables.Le routeur RE fait églement office de serveur DNS pour l’intranet. Il s’agit d’un simple relay DNS. On vousdemande d’installer BIND pour réaliser cela et de le placer en écoute sur l’interface intranet.
2.2.2 Scénario 2 : accès SSH à un serveur de I
On désire pouvoir accéder directement au serveur S de l’intranet par SSH à partir du client C pour pouvoiréditer des fichiers de configuration du serveur, par exemple ceux se trouvant dans le répertoire /etc. Notezque la machine cliente C est elle-même sur un réseau appelé intranet client IC avec un routeur client RCqui permet un accès non limité à Internet1. Cela est représenté à la figure 2.2. Le serveur vmX-1 jouera lerôle de serveur S.Si on ne désire pas disposer d’un terminal bash sur RE mais qu’on désire malgré tout disposer d’un accès àS pour l’édition de fichiers, comment peut-on faire ? Nous vous invitons à regarder les options -f et -N dela commande SSH.
1En tout cas sur le port 22 comme c’est le cas sur le réseau de l’école.
13 septembre 2016 19:44 Administration UNIX 1 & 2 4
HEPL 2016–2017 2. Labo 1 : accès distant sécurisé à l’intranet L. Kuty & M. Madani
Fig. 2.1: Topologie de l’entreprise X
Internetserveur vmX-Y
routeur RE(vmX-gw.khi.be)
Entreprise E
trafic initial
trafic en retour
routerDNS forwarder
Fig. 2.2: Accès SSH à l’intranet X
serveur SSH S
routeur RE
Enterprise E
laptop client C
�� ��
13 septembre 2016 19:44 Administration UNIX 1 & 2 5
HEPL 2016–2017 2. Labo 1 : accès distant sécurisé à l’intranet L. Kuty & M. Madani
Fig. 2.3: Accès SSH à S1
serveur SSH S1
routeur RE
Enterprise E
laptop client C
�� ��
��
2.2.3 Scénario 3 : accès à I par un serveur de I
Imaginons que RE n’écoute pas sur son port 22 avec le protocole SSH ou plus précisément qu’il écoute surson port 22 mais que cela ne permet que de donner un accès local (aucun forwarding) comme un véritablerouteur pourrait le faire. Pensez par exemple à un routeur Cisco. Configurez le serveur SSH sur RE pourque cette restriction soit effective.A l’aide de netcat (command nc), montrez que le trafic TCP à destination du port 21 n’est pas filtré lorsquevous tentez une connexion du client C au routeur RE. Réalisez la même opération à l’aide de tcpdump envous limitant aux demandes de connexion (SYN).Le routeur RE possède une règle NAT qui permet d’atteindre le service SSH de S1 en accédant au port 21(de RE). Cela est illustré sur la figure 2.3. On vous demande d’ajouter cette règle NAT avec iptables.Donnez un accès grâce à SSH à S1. On doit pouvoir accéder aux fichiers de S1. Attention, pour un maximumde sécurité, nous vous invitons à placer un filtrage basé sur l’IP source. Nous vous invitons également àconsidérer les options -A et -t de la commande ssh.
2.3 OpenVPN
On vous demande de configurer OpenVPN sur RE de manière à avoir un accès au LAN.
13 septembre 2016 19:44 Administration UNIX 1 & 2 6
HEPL 2016–2017 3. iptables L. Kuty & M. Madani
Chapitre 3
iptables
3.1 Introduction
Nous sommes intéressés par la sécurité réseau de notre réseau d’entreprise. Si on considère un contexte plusgénéral, de quoi désire-t-on se protéger ?
• Accès physique à la machine Unix.• Escalade de privilège local: obtenir un accès root grâce à une vulnérabilité ou une mauvaise configura-
tion. L’attaquant a déjà accès au système. On parle de ”local privilege escalation” en anglais.• Attaques distantes contre les services en écoute sur une adresse qui n’est pas de type loopback. En
particulier sur une adresse Internet publique. Les attaques directes contre l’implémentation de la pilede protocoles (network stack) sont possibles mais rare.
Nous allons nous facoliser sur la sécurité réseau et sur les attaques réseau provenant d’Internet. Une desmanières de se protéger de ce type d’attaque est d’utiliser un pare-feu (firewall ou FW).On trouve communément deux types de FW selon la fonctionnalité principale proposée :
• Protection du réseau. Le FW est une machine en bordure du réseau : hardware ou software. Parexemple, Cisco PIX, Check Point, SmoothWall.
• Protection d’un hôte unique. Le FW est un composant software comme iptables ou le FW de votresolution de sécurité sur votre PC.
Nous sommes concernés par la protection de la machine en bordure de notre réseau (vmX-gw) ainsi que parla sécurité de l’intranet de notre entreprise.
3.2 Netfilter
Netfilter1 is a set of hooks inside the Linux kernel. It allows kernel modules to register callback functionswith the network stack. A registered callback function is then called back for every packet that traversesthe respective hook within the network stack. Thus, a piece of software is given the possibility to know andalter the flow of packets coming in or out of the system. This is illustrated at figures 3.1 and 3.2.After callback functions have done their processing of a packet, they return a code that tells the kernel whatit is supposed to do with the packet. The return codes are shown in the table below.
1http://www.netfilter.org/
13 septembre 2016 19:44 Administration UNIX 1 & 2 7
HEPL 2016–2017 3. iptables L. Kuty & M. Madani
Fig. 3.1: Netfilter hooks
NF_IP_PRE_ROUTING
NF_IP_LOCAL_IN NF_IP_LOCAL_OUT
NF_IP_POST_ROUTING
packet has entered interfacesanity checks ok
ROUTING
packet is for this host
ROUTING
going outthe interface
PACKET IN PACKET OUT
NF_IP_FORWARD
packet is for another host
localprocess
Fig. 3.2: Netfilter hooks
NF_IP_PRE_ROUTING
NF_IP_LOCAL_IN
NF_IP_LOCAL_OUT
NF_IP_FORWARDROUTING
localprocess
NF_IP_POST_ROUTING
ROUTING
13 septembre 2016 19:44 Administration UNIX 1 & 2 8
HEPL 2016–2017 3. iptables L. Kuty & M. Madani
Code MeaningNF_DROP Discard the packet and free ressourcesNF_ACCEPT Keep the packet and resume normal processingNF_STOLEN Forget the packet. The hook function has taken ownership
of the packet. Ressources are not freedNF_QUEUE Queue packet for userspaceNF_REPEAT Call the hook function once again
Netfilter was written by Rusty Russel to be the framework used by iptables. The chronological evolution isas follows:
• In kernel 2.0.x: ipfwadm.• In kernel 2.2.x: ipchains. Also written by Rusty Russel.• In kernel 2.4.x and 2.6.x: iptables on top of netfilter.
3.3 Iptables
Iptables is a packet filter built over the netfilter framework and implements the filtering mechanism with asimple linear algorithm. It has three concepts: tables, chains and rules. The associated userspace commandis iptables. Note that there exists an efficient lookup algorithm built in the nf-HiPAC2 packet filter.
3.3.1 Tables
Packets are fed to specific tables depending on the chosen hook. Thus, iptables registers hook functions withnetfilter to feed its tables. The tables are raw, filter, nat and mangle. They are described in the tablebelow and depicted on the figure 3.3. A table contains chains.
Table Meaningraw Used to avoid the connection tracking system. Check before
hitting connection tracking. May return NOTRACK.filter Used to filter out packets. This the main function of the
firewall.nat Used to perform NAT.mangle Used to alter packet content.
3.3.2 Chains
A chain is a set of rules examined in sequence for each packet. When a packet flows through iptables, ittraverses chains that are into tables. For example, an incoming packet for our machine will pass through thefilter INPUT chain. filter is the table, INPUT is the chain. There are default chains and user chains.The figure 3.4 shows the traversal of chains when a packet is send to our machine (enters our machine), thefigure 3.5 shows the traversal when a packet is send from our machine (exits our machine) and the figure3.6 shows what happens to a packet when it flows through our machine i.e. when it is forwarded. In thiscase, the machine acts as a router. All of this is pictured at figure 3.7.
2http://www.hipac.org/
13 septembre 2016 19:44 Administration UNIX 1 & 2 9
HEPL 2016–2017 3. iptables L. Kuty & M. Madani
Fig. 3.3: Tables and netfilter hooks: how iptables feed its tables.
NF_IP_PRE_ROUTING
NF_IP_LOCAL_IN NF_IP_LOCAL_OUT
NF_IP_POST_ROUTING
packet has entered interfacesanity checks ok
ROUTING
packet is for this host
ROUTING
going outthe interface
PACKET IN PACKET OUT
NF_IP_FORWARD
packet is for another host
localprocess
rawmangle
nat
manglefilter
manglefilter
manglenat
rawmangle
natfilter
feed thetables
feed thetables
feed thetables
feed thetables
feed thetables
Fig. 3.4: Traversal of iptables chains when a packet enters the machine.
Internet eth0 rawPREROUTING
manglePREROUTING
natPREROUTING
ROUTINGmangleINPUT
filterINPUT
localprocess
tablechain packet destined
for our own machine
Fig. 3.5: Traversal of iptables chains when a packet exits the machine.
Internet eth0
rawOUTPUT
mangleOUTPUTROUTING
manglePOSTROUTING
filterOUTPUT
localprocess
packet sourcedfrom our own machine
choose the out interfaceand the src address
natOUTPUT
ROUTINGnatPOSTROUTING
do SNAT
13 septembre 2016 19:44 Administration UNIX 1 & 2 10
HEPL 2016–2017 3. iptables L. Kuty & M. Madani
Fig. 3.6: Traversal of iptables chains when a packet is forwarded by the machine.
Internet eth0 rawPREROUTING
manglePREROUTING
natPREROUTING
manglePOSTROUTING
natPOSTROUTING
tablechain
packet forwardedby our machine
ROUTING
mangleFORWARD
filterFORWARDeth1
Fig. 3.7: Traversal of iptables chains.
Network
raw PREROUTING
mangle PREROUTING
nat PREROUTING
routingdecision
mangle INPUT
filter INPUT
localprocess
routingdecision
raw OUTPUT
mangle OUTPUT
nat OUTPUT
filter OUTPUT
routingdecision
mangle FORWARD
filter FORWARD
mangle POSTROUTING
nat POSTROUTING
Network
13 septembre 2016 19:44 Administration UNIX 1 & 2 11
HEPL 2016–2017 3. iptables L. Kuty & M. Madani
3.3.3 Rules
Inside chains we find rules. Each rule has a match expression and a target. The order of the rules in a chainmatters. The basic linear algorithm to find a matching rule for a given packet works like this: the machineasks itself if the rule and the packet match. There are two outcomes:
• No: we try the next rule.• Yes: we use the target action.
Targets indicate what to do with a packet. Each table has a set of valid targets that can be used with rules.There are more than 25 targets e.g. ACCEPT, DROP, REJECT, LOG and RETURN. Each of these common targetsare detailed in the table below.
Target Table MeaningACCEPT All The packet is accepted. Packet processing is resumed.DROP All The packet is simply dropped.
REJECT INPUT, FOR-WARD, OUT-PUT
The packet is dropped and an icmp packet informs the sen-ding host that the packet was rejected.
LOG All Log to syslog. ULOG can log to a DB.RETURN All Returns to the calling chain. If in a built-in chain, use the
policy as a target (default target).
3.3.4 Policies
A policy is a default action on a packet that has not matched any rules in a built-in chain. Each built-inchain has a policy. The policy is specified using a target. By default, INPUT and OUTPUT have ACCEPT andFORWARD has DROP.At listing 3.1 we look at the policy of the INPUT chain and change it to DROP. Note that since the defaultpolicy for the INPUT chain is ACCEPT, it is a security hole in a firewall and you should consider replacing itwith DROP.
Listing 3.1: Policy of the INPUT chain.
# iptables -L INPUT -n --line-numbers | head -n 1Chain INPUT (policy ACCEPT)# iptables -P INPUT DROP# iptables -L INPUT -n --line-numbers | head -n 1Chain INPUT (policy DROP)
Now we can show the complete sequence of rules used when processing a packet when no user-defined chainis called at figure 3.8.
3.3.5 User-defined chains
User can create their own chains called user-defined chains or user-specified chains. They are traversed byusing a jump from another chain in the same table. Typically from a built-in chain. If no rule is matched ina user-defined chain, the default behavior is to jump back to the originating chain. The two different waysof returning from a user-defined chain are shown at figures 3.9 and 3.10.
13 septembre 2016 19:44 Administration UNIX 1 & 2 12
HEPL 2016–2017 3. iptables L. Kuty & M. Madani
Fig. 3.8: Sequence of rules without any user-defined chain.
rule 1
rule 2
...
rule n
chain
no rule matches, use thechain policy
rule matches ! use the target action on packet
scen
ario
1
scen
ario
2Fig. 3.9: Return from a user-defined chain using an explicit RETURN action.
rule 1
rule 2
rule 3
rule 4
...
rule n
chain 1
rule 1
rule 2
...
chain 2
JUMPRETURN
Fig. 3.10: Return from a user-defined chain implicitly when reaching the bottom of it.
rule 1
rule 2
rule 3
rule 4
...
rule n
chain 1
rule 1
...
rule m
chain 2
JUMP
no rule matches, return tothe calling chain
13 septembre 2016 19:44 Administration UNIX 1 & 2 13
HEPL 2016–2017 3. iptables L. Kuty & M. Madani
3.3.6 Filter table
The filter is where the main function of the firewall is taking place. It is meant to filter out packets e.g. todrop all packets from a specific source. Thus we will mainly study this table.
3.4 iptables command tool
The iptables command tool is an administration tool for IPv4 packet filtering that is used to create/list/-modify/delete (CRUD operations) chains and rules. It has to be installed on the system as it usually is notpart of the system.
apt-get install iptables
3.4.1 Add a new rule
Let’s say that we want to accept all packets going to port 22 on our eth0 interface. We will enter thefollowing command:
iptables -t filter -A INPUT -i eth0 -p tcp --dport 22 -j ACCEPT
• -t to choose the table. By default it is filter.• -A to append a new rule to a specified chain. INPUT in our case.• -i to specify the interface. By default, all interfaces.• -p to choose from tcp, udp, icmp, all, …. We can specify the protocol numerically3 or by using a
keyword from /etc/protocols. This option enables suboptions like --dport for tcp.• --dport for the destination port. By default, all ports. We can use it (or its source counterpart --
sport) with a symbolic name taken from /etc/services. This file should be protected.• -j to choose the target: another chain, a built-in word or an extension.• Most of the options can be negated using the prefix !.
Now we can change our INPUT policy to DROP. Thanks to the previous rule, we can still have SSH sessionson our machine.When we add a new rule we have to choose where to insert it in the chain:
• -A to append a rule.• -I to insert the rule in front of the chain.• -I with a line number to choose precisely where to insert the rule. Use --line-numbers to know where
to insert it.• If a rule already exists, the new one is added ahead of the existing one.
3.4.2 List the existing rules
1 iptables -L -n --line-numbers2 iptables -L INPUT -n --line-numbers
• Lists the content of the INPUT chain of the filter table. By default, it lists all chains.3http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xml
13 septembre 2016 19:44 Administration UNIX 1 & 2 14
HEPL 2016–2017 3. iptables L. Kuty & M. Madani
• Use -t to specify the table.
3.4.3 Removing a rule, flushing a chain or removing a chain
1 iptables -D INPUT <rule specification>2 iptables -D INPUT 33 iptables -F INPUT4 iptables -X OLD_CHAIN5 iptables -X
Command at line 1 and 2 remove a specific rule in the INPUT chain, command at line 3 flushes the entireINPUT chain, command at line 4 to remove a specific user-defined chain and command at line 5 to removeall user-defined chains. Note that you can’t remove a built-in chain.
• The rule specification must exactly match the specification of the rule to be deleted.• We can provide a rule number.• -F flushes all the rules in a given chain. By default, it flushes the rules in all chains.
3.4.4 Creating or renaming a chain
1 iptables -N NEW_CHAIN2 iptables -E NEW_CHAIN OLD_CHAIN
As you can see:• -N to create a new user chain.• -E to change the name of a user created chain.
3.5 Example
Listing 3.2: INPUT chain of filter table.
# iptables -L -n --line-numbersChain INPUT (policy ACCEPT)num target prot opt source destination1 fail2ban-SSH tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:222 fail2ban-VSFTPD tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:213 IDENTD tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:1134 DROP tcp -- !127.0.0.0/8 0.0.0.0/0 /* No access to epmd erlang servicefrom outside */ tcp dpt:4369
The first three rules are used to invoke or call user-defined chains. If something is coming in for port 22, wewant to evaluate the rules in the fail2ban-SSH chain. The rules in this chain are dynamically inserted andremoved by a program called fail2ban based on logs. We have the same functionality for access to the FTPport 21. When something tries to connect to port 113 where the identd daemon listens to request from IRCservers to know your identity, we check that it is a well known server from a list of servers defined in theIDENTD user-defined chain.Last but not least, everything not coming from the localhost and going to the epmd daemon (used bythe Erlang programming language when performing distributed computation) is dropped without warning.
13 septembre 2016 19:44 Administration UNIX 1 & 2 15
HEPL 2016–2017 3. iptables L. Kuty & M. Madani
There was no way in the Erlang configuration to force it to listens to a private address instead of the publicone. Thanks to iptables we can provide the filter our program doesn’t provide.Note that:
• The targets at rule number 1, 2 and 3 are user-defined chains.• The destination 0.0.0.0/0 means ”going to any interface”.• The target at rule number 4 is a predefined action.• The source at rule number 4 matches everything that is not coming from localhost.
Listing 3.3: IDENTD user-defined chain.
Chain IDENTD (1 references)num target prot opt source destination1 RETURN all -- 195.144.12.5 0.0.0.0/0 /* Elsene.Be.Eu.undernet.org */2 RETURN all -- 194.109.20.90 0.0.0.0/0 /* Diemen.NL.EU.Undernet.Org */3 RETURN all -- 193.109.122.67 0.0.0.0/0 /* Ede.NL.EU.UnderNet.Org */4 DROP all -- 0.0.0.0/0 0.0.0.0/0
• The first three rules use the RETURN target to return to the calling chain and thus to avoid droppingthe packet and to resume processing.
• The fourth rule with DROP target drops any packet that does not match a previous rule in the chain.It is coming from an unwanted server.
• With this chain, if we match it is ok and we return.
Listing 3.4: fail2ban-SSH user-defined chain.
Chain fail2ban-SSH (2 references)num target prot opt source destination1 DROP all -- 83.229.249.251 0.0.0.0/02 DROP all -- 99.12.131.245 0.0.0.0/0...43 RETURN all -- 0.0.0.0/0 0.0.0.0/0
• The first 42 rules drop any packet coming from the given banned server.• Rule 43 returns to the calling chain to resume processing of a packet coming from a server that is not
banned.• With this chain, if we match it is not ok and we drop.
3.6 Extended modules
The basic components used to build a matching specification are too simple. Thus, extended packet matchingmodules or match extensions can be used to get a richer specification syntax. We have two ways to selectan extended module:
• -p to implicitly choose the module based on the protocol• or -m using the explicit module name.
Multiple -m options can be specified. All the modules are detailed in the iptables manpage. We can alsohave informations by using the integrated help in the iptables command by using the -h option as shownbelow.
13 septembre 2016 19:44 Administration UNIX 1 & 2 16
HEPL 2016–2017 3. iptables L. Kuty & M. Madani
iptables -p tcp -hiptables -m tcp -h
3.6.1 tcp module
We have already seen --dport and --sport to specify the TCP ports. The --syn option is also veryinteresting to identify connection attempts i.e. TCP packets with the SYN flag.
3.6.2 comment module
Use the comment module to add a comment to a rule to make it more readable.
1 root@unix2:~# iptables -A INPUT -p tcp --dport 80 -m comment --comment "Access to Webservice is restricted" -j DROP
2 root@unix2:~# iptables -L INPUT -n3 Chain INPUT (policy ACCEPT)4 target prot opt source destination5 DROP tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:80 /* Access to Web service is restricted */
3.6.3 connbytes module
Match by ”how many bytes” or ”how many packets” a connection has transferred so far. It can be done byaverage bytes per packet. It is useful to detect excessive traffic on a connection and mark it or reset it. Thecounters used are 64 bits that means 1.8E19 packets or 17 billions of GB.
3.7 Fail2ban
Fail2ban4 is a program that is used to ban hosts based on unsuccessful attempts found in log files. It does soby using a firewalling mechanism like iptables after having found suspect lines in log files thanks to regularexpressions. The ban rules are added in specific user-defined chains.
3.8 References
• Hardening Linux, James Turnbull, Apress, 2005, éditeur. Chapter 2: ”Firewalling Your Hosts”.• Iptables Tutorial 1.2.2, Oskar Andreasson.• The manpages of iptables.
4http://www.fail2ban.org/wiki/index.php/Main_Page
13 septembre 2016 19:44 Administration UNIX 1 & 2 17