-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup-server.sh
More file actions
executable file
·562 lines (468 loc) · 17 KB
/
setup-server.sh
File metadata and controls
executable file
·562 lines (468 loc) · 17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
#!/usr/bin/env bash
# =============================================================================
# PiSovereign — Linux Server Setup Script
# =============================================================================
#
# Fully automated installation and hardening of a Linux server for PiSovereign.
# Run once as root — everything else happens automatically afterwards.
#
# What this script does:
# 1. Installs Docker Engine + Docker Compose plugin
# 2. Installs security packages (UFW, fail2ban, fwupd)
# 3. Configures automatic OS + firmware updates at 22:00
# 4. Configures automatic Docker image updates at 22:00
# 5. Hardens SSH and kernel network parameters
# 6. Enables Docker to start on boot (containers auto-restart via compose policy)
#
# Usage:
# curl -fsSL https://raw.githubusercontent.com/twohreichel/PiSovereign/main/setup-server.sh | sudo bash
# # — or —
# chmod +x setup-server.sh && sudo ./setup-server.sh
#
# Supported distributions: Debian 12+, Ubuntu 22.04+, Raspberry Pi OS (Bookworm)
# =============================================================================
set -euo pipefail
# -- Constants ----------------------------------------------------------------
readonly SCRIPT_VERSION="1.0.0"
readonly LOG_FILE="/var/log/pisovereign-setup.log"
readonly PISOVEREIGN_DIR="/opt/pisovereign"
readonly COMPOSE_DIR="${PISOVEREIGN_DIR}/docker"
readonly UPDATE_HOUR="22"
readonly REPO_URL="https://github.com/twohreichel/PiSovereign.git"
# -- Colors -------------------------------------------------------------------
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# -- Helpers ------------------------------------------------------------------
log() { echo -e "${GREEN}[✓]${NC} $*" | tee -a "$LOG_FILE"; }
warn() { echo -e "${YELLOW}[⚠]${NC} $*" | tee -a "$LOG_FILE"; }
err() { echo -e "${RED}[✗]${NC} $*" | tee -a "$LOG_FILE" >&2; }
info() { echo -e "${BLUE}[i]${NC} $*" | tee -a "$LOG_FILE"; }
die() { err "$*"; exit 1; }
# -- Preflight checks --------------------------------------------------------
preflight() {
echo ""
echo "========================================"
echo " PiSovereign Server Setup v${SCRIPT_VERSION}"
echo "========================================"
echo ""
# Must be root
[[ $EUID -eq 0 ]] || die "This script must be run as root (use sudo)."
# Must be a supported Debian/Ubuntu derivative
if [[ ! -f /etc/os-release ]]; then
die "Unsupported OS — /etc/os-release not found."
fi
# shellcheck source=/dev/null
. /etc/os-release
case "${ID:-}" in
debian|ubuntu|raspbian) ;;
*) die "Unsupported distribution: ${ID:-unknown}. Supported: Debian, Ubuntu, Raspberry Pi OS." ;;
esac
log "OS detected: ${PRETTY_NAME:-${ID} ${VERSION_ID:-}}"
}
# -- 1. System update ---------------------------------------------------------
system_update() {
info "Updating system packages …"
apt-get update -qq
DEBIAN_FRONTEND=noninteractive apt-get upgrade -y -qq
log "System packages updated."
}
# -- 2. Install Docker --------------------------------------------------------
install_docker() {
if command -v docker &>/dev/null; then
log "Docker already installed: $(docker --version)"
else
info "Installing Docker Engine …"
# Prerequisites
apt-get install -y -qq \
ca-certificates \
curl \
gnupg \
lsb-release
# Docker GPG key
install -m 0755 -d /etc/apt/keyrings
curl -fsSL "https://download.docker.com/linux/${ID}/gpg" \
| gpg --dearmor -o /etc/apt/keyrings/docker.gpg
chmod a+r /etc/apt/keyrings/docker.gpg
# Repository
# shellcheck source=/dev/null
. /etc/os-release
local arch
arch="$(dpkg --print-architecture)"
local codename="${VERSION_CODENAME:-$(lsb_release -cs 2>/dev/null || echo bookworm)}"
# Raspberry Pi OS uses Debian repos
local repo_id="${ID}"
if [[ "${ID}" == "raspbian" ]]; then
repo_id="debian"
fi
echo \
"deb [arch=${arch} signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/${repo_id} ${codename} stable" \
> /etc/apt/sources.list.d/docker.list
apt-get update -qq
apt-get install -y -qq \
docker-ce \
docker-ce-cli \
containerd.io \
docker-buildx-plugin \
docker-compose-plugin
log "Docker installed: $(docker --version)"
fi
# Enable Docker on boot
systemctl enable --now docker
log "Docker enabled and started."
}
# -- 3. Security packages -----------------------------------------------------
install_security() {
info "Installing security packages …"
apt-get install -y -qq \
ufw \
fail2ban \
unattended-upgrades \
apt-listchanges \
fwupd \
needrestart \
libpam-tmpdir
log "Security packages installed."
}
# -- 4. Configure UFW firewall ------------------------------------------------
configure_firewall() {
info "Configuring UFW firewall …"
# Allow SSH (essential — never lock yourself out)
ufw allow OpenSSH
# Allow HTTP (Traefik reverse proxy)
ufw allow 80/tcp
# Enable firewall (non-interactive)
ufw --force enable
ufw reload
log "UFW firewall active — allowed: SSH (22), HTTP (80)."
}
# -- 5. Configure fail2ban ----------------------------------------------------
configure_fail2ban() {
info "Configuring fail2ban …"
cat > /etc/fail2ban/jail.local <<'JAIL'
# PiSovereign fail2ban configuration
[DEFAULT]
bantime = 2h
findtime = 10m
maxretry = 5
banaction = ufw
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = %(sshd_log)s
maxretry = 3
bantime = 4h
JAIL
systemctl enable --now fail2ban
systemctl restart fail2ban
log "fail2ban configured and active (default: 2h ban, SSH: 3 retries → 4h ban)."
}
# -- 6. Configure automatic OS updates at 22:00 -------------------------------
configure_auto_updates() {
info "Configuring automatic OS updates at ${UPDATE_HOUR}:00 …"
# Enable unattended-upgrades
cat > /etc/apt/apt.conf.d/20auto-upgrades <<APT
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
APT::Periodic::Download-Upgradeable-Packages "1";
APT::Periodic::AutocleanInterval "7";
APT
log "APT automatic updates enabled."
# Configure what to upgrade
cat > /etc/apt/apt.conf.d/50unattended-upgrades <<'UNATTENDED'
Unattended-Upgrade::Allowed-Origins {
"${distro_id}:${distro_codename}";
"${distro_id}:${distro_codename}-security";
"${distro_id}:${distro_codename}-updates";
"${distro_id}ESMApps:${distro_codename}-apps-security";
"${distro_id}ESM:${distro_codename}-infra-security";
};
// Remove unused kernel packages after update
Unattended-Upgrade::Remove-Unused-Kernel-Packages "true";
// Remove unused auto-installed dependencies
Unattended-Upgrade::Remove-Unused-Dependencies "true";
// Automatically reboot if required (e.g. kernel update)
Unattended-Upgrade::Automatic-Reboot "true";
// Reboot at 03:00 (after dream mode finishes around 02:00)
Unattended-Upgrade::Automatic-Reboot-Time "03:00";
// Write upgrade log
Unattended-Upgrade::SyslogEnable "true";
UNATTENDED
log "Unattended upgrades configured (security + updates)."
# Schedule APT updates at 22:00 via systemd timer override
mkdir -p /etc/systemd/system/apt-daily.timer.d
cat > /etc/systemd/system/apt-daily.timer.d/override.conf <<TIMER
[Timer]
OnCalendar=
OnCalendar=*-*-* ${UPDATE_HOUR}:00
RandomizedDelaySec=0
TIMER
mkdir -p /etc/systemd/system/apt-daily-upgrade.timer.d
cat > /etc/systemd/system/apt-daily-upgrade.timer.d/override.conf <<TIMER
[Timer]
OnCalendar=
OnCalendar=*-*-* ${UPDATE_HOUR}:15
RandomizedDelaySec=0
TIMER
systemctl daemon-reload
systemctl enable --now apt-daily.timer apt-daily-upgrade.timer
log "OS updates scheduled at ${UPDATE_HOUR}:00, upgrades at ${UPDATE_HOUR}:15."
}
# -- 7. Configure automatic firmware updates ----------------------------------
configure_firmware_updates() {
info "Configuring automatic firmware updates …"
# Enable fwupd systemd timer for automatic firmware checks
systemctl enable fwupd-refresh.timer 2>/dev/null || true
systemctl start fwupd-refresh.timer 2>/dev/null || true
log "Firmware auto-update enabled (fwupd)."
}
# -- 8. Docker image auto-update + restart at 22:00 ---------------------------
configure_docker_auto_update() {
info "Configuring automatic Docker image updates at ${UPDATE_HOUR}:00 …"
# Create the update script
cat > /usr/local/bin/pisovereign-update <<'UPDATESCRIPT'
#!/usr/bin/env bash
# =============================================================================
# PiSovereign Docker Auto-Update
# Pulls latest images and restarts changed containers.
# Called by systemd timer at 22:00 daily.
# =============================================================================
set -euo pipefail
COMPOSE_DIR="/opt/pisovereign/docker"
LOG="/var/log/pisovereign-update.log"
log() { echo "[$(date -Iseconds)] $*" >> "$LOG"; }
if [[ ! -d "$COMPOSE_DIR" ]]; then
log "ERROR: $COMPOSE_DIR not found — skipping update."
exit 0
fi
cd "$COMPOSE_DIR"
log "--- Docker image update started ---"
# Pull latest images for all services
if docker compose pull --quiet 2>>"$LOG"; then
log "Images pulled successfully."
else
log "WARNING: Some images failed to pull (offline or build-only)."
fi
# Recreate only containers whose images changed (zero-downtime for unchanged)
if docker compose up -d --remove-orphans 2>>"$LOG"; then
log "Containers updated successfully."
else
log "WARNING: Container update had issues."
fi
# Clean up dangling images to free disk space
docker image prune -f >>"$LOG" 2>&1 || true
log "--- Docker image update complete ---"
UPDATESCRIPT
chmod +x /usr/local/bin/pisovereign-update
# Systemd service
cat > /etc/systemd/system/pisovereign-update.service <<SERVICE
[Unit]
Description=PiSovereign Docker Image Auto-Update
Wants=docker.service
After=docker.service network-online.target
Requires=docker.service
[Service]
Type=oneshot
ExecStart=/usr/local/bin/pisovereign-update
TimeoutStartSec=600
SERVICE
# Systemd timer — daily at 22:00
cat > /etc/systemd/system/pisovereign-update.timer <<TIMER
[Unit]
Description=PiSovereign Docker Auto-Update Timer (daily at ${UPDATE_HOUR}:00)
[Timer]
OnCalendar=*-*-* ${UPDATE_HOUR}:00
Persistent=true
[Install]
WantedBy=timers.target
TIMER
systemctl daemon-reload
systemctl enable --now pisovereign-update.timer
log "Docker auto-update scheduled at ${UPDATE_HOUR}:00 daily."
}
# -- 9. Harden SSH ------------------------------------------------------------
harden_ssh() {
info "Hardening SSH configuration …"
local sshd_config="/etc/ssh/sshd_config"
local hardening_file="/etc/ssh/sshd_config.d/99-pisovereign-hardening.conf"
# Check if any user has authorized_keys before disabling password auth
local disable_passwords="yes"
local has_keys=false
for home_dir in /root /home/*; do
if [[ -s "${home_dir}/.ssh/authorized_keys" ]]; then
has_keys=true
break
fi
done
if [[ "$has_keys" != "true" ]]; then
disable_passwords="no"
warn "No SSH authorized_keys found — keeping password authentication enabled."
warn "Add your SSH public key and re-run, or manually set PasswordAuthentication no."
fi
# Use drop-in directory if supported, otherwise modify main config
if [[ -d /etc/ssh/sshd_config.d ]]; then
cat > "$hardening_file" <<SSH
# PiSovereign SSH Hardening
PermitRootLogin prohibit-password
PasswordAuthentication ${disable_passwords}
MaxAuthTries 3
X11Forwarding no
AllowAgentForwarding no
AllowTcpForwarding no
ClientAliveInterval 300
ClientAliveCountMax 2
SSH
log "SSH hardened via ${hardening_file}."
else
# Fallback: modify sshd_config directly
sed -i 's/^#\?PermitRootLogin .*/PermitRootLogin prohibit-password/' "$sshd_config"
sed -i 's/^#\?MaxAuthTries .*/MaxAuthTries 3/' "$sshd_config"
sed -i 's/^#\?X11Forwarding .*/X11Forwarding no/' "$sshd_config"
log "SSH hardened via ${sshd_config}."
fi
# Restart SSH only if running (avoid lockout on fresh installs)
if systemctl is-active --quiet sshd 2>/dev/null || systemctl is-active --quiet ssh 2>/dev/null; then
systemctl reload sshd 2>/dev/null || systemctl reload ssh 2>/dev/null || true
log "SSH service reloaded."
fi
}
# -- 10. Kernel hardening (sysctl) --------------------------------------------
harden_kernel() {
info "Applying kernel network hardening …"
cat > /etc/sysctl.d/99-pisovereign.conf <<'SYSCTL'
# PiSovereign kernel hardening
# Prevent IP spoofing
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
# Disable source routing
net.ipv4.conf.all.accept_source_route = 0
net.ipv6.conf.all.accept_source_route = 0
# Disable ICMP redirects
net.ipv4.conf.all.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0
# Enable SYN cookies (SYN flood protection)
net.ipv4.tcp_syncookies = 1
# Log suspicious packets
net.ipv4.conf.all.log_martians = 1
# Disable IPv6 router advertisements
net.ipv6.conf.all.accept_ra = 0
net.ipv6.conf.default.accept_ra = 0
# Restrict kernel pointer leaks (hides from all users including root;
# may affect kernel debugging tools — acceptable for production servers)
kernel.kptr_restrict = 2
# Restrict dmesg access
kernel.dmesg_restrict = 1
SYSCTL
sysctl --system --quiet 2>/dev/null || sysctl -p /etc/sysctl.d/99-pisovereign.conf
log "Kernel network hardening applied."
}
# -- 11. Clone PiSovereign ----------------------------------------------------
setup_pisovereign() {
info "Setting up PiSovereign in ${PISOVEREIGN_DIR} …"
# Install git if missing
if ! command -v git &>/dev/null; then
apt-get install -y -qq git
fi
if [[ -d "${PISOVEREIGN_DIR}/.git" ]]; then
log "PiSovereign already cloned — pulling latest changes."
# Stash local changes, pull, then re-apply
git -C "$PISOVEREIGN_DIR" stash --quiet 2>/dev/null || true
git -C "$PISOVEREIGN_DIR" pull --ff-only || warn "git pull failed — using existing version."
git -C "$PISOVEREIGN_DIR" stash pop --quiet 2>/dev/null || true
else
git clone "$REPO_URL" "$PISOVEREIGN_DIR"
log "PiSovereign cloned to ${PISOVEREIGN_DIR}."
fi
# Create .env from example if not present
if [[ ! -f "${COMPOSE_DIR}/.env" ]]; then
cp "${COMPOSE_DIR}/.env.example" "${COMPOSE_DIR}/.env"
warn ".env created from example — edit ${COMPOSE_DIR}/.env with your settings before starting."
fi
}
# -- 12. Log rotation ---------------------------------------------------------
configure_log_rotation() {
info "Configuring log rotation …"
cat > /etc/logrotate.d/pisovereign <<'LOGROTATE'
/var/log/pisovereign-*.log {
weekly
rotate 4
compress
delaycompress
missingok
notifempty
create 0640 root root
}
LOGROTATE
log "Log rotation configured for PiSovereign logs."
}
# -- 13. Ensure Docker auto-start on boot ------------------------------------
configure_docker_autostart() {
info "Ensuring Docker containers start on boot …"
# All compose services use 'restart: unless-stopped' so Docker handles this.
# We just need Docker itself to start on boot.
systemctl enable docker
systemctl enable containerd
log "Docker auto-start on boot confirmed."
info "All PiSovereign containers use 'restart: unless-stopped' — they will"
info "automatically restart after a reboot once Docker starts."
}
# -- Summary ------------------------------------------------------------------
summary() {
echo ""
echo "========================================"
echo " Setup Complete!"
echo "========================================"
echo ""
log "PiSovereign server setup finished successfully."
echo ""
echo " Installed:"
echo " • Docker Engine + Compose plugin"
echo " • UFW firewall (ports 22, 80)"
echo " • fail2ban (SSH brute-force protection, 4h ban)"
echo " • unattended-upgrades (OS security updates)"
echo " • fwupd (firmware updates)"
echo " • needrestart (service restart detection)"
echo ""
echo " Scheduled (daily at ${UPDATE_HOUR}:00):"
echo " • OS package updates + security patches"
echo " • Docker image pulls + container restart"
echo " • Firmware update checks"
echo " • Auto-reboot at 03:00 if kernel updated"
echo ""
echo " Security hardening:"
echo " • SSH: root login by key only, max 3 auth tries"
echo " • Kernel: SYN cookies, anti-spoofing, restricted dmesg"
echo " • Docker: auto-start on boot, all containers restart automatically"
echo ""
echo -e " ${YELLOW}Next steps:${NC}"
echo " 1. Edit ${COMPOSE_DIR}/.env with your configuration"
echo " 2. cd ${COMPOSE_DIR} && docker compose up -d"
echo " 3. Initialize Vault: docker compose exec vault /vault/init.sh"
echo ""
echo " Logs: ${LOG_FILE}"
echo " Update log: /var/log/pisovereign-update.log"
echo ""
}
# -- Main ---------------------------------------------------------------------
main() {
preflight
system_update
install_docker
install_security
configure_firewall
configure_fail2ban
configure_auto_updates
configure_firmware_updates
configure_docker_auto_update
harden_ssh
harden_kernel
setup_pisovereign
configure_log_rotation
configure_docker_autostart
summary
}
main "$@"