Ceci est une ancienne révision du document !
Table des matières
Version : 2024.01
Dernière mise-à-jour : 2024/10/02 11:30
LCF606 - Gestion de la Sécurité
Contenu du Module
- LCF606 - Gestion de Netfilter et de Firewalld
- Contenu du Module
- Le Pare-feu Netfilter/iptables
- LAB #1 - La Configuration par firewalld
- La Configuration de Base de firewalld
- La Commande firewall-cmd
- La Configuration Avancée de firewalld
- Le mode Panic de firewalld
- System Hardening
- Les compilateurs
- Les paquets
- Les démons et services
- Les fichiers .rhosts
- Les fichiers et les repertoires sans proprietaire
- Limiter le delai d'inactivite d'une session shell
- Renforcer la securite d'init
- Les Distributions SysVInit
- Les Distributions Upstart
- Renforcer la sécurité du Noyau
- La commande sysctl
- Mise en place de SELinux pour sécuriser le serveur
- Introducton
- 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
- Commandes SELinux
- Les Etats de SELinux
- Booléens
- LAB #2 - Travailler avec SELinux
- Copier et Déplacer des Fichiers
- Vérifier les SC des Processus
- Visualiser la SC d'un Utilisateur
- Vérifier la SC d'un fichier
- Troubleshooting SELinux
- La commande chcon
- La commande restorecon
- Le fichier /.autorelabel
- La commande semanage
- La commande audit2allow
Le Pare-feu Netfilter
Netfilter est composé de 5 hooks :
- NF_IP_PRE_ROUTING
- NF_IP_LOCAL_IN
- NF_IP_LOCAL_OUT
- NF_IP_FORWARD
- NF_IP_POSTROUTING
Ces hooks sont utilisés par deux branches, la première est celle concernée par les paquets qui entrent vers des services locaux :
- NF_IP_PRE_ROUTING > NF_IP_LOCAL_IN > NF_IP_LOCAL_OUT > NF_IP_POSTROUTING
tandis que la deuxième concerne les paquets qui traversent la passerelle:
- NF_IP_PRE_ROUTING > NF_IP_FORWARD > NF_IP_POSTROUTING
Si IPTABLES a été compilé en tant que module, son utilisation nécessite le chargement de plusieurs modules supplémentaires en fonction de la situation:
- iptable_filter
- iptable_mangle
- iptable_net
- etc
Netfilter est organisé en tables. La commande iptables de netfilter permet d'insérer des policies dans les chaines:
- La table FILTER
- La chaîne INPUT
- Concerne les paquets entrants
- Policies: ACCEPT, DROP, REJECT
- La chaîne OUTPUT
- Concerne les paquets sortants
- Policies: ACCEPT, DROP, REJECT
- La chaîne FORWARD
- Concerne les paquets traversant le par-feu.
- Policies: ACCEPT, DROP, REJECT
Si aucune table n'est précisée, c'est la table FILTER qui s'applique par défaut.
- La table NAT
- La chaîne PREROUTING
- Permet de faire la translation d'adresse de destination
- Cibles: SNAT, DNAT, MASQUERADE
- La chaîne POSTROUTING
- Permet de faire la translation d'adresse de la source
- Cibles: SNAT, DNAT, MASQUERADE
- Le cas spécifique OUTPUT
- Permet la modification de la destination des paquets générés localement
- La table MANGLE
- Permet le marquage de paquets générés localement (OUTPUT) et entrants (PREROUTING)
Les policies sont:
- ACCEPT
- Permet d'accepter le paquet concerné
- DROP
- Permet de rejeter le paquet concerné sans générer un message d'erreur
- REJECT
- Permet de rejeter le paquet concerné en générant une message d'erreur
Les cibles sont:
- SNAT
- Permet de modifier l'adresse source du paquet concerné
- DNAT
- Permet de modifier l'adresse de destination du paquet concerné
- MASQUERADE
- Permet de remplacer l'adresse IP privée de l'expéditeur par un socket public de la passerelle.
IPTABLES peut être configuré soit par des outils tels shorewall, soit en utilisant des lignes de commandes ou un script. Dans ce dernier cas, la ligne prend la forme:
# IPTABLES --action CHAINE --option1 --option2
Les actions sont:
Action | Abréviation | Déscription |
---|---|---|
- -append | -A | Ajouter une règle à la fin de la chaîne spécifiée |
- -delete | -D | Supprimer une règle en spécifiant son numéro ou la règle à supprimer |
- -replace | -R | Permet de remplacer la règle spécifée par son numéro |
- -insert | -I | Permet d'insérer une règle à l'endroit spécifié |
- -list | -L | Permet d'afficher des règles |
- -flush | -F | Permet de vider toutes les règles d'une chaîne |
Les options sont:
Option | Abréviation | Déscription |
---|---|---|
- -protocol | -p | Permet de spécifier un protocol - tcp, udp, icmp, all |
- -source | -s | Permet de spécifier une adresse source |
- -destination | -d | Permet de spécifier une adresse de destination |
- -in-interface | -i | Permet de spécifier une interface réseau d'entrée |
- -out-interface | -o | Permet de spécifier une interface réseau de sortie |
- -fragment | -f | Permet de ne spécifier que les paquets fragmentés |
- -source-port | -sport | Permet de spécifier un port source ou une plage de ports source |
- -destination-port | -dport | Permet de spécifier un port de destination ou une plage de ports de destination |
- -tcp-flags | s/o | Permet de spécifier un flag TCP à matcher - SYN, ACK, FIN, RST, URG, PSH, ALL, NONE |
- -icmp-type | s/o | Permet de spécifier un type de paquet ICMP |
- -mac-source | s/o | Permet de spécifier une adresse MAC |
Les options spécifiques à NET sont:
- -to-destination | s/o | Permet de spécifier l'adresse de destination d'une translation |
- -to-source | s/o | Permet spécifier l'adresse source d'une translation |
Les options spécifiques aux LOGS sont:
- -log-level | s/o | Permet de spécifier le niveau de logs |
- -log-prefix | s/o | Permet de spécifier un préfix pour les logs |
L'option spécifique au STATEFUL est:
- -state | s/o | Permet de spécifier l'état du paquet à vérifier |
Ce dernier cas fait référence au STATEFUL. Le STATEFUL est la capacité du par-feu à enregistrer dans une table spécifique, l'état des différentes connexions. Cette table s'appelle une table d'état. Le principe du fonctionnement de STATEFUL est simple, à savoir, si le paquet entrant appartient à une communication déjà établie, celui-ci n'est pas vérifié.
Il existe 4 états:
- NEW
- Le paquet concerne une nouvelle connexion et contient donc un flag SYN à 1
- ESTABLISHED
- Le paquet concerne une connexion déjà établie. Le paquet ne doit contenir ni flag SYN à 1, ni flag FIN à 1
- RELATED
- Le paquet est d'une connexion qui présente une relation avec une autre connexion
- INVALID
- La paquet provient d'une connexion anormale.
LAB #1 - La Configuration par firewalld
Firewalld utilise des zones - des jeux de règles pré-définis dans lesquels sont placés les interfaces :
- trusted - un réseau fiable. Dans ce cas tous les ports sont autorisés,
- work, home, internal - un réseau partiellement fiable. Dans ce cas quelques ports sont autorisés,
- dmz, public, external - un réseau non fiable. Dans ce cas peu de ports sont autorisés,
- block, drop - tout est interdit. La zone drop n'envoie pas de messages d'erreurs.
Important - Une interface ne peut être que dans une zone à la fois tandis que plusieurs interfaces peuvent être dans la même zone.
Le service firewalld doit toujours être lancé :
[root@centos8 ~]# systemctl status firewalld.service ● firewalld.service - firewalld - dynamic firewall daemon Loaded: loaded (/usr/lib/systemd/system/firewalld.service; enabled; vendor preset: enabled) Active: active (running) since Tue 2024-10-01 12:13:55 CEST; 1h 43min ago Docs: man:firewalld(1) Main PID: 1079 (firewalld) Tasks: 2 (limit: 100949) Memory: 32.7M CGroup: /system.slice/firewalld.service └─1079 /usr/libexec/platform-python -s /usr/sbin/firewalld --nofork --nopid Oct 01 12:13:53 centos8.ittraining.loc systemd[1]: Starting firewalld - dynamic firewall daemon... Oct 01 12:13:55 centos8.ittraining.loc systemd[1]: Started firewalld - dynamic firewall daemon. Oct 01 12:13:56 centos8.ittraining.loc firewalld[1079]: WARNING: AllowZoneDrifting is enabled. This is considered an insecure configuration option. It will be removed in a future release. [q]
La Configuration de Base de firewalld
La configuration par défaut de firewalld se trouve dans /usr/lib/firewalld :
[root@centos8 ~]# ls -l /usr/lib/firewalld/ total 16 drwxr-xr-x. 2 root root 224 Mar 6 2022 helpers drwxr-xr-x. 2 root root 4096 Mar 6 2022 icmptypes drwxr-xr-x. 2 root root 20 Mar 6 2022 ipsets drwxr-xr-x. 2 root root 33 Mar 6 2022 policies drwxr-xr-x. 2 root root 8192 Mar 6 2022 services drwxr-xr-x. 2 root root 203 Mar 6 2022 zones [root@centos8 ~]# ls -l /usr/lib/firewalld/zones total 44 -rw-r--r--. 1 root root 299 Aug 9 2021 block.xml -rw-r--r--. 1 root root 293 Aug 9 2021 dmz.xml -rw-r--r--. 1 root root 291 Aug 9 2021 drop.xml -rw-r--r--. 1 root root 304 Aug 9 2021 external.xml -rw-r--r--. 1 root root 397 Aug 9 2021 home.xml -rw-r--r--. 1 root root 412 Aug 9 2021 internal.xml -rw-r--r--. 1 root root 809 Nov 26 2019 libvirt.xml -rw-r--r--. 1 root root 729 Aug 18 2021 nm-shared.xml -rw-r--r--. 1 root root 343 Aug 9 2021 public.xml -rw-r--r--. 1 root root 162 Aug 9 2021 trusted.xml -rw-r--r--. 1 root root 339 Aug 9 2021 work.xml [root@centos8 ~]# ls -l /usr/lib/firewalld/services total 704 -rw-r--r--. 1 root root 399 Aug 9 2021 amanda-client.xml -rw-r--r--. 1 root root 427 Aug 9 2021 amanda-k5-client.xml -rw-r--r--. 1 root root 283 Aug 9 2021 amqps.xml -rw-r--r--. 1 root root 273 Aug 9 2021 amqp.xml -rw-r--r--. 1 root root 285 Aug 9 2021 apcupsd.xml -rw-r--r--. 1 root root 301 Aug 9 2021 audit.xml -rw-r--r--. 1 root root 320 Aug 9 2021 bacula-client.xml -rw-r--r--. 1 root root 346 Aug 9 2021 bacula.xml -rw-r--r--. 1 root root 429 Aug 9 2021 bb.xml -rw-r--r--. 1 root root 339 Aug 9 2021 bgp.xml -rw-r--r--. 1 root root 275 Aug 9 2021 bitcoin-rpc.xml -rw-r--r--. 1 root root 307 Aug 9 2021 bitcoin-testnet-rpc.xml -rw-r--r--. 1 root root 281 Aug 9 2021 bitcoin-testnet.xml -rw-r--r--. 1 root root 244 Aug 9 2021 bitcoin.xml -rw-r--r--. 1 root root 410 Aug 9 2021 bittorrent-lsd.xml -rw-r--r--. 1 root root 294 Aug 9 2021 ceph-mon.xml -rw-r--r--. 1 root root 329 Aug 9 2021 ceph.xml -rw-r--r--. 1 root root 168 Aug 9 2021 cfengine.xml -rw-r--r--. 1 root root 211 Aug 9 2021 cockpit.xml -rw-r--r--. 1 root root 296 Aug 9 2021 collectd.xml -rw-r--r--. 1 root root 260 Aug 9 2021 condor-collector.xml -rw-r--r--. 1 root root 296 Aug 9 2021 ctdb.xml -rw-r--r--. 1 root root 305 Aug 9 2021 dhcpv6-client.xml -rw-r--r--. 1 root root 234 Aug 9 2021 dhcpv6.xml -rw-r--r--. 1 root root 227 Aug 9 2021 dhcp.xml -rw-r--r--. 1 root root 205 Aug 9 2021 distcc.xml -rw-r--r--. 1 root root 318 Aug 9 2021 dns-over-tls.xml -rw-r--r--. 1 root root 346 Aug 9 2021 dns.xml -rw-r--r--. 1 root root 374 Aug 9 2021 docker-registry.xml -rw-r--r--. 1 root root 391 Aug 9 2021 docker-swarm.xml -rw-r--r--. 1 root root 228 Aug 9 2021 dropbox-lansync.xml -rw-r--r--. 1 root root 338 Aug 9 2021 elasticsearch.xml -rw-r--r--. 1 root root 304 Aug 9 2021 etcd-client.xml -rw-r--r--. 1 root root 304 Aug 9 2021 etcd-server.xml -rw-r--r--. 1 root root 224 Aug 9 2021 finger.xml -rw-r--r--. 1 root root 270 Aug 9 2021 foreman-proxy.xml -rw-r--r--. 1 root root 408 Aug 9 2021 foreman.xml -rw-r--r--. 1 root root 709 Aug 9 2021 freeipa-4.xml -rw-r--r--. 1 root root 489 Aug 9 2021 freeipa-ldaps.xml -rw-r--r--. 1 root root 488 Aug 9 2021 freeipa-ldap.xml -rw-r--r--. 1 root root 242 Aug 9 2021 freeipa-replication.xml -rw-r--r--. 1 root root 657 Aug 9 2021 freeipa-trust.xml -rw-r--r--. 1 root root 361 Aug 9 2021 ftp.xml -rw-r--r--. 1 root root 292 Aug 9 2021 galera.xml -rw-r--r--. 1 root root 184 Aug 9 2021 ganglia-client.xml -rw-r--r--. 1 root root 176 Aug 9 2021 ganglia-master.xml -rw-r--r--. 1 root root 212 Aug 9 2021 git.xml -rw-r--r--. 1 root root 218 Aug 9 2021 grafana.xml -rw-r--r--. 1 root root 119 Aug 9 2021 gre.xml -rw-r--r--. 1 root root 608 Aug 9 2021 high-availability.xml -rw-r--r--. 1 root root 448 Aug 9 2021 https.xml -rw-r--r--. 1 root root 353 Aug 9 2021 http.xml -rw-r--r--. 1 root root 372 Aug 9 2021 imaps.xml -rw-r--r--. 1 root root 327 Aug 9 2021 imap.xml -rw-r--r--. 1 root root 454 Aug 9 2021 ipp-client.xml -rw-r--r--. 1 root root 427 Aug 9 2021 ipp.xml -rw-r--r--. 1 root root 894 Aug 9 2021 ipsec.xml -rw-r--r--. 1 root root 255 Aug 9 2021 ircs.xml -rw-r--r--. 1 root root 247 Aug 9 2021 irc.xml -rw-r--r--. 1 root root 264 Aug 9 2021 iscsi-target.xml -rw-r--r--. 1 root root 358 Aug 9 2021 isns.xml -rw-r--r--. 1 root root 213 Aug 9 2021 jenkins.xml -rw-r--r--. 1 root root 182 Aug 9 2021 kadmin.xml -rw-r--r--. 1 root root 272 Aug 9 2021 kdeconnect.xml -rw-r--r--. 1 root root 233 Aug 9 2021 kerberos.xml -rw-r--r--. 1 root root 384 Aug 9 2021 kibana.xml -rw-r--r--. 1 root root 249 Aug 9 2021 klogin.xml -rw-r--r--. 1 root root 221 Aug 9 2021 kpasswd.xml -rw-r--r--. 1 root root 182 Aug 9 2021 kprop.xml -rw-r--r--. 1 root root 242 Aug 9 2021 kshell.xml -rw-r--r--. 1 root root 308 Aug 9 2021 kube-apiserver.xml -rw-r--r--. 1 root root 232 Aug 9 2021 ldaps.xml -rw-r--r--. 1 root root 199 Aug 9 2021 ldap.xml -rw-r--r--. 1 root root 385 Aug 9 2021 libvirt-tls.xml -rw-r--r--. 1 root root 389 Aug 9 2021 libvirt.xml -rw-r--r--. 1 root root 269 Aug 9 2021 lightning-network.xml -rw-r--r--. 1 root root 324 Aug 9 2021 llmnr.xml -rw-r--r--. 1 root root 349 Aug 9 2021 managesieve.xml -rw-r--r--. 1 root root 432 Aug 9 2021 matrix.xml -rw-r--r--. 1 root root 424 Aug 9 2021 mdns.xml -rw-r--r--. 1 root root 245 Aug 9 2021 memcache.xml -rw-r--r--. 1 root root 343 Aug 9 2021 minidlna.xml -rw-r--r--. 1 root root 237 Aug 9 2021 mongodb.xml -rw-r--r--. 1 root root 473 Aug 9 2021 mosh.xml -rw-r--r--. 1 root root 211 Aug 9 2021 mountd.xml -rw-r--r--. 1 root root 296 Aug 9 2021 mqtt-tls.xml -rw-r--r--. 1 root root 287 Aug 9 2021 mqtt.xml -rw-r--r--. 1 root root 170 Aug 9 2021 mssql.xml -rw-r--r--. 1 root root 190 Aug 9 2021 ms-wbt.xml -rw-r--r--. 1 root root 242 Aug 9 2021 murmur.xml -rw-r--r--. 1 root root 171 Aug 9 2021 mysql.xml -rw-r--r--. 1 root root 250 Aug 9 2021 nbd.xml -rw-r--r--. 1 root root 342 Aug 9 2021 nfs3.xml -rw-r--r--. 1 root root 324 Aug 9 2021 nfs.xml -rw-r--r--. 1 root root 293 Aug 9 2021 nmea-0183.xml -rw-r--r--. 1 root root 247 Aug 9 2021 nrpe.xml -rw-r--r--. 1 root root 389 Aug 9 2021 ntp.xml -rw-r--r--. 1 root root 368 Aug 9 2021 nut.xml -rw-r--r--. 1 root root 335 Aug 9 2021 openvpn.xml -rw-r--r--. 1 root root 260 Aug 9 2021 ovirt-imageio.xml -rw-r--r--. 1 root root 343 Aug 9 2021 ovirt-storageconsole.xml -rw-r--r--. 1 root root 235 Aug 9 2021 ovirt-vmconsole.xml -rw-r--r--. 1 root root 1024 Aug 9 2021 plex.xml -rw-r--r--. 1 root root 433 Aug 9 2021 pmcd.xml -rw-r--r--. 1 root root 474 Aug 9 2021 pmproxy.xml -rw-r--r--. 1 root root 544 Aug 9 2021 pmwebapis.xml -rw-r--r--. 1 root root 460 Aug 9 2021 pmwebapi.xml -rw-r--r--. 1 root root 357 Aug 9 2021 pop3s.xml -rw-r--r--. 1 root root 348 Aug 9 2021 pop3.xml -rw-r--r--. 1 root root 181 Aug 9 2021 postgresql.xml -rw-r--r--. 1 root root 509 Aug 9 2021 privoxy.xml -rw-r--r--. 1 root root 213 Aug 9 2021 prometheus.xml -rw-r--r--. 1 root root 261 Aug 9 2021 proxy-dhcp.xml -rw-r--r--. 1 root root 424 Aug 9 2021 ptp.xml -rw-r--r--. 1 root root 414 Aug 9 2021 pulseaudio.xml -rw-r--r--. 1 root root 297 Aug 9 2021 puppetmaster.xml -rw-r--r--. 1 root root 273 Aug 9 2021 quassel.xml -rw-r--r--. 1 root root 520 Aug 9 2021 radius.xml -rw-r--r--. 1 root root 183 Aug 9 2021 rdp.xml -rw-r--r--. 1 root root 212 Aug 9 2021 redis-sentinel.xml -rw-r--r--. 1 root root 268 Aug 9 2021 redis.xml -rw-r--r--. 1 root root 381 Aug 9 2021 RH-Satellite-6-capsule.xml -rw-r--r--. 1 root root 556 Aug 9 2021 RH-Satellite-6.xml -rw-r--r--. 1 root root 214 Aug 9 2021 rpc-bind.xml -rw-r--r--. 1 root root 213 Aug 9 2021 rquotad.xml -rw-r--r--. 1 root root 310 Aug 9 2021 rsh.xml -rw-r--r--. 1 root root 311 Aug 9 2021 rsyncd.xml -rw-r--r--. 1 root root 350 Aug 9 2021 rtsp.xml -rw-r--r--. 1 root root 329 Aug 9 2021 salt-master.xml -rw-r--r--. 1 root root 371 Aug 9 2021 samba-client.xml -rw-r--r--. 1 root root 1298 Aug 9 2021 samba-dc.xml -rw-r--r--. 1 root root 448 Aug 9 2021 samba.xml -rw-r--r--. 1 root root 324 Aug 9 2021 sane.xml -rw-r--r--. 1 root root 283 Aug 9 2021 sips.xml -rw-r--r--. 1 root root 496 Aug 9 2021 sip.xml -rw-r--r--. 1 root root 299 Aug 9 2021 slp.xml -rw-r--r--. 1 root root 231 Aug 9 2021 smtp-submission.xml -rw-r--r--. 1 root root 577 Aug 9 2021 smtps.xml -rw-r--r--. 1 root root 550 Aug 9 2021 smtp.xml -rw-r--r--. 1 root root 308 Aug 9 2021 snmptrap.xml -rw-r--r--. 1 root root 342 Aug 9 2021 snmp.xml -rw-r--r--. 1 root root 405 Aug 9 2021 spideroak-lansync.xml -rw-r--r--. 1 root root 275 Aug 9 2021 spotify-sync.xml -rw-r--r--. 1 root root 173 Aug 9 2021 squid.xml -rw-r--r--. 1 root root 421 Aug 9 2021 ssdp.xml -rw-r--r--. 1 root root 463 Aug 9 2021 ssh.xml -rw-r--r--. 1 root root 631 Aug 9 2021 steam-streaming.xml -rw-r--r--. 1 root root 287 Aug 9 2021 svdrp.xml -rw-r--r--. 1 root root 231 Aug 9 2021 svn.xml -rw-r--r--. 1 root root 297 Aug 9 2021 syncthing-gui.xml -rw-r--r--. 1 root root 311 Aug 9 2021 syncthing.xml -rw-r--r--. 1 root root 496 Aug 9 2021 synergy.xml -rw-r--r--. 1 root root 444 Aug 9 2021 syslog-tls.xml -rw-r--r--. 1 root root 329 Aug 9 2021 syslog.xml -rw-r--r--. 1 root root 393 Aug 9 2021 telnet.xml -rw-r--r--. 1 root root 252 Aug 9 2021 tentacle.xml -rw-r--r--. 1 root root 288 Aug 9 2021 tftp-client.xml -rw-r--r--. 1 root root 424 Aug 9 2021 tftp.xml -rw-r--r--. 1 root root 221 Aug 9 2021 tile38.xml -rw-r--r--. 1 root root 336 Aug 9 2021 tinc.xml -rw-r--r--. 1 root root 771 Aug 9 2021 tor-socks.xml -rw-r--r--. 1 root root 244 Aug 9 2021 transmission-client.xml -rw-r--r--. 1 root root 264 Aug 9 2021 upnp-client.xml -rw-r--r--. 1 root root 593 Aug 9 2021 vdsm.xml -rw-r--r--. 1 root root 475 Aug 9 2021 vnc-server.xml -rw-r--r--. 1 root root 310 Aug 9 2021 wbem-https.xml -rw-r--r--. 1 root root 352 Aug 9 2021 wbem-http.xml -rw-r--r--. 1 root root 323 Aug 9 2021 wsmans.xml -rw-r--r--. 1 root root 316 Aug 9 2021 wsman.xml -rw-r--r--. 1 root root 329 Aug 9 2021 xdmcp.xml -rw-r--r--. 1 root root 509 Aug 9 2021 xmpp-bosh.xml -rw-r--r--. 1 root root 488 Aug 9 2021 xmpp-client.xml -rw-r--r--. 1 root root 264 Aug 9 2021 xmpp-local.xml -rw-r--r--. 1 root root 545 Aug 9 2021 xmpp-server.xml -rw-r--r--. 1 root root 314 Aug 9 2021 zabbix-agent.xml -rw-r--r--. 1 root root 315 Aug 9 2021 zabbix-server.xml [root@centos8 ~]# ls -l /usr/lib/firewalld/icmptypes/ total 180 -rw-r--r--. 1 root root 385 Aug 9 2021 address-unreachable.xml -rw-r--r--. 1 root root 258 Aug 9 2021 bad-header.xml -rw-r--r--. 1 root root 294 Aug 9 2021 beyond-scope.xml -rw-r--r--. 1 root root 279 Aug 9 2021 communication-prohibited.xml -rw-r--r--. 1 root root 222 Aug 9 2021 destination-unreachable.xml -rw-r--r--. 1 root root 173 Aug 9 2021 echo-reply.xml -rw-r--r--. 1 root root 210 Aug 9 2021 echo-request.xml -rw-r--r--. 1 root root 261 Aug 9 2021 failed-policy.xml -rw-r--r--. 1 root root 280 Aug 9 2021 fragmentation-needed.xml -rw-r--r--. 1 root root 266 Aug 9 2021 host-precedence-violation.xml -rw-r--r--. 1 root root 257 Aug 9 2021 host-prohibited.xml -rw-r--r--. 1 root root 242 Aug 9 2021 host-redirect.xml -rw-r--r--. 1 root root 239 Aug 9 2021 host-unknown.xml -rw-r--r--. 1 root root 247 Aug 9 2021 host-unreachable.xml -rw-r--r--. 1 root root 229 Aug 9 2021 ip-header-bad.xml -rw-r--r--. 1 root root 355 Aug 9 2021 neighbour-advertisement.xml -rw-r--r--. 1 root root 457 Aug 9 2021 neighbour-solicitation.xml -rw-r--r--. 1 root root 250 Aug 9 2021 network-prohibited.xml -rw-r--r--. 1 root root 248 Aug 9 2021 network-redirect.xml -rw-r--r--. 1 root root 239 Aug 9 2021 network-unknown.xml -rw-r--r--. 1 root root 247 Aug 9 2021 network-unreachable.xml -rw-r--r--. 1 root root 239 Aug 9 2021 no-route.xml -rw-r--r--. 1 root root 328 Aug 9 2021 packet-too-big.xml -rw-r--r--. 1 root root 225 Aug 9 2021 parameter-problem.xml -rw-r--r--. 1 root root 233 Aug 9 2021 port-unreachable.xml -rw-r--r--. 1 root root 256 Aug 9 2021 precedence-cutoff.xml -rw-r--r--. 1 root root 249 Aug 9 2021 protocol-unreachable.xml -rw-r--r--. 1 root root 185 Aug 9 2021 redirect.xml -rw-r--r--. 1 root root 244 Aug 9 2021 reject-route.xml -rw-r--r--. 1 root root 241 Aug 9 2021 required-option-missing.xml -rw-r--r--. 1 root root 227 Aug 9 2021 router-advertisement.xml -rw-r--r--. 1 root root 223 Aug 9 2021 router-solicitation.xml -rw-r--r--. 1 root root 248 Aug 9 2021 source-quench.xml -rw-r--r--. 1 root root 236 Aug 9 2021 source-route-failed.xml -rw-r--r--. 1 root root 253 Aug 9 2021 time-exceeded.xml -rw-r--r--. 1 root root 233 Aug 9 2021 timestamp-reply.xml -rw-r--r--. 1 root root 228 Aug 9 2021 timestamp-request.xml -rw-r--r--. 1 root root 258 Aug 9 2021 tos-host-redirect.xml -rw-r--r--. 1 root root 257 Aug 9 2021 tos-host-unreachable.xml -rw-r--r--. 1 root root 272 Aug 9 2021 tos-network-redirect.xml -rw-r--r--. 1 root root 269 Aug 9 2021 tos-network-unreachable.xml -rw-r--r--. 1 root root 293 Aug 9 2021 ttl-zero-during-reassembly.xml -rw-r--r--. 1 root root 256 Aug 9 2021 ttl-zero-during-transit.xml -rw-r--r--. 1 root root 259 Aug 9 2021 unknown-header-type.xml -rw-r--r--. 1 root root 249 Aug 9 2021 unknown-option.xml
Ces fichiers sont au format xml, par exemple :
[root@centos8 ~]# cat /usr/lib/firewalld/zones/home.xml <?xml version="1.0" encoding="utf-8"?> <zone> <short>Home</short> <description>For use in home areas. You mostly trust the other computers on networks to not harm your computer. Only selected incoming connections are accepted.</description> <service name="ssh"/> <service name="mdns"/> <service name="samba-client"/> <service name="dhcpv6-client"/> <service name="cockpit"/> </zone>
La configuration de firewalld ainsi que les définitions et règles personnalisées se trouvent dans /etc/firewalld :
[root@centos8 ~]# ls -l /etc/firewalld/ total 8 -rw-r--r--. 1 root root 2840 Aug 9 2021 firewalld.conf drwxr-x---. 2 root root 6 Aug 9 2021 helpers drwxr-x---. 2 root root 6 Aug 9 2021 icmptypes drwxr-x---. 2 root root 6 Aug 9 2021 ipsets -rw-r--r--. 1 root root 283 Aug 9 2021 lockdown-whitelist.xml drwxr-x---. 2 root root 6 Aug 9 2021 policies drwxr-x---. 2 root root 6 Aug 9 2021 services drwxr-x---. 2 root root 46 Aug 9 2021 zones [root@centos8 ~]# ls -l /etc/firewalld/zones/ total 8 -rw-r--r--. 1 root root 380 Jun 16 2021 public.xml -rw-r--r--. 1 root root 343 Jun 16 2021 public.xml.old [root@centos8 ~]# ls -l /etc/firewalld/services/ total 0 [root@centos8 ~]# ls -l /etc/firewalld/icmptypes/ total 0
Le fichier de configuration de firewalld est /etc/firewalld/firewalld.conf :
[root@centos8 ~]# cat /etc/firewalld/firewalld.conf # firewalld config file # default zone # The default zone used if an empty zone string is used. # Default: public DefaultZone=public # Clean up on exit # If set to no or false the firewall configuration will not get cleaned up # on exit or stop of firewalld # Default: yes CleanupOnExit=yes # Lockdown # If set to enabled, firewall changes with the D-Bus interface will be limited # to applications that are listed in the lockdown whitelist. # The lockdown whitelist file is lockdown-whitelist.xml # Default: no Lockdown=no # IPv6_rpfilter # Performs a reverse path filter test on a packet for IPv6. If a reply to the # packet would be sent via the same interface that the packet arrived on, the # packet will match and be accepted, otherwise dropped. # The rp_filter for IPv4 is controlled using sysctl. # Note: This feature has a performance impact. See man page FIREWALLD.CONF(5) # for details. # Default: yes IPv6_rpfilter=yes # IndividualCalls # Do not use combined -restore calls, but individual calls. This increases the # time that is needed to apply changes and to start the daemon, but is good for # debugging. # Default: no IndividualCalls=no # LogDenied # Add logging rules right before reject and drop rules in the INPUT, FORWARD # and OUTPUT chains for the default rules and also final reject and drop rules # in zones. Possible values are: all, unicast, broadcast, multicast and off. # Default: off LogDenied=off # FirewallBackend # Selects the firewall backend implementation. # Choices are: # - nftables (default) # - iptables (iptables, ip6tables, ebtables and ipset) FirewallBackend=nftables # FlushAllOnReload # Flush all runtime rules on a reload. In previous releases some runtime # configuration was retained during a reload, namely; interface to zone # assignment, and direct rules. This was confusing to users. To get the old # behavior set this to "no". # Default: yes FlushAllOnReload=yes # RFC3964_IPv4 # As per RFC 3964, filter IPv6 traffic with 6to4 destination addresses that # correspond to IPv4 addresses that should not be routed over the public # internet. # Defaults to "yes". RFC3964_IPv4=yes # AllowZoneDrifting # Older versions of firewalld had undocumented behavior known as "zone # drifting". This allowed packets to ingress multiple zones - this is a # violation of zone based firewalls. However, some users rely on this behavior # to have a "catch-all" zone, e.g. the default zone. You can enable this if you # desire such behavior. It's disabled by default for security reasons. # Note: If "yes" packets will only drift from source based zones to interface # based zones (including the default zone). Packets never drift from interface # based zones to other interfaces based zones (including the default zone). # Possible values; "yes", "no". Defaults to "yes". AllowZoneDrifting=yes
La Commande firewall-cmd
firewalld s'appuie sur netfilter. Pour cette raison, l'utilisation de firewall-cmd est incompatible avec l'utilisation des commandes iptables et system-config-firewall.
Important - firewall-cmd est le front-end de firewalld en ligne de commande. Il existe aussi la commande firewall-config qui lance un outi de configuration graphique.
Pour obtenir la liste de toutes les zones prédéfinies, utilisez la commande suivante :
[root@centos8 ~]# firewall-cmd --get-zones block dmz drop external home internal libvirt nm-shared public trusted work
Pour obtenir la liste de toutes les services prédéfinis, utilisez la commande suivante :
[root@centos8 ~]# firewall-cmd --get-services RH-Satellite-6 RH-Satellite-6-capsule amanda-client amanda-k5-client amqp amqps apcupsd audit bacula bacula-client bb bgp bitcoin bitcoin-rpc bitcoin-testnet bitcoin-testnet-rpc bittorrent-lsd ceph ceph-mon cfengine cockpit collectd condor-collector ctdb dhcp dhcpv6 dhcpv6-client distcc dns dns-over-tls docker-registry docker-swarm dropbox-lansync elasticsearch etcd-client etcd-server finger foreman foreman-proxy freeipa-4 freeipa-ldap freeipa-ldaps freeipa-replication freeipa-trust ftp galera ganglia-client ganglia-master git grafana gre high-availability http https imap imaps ipp ipp-client ipsec irc ircs iscsi-target isns jenkins kadmin kdeconnect kerberos kibana klogin kpasswd kprop kshell kube-apiserver ldap ldaps libvirt libvirt-tls lightning-network llmnr managesieve matrix mdns memcache minidlna mongodb mosh mountd mqtt mqtt-tls ms-wbt mssql murmur mysql nbd nfs nfs3 nmea-0183 nrpe ntp nut openvpn ovirt-imageio ovirt-storageconsole ovirt-vmconsole plex pmcd pmproxy pmwebapi pmwebapis pop3 pop3s postgresql privoxy prometheus proxy-dhcp ptp pulseaudio puppetmaster quassel radius rdp redis redis-sentinel rpc-bind rquotad rsh rsyncd rtsp salt-master samba samba-client samba-dc sane sip sips slp smtp smtp-submission smtps snmp snmptrap spideroak-lansync spotify-sync squid ssdp ssh steam-streaming svdrp svn syncthing syncthing-gui synergy syslog syslog-tls telnet tentacle tftp tftp-client tile38 tinc tor-socks transmission-client upnp-client vdsm vnc-server wbem-http wbem-https wsman wsmans xdmcp xmpp-bosh xmpp-client xmpp-local xmpp-server zabbix-agent zabbix-server
Pour obtenir la liste de toutes les types ICMP prédéfinis, utilisez la commande suivante :
[root@centos8 ~]# firewall-cmd --get-icmptypes address-unreachable bad-header beyond-scope communication-prohibited destination-unreachable echo-reply echo-request failed-policy fragmentation-needed host-precedence-violation host-prohibited host-redirect host-unknown host-unreachable ip-header-bad neighbour-advertisement neighbour-solicitation network-prohibited network-redirect network-unknown network-unreachable no-route packet-too-big parameter-problem port-unreachable precedence-cutoff protocol-unreachable redirect reject-route required-option-missing router-advertisement router-solicitation source-quench source-route-failed time-exceeded timestamp-reply timestamp-request tos-host-redirect tos-host-unreachable tos-network-redirect tos-network-unreachable ttl-zero-during-reassembly ttl-zero-during-transit unknown-header-type unknown-option
Pour obtenir la liste des zones de la configuration courante, utilisez la commande suivante :
[root@centos8 ~]# firewall-cmd --get-active-zones libvirt interfaces: virbr0 public interfaces: ens18
Pour obtenir la liste des zones de la configuration courante pour une interface spécifique, utilisez la commande suivante :
[root@centos8 ~]# firewall-cmd --get-zone-of-interface=ens18 public
Pour obtenir la liste des services autorisés pour la zone public, utilisez la commande suivante :
[root@centos8 ~]# firewall-cmd --zone=public --list-services cockpit dhcpv6-client ssh
Pour obtenir toute la configuration pour la zone public, utilisez la commande suivante :
[root@centos8 ~]# firewall-cmd --get-active-zones libvirt interfaces: virbr0 public interfaces: ens18 [root@centos8 ~]# firewall-cmd --get-zone-of-interface=ens18 public [root@centos8 ~]# firewall-cmd --zone=public --list-services cockpit dhcpv6-client ssh [root@centos8 ~]# firewall-cmd --zone=public --list-all public (active) target: default icmp-block-inversion: no interfaces: ens18 sources: services: cockpit dhcpv6-client ssh ports: 5901/tcp protocols: forward: no masquerade: no forward-ports: source-ports: icmp-blocks: rich rules:
Pour obtenir la liste complète de toutes les zones et leurs configurations, utilisez la commande suivante :
root@centos8 ~]# firewall-cmd --zone=public --list-all public (active) target: default icmp-block-inversion: no interfaces: ens18 sources: services: cockpit dhcpv6-client ssh ports: 5901/tcp protocols: forward: no masquerade: no forward-ports: source-ports: icmp-blocks: rich rules: [root@centos8 ~]# firewall-cmd --list-all-zones block target: %%REJECT%% icmp-block-inversion: no interfaces: sources: services: ports: protocols: forward: no masquerade: no forward-ports: source-ports: icmp-blocks: rich rules: dmz target: default icmp-block-inversion: no interfaces: sources: services: ssh ports: protocols: forward: no masquerade: no forward-ports: source-ports: icmp-blocks: rich rules: drop target: DROP icmp-block-inversion: no interfaces: sources: services: ports: protocols: forward: no masquerade: no forward-ports: source-ports: icmp-blocks: rich rules: external target: default icmp-block-inversion: no interfaces: sources: services: ssh ports: protocols: forward: no masquerade: yes forward-ports: source-ports: icmp-blocks: rich rules: home target: default icmp-block-inversion: no interfaces: sources: services: cockpit dhcpv6-client mdns samba-client ssh ports: protocols: forward: no masquerade: no forward-ports: source-ports: icmp-blocks: rich rules: internal target: default icmp-block-inversion: no interfaces: sources: services: cockpit dhcpv6-client mdns samba-client ssh ports: protocols: forward: no masquerade: no forward-ports: source-ports: icmp-blocks: rich rules: libvirt (active) target: ACCEPT icmp-block-inversion: no interfaces: virbr0 sources: services: dhcp dhcpv6 dns ssh tftp ports: protocols: icmp ipv6-icmp forward: no masquerade: no forward-ports: source-ports: icmp-blocks: rich rules: rule priority="32767" reject nm-shared target: ACCEPT icmp-block-inversion: no interfaces: sources: services: dhcp dns ssh ports: protocols: icmp ipv6-icmp forward: no masquerade: no forward-ports: source-ports: icmp-blocks: rich rules: rule priority="32767" reject public (active) target: default icmp-block-inversion: no interfaces: ens18 sources: services: cockpit dhcpv6-client ssh ports: 5901/tcp protocols: forward: no masquerade: no forward-ports: source-ports: icmp-blocks: rich rules: trusted target: ACCEPT icmp-block-inversion: no interfaces: sources: services: ports: protocols: forward: no masquerade: no forward-ports: source-ports: icmp-blocks: rich rules: work target: default icmp-block-inversion: no interfaces: sources: services: cockpit dhcpv6-client ssh ports: protocols: forward: no masquerade: no forward-ports: source-ports: icmp-blocks: rich rules:
Pour changer la zone par défaut de public à work, utilisez la commande suivante :
[root@centos8 ~]# firewall-cmd --set-default-zone=work success [root@centos8 ~]# firewall-cmd --get-active-zones libvirt interfaces: virbr0 work interfaces: ens18
Pour ajouter l'interface ip_fixe à la zone work, utilisez la commande suivante :
[root@centos8 ~]# firewall-cmd --zone=work --add-interface=ip_fixe success [root@centos8 ~]# firewall-cmd --get-active-zones libvirt interfaces: virbr0 work interfaces: ens18 ip_fixe
Pour supprimer l'interface ip_fixe à la zone work, utilisez la commande suivante :
[root@centos8 ~]# firewall-cmd --zone=work --remove-interface=ip_fixe success [root@centos8 ~]# firewall-cmd --get-active-zones libvirt interfaces: virbr0 work interfaces: ens18
Pour ajouter le service http à la zone work, utilisez la commande suivante :
[root@centos8 ~]# firewall-cmd --zone=work --add-service=http success [root@centos8 ~]# firewall-cmd --zone=work --list-services cockpit dhcpv6-client http ssh
Pour supprimer le service http de la zone work, utilisez la commande suivante :
[root@centos8 ~]# firewall-cmd --zone=work --remove-service=http success [root@centos8 ~]# firewall-cmd --zone=work --list-services cockpit dhcpv6-client ssh
Pour ajouter un nouveau bloc ICMP, utilisez la commande suivante :
[root@centos8 ~]# firewall-cmd --zone=work --add-icmp-block=echo-reply success [root@centos8 ~]# firewall-cmd --zone=work --list-icmp-blocks echo-reply
Pour supprimer un bloc ICMP, utilisez la commande suivante :
[root@centos8 ~]# firewall-cmd --zone=work --remove-icmp-block=echo-reply success [root@centos8 ~]# firewall-cmd --zone=work --list-icmp-blocks [root@centos8 ~]#
Pour ajouter le port 591/tcp à la zone work, utilisez la commande suivante :
[root@centos8 ~]# firewall-cmd --zone=work --add-port=591/tcp success [root@centos8 ~]# firewall-cmd --zone=work --list-ports 591/tcp
Pour supprimer le port 591/tcp à la zone work, utilisez la commande suivante :
[root@centos8 ~]# firewall-cmd --zone=work --remove-port=591/tcp success [root@centos8 ~]# firewall-cmd --zone=work --list-ports [root@centos8 ~]#
Pour créer un nouveau service, il convient de :
- copier un fichier existant se trouvant dans le répertoire /usr/lib/firewalld/services vers /etc/firewalld/services,
- modifier le fichier,
- recharger la configuration de firewalld,
- vérifier que firewalld voit le nouveau service.
Par exemple :
[root@centos8 ~]# cp /usr/lib/firewalld/services/http.xml /etc/firewalld/services/filemaker.xml [root@centos8 ~]# vi /etc/firewalld/services/filemaker.xml [root@centos8 ~]# cat /etc/firewalld/services/filemaker.xml <?xml version="1.0" encoding="utf-8"?> <service> <short>FileMakerPro</short> <description>fichier de service firewalld pour FileMaker Pro</description> <port protocol="tcp" port="591"/> </service> [root@centos8 ~]# firewall-cmd --reload success [root@centos8 ~]# firewall-cmd --get-services RH-Satellite-6 RH-Satellite-6-capsule amanda-client amanda-k5-client amqp amqps apcupsd audit bacula bacula-client bb bgp bitcoin bitcoin-rpc bitcoin-testnet bitcoin-testnet-rpc bittorrent-lsd ceph ceph-mon cfengine cockpit collectd condor-collector ctdb dhcp dhcpv6 dhcpv6-client distcc dns dns-over-tls docker-registry docker-swarm dropbox-lansync elasticsearch etcd-client etcd-server filemaker finger foreman foreman-proxy freeipa-4 freeipa-ldap freeipa-ldaps freeipa-replication freeipa-trust ftp galera ganglia-client ganglia-master git grafana gre high-availability http https imap imaps ipp ipp-client ipsec irc ircs iscsi-target isns jenkins kadmin kdeconnect kerberos kibana klogin kpasswd kprop kshell kube-apiserver ldap ldaps libvirt libvirt-tls lightning-network llmnr managesieve matrix mdns memcache minidlna mongodb mosh mountd mqtt mqtt-tls ms-wbt mssql murmur mysql nbd nfs nfs3 nmea-0183 nrpe ntp nut openvpn ovirt-imageio ovirt-storageconsole ovirt-vmconsole plex pmcd pmproxy pmwebapi pmwebapis pop3 pop3s postgresql privoxy prometheus proxy-dhcp ptp pulseaudio puppetmaster quassel radius rdp redis redis-sentinel rpc-bind rquotad rsh rsyncd rtsp salt-master samba samba-client samba-dc sane sip sips slp smtp smtp-submission smtps snmp snmptrap spideroak-lansync spotify-sync squid ssdp ssh steam-streaming svdrp svn syncthing syncthing-gui synergy syslog syslog-tls telnet tentacle tftp tftp-client tile38 tinc tor-socks transmission-client upnp-client vdsm vnc-server wbem-http wbem-https wsman wsmans xdmcp xmpp-bosh xmpp-client xmpp-local xmpp-server zabbix-agent zabbix-server
La Configuration Avancée de firewalld
La configuration de base de firewalld ne permet que la configuration des zones, services, blocs ICMP et les ports non-standard. Cependant firewalld peut également être configuré avec des Rich Rules ou Règles Riches. Rich Rules ou Règles Riches évaluent des critères pour ensuite entreprendre une action.
Les Critères sont :
- source address=“<adresse_IP>“
- destination address=”<adresse_IP>“,
- rule port port=”<numéro_du_port>“,
- service name=<nom_d'un_sevice_prédéfini>.
Les Actions sont :
- accept,
- reject,
- une Action reject peut être associée avec un message d'erreur spécifique par la clause type=”<type_d'erreur>,
- drop.
Saisissez la commande suivante pour ouvrir le port 80 :
[root@centos8 ~]# firewall-cmd --add-rich-rule='rule port port="80" protocol="tcp" accept' success
Important - Notez que la Rich Rule doit être entourée de caractères '.
Important - Notez que la Rich Rule a créé deux règles, une pour IPv4 et une deuxième pour IPv6. Une règle peut être créée pour IPv4 seul en incluant le Critère family=ipv4. De la même façon, une règle peut être créée pour IPv6 seul en incluant le Critère family=ipv6.
Cette nouvelle règle est écrite en mémoire mais non pas sur disque. Pour l'écrire sur disque dans le fichier zone se trouvant dans /etc/firewalld, il faut ajouter l'option –permanent :
[root@centos8 ~]# firewall-cmd --add-rich-rule='rule port port="80" protocol="tcp" accept' --permanent success [root@centos8 ~]# cat /etc/firewalld/zones/work.xml <?xml version="1.0" encoding="utf-8"?> <zone> <short>Work</short> <description>For use in work areas. You mostly trust the other computers on networks to not harm your computer. Only selected incoming connections are accepted.</description> <service name="ssh"/> <service name="dhcpv6-client"/> <service name="cockpit"/> <rule> <port port="80" protocol="tcp"/> <accept/> </rule> </zone>
Important - Attention ! La règle ajoutée avec l'option –permanent n'est pas prise en compte imédiatement mais uniquement au prochain redémmarge. Pour qu'une règle soit appliquée immédiatement et être écrite sur disque, il faut saisir la commande deux fois dont une avec l'option –permanent et l'autre sans l'option –permanent.
Redémarrez le service firewalld :
[root@centos8 ~]# systemctl restart firewalld.service
Pour visualiser cette règle dans la configuration de firewalld, il convient de saisir la commande suivante :
[root@centos8 ~]# firewall-cmd --zone=work --list-all work (active) target: default icmp-block-inversion: no interfaces: ens18 sources: services: cockpit dhcpv6-client ssh ports: protocols: forward: no masquerade: no forward-ports: source-ports: icmp-blocks: rich rules: rule port port="80" protocol="tcp" accept
Notez que la Rich Rule est créée dans la Zone par Défaut. Il est possible de créer une Rich Rule dans une autre zone en utilisant l'option –zone=<zone> de la commande firewall-cmd :
[root@centos8 ~]# firewall-cmd --zone=public --add-rich-rule='rule port port="80" protocol="tcp" accept' success [root@centos8 ~]# firewall-cmd --zone=public --list-all public target: default icmp-block-inversion: no interfaces: sources: services: cockpit dhcpv6-client ssh ports: 5901/tcp protocols: forward: no masquerade: no forward-ports: source-ports: icmp-blocks: rich rules: rule port port="80" protocol="tcp" accept
Pour supprimer une Rich Rule, il faut copier la ligne entière la concernant qui se trouve dans la sortie de la commande firewall-cmd –list-all-zones :
[root@centos8 ~]# firewall-cmd --zone=public --remove-rich-rule='rule port port="80" protocol="tcp" accept' success
Le mode Panic de firewalld
Le mode Panic de firewalld permet de bloquer tout le trafic avec une seule commande. Pour connaître l'état du mode Panic, utilisez la commande suivante :
[root@centos8 ~]# firewall-cmd --query-panic no
Pour activer le mode Panic, il convient de saisir la commande suivante :
# firewall-cmd --panic-on
Pour désactiver le mode Panic, il convient de saisir la commande suivante :
# firewall-cmd --panic-off
System Hardening
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 installes puis de supprimer ceux qui sont juges être inutiles :
[root@centos8 ~]# rpm -qa | more librepo-1.14.0-2.el8.x86_64 prefixdevname-0.1.0-6.el8.x86_64 zip-3.0-23.el8.x86_64 gnome-shell-extension-desktop-icons-3.32.1-22.el8_5.noarch python3-setuptools-wheel-39.2.0-6.el8.noarch perl-Term-Cap-1.17-395.el8.noarch accountsservice-libs-0.6.55-2.el8_5.2.x86_64 enchant2-2.2.3-3.el8.x86_64 google-noto-sans-lisu-fonts-20161022-7.el8.1.noarch ipset-libs-7.1-1.el8.x86_64 pangomm-2.40.1-6.el8.x86_64 anaconda-gui-33.16.5.6-1.el8.x86_64 libibverbs-35.0-1.el8.x86_64 thai-scalable-waree-fonts-0.6.5-1.el8.noarch libidn-1.34-5.el8.x86_64 tuned-2.16.0-1.el8.noarch kbd-legacy-2.0.4-10.el8.noarch NetworkManager-team-1.32.10-4.el8.x86_64 lohit-kannada-fonts-2.5.4-3.el8.noarch ipxe-roms-qemu-20181214-8.git133f4c47.el8.noarch openssh-server-8.0p1-10.el8.x86_64 sssd-nfs-idmap-2.5.2-2.el8_5.3.x86_64 cronie-anacron-1.5.2-4.el8.x86_64 libgdither-0.6-17.el8.x86_64 libcanberra-gtk3-0.30-18.el8.x86_64 net-snmp-libs-5.8-22.el8.x86_64 libnl3-3.5.0-1.el8.x86_64 libblockdev-lvm-2.24-7.el8.x86_64 libjose-10-2.el8.x86_64 jq-1.5-12.el8.x86_64 zenity-3.28.1-1.el8.x86_64 lz4-1.8.3-3.el8_4.x86_64 flatpak-selinux-1.8.5-5.el8_5.noarch python3-ordered-set-2.0.2-4.el8.noarch bash-4.4.20-2.el8.x86_64 libpkgconf-1.4.2-1.el8.x86_64 gnome-keyring-3.28.2-1.el8.x86_64 iwl100-firmware-39.31.5.1-103.el8.1.noarch python3-libstoragemgmt-1.9.1-1.el8.x86_64 libtevent-0.11.0-0.el8.x86_64 gnome-themes-standard-3.22.3-4.el8.x86_64 augeas-libs-1.12.0-6.el8.x86_64 fprintd-pam-1.90.9-2.el8.x86_64 setroubleshoot-plugins-3.3.14-1.el8.noarch osinfo-db-tools-1.9.0-1.el8.x86_64 libwayland-server-1.19.0-1.el8.x86_64 libvirt-daemon-driver-interface-6.0.0-37.module_el8.5.0+1002+36725df2.x86_64 kernel-modules-4.18.0-305.3.1.el8.x86_64 libbpf-0.4.0-1.el8.x86_64 libexif-0.6.22-5.el8_3.x86_64 python3-simpleline-1.1.1-2.el8.noarch cockpit-system-251.1-1.el8.noarch python3-setools-4.3.0-2.el8.x86_64 perl-IO-1.38-420.el8.x86_64 ibus-typing-booster-2.1.0-5.el8.noarch --More-- [q]
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 juges être inutiles;
- ps aux
- chkconfig –list
- systemctl list-unit-files
[root@centos8 ~]# ps aux | more USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 1 0.0 0.0 241416 14192 ? Ss 12:13 0:02 /usr/lib/systemd/systemd --switched-root --system --deserialize 18 root 2 0.0 0.0 0 0 ? S 12:13 0:00 [kthreadd] root 3 0.0 0.0 0 0 ? I< 12:13 0:00 [rcu_gp] root 4 0.0 0.0 0 0 ? I< 12:13 0:00 [rcu_par_gp] root 6 0.0 0.0 0 0 ? I< 12:13 0:00 [kworker/0:0H-events_highpri] root 9 0.0 0.0 0 0 ? I< 12:13 0:00 [mm_percpu_wq] root 10 0.0 0.0 0 0 ? S 12:13 0:00 [ksoftirqd/0] root 11 0.0 0.0 0 0 ? I 12:13 0:00 [rcu_sched] root 12 0.0 0.0 0 0 ? S 12:13 0:00 [migration/0] root 13 0.0 0.0 0 0 ? S 12:13 0:00 [watchdog/0] root 14 0.0 0.0 0 0 ? S 12:13 0:00 [cpuhp/0] root 15 0.0 0.0 0 0 ? S 12:13 0:00 [cpuhp/1] root 16 0.0 0.0 0 0 ? S 12:13 0:00 [watchdog/1] root 17 0.0 0.0 0 0 ? S 12:13 0:00 [migration/1] root 18 0.0 0.0 0 0 ? S 12:13 0:00 [ksoftirqd/1] root 20 0.0 0.0 0 0 ? I< 12:13 0:00 [kworker/1:0H-events_highpri] root 21 0.0 0.0 0 0 ? S 12:13 0:00 [cpuhp/2] root 22 0.0 0.0 0 0 ? S 12:13 0:00 [watchdog/2] root 23 0.0 0.0 0 0 ? S 12:13 0:00 [migration/2] root 24 0.0 0.0 0 0 ? S 12:13 0:00 [ksoftirqd/2] root 26 0.0 0.0 0 0 ? I< 12:13 0:00 [kworker/2:0H-events_highpri] root 27 0.0 0.0 0 0 ? S 12:13 0:00 [cpuhp/3] root 28 0.0 0.0 0 0 ? S 12:13 0:00 [watchdog/3] root 29 0.0 0.0 0 0 ? S 12:13 0:00 [migration/3] root 30 0.0 0.0 0 0 ? S 12:13 0:00 [ksoftirqd/3] root 32 0.0 0.0 0 0 ? I< 12:13 0:00 [kworker/3:0H-events_highpri] root 33 0.0 0.0 0 0 ? S 12:13 0:00 [cpuhp/4] root 34 0.0 0.0 0 0 ? S 12:13 0:00 [watchdog/4] root 35 0.0 0.0 0 0 ? S 12:13 0:00 [migration/4] root 36 0.0 0.0 0 0 ? S 12:13 0:00 [ksoftirqd/4] root 38 0.0 0.0 0 0 ? I< 12:13 0:00 [kworker/4:0H-events_highpri] root 39 0.0 0.0 0 0 ? S 12:13 0:00 [cpuhp/5] root 40 0.0 0.0 0 0 ? S 12:13 0:00 [watchdog/5] root 41 0.0 0.0 0 0 ? S 12:13 0:00 [migration/5] root 42 0.0 0.0 0 0 ? S 12:13 0:00 [ksoftirqd/5] root 44 0.0 0.0 0 0 ? I< 12:13 0:00 [kworker/5:0H-events_highpri] root 45 0.0 0.0 0 0 ? S 12:13 0:00 [cpuhp/6] root 46 0.0 0.0 0 0 ? S 12:13 0:00 [watchdog/6] root 47 0.0 0.0 0 0 ? S 12:13 0:00 [migration/6] root 48 0.0 0.0 0 0 ? S 12:13 0:00 [ksoftirqd/6] root 49 0.0 0.0 0 0 ? I 12:13 0:00 [kworker/6:0-mm_percpu_wq] root 50 0.0 0.0 0 0 ? I< 12:13 0:00 [kworker/6:0H-events_highpri] root 51 0.0 0.0 0 0 ? S 12:13 0:00 [cpuhp/7] root 52 0.0 0.0 0 0 ? S 12:13 0:00 [watchdog/7] root 53 0.0 0.0 0 0 ? S 12:13 0:00 [migration/7] root 54 0.0 0.0 0 0 ? S 12:13 0:00 [ksoftirqd/7] root 56 0.0 0.0 0 0 ? I< 12:13 0:00 [kworker/7:0H-events_highpri] root 65 0.0 0.0 0 0 ? S 12:13 0:00 [kdevtmpfs] root 66 0.0 0.0 0 0 ? I< 12:13 0:00 [netns] root 67 0.0 0.0 0 0 ? S 12:13 0:00 [rcu_tasks_trace] root 68 0.0 0.0 0 0 ? S 12:13 0:00 [rcu_tasks_rude_] root 69 0.0 0.0 0 0 ? S 12:13 0:00 [kauditd] root 70 0.0 0.0 0 0 ? S 12:13 0:00 [khungtaskd] root 71 0.0 0.0 0 0 ? S 12:13 0:00 [oom_reaper] --More-- [q]
[root@centos8 ~]# chkconfig --list Note: This output shows SysV services only and does not include native systemd services. SysV configuration data might be overridden by native systemd configuration. If you want to list systemd services use 'systemctl list-unit-files'. To see services enabled on particular target use 'systemctl list-dependencies [target]'.
[root@centos8 ~]# systemctl list-unit-files UNIT FILE STATE proc-sys-fs-binfmt_misc.automount static -.mount generated boot.mount generated dev-hugepages.mount static dev-mqueue.mount static proc-fs-nfsd.mount static proc-sys-fs-binfmt_misc.mount static run-vmblock\x2dfuse.mount disabled sys-fs-fuse-connections.mount static sys-kernel-config.mount static sys-kernel-debug.mount static tmp.mount disabled var-lib-machines.mount static var-lib-nfs-rpc_pipefs.mount static cups.path enabled ostree-finalize-staged.path disabled systemd-ask-password-console.path static systemd-ask-password-plymouth.path static systemd-ask-password-wall.path static session-1.scope transient session-5.scope transient session-c1.scope transient accounts-daemon.service enabled alsa-restore.service static alsa-state.service static anaconda-direct.service static anaconda-fips.service static anaconda-nm-config.service static anaconda-noshell.service static anaconda-pre.service static anaconda-shell@.service static anaconda-sshd.service static anaconda-tmux@.service static anaconda.service static arp-ethers.service disabled atd.service enabled auditd.service enabled auth-rpcgss-module.service static autovt@.service enabled avahi-daemon.service enabled blivet.service static blk-availability.service disabled bluetooth.service enabled bolt.service static brltty.service disabled btattach-bcm@.service static canberra-system-bootup.service disabled canberra-system-shutdown-reboot.service disabled canberra-system-shutdown.service disabled chrony-dnssrv@.service static chrony-wait.service disabled chronyd.service enabled cockpit-motd.service static cockpit-wsinstance-http-redirect.service static lines 1-55 [q]
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
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@centos8 ~]# cat /etc/profile # /etc/profile # System wide environment and startup programs, for login setup # Functions and aliases go in /etc/bashrc # It's NOT a good idea to change this file unless you know what you # are doing. It's much better to create a custom.sh shell script in # /etc/profile.d/ to make custom changes to your environment, as this # will prevent the need for merging in future updates. pathmunge () { case ":${PATH}:" in *:"$1":*) ;; *) if [ "$2" = "after" ] ; then PATH=$PATH:$1 else PATH=$1:$PATH fi esac } if [ -x /usr/bin/id ]; then if [ -z "$EUID" ]; then # ksh workaround EUID=`/usr/bin/id -u` UID=`/usr/bin/id -ru` fi USER="`/usr/bin/id -un`" LOGNAME=$USER MAIL="/var/spool/mail/$USER" fi # Path manipulation if [ "$EUID" = "0" ]; then pathmunge /usr/sbin pathmunge /usr/local/sbin else pathmunge /usr/local/sbin after pathmunge /usr/sbin after fi HOSTNAME=`/usr/bin/hostname 2>/dev/null` HISTSIZE=1000 if [ "$HISTCONTROL" = "ignorespace" ] ; then export HISTCONTROL=ignoreboth else export HISTCONTROL=ignoredups fi export PATH USER LOGNAME MAIL HOSTNAME HISTSIZE HISTCONTROL # By default, we want umask to get set. This sets it for login shell # Current threshold for system reserved uid/gids is 200 # You could check uidgid reservation validity in # /usr/share/doc/setup-*/uidgid file if [ $UID -gt 199 ] && [ "`/usr/bin/id -gn`" = "`/usr/bin/id -un`" ]; then umask 002 else umask 022 fi for i in /etc/profile.d/*.sh /etc/profile.d/sh.local ; do if [ -r "$i" ]; then if [ "${-#*i}" != "$-" ]; then . "$i" else . "$i" >/dev/null fi fi done unset i unset -f pathmunge if [ -n "${BASH_VERSION-}" ] ; then if [ -f /etc/bashrc ] ; then # Bash login shells run only /etc/profile # Bash non-login shells run only /etc/bashrc # Check for double sourcing is done in /etc/bashrc. . /etc/bashrc fi 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/profile.
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"
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@centos8 ~]# cat /etc/sysctl.conf # sysctl settings are defined through files in # /usr/lib/sysctl.d/, /run/sysctl.d/, and /etc/sysctl.d/. # # Vendors settings live in /usr/lib/sysctl.d/. # To override a whole file, create a new file with the same in # /etc/sysctl.d/ and put new settings there. To override # only specific settings, add a file with a lexically later # name in /etc/sysctl.d/ and put new settings there. # # For more information, see sysctl.conf(5) and sysctl.d(5).
[root@centos8 ~]# ls -la /etc/sysctl.d total 12 drwxr-xr-x. 2 root root 28 Dec 21 2021 . drwxr-xr-x. 143 root root 8192 Oct 1 12:13 .. lrwxrwxrwx. 1 root root 14 Dec 21 2021 99-sysctl.conf -> ../sysctl.conf
Options de la commande
Les options de la commande sysctl sont :
[root@centos8 ~]# 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 -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).
Important : Consultez la page de la traduction du manuel de sysctl ici pour comprendre la commande.
LAB #2 - Mise en place de SELinux pour sécuriser le serveur
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 : ur
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é 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.
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.
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 RHEL/CentOS 8, le fichier /etc/selinux/targeted/setrans.conf contient la correspondance entre les niveaux et leurs valeurs compréhensibles par l'utilisateur :
[root@centos8 ~]# cat /etc/selinux/targeted/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
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@centos8 ~]# /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 *
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 :
[root@centos8 ~]# ls -lR /etc/selinux/ | more /etc/selinux/: total 8 -rw-r--r--. 1 root root 548 Jun 16 2021 config -rw-r--r--. 1 root root 2647 Feb 3 2021 semanage.conf drwxr-xr-x. 5 root root 133 Mar 6 2022 targeted /etc/selinux/targeted: total 16 -rw-r--r--. 1 root root 2367 Dec 21 2021 booleans.subs_dist drwxr-xr-x. 4 root root 4096 Mar 6 2022 contexts drwxr-xr-x. 2 root root 6 Dec 21 2021 logins drwxr-xr-x. 2 root root 23 Mar 6 2022 policy -rw-r--r--. 1 root root 607 Dec 21 2021 setrans.conf -rw-r--r--. 1 root root 73 Mar 6 2022 seusers /etc/selinux/targeted/contexts: total 68 -rw-r--r--. 1 root root 262 Mar 6 2022 customizable_types -rw-r--r--. 1 root root 195 Dec 21 2021 dbus_contexts -rw-r--r--. 1 root root 1111 Dec 21 2021 default_contexts -rw-r--r--. 1 root root 114 Dec 21 2021 default_type -rw-r--r--. 1 root root 29 Dec 21 2021 failsafe_context drwxr-xr-x. 2 root root 213 Mar 6 2022 files -rw-r--r--. 1 root root 30 Dec 21 2021 initrc_context -rw-r--r--. 1 root root 372 Dec 21 2021 lxc_contexts -rw-r--r--. 1 root root 27 Dec 21 2021 openssh_contexts -rw-r--r--. 1 root root 33 Dec 21 2021 removable_context -rw-r--r--. 1 root root 74 Dec 21 2021 securetty_types -rw-r--r--. 1 root root 1170 Dec 21 2021 sepgsql_contexts -rw-r--r--. 1 root root 53 Dec 21 2021 snapperd_contexts -rw-r--r--. 1 root root 57 Dec 21 2021 systemd_contexts -rw-r--r--. 1 root root 33 Dec 21 2021 userhelper_context drwxr-xr-x. 2 root root 114 Dec 21 2021 users -rw-r--r--. 1 root root 62 Dec 21 2021 virtual_domain_context -rw-r--r--. 1 root root 71 Dec 21 2021 virtual_image_context -rw-r--r--. 1 root root 2920 Dec 21 2021 x_contexts /etc/selinux/targeted/contexts/files: total 1008 -rw-r--r--. 1 root root 407436 Mar 6 2022 file_contexts -rw-r--r--. 1 root root 574118 Mar 6 2022 file_contexts.bin -rw-r--r--. 1 root root 14704 Mar 6 2022 file_contexts.homedirs -rw-r--r--. 1 root root 20149 Mar 6 2022 file_contexts.homedirs.bin -rw-r--r--. 1 root root 0 Dec 21 2021 file_contexts.local -rw-r--r--. 1 root root 0 Dec 21 2021 file_contexts.subs -rw-r--r--. 1 root root 597 Dec 21 2021 file_contexts.subs_dist -rw-r--r--. 1 root root 139 Dec 21 2021 media /etc/selinux/targeted/contexts/users: total 28 -rw-r--r--. 1 root root 342 Dec 21 2021 guest_u -rw-r--r--. 1 root root 724 Dec 21 2021 root -rw-r--r--. 1 root root 562 Dec 21 2021 staff_u -rw-r--r--. 1 root root 589 Dec 21 2021 sysadm_u -rw-r--r--. 1 root root 612 Dec 21 2021 unconfined_u --More-- [q]
Afin d'utiliser SELinux en ligne de commande sous RHEL/CentOS 8, il est nécessaire d'installer le paquet setools-console :
[root@centos8 ~]# dnf install setools-console Last metadata expiration check: 0:28:26 ago on Tue 01 Oct 2024 16:11:14 CEST. Dependencies resolved. ================================================================================================================================================================================================================== Package Architecture Version Repository Size ================================================================================================================================================================================================================== Installing: setools-console x86_64 4.3.0-2.el8 baseos 42 k Transaction Summary ================================================================================================================================================================================================================== Install 1 Package Total download size: 42 k Installed size: 122 k Is this ok [y/N]: y Downloading Packages: setools-console-4.3.0-2.el8.x86_64.rpm 76 kB/s | 42 kB 00:00 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ Total 76 kB/s | 42 kB 00:00 Running transaction check Transaction check succeeded. Running transaction test Transaction test succeeded. Running transaction Preparing : 1/1 Installing : setools-console-4.3.0-2.el8.x86_64 1/1 Running scriptlet: setools-console-4.3.0-2.el8.x86_64 1/1 Verifying : setools-console-4.3.0-2.el8.x86_64 1/1 Installed products updated. Installed: setools-console-4.3.0-2.el8.x86_64 Complete!
Pour consulter les statistiques de la politique, il convient d'utiliser la commande seinfo :
[root@centos8 ~]# seinfo Statistics for policy file: /sys/fs/selinux/policy Policy Version: 31 (MLS enabled) Target Policy: selinux Handle unknown classes: allow Classes: 132 Permissions: 464 Sensitivities: 1 Categories: 1024 Types: 4974 Attributes: 255 Users: 8 Roles: 14 Booleans: 342 Cond. Expr.: 391 Allow: 113176 Neverallow: 0 Auditallow: 166 Dontaudit: 10378 Type_trans: 253825 Type_change: 87 Type_member: 35 Range_trans: 6015 Role allow: 38 Role_trans: 423 Constraints: 72 Validatetrans: 0 MLS Constrain: 72 MLS Val. Tran: 0 Permissives: 0 Polcap: 5 Defaults: 7 Typebounds: 0 Allowxperm: 0 Neverallowxperm: 0 Auditallowxperm: 0 Dontauditxperm: 0 Ibendportcon: 0 Ibpkeycon: 0 Initial SIDs: 27 Fs_use: 34 Genfscon: 107 Portcon: 642 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.
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 |
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@centos8 ~]# 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=enforcing # SELINUXTYPE= can take one of these three values: # targeted - Targeted processes are protected, # minimum - Modification of targeted policy. Only selected processes are protected. # mls - Multi Level Security protection. SELINUXTYPE=targeted
Afin de connaître l'état de SELinux, il convient d'utiliser la commande getenforce :
[root@centos8 ~]# getenforce Enforcing
Pour modifier l'état de SELinux, il convient d'utiliser la commande setenforce :
[root@centos8 ~]# setenforce permissive [root@centos8 ~]# getenforce Permissive
La commande sestatus vous informe sur la configuration de SELinux et notamment sur la version de la politique utilisée :
[root@centos8 ~]# sestatus SELinux status: enabled SELinuxfs mount: /sys/fs/selinux SELinux root directory: /etc/selinux Loaded policy name: targeted Current mode: permissive Mode from config file: enforcing 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@centos8 ~]# sestatus -v SELinux status: enabled SELinuxfs mount: /sys/fs/selinux SELinux root directory: /etc/selinux Loaded policy name: targeted Current mode: permissive Mode from config file: enforcing 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 /usr/sbin/sshd system_u:system_r:sshd_t:s0-s0:c0.c1023 File contexts: Controlling terminal: unconfined_u:object_r:user_devpts_t:s0 /etc/passwd system_u:object_r:passwd_file_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
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@centos8 ~]# getsebool -a | more abrt_anon_write --> off abrt_handle_event --> off abrt_upload_watch_anon_write --> on antivirus_can_scan_system --> off antivirus_use_jit --> off auditadm_exec_content --> on authlogin_nsswitch_use_ldap --> off authlogin_radius --> off authlogin_yubikey --> off awstats_purge_apache_log_files --> off boinc_execmem --> on cdrecord_read_content --> off cluster_can_network_connect --> off cluster_manage_all_files --> off cluster_use_execmem --> off cobbler_anon_write --> off cobbler_can_network_connect --> off cobbler_use_cifs --> off cobbler_use_nfs --> off collectd_tcp_network_connect --> off colord_use_nfs --> off condor_tcp_network_connect --> off conman_can_network --> off conman_use_nfs --> off container_connect_any --> off container_manage_cgroup --> off container_use_cephfs --> off cron_can_relabel --> off cron_system_cronjob_use_shares --> off cron_userdomain_transition --> on cups_execmem --> off cvs_read_shadow --> off daemons_dump_core --> off daemons_enable_cluster_mode --> off daemons_use_tcp_wrapper --> off daemons_use_tty --> off dbadm_exec_content --> on dbadm_manage_user_files --> off dbadm_read_user_files --> off deny_bluetooth --> off deny_execmem --> off deny_ptrace --> off dhcpc_exec_iptables --> off dhcpd_use_ldap --> off domain_can_mmap_files --> off domain_can_write_kmsg --> off domain_fd_use --> on domain_kernel_load_modules --> off entropyd_use_audio --> on exim_can_connect_db --> off exim_manage_user_files --> off exim_read_user_files --> off fcron_crond --> off fenced_can_network_connect --> off fenced_can_ssh --> off --More-- [q]
ou la commande sestatus -b :
[root@centos8 ~]# sestatus -b | more SELinux status: enabled SELinuxfs mount: /sys/fs/selinux SELinux root directory: /etc/selinux Loaded policy name: targeted Current mode: permissive Mode from config file: enforcing Policy MLS status: enabled Policy deny_unknown status: allowed Memory protection checking: actual (secure) Max kernel policy version: 33 Policy booleans: abrt_anon_write off abrt_handle_event off abrt_upload_watch_anon_write on antivirus_can_scan_system off antivirus_use_jit off auditadm_exec_content on authlogin_nsswitch_use_ldap off authlogin_radius off authlogin_yubikey off awstats_purge_apache_log_files off boinc_execmem on cdrecord_read_content off cluster_can_network_connect off cluster_manage_all_files off cluster_use_execmem off cobbler_anon_write off cobbler_can_network_connect off cobbler_use_cifs off cobbler_use_nfs off collectd_tcp_network_connect off colord_use_nfs off condor_tcp_network_connect off conman_can_network off conman_use_nfs off container_connect_any off container_manage_cgroup off container_use_cephfs off cron_can_relabel off cron_system_cronjob_use_shares off cron_userdomain_transition on cups_execmem off cvs_read_shadow off daemons_dump_core off daemons_enable_cluster_mode off daemons_use_tcp_wrapper off daemons_use_tty off dbadm_exec_content on dbadm_manage_user_files off dbadm_read_user_files off deny_bluetooth off deny_execmem off deny_ptrace off dhcpc_exec_iptables off --More-- [q]
Pour fixer l'état d'un booléen, il convient d'utiliser la commande setsebool :
[root@centos8 ~]# setsebool antivirus_can_scan_system 1 [root@centos8 ~]# getsebool antivirus_can_scan_system antivirus_can_scan_system --> on [root@centos8 ~]# setsebool antivirus_can_scan_system 0 [root@centos8 ~]# getsebool antivirus_can_scan_system antivirus_can_scan_system --> off
LAB #3 - Travailler avec SELinux
Afin reconstruire la politique actuelle sans les règles dontaudit, utilisez la commande semodule :
[root@centos8 ~]# semodule -DB
Vérifiez qu'il ne reste aucune règle de type dontaudit :
[root@centos8 ~]# seinfo Statistics for policy file: /sys/fs/selinux/policy Policy Version: 31 (MLS enabled) Target Policy: selinux Handle unknown classes: allow Classes: 132 Permissions: 464 Sensitivities: 1 Categories: 1024 Types: 4964 Attributes: 255 Users: 8 Roles: 14 Booleans: 338 Cond. Expr.: 386 Allow: 112733 Neverallow: 0 Auditallow: 166 Dontaudit: 0 Type_trans: 252829 Type_change: 87 Type_member: 35 Range_trans: 5781 Role allow: 38 Role_trans: 421 Constraints: 72 Validatetrans: 0 MLS Constrain: 72 MLS Val. Tran: 0 Permissives: 0 Polcap: 5 Defaults: 7 Typebounds: 0 Allowxperm: 0 Neverallowxperm: 0 Auditallowxperm: 0 Dontauditxperm: 0 Ibendportcon: 0 Ibpkeycon: 0 Initial SIDs: 27 Fs_use: 34 Genfscon: 107 Portcon: 642 Netifcon: 0 Nodecon: 0
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@centos8 ~]# exit logout [trainee@centos8 ~]$ touch file1 file2 [trainee@centos8 ~]$ ls -Z file* unconfined_u:object_r:user_home_t:s0 file1 unconfined_u:object_r:user_home_t:s0 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@centos8 ~]$ cp file1 /tmp [trainee@centos8 ~]$ ls -Z /tmp/file1 unconfined_u:object_r:user_tmp_t:s0 /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@centos8 ~]$ mv file2 /tmp [trainee@centos8 ~]$ ls -Z /tmp/file2 unconfined_u:object_r:user_home_t:s0 /tmp/file2
Notez que la commande mv maintient le type d'origine.
Vérifier les SC des Processus
Il convient d'utiliser l'option Z avec la commande ps :
[trainee@centos8 ~]$ 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.0 241416 14192 ? Ss 12:13 0:04 /usr/lib/systemd/systemd --switched-root --system --deserialize 18 system_u:system_r:kernel_t:s0 root 2 0.0 0.0 0 0 ? S 12:13 0:00 [kthreadd] system_u:system_r:kernel_t:s0 root 3 0.0 0.0 0 0 ? I< 12:13 0:00 [rcu_gp] system_u:system_r:kernel_t:s0 root 4 0.0 0.0 0 0 ? I< 12:13 0:00 [rcu_par_gp] system_u:system_r:kernel_t:s0 root 6 0.0 0.0 0 0 ? I< 12:13 0:00 [kworker/0:0H-events_highpri] system_u:system_r:kernel_t:s0 root 9 0.0 0.0 0 0 ? I< 12:13 0:00 [mm_percpu_wq] system_u:system_r:kernel_t:s0 root 10 0.0 0.0 0 0 ? S 12:13 0:00 [ksoftirqd/0] system_u:system_r:kernel_t:s0 root 11 0.0 0.0 0 0 ? I 12:13 0:00 [rcu_sched] system_u:system_r:kernel_t:s0 root 12 0.0 0.0 0 0 ? S 12:13 0:00 [migration/0] system_u:system_r:kernel_t:s0 root 13 0.0 0.0 0 0 ? S 12:13 0:00 [watchdog/0] system_u:system_r:kernel_t:s0 root 14 0.0 0.0 0 0 ? S 12:13 0:00 [cpuhp/0] system_u:system_r:kernel_t:s0 root 15 0.0 0.0 0 0 ? S 12:13 0:00 [cpuhp/1] system_u:system_r:kernel_t:s0 root 16 0.0 0.0 0 0 ? S 12:13 0:00 [watchdog/1] system_u:system_r:kernel_t:s0 root 17 0.0 0.0 0 0 ? S 12:13 0:00 [migration/1] system_u:system_r:kernel_t:s0 root 18 0.0 0.0 0 0 ? S 12:13 0:00 [ksoftirqd/1] system_u:system_r:kernel_t:s0 root 20 0.0 0.0 0 0 ? I< 12:13 0:00 [kworker/1:0H-events_highpri] system_u:system_r:kernel_t:s0 root 21 0.0 0.0 0 0 ? S 12:13 0:00 [cpuhp/2] system_u:system_r:kernel_t:s0 root 22 0.0 0.0 0 0 ? S 12:13 0:00 [watchdog/2] system_u:system_r:kernel_t:s0 root 23 0.0 0.0 0 0 ? S 12:13 0:00 [migration/2] system_u:system_r:kernel_t:s0 root 24 0.0 0.0 0 0 ? S 12:13 0:00 [ksoftirqd/2] system_u:system_r:kernel_t:s0 root 26 0.0 0.0 0 0 ? I< 12:13 0:00 [kworker/2:0H-events_highpri] system_u:system_r:kernel_t:s0 root 27 0.0 0.0 0 0 ? S 12:13 0:00 [cpuhp/3] system_u:system_r:kernel_t:s0 root 28 0.0 0.0 0 0 ? S 12:13 0:00 [watchdog/3] system_u:system_r:kernel_t:s0 root 29 0.0 0.0 0 0 ? S 12:13 0:00 [migration/3] system_u:system_r:kernel_t:s0 root 30 0.0 0.0 0 0 ? S 12:13 0:00 [ksoftirqd/3] system_u:system_r:kernel_t:s0 root 32 0.0 0.0 0 0 ? I< 12:13 0:00 [kworker/3:0H-events_highpri] system_u:system_r:kernel_t:s0 root 33 0.0 0.0 0 0 ? S 12:13 0:00 [cpuhp/4] system_u:system_r:kernel_t:s0 root 34 0.0 0.0 0 0 ? S 12:13 0:00 [watchdog/4] system_u:system_r:kernel_t:s0 root 35 0.0 0.0 0 0 ? S 12:13 0:00 [migration/4] system_u:system_r:kernel_t:s0 root 36 0.0 0.0 0 0 ? S 12:13 0:00 [ksoftirqd/4] system_u:system_r:kernel_t:s0 root 38 0.0 0.0 0 0 ? I< 12:13 0:00 [kworker/4:0H-events_highpri] system_u:system_r:kernel_t:s0 root 39 0.0 0.0 0 0 ? S 12:13 0:00 [cpuhp/5] system_u:system_r:kernel_t:s0 root 40 0.0 0.0 0 0 ? S 12:13 0:00 [watchdog/5] system_u:system_r:kernel_t:s0 root 41 0.0 0.0 0 0 ? S 12:13 0:00 [migration/5] system_u:system_r:kernel_t:s0 root 42 0.0 0.0 0 0 ? S 12:13 0:00 [ksoftirqd/5] system_u:system_r:kernel_t:s0 root 44 0.0 0.0 0 0 ? I< 12:13 0:00 [kworker/5:0H-events_highpri] system_u:system_r:kernel_t:s0 root 45 0.0 0.0 0 0 ? S 12:13 0:00 [cpuhp/6] system_u:system_r:kernel_t:s0 root 46 0.0 0.0 0 0 ? S 12:13 0:00 [watchdog/6] system_u:system_r:kernel_t:s0 root 47 0.0 0.0 0 0 ? S 12:13 0:00 [migration/6] system_u:system_r:kernel_t:s0 root 48 0.0 0.0 0 0 ? S 12:13 0:00 [ksoftirqd/6] system_u:system_r:kernel_t:s0 root 50 0.0 0.0 0 0 ? I< 12:13 0:00 [kworker/6:0H-events_highpri] system_u:system_r:kernel_t:s0 root 51 0.0 0.0 0 0 ? S 12:13 0:00 [cpuhp/7] system_u:system_r:kernel_t:s0 root 52 0.0 0.0 0 0 ? S 12:13 0:00 [watchdog/7] system_u:system_r:kernel_t:s0 root 53 0.0 0.0 0 0 ? S 12:13 0:00 [migration/7] system_u:system_r:kernel_t:s0 root 54 0.0 0.0 0 0 ? S 12:13 0:00 [ksoftirqd/7] system_u:system_r:kernel_t:s0 root 56 0.0 0.0 0 0 ? I< 12:13 0:00 [kworker/7:0H-events_highpri] system_u:system_r:kernel_t:s0 root 65 0.0 0.0 0 0 ? S 12:13 0:00 [kdevtmpfs] system_u:system_r:kernel_t:s0 root 66 0.0 0.0 0 0 ? I< 12:13 0:00 [netns] system_u:system_r:kernel_t:s0 root 67 0.0 0.0 0 0 ? S 12:13 0:00 [rcu_tasks_trace] system_u:system_r:kernel_t:s0 root 68 0.0 0.0 0 0 ? S 12:13 0:00 [rcu_tasks_rude_] system_u:system_r:kernel_t:s0 root 69 0.0 0.0 0 0 ? S 12:13 0:00 [kauditd] system_u:system_r:kernel_t:s0 root 70 0.0 0.0 0 0 ? S 12:13 0:00 [khungtaskd] system_u:system_r:kernel_t:s0 root 71 0.0 0.0 0 0 ? S 12:13 0:00 [oom_reaper] system_u:system_r:kernel_t:s0 root 72 0.0 0.0 0 0 ? I< 12:13 0:00 [writeback] --More-- [q]
Visualiser la SC d'un Utilisateur
Utilisez l'option -Z avec la commande id :
[trainee@centos8 ~]$ 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@centos8 ~]$ id root uid=0(root) gid=0(root) groups=0(root) [trainee@centos8 ~]$ id -Z root id: cannot print security context when user specified
Vérifier la SC d'un fichier
Il convient d'utiliser la commande ls avec l'option -Z :
[trainee@centos8 ~]$ cd /etc [trainee@centos8 etc]$ ls -Z l* -d unconfined_u:object_r:ld_so_cache_t:s0 ld.so.cache system_u:object_r:etc_t:s0 libpaper.d system_u:object_r:etc_t:s0 login.defs system_u:object_r:etc_t:s0 ld.so.conf system_u:object_r:etc_t:s0 libreport system_u:object_r:etc_t:s0 logrotate.conf system_u:object_r:etc_t:s0 ld.so.conf.d system_u:object_r:etc_t:s0 libssh system_u:object_r:etc_t:s0 logrotate.d system_u:object_r:etc_t:s0 libaudit.conf system_u:object_r:etc_t:s0 libuser.conf system_u:object_r:etc_t:s0 lsm system_u:object_r:etc_t:s0 libblockdev system_u:object_r:virt_etc_t:s0 libvirt system_u:object_r:lvm_etc_t:s0 lvm system_u:object_r:etc_t:s0 libibverbs.d system_u:object_r:locale_t:s0 locale.conf system_u:object_r:etc_t:s0 libnl system_u:object_r:locale_t:s0 localtime
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 :
La commande chcon
La commande chcon permet de modifier temporairement une SC.
[trainee@centos8 etc]$ cd ~ [trainee@centos8 ~]$ 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/> Report chcon translation bugs to <https://translationproject.org/team/> Full documentation at: <https://www.gnu.org/software/coreutils/chcon> or available locally via: info '(coreutils) chcon invocation'
HERE
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@centos8 ~]$ su - Password:fenestros [root@centos8 ~]# mkdir /www [root@centos8 ~]# touch /www/index.html
Installez maintenant le serveur Apache :
[root@centos8 ~]# dnf install httpd -y
Modifiez ensuite la directive DocumentRoot dans le fichier /etc/httpd/conf/httpd.conf :
[...] #DocumentRoot "/var/www/html" DocumentRoot "/www" [...]
Ajoutez les section <Directory ”/www“>:
... <Directory "/var/www"> AllowOverride None # Allow open access: Require all granted </Directory> <Directory "/www"> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> # Further relax access to the default document root: <Directory "/var/www/html"> ...
Créez le fichier /www/index.html :
[root@centos8 ~]# cat /www/index.html <html> <title> This is a test </title> <body> www test page </body> </html>
Modifiez ensuite le propriétaire et le groupe du répertoire /www et son contenu :
[root@centos8 ~]# chown -R apache:apache /www
Dernièrement, créez un fichier index.html vide dans le répertoire /var/www/html/ :
[root@centos8 ~]# touch /var/www/html/index.html
Redémarrez maintenant le service httpd :
[root@centos8 ~]# systemctl restart httpd.service [root@centos8 ~]# systemctl status httpd.service ● httpd.service - The Apache HTTP Server Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled) Active: active (running) since Wed 2024-10-02 12:24:15 CEST; 15s ago Docs: man:httpd.service(8) Main PID: 53680 (httpd) Status: "Running, listening on: port 80" Tasks: 213 (limit: 100949) Memory: 39.3M CGroup: /system.slice/httpd.service ├─53680 /usr/sbin/httpd -DFOREGROUND ├─53683 /usr/sbin/httpd -DFOREGROUND ├─53684 /usr/sbin/httpd -DFOREGROUND ├─53685 /usr/sbin/httpd -DFOREGROUND └─53686 /usr/sbin/httpd -DFOREGROUND Oct 02 12:24:14 centos8.ittraining.loc systemd[1]: Starting The Apache HTTP Server... Oct 02 12:24:15 centos8.ittraining.loc systemd[1]: Started The Apache HTTP Server. Oct 02 12:24:15 centos8.ittraining.loc httpd[53680]: Server configured, listening on: port 80
Passez SELinux en mode enforcing :
Consultez le site localhost en utilisant lynx :
[root@centos8 ~]# lynx localhost bash: lynx: command not found... Install package 'lynx' to provide command 'lynx'? [N/y] y * Waiting in queue... * Loading list of packages.... The following packages have to be installed: lynx-2.8.9-2.el8.x86_64 A text-based Web browser Proceed with changes? [N/y] y * Waiting in queue... * Waiting for authentication... * Waiting in queue... * Downloading packages... * Requesting data... * Testing changes... * Installing packages... HTTP Server Test Page This page is used to test the proper operation of the HTTP server after it has been installed. If you can read this page it means that this site is working properly. This server is powered by [1]CentOS. __________________________________________________________________ If you are a member of the general public: The website you just visited is either experiencing problems or is undergoing routine maintenance. If you would like to let the administrators of this website know that you've seen this page instead of the page you expected, you should send them e-mail. In general, mail sent to the name "webmaster" and directed to the website's domain should reach the appropriate person. For example, if you experienced problems while visiting www.example.com, you should send e-mail to "webmaster@example.com". If you are the website administrator: You may now add content to the webroot directory. Note that until you do so, people visiting your website will see this page, and not your content. For systems using the Apache HTTP Server: You may now add content to the directory /var/www/html/. Note that until you do so, people visiting your website will see this page, and not your content. To prevent this page from ever being used, follow the instructions in the file /etc/httpd/conf.d/welcome.conf. For systems using NGINX: You should now put your content in a location of your choice and edit the root configuration directive in the nginx configuration file /etc/nginx/nginx.conf. [2][ Powered by CentOS ] [ Powered by CentOS ] __________________________________________________________________ Important note! The CentOS Project has nothing to do with this website or its content, it just provides the software that makes the website run. If you have issues with the content of this site, contact the owner of the domain, not the CentOS project. Unless you intended to visit CentOS.org, the CentOS Project does not have anything to do with this website, the content or the lack of it. For example, if this website is www.example.com, you would find the owner of the example.com domain at the following WHOIS server: [3]http://www.internic.net/whois.html © 2021 The CentOS Project | [4]Legal | [5]Privacy References 1. http://centos.org/ 2. https://www.centos.org/ 3. http://www.internic.net/whois.html 4. https://www.centos.org/legal/ 5. https://www.centos.org/legal/privacy/
Consultez les messages d'alerte de SELinux dans le fichier /var/log/messages : <code> [root@centos8 ~]# grep “SELinux is preventing” /var/log/messages … Oct 2 12:44:28 centos8 setroubleshoot[57035]: SELinux is preventing /usr/sbin/httpd from using the net_admin capability. For complete SELinux messages run: sealert -l a169ef1e-7a43-47d5-ac8f-36d5459c82b6 Oct 2 12:44:28 centos8 setroubleshoot[57035]: SELinux is preventing /usr/sbin/httpd from using the net_admin capability.#012#012* Plugin catchall (100. confidence) suggests #012#012If you believe that httpd should have the net_admin capability by default.#012Then you should report this as a bug.#012You can generate a local policy module to allow this access.#012Do#012allow this access for now by executing:#012# ausearch -c 'httpd' –raw | audit2allow -M my-httpd#012# semodule -X 300 -i my-httpd.pp#012 Oct 2 12:44:38 centos8 setroubleshoot[57035]: SELinux is preventing /usr/sbin/httpd from using the net_admin capability. For complete SELinux messages run: sealert -l a169ef1e-7a43-47d5-ac8f-36d5459c82b6 Oct 2 12:44:38 centos8 setroubleshoot[57035]: SELinux is preventing /usr/sbin/httpd from using the net_admin capability.#012#012* Plugin catchall (100. confidence) suggests #012#012If you believe that httpd should have the net_admin capability by default.#012Then you should report this as a bug.#012You can generate a local policy module to allow this access.#012Do#012allow this access for now by executing:#012# ausearch -c 'httpd' –raw | audit2allow -M my-httpd#012# semodule -X 300 -i my-httpd.pp#012 </code> La commande sealert possède à la fois une interface graphique et un mode en ligne de commande. <code> [root@centos8 ~]# sealert -l a169ef1e-7a43-47d5-ac8f-36d5459c82b6 SELinux is preventing /usr/sbin/httpd from using the net_admin capability. * Plugin catchall (100. confidence) suggests
If you believe that httpd should have the net_admin capability by default. Then you should report this as a bug. You can generate a local policy module to allow this access. Do allow this access for now by executing: # ausearch -c 'httpd' –raw | audit2allow -M my-httpd # semodule -X 300 -i my-httpd.pp
Additional Information: Source Context system_u:system_r:httpd_t:s0 Target Context system_u:system_r:httpd_t:s0 Target Objects Unknown [ capability ] Source httpd Source Path /usr/sbin/httpd Port <Unknown> Host centos8.ittraining.loc Source RPM Packages Target RPM Packages SELinux Policy RPM selinux-policy-targeted-3.14.3-80.el8_5.2.noarch Local Policy RPM selinux-policy-targeted-3.14.3-80.el8_5.2.noarch Selinux Enabled True Policy Type targeted Enforcing Mode Enforcing Host Name centos8.ittraining.loc Platform Linux centos8.ittraining.loc
4.18.0-348.7.1.el8_5.x86_64 #1 SMP Wed Dec 22 13:25:12 UTC 2021 x86_64 x86_64
Alert Count 110 First Seen 2024-10-02 12:24:14 CEST Last Seen 2024-10-02 12:48:45 CEST Local ID a169ef1e-7a43-47d5-ac8f-36d5459c82b6
Raw Audit Messages type=AVC msg=audit(1727866125.775:861): avc: denied { net_admin } for pid=53680 comm=“httpd” capability=12 scontext=system_u:system_r:httpd_t:s0 tcontext=system_u:system_r:httpd_t:s0 tclass=capability permissive=0
Hash: httpd,httpd_t,httpd_t,capability,net_admin </code>
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@centos8 ~]# ls -Z /www/index.html unconfined_u:object_r:default_t:s0 /www/index.html
[root@centos8 ~]# ls -Z /var/www/html/index.html unconfined_u:object_r:httpd_sys_content_t:s0 /var/www/html/index.html
L'exemple ci-dessus nous montre clairement que le type pour /www/index.html est default_t or apache a besoin du type httpd_sys_content_t pour pouvoir accéder au fichier.
Pour vérifier la cause de l'erreur, utilisez la commande suivante :
[root@centos8 ~]# grep "/www/index.html" /var/log/messages ... Oct 2 12:44:48 centos8 setroubleshoot[57035]: SELinux is preventing /usr/sbin/httpd from getattr access on the file /www/index.html. For complete SELinux messages run: sealert -l 874480af-4890-4ae4-a1a2-961f5c528f3e ...
Modifiez donc la SC de /www et /www/index.html en utilisant la commande chcon :
[root@centos8 ~]# chcon -Rv --type=httpd_sys_content_t /www changing security context of '/www/index.html' changing security context of '/www' [root@centos8 ~]# 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@centos8 ~]# semanage fcontext -a -t httpd_sys_content_t "/www(/.*)?"
Vérifiez que ces modifications fonctionnent :
[root@centos8 ~]# lynx --dump localhost www test page
La commande restorecon
usage: restorecon [-iFnrRv] [-e excludedir ] [-o filename ] [-f filename | pathname... ]
Pour illustrer l'utilisation de cette commande, créez les fichiers copy.html et move.html dans le répertoire /tmp :
[root@centos8 ~]# cd /tmp ; touch copy.html move.html [root@centos8 tmp]# ls -Z | grep html unconfined_u:object_r:user_tmp_t:s0 copy.html unconfined_u:object_r:user_tmp_t:s0 move.html
Copiez le fichier copy.html vers /var/www/html et déplacez le fichier move.html vers la même cible :
[root@centos8 tmp]# cp copy.html /var/www/html/ [root@centos8 tmp]# mv move.html /var/www/html/ [root@centos8 tmp]# ls -Z /var/www/html unconfined_u:object_r:httpd_sys_content_t:s0 copy.html unconfined_u:object_r:httpd_sys_content_t:s0 index.html unconfined_u:object_r:user_tmp_t:s0 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 sa création.
Restaurez maintenant la SC par défaut de move.html compte tenu de son emplacement en utilisant la commande restorecon :
[root@centos8 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@centos8 tmp]# ls -Z /var/www/html unconfined_u:object_r:httpd_sys_content_t:s0 copy.html unconfined_u:object_r:httpd_sys_content_t:s0 index.html unconfined_u:object_r:httpd_sys_content_t:s0 move.html
Le fichier /.autorelabel
En cas de besoin il est intéressant de pouvoir restaurer les SC par défaut sur l'ensemble des objets du système. Cette procédure est très simple à mettre en oeuvre. Il convient de créer le fichier .autorelabel à la racine et de redémarrer le système :
[root@centos8 tmp]# touch /.autorelabel [root@centos8 tmp]# shutdown -r now
root@computeXX:~# ssh -l trainee 10.0.2.45 trainee@10.0.2.45's password: trainee Activate the web console with: systemctl enable --now cockpit.socket Last login: Wed Oct 2 11:47:29 2024 from 10.0.2.1 [trainee@centos8 ~]$ su - Password: fenestros
La commande semanage
La commande semanage peut prendre plusieurs options :
[root@centos8 ~]# 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 optional arguments: -h, --help show this help message and exit
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@centos8 ~]# semanage port -l SELinux Port Type Proto Port Number afs3_callback_port_t tcp 7001 afs3_callback_port_t udp 7001 afs_bos_port_t udp 7007 afs_fs_port_t tcp 2040 afs_fs_port_t udp 7000, 7005 afs_ka_port_t udp 7004 afs_pt_port_t tcp 7002 afs_pt_port_t udp 7002 afs_vl_port_t udp 7003 agentx_port_t tcp 705 agentx_port_t udp 705 amanda_port_t tcp 10080-10083 amanda_port_t udp 10080-10082 amavisd_recv_port_t tcp 10024 amavisd_send_port_t tcp 10025 amqp_port_t tcp 15672, 5671-5672 amqp_port_t udp 5671-5672 aol_port_t tcp 5190-5193 aol_port_t udp 5190-5193 apc_port_t tcp 3052 apc_port_t udp 3052 apcupsd_port_t tcp 3551 apcupsd_port_t udp 3551 apertus_ldp_port_t tcp 539 apertus_ldp_port_t udp 539 appswitch_emp_port_t tcp 2616 appswitch_emp_port_t udp 2616 asterisk_port_t tcp 1720 asterisk_port_t udp 2427, 2727, 4569 audit_port_t tcp 60 auth_port_t tcp 113 babel_port_t udp 6696 bacula_port_t tcp 9103 bacula_port_t udp 9103 bctp_port_t tcp 8999 bctp_port_t udp 8999 bfd_control_port_t tcp 3784 bfd_control_port_t udp 3784 bgp_port_t tcp 179, 2605 bgp_port_t udp 179, 2605 boinc_client_port_t tcp 1043 boinc_client_port_t udp 1034 boinc_port_t tcp 31416 brlp_port_t tcp 4101 certmaster_port_t tcp 51235 chronyd_port_t udp 323 clamd_port_t tcp 3310 clockspeed_port_t udp 4041 cluster_port_t tcp 5149, 40040, 50006-50008 cluster_port_t udp 5149, 50006-50008 cma_port_t tcp 1050 cma_port_t udp 1050 cobbler_port_t tcp 25151 collectd_port_t udp 25826 commplex_link_port_t tcp 4331, 5001 commplex_link_port_t udp 5001 commplex_main_port_t tcp 5000 commplex_main_port_t udp 5000 comsat_port_t udp 512 condor_port_t tcp 9618 condor_port_t udp 9618 conman_port_t tcp 7890 conman_port_t udp 7890 connlcli_port_t tcp 1358 connlcli_port_t udp 1358 conntrackd_port_t udp 3780 couchdb_port_t tcp 5984, 6984 couchdb_port_t udp 5984, 6984 ctdb_port_t tcp 4379 ctdb_port_t udp 4379 cvs_port_t tcp 2401 cvs_port_t udp 2401 cyphesis_port_t tcp 6767, 6769, 6780-6799 cyphesis_port_t udp 32771 cyrus_imapd_port_t tcp 2005 daap_port_t tcp 3689 daap_port_t udp 3689 dbskkd_port_t tcp 1178 dcc_port_t udp 6276, 6277 dccm_port_t tcp 5679 dccm_port_t udp 5679 dey_keyneg_port_t tcp 8750 dey_keyneg_port_t udp 8750 dey_sapi_port_t tcp 4330 dhcpc_port_t tcp 68, 546, 5546 dhcpc_port_t udp 68, 546, 5546 dhcpd_port_t tcp 547, 548, 647, 847, 7911 dhcpd_port_t udp 67, 547, 548, 647, 847 dict_port_t tcp 2628 distccd_port_t tcp 3632 dns_port_t tcp 53, 853 dns_port_t udp 53, 853 dnssec_port_t tcp 8955 dogtag_port_t tcp 7390 echo_port_t tcp 7 echo_port_t udp 7 efs_port_t tcp 520 embrace_dp_c_port_t tcp 3198 embrace_dp_c_port_t udp 3198 ephemeral_port_t tcp 32768-60999 ephemeral_port_t udp 32768-60999 epmap_port_t tcp 135 epmap_port_t udp 135 epmd_port_t tcp 4369 epmd_port_t udp 4369 fac_restore_port_t tcp 5582 fac_restore_port_t udp 5582 fingerd_port_t tcp 79 firepower_port_t tcp 2615 firepower_port_t udp 2615 flash_port_t tcp 843, 1935 flash_port_t udp 1935 fmpro_internal_port_t tcp 5003 fmpro_internal_port_t udp 5003 freeipmi_port_t tcp 9225 freeipmi_port_t udp 9225 ftp_data_port_t tcp 20 ftp_port_t tcp 21, 989, 990 ftp_port_t udp 989, 990 gatekeeper_port_t tcp 1721, 7000 gatekeeper_port_t udp 1718, 1719 gdomap_port_t tcp 538 gdomap_port_t udp 538 gds_db_port_t tcp 3050 gds_db_port_t udp 3050 gear_port_t tcp 43273 gear_port_t udp 43273 geneve_port_t tcp 6080 giftd_port_t tcp 1213 git_port_t tcp 9418 git_port_t udp 9418 glance_port_t tcp 9292 glance_port_t udp 9292 glance_registry_port_t tcp 9191 glance_registry_port_t udp 9191 gluster_port_t tcp 38465-38469, 24007-24027 gopher_port_t tcp 70 gopher_port_t udp 70 gpsd_port_t tcp 2947 hadoop_datanode_port_t tcp 50010 hadoop_namenode_port_t tcp 8020 hddtemp_port_t tcp 7634 hi_reserved_port_t sctp 512-1023 hi_reserved_port_t tcp 512-1023 hi_reserved_port_t udp 512-1023 howl_port_t tcp 5335 howl_port_t udp 5353 hplip_port_t tcp 1782, 2207, 2208, 8290, 8292, 9100, 9101, 9102, 9220, 9221, 9222, 9280, 9281, 9282, 9290, 9291, 50000, 50002 http_cache_port_t tcp 8080, 8118, 8123, 10001-10010 http_cache_port_t udp 3130 http_port_t tcp 80, 81, 443, 488, 8008, 8009, 8443, 9000 ...
Notez par exemple que le serveur apache est autorisé d'utiliser les ports suivants :
http_port_t tcp 80, 81, 443, 488, 8008, 8009, 8443, 9000
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@centos8 ~]# 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@centos8 ~]# semanage port -l | grep http http_cache_port_t tcp 8080, 8118, 8123, 10001-10010 http_cache_port_t udp 3130 http_port_t tcp 8090, 80, 81, 443, 488, 8008, 8009, 8443, 9000 pegasus_http_port_t tcp 5988 pegasus_https_port_t tcp 5989
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.
[root@centos8 ~]# 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
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@centos8 tmp]# mkdir /www1 [root@centos8 tmp]# touch /www1/index.html
Éditez le fichier /etc/httpd/conf/httpd.conf :
[...] #DocumentRoot "/var/www/html" DocumentRoot "/www1" [...]
Ajoutez les section <Directory ”/www“>:
... <Directory "/var/www"> AllowOverride None # Allow open access: Require all granted </Directory> <Directory "/www1"> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> # Further relax access to the default document root: <Directory "/var/www/html"> ...
Créez le fichier /www1/index.html :
[root@centos8 ~]# vi /www1/index.html [root@centos8 ~]# cat /www1/index.html <html> <title> This is a test </title> <body> www1 test page </body> </html>
Modifiez ensuite le propriétaire et le groupe du répertoire /www1 et son contenu :
[root@centos8 ~]# chown -R apache:apache /www1
Redémarrez le service httpd :
[root@centos8 ~]# systemctl restart httpd.service [root@centos8 ~]# systemctl status httpd.service ● httpd.service - The Apache HTTP Server Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled) Active: active (running) since Wed 2024-10-02 13:17:32 CEST; 12s ago Docs: man:httpd.service(8) Main PID: 3255 (httpd) Status: "Running, listening on: port 80" Tasks: 213 (limit: 100949) Memory: 49.2M CGroup: /system.slice/httpd.service ├─3255 /usr/sbin/httpd -DFOREGROUND ├─3256 /usr/sbin/httpd -DFOREGROUND ├─3257 /usr/sbin/httpd -DFOREGROUND ├─3258 /usr/sbin/httpd -DFOREGROUND └─3259 /usr/sbin/httpd -DFOREGROUND Oct 02 13:17:31 centos8.ittraining.loc systemd[1]: Starting The Apache HTTP Server... Oct 02 13:17:32 centos8.ittraining.loc systemd[1]: Started The Apache HTTP Server. Oct 02 13:17:32 centos8.ittraining.loc httpd[3255]: Server configured, listening on: port 80
Consultez le site localhost en utilisant lynx :
[root@centos8 ~]# lynx --dump localhost HTTP Server Test Page This page is used to test the proper operation of the HTTP server after it has been installed. If you can read this page it means that this site is working properly. This server is powered by [1]CentOS. __________________________________________________________________ If you are a member of the general public: The website you just visited is either experiencing problems or is undergoing routine maintenance. If you would like to let the administrators of this website know that you've seen this page instead of the page you expected, you should send them e-mail. In general, mail sent to the name "webmaster" and directed to the website's domain should reach the appropriate person. For example, if you experienced problems while visiting www.example.com, you should send e-mail to "webmaster@example.com". If you are the website administrator: You may now add content to the webroot directory. Note that until you do so, people visiting your website will see this page, and not your content. For systems using the Apache HTTP Server: You may now add content to the directory /var/www/html/. Note that until you do so, people visiting your website will see this page, and not your content. To prevent this page from ever being used, follow the instructions in the file /etc/httpd/conf.d/welcome.conf. For systems using NGINX: You should now put your content in a location of your choice and edit the root configuration directive in the nginx configuration file /etc/nginx/nginx.conf. [2][ Powered by CentOS ] [ Powered by CentOS ] __________________________________________________________________ Important note! The CentOS Project has nothing to do with this website or its content, it just provides the software that makes the website run. If you have issues with the content of this site, contact the owner of the domain, not the CentOS project. Unless you intended to visit CentOS.org, the CentOS Project does not have anything to do with this website, the content or the lack of it. For example, if this website is www.example.com, you would find the owner of the example.com domain at the following WHOIS server: [3]http://www.internic.net/whois.html © 2021 The CentOS Project | [4]Legal | [5]Privacy References 1. http://centos.org/ 2. https://www.centos.org/ 3. http://www.internic.net/whois.html 4. https://www.centos.org/legal/ 5. https://www.centos.org/legal/privacy/
Le fichier /var/log/audit/audit.log contient maintenant des notifications de type AVC :
Oct 2 13:20:57 centos8 setroubleshoot[3502]: SELinux is preventing /usr/sbin/httpd from getattr access on the file /www1/index.html. For complete SELinux messages run: sealert -l 874480af-4890-4ae4-a1a2-961f5c528f3e Oct 2 13:20:57 centos8 setroubleshoot[3502]: SELinux is preventing /usr/sbin/httpd from getattr access on the file /www1/index.html.#012#012***** Plugin catchall_labels (83.8 confidence) suggests *******************#012#012If you want to allow httpd to have getattr access on the index.html file#012Then you need to change the label on /www1/index.html#012Do#012# semanage fcontext -a -t FILE_TYPE '/www1/index.html'#012where FILE_TYPE is one of the following: NetworkManager_exec_t, NetworkManager_log_t, NetworkManager_tmp_t, abrt_dump_oops_exec_t, abrt_etc_t, abrt_exec_t, abrt_handle_event_exec_t, abrt_helper_exec_t, abrt_retrace_coredump_exec_t, abrt_retrace_spool_t, abrt_retrace_worker_exec_t, abrt_tmp_t, abrt_upload_watch_tmp_t, abrt_var_cache_t, abrt_var_log_t, abrt_var_run_t, accountsd_exec_t, acct_data_t, acct_exec_t, admin_crontab_tmp_t, admin_passwd_exec_t, afs_logfile_t, aide_exec_t, aide_log_t, alsa_exec_t, alsa_tmp_t, amanda_exec_t, amanda_log_t, amanda_recover_exec_t, amanda_tmp_t, amtu_exec_t, anacron_exec_t, anon_inodefs_t, antivirus_exec_t, antivirus_log_t, antivirus_tmp_t, apcupsd_cgi_content_t, apcupsd_cgi_htaccess_t, apcupsd_cgi_ra_content_t, apcupsd_cgi_rw_content_t, apcupsd_cgi_script_exec_t, apcupsd_log_t, apcupsd_tmp_t, apm_exec_t, apmd_log_t, apmd_tmp_t, arpwatch_tmp_t, asterisk_log_t, asterisk_tmp_t, audisp_exec_t, auditadm_sudo_tmp_t, auditctl_exec_t, auditd_tmp_t, auth_cache_t, authconfig_exec_t, automount_tmp_t, avahi_exec_t, awstats_content_t, awstats_htaccess_t, awstats_ra_content_t, awstats_rw_content_t, awstats_script_exec_t, awstats_tmp_t, bacula_admin_exec_t, bacula_log_t, bacula_tmp_t, bacula_unconfined_script_exec_t, bin_t, bitlbee_log_t, bitlbee_tmp_t, blueman_exec_t, blueman_tmp_t, bluetooth_helper_exec_t, bluetooth_helper_tmp_t, bluetooth_helper_tmpfs_t, bluetooth_tmp_t, boinc_log_t, boinc_project_tmp_t, boinc_tmp_t, boot_t, bootloader_exec_t, bootloader_tmp_t, brctl_exec_t, brltty_log_t, bugzilla_content_t, bugzilla_htaccess_t, bugzilla_ra_content_t, bugzilla_rw_content_t, bugzilla_script_exec_t, bugzilla_tmp_t, calamaris_exec_t, calamaris_log_t, calamaris_www_t, callweaver_log_t, canna_log_t, cardctl_exec_t, cardmgr_dev_t, ccs_tmp_t, ccs_var_lib_t, ccs_var_log_t, cdcc_exec_t, cdcc_tmp_t, cdrecord_exec_t, cert_t, certmaster_var_log_t, certmonger_tmp_t, certmonger_unconfined_exec_t, certwatch_exec_t, cfengine_log_t, cgred_log_t, cgroup_t, checkpc_exec_t, checkpc_log_t, checkpolicy_exec_t, chfn_exec_t, chkpwd_exec_t, chrome_sandbox_exec_t, chrome_sandbox_nacl_exec_t, chrome_sandbox_tmp_t, chronyc_exec_t, chronyd_tmp_t, chronyd_var_log_t, cinder_api_tmp_t, cinder_backup_tmp_t, cinder_log_t, cinder_scheduler_tmp_t, cinder_volume_tmp_t, cloud_init_tmp_t, cloud_log_t, cluster_conf_t, cluster_tmp_t, cluster_var_lib_t, cluster_var_log_t, cluster_var_run_t, cobbler_etc_t, cobbler_tmp_t, cobbler_var_lib_t, cobbler_var_log_t, cockpit_tmp_t, cockpit_tmpfs_t, collectd_content_t, collectd_htaccess_t, collectd_log_t, collectd_ra_content_t, collectd_rw_content_t, collectd_script_exec_t, collectd_script_tmp_t, colord_exec_t, colord_tmp_t, comsat_tmp_t, condor_log_t, condor_master_tmp_t, condor_schedd_tmp_t, condor_startd_tmp_t, conman_log_t, conman_tmp_t, conman_unconfined_script_exec_t, conntrackd_log_t, consolehelper_exec_t, consolekit_exec_t, consolekit_log_t, container_file_t, container_log_t, container_runtime_tmp_t, couchdb_log_t, couchdb_tmp_t, courier_exec_t, cpu_online_t, cpucontrol_exec_t, cpufreqselector_exec_t, cpuspeed_exec_t, crack_exec_t, crack_tmp_t, cron_log_t, crond_tmp_t, crontab_exec_t, crontab_tmp_t, ctdbd_log_t, ctdbd_tmp_t, cups_pdf_tmp_t, cupsd_config_exec_t, cupsd_log_t, cupsd_lpd_tmp_t, cupsd_tmp_t, cvs_content_t, cvs_data_t, cvs_exec_t, cvs_htaccess_t, cvs_ra_content_t, cvs_rw_content_t, cvs_script_exec_t, cvs_tmp_t, cyphesis_exec_t, cyphesis_log_t, cyphesis_tmp_t, cyrus_tmp_t, dbadm_sudo_tmp_t, dbskkd_tmp_t, dbusd_etc_t, dbusd_exec_t, dcc_client_exec_t, dcc_client_tmp_t, dcc_dbclean_exec_t, dcc_dbclean_tmp_t, dccd_tmp_t, dccifd_tmp_t, dccm_tmp_t, ddclient_log_t, ddclient_tmp_t, debuginfo_exec_t, deltacloudd_log_t, deltacloudd_tmp_t, denyhosts_var_log_t, devicekit_disk_exec_t, devicekit_exec_t, devicekit_power_exec_t, devicekit_tmp_t, devicekit_var_log_t, dhcpc_exec_t, dhcpc_tmp_t, dhcpd_tmp_t, dirsrv_config_t, dirsrv_share_t, dirsrv_snmp_var_log_t, dirsrv_tmp_t, dirsrv_var_log_t, dirsrv_var_run_t, dirsrvadmin_config_t, dirsrvadmin_content_t, dirsrvadmin_htaccess_t, dirsrvadmin_ra_content_t, dirsrvadmin_rw_content_t, dirsrvadmin_script_exec_t, dirsrvadmin_tmp_t, dirsrvadmin_unconfined_script_exec_t, disk_munin_plugin_exec_t, disk_munin_plugin_tmp_t, dkim_milter_tmp_t, dlm_controld_var_log_t, dmesg_exec_t, dmidecode_exec_t, dnsmasq_tmp_t, dnsmasq_var_log_t, dnssec_trigger_tmp_t, dovecot_auth_tmp_t, dovecot_deliver_tmp_t, dovecot_tmp_t, dovecot_var_log_t, drbd_tmp_t, dspam_content_t, dspam_htaccess_t, dspam_log_t, dspam_ra_content_t, dspam_rw_content_t, dspam_script_exec_t, efivarfs_t, etc_runtime_t, etc_t, evtchnd_var_log_t, exim_exec_t, exim_log_t, exim_tmp_t, fail2ban_client_exec_t, fail2ban_log_t, fail2ban_tmp_t, fail2ban_var_lib_t, faillog_t, fenced_tmp_t, fenced_var_log_t, fetchmail_exec_t, fetchmail_log_t, file_context_t, fingerd_log_t, firewalld_exec_t, firewalld_tmp_t, firewalld_var_log_t, firewallgui_exec_t, firewallgui_tmp_t, firstboot_exec_t, flatpak_helper_exec_t, foghorn_var_log_t, fonts_cache_t, fonts_t, fprintd_exec_t, fprintd_tmp_t, freqset_exec_t, fsadm_exec_t, fsadm_log_t, fsadm_tmp_t, fsdaemon_tmp_t, ftpd_tmp_t, ftpdctl_exec_t, ftpdctl_tmp_t, fwupd_exec_t, games_exec_t, games_tmp_t, games_tmpfs_t, gconf_tmp_t, gconfd_exec_t, gconfdefaultsm_exec_t, geoclue_exec_t, geoclue_tmp_t, getty_exec_t, getty_log_t, getty_tmp_t, gfs_controld_var_log_t, git_content_t, git_htaccess_t, git_ra_content_t, git_rw_content_t, git_script_exec_t, git_script_tmp_t, git_sys_content_t, gitd_exec_t, gitosis_exec_t, gitosis_var_lib_t, gkeyringd_exec_t, gkeyringd_tmp_t, glance_log_t, glance_registry_tmp_t, glance_tmp_t, gnomesystemmm_exec_t, gpg_agent_exec_t, gpg_agent_tmp_t, gpg_agent_tmpfs_t, gpg_exec_t, gpg_helper_exec_t, gpg_pinentry_tmp_t, gpg_pinentry_tmpfs_t, gpm_tmp_t, gpsd_exec_t, groupadd_exec_t, groupd_var_log_t, gssd_tmp_t, haproxy_var_log_t, hostname_etc_t, hostname_exec_t, hsqldb_tmp_t, httpd_cache_t, httpd_config_t, httpd_exec_t, httpd_helper_exec_t, httpd_keytab_t, httpd_lock_t, httpd_log_t, httpd_modules_t, httpd_passwd_exec_t, httpd_php_exec_t, httpd_php_tmp_t, httpd_rotatelogs_exec_t, httpd_squirrelmail_t, httpd_suexec_exec_t, httpd_suexec_tmp_t, httpd_sys_content_t, httpd_sys_htaccess_t, httpd_sys_ra_content_t, httpd_sys_rw_content_t, httpd_sys_script_exec_t, httpd_tmp_t, httpd_tmpfs_t, httpd_unconfined_script_exec_t, httpd_user_htaccess_t, httpd_user_ra_content_t, httpd_user_rw_content_t, httpd_user_script_exec_t, httpd_var_lib_t, httpd_var_run_t, hugetlbfs_t, hwclock_exec_t, hwloc_dhwd_exec_t, ibacm_log_t, iceauth_exec_t, icecast_exec_t, icecast_log_t, ifconfig_exec_t, inetd_child_tmp_t, inetd_log_t, inetd_tmp_t, init_tmp_t, initrc_tmp_t, initrc_var_log_t, innd_log_t, install_exec_t, iotop_exec_t, ipsec_log_t, ipsec_mgmt_exec_t, ipsec_tmp_t, iptables_exec_t, iptables_tmp_t, irc_exec_t, irssi_exec_t, iscsi_log_t, iscsi_tmp_t, iso9660_t, iwhd_log_t, jetty_cache_t, jetty_log_t, jetty_tmp_t, jetty_unit_file_t, jetty_var_lib_t, jetty_var_run_t, jockey_exec_t, jockey_var_log_t, journalctl_exec_t, kadmind_log_t, kadmind_tmp_t, kdump_exec_t, kdumpctl_tmp_t, kdumpgui_exec_t, kdumpgui_tmp_t, keepalived_tmp_t, keepalived_unconfined_script_exec_t, keystone_cgi_content_t, keystone_cgi_htaccess_t, keystone_cgi_ra_content_t, keystone_cgi_rw_content_t, keystone_cgi_script_exec_t, keystone_log_t, keystone_tmp_t, kismet_exec_t, kismet_log_t, kismet_tmp_t, kismet_tmpfs_t, klogd_tmp_t, kmod_exec_t, kmod_tmp_t, kpatch_exec_t, krb5_conf_t, krb5_host_rcache_t, krb5_keytab_t, krb5kdc_conf_t, krb5kdc_log_t, krb5kdc_tmp_t, ksmtuned_log_t, ktalkd_log_t, ktalkd_tmp_t, l2tpd_tmp_t, lastlog_t, ld_so_cache_t, ld_so_t, ldconfig_exec_t, ldconfig_tmp_t, lib
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@centos8 ~]# grep httpd_t /var/log/audit/audit.log | audit2allow -m httpdlocal > httpdlocal.te
L'examen du fichier httpdlocal.te révèle la création de ces règles :
[root@centos8 ~]# cat httpdlocal.te module httpdlocal 1.0; require { type httpd_t; type default_t; class capability net_admin; class file { getattr map open read }; } #============= httpd_t ============== #!!!! This avc can be allowed using the boolean 'domain_can_mmap_files' allow httpd_t default_t:file map; allow httpd_t default_t:file { getattr open read }; #!!!! This avc has a dontaudit rule in the current policy allow httpd_t self:capability net_admin;
L'audit du fichier terminé, il faut maintenant utiliser audit2allow pour fabriquer un module de politique :
[root@centos8 ~]# 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@centos8 ~]# semodule -i httpdlocal.pp
Vérifiez que le module est chargé :
[root@centos8 ~]# semodule -l | grep httpd httpdlocal
Redémarrez le service httpd :
[root@centos8 ~]# systemctl restart httpd.service [root@centos8 ~]# systemctl status httpd.service ● httpd.service - The Apache HTTP Server Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled) Active: active (running) since Wed 2024-10-02 13:28:09 CEST; 8s ago Docs: man:httpd.service(8) Main PID: 3620 (httpd) Status: "Started, listening on: port 80" Tasks: 213 (limit: 100949) Memory: 42.7M CGroup: /system.slice/httpd.service ├─3620 /usr/sbin/httpd -DFOREGROUND ├─3622 /usr/sbin/httpd -DFOREGROUND ├─3623 /usr/sbin/httpd -DFOREGROUND ├─3624 /usr/sbin/httpd -DFOREGROUND └─3625 /usr/sbin/httpd -DFOREGROUND Oct 02 13:28:09 centos8.ittraining.loc systemd[1]: Starting The Apache HTTP Server... Oct 02 13:28:09 centos8.ittraining.loc systemd[1]: Started The Apache HTTP Server. Oct 02 13:28:09 centos8.ittraining.loc httpd[3620]: Server configured, listening on: port 80
Consultez le site localhost :
[root@centos8 ~]# lynx --dump localhost www1 test page
Copyright © 2024 Hugh Norris.