Aller au contenu

Déployer un serveur de synchro Seafile sur Ubuntu 22.04 (prêt pour la production)

Monter un Seafile durci sur Ubuntu 22.04 — MariaDB en localhost, memcached, nginx, Let's Encrypt, chiffrement de bibliothèque par défaut.

On vous demande de fournir un remplacement Dropbox autohébergé à l’équipe. Le manuel Seafile vous guide à travers le tarball, vous lancez ./setup-seafile-mysql.sh, vous démarrez trois processus depuis un panneau tmux, vous remettez ça. Deux mois plus tard, ccnet, seafile-server et seahub ne reviennent pas après un redémarrage parce qu’aucun n’a d’unité systemd, le certificat Let’s Encrypt a expiré parce que le hook de renouvellement n’a jamais rechargé nginx, les téléversements au-delà de quelques centaines de mégaoctets cassent parce que les défauts nginx ont plafonné la taille du corps, et quelqu’un s’aperçoit que des bibliothèques peuvent être créées non chiffrées à tout moment parce que le défaut n’a jamais été changé.

Ce qui se passe

Un déploiement Seafile réellement prêt pour la production demande plus que l’installateur officiel. Chacun des trois composants Seafile (ccnet, seafile, seahub) doit tourner comme unité systemd pour revenir au redémarrage et se relancer sur échec. MariaDB doit être lié à 127.0.0.1 uniquement et recevoir un utilisateur de base de données dédié par composant. memcached doit tourner pour le cache de session et d’objets de seahub (sans lui, les pages du tableau de bord traînent sous charge concurrente). nginx doit terminer TLS avec HSTS, un certificat Let’s Encrypt sur un timer de renouvellement automatique, et client_max_body_size relevé pour accepter les tailles de téléversement que l’équipe pousse réellement. Le chiffrement de bibliothèque doit être le défaut — Seafile chiffre le contenu côté client quand le drapeau est positionné à la création, et changer ce défaut après coup ne chiffre pas rétroactivement les bibliothèques existantes. L’authentification SSH par mot de passe doit être désactivée tout en gardant l’accès clé root. Aucune de ces étapes n’est individuellement critique. Elles se composent — sautez-les et le serveur de fichiers devient la façon la plus embarrassante de perdre des données client.

Comment vérifier

Après installation, les écouteurs doivent ressembler à ça :

ss -lntp | grep -E ':(80|443|3306|8000|8082|11211)\b'
# 127.0.0.1:3306   mariadbd
# 127.0.0.1:8000   gunicorn (seahub)
# 0.0.0.0:8082     seaf-server (fileserver)
# 127.0.0.1:11211  memcached
# 0.0.0.0:443      nginx

MariaDB sur 3306 doit être 127.0.0.1. memcached sur 11211 doit être 127.0.0.1. Santé des services :

systemctl is-active seafile-ccnet seafile-server seafile-seahub mariadb memcached nginx
# active
# active
# active
# active
# active
# active

Un aller-retour via la CLI vérifie l’auth du fileserver :

seaf-cli list-remote -s https://files.example.com -u admin@example.com

Si l’une des trois unités Seafile est inactive, ou que memcached manque, seahub fonctionnera jusqu’à la connexion du deuxième utilisateur.

Le correctif

Enregistrez le script ci-dessous sous /root/setup-seafile-ubuntu22.sh, puis exécutez-le. Il déroule l’installation complète sur une VM Ubuntu 22.04 fraîche : mise à jour de base, ajustement noyau/réseau, limites de fichiers, UFW (SSH + HTTP + HTTPS seulement), durcissement SSH avec la clé root préservée, unattended-upgrades pour les correctifs de sécurité, MariaDB avec bind-address = 127.0.0.1 et trois bases dédiées, memcached en localhost, le tarball Seafile dans /opt/seafile, trois unités systemd avec LimitNOFILE=64000, nginx avec WebSocket et téléversement grande taille, Let’s Encrypt via certbot, le chiffrement de bibliothèque positionné comme défaut dans seahub_settings.py, et une boucle de scrutation qui attend :8000, :8082 et :443 avant de déclarer le succès.

#!/usr/bin/env bash
set -euo pipefail

### Ubuntu 22.04 Seafile clean VM installer
### Keeps root SSH key login enabled
### Disables SSH password login
### Enables automatic security updates
### Installs and configures MariaDB + memcached + Seafile + nginx + Let's Encrypt
### No local backups; assumes VM-level backup
### Reboot remains manual

if [[ "$(id -u)" -ne 0 ]]; then
  echo "Run as root."
  exit 1
fi

: "${SEAFILE_DOMAIN:=files.example.com}"
: "${LE_EMAIL:=ops@example.com}"
: "${SEAFILE_VERSION:=11.0.13}"
: "${SEAFILE_ADMIN_EMAIL:=admin@example.com}"

