Différences

Ci-dessous, les différences entre deux révisions de la page.

Lien vers cette vue comparative

Les deux révisions précédentesRévision précédente
Prochaine révision
Révision précédente
elearning:workbooks:centos:8:avance:l114 [2024/10/02 11:30] adminelearning:workbooks:centos:8:avance:l114 [2024/10/18 07:58] (Version actuelle) admin
Ligne 9: Ligne 9:
 =====Contenu du Module===== =====Contenu du Module=====
  
-  * **LCF606 - Gestion de Netfilter et de Firewalld**+  * **LCF606 - Gestion de la Sécurité**
     * Contenu du Module     * Contenu du Module
     * Le Pare-feu Netfilter/iptables     * Le Pare-feu Netfilter/iptables
Ligne 57: Ligne 57:
       * La commande semanage       * La commande semanage
       * La commande audit2allow       * La commande audit2allow
 +    * Mots de Passe
 +      * LAB #3 - John the Ripper
 +      * LAB #4 - Mise en place du Système de Prévention d'Intrusion Fail2Ban
 +        * Installation
 +        * Configuration
 +        * Le répertoire /etc/fail2ban
 +          * Le fichier fail2ban.conf
 +          * Le répertoire /etc/fail2ban/filter.d/
 +          * Le répertoire /etc/fail2ban/action.d/
 +        * Commandes
 +          * Activer et Démarrer le Serveur
 +          * Utiliser la Commande Fail2Ban-server
 +          * Ajouter un Prison
 +    * Balayage des Ports
 +      * LAB #5 - Utilisation de nmap et de netcat
 +        * nmap
 +          * Installation
 +          * Utilisation
 +          * Fichiers de Configuration
 +          * Scripts
 +        * netcat
 +          * Utilisation
 +      * LAB #6 - Mise en place du Système de Détection et de Prévention d'Intrusion Portsentry
 +        * Installation
 +        * Configuration
 +        * Utilisation
 +    * Système de Fichiers
 +      * LAB #7 - Mise en place du File Integrity Checker Afick
 +        * Présentation
 +        * Installation
 +        * Configuration
 +          * La Section Directives
 +          * La Section Alias
 +          * La Section File
 +        * Utilisation
 +        * Automatiser Afick
 +      * LAB #8 - Mise en place de rkhunter
 +        * Installation
 +        * Les options de la commande
 +        * Utilisation
 +        * Configuration
 +
  
 =====Le Pare-feu Netfilter===== =====Le Pare-feu Netfilter=====
Ligne 1053: Ligne 1095:
  
 <WRAP center round important 50%> <WRAP center round important 50%>
-**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.+**Important** - Attention ! La règle ajoutée avec l'option --permanent n'est pas prise en compte immédiatement mais uniquement au prochain redémarrage. 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.
 </WRAP> </WRAP>
  
Ligne 1352: Ligne 1394:
 ====Les fichiers .rhosts==== ====Les fichiers .rhosts====
  
-Le systeme rhosts presente une faille de securite importante pour un serveur Linux. Pour cette raison, il convient de supprimer les fichiers **.rhosts** des utilisateurs. Utilisez la commande suivante:+Le système rhosts présente une faille de sécurité importante pour un serveur Linux. Pour cette raison, il convient de supprimer les fichiers **.rhosts** des utilisateurs. Utilisez la commande suivante:
  
   # find / -name "\.rhosts" -exec rm -f \{\} \; [Entree]   # find / -name "\.rhosts" -exec rm -f \{\} \; [Entree]
Ligne 1358: Ligne 1400:
 ====Les fichiers et les repertoires sans proprietaire==== ====Les fichiers et les repertoires sans proprietaire====
  
-Afin de dresser la liste des fichiers et des groupes sans proprietaires sur le serveur, il convient d'utiliser les deux commandes suivantes:+Afin de dresser la liste des fichiers et des groupes sans propriétaires sur le serveur, il convient d'utiliser les deux commandes suivantes:
  
   # find / -nouser -exec ls -l \{\} \; 2> sans_pro.txt [Entree]   # find / -nouser -exec ls -l \{\} \; 2> sans_pro.txt [Entree]
Ligne 1374: Ligne 1416:
 ====Limiter le delai d'inactivite d'une session shell==== ====Limiter le delai d'inactivite d'une session shell====
  
-Une session de shell laissee ouverte inutilement et d'une maniere sans surveillance est un risque de securiteVerifiez donc le contenu du fichier **/etc/profile** :+Une session de shell laissée ouverte inutilement et d'une manière sans surveillance est un risque de sécuritéVérifiez donc le contenu du fichier **/etc/profile** :
  
 <code> <code>
Ligne 1465: Ligne 1507:
 </code> </code>
  
-A ce fichier doivent etre ajoutées les deux lignes suivantes:+A ce fichier doivent être ajoutées les deux lignes suivantes:
  
 <file> <file>
Ligne 1593: Ligne 1635:
 </WRAP> </WRAP>
  
-=====LAB #2 - Mise en place de SELinux pour sécuriser le serveur=====+=====Mise en place de SELinux pour sécuriser le serveur=====
  
 ====Introducton==== ====Introducton====
Ligne 2160: Ligne 2202:
 </code> </code>
  
-=====LAB #- Travailler avec SELinux=====+=====LAB #- Travailler avec SELinux=====
  
 Afin reconstruire la politique actuelle **sans** les règles **dontaudit**, utilisez la commande **semodule** : Afin reconstruire la politique actuelle **sans** les règles **dontaudit**, utilisez la commande **semodule** :
Ligne 2491: Ligne 2533:
  
 <code> <code>
 +[root@centos8 ~]# setenforce enforcing
  
 +[root@centos8 ~]# getenforce
 +Enforcing
 </code> </code>
  
Ligne 2581: Ligne 2626:
 </code> </code>
  
-Consultez les messages d'alerte de SELinux dans le fichier **/var/log/messages :+Consultez les messages d'alerte de SELinux dans le fichier **/var/log/messages** :
  
 <code> <code>
