Ceci est une ancienne révision du document !


APPARMOR

Version : 2026.01

Dernière mise-à-jour : 2025/12/01 08:05

LDF405 - System Hardening

Contenu du Module

  • LDF405 - System Hardening
    • Contenu du Module
    • System Hardening Manuel
      • Les compilateurs
      • Les paquets
      • Les démons et services
      • Les fichiers .rhosts
      • Les fichiers et les répertoires sans propriétaire
      • Interdire les connexions de root via le réseau
      • Limiter le delai d’inactivité d'une session shell
      • Renforcer la sécurité d'init
        • Les Distributions SysVInit
        • Les Distributions Upstart
      • Renforcer la sécurité du Noyau
        • La commande sysctl
    • LAB #1 - System Hardening à l'aide de l'outil Lynis
      • 1.1 - Présentation
      • 1.2 - Installation
      • 1.3 - Utilisation
    • LAB #2 - Mise en place de AppArmor pour sécuriser le serveur
    • LAB #3 - Travailler avec AppArmor
    • LAB #4 - Mise en place de SELinux pour sécuriser le serveur
      • 4.1 - Introduction
      • 4.2 - Définitions
        • Security Context
        • Domains et Types
        • Roles
        • Politiques de Sécurité
        • Langage de Politiques
          • allow
          • type
        • type_transition
        • Décisions de SELinux
          • Décisions d'Accès
          • Décisions de Transition
      • 4.3 - Commandes SELinux
      • 4.4 - Les Etats de SELinux
      • 4.5 - Booléens
    • LAB #5 - Travailler avec SELinux
      • 5.1 - Copier et Déplacer des Fichiers
      • 5.2 - Vérifier les SC des Processus
      • 5.3 - Visualiser la SC d'un Utilisateur
      • 5.4 - Vérifier la SC d'un fichier
      • 5.5 - Troubleshooting SELinux
        • La commande chcon
        • La commande restorecon
      • 5.6 - Le fichier /.autorelabel
      • 5.7 - La commande semanage
      • 5.8 - La commande audit2allow

System Hardening Manuel

Les compilateurs

Afin d'empêcher un pirate de créer des exécutables sur le serveur vous devez modifier les permissions sur les compilateurs éventuellement présents afin que seulement root puisse les exécuter.

Les paquets

Il convient dans ce cas de passer en revue la liste des paquets installés puis de supprimer ceux qui sont jugés être inutiles :

root@debian12:~# dpkg --get-selections | more
acl                                             install
adduser                                         install
adwaita-icon-theme                              install
afick                                           install
afick-gui                                       deinstall
alsa-topology-conf                              install
alsa-ucm-conf                                   install
alsa-utils                                      install
anacron                                         install
apache2                                         install
apache2-bin                                     install
apache2-data                                    install
apache2-utils                                   install
apparmor                                        install
apt                                             install
apt-listchanges                                 install
apt-utils                                       install
aspell                                          install
aspell-en                                       install
at-spi2-common                                  install
at-spi2-core                                    install
atril                                           install
atril-common                                    install
--More--

Important : Avec une distribution basée sur RedHat, utilisez la commande rpm -qa | more.

Les démons et services