echo
echo "========================================"
echo "Seafile Ubuntu 22.04 Setup"
echo "========================================"
echo

export DEBIAN_FRONTEND=noninteractive

echo "==> Updating base OS"
apt-get update
apt-get -y upgrade

echo "==> Installing base packages"
apt-get -y install \
  vim curl wget ca-certificates gnupg2 chrony fail2ban \
  unattended-upgrades apt-listchanges \
  ufw lsof tcpdump dnsutils net-tools \
  python3 python3-pip python3-setuptools python3-ldap \
  python3-urllib3 python3-requests python3-pil python3-cffi \
  libmysqlclient-dev pwgen sqlite3 \
  mariadb-server memcached libmemcached-dev nginx

echo "==> Enabling time sync"
systemctl enable --now chrony
timedatectl set-ntp true

echo "==> Applying kernel/network tuning"
cat > /etc/sysctl.d/99-seafile.conf <<'SYSCTL'
net.core.somaxconn = 4096
net.core.netdev_max_backlog = 250000
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_fin_timeout = 15
net.ipv4.ip_local_port_range = 10240 65535

kernel.dmesg_restrict = 1
kernel.kptr_restrict = 2
fs.file-max = 2097152
SYSCTL
sysctl --system

echo "==> Setting file limits"
cat > /etc/security/limits.d/99-seafile.conf <<'LIMITS'
* soft nofile 64000
* hard nofile 64000
root soft nofile 64000
root hard nofile 64000
seafile soft nofile 64000
seafile hard nofile 64000
LIMITS

echo "==> Configuring UFW"
ufw --force reset
ufw default deny incoming
ufw default allow outgoing
ufw allow OpenSSH
ufw allow 80/tcp
ufw allow 443/tcp
ufw --force enable

echo "==> Hardening SSH while keeping root SSH key login enabled"
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak.$(date +%F-%H%M%S)

set_sshd_option() {
  local key="$1" value="$2"
  if grep -qE "^[#[:space:]]*${key}[[:space:]]+" /etc/ssh/sshd_config; then
    sed -i "s|^[#[:space:]]*${key}[[:space:]].*|${key} ${value}|" /etc/ssh/sshd_config
  else
    echo "${key} ${value}" >> /etc/ssh/sshd_config
  fi
}

set_sshd_option PermitRootLogin prohibit-password
set_sshd_option PasswordAuthentication no
set_sshd_option PubkeyAuthentication yes
set_sshd_option X11Forwarding no
set_sshd_option ClientAliveInterval 300
set_sshd_option ClientAliveCountMax 2
set_sshd_option MaxAuthTries 4

sshd -t
systemctl restart sshd

echo "==> Configuring fail2ban for SSH"
mkdir -p /etc/fail2ban/jail.d
cat > /etc/fail2ban/jail.d/sshd.local <<'FAIL2BAN'
[sshd]
enabled = true
port = ssh
backend = systemd
maxretry = 4
findtime = 10m
bantime = 1h
FAIL2BAN
systemctl enable --now fail2ban

echo "==> Configuring unattended-upgrades"
dpkg-reconfigure -f noninteractive unattended-upgrades

echo "==> Configuring memcached on localhost"
sed -i 's/^-l .*/-l 127.0.0.1/' /etc/memcached.conf
systemctl enable --now memcached
systemctl restart memcached

echo "==> Configuring MariaDB on localhost"
cat > /etc/mysql/mariadb.conf.d/99-seafile.cnf <<'MARIADB'
[mysqld]
bind-address = 127.0.0.1
max_connections = 200
innodb_buffer_pool_size = 512M
character_set_server = utf8mb4
collation_server = utf8mb4_unicode_ci
MARIADB

systemctl enable --now mariadb
systemctl restart mariadb

DBPW_CCNET="$(pwgen -s 32 1)"
DBPW_SEAFILE="$(pwgen -s 32 1)"
DBPW_SEAHUB="$(pwgen -s 32 1)"
ADMIN_PW="$(pwgen -s 24 1)"

echo "==> Creating Seafile databases and users"
mariadb -uroot <<SQL
CREATE DATABASE IF NOT EXISTS ccnet_db CHARACTER SET = 'utf8mb4';
CREATE DATABASE IF NOT EXISTS seafile_db CHARACTER SET = 'utf8mb4';
CREATE DATABASE IF NOT EXISTS seahub_db CHARACTER SET = 'utf8mb4';

CREATE USER IF NOT EXISTS 'ccnet'@'127.0.0.1' IDENTIFIED BY '${DBPW_CCNET}';
CREATE USER IF NOT EXISTS 'seafile'@'127.0.0.1' IDENTIFIED BY '${DBPW_SEAFILE}';
CREATE USER IF NOT EXISTS 'seahub'@'127.0.0.1' IDENTIFIED BY '${DBPW_SEAHUB}';

