Skip to main content

System hardening and security


Table of contents

  1. Security principles
  2. System hardening
  3. User and access management
  4. SELinux and AppArmor
  5. Audit and compliance
  6. Practical exercises


1 - Security principles

Defense in Depth

Principle of least privilege

ConceptApplication
UsersMinimum required rights
ServicesDedicated non-root accounts
FilesRestrictive permissions
NetworkMinimum open ports

Attack surface

# Réduire la surface d'attaque

# 1. Services inutiles
systemctl list-unit-files --type=service --state=enabled

# 2. Ports ouverts
ss -tlnp

# 3. Packages installés
dpkg -l | wc -l # Debian
rpm -qa | wc -l # RHEL
Golden rule

If it isn't needed, disable it or remove it.

🔝 Back to table of contents



2 - System hardening

Security updates

# Debian/Ubuntu
apt update && apt upgrade -y
apt install unattended-upgrades
dpkg-reconfigure unattended-upgrades

# RHEL/CentOS
yum update -y
yum install yum-cron
systemctl enable --now yum-cron

sysctl configuration

# /etc/sysctl.d/99-hardening.conf

# Désactiver le forwarding IP (sauf si routeur)
net.ipv4.ip_forward = 0
net.ipv6.conf.all.forwarding = 0

# Protection contre les attaques réseau
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.icmp_echo_ignore_broadcasts = 1

# Protection contre SYN flood
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_syn_backlog = 2048

# Désactiver IPv6 si non utilisé
net.ipv6.conf.all.disable_ipv6 = 1

# Protection kernel
kernel.randomize_va_space = 2
kernel.exec-shield = 1
# Appliquer
sysctl -p /etc/sysctl.d/99-hardening.conf

Securing the bootloader

# GRUB - Définir un mot de passe
grub2-setpassword

# Permissions
chmod 600 /boot/grub2/grub.cfg

# Désactiver le boot USB/CD dans le BIOS

Securing SSH

# /etc/ssh/sshd_config

# Désactiver root login
PermitRootLogin no

# Authentification par clé uniquement
PasswordAuthentication no
PubkeyAuthentication yes

# Limiter les utilisateurs
AllowUsers admin deploy

# Port non standard (optionnel)
Port 2222

# Autres options de sécurité
Protocol 2
MaxAuthTries 3
LoginGraceTime 20
PermitEmptyPasswords no
X11Forwarding no
AllowTcpForwarding no
ClientAliveInterval 300
ClientAliveCountMax 2
# Vérifier et redémarrer
sshd -t && systemctl restart sshd

Firewall with iptables/nftables

# UFW (Ubuntu)
ufw default deny incoming
ufw default allow outgoing
ufw allow ssh
ufw allow 80/tcp
ufw allow 443/tcp
ufw enable

# iptables basique
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT

🔝 Back to table of contents



3 - User and access management

Password policy

# /etc/login.defs
PASS_MAX_DAYS 90
PASS_MIN_DAYS 7
PASS_MIN_LEN 12
PASS_WARN_AGE 14

# PAM - /etc/pam.d/common-password (Debian)
password requisite pam_pwquality.so retry=3 \
minlen=12 \
dcredit=-1 \
ucredit=-1 \
ocredit=-1 \
lcredit=-1

Lockout after failed attempts

# /etc/pam.d/common-auth
auth required pam_tally2.so deny=5 unlock_time=900 onerr=fail

# Vérifier les tentatives
pam_tally2 --user=username

# Débloquer un utilisateur
pam_tally2 --user=username --reset

System and service accounts

# Créer un compte service
useradd -r -s /usr/sbin/nologin -d /nonexistent myservice

# Vérifier les shells
grep -v '/sbin/nologin\|/bin/false' /etc/passwd

# Désactiver les comptes inutilisés
usermod -L -e 1 olduser

sudo configuration

# /etc/sudoers.d/admins
# Groupe admin avec tous les droits
%admins ALL=(ALL:ALL) ALL

# Utilisateur spécifique avec commandes limitées
deploy ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart myapp

# Logger toutes les commandes sudo
Defaults log_output
Defaults!/usr/bin/sudoreplay !log_output

🔝 Back to table of contents



4 - SELinux and AppArmor

SELinux (RHEL/CentOS)

# Vérifier le statut
getenforce
sestatus

# Modes
# Enforcing : Applique les règles
# Permissive : Log sans bloquer
# Disabled : Désactivé

# Changer temporairement
setenforce 0 # Permissive
setenforce 1 # Enforcing

# Configuration permanente
# /etc/selinux/config
SELINUX=enforcing
SELINUXTYPE=targeted

Common SELinux commands

# Voir les contextes
ls -Z /var/www/html

# Restaurer les contextes par défaut
restorecon -Rv /var/www/html

