Restructure the repository per session

session1/ now holds the whole live lab (content, platforms, docs, answer key,
README); session2/ keeps the design for the second workshop. The root README
indexes both and states that session2 modifies session1 rather than
duplicating it.

build-bundle.sh builds from session1 and still produces a flat archive, so
the documented paths inside a deployment (platforms/<p>/lab.sh) are
unchanged. .gitignore follows the move.
This commit is contained in:
2026-10-24 14:22:39 -04:00
parent 62d3c4282c
commit dcb64ac65e
359 changed files with 219 additions and 175 deletions
+213
View File
@@ -0,0 +1,213 @@
# shellcheck shell=bash
# cmd_check — preflight for the selected backend.
# Fatal problems set CHECK_FAILS, advisory ones set CHECK_WARNS.
# `--strict` turns warnings into a non-zero exit.
CHECK_FAILS=0
CHECK_WARNS=0
_c_ok() { ok "$*"; }
_c_warn() { warn "$*"; CHECK_WARNS=$(( CHECK_WARNS + 1 )); }
_c_fail() { fail "$*"; CHECK_FAILS=$(( CHECK_FAILS + 1 )); }
cmd_check() {
local arg
for arg in "$@"; do
[[ $arg == --strict ]] && STRICT=1
done
CHECK_FAILS=0
CHECK_WARNS=0
local os_pretty="unknown release"
if [[ -r /etc/os-release ]]; then
# shellcheck disable=SC1091
os_pretty=$(. /etc/os-release; printf '%s' "${PRETTY_NAME:-unknown release}")
fi
step "host"
info " ${os_pretty} · $(nproc) threads · kernel $(uname -r) · ${PLATFORM:-qemu} platform"
_check_commands
[[ ${PLATFORM:-qemu} == qemu ]] && _check_kvm
_check_ram
step "storage"
_check_storage
step "network"
_check_network
step "config"
_check_config
_check_backend
printf '\n'
if (( CHECK_FAILS > 0 )); then
fail "${CHECK_FAILS} blocking issue(s), ${CHECK_WARNS} warning(s)"
return 1
fi
if (( CHECK_WARNS > 0 && STRICT )); then
warn "${CHECK_WARNS} warning(s) with --strict"
return 1
fi
ok "preflight passed · ${CHECK_WARNS} warning(s)"
}
_check_commands() {
local missing=() cmd
local needed
if [[ ${PLATFORM:-qemu} == proxmox ]]; then
needed=(qm pvesm python3 curl)
else
needed=(qemu-system-x86_64 qemu-img socat python3 curl)
fi
for cmd in "${needed[@]}"; do
have_cmd "$cmd" || missing+=("$cmd")
done
if (( ${#missing[@]} > 0 )); then
_c_fail "missing commands: ${missing[*]}"
else
_c_ok "required commands present"
fi
have_cmd genisoimage || have_cmd xorriso \
|| _c_warn "no genisoimage/xorriso: seed ISOs cannot be built"
}
_check_kvm() {
if [[ ! -e /dev/kvm ]]; then
_c_fail "/dev/kvm absent: software emulation would be unusably slow"
return
fi
if [[ -r /dev/kvm && -w /dev/kvm ]]; then
_c_ok "KVM device accessible to $(id -un)"
else
_c_fail "/dev/kvm not readable/writable by $(id -un)"
fi
if grep -qm1 -E '(vmx|svm)' /proc/cpuinfo; then
_c_ok "CPU virtualization flag present"
else
_c_fail "CPU reports no vmx/svm flag"
fi
}
_check_ram() {
local total avail need
total=$(awk '/^MemTotal:/{printf "%d", $2/1024}' /proc/meminfo)
avail=$(awk '/^MemAvailable:/{printf "%d", $2/1024}' /proc/meminfo)
need=$(( $(sum_vm_ram_mb) + 2048 ))
detail "total ${total} MB · available ${avail} MB · VMs ${need} MB"
if (( avail < need )); then
_c_warn "only ${avail} MB available, ${need} MB planned (close heavy apps)"
else
_c_ok "RAM: ${avail} MB available, ${need} MB planned"
fi
}
_check_storage() {
local ft free need_gb nominal dev
ft=$(fstype_of "$LAB_ROOT")
case $ft in
fuseblk|vfat|exfat)
_c_fail "LAB_ROOT is on ${ft}: qcow2 needs a POSIX filesystem"
;;
*)
_c_ok "LAB_ROOT filesystem: ${ft}"
;;
esac
dev=$(device_of "$LAB_ROOT")
if is_emergency_ro "$LAB_ROOT"; then
_c_fail "${dev} is mounted read-only after I/O errors"
fi
if [[ $dev == /dev/sda1 ]]; then
_c_fail "LAB_ROOT resolves to ${dev}, the known-bad disk"
fi
if [[ $LAB_ROOT == *oof* || $LAB_ISO_CACHE == *oof* ]]; then
_c_fail "a configured path points at /media/oof (excluded on purpose)"
fi
free=$(free_gb_of "$LAB_ROOT")
nominal=$(sum_vm_disk_gb)
need_gb=$(( ISO_BUDGET_GB + nominal * DISK_FILL_RATIO / 100 + MIN_FREE_GB ))
detail "free ${free} GB · projected need ${need_gb} GB"
if (( free < need_gb )); then
_c_fail "not enough space on ${LAB_ROOT}: ${free} GB free, ${need_gb} GB projected"
else
_c_ok "disk: ${free} GB free, ${need_gb} GB projected"
fi
if [[ ${PLATFORM:-qemu} == qemu ]]; then
if is_mounted "$LAB_ISO_CACHE"; then
_c_ok "ISO cache mounted: $(mountpoint_of "$LAB_ISO_CACHE")"
else
_c_warn "ISO cache parent $(dirname "$LAB_ISO_CACHE") is not a mount point"
fi
fi
if [[ ${PLATFORM:-qemu} == qemu && $ft == btrfs ]]; then
if [[ -d $LAB_ROOT/images ]] && lsattr -d "$LAB_ROOT/images" 2>/dev/null | awk '{print $1}' | grep -q 'C'; then
_c_ok "images/ has +C (CoW disabled)"
else
_c_warn "images/ missing or without +C: run ./lab.sh init"
fi
fi
}
_check_network() {
local addrs
if ip link show "$LAB_BRIDGE" >/dev/null 2>&1; then
_c_ok "bridge ${LAB_BRIDGE} exists"
else
if [[ ${PLATFORM:-qemu} == proxmox ]]; then
_c_warn "bridge ${LAB_BRIDGE} missing: create it in the Proxmox GUI"
else
_c_warn "bridge ${LAB_BRIDGE} missing: run sudo ./platforms/qemu/setup-network.sh"
fi
fi
if [[ ${PLATFORM:-qemu} == qemu ]]; then
if [[ -r /etc/qemu/bridge.conf ]] && grep -qx "allow ${LAB_BRIDGE}" /etc/qemu/bridge.conf; then
_c_ok "qemu-bridge-helper allows ${LAB_BRIDGE}"
else
_c_warn "/etc/qemu/bridge.conf does not allow ${LAB_BRIDGE}"
fi
if [[ $(sysctl -n net.ipv4.ip_forward 2>/dev/null) == 1 ]]; then
_c_ok "ip_forward enabled"
else
_c_warn "ip_forward disabled"
fi
fi
addrs=$(ip -4 -o addr show scope global 2>/dev/null | awk '{ printf "%s=%s ", $2, $4 }')
detail "host addresses: ${addrs}"
}
_check_config() {
local i name dup bad=0
for i in "${!VM_NAMES[@]}"; do
name=${VM_NAMES[$i]}
if [[ ${VM_IPS[$i]} != "${LAB_PREFIX}."* ]]; then
_c_fail "vm ${name}: ${VM_IPS[$i]} is outside ${LAB_SUBNET}"
bad=1
fi
[[ ${VM_RAM[$i]} =~ ^[0-9]+$ ]] || { _c_fail "vm ${name}: ram_mb not numeric"; bad=1; }
[[ ${VM_DISK[$i]} =~ ^[0-9]+$ ]] || { _c_fail "vm ${name}: disk_gb not numeric"; bad=1; }
done
dup=$(printf '%s\n' "${VM_IPS[@]}" | sort | uniq -d)
[[ -z $dup ]] || { _c_fail "duplicate IPs: ${dup}"; bad=1; }
(( bad )) || _c_ok "config: ${#VM_NAMES[@]} VMs on ${LAB_SUBNET}"
detail "domain ${DOMAIN} · netbios ${NETBIOS} · backend ${BACKEND}"
}
_check_backend() {
case $BACKEND in
qemu|proxmox) backend_check ;;
*) _c_fail "unknown backend: ${BACKEND}" ;;
esac
}
+174
View File
@@ -0,0 +1,174 @@
# shellcheck shell=bash
# cmd_build / cmd_up / cmd_down / cmd_status — VM lifecycle for the qemu backend.
cmd_build() {
local dry=0 arg
for arg in "$@"; do
case $arg in
--dry-run) dry=1 ;;
-h|--help) info "usage: ./lab.sh build [--dry-run]"; return 0 ;;
*) die "unknown argument: $arg" ;;
esac
done
step "answer files"
if (( dry )); then
info " + render ${#VM_NAMES[@]} unattend file(s) and pack seed ISOs"
else
cmd_seeds >/dev/null || die "seed build failed"
ok "${#VM_NAMES[@]} seed ISO(s) ready"
fi
if [[ ! -f $WINDOWS_ISO ]]; then
(( dry )) || die "missing Windows ISO: $WINDOWS_ISO (run ./lab.sh isos)"
fi
step "virtual disks"
local name
for name in "${VM_NAMES[@]}"; do
backend_create_disk "$name" "$dry"
done
step "launch"
for name in "${VM_NAMES[@]}"; do
if backend_running "$name"; then
info " $name already running"
continue
fi
backend_launch "$name" install "$dry" || die "could not start $name"
done
if (( dry )); then
printf '\n'
ok "dry run complete — nothing was created"
return 0
fi
_wait_for_boot
}
_wait_for_boot() {
local deadline=$(( SECONDS + ${BUILD_TIMEOUT:-2700} ))
local i name ip
local -A pending=()
for i in "${!VM_NAMES[@]}"; do
backend_running "${VM_NAMES[$i]}" && pending["${VM_NAMES[$i]}"]=${VM_IPS[$i]}
done
step "waiting for unattended installs"
info " poll every 15 s, up to $(( ${BUILD_TIMEOUT:-2700} / 60 )) min"
info " watch one: ./lab.sh vnc <vm> · logs: ${LAB_ROOT}/run/"
local reported=1
while (( ${#pending[@]} > 0 )); do
if (( SECONDS > deadline )); then
fail "timed out waiting for: ${!pending[*]}"
return 1
fi
for name in "${!pending[@]}"; do
if tcp_open "${pending[$name]}" 5985; then
ok "$(printf '%-6s installed and reachable on 5985' "$name")"
unset 'pending[$name]'
fi
done
if (( ${#pending[@]} > 0 )); then
if (( SECONDS - reported >= 60 )); then
info " still waiting: ${!pending[*]}"
reported=$SECONDS
fi
sleep 15
fi
done
printf '\n'
ok "all VMs installed and reachable"
if declare -F backend_finalize >/dev/null; then
step "finalize"
for name in "${VM_NAMES[@]}"; do
backend_finalize "$name" || warn "$name: finalize step failed"
done
fi
info " next: ./lab.sh status"
}
# Start the DC first and wait for it: a member that boots before the DC
# loses its machine-account channel and fails to authenticate (NO_LOGON_SERVERS).
_start_lab() {
local name
if vm_index dc01 >/dev/null 2>&1; then
if backend_running dc01; then
info " dc01 already running"
else
backend_launch dc01 run || { fail "dc01 did not start"; return 1; }
fi
backend_ready dc01 240 || warn "dc01 did not answer in time"
fi
for name in "${VM_NAMES[@]}"; do
[[ $name == dc01 ]] && continue
if backend_running "$name"; then
info " $name already running"
else
backend_launch "$name" run || { fail "$name did not start"; return 1; }
fi
done
}
cmd_up() {
step "start"
_start_lab
}
cmd_down() {
local name
step "stop"
for name in "${VM_NAMES[@]}"; do
backend_stop "$name"
done
}
cmd_status() {
local i name ip pid state sync
printf '\n%s%-7s %-14s %-9s %-8s %s%s\n' "$C_BOLD" VM IP STATE PID VNC "$C_RESET"
for i in "${!VM_NAMES[@]}"; do
name=${VM_NAMES[$i]}
ip=${VM_IPS[$i]}
if backend_running "$name"; then
state="running"
pid=$(<"$(qemu_pidfile "$name")")
else
state="stopped"
pid="-"
fi
printf '%-7s %-14s %-9s %-8s %s\n' "$name" "$ip" "$state" "$pid" "$(( 5900 + i + 1 ))"
done
# Reachability is only meaningful once the guest has bootstrapped.
printf '\n'
for i in "${!VM_NAMES[@]}"; do
name=${VM_NAMES[$i]}
ip=${VM_IPS[$i]}
backend_running "$name" || continue
sync="no"
tcp_open "$ip" 5985 && sync="yes"
printf ' %-6s winrm: %s\n' "$name" "$sync"
done
}
cmd_vnc() {
local name=${1:-}
local i
[[ -n $name ]] || die "usage: ./lab.sh vnc <vm> (VMs: ${VM_NAMES[*]})"
i=$(vm_index "$name") || die "unknown vm: $name"
local port=$(( 5900 + i + 1 ))
if have_cmd remote-viewer; then
exec remote-viewer "vnc://127.0.0.1:${port}"
elif have_cmd vncviewer; then
exec vncviewer "127.0.0.1:${port}"
fi
info "no VNC client found. Connect to 127.0.0.1:${port} (display :$(( i + 1 )))"
}
+162
View File
@@ -0,0 +1,162 @@
# shellcheck shell=bash
# cmd_doctor — end-to-end health check of the running laboratory.
_d_ok() { ok "$*"; }
_d_warn() { warn "$*"; DOCTOR_WARNS=$(( DOCTOR_WARNS + 1 )); }
_d_fail() { fail "$*"; DOCTOR_FAILS=$(( DOCTOR_FAILS + 1 )); }
cmd_doctor() {
DOCTOR_FAILS=0
DOCTOR_WARNS=0
local i name ip
step "host"
if ip link show "$LAB_BRIDGE" >/dev/null 2>&1; then
_d_ok "bridge ${LAB_BRIDGE} present"
else
_d_fail "bridge ${LAB_BRIDGE} missing — run sudo ./platforms/qemu/setup-network.sh"
fi
step "machines"
for i in "${!VM_NAMES[@]}"; do
name=${VM_NAMES[$i]}
ip=${VM_IPS[$i]}
if ! backend_running "$name"; then
_d_fail "$name is not running — ./lab.sh up"
continue
fi
if tcp_open "$ip" 445; then
_d_ok "$(printf '%-6s %-14s smb up' "$name" "$ip")"
else
_d_warn "$(printf '%-6s %-14s smb not answering' "$name" "$ip")"
fi
if [[ $name == dc01 || $name == ws01 || $name == fs01 ]]; then
if tcp_open "$ip" 5985; then
_d_ok "$(printf '%-6s %-14s winrm up' "$name" "$ip")"
else
_d_warn "$(printf '%-6s %-14s winrm not answering' "$name" "$ip")"
fi
fi
done
step "domain"
if have_cmd dig; then
local www
www=$(dig +short +time=2 +tries=1 "@$LAB_DC_IP" www.norbourg.lab 2>/dev/null | head -1)
if [[ $www == 10.10.10.20 ]]; then
_d_ok "dns: www.norbourg.lab -> $www"
else
_d_fail "dns: www.norbourg.lab did not resolve via ${LAB_DC_IP} (got '${www:-nothing}')"
fi
local srv
srv=$(dig +short +time=2 +tries=1 "@$LAB_DC_IP" SRV _ldap._tcp.dc._msdcs.norbourg.lab 2>/dev/null | head -1)
if [[ -n $srv ]]; then
_d_ok "dns: ldap SRV record present"
else
_d_fail "dns: ldap SRV record missing — AD discovery would fail"
fi
else
_d_warn "dig not installed, DNS checks skipped"
fi
step "lab state"
_lab_state
step "web"
local code
code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 5 "http://10.10.10.20/" 2>/dev/null || true)
if [[ $code == 200 ]]; then
_d_ok "site answers on 10.10.10.20"
else
_d_fail "site not answering (${code:-timeout}) — ./lab.sh web --sync"
fi
code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 5 "http://10.10.10.20/public/IT-inventaire.txt" 2>/dev/null || true)
if [[ $code == 200 ]]; then
_d_ok "entry point reachable: /public/IT-inventaire.txt"
else
_d_fail "entry point missing (${code:-timeout})"
fi
step "share"
if have_cmd smbclient; then
if smbclient //10.10.10.20/Public -U 'NORBOURG\helpdesk1%Welcome2024!' -c 'ls' 2>/dev/null | grep -q 'IT-inventaire'; then
_d_ok "Public share reachable with the leaked credential"
else
_d_warn "Public share not readable as helpdesk1 (domain channel or DNS?)"
fi
else
_d_warn "smbclient not installed, share check skipped"
fi
printf '\n'
if (( DOCTOR_FAILS )); then
fail "${DOCTOR_FAILS} problem(s), ${DOCTOR_WARNS} warning(s)"
return 1
fi
ok "laboratory healthy · ${DOCTOR_WARNS} warning(s)"
}
# The puzzle has invariants that services do not reveal: a delegated right, an
# SPN, disabled pre-authentication, a password policy, replication rights.
# SDProp quietly reverts ACEs on protected objects, so the target must stay
# outside protected groups — worth checking every time.
_lab_state() {
local out key value
out=$(backend_ps dc01 '
Import-Module ActiveDirectory,DnsServer
$dom = Get-ADDomain
$base = $dom.DistinguishedName
$acl = Get-Acl ("AD:\" + (Get-ADUser t.smith).DistinguishedName)
"ace=" + @($acl.Access | Where-Object { $_.IdentityReference.Value -like "*svc_backup*" }).Count
$plainAcl = Get-Acl ("AD:\" + (Get-ADUser m.legault).DistinguishedName)
"ace_plain=" + @($plainAcl.Access | Where-Object { $_.IdentityReference.Value -like "*svc_backup*" }).Count
"plain_enabled=" + (Get-ADUser m.legault).Enabled
"mcount=" + (Get-ADUser m.legault -Properties adminCount).adminCount
"repl=" + @((dsacls.exe $base | Select-String "Sauvegarde-AD")).Count
"share=" + ((Get-SmbShare -Name "Sauvegarde$" -ErrorAction SilentlyContinue) -ne $null)
"root=" + (Test-Path C:\Sauvegarde\root.txt)
"spn=" + @((Get-ADUser svc_backup -Properties ServicePrincipalNames).ServicePrincipalNames).Count
"preauth=" + (Get-ADUser j.contractor -Properties DoesNotRequirePreAuth).DoesNotRequirePreAuth
"minage=" + (Get-ADDefaultDomainPasswordPolicy).MinPasswordAge.TotalHours
"txt=" + ((Get-DnsServerResourceRecord -ZoneName norbourg.lab -Name yourlove -EA SilentlyContinue) -ne $null)
"dhcp=" + ((Get-DhcpServerv4Scope -EA SilentlyContinue) -ne $null)
"kali_res=" + @((Get-DhcpServerv4Reservation -ScopeId 10.10.10.0 -EA SilentlyContinue) | Where-Object { $_.IPAddress -eq "10.10.10.101" }).Count
' 2>/dev/null) || { _d_warn "cannot query DC01 for lab state"; return; }
while IFS='=' read -r key value; do
value=${value//$'\r'/}
case $key in
ace) if [[ $value -ge 1 ]]; then _d_ok "delegated right: svc_backup has an ACE on t.smith (decoy)"
else _d_warn "decoy ACE on t.smith reverted by SDProp (expected)"; fi ;;
ace_plain) if [[ $value -ge 1 ]]; then _d_ok "stable path: svc_backup has an ACE on m.legault"
else _d_fail "stable path missing (ACE on m.legault)"; fi ;;
plain_enabled) if [[ $value == True ]]; then _d_ok "m.legault account enabled"
else _d_fail "m.legault is disabled — the path is dead"; fi ;;
mcount) if [[ -z $value || $value == 0 ]]; then _d_ok "m.legault outside protected groups"
else _d_fail "adminCount=$value: m.legault is protected, SDProp will wipe the ACE"; fi ;;
repl) if [[ $value -ge 2 ]]; then _d_ok "Sauvegarde-AD holds replication rights (DCSync)"
else _d_fail "replication rights missing on Sauvegarde-AD"; fi ;;
share) if [[ $value == True ]]; then _d_ok "backup share with the flag"
else _d_fail "Sauvegarde\$ share missing"; fi ;;
root) if [[ $value == True ]]; then _d_ok "root.txt reachable through the backup share"
else _d_fail "root.txt missing"; fi ;;
spn) if [[ $value -ge 1 ]]; then _d_ok "service account: SPN present"
else _d_fail "svc_backup has no SPN"; fi ;;
preauth) if [[ $value == True ]]; then _d_ok "pre-auth disabled on j.contractor"
else _d_fail "j.contractor still requires pre-auth"; fi ;;
minage) if [[ $value == 0 ]]; then _d_ok "minimum password age: 0"
else _d_fail "minimum password age is $value h"; fi ;;
txt) if [[ $value == True ]]; then _d_ok "easter egg TXT record"
else _d_warn "yourlove TXT record missing"; fi ;;
dhcp) if [[ $value == True ]]; then _d_ok "DHCP scope present"
else _d_fail "DHCP scope missing"; fi ;;
kali_res) if [[ $value -ge 1 ]]; then _d_ok "DHCP reservation 10.10.10.101"
else _d_fail "Kali reservation missing"; fi ;;
esac
done <<< "$out"
}
+42
View File
@@ -0,0 +1,42 @@
# shellcheck shell=bash
# cmd_init — create the storage layout. No ISOs downloaded yet (phase 3).
cmd_init() {
step "storage layout"
mkdir -p "$LAB_ROOT"/images "$LAB_ROOT"/seeds "$LAB_ROOT"/run "$LAB_ROOT"/logs
ok "LAB_ROOT ${LAB_ROOT}"
# chattr +C must be set on the directory *before* any file is created in it,
# otherwise btrfs keeps CoW for the existing tree.
if [[ $(fstype_of "$LAB_ROOT") == btrfs ]]; then
mkdir -p "$LAB_ROOT/images/base" "$LAB_ROOT/images/overlays"
if chattr +C "$LAB_ROOT/images" 2>/dev/null; then
if lsattr -d "$LAB_ROOT/images" 2>/dev/null | awk '{print $1}' | grep -q 'C'; then
ok "images/ : +C set (CoW disabled)"
else
warn "images/ : chattr +C did not stick"
fi
else
warn "images/ : chattr +C failed (btrfs?)"
fi
else
mkdir -p "$LAB_ROOT/images/base" "$LAB_ROOT/images/overlays"
info " images/ : $(fstype_of "$LAB_ROOT") — no +C needed"
fi
step "iso cache"
if is_mounted "$LAB_ISO_CACHE" || is_mounted "$(dirname "$LAB_ISO_CACHE")"; then
mkdir -p "$LAB_ISO_CACHE"
ok "ISO cache ${LAB_ISO_CACHE}"
else
warn "ISO cache parent $(dirname "$LAB_ISO_CACHE") is not mounted — skipped"
fi
step "directories"
for d in images/base images/overlays seeds run logs; do
printf ' %-24s %s\n' "$d" "$([[ -d $LAB_ROOT/$d ]] && echo present || echo missing)"
done
printf '\n'
ok "layout ready — next: ./lab.sh check"
}
+51
View File
@@ -0,0 +1,51 @@
# shellcheck shell=bash
# cmd_isos — fetch the Windows media into LAB_ISO_CACHE.
# Read-only content, so an NTFS/FUSE cache directory is fine here.
# name|url|minimum size in MB
ISO_ITEMS=(
"SERVER_EVAL_x64FRE_en-us.iso|https://go.microsoft.com/fwlink/?linkid=2195280|2000"
"virtio-win.iso|https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/stable-virtio/virtio-win.iso|200"
)
cmd_isos() {
have_cmd curl || die "curl is required"
mkdir -p "$LAB_ISO_CACHE" || die "cannot create $LAB_ISO_CACHE"
local item name url min_mb target tmp size_mb
for item in "${ISO_ITEMS[@]}"; do
IFS='|' read -r name url min_mb <<< "$item"
target="$LAB_ISO_CACHE/$name"
tmp="$target.part"
if [[ -f $target ]]; then
size_mb=$(( $(stat -c %s "$target") / 1024 / 1024 ))
if (( size_mb >= min_mb )); then
ok "$name present (${size_mb} MB)"
continue
fi
warn "$name is only ${size_mb} MB, re-downloading"
rm -f "$target"
fi
step "download $name"
info " from $url"
local curl_opts=(-L --fail --retry 3 --retry-delay 5 -C - -o "$tmp")
if [[ -t 1 ]]; then
curl "${curl_opts[@]}" --progress-bar "$url" || { rm -f "$tmp"; die "download failed: $name"; }
else
curl "${curl_opts[@]}" -sS "$url" || { rm -f "$tmp"; die "download failed: $name"; }
fi
mv -f "$tmp" "$target"
size_mb=$(( $(stat -c %s "$target") / 1024 / 1024 ))
if (( size_mb < min_mb )); then
die "$name looks truncated: ${size_mb} MB (expected >= ${min_mb} MB)"
fi
ok "$name ready (${size_mb} MB)"
done
printf '\n'
ok "ISO cache complete: ${LAB_ISO_CACHE}"
}
+218
View File
@@ -0,0 +1,218 @@
# shellcheck shell=bash
# cmd_kali — optional attacker VM on the qemu platform.
#
# Uses the official Kali QEMU image (full toolset, kali/kali). It is kept as a
# read-only base plus a throwaway overlay, exactly like the Windows guests.
# Two NICs: br-lab (lab network, DHCP from DC01) and QEMU user networking so
# apt still works while the lab itself stays isolated.
_kali_base() { printf '%s/images/base/kali-base.qcow2' "$LAB_ROOT"; }
_kali_disk() { printf '%s/images/overlays/kali.qcow2' "$LAB_ROOT"; }
_kali_pid() { printf '%s/run/kali.pid' "$LAB_ROOT"; }
_kali_log() { printf '%s/run/kali.log' "$LAB_ROOT"; }
_kali_installed() { [[ -f $(_kali_base) ]]; }
_kali_tools_iso() { printf '%s/seeds/kali-tools.iso' "$LAB_ROOT"; }
# The stock Kali image ships without the lab wordlist. A small ISO carries it
# into the guest, so a fresh redeploy is reproducible without network access.
_kali_build_tools() {
local iso dir
iso=$(_kali_tools_iso)
dir=$(mktemp -d)
mkdir -p "$(dirname "$iso")"
cp "$CONTENT_DIR/scripts/wordlists/norbourg.txt" "$dir/"
cat > "$dir/README.txt" <<'EOF'
Outils de l'atelier Norbourg
============================
norbourg.txt : liste de mots ciblee (1716 entrees), dimensionnee pour que le
cassage prenne quelques secondes.
Installation dans Kali :
sudo mkdir -p /opt/norbourg/wordlists
sudo cp /media/cdrom/norbourg.txt /opt/norbourg/wordlists/
sudo chmod 644 /opt/norbourg/wordlists/norbourg.txt
EOF
if have_cmd genisoimage; then
genisoimage -quiet -volid NORBOURG_TOOLS -J -R -o "$iso" "$dir"
else
xorriso -as mkisofs -quiet -V NORBOURG_TOOLS -J -R -o "$iso" "$dir"
fi
rm -rf "$dir"
ok "tool ISO: $iso"
}
_kali_ensure_overlay() {
local base overlay
base=$(_kali_base)
overlay=$(_kali_disk)
_kali_installed || return 1
mkdir -p "$(dirname "$overlay")"
[[ -f $overlay ]] && return 0
qemu-img create -q -f qcow2 -F qcow2 -b "../base/kali-base.qcow2" "$overlay"
}
cmd_kali() {
local action=${1:-up}
case $action in
install) _kali_install ;;
up) _kali_up ;;
down) _kali_down ;;
reset) _kali_reset ;;
snapshot) _kali_snapshot ;;
status) _kali_status ;;
*) info "usage: ./lab.sh kali install|up|down|reset|snapshot|status"; return 2 ;;
esac
}
_kali_install() {
local archive="$LAB_ISO_CACHE/kali-qemu.7z"
local base tmp found
have_cmd 7z || die "7z is required to extract the Kali image"
base=$(_kali_base)
if _kali_installed; then
ok "Kali base image already present ($(du -h "$base" | cut -f1))"
return 0
fi
mkdir -p "$LAB_ISO_CACHE" "$(dirname "$base")"
if [[ ! -f $archive ]]; then
step "download Kali QEMU image (~4 GB)"
curl -L --fail --retry 3 -C - -o "$archive.part" "$KALI_ARCHIVE_URL" -sS \
|| { rm -f "$archive.part"; die "download failed"; }
mv -f "$archive.part" "$archive"
fi
ok "archive: $(du -h "$archive" | cut -f1)"
step "extract"
tmp=$(mktemp -d "$LAB_ROOT/run/kali-extract.XXXXXX")
( cd "$tmp" && 7z x -y "$archive" >/dev/null ) || { rm -rf "$tmp"; die "extraction failed"; }
found=$(find "$tmp" -maxdepth 2 -name '*.qcow2' -print -quit)
[[ -n $found ]] || { rm -rf "$tmp"; die "no qcow2 inside the archive"; }
mv "$found" "$base"
rm -rf "$tmp"
if [[ ${KALI_DISK_GB:-40} -gt 0 ]]; then
qemu-img resize -q "$base" "${KALI_DISK_GB}G" >/dev/null 2>&1 || true
fi
ok "base image: $(du -h "$base" | cut -f1) (${KALI_DISK_GB:-40}G nominal)"
_kali_ensure_overlay
_kali_build_tools
printf '\n'
ok "Kali installed — ./lab.sh kali up"
info " default credentials: kali / kali"
}
_kali_up() {
local base overlay pid vnc
_kali_installed || die "Kali is not installed — ./lab.sh kali install"
_kali_ensure_overlay || die "could not create the Kali overlay"
if _kali_status >/dev/null 2>&1; then
info "Kali already running"
return 0
fi
base=$(_kali_base)
overlay=$(_kali_disk)
vnc=${KALI_VNC_DISPLAY:-9}
mkdir -p "$LAB_ROOT/run"
[[ -f $(_kali_tools_iso) ]] || _kali_build_tools
# net0: the lab bridge (DHCP from DC01). net1: user networking so apt works
# without punching a hole through the lab isolation policy.
local cd_args=()
if [[ -f $(_kali_tools_iso) ]]; then
cd_args=( -drive "if=none,id=cd1,media=cdrom,file=$(_kali_tools_iso)" -device "ide-cd,drive=cd1,bus=ide.1" )
fi
nohup qemu-system-x86_64 \
-name norbourg-kali \
-machine q35,accel=kvm -cpu host \
-smp "${KALI_VCPU:-2},sockets=1,cores=${KALI_VCPU:-2}" \
-m "${KALI_RAM:-4096}" \
-rtc base=localtime,clock=host \
-drive "if=none,id=disk,file=$overlay,format=qcow2,cache=none,aio=native" \
-device ide-hd,drive=disk,bus=ide.0 \
-netdev "bridge,id=net0,br=$LAB_BRIDGE" \
-device "e1000,netdev=net0,mac=$(qemu_mac_for "${KALI_IP:-10.10.10.101}")" \
-netdev "user,id=net1,hostfwd=tcp:127.0.0.1:${KALI_SSH_PORT:-2222}-:22" \
-device "e1000,netdev=net1" \
-monitor "unix:$LAB_ROOT/run/kali.monitor,server,nowait" \
"${cd_args[@]}" \
-display none -vnc "127.0.0.1:$vnc" \
>>"$(_kali_log)" 2>&1 &
printf '%s\n' "$!" > "$(_kali_pid)"
sleep 2
if kill -0 "$(<"$(_kali_pid)")" 2>/dev/null; then
ok "Kali started · vnc 127.0.0.1:$(( 5900 + vnc )) · ssh 127.0.0.1:${KALI_SSH_PORT:-2222}"
info " login kali/kali · bridge address via DHCP (${KALI_IP:-10.10.10.101} reserved)"
info " wordlist on the tool CD: mount /dev/sr0 /mnt && cp /mnt/norbourg.txt /opt/norbourg/wordlists/"
else
fail "Kali failed to start — see $(_kali_log)"
return 1
fi
}
_kali_down() {
local pid sock
_kali_status >/dev/null 2>&1 || { info "Kali already stopped"; return 0; }
pid=$(<"$(_kali_pid)")
sock="$LAB_ROOT/run/kali.monitor"
if [[ -S $sock ]]; then
printf 'system_powerdown\n' | socat - "UNIX-CONNECT:$sock" >/dev/null 2>&1 || true
fi
for _ in $(seq 1 30); do kill -0 "$pid" 2>/dev/null || break; sleep 1; done
kill -0 "$pid" 2>/dev/null && { kill "$pid" 2>/dev/null; sleep 2; }
rm -f "$(_kali_pid)"
ok "Kali stopped"
}
# Fold the current overlay into the base image: wordlist, DNS, packages and
# any tooling you installed survive a reset from then on.
_kali_snapshot() {
local overlay
_kali_installed || die "Kali is not installed"
overlay=$(_kali_disk)
_kali_down >/dev/null 2>&1 || true
if [[ ! -f $overlay ]]; then
ok "nothing to commit — no working overlay"
return 0
fi
step "commit the overlay into ${KALI_NAME:-kali}'s base image"
qemu-img commit -q "$overlay" || die "qemu-img commit failed"
rm -f "$overlay"
_kali_ensure_overlay
ok "baseline updated: ./lab.sh kali reset now returns to this state"
}
_kali_reset() {
local overlay
_kali_installed || die "Kali is not installed"
_kali_down >/dev/null 2>&1 || true
overlay=$(_kali_disk)
rm -f "$overlay"
_kali_ensure_overlay
ok "Kali reverted to the clean image"
}
_kali_status() {
local pid
_kali_installed || return 1
[[ -r $(_kali_pid) ]] || return 1
pid=$(<"$(_kali_pid)")
[[ -n $pid ]] && kill -0 "$pid" 2>/dev/null
}
+42
View File
@@ -0,0 +1,42 @@
# shellcheck shell=bash
# cmd_answers / cmd_destroy — small utilities shared by both platforms.
cmd_answers() {
local file="$ROOT_DIR/answers/walkthrough.md"
[[ -r $file ]] || die "no answer key at $file"
cat "$file"
}
cmd_destroy() {
local name i
step "stop"
for name in "${VM_NAMES[@]}"; do
backend_stop "$name" >/dev/null 2>&1 || true
done
step "remove"
for name in "${VM_NAMES[@]}"; do
backend_destroy "$name" || warn "could not fully remove $name"
done
# Kali lives outside the VMS table; stop it but keep its 16 GB base image.
if declare -F _kali_installed >/dev/null && _kali_installed; then
_kali_down >/dev/null 2>&1 || true
info "kali stopped; base image kept ($(du -h "$(_kali_base)" | cut -f1))"
fi
step "generated artifacts"
rm -rf "$LAB_ROOT/seeds" "$LAB_ROOT/run" "$LAB_ROOT/provision"
ok "seed ISOs, runtime state and provisioning scratch removed"
printf '\n'
info "kept: ${LAB_ROOT}/images (baselines), logs, and the ISO cache"
info "remove those by hand if you really want the space back"
}
# Platforms that support participant tunnels override this.
cmd_peers() { planned peers; }
# Overridden by the qemu platform, which ships the Kali image helper.
cmd_kali() { planned kali; }
+61
View File
@@ -0,0 +1,61 @@
# shellcheck shell=bash
# cmd_provision — run the role stages inside each guest.
#
# The role scripts travel on the seed ISO and bootstrap copies them to
# C:\norbourg, so provisioning never transfers files: it only asks the guest
# to run a script and waits for its .done marker. The transport (WinRM or the
# QEMU guest agent) lives in the backend.
cmd_provision() {
local only=""
while (( $# > 0 )); do
case $1 in
--role) only=$2; shift 2 ;;
-h|--help) info "usage: ./lab.sh provision [--role NAME]"; return 0 ;;
*) die "unknown argument: $1" ;;
esac
done
: "${LAB_SAFE_MODE_PASSWORD:?LAB_SAFE_MODE_PASSWORD is not set in lab.conf}"
local i name role script marker
for i in "${!VM_NAMES[@]}"; do
name=${VM_NAMES[$i]}
role=${VM_ROLES[$i]}
script="C:\\norbourg\\roles\\${role}.ps1"
[[ -n $only && $only != "$name" && $only != "$role" ]] && continue
step "$name ($role)"
if [[ $role != dc01 ]]; then
backend_ready dc01 300 || die "dc01 is not reachable — provision dc01 first"
fi
backend_ready "$name" 600 || { fail "$name: guest agent/WinRM unreachable"; return 1; }
backend_start "$name" "$script" || die "$name: could not start ${role}.ps1"
marker=$(backend_wait "$name" "$script" 3600) || {
fail "$name: ${role}.ps1 did not finish"
return 1
}
[[ $marker == FAIL* ]] && { fail "$name: ${role}.ps1 failed — $marker"; return 1; }
ok "$name: $marker"
if [[ -f $CONTENT_DIR/windows/roles/${role}-post.ps1 ]]; then
info " waiting for the guest to come back"
backend_ready "$name" 900 || { fail "$name: did not come back after reboot"; return 1; }
script="C:\\norbourg\\roles\\${role}-post.ps1"
backend_start "$name" "$script" || { fail "$name: could not start the post stage"; return 1; }
marker=$(backend_wait "$name" "$script" 3600) || {
fail "$name: ${role}-post.ps1 did not finish"
return 1
}
[[ $marker == FAIL* ]] && { fail "$name: ${role}-post.ps1 failed — $marker"; return 1; }
ok "$name: $marker"
fi
done
printf '\n'
ok "provisioning complete"
}
+75
View File
@@ -0,0 +1,75 @@
# shellcheck shell=bash
# cmd_seeds — render one unattend + payload per VM and pack a seed ISO.
# Nothing here needs root or a downloaded ISO; it is pure file assembly.
cmd_seeds() {
local tmpl="$CONTENT_DIR/seed/Autounattend.xml.tmpl"
local payload="$CONTENT_DIR/seed/payload"
[[ -r $tmpl ]] || die "missing template: $tmpl"
[[ -d $payload ]] || die "missing payload dir: $payload"
have_cmd genisoimage || have_cmd xorriso || die "genisoimage or xorriso is required"
: "${LAB_ADMIN_PASSWORD:?LAB_ADMIN_PASSWORD is not set in lab.conf}"
mkdir -p "$SEED_DIR"
local i name ip role work iso volid dns
for i in "${!VM_NAMES[@]}"; do
name=${VM_NAMES[$i]}
ip=${VM_IPS[$i]}
role=${VM_ROLES[$i]}
dns=$LAB_DC_IP # every lab VM resolves through the DC
work="$SEED_DIR/$name"
rm -rf "$work"
mkdir -p "$work/norbourg/roles"
sed -e "s|@@HOSTNAME@@|${name}|g" \
-e "s|@@ADMIN_PASSWORD@@|${LAB_ADMIN_PASSWORD}|g" \
-e "s|@@IMAGE_INDEX@@|${WINDOWS_IMAGE_INDEX:-2}|g" \
"$tmpl" > "$work/Autounattend.xml"
cp "$payload/bootstrap.cmd" "$work/norbourg/"
cp "$payload/bootstrap.ps1" "$work/norbourg/"
# Ship the role scripts on the ISO so the guest never needs a file
# transfer: bootstrap copies this tree to C:\norbourg and runs from there.
mkdir -p "$work/norbourg/lib" "$work/norbourg/roles"
cp "$CONTENT_DIR/windows/lib/common.ps1" "$work/norbourg/lib/"
render_role "$CONTENT_DIR/windows/roles/${role}.ps1" "$work/norbourg/roles/${role}.ps1"
if [[ -f $CONTENT_DIR/windows/roles/${role}-post.ps1 ]]; then
render_role "$CONTENT_DIR/windows/roles/${role}-post.ps1" "$work/norbourg/roles/${role}-post.ps1"
fi
cat > "$work/norbourg/config.ps1" <<EOF
\$Config = @{
Hostname = '${name}'
IP = '${ip}'
Prefix = ${LAB_NETMASK}
Gateway = '${LAB_GATEWAY}'
DNS = '${dns}'
Role = '${role}'
Domain = '${DOMAIN}'
}
EOF
# A malformed answer file means a 20-minute silent install failure; catch it here.
python3 - "$work/Autounattend.xml" <<'PY' || die "rendered answer file is not valid XML for ${name}"
import sys, xml.etree.ElementTree as ET
ET.parse(sys.argv[1])
PY
iso="$SEED_DIR/${name}-seed.iso"
volid="NRBG_${name^^}"
if have_cmd genisoimage; then
genisoimage -quiet -volid "$volid" -J -R -o "$iso" "$work"
else
xorriso -as mkisofs -quiet -V "$volid" -J -R -o "$iso" "$work"
fi
ok "$(printf '%-6s %-14s %-4s %s' "$name" "$ip" "$role" "$iso")"
done
printf '\n'
ok "${#VM_NAMES[@]} seed ISO(s) in ${SEED_DIR}"
}
+80
View File
@@ -0,0 +1,80 @@
# shellcheck shell=bash
# cmd_snapshot / cmd_reset — freeze a clean baseline and revert to it.
# qemu backend: the golden disk becomes a read-only base, each run boots a
# thin overlay. Reset deletes the overlay, so it takes about a second.
cmd_snapshot() {
local name update=0
for name in "$@"; do
case $name in
--update) update=1 ;;
-h|--help) info "usage: ./lab.sh snapshot [--update]"; return 0 ;;
*) die "unknown argument: $name" ;;
esac
done
step "stop"
for name in "${VM_NAMES[@]}"; do
backend_stop "$name"
done
if (( update )); then
step "commit current state into the baseline"
for name in "${VM_NAMES[@]}"; do
backend_commit "$name" || die "commit failed for $name"
done
printf '\n'
ok "baseline updated"
info " ./lab.sh up to start · ./lab.sh reset to revert to this state"
return 0
fi
step "freeze baseline"
for name in "${VM_NAMES[@]}"; do
backend_snapshot "$name" || die "snapshot failed for $name"
done
printf '\n'
ok "baseline ready"
info " start with ./lab.sh up · revert with ./lab.sh reset"
}
cmd_reset() {
local name
step "revert to baseline"
for name in "${VM_NAMES[@]}"; do
backend_reset "$name" || die "reset failed for $name"
done
step "start"
_start_lab
printf '\n'
ok "laboratory reset — previous state discarded"
}
# The closing step of every change: freeze the current state into the
# baseline, then bring the lab back up. Falls back to a first-time snapshot
# when no baseline exists yet.
cmd_save() {
local name need_full=0
if declare -F backend_has_baseline >/dev/null; then
for name in "${VM_NAMES[@]}"; do
backend_has_baseline "$name" || need_full=1
done
else
need_full=1
fi
if (( need_full )); then
cmd_snapshot
else
cmd_snapshot --update
fi
step "start"
_start_lab
}
+79
View File
@@ -0,0 +1,79 @@
# shellcheck shell=bash
# cmd_web — assemble the archived site and apply the seed layer.
# Syncing to FS01 arrives with phase 7, once the VM exists.
cmd_web() {
local site="$CONTENT_DIR/web/site" seed="$CONTENT_DIR/web/seed"
local sync=0 arg
for arg in "$@"; do
case $arg in
--sync) sync=1 ;;
-h|--help) info "usage: ./lab.sh web [--sync]"; return 0 ;;
*) die "unknown argument: $arg" ;;
esac
done
step "assemble"
python3 "$CONTENT_DIR/scripts/prepare_site.py" || die "site assembly failed"
step "seed layer"
[[ -d $seed ]] || die "missing $seed"
cp -a "$seed/." "$site/"
ok "seed applied: $(find "$seed" -type f | wc -l) file(s)"
step "layout"
printf ' %-34s %s\n' "public/IT-inventaire.txt" \
"$([[ -f $site/public/IT-inventaire.txt ]] && echo present || echo MISSING)"
printf ' %-34s %s\n' "robots.txt" \
"$([[ -f $site/robots.txt ]] && echo present || echo MISSING)"
printf ' %-34s %s\n' "index.html" \
"$([[ -f $site/index.html ]] && echo present || echo MISSING)"
if (( ! sync )); then
printf '\n'
ok "web root ready: ${site#$CONTENT_DIR/}"
info " preview: python3 -m http.server 8080 --directory ${site#$CONTENT_DIR/}"
info " push to FS01: ./lab.sh web --sync"
return 0
fi
_web_sync "$site"
}
_web_sync() {
local site=$1
local i ip remote='C:\\norbourg\\site'
i=$(vm_index fs01) || die "fs01 is not defined in lab.conf"
ip=${VM_IPS[$i]}
step "push to fs01 ($ip)"
tcp_open "$ip" 445 || die "fs01 SMB is not reachable — is it provisioned?"
have_cmd smbclient || die "smbclient is required to push the site"
# Clear the staging folder first: smbclient only adds, so an old file would
# otherwise come back on every sync.
backend_ready fs01 120 >/dev/null 2>&1 || true
backend_ps fs01 "Remove-Item -Recurse -Force -ErrorAction SilentlyContinue 'C:\\norbourg\\site'" >/dev/null 2>&1 || true
# Bulk copy goes over SMB: WinRM caps the command line at ~8 KB.
smbclient "//$ip/C\$" -W "$NETBIOS" \
-U "$LAB_USER%$LAB_ADMIN_PASSWORD" \
-c "prompt OFF; recurse ON; mkdir norbourg; mkdir norbourg\\site; lcd $site; cd norbourg\\site; mput *" \
>/dev/null 2>&1 || true
backend_ready fs01 300 || die "fs01 did not answer"
# Mirror, not merge: remove everything except the web.config that fs01.ps1
# places in public/, otherwise files deleted from the repo keep being served.
backend_ps fs01 "
Get-ChildItem 'C:\inetpub\wwwroot' -Force | Where-Object { \$_.Name -ne 'public' } |
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
Get-ChildItem 'C:\inetpub\wwwroot\public' -Force | Where-Object { \$_.Name -ne 'web.config' } |
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
Copy-Item -Path 'C:\norbourg\site\*' -Destination 'C:\inetpub\wwwroot' -Recurse -Force
Test-Path 'C:\inetpub\wwwroot\index.html'" \
| grep -qi true || die "copy failed on fs01"
ok "site published to C:\\inetpub\\wwwroot"
info " http://10.10.10.20/ · http://www.norbourg.lab/"
}
+175
View File
@@ -0,0 +1,175 @@
# shellcheck shell=bash
# Shared helpers for lab.sh. Sourced, never executed directly.
LAB_SH_VERSION="0.1.0"
# ------------------------------------------------------------------ output
if [[ -t 1 && -z ${NO_COLOR:-} ]]; then
C_RESET=$'\e[0m'; C_BOLD=$'\e[1m'; C_DIM=$'\e[2m'
C_RED=$'\e[31m'; C_GREEN=$'\e[32m'; C_YELLOW=$'\e[33m'; C_BLUE=$'\e[34m'
else
C_RESET=""; C_BOLD=""; C_DIM=""; C_RED=""; C_GREEN=""; C_YELLOW=""; C_BLUE=""
fi
VERBOSE=${VERBOSE:-0}
STRICT=${STRICT:-0}
info() { printf '%s\n' "$*"; }
raw() { printf '%s\n' "$*"; }
ok() { printf '%s[ ok ]%s %s\n' "$C_GREEN" "$C_RESET" "$*"; }
warn() { printf '%s[warn]%s %s\n' "$C_YELLOW" "$C_RESET" "$*" >&2; }
fail() { printf '%s[fail]%s %s\n' "$C_RED" "$C_RESET" "$*" >&2; }
die() { fail "$*"; exit 1; }
step() { printf '\n%s==> %s%s\n' "$C_BLUE" "$*" "$C_RESET"; }
detail() { if (( VERBOSE )); then printf '%s %s%s\n' "$C_DIM" "$*" "$C_RESET"; fi; return 0; }
# Substitute the lab-wide tokens in a role script.
render_role() {
local src=$1 dst=$2
sed -e "s|@@DOMAIN@@|${DOMAIN}|g" \
-e "s|@@NETBIOS@@|${NETBIOS}|g" \
-e "s|@@BASE_DN@@|${BASE_DN}|g" \
-e "s|@@ADMIN_PASSWORD@@|${LAB_ADMIN_PASSWORD}|g" \
-e "s|@@SAFE_MODE_PASSWORD@@|${LAB_SAFE_MODE_PASSWORD}|g" \
-e "s|@@LAB_DC_IP@@|${LAB_DC_IP}|g" \
-e "s|@@LAB_GATEWAY@@|${LAB_GATEWAY:-}|g" \
"$src" > "$dst"
}
# Deterministic MAC from the last two octets: 10.10.10.31 -> 52:54:00:0a:1f:00
# (six octets — a five-byte value is rejected as "invalid ethernet address")
qemu_mac_for() {
local ip=$1
local b3=${ip##*.}
local rest=${ip%.*}
local b2=${rest##*.}
printf '52:54:00:%02x:%02x:00' "$b2" "$b3"
}
# ------------------------------------------------------------------ commands
have_cmd() { command -v "$1" >/dev/null 2>&1; }
require_cmd() {
have_cmd "$1" || die "required command not found: $1${2:+ ($2)}"
}
# ------------------------------------------------------------------ config
load_config() {
LAB_CONF=${LAB_CONF:-$LAB_DIR/lab.conf}
[[ -r $LAB_CONF ]] || die "config not found: $LAB_CONF"
set -a
# shellcheck disable=SC1090
source "$LAB_CONF"
set +a
# A local override wins over the committed config (sourced last on purpose).
if [[ -r $LAB_DIR/lab.conf.local ]]; then
set -a
# shellcheck disable=SC1091
source "$LAB_DIR/lab.conf.local"
set +a
fi
: "${LAB_ROOT:?LAB_ROOT is not set}"
: "${LAB_ISO_CACHE:?LAB_ISO_CACHE is not set}"
: "${LAB_PREFIX:?LAB_PREFIX is not set}"
BACKEND=${BACKEND:-qemu}
BASE_DN="DC=${DOMAIN%%.*},DC=${DOMAIN#*.}"
# Each platform names its bridge differently (br-lab / vmbr10).
LAB_BRIDGE=${LAB_BRIDGE:-${BRIDGE:-${PVE_BRIDGE:-}}}
: "${LAB_BRIDGE:?no lab bridge configured (BRIDGE or PVE_BRIDGE)}"
MIN_FREE_GB=${MIN_FREE_GB:-20}
SEED_DIR=${SEED_DIR:-$LAB_ROOT/seeds}
LAB_USER=${LAB_USER:-Administrator}
DISK_FILL_RATIO=${DISK_FILL_RATIO:-60}
ISO_BUDGET_GB=${ISO_BUDGET_GB:-8}
load_vms
}
# VMS is a small whitespace-separated table; load it into parallel arrays.
load_vms() {
VM_NAMES=(); VM_IPS=(); VM_RAM=(); VM_DISK=(); VM_VCPU=(); VM_ROLES=()
local name ip ram disk vcpu role
while read -r name ip ram disk vcpu role; do
[[ -z ${name:-} || ${name:0:1} == '#' ]] && continue
VM_NAMES+=("$name")
VM_IPS+=("$ip")
VM_RAM+=("$ram")
VM_DISK+=("$disk")
VM_VCPU+=("$vcpu")
VM_ROLES+=("$role")
done <<< "${VMS:-}"
(( ${#VM_NAMES[@]} > 0 )) || die "no VMs defined in VMS (lab.conf)"
}
vm_index() {
local name=$1 i
for i in "${!VM_NAMES[@]}"; do
if [[ ${VM_NAMES[$i]} == "$name" ]]; then
printf '%s\n' "$i"
return 0
fi
done
return 1
}
# Bash-native TCP probe: no nc dependency, 1 s timeout.
tcp_open() {
local host=$1 port=$2
timeout 1 bash -c "exec 3<>/dev/tcp/${host}/${port}" 2>/dev/null
}
sum_vm_ram_mb() {
local total=0 r
for r in "${VM_RAM[@]}"; do total=$(( total + r )); done
printf '%s\n' "$total"
}
sum_vm_disk_gb() {
local total=0 d
for d in "${VM_DISK[@]}"; do total=$(( total + d )); done
printf '%s\n' "$total"
}
# ------------------------------------------------------------------ filesystem
# Walk up until the path exists; useful before LAB_ROOT is created.
existing_ancestor() {
local p=$1
while [[ ! -e $p ]]; do p=$(dirname -- "$p"); done
printf '%s\n' "$p"
}
fstype_of() {
stat -f -c %T -- "$(existing_ancestor "$1")" 2>/dev/null || printf 'unknown\n'
}
device_of() {
df --output=source -- "$(existing_ancestor "$1")" 2>/dev/null | tail -n1
}
free_gb_of() {
df -BG --output=avail -- "$(existing_ancestor "$1")" 2>/dev/null | tail -n1 | tr -dc '0-9'
}
# ext4 marks a filesystem "emergency_ro" in /proc/mounts after a fatal I/O error.
is_emergency_ro() {
local dev
dev=$(device_of "$1")
[[ -n $dev ]] || return 1
awk -v d="$dev" '$1 == d && $4 ~ /emergency_ro/ { found = 1 } END { exit(found ? 0 : 1) }' /proc/mounts
}
is_mounted() {
local target
target=$(mountpoint_of "$1")
[[ -n $target && $target != "/" ]]
}
mountpoint_of() {
findmnt -rn --target "$(existing_ancestor "$1")" -o TARGET 2>/dev/null
}
+107
View File
@@ -0,0 +1,107 @@
# shellcheck shell=bash
# Shared command dispatcher. Sourced by each platform's lab.sh after the
# command implementations and before anything runs.
#
# The platform provides: LAB_DIR, CONTENT_DIR, PLATFORM, and its backend file
# at $LAB_DIR/backends/<PLATFORM>.sh.
usage() {
cat <<EOF
Norbourg lab ${LAB_SH_VERSION} — ${PLATFORM} platform
Usage: ./lab.sh [options] <command>
Options:
--strict treat check warnings as failures
-v, --verbose extra detail
-h, --help this text
--version print the version
Commands:
check preflight: host, storage, network, configuration
init create the storage layout and the runtime venv if needed
isos download the Windows media
seeds render unattend files and pack the seed ISOs
build create the VMs and run the unattended installs
provision run the role stages (--role NAME for a single VM)
web assemble the site; --sync publishes it to FS01
snapshot freeze a clean baseline
save snapshot --update then start (the closing step)
reset revert to the baseline and start
up, down start / stop the VMs
status VM table
vnc open a console on a VM
doctor end-to-end health check
kali install / start / stop the optional Kali attacker VM
answers print the instructor walkthrough
destroy remove the VMs and generated artifacts
EOF
case $PLATFORM in
proxmox) printf ' peers generate WireGuard configs for participants\n' ;;
esac
}
planned() {
warn "'$1' is not implemented on this platform"
return 3
}
# ------------------------------------------------------------------ arguments
cmd=""
while (( $# > 0 )); do
case $1 in
--strict) STRICT=1; shift ;;
-v|--verbose) VERBOSE=1; shift ;;
-h|--help|help) usage; exit 0 ;;
--version) printf '%s\n' "$LAB_SH_VERSION"; exit 0 ;;
--) shift; break ;;
-*)
# Before the command this is a typo; after it, the flag belongs to the verb.
[[ -z $cmd ]] && die "unknown option: $1 (try --help)"
break
;;
*)
# First positional is the command; everything after it belongs to the verb
# (peers wants a list of names, provision wants --role NAME).
if [[ -z $cmd ]]; then cmd=$1; shift; fi
break
;;
esac
done
if [[ -z $cmd ]]; then
usage
exit 2
fi
load_config
backend_file="$LAB_DIR/backends/${BACKEND}.sh"
[[ -r $backend_file ]] || die "no backend '${BACKEND}' for the ${PLATFORM} platform (looked for ${backend_file})"
# shellcheck disable=SC1090
source "$backend_file"
# ------------------------------------------------------------------ dispatch
case $cmd in
check) cmd_check "$@" || exit $? ;;
init) cmd_init "$@" ;;
isos) cmd_isos "$@" ;;
seeds) cmd_seeds "$@" ;;
web) cmd_web "$@" ;;
build) cmd_build "$@" ;;
up) cmd_up "$@" ;;
down) cmd_down "$@" ;;
status) cmd_status "$@" ;;
vnc) cmd_vnc "$@" ;;
provision) cmd_provision "$@" ;;
snapshot) cmd_snapshot "$@" ;;
save) cmd_save "$@" ;;
reset) cmd_reset "$@" ;;
doctor) cmd_doctor "$@" ;;
kali) cmd_kali "$@" ;;
answers) cmd_answers "$@" ;;
destroy) cmd_destroy "$@" ;;
peers) cmd_peers "$@" ;;
*) die "unknown command: ${cmd} (try --help)" ;;
esac