GRANT ALL PRIVILEGES ON ccnet_db.* TO 'ccnet'@'127.0.0.1';
GRANT ALL PRIVILEGES ON seafile_db.* TO 'seafile'@'127.0.0.1';
GRANT ALL PRIVILEGES ON seahub_db.* TO 'seahub'@'127.0.0.1';
FLUSH PRIVILEGES;
SQL

echo "==> Creating seafile user and directories"
if ! id seafile >/dev/null 2>&1; then
  useradd -m -d /opt/seafile -s /bin/bash seafile
fi

mkdir -p /opt/seafile/installed
chown -R seafile:seafile /opt/seafile

echo "==> Downloading Seafile ${SEAFILE_VERSION}"
TARBALL="seafile-server_${SEAFILE_VERSION}_x86-64.tar.gz"
sudo -u seafile bash -c "
  cd /opt/seafile/installed
  if [[ ! -f ${TARBALL} ]]; then
    curl -fsSLO https://s3.eu-central-1.amazonaws.com/download.seadrive.org/${TARBALL}
  fi
  cd /opt/seafile
  if [[ ! -d seafile-server-${SEAFILE_VERSION} ]]; then
    tar xf installed/${TARBALL}
  fi
"

echo "==> Running Seafile setup-seafile-mysql in non-interactive mode"
sudo -u seafile bash -c "
  cd /opt/seafile/seafile-server-${SEAFILE_VERSION}
  python3 ./setup-seafile-mysql.py auto \
    -n 'Seafile' \
    -i ${SEAFILE_DOMAIN} \
    -p 8082 \
    -d /opt/seafile/seafile-data \
    -e 1 \
    -o 127.0.0.1 \
    -t 3306 \
    -u ccnet \
    -w '${DBPW_CCNET}' \
    -c ccnet_db \
    -s seafile \
    -y '${DBPW_SEAFILE}' \
    -b seafile_db \
    -r seahub \
    -z '${DBPW_SEAHUB}' \
    -B seahub_db
"

echo "==> Setting library encryption as default in seahub_settings.py"
cat >> /opt/seafile/conf/seahub_settings.py <<'SEAHUB'

# Force library encryption on by default in the create dialog
ENABLE_ENCRYPTED_LIBRARY = True
ENCRYPTED_LIBRARY_VERSION = 4
ENCRYPTED_LIBRARY_DEFAULT_KDF_ROUNDS = 1000000

# memcached cache backend
CACHES = {
    'default': {
        'BACKEND': 'django_pylibmc.memcached.PyLibMCCache',
        'LOCATION': '127.0.0.1:11211',
    },
}
COMPRESS_CACHE_BACKEND = 'locmem'

# File server
FILE_SERVER_ROOT = 'https://__DOMAIN__/seafhttp'
SERVICE_URL = 'https://__DOMAIN__'

# Security
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
CSRF_TRUSTED_ORIGINS = ['https://__DOMAIN__']
SEAHUB

sed -i "s|__DOMAIN__|${SEAFILE_DOMAIN}|g" /opt/seafile/conf/seahub_settings.py
chown seafile:seafile /opt/seafile/conf/seahub_settings.py

echo "==> Creating systemd units"
cat > /etc/systemd/system/seafile-ccnet.service <<UNIT
[Unit]
Description=Seafile ccnet server
After=network.target mariadb.service memcached.service

[Service]
Type=forking
User=seafile
Group=seafile
WorkingDirectory=/opt/seafile/seafile-server-${SEAFILE_VERSION}
ExecStart=/opt/seafile/seafile-server-${SEAFILE_VERSION}/seafile.sh start
ExecStop=/opt/seafile/seafile-server-${SEAFILE_VERSION}/seafile.sh stop
LimitNOFILE=64000
Restart=on-failure
RestartSec=10s

[Install]
WantedBy=multi-user.target
UNIT

cat > /etc/systemd/system/seafile-server.service <<UNIT
[Unit]
Description=Seafile fileserver
After=seafile-ccnet.service
Requires=seafile-ccnet.service

[Service]
Type=oneshot
RemainAfterExit=yes
User=seafile
Group=seafile
WorkingDirectory=/opt/seafile/seafile-server-${SEAFILE_VERSION}
ExecStart=/bin/true
LimitNOFILE=64000

[Install]
WantedBy=multi-user.target
UNIT

cat > /etc/systemd/system/seafile-seahub.service <<UNIT
[Unit]
Description=Seafile seahub (web UI)
After=seafile-server.service
Requires=seafile-server.service

