Files
pentest.intro/session1/platforms/proxmox/backends/proxmox.sh
T
quoije 30dbefdb1b proxmox: tolerate NUL-padded agent output and avoid false stage guards
powershell.exe over the guest agent can return UTF-16LE, so Test-Path read
as T\0r\0u\0e and every 'grep true' failed. Strip NULs in _qga_unwrap,
and only treat an explicit False as proof that the role script is absent.
2026-10-26 17:58:06 -04:00

847 lines
29 KiB
Bash

# shellcheck shell=bash
# Proxmox VE backend.
#
# Hardware model mirrors the QEMU platform: q35 + SATA + e1000, so the same
# unattended file and the same role scripts work unchanged. Provisioning talks
# to the QEMU guest agent (`qm guest exec`), so the Proxmox host needs no
# Python packages beyond its own.
# ------------------------------------------------------------------ helpers
pve_vmid() {
local i
i=$(vm_index "$1") || return 1
printf '%s' $(( PVE_VMID_BASE + i ))
}
pve_template_vmid() {
local i
i=$(vm_index "$1") || return 1
printf '%s' $(( PVE_VMID_BASE + 100 + i ))
}
pve_exists() { qm status "$1" >/dev/null 2>&1; }
pve_is_template() { qm config "$1" 2>/dev/null | grep -qx 'template: 1'; }
pve_running() { qm status "$1" 2>/dev/null | grep -q 'status: running'; }
pve_ip() { local i; i=$(vm_index "$1"); printf '%s' "${VM_IPS[$i]}"; }
# ------------------------------------------------------------------ preflight
# Which storages advertise iso content. `pvesm status --content` is not
# available on every version, so fall back to parsing storage.cfg.
pve_iso_storages() {
local out
out=$(pvesm status --content iso 2>/dev/null | awk 'NR>1{print $1}' | tr '\n' ' ')
if [[ -z ${out// /} && -r /etc/pve/storage.cfg ]]; then
out=$(awk '/^[a-z]+: /{name=$2} /^[[:space:]]*content[[:space:]]/ && /iso/ {print name}' \
/etc/pve/storage.cfg | tr '\n' ' ')
fi
printf '%s' "$out"
}
backend_check() {
if ! command -v qm >/dev/null 2>&1; then
_c_fail "qm not found — this script must run on a Proxmox VE host"
return
fi
_c_ok "qm present ($(pveversion 2>/dev/null | cut -d/ -f1-2))"
command -v pvesm >/dev/null 2>&1 && _c_ok "pvesm present" || _c_fail "pvesm missing"
# storages
local iso_content
if pvesm status 2>/dev/null | awk 'NR>1{print $1}' | grep -qx "$PVE_STORAGE_DISKS"; then
_c_ok "disk storage ${PVE_STORAGE_DISKS} present"
else
_c_fail "disk storage ${PVE_STORAGE_DISKS} not found (run pvesm status)"
fi
iso_content=$(pve_iso_storages)
if [[ " $iso_content " == *" ${PVE_STORAGE_ISO} "* ]]; then
_c_ok "iso storage ${PVE_STORAGE_ISO} present"
else
_c_fail "storage ${PVE_STORAGE_ISO} has no iso content (available: ${iso_content:-none})"
fi
if [[ -d $PVE_ISO_DIR && -w $PVE_ISO_DIR ]]; then
_c_ok "iso directory ${PVE_ISO_DIR} writable"
else
_c_fail "iso directory ${PVE_ISO_DIR} missing or not writable"
fi
# isolated bridge
if [[ -d /sys/class/net/$PVE_BRIDGE ]]; then
if ip -4 -o addr show dev "$PVE_BRIDGE" 2>/dev/null | grep -q "inet ${LAB_HOST_IP}/"; then
_c_ok "bridge ${PVE_BRIDGE} has ${LAB_HOST_IP}"
else
_c_fail "bridge ${PVE_BRIDGE} exists but does not carry ${LAB_HOST_IP}"
fi
else
_c_fail "bridge ${PVE_BRIDGE} missing — create it in the GUI (see lab.conf)"
fi
# guest agent is what provisioning talks to; it cannot be probed before boot
_c_ok "provisioning over qm guest exec (agent installed by bootstrap)"
[[ -f $WINDOWS_ISO ]] && _c_ok "Windows ISO present" \
|| _c_warn "Windows ISO missing: run ./lab.sh isos"
if command -v genisoimage >/dev/null 2>&1 || command -v xorriso >/dev/null 2>&1; then
_c_ok "ISO tooling present"
else
_c_fail "genisoimage or xorriso required to build seed ISOs"
fi
have_cmd smbclient || _c_fail "smbclient required (apt install smbclient): site sync and install finalize"
have_cmd python3 || _c_fail "python3 required to read the guest agent output"
# participant Kali clones
local kali_count=${KALI_COUNT:-0}
if (( kali_count > 0 )); then
command -v 7z >/dev/null 2>&1 || _c_warn "7z missing: apt install p7zip-full (Kali image extraction)"
command -v pveum >/dev/null 2>&1 || _c_fail "pveum missing (participant accounts)"
local base=${KALI_IP_BASE:-41}
if (( base + kali_count - 1 > 99 )); then
_c_warn "KALI_IP_BASE=${base} with ${kali_count} guests reaches into the DHCP pool (100-200)"
else
_c_ok "kali addresses 10.10.10.${base} .. 10.10.10.$(( base + kali_count - 1 ))"
fi
local vm_ram need_mb mem_mb
vm_ram=$(awk '{s+=$3} END{print s+0}' <<<"$VMS")
need_mb=$(( vm_ram + kali_count * ${KALI_RAM:-3072} ))
mem_mb=$(awk '/MemTotal/{print int($2/1024)}' /proc/meminfo)
if (( need_mb + 2048 > mem_mb )); then
_c_warn "configured RAM ${need_mb} MB + 2 GB host overhead exceeds ${mem_mb} MB (lower KALI_COUNT or KALI_RAM)"
else
_c_ok "RAM budget ${need_mb} MB of ${mem_mb} MB"
fi
fi
}
# ------------------------------------------------------------------ lifecycle
backend_running() {
local vmid
vmid=$(pve_vmid "$1") || return 1
pve_running "$vmid"
}
backend_create_disk() {
local name=$1 dry=${2:-0}
local i vmid ram disk vcpu seed win mac
i=$(vm_index "$name") || die "unknown vm: $name"
vmid=$(pve_vmid "$name")
ram=${VM_RAM[$i]}; disk=${VM_DISK[$i]}; vcpu=${VM_VCPU[$i]}
seed="$SEED_DIR/${name}-seed.iso"
win=$WINDOWS_ISO
mac=$(qemu_mac_for "${VM_IPS[$i]}")
if pve_exists "$vmid"; then
ok "$(printf '%-6s vm %s already exists' "$name" "$vmid")"
return 0
fi
[[ -f $seed ]] || (( dry )) || die "missing seed ISO for $name (run ./lab.sh seeds)"
[[ -f $win ]] || (( dry )) || die "missing Windows ISO: $win (run ./lab.sh isos)"
local args=(
"$vmid"
--name "norbourg-$name"
--memory "$ram" --cores "$vcpu" --sockets 1
--machine "$PVE_MACHINE" --bios "$PVE_BIOS" --ostype "$PVE_OSTYPE" --cpu "$PVE_CPU"
--net0 "${PVE_NET_MODEL},bridge=${PVE_BRIDGE},macaddr=${mac}"
--sata0 "${PVE_STORAGE_DISKS}:${disk}"
--ide2 "${PVE_STORAGE_ISO}:iso/$(basename "$win"),media=cdrom"
--ide0 "${PVE_STORAGE_ISO}:iso/$(basename "$seed"),media=cdrom"
--boot "order=ide2;ide0"
--onboot 0
)
(( PVE_AGENT )) && args+=( --agent enabled=1 )
# virtio-win carries the QEMU guest agent that provisioning talks to.
if [[ -f $VIRTIO_ISO ]]; then
args+=( --ide3 "${PVE_STORAGE_ISO}:iso/$(basename "$VIRTIO_ISO"),media=cdrom" )
else
warn "virtio-win.iso missing: the guest agent cannot be installed (run ./lab.sh isos)"
fi
if (( dry )); then
info " + qm create ${args[*]}"
return 0
fi
qm create "${args[@]}" || { fail "qm create failed for $name"; return 1; }
ok "$(printf '%-6s vm %s created (%sG on %s)' "$name" "$vmid" "$disk" "$PVE_STORAGE_DISKS")"
}
backend_launch() {
local name=$1 mode=${2:-run} dry=${3:-0}
local vmid
vmid=$(pve_vmid "$name")
if (( dry )); then
info " + qm start $vmid"
return 0
fi
pve_running "$vmid" && { info " $name already running"; return 0; }
if pve_is_template "$vmid"; then
fail "$name is a template, not a working VM (./lab.sh destroy && ./lab.sh build)"
return 1
fi
if ! pve_exists "$vmid"; then
local tpl
tpl=$(pve_template_vmid "$name")
pve_exists "$tpl" || { fail "$name has no VM and no template (run ./lab.sh build)"; return 1; }
qm clone "$tpl" "$vmid" --name "norbourg-$name" --full 1 >/dev/null \
|| { fail "qm clone failed for $name"; return 1; }
ok "$(printf '%-6s cloned from template %s' "$name" "$tpl")"
fi
qm start "$vmid" >/dev/null || { fail "qm start failed for $name"; return 1; }
ok "$(printf '%-6s started (vm %s)' "$name" "$vmid")"
}
backend_stop() {
local name=$1 vmid
vmid=$(pve_vmid "$name")
pve_running "$vmid" || { info " $name already stopped"; return 0; }
qm shutdown "$vmid" --timeout 90 >/dev/null 2>&1 || true
if pve_running "$vmid"; then
warn "$name did not shut down cleanly, forcing stop"
qm stop "$vmid" >/dev/null 2>&1 || true
sleep 2
fi
ok "$name stopped"
}
backend_snapshot() {
local name=$1 vmid tpl
vmid=$(pve_vmid "$name")
tpl=$(pve_template_vmid "$name")
pve_running "$vmid" && { fail "$name is still running"; return 1; }
pve_exists "$vmid" || { fail "$name has no VM to freeze"; return 1; }
# The working VM keeps its id; the baseline is an independent full clone
# converted to a template, so reset can always recreate the working VM.
if pve_exists "$tpl"; then
qm destroy "$tpl" --purge 1 >/dev/null 2>&1 || true
fi
qm clone "$vmid" "$tpl" --name "norbourg-${name}-tpl" --full 1 >/dev/null \
|| { fail "qm clone failed for $name"; return 1; }
qm template "$tpl" >/dev/null || { fail "qm template failed for $name"; return 1; }
ok "$(printf '%-6s frozen as template %s' "$name" "$tpl")"
}
# `save` commits the current state into the baseline; same operation here.
backend_commit() { backend_snapshot "$@"; }
backend_has_baseline() { pve_exists "$(pve_template_vmid "$1")"; }
backend_reset() {
local name=$1 vmid tpl
vmid=$(pve_vmid "$name")
tpl=$(pve_template_vmid "$name")
pve_running "$vmid" && backend_stop "$name" >/dev/null 2>&1 || true
pve_exists "$tpl" || { fail "$name has no template — run ./lab.sh snapshot first"; return 1; }
pve_exists "$vmid" && qm destroy "$vmid" --purge 1 >/dev/null 2>&1
qm clone "$tpl" "$vmid" --name "norbourg-$name" --full 1 >/dev/null \
|| { fail "qm clone failed for $name"; return 1; }
ok "$(printf '%-6s reverted from template %s' "$name" "$tpl")"
}
backend_destroy() {
local name=$1 vmid tpl
vmid=$(pve_vmid "$name")
tpl=$(pve_template_vmid "$name")
pve_running "$vmid" && backend_stop "$name" >/dev/null 2>&1 || true
if pve_exists "$vmid"; then
qm destroy "$vmid" --purge 1 >/dev/null 2>&1 || true
fi
if pve_exists "$tpl"; then
qm destroy "$tpl" --purge 1 >/dev/null 2>&1 || true
fi
ok "$name removed"
}
# ------------------------------------------------------------------ transport
# qm guest exec returns JSON; unwrap it without adding Python dependencies.
_qga() {
local name=$1; shift
local vmid
vmid=$(pve_vmid "$name")
qm guest exec "$vmid" --timeout "${QGA_TIMEOUT:-180}" -- "$@"
}
_qga_unwrap() {
python3 - "$1" <<'PY'
import json, sys
try:
data = json.loads(sys.argv[1])
except Exception:
print("could not parse guest agent output", file=sys.stderr)
sys.exit(2)
out = data.get("out", "").replace("\x00", "")
err = data.get("err", "").replace("\x00", "")
sys.stdout.write(out)
if err.strip():
sys.stderr.write(err)
sys.exit(int(data.get("exitcode", 0)))
PY
}
backend_ps() {
local name=$1 script=$2 json
json=$(_qga "$name" powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command "$script" 2>/dev/null) \
|| return 2
_qga_unwrap "$json"
}
backend_ready() {
local name=$1 timeout=${2:-300}
local deadline=$(( SECONDS + timeout )) vmid
vmid=$(pve_vmid "$name")
while (( SECONDS < deadline )); do
pve_running "$vmid" || { sleep 10; continue; }
if _qga "$name" cmd.exe /c exit >/dev/null 2>&1; then
return 0
fi
sleep 10
done
fail "$name: guest agent not answering (is qemu-ga installed? see C:\\norbourg\\bootstrap.log)"
return 1
}
backend_start() {
local name=$1 remote=$2
# Fail in seconds, not after the one-hour marker wait, when the seed
# payload never reached the guest. Only an explicit False is conclusive.
local exists
exists=$(backend_ps "$name" "Test-Path '${remote}'" 2>/dev/null | tr -d '[:space:]')
if [[ $exists == False ]]; then
fail "$name: ${remote} is missing — the seed payload was not copied"
return 1
fi
backend_ps "$name" "
Remove-Item -Force -ErrorAction SilentlyContinue '${remote}.done'
schtasks.exe /End /TN NorbourgStage 2>\$null | Out-Null
schtasks.exe /Delete /TN NorbourgStage /F 2>\$null | Out-Null
\$tr = 'powershell.exe -NoProfile -ExecutionPolicy Bypass -File \"${remote}\"'
schtasks.exe /Create /TN NorbourgStage /F /SC ONCE /ST 00:00 /RU SYSTEM /RL HIGHEST /TR \$tr | Out-Null
schtasks.exe /Run /TN NorbourgStage | Out-Null
"
}
backend_wait() {
local name=$1 remote=$2 timeout=${3:-1800}
local deadline=$(( SECONDS + timeout )) out
while (( SECONDS < deadline )); do
out=$(backend_ps "$name" "Test-Path '${remote}.done'" 2>/dev/null | tr -d '\r\n ')
if [[ $out == True ]]; then
backend_ps "$name" "Get-Content -Raw '${remote}.done'" 2>/dev/null | sed '/^$/d'
return 0
fi
sleep 10
done
return 3
}
# ------------------------------------------------------------------ peers
# Generate one WireGuard config per participant, plus the router's wg0.conf.
cmd_peers() {
local names=("$@")
(( ${#names[@]} )) || die "usage: ./lab.sh peers <name> [name...]"
have_cmd wg || die "wireguard-tools is required (apt install wireguard-tools)"
mkdir -p "$WG_DIR"
chmod 700 "$WG_DIR"
if [[ ! -f $WG_DIR/server.key ]]; then
( umask 077; wg genkey > "$WG_DIR/server.key" )
wg pubkey < "$WG_DIR/server.key" > "$WG_DIR/server.pub"
ok "server key generated"
fi
local endpoint=${WG_ENDPOINT:-}
if [[ -z $endpoint ]]; then
local iface ip
iface=$(ip route show default 2>/dev/null | awk '/default/{print $5; exit}')
ip=$(ip -4 -o addr show dev "${iface:-vmbr0}" 2>/dev/null | awk '{print $4}' | cut -d/ -f1 | head -1)
endpoint="${ip:-<LAN-IP>}:${WG_PORT}"
else
endpoint="${endpoint}:${WG_PORT}"
fi
local i name addr priv pub psk router_peers=""
local LAB_IFACE=${WG_LAB_IFACE:-eth1}
for i in "${!names[@]}"; do
name=${names[$i]}
addr="10.10.10.$(( 101 + i ))/32"
( umask 077; wg genkey > "$WG_DIR/${name}.key" )
wg pubkey < "$WG_DIR/${name}.key" > "$WG_DIR/${name}.pub"
( umask 077; wg genpsk > "$WG_DIR/${name}.psk" )
priv=$(<"$WG_DIR/${name}.key")
pub=$(<"$WG_DIR/${name}.pub")
psk=$(<"$WG_DIR/${name}.psk")
cat > "$WG_DIR/${name}.conf" <<CONF
[Interface]
PrivateKey = ${priv}
Address = ${addr}
DNS = ${LAB_DC_IP}
[Peer]
PublicKey = $(<"$WG_DIR/server.pub")
PresharedKey = ${psk}
Endpoint = ${endpoint}
AllowedIPs = ${LAB_SUBNET}
PersistentKeepalive = 25
CONF
chmod 600 "$WG_DIR/${name}.conf"
router_peers+="
[Peer]
# ${name}
PublicKey = ${pub}
PresharedKey = ${psk}
AllowedIPs = ${addr}"
ok "$(printf '%-10s %-16s %s' "$name" "${addr%/32}" "$WG_DIR/${name}.conf")"
done
cat > "$WG_DIR/wg0.conf" <<CONF
# Router VM — /etc/wireguard/wg0.conf, then: systemctl enable --now wg-quick@wg0
#
# The VM needs TWO interfaces:
# eth0 on vmbr0 (your LAN) — optional, for management
# eth1 on vmbr10 (the lab bridge) — give it 10.10.10.251/24
# wg0 is a /32 inside the lab subnet so it does not collide with those /24s:
# traffic to .250 goes through the tunnel, everything else through eth1.
# Adjust LAB_IFACE below if your lab NIC is not eth1.
[Interface]
Address = 10.10.10.250/32
ListenPort = ${WG_PORT}
PrivateKey = $(<"$WG_DIR/server.key")
PostUp = sysctl -w net.ipv4.ip_forward=1
PostUp = nft add rule inet filter forward iifname "wg0" oifname "${LAB_IFACE}" accept
PostUp = nft add rule inet filter forward iifname "${LAB_IFACE}" oifname "wg0" ct state established,related accept
PostDown = nft delete rule inet filter forward iifname "wg0" oifname "${LAB_IFACE}" accept
PostDown = nft delete rule inet filter forward iifname "${LAB_IFACE}" oifname "wg0" ct state established,related accept
${router_peers}
CONF
chmod 600 "$WG_DIR/wg0.conf"
printf '\n'
ok "peer configs in ${WG_DIR}"
info " router config: ${WG_DIR}/wg0.conf (address 10.10.10.250 on the lab bridge)"
}
# After a successful install, stop booting from the installer CD: otherwise
# every boot waits five seconds and a stray keypress re-enters Setup.
backend_finalize() {
local name=$1 vmid ip deadline
vmid=$(pve_vmid "$name")
ip=$(pve_ip "$name")
qm set "$vmid" --boot 'order=sata0' --delete ide2 >/dev/null 2>&1 || true
ok "$(printf '%-6s boots from disk (installer ISO detached)' "$name")"
# WinRM answers while the first-logon bootstrap is still running (it
# enables remoting early). Rebooting before stamp.txt exists would abort
# the agent install, so wait for the end marker first. SMB is already up
# and, unlike the agent, does not depend on vioser.
if have_cmd smbclient; then
deadline=$(( SECONDS + 300 ))
while (( SECONDS < deadline )); do
smbclient "//$ip/C\$" -W "$NETBIOS" -U "$LAB_USER%$LAB_ADMIN_PASSWORD" \
-c 'ls norbourg\stamp.txt' >/dev/null 2>&1 && break
sleep 5
done
else
warn "smbclient missing: cannot wait for the bootstrap marker, pausing 60 s"
sleep 60
fi
# The virtio-serial port appears on the next boot: the agent installed at
# first logon started before its device existed and never connected, so
# Proxmox reports "guest agent is not running". Reboot once and wait.
qm reboot "$vmid" >/dev/null 2>&1 || qm start "$vmid" >/dev/null 2>&1 || true
deadline=$(( SECONDS + 300 ))
while (( SECONDS < deadline )); do
if _qga "$name" cmd.exe /c exit >/dev/null 2>&1; then
ok "$(printf '%-6s guest agent answering' "$name")"
return 0
fi
sleep 5
done
warn "$name: guest agent still silent after the post-install reboot"
return 1
}
# ------------------------------------------------------------------ kali
# One attacker VM per participant. Configured through the QEMU guest agent
# (the Kali image ships it as a static unit, so Proxmox starts it), reached
# entirely through the Proxmox web console: no VPN, no client setup.
pve_node() { hostname -s; }
kali_template_vmid() { printf '%s' $(( KALI_VMID_BASE + 90 )); }
kali_vmid() { printf '%s' $(( KALI_VMID_BASE + $1 )); }
kali_ip() { printf '10.10.10.%s' $(( KALI_IP_BASE + $1 - 1 )); }
kali_tools_iso() { printf '%s/kali-tools.iso' "$SEED_DIR"; }
_px_kali_tools() {
local iso dir
iso=$(kali_tools_iso)
[[ -f $iso ]] && { ok "tool ISO present"; return 0; }
dir=$(mktemp -d)
cp "$CONTENT_DIR/scripts/wordlists/norbourg.txt" "$dir/"
cat > "$dir/README.txt" <<'EOF'
Outils de l'atelier Norbourg
============================
norbourg.txt : liste de mots ciblee, dimensionnee pour un cassage de
quelques secondes.
sudo mkdir -p /opt/norbourg/wordlists
sudo cp /media/cdrom/norbourg.txt /opt/norbourg/wordlists/
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"
}
_px_kali_template() {
local tpl archive work qcow
tpl=$(kali_template_vmid)
if pve_exists "$tpl"; then
pve_is_template "$tpl" && { ok "Kali template ${tpl} already exists"; return 0; }
die "vm ${tpl} exists but is not a template (remove it: qm destroy ${tpl})"
fi
have_cmd 7z || die "7z is required to extract the Kali image (apt install p7zip-full)"
archive="$LAB_ISO_CACHE/kali-qemu.7z"
if [[ ! -f $archive ]]; then
step "download Kali 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
step "extract"
work=$(mktemp -d)
( cd "$work" && 7z x -y "$archive" >/dev/null ) || { rm -rf "$work"; die "extraction failed"; }
qcow=$(find "$work" -maxdepth 2 -name '*.qcow2' -print -quit)
[[ -n $qcow ]] || { rm -rf "$work"; die "no qcow2 in the archive"; }
qm create "$tpl" --name norbourg-kali-base --memory 1024 --cores 1 \
--ostype l26 --net0 "e1000,bridge=${PVE_BRIDGE}" --agent enabled=1 >/dev/null
qm importdisk "$tpl" "$qcow" "$PVE_STORAGE_DISKS" >/dev/null 2>&1 \
|| die "qm importdisk failed"
local vol
vol=$(qm config "$tpl" | awk -F': ' '/^unused0:/{print $2; exit}')
[[ -n $vol ]] || die "imported disk was not registered as unused0"
qm set "$tpl" --sata0 "$vol" --boot order=sata0 >/dev/null \
|| die "could not attach the imported disk"
qm set "$tpl" --delete unused0 >/dev/null 2>&1 || true
qm template "$tpl" >/dev/null
rm -rf "$work"
ok "Kali template ${tpl} created"
}
# Deterministic address per participant, held by MAC on DC01.
_px_kali_reserve() {
local ip=$1 mac=$2 name=$3
backend_ps dc01 "
Import-Module DhcpServer
if (-not (Get-DhcpServerv4Reservation -ScopeId '10.10.10.0' -ErrorAction SilentlyContinue |
Where-Object { \$_.IPAddress -eq '${ip}' })) {
Add-DhcpServerv4Reservation -ScopeId '10.10.10.0' -IPAddress '${ip}' \
-ClientId '${mac}' -Name '${name}' -Description 'participant VM'
}
'reserved'
" >/dev/null 2>&1 || warn "could not reserve ${ip} on DC01"
}
_px_kali_configure() {
local vmid=$1 name=$2 ip=$3
local tmp b64 json out deadline=$(( SECONDS + 420 ))
while (( SECONDS < deadline )); do
qm guest exec "$vmid" --timeout 10 -- /bin/true >/dev/null 2>&1 && break
sleep 5
done
if ! qm guest exec "$vmid" --timeout 10 -- /bin/true >/dev/null 2>&1; then
warn "$name: guest agent not answering after 7 min"
return 1
fi
tmp=$(mktemp)
cat > "$tmp" <<'SCRIPT'
set -e
hostnamectl set-hostname __NAME__
systemctl enable --now ssh 2>/dev/null || true
mkdir -p /opt/norbourg/wordlists /mnt/tools
src=""
for c in /media/cdrom/norbourg.txt /media/cdrom0/norbourg.txt /mnt/tools/norbourg.txt; do
if [ -f "$c" ]; then src=$c; break; fi
done
if [ -z "$src" ]; then
mount -o ro /dev/sr0 /mnt/tools 2>/dev/null || true
if [ -f /mnt/tools/norbourg.txt ]; then src=/mnt/tools/norbourg.txt; fi
fi
if [ -n "$src" ]; then
cp "$src" /opt/norbourg/wordlists/
chmod 644 /opt/norbourg/wordlists/norbourg.txt
umount /mnt/tools 2>/dev/null || true
fi
if ip -4 -br addr show | grep -q '10\.10\.10\.'; then echo NET_OK; else echo NET_FAIL; fi
if getent hosts dc01.norbourg.lab >/dev/null; then echo DNS_OK; else echo DNS_FAIL; fi
wc -l < /opt/norbourg/wordlists/norbourg.txt 2>/dev/null || echo 0
SCRIPT
sed -i "s|__NAME__|${name}|" "$tmp"
b64=$(base64 -w0 < "$tmp")
rm -f "$tmp"
json=$(qm guest exec "$vmid" --timeout 240 -- /bin/bash -c \
"echo ${b64} | base64 -d > /tmp/norbourg-setup.sh; bash /tmp/norbourg-setup.sh" 2>/dev/null) || {
warn "$name: setup script failed"; return 1; }
out=$(printf '%s' "$json" | python3 -c 'import json,sys; print(json.load(sys.stdin).get("out",""))' 2>/dev/null)
if [[ $out == *NET_OK* && $out == *DNS_OK* ]]; then
ok "$(printf '%-12s %-14s ready' "$name" "$ip")"
else
warn "$name: network or DNS check failed (${out//$'\n'/ })"
fi
}
_px_kali_create() {
local i=$1 vmid ip name mac
vmid=$(kali_vmid "$i")
ip=$(kali_ip "$i")
name="kali-$(printf '%02d' "$i")"
mac=$(qemu_mac_for "$ip")
if pve_exists "$vmid"; then
if pve_running "$vmid"; then
ok "$(printf '%-12s exists (vm %s, running)' "$name" "$vmid")"
elif qm start "$vmid" >/dev/null 2>&1; then
ok "$(printf '%-12s started (vm %s)' "$name" "$vmid")"
_px_kali_configure "$vmid" "$name" "$ip" || true
else
fail "$name: could not start vm $vmid"
fi
return 0
fi
local full=0
(( KALI_LINKED_CLONE )) || full=1
if ! qm clone "$(kali_template_vmid)" "$vmid" --name "norbourg-${name}" --full "$full" >/dev/null 2>&1; then
if (( full == 0 )); then
# dir/qcow2 storage cannot host linked clones
warn "linked clone refused by the storage, copying the disk instead"
qm clone "$(kali_template_vmid)" "$vmid" --name "norbourg-${name}" --full 1 >/dev/null \
|| { fail "$name: clone failed"; return 1; }
else
fail "$name: clone failed"
return 1
fi
fi
qm set "$vmid" \
--memory "$KALI_RAM" --cores "$KALI_VCPU" \
--net0 "e1000,bridge=${PVE_BRIDGE},macaddr=${mac}" \
--agent enabled=1 >/dev/null
if [[ -f $(kali_tools_iso) ]]; then
qm set "$vmid" --ide2 "${PVE_STORAGE_ISO}:iso/$(basename "$(kali_tools_iso)")",media=cdrom >/dev/null
fi
_px_kali_reserve "$ip" "${mac//:/-}" "$name"
qm start "$vmid" >/dev/null || { fail "$name: start failed"; return 1; }
ok "$(printf '%-12s started (vm %s, %s)' "$name" "$vmid" "$ip")"
_px_kali_configure "$vmid" "$name" "$ip" || true
}
cmd_kali() {
local action=${1:-} count=${KALI_COUNT:-5} i
case $action in
install)
_px_kali_tools
_px_kali_template
if ! backend_running dc01; then
warn "dc01 is not running: clones will start without their reserved address"
warn "run ./lab.sh up first, then ./lab.sh kali configure"
fi
for i in $(seq 1 "$count"); do _px_kali_create "$i"; done
printf '\n'
ok "${count} Kali VM(s) ready — share the console URLs: ./lab.sh users <name>..."
;;
up)
for i in $(seq 1 "$count"); do _px_kali_create "$i"; done
;;
down)
for i in $(seq 1 "$count"); do
local vmid; vmid=$(kali_vmid "$i")
pve_exists "$vmid" || continue
qm shutdown "$vmid" --timeout 60 >/dev/null 2>&1 || qm stop "$vmid" >/dev/null 2>&1 || true
ok "kali-$(printf '%02d' "$i") stopped"
done
;;
status)
for i in $(seq 1 "$count"); do
local vmid; vmid=$(kali_vmid "$i")
if pve_exists "$vmid"; then
printf '%-10s vm %-6s %-12s %s\n' "kali-$(printf '%02d' "$i")" "$vmid" "$(kali_ip "$i")" "$(qm status "$vmid" 2>/dev/null | awk '{print $2}')"
fi
done
;;
configure)
for i in $(seq 1 "$count"); do
local vmid; vmid=$(kali_vmid "$i")
pve_exists "$vmid" || continue
pve_running "$vmid" || qm start "$vmid" >/dev/null 2>&1 || true
_px_kali_configure "$vmid" "kali-$(printf '%02d' "$i")" "$(kali_ip "$i")" || true
done
;;
reset)
for i in $(seq 1 "$count"); do
local vmid; vmid=$(kali_vmid "$i")
if pve_exists "$vmid"; then
qm stop "$vmid" >/dev/null 2>&1 || true
qm destroy "$vmid" --purge 1 >/dev/null 2>&1 || true
fi
_px_kali_create "$i"
done
;;
*)
info "usage: ./lab.sh kali install|up|down|status|configure|reset"
return 2
;;
esac
}
# Called by cmd_destroy on platforms with extra VMs.
platform_destroy_extra() {
local count=${KALI_COUNT:-5} i vmid found=0
for i in $(seq 1 "$count"); do
vmid=$(kali_vmid "$i")
pve_exists "$vmid" || continue
qm stop "$vmid" >/dev/null 2>&1 || true
qm destroy "$vmid" --purge 1 >/dev/null 2>&1 || true
found=1
done
vmid=$(kali_template_vmid)
if pve_exists "$vmid"; then
qm destroy "$vmid" --purge 1 >/dev/null 2>&1 || true
found=1
fi
(( found )) && ok "participant Kali VMs and template removed"
return 0
}
# ------------------------------------------------------------------ users
# A Proxmox account per participant, scoped to their own Kali VM, plus the
# console URL to hand out.
cmd_users() {
local names=("$@") i name pw vmid node host
(( ${#names[@]} )) || die "usage: ./lab.sh users <name> [name...]"
node=$(pve_node)
host=${PVE_WEB_HOST:-$(hostname -f 2>/dev/null || hostname)}
printf '\n%-12s %-15s %-14s %s\n' "USER" "PASSWORD" "KALI" "CONSOLE URL"
for i in "${!names[@]}"; do
name=${names[$i]}
vmid=$(kali_vmid $(( i + 1 )))
if ! pve_exists "$vmid"; then
warn "$name: no Kali VM at id ${vmid} (run ./lab.sh kali install --count ${#names[@]})"
continue
fi
if ! pveum user list --output-format json 2>/dev/null | tr -d ' \n' \
| grep -q "\"userid\":\"${name}@pve\""; then
pw=$(openssl rand -base64 18 | tr -dc 'A-Za-z0-9' | head -c 14)
pveum user add "${name}@pve" --password "$pw" --comment "Norbourg lab" >/dev/null \
|| die "could not create ${name}@pve"
else
pw="(unchanged)"
fi
pveum acl modify "/vms/${vmid}" --users "${name}@pve" --roles PVEVMUser >/dev/null 2>&1 \
|| warn "ACL failed for ${name} on vm ${vmid}"
printf '%-12s %-15s %-14s %s\n' "$name" "$pw" "vm ${vmid}" \
"https://${host}:8006/?console=kvm&novnc=1&vmid=${vmid}&node=${node}&resize=scale"
done
printf '\n'
info "Guest credentials inside Kali: kali / kali"
}
# ------------------------------------------------------------------ status
# The shared table reads a qemu pidfile and a VNC display; neither exists
# here, so show the Proxmox view instead.
cmd_status() {
local i name ip vmid state role n
printf '\n%s%-7s %-14s %-7s %-9s %s%s\n' "$C_BOLD" VM IP VMID STATE ROLE "$C_RESET"
for i in "${!VM_NAMES[@]}"; do
name=${VM_NAMES[$i]}; ip=${VM_IPS[$i]}; role=${VM_ROLES[$i]}
vmid=$(pve_vmid "$name")
if ! pve_exists "$vmid"; then state="absent"
elif pve_running "$vmid"; then state="running"
else state="stopped"; fi
printf '%-7s %-14s %-7s %-9s %s\n' "$name" "$ip" "$vmid" "$state" "$role"
done
printf '\n'
for i in "${!VM_NAMES[@]}"; do
name=${VM_NAMES[$i]}; ip=${VM_IPS[$i]}
pve_running "$(pve_vmid "$name")" || continue
if tcp_open "$ip" 5985; then state="yes"; else state="no"; fi
printf ' %-6s winrm: %s\n' "$name" "$state"
done
for n in $(seq 1 "${KALI_COUNT:-0}"); do
vmid=$(kali_vmid "$n")
pve_exists "$vmid" || continue
if pve_running "$vmid"; then state="running"; else state="stopped"; fi
printf ' %-10s vm %-6s %-12s %s\n' "kali-$(printf '%02d' "$n")" "$vmid" "$(kali_ip "$n")" "$state"
done
printf '\n'
}
cmd_vnc() {
local name=${1:-} vmid node host
[[ -n $name ]] || die "usage: ./lab.sh vnc <vm> (VMs: ${VM_NAMES[*]})"
vmid=$(pve_vmid "$name") || die "unknown vm: $name"
node=$(pve_node)
host=${PVE_WEB_HOST:-$(hostname -f 2>/dev/null || hostname)}
info "console: https://${host}:8006/?console=kvm&novnc=1&vmid=${vmid}&node=${node}&resize=scale"
info "or from this host: qm terminal ${vmid} (Linux guests only)"
}