Configuration avancée, sécurité, performance et production
Samba est une implémentation libre des protocoles SMB/CIFS qui permet l'interopérabilité entre systèmes Unix/Linux et Windows. Cette section couvre l'architecture interne et les concepts avancés nécessaires pour une maîtrise complète.
Samba 4 introduit une architecture modulaire révolutionnaire avec plusieurs démons spécialisés :
| Version SMB | Alias | Fonctionnalités clés | Sécurité |
|---|---|---|---|
| SMB 1.0 | CIFS | Base, NetBIOS | ⚠️ Obsolète |
| SMB 2.0 | SMB2 | Performance améliorée | ✅ Acceptable |
| SMB 2.1 | SMB2.1 | Oplocks, Large MTU | ✅ Bon |
| SMB 3.0 | SMB3 | Chiffrement, Multichannel | 🔒 Excellent |
| SMB 3.1.1 | SMB3.1.1 | Pré-authentification | 🔒 Maximum |
En production, désactivez SMB1 complètement et forcez SMB 3.0+ pour la sécurité. Utilisez min protocol = SMB3 dans votre configuration.
Samba implémente plusieurs couches de sécurité :
# Mise à jour complète
sudo apt update && sudo apt full-upgrade -y
# Installation des dépendances
sudo apt install -y build-essential libacl1-dev libattr1-dev \
libblkid-dev libgnutls28-dev libreadline-dev python3-dev \
libpam0g-dev python3-dnspython gdb pkg-config libpopt-dev \
libldap2-dev dnsutils libbsd-dev attr krb5-user docbook-xsl \
libcups2-dev acl python3-markdown python3-dnspython
# Configuration du hostname (critique pour AD)
sudo hostnamectl set-hostname samba-srv.domain.local
echo "127.0.1.1 samba-srv.domain.local samba-srv" | sudo tee -a /etc/hosts
Pour un contrôle total et les dernières fonctionnalités :
# Téléchargement des sources
cd /usr/src
sudo wget https://download.samba.org/pub/samba/stable/samba-4.19.4.tar.gz
sudo tar -xzf samba-4.19.4.tar.gz
cd samba-4.19.4
# Configuration de la compilation
sudo ./configure \
--enable-fhs \
--prefix=/usr \
--sysconfdir=/etc \
--localstatedir=/var \
--with-privatedir=/var/lib/samba/private \
--with-smbpasswd-file=/etc/samba/smbpasswd \
--enable-cups \
--with-acl-support \
--with-ads \
--with-automount \
--with-fhs \
--with-pam \
--with-winbind \
--with-shared-modules=idmap_ad,idmap_rid,idmap_adex,idmap_hash,idmap_tdb2
# Compilation (utilise tous les cœurs)
sudo make -j$(nproc)
# Installation
sudo make install
# Configuration des services systemd
sudo cp examples/systemd/samba.service /etc/systemd/system/
sudo systemctl daemon-reload
# Installation complète Samba
sudo apt install -y samba samba-common-bin smbclient winbind \
libnss-winbind libpam-winbind krb5-config krb5-user
# Pour contrôleur de domaine AD
sudo apt install -y samba-dsdb-modules samba-vfs-modules
# Outils d'administration
sudo apt install -y samba-tool python3-samba
# Activation des dépôts
sudo dnf install -y epel-release
sudo dnf config-manager --set-enabled powertools
# Installation Samba
sudo dnf install -y samba samba-client samba-common \
samba-winbind samba-winbind-clients
# Démarrage des services
sudo systemctl enable --now smb nmb winbind
Sur CentOS/RHEL, configurez SELinux pour Samba : sudo setsebool -P samba_enable_home_dirs on
Le fichier /etc/samba/smb.conf est divisé en sections. Voici une configuration de base optimisée :
# ============================================================================
# CONFIGURATION SAMBA EXPERT - PRODUCTION READY
# ============================================================================
[global]
# === IDENTIFICATION DU SERVEUR ===
workgroup = DOMAIN
server string = Samba Server %v
netbios name = SAMBA-SRV
server role = standalone server
# === PROTOCOLES ET SÉCURITÉ ===
# Désactivation SMB1 (sécurité)
min protocol = SMB2
max protocol = SMB3
# Chiffrement obligatoire
smb encrypt = required
# Authentification
security = user
passdb backend = tdbsam
# Mappage des utilisateurs
map to guest = bad user
guest account = nobody
# === OPTIMISATIONS RÉSEAU ===
# Interfaces réseau
interfaces = lo eth0
bind interfaces only = yes
# Optimisations TCP
socket options = TCP_NODELAY IPTOS_LOWDELAY SO_RCVBUF=131072 SO_SNDBUF=131072
# Cache et performance
getwd cache = yes
stat cache = yes
# Oplocks pour les performances
oplocks = yes
level2 oplocks = yes
kernel oplocks = no
# === LOGS ET MONITORING ===
log file = /var/log/samba/log.%m
max log size = 1000
log level = 1 auth:3 winbind:2
# Audit (optionnel)
# vfs objects = full_audit
# full_audit:prefix = %u|%I|%S
# full_audit:success = open opendir write unlink rename mkdir rmdir
# full_audit:failure = all
# === PARTAGES DE FICHIERS ===
# Permissions Unix
create mask = 0664
directory mask = 0775
force create mode = 0664
force directory mode = 0775
# Préservation des attributs
map archive = no
map hidden = no
map read only = no
map system = no
store dos attributes = yes
# === OPTIMISATIONS AVANCÉES ===
# Cache des noms
name cache timeout = 660
# Optimisations disque
strict sync = no
sync always = no
# Gestion des verrous
strict locking = auto
# Performance des gros fichiers
use sendfile = yes
aio read size = 16384
aio write size = 16384
# ============================================================================
# PARTAGES
# ============================================================================
[homes]
comment = Répertoires personnels
browseable = no
read only = no
create mask = 0700
directory mask = 0700
valid users = %S
[public]
comment = Partage public
path = /srv/samba/public
browseable = yes
read only = no
guest ok = yes
create mask = 0664
directory mask = 0775
force user = nobody
force group = nogroup
[secure]
comment = Partage sécurisé
path = /srv/samba/secure
browseable = yes
read only = no
valid users = @samba-users
create mask = 0660
directory mask = 0770
force group = samba-users
# Création des répertoires de partage
sudo mkdir -p /srv/samba/{public,secure}
# Création du groupe samba-users
sudo groupadd samba-users
# Permissions pour le partage public
sudo chown nobody:nogroup /srv/samba/public
sudo chmod 775 /srv/samba/public
# Permissions pour le partage sécurisé
sudo chown root:samba-users /srv/samba/secure
sudo chmod 770 /srv/samba/secure
# ACL par défaut (optionnel)
sudo setfacl -d -m g:samba-users:rwx /srv/samba/secure
sudo setfacl -d -m o::--- /srv/samba/secure
# Création d'un utilisateur système
sudo useradd -m -s /bin/bash -G samba-users john
# Définition du mot de passe système
sudo passwd john
# Ajout à Samba avec mot de passe
sudo smbpasswd -a john
# Activation du compte Samba
sudo smbpasswd -e john
# Script de création en masse
cat << 'EOF' > /tmp/create_samba_users.sh
#!/bin/bash
USERS=("alice" "bob" "charlie")
for user in "${USERS[@]}"; do
sudo useradd -m -s /bin/bash -G samba-users "$user"
echo "Password123!" | sudo passwd --stdin "$user" 2>/dev/null || echo "Password123!" | sudo chpasswd
echo -e "Password123!\nPassword123!" | sudo smbpasswd -a "$user"
sudo smbpasswd -e "$user"
echo "Utilisateur $user créé avec succès"
done
EOF
chmod +x /tmp/create_samba_users.sh
sudo /tmp/create_samba_users.sh
Sécurisation complète des communications Samba :
# Ajout dans [global] de smb.conf
[global]
# === CHIFFREMENT OBLIGATOIRE ===
smb encrypt = required
server signing = mandatory
client signing = mandatory
# === CERTIFICATS SSL ===
tls enabled = yes
tls keyfile = /etc/samba/tls/private.key
tls certfile = /etc/samba/tls/cert.pem
tls cafile = /etc/samba/tls/ca.pem
# === PROTOCOLES SÉCURISÉS UNIQUEMENT ===
min protocol = SMB3_00
max protocol = SMB3_11
# === AUTHENTIFICATION RENFORCÉE ===
ntlm auth = no
raw NTLMv2 auth = no
lanman auth = no
client NTLMv2 auth = yes
client lanman auth = no
client plaintext auth = no
# Création du répertoire TLS
sudo mkdir -p /etc/samba/tls
cd /etc/samba/tls
# Génération de la clé privée CA
sudo openssl genrsa -out ca.key 4096
# Génération du certificat CA
sudo openssl req -new -x509 -days 3650 -key ca.key -out ca.pem \
-subj "/C=FR/ST=IDF/L=Paris/O=MonEntreprise/OU=IT/CN=Samba-CA"
# Génération de la clé privée du serveur
sudo openssl genrsa -out private.key 4096
# Génération de la demande de certificat
sudo openssl req -new -key private.key -out server.csr \
-subj "/C=FR/ST=IDF/L=Paris/O=MonEntreprise/OU=IT/CN=samba-srv.domain.local"
# Signature du certificat serveur
sudo openssl x509 -req -days 365 -in server.csr -CA ca.pem -CAkey ca.key \
-CAcreateserial -out cert.pem
# Permissions sécurisées
sudo chmod 600 private.key ca.key
sudo chmod 644 cert.pem ca.pem
sudo chown root:root /etc/samba/tls/*
# Activation UFW
sudo ufw enable
# Règles Samba spécifiques
sudo ufw allow from 192.168.1.0/24 to any port 139 comment 'SMB NetBIOS'
sudo ufw allow from 192.168.1.0/24 to any port 445 comment 'SMB Direct'
sudo ufw allow from 192.168.1.0/24 to any port 137:138/udp comment 'NetBIOS Name'
# Règles pour contrôleur de domaine (si applicable)
sudo ufw allow from 192.168.1.0/24 to any port 53 comment 'DNS'
sudo ufw allow from 192.168.1.0/24 to any port 88 comment 'Kerberos'
sudo ufw allow from 192.168.1.0/24 to any port 389 comment 'LDAP'
sudo ufw allow from 192.168.1.0/24 to any port 636 comment 'LDAPS'
sudo ufw allow from 192.168.1.0/24 to any port 464 comment 'Kerberos Password'
# Limitation du taux de connexion
sudo ufw limit ssh
# Vérification des règles
sudo ufw status numbered
# Ajout dans [global]
[global]
# === AUDIT COMPLET ===
vfs objects = full_audit
full_audit:prefix = %u|%I|%m|%S
full_audit:success = pread pwrite read write open opendir mkdir rmdir closedir unlink rename
full_audit:failure = all
full_audit:facility = local5
full_audit:priority = notice
# === LOGS DÉTAILLÉS ===
log level = 2 auth:5 winbind:3 passdb:3 sam:3
max log size = 10000
log file = /var/log/samba/log.%m
# === SYSLOG INTEGRATION ===
syslog = 1
syslog only = no
# Configuration rsyslog pour Samba
# Ajouter dans /etc/rsyslog.d/10-samba.conf :
# local5.* /var/log/samba/audit.log
# & stop
Pour un environnement ultra-sécurisé, implémentez également : fail2ban pour les tentatives de connexion, rotation automatique des logs, monitoring en temps réel avec ELK Stack.
Intégration complète avec un domaine Active Directory existant :
# Configuration DNS pour pointer vers le DC
echo "nameserver 192.168.1.10" | sudo tee /etc/resolv.conf
echo "search domain.local" | sudo tee -a /etc/resolv.conf
# Synchronisation temporelle (critique)
sudo apt install -y chrony
echo "server dc1.domain.local iburst" | sudo tee -a /etc/chrony/chrony.conf
sudo systemctl restart chrony
# Vérification de la résolution DNS
nslookup domain.local
nslookup dc1.domain.local
# Test de connectivité Kerberos
kinit administrator@DOMAIN.LOCAL
[libdefaults]
default_realm = DOMAIN.LOCAL
dns_lookup_realm = true
dns_lookup_kdc = true
ticket_lifetime = 24h
renew_lifetime = 7d
forwardable = true
proxiable = true
default_tkt_enctypes = aes256-cts-hmac-sha1-96 aes128-cts-hmac-sha1-96
default_tgs_enctypes = aes256-cts-hmac-sha1-96 aes128-cts-hmac-sha1-96
permitted_enctypes = aes256-cts-hmac-sha1-96 aes128-cts-hmac-sha1-96
[realms]
DOMAIN.LOCAL = {
kdc = dc1.domain.local
kdc = dc2.domain.local
admin_server = dc1.domain.local
default_domain = domain.local
}
[domain_realm]
.domain.local = DOMAIN.LOCAL
domain.local = DOMAIN.LOCAL
[logging]
kdc = FILE:/var/log/krb5kdc.log
admin_server = FILE:/var/log/kadmin.log
default = FILE:/var/log/krb5lib.log
[global]
# === CONFIGURATION DOMAINE AD ===
workgroup = DOMAIN
realm = DOMAIN.LOCAL
security = ads
server role = member server
# === AUTHENTIFICATION KERBEROS ===
kerberos method = secrets and keytab
client use spnego = yes
client ntlmv2 auth = yes
encrypt passwords = yes
# === WINBIND CONFIGURATION ===
winbind use default domain = yes
winbind offline logon = yes
winbind nss info = rfc2307
winbind enum users = no
winbind enum groups = no
winbind cache time = 300
winbind max domain connections = 10
# === MAPPAGE ID ===
idmap config * : backend = tdb
idmap config * : range = 10000-19999
idmap config DOMAIN : backend = ad
idmap config DOMAIN : range = 20000-99999
idmap config DOMAIN : schema_mode = rfc2307
idmap config DOMAIN : unix_nss_info = yes
# === TEMPLATES SHELL ===
template shell = /bin/bash
template homedir = /home/%U
# === LOGS WINBIND ===
log file = /var/log/samba/log.%m
log level = 1 winbind:3 idmap:3
# Test de la configuration
sudo testparm
# Arrêt des services
sudo systemctl stop smbd nmbd winbind
# Jonction au domaine
sudo net ads join -U administrator
# Configuration NSS
sudo sed -i 's/passwd:.*files systemd/passwd: files winbind systemd/' /etc/nsswitch.conf
sudo sed -i 's/group:.*files systemd/group: files winbind systemd/' /etc/nsswitch.conf
# Démarrage des services
sudo systemctl start smbd nmbd winbind
sudo systemctl enable smbd nmbd winbind
# Vérification de la jonction
sudo net ads testjoin
sudo wbinfo -t
sudo wbinfo -u
sudo wbinfo -g
# Test d'authentification
getent passwd administrator
id administrator@domain.local
Configuration d'un contrôleur de domaine Samba 4 avec toutes les fonctionnalités AD :
# Arrêt des services existants
sudo systemctl stop smbd nmbd winbind
# Sauvegarde de la configuration existante
sudo mv /etc/samba/smb.conf /etc/samba/smb.conf.backup
# Provisioning du domaine
sudo samba-tool domain provision \
--realm=DOMAIN.LOCAL \
--domain=DOMAIN \
--adminpass='ComplexPassword123!' \
--server-role=dc \
--dns-backend=SAMBA_INTERNAL \
--host-name=DC1 \
--host-ip=192.168.1.10
# Configuration DNS
echo "nameserver 127.0.0.1" | sudo tee /etc/resolv.conf
echo "search domain.local" | sudo tee -a /etc/resolv.conf
# Démarrage du service samba
sudo systemctl enable samba-ad-dc
sudo systemctl start samba-ad-dc
# Vérification du domaine
sudo samba-tool domain level show
sudo samba-tool dns query localhost domain.local @ ALL
Les modules VFS étendent les fonctionnalités de Samba :
[partage-enterprise]
comment = Partage Enterprise avec fonctionnalités avancées
path = /srv/samba/enterprise
browseable = yes
read only = no
valid users = @enterprise-users
# === MODULES VFS AVANCÉS ===
vfs objects = full_audit recycle shadow_copy2 streams_xattr acl_xattr
# === AUDIT COMPLET ===
full_audit:prefix = %u|%I|%m|%S|%T
full_audit:success = pread pwrite read write open opendir mkdir rmdir rename unlink
full_audit:failure = all
full_audit:facility = local5
full_audit:priority = notice
# === CORBEILLE ===
recycle:repository = .recycle/%U
recycle:keeptree = yes
recycle:versions = yes
recycle:touch = yes
recycle:maxsize = 1073741824
recycle:exclude = *.tmp,*.temp,~$*
# === SNAPSHOTS (Shadow Copy) ===
shadow:snapdir = /srv/snapshots/enterprise
shadow:basedir = /srv/samba/enterprise
shadow:sort = desc
shadow:format = @GMT-%Y.%m.%d-%H.%M.%S
shadow:localtime = yes
# === FLUX ALTERNATIFS ===
streams_xattr:prefix = user.
streams_xattr:store_stream_type = yes
# === ACL ÉTENDUES ===
acl_xattr:ignore system acls = yes
acl_xattr:default acl style = windows
# === OPTIMISATIONS ===
strict allocate = yes
allocation roundup size = 1048576
# Installation des outils de quota
sudo apt install -y quota quotatool
# Modification de /etc/fstab pour activer les quotas
# /dev/sdb1 /srv/samba ext4 defaults,usrquota,grpquota 0 2
# Remontage avec quotas
sudo mount -o remount /srv/samba
# Création des fichiers de quota
sudo quotacheck -cug /srv/samba
sudo quotaon /srv/samba
# Configuration des quotas utilisateur (exemple: 10GB soft, 12GB hard)
sudo setquota -u john 10485760 12582912 0 0 /srv/samba
# Configuration des quotas groupe
sudo setquota -g enterprise-users 104857600 125829120 0 0 /srv/samba
# Script de monitoring des quotas
cat << 'EOF' > /usr/local/bin/quota-monitor.sh
#!/bin/bash
THRESHOLD=90
quota -u | awk -v threshold=$THRESHOLD '
NR>2 && $3 > 0 {
usage = ($2 / $3) * 100
if (usage > threshold) {
print "ALERTE: Utilisateur " $1 " utilise " usage "% de son quota"
}
}'
EOF
chmod +x /usr/local/bin/quota-monitor.sh
# Configuration DFS dans smb.conf
[global]
# Activation DFS
host msdfs = yes
[dfs-root]
comment = Racine DFS
path = /srv/dfs
msdfs root = yes
browseable = yes
read only = no
# Création de la structure DFS
sudo mkdir -p /srv/dfs
sudo mkdir -p /srv/dfs/shares
# Création des liens DFS
sudo ln -s "msdfs:server1.domain.local\\share1,server2.domain.local\\share1" /srv/dfs/shares/documents
sudo ln -s "msdfs:server1.domain.local\\share2" /srv/dfs/shares/projects
# Vérification DFS
smbclient -L localhost -U%
# ============================================================================
# OPTIMISATIONS NOYAU POUR SAMBA HAUTE PERFORMANCE
# ============================================================================
# === RÉSEAU ===
# Augmentation des buffers réseau
net.core.rmem_default = 262144
net.core.rmem_max = 16777216
net.core.wmem_default = 262144
net.core.wmem_max = 16777216
# Optimisations TCP
net.ipv4.tcp_rmem = 4096 65536 16777216
net.ipv4.tcp_wmem = 4096 65536 16777216
net.ipv4.tcp_congestion_control = bbr
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_timestamps = 1
net.ipv4.tcp_sack = 1
net.ipv4.tcp_fack = 1
net.ipv4.tcp_low_latency = 1
# Optimisations pour les connexions multiples
net.core.netdev_max_backlog = 5000
net.ipv4.tcp_max_syn_backlog = 8192
net.core.somaxconn = 1024
# === SYSTÈME DE FICHIERS ===
# Cache des dentries et inodes
vm.vfs_cache_pressure = 50
vm.dirty_background_ratio = 5
vm.dirty_ratio = 10
vm.dirty_expire_centisecs = 3000
vm.dirty_writeback_centisecs = 500
# === MÉMOIRE ===
# Optimisations mémoire pour serveur de fichiers
vm.swappiness = 10
vm.overcommit_memory = 1
vm.min_free_kbytes = 65536
# === SÉCURITÉ ===
# Protection contre les attaques réseau
net.ipv4.tcp_syncookies = 1
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
# Application immédiate
sudo sysctl -p /etc/sysctl.d/99-samba-performance.conf
# Vérification
sudo sysctl net.core.rmem_max
sudo sysctl vm.dirty_ratio
[global]
# === OPTIMISATIONS RÉSEAU AVANCÉES ===
socket options = TCP_NODELAY IPTOS_LOWDELAY SO_RCVBUF=524288 SO_SNDBUF=524288
# === THREADING ET PROCESSUS ===
max smbd processes = 1000
max connections = 0
deadtime = 15
keepalive = 30
# === CACHE OPTIMISÉ ===
getwd cache = yes
stat cache = yes
case sensitive = yes
preserve case = yes
short preserve case = yes
# === OPLOCKS AGRESSIFS ===
oplocks = yes
level2 oplocks = yes
kernel oplocks = no
oplock break wait time = 0
# === OPTIMISATIONS I/O ===
use sendfile = yes
aio read size = 65536
aio write size = 65536
aio write behind = yes
# === SYNCHRONISATION OPTIMISÉE ===
strict sync = no
sync always = no
strict allocate = yes
allocation roundup size = 1048576
# === CACHE DE NOMS ===
name cache timeout = 660
netbios cache timeout = 660
# === OPTIMISATIONS PROTOCOLE ===
large readwrite = yes
max xmit = 65535
read raw = yes
write raw = yes
# === GESTION MÉMOIRE ===
max open files = 65536
# === OPTIMISATIONS SPÉCIFIQUES ===
# Pour les gros fichiers
min receivefile size = 16384
# Pour les nombreux petits fichiers
mangled names = no
# Cache des attributs étendus
ea support = yes
store dos attributes = yes
#!/bin/bash
# /usr/local/bin/samba-performance-monitor.sh
LOG_FILE="/var/log/samba/performance.log"
DATE=$(date '+%Y-%m-%d %H:%M:%S')
# Fonction de logging
log_metric() {
echo "[$DATE] $1: $2" >> $LOG_FILE
}
# Connexions actives
CONNECTIONS=$(smbstatus -b | grep -c "^[0-9]")
log_metric "CONNECTIONS" $CONNECTIONS
# Utilisation CPU par smbd
CPU_USAGE=$(ps aux | grep smbd | grep -v grep | awk '{sum += $3} END {print sum}')
log_metric "CPU_USAGE" "${CPU_USAGE:-0}%"
# Utilisation mémoire
MEM_USAGE=$(ps aux | grep smbd | grep -v grep | awk '{sum += $4} END {print sum}')
log_metric "MEMORY_USAGE" "${MEM_USAGE:-0}%"
# Statistiques réseau
RX_BYTES=$(cat /proc/net/dev | grep eth0 | awk '{print $2}')
TX_BYTES=$(cat /proc/net/dev | grep eth0 | awk '{print $10}')
log_metric "RX_BYTES" $RX_BYTES
log_metric "TX_BYTES" $TX_BYTES
# Locks actifs
LOCKS=$(smbstatus -L | grep -c "^[0-9]")
log_metric "ACTIVE_LOCKS" $LOCKS
# Utilisation disque des partages
for share in /srv/samba/*; do
if [ -d "$share" ]; then
USAGE=$(df -h "$share" | tail -1 | awk '{print $5}' | sed 's/%//')
SHARE_NAME=$(basename "$share")
log_metric "DISK_USAGE_$SHARE_NAME" "${USAGE}%"
fi
done
# Alertes si nécessaire
if [ $CONNECTIONS -gt 500 ]; then
echo "ALERTE: Nombre de connexions élevé: $CONNECTIONS" | mail -s "Samba Alert" admin@domain.local
fi
if [ "${CPU_USAGE%.*}" -gt 80 ]; then
echo "ALERTE: Utilisation CPU élevée: $CPU_USAGE%" | mail -s "Samba Alert" admin@domain.local
fi
# Ajout au crontab
sudo crontab -e
# Monitoring toutes les 5 minutes
*/5 * * * * /usr/local/bin/samba-performance-monitor.sh
# Rapport quotidien
0 8 * * * /usr/local/bin/samba-daily-report.sh
# Nettoyage des logs anciens
0 2 * * 0 find /var/log/samba -name "*.log" -mtime +30 -delete
# Ajout du dépôt Elastic
wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add -
echo "deb https://artifacts.elastic.co/packages/8.x/apt stable main" | sudo tee /etc/apt/sources.list.d/elastic-8.x.list
# Installation
sudo apt update
sudo apt install -y elasticsearch logstash kibana filebeat
# Configuration Elasticsearch
sudo sed -i 's/#network.host: 192.168.0.1/network.host: localhost/' /etc/elasticsearch/elasticsearch.yml
sudo sed -i 's/#http.port: 9200/http.port: 9200/' /etc/elasticsearch/elasticsearch.yml
# Démarrage des services
sudo systemctl enable elasticsearch logstash kibana
sudo systemctl start elasticsearch
input {
file {
path => "/var/log/samba/log.*"
type => "samba"
start_position => "beginning"
}
file {
path => "/var/log/samba/audit.log"
type => "samba-audit"
start_position => "beginning"
}
}
filter {
if [type] == "samba" {
grok {
match => {
"message" => "\[%{TIMESTAMP_ISO8601:timestamp}\]%{SPACE}%{LOGLEVEL:level}%{SPACE}%{GREEDYDATA:message_content}"
}
}
date {
match => [ "timestamp", "yyyy/MM/dd HH:mm:ss" ]
}
}
if [type] == "samba-audit" {
grok {
match => {
"message" => "%{USER:user}\|%{IP:client_ip}\|%{WORD:machine}\|%{WORD:share}\|%{TIMESTAMP_ISO8601:timestamp}\|%{WORD:operation}\|%{GREEDYDATA:file_path}"
}
}
date {
match => [ "timestamp", "yyyy-MM-dd HH:mm:ss" ]
}
}
}
output {
elasticsearch {
hosts => ["localhost:9200"]
index => "samba-logs-%{+YYYY.MM.dd}"
}
stdout { codec => rubydebug }
}
# Installation Grafana
sudo apt-get install -y software-properties-common
sudo add-apt-repository "deb https://packages.grafana.com/oss/deb stable main"
wget -q -O - https://packages.grafana.com/gpg.key | sudo apt-key add -
sudo apt-get update
sudo apt-get install -y grafana
# Configuration
sudo systemctl enable grafana-server
sudo systemctl start grafana-server
# Accès: http://localhost:3000 (admin/admin)
#!/bin/bash
# /usr/local/bin/samba-alerting.sh
WEBHOOK_URL="https://hooks.slack.com/services/YOUR/SLACK/WEBHOOK"
EMAIL="admin@domain.local"
# Vérification des services
check_service() {
if ! systemctl is-active --quiet $1; then
MESSAGE="🚨 ALERTE: Service $1 est arrêté sur $(hostname)"
echo "$MESSAGE" | mail -s "Samba Alert" $EMAIL
curl -X POST -H 'Content-type: application/json' \
--data "{\"text\":\"$MESSAGE\"}" $WEBHOOK_URL
fi
}
# Vérification de l'espace disque
check_disk_space() {
THRESHOLD=90
df -h | grep -E '/srv/samba' | while read line; do
USAGE=$(echo $line | awk '{print $5}' | sed 's/%//')
MOUNT=$(echo $line | awk '{print $6}')
if [ $USAGE -gt $THRESHOLD ]; then
MESSAGE="🚨 ALERTE: Espace disque $MOUNT à ${USAGE}% sur $(hostname)"
echo "$MESSAGE" | mail -s "Samba Disk Alert" $EMAIL
curl -X POST -H 'Content-type: application/json' \
--data "{\"text\":\"$MESSAGE\"}" $WEBHOOK_URL
fi
done
}
# Vérification des connexions
check_connections() {
MAX_CONN=800
CURRENT_CONN=$(smbstatus -b | grep -c "^[0-9]")
if [ $CURRENT_CONN -gt $MAX_CONN ]; then
MESSAGE="🚨 ALERTE: $CURRENT_CONN connexions actives (max: $MAX_CONN) sur $(hostname)"
echo "$MESSAGE" | mail -s "Samba Connection Alert" $EMAIL
curl -X POST -H 'Content-type: application/json' \
--data "{\"text\":\"$MESSAGE\"}" $WEBHOOK_URL
fi
}
# Exécution des vérifications
check_service "smbd"
check_service "nmbd"
check_service "winbind"
check_disk_space
check_connections
CTDB permet de créer un cluster Samba haute disponibilité :
# Installation sur tous les nœuds
sudo apt install -y ctdb
# Configuration des nœuds
echo "192.168.1.10" | sudo tee /etc/ctdb/nodes
echo "192.168.1.11" | sudo tee -a /etc/ctdb/nodes
echo "192.168.1.12" | sudo tee -a /etc/ctdb/nodes
# Configuration des IPs publiques
echo "192.168.1.100/24 eth0" | sudo tee /etc/ctdb/public_addresses
echo "192.168.1.101/24 eth0" | sudo tee -a /etc/ctdb/public_addresses
echo "192.168.1.102/24 eth0" | sudo tee -a /etc/ctdb/public_addresses
[global]
# === CONFIGURATION CLUSTER ===
clustering = yes
ctdbd socket = /tmp/ctdb.socket
# === STOCKAGE PARTAGÉ ===
private dir = /shared/samba/private
lock directory = /shared/samba/lock
state directory = /shared/samba/state
cache directory = /shared/samba/cache
# === OPTIMISATIONS CLUSTER ===
kernel oplocks = no
posix locking = no
# === CONFIGURATION RÉSEAU ===
interfaces = eth0
bind interfaces only = yes
# Installation GlusterFS sur tous les nœuds
sudo apt install -y glusterfs-server
# Démarrage du service
sudo systemctl enable glusterd
sudo systemctl start glusterd
# Configuration du cluster (sur le nœud principal)
sudo gluster peer probe node2.domain.local
sudo gluster peer probe node3.domain.local
# Création du volume répliqué
sudo gluster volume create samba-vol replica 3 \
node1.domain.local:/data/gluster/samba \
node2.domain.local:/data/gluster/samba \
node3.domain.local:/data/gluster/samba
# Démarrage du volume
sudo gluster volume start samba-vol
# Montage sur tous les nœuds
echo "localhost:/samba-vol /shared/samba glusterfs defaults,_netdev 0 0" | sudo tee -a /etc/fstab
sudo mount -a
Cette configuration offre une disponibilité de 99.9% avec basculement automatique en cas de panne d'un nœud. Le temps de basculement est généralement inférieur à 30 secondes.
#!/bin/bash
# samba-auto-deploy.sh - Déploiement automatisé Samba Expert
set -euo pipefail
# Variables de configuration
DOMAIN="DOMAIN.LOCAL"
WORKGROUP="DOMAIN"
ADMIN_PASSWORD="ComplexPassword123!"
SERVER_IP="192.168.1.10"
DNS_FORWARDER="8.8.8.8"
# Couleurs pour l'affichage
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
log() {
echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')] $1${NC}"
}
warn() {
echo -e "${YELLOW}[$(date +'%Y-%m-%d %H:%M:%S')] WARNING: $1${NC}"
}
error() {
echo -e "${RED}[$(date +'%Y-%m-%d %H:%M:%S')] ERROR: $1${NC}"
exit 1
}
# Vérification des prérequis
check_prerequisites() {
log "Vérification des prérequis..."
# Vérification root
if [[ $EUID -ne 0 ]]; then
error "Ce script doit être exécuté en tant que root"
fi
# Vérification de la connectivité
if ! ping -c 1 8.8.8.8 &> /dev/null; then
error "Pas de connectivité Internet"
fi
# Vérification de l'espace disque
AVAILABLE_SPACE=$(df / | tail -1 | awk '{print $4}')
if [[ $AVAILABLE_SPACE -lt 5000000 ]]; then
error "Espace disque insuffisant (minimum 5GB requis)"
fi
log "Prérequis validés ✓"
}
# Installation des paquets
install_packages() {
log "Installation des paquets Samba..."
apt update
apt install -y samba samba-common-bin smbclient winbind \
libnss-winbind libpam-winbind krb5-config krb5-user \
samba-dsdb-modules samba-vfs-modules python3-samba \
acl attr quota quotatool chrony ufw fail2ban
log "Paquets installés ✓"
}
# Configuration du système
configure_system() {
log "Configuration du système..."
# Configuration hostname
hostnamectl set-hostname "dc1.${DOMAIN,,}"
echo "127.0.1.1 dc1.${DOMAIN,,} dc1" >> /etc/hosts
# Configuration réseau
echo "nameserver 127.0.0.1" > /etc/resolv.conf
echo "search ${DOMAIN,,}" >> /etc/resolv.conf
# Synchronisation temporelle
systemctl enable chrony
systemctl start chrony
# Configuration du pare-feu
ufw --force enable
ufw allow from 192.168.0.0/16 to any port 53
ufw allow from 192.168.0.0/16 to any port 88
ufw allow from 192.168.0.0/16 to any port 135
ufw allow from 192.168.0.0/16 to any port 139
ufw allow from 192.168.0.0/16 to any port 389
ufw allow from 192.168.0.0/16 to any port 445
ufw allow from 192.168.0.0/16 to any port 464
ufw allow from 192.168.0.0/16 to any port 636
ufw allow ssh
log "Système configuré ✓"
}
# Provisioning du domaine
provision_domain() {
log "Provisioning du domaine Active Directory..."
# Arrêt des services
systemctl stop smbd nmbd winbind 2>/dev/null || true
systemctl disable smbd nmbd winbind 2>/dev/null || true
# Sauvegarde de la configuration existante
if [[ -f /etc/samba/smb.conf ]]; then
cp /etc/samba/smb.conf /etc/samba/smb.conf.backup.$(date +%Y%m%d)
fi
# Provisioning
samba-tool domain provision \
--realm="$DOMAIN" \
--domain="$WORKGROUP" \
--adminpass="$ADMIN_PASSWORD" \
--server-role=dc \
--dns-backend=SAMBA_INTERNAL \
--host-name=DC1 \
--host-ip="$SERVER_IP"
# Configuration des services
systemctl enable samba-ad-dc
systemctl start samba-ad-dc
log "Domaine provisionné ✓"
}
# Configuration avancée
configure_advanced() {
log "Configuration avancée..."
# Optimisations système
cat > /etc/sysctl.d/99-samba-performance.conf << EOF
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.ipv4.tcp_rmem = 4096 65536 16777216
net.ipv4.tcp_wmem = 4096 65536 16777216
vm.dirty_ratio = 10
vm.dirty_background_ratio = 5
vm.swappiness = 10
EOF
sysctl -p /etc/sysctl.d/99-samba-performance.conf
# Configuration des logs
mkdir -p /var/log/samba
# Script de monitoring
cat > /usr/local/bin/samba-health-check.sh << 'EOF'
#!/bin/bash
# Health check automatique
if ! systemctl is-active --quiet samba-ad-dc; then
echo "CRITICAL: Samba AD DC service is down" | mail -s "Samba Alert" admin@domain.local
systemctl restart samba-ad-dc
fi
# Vérification DNS
if ! nslookup domain.local localhost > /dev/null 2>&1; then
echo "WARNING: DNS resolution issue detected" | mail -s "Samba DNS Alert" admin@domain.local
fi
EOF
chmod +x /usr/local/bin/samba-health-check.sh
# Crontab pour le monitoring
echo "*/5 * * * * /usr/local/bin/samba-health-check.sh" | crontab -
log "Configuration avancée terminée ✓"
}
# Tests de validation
run_tests() {
log "Exécution des tests de validation..."
# Test du service
if ! systemctl is-active --quiet samba-ad-dc; then
error "Le service samba-ad-dc n'est pas actif"
fi
# Test DNS
if ! nslookup "$DOMAIN" localhost > /dev/null 2>&1; then
warn "Problème de résolution DNS détecté"
fi
# Test de la base de données
if ! samba-tool domain level show > /dev/null 2>&1; then
error "Problème avec la base de données du domaine"
fi
log "Tests de validation réussis ✓"
}
# Affichage des informations finales
show_summary() {
log "=== DÉPLOIEMENT TERMINÉ ==="
echo
echo "Domaine: $DOMAIN"
echo "Contrôleur: dc1.${DOMAIN,,}"
echo "IP: $SERVER_IP"
echo "Administrateur: Administrator"
echo "Mot de passe: $ADMIN_PASSWORD"
echo
echo "Services actifs:"
systemctl status samba-ad-dc --no-pager -l
echo
echo "Pour rejoindre le domaine depuis un client:"
echo "realm join $DOMAIN -U Administrator"
echo
log "Déploiement Samba Expert terminé avec succès! 🎉"
}
# Fonction principale
main() {
log "Début du déploiement Samba Expert"
check_prerequisites
install_packages
configure_system
provision_domain
configure_advanced
run_tests
show_summary
}
# Gestion des signaux
trap 'error "Script interrompu par l'\''utilisateur"' INT TERM
# Exécution
main "$@"
#!/bin/bash
# samba-backup.sh - Sauvegarde complète Samba
BACKUP_DIR="/backup/samba"
DATE=$(date +%Y%m%d_%H%M%S)
RETENTION_DAYS=30
# Création du répertoire de sauvegarde
mkdir -p "$BACKUP_DIR/$DATE"
# Sauvegarde de la configuration
tar -czf "$BACKUP_DIR/$DATE/config.tar.gz" /etc/samba/
# Sauvegarde des données utilisateurs
rsync -av --delete /srv/samba/ "$BACKUP_DIR/$DATE/data/"
# Sauvegarde de la base de données AD (si contrôleur de domaine)
if systemctl is-active --quiet samba-ad-dc; then
samba-tool domain backup offline --targetdir="$BACKUP_DIR/$DATE/"
fi
# Nettoyage des anciennes sauvegardes
find "$BACKUP_DIR" -type d -mtime +$RETENTION_DAYS -exec rm -rf {} \;
# Notification
echo "Sauvegarde Samba terminée: $BACKUP_DIR/$DATE" | mail -s "Samba Backup" admin@domain.local
#!/bin/bash
# samba-diagnostic.sh - Diagnostic complet Samba
echo "=== DIAGNOSTIC SAMBA EXPERT ==="
echo "Date: $(date)"
echo "Hostname: $(hostname)"
echo
# Vérification des services
echo "=== STATUT DES SERVICES ==="
for service in smbd nmbd winbind samba-ad-dc; do
if systemctl list-unit-files | grep -q "$service"; then
status=$(systemctl is-active "$service" 2>/dev/null || echo "inactive")
echo "$service: $status"
fi
done
echo
# Vérification de la configuration
echo "=== VÉRIFICATION CONFIGURATION ==="
testparm -s 2>/dev/null | head -20
echo
# Vérification réseau
echo "=== CONNECTIVITÉ RÉSEAU ==="
echo "Interfaces actives:"
ip addr show | grep -E "inet.*scope global"
echo
echo "Ports en écoute:"
netstat -tlnp | grep -E "(139|445|53|88|389|636)"
echo
# Vérification DNS
echo "=== RÉSOLUTION DNS ==="
nslookup $(hostname) 2>/dev/null || echo "Erreur résolution hostname"
echo
# Vérification Active Directory
echo "=== ACTIVE DIRECTORY ==="
if systemctl is-active --quiet samba-ad-dc; then
echo "Mode: Contrôleur de domaine"
samba-tool domain level show 2>/dev/null || echo "Erreur niveau domaine"
elif systemctl is-active --quiet winbind; then
echo "Mode: Membre de domaine"
wbinfo -t 2>/dev/null || echo "Erreur trust domaine"
wbinfo -u | head -5 2>/dev/null || echo "Erreur énumération utilisateurs"
fi
echo
# Vérification des partages
echo "=== PARTAGES ACTIFS ==="
smbclient -L localhost -N 2>/dev/null | grep -E "Disk|IPC"
echo
# Vérification des connexions
echo "=== CONNEXIONS ACTIVES ==="
smbstatus -b 2>/dev/null | head -10
echo
# Vérification des logs
echo "=== DERNIÈRES ERREURS ==="
tail -20 /var/log/samba/log.smbd 2>/dev/null | grep -i error || echo "Aucune erreur récente"
echo
# Vérification des performances
echo "=== PERFORMANCES ==="
echo "Charge système: $(uptime | awk -F'load average:' '{print $2}')"
echo "Mémoire libre: $(free -h | grep Mem | awk '{print $7}')"
echo "Espace disque:"
df -h | grep -E "(samba|srv)"
echo
echo "=== FIN DU DIAGNOSTIC ==="
Symptômes : Lenteur d'accès aux fichiers, timeouts
Solutions :
testparm | grep oplocksamba-tool domain level showDiagnostic :
# Test authentification locale
smbclient -L localhost -U username
# Test Kerberos
kinit username@DOMAIN.LOCAL
klist
# Vérification winbind
wbinfo -t
wbinfo -a username%password
# Debug logs
tail -f /var/log/samba/log.winbind
Cette configuration Samba Expert est prête pour un environnement de production avec plus de 1000 utilisateurs, haute disponibilité 99.9%, et sécurité renforcée.