Split into qemu and proxmox platforms over a shared content tree
platforms/qemu and platforms/proxmox each have their own lab.sh and lab.conf; content/ holds everything shared (roles, seed, site, helpers). The dispatcher, preflight and command implementations are common and take platform differences from the backend. Proxmox backend: qm create with q35/SATA/e1000, ISOs and seed ISOs in an ISO storage, provisioning over qm guest exec (no Python packages needed on the host), template + clone for reset, and peers/ to emit WireGuard configs. The role scripts now ride on the seed ISO, so provisioning transfers nothing. build-bundle.sh produces a self-contained tarball per platform, for hosts that cannot reach the git server. Both configs are generic: no absolute path from this machine remains.
This commit is contained in:
Executable
+52
@@ -0,0 +1,52 @@
|
||||
#!/usr/bin/env bash
|
||||
# kali-setup.sh — prepare a participant's Kali for the workshop.
|
||||
#
|
||||
# ./scripts/kali-setup.sh
|
||||
#
|
||||
# Installs the toolset used in the lab and copies the targeted wordlist to
|
||||
# /opt/norbourg/wordlists/. Safe to run twice.
|
||||
set -euo pipefail
|
||||
|
||||
HERE=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)
|
||||
WORDLIST="$HERE/wordlists/norbourg.txt"
|
||||
|
||||
info() { printf '[*] %s\n' "$*"; }
|
||||
ok() { printf '[ok] %s\n' "$*"; }
|
||||
warn() { printf '[!] %s\n' "$*" >&2; }
|
||||
|
||||
if [[ $EUID -eq 0 ]]; then
|
||||
SUDO=""
|
||||
else
|
||||
SUDO="sudo"
|
||||
fi
|
||||
|
||||
info "installing packages (this takes a few minutes)"
|
||||
$SUDO apt-get update -qq || warn "apt-get update failed, continuing"
|
||||
$SUDO DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \
|
||||
netexec impacket-scripts bloodyad evil-winrm bloodhound.py \
|
||||
hashcat seclists smbclient dnsutils python3-pip \
|
||||
|| warn "some packages failed to install, see the list below"
|
||||
|
||||
info "installing the lab wordlist"
|
||||
$SUDO mkdir -p /opt/norbourg/wordlists
|
||||
$SUDO cp "$WORDLIST" /opt/norbourg/wordlists/norbourg.txt
|
||||
$SUDO chmod 0644 /opt/norbourg/wordlists/norbourg.txt
|
||||
|
||||
info "checking the toolset"
|
||||
check() {
|
||||
if command -v "$1" >/dev/null 2>&1; then
|
||||
ok "$1"
|
||||
else
|
||||
warn "$1 missing"
|
||||
fi
|
||||
}
|
||||
for tool in nxc netexec evil-winrm hashcat smbclient dig; do
|
||||
check "$tool"
|
||||
done
|
||||
command -v impacket-GetUserSPNs >/dev/null 2>&1 && ok "impacket-GetUserSPNs" \
|
||||
|| warn "impacket scripts missing (impacket-scripts)"
|
||||
command -v bloodhound-python >/dev/null 2>&1 && ok "bloodhound-python" \
|
||||
|| warn "bloodhound-python missing"
|
||||
|
||||
printf '\n'
|
||||
ok "done. Lab access is configured separately: see docs/prerequis.md"
|
||||
Executable
+173
@@ -0,0 +1,173 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Minimal WinRM client for the Norbourg lab.
|
||||
|
||||
Runs PowerShell on a guest over NTLM/HTTP. Credentials come from the
|
||||
environment so the password never lands in a command line.
|
||||
|
||||
labwinrm.py HOST ps "<powershell>" run, print output, exit with status
|
||||
labwinrm.py HOST put LOCAL REMOTE upload a file (base64, chunked)
|
||||
labwinrm.py HOST start REMOTE [LOG] start a script detached
|
||||
labwinrm.py HOST wait REMOTE [TIMEOUT] wait for REMOTE.done to appear
|
||||
labwinrm.py HOST get REMOTE read a text file
|
||||
|
||||
Exit codes: 0 ok, 1 command failed, 2 connection/auth problem, 3 timeout.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
try:
|
||||
import winrm
|
||||
except ImportError: # pragma: no cover
|
||||
print("pywinrm is not installed: python3 -m pip install --user pywinrm", file=sys.stderr)
|
||||
raise SystemExit(2)
|
||||
|
||||
CHUNK = 1500 # -EncodedCommand is UTF-16, so 1500 chars becomes ~4000 base64 chars
|
||||
|
||||
|
||||
def connect(host: str, user: str, password: str, port: int) -> "winrm.Session":
|
||||
return winrm.Session(
|
||||
f"{host}:{port}",
|
||||
auth=(user, password),
|
||||
transport="ntlm",
|
||||
server_cert_validation="ignore",
|
||||
operation_timeout_sec=40,
|
||||
read_timeout_sec=90,
|
||||
)
|
||||
|
||||
|
||||
def ps(session, script: str) -> tuple[int, str, str]:
|
||||
# Progress records come back as CLIXML noise on stderr.
|
||||
result = session.run_ps("$ProgressPreference = 'SilentlyContinue';\n" + script)
|
||||
return (
|
||||
result.status_code,
|
||||
result.std_out.decode("utf-8", "replace"),
|
||||
result.std_err.decode("utf-8", "replace"),
|
||||
)
|
||||
|
||||
|
||||
def upload(session, local: str, remote: str) -> None:
|
||||
payload = base64.b64encode(open(local, "rb").read()).decode("ascii")
|
||||
parent = remote.rsplit("\\", 1)[0]
|
||||
rc, _, err = ps(session, f"New-Item -ItemType Directory -Force -Path '{parent}' | Out-Null")
|
||||
if rc != 0:
|
||||
raise SystemExit(f"mkdir failed: {err}")
|
||||
|
||||
tmp = remote + ".b64"
|
||||
ps(session, f"Remove-Item -Force -ErrorAction SilentlyContinue '{tmp}'")
|
||||
for offset in range(0, len(payload), CHUNK):
|
||||
piece = payload[offset:offset + CHUNK]
|
||||
rc, _, err = ps(session, f"Add-Content -NoNewline -Path '{tmp}' -Value '{piece}'")
|
||||
if rc != 0:
|
||||
raise SystemExit(f"upload failed at offset {offset}: {err}")
|
||||
|
||||
# -Encoding ASCII keeps PowerShell 5.1 from writing UTF-16.
|
||||
rc, _, err = ps(
|
||||
session,
|
||||
f"$b = Get-Content -Raw '{tmp}'; "
|
||||
f"[IO.File]::WriteAllBytes('{remote}', [Convert]::FromBase64String($b)); "
|
||||
f"Remove-Item -Force '{tmp}'",
|
||||
)
|
||||
if rc != 0:
|
||||
raise SystemExit(f"decode failed: {err}")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("host")
|
||||
ap.add_argument("action", choices=["ps", "put", "start", "wait", "get"])
|
||||
ap.add_argument("args", nargs="*")
|
||||
ap.add_argument("--user", default=os.environ.get("LAB_USER", "Administrator"))
|
||||
ap.add_argument("--password", default=os.environ.get("LAB_PASSWORD"))
|
||||
ap.add_argument("--port", type=int, default=5985)
|
||||
opts = ap.parse_args()
|
||||
|
||||
if not opts.password:
|
||||
print("LAB_PASSWORD is not set", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
session = connect(opts.host, opts.user, opts.password, opts.port)
|
||||
|
||||
try:
|
||||
if opts.action == "ps":
|
||||
script = " ".join(opts.args)
|
||||
rc, out, err = ps(session, script)
|
||||
sys.stdout.write(out)
|
||||
if err.strip():
|
||||
sys.stderr.write(err)
|
||||
return 0 if rc == 0 else 1
|
||||
|
||||
if opts.action == "put":
|
||||
local, remote = opts.args
|
||||
upload(session, local, remote)
|
||||
return 0
|
||||
|
||||
if opts.action == "start":
|
||||
remote = opts.args[0]
|
||||
done = remote + ".done"
|
||||
# A Start-Process child dies with the WinRM shell. A scheduled task
|
||||
# runs under the Task Scheduler service and survives the disconnect,
|
||||
# which matters for anything that reboots the guest.
|
||||
ps(session, f"Remove-Item -Force -ErrorAction SilentlyContinue '{done}'")
|
||||
# A task left over from an interrupted run stays in "Running" and
|
||||
# blocks the next one; clear it first.
|
||||
ps(session, "schtasks.exe /End /TN NorbourgStage 2>$null | Out-Null; "
|
||||
"schtasks.exe /Delete /TN NorbourgStage /F 2>$null | Out-Null")
|
||||
task = (
|
||||
'$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; "
|
||||
"schtasks.exe /Run /TN NorbourgStage"
|
||||
)
|
||||
rc, out, err = ps(session, task)
|
||||
if rc != 0:
|
||||
print(f"{out}\n{err}", file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
if opts.action == "wait":
|
||||
remote = opts.args[0]
|
||||
timeout = int(opts.args[1]) if len(opts.args) > 1 else 1800
|
||||
done = remote + ".done"
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
rc, out, _ = ps(session, f"Test-Path '{done}'")
|
||||
if out.strip().lower() == "true":
|
||||
rc, out, _ = ps(session, f"Get-Content -Raw '{done}'")
|
||||
print(out.strip())
|
||||
return 0
|
||||
except Exception as exc: # noqa: BLE001 - reboots are expected
|
||||
print(f"retrying ({type(exc).__name__})", file=sys.stderr)
|
||||
try:
|
||||
session = connect(opts.host, opts.user, opts.password, opts.port)
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(10)
|
||||
return 3
|
||||
|
||||
if opts.action == "get":
|
||||
rc, out, err = ps(session, f"Get-Content -Raw '{opts.args[0]}'")
|
||||
sys.stdout.write(out)
|
||||
if rc != 0:
|
||||
sys.stderr.write(err)
|
||||
return 1
|
||||
return 0
|
||||
except winrm.exceptions.WinRMTransportError as exc:
|
||||
print(f"transport: {exc}", file=sys.stderr)
|
||||
return 2
|
||||
except Exception as exc: # noqa: BLE001 - surface anything else as a connection issue
|
||||
print(f"{type(exc).__name__}: {exc}", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,208 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Assemble the lab's web root from the archived 2002 site.
|
||||
|
||||
Input : site-src/norbourg-2002/ (Wayback mirror, 46 pages)
|
||||
site-src/norbourg-static/ (rebuilt home page + repaired images)
|
||||
Output : web/site/ (served by IIS on FS01)
|
||||
|
||||
The mirror was captured for offline reading, not for hosting: it keeps absolute
|
||||
links to web.archive.org, points at a dead hit counter, and ships crawler
|
||||
metadata that would tell students they are looking at an archive. This script
|
||||
removes all of that and fails if a local reference is left dangling.
|
||||
|
||||
Usage:
|
||||
python3 scripts/prepare_site.py [--warn-only] [--quiet]
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
CONTENT = Path(__file__).resolve().parent.parent
|
||||
REPO = CONTENT.parent
|
||||
SRC_MIRROR = CONTENT / "site-src" / "norbourg-2002"
|
||||
SRC_HOME = CONTENT / "site-src" / "norbourg-static"
|
||||
OUT = CONTENT / "web" / "site"
|
||||
|
||||
# Files that exist only for the archivist.
|
||||
DROP_FILES = {"MIRROR.txt", "_index.json"}
|
||||
|
||||
# https://web.archive.org/web/20020929201450/http://norbourg.com/pdfs/s0102.pdf
|
||||
WAYBACK = re.compile(
|
||||
r"""https?://web\.archive\.org/web/\d+/ # capture timestamp
|
||||
(?:https?://)?(?:www\.)?norbourg\.com # original host
|
||||
(/[^"'\s>]*)""",
|
||||
re.VERBOSE | re.IGNORECASE,
|
||||
)
|
||||
|
||||
# The 2002 hit counter (/webstat/webstat.exe) was not archived: 42 pages point
|
||||
# at it and would render a broken-image icon.
|
||||
HITCOUNTER_TAG = re.compile(r"<img[^>]*webstat[^>]*>", re.IGNORECASE)
|
||||
HITCOUNTER_ANY = re.compile(r"""["']/webstat/webstat\.exe["']""", re.IGNORECASE)
|
||||
|
||||
# In-universe breadcrumb for the SMB pivot; injected into the home page only.
|
||||
HOME_HINT = (
|
||||
"\n<!-- TI: penser a migrer \\\\FS01\\Public vers le nouveau serveur "
|
||||
"avant la fermeture du site -->\n"
|
||||
)
|
||||
|
||||
LINK_ATTR = re.compile(r"""(?:href|src)\s*=\s*["']([^"']+)["']""", re.IGNORECASE)
|
||||
HREF_ATTR = re.compile(r"""href\s*=\s*["']([^"']+)["']""", re.IGNORECASE)
|
||||
SKIP_PREFIX = ("http://", "https://", "mailto:", "javascript:", "data:", "#", "ftp://")
|
||||
|
||||
|
||||
def decode(raw: bytes) -> str:
|
||||
# The mirror is ISO-8859-1 with CRLF; round-trip through latin-1 so nothing
|
||||
# gets mangled and the served bytes stay identical to the original.
|
||||
return raw.decode("latin-1")
|
||||
|
||||
|
||||
def encode(text: str) -> bytes:
|
||||
return text.encode("latin-1", errors="replace")
|
||||
|
||||
|
||||
def rewrite_links(text: str, out_root: Path, page_dir: Path) -> tuple[str, int]:
|
||||
"""Point archive links back at local files, or neutralise them."""
|
||||
changed = 0
|
||||
|
||||
def replace(match: re.Match[str]) -> str:
|
||||
nonlocal changed
|
||||
path = match.group(1).split("?")[0].split("#")[0]
|
||||
candidate = out_root / path.lstrip("/")
|
||||
if candidate.is_file():
|
||||
changed += 1
|
||||
return path
|
||||
changed += 1
|
||||
return "#"
|
||||
|
||||
text = WAYBACK.sub(replace, text)
|
||||
text = HITCOUNTER_TAG.sub("", text)
|
||||
text = HITCOUNTER_ANY.sub('"#"', text)
|
||||
return text, changed
|
||||
|
||||
|
||||
def local_links(text: str, page: Path, out_root: Path) -> list[str]:
|
||||
"""Return local references that do not resolve to a file."""
|
||||
missing: list[str] = []
|
||||
for ref in LINK_ATTR.findall(text):
|
||||
if ref.lower().startswith(SKIP_PREFIX):
|
||||
continue
|
||||
target = ref.split("?")[0].split("#")[0]
|
||||
if not target:
|
||||
continue
|
||||
if target.startswith("/"):
|
||||
resolved = out_root / target.lstrip("/")
|
||||
else:
|
||||
resolved = (page.parent / target).resolve()
|
||||
if not resolved.exists():
|
||||
missing.append(ref)
|
||||
return missing
|
||||
|
||||
|
||||
def neutralize_missing(text: str, page: Path, out_root: Path) -> tuple[str, int]:
|
||||
"""Turn hrefs that resolve to nothing into anchors.
|
||||
|
||||
The mirror never captured a few ASP pages and PDFs. A dead link is better
|
||||
than a 404 in a lab where students click everything, and it matches how the
|
||||
archive links were already rewritten to '#'.
|
||||
"""
|
||||
changed = 0
|
||||
|
||||
def replace(match: re.Match[str]) -> str:
|
||||
nonlocal changed
|
||||
ref = match.group(1)
|
||||
if ref.lower().startswith(SKIP_PREFIX):
|
||||
return match.group(0)
|
||||
target = ref.split("?")[0].split("#")[0]
|
||||
if not target:
|
||||
return match.group(0)
|
||||
resolved = (out_root / target.lstrip("/")) if target.startswith("/") \
|
||||
else (page.parent / target).resolve()
|
||||
if resolved.exists():
|
||||
return match.group(0)
|
||||
changed += 1
|
||||
return 'href="#"'
|
||||
|
||||
return HREF_ATTR.sub(replace, text), changed
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--warn-only", action="store_true",
|
||||
help="report dangling references but exit 0")
|
||||
parser.add_argument("--quiet", action="store_true")
|
||||
args = parser.parse_args()
|
||||
|
||||
if not SRC_MIRROR.is_dir():
|
||||
print(f"error: mirror not found: {SRC_MIRROR}", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
if OUT.exists():
|
||||
shutil.rmtree(OUT)
|
||||
shutil.copytree(SRC_MIRROR, OUT)
|
||||
|
||||
# Rebuilt home page and repaired images replace the mirror's versions.
|
||||
home = SRC_HOME / "index.html"
|
||||
if home.is_file():
|
||||
shutil.copy2(home, OUT / "index.html")
|
||||
if (SRC_HOME / "images").is_dir():
|
||||
shutil.copytree(SRC_HOME / "images", OUT / "images", dirs_exist_ok=True)
|
||||
|
||||
for name in DROP_FILES:
|
||||
target = OUT / name
|
||||
if target.exists():
|
||||
target.unlink()
|
||||
|
||||
pages = sorted(OUT.rglob("*.html"))
|
||||
rewritten = 0
|
||||
neutralized = 0
|
||||
for page in pages:
|
||||
text = decode(page.read_bytes())
|
||||
text, changed = rewrite_links(text, OUT, page.parent)
|
||||
rewritten += changed
|
||||
text, dead = neutralize_missing(text, page, OUT)
|
||||
neutralized += dead
|
||||
page.write_bytes(encode(text))
|
||||
|
||||
# Home-page breadcrumb: the only thing this script adds to the site itself.
|
||||
index = OUT / "index.html"
|
||||
if index.is_file():
|
||||
text = decode(index.read_bytes())
|
||||
if "FS01" not in text:
|
||||
marker = re.search(r"<body[^>]*>", text, re.IGNORECASE)
|
||||
if marker:
|
||||
text = text[: marker.end()] + HOME_HINT + text[marker.end():]
|
||||
else:
|
||||
text = HOME_HINT + text
|
||||
index.write_bytes(encode(text))
|
||||
|
||||
dangling: dict[str, list[str]] = {}
|
||||
for page in pages:
|
||||
missing = local_links(decode(page.read_bytes()), page, OUT)
|
||||
if missing:
|
||||
dangling[str(page.relative_to(OUT))] = sorted(set(missing))
|
||||
|
||||
if not args.quiet:
|
||||
total = sum(1 for _ in OUT.rglob("*") if _.is_file())
|
||||
print(f"assembled {OUT.relative_to(REPO)} ({total} files, {len(pages)} pages)")
|
||||
print(f"rewrote {rewritten} archive references")
|
||||
print(f"neutered {neutralized} link(s) with no archived target")
|
||||
if dangling:
|
||||
print(f"dangling {len(dangling)} page(s):")
|
||||
for name, refs in list(dangling.items())[:15]:
|
||||
print(f" {name}: {', '.join(refs[:4])}"
|
||||
+ (" ..." if len(refs) > 4 else ""))
|
||||
if len(dangling) > 15:
|
||||
print(f" ... and {len(dangling) - 15} more")
|
||||
|
||||
if dangling and not args.warn_only:
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user