Il convient dans ce cas de passer en revue la liste des démons et services actives puis de supprimer ceux qui sont jugés être inutiles;

  • ps aux
  • systemctl list-unit-files
  • chkconfig –list ( pour les systèmes n'utilisant pas systemd )
root@debian12:~# ps aux | more
USER         PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root           1  0.0  0.0 168564 13040 ?        Ss   Nov26   0:09 /sbin/init
root           2  0.0  0.0      0     0 ?        S    Nov26   0:00 [kthreadd]
root           3  0.0  0.0      0     0 ?        I<   Nov26   0:00 [rcu_gp]
root           4  0.0  0.0      0     0 ?        I<   Nov26   0:00 [rcu_par_gp]
root           5  0.0  0.0      0     0 ?        I<   Nov26   0:00 [slub_flushwq]
root           6  0.0  0.0      0     0 ?        I<   Nov26   0:00 [netns]
root           8  0.0  0.0      0     0 ?        I<   Nov26   0:00 [kworker/0:0H-events_highpri]
root          10  0.0  0.0      0     0 ?        I<   Nov26   0:00 [mm_percpu_wq]
root          11  0.0  0.0      0     0 ?        I    Nov26   0:00 [rcu_tasks_kthread]
root          12  0.0  0.0      0     0 ?        I    Nov26   0:00 [rcu_tasks_rude_kthread]
root          13  0.0  0.0      0     0 ?        I    Nov26   0:00 [rcu_tasks_trace_kthread]
root          14  0.0  0.0      0     0 ?        S    Nov26   0:00 [ksoftirqd/0]
root          15  0.0  0.0      0     0 ?        I    Nov26   0:01 [rcu_preempt]
root          16  0.0  0.0      0     0 ?        S    Nov26   0:01 [migration/0]
root          18  0.0  0.0      0     0 ?        S    Nov26   0:00 [cpuhp/0]
root          19  0.0  0.0      0     0 ?        S    Nov26   0:00 [cpuhp/1]
root          20  0.0  0.0      0     0 ?        S    Nov26   0:02 [migration/1]
root          21  0.0  0.0      0     0 ?        S    Nov26   0:00 [ksoftirqd/1]
root          23  0.0  0.0      0     0 ?        I<   Nov26   0:00 [kworker/1:0H-events_highpri]
root          24  0.0  0.0      0     0 ?        S    Nov26   0:00 [cpuhp/2]
root          25  0.0  0.0      0     0 ?        S    Nov26   0:02 [migration/2]
root          26  0.0  0.0      0     0 ?        S    Nov26   0:00 [ksoftirqd/2]
root          28  0.0  0.0      0     0 ?        I<   Nov26   0:00 [kworker/2:0H-events_highpri]
root          29  0.0  0.0      0     0 ?        S    Nov26   0:00 [cpuhp/3]
root          30  0.0  0.0      0     0 ?        S    Nov26   0:02 [migration/3]
root          31  0.0  0.0      0     0 ?        S    Nov26   0:00 [ksoftirqd/3]
root          33  0.0  0.0      0     0 ?        I<   Nov26   0:00 [kworker/3:0H-events_highpri]
root          34  0.0  0.0      0     0 ?        S    Nov26   0:00 [cpuhp/4]
root          35  0.0  0.0      0     0 ?        S    Nov26   0:02 [migration/4]
root          36  0.0  0.0      0     0 ?        S    Nov26   0:00 [ksoftirqd/4]
root          38  0.0  0.0      0     0 ?        I<   Nov26   0:00 [kworker/4:0H-events_highpri]
root          39  0.0  0.0      0     0 ?        S    Nov26   0:00 [cpuhp/5]
root          40  0.0  0.0      0     0 ?        S    Nov26   0:02 [migration/5]
root          41  0.0  0.0      0     0 ?        S    Nov26   0:00 [ksoftirqd/5]
root          43  0.0  0.0      0     0 ?        I<   Nov26   0:00 [kworker/5:0H-events_highpri]
root          44  0.0  0.0      0     0 ?        S    Nov26   0:00 [cpuhp/6]
root          45  0.0  0.0      0     0 ?        S    Nov26   0:02 [migration/6]
root          46  0.0  0.0      0     0 ?        S    Nov26   0:00 [ksoftirqd/6]
root          48  0.0  0.0      0     0 ?        I<   Nov26   0:00 [kworker/6:0H-events_highpri]
root          49  0.0  0.0      0     0 ?        S    Nov26   0:00 [cpuhp/7]
root          50  0.0  0.0      0     0 ?        S    Nov26   0:02 [migration/7]
root          51  0.0  0.0      0     0 ?        S    Nov26   0:00 [ksoftirqd/7]
root          53  0.0  0.0      0     0 ?        I<   Nov26   0:00 [kworker/7:0H-events_highpri]
root          62  0.0  0.0      0     0 ?        S    Nov26   0:00 [kdevtmpfs]
root          63  0.0  0.0      0     0 ?        I<   Nov26   0:00 [inet_frag_wq]
root          64  0.0  0.0      0     0 ?        S    Nov26   0:00 [kauditd]
root          65  0.0  0.0      0     0 ?        S    Nov26   0:00 [khungtaskd]
root          66  0.0  0.0      0     0 ?        S    Nov26   0:00 [oom_reaper]
root          67  0.0  0.0      0     0 ?        I<   Nov26   0:00 [writeback]
root          68  0.0  0.0      0     0 ?        S    Nov26   0:12 [kcompactd0]
root          69  0.0  0.0      0     0 ?        SN   Nov26   0:00 [ksmd]
root          70  0.0  0.0      0     0 ?        SN   Nov26   0:02 [khugepaged]
root          71  0.0  0.0      0     0 ?        I<   Nov26   0:00 [kintegrityd]
root          72  0.0  0.0      0     0 ?        I<   Nov26   0:00 [kblockd]
--More--
root@debian12:~# systemctl list-unit-files | more
UNIT FILE                                                                 STATE           PRESET
proc-sys-fs-binfmt_misc.automount                                         static          -
-.mount                                                                   generated       -
dev-hugepages.mount                                                       static          -
dev-mqueue.mount                                                          static          -
media-cdrom0.mount                                                        generated       -
proc-sys-fs-binfmt_misc.mount                                             disabled        disabled
snap-core-17247.mount                                                     enabled         enabled
snap-core24-1225.mount                                                    enabled         enabled
snap-john\x2dthe\x2dripper-706.mount                                      enabled         enabled
snap-snapd-25577.mount                                                    enabled         enabled
sys-fs-fuse-connections.mount                                             static          -
sys-kernel-config.mount                                                   static          -
sys-kernel-debug.mount                                                    static          -
sys-kernel-tracing.mount                                                  static          -
cups.path                                                                 enabled         enabled
systemd-ask-password-console.path                                         static          -
systemd-ask-password-plymouth.path                                        static          -
systemd-ask-password-wall.path                                            static          -
session-100.scope                                                         transient       -
session-11.scope                                                          transient       -
session-112.scope                                                         transient       -
session-18.scope                                                          transient       -
session-c1.scope                                                          transient       -
alsa-restore.service                                                      static          -
alsa-state.service                                                        static          -
alsa-utils.service                                                        masked          enabled
anacron.service                                                           enabled         enabled
apache-htcacheclean.service                                               disabled        enabled
apache-htcacheclean@.service                                              disabled        enabled
apache2.service                                                           enabled         enabled
apache2@.service                                                          disabled        enabled
apparmor.service                                                          enabled         enabled
apt-daily-upgrade.service                                                 static          -
apt-daily.service                                                         static          -
autovt@.service                                                           alias           -
avahi-daemon.service                                                      enabled         enabled
colord.service                                                            static          -
configure-printer@.service                                                static          -
console-getty.service                                                     disabled        disabled
console-setup.service                                                     enabled         enabled
container-getty@.service                                                  static          -
cron.service                                                              enabled         enabled
cryptdisks-early.service                                                  masked          enabled
cryptdisks.service                                                        masked          enabled
cups-browsed.service                                                      enabled         enabled
cups.service                                                              enabled         enabled
dbus-fi.w1.wpa_supplicant1.service                                        alias           -
dbus-org.fedoraproject.FirewallD1.service                                 alias           -
dbus-org.freedesktop.Avahi.service                                        alias           -
dbus-org.freedesktop.hostname1.service                                    alias           -
dbus-org.freedesktop.locale1.service                                      alias           -
dbus-org.freedesktop.login1.service                                       alias           -
dbus-org.freedesktop.ModemManager1.service                                alias           -
dbus-org.freedesktop.nm-dispatcher.service                                alias           -
--More--

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:

# find / -name "\.rhosts" -exec rm -f \{\} \; [Entree]

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:

# find / -nouser -exec ls -l \{\} \; 2> sans_pro.txt [Entree]
# find / -nogroup -exec ls -l \{\} \; 2>> sans_pro.txt[Entree]

Ces commandes produiront une liste éventuelle dans le fichier sans_pro.txt.

L'examen de cette liste pourrait dévoiler des anomalies au quel cas il conviendrait de:

  • modifier le propriétaire a root
  • modifier le groupe a root
  • modifier les permissions a 700

Interdire les connexions de root via le reseau

Le fichier de configuration des connexions de root est /etc/securetty :

root@debian12:~# vi /etc/securetty

root@debian12:~# cat /etc/securetty
# Virtual Consoles (local access)
tty1
tty2
tty3
tty4
tty5
tty6

# System Console (rarely needed for direct root login)
console

Important : Afin d'empêcher une connexion de root directement via le réseau et donc d'obliger une connexion en utilisant un compte d'utilisateur normal avant de passer en root grâce à la commande su, ce fichier ne doit pas contenir des entrees du type ttysX ou X = 0,1,2 etc. Un fichier /etc/securetty vide empechera toute connexion directe de l'utilisateur root. Notez que le fichier /etc/securetty n'a aucune incidence sur les connexions SSH.

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 securite. Verifiez donc le contenu du fichier /etc/profile :

root@debian12:~# cat /etc/profile
# /etc/profile: system-wide .profile file for the Bourne shell (sh(1))
# and Bourne compatible shells (bash(1), ksh(1), ash(1), ...).

if [ "$(id -u)" -eq 0 ]; then
  PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
else
  PATH="/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games"
fi
export PATH

if [ "${PS1-}" ]; then
  if [ "${BASH-}" ] && [ "$BASH" != "/bin/sh" ]; then
    # The file bash.bashrc already sets the default PS1.
    # PS1='\h:\w\$ '
    if [ -f /etc/bash.bashrc ]; then
      . /etc/bash.bashrc
    fi
  else
    if [ "$(id -u)" -eq 0 ]; then
      PS1='# '
    else
      PS1='$ '
    fi
  fi
fi

if [ -d /etc/profile.d ]; then
  for i in /etc/profile.d/*.sh; do
    if [ -r $i ]; then
      . $i
    fi
  done
  unset i
fi

A ce fichier doivent etre ajoutées les deux lignes suivantes:

readonly TMOUT=300
export TMOUT

Par cette action, vous définissez le délai d’inactivité d'une session shell a une durée de 5 minutes.

Dernièrement, afin de se protéger contre des permissions trop permissives lors de la création de fichiers et de répertoires, il convient de passer la valeur d'umask à 077 dans le fichier /etc/login.defs.

Renforcer la securite d'init

Les Distributions SysVInit

Le fichier /etc/inittab est utilise pour configurer le démarrage de votre serveur.

La première modification à effectuer est de spécifier le niveau d’exécution par défaut a 3 au lieu de 5. Ceci permet de ne pas lancer les sessions graphiques sur une serveur de production. Cherchez donc la ligne suivante:

id:5:initdefault:

Modifiez-la en:

id:3:initdefault:

Le mode single user de démarrage de Linux n'est pas habituellement protégé par un mot de passe. Afin de remédier a cela, ajoutez les lignes suivantes:

# Single user mode
~~:S:wait:/sbin/sulogin

Dernièrement, afin d'empêcher une personne a redémarrer le serveur à l'aide des touches ctrl+alt+supp, il convient de mettre en commentaire la ligne correspondante:

# ca::ctrlaltdel:/sbin/shutdown -t3 -r now

Les Distributions Upstart

Afin d'empêcher une personne à redémarrer le serveur à l'aide des touches ctrl+alt+supp, éditez le fichier /etc/init/control-alt-delete.conf en modifiant la ligne suivante :

exec /sbin/shutdown -r now "Control-Alt-Delete pressed"

en

#exec /sbin/shutdown -k now "Control-Alt-Delete pressed"

Les Distributions Systemd

Afin d'empêcher une personne à redémarrer le serveur à l'aide des touches ctrl+alt+supp, saisissez la commande suivante :

# systemctl mask ctrl-alt-del.target

Renforcer la sécurité du Noyau

La commande sysctl

Les fichiers dans le répertoire /proc/sys peuvent être administrés par la commande sysctl en temps réel.

La commande sysctl applique les règles consignés dans le fichier /etc/sysctl.conf au démarrage de la machine.

Saisissez la commande :

root@debian12:~# cat /etc/sysctl.conf
#
# /etc/sysctl.conf - Configuration file for setting system variables
# See /etc/sysctl.d/ for additional system variables.
# See sysctl.conf (5) for information.
#

#kernel.domainname = example.com

# Uncomment the following to stop low-level messages on console
#kernel.printk = 3 4 1 3

###################################################################
# Functions previously found in netbase
#

# Uncomment the next two lines to enable Spoof protection (reverse-path filter)
# Turn on Source Address Verification in all interfaces to
# prevent some spoofing attacks
#net.ipv4.conf.default.rp_filter=1
#net.ipv4.conf.all.rp_filter=1

# Uncomment the next line to enable TCP/IP SYN cookies
# See http://lwn.net/Articles/277146/
# Note: This may impact IPv6 TCP sessions too
#net.ipv4.tcp_syncookies=1

# Uncomment the next line to enable packet forwarding for IPv4
#net.ipv4.ip_forward=1

# Uncomment the next line to enable packet forwarding for IPv6
#  Enabling this option disables Stateless Address Autoconfiguration
#  based on Router Advertisements for this host
#net.ipv6.conf.all.forwarding=1


###################################################################
# Additional settings - these settings can improve the network
# security of the host and prevent against some network attacks
# including spoofing attacks and man in the middle attacks through
# redirection. Some network environments, however, require that these
# settings are disabled so review and enable them as needed.
#
# Do not accept ICMP redirects (prevent MITM attacks)
#net.ipv4.conf.all.accept_redirects = 0
#net.ipv6.conf.all.accept_redirects = 0
# _or_
# Accept ICMP redirects only for gateways listed in our default
# gateway list (enabled by default)
# net.ipv4.conf.all.secure_redirects = 1
#
# Do not send ICMP redirects (we are not a router)
#net.ipv4.conf.all.send_redirects = 0
#
# Do not accept IP source route packets (we are not a router)
#net.ipv4.conf.all.accept_source_route = 0
#net.ipv6.conf.all.accept_source_route = 0
#
# Log Martian Packets
#net.ipv4.conf.all.log_martians = 1
#

###################################################################
# Magic system request Key
# 0=disable, 1=enable all, >1 bitmask of sysrq functions
# See https://www.kernel.org/doc/html/latest/admin-guide/sysrq.html
# for what other values do
#kernel.sysrq=438
Options de la commande

Les options de la commande sysctl sont :

root@debian12:~# sysctl --help

Usage:
 sysctl [options] [variable[=value] ...]

Options:
  -a, --all            display all variables
  -A                   alias of -a
  -X                   alias of -a
      --deprecated     include deprecated parameters to listing
      --dry-run        Print the key and values but do not write
  -b, --binary         print value without new line
  -e, --ignore         ignore unknown variables errors
  -N, --names          print variable names without values
  -n, --values         print only values of the given variable(s)
  -p, --load[=<file>]  read values from file
  -f                   alias of -p
      --system         read values from all system directories
  -r, --pattern <expression>
                       select setting that match expression
  -q, --quiet          do not echo variable set
  -w, --write          enable writing a value to variable
  -o                   does nothing
  -x                   does nothing
  -d                   alias of -h

 -h, --help     display this help and exit
 -V, --version  output version information and exit

For more details see sysctl(8).

Sections clefs de la sortie :

  • Indice de Renforcement (Hardening Index) : C'est un score qui indique le niveau de sécurité global de votre système. Un nombre plus élevé est meilleur, et votre objectif est d'augmenter ce score en abordant les suggestions.
  • Avertissements (Warnings) : Problèmes qui présentent un risque de sécurité potentiel et doivent être traités immédiatement (par exemple, logiciels obsolètes, mots de passe faibles).
  • Suggestions : Recommandations pour améliorer la configuration de sécurité de votre système (par exemple, meilleure rotation des journaux, renforcement du noyau). Chaque suggestion inclut un ID de test unique (par exemple, BANN-7126) et une URL pour plus d'informations.

Important : Consultez la page de la traduction du manuel de sysctl ici pour comprendre la commande.

LAB #1 - System Hardening à l'aide de l'outil Lynis

1.1 - Présentation

Lynis est un outil de renforcement de la sécurité pour certaines distributions de Linux dont RHEL, CentOS et Debian.

1.2 - Installation

Installez Lynis en utilisant APT :

root@debian12:~# apt install lynis

1.3 - Utilisation

Pour démarrez Lynis, saisissez la commande suivante :

root@debian12:~# lynis audit system

[ Lynis 3.0.8 ]

################################################################################
  Lynis comes with ABSOLUTELY NO WARRANTY. This is free software, and you are
  welcome to redistribute it under the terms of the GNU General Public License.
  See the LICENSE file for details about using this software.

  2007-2021, CISOfy - https://cisofy.com/lynis/
  Enterprise support available (compliance, plugins, interface and tools)
################################################################################


[+] Initializing program
------------------------------------
  - Detecting OS...                                           [ DONE ]
  - Checking profiles...                                      [ DONE ]

  ---------------------------------------------------
  Program version:           3.0.8
  Operating system:          Linux
  Operating system name:     Debian
  Operating system version:  12
  Kernel version:            6.1.0
  Hardware platform:         x86_64
  Hostname:                  debian12
  ---------------------------------------------------
  Profiles:                  /etc/lynis/default.prf
  Log file:                  /var/log/lynis.log
  Report file:               /var/log/lynis-report.dat
  Report version:            1.0
  Plugin directory:          /etc/lynis/plugins
  ---------------------------------------------------
  Auditor:                   [Not Specified]
  Language:                  en
  Test category:             all
  Test group:                all
  ---------------------------------------------------
  - Program update status...                                  [ NO UPDATE ]

[+] System tools
------------------------------------
  - Scanning available tools...
  - Checking system binaries...

[+] Plugins (phase 1)
------------------------------------
 Note: plugins have more extensive tests and may take several minutes to complete
  
  - Plugin: debian
    [
[+] Debian Tests
------------------------------------
  - Checking for system binaries that are required by Debian Tests...
    - Checking /bin...                                        [ FOUND ]
    - Checking /sbin...                                       [ FOUND ]
    - Checking /usr/bin...                                    [ FOUND ]
    - Checking /usr/sbin...                                   [ FOUND ]
    - Checking /usr/local/bin...                              [ FOUND ]
    - Checking /usr/local/sbin...                             [ FOUND ]
  - Authentication:
    - PAM (Pluggable Authentication Modules):
      - libpam-tmpdir                                         [ Not Installed ]
  - File System Checks:
    - DM-Crypt, Cryptsetup & Cryptmount:
  - Software:
    - apt-listbugs                                            [ Not Installed ]
    - apt-listchanges                                         [ Installed and enabled for apt ]
    - needrestart                                             [ Not Installed ]
    - fail2ban                                                [ Installed with jail.local ]
]

[+] Boot and services
------------------------------------
  - Service Manager                                           [ systemd ]
  - Checking UEFI boot                                        [ DISABLED ]
  - Checking presence GRUB2                                   [ FOUND ]
    - Checking for password protection                        [ NONE ]
  - Check running services (systemctl)                        [ DONE ]
        Result: found 27 running services
  - Check enabled services at boot (systemctl)                [ DONE ]
        Result: found 36 enabled services
  - Check startup files (permissions)                         [ OK ]
  - Running 'systemd-analyze security'
        - ModemManager.service:                               [ MEDIUM ]
        - NetworkManager.service:                             [ EXPOSED ]
        - anacron.service:                                    [ UNSAFE ]
        - apache-htcacheclean.service:                        [ UNSAFE ]
        - apache2.service:                                    [ UNSAFE ]
        - avahi-daemon.service:                               [ UNSAFE ]
        - cron.service:                                       [ UNSAFE ]
        - cups-browsed.service:                               [ UNSAFE ]
        - cups.service:                                       [ UNSAFE ]
        - dbus.service:                                       [ UNSAFE ]
        - emergency.service:                                  [ UNSAFE ]
        - fail2ban.service:                                   [ UNSAFE ]
        - firewalld.service:                                  [ UNSAFE ]
        - getty@tty1.service:                                 [ UNSAFE ]
        - lightdm.service:                                    [ UNSAFE ]
        - lynis.service:                                      [ UNSAFE ]
        - plymouth-start.service:                             [ UNSAFE ]
...
================================================================================

  Lynis security scan details:

  Hardening index : 64 [############        ]
  Tests performed : 259
  Plugins enabled : 1

  Components:
  - Firewall               [V]
  - Malware scanner        [X]

  Scan mode:
  Normal [V]  Forensics [ ]  Integration [ ]  Pentest [ ]

  Lynis modules:
  - Compliance status      [?]
  - Security audit         [V]
  - Vulnerability scan     [V]

  Files:
  - Test and debug information      : /var/log/lynis.log
  - Report data                     : /var/log/lynis-report.dat

================================================================================

  Lynis 3.0.8

  Auditing, system hardening, and compliance for UNIX-based systems
  (Linux, macOS, BSD, and others)

  2007-2021, CISOfy - https://cisofy.com/lynis/
  Enterprise support available (compliance, plugins, interface and tools)

================================================================================

  [TIP]: Enhance Lynis audits by adding your settings to custom.prf (see /etc/lynis/default.prf for all settings)

Le comportement de Lynis est configuré dans le fichier /etc/lynis/default.prf :

root@debian12:~# more /etc/lynis/default.prf
#################################################################################
#
#
# Lynis - Default scan profile
#
#
#################################################################################
#
#
# This profile provides Lynis with most of its initial values to perform a
# system audit.
#
#
# WARNINGS
# ----------
#
# Do NOT make changes to this file. Instead, copy only your changes into
# the file custom.prf and put it in the same directory as default.prf
#
# To discover where your profiles are located: lynis show profiles
#
#
# Lynis performs a strict check on profiles to avoid the inclusion of
# possibly harmful injections. See include/profiles for details.
#
#
#################################################################################
#
# All empty lines or with the # prefix will be skipped
#
#################################################################################

# Use colored output
colors=yes

# Compressed uploads (set to zero when errors with uploading occur)
compressed-uploads=yes

# Amount of connections in WAIT state before reporting it as a suggestion
#connections-max-wait-state=5000

# Debug mode (for debugging purposes, extra data logged to screen)
#debug=yes

# Show non-zero exit code when warnings are found
error-on-warnings=no

# Use Lynis in your own language (by default auto-detected)
language=

# Log tests from another guest operating system (default: yes)
#log-tests-incorrect-os=yes

# Define if available NTP daemon is configured as a server or client on the network
# values: server or client (default: client)
--More--(7%)

Lynis journalise sa sortie dans le fichier ∕var∕log∕lynis.log :

root@debian12:~# more /var/log/lynis.log
2025-11-30 07:51:41 Starting Lynis 3.0.8 with PID 10764, build date 2022-05-17
2025-11-30 07:51:41 ====
2025-11-30 07:51:41 ### 2007-2021, CISOfy - https://cisofy.com/lynis/ ###
2025-11-30 07:51:41 Checking permissions of /usr/share/lynis/include/profiles
2025-11-30 07:51:41 File permissions are OK
2025-11-30 07:51:41 Reading profile/configuration /etc/lynis/default.prf
2025-11-30 07:51:41 Action: created temporary file /tmp/lynis.BQ3mIliUFT
2025-11-30 07:51:41 Language set via profile to ''
2025-11-30 07:51:41 Plugin 'authentication' enabled according profile (/etc/lynis/default.prf)
2025-11-30 07:51:41 Plugin 'compliance' enabled according profile (/etc/lynis/default.prf)
2025-11-30 07:51:41 Plugin 'configuration' enabled according profile (/etc/lynis/default.prf)
2025-11-30 07:51:41 Plugin 'control-panels' enabled according profile (/etc/lynis/default.prf)
2025-11-30 07:51:41 Plugin 'crypto' enabled according profile (/etc/lynis/default.prf)
2025-11-30 07:51:41 Plugin 'dns' enabled according profile (/etc/lynis/default.prf)
2025-11-30 07:51:41 Plugin 'docker' enabled according profile (/etc/lynis/default.prf)
2025-11-30 07:51:41 Plugin 'file-integrity' enabled according profile (/etc/lynis/default.prf)
2025-11-30 07:51:41 Plugin 'file-systems' enabled according profile (/etc/lynis/default.prf)
2025-11-30 07:51:41 Plugin 'firewalls' enabled according profile (/etc/lynis/default.prf)
2025-11-30 07:51:41 Plugin 'forensics' enabled according profile (/etc/lynis/default.prf)
2025-11-30 07:51:41 Plugin 'hardware' enabled according profile (/etc/lynis/default.prf)
2025-11-30 07:51:41 Plugin 'intrusion-detection' enabled according profile (/etc/lynis/default.prf)
2025-11-30 07:51:41 Plugin 'intrusion-prevention' enabled according profile (/etc/lynis/default.prf)
2025-11-30 07:51:41 Plugin 'kernel' enabled according profile (/etc/lynis/default.prf)
2025-11-30 07:51:41 Plugin 'malware' enabled according profile (/etc/lynis/default.prf)
2025-11-30 07:51:41 Plugin 'memory' enabled according profile (/etc/lynis/default.prf)
2025-11-30 07:51:41 Plugin 'nginx' enabled according profile (/etc/lynis/default.prf)
2025-11-30 07:51:41 Plugin 'pam' enabled according profile (/etc/lynis/default.prf)
2025-11-30 07:51:41 Plugin 'processes' enabled according profile (/etc/lynis/default.prf)
2025-11-30 07:51:41 Plugin 'security-modules' enabled according profile (/etc/lynis/default.prf)
2025-11-30 07:51:41 Plugin 'software' enabled according profile (/etc/lynis/default.prf)
2025-11-30 07:51:41 Plugin 'system-integrity' enabled according profile (/etc/lynis/default.prf)
2025-11-30 07:51:41 Plugin 'systemd' enabled according profile (/etc/lynis/default.prf)
2025-11-30 07:51:41 Plugin 'users' enabled according profile (/etc/lynis/default.prf)
2025-11-30 07:51:42 Plugin 'debian' enabled according profile (/etc/lynis/default.prf)
2025-11-30 07:51:42 Set option to default value: NTPD_ROLE --> client
2025-11-30 07:51:42 ====
2025-11-30 07:51:42 EOL check: 255
2025-11-30 07:51:42 Note: the end-of-life of 'Debian GNU/Linux 12 (bookworm)' could not be checked. Entry missing in software-eol.db?
2025-11-30 07:51:42 Program version:           3.0.8
2025-11-30 07:51:42 Operating system:          Linux
2025-11-30 07:51:42 Operating system name:     Debian
2025-11-30 07:51:42 Operating system version:  12
2025-11-30 07:51:42 Kernel version:            6.1.0
2025-11-30 07:51:42 Kernel version (full):     6.1.0-41-amd64
2025-11-30 07:51:42 Hardware platform:         x86_64
2025-11-30 07:51:42 -----------------------------------------------------
2025-11-30 07:51:42 Hostname:                  debian12
2025-11-30 07:51:42 Auditor:                   [Not Specified]
2025-11-30 07:51:42 Profiles:                  /etc/lynis/default.prf
2025-11-30 07:51:42 Work directory:            /root
2025-11-30 07:51:42 Include directory:         /usr/share/lynis/include
2025-11-30 07:51:42 Plugin directory:          /etc/lynis/plugins
2025-11-30 07:51:42 -----------------------------------------------------
2025-11-30 07:51:42 Log file:                  /var/log/lynis.log
2025-11-30 07:51:42 Report file:               /var/log/lynis-report.dat
--More--(0%)

Dans le journal se trouve des suggestions pour durcir le système, par exemple :

root@debian12:~# cat /var/log/lynis.log | grep BANN-7126
2025-11-30 07:52:25 Performing test ID BANN-7126 (Check issue banner file contents)
2025-11-30 07:52:25 Suggestion: Add a legal banner to /etc/issue, to warn unauthorized users [test:BANN-7126] [details:-] [solution:-]
root@debian12:~# cat /var/log/lynis.log | grep FILE-7524
2025-11-30 07:52:47 Performing test ID FILE-7524 (Perform file permissions check)
2025-11-30 07:52:48 Suggestion: Consider restricting file permissions [test:FILE-7524] [details:See screen output or log file] [solution:text:Use chmod to change file permissions]

A l'issue de l'implémentation des suggestions, il convient d'exécuter de nouveau la commande lynis audit system.

A Faire - Passez en revue et implémentez les suggestions de Lynis.

LAB #4 - Mise en place de SELinux pour sécuriser le serveur

4.1 - Installation

Désactivez AppArmor :

root@debian12:~# systemctl disable apparmor --now
Synchronizing state of apparmor.service with SysV service script with /lib/systemd/systemd-sysv-install.
Executing: /lib/systemd/systemd-sysv-install disable apparmor
Removed "/etc/systemd/system/sysinit.target.wants/apparmor.service".

root@debian12:~# systemctl status apparmor
○ apparmor.service - Load AppArmor profiles
     Loaded: loaded (/lib/systemd/system/apparmor.service; disabled; preset: enabled)
     Active: inactive (dead) since Sun 2025-11-30 09:59:03 CET; 1min 30s ago
   Duration: 5d 48min 44.395s
       Docs: man:apparmor(7)
             https://gitlab.com/apparmor/apparmor/wikis/home/
    Process: 57991 ExecStop=/bin/true (code=exited, status=0/SUCCESS)
   Main PID: 322 (code=exited, status=0/SUCCESS)
        CPU: 1ms

Nov 25 09:10:18 debian12 apparmor.systemd[322]: Restarting AppArmor
Nov 25 09:10:18 debian12 apparmor.systemd[322]: Reloading AppArmor profiles
Nov 25 09:10:17 debian12 systemd[1]: Starting apparmor.service - Load AppArmor profiles...
Nov 25 09:10:19 debian12 systemd[1]: Finished apparmor.service - Load AppArmor profiles.
Nov 30 09:59:03 debian12 systemd[1]: Stopping apparmor.service - Load AppArmor profiles...
Nov 30 09:59:03 debian12 systemd[1]: apparmor.service: Deactivated successfully.
Nov 30 09:59:03 debian12 systemd[1]: Stopped apparmor.service - Load AppArmor profiles.

Installez SELinux :

root@debian12:~# apt install selinux-basics selinux-policy-default selinux-utils policycoreutils auditd -y
root@debian12:~# selinux-activate
Activating SE Linux
Generating grub configuration file ...
Found background image: /usr/share/images/desktop-base/desktop-grub.png
Found linux image: /boot/vmlinuz-6.1.0-41-amd64
Found initrd image: /boot/initrd.img-6.1.0-41-amd64
Found linux image: /boot/vmlinuz-5.10.0-36-amd64
Found initrd image: /boot/initrd.img-5.10.0-36-amd64
Warning: os-prober will not be executed to detect other bootable partitions.
Systems on them will not be added to the GRUB boot configuration.
Check GRUB_DISABLE_OS_PROBER documentation entry.
done
SE Linux is activated.  You may need to reboot now.

root@debian12:~# reboot

Important - La commande selinux-activate modifie la configuration de GRUB afin que SELinux soit activé au démarrage de la VM et crée ensuite le fichier /.autorelabel. Le fichier /.autorelabel force SELinux à étiqueter les fichiers, services, etc avec un Security Context.

Lors de votre reconnexion à la VM, saisissez la commande ls -l :

root@debian12:~# ls -l
total 3528
drwxr-xr-x. 3 root root    4096 Nov 25 15:16 attributs
-rw-r--r--. 1 root root       0 Nov 27 14:07 mypasswd

Important - Notez le caractère . à la fin du masque des permissions de chaque objet. Ceci implique que SELinux a étiqueté l'objet concerné.

4.2 - Introducton

L'approche SELinux (Security Enhanced Linux) à la sécurité est une approche de type TE. Elle essaie aussi d'intégrer les notions des approches de type RBAC, MAC et MLS sous la forme de MCS :

Type de Sécurité Nom Description
TE Type enforcement Chaque objet a une étiquette appelé type pour un fichier et domaine pour un processus. La politique de sécurité définit l'interaction entre les types et les domaines.
RBAC Role Based Access Control Un utilisateur a un ou plusieurs rôles. Les droits sont attribués aux rôles.
MAC Mandatory Access Control L'accès aux objets est en fonction de la classification de l'objet (Très secret, Secret, Confidentiel, Public). L'administrateur définit la politique de sécurité et les utilisateurs s'y conforment.
MLS Multi-Level Security Les politiques de sécurité imposent que qu'un sujet doit dominer un objet pour pouvoir le lire tandis que l'objet doit dominer le sujet pour que ce dernier puisse y écrire.

Même quand le modèle SELinux de sécurité est actif, la sécurité de type DAC est toujours active. Cependant dans le cas où la sécurité du type DAC autorise une action, SELinux va évaluer cette action par rapport à ses propres règles avant de l'autoriser. Pour résumer, SELinux prime sur les droits DAC.

SELinux évalue toujours des actions tentées par des sujets sur des objets.

Dans le contexte de SELinux :

  • un sujet est toujours un processus,
  • un objet peut être un fichier, un répertoire, un autre processus ou une ressource système,
  • une action est une permission.

Chaque classe d'objet possède un jeu de permissions possibles ou actions qui peuvent être uniques à la classe ou bien héritées d'autres classes.

4.3 - Définitions

Security Context

SELinux associe un Security Context (SC) à chaque objet et sujet du système.

Un SC prend la forme identité:rôle:type:niveau :

Nom Descriptions
Identité Le nom du propriétaire de l'objet. Une identité est associée à des rôles. Par défaut l'utilisateur à une identité de user_u.
Rôle Essentiellement appliqué aux processus, le rôle est appelé une domaine. Dans le cas d'un rôle de fichier, celui-ci est toujours object_r. Un rôle se termine généralement par _r.
Type Définit la classification de sécurité de l'objet. Un type se termine généralement par _t.
Niveau Un niveau est un attribut de MLS et MCS. Une plage MLS est une paire de niveaux exprimée en utilisant la syntaxe niveaubas-niveauhaut. Chaque niveau est une paire exprimée en tant que sensibilitéhaut-sensibilitébas:catégoriehaut:catégoriebas par exemple s0-s0:c0.c1023. Il est important de noter que s0-s0 s'exprime aussi s0 et c0, c1, c2, c3 est exprimé c0.c3.

Sous Debian, le fichier /etc/selinux/default/setrans.conf contient la correspondance entre les niveaux et leurs valeurs compréhensibles par l'utilisateur :

root@debian12:~# cat /etc/selinux/default/setrans.conf
#
# Multi-Category Security translation table for SELinux
# 
# Uncomment the following to disable translation libary
# disable=1
#
# Objects can be categorized with 0-1023 categories defined by the admin.
# Objects can be in more than one category at a time.
# Categories are stored in the system as c0-c1023.  Users can use this
# table to translate the categories into a more meaningful output.
# Examples:
# s0:c0=CompanyConfidential
# s0:c1=PatientRecord
# s0:c2=Unclassified
# s0:c3=TopSecret
# s0:c1,c3=CompanyConfidentialRedHat
s0=SystemLow
s0-s0:c0.c1023=SystemLow-SystemHigh
s0:c0.c1023=SystemHigh

Important - Notez que sous RedHat, le fichier setrans.conf se trouve dans le répertoire /etc/selinux/targeted/setrans.conf.

Dans le contexte d'un SC pour un sujet, le champ identité indique les privilèges de l'utilisateur SELinux utilisés par le sujet.

Dans le contexte d'un SC pour un objet, le champ identité indique à quel utilisateur SELinux appartient l'objet.

SELinux maintient sa propre liste d'utilisateurs, différente de la liste DAC de Linux. Il existe cependant une correspondance entre les deux listes de façon à ce que les utilisateurs MAC puissent être soumissent aux restrictions de SELinux :

root@debian12:~# /usr/sbin/semanage login -l

Login Name           SELinux User         MLS/MCS Range        Service

__default__          unconfined_u         s0-s0:c0.c1023       *
root                 unconfined_u         s0-s0:c0.c1023       *
sddm                 xdm                  s0-s0                * 

Domains et Types

Le Domain est l'endroit d'exécution d'un processus. Chaque processus a un Domain. Le Domain détermine les accès du processus.

Le Domain contient des objets et des sujets qui interagissent ensemble. Ce modèle, où chaque sujet se voit attribué à un Domain et où uniquement certaines opérations sont permises, est appelé Type Enforcement.

Dans SELinux on utilise le mot :

  • Domain pour un processus,
  • Type pour un fichier.

Roles

Un Rôle est comme un utilisateur dans le système de sécurité DAC de Linux. Chaque utilisateur autorisé peut assumer l'identité du Rôle afin d'exécuter les commandes liées au Rôle.

Politiques de Sécurité

Une politique de sécurité définit les SC de chaque application. Elle définit des droits d'accès des domaines aux types. Il y a deux types de politique possible :

Politique Description
targeted Les politiques de sécurité ne s'appliquent qu'à certaines applications
mls Multi Level Security protection

Les politiques de sécurité se trouvent dans le répertoire /etc/selinux/default/policy :

root@debian12:~# ls -l /etc/selinux/default/policy
total 2100
-rw-r--r--. 1 root root 2148201 Nov 30 10:19 policy.33

Pour consulter les statistiques de la politique, il convient d'utiliser la commande seinfo :

root@debian12:~# seinfo
Statistics for policy file: /sys/fs/selinux/policy
Policy Version:             33 (MLS enabled)
Target Policy:              selinux
Handle unknown classes:     allow
  Classes:             134    Permissions:         425
  Sensitivities:         1    Categories:         1024
  Types:              3936    Attributes:          217
  Users:                 7    Roles:                15
  Booleans:            291    Cond. Expr.:         321
  Allow:            104302    Neverallow:            0
  Auditallow:           21    Dontaudit:         16813
  Type_trans:         9245    Type_change:         123
  Type_member:          16    Range_trans:          14
  Role allow:           32    Role_trans:          376
  Constraints:         133    Validatetrans:         0
  MLS Constrain:       110    MLS Val. Tran:         0
  Permissives:           0    Polcap:                5
  Defaults:              0    Typebounds:            0
  Allowxperm:            0    Neverallowxperm:       0
  Auditallowxperm:       0    Dontauditxperm:        0
  Ibendportcon:          0    Ibpkeycon:             0
  Initial SIDs:         27    Fs_use:               29
  Genfscon:             93    Portcon:             479
  Netifcon:              0    Nodecon:               0

Important : Notez ici le grand nombre de la catégorie Dontaudit.

Langage de Politiques

Un politique est composé de centaines de directives. Les principales directives sont :

allow

allow autorise l'accès d'un processus d'un domaine à des fichiers appartenant à un type donné. Le format de la directive est :

allow user_t domaine_t : file (read execute getattr) ;

Dans cette directive :

  • user_t est le type de fichier,
  • domaine_t est le domaine des processus qui sont autorisés par allow,
  • file (droit1 droit2 etc) est la liste des permissions accordées.

Les permissions possibles sont :

  • read
  • write
  • append
  • execute
  • getattr
  • setattr
  • lock
  • link
  • unlink
  • rename
  • ioctl
type

La directive type définit un type SELinux. Le type se termine généralement par _t.

auditallow, dontaudit

La directive auditallow demande l'écriture d'un message de type avc dans les journaux. Elle n'est associée à aucune restriction.

L'inverse peut être obtenue avec dontaudit, à savoir, cette directive demande à ce qu'il n'y ait pas de journalisation après une interdiction.

type_transition

Normalement quand un fichier est créé, il hérite du SC du répertoire parent. De même quand un processus SELinux active un nouveau processus, ce dernier s'exécute dans le même domaine que son parent. La directive type_transition permet de modifier ce comportement.

Décisions de SELinux

Il existe deux types de décisions auxquelles SELinux doit faire face :

  • Décisions d'Accès
  • Décisions de Transition
Décisions d'Accès

Dans ce type de décision SELinux doit décider d'accorder ou non la permission à :

  • un sujet de faire quelque chose à un objet existant,
  • un sujet de créer de nouvelles choses dans le Domain.
Décisions de Transition

Dans ce type de décision SELinux doit décider d'accorder ou non la permission :

  • d'invoquer un processus dans un Domain différent du Domain courant du sujet,
  • de créer des objets dans différents Types que le répertoire parent de l'objet.

4.4 - Commandes SELinux

Commande Description
chcon Changer le SC d'un fichier
audit2allow Générer la source de la règle de sécurité à l'origine d'une erreur
restorecon Restaurer le SC par défaut à un ou plusieurs fichiers
setfiles -n Vérifier si les SC sont corrects
semodule Gèrer les modules de politiques
semodule -i Installer un module de politiques
checkmodule Compiler un module
semodule_package Créer un module installable par semodule
semanage Administrer une politique
audit2allow -M Créer un module à partir d'un message d'audit
sesearch Recherche des règles SELinux
seinfo Effectuer des recherches dans la politique
getsebool Affiche l'état d'un booléen
getsebool -a Affiche l'état de l'ensemble des booléens
sestatus -b Affiche l'état de l'ensemble des booléens
setsebool Modifie l'état d'un booléen
togglesebool Bascule la valeur d'un booléen

4.5 - Les Etats de SELinux

SELinux connait trois états :

Etat Description
disabled SELinux est inactif.
permissive SELinux est actif mais tout est permis. Des interdictions ne font que de générer des messages d'erreurs dans les logs.
enforcing SELinux est actif.

L'examen du contenu du fichier /selinux/enforce révèle une de deux valeurs qui correspondent à l'état de SELinux :

Valeur Description
0 SELinux est en mode permissive
1 SELinux est en mode enforcing

La configuration de l'activation de SELinux ainsi que son état est effectuée grâce au fichier /etc/selinux/config :

root@debian12:~# cat /etc/selinux/config
# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
# enforcing - SELinux security policy is enforced.
# permissive - SELinux prints warnings instead of enforcing.
# disabled - No SELinux policy is loaded.
SELINUX=permissive
# SELINUXTYPE= can take one of these two values:
# default - equivalent to the old strict and targeted policies
# mls     - Multi-Level Security (for military and educational use)
# src     - Custom policy built from source
SELINUXTYPE=default

# SETLOCALDEFS= Check local definition changes
SETLOCALDEFS=0 

Afin de connaître l'état de SELinux, il convient d'utiliser la commande getenforce :

root@debian12:~# getenforce
Permissive

Pour modifier l'état de SELinux, il convient d'utiliser la commande setenforce :

root@debian12:~# setenforce enforcing

root@debian12:~# getenforce
Enforcing

La commande sestatus vous informe sur la configuration de SELinux et notamment sur la version de la politique utilisée :

root@debian12:~# sestatus
SELinux status:                 enabled
SELinuxfs mount:                /sys/fs/selinux
SELinux root directory:         /etc/selinux
Loaded policy name:             default
Current mode:                   enforcing
Mode from config file:          permissive
Policy MLS status:              enabled
Policy deny_unknown status:     allowed
Memory protection checking:     actual (secure)
Max kernel policy version:      33

Les différentes versions de politiques évolue en même temps que le noyau Linux.

La commande sestatus peut aussi prendre l'option -v :

root@debian12:~# sestatus -v
SELinux status:                 enabled
SELinuxfs mount:                /sys/fs/selinux
SELinux root directory:         /etc/selinux
Loaded policy name:             default
Current mode:                   enforcing
Mode from config file:          permissive
Policy MLS status:              enabled
Policy deny_unknown status:     allowed
Memory protection checking:     actual (secure)
Max kernel policy version:      33

Process contexts:
Current context:                unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
Init context:                   system_u:system_r:init_t:s0
/sbin/agetty                    system_u:system_r:getty_t:s0
/usr/sbin/sshd                  system_u:system_r:sshd_t:s0

File contexts:
Controlling terminal:           unconfined_u:object_r:user_devpts_t:s0
/etc/passwd                     system_u:object_r:etc_t:s0
/etc/shadow                     system_u:object_r:shadow_t:s0
/bin/bash                       system_u:object_r:shell_exec_t:s0
/bin/login                      system_u:object_r:login_exec_t:s0
/bin/sh                         system_u:object_r:bin_t:s0 -> system_u:object_r:shell_exec_t:s0
/sbin/agetty                    system_u:object_r:getty_exec_t:s0
/sbin/init                      system_u:object_r:bin_t:s0 -> system_u:object_r:init_exec_t:s0
/usr/sbin/sshd                  system_u:object_r:sshd_exec_t:s0

4.6 - Booléens

Les booléens permettent à des ensembles de règles d'être utilisées d'une manière alternative.

Pour visualiser l'état l'ensemble des booléens, il convient d'utiliser la commande getsebool -a :

root@debian12:~# getsebool -a | more
aide_mmap_files --> off
allow_cvs_read_shadow --> off
allow_execheap --> off
allow_execmem --> off
allow_execmod --> off
allow_execstack --> off
allow_ftpd_anon_write --> off
allow_ftpd_full_access --> off
allow_ftpd_use_cifs --> off
allow_ftpd_use_nfs --> off
allow_gssd_read_tmp --> off
allow_gssd_write_tmp --> off
allow_httpd_anon_write --> off
allow_httpd_apcupsd_cgi_script_anon_write --> off
allow_httpd_awstats_script_anon_write --> off
allow_httpd_collectd_script_anon_write --> off
allow_httpd_cvs_script_anon_write --> off
allow_httpd_lightsquid_script_anon_write --> off
allow_httpd_man2html_script_anon_write --> off
allow_httpd_mediawiki_script_anon_write --> off
allow_httpd_mod_auth_pam --> off
allow_httpd_mojomojo_script_anon_write --> off
allow_httpd_munin_script_anon_write --> off
allow_httpd_nagios_script_anon_write --> off
allow_httpd_nutups_cgi_script_anon_write --> off
allow_httpd_prewikka_script_anon_write --> off
allow_httpd_smokeping_cgi_script_anon_write --> off
allow_httpd_squid_script_anon_write --> off
allow_httpd_sys_script_anon_write --> off
allow_httpd_unconfined_script_anon_write --> off
allow_httpd_user_script_anon_write --> off
allow_httpd_webalizer_script_anon_write --> off
allow_java_execstack --> off
allow_kerberos --> off
allow_mount_anyfile --> off
allow_mplayer_execstack --> off
allow_nfsd_anon_write --> off
allow_polyinstantiation --> off
allow_ptrace --> off
allow_raw_memory_access --> off
allow_rsync_anon_write --> off
allow_saslauthd_read_shadow --> off
allow_smbd_anon_write --> off
allow_ssh_keysign --> off
allow_user_mysql_connect --> off
allow_user_postgresql_connect --> off
allow_write_xshm --> off
allow_ypbind --> off
allow_zebra_write_config --> off
amavis_use_jit --> off
authlogin_nsswitch_use_ldap --> off
authlogin_pam --> on
awstats_purge_apache_log_files --> off
boinc_execmem --> on
boinc_gpu --> on
--More--

ou la commande sestatus -b :

root@debian12:~# sestatus -b | more
SELinux status:                 enabled
SELinuxfs mount:                /sys/fs/selinux
SELinux root directory:         /etc/selinux
Loaded policy name:             default
Current mode:                   enforcing
Mode from config file:          permissive
Policy MLS status:              enabled
Policy deny_unknown status:     allowed
Memory protection checking:     actual (secure)
Max kernel policy version:      33

Policy booleans:
aide_mmap_files                              off
allow_cvs_read_shadow                        off
allow_execheap                               off
allow_execmem                                off
allow_execmod                                off
allow_execstack                              off
allow_ftpd_anon_write                        off
allow_ftpd_full_access                       off
allow_ftpd_use_cifs                          off
allow_ftpd_use_nfs                           off
allow_gssd_read_tmp                          off
allow_gssd_write_tmp                         off
allow_httpd_anon_write                       off
allow_httpd_apcupsd_cgi_script_anon_write    off
allow_httpd_awstats_script_anon_write        off
allow_httpd_collectd_script_anon_write       off
allow_httpd_cvs_script_anon_write            off
allow_httpd_lightsquid_script_anon_write     off
allow_httpd_man2html_script_anon_write       off
allow_httpd_mediawiki_script_anon_write      off
allow_httpd_mod_auth_pam                     off
allow_httpd_mojomojo_script_anon_write       off
allow_httpd_munin_script_anon_write          off
allow_httpd_nagios_script_anon_write         off
allow_httpd_nutups_cgi_script_anon_write     off
allow_httpd_prewikka_script_anon_write       off
allow_httpd_smokeping_cgi_script_anon_write  off
allow_httpd_squid_script_anon_write          off
allow_httpd_sys_script_anon_write            off
allow_httpd_unconfined_script_anon_write     off
allow_httpd_user_script_anon_write           off
allow_httpd_webalizer_script_anon_write      off
allow_java_execstack                         off
allow_kerberos                               off
allow_mount_anyfile                          off
allow_mplayer_execstack                      off
allow_nfsd_anon_write                        off
allow_polyinstantiation                      off
allow_ptrace                                 off
allow_raw_memory_access                      off
allow_rsync_anon_write                       off
allow_saslauthd_read_shadow                  off
allow_smbd_anon_write                        off
--More--

Pour fixer l'état d'un booléen, il convient d'utiliser la commande setsebool :

root@debian12:~# setsebool allow_ftpd_anon_write 1

root@debian12:~# getsebool allow_ftpd_anon_write
allow_ftpd_anon_write --> on

root@debian12:~# setsebool allow_ftpd_anon_write 0

root@debian12:~# getsebool allow_ftpd_anon_write
allow_ftpd_anon_write --> off

LAB #5 - Travailler avec SELinux

Afin reconstruire la politique actuelle sans les règles dontaudit, utilisez la commande semodule :

root@debian12:~# semodule -DB
libsemanage.add_user: user sddm not in password file

Vérifiez qu'il ne reste aucune règle de type dontaudit :

root@debian12:~# seinfo
Statistics for policy file: /sys/fs/selinux/policy
Policy Version:             33 (MLS enabled)
Target Policy:              selinux
Handle unknown classes:     allow
  Classes:             134    Permissions:         425
  Sensitivities:         1    Categories:         1024
  Types:              3936    Attributes:          217
  Users:                 7    Roles:                15
  Booleans:            291    Cond. Expr.:         321
  Allow:            104302    Neverallow:            0
  Auditallow:           21    Dontaudit:             0
  Type_trans:         9245    Type_change:         123
  Type_member:          16    Range_trans:          14
  Role allow:           32    Role_trans:          376
  Constraints:         133    Validatetrans:         0
  MLS Constrain:       110    MLS Val. Tran:         0
  Permissives:           0    Polcap:                5
  Defaults:              0    Typebounds:            0
  Allowxperm:            0    Neverallowxperm:       0
  Auditallowxperm:       0    Dontauditxperm:        0
  Ibendportcon:          0    Ibpkeycon:             0
  Initial SIDs:         27    Fs_use:               29
  Genfscon:             93    Portcon:             479
  Netifcon:              0    Nodecon:               0

5.1 - Copier et Déplacer des Fichiers

Créez deux fichiers file1 et file2 en tant que l'utilisateur trainee puis visualisez les SC des fichiers :

root@debian12:~# exit
logout

trainee@debian12:~$ touch file1 file2

trainee@debian12:~$ ls -lZ file*
-rw-r--r--. 1 trainee trainee unconfined_u:object_r:user_home_t:s0 0 Nov 30 15:11 file1
-rw-r--r--. 1 trainee trainee unconfined_u:object_r:user_home_t:s0 0 Nov 30 15:11 file2

Notez que le type des deux fichiers est user_home_t.

Copiez maintenant le fichier file1 vers /tmp en utilisant la commande cp et visualiser son SC :

trainee@debian12:~$ cp file1 /tmp

trainee@debian12:~$ ls -lZ /tmp/file1
-rw-r--r--. 1 trainee trainee unconfined_u:object_r:user_tmp_t:s0 0 Nov 30 15:13 /tmp/file1

Notez que le fichier ainsi copié a hérité du type du répertoire parent, à savoir tmp_t.

Déplacez maintenant le fichier file2 dans le répertoire /tmp et contrôlez son SC :

trainee@debian12:~$ mv file2 /tmp

trainee@debian12:~$ ls -lZ /tmp/file2
-rw-r--r--. 1 trainee trainee unconfined_u:object_r:user_home_t:s0 0 Nov 30 15:11 /tmp/file2

Notez que la commande mv maintient le type d'origine.

5.2 - Vérifier les SC des Processus

Il convient d'utiliser l'option Z avec la commande ps :

trainee@debian12:~$ ps auxZ | more
LABEL                           USER         PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
system_u:system_r:init_t:s0     root           1  0.0  0.2 211972 48516 ?        Ss   10:22   0:02 /sbin/init
system_u:system_r:kernel_t:s0   root           2  0.0  0.0      0     0 ?        S    10:22   0:00 [kthreadd]
system_u:system_r:kernel_t:s0   root           3  0.0  0.0      0     0 ?        I<   10:22   0:00 [rcu_gp]
system_u:system_r:kernel_t:s0   root           4  0.0  0.0      0     0 ?        I<   10:22   0:00 [rcu_par_gp]
system_u:system_r:kernel_t:s0   root           5  0.0  0.0      0     0 ?        I<   10:22   0:00 [slub_flushwq]
system_u:system_r:kernel_t:s0   root           6  0.0  0.0      0     0 ?        I<   10:22   0:00 [netns]
system_u:system_r:kernel_t:s0   root           8  0.0  0.0      0     0 ?        I<   10:22   0:00 [kworker/0:0H-events_highpri]
system_u:system_r:kernel_t:s0   root          10  0.0  0.0      0     0 ?        I<   10:22   0:00 [mm_percpu_wq]
system_u:system_r:kernel_t:s0   root          11  0.0  0.0      0     0 ?        I    10:22   0:00 [rcu_tasks_kthread]
system_u:system_r:kernel_t:s0   root          12  0.0  0.0      0     0 ?        I    10:22   0:00 [rcu_tasks_rude_kthread]
system_u:system_r:kernel_t:s0   root          13  0.0  0.0      0     0 ?        I    10:22   0:00 [rcu_tasks_trace_kthread]
system_u:system_r:kernel_t:s0   root          14  0.0  0.0      0     0 ?        S    10:22   0:00 [ksoftirqd/0]
system_u:system_r:kernel_t:s0   root          15  0.0  0.0      0     0 ?        I    10:22   0:00 [rcu_preempt]
system_u:system_r:kernel_t:s0   root          16  0.0  0.0      0     0 ?        S    10:22   0:00 [migration/0]
system_u:system_r:kernel_t:s0   root          18  0.0  0.0      0     0 ?        S    10:22   0:00 [cpuhp/0]
system_u:system_r:kernel_t:s0   root          19  0.0  0.0      0     0 ?        S    10:22   0:00 [cpuhp/1]
system_u:system_r:kernel_t:s0   root          20  0.0  0.0      0     0 ?        S    10:22   0:00 [migration/1]
system_u:system_r:kernel_t:s0   root          21  0.0  0.0      0     0 ?        S    10:22   0:00 [ksoftirqd/1]
system_u:system_r:kernel_t:s0   root          23  0.0  0.0      0     0 ?        I<   10:22   0:00 [kworker/1:0H-events_highpri]
system_u:system_r:kernel_t:s0   root          24  0.0  0.0      0     0 ?        S    10:22   0:00 [cpuhp/2]
system_u:system_r:kernel_t:s0   root          25  0.0  0.0      0     0 ?        S    10:22   0:00 [migration/2]
system_u:system_r:kernel_t:s0   root          26  0.0  0.0      0     0 ?        S    10:22   0:00 [ksoftirqd/2]
system_u:system_r:kernel_t:s0   root          27  0.0  0.0      0     0 ?        I    10:22   0:00 [kworker/2:0-events]
system_u:system_r:kernel_t:s0   root          28  0.0  0.0      0     0 ?        I<   10:22   0:00 [kworker/2:0H-events_highpri]
system_u:system_r:kernel_t:s0   root          29  0.0  0.0      0     0 ?        S    10:22   0:00 [cpuhp/3]
system_u:system_r:kernel_t:s0   root          30  0.0  0.0      0     0 ?        S    10:22   0:00 [migration/3]
system_u:system_r:kernel_t:s0   root          31  0.0  0.0      0     0 ?        S    10:22   0:00 [ksoftirqd/3]
system_u:system_r:kernel_t:s0   root          33  0.0  0.0      0     0 ?        I<   10:22   0:00 [kworker/3:0H-events_highpri]
system_u:system_r:kernel_t:s0   root          34  0.0  0.0      0     0 ?        S    10:22   0:00 [cpuhp/4]
system_u:system_r:kernel_t:s0   root          35  0.0  0.0      0     0 ?        S    10:22   0:00 [migration/4]
system_u:system_r:kernel_t:s0   root          36  0.0  0.0      0     0 ?        S    10:22   0:00 [ksoftirqd/4]
system_u:system_r:kernel_t:s0   root          38  0.0  0.0      0     0 ?        I<   10:22   0:00 [kworker/4:0H-events_highpri]
system_u:system_r:kernel_t:s0   root          39  0.0  0.0      0     0 ?        S    10:22   0:00 [cpuhp/5]
system_u:system_r:kernel_t:s0   root          40  0.0  0.0      0     0 ?        S    10:22   0:00 [migration/5]
system_u:system_r:kernel_t:s0   root          41  0.0  0.0      0     0 ?        S    10:22   0:00 [ksoftirqd/5]
system_u:system_r:kernel_t:s0   root          43  0.0  0.0      0     0 ?        I<   10:22   0:00 [kworker/5:0H-events_highpri]
system_u:system_r:kernel_t:s0   root          44  0.0  0.0      0     0 ?        S    10:22   0:00 [cpuhp/6]
system_u:system_r:kernel_t:s0   root          45  0.0  0.0      0     0 ?        S    10:22   0:00 [migration/6]
system_u:system_r:kernel_t:s0   root          46  0.0  0.0      0     0 ?        S    10:22   0:00 [ksoftirqd/6]
system_u:system_r:kernel_t:s0   root          48  0.0  0.0      0     0 ?        I<   10:22   0:00 [kworker/6:0H-events_highpri]
system_u:system_r:kernel_t:s0   root          49  0.0  0.0      0     0 ?        S    10:22   0:00 [cpuhp/7]
system_u:system_r:kernel_t:s0   root          50  0.0  0.0      0     0 ?        S    10:22   0:00 [migration/7]
system_u:system_r:kernel_t:s0   root          51  0.0  0.0      0     0 ?        S    10:22   0:00 [ksoftirqd/7]
system_u:system_r:kernel_t:s0   root          53  0.0  0.0      0     0 ?        I<   10:22   0:00 [kworker/7:0H-events_highpri]
system_u:system_r:kernel_t:s0   root          62  0.0  0.0      0     0 ?        S    10:22   0:00 [kdevtmpfs]
system_u:system_r:kernel_t:s0   root          63  0.0  0.0      0     0 ?        I<   10:22   0:00 [inet_frag_wq]
system_u:system_r:kernel_t:s0   root          64  0.0  0.0      0     0 ?        S    10:22   0:00 [kauditd]
system_u:system_r:kernel_t:s0   root          65  0.0  0.0      0     0 ?        I    10:22   0:06 [kworker/1:1-events]
system_u:system_r:kernel_t:s0   root          66  0.0  0.0      0     0 ?        S    10:22   0:00 [khungtaskd]
system_u:system_r:kernel_t:s0   root          67  0.0  0.0      0     0 ?        S    10:22   0:00 [oom_reaper]
system_u:system_r:kernel_t:s0   root          68  0.0  0.0      0     0 ?        I<   10:22   0:00 [writeback]
system_u:system_r:kernel_t:s0   root          69  0.0  0.0      0     0 ?        S    10:22   0:00 [kcompactd0]
system_u:system_r:kernel_t:s0   root          70  0.0  0.0      0     0 ?        SN   10:22   0:00 [ksmd]
system_u:system_r:kernel_t:s0   root          71  0.0  0.0      0     0 ?        SN   10:22   0:00 [khugepaged]
--More--

5.3 - Visualiser la SC d'un Utilisateur

Utilisez l'option -Z avec la commande id :

trainee@debian12:~$ id -Z
unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023

Notez que vous ne pouvez pas consulter le SC d'un autre utilisateur :

trainee@debian12:~$ id root
uid=0(root) gid=0(root) groups=0(root)

trainee@debian12:~$ id -Z root
id: cannot print security context when user specified

5.4 - Vérifier la SC d'un fichier

Il convient d'utiliser la commande ls avec l'option -Z :

trainee@debian12:~$ cd /etc

trainee@debian12:/etc$ ls -lZ l* -d
drwxr-xr-x. 2 root root system_u:object_r:etc_t:s0           4096 Nov 24 16:47 ldap
-rw-r--r--. 1 root root system_u:object_r:ld_so_cache_t:s0  71363 Nov 30 10:11 ld.so.cache
-rw-r--r--. 1 root root system_u:object_r:etc_t:s0             34 Jul 29  2019 ld.so.conf
drwxr-xr-x. 2 root root system_u:object_r:etc_t:s0           4096 Nov 24 17:22 ld.so.conf.d
-rw-r--r--. 1 root root system_u:object_r:etc_t:s0             26 Dec 20  2020 libao.conf
-rw-r--r--. 1 root root system_u:object_r:etc_t:s0            191 Jan  6  2021 libaudit.conf
drwxr-xr-x. 3 root root system_u:object_r:etc_t:s0           4096 Apr 25  2022 libblockdev
drwxr-xr-x. 2 root root system_u:object_r:etc_t:s0           4096 Nov 24 17:22 libnl-3
drwxr-xr-x. 2 root root system_u:object_r:etc_t:s0           4096 Aug 18  2019 libpaper.d
drwxr-xr-x. 3 root root system_u:object_r:etc_t:s0           4096 Nov 24 17:26 libreoffice
drwxr-xr-x. 2 root root system_u:object_r:etc_t:s0           4096 Nov 24 17:27 lightdm
drwxr-xr-x. 4 root root system_u:object_r:httpd_config_t:s0  4096 Apr 25  2022 lighttpd
-rw-r--r--. 1 root root system_u:object_r:locale_t:s0        2996 Aug 25 21:11 locale.alias
-rw-r--r--. 1 root root system_u:object_r:etc_t:s0           9449 Nov 24 17:22 locale.gen
lrwxrwxrwx. 1 root root system_u:object_r:etc_t:s0             32 Nov 24 15:49 localtime -> /usr/share/zoneinfo/Europe/Paris
drwxr-xr-x. 4 root root system_u:object_r:etc_t:s0           4096 Nov 27 14:27 logcheck
-rw-r--r--. 1 root root system_u:object_r:etc_t:s0          12569 Apr  7  2025 login.defs
-rw-r--r--. 1 root root system_u:object_r:etc_t:s0            494 Feb 28  2021 logrotate.conf
drwxr-xr-x. 2 root root system_u:object_r:etc_t:s0           4096 Nov 27 14:54 logrotate.d
drwxr-xr-x. 3 root root system_u:object_r:etc_t:s0           4096 Nov 30 07:51 lynis
drwxr-xr-x. 2 root root system_u:object_r:etc_t:s0           4096 Nov 24 17:22 lynx

5.5 - Troubleshooting SELinux

L'interprétation des messages journalisés de SELinux est souvent la clef d'un dépannage efficace et rapide.

Si le démon auditd est démarré, les messages de SELinux sont consignés dans le fichier /var/log/audit/audit.log. Dans le cas contraire, les mêmes messages sont consignés dans le fichier /var/log/messages. Dans les deux cas, chaque message de SELinux contient le mot clef AVC.

Avant de poursuivre, mettez SELinux en mode Permissive :

root@debian12:~# setenforce permissive

root@debian12:~# getenforce
Permissive

La commande chcon

La commande chcon permet de modifier temporairement une SC.

Prenons le cas de la création d'un répertoire à la racine du système de fichiers afin d'y stocker les pages web du serveur apache :

trainee@debian12:/etc$ cd ~

trainee@debian12:~$ systemctl status apache2
● apache2.service - The Apache HTTP Server
     Loaded: loaded (/lib/systemd/system/apache2.service; enabled; preset: enabled)
     Active: active (running) since Sun 2025-11-30 10:23:14 CET; 4h 54min ago
       Docs: https://httpd.apache.org/docs/2.4/
    Process: 982 ExecStart=/usr/sbin/apachectl start (code=exited, status=0/SUCCESS)
   Main PID: 1109 (apache2)
      Tasks: 55 (limit: 19123)
     Memory: 23.7M
        CPU: 1.074s
     CGroup: /system.slice/apache2.service
             ├─1109 /usr/sbin/apache2 -k start
             ├─1111 /usr/sbin/apache2 -k start
             └─1112 /usr/sbin/apache2 -k start

Warning: some journal files were not opened due to insufficient permissions.

trainee@debian12:~$ su -
Password: fenestros

root@debian12:~# mkdir /www

root@debian12:~# vi /www/index.html

root@debian12:~# cat /www/index.html
<html>
<title>
This is a test
</title>
<body>
www test page
</body>
</html>

Modifiez ensuite la directive DocumentRoot dans le fichier /etc/apache2/sites-enabled/000-default.conf :

root@debian12:~# vi /etc/apache2/sites-enabled/000-default.conf 

root@debian12:~# cat /etc/apache2/sites-enabled/000-default.conf 
<VirtualHost *:80>
        # The ServerName directive sets the request scheme, hostname and port that
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.
        #ServerName www.example.com

        ServerAdmin webmaster@localhost
        #DocumentRoot /var/www/html
        DocumentRoot /www

        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf
</VirtualHost>

Ajoutez la section <Directory “/www”> au fichier /etc/apache2/apache2.conf/ :

...
# Sets the default security model of the Apache2 HTTPD server. It does
# not allow access to the root filesystem outside of /usr/share and /var/www.
# The former is used by web applications packaged in Debian,
# the latter may be used for local directories served by the web server. If
# your system is serving content from a sub-directory in /srv you must allow
# access here, or in any related virtual host.
<Directory />
        Options FollowSymLinks
        AllowOverride None
        Require all denied
</Directory> 

<Directory /usr/share>
        AllowOverride None
        Require all granted
</Directory>

<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
</Directory>

<Directory /www/>
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
</Directory>

#<Directory /srv/>
#       Options Indexes FollowSymLinks
#       AllowOverride None
#       Require all granted
#</Directory>
...

Modifiez ensuite le propriétaire et le groupe du répertoire /www et son contenu :

root@debian12:~# chown -R www-data:www-data /www

Redémarrez maintenant le service apache2 :

root@debian12:~# systemctl restart apache2

root@debian12:~# systemctl status apache2
● apache2.service - The Apache HTTP Server
     Loaded: loaded (/lib/systemd/system/apache2.service; enabled; preset: enabled)
     Active: active (running) since Sun 2025-11-30 15:28:15 CET; 11s ago
       Docs: https://httpd.apache.org/docs/2.4/
    Process: 2234 ExecStart=/usr/sbin/apachectl start (code=exited, status=0/SUCCESS)
   Main PID: 2239 (apache2)
      Tasks: 55 (limit: 19123)
     Memory: 21.0M
        CPU: 45ms
     CGroup: /system.slice/apache2.service
             ├─2239 /usr/sbin/apache2 -k start
             ├─2241 /usr/sbin/apache2 -k start
             └─2242 /usr/sbin/apache2 -k start

Nov 30 15:28:15 debian12 systemd[1]: Starting apache2.service - The Apache HTTP Server...
Nov 30 15:28:15 debian12 apachectl[2234]: /usr/sbin/apachectl: 99: ulimit: error setting limit (Permission denied)
Nov 30 15:28:15 debian12 apachectl[2234]: Setting ulimit failed. See README.Debian for more information.
Nov 30 15:28:15 debian12 apachectl[2238]: AH00557: apache2: apr_sockaddr_info_get() failed for debian12
Nov 30 15:28:15 debian12 apachectl[2238]: AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1. Set the 'ServerName' directive globally to suppress this mess>
Nov 30 15:28:15 debian12 systemd[1]: Started apache2.service - The Apache HTTP Server.

Consultez le site localhost en utilisant lynx :

root@debian12:~# lynx localhost

Pour consulter les messages d'alerte de SELinux, vous disposez de la commande audit2why :

root@debian12:~# ausearch -m avc -ts recent | audit2why | grep apache2
type=AVC msg=audit(1764512954.745:600): avc:  denied  { map } for  pid=2241 comm="apache2" path="/www/index.html" dev="sda1" ino=1700626 scontext=system_u:system_r:httpd_t:s0 tcontext=unconfined_u:object_r:etc_runtime_t:s0 tclass=file permissive=0

Ce message a été généré parce que le repertoire /www ainsi que le fichier index.html ne possèdent pas le type nécessaire pour que le service apache puisse les utiliser :

root@debian12:~# ls -Z /www/index.html
unconfined_u:object_r:etc_runtime_t:s0 /www/index.html

root@debian12:~# ls -Z /var/www/html
system_u:object_r:httpd_sys_content_t:s0 index.html

L'exemple ci-dessus nous montre clairement que le type pour /www/index.html est etc_runtime_t or apache a besoin du type httpd_sys_content_t pour pouvoir accéder au fichier.

Modifiez donc la SC de /www et /www/index.html en utilisant la commande chcon :

root@debian12:~# chcon -Rv --type=httpd_sys_content_t /www
changing security context of '/www/index.html'
changing security context of '/www'

root@debian12:~# ls -Z /www/index.html
unconfined_u:object_r:httpd_sys_content_t:s0 /www/index.html

Afin de maintenir ces SC lors d'une restauration des SC par défaut, il convient d'utiliser la commande semanage afin d'appliquer la modification d'une manière définitive :

root@debian12:~# semanage fcontext -a -t httpd_sys_content_t "/www(/.*)?"
libsemanage.add_user: user sddm not in password file

Options de la Commande

root@debian12:~# chcon --help
Usage: chcon [OPTION]... CONTEXT FILE...
  or:  chcon [OPTION]... [-u USER] [-r ROLE] [-l RANGE] [-t TYPE] FILE...
  or:  chcon [OPTION]... --reference=RFILE FILE...
Change the SELinux security context of each FILE to CONTEXT.
With --reference, change the security context of each FILE to that of RFILE.

Mandatory arguments to long options are mandatory for short options too.
      --dereference      affect the referent of each symbolic link (this is
                         the default), rather than the symbolic link itself
  -h, --no-dereference   affect symbolic links instead of any referenced file
  -u, --user=USER        set user USER in the target security context
  -r, --role=ROLE        set role ROLE in the target security context
  -t, --type=TYPE        set type TYPE in the target security context
  -l, --range=RANGE      set range RANGE in the target security context
      --no-preserve-root  do not treat '/' specially (the default)
      --preserve-root    fail to operate recursively on '/'
      --reference=RFILE  use RFILE's security context rather than specifying
                         a CONTEXT value
  -R, --recursive        operate on files and directories recursively
  -v, --verbose          output a diagnostic for every file processed

The following options modify how a hierarchy is traversed when the -R
option is also specified.  If more than one is specified, only the final
one takes effect.

  -H                     if a command line argument is a symbolic link
                         to a directory, traverse it
  -L                     traverse every symbolic link to a directory
                         encountered
  -P                     do not traverse any symbolic links (default)

      --help        display this help and exit
      --version     output version information and exit

GNU coreutils online help: <https://www.gnu.org/software/coreutils/>
Full documentation <https://www.gnu.org/software/coreutils/chcon>
or available locally via: info '(coreutils) chcon invocation'

La commande restorecon

Pour illustrer l'utilisation de cette commande, créez les fichiers copy.html et move.html dans le répertoire /tmp :

root@debian12:~# cd /tmp ; touch copy.html move.html

root@debian12:/tmp# ls -lZ | grep html
-rw-r--r--. 1 root    root unconfined_u:object_r:user_tmp_t:s0     0 Nov 30 15:46 copy.html
-rw-r--r--. 1 root    root unconfined_u:object_r:user_tmp_t:s0     0 Nov 30 15:46 move.html

Copiez le fichier copy.html vers /var/www/html et déplacez le fichier move.html vers la même cible :

root@debian12:/tmp# cp copy.html /var/www/html/

root@debian12:/tmp# mv move.html /var/www/html/

root@debian12:/tmp# ls -lZ /var/www/html
total 12
-rw-r--r--. 1 root root unconfined_u:object_r:httpd_sys_content_t:s0     0 Nov 30 15:48 copy.html
-rw-r--r--. 1 root root system_u:object_r:httpd_sys_content_t:s0     10701 Nov 27 14:54 index.html
-rw-r--r--. 1 root root unconfined_u:object_r:user_tmp_t:s0              0 Nov 30 15:46 move.html

Important : Notez ici que copy.html a pris le type du répertoire de destination tandis que move.html retient le type obtenu lors de la création.

Restaurez maintenant la SC par défaut de move.html compte tenu de son emplacement en utilisant la commande restorecon :

root@debian12:/tmp# restorecon -v /var/www/html/move.html
Relabeled /var/www/html/move.html from unconfined_u:object_r:user_tmp_t:s0 to unconfined_u:object_r:httpd_sys_content_t:s0

root@debian12:/tmp# ls -lZ /var/www/html
total 12
-rw-r--r--. 1 root root unconfined_u:object_r:httpd_sys_content_t:s0     0 Nov 30 15:48 copy.html
-rw-r--r--. 1 root root system_u:object_r:httpd_sys_content_t:s0     10701 Nov 27 14:54 index.html
-rw-r--r--. 1 root root unconfined_u:object_r:httpd_sys_content_t:s0     0 Nov 30 15:46 move.html

Options de la Commande

root@debian12:/tmp# restorecon --help
restorecon: invalid option -- '-'
usage:  restorecon [-iIDFmnprRv0xT] [-e excludedir] pathname...
usage:  restorecon [-iIDFmnprRv0xT] [-e excludedir] -f filename

5.7 - La commande semanage

Pour illustrer l'utilisation de cette commande, considérez le besoin de mettre le service apache à l'écoute du port 8090 au lieu du port standard.

SELinux gère aussi l'accès aux ports par les différents serveurs. La liste complète des ports autorisés par serveur puet être visualiser à l'aide de la commande semanage :

root@debian12:/tmp# semanage port -l | grep http
http_cache_port_t              tcp      3128, 8080, 8118, 10001-10010
http_cache_port_t              udp      3130
http_port_t                    tcp      80, 443, 488, 8008, 8009, 8443, 8448
pegasus_http_port_t            tcp      5988
pegasus_https_port_t           tcp      5989

Notez par exemple que le serveur apache est autorisé d'utiliser les ports suivants :

http_port_t                    tcp      80, 443, 488, 8008, 8009, 8443, 8448

Dans le cas où on souhaite qu'apache utilise le port 8090 par exemple, il est nécessaire de créer la règle adéquate avec la commande semanage :

root@debian12:/tmp# semanage port -a -t http_port_t -p tcp 8090

Vous noterez que le port 8090 a été ajouté à la liste des ports reconnus comme valides par SELinux :

root@debian12:/tmp# semanage port -a -t http_port_t -p tcp 8090
libsemanage.add_user: user sddm not in password file

root@debian12:/tmp# semanage port -l | grep http
http_cache_port_t              tcp      3128, 8080, 8118, 10001-10010
http_cache_port_t              udp      3130
http_port_t                    tcp      8090, 80, 443, 488, 8008, 8009, 8443, 8448
pegasus_http_port_t            tcp      5988
pegasus_https_port_t           tcp      5989

Options de la Commande

root@debian12:/tmp# semanage --help
usage: semanage [-h] {import,export,login,user,port,ibpkey,ibendport,interface,module,node,fcontext,boolean,permissive,dontaudit} ...

semanage is used to configure certain elements of SELinux policy with-out requiring modification to or recompilation from policy source.

positional arguments:
  {import,export,login,user,port,ibpkey,ibendport,interface,module,node,fcontext,boolean,permissive,dontaudit}
    import              Import local customizations
    export              Output local customizations
    login               Manage login mappings between linux users and SELinux confined users
    user                Manage SELinux confined users (Roles and levels for an SELinux user)
    port                Manage network port type definitions
    ibpkey              Manage infiniband ibpkey type definitions
    ibendport           Manage infiniband end port type definitions
    interface           Manage network interface type definitions
    module              Manage SELinux policy modules
    node                Manage network node type definitions
    fcontext            Manage file context mapping definitions
    boolean             Manage booleans to selectively enable functionality
    permissive          Manage process type enforcement mode
    dontaudit           Disable/Enable dontaudit rules in policy

options:
  -h, --help            show this help message and exit

5.8 - La commande audit2allow

La création d'un module de politique personnalisé se fait en utilisant la commande audit2allow. L'administrateur de sécurité à recours à la création de modules quand, et uniquement quand :

  • la résolution du problème n'est pas possible en utilisant une des commandes précédemment citées,
  • il n'existe pas de booléen capable de régler le problème.

Pour illustrer l'utilisation de cette commande, créez un nouveau répertoire pour les documents d'apache ainsi que la page d'accueil :

root@debian12:/tmp# mkdir /www1

root@debian12:/tmp# vi /www1/index.html

root@debian12:/tmp# cat /www1/index.html
<html>
<title>
This is a test
</title>
<body>
www test page
</body>
</html>

Modifiez ensuite la directive DocumentRoot dans le fichier /etc/apache2/sites-enabled/000-default.conf :

root@debian12:~# vi /etc/apache2/sites-enabled/000-default.conf 

root@debian12:~# cat /etc/apache2/sites-enabled/000-default.conf 
<VirtualHost *:80>
        # The ServerName directive sets the request scheme, hostname and port that
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.
        #ServerName www.example.com

        ServerAdmin webmaster@localhost
        #DocumentRoot /var/www/html
        DocumentRoot /www

        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf
</VirtualHost>

Modifiez la section <Directory “/www”> au fichier /etc/apache2/apache2.conf/ :

...
# Sets the default security model of the Apache2 HTTPD server. It does
# not allow access to the root filesystem outside of /usr/share and /var/www.
# The former is used by web applications packaged in Debian,
# the latter may be used for local directories served by the web server. If
# your system is serving content from a sub-directory in /srv you must allow
# access here, or in any related virtual host.
<Directory />
        Options FollowSymLinks
        AllowOverride None
        Require all denied
</Directory> 

<Directory /usr/share>
        AllowOverride None
        Require all granted
</Directory>

<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
</Directory>

<Directory /www1/>
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
</Directory>

#<Directory /srv/>
#       Options Indexes FollowSymLinks
#       AllowOverride None
#       Require all granted
#</Directory>
...

Modifiez ensuite le propriétaire et le groupe du répertoire /www et son contenu :

root@debian12:~# chown -R www-data:www-data /www

Redémarrez maintenant le service apache2 :

root@debian12:/tmp# systemctl restart apache2

root@debian12:/tmp# systemctl status apache2
● apache2.service - The Apache HTTP Server
     Loaded: loaded (/lib/systemd/system/apache2.service; enabled; preset: enabled)
     Active: active (running) since Sun 2025-11-30 16:04:11 CET; 14s ago
       Docs: https://httpd.apache.org/docs/2.4/
    Process: 2421 ExecStart=/usr/sbin/apachectl start (code=exited, status=0/SUCCESS)
   Main PID: 2425 (apache2)
      Tasks: 55 (limit: 19123)
     Memory: 21.2M
        CPU: 47ms
     CGroup: /system.slice/apache2.service
             ├─2425 /usr/sbin/apache2 -k start
             ├─2426 /usr/sbin/apache2 -k start
             └─2427 /usr/sbin/apache2 -k start

Nov 30 16:04:11 debian12 systemd[1]: Starting apache2.service - The Apache HTTP Server...
Nov 30 16:04:11 debian12 apachectl[2421]: /usr/sbin/apachectl: 99: ulimit: error setting limit (Permission denied)
Nov 30 16:04:11 debian12 apachectl[2421]: Setting ulimit failed. See README.Debian for more information.
Nov 30 16:04:11 debian12 apachectl[2424]: AH00557: apache2: apr_sockaddr_info_get() failed for debian12
Nov 30 16:04:11 debian12 apachectl[2424]: AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1. Set the 'ServerName' directive globally to suppress this mess>
Nov 30 16:04:11 debian12 systemd[1]: Started apache2.service - The Apache HTTP Server.
root@debian12:/tmp# 

Consultez le site localhost en utilisant lynx :

root@debian12:/tmp# lynx --dump localhost
   www test page

Le fichier /var/log/audit/audit.log contient des notifications de type AVC :

root@debian12:/tmp# cat /var/log/audit/audit.log | grep AVC | grep apache2
type=AVC msg=audit(1764494594.988:204): avc:  denied  { watch } for  pid=984 comm="fail2ban-server" path="/var/log/apache2" dev="sda1" ino=1572133 scontext=system_u:system_r:fail2ban_t:s0 tcontext=system_u:object_r:httpd_log_t:s0 tclass=dir permissive=1
type=AVC msg=audit(1764494594.988:205): avc:  denied  { watch } for  pid=984 comm="fail2ban-server" path="/var/log/apache2/error.log" dev="sda1" ino=1574561 scontext=system_u:system_r:fail2ban_t:s0 tcontext=system_u:object_r:httpd_log_t:s0 tclass=file permissive=1
type=AVC msg=audit(1764512954.745:600): avc:  denied  { map } for  pid=2241 comm="apache2" path="/www/index.html" dev="sda1" ino=1700626 scontext=system_u:system_r:httpd_t:s0 tcontext=unconfined_u:object_r:etc_runtime_t:s0 tclass=file permissive=0
type=AVC msg=audit(1764515158.228:660): avc:  denied  { map } for  pid=2427 comm="apache2" path="/www1/index.html" dev="sda1" ino=1700628 scontext=system_u:system_r:httpd_t:s0 tcontext=unconfined_u:object_r:etc_runtime_t:s0 tclass=file permissive=0

A l'aide de la commande grep, il convient maintenant d'envoyer les messages d'erreurs en provenance du fichier /var/log/audit/audit.log sur l'entrée standard de la commande audit2allow afin de permettre celle-ci de créer des règles permettant l'autorisation de ce qui a été précédemment interdit par SELinux :

root@debian12:/tmp# grep httpd_t /var/log/audit/audit.log | audit2allow -m httpdlocal > httpdlocal.te

root@debian12:/tmp# cat httpdlocal.te

module httpdlocal 1.0;

require {
        type selinux_config_t;
        type etc_runtime_t;
        type httpd_t;
        class dir search;
        class process setrlimit;
        class file map;
}

#============= httpd_t ==============
allow httpd_t etc_runtime_t:file map;

#!!!! This avc can be allowed using the boolean 'httpd_setrlimit'
allow httpd_t self:process setrlimit;

#!!!! This avc can be allowed using the boolean 'allow_kerberos'
allow httpd_t selinux_config_t:dir search;

L'audit du fichier terminé, il faut maintenant utiliser audit2allow pour fabriquer un module de politique :

root@debian12:/tmp# grep httpd_t /var/log/audit/audit.log | audit2allow -M httpdlocal
******************** IMPORTANT ***********************
To make this policy package active, execute:

semodule -i httpdlocal.pp

Chargez maintenant le module dans la politique SELinux :

root@debian12:/tmp# semodule -i httpdlocal.pp
libsemanage.add_user: user sddm not in password file

Vérifiez que le module est chargé :

root@debian12:/tmp# semodule -l | grep httpd
httpdlocal

Redémarrez le service apache2 :

root@debian12:/tmp# systemctl restart apache2

root@debian12:/tmp# systemctl status apache2
● apache2.service - The Apache HTTP Server
     Loaded: loaded (/lib/systemd/system/apache2.service; enabled; preset: enabled)
     Active: active (running) since Sun 2025-11-30 16:12:47 CET; 9s ago
       Docs: https://httpd.apache.org/docs/2.4/
    Process: 2538 ExecStart=/usr/sbin/apachectl start (code=exited, status=0/SUCCESS)
   Main PID: 2542 (apache2)
      Tasks: 55 (limit: 19123)
     Memory: 17.1M
        CPU: 43ms
     CGroup: /system.slice/apache2.service
             ├─2542 /usr/sbin/apache2 -k start
             ├─2543 /usr/sbin/apache2 -k start
             └─2544 /usr/sbin/apache2 -k start

Nov 30 16:12:47 debian12 systemd[1]: Starting apache2.service - The Apache HTTP Server...
Nov 30 16:12:47 debian12 apachectl[2541]: AH00557: apache2: apr_sockaddr_info_get() failed for debian12
Nov 30 16:12:47 debian12 apachectl[2541]: AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1. Set the 'ServerName' directive globally to suppress this mess>
Nov 30 16:12:47 debian12 systemd[1]: Started apache2.service - The Apache HTTP Server. 

Videz le fichier /var/log/audit/audit.log :

root@debian12:/tmp# ls -l /var/log/audit/audit.log
-rw-r-----. 1 root adm 0 Nov 30 16:15 /var/log/audit/audit.log

Consultez le site localhost :

root@debian12:/tmp# lynx --dump localhost
   www test page

Constatez que la consultation ne génère plus de messages de type AVC :

root@debian12:/tmp# cat /var/log/audit/audit.log
root@debian12:/tmp# 

Options de la Commande

root@debian12:/tmp# audit2allow --help
Usage: audit2allow [options]

Options:
  --version             show program's version number and exit
  -h, --help            show this help message and exit
  -b, --boot            audit messages since last boot conflicts with -i
  -a, --all             read input from audit log - conflicts with -i
  -p POLICY, --policy=POLICY
                        Policy file to use for analysis
  -d, --dmesg           read input from dmesg - conflicts with --all and
                        --input
  -i INPUT, --input=INPUT
                        read input from <input> - conflicts with -a
  -l, --lastreload      read input only after the last reload
  -r, --requires        generate require statements for rules
  -m MODULE, --module=MODULE
                        set the module name - implies --requires
  -M MODULE_PACKAGE, --module-package=MODULE_PACKAGE
                        generate a module package - conflicts with -o and -m
  -o OUTPUT, --output=OUTPUT
                        append output to <filename>, conflicts with -M
  -D, --dontaudit       generate policy with dontaudit rules
  -R, --reference       generate refpolicy style output
  -N, --noreference     do not generate refpolicy style output
  -v, --verbose         explain generated output
  -e, --explain         fully explain generated output
  -t TYPE, --type=TYPE  only process messages with a type that matches this
                        regex
  --perm-map=PERM_MAP   file name of perm map
  --interface-info=INTERFACE_INFO
                        file name of interface information
  -x, --xperms          generate extended permission rules
  --debug               leave generated modules for -M
  -w, --why             Translates SELinux audit messages into a description
                        of why the access was denied

Copyright © 2025 Hugh Norris.

Menu