adminSys update - add config firewall web

This commit is contained in:
2026-03-07 10:51:14 +01:00
parent 897214921f
commit 65fde7640b
4 changed files with 393 additions and 0 deletions

31
servers/linux/README.md Normal file
View File

@@ -0,0 +1,31 @@
# 🛠️ Server Admin Setup (Debian/Ubuntu)
Ce dépôt contient un script d'automatisation pour la configuration initiale et la surveillance de serveurs Linux (Debian/Ubuntu).
## 🚀 Fonctionnalités
Le script `config_adminSys.sh` déploie les briques suivantes :
* **Sécurité Réseau** : Configuration de `UFW` (bloque tout sauf SSH/22) et installation de `Fail2Ban`. /!\ A personnaliser si c'est un serveur Web, postgres....
* **Maintenance** : Activation des `unattended-upgrades` pour les patchs de sécurité automatiques.
* **Alertes Mail** : Configuration de `msmtp` pour l'envoi de rapports système via SMTP.
* **Monitoring de Santé** : Script de surveillance (`sys_check.sh`) installé dans `/usr/local/bin/`. a paramétrer
* Alerte si **Disque > 90%**
* Alerte si **Inodes > 90%**
* Alerte si **RAM > 90%**
* **Automatisation** : Tâche Cron horaire pour le check de santé.
## 📋 Prérequis
1. Un serveur sous **Debian** ou compatible.
2. Un compte mail dédié (ex: `srv.hostname@domain.tld`).
3. Un **App Password** (Mot de passe d'application).
## 💻 Utilisation Rapide (One-Liner)
Connectez-vous à votre nouveau serveur et lancez la commande suivante :
```bash
wget -qO- [https://raw.githubusercontent.com/VOTRE_USER/VOTRE_REPO/main/config_adminSys.sh](https://raw.githubusercontent.com/VOTRE_USER/VOTRE_REPO/main/config_adminSys.sh) | sudo bash

109
servers/linux/config_adminSys.sh Executable file
View File

@@ -0,0 +1,109 @@
#!/bin/bash
# --- 0. VÉRIFICATION DES DROITS ---
if [ "$EUID" -ne 0 ]; then
echo "❌ Erreur : Ce script doit être lancé avec sudo."
exit 1
fi
# --- 1. CONFIGURATION DYNAMIQUE ---
HOSTNAME=$(hostname)
SMTP_HOST="mail.acemail.fr"
SMTP_PORT="587"
SMTP_USER="srv.${HOSTNAME}@a5l.fr"
DEST_EMAIL="cedric+${HOSTNAME}@abonnel.fr"
echo "=========================================================="
echo " VÉRIFICATION SMTP & DÉPLOIEMENT - ${HOSTNAME}"
echo "=========================================================="
# --- 2. TEST DU MOT DE PASSE SMTP ---
AUTH_OK=false
while [ "$AUTH_OK" = false ]; do
echo -n "🔑 Entrez le mot de passe SMTP pour ${SMTP_USER} : "
read -s SMTP_PASS
echo -e "\n⏳ Test de connexion en cours..."
# Config temporaire pour le test
cat > /tmp/.msmtp_test <<EOF
defaults
auth on
tls on
tls_trust_file /etc/ssl/certs/ca-certificates.crt
account test
host $SMTP_HOST
port $SMTP_PORT
from $SMTP_USER
user $SMTP_USER
password $SMTP_PASS
account default : test
EOF
chmod 600 /tmp/.msmtp_test
# Tentative d'envoi
echo "Test de configuration" | msmtp --file=/tmp/.msmtp_test -t "$DEST_EMAIL" 2>/dev/null
if [ $? -eq 0 ]; then
echo "✅ Authentification SMTP réussie !"
AUTH_OK=true
rm /tmp/.msmtp_test
else
echo "❌ Échec. Vérifiez le mot de passe ou la connexion réseau."
rm /tmp/.msmtp_test
fi
done
# --- 3. INSTALLATION ---
echo "--- Installation des paquets ---"
DEBIAN_FRONTEND=noninteractive apt update
DEBIAN_FRONTEND=noninteractive apt install -y msmtp msmtp-mta bsd-mailx ufw fail2ban unattended-upgrades curl
# --- 4. CONFIGURATION MSMTP ---
echo "--- Configuration MSMTP ---"
cat > /etc/msmtprc <<EOF
defaults
auth on
tls on
tls_trust_file /etc/ssl/certs/ca-certificates.crt
logfile /var/log/msmtp.log
account default
host $SMTP_HOST
port $SMTP_PORT
from $SMTP_USER
user $SMTP_USER
password $SMTP_PASS
EOF
chmod 600 /etc/msmtprc
ln -sf /usr/bin/msmtp /usr/sbin/sendmail
# --- 5. SCRIPT DE SURVEILLANCE ---
echo "--- Création du check santé ---"
# On utilise cat directement ici car on est déjà en root
cat > /usr/local/bin/sys_check.sh <<EOF
#!/bin/bash
THRESHOLD=90
EMAIL="$DEST_EMAIL"
HOST="\$(hostname)"
DISK_USAGE=\$(df / | awk 'NR==2 {print \$5}' | sed 's/%//')
RAM_USAGE=\$(free | grep Mem | awk '{print int(\$3/\$2 * 100)}')
if [ "\$DISK_USAGE" -gt "\$THRESHOLD" ] || [ "\$RAM_USAGE" -gt "\$THRESHOLD" ]; then
MESSAGE="ALERTE sur \$HOST\nDisque: \$DISK_USAGE% | RAM: \$RAM_USAGE%\nDate: \$(date)"
echo -e "\$MESSAGE" | mail -s "⚠️ ALERTE : \$HOST" "\$EMAIL"
fi
EOF
chmod +x /usr/local/bin/sys_check.sh
# --- 6. SÉCURITÉ & AUTOMATISATION ---
echo "--- Activation Sécurité & Cron ---"
ufw allow 22/tcp
ufw --force enable
systemctl restart fail2ban
(crontab -l 2>/dev/null | grep -v "sys_check.sh" ; echo "0 * * * * /usr/local/bin/sys_check.sh") | crontab -
# --- 7. RAPPORT FINAL ---
echo "Le déploiement est terminé avec succès sur $HOSTNAME." | mail -s "[OK] Setup Admin : $HOSTNAME" "$DEST_EMAIL"
echo "✅ Terminé avec succès !"

140
servers/linux/firewall.php Normal file
View File

@@ -0,0 +1,140 @@
<?php
// Configuration : ports à ne JAMAIS supprimer via l'interface
$protected_ports = ['22', '2222', '80', '443'];
$message = "";
$status = "Inactive";
// --- LOGIQUE D'ACTION ---
// Ajouter un port
if (isset($_POST['add_port']) && !empty($_POST['port'])) {
$port = escapeshellarg(trim($_POST['port']));
$proto = escapeshellarg($_POST['proto']);
exec("sudo /usr/sbin/ufw allow $port/$proto", $output, $return);
$message = ($return == 0) ? "✅ Port $port/$proto ouvert." : "❌ Erreur UFW.";
}
// Supprimer une règle
if (isset($_GET['delete'])) {
$id = (int)$_GET['delete'];
// Récupérer les détails de la règle avant suppression pour la sécurité
exec("sudo /usr/sbin/ufw status numbered", $check_output);
foreach ($check_output as $line) {
if (strpos($line, "[$id]") !== false) {
foreach ($protected_ports as $p) {
if (strpos($line, $p) !== false) {
die("🛑 ERREUR : La règle #$id semble protéger un port critique ($p). Suppression annulée par sécurité.");
}
}
}
}
exec("echo 'y' | sudo /usr/sbin/ufw delete $id", $output, $return);
header("Location: " . strtok($_SERVER["REQUEST_URI"], '?') . "?msg=deleted");
exit;
}
if (isset($_GET['msg']) && $_GET['msg'] == 'deleted') $message = "🗑️ Règle supprimée.";
// --- RÉCUPÉRATION DES DONNÉES ---
exec("sudo /usr/sbin/ufw status numbered", $ufw_output);
if (isset($ufw_output[0]) && strpos($ufw_output[0], 'active') !== false) {
$status = "Active";
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>UFW Manager Local</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.4/css/bulma.min.css">
<style>
.status-badge { font-weight: bold; padding: 5px 10px; border-radius: 4px; }
.status-Active { background: #48c78e; color: white; }
.status-Inactive { background: #f14668; color: white; }
</style>
</head>
<body class="has-background-light" style="min-height: 100vh;">
<section class="section">
<div class="container is-max-desktop">
<div class="level">
<div class="level-left">
<h1 class="title">🔥 UFW Manager</h1>
</div>
<div class="level-right">
<span class="status-badge status-<?php echo $status; ?>">Status: <?php echo $status; ?></span>
</div>
</div>
<?php if ($message): ?>
<div class="notification is-primary is-light"><?php echo $message; ?></div>
<?php endif; ?>
<div class="box">
<form method="POST" class="field is-grouped">
<div class="control is-expanded">
<input class="input" type="text" name="port" placeholder="Port ou Service (ex: 8080)">
</div>
<div class="control">
<div class="select">
<select name="proto">
<option value="tcp">TCP</option>
<option value="udp">UDP</option>
</select>
</div>
</div>
<div class="control">
<button type="submit" name="add_port" class="button is-dark">Autoriser</button>
</div>
</form>
</div>
<div class="box p-0">
<table class="table is-fullwidth is-hoverable m-0">
<thead>
<tr class="has-background-white-ter">
<th class="pl-5">#</th>
<th>Vers</th>
<th>Action</th>
<th>Depuis</th>
<th class="has-text-right pr-5">Action</th>
</tr>
</thead>
<tbody>
<?php
$rules_found = false;
foreach ($ufw_output as $line) {
if (preg_match('/\[\s*(\d+)\]\s+(.*?)\s+(ALLOW|DENY|ALLOW IN|DENY IN)\s+(.*)/', $line, $matches)) {
$rules_found = true;
$is_critical = false;
foreach ($protected_ports as $p) { if (strpos($matches[2], $p) !== false) $is_critical = true; }
echo "<tr>
<td class='pl-5'><b>{$matches[1]}</b></td>
<td><code>{$matches[2]}</code></td>
<td><span class='tag is-light is-success'>{$matches[3]}</span></td>
<td><small>{$matches[4]}</small></td>
<td class='has-text-right pr-5'>";
if (!$is_critical) {
echo "<a href='?delete={$matches[1]}' class='button is-small is-danger is-outlined' onclick='return confirm(\"Supprimer la règle #{$matches[1]} ?\")'>Supprimer</a>";
} else {
echo "<span class='tag is-warning is-light'>Protégé</span>";
}
echo "</td></tr>";
}
}
if (!$rules_found) echo "<tr><td colspan='5' class='has-text-centered p-5'>Aucune règle active.</td></tr>";
?>
</tbody>
</table>
</div>
<p class="help has-text-centered mt-4">Lancé en mode local. Ctrl+C dans le terminal pour quitter.</p>
</div>
</section>
</body>
</html>

View File

@@ -0,0 +1,113 @@
#!/bin/bash
# --- 0. VERIFICATION DES DROITS ---
if [ "$EUID" -ne 0 ]; then
echo "❌ Erreur : Ce script doit être lancé avec sudo."
exit 1
fi
# Récupérer le vrai nom de l'utilisateur qui a lancé le sudo
REAL_USER=${SUDO_USER:-$USER}
echo "--- 1. Installation de PHP ---"
apt update && apt install -y php-cli
# --- 2. CONFIGURATION SUDOERS ---
echo "--- 2. Autorisation UFW pour l'utilisateur $REAL_USER ---"
SUDOERS_FILE="/etc/sudoers.d/ufw-php-manager"
if [ ! -f "$SUDOERS_FILE" ]; then
echo "$REAL_USER ALL=(ALL) NOPASSWD: /usr/sbin/ufw" > "$SUDOERS_FILE"
chmod 440 "$SUDOERS_FILE"
echo "✅ Sudoers configuré."
fi
# --- 3. OUVERTURE DU PORT 8080 ---
echo "--- 3. Configuration du Firewall pour l'interface ---"
ufw allow 8080/tcp
echo "✅ Port 8080 ouvert dans UFW."
# --- 4. CREATION DU FICHIER PHP ---
echo "--- 4. Création de firewall.php ---"
cat > firewall.php <<'EOF'
<?php
$protected_ports = ['22', '80', '443', '8080'];
$message = "";
// Action : Ajouter
if (isset($_POST['add_port']) && !empty($_POST['port'])) {
$port = escapeshellarg(trim($_POST['port']));
$proto = escapeshellarg($_POST['proto']);
exec("sudo /usr/sbin/ufw allow $port/$proto", $output, $return);
$message = ($return == 0) ? "✅ Port $port/$proto ouvert." : "❌ Erreur UFW.";
}
// Action : Supprimer
if (isset($_GET['delete'])) {
$id = (int)$_GET['delete'];
exec("sudo /usr/sbin/ufw status numbered", $check_output);
$is_protected = false;
foreach ($check_output as $line) {
if (strpos($line, "[$id]") !== false) {
foreach ($protected_ports as $p) {
if (strpos($line, $p) !== false) $is_protected = true;
}
}
}
if ($is_protected) {
$message = "🛑 Impossible de supprimer un port critique ($id).";
} else {
exec("echo 'y' | sudo /usr/sbin/ufw delete $id", $output, $return);
header("Location: firewall.php?msg=deleted");
exit;
}
}
if (isset($_GET['msg']) && $_GET['msg'] == 'deleted') $message = "🗑️ Règle supprimée.";
exec("sudo /usr/sbin/ufw status numbered", $ufw_output);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>UFW Remote Manager</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.4/css/bulma.min.css">
</head>
<body class="p-5">
<div class="container is-max-desktop">
<h1 class="title">🔥 UFW Remote Manager</h1>
<?php if ($message) echo "<div class='notification is-info'>$message</div>"; ?>
<div class="box">
<form method="POST" class="field is-grouped">
<input class="input mr-2" type="text" name="port" placeholder="Port">
<div class="select mr-2"><select name="proto"><option value="tcp">TCP</option><option value="udp">UDP</option></select></div>
<button type="submit" name="add_port" class="button is-dark">Ajouter</button>
</form>
</div>
<table class="table is-fullwidth box">
<thead><tr><th>#</th><th>Vers</th><th>Action</th><th>Depuis</th><th>Action</th></tr></thead>
<tbody>
<?php foreach ($ufw_output as $line): ?>
<?php if (preg_match('/\[\s*(\d+)\]\s+(.*?)\s+(ALLOW|DENY|ALLOW IN)\s+(.*)/', $line, $m)): ?>
<tr>
<td><?= $m[1] ?></td><td><code><?= $m[2] ?></code></td><td><?= $m[3] ?></td><td><?= $m[4] ?></td>
<td><a href="?delete=<?= $m[1] ?>" class="button is-small is-danger">Supprimer</a></td>
</tr>
<?php endif; ?>
<?php endforeach; ?>
</tbody>
</table>
</div>
</body>
</html>
EOF
chown $REAL_USER:$REAL_USER firewall.php
# --- 5. LANCEMENT ---
echo "--- 5. Lancement du serveur ---"
echo "🚀 L'interface est disponible sur : http://$(hostname -I | awk '{print $1}'):8080/firewall.php"
echo "Pressez Ctrl+C pour arrêter le serveur."
# Lancer en tant qu'utilisateur normal (pas root) pour plus de sécurité
sudo -u $REAL_USER php -S 0.0.0.0:8080