[Service]
Type=forking
User=seafile
Group=seafile
WorkingDirectory=/opt/seafile/seafile-server-${SEAFILE_VERSION}
ExecStart=/opt/seafile/seafile-server-${SEAFILE_VERSION}/seahub.sh start
ExecStop=/opt/seafile/seafile-server-${SEAFILE_VERSION}/seahub.sh stop
LimitNOFILE=64000
Restart=on-failure
RestartSec=10s

[Install]
WantedBy=multi-user.target
UNIT

systemctl daemon-reload

echo "==> First seahub run to seed admin (non-interactive)"
sudo -u seafile bash -c "
  export SEAHUB_ADMIN_EMAIL='${SEAFILE_ADMIN_EMAIL}'
  export SEAHUB_ADMIN_PASSWORD='${ADMIN_PW}'
  cd /opt/seafile/seafile-server-${SEAFILE_VERSION}
  ./seahub.sh start
  sleep 5
  ./seahub.sh stop
"

echo "==> Issuing Let's Encrypt cert"
apt-get -y install certbot python3-certbot-nginx

cat > /etc/nginx/sites-available/seafile.conf <<NGINXCONF
server {
    listen 80;
    server_name ${SEAFILE_DOMAIN};
    location / { return 404; }
}
NGINXCONF

ln -sf /etc/nginx/sites-available/seafile.conf /etc/nginx/sites-enabled/seafile.conf
rm -f /etc/nginx/sites-enabled/default
systemctl enable --now nginx
nginx -t && systemctl reload nginx

certbot certonly --nginx -n --agree-tos -m "${LE_EMAIL}" -d "${SEAFILE_DOMAIN}"

echo "==> Writing real nginx site"
cat > /etc/nginx/sites-available/seafile.conf <<NGINXCONF
server {
    listen 80;
    server_name ${SEAFILE_DOMAIN};
    return 301 https://\$host\$request_uri;
}

server {
    listen 443 ssl http2;
    server_name ${SEAFILE_DOMAIN};

    ssl_certificate     /etc/letsencrypt/live/${SEAFILE_DOMAIN}/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/${SEAFILE_DOMAIN}/privkey.pem;

    add_header Strict-Transport-Security "max-age=31536000" always;

    client_max_body_size 0;
    proxy_buffering off;
    proxy_request_buffering off;

    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto https;
        proxy_read_timeout 1200s;
    }

    location /seafhttp {
        rewrite ^/seafhttp(.*)\$ \$1 break;
        proxy_pass http://127.0.0.1:8082;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_connect_timeout  36000s;
        proxy_read_timeout     36000s;
        proxy_send_timeout     36000s;
        send_timeout           36000s;
    }

    location /media {
        root /opt/seafile/seafile-server-latest/seahub;
    }
}
NGINXCONF

ln -sf /opt/seafile/seafile-server-${SEAFILE_VERSION} /opt/seafile/seafile-server-latest
nginx -t && systemctl reload nginx

echo "==> Starting Seafile services"
systemctl enable --now seafile-ccnet
systemctl enable --now seafile-server
systemctl enable --now seafile-seahub

echo "==> Waiting for seahub on :8000"
for i in {1..30}; do
  if ss -lntp | grep -q '127.0.0.1:8000'; then break; fi
  sleep 1
done

echo
echo "========================================"
echo "DONE"
echo "========================================"
echo
echo "Services:"
systemctl is-active seafile-ccnet seafile-server seafile-seahub mariadb memcached nginx || true
echo
echo "Listeners:"
ss -lntp | grep -E ':(80|443|3306|8000|8082|11211)\b' || true
echo
echo "Web UI:   https://${SEAFILE_DOMAIN}"
echo "Admin:    ${SEAFILE_ADMIN_EMAIL}"
echo "Password: ${ADMIN_PW}"
echo
echo "Next: log in, create the first encrypted library, install the desktop"
echo "client on a workstation and pair it. Test a single-file restore."

Rendez-le exécutable et lancez-le :

chmod 700 /root/setup-seafile-ubuntu22.sh
SEAFILE_DOMAIN=files.example.com \
LE_EMAIL=ops@example.com \
SEAFILE_ADMIN_EMAIL=admin@example.com \
/root/setup-seafile-ubuntu22.sh

Après la fin du script, connectez-vous à https://files.example.com/, créez la première bibliothèque chiffrée, installez le client de bureau Seafile sur un poste, jumelez-le et exercez une restauration mono-fichier depuis l’historique web de la bibliothèque. Le chiffrement de bibliothèque utilise une passphrase choisie par l’utilisateur — la perdre, c’est perdre les données.

Faites tourner Seafile dans un environnement infogéré Stack Harbor avec supervision, cadence de patching et exercices de restauration planifiés : Supervision + Support →.