Ligne 3254: Ligne 3299:
    www1 test page    www1 test page
 </code> </code>
 +
 +=====Mots de Passe=====
 +
 +Un pirate peut utiliser un logiciel de **crackage** pour tenter de découvrir un mot de passe. Le plus connu est **[[http://www.dawal.org/article.php3?id_article=48|John The Ripper]]**.
 +
 +Le principe de ces logiciels est simples - le logiciel utilise des dictionnaires de mots de passe qui sont utilisés le uns après les autres à une vitesse qui peut atteindre des milliers par seconde.
 +
 +====LAB #3 - John the Ripper====
 +
 +===Installation===
 +
 +Créez le script suivant dans un terminal de RHEL/CentOS 7 en tant que root :
 +
 +<code>
 +[root@centos8 ~]# vi john.sh
 +[root@centos8 ~]# cat john.sh
 +#!/bin/bash
 +# Centos 7 John the Ripper Installation
 +yum -y install wget gpgme
 +yum -y group install "Development Tools"
 +cd
 +wget http://www.openwall.com/john/j/john-1.8.0.tar.xz
 +wget http://www.openwall.com/john/j/john-1.8.0.tar.xz.sign
 +wget http://www.openwall.com/signatures/openwall-signatures.asc
 +gpg --import openwall-signatures.asc
 +gpg --verify john-1.8.0.tar.xz.sign
 +tar xvfJ john-1.8.0.tar.xz
 +cd john-1.8.0/src
 +make clean linux-x86-64
 +cd ../run/
 +./john --test
 +#password dictionnary download
 +wget -O - http://mirrors.kernel.org/openwall/wordlists/all.gz | gunzip -c > openwall.dico
 +</code>
 +
 +Rendez-le exécutable :
 +
 +<code>
 +[root@centos8 ~]# chmod u+x john.sh 
 +</code>
 +
 +Exécutez le script :
 +
 +<code>
 +[root@centos8 ~]# ./john.sh 
 +</code>
 +
 +===Utilisation===
 +
 +Placez-vous dans le répertoire **/root/john-1.8.0/run** :
 +
 +<code>
 +[root@centos8 ~]# cd john-1.8.0/run/
 +</code>
 +
 +Utilisez l'utilitare **unshadow** pour créer le fichier des mots de passe :
 +
 +<code>
 +[root@centos8 run]# ./unshadow /etc/passwd /etc/shadow > mypasswd
 +</code>
 +
 +Consultez le fichier **mypasswd** :
 +
 +<code>
 +[root@centos8 run]# cat mypasswd
 +root:$6$ZagUzfR879NQxAks$hgn8rjBjwk9O/Bd6fsjQ9p5DPSw3ZoeJVz1SXahzeWsnov3VKn93WNHrqUsqmTqKV.jqza4Jdym7t5jzTA2ez.:0:0:root:/root:/bin/bash
 +bin:*:1:1:bin:/bin:/sbin/nologin
 +daemon:*:2:2:daemon:/sbin:/sbin/nologin
 +adm:*:3:4:adm:/var/adm:/sbin/nologin
 +lp:*:4:7:lp:/var/spool/lpd:/sbin/nologin
 +sync:*:5:0:sync:/sbin:/bin/sync
 +shutdown:*:6:0:shutdown:/sbin:/sbin/shutdown
 +halt:*:7:0:halt:/sbin:/sbin/halt
 +mail:*:8:12:mail:/var/spool/mail:/sbin/nologin
 +operator:*:11:0:operator:/root:/sbin/nologin
 +games:*:12:100:games:/usr/games:/sbin/nologin
 +ftp:*:14:50:FTP User:/var/ftp:/sbin/nologin
 +nobody:*:65534:65534:Kernel Overflow User:/:/sbin/nologin
 +dbus:!!:81:81:System message bus:/:/sbin/nologin
 +systemd-coredump:!!:999:997:systemd Core Dumper:/:/sbin/nologin
 +systemd-resolve:!!:193:193:systemd Resolver:/:/sbin/nologin
 +tss:!!:59:59:Account used for TPM access:/dev/null:/sbin/nologin
 +polkitd:!!:998:996:User for polkitd:/:/sbin/nologin
 +geoclue:!!:997:995:User for geoclue:/var/lib/geoclue:/sbin/nologin
 +rtkit:!!:172:172:RealtimeKit:/proc:/sbin/nologin
 +pipewire:!!:996:992:PipeWire System Daemon:/var/run/pipewire:/sbin/nologin
 +libstoragemgmt:!!:995:991:daemon account for libstoragemgmt:/var/run/lsm:/sbin/nologin
 +qemu:!!:107:107:qemu user:/:/sbin/nologin
 +clevis:!!:994:990:Clevis Decryption Framework unprivileged user:/var/cache/clevis:/sbin/nologin
 +usbmuxd:!!:113:113:usbmuxd user:/:/sbin/nologin
 +unbound:!!:993:989:Unbound DNS resolver:/etc/unbound:/sbin/nologin
 +gluster:!!:992:988:GlusterFS daemons:/run/gluster:/sbin/nologin
 +rpc:!!:32:32:Rpcbind Daemon:/var/lib/rpcbind:/sbin/nologin
 +avahi:!!:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin
 +dnsmasq:!!:987:987:Dnsmasq DHCP and DNS server:/var/lib/dnsmasq:/sbin/nologin
 +radvd:!!:75:75:radvd user:/:/sbin/nologin
 +saslauth:!!:986:76:Saslauthd user:/run/saslauthd:/sbin/nologin
 +sssd:!!:985:986:User for sssd:/:/sbin/nologin
 +cockpit-ws:!!:984:984:User for cockpit web service:/nonexisting:/sbin/nologin
 +cockpit-wsinstance:!!:983:983:User for cockpit-ws instances:/nonexisting:/sbin/nologin
 +chrony:!!:982:982::/var/lib/chrony:/sbin/nologin
 +colord:!!:981:981:User for colord:/var/lib/colord:/sbin/nologin
 +rpcuser:!!:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin
 +pulse:!!:171:171:PulseAudio System Daemon:/var/run/pulse:/sbin/nologin
 +setroubleshoot:!!:980:977::/var/lib/setroubleshoot:/sbin/nologin
 +flatpak:!!:979:976:User for flatpak system helper:/:/sbin/nologin
 +gdm:!!:42:42::/var/lib/gdm:/sbin/nologin
 +gnome-initial-setup:!!:978:975::/run/gnome-initial-setup/:/sbin/nologin
 +sshd:!!:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
 +tcpdump:!!:72:72::/:/sbin/nologin
 +trainee:$6$g0ugY2dcMmHB1AIX$/JB8OG1MD.ExKh0Tvm3.SZWAyr5w3jJLVeT9cu4sENvGcCQAnJjKWQIAEug1K5HGcNk5RGr.RGYzbJn60m/4L.:1000:1000:trainee:/home/trainee:/bin/bash
 +apache:!!:48:48:Apache:/usr/share/httpd:/sbin/nologin
 +pesign:!!:977:974:Group for the pesign signing daemon:/var/run/pesign:/sbin/nologin
 +</code>
 +
 +Lancez **john** pour craquer le fichier **mypasswd** :
 +
 +<code>
 +[root@centos8 run]# ./john mypasswd
 +Loaded 2 password hashes with 2 different salts (crypt, generic crypt(3) [?/64])
 +Press 'q' or Ctrl-C to abort, almost any other key for status
 +trainee          (trainee)
 +[q] <--------------------------------------------------------------------------------------appuyez sur la touche q
 +1g 0:00:00:27 5% 2/3 0.03650g/s 282.4p/s 282.4c/s 282.4C/s Notta1..Notused
 +Use the "--show" option to display all of the cracked passwords reliably
 +Session aborted
 +</code>
 +
 +Consultez la liste des mots de passe craqués :
 +
 +<code>
 +[root@centos8 run]# ./john --show mypasswd
 +trainee:trainee:1000:1000:trainee:/home/trainee:/bin/bash
 +
 +1 password hash cracked, 1 left
 +</code>
 +
 +====LAB #4 - Mise en place du Système de Prévention d'Intrusion Fail2Ban====
 +
 +<WRAP center round important 50%>
 +**Important** - Pour continuer, il faut travailler sur un CentOS 8 Stream. 
 +</WRAP>
 +
 +Fail2Ban est un **S**ystème de **P**révention d'**I**ntrusion. Fail2Ban lit les logs de divers services (SSH, Apache, FTP…) à la recherche d’erreurs d'authentification répétées et ajoute une règle à iptables pour bannir l'adresse IP de la source.
 +
 +===Installation===
 +
 +Installez Fail2Ban :
 +
 +<code>
 +[root@centos8 run]# cd ~
 +[root@centos8 ~]# dnf install fail2ban
 +</code>
 +
 +===Configuration===
 +
 +La configuration de Fail2Ban se trouve dans le fichier **/etc/fail2ban/jail.conf** :
 +
 +<code>
 +[root@centos8 ~]# more /etc/fail2ban/jail.conf
 +#
 +# WARNING: heavily refactored in 0.9.0 release.  Please review and
 +#          customize settings for your setup.
 +#
 +# Changes:  in most of the cases you should not modify this
 +#           file, but provide customizations in jail.local file,
 +#           or separate .conf files under jail.d/ directory, e.g.:
 +#
 +# HOW TO ACTIVATE JAILS:
 +#
 +# YOU SHOULD NOT MODIFY THIS FILE.
 +#
 +# It will probably be overwritten or improved in a distribution update.
 +#
 +# Provide customizations in a jail.local file or a jail.d/customisation.local.
 +# For example to change the default bantime for all jails and to enable the
 +# ssh-iptables jail the following (uncommented) would appear in the .local file.
 +# See man 5 jail.conf for details.
 +#
 +# [DEFAULT]
 +# bantime = 1h
 +#
 +# [sshd]
 +# enabled = true
 +#
 +# See jail.conf(5) man page for more information
 +
 +
 +
 +# Comments: use '#' for comment lines and ';' (following a space) for inline comments
 +
 +
 +[INCLUDES]
 +
 +#before = paths-distro.conf
 +before = paths-fedora.conf
 +
 +# The DEFAULT allows a global definition of the options. They can be overridden
 +# in each jail afterwards.
 +
 +[DEFAULT]
 +
 +#
 +# MISCELLANEOUS OPTIONS
 +#
 +
 +# "bantime.increment" allows to use database for searching of previously banned ip's to increase a 
 +# default ban time using special formula, default it is banTime * 1, 2, 4, 8, 16, 32...
 +#bantime.increment = true
 +
 +# "bantime.rndtime" is the max number of seconds using for mixing with random time 
 +# to prevent "clever" botnets calculate exact time IP can be unbanned again:
 +#bantime.rndtime = 
 +
 +# "bantime.maxtime" is the max number of seconds using the ban time can reach (doesn't grow further)
 +#bantime.maxtime = 
 +
 +# "bantime.factor" is a coefficient to calculate exponent growing of the formula or common multiplier,
 +--More--(6%)
 +[q]
 +</code>
 +
 +Dans ce fichier se trouvent des sections pour configurer l'action de Fail2Ban pour chaque service :
 +
 +<code>
 +...
 +[sshd]
 +
 +# To use more aggressive sshd modes set filter parameter "mode" in jail.local:
 +# normal (default), ddos, extra or aggressive (combines all).
 +# See "tests/files/logs/sshd" or "filter.d/sshd.conf" for usage example and details.
 +#mode   = normal
 +port    = ssh
 +logpath = %(sshd_log)s
 +backend = %(sshd_backend)s
 +...
 +</code> 
 +
 +Ces sections, appelées des Prisons (//Jails// en anglais), peuvent contenir des directives telles que :
 +
 +^ Directive ^ Description ^
 +| enabled | Indique si oui (true) ou non (false) le prison est activé. |
 +| port | Le port à bloquer dans iptables. |
 +| filter | Le nom du filtre, une expression régulière, associé au prison et utilisé pour trouver une activité suspect. Le nom dans ce champs, sans l'extention .conf, fait référence à un fichier dans le répertoire **/etc/fail2ban/filter.d/**. Par exemple la valeur **sshd** fait reférence au fichier **/etc/fail2ban/filter.d/sshd.conf**. |
 +| logpath | Le nom et le chemin du journal à examiner. |
 +| maxretry | Le nombre maximal de tentatives. |
 +| action | Spécifie l'action à entreprendre lors d'une corréspondance du **filter**. Le nom dans ce champs, sans l'extention .conf, fait référence à un fichier dans le répertoire **/etc/fail2ban/action.d/**. Par exemple la valeur **iptables** fait reférence au fichier **/etc/fail2ban/action.d/iptables.conf**. |
 +
 +Il n'est pas recommandé de modifier ce fichier afin de ne pas voir ses modifications écrasées lors de la prochaine mise-à-jour de Fail2Ban. Fail2Ban nous donne la possibilité de créer le fichier **/etc/fail2ban/jail.local** pour contenir nos modifications. Créez donc ce fichier avec le contenu ci-dessous :
 +
 +<code>
 +[root@centos8 ~]# vi /etc/fail2ban/jail.local
 +[root@centos8 ~]# cat /etc/fail2ban/jail.local
 +[DEFAULT]
 +ignoreip = 127.0.0.1 172.YY+20.0.3 
 +findtime = 3600
 +bantime = 86400
 +maxretry = 5
 +
 +[sshd]
 +enabled = true
 +</code>
 +
 +Il est à noter que les directives dans le fichier **jail.conf** sont surchargées par celles dans les fichiers suivantes et dans l'ordre suivant :
 +
 +  * **/etc/fail2ban/jail.d/*.conf** dans l'ordre alphabétique,
 +  * **/etc/fail2ban/jail.local**,
 +  * **/etc/fail2ban/jail.d/*.local** dans l'ordre alphabétique.
 +
 +<WRAP center round important 50%>
 +**Important** - Notez que la définition des variables dans la section **[DEFAULT]** du fichier **/etc/fail2ban/jail.local** s'appliquent à toutes les sections de prisons actives dans les fichiers **/etc/fail2ban/jail.local** et **/etc/fail2ban/jail.conf** sauf si dans la section du prison elle-même, la variable est redéfinie.
 +</WRAP>
 +
 +Dans ce fichier, les directives sont donc :
 +
 +^ Directive ^ Description ^
 +| ignoreip | Liste des adresses IP, séparées par un **espace**, qui ne sont pas concernées par l'action de Fail2Ban ou une liste d'adresses de réseaux, exprimées au format CIDR. |
 +| findtime | L'intervale de temps en secondes, avant l'heure actuelle, pendant laquelle des authentifications infructueueses sont prises en compte pour le calcul de banir l'adresse IP ou non. |
 +| bantime | La durée de vie des règles, en secondes, inscrites dans le pare-feu iptables. |
 +| maxretry | Le nombre maximal de tentatives. La règle sera donc inscrite dans le pare-feu lors de la sixième tentative. |
 +
 +==Le répertoire /etc/fail2ban==
 +
 +Le répertoire **/etc/fail2ban/** contient des fichiers et répertoires importants pour le fonctionnement de Fail2Ban :
 +
 +<code>
 +[root@centos8 ~]# ls -l /etc/fail2ban/
 +total 56
 +drwxr-xr-x. 2 root root  4096 Oct  2 16:19 action.d
 +-rw-r--r--. 1 root root  3017 Apr  1  2023 fail2ban.conf
 +drwxr-xr-x. 2 root root     6 Apr  1  2023 fail2ban.d
 +drwxr-xr-x. 3 root root  4096 Oct  2 16:19 filter.d
 +-rw-r--r--. 1 root root 25607 Apr  1  2023 jail.conf
 +drwxr-xr-x. 2 root root    31 Oct  2 16:19 jail.d
 +-rw-r--r--. 1 root root   114 Oct  2 16:26 jail.local
 +-rw-r--r--. 1 root root  2728 Apr  1  2023 paths-common.conf
 +-rw-r--r--. 1 root root   930 Apr  1  2023 paths-fedora.conf
 +</code>
 +
 +==Le fichier fail2ban.conf==
 +
 +Ce fichier définit les configurations globales de Fail2Ban, telles le **pidfile**, le **socket** et le niveau syslog de journalisation :
 +
 +<code>
 +[root@centos8 ~]# cat /etc/fail2ban/fail2ban.conf
 +# Fail2Ban main configuration file
 +#
 +# Comments: use '#' for comment lines and ';' (following a space) for inline comments
 +#
 +# Changes:  in most of the cases you should not modify this
 +#           file, but provide customizations in fail2ban.local file, e.g.:
 +#
 +# [DEFAULT]
 +# loglevel = DEBUG
 +#
 +
 +[DEFAULT]
 +
 +# Option: loglevel
 +# Notes.: Set the log level output.
 +#         CRITICAL
 +#         ERROR
 +#         WARNING
 +#         NOTICE
 +#         INFO
 +#         DEBUG
 +# Values: [ LEVEL ]  Default: INFO
 +#
 +loglevel = INFO
 +
 +# Option: logtarget
 +# Notes.: Set the log target. This could be a file, SYSTEMD-JOURNAL, SYSLOG, STDERR or STDOUT.
 +#         Only one log target can be specified.
 +#         If you change logtarget from the default value and you are
 +#         using logrotate -- also adjust or disable rotation in the
 +#         corresponding configuration file
 +#         (e.g. /etc/logrotate.d/fail2ban on Debian systems)
 +# Values: [ STDOUT | STDERR | SYSLOG | SYSOUT | SYSTEMD-JOURNAL | FILE ]  Default: STDERR
 +#
 +logtarget = /var/log/fail2ban.log
 +
 +# Option: syslogsocket
 +# Notes: Set the syslog socket file. Only used when logtarget is SYSLOG
 +#        auto uses platform.system() to determine predefined paths
 +# Values: [ auto | FILE ]  Default: auto
 +syslogsocket = auto
 +
 +# Option: socket
 +# Notes.: Set the socket file. This is used to communicate with the daemon. Do
 +#         not remove this file when Fail2ban runs. It will not be possible to
 +#         communicate with the server afterwards.
 +# Values: [ FILE ]  Default: /var/run/fail2ban/fail2ban.sock
 +#
 +socket = /var/run/fail2ban/fail2ban.sock
 +
 +# Option: pidfile
 +# Notes.: Set the PID file. This is used to store the process ID of the
 +#         fail2ban server.
 +# Values: [ FILE ]  Default: /var/run/fail2ban/fail2ban.pid
 +#
 +pidfile = /var/run/fail2ban/fail2ban.pid
 +
 +# Option: allowipv6
 +# Notes.: Allows IPv6 interface:
 +#         Default: auto
 +# Values: [ auto yes (on, true, 1) no (off, false, 0) ] Default: auto
 +#allowipv6 = auto
 +
 +# Options: dbfile
 +# Notes.: Set the file for the fail2ban persistent data to be stored.
 +#         A value of ":memory:" means database is only stored in memory 
 +#         and data is lost when fail2ban is stopped.
 +#         A value of "None" disables the database.
 +# Values: [ None :memory: FILE ] Default: /var/lib/fail2ban/fail2ban.sqlite3
 +dbfile = /var/lib/fail2ban/fail2ban.sqlite3
 +
 +# Options: dbpurgeage
 +# Notes.: Sets age at which bans should be purged from the database
 +# Values: [ SECONDS ] Default: 86400 (24hours)
 +dbpurgeage = 1d
 +
 +# Options: dbmaxmatches
 +# Notes.: Number of matches stored in database per ticket (resolvable via 
 +#         tags <ipmatches>/<ipjailmatches> in actions)
 +# Values: [ INT ] Default: 10
 +dbmaxmatches = 10
 +
 +[Definition]
 +
 +
 +[Thread]
 +
 +# Options: stacksize
 +# Notes.: Specifies the stack size (in KiB) to be used for subsequently created threads,
 +#         and must be 0 or a positive integer value of at least 32.
 +# Values: [ SIZE ] Default: 0 (use platform or configured default)
 +#stacksize = 0
 +</code>
 +
 +==Le répertoire /etc/fail2ban/filter.d/==
 +
 +Ce répertoire contient les fichiers appelés par les directives **filter** dans les sections des prisons :
 +
 +<code>
 +[root@centos8 ~]# ls -l /etc/fail2ban/filter.d/
 +total 380
 +-rw-r--r--. 1 root root  467 Apr  1  2023 3proxy.conf
 +-rw-r--r--. 1 root root 3228 Apr  1  2023 apache-auth.conf
 +-rw-r--r--. 1 root root 2831 Apr  1  2023 apache-badbots.conf
 +-rw-r--r--. 1 root root 1265 Apr  1  2023 apache-botsearch.conf
 +-rw-r--r--. 1 root root 1619 Apr  1  2023 apache-common.conf
 +-rw-r--r--. 1 root root  403 Apr  1  2023 apache-fakegooglebot.conf
 +-rw-r--r--. 1 root root  511 Apr  1  2023 apache-modsecurity.conf
 +-rw-r--r--. 1 root root  596 Apr  1  2023 apache-nohome.conf
 +-rw-r--r--. 1 root root 1246 Apr  1  2023 apache-noscript.conf
 +-rw-r--r--. 1 root root 2187 Apr  1  2023 apache-overflows.conf
 +-rw-r--r--. 1 root root  362 Apr  1  2023 apache-pass.conf
 +-rw-r--r--. 1 root root 1020 Apr  1  2023 apache-shellshock.conf
 +-rw-r--r--. 1 root root 3492 Apr  1  2023 assp.conf
 +-rw-r--r--. 1 root root 2386 Apr  1  2023 asterisk.conf
 +-rw-r--r--. 1 root root  427 Apr  1  2023 bitwarden.conf
 +-rw-r--r--. 1 root root  522 Apr  1  2023 botsearch-common.conf
 +-rw-r--r--. 1 root root  307 Apr  1  2023 centreon.conf
 +-rw-r--r--. 1 root root 2776 Apr  1  2023 common.conf
 +-rw-r--r--. 1 root root  244 Apr  1  2023 counter-strike.conf
 +-rw-r--r--. 1 root root  463 Apr  1  2023 courier-auth.conf
 +-rw-r--r--. 1 root root  512 Apr  1  2023 courier-smtp.conf
 +-rw-r--r--. 1 root root  444 Apr  1  2023 cyrus-imap.conf
 +-rw-r--r--. 1 root root  338 Apr  1  2023 directadmin.conf
 +-rw-r--r--. 1 root root 2107 Apr  1  2023 domino-smtp.conf
 +-rw-r--r--. 1 root root 2647 Apr  1  2023 dovecot.conf
 +-rw-r--r--. 1 root root 1730 Apr  1  2023 dropbear.conf
 +-rw-r--r--. 1 root root  547 Apr  1  2023 drupal-auth.conf
 +-rw-r--r--. 1 root root 1572 Apr  1  2023 ejabberd-auth.conf
 +-rw-r--r--. 1 root root  534 Apr  1  2023 exim-common.conf
 +-rw-r--r--. 1 root root 2875 Apr  1  2023 exim.conf
 +-rw-r--r--. 1 root root 2158 Apr  1  2023 exim-spam.conf
 +-rw-r--r--. 1 root root 1922 Apr  1  2023 freeswitch.conf
 +-rw-r--r--. 1 root root 1210 Apr  1  2023 froxlor-auth.conf
 +-rw-r--r--. 1 root root  236 Apr  1  2023 gitlab.conf
 +-rw-r--r--. 1 root root  388 Apr  1  2023 grafana.conf
 +-rw-r--r--. 1 root root  236 Apr  1  2023 groupoffice.conf
 +-rw-r--r--. 1 root root  322 Apr  1  2023 gssftpd.conf
 +-rw-r--r--. 1 root root 1447 Apr  1  2023 guacamole.conf
 +-rw-r--r--. 1 root root 1170 Apr  1  2023 haproxy-http-auth.conf
 +-rw-r--r--. 1 root root  404 Apr  1  2023 horde.conf
 +drwxr-xr-x. 2 root root   34 Oct  2 16:19 ignorecommands
 +-rw-r--r--. 1 root root  938 Apr  1  2023 kerio.conf
 +-rw-r--r--. 1 root root  459 Apr  1  2023 lighttpd-auth.conf
 +-rw-r--r--. 1 root root 2279 Apr  1  2023 mongodb-auth.conf
 +-rw-r--r--. 1 root root  787 Apr  1  2023 monit.conf
 +-rw-r--r--. 1 root root  640 Apr  1  2023 monitorix.conf
 +-rw-r--r--. 1 root root  441 Apr  1  2023 mssql-auth.conf
 +-rw-r--r--. 1 root root  927 Apr  1  2023 murmur.conf
 +-rw-r--r--. 1 root root  953 Apr  1  2023 mysqld-auth.conf
 +-rw-r--r--. 1 root root  400 Apr  1  2023 nagios.conf
 +-rw-r--r--. 1 root root 1600 Apr  1  2023 named-refused.conf
 +-rw-r--r--. 1 root root  474 Apr  1  2023 nginx-bad-request.conf
 +-rw-r--r--. 1 root root  740 Apr  1  2023 nginx-botsearch.conf
 +-rw-r--r--. 1 root root 1048 Apr  1  2023 nginx-http-auth.conf
 +-rw-r--r--. 1 root root 1513 Apr  1  2023 nginx-limit-req.conf
 +-rw-r--r--. 1 root root  779 Apr  1  2023 nsd.conf
 +-rw-r--r--. 1 root root  452 Apr  1  2023 openhab.conf
 +-rw-r--r--. 1 root root  495 Apr  1  2023 openwebmail.conf
 +-rw-r--r--. 1 root root 1937 Apr  1  2023 oracleims.conf
 +-rw-r--r--. 1 root root  947 Apr  1  2023 pam-generic.conf
 +-rw-r--r--. 1 root root  568 Apr  1  2023 perdition.conf
 +-rw-r--r--. 1 root root  278 Apr  1  2023 phpmyadmin-syslog.conf
 +-rw-r--r--. 1 root root  891 Apr  1  2023 php-url-fopen.conf
 +-rw-r--r--. 1 root root  242 Apr  1  2023 portsentry.conf
 +-rw-r--r--. 1 root root 3222 Apr  1  2023 postfix.conf
 +-rw-r--r--. 1 root root 1163 Apr  1  2023 proftpd.conf
 +-rw-r--r--. 1 root root 2409 Apr  1  2023 pure-ftpd.conf
 +-rw-r--r--. 1 root root  795 Apr  1  2023 qmail.conf
 +-rw-r--r--. 1 root root 1374 Apr  1  2023 recidive.conf
 +-rw-r--r--. 1 root root 1499 Apr  1  2023 roundcube-auth.conf
 +-rw-r--r--. 1 root root  354 Apr  1  2023 scanlogd.conf
 +-rw-r--r--. 1 root root  821 Apr  1  2023 screensharingd.conf
 +-rw-r--r--. 1 root root  538 Apr  1  2023 selinux-common.conf
 +-rw-r--r--. 1 root root  570 Apr  1  2023 selinux-ssh.conf
 +-rw-r--r--. 1 root root  790 Apr  1  2023 sendmail-auth.conf
 +-rw-r--r--. 1 root root 2970 Apr  1  2023 sendmail-reject.conf
 +-rw-r--r--. 1 root root  371 Apr  1  2023 sieve.conf
 +-rw-r--r--. 1 root root  706 Apr  1  2023 slapd.conf
 +-rw-r--r--. 1 root root  451 Apr  1  2023 softethervpn.conf
 +-rw-r--r--. 1 root root  722 Apr  1  2023 sogo-auth.conf
 +-rw-r--r--. 1 root root 1094 Apr  1  2023 solid-pop3d.conf
 +-rw-r--r--. 1 root root  260 Apr  1  2023 squid.conf
 +-rw-r--r--. 1 root root  191 Apr  1  2023 squirrelmail.conf
 +-rw-r--r--. 1 root root 7879 Apr  1  2023 sshd.conf
 +-rw-r--r--. 1 root root  363 Apr  1  2023 stunnel.conf
 +-rw-r--r--. 1 root root  649 Apr  1  2023 suhosin.conf
 +-rw-r--r--. 1 root root  890 Apr  1  2023 tine20.conf
 +-rw-r--r--. 1 root root 2390 Apr  1  2023 traefik-auth.conf
 +-rw-r--r--. 1 root root  374 Apr  1  2023 uwimap-auth.conf
 +-rw-r--r--. 1 root root  637 Apr  1  2023 vsftpd.conf
 +-rw-r--r--. 1 root root  444 Apr  1  2023 webmin-auth.conf
 +-rw-r--r--. 1 root root  520 Apr  1  2023 wuftpd.conf
 +-rw-r--r--. 1 root root  521 Apr  1  2023 xinetd-fail.conf
 +-rw-r--r--. 1 root root  912 Apr  1  2023 znc-adminlog.conf
 +-rw-r--r--. 1 root root 1146 Apr  1  2023 zoneminder.conf
 +</code>
 +
 +==Le répertoire /etc/fail2ban/action.d/==
 +
 +Ce répertoire contient les fichiers appelés par les directives **action** dans les sections des prisons :
 +
 +<code>
 +[root@centos8 ~]# ls -l /etc/fail2ban/action.d/
 +total 228
 +-rw-r--r--. 1 root root 3748 Apr  1  2023 abuseipdb.conf
 +-rw-r--r--. 1 root root  587 Apr  1  2023 apf.conf
 +-rw-r--r--. 1 root root 1413 Apr  1  2023 apprise.conf
 +-rw-r--r--. 1 root root 2715 Apr  1  2023 blocklist_de.conf
 +-rw-r--r--. 1 root root 3037 Apr  1  2023 cloudflare.conf
 +-rw-r--r--. 1 root root 3004 Apr  1  2023 cloudflare-token.conf
 +-rw-r--r--. 1 root root 7684 Apr  1  2023 dshield.conf
 +-rw-r--r--. 1 root root 1717 Apr  1  2023 dummy.conf
 +-rw-r--r--. 1 root root 1501 Apr  1  2023 firewallcmd-allports.conf
 +-rw-r--r--. 1 root root 2649 Apr  1  2023 firewallcmd-common.conf
 +-rw-r--r--. 1 root root 3669 Apr  1  2023 firewallcmd-ipset.conf
 +-rw-r--r--. 1 root root 1270 Apr  1  2023 firewallcmd-multiport.conf
 +-rw-r--r--. 1 root root 1898 Apr  1  2023 firewallcmd-new.conf
 +-rw-r--r--. 1 root root 1021 Apr  1  2023 firewallcmd-rich-logging.conf
 +-rw-r--r--. 1 root root 1753 Apr  1  2023 firewallcmd-rich-rules.conf
 +-rw-r--r--. 1 root root  592 Apr  1  2023 helpers-common.conf
 +-rw-r--r--. 1 root root  291 Apr  1  2023 iptables-allports.conf
 +-rw-r--r--. 1 root root 4790 Apr  1  2023 iptables.conf
 +-rw-r--r--. 1 root root 2576 Apr  1  2023 iptables-ipset.conf
 +-rw-r--r--. 1 root root 1980 Apr  1  2023 iptables-ipset-proto4.conf
 +-rw-r--r--. 1 root root  814 Apr  1  2023 iptables-ipset-proto6-allports.conf
 +-rw-r--r--. 1 root root  773 Apr  1  2023 iptables-ipset-proto6.conf
 +-rw-r--r--. 1 root root  232 Apr  1  2023 iptables-multiport.conf
 +-rw-r--r--. 1 root root 2163 Apr  1  2023 iptables-multiport-log.conf
 +-rw-r--r--. 1 root root  332 Apr  1  2023 iptables-new.conf
 +-rw-r--r--. 1 root root 2842 Apr  1  2023 iptables-xt_recent-echo.conf
 +-rw-r--r--. 1 root root 4292 Apr  1  2023 ipthreat.conf
 +-rw-r--r--. 1 root root 1051 Apr  1  2023 mail-whois-common.conf
 +-rw-r--r--. 1 root root 5321 Apr  1  2023 mynetwatchman.conf
 +-rw-r--r--. 1 root root 1493 Apr  1  2023 netscaler.conf
 +-rw-r--r--. 1 root root  383 Apr  1  2023 nftables-allports.conf
 +-rw-r--r--. 1 root root 6318 Apr  1  2023 nftables.conf
 +-rw-r--r--. 1 root root  384 Apr  1  2023 nftables-multiport.conf
 +-rw-r--r--. 1 root root 4010 Apr  1  2023 nginx-block-map.conf
 +-rw-r--r--. 1 root root 1524 Apr  1  2023 npf.conf
 +-rw-r--r--. 1 root root 3234 Apr  1  2023 nsupdate.conf
 +-rw-r--r--. 1 root root 1023 Apr  1  2023 route.conf
 +-rw-r--r--. 1 root root 2806 Apr  1  2023 sendmail-buffered.conf
 +-rw-r--r--. 1 root root 1938 Apr  1  2023 sendmail-common.conf
 +-rw-r--r--. 1 root root  829 Apr  1  2023 sendmail.conf
 +-rw-r--r--. 1 root root 1761 Apr  1  2023 sendmail-geoip-lines.conf
 +-rw-r--r--. 1 root root  950 Apr  1  2023 sendmail-whois.conf
 +-rw-r--r--. 1 root root 1055 Apr  1  2023 sendmail-whois-ipjailmatches.conf
 +-rw-r--r--. 1 root root 1036 Apr  1  2023 sendmail-whois-ipmatches.conf
 +-rw-r--r--. 1 root root 1299 Apr  1  2023 sendmail-whois-lines.conf
 +-rw-r--r--. 1 root root 1000 Apr  1  2023 sendmail-whois-matches.conf
 +-rw-r--r--. 1 root root 3521 Apr  1  2023 shorewall-ipset-proto6.conf
 +-rw-r--r--. 1 root root 6277 Apr  1  2023 smtp.py
 +-rw-r--r--. 1 root root 1503 Apr  1  2023 symbiosis-blacklist-allports.conf
 +-rw-r--r--. 1 root root 6443 Apr  1  2023 xarf-login-attack.conf
 +</code>
 +
 +===Commandes===
 +
 +Fail2Ban est constitué de deux commandes :
 +
 +<code>
 +[root@centos8 ~]# which fail2ban-client
 +/usr/bin/fail2ban-client
 +
 +[root@centos8 ~]# which fail2ban-server
 +/usr/bin/fail2ban-server
 +</code>
 +
 +L'exécutable **fail2ban-server** est responsable de l'examen des fichiers de journalisation ainsi que les commandes de blocage/déblocage. La commande fail2ban-client est utilisée pour configurer le **fail2ban-server**.
 +
 +Les options de la commande **fail2ban-server** sont :
 +
 +<code>
 +[root@centos8 ~]# fail2ban-server --help
 +Usage: fail2ban-server [OPTIONS]
 +
 +Fail2Ban v1.0.2 reads log file that contains password failure report
 +and bans the corresponding IP addresses using firewall rules.
 +
 +Options:
 +    -c, --conf <DIR>        configuration directory
 +    -s, --socket <FILE>     socket path
 +    -p, --pidfile <FILE>    pidfile path
 +    --pname <NAME>          name of the process (main thread) to identify instance (default fail2ban-server)
 +    --loglevel <LEVEL>      logging level
 +    --logtarget <TARGET>    logging target, use file-name or stdout, stderr, syslog or sysout.
 +    --syslogsocket auto|<FILE>
 +    -d                      dump configuration. For debugging
 +    --dp, --dump-pretty     dump the configuration using more human readable representation
 +    -t, --test              test configuration (can be also specified with start parameters)
 +    -i                      interactive mode
 +    -v                      increase verbosity
 +    -q                      decrease verbosity
 +    -x                      force execution of the server (remove socket file)
 +    -b                      start server in background (default)
 +    -f                      start server in foreground
 +    --async                 start server in async mode (for internal usage only, don't read configuration)
 +    --timeout               timeout to wait for the server (for internal usage only, don't read configuration)
 +    --str2sec <STRING>      convert time abbreviation format to seconds
 +    -h, --help              display this help message
 +    -V, --version           print the version (-V returns machine-readable short format)
 +
 +Report bugs to https://github.com/fail2ban/fail2ban/issues
 +</code>
 +
 +Les options de la commande **fail2ban-client** sont :
 +
 +<code>
 +[root@centos8 ~]# fail2ban-client --help
 +Usage: fail2ban-client [OPTIONS] <COMMAND>
 +
 +Fail2Ban v1.0.2 reads log file that contains password failure report
 +and bans the corresponding IP addresses using firewall rules.
 +
 +Options:
 +    -c, --conf <DIR>        configuration directory
 +    -s, --socket <FILE>     socket path
 +    -p, --pidfile <FILE>    pidfile path
 +    --pname <NAME>          name of the process (main thread) to identify instance (default fail2ban-server)
 +    --loglevel <LEVEL>      logging level
 +    --logtarget <TARGET>    logging target, use file-name or stdout, stderr, syslog or sysout.
 +    --syslogsocket auto|<FILE>
 +    -d                      dump configuration. For debugging
 +    --dp, --dump-pretty     dump the configuration using more human readable representation
 +    -t, --test              test configuration (can be also specified with start parameters)
 +    -i                      interactive mode
 +    -v                      increase verbosity
 +    -q                      decrease verbosity
 +    -x                      force execution of the server (remove socket file)
 +    -b                      start server in background (default)
 +    -f                      start server in foreground
 +    --async                 start server in async mode (for internal usage only, don't read configuration)
 +    --timeout               timeout to wait for the server (for internal usage only, don't read configuration)
 +    --str2sec <STRING>      convert time abbreviation format to seconds
 +    -h, --help              display this help message
 +    -V, --version           print the version (-V returns machine-readable short format)
 +
 +Command:
 +                                             BASIC
 +    start                                    starts the server and the jails
 +    restart                                  restarts the server
 +    restart [--unban] [--if-exists] <JAIL>   restarts the jail <JAIL> (alias
 +                                             for 'reload --restart ... <JAIL>')
 +    reload [--restart] [--unban] [--all]     reloads the configuration without
 +                                             restarting of the server, the
 +                                             option '--restart' activates
 +                                             completely restarting of affected
 +                                             jails, thereby can unban IP
 +                                             addresses (if option '--unban'
 +                                             specified)
 +    reload [--restart] [--unban] [--if-exists] <JAIL>
 +                                             reloads the jail <JAIL>, or
 +                                             restarts it (if option '--restart'
 +                                             specified)
 +    stop                                     stops all jails and terminate the
 +                                             server
 +    unban --all                              unbans all IP addresses (in all
 +                                             jails and database)
 +    unban <IP> ... <IP>                      unbans <IP> (in all jails and
 +                                             database)
 +    banned                                   return jails with banned IPs as
 +                                             dictionary
 +    banned <IP> ... <IP>                   return list(s) of jails where
 +                                             given IP(s) are banned
 +    status                                   gets the current status of the
 +                                             server
 +    ping                                     tests if the server is alive
 +    echo                                     for internal usage, returns back
 +                                             and outputs a given string
 +    help                                     return this output
 +    version                                  return the server version
 +
 +                                             LOGGING
 +    set loglevel <LEVEL>                     sets logging level to <LEVEL>.
 +                                             Levels: CRITICAL, ERROR, WARNING,
 +                                             NOTICE, INFO, DEBUG, TRACEDEBUG,
 +                                             HEAVYDEBUG or corresponding
 +                                             numeric value (50-5)
 +    get loglevel                             gets the logging level
 +    set logtarget <TARGET>                   sets logging target to <TARGET>.
 +                                             Can be STDOUT, STDERR, SYSLOG,
 +                                             SYSTEMD-JOURNAL or a file
 +    get logtarget                            gets logging target
 +    set syslogsocket auto|<SOCKET>           sets the syslog socket path to
 +                                             auto or <SOCKET>. Only used if
 +                                             logtarget is SYSLOG
 +    get syslogsocket                         gets syslog socket path
 +    flushlogs                                flushes the logtarget if a file
 +                                             and reopens it. For log rotation.
 +
 +                                             DATABASE
 +    set dbfile <FILE>                        set the location of fail2ban
 +                                             persistent datastore. Set to
 +                                             "None" to disable
 +    get dbfile                               get the location of fail2ban
 +                                             persistent datastore
 +    set dbmaxmatches <INT>                   sets the max number of matches
 +                                             stored in database per ticket
 +    get dbmaxmatches                         gets the max number of matches
 +                                             stored in database per ticket
 +    set dbpurgeage <SECONDS>                 sets the max age in <SECONDS> that
 +                                             history of bans will be kept
 +    get dbpurgeage                           gets the max age in seconds that
 +                                             history of bans will be kept
 +
 +                                             JAIL CONTROL
 +    add <JAIL> <BACKEND>                     creates <JAIL> using <BACKEND>
 +    start <JAIL>                             starts the jail <JAIL>
 +    stop <JAIL>                              stops the jail <JAIL>. The jail is
 +                                             removed
 +    status <JAIL> [FLAVOR]                   gets the current status of <JAIL>,
 +                                             with optional flavor or extended
 +                                             info
 +
 +                                             JAIL CONFIGURATION
 +    set <JAIL> idle on|off                   sets the idle state of <JAIL>
 +    set <JAIL> ignoreself true|false         allows the ignoring of own IP
 +                                             addresses
 +    set <JAIL> addignoreip <IP>              adds <IP> to the ignore list of
 +                                             <JAIL>
 +    set <JAIL> delignoreip <IP>              removes <IP> from the ignore list
 +                                             of <JAIL>
 +    set <JAIL> ignorecommand <VALUE>         sets ignorecommand of <JAIL>
 +    set <JAIL> ignorecache <VALUE>           sets ignorecache of <JAIL>
 +    set <JAIL> addlogpath <FILE> ['tail'   adds <FILE> to the monitoring list
 +                                             of <JAIL>, optionally starting at
 +                                             the 'tail' of the file (default
 +                                             'head').
 +    set <JAIL> dellogpath <FILE>             removes <FILE> from the monitoring
 +                                             list of <JAIL>
 +    set <JAIL> logencoding <ENCODING>        sets the <ENCODING> of the log
 +                                             files for <JAIL>
 +    set <JAIL> addjournalmatch <MATCH>       adds <MATCH> to the journal filter
 +                                             of <JAIL>
 +    set <JAIL> deljournalmatch <MATCH>       removes <MATCH> from the journal
 +                                             filter of <JAIL>
 +    set <JAIL> addfailregex <REGEX>          adds the regular expression
 +                                             <REGEX> which must match failures
 +                                             for <JAIL>
 +    set <JAIL> delfailregex <INDEX>          removes the regular expression at
 +                                             <INDEX> for failregex
 +    set <JAIL> addignoreregex <REGEX>        adds the regular expression
 +                                             <REGEX> which should match pattern
 +                                             to exclude for <JAIL>
 +    set <JAIL> delignoreregex <INDEX>        removes the regular expression at
 +                                             <INDEX> for ignoreregex
 +    set <JAIL> findtime <TIME>               sets the number of seconds <TIME>
 +                                             for which the filter will look
 +                                             back for <JAIL>
 +    set <JAIL> bantime <TIME>                sets the number of seconds <TIME>
 +                                             a host will be banned for <JAIL>
 +    set <JAIL> datepattern <PATTERN>         sets the <PATTERN> used to match
 +                                             date/times for <JAIL>
 +    set <JAIL> usedns <VALUE>                sets the usedns mode for <JAIL>
 +    set <JAIL> attempt <IP> [<failure1> ... <failureN>]
 +                                             manually notify about <IP> failure
 +    set <JAIL> banip <IP> ... <IP>           manually Ban <IP> for <JAIL>
 +    set <JAIL> unbanip [--report-absent] <IP> ... <IP>
 +                                             manually Unban <IP> in <JAIL>
 +    set <JAIL> maxretry <RETRY>              sets the number of failures
 +                                             <RETRY> before banning the host
 +                                             for <JAIL>
 +    set <JAIL> maxmatches <INT>              sets the max number of matches
 +                                             stored in memory per ticket in
 +                                             <JAIL>
 +    set <JAIL> maxlines <LINES>              sets the number of <LINES> to
 +                                             buffer for regex search for <JAIL>
 +    set <JAIL> addaction <ACT>[ <PYTHONFILE> <JSONKWARGS>]
 +                                             adds a new action named <ACT> for
 +                                             <JAIL>. Optionally for a Python
 +                                             based action, a <PYTHONFILE> and
 +                                             <JSONKWARGS> can be specified,
 +                                             else will be a Command Action
 +    set <JAIL> delaction <ACT>               removes the action <ACT> from
 +                                             <JAIL>
 +
 +                                             COMMAND ACTION CONFIGURATION
 +    set <JAIL> action <ACT> actionstart <CMD>
 +                                             sets the start command <CMD> of
 +                                             the action <ACT> for <JAIL>
 +    set <JAIL> action <ACT> actionstop <CMD> sets the stop command <CMD> of the
 +                                             action <ACT> for <JAIL>
 +    set <JAIL> action <ACT> actioncheck <CMD>
 +                                             sets the check command <CMD> of
 +                                             the action <ACT> for <JAIL>
 +    set <JAIL> action <ACT> actionban <CMD>  sets the ban command <CMD> of the
 +                                             action <ACT> for <JAIL>
 +    set <JAIL> action <ACT> actionunban <CMD>
 +                                             sets the unban command <CMD> of
 +                                             the action <ACT> for <JAIL>
 +    set <JAIL> action <ACT> timeout <TIMEOUT>
 +                                             sets <TIMEOUT> as the command
 +                                             timeout in seconds for the action
 +                                             <ACT> for <JAIL>
 +
 +                                             GENERAL ACTION CONFIGURATION
 +    set <JAIL> action <ACT> <PROPERTY> <VALUE>
 +                                             sets the <VALUE> of <PROPERTY> for
 +                                             the action <ACT> for <JAIL>
 +    set <JAIL> action <ACT> <METHOD>[ <JSONKWARGS>]
 +                                             calls the <METHOD> with
 +                                             <JSONKWARGS> for the action <ACT>
 +                                             for <JAIL>
 +
 +                                             JAIL INFORMATION
 +    get <JAIL> banned                        return banned IPs of <JAIL>
 +    get <JAIL> banned <IP> ... <IP>        return 1 if IP is banned in <JAIL>
 +                                             otherwise 0, or a list of 1/0 for
 +                                             multiple IPs
 +    get <JAIL> logpath                       gets the list of the monitored
 +                                             files for <JAIL>
 +    get <JAIL> logencoding                   gets the encoding of the log files
 +                                             for <JAIL>
 +    get <JAIL> journalmatch                  gets the journal filter match for
 +                                             <JAIL>
 +    get <JAIL> ignoreself                    gets the current value of the
 +                                             ignoring the own IP addresses
 +    get <JAIL> ignoreip                      gets the list of ignored IP
 +                                             addresses for <JAIL>
 +    get <JAIL> ignorecommand                 gets ignorecommand of <JAIL>
 +    get <JAIL> failregex                     gets the list of regular
 +                                             expressions which matches the
 +                                             failures for <JAIL>
 +    get <JAIL> ignoreregex                   gets the list of regular
 +                                             expressions which matches patterns
 +                                             to ignore for <JAIL>
 +    get <JAIL> findtime                      gets the time for which the filter
 +                                             will look back for failures for
 +                                             <JAIL>
 +    get <JAIL> bantime                       gets the time a host is banned for
 +                                             <JAIL>
 +    get <JAIL> datepattern                   gets the pattern used to match
 +                                             date/times for <JAIL>
 +    get <JAIL> usedns                        gets the usedns setting for <JAIL>
 +    get <JAIL> banip [<SEP>|--with-time]     gets the list of of banned IP
 +                                             addresses for <JAIL>. Optionally
 +                                             the separator character ('<SEP>',
 +                                             default is space) or the option '
 +                                             --with-time' (printing the times
 +                                             of ban) may be specified. The IPs
 +                                             are ordered by end of ban.
 +    get <JAIL> maxretry                      gets the number of failures
 +                                             allowed for <JAIL>
 +    get <JAIL> maxmatches                    gets the max number of matches
 +                                             stored in memory per ticket in
 +                                             <JAIL>
 +    get <JAIL> maxlines                      gets the number of lines to buffer
 +                                             for <JAIL>
 +    get <JAIL> actions                       gets a list of actions for <JAIL>
 +
 +                                             COMMAND ACTION INFORMATION
 +    get <JAIL> action <ACT> actionstart      gets the start command for the
 +                                             action <ACT> for <JAIL>
 +    get <JAIL> action <ACT> actionstop       gets the stop command for the
 +                                             action <ACT> for <JAIL>
 +    get <JAIL> action <ACT> actioncheck      gets the check command for the
 +                                             action <ACT> for <JAIL>
 +    get <JAIL> action <ACT> actionban        gets the ban command for the
 +                                             action <ACT> for <JAIL>
 +    get <JAIL> action <ACT> actionunban      gets the unban command for the
 +                                             action <ACT> for <JAIL>
 +    get <JAIL> action <ACT> timeout          gets the command timeout in
 +                                             seconds for the action <ACT> for
 +                                             <JAIL>
 +
 +                                             GENERAL ACTION INFORMATION
 +    get <JAIL> actionproperties <ACT>        gets a list of properties for the
 +                                             action <ACT> for <JAIL>
 +    get <JAIL> actionmethods <ACT>           gets a list of methods for the
 +                                             action <ACT> for <JAIL>
 +    get <JAIL> action <ACT> <PROPERTY>       gets the value of <PROPERTY> for
 +                                             the action <ACT> for <JAIL>
 +
 +Report bugs to https://github.com/fail2ban/fail2ban/issues
 +</code>
 +
 +==Activer et Démarrer le Serveur==
 +
 +Pour prendre en compte la configuration dans le fichier **/etc/fail2ban/jail.local**, activez et démarrez le server :
 +
 +<code>
 +[root@centos8 ~]# systemctl status fail2ban
 +● fail2ban.service - Fail2Ban Service
 +   Loaded: loaded (/usr/lib/systemd/system/fail2ban.service; disabled; vendor preset: disabled)
 +   Active: inactive (dead)
 +     Docs: man:fail2ban(1)
 +
 +[root@centos8 ~]# systemctl enable fail2ban
 +Created symlink /etc/systemd/system/multi-user.target.wants/fail2ban.service → /usr/lib/systemd/system/fail2ban.service.
 +
 +[root@centos8 ~]# systemctl start fail2ban
 +
 +[root@centos8 ~]# systemctl status fail2ban
 +● fail2ban.service - Fail2Ban Service
 +   Loaded: loaded (/usr/lib/systemd/system/fail2ban.service; enabled; vendor preset: disabled)
 +   Active: active (running) since Wed 2024-10-02 16:31:33 CEST; 16s ago
 +     Docs: man:fail2ban(1)
 +  Process: 8319 ExecStartPre=/bin/mkdir -p /run/fail2ban (code=exited, status=0/SUCCESS)
 + Main PID: 8321 (fail2ban-server)
 +    Tasks: 5 (limit: 100483)
 +   Memory: 12.7M
 +   CGroup: /system.slice/fail2ban.service
 +           └─8321 /usr/bin/python3.6 -s /usr/bin/fail2ban-server -xf start
 +
 +Oct 02 16:31:33 centos8.ittraining.loc systemd[1]: Starting Fail2Ban Service...
 +Oct 02 16:31:33 centos8.ittraining.loc systemd[1]: Started Fail2Ban Service.
 +Oct 02 16:31:34 centos8.ittraining.loc fail2ban-server[8321]: Server ready
 +
 +[root@centos8 ~]# ps aux | grep fail2ban-server
 +root        8321  0.5  0.1 512900 24400 ?        Ssl  16:31   0:00 /usr/bin/python3.6 -s /usr/bin/fail2ban-server -xf start
 +root        8341  0.0  0.0  12216  1048 pts/0    S+   16:32   0:00 grep --color=auto fail2ban-server
 +</code>
 +
 +==Utiliser la Commande Fail2Ban-server==
 +
 +Pour connaître le status de Fail2Ban-server, saisissez la commande suivante :
 +
 +<code>
 +[root@centos8 ~]# fail2ban-client status
 +Status
 +|- Number of jail:      1
 +`- Jail list:   sshd
 +</code>
 +
 +Il est aussi possible de se renseigner sur le statut d'un prison particulier :
 +
 +<code>
 +[root@centos8 ~]# fail2ban-client status sshd
 +Status for the jail: sshd
 +|- Filter
 +|  |- Currently failed: 0
 +|  |- Total failed:     0
 +|  `- Journal matches:  _SYSTEMD_UNIT=sshd.service + _COMM=sshd
 +`- Actions
 +   |- Currently banned: 0
 +   |- Total banned:     0
 +   `- Banned IP list:
 +</code>
 +
 +La commande **fail2ban-client** peut être utilisée pour contrôler un prison :
 +
 +<code>
 +[root@centos8 ~]# fail2ban-client stop sshd
 +Jail stopped
 +
 +[root@centos8 ~]# fail2ban-client status sshd
 +2024-10-02 16:33:54,336 fail2ban                [8353]: ERROR   NOK: ('sshd',)
 +Sorry but the jail 'sshd' does not exist
 +
 +[root@centos8 ~]# fail2ban-client reload
 +OK
 +
 +[root@centos8 ~]# fail2ban-client status sshd
 +Status for the jail: sshd
 +|- Filter
 +|  |- Currently failed: 0
 +|  |- Total failed:     0
 +|  `- Journal matches:  _SYSTEMD_UNIT=sshd.service + _COMM=sshd
 +`- Actions
 +   |- Currently banned: 0
 +   |- Total banned:     0
 +   `- Banned IP list:
 +</code>
 +
 +==Ajouter un Prison==
 +
 +Modifiez maintenant votre fichier **/etc/fail2ban/jail.local** :
 +
 +<code>
 +[root@centos8 ~]# vi /etc/fail2ban/jail.local
 +[root@centos8 ~]# cat /etc/fail2ban/jail.local
 +[DEFAULT]
 +ignoreip = 127.0.0.1 10.0.2.15 
 +findtime = 3600
 +bantime = 86400
 +maxretry = 5
 +
 +[sshd]
 +enabled = true
 +
 +[apache-auth]
 +enabled = true
 +</code>
 +
 +Appliquez la nouvelle configuration et constatez le résultat :
 +
 +<code>
 +[root@centos8 ~]# fail2ban-client reload
 +OK
 +
 +[root@centos8 ~]# fail2ban-client status
 +Status
 +|- Number of jail:      2
 +`- Jail list:   apache-auth, sshd
 +</code>
 +
 +=====Balayage des Ports=====
 +
 +====LAB #5 - Utilisation de nmap et de netcat====
 +
 +=== nmap ===
 +
 +==Installation==
 +
 +Sous RHEL/CentOS 8, **nmap** n'est pas installé par défaut :
 +
 +<code>
 +[root@centos8 ~]# which nmap
 +/usr/bin/which: no nmap in (/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin)
 +</code>
 +
 +Installez donc nmap en utilisant yum :
 +
 +<code>
 +[root@centos8 ~]# dnf install nmap
 +</code>
 +
 +==Options de la commande==
 +
 +Les options de cette commande sont :
 +
 +<code>
 +[root@centos8 ~]# nmap --help
 +Nmap 7.92 ( https://nmap.org )
 +Usage: nmap [Scan Type(s)] [Options] {target specification}
 +TARGET SPECIFICATION:
 +  Can pass hostnames, IP addresses, networks, etc.
 +  Ex: scanme.nmap.org, microsoft.com/24, 192.168.0.1; 10.0.0-255.1-254
 +  -iL <inputfilename>: Input from list of hosts/networks
 +  -iR <num hosts>: Choose random targets
 +  --exclude <host1[,host2][,host3],...>: Exclude hosts/networks
 +  --excludefile <exclude_file>: Exclude list from file
 +HOST DISCOVERY:
 +  -sL: List Scan - simply list targets to scan
 +  -sn: Ping Scan - disable port scan
 +  -Pn: Treat all hosts as online -- skip host discovery
 +  -PS/PA/PU/PY[portlist]: TCP SYN/ACK, UDP or SCTP discovery to given ports
 +  -PE/PP/PM: ICMP echo, timestamp, and netmask request discovery probes
 +  -PO[protocol list]: IP Protocol Ping
 +  -n/-R: Never do DNS resolution/Always resolve [default: sometimes]
 +  --dns-servers <serv1[,serv2],...>: Specify custom DNS servers
 +  --system-dns: Use OS's DNS resolver
 +  --traceroute: Trace hop path to each host
 +SCAN TECHNIQUES:
 +  -sS/sT/sA/sW/sM: TCP SYN/Connect()/ACK/Window/Maimon scans
 +  -sU: UDP Scan
 +  -sN/sF/sX: TCP Null, FIN, and Xmas scans
 +  --scanflags <flags>: Customize TCP scan flags
 +  -sI <zombie host[:probeport]>: Idle scan
 +  -sY/sZ: SCTP INIT/COOKIE-ECHO scans
 +  -sO: IP protocol scan
 +  -b <FTP relay host>: FTP bounce scan
 +PORT SPECIFICATION AND SCAN ORDER:
 +  -p <port ranges>: Only scan specified ports
 +    Ex: -p22; -p1-65535; -p U:53,111,137,T:21-25,80,139,8080,S:9
 +  --exclude-ports <port ranges>: Exclude the specified ports from scanning
 +  -F: Fast mode - Scan fewer ports than the default scan
 +  -r: Scan ports consecutively - don't randomize
 +  --top-ports <number>: Scan <number> most common ports
 +  --port-ratio <ratio>: Scan ports more common than <ratio>
 +SERVICE/VERSION DETECTION:
 +  -sV: Probe open ports to determine service/version info
 +  --version-intensity <level>: Set from 0 (light) to 9 (try all probes)
 +  --version-light: Limit to most likely probes (intensity 2)
 +  --version-all: Try every single probe (intensity 9)
 +  --version-trace: Show detailed version scan activity (for debugging)
 +SCRIPT SCAN:
 +  -sC: equivalent to --script=default
 +  --script=<Lua scripts>: <Lua scripts> is a comma separated list of
 +           directories, script-files or script-categories
 +  --script-args=<n1=v1,[n2=v2,...]>: provide arguments to scripts
 +  --script-args-file=filename: provide NSE script args in a file
 +  --script-trace: Show all data sent and received
 +  --script-updatedb: Update the script database.
 +  --script-help=<Lua scripts>: Show help about scripts.
 +           <Lua scripts> is a comma-separated list of script-files or
 +           script-categories.
 +OS DETECTION:
 +  -O: Enable OS detection
 +  --osscan-limit: Limit OS detection to promising targets
 +  --osscan-guess: Guess OS more aggressively
 +TIMING AND PERFORMANCE:
 +  Options which take <time> are in seconds, or append 'ms' (milliseconds),
 +  's' (seconds), 'm' (minutes), or 'h' (hours) to the value (e.g. 30m).
 +  -T<0-5>: Set timing template (higher is faster)
 +  --min-hostgroup/max-hostgroup <size>: Parallel host scan group sizes
 +  --min-parallelism/max-parallelism <numprobes>: Probe parallelization
 +  --min-rtt-timeout/max-rtt-timeout/initial-rtt-timeout <time>: Specifies
 +      probe round trip time.
 +  --max-retries <tries>: Caps number of port scan probe retransmissions.
 +  --host-timeout <time>: Give up on target after this long
 +  --scan-delay/--max-scan-delay <time>: Adjust delay between probes
 +  --min-rate <number>: Send packets no slower than <number> per second
 +  --max-rate <number>: Send packets no faster than <number> per second
 +FIREWALL/IDS EVASION AND SPOOFING:
 +  -f; --mtu <val>: fragment packets (optionally w/given MTU)
 +  -D <decoy1,decoy2[,ME],...>: Cloak a scan with decoys
 +  -S <IP_Address>: Spoof source address
 +  -e <iface>: Use specified interface
 +  -g/--source-port <portnum>: Use given port number
 +  --proxies <url1,[url2],...>: Relay connections through HTTP/SOCKS4 proxies
 +  --data <hex string>: Append a custom payload to sent packets
 +  --data-string <string>: Append a custom ASCII string to sent packets
 +  --data-length <num>: Append random data to sent packets
 +  --ip-options <options>: Send packets with specified ip options
 +  --ttl <val>: Set IP time-to-live field
 +  --spoof-mac <mac address/prefix/vendor name>: Spoof your MAC address
 +  --badsum: Send packets with a bogus TCP/UDP/SCTP checksum
 +OUTPUT:
 +  -oN/-oX/-oS/-oG <file>: Output scan in normal, XML, s|<rIpt kIddi3,
 +     and Grepable format, respectively, to the given filename.
 +  -oA <basename>: Output in the three major formats at once
 +  -v: Increase verbosity level (use -vv or more for greater effect)
 +  -d: Increase debugging level (use -dd or more for greater effect)
 +  --reason: Display the reason a port is in a particular state
 +  --open: Only show open (or possibly open) ports
 +  --packet-trace: Show all packets sent and received
 +  --iflist: Print host interfaces and routes (for debugging)
 +  --append-output: Append to rather than clobber specified output files
 +  --resume <filename>: Resume an aborted scan
 +  --noninteractive: Disable runtime interactions via keyboard
 +  --stylesheet <path/URL>: XSL stylesheet to transform XML output to HTML
 +  --webxml: Reference stylesheet from Nmap.Org for more portable XML
 +  --no-stylesheet: Prevent associating of XSL stylesheet w/XML output
 +MISC:
 +  -6: Enable IPv6 scanning
 +  -A: Enable OS detection, version detection, script scanning, and traceroute
 +  --datadir <dirname>: Specify custom Nmap data file location
 +  --send-eth/--send-ip: Send using raw ethernet frames or IP packets
 +  --privileged: Assume that the user is fully privileged
 +  --unprivileged: Assume the user lacks raw socket privileges
 +  -V: Print version number
 +  -h: Print this help summary page.
 +EXAMPLES:
 +  nmap -v -A scanme.nmap.org
 +  nmap -v -sn 192.168.0.0/16 10.0.0.0/8
 +  nmap -v -iR 10000 -Pn -p 80
 +SEE THE MAN PAGE (https://nmap.org/book/man.html) FOR MORE OPTIONS AND EXAMPLES
 +</code>
 +
 +==Utilisation==
 +
 +Pour connaître la liste des ports ouverts sur votre machine virtuelle, saisissez la commande suivante :
 +
 +<code>
 +[root@centos8 ~]# nmap 127.0.0.1
 +Starting Nmap 7.92 ( https://nmap.org ) at 2024-10-02 16:58 CEST
 +Nmap scan report for localhost (127.0.0.1)
 +Host is up (0.000011s latency).
 +Not shown: 996 closed tcp ports (reset)
 +PORT    STATE SERVICE
 +22/tcp  open  ssh
 +80/tcp  open  http
 +111/tcp open  rpcbind
 +631/tcp open  ipp
 +
 +Nmap done: 1 IP address (1 host up) scanned in 0.17 seconds
 +</code>
 +
 +<WRAP center round important 50%>
 +**Important** - Pour connaître les ports ouverts sur une machine distante, la procédure est identique sauf que vous devez utiliser l'adresse IP de votre cible.
 +</WRAP>
 +
 +==Fichiers de Configuration==
 +
 +**nmap** utilise un fichier spécifique pour identifier les ports. Ce fichier est **/usr/share/nmap/nmap-services**:
 +
 +<code>
 +[root@centos8 ~]# more /usr/share/nmap/nmap-services
 +# THIS FILE IS GENERATED AUTOMATICALLY FROM A MASTER - DO NOT EDIT.
 +# EDIT /nmap-private-dev/nmap-services-all IN SVN INSTEAD.
 +# Well known service port numbers -*- mode: fundamental; -*-
 +# From the Nmap Security Scanner ( https://nmap.org/ )
 +#
 +# $Id: nmap-services 38272 2021-08-06 18:05:30Z dmiller $
 +#
 +# Derived from IANA data and our own research
 +#
 +# This collection of service data is (C) 1996-2020 by Insecure.Com
 +# LLC.  It is distributed under the Nmap Public Source license as
 +# provided in the LICENSE file of the source distribution or at
 +# https://svn.nmap.org/nmap/LICENSE .  Note that this license
 +# requires you to license your own work under a compatable open source
 +# license.  If you wish to embed Nmap technology into proprietary
 +# software, we sell alternative licenses (contact sales@insecure.com).
 +# Dozens of software vendors already license Nmap technology such as
 +# host discovery, port scanning, OS detection, and version detection.
 +# For more details, see https://nmap.org/book/man-legal.html
 +#
 +# Fields in this file are: Service name, portnum/protocol, open-frequency, optional comments
 +#
 +tcpmux  1/tcp   0.001995        # TCP Port Service Multiplexer [rfc-1078] | TCP Port Service Multiplexer
 +tcpmux  1/udp   0.001236        # TCP Port Service Multiplexer
 +compressnet     2/tcp   0.000013        # Management Utility
 +compressnet     2/udp   0.001845        # Management Utility
 +compressnet     3/tcp   0.001242        # Compression Process
 +compressnet     3/udp   0.001532        # Compression Process
 +unknown 4/tcp   0.000477
 +rje     5/tcp   0.000000        # Remote Job Entry
 +rje     5/udp   0.000593        # Remote Job Entry
 +unknown 6/tcp   0.000502
 +echo    7/sctp  0.000000
 +echo    7/tcp   0.004855
 +echo    7/udp   0.024679
 +unknown 8/tcp   0.000013
 +discard 9/sctp  0.000000        # sink null
 +discard 9/tcp   0.003764        # sink null
 +discard 9/udp   0.015733        # sink null
 +unknown 10/tcp  0.000063
 +systat  11/tcp  0.000075        # Active Users
 +systat  11/udp  0.000577        # Active Users
 +unknown 12/tcp  0.000063
 +daytime 13/tcp  0.003927
 +daytime 13/udp  0.004827
 +unknown 14/tcp  0.000038
 +netstat 15/tcp  0.000038
 +unknown 16/tcp  0.000050
 +qotd    17/tcp  0.002346        # Quote of the Day
 +qotd    17/udp  0.009209        # Quote of the Day
 +msp     18/tcp  0.000000        # Message Send Protocol | Message Send Protocol (historic)
 +msp     18/udp  0.000610        # Message Send Protocol
 +chargen 19/tcp  0.002559        # ttytst source Character Generator | Character Generator
 +chargen 19/udp  0.015865        # ttytst source Character Generator
 +ftp-data        20/sctp 0.000000        # File Transfer [Default Data] | FTP
 +--More--(0%)
 +[q]
 +</code>
 +
 +Le répertoire **/usr/share/nmap** contient d'autres fichiers importants :
 +
 +<code>
 +[root@centos8 ~]# ls -l /usr/share/nmap
 +total 9312
 +-rw-r--r--. 1 root root   10834 Mar 22  2023 nmap.dtd
 +-rw-r--r--. 1 root root  767503 Mar 22  2023 nmap-mac-prefixes
 +-rw-r--r--. 1 root root 5033049 Mar 22  2023 nmap-os-db
 +-rw-r--r--. 1 root root   21253 Mar 22  2023 nmap-payloads
 +-rw-r--r--. 1 root root    6756 Mar 22  2023 nmap-protocols
 +-rw-r--r--. 1 root root   43755 Mar 22  2023 nmap-rpc
 +-rw-r--r--. 1 root root 2498555 Mar 22  2023 nmap-service-probes
 +-rw-r--r--. 1 root root 1002889 Mar 22  2023 nmap-services
 +-rw-r--r--. 1 root root   31936 Mar 22  2023 nmap.xsl
 +drwxr-xr-x. 3 root root    8192 Oct  2 16:57 nselib
 +-rw-r--r--. 1 root root   48627 Mar 22  2023 nse_main.lua
 +drwxr-xr-x. 2 root root   28672 Oct  2 16:57 scripts
 +</code>
 +
 +Voici la liste des fichiers les plus importants :
 +
 +^ Fichier ^ Description ^
 +| /usr/share/nmap/nmap-protocols | Contient la liste des protocols reconnus par **nmap**. |
 +| /usr/share/nmap/nmap-service-probes | Contient les règles de balayage utilisées par **nmap** pour identifier le service actif sur un port donné. |
 +| /usr/share/nmap/nmap-mac-prefixes | Contient une liste de préfix d'adresses MAC par fabricant reconnu par **nmap**. |
 +| /usr/share/nmap/nmap-rpc | Contient une liste des services RPC reconnus par **nmap**. |
 +
 +==Scripts==
 +
 +**nmap** utilise des scripts pour accomplir certaines tâches allant de la découverte simple de ports ouverts jusqu'à l'intrusion :
 +
 +<code>
 +[root@centos8 ~]# ls /usr/share/nmap/scripts/
 +acarsd-info.nse                       fcrdns.nse                              https-redirect.nse               ms-sql-info.nse                 smb-flood.nse
 +address-info.nse                      finger.nse                              http-stored-xss.nse              ms-sql-ntlm-info.nse            smb-ls.nse
 +afp-brute.nse                         fingerprint-strings.nse                 http-svn-enum.nse                ms-sql-query.nse                smb-mbenum.nse
 +afp-ls.nse                            firewalk.nse                            http-svn-info.nse                ms-sql-tables.nse               smb-os-discovery.nse
 +afp-path-vuln.nse                     firewall-bypass.nse                     http-title.nse                   ms-sql-xp-cmdshell.nse          smb-print-text.nse
 +afp-serverinfo.nse                    flume-master-info.nse                   http-tplink-dir-traversal.nse    mtrace.nse                      smb-protocols.nse
 +afp-showmount.nse                     fox-info.nse                            http-trace.nse                   murmur-version.nse              smb-psexec.nse
 +ajp-auth.nse                          freelancer-info.nse                     http-traceroute.nse              mysql-audit.nse                 smb-security-mode.nse
 +ajp-brute.nse                         ftp-anon.nse                            http-trane-info.nse              mysql-brute.nse                 smb-server-stats.nse
 +ajp-headers.nse                       ftp-bounce.nse                          http-unsafe-output-escaping.nse  mysql-databases.nse             smb-system-info.nse
 +ajp-methods.nse                       ftp-brute.nse                           http-useragent-tester.nse        mysql-dump-hashes.nse           smb-vuln-conficker.nse
 +ajp-request.nse                       ftp-libopie.nse                         http-userdir-enum.nse            mysql-empty-password.nse        smb-vuln-cve2009-3103.nse
 +allseeingeye-info.nse                 ftp-proftpd-backdoor.nse                http-vhosts.nse                  mysql-enum.nse                  smb-vuln-cve-2017-7494.nse
 +amqp-info.nse                         ftp-syst.nse                            http-virustotal.nse              mysql-info.nse                  smb-vuln-ms06-025.nse
 +asn-query.nse                         ftp-vsftpd-backdoor.nse                 http-vlcstreamer-ls.nse          mysql-query.nse                 smb-vuln-ms07-029.nse
 +auth-owners.nse                       ftp-vuln-cve2010-4221.nse               http-vmware-path-vuln.nse        mysql-users.nse                 smb-vuln-ms08-067.nse
 +auth-spoof.nse                        ganglia-info.nse                        http-vuln-cve2006-3392.nse       mysql-variables.nse             smb-vuln-ms10-054.nse
 +backorifice-brute.nse                 giop-info.nse                           http-vuln-cve2009-3960.nse       mysql-vuln-cve2012-2122.nse     smb-vuln-ms10-061.nse
 +backorifice-info.nse                  gkrellm-info.nse                        http-vuln-cve2010-0738.nse       nat-pmp-info.nse                smb-vuln-ms17-010.nse
 +bacnet-info.nse                       gopher-ls.nse                           http-vuln-cve2010-2861.nse       nat-pmp-mapport.nse             smb-vuln-regsvc-dos.nse
 +banner.nse                            gpsd-info.nse                           http-vuln-cve2011-3192.nse       nbd-info.nse                    smb-vuln-webexec.nse
 +bitcoin-getaddr.nse                   hadoop-datanode-info.nse                http-vuln-cve2011-3368.nse       nbns-interfaces.nse             smb-webexec-exploit.nse
 +bitcoin-info.nse                      hadoop-jobtracker-info.nse              http-vuln-cve2012-1823.nse       nbstat.nse                      smtp-brute.nse
 +bitcoinrpc-info.nse                   hadoop-namenode-info.nse                http-vuln-cve2013-0156.nse       ncp-enum-users.nse              smtp-commands.nse
 +bittorrent-discovery.nse              hadoop-secondary-namenode-info.nse      http-vuln-cve2013-6786.nse       ncp-serverinfo.nse              smtp-enum-users.nse
 +bjnp-discover.nse                     hadoop-tasktracker-info.nse             http-vuln-cve2013-7091.nse       ndmp-fs-info.nse                smtp-ntlm-info.nse
 +broadcast-ataoe-discover.nse          hbase-master-info.nse                   http-vuln-cve2014-2126.nse       ndmp-version.nse                smtp-open-relay.nse
 +broadcast-avahi-dos.nse               hbase-region-info.nse                   http-vuln-cve2014-2127.nse       nessus-brute.nse                smtp-strangeport.nse
 +broadcast-bjnp-discover.nse           hddtemp-info.nse                        http-vuln-cve2014-2128.nse       nessus-xmlrpc-brute.nse         smtp-vuln-cve2010-4344.nse
 +broadcast-db2-discover.nse            hnap-info.nse                           http-vuln-cve2014-2129.nse       netbus-auth-bypass.nse          smtp-vuln-cve2011-1720.nse
 +broadcast-dhcp6-discover.nse          hostmap-bfk.nse                         http-vuln-cve2014-3704.nse       netbus-brute.nse                smtp-vuln-cve2011-1764.nse
 +broadcast-dhcp-discover.nse           hostmap-crtsh.nse                       http-vuln-cve2014-8877.nse       netbus-info.nse                 sniffer-detect.nse
 +broadcast-dns-service-discovery.nse   hostmap-robtex.nse                      http-vuln-cve2015-1427.nse       netbus-version.nse              snmp-brute.nse
 +broadcast-dropbox-listener.nse        http-adobe-coldfusion-apsa1301.nse      http-vuln-cve2015-1635.nse       nexpose-brute.nse               snmp-hh3c-logins.nse
 +broadcast-eigrp-discovery.nse         http-affiliate-id.nse                   http-vuln-cve2017-1001000.nse    nfs-ls.nse                      snmp-info.nse
 +broadcast-hid-discoveryd.nse          http-apache-negotiation.nse             http-vuln-cve2017-5638.nse       nfs-showmount.nse               snmp-interfaces.nse
 +broadcast-igmp-discovery.nse          http-apache-server-status.nse           http-vuln-cve2017-5689.nse       nfs-statfs.nse                  snmp-ios-config.nse
 +broadcast-jenkins-discover.nse        http-aspnet-debug.nse                   http-vuln-cve2017-8917.nse       nje-node-brute.nse              snmp-netstat.nse
 +broadcast-listener.nse                http-auth-finder.nse                    http-vuln-misfortune-cookie.nse  nje-pass-brute.nse              snmp-processes.nse
 +broadcast-ms-sql-discover.nse         http-auth.nse                           http-vuln-wnr1000-creds.nse      nntp-ntlm-info.nse              snmp-sysdescr.nse
 +broadcast-netbios-master-browser.nse  http-avaya-ipoffice-users.nse           http-waf-detect.nse              nping-brute.nse                 snmp-win32-services.nse
 +broadcast-networker-discover.nse      http-awstatstotals-exec.nse             http-waf-fingerprint.nse         nrpe-enum.nse                   snmp-win32-shares.nse
 +broadcast-novell-locate.nse           http-axis2-dir-traversal.nse            http-webdav-scan.nse             ntp-info.nse                    snmp-win32-software.nse
 +broadcast-ospf2-discover.nse          http-backup-finder.nse                  http-wordpress-brute.nse         ntp-monlist.nse                 snmp-win32-users.nse
 +broadcast-pc-anywhere.nse             http-barracuda-dir-traversal.nse        http-wordpress-enum.nse          omp2-brute.nse                  socks-auth-info.nse
 +broadcast-pc-duo.nse                  http-bigip-cookie.nse                   http-wordpress-users.nse         omp2-enum-targets.nse           socks-brute.nse
 +broadcast-pim-discovery.nse           http-brute.nse                          http-xssed.nse                   omron-info.nse                  socks-open-proxy.nse
 +broadcast-ping.nse                    http-cakephp-version.nse                iax2-brute.nse                   openflow-info.nse               ssh2-enum-algos.nse
 +broadcast-pppoe-discover.nse          http-chrono.nse                         iax2-version.nse                 openlookup-info.nse             ssh-auth-methods.nse
 +broadcast-rip-discover.nse            http-cisco-anyconnect.nse               icap-info.nse                    openvas-otp-brute.nse           ssh-brute.nse
 +broadcast-ripng-discover.nse          http-coldfusion-subzero.nse             iec-identify.nse                 openwebnet-discovery.nse        ssh-hostkey.nse
 +broadcast-sonicwall-discover.nse      http-comments-displayer.nse             ike-version.nse                  oracle-brute.nse                ssh-publickey-acceptance.nse
 +broadcast-sybase-asa-discover.nse     http-config-backup.nse                  imap-brute.nse                   oracle-brute-stealth.nse        ssh-run.nse
 +broadcast-tellstick-discover.nse      http-cookie-flags.nse                   imap-capabilities.nse            oracle-enum-users.nse           sshv1.nse
 +broadcast-upnp-info.nse               http-cors.nse                           imap-ntlm-info.nse               oracle-sid-brute.nse            ssl-ccs-injection.nse
 +broadcast-versant-locate.nse          http-cross-domain-policy.nse            impress-remote-discover.nse      oracle-tns-version.nse          ssl-cert-intaddr.nse
 +broadcast-wake-on-lan.nse             http-csrf.nse                           informix-brute.nse               ovs-agent-version.nse           ssl-cert.nse
 +broadcast-wpad-discover.nse           http-date.nse                           informix-query.nse               p2p-conficker.nse               ssl-date.nse
 +broadcast-wsdd-discover.nse           http-default-accounts.nse               informix-tables.nse              path-mtu.nse                    ssl-dh-params.nse
 +broadcast-xdmcp-discover.nse          http-devframework.nse                   ip-forwarding.nse                pcanywhere-brute.nse            ssl-enum-ciphers.nse
 +cassandra-brute.nse                   http-dlink-backdoor.nse                 ip-geolocation-geoplugin.nse     pcworx-info.nse                 ssl-heartbleed.nse
 +cassandra-info.nse                    http-dombased-xss.nse                   ip-geolocation-ipinfodb.nse      pgsql-brute.nse                 ssl-known-key.nse
 +cccam-version.nse                     http-domino-enum-passwords.nse          ip-geolocation-map-bing.nse      pjl-ready-message.nse           ssl-poodle.nse
 +cics-enum.nse                         http-drupal-enum.nse                    ip-geolocation-map-google.nse    pop3-brute.nse                  sslv2-drown.nse
 +cics-info.nse                         http-drupal-enum-users.nse              ip-geolocation-map-kml.nse       pop3-capabilities.nse           sslv2.nse
 +cics-user-brute.nse                   http-enum.nse                           ip-geolocation-maxmind.nse       pop3-ntlm-info.nse              sstp-discover.nse
 +cics-user-enum.nse                    http-errors.nse                         ip-https-discover.nse            port-states.nse                 stun-info.nse
 +citrix-brute-xml.nse                  http-exif-spider.nse                    ipidseq.nse                      pptp-version.nse                stun-version.nse
 +citrix-enum-apps.nse                  http-favicon.nse                        ipmi-brute.nse                   puppet-naivesigning.nse         stuxnet-detect.nse
 +citrix-enum-apps-xml.nse              http-feed.nse                           ipmi-cipher-zero.nse             qconn-exec.nse                  supermicro-ipmi-conf.nse
 +citrix-enum-servers.nse               http-fetch.nse                          ipmi-version.nse                 qscan.nse                       svn-brute.nse
 +citrix-enum-servers-xml.nse           http-fileupload-exploiter.nse           ipv6-multicast-mld-list.nse      quake1-info.nse                 targets-asn.nse
 +clamav-exec.nse                       http-form-brute.nse                     ipv6-node-info.nse               quake3-info.nse                 targets-ipv6-map4to6.nse
 +clock-skew.nse                        http-form-fuzzer.nse                    ipv6-ra-flood.nse                quake3-master-getservers.nse    targets-ipv6-multicast-echo.nse
 +coap-resources.nse                    http-frontpage-login.nse                irc-botnet-channels.nse          rdp-enum-encryption.nse         targets-ipv6-multicast-invalid-dst.nse
 +couchdb-databases.nse                 http-generator.nse                      irc-brute.nse                    rdp-ntlm-info.nse               targets-ipv6-multicast-mld.nse
 +couchdb-stats.nse                     http-git.nse                            irc-info.nse                     rdp-vuln-ms12-020.nse           targets-ipv6-multicast-slaac.nse
 +creds-summary.nse                     http-gitweb-projects-enum.nse           irc-sasl-brute.nse               realvnc-auth-bypass.nse         targets-ipv6-wordlist.nse
 +cups-info.nse                         http-google-malware.nse                 irc-unrealircd-backdoor.nse      redis-brute.nse                 targets-sniffer.nse
 +cups-queue-info.nse                   http-grep.nse                           iscsi-brute.nse                  redis-info.nse                  targets-traceroute.nse
 +cvs-brute.nse                         http-headers.nse                        iscsi-info.nse                   resolveall.nse                  targets-xml.nse
 +cvs-brute-repository.nse              http-hp-ilo-info.nse                    isns-info.nse                    reverse-index.nse               teamspeak2-version.nse
 +daap-get-library.nse                  http-huawei-hg5xx-vuln.nse              jdwp-exec.nse                    rexec-brute.nse                 telnet-brute.nse
 +daytime.nse                           http-icloud-findmyiphone.nse            jdwp-info.nse                    rfc868-time.nse                 telnet-encryption.nse
 +db2-das-info.nse                      http-icloud-sendmsg.nse                 jdwp-inject.nse                  riak-http-info.nse              telnet-ntlm-info.nse
 +deluge-rpc-brute.nse                  http-iis-short-name-brute.nse           jdwp-version.nse                 rlogin-brute.nse                tftp-enum.nse
 +dhcp-discover.nse                     http-iis-webdav-vuln.nse                knx-gateway-discover.nse         rmi-dumpregistry.nse            tls-alpn.nse
 +dicom-brute.nse                       http-internal-ip-disclosure.nse         knx-gateway-info.nse             rmi-vuln-classloader.nse        tls-nextprotoneg.nse
 +dicom-ping.nse                        http-joomla-brute.nse                   krb5-enum-users.nse              rpcap-brute.nse                 tls-ticketbleed.nse
 +dict-info.nse                         http-jsonp-detection.nse                ldap-brute.nse                   rpcap-info.nse                  tn3270-screen.nse
 +distcc-cve2004-2687.nse               http-litespeed-sourcecode-download.nse  ldap-novell-getpass.nse          rpc-grind.nse                   tor-consensus-checker.nse
 +dns-blacklist.nse                     http-ls.nse                             ldap-rootdse.nse                 rpcinfo.nse                     traceroute-geolocation.nse
 +dns-brute.nse                         http-majordomo2-dir-traversal.nse       ldap-search.nse                  rsa-vuln-roca.nse               tso-brute.nse
 +dns-cache-snoop.nse                   http-malware-host.nse                   lexmark-config.nse               rsync-brute.nse                 tso-enum.nse
 +dns-check-zone.nse                    http-mcmp.nse                           llmnr-resolve.nse                rsync-list-modules.nse          ubiquiti-discovery.nse
 +dns-client-subnet-scan.nse            http-methods.nse                        lltd-discovery.nse               rtsp-methods.nse                unittest.nse
 +dns-fuzz.nse                          http-method-tamper.nse                  lu-enum.nse                      rtsp-url-brute.nse              unusual-port.nse
 +dns-ip6-arpa-scan.nse                 http-mobileversion-checker.nse          maxdb-info.nse                   rusers.nse                      upnp-info.nse
 +dns-nsec3-enum.nse                    http-ntlm-info.nse                      mcafee-epo-agent.nse             s7-info.nse                     uptime-agent-info.nse
 +dns-nsec-enum.nse                     http-open-proxy.nse                     membase-brute.nse                samba-vuln-cve-2012-1182.nse    url-snarf.nse
 +dns-nsid.nse                          http-open-redirect.nse                  membase-http-info.nse            script.db                       ventrilo-info.nse
 +dns-random-srcport.nse                http-passwd.nse                         memcached-info.nse               servicetags.nse                 versant-info.nse
 +dns-random-txid.nse                   http-phpmyadmin-dir-traversal.nse       metasploit-info.nse              shodan-api.nse                  vmauthd-brute.nse
 +dns-recursion.nse                     http-phpself-xss.nse                    metasploit-msgrpc-brute.nse      sip-brute.nse                   vmware-version.nse
 +dns-service-discovery.nse             http-php-version.nse                    metasploit-xmlrpc-brute.nse      sip-call-spoof.nse              vnc-brute.nse
 +dns-srv-enum.nse                      http-proxy-brute.nse                    mikrotik-routeros-brute.nse      sip-enum-users.nse              vnc-info.nse
 +dns-update.nse                        http-put.nse                            mmouse-brute.nse                 sip-methods.nse                 vnc-title.nse
 +dns-zeustracker.nse                   http-qnap-nas-info.nse                  mmouse-exec.nse                  skypev2-version.nse             voldemort-info.nse
 +dns-zone-transfer.nse                 http-referer-checker.nse                modbus-discover.nse              smb2-capabilities.nse           vtam-enum.nse
 +docker-version.nse                    http-rfi-spider.nse                     mongodb-brute.nse                smb2-security-mode.nse          vulners.nse
 +domcon-brute.nse                      http-robots.txt.nse                     mongodb-databases.nse            smb2-time.nse                   vuze-dht-info.nse
 +domcon-cmd.nse                        http-robtex-reverse-ip.nse              mongodb-info.nse                 smb2-vuln-uptime.nse            wdb-version.nse
 +domino-enum-users.nse                 http-robtex-shared-ns.nse               mqtt-subscribe.nse               smb-brute.nse                   weblogic-t3-info.nse
 +dpap-brute.nse                        http-sap-netweaver-leak.nse             mrinfo.nse                       smb-double-pulsar-backdoor.nse  whois-domain.nse
 +drda-brute.nse                        http-security-headers.nse               msrpc-enum.nse                   smb-enum-domains.nse            whois-ip.nse
 +drda-info.nse                         http-server-header.nse                  ms-sql-brute.nse                 smb-enum-groups.nse             wsdd-discover.nse
 +duplicates.nse                        http-shellshock.nse                     ms-sql-config.nse                smb-enum-processes.nse          x11-access.nse
 +eap-info.nse                          http-sitemap-generator.nse              ms-sql-dac.nse                   smb-enum-services.nse           xdmcp-discover.nse
 +enip-info.nse                         http-slowloris-check.nse                ms-sql-dump-hashes.nse           smb-enum-sessions.nse           xmlrpc-methods.nse
 +epmd-info.nse                         http-slowloris.nse                      ms-sql-empty-password.nse        smb-enum-shares.nse             xmpp-brute.nse
 +eppc-enum-processes.nse               http-sql-injection.nse                  ms-sql-hasdbaccess.nse           smb-enum-users.nse              xmpp-info.nse
 +</code>
 +
 +Les scripts sont regroupés dans des catégories : **auth**, **broadcast**, **brute**, **default**, **discovery**, **dos**, **exploit**, **external**, **fuzzer**, **intrusive**, **malware**, **safe**, **version** and **vuln**.
 +
 +<WRAP center round important 50%>
 +**Important** - Pour plus d'informations concernant ces catégories, consultez cette [[https://nmap.org/man/fr/man-nse.html|page]].
 +</WRAP>
 +
 +La catégorie la plus utilisée est **default** qui est appelée par l'utilisation de l'option **-sC**. Cette catégorie contient une liste de scripts par défaut.
 +
 +<code>
 +[root@centos8 ~]# nmap -v -sC localhost
 +Starting Nmap 7.92 ( https://nmap.org ) at 2024-10-02 17:02 CEST
 +NSE: Loaded 125 scripts for scanning.
 +NSE: Script Pre-scanning.
 +Initiating NSE at 17:02
 +Completed NSE at 17:02, 0.00s elapsed
 +Initiating NSE at 17:02
 +Completed NSE at 17:02, 0.00s elapsed
 +Initiating SYN Stealth Scan at 17:02
 +Scanning localhost (127.0.0.1) [1000 ports]
 +Discovered open port 80/tcp on 127.0.0.1
 +Discovered open port 111/tcp on 127.0.0.1
 +Discovered open port 22/tcp on 127.0.0.1
 +Discovered open port 631/tcp on 127.0.0.1
 +Completed SYN Stealth Scan at 17:02, 0.04s elapsed (1000 total ports)
 +NSE: Script scanning 127.0.0.1.
 +Initiating NSE at 17:02
 +Completed NSE at 17:02, 0.38s elapsed
 +Initiating NSE at 17:02
 +Completed NSE at 17:02, 0.00s elapsed
 +Nmap scan report for localhost (127.0.0.1)
 +Host is up (0.000011s latency).
 +Other addresses for localhost (not scanned): ::1
 +Not shown: 996 closed tcp ports (reset)
 +PORT    STATE SERVICE
 +22/tcp  open  ssh
 +| ssh-hostkey: 
 +|   3072 11:65:f2:24:6b:e1:f6:dc:31:be:12:28:5a:90:46:84 (RSA)
 +|   256 9d:99:66:02:fd:cb:cc:58:00:79:38:64:28:55:43:34 (ECDSA)
 +|_  256 d9:8a:d9:46:96:c1:5a:ad:78:f7:bc:38:d1:d7:06:72 (ED25519)
 +80/tcp  open  http
 +| http-methods: 
 +|   Supported Methods: GET POST OPTIONS HEAD TRACE
 +|_  Potentially risky methods: TRACE
 +|_http-title: This is a test
 +111/tcp open  rpcbind
 +| rpcinfo: 
 +|   program version    port/proto  service
 +|   100000  2,3,4        111/tcp   rpcbind
 +|   100000  2,3,4        111/udp   rpcbind
 +|   100000  3,4          111/tcp6  rpcbind
 +|_  100000  3,4          111/udp6  rpcbind
 +631/tcp open  ipp
 +| http-robots.txt: 1 disallowed entry 
 +|_/
 +|_http-title: Home - CUPS 2.2.6
 +| ssl-cert: Subject: commonName=centos8.ittraining.loc/organizationName=centos8.ittraining.loc/stateOrProvinceName=Unknown/countryName=GB
 +| Issuer: commonName=centos8.ittraining.loc/organizationName=centos8.ittraining.loc/stateOrProvinceName=Unknown/countryName=GB
 +| Public Key type: rsa
 +| Public Key bits: 2048
 +| Signature Algorithm: sha256WithRSAEncryption
 +| Not valid before: 2024-10-02T15:02:15
 +| Not valid after:  2034-09-30T15:02:15
 +| MD5:   3dbd 816b b33c 9bd8 d9f0 f0c4 8204 a60b
 +|_SHA-1: 9d58 dda8 a024 41db 63cb bb85 fea9 86c1 6238 399b
 +| http-methods: 
 +|_  Supported Methods: GET HEAD POST OPTIONS
 +|_ssl-date: TLS randomness does not represent time
 +
 +NSE: Script Post-scanning.
 +Initiating NSE at 17:02
 +Completed NSE at 17:02, 0.00s elapsed
 +Initiating NSE at 17:02
 +Completed NSE at 17:02, 0.00s elapsed
 +Read data files from: /usr/bin/../share/nmap
 +Nmap done: 1 IP address (1 host up) scanned in 0.82 seconds
 +           Raw packets sent: 1000 (44.000KB) | Rcvd: 2004 (84.176KB)
 +</code>
 +
 +<WRAP center round warning 50%>
 +**Attention** - La catégorie par défaut **default** contient certains scripts de la catégorie **intrusive**. Vous ne devez donc jamais utiliser cette option sur un réseau sans avoir obtenu un accord au préalable.
 +</WRAP>
 +
 +===netcat ===
 +
 +**netcat** est un couteau suisse. Il permet non seulement de scanner des ports mais aussi de lancer la connexion lors de la découverte d'un port ouvert.
 +
 +==Options de la commande==
 +
 +Les options de cette commande sont :
 +
 +<code>
 +[root@centos8 ~]# nc --help
 +Ncat 7.92 ( https://nmap.org/ncat )
 +Usage: ncat [options] [hostname] [port]
 +
 +Options taking a time assume seconds. Append 'ms' for milliseconds,
 +'s' for seconds, 'm' for minutes, or 'h' for hours (e.g. 500ms).
 +  -4                         Use IPv4 only
 +  -6                         Use IPv6 only
 +  -U, --unixsock             Use Unix domain sockets only
 +      --vsock                Use vsock sockets only
 +  -C, --crlf                 Use CRLF for EOL sequence
 +  -c, --sh-exec <command>    Executes the given command via /bin/sh
 +  -e, --exec <command>       Executes the given command
 +      --lua-exec <filename>  Executes the given Lua script
 +  -g hop1[,hop2,...]         Loose source routing hop points (8 max)
 +  -G <n>                     Loose source routing hop pointer (4, 8, 12, ...)
 +  -m, --max-conns <n>        Maximum <n> simultaneous connections
 +  -h, --help                 Display this help screen
 +  -d, --delay <time>         Wait between read/writes
 +  -o, --output <filename>    Dump session data to a file
 +  -x, --hex-dump <filename>  Dump session data as hex to a file
 +  -i, --idle-timeout <time>  Idle read/write timeout
 +  -p, --source-port port     Specify source port to use
 +  -s, --source addr          Specify source address to use (doesn't affect -l)
 +  -l, --listen               Bind and listen for incoming connections
 +  -k, --keep-open            Accept multiple connections in listen mode
 +  -n, --nodns                Do not resolve hostnames via DNS
 +  -t, --telnet               Answer Telnet negotiations
 +  -u, --udp                  Use UDP instead of default TCP
 +      --sctp                 Use SCTP instead of default TCP
 +  -v, --verbose              Set verbosity level (can be used several times)
 +  -w, --wait <time>          Connect timeout
 +  -z                         Zero-I/O mode, report connection status only
 +      --append-output        Append rather than clobber specified output files
 +      --send-only            Only send data, ignoring received; quit on EOF
 +      --recv-only            Only receive data, never send anything
 +      --no-shutdown          Continue half-duplex when receiving EOF on stdin
 +      --allow                Allow only given hosts to connect to Ncat
 +      --allowfile            A file of hosts allowed to connect to Ncat
 +      --deny                 Deny given hosts from connecting to Ncat
 +      --denyfile             A file of hosts denied from connecting to Ncat
 +      --broker               Enable Ncat's connection brokering mode
 +      --chat                 Start a simple Ncat chat server
 +      --proxy <addr[:port]>  Specify address of host to proxy through
 +      --proxy-type <type>    Specify proxy type ("http", "socks4", "socks5")
 +      --proxy-auth <auth>    Authenticate with HTTP or SOCKS proxy server
 +      --proxy-dns <type>     Specify where to resolve proxy destination
 +      --ssl                  Connect or listen with SSL
 +      --ssl-cert             Specify SSL certificate file (PEM) for listening
 +      --ssl-key              Specify SSL private key (PEM) for listening
 +      --ssl-verify           Verify trust and domain name of certificates
 +      --ssl-trustfile        PEM file containing trusted SSL certificates
 +      --ssl-ciphers          Cipherlist containing SSL ciphers to use
 +      --ssl-servername       Request distinct server name (SNI)
 +      --ssl-alpn             ALPN protocol list to use
 +      --version              Display Ncat's version information and exit
 +
 +See the ncat(1) manpage for full options, descriptions and usage examples
 +</code>
 +
 +==Utilisation==
 +
 +Dans l'exemple qui suite, un scan est lancé sur le port 80 puis sur le port 25 :
 +
 +<code>
 +[root@centos8 ~]# nc 127.0.0.1 80 -w 1 -vv
 +Ncat: Version 7.92 ( https://nmap.org/ncat )
 +NCAT DEBUG: Using system default trusted CA certificates and those in /usr/share/ncat/ca-bundle.crt.
 +NCAT DEBUG: Unable to load trusted CA certificates from /usr/share/ncat/ca-bundle.crt: error:02001002:system library:fopen:No such file or directory
 +libnsock nsock_iod_new2(): nsock_iod_new (IOD #1)
 +libnsock nsock_connect_tcp(): TCP connection requested to 127.0.0.1:80 (IOD #1) EID 8
 +libnsock nsock_trace_handler_callback(): Callback: CONNECT SUCCESS for EID 8 [127.0.0.1:80]
 +Ncat: Connected to 127.0.0.1:80.
 +libnsock nsock_iod_new2(): nsock_iod_new (IOD #2)
 +libnsock nsock_read(): Read request from IOD #1 [127.0.0.1:80] (timeout: -1ms) EID 18
 +libnsock nsock_readbytes(): Read request for 0 bytes from IOD #2 [peer unspecified] EID 26
 +^C
 +
 +[root@centos8 ~]# nc 127.0.0.1 25 -w 1 -vv
 +Ncat: Version 7.92 ( https://nmap.org/ncat )
 +NCAT DEBUG: Using system default trusted CA certificates and those in /usr/share/ncat/ca-bundle.crt.
 +NCAT DEBUG: Unable to load trusted CA certificates from /usr/share/ncat/ca-bundle.crt: error:02001002:system library:fopen:No such file or directory
 +libnsock nsock_iod_new2(): nsock_iod_new (IOD #1)
 +libnsock nsock_connect_tcp(): TCP connection requested to 127.0.0.1:25 (IOD #1) EID 8
 +libnsock nsock_trace_handler_callback(): Callback: CONNECT ERROR [Connection refused (111)] for EID 8 [127.0.0.1:25]
 +Ncat: Connection refused.
 +</code>
 +
 +<WRAP center round important 50%>
 +**Important** - Notez que **netcat** se connecte au port 25 qui est ouvert.
 +</WRAP>
 +
 +====LAB #6 - Mise en place du Système de Détection et de Prévention d'Intrusion Portsentry====
 +
 +Portsentry est un **S**ystème de **D**étection et de **Prévention** d'**I**ntrusion (SDPI) qui surveille les requêtes entrantes et en cas d'anomalie bloque l'adresse IP de l'attaquant en inscrivant une règle dans le pare-feu NetFilter (Iptables).
 +
 +=== Installation ===
 +
 +Sous RHEL/CentOS 8, **portsentry** n'est pas installé par défaut. Qui plus est **portsentry** ne se trouve pas dans les dépôts standards. Installez donc le paquet **portsentry-1.2-1.el5.x86_64.rpm** à partir de l'URL ci-dessous :
 +
 +<code>
 +[root@centos8 ~]# rpm -ivh https://www.dropbox.com/scl/fi/v1iniimmjkvj0kx6xllmt/portsentry-1.2-1.el5.x86_64.rpm?rlkey=zyyvgd2a1ksi27y2v2maf6fuh&st=kdgnkvfe
 +[1] 9629
 +[root@centos8 ~]# Retrieving https://www.dropbox.com/scl/fi/v1iniimmjkvj0kx6xllmt/portsentry-1.2-1.el5.x86_64.rpm?rlkey=zyyvgd2a1ksi27y2v2maf6fuh
 +warning: /var/tmp/rpm-tmp.FP6pPg: Header V3 DSA/SHA1 Signature, key ID 4026433f: NOKEY
 +Verifying...                          ################################# [100%]
 +Preparing...                          ################################# [100%]
 +Updating / installing...
 +   1:portsentry-1.2-1.el5             ################################# [100%]
 +^C
 +</code>
 +
 +===Configuration===
 +
 +Téléchargez le fichier **/etc/portsentry/portsentry.conf** :
 +
 +<code>
 +[root@centos8 ~]# wget https://www.dropbox.com/scl/fi/vaz781ja31t14cd95yc8p/portsentry.conf?rlkey=0bkalz8bjn7zsimp03xine5fz&st=ee9d9vzs
 +[1] 9676
 +[root@centos8 ~]# 
 +Redirecting output to ‘wget-log’.
 +^C
 +[1]+  Done                    wget https://www.dropbox.com/scl/fi/vaz781ja31t14cd95yc8p/portsentry.conf?rlkey=0bkalz8bjn7zsimp03xine5fz
 +
 +[root@centos8 ~]# mv 'portsentry.conf?rlkey=0bkalz8bjn7zsimp03xine5fz' /etc/portsentry/portsentry.conf
 +mv: overwrite '/etc/portsentry/portsentry.conf'? y
 +</code>
 +
 +Pour rendre le service SysVInit compatible avec Systemd, éditez le fichier **/etc/init.d/portsentry** en supprimant la ligne **11** :
 +
 +<code>
 +[root@centos8 ~]# nl /etc/init.d/portsentry
 +     1 #!/bin/bash
 +     2 #
 +     3 # Startup script for the Portsentry portscan detector 
 +     4 #
 +     5 # chkconfig: 345 98 02
 +     6 # description: PortSentry Port Scan Detector is part of the Abacus Project \
 +     7 #              suite of tools. The Abacus Project is an initiative to release \
 +     8 #              low-maintenance, generic, and reliable host based intrusion \
 +     9 #              detection software to the Internet community.
 +    10 # processname: portsentry
 +    11 # pidfile: /var/run/portsentry.pid  <--------------------------------SUPPRIMEZ cette ligne
 +    12 # config: /etc/portsentry/portsentry.conf
 +       
 +    13 # Source function library.
 +...
 +</code>
 +
 +Puis ajoutez la ligne **80** :
 +
 +<code>
 +...
 +    77 stop() {
 +    78 echo -n $"Stopping $prog: "
 +    79 killproc portsentry
 +    80 killall portsentry  <--------------------------------AJOUTEZ cette ligne
 +    81 RETVAL=$?
 +    82 echo
 +    83 [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/portsentry
 +    84 }
 +       
 +    85 # See how we were called.
 +...
 +</code>
 +
 +Exécutez la commande suivante pour prendre en compte les modifications :
 +
 +<code>
 +[root@centos8 ~]# systemctl daemon-reload
 +</code>
 +
 +===Utilisation===
 +
 +Démarrez le service **portsentry** :
 +
 +<code>
 +[root@centos8 ~]# systemctl restart portsentry
 +
 +[root@centos8 ~]# systemctl status portsentry
 +● portsentry.service - SYSV: PortSentry Port Scan Detector is part of the Abacus Project suite of tools. The Abacus Project is an initiative to release low-maintenance, generic, and reliable host based intrusi>
 +   Loaded: loaded (/etc/rc.d/init.d/portsentry; generated)
 +   Active: active (running) since Wed 2024-10-02 17:37:33 CEST; 4s ago
 +     Docs: man:systemd-sysv-generator(8)
 +  Process: 10142 ExecStart=/etc/rc.d/init.d/portsentry start (code=exited, status=0/SUCCESS)
 +    Tasks: 6 (limit: 100483)
 +   Memory: 1.5M
 +   CGroup: /system.slice/portsentry.service
 +           ├─ 9907 /usr/sbin/portsentry -atcp
 +           ├─ 9909 /usr/sbin/portsentry -audp
 +           ├─10086 /usr/sbin/portsentry -atcp
 +           ├─10088 /usr/sbin/portsentry -audp
 +           ├─10169 /usr/sbin/portsentry -atcp
 +           └─10171 /usr/sbin/portsentry -audp
 +
 +Oct 02 17:37:33 centos8.ittraining.loc portsentry[10169]: adminalert: Advanced Stealth scan detection mode activated. Ignored TCP port: 25
 +Oct 02 17:37:33 centos8.ittraining.loc portsentry[10169]: adminalert: Advanced Stealth scan detection mode activated. Ignored TCP port: 53
 +Oct 02 17:37:33 centos8.ittraining.loc portsentry[10169]: adminalert: Advanced Stealth scan detection mode activated. Ignored TCP port: 80
 +Oct 02 17:37:33 centos8.ittraining.loc portsentry[10169]: adminalert: Advanced Stealth scan detection mode activated. Ignored TCP port: 110
 +Oct 02 17:37:33 centos8.ittraining.loc portsentry[10169]: adminalert: Advanced Stealth scan detection mode activated. Ignored TCP port: 113
 +Oct 02 17:37:33 centos8.ittraining.loc portsentry[10169]: adminalert: Advanced Stealth scan detection mode activated. Ignored TCP port: 137
 +Oct 02 17:37:33 centos8.ittraining.loc portsentry[10169]: adminalert: Advanced Stealth scan detection mode activated. Ignored TCP port: 138
 +Oct 02 17:37:33 centos8.ittraining.loc portsentry[10169]: adminalert: Advanced Stealth scan detection mode activated. Ignored TCP port: 139
 +Oct 02 17:37:33 centos8.ittraining.loc portsentry[10169]: adminalert: Advanced Stealth scan detection mode activated. Ignored TCP port: 443
 +Oct 02 17:37:33 centos8.ittraining.loc portsentry[10169]: adminalert: PortSentry is now active and listening.
 +
 +[root@centos8 ~]# ps aux | grep portsentry
 +root        9907  0.0  0.0   4468   100 ?        Ss   17:23   0:00 /usr/sbin/portsentry -atcp
 +root        9909  0.0  0.0   4468   100 ?        Ss   17:23   0:00 /usr/sbin/portsentry -audp
 +root       10086  0.1  0.0   4468    96 ?        Ss   17:35   0:00 /usr/sbin/portsentry -atcp
 +root       10088  0.1  0.0   4468   100 ?        Ss   17:35   0:00 /usr/sbin/portsentry -audp
 +root       10169  0.2  0.0   4468   100 ?        Ss   17:37   0:00 /usr/sbin/portsentry -atcp
 +root       10171  0.2  0.0   4468    96 ?        Ss   17:37   0:00 /usr/sbin/portsentry -audp
 +root       10192  0.0  0.0  12216  1208 pts/0    S+   17:39   0:00 grep --color=auto portsentry
 +</code>
 +
 +Editez le fichier **/etc/portsentry/portsentry.ignore** en supprimant la ligne contenant votre adresse IP 10.0.2.45 :
 +
 +<code>
 +[root@centos8 ~]# vi /etc/portsentry/portsentry.ignore
 +
 +[root@centos8 ~]# cat /etc/portsentry/portsentry.ignore
 +# Put hosts in here you never want blocked. This includes the IP addresses
 +# of all local interfaces on the protected host (i.e virtual host, mult-home)
 +# Keep 127.0.0.1 and 0.0.0.0 to keep people from playing games.
 +#
 +# PortSentry can support full netmasks for networks as well. Format is:
 +#
 +# <IP Address>/<Netmask>
 +#
 +# Example:
 +#
 +# 192.168.2.0/24
 +# 192.168.0.0/16
 +# 192.168.2.1/32
 +# Etc.
 +#
 +# If you don't supply a netmask it is assumed to be 32 bits.
 +#
 +#
 +
 +127.0.0.1/32
 +0.0.0.0
 +#########################################
 +# Do NOT edit below this line, if you   #
 +# do, your changes will be lost when    #
 +# portsentry is restarted via the       #
 +# initscript. Make all changes above    #
 +# this box.                             #
 +#########################################
 +
 +# Exclude all local interfaces
 +fe80::8af3:5782:3598:aa0f
 +127.0.0.1
 +::1
 +192.168.122.1
 +
 +# Exclude the default gateway(s)
 +10.0.2.1
 +
 +# Exclude the nameservers
 +8.8.8.8
 +
 +# And last but not least...
 +0.0.0.0
 +</code>
 +
 +Installez maintenant le paquet **mailx** :
 +
 +<code>
 +[root@centos8 ~]# dnf install mailx
 +</code>
 +
 +**Sans** re-démarrez le service portsentry, lancez un scan des ports avec nmap :
 +
 +<code>
 +[root@centos8 ~]# nmap -sC 10.0.2.45
 +Starting Nmap 7.92 ( https://nmap.org ) at 2024-10-02 17:45 CEST
 +^C
 +[root@centos8 ~]#
 +</code>
 +
 +<WRAP center round important 50%>
 +**Important** - Notez l'utilisation de la combinaison de touches <key>C</key><key>c</key> pour arrêter nmap.
 +</WRAP>
 +
 +Consultez les règles d'iptables :
 +
 +<code>
 +[root@centos8 ~]# iptables -L
 +Chain INPUT (policy ACCEPT)
 +target     prot opt source               destination         
 +DROP       all  --  centos8.ittraining.loc  anywhere  <--------------------------------REGARDEZ cette ligne.          
 +LIBVIRT_INP  all  --  anywhere             anywhere            
 +
 +Chain FORWARD (policy ACCEPT)
 +target     prot opt source               destination         
 +LIBVIRT_FWX  all  --  anywhere             anywhere            
 +LIBVIRT_FWI  all  --  anywhere             anywhere            
 +LIBVIRT_FWO  all  --  anywhere             anywhere            
 +
 +Chain OUTPUT (policy ACCEPT)
 +target     prot opt source               destination         
 +LIBVIRT_OUT  all  --  anywhere             anywhere            
 +
 +Chain LIBVIRT_INP (1 references)
 +target     prot opt source               destination         
 +ACCEPT     udp  --  anywhere             anywhere             udp dpt:domain
 +ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:domain
 +ACCEPT     udp  --  anywhere             anywhere             udp dpt:bootps
 +ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:bootps
 +
 +Chain LIBVIRT_OUT (1 references)
 +target     prot opt source               destination         
 +ACCEPT     udp  --  anywhere             anywhere             udp dpt:domain
 +ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:domain
 +ACCEPT     udp  --  anywhere             anywhere             udp dpt:bootpc
 +ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:bootpc
 +
 +Chain LIBVIRT_FWO (1 references)
 +target     prot opt source               destination         
 +ACCEPT     all  --  192.168.122.0/24     anywhere            
 +REJECT     all  --  anywhere             anywhere             reject-with icmp-port-unreachable
 +
 +Chain LIBVIRT_FWI (1 references)
 +target     prot opt source               destination         
 +ACCEPT     all  --  anywhere             192.168.122.0/24     ctstate RELATED,ESTABLISHED
 +REJECT     all  --  anywhere             anywhere             reject-with icmp-port-unreachable
 +
 +Chain LIBVIRT_FWX (1 references)
 +target     prot opt source               destination         
 +ACCEPT     all  --  anywhere             anywhere
 +</code>
 +
 +Pour nettoyer la règle, re-démarrez le service **firewalld** :
 +
 +<code>
 +[root@centos8 ~]# systemctl restart firewalld
 +</code>
 +
 +=====Système de Fichiers=====
 +
 +==== LAB #7 - Mise en place du File Integrity Checker Afick ====
 +
 +===Présentation===
 +
 +**[[http://afick.sourceforge.net/index.fr.html|Afick]]** ( Another File Intergrity Checker ) est un programme "controleur d'integrité des fichiers" :
 +un logiciel dédié à la sécurité informatique, analogue au très connu **tripwire**. Il permet de suivre les modifications des systèmes de fichiers, et en particulier de détecter les intrusions. Il fonctionne en créant une base de données stockant des informations concernant le système de fichiers d'un serveur puis en vérifiant périodiquement le système de fichiers contre cette base afin de vous prévenir de toute modification éventuelle. Pour cette raison, il convient d'installer afick sur le serveur au plus tôt.
 +
 +===Installation===
 +
 +Téléchargez la dernière version d'Afick :
 +
 +<code>
 +[root@centos8 ~]# wget https://sourceforge.net/projects/afick/files/afick/3.8.1/afick-3.8.1-1.noarch.rpm
 +</code>
 +
 +Pour installer **Afick**, utilisez la commande suivante :
 +
 +<code>
 +[root@centos8 ~]# dnf localinstall afick-3.8.1-1.noarch.rpm --nogpgcheck
 +</code>
 +
 +===Configuration===
 +
 +La configuration d'Afick est contenu dans le fichier **/etc/afick.conf**.
 +
 +Dans ce fichier, plusieurs sections nous intéressent :
 +
 +==La Section Directives==
 +
 +<file>
 +####################
 +# directives section
 +####################
 +# binary values can be : yes/1/true or no/0/false
 +# database : name with full path to database file
 +database:=/var/lib/afick/afick
 +# history : full path to history file
 +history := /var/lib/afick/history
 +# archive : full path to directory for archived results
 +archive := /var/lib/afick/archive
 +# report_url : where to send the result : stdout/stderr/null
 +report_url := stdout
 +# report_syslog : send output to syslog ?
 +report_syslog := no
 +# mask_sysupdate : report packages update
 +mask_sysupdate := no
 +# verbose : (obsolete) boolean value for debugging messages
 +# use debug parameter below
 +verbose := no
 +# debug : set a level of debugging messages, from 0 (none) to 4 (full)
 +debug := 0
 +# warn_dead_symlinks : boolean : if set, warn about dead symlinks
 +warn_dead_symlinks := no
 +# follow_symlinks : boolean : if set, do checksum on target file (else on target file name)
 +follow_symlinks := no
 +# allow_overload : boolean : if set, allow to overload rules (the last rule wins), else put a warning
 +allow_overload := yes
 +# report_context : boolean : if set, display all changed attributes, not just those selected by rules
 +report_context := no
 +# report_full_newdel : boolean : if set, report all changes, if not set, report only a summary on top directories
 +report_full_newdel := no
 +# report_summary : boolean ; if set, report the summary section
 +report_summary := yes
 +# warn_missing_file  : boolean : is set, warn about selected files (in this config), which does not exist
 +warn_missing_file := no
 +# running_files : boolean : if set, warn about files changed during a program run
 +running_files := yes
 +# timing : boolean : if set, print timing statistics about the job
 +timing := yes
 +# ignore_case : boolean : if set, ignore case on file name
 +ignore_case := no
 +# max_checksum_size : numeric : only compute checksum on first max_checksum_size bytes ( 0 means unlimited)
 +max_checksum_size := 10000000
 +# allow_relativepath : boolean : if set, afick files, config and databases are stored as relative path
 +allow_relativepath := 0
 +# utc_time : boolean; if set display date in utc time, else in local time
 +utc_time := 0
 +
 +# only_suffix : list of suffix to scan (and just this ones) : is empty (disabled) by default
 +# not very usefull on unix, but is ok on windows
 +# this will speed up the scan, but with a lesser security
 +# only_suffix :=
 +
 +# the 3 next directives : exclude_suffix exclude_prefix exclude_re
 +# can be written on several lines
 +# exclude_suffix : list of suffixes to ignore
 +# text files
 +exclude_suffix := log LOG html htm HTM txt TXT xml
 +# help files
 +exclude_suffix := hlp pod chm
 +# old files
 +exclude_suffix := tmp old bak
 +# fonts
 +exclude_suffix := fon ttf TTF
 +# images
 +exclude_suffix := bmp BMP jpg JPG gif png ico
 +# audio
 +exclude_suffix := wav WAV mp3 avi
 +# python
 +exclude_suffix := pyc
 +
 +# exclude_prefix : list of prefixes to ignore
 +exclude_prefix := __pycache__
 +
 +# exclude_re : a file pattern (using regex syntax) to ignore (apply on full path)
 +# one pattern by line
 +#exclude_re :=
 +</file>
 +
 +Cette section définit les directives globales et notamment :
 +
 +  * l'emplacement de la base de données
 +
 +<file>
 +database:=/var/lib/afick/afick
 +</file>
 +
 +<WRAP center round important 50%>
 +**Important** - Veuillez à sauvegarder régulièrement votre base de données. En effet, dans le cas où votre système est compromis, sans sauvegarde de votre base, vous ne serez plus certain de l'exactitude de cette dernière.
 +</WRAP>
 +
 +  * l'exclusion de certaines extensions de la vérification
 +
 +<file>
 +exclude_suffix := log LOG html htm HTM txt TXT xml
 +</file>
 +
 +==La Section Alias==
 +
 +<file>
 +###############
 +# alias section
 +###############
 +# action : a list of item to check :
 +# md5 : md5 checksum
 +# sha1 : sha-1 checksum
 +# sha256 : sha-256 checksum
 +# sha512 : sha-512 checksum
 +# d : device
 +# i : inode
 +# p : permissions
 +# n : number of links
 +# u : user
 +# g : group
 +# s : size
 +# b : number of blocks
 +# m : mtime
 +# c : ctime
 +# a : atime
 +# acl : acl
 +
 +#all:    p+d+i+n+u+g+s+b+m+c+md5+acl
 +#R:      p+d+i+n+u+g+s+m+c+md5
 +#L:      p+d+i+n+u+g
 +#P:      p+n+u+g+s+md5
 +#E:      ''
 +
 +# action alias may be configured with
 +# your_alias = another_alias|item[+item][-item]
 +# all is a pre-defined alias for all items except "a"
 +DIR = p+i+n+u+g
 +ETC = p+d+u+g+s+md5
 +Logs = p+n+u+g
 +MyRule = p+d+n+u+g+s+b+md5
 +</file>
 +
 +Cette partie du fichier de configuration détaille les combinaisons de vérifications de fichiers à réaliser :
 +
 +<file>
 +DIR=p+i+n+u+g
 +ETC = p+d+i+u+g+s+md5
 +Logs = p+n+u+g
 +MyRule = p+d+n+u+g+s+b+md5
 +</file>
 +
 +Les options détaillées sont :
 +
 +^ Option ^ Description ^
 +|  md5  | Vérifie la somme de contrôle md5 du contenu du fichier |
 +|  sha1  | Vérifie la somme de contrôle sha1 du contenu du fichier |
 +|  d  | Vérifie pour un périphérique son "major number" et son "minor number" |
 +|  i  | Vérifie le numéro d'inode |
 +|  p  | Vérifie les droits d'accès au fichier |
 +|  n  | Vérifie le nombre de liens |
 +|  u  | Vérifie l'utilisateur propriétaire du fichier |
 +|  g  | Vérifie le groupe propriétaire du fichier |
 +|  s  | Vérifie la taille du fichier |
 +|  b  | Vérifie le nombre de blocs alloués au fichier |
 +|  m  | Vérifie la date de la dernière modification du contenu du fichier |
 +|  c  | Vérifie la date de la dernière modification de l'inode |
 +|  a  | Vérifie la date du dernier accès |
 +
 +==La Section File==
 +
 +<file>
 +##############
 +# file section
 +##############
 +# 3 syntaxe are available :
 +# file action
 +#     to scan a file/directory with "action" parameters
 +# ! file
 +#     to remove file from scan
 +# = directory action
 +#       to scan the directory but not sub-directories
 +# file with blank character have to be quoted
 +#
 +# action is the list of attribute used to detect a change
 +
 += /  DIR
 +
 +/bin    MyRule
 +
 +/boot   MyRule
 +# ! /boot/map
 +# ! /boot/System.map
 +
 +/dev p+n
 +# ! /dev/.udev/db
 +# ! /dev/.udev/failed
 +# ! /dev/.udev/names
 +# ! /dev/.udev/watch
 +! /dev/bsg
 +! /dev/bus
 +! /dev/pts
 +! /dev/shm
 +# to avoid problems with pending usb
 +# = /dev/scsi p+n
 +
 +/etc    ETC
 +/etc/mtab ETC - md5 - s
 +/etc/adjtime ETC - md5 -s
 +# /etc/aliases.db ETC - md5 -s
 +# /etc/mail/statistics ETC - md5 -s
 +/etc/motd ETC
 +# /etc/ntp/drift ETC - md5 -s
 +# /etc/urpmi/urpmi.cfg Logs
 +# /etc/urpmi/proxy.cfg Logs
 +# /etc/prelink.cache ETC - md5 - s
 +! /etc/cups
 +# ! /etc/map
 +# ! /etc/postfix/prng_exch
 +# ! /etc/samba/secrets.tdb
 +# ! /etc/webmin/sysstats/modules/
 +# ! /etc/webmin/package-updates/
 +# ! /etc/webmin/system-status/
 +
 +/lib    MyRule
 +/lib64  MyRule
 +/lib/modules MyRule
 +# /lib/dev-state MyRule -u
 +
 +/root MyRule
 +! /root/.viminfo
 +! /root/.bash_history
 +# ! /root/.mc
 +# ! /root/tmp
 +! /root/.cache
 +
 +/sbin   MyRule
 +
 +/usr/bin        MyRule
 +/usr/sbin       MyRule
 +/usr/lib        MyRule
 +! /usr/lib/.build-id/
 +! /usr/lib/fontconfig/cache/
 +/usr/lib64      MyRule
 +/usr/local/bin  MyRule
 +/usr/local/sbin MyRule
 +/usr/local/lib  MyRule
 +
 +/var/ftp MyRule
 +/var/log Logs
 +# ! /var/log/journal
 += /var/log/afick Logs
 +# ! /var/log/ksymoops
 +/var/www MyRule
 +# ! /var/www/html/snortsnarf
 +</file>
 +
 +Cette partie du fichier de configuration détaille les vérifications de fichiers à réaliser, en voici un extrait :
 +
 +<file>
 +...
 +/etc ETC
 +/etc/mtab ETC - md5 - s
 +/etc/adjtime ETC - md5
 +...
 +</file>
 +
 +Cet extrait indique que :
 +
 +  * le répertoire /etc sera vérifié selon l'alias **ETC**,
 +  * le fichier /etc/mtab sera vérifié selon l'alias **ETC** à l'exception des règles **md5** et **s**,
 +  * le fichier /etc/adjtime sera vérifié selon l'alias **ETC** à l'exception de la règle **md5**.
 +
 +===Utilisation===
 +
 +Commencez par créer la base de données d'afick :
 +
 +<code>
 +[root@centos8 ~]# afick -i
 +# Afick (3.8.1) init at 2024/10/03 11:16:16 with options (/etc/afick.conf):
 +# archive:=/var/lib/afick/archive
 +# database:=/var/lib/afick/afick
 +# exclude_prefix:=__pycache__
 +# exclude_suffix:=log LOG html htm HTM txt TXT xml hlp pod chm tmp old bak fon ttf TTF bmp BMP jpg JPG gif png ico wav WAV mp3 avi pyc
 +# history:=/var/lib/afick/history
 +# max_checksum_size:=10000000
 +# running_files:=1
 +# timing:=1
 +# dbm:=Storable
 +# #################################################################
 +# MD5 hash of /var/lib/afick/afick => iYqXZ6neFdA/2qBYQPPDcg
 +
 +# Hash database created successfully. 46551 files entered.
 +# user time : 18.88; system time : 6.49; real time : 117
 +</code>
 +
 +Au moment où vous souhaitez vérifier l'intégrité de votre système de fichiers, utilisez la commende suivante :
 +
 +  * **afick -k**
 +
 +En cas de modifications, celles-ci vous seront clairement indiquées.
 +
 +Il est aussi nécessaire de mettre à jour votre base de données chaque fois que vous installez un nouveau paquet ou que vous mettez à jour un paquet déjà installé. Dans ce cas, utilisez la commande suivante :
 +
 +  * **afick -u**
 +
 +===Automatiser Afick===
 +
 +Lors de l'installation d'afick, le fichier **afick_cron** a été copié dans le répertoire /etc/cron.daily :
 +
 +<code>
 +[root@centos8 ~]# cat /etc/cron.daily/afick_cron
 +#!/usr/bin/env sh
 +###############################################################################
 +#   afick_cron
 +#      it's a part of the afick project
 +#
 +#    Copyright (C) 2002, 2003 by Eric Gerbier
 +#    Bug reports to: eric.gerbier@tutanota.com
 +#    $Id$
 +#
 +#    This program is free software; you can redistribute it and/or modify
 +#    it under the terms of the GNU General Public License as published by
 +#    the Free Software Foundation; either version 2 of the License, or
 +#    (at your option) any later version.
 +#
 +#    This program is distributed in the hope that it will be useful,
 +#    but WITHOUT ANY WARRANTY; without even the implied warranty of
 +#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 +#    GNU General Public License for more details.
 +#
 +###############################################################################
 +# script for cron job
 +# this script use the "macro" lines of afick configuration file
 +# the goals are :
 +# - set the nice priority
 +# - truncate too long reports to avoid big mails
 +# - avoid mails if no changes detected
 +# - sent report to the specicified email adress
 +# - write reports to /var/log/afick
 +# - archive retention management
 +
 +AFICK="/usr/bin/afick.pl"
 +PATH="/bin:/usr/bin"
 +LOGDIR="/var/log/afick"
 +LOGFILE="$LOGDIR/afick.log"
 +ERRORLOG="$LOGDIR/error.log"
 +CONFFILE="/etc/afick.conf"
 +
 +# the default action is "update" (-u), you can also use "compare" (-k)
 +ACTION="-u"
 +
 +###############################################################################
 +treat_log() {
 +        if [ -n "$VERBOSE_AFICK" ]
 +        then
 +                echo "# This is an automated report generated by Another File Integrity Checker on $FQDN $DATE."
 +        fi
 +
 +        # "normal" afick output : changes result
 +        if [ -s $LOGFILE ]; then
 +                loglines=`wc -l $LOGFILE | awk '{ print $1 }'`
 +                if [ ${loglines:=0} -gt $LINES ]; then
 +                        echo "# TRUNCATED (!) output of the daily afick run:"
 +                        echo "# Output is $loglines lines, truncated to $LINES."
 +                        head -$LINES $LOGFILE
 +                        echo "# The full output can be found in $LOGFILE."
 +                else
 +                        echo "# Output of the daily afick run:"
 +                        cat $LOGFILE
 +                fi
 +        elif [ -n "$VERBOSE_AFICK" ]
 +        then
 +                echo "# afick detected no changes."
 +        fi
 +
 +        # afick errors
 +        if [ -s $ERRORLOG ]; then
 +                errorlines=`wc -l $ERRORLOG | awk '{ print $1 }'`
 +                if [ ${errorlines:=0} -gt $LINES ]; then
 +                        echo "# TRUNCATED (!) output of errors produced:"
 +                        echo "# Error output is $errorlines lines, truncated to $LINES."
 +                        head -$LINES $ERRORLOG
 +                        echo "# The full output can be found in $ERRORLOG."
 +                else
 +                        echo "# Errors produced:"
 +                        cat $ERRORLOG
 +                fi
 +        elif [ -n "$VERBOSE_AFICK" ]
 +        then
 +                echo "# afick produced no errors."
 +        fi
 +
 +        # check end of report (summary)
 +        if [ -s $LOGFILE ]; then
 +                summary=` grep "MD5 hash of" $LOGFILE `
 +                if [ -z "$summary" ]
 +                then
 +                        echo "WARNING: truncated report (no summary)"
 +                fi
 +        fi
 +
 +}
 +###############################################################################
 +# extract macro value from config file
 +macro () {
 +        key=$1
 +        grep -m 1 "^@@define $key" $CONFFILE |  sed -e "s/^@@define $key *//"
 +}
 +###############################################################################
 +send_mail() {
 +        echo "$OUTPUT" | mail -s "[AFICK] Daily report for $FQDN" $MAILTO
 +}
 +###############################################################################
 +send_nagios() {
 +        NAGIOS_STATUS=3 # UNKNOWN initial status
 +        if [ -s $LOGFILE ]
 +        then
 +                NAGIOS_MSG=`tail -4 $LOGFILE | head -1 | sed -e "s/^[^0-9]*\(.*changed\) (.*$/\1/ "`
 +                NUM_CHANGES=`echo $NAGIOS_MSG | cut -d " " -f 4`
 +                if [ $NUM_CHANGES -gt 0 ]
 +                then
 +                        if [ $NUM_CHANGES -ge $NAGIOS_CRITICAL_CHANGES ]
 +                        then
 +                                NAGIOS_STATUS=2 # CRITICAL
 +                        else
 +                                NAGIOS_STATUS=1 # WARNING
 +                        fi
 +                else
 +                        NAGIOS_STATUS=0 # OK
 +                fi
 +        fi
 +        HOST=`hostname`
 +        echo "${HOST}\t${NAGIOS_CHECK_NAME}\t${NAGIOS_STATUS}\t${NAGIOS_MSG}\n" | $NAGIOS_NSCA -H $NAGIOS_SERVER -c $NAGIOS_CONFIG >/dev/null
 +}
 +###############################################################################
 +# MAIN
 +###############################################################################
 +
 +[ -x $AFICK ] || exit 0
 +
 +# hostname -f only exists on GNU systems, 
 +# on others (HPUX, AIX, Solaris, Tru64), it return an error on stderr 
 +# and a usage message on stdout
 +FQDN=`( hostname -f  || hostname ) 2>/dev/null |tail -1`
 +DATE=`date +"at %X on %x"`
 +MAILTO=`macro MAILTO`
 +LINES=`macro LINES`
 +VERBOSE=`macro VERBOSE`
 +REPORT=`macro REPORT`
 +NICE=`macro NICE`
 +BATCH=`macro BATCH`
 +MOUNT=`macro MOUNT`
 +NAGIOS=`macro NAGIOS`
 +NAGIOS_SERVER=`macro NAGIOS_SERVER`
 +NAGIOS_CONFIG=`macro NAGIOS_CONFIG`
 +NAGIOS_CHECK_NAME=`macro NAGIOS_CHECK_NAME`
 +NAGIOS_CRITICAL_CHANGES=`macro NAGIOS_CRITICAL_CHANGES`
 +NAGIOS_NSCA=`macro NAGIOS_NSCA`
 +ARCHIVE_RETENTION=`macro ARCHIVE_RETENTION`
 +
 +# default values
 +[ -z "$FQDN" ] && FQDN=`hostname`
 +[ -z "$MAILTO" ] && MAILTO="root"
 +[ -z "$LINES" ] && LINES="1000"
 +[ -z "$VERBOSE" ] && VERBOSE=0
 +[ -z "$REPORT" ] && REPORT=1
 +[ -z "$NICE" ] && NICE=15
 +[ -z "$BATCH" ] && BATCH=1
 +[ -z "$NAGIOS" ] && NAGIOS=0
 +[ -z "$NAGIOS_SERVER" ] && NAGIOS="localhost"
 +[ -z "$NAGIOS_CONFIG" ] && NAGIOS_CONFIG="/etc/send_nsca.cfg"
 +[ -z "$NAGIOS_CHECK_NAME" ] && NAGIOS_CHECK_NAME="Another File Integrity Checker"
 +[ -z "$NAGIOS_CRITICAL_CHANGES" ] && NAGIOS_CRITICAL_CHANGES=2
 +[ -z "$NAGIOS_NCSA" ] && NAGIOS_NCSA="/usr/sbin/send_nsca"
 +[ -z "$ARCHIVE_RETENTION" ] && ARCHIVE_RETENTION=0
 +
 +#echo "MAILTO=$MAILTO LINES=$LINES VERBOSE=$VERBOSE NICE=$NICE BATCH=$BATCH"
 +
 +if [ "$BATCH" = "0" ]
 +then
 +        exit 0
 +fi
 +
 +if [ "$VERBOSE" = "1" ]
 +then
 +        # verbose mail
 +        export VERBOSE_AFICK=1
 +fi
 +
 +# the mount point must be already defined in /etc/fstab
 +if [ -n "$MOUNT" ]
 +then
 +        mount $MOUNT
 +fi
 +
 +# launch command
 +nice -n $NICE $AFICK -c $CONFFILE $ACTION > $LOGFILE 2> $ERRORLOG
 +
 +# archive retention
 +if [ "$ARCHIVE_RETENTION" != "0" ]
 +then
 +        echo "###############" >> $LOGFILE
 +        echo "# afick_archive" >> $LOGFILE
 +        /usr/bin/afick_archive.pl -c $CONFFILE -H -k $ARCHIVE_RETENTION >> $LOGFILE 2>> $ERRORLOG
 +fi
 +
 +if [ -n "$MOUNT" ]
 +then
 +        umount $MOUNT
 +fi
 +
 +# nagios ?
 +if [ "$NAGIOS" = "1" ]
 +then
 +        send_nagios
 +fi
 +
 +if [ "$REPORT" = "0" ]
 +then
 +        # no report
 +        exit
 +fi
 +
 +# filter output to send by mail
 +OUTPUT=`treat_log`
 +if [ "$VERBOSE" = "1" ]
 +then
 +        send_mail
 +else
 +        # skip comments and empty lines
 +        OUTPUT_FILTRE=`echo "$OUTPUT" | grep -v "^#" | grep -v "^$"`
 +        if [ -n "$OUTPUT_FILTRE" ]
 +        then
 +                send_mail
 +        fi
 +fi
 +</code>
 +
 +Ce fichier permet d'intégrer Afick dans les tâches gérées par **cron**. Entre autre, il envoie un résumé par email à **root**.
 +
 +L'adresse email à utiliser peut être modifiée dans la section **macros section** du fichier **/etc/afick.conf** :
 +
 +<file>
 +#################
 +# macros section
 +#################
 +# used by cron job (afick_cron)
 +# define the mail adress to send cron job result
 +@@define MAILTO root@localhost
 +# truncate the result sended by mail to the number of lines (avoid too long mails)
 +@@define LINES 1000
 +# REPORT = 1 to enable mail reports, =0 to disable report
 +@@define REPORT 1
 +# VERBOSE = 1 to have one mail by run, =0 to have a mail only if changes are detected
 +@@define VERBOSE 0
 +# define the nice value : from 0 to 19 (priority of the job)
 +@@define NICE 18
 +# = 1 to allow cron job, = 0 to suppress cron job
 +@@define BATCH 1
 +# (optionnal, for unix) specify a file system to mount before the scan
 +# it must be defined in /etc/fstab
 +#@@define MOUNT /mnt/dist
 +# if set to 0, keep all archives, else define the number of days to keep
 +# with the syntaxe nS , n for a number, S for the scale
 +# (d for day, w for week, m for month, y for year)
 +# ex : for 5 months : 5m
 +@@define ARCHIVE_RETENTION 0
 +
 +# send nagios messages by NSCA (= 1 to allow, = 0 to block)
 +@@define NAGIOS 0
 +# address of the nagios server to send messages to
 +@@define NAGIOS_SERVER my.nagios.server.org
 +# NSCA configuration file
 +# @@define NAGIOS_CONFIG /etc/send_nsca.cfg
 +# name used for nagios passive check on the nagios server side
 +@@define NAGIOS_CHECK_NAME Another File Integrity Checker
 +# number c of the changes that are considered critical => nagios state CRITICAL
 +# (0 changes => nagios state OK; 0> and <c changes => nagios state WARNING)
 +@@define NAGIOS_CRITICAL_CHANGES 2
 +# path to nsca binary
 +# @@define NAGIOS_NSCA /usr/sbin/send_nsca
 +</file>
 +
 +====Root Kits====
 +
 +Un **rootkit** est un paquet logiciel qui permet à un utilisateur non-autorisé d'obtenir les droits de **root**. 
 +
 +Les rootkits sont essentiellement de deux types, voire un mélange des deux :
 +
 +  * des modules du noyau,
 +  * des paquets logiciels d'un utilisateur qui prennent la place de binaires système.
 +
 +Les rootkits de type modules du noyau insèrent des modules qui remplacent des appels systèmes et cachent des informations concernant certains processus spécifiques.
 +
 +Les rootkits de type paquets logiciels remplacement en règle générale des binaires système tels **ps**, **login** etc. Les binaires de remplacement cachent des processus et des répertoires de l'attaquant.
 +
 +===LAB #8 - Mise en place de rkhunter===
 +
 +**rkhunter** est un logiciel utilisé pour détecter les rootkits présents sur votre machine.
 +
 +==Installation==
 +
 +L'installation de rkhunter se fait simplement en utilisant yum :
 +
 +<code>
 +[root@centos8 ~]# dnf install rkhunter
 +</code>
 +
 +==Les options de la commande==
 +
 +Les options de cette commande sont :
 +
 +<code>
 +[root@centos8 ~]# rkhunter --help
 +
 +Usage: rkhunter {--check | --unlock | --update | --versioncheck |
 +                 --propupd [{filename | directory | package name},...] |
 +                 --list [{tests | {lang | languages} | rootkits | perl | propfiles}] |
 +                 --config-check | --version | --help} [options]
 +
 +Current options are:
 +         --append-log                  Append to the logfile, do not overwrite
 +         --bindir <directory>...       Use the specified command directories
 +     -c, --check                       Check the local system
 +     -C, --config-check                Check the configuration file(s), then exit
 +  --cs2, --color-set2                  Use the second color set for output
 +         --configfile <file>           Use the specified configuration file
 +         --cronjob                     Run as a cron job
 +                                       (implies -c, --sk and --nocolors options)
 +         --dbdir <directory>           Use the specified database directory
 +         --debug                       Debug mode
 +                                       (Do not use unless asked to do so)
 +         --disable <test>[,<test>...]  Disable specific tests
 +                                       (Default is to disable no tests)
 +         --display-logfile             Display the logfile at the end
 +         --enable  <test>[,<test>...]  Enable specific tests
 +                                       (Default is to enable all tests)
 +         --hash {MD5 | SHA1 | SHA224 | SHA256 | SHA384 | SHA512 |
 +                 NONE | <command>    Use the specified file hash function
 +                                       (Default is SHA256)
 +     -h, --help                        Display this help menu, then exit
 + --lang, --language <language>         Specify the language to use
 +                                       (Default is English)
 +         --list [tests | languages |   List the available test names, languages,
 +                 rootkits | perl |     rootkit names, perl module status
 +                 propfiles]            or file properties database, then exit
 +     -l, --logfile [file]              Write to a logfile
 +                                       (Default is /var/log/rkhunter.log)
 +         --noappend-log                Do not append to the logfile, overwrite it
 +         --nocf                        Do not use the configuration file entries
 +                                       for disabled tests (only valid with --disable)
 +         --nocolors                    Use black and white output
 +         --nolog                       Do not write to a logfile
 +--nomow, --no-mail-on-warning          Do not send a message if warnings occur
 +   --ns, --nosummary                   Do not show the summary of check results
 + --novl, --no-verbose-logging          No verbose logging
 +         --pkgmgr {RPM | DPKG | BSD |  Use the specified package manager to obtain
 +                   BSDng | SOLARIS |   or verify file property values.
 +                   NONE}               (Default is NONE)
 +         --propupd [file | directory | Update the entire file properties database,
 +                    package]...        or just for the specified entries
 +     -q, --quiet                       Quiet mode (no output at all)
 +  --rwo, --report-warnings-only        Show only warning messages
 +   --sk, --skip-keypress               Don't wait for a keypress after each test
 +         --summary                     Show the summary of system check results
 +                                       (This is the default)
 +         --syslog [facility.priority]  Log the check start and finish times to syslog
 +                                       (Default level is authpriv.notice)
 +         --tmpdir <directory>          Use the specified temporary directory
 +         --unlock                      Unlock (remove) the lock file
 +         --update                      Check for updates to database files
 +   --vl, --verbose-logging             Use verbose logging (on by default)
 +     -V, --version                     Display the version number, then exit
 +         --versioncheck                Check for latest version of program
 +     -x, --autox                       Automatically detect if X is in use
 +     -X, --no-autox                    Do not automatically detect if X is in use
 +</code>
 +
 +==Utilisation==
 +
 +Lancez **rkhunter** simplement en appelant son exécutable. A l'issu de son exécution, vous observerez un résumé :
 +
 +<code>
 +[root@centos7 ~]# rkhunter -c
 +...
 +System checks summary
 +=====================
 +
 +File properties checks...
 +    Required commands check failed
 +    Files checked: 137
 +    Suspect files: 4
 +
 +Rootkit checks...
 +    Rootkits checked : 498
 +    Possible rootkits: 0
 +
 +Applications checks...
 +    All checks skipped
 +
 +The system checks took: 2 minutes and 10 seconds
 +
 +All results have been written to the log file: /var/log/rkhunter/rkhunter.log
 +
 +One or more warnings have been found while checking the system.
 +Please check the log file (/var/log/rkhunter/rkhunter.log)
 +</code>
 +
 +==Configuration==
 +
 +**rkhunter** peut être configuré soit par des options sur la ligne de commande soit par l'édition de son fichier de configuration **/etc/rkhunter.conf**.
  
 ----- -----
 Copyright © 2024 Hugh Norris. Copyright © 2024 Hugh Norris.
Menu