# Modifier un contexte
chcon -t httpd_sys_content_t /var/www/html/index.html

# Gérer les booléens
getsebool -a | grep httpd
setsebool -P httpd_can_network_connect on

# Analyser les logs
audit2why < /var/log/audit/audit.log
audit2allow -a # Générer une politique

AppArmor (Debian/Ubuntu)

# Statut
aa-status
apparmor_status

# Modes par profil
# enforce : Applique
# complain : Log sans bloquer

# Mettre en mode complain
aa-complain /etc/apparmor.d/usr.bin.firefox

# Mettre en mode enforce
aa-enforce /etc/apparmor.d/usr.bin.firefox

# Recharger les profils
apparmor_parser -r /etc/apparmor.d/usr.bin.firefox

AppArmor profile example

# /etc/apparmor.d/usr.local.bin.myapp
#include <tunables/global>

/usr/local/bin/myapp {
#include <abstractions/base>

/usr/local/bin/myapp mr,
/var/log/myapp/** rw,
/etc/myapp/** r,
/tmp/myapp-* rw,

network inet tcp,

deny /etc/passwd r,
deny /etc/shadow r,
}

🔝 Back to table of contents



5 - Audit and compliance

Auditd - System auditing

# Installer
apt install auditd # Debian
yum install audit # RHEL

# Règles d'audit
# /etc/audit/rules.d/audit.rules

# Surveiller les modifications de fichiers sensibles
-w /etc/passwd -p wa -k identity
-w /etc/shadow -p wa -k identity
-w /etc/sudoers -p wa -k sudoers

# Surveiller les commandes privilégiées
-a always,exit -F path=/usr/bin/sudo -F perm=x -k privileged

# Surveiller les modifications système
-w /etc/sysctl.conf -p wa -k sysctl

# Charger les règles
auditctl -R /etc/audit/rules.d/audit.rules

Analyzing audit logs

# Rechercher par clé
ausearch -k identity

# Rapport des événements
aureport --summary
aureport --login
aureport --auth

# Événements récents
ausearch -ts recent

Security scanning tools

# Lynis - Audit système
apt install lynis
lynis audit system

# OpenSCAP - Conformité
apt install libopenscap8 ssg-debian
oscap xccdf eval --profile xccdf_org.ssgproject.content_profile_standard \
--results results.xml /usr/share/xml/scap/ssg/content/ssg-debian10-ds.xml

# Nmap - Scan réseau
nmap -sV -O localhost

# Rkhunter - Rootkit
rkhunter --check

Hardening checklist

#!/bin/bash
# Script de vérification de sécurité basique

echo "=== Vérification de sécurité ==="

echo -n "SSH root login: "
grep -q "^PermitRootLogin no" /etc/ssh/sshd_config && echo "OK" || echo "FAIL"

echo -n "Password auth SSH: "
grep -q "^PasswordAuthentication no" /etc/ssh/sshd_config && echo "OK" || echo "WARN"

echo -n "Firewall actif: "
ufw status | grep -q "active" && echo "OK" || echo "FAIL"

echo -n "Mises à jour auto: "
dpkg -l | grep -q unattended-upgrades && echo "OK" || echo "WARN"

echo -n "Comptes sans mot de passe: "
awk -F: '($2 == "" ) { print $1 }' /etc/shadow | wc -l

🔝 Back to table of contents



6 - Practical exercises

Exercise 1: SSH hardening

Secure your server's SSH configuration:

  • Disable root login
  • Key-based authentication only
  • Restrict to certain users
Solution
# Générer une clé sur le client
ssh-keygen -t ed25519

# Copier sur le serveur
ssh-copy-id user@server

# Modifier /etc/ssh/sshd_config
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
AllowUsers admin

# Tester et redémarrer
sshd -t && systemctl restart sshd

Exercise 2: auditd configuration

Configure auditd to monitor:

  • Changes to /etc/passwd
  • Execution of sudo
Solution
# /etc/audit/rules.d/custom.rules
-w /etc/passwd -p wa -k passwd_changes
-a always,exit -F path=/usr/bin/sudo -F perm=x -k sudo_exec

# Recharger
auditctl -R /etc/audit/rules.d/custom.rules

# Vérifier
ausearch -k passwd_changes
ausearch -k sudo_exec

Quiz

Q1. Which command enables SELinux in Enforcing mode?

Answer

setenforce 1

Q2. Which sysctl parameter protects against SYN flood attacks?

Answer

net.ipv4.tcp_syncookies = 1

🔝 Back to table of contents



Key takeaways

  • Defense in Depth: multiple layers of security
  • Least privilege: grant only the required rights
  • SSH hardening: keys, no root, limited users
  • SELinux/AppArmor: mandatory access control
  • Auditd: traceability of actions
  • Automatic updates: security patches

🔝 Back to table of contents


← Previous chapter | Next chapter: Log management →