Phase 5: AD role scripts, WinRM provisioning and lab wordlist
dc01 promotes the forest then runs a startup-scheduled post stage for OUs, users, groups, the SPN on svc_backup, pre-auth disabled on j.contractor, GenericAll over t.smith, the www A record, flags and advanced audit policy. fs01 installs IIS, shares the web root's public/ as \\FS01\Public and joins. ws01 joins, then adds WS Admins to local Administrators. provision uploads over WinRM, starts scripts detached, waits on a .done marker and survives the promotion reboot.
This commit is contained in:
@@ -0,0 +1,100 @@
|
|||||||
|
# Guide du participant
|
||||||
|
|
||||||
|
## Le contexte
|
||||||
|
|
||||||
|
Norbourg Services Financiers a fermé ses portes en 2005. Le serveur de fichiers, lui, n'a jamais
|
||||||
|
été mis au rancart : il tourne encore, avec son site Web de 2002, dans un coin du réseau. La
|
||||||
|
direction veut savoir ce qu'un attaquant pourrait y faire avant de confier la migration à un
|
||||||
|
sous-traitant.
|
||||||
|
|
||||||
|
Vous êtes ce sous-traitant. Votre mandat tient en une phrase : **obtenir les droits de Domain
|
||||||
|
Admin**.
|
||||||
|
|
||||||
|
## Votre objectif
|
||||||
|
|
||||||
|
Deux drapeaux à rapporter :
|
||||||
|
|
||||||
|
| Drapeau | Où | Ce qu'il prouve |
|
||||||
|
|---|---|---|
|
||||||
|
| `user.txt` | sur un poste de travail | vous avez compromis une machine |
|
||||||
|
| `root.txt` | sur le contrôleur de domaine | vous contrôlez le domaine |
|
||||||
|
|
||||||
|
Un drapeau a le format `NORBOURG{...}`. Notez-le et gardez-le pour le débriefing.
|
||||||
|
|
||||||
|
## Règles d'engagement
|
||||||
|
|
||||||
|
- **Seulement `10.10.10.0/24`.** Ne touchez pas à `10.10.10.230` (l'hôte du laboratoire) ni à
|
||||||
|
quoi que ce soit sur `192.168.10.0/24`.
|
||||||
|
- **Pas de déni de service.** Pas de balayage agressif, pas de saturation, pas de `--flood`.
|
||||||
|
- **Pas de destruction.** Ne supprimez pas de comptes, ne réinitialisez pas de mots de passe dont
|
||||||
|
vous n'avez pas besoin, ne chiffrez rien.
|
||||||
|
- **Tout reste dans le laboratoire.** Aucune donnée ne sort du réseau.
|
||||||
|
- Si vous cassez quelque chose, dites-le : c'est un laboratoire, ça se répare, mais il faut le
|
||||||
|
savoir pour les autres.
|
||||||
|
|
||||||
|
## Méthodologie suggérée
|
||||||
|
|
||||||
|
1. **Reconnaissance** — quelles machines répondent, quels services écoutent.
|
||||||
|
2. **Énumération** — qu'est-ce que ces services racontent : partages, utilisateurs, pages Web.
|
||||||
|
3. **Point d'entrée** — trouver un premier identifiant valide.
|
||||||
|
4. **Élévation** — transformer un compte ordinaire en compte puissant.
|
||||||
|
5. **Déplacement latéral** — passer d'une machine à l'autre avec les droits obtenus.
|
||||||
|
6. **Compromission du domaine** — la cible finale.
|
||||||
|
|
||||||
|
Ne sautez pas d'étape. La plupart des impasses viennent d'une énumération bâclée, pas d'un
|
||||||
|
manque d'outil.
|
||||||
|
|
||||||
|
## Aide-mémoire
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# découverte
|
||||||
|
nmap -sn 10.10.10.0/24
|
||||||
|
nmap -sV -p- 10.10.10.10
|
||||||
|
|
||||||
|
# SMB / AD
|
||||||
|
netexec smb 10.10.10.0/24
|
||||||
|
netexec smb 10.10.10.10 -u '<user>' -p '<pass>' --shares
|
||||||
|
netexec smb 10.10.10.10 -u '<user>' -p '<pass>' --users
|
||||||
|
|
||||||
|
# Kerberos
|
||||||
|
impacket-GetUserSPNs norbourg.lab/<user>:<pass> -dc-ip 10.10.10.10 -request
|
||||||
|
|
||||||
|
# cassage
|
||||||
|
hashcat -m 13100 hash.txt /opt/norbourg/wordlists/norbourg.txt
|
||||||
|
hashcat -m 18200 hash.txt /opt/norbourg/wordlists/norbourg.txt
|
||||||
|
|
||||||
|
# mouvement latéral
|
||||||
|
netexec winrm 10.10.10.31 -u '<user>' -p '<pass>'
|
||||||
|
evil-winrm -i 10.10.10.31 -u '<user>' -p '<pass>'
|
||||||
|
|
||||||
|
# cartographie du domaine
|
||||||
|
bloodhound-python -d norbourg.lab -u '<user>' -p '<pass>' -ns 10.10.10.10 -c all
|
||||||
|
```
|
||||||
|
|
||||||
|
Les mots de passe du laboratoire se cassent en quelques secondes avec
|
||||||
|
`/opt/norbourg/wordlists/norbourg.txt`. Inutile de lancer `rockyou.txt` complet : vous perdriez
|
||||||
|
vingt minutes pour rien.
|
||||||
|
|
||||||
|
## Rappel terminal
|
||||||
|
|
||||||
|
Si vous n'êtes pas à l'aise en ligne de commande :
|
||||||
|
|
||||||
|
| Commande | Effet |
|
||||||
|
|---|---|
|
||||||
|
| `ls` | lister le dossier courant |
|
||||||
|
| `cd <dossier>` | entrer dans un dossier |
|
||||||
|
| `cat <fichier>` | afficher un fichier |
|
||||||
|
| `grep mot fichier` | chercher un mot |
|
||||||
|
| `commande \| grep mot` | filtrer la sortie d'une commande |
|
||||||
|
| `commande > fichier` | écrire la sortie dans un fichier |
|
||||||
|
| `Ctrl-C` | interrompre |
|
||||||
|
| `man <commande>` | documentation |
|
||||||
|
|
||||||
|
Une commande qui « ne fait rien » affiche souvent son erreur sur la sortie d'erreur : lisez-la.
|
||||||
|
|
||||||
|
## Si vous êtes bloqué
|
||||||
|
|
||||||
|
- Relisez la sortie de vos commandes : les outils d'énumération disent souvent quoi faire ensuite.
|
||||||
|
- Vérifiez votre configuration réseau (voir `prerequis.md`) : un `NXDOMAIN` n'est pas un serveur
|
||||||
|
mort, c'est un DNS mal pointé.
|
||||||
|
- Demandez un indice à l'instructeur : il en existe trois niveaux, du plus vague au plus direct.
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
# Prérequis — participants
|
||||||
|
|
||||||
|
À faire **avant** l'atelier. Comptez quinze minutes, dont la majeure partie consiste à
|
||||||
|
attendre que votre machine virtuelle démarre.
|
||||||
|
|
||||||
|
## Ce qu'il vous faut
|
||||||
|
|
||||||
|
- Une machine Kali Linux, en VM ou sur votre poste, branchée sur le même réseau que l'hôte du
|
||||||
|
laboratoire (`192.168.10.0/24`).
|
||||||
|
- Les droits `sudo` dans ce Kali.
|
||||||
|
- Rien d'autre : l'image fournie contient déjà tous les outils de l'atelier
|
||||||
|
(`netexec`, Impacket, BloodHound, hashcat, rockyou).
|
||||||
|
|
||||||
|
> Le laboratoire est isolé : une fois connecté, la résolution de noms vers Internet cesse de
|
||||||
|
> fonctionner. C'est normal et voulu. La section 5 explique comment revenir en arrière.
|
||||||
|
|
||||||
|
## 1. Route vers le laboratoire
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo ip route add 10.10.10.0/24 via 192.168.10.230
|
||||||
|
```
|
||||||
|
|
||||||
|
Pour que la route survive à un redémarrage, utilisez plutôt NetworkManager :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo nmcli con mod "<votre-connexion>" +ipv4.routes "10.10.10.0/24 192.168.10.230"
|
||||||
|
sudo nmcli con up "<votre-connexion>"
|
||||||
|
```
|
||||||
|
|
||||||
|
Remplacez `<votre-connexion>` par le nom affiché par `nmcli con show` (souvent `Wired
|
||||||
|
connection 1` ou `eth0`).
|
||||||
|
|
||||||
|
## 2. DNS vers le contrôleur de domaine
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo nmcli con mod "<votre-connexion>" ipv4.dns 10.10.10.10 ipv4.ignore-auto-dns yes
|
||||||
|
sudo nmcli con up "<votre-connexion>"
|
||||||
|
```
|
||||||
|
|
||||||
|
**Pourquoi le DNS et non `/etc/hosts` ?** Active Directory se découvre par des
|
||||||
|
enregistrements `SRV` (`_ldap._tcp.dc._msdcs.norbourg.lab`). Un fichier `hosts` ne fournit que
|
||||||
|
des noms de machines : la découverte du domaine, `netexec smb norbourg.lab` et les requêtes
|
||||||
|
Kerberos par nom échoueront. Le fichier `hosts` est un pis-aller, pas une solution.
|
||||||
|
|
||||||
|
## 3. Vérification
|
||||||
|
|
||||||
|
Les quatre commandes doivent répondre :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ping -c 2 10.10.10.10
|
||||||
|
nslookup www.norbourg.lab
|
||||||
|
nslookup -type=SRV _ldap._tcp.dc._msdcs.norbourg.lab
|
||||||
|
nmap -Pn -p 88,389,445 10.10.10.10
|
||||||
|
```
|
||||||
|
|
||||||
|
Résultats attendus :
|
||||||
|
|
||||||
|
| Commande | Attendu |
|
||||||
|
|---|---|
|
||||||
|
| `ping` | réponses de `10.10.10.10` |
|
||||||
|
| `nslookup www` | `10.10.10.20` |
|
||||||
|
| `nslookup -type=SRV` | un enregistrement pointant vers `dc01.norbourg.lab` |
|
||||||
|
| `nmap` | ports `88`, `389` et `445` ouverts |
|
||||||
|
|
||||||
|
## 4. Si quelque chose ne répond pas
|
||||||
|
|
||||||
|
| Symptôme | Cause probable | Correctif |
|
||||||
|
|---|---|---|
|
||||||
|
| `ping` sans réponse | route absente | refaire l'étape 1 |
|
||||||
|
| `ping` OK, `nslookup` en `NXDOMAIN` | DNS encore chez le routeur du bureau | refaire l'étape 2 |
|
||||||
|
| `nslookup` OK, `nmap` en `filtered` | pare-feu de l'hôte | aviser l'instructeur |
|
||||||
|
| `ping` OK mais tout le reste échoue | vous êtes sur le Wi-Fi invité, pas sur le réseau du labo | changer de réseau |
|
||||||
|
|
||||||
|
## 5. Revenir en arrière
|
||||||
|
|
||||||
|
Après l'atelier, pour retrouver Internet :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo ip route del 10.10.10.0/24 via 192.168.10.230
|
||||||
|
sudo nmcli con mod "<votre-connexion>" ipv4.ignore-auto-dns no ipv4.dns ""
|
||||||
|
sudo nmcli con up "<votre-connexion>"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Adresses du laboratoire
|
||||||
|
|
||||||
|
| Machine | Adresse | Rôle |
|
||||||
|
|---|---|---|
|
||||||
|
| Passerelle | `10.10.10.230` | hôte du laboratoire, ne pas attaquer |
|
||||||
|
| `dc01` | `10.10.10.10` | contrôleur de domaine, DNS |
|
||||||
|
| `fs01` | `10.10.10.20` | serveur de fichiers, site archivé |
|
||||||
|
| `ws01` | `10.10.10.31` | poste de travail |
|
||||||
|
|
||||||
|
Les adresses `10.10.10.1` à `10.10.10.9` et `10.10.10.200` et plus ne font pas partie du
|
||||||
|
laboratoire.
|
||||||
@@ -39,11 +39,11 @@ WINDOWS_ISO="$LAB_ISO_CACHE/SERVER_EVAL_x64FRE_en-us.iso"
|
|||||||
VIRTIO_ISO="$LAB_ISO_CACHE/virtio-win.iso"
|
VIRTIO_ISO="$LAB_ISO_CACHE/virtio-win.iso"
|
||||||
|
|
||||||
# ---------------------------------------------------------------- vms
|
# ---------------------------------------------------------------- vms
|
||||||
# name ip ram_mb disk_gb vcpu role
|
# name ip ram_mb disk_gb vcpu role (= VM name, selects windows/roles/<role>.ps1)
|
||||||
VMS=$(cat <<'EOF'
|
VMS=$(cat <<'EOF'
|
||||||
dc01 10.10.10.10 4096 36 2 dc
|
dc01 10.10.10.10 4096 36 2 dc01
|
||||||
fs01 10.10.10.20 4096 36 2 fs
|
fs01 10.10.10.20 4096 36 2 fs01
|
||||||
ws01 10.10.10.31 4096 36 2 ws
|
ws01 10.10.10.31 4096 36 2 ws01
|
||||||
EOF
|
EOF
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -53,6 +53,8 @@ EOF
|
|||||||
LAB_ADMIN_PASSWORD="${LAB_ADMIN_PASSWORD:-Norbourg!2026}"
|
LAB_ADMIN_PASSWORD="${LAB_ADMIN_PASSWORD:-Norbourg!2026}"
|
||||||
# Index of the image inside the eval ISO (2 = Standard, Desktop Experience).
|
# Index of the image inside the eval ISO (2 = Standard, Desktop Experience).
|
||||||
WINDOWS_IMAGE_INDEX=2
|
WINDOWS_IMAGE_INDEX=2
|
||||||
|
# DSRM password for the forest. Distinct from the admin password on purpose.
|
||||||
|
LAB_SAFE_MODE_PASSWORD="${LAB_SAFE_MODE_PASSWORD:-NorbourgDsrm!2026}"
|
||||||
# Local milestone uses Server 2022 for every role (no TPM/Secure Boot friction).
|
# Local milestone uses Server 2022 for every role (no TPM/Secure Boot friction).
|
||||||
# Proxmox enables Windows 11 workstations and the WS02 decoy.
|
# Proxmox enables Windows 11 workstations and the WS02 decoy.
|
||||||
WORKSTATION_OS="srv2022" # srv2022 | win11
|
WORKSTATION_OS="srv2022" # srv2022 | win11
|
||||||
|
|||||||
@@ -20,6 +20,8 @@ source "$LAB_DIR/lib/cmd_isos.sh"
|
|||||||
source "$LAB_DIR/lib/cmd_seeds.sh"
|
source "$LAB_DIR/lib/cmd_seeds.sh"
|
||||||
# shellcheck source=lib/cmd_build.sh
|
# shellcheck source=lib/cmd_build.sh
|
||||||
source "$LAB_DIR/lib/cmd_build.sh"
|
source "$LAB_DIR/lib/cmd_build.sh"
|
||||||
|
# shellcheck source=lib/cmd_provision.sh
|
||||||
|
source "$LAB_DIR/lib/cmd_provision.sh"
|
||||||
|
|
||||||
usage() {
|
usage() {
|
||||||
cat <<EOF
|
cat <<EOF
|
||||||
@@ -39,7 +41,7 @@ Commands:
|
|||||||
isos download the Windows media into LAB_ISO_CACHE
|
isos download the Windows media into LAB_ISO_CACHE
|
||||||
seeds render unattend files and pack the seed ISOs
|
seeds render unattend files and pack the seed ISOs
|
||||||
build create VMs, run unattended installs (phase 3)
|
build create VMs, run unattended installs (phase 3)
|
||||||
provision run role scripts over WinRM (phase 5)
|
provision run role scripts over WinRM (--role NAME for one)
|
||||||
snapshot freeze a clean baseline (phase 8)
|
snapshot freeze a clean baseline (phase 8)
|
||||||
up, down start / stop the VMs (phase 3)
|
up, down start / stop the VMs (phase 3)
|
||||||
reset revert to baseline (phase 8)
|
reset revert to baseline (phase 8)
|
||||||
@@ -142,7 +144,7 @@ case $cmd in
|
|||||||
down) cmd_down "$@" ;;
|
down) cmd_down "$@" ;;
|
||||||
status) cmd_status "$@" ;;
|
status) cmd_status "$@" ;;
|
||||||
vnc) cmd_vnc "$@" ;;
|
vnc) cmd_vnc "$@" ;;
|
||||||
provision) planned provision "phase 5" ;;
|
provision) cmd_provision "$@" ;;
|
||||||
snapshot) planned snapshot "phase 8" ;;
|
snapshot) planned snapshot "phase 8" ;;
|
||||||
reset) planned reset "phase 8" ;;
|
reset) planned reset "phase 8" ;;
|
||||||
doctor) planned doctor "phase 8" ;;
|
doctor) planned doctor "phase 8" ;;
|
||||||
|
|||||||
@@ -0,0 +1,121 @@
|
|||||||
|
# shellcheck shell=bash
|
||||||
|
# cmd_provision — upload role scripts over WinRM, run them detached, wait for
|
||||||
|
# their .done marker, survive reboots, then run the optional -post stage.
|
||||||
|
|
||||||
|
LAB_USER=${LAB_USER:-Administrator}
|
||||||
|
|
||||||
|
_winrm() {
|
||||||
|
LAB_PASSWORD=$LAB_ADMIN_PASSWORD python3 "$LAB_DIR/scripts/labwinrm.py" \
|
||||||
|
"$@" --user "$LAB_USER" --password "$LAB_ADMIN_PASSWORD"
|
||||||
|
}
|
||||||
|
|
||||||
|
_wait_winrm() {
|
||||||
|
local host=$1 timeout=${2:-1800}
|
||||||
|
local deadline=$(( SECONDS + timeout ))
|
||||||
|
while (( SECONDS < deadline )); do
|
||||||
|
if tcp_open "$host" 5985; then
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
sleep 10
|
||||||
|
done
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
_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" \
|
||||||
|
"$src" > "$dst"
|
||||||
|
}
|
||||||
|
|
||||||
|
_provision_one() {
|
||||||
|
local name=$1 ip=$2 role=$3
|
||||||
|
local work="$LAB_ROOT/provision/$name"
|
||||||
|
|
||||||
|
step "$name ($role, $ip)"
|
||||||
|
_wait_winrm "$ip" 600 || { fail "$name: WinRM unreachable"; return 1; }
|
||||||
|
|
||||||
|
rm -rf "$work"; mkdir -p "$work"
|
||||||
|
_render_role "$LAB_DIR/windows/roles/$role.ps1" "$work/$role.ps1"
|
||||||
|
|
||||||
|
_winrm "$ip" put "$LAB_DIR/windows/lib/common.ps1" 'C:\norbourg\lib\common.ps1' \
|
||||||
|
|| die "$name: could not upload common.ps1"
|
||||||
|
_winrm "$ip" put "$work/$role.ps1" "C:\\norbourg\\roles\\$role.ps1" \
|
||||||
|
|| die "$name: could not upload $role.ps1"
|
||||||
|
|
||||||
|
local post="$LAB_DIR/windows/roles/$role-post.ps1"
|
||||||
|
if [[ -f $post ]]; then
|
||||||
|
_render_role "$post" "$work/$role-post.ps1"
|
||||||
|
_winrm "$ip" put "$work/$role-post.ps1" "C:\\norbourg\\roles\\$role-post.ps1" \
|
||||||
|
|| die "$name: could not upload $role-post.ps1"
|
||||||
|
fi
|
||||||
|
|
||||||
|
_winrm "$ip" start "C:\\norbourg\\roles\\$role.ps1" "C:\\norbourg\\roles\\$role.log" \
|
||||||
|
|| die "$name: could not start $role.ps1"
|
||||||
|
info " running, waiting for the stage marker"
|
||||||
|
|
||||||
|
local marker
|
||||||
|
marker=$(_winrm "$ip" wait "C:\\norbourg\\roles\\$role.ps1" 3600) || {
|
||||||
|
fail "$name: $role.ps1 did not finish"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
if [[ $marker == FAIL* ]]; then
|
||||||
|
fail "$name: $role.ps1 failed — $marker"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
ok "$name: $marker"
|
||||||
|
|
||||||
|
# A reboot stage drops WinRM; wait for the guest to come back before post.
|
||||||
|
if [[ $marker == *reboot* ]] || [[ -f $post ]]; then
|
||||||
|
info " waiting for the guest to come back"
|
||||||
|
_wait_winrm "$ip" 900 || { fail "$name: did not come back after reboot"; return 1; }
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -f $post ]]; then
|
||||||
|
marker=$(_winrm "$ip" wait "C:\\norbourg\\roles\\$role-post.ps1" 3600) || {
|
||||||
|
fail "$name: $role-post.ps1 did not finish"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
if [[ $marker == FAIL* ]]; then
|
||||||
|
fail "$name: $role-post.ps1 failed — $marker"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
ok "$name: $marker"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
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}"
|
||||||
|
BASE_DN="DC=${DOMAIN%%.*},DC=${DOMAIN#*.}"
|
||||||
|
|
||||||
|
local i name ip role
|
||||||
|
for i in "${!VM_NAMES[@]}"; do
|
||||||
|
name=${VM_NAMES[$i]}
|
||||||
|
ip=${VM_IPS[$i]}
|
||||||
|
role=${VM_ROLES[$i]}
|
||||||
|
|
||||||
|
[[ -n $only && $only != "$name" && $only != "$role" ]] && continue
|
||||||
|
|
||||||
|
# The domain must exist before anyone joins it.
|
||||||
|
if [[ $role != dc ]]; then
|
||||||
|
_wait_winrm "$LAB_DC_IP" 300 || die "DC01 is not reachable; provision dc01 first"
|
||||||
|
fi
|
||||||
|
|
||||||
|
_provision_one "$name" "$ip" "$role" || die "provision failed for $name"
|
||||||
|
done
|
||||||
|
|
||||||
|
printf '\n'
|
||||||
|
ok "provisioning complete"
|
||||||
|
}
|
||||||
Executable
+158
@@ -0,0 +1,158 @@
|
|||||||
|
#!/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 = 1400 # keep each WinRM command well under the payload limit
|
||||||
|
|
||||||
|
|
||||||
|
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]
|
||||||
|
log = opts.args[1] if len(opts.args) > 1 else remote + ".log"
|
||||||
|
done = remote + ".done"
|
||||||
|
ps(session, f"Remove-Item -Force -ErrorAction SilentlyContinue '{done}'")
|
||||||
|
rc, _, err = ps(
|
||||||
|
session,
|
||||||
|
f"Start-Process powershell -WindowStyle Hidden "
|
||||||
|
f"-ArgumentList '-NoProfile','-ExecutionPolicy','Bypass','-File','{remote}' "
|
||||||
|
f"-RedirectStandardOutput '{log}' -RedirectStandardError '{log}.err'",
|
||||||
|
)
|
||||||
|
if rc != 0:
|
||||||
|
print(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:
|
||||||
|
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
|
||||||
|
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())
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,42 @@
|
|||||||
|
# Norbourg lab — shared helpers for role scripts.
|
||||||
|
# Every role script writes a "<script>.done" marker so the host can wait
|
||||||
|
# without parsing output, and so a failure is visible instead of silent.
|
||||||
|
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
$ProgressPreference = 'SilentlyContinue'
|
||||||
|
|
||||||
|
function Get-LabBase { 'C:\norbourg' }
|
||||||
|
|
||||||
|
function Write-LabLog {
|
||||||
|
param([string]$Message)
|
||||||
|
$line = "{0} {1}" -f (Get-Date -Format 'HH:mm:ss'), $Message
|
||||||
|
Write-Host $line
|
||||||
|
Add-Content -Path (Join-Path (Get-LabBase) 'provision.log') -Value $line
|
||||||
|
}
|
||||||
|
|
||||||
|
function Complete-Stage {
|
||||||
|
param([string]$Path, [string]$Message = 'ok')
|
||||||
|
Set-Content -Path "$Path.done" -Value $Message -Encoding ascii
|
||||||
|
Write-LabLog "stage done: $Message"
|
||||||
|
}
|
||||||
|
|
||||||
|
function Fail-Stage {
|
||||||
|
param([string]$Path, [string]$Message)
|
||||||
|
Set-Content -Path "$Path.done" -Value "FAIL $Message" -Encoding ascii
|
||||||
|
Write-LabLog "stage failed: $Message"
|
||||||
|
throw $Message
|
||||||
|
}
|
||||||
|
|
||||||
|
function Wait-ForDomain {
|
||||||
|
param([int]$TimeoutSeconds = 600)
|
||||||
|
$deadline = (Get-Date).AddSeconds($TimeoutSeconds)
|
||||||
|
while ((Get-Date) -lt $deadline) {
|
||||||
|
try {
|
||||||
|
$null = Get-ADDomain -ErrorAction Stop
|
||||||
|
return
|
||||||
|
} catch {
|
||||||
|
Start-Sleep -Seconds 10
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw 'domain services did not come up in time'
|
||||||
|
}
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
# Norbourg lab — DC01 stage 2: directory content, misconfigurations, flags.
|
||||||
|
# Runs once at startup as SYSTEM, right after the promotion reboot.
|
||||||
|
|
||||||
|
. "$PSScriptRoot\..\lib\common.ps1"
|
||||||
|
|
||||||
|
$self = $PSCommandPath
|
||||||
|
Write-LabLog 'dc01: post stage starting'
|
||||||
|
|
||||||
|
try {
|
||||||
|
Wait-ForDomain 900
|
||||||
|
Import-Module ActiveDirectory
|
||||||
|
Write-LabLog 'dc01: directory services reachable'
|
||||||
|
|
||||||
|
$dom = Get-ADDomain
|
||||||
|
$base = $dom.DistinguishedName
|
||||||
|
|
||||||
|
# ------------------------------------------------------------ structure
|
||||||
|
$ous = @('Norbourg', 'Utilisateurs', 'TI', 'Groupes', 'Ordinateurs')
|
||||||
|
foreach ($ou in $ous) {
|
||||||
|
$path = "OU=$ou,$base"
|
||||||
|
if ($ou -eq 'Norbourg') { $path = "OU=Norbourg,$base" }
|
||||||
|
if (-not (Get-ADOrganizationalUnit -Filter "Name -eq '$ou'" -SearchBase $base -ErrorAction SilentlyContinue)) {
|
||||||
|
New-ADOrganizationalUnit -Name $ou -Path $(if ($ou -eq 'Norbourg') { $base } else { "OU=Norbourg,$base" }) -ProtectedFromAccidentalDeletion $false
|
||||||
|
Write-LabLog "dc01: OU $ou created"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# ------------------------------------------------------------ users
|
||||||
|
$users = @(
|
||||||
|
@{ Sam='m.legault'; Given='Marie'; Surname='Legault'; Pwd='Legault2024!'; OU='TI'; Title='Directrice des TI' }
|
||||||
|
@{ Sam='s.bergeron'; Given='Sophie'; Surname='Bergeron'; Pwd='Bergeron2024!'; OU='TI'; Title='Technicienne, soutien aux usagers' }
|
||||||
|
@{ Sam='helpdesk1'; Given='Sylvie'; Surname='Tremblay'; Pwd='Welcome2024!'; OU='TI'; Title='Compte partage du helpdesk' }
|
||||||
|
@{ Sam='svc_backup'; Given='Service'; Surname='Sauvegarde'; Pwd='Backup2023!'; OU='TI'; Title='Compte de service, sauvegarde' }
|
||||||
|
@{ Sam='t.smith'; Given='Thomas'; Surname='Smith'; Pwd='Str0ngAdmin!2026'; OU='TI'; Title='Administrateur de domaine' }
|
||||||
|
@{ Sam='j.contractor'; Given='Jacques'; Surname='Contractor'; Pwd='Winter2024!'; OU='Utilisateurs'; Title='Consultant, migration' }
|
||||||
|
@{ Sam='a.gagnon'; Given='Annie'; Surname='Gagnon'; Pwd='Gagnon2023!'; OU='Utilisateurs'; Title='Comptabilite' }
|
||||||
|
@{ Sam='p.roy'; Given='Pierre'; Surname='Roy'; Pwd='Roy2022!'; OU='Utilisateurs'; Title='Analyste, operations' }
|
||||||
|
)
|
||||||
|
|
||||||
|
foreach ($u in $users) {
|
||||||
|
if (Get-ADUser -Filter "SamAccountName -eq '$($u.Sam)'" -ErrorAction SilentlyContinue) {
|
||||||
|
Write-LabLog "dc01: user $($u.Sam) exists"
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
$ou = if ($u.OU -eq 'TI') { "OU=TI,OU=Norbourg,$base" } else { "OU=Utilisateurs,OU=Norbourg,$base" }
|
||||||
|
New-ADUser -SamAccountName $u.Sam `
|
||||||
|
-Name "$($u.Given) $($u.Surname)" `
|
||||||
|
-GivenName $u.Given -Surname $u.Surname `
|
||||||
|
-DisplayName "$($u.Given) $($u.Surname)" `
|
||||||
|
-Title $u.Title `
|
||||||
|
-Path $ou `
|
||||||
|
-AccountPassword (ConvertTo-SecureString $u.Pwd -AsPlainText -Force) `
|
||||||
|
-Enabled $true -PasswordNeverExpires $true -ChangePasswordAtLogon $false
|
||||||
|
Write-LabLog "dc01: user $($u.Sam) created"
|
||||||
|
}
|
||||||
|
|
||||||
|
# ------------------------------------------------------------ groups
|
||||||
|
$groups = @{
|
||||||
|
'TI-Support' = @('s.bergeron', 'helpdesk1')
|
||||||
|
'WS Admins' = @('svc_backup')
|
||||||
|
'Serveurs-Admins' = @('m.legault')
|
||||||
|
}
|
||||||
|
foreach ($name in $groups.Keys) {
|
||||||
|
if (-not (Get-ADGroup -Filter "Name -eq '$name'" -ErrorAction SilentlyContinue)) {
|
||||||
|
New-ADGroup -Name $name -GroupScope Global -GroupCategory Security -Path "OU=Groupes,OU=Norbourg,$base"
|
||||||
|
Write-LabLog "dc01: group $name created"
|
||||||
|
}
|
||||||
|
foreach ($member in $groups[$name]) {
|
||||||
|
try { Add-ADGroupMember -Identity $name -Members $member -ErrorAction Stop }
|
||||||
|
catch { Write-LabLog "dc01: $member already in $name" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try { Add-ADGroupMember -Identity 'Domain Admins' -Members 't.smith' -ErrorAction Stop }
|
||||||
|
catch { Write-LabLog 'dc01: t.smith already Domain Admin' }
|
||||||
|
|
||||||
|
# ------------------------------------------------------------ misconfigs
|
||||||
|
# Kerberoastable: an SPN on a normal user account.
|
||||||
|
Set-ADUser -Identity 'svc_backup' -ServicePrincipalNames @{ Add = 'MSSQLSvc/fs01.norbourg.lab:1433' }
|
||||||
|
Write-LabLog 'dc01: SPN set on svc_backup'
|
||||||
|
|
||||||
|
# AS-REP roastable: pre-authentication disabled.
|
||||||
|
Set-ADAccountControl -Identity 'j.contractor' -DoesNotRequirePreAuth $true
|
||||||
|
Write-LabLog 'dc01: pre-auth disabled on j.contractor'
|
||||||
|
|
||||||
|
# ACL abuse: svc_backup has GenericAll on a Domain Admin.
|
||||||
|
$target = Get-ADUser 't.smith'
|
||||||
|
$sid = (Get-ADUser 'svc_backup').SID
|
||||||
|
$aclPath = "AD:\$($target.DistinguishedName)"
|
||||||
|
$acl = Get-Acl $aclPath
|
||||||
|
$already = $acl.Access | Where-Object { $_.IdentityReference -eq $sid -and $_.ActiveDirectoryRights -match 'GenericAll' }
|
||||||
|
if (-not $already) {
|
||||||
|
$rule = New-Object System.DirectoryServices.ActiveDirectoryAccessRule(
|
||||||
|
$sid,
|
||||||
|
[System.DirectoryServices.ActiveDirectoryRights]::GenericAll,
|
||||||
|
[System.Security.AccessControl.AccessControlType]::Allow)
|
||||||
|
$acl.AddAccessRule($rule)
|
||||||
|
Set-Acl -Path $aclPath -AclObject $acl
|
||||||
|
Write-LabLog 'dc01: GenericAll granted to svc_backup over t.smith'
|
||||||
|
}
|
||||||
|
|
||||||
|
# ------------------------------------------------------------ dns
|
||||||
|
try {
|
||||||
|
Add-DnsServerResourceRecordA -Name 'www' -ZoneName '@@DOMAIN@@' -IPv4Address '10.10.10.20' -ErrorAction Stop
|
||||||
|
Write-LabLog 'dc01: www A record created'
|
||||||
|
} catch {
|
||||||
|
Write-LabLog 'dc01: www A record already present'
|
||||||
|
}
|
||||||
|
|
||||||
|
# ------------------------------------------------------------ flags
|
||||||
|
$flagDir = 'C:\flag'
|
||||||
|
New-Item -ItemType Directory -Force -Path $flagDir | Out-Null
|
||||||
|
$rootPath = Join-Path $flagDir 'root.txt'
|
||||||
|
if (-not (Test-Path $rootPath)) {
|
||||||
|
Set-Content -Path $rootPath -Value 'NORBOURG{do_m41n_4dm1n_0n_dc01}' -Encoding ascii
|
||||||
|
}
|
||||||
|
# Administrators only: SYSTEM + Domain Admins inherit through the default ACL.
|
||||||
|
$acl = Get-Acl $flagDir
|
||||||
|
$acl.SetAccessRuleProtection($true, $false)
|
||||||
|
foreach ($id in @('BUILTIN\Administrators', 'NT AUTHORITY\SYSTEM')) {
|
||||||
|
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule(
|
||||||
|
$id, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')
|
||||||
|
$acl.AddAccessRule($rule)
|
||||||
|
}
|
||||||
|
Set-Acl -Path $flagDir -AclObject $acl
|
||||||
|
Write-LabLog 'dc01: root.txt in place'
|
||||||
|
|
||||||
|
# ------------------------------------------------------------ auditing
|
||||||
|
# Legacy policy off, advanced subcategories on: this is what the blue-team
|
||||||
|
# debrief reads back from the event log.
|
||||||
|
$lsa = 'HKLM:\SYSTEM\CurrentControlSet\Control\Lsa'
|
||||||
|
Set-ItemProperty -Path $lsa -Name SCENoApplyLegacyAuditPolicy -Value 1 -Type DWord
|
||||||
|
|
||||||
|
$subcategories = @(
|
||||||
|
'Kerberos Authentication Service',
|
||||||
|
'Kerberos Service Ticket Operations',
|
||||||
|
'Logon',
|
||||||
|
'User Account Management',
|
||||||
|
'Directory Service Access',
|
||||||
|
'Directory Service Changes',
|
||||||
|
'Computer Account Management'
|
||||||
|
)
|
||||||
|
foreach ($sub in $subcategories) {
|
||||||
|
$null = auditpol.exe /set /subcategory:"$sub" /success:enable /failure:enable
|
||||||
|
}
|
||||||
|
Write-LabLog 'dc01: advanced audit policy enabled'
|
||||||
|
|
||||||
|
$null = schtasks.exe /Delete /TN 'NorbourgDcPost' /F
|
||||||
|
Complete-Stage $self 'ok'
|
||||||
|
} catch {
|
||||||
|
Fail-Stage $self $_.Exception.Message
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
# Norbourg lab — DC01 stage 1: install AD DS and create the forest.
|
||||||
|
# Promotion reboots the machine, so the account/ACL work lives in dc01-post.ps1
|
||||||
|
# and is scheduled as a startup task before the reboot.
|
||||||
|
|
||||||
|
. "$PSScriptRoot\..\lib\common.ps1"
|
||||||
|
|
||||||
|
$self = $PSCommandPath
|
||||||
|
Write-LabLog 'dc01: stage 1 starting'
|
||||||
|
|
||||||
|
try {
|
||||||
|
$feature = Get-WindowsFeature -Name AD-Domain-Services
|
||||||
|
if (-not $feature.Installed) {
|
||||||
|
Write-LabLog 'dc01: installing AD-Domain-Services'
|
||||||
|
$null = Install-WindowsFeature -Name AD-Domain-Services -IncludeManagementTools
|
||||||
|
} else {
|
||||||
|
Write-LabLog 'dc01: AD-Domain-Services already installed'
|
||||||
|
}
|
||||||
|
|
||||||
|
$post = Join-Path $PSScriptRoot 'dc01-post.ps1'
|
||||||
|
if (-not (Test-Path $post)) { Fail-Stage $self 'dc01-post.ps1 missing next to dc01.ps1' }
|
||||||
|
|
||||||
|
# Run the account/ACL stage once, at next startup, as SYSTEM.
|
||||||
|
$null = schtasks.exe /Create /TN 'NorbourgDcPost' /F /SC ONSTART /RU SYSTEM /RL HIGHEST `
|
||||||
|
/TR "powershell.exe -NoProfile -ExecutionPolicy Bypass -File `"$post`""
|
||||||
|
Write-LabLog 'dc01: scheduled dc01-post.ps1 at startup'
|
||||||
|
|
||||||
|
$safeMode = ConvertTo-SecureString '@@SAFE_MODE_PASSWORD@@' -AsPlainText -Force
|
||||||
|
|
||||||
|
Write-LabLog 'dc01: creating forest norbourg.lab'
|
||||||
|
$null = Install-ADDSForest `
|
||||||
|
-DomainName '@@DOMAIN@@' `
|
||||||
|
-DomainNetbiosName '@@NETBIOS@@' `
|
||||||
|
-InstallDns `
|
||||||
|
-SafeModeAdministratorPassword $safeMode `
|
||||||
|
-ForestMode WinThreshold `
|
||||||
|
-DomainMode WinThreshold `
|
||||||
|
-NoRebootOnCompletion `
|
||||||
|
-Force
|
||||||
|
|
||||||
|
Complete-Stage $self 'ok reboot'
|
||||||
|
Restart-Computer -Force
|
||||||
|
} catch {
|
||||||
|
Fail-Stage $self $_.Exception.Message
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
# Norbourg lab — FS01: file server and the archived site.
|
||||||
|
# The web root's "public" folder is both an IIS directory and the SMB share,
|
||||||
|
# so the web and SMB discovery paths lead to the same file.
|
||||||
|
|
||||||
|
. "$PSScriptRoot\..\lib\common.ps1"
|
||||||
|
|
||||||
|
$self = $PSCommandPath
|
||||||
|
Write-LabLog 'fs01: starting'
|
||||||
|
|
||||||
|
try {
|
||||||
|
$features = @(
|
||||||
|
'Web-Server', 'Web-Common-Http', 'Web-Default-Doc',
|
||||||
|
'Web-Static-Content', 'Web-Directory-Browsing', 'Web-Http-Logging'
|
||||||
|
)
|
||||||
|
foreach ($f in $features) {
|
||||||
|
if (-not (Get-WindowsFeature -Name $f).Installed) {
|
||||||
|
Write-LabLog "fs01: installing $f"
|
||||||
|
$null = Install-WindowsFeature -Name $f -IncludeManagementTools
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$root = 'C:\inetpub\wwwroot'
|
||||||
|
$public = Join-Path $root 'public'
|
||||||
|
New-Item -ItemType Directory -Force -Path $public | Out-Null
|
||||||
|
|
||||||
|
# Directory browsing only where the lab wants it: the leftover upload dir.
|
||||||
|
$webconfig = @'
|
||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<configuration>
|
||||||
|
<system.webServer>
|
||||||
|
<directoryBrowse enabled="true" />
|
||||||
|
</system.webServer>
|
||||||
|
</configuration>
|
||||||
|
'@
|
||||||
|
Set-Content -Path (Join-Path $public 'web.config') -Value $webconfig -Encoding UTF8
|
||||||
|
|
||||||
|
if (-not (Get-SmbShare -Name 'Public' -ErrorAction SilentlyContinue)) {
|
||||||
|
New-SmbShare -Name 'Public' -Path $public -ReadAccess 'Everyone' | Out-Null
|
||||||
|
Write-LabLog 'fs01: share Public created'
|
||||||
|
}
|
||||||
|
|
||||||
|
# Placeholder so a fresh box is not an empty directory listing.
|
||||||
|
$placeholder = Join-Path $public 'lisez-moi.txt'
|
||||||
|
if (-not (Test-Path $placeholder)) {
|
||||||
|
Set-Content -Path $placeholder -Encoding ascii -Value @'
|
||||||
|
Depot public du site norbourg.lab
|
||||||
|
Les formulaires du site deposent leurs pieces jointes ici.
|
||||||
|
Ne pas supprimer.
|
||||||
|
'@
|
||||||
|
}
|
||||||
|
|
||||||
|
$cred = New-Object System.Management.Automation.PSCredential(
|
||||||
|
'@@DOMAIN@@\Administrator',
|
||||||
|
(ConvertTo-SecureString '@@ADMIN_PASSWORD@@' -AsPlainText -Force))
|
||||||
|
|
||||||
|
Write-LabLog 'fs01: joining the domain'
|
||||||
|
Add-Computer -DomainName '@@DOMAIN@@' -Credential $cred `
|
||||||
|
-OUPath 'OU=Ordinateurs,OU=Norbourg,@@BASE_DN@@' -Force
|
||||||
|
|
||||||
|
Complete-Stage $self 'ok reboot'
|
||||||
|
Restart-Computer -Force
|
||||||
|
} catch {
|
||||||
|
Fail-Stage $self $_.Exception.Message
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
# Norbourg lab — WS01 stage 2: local privileges and the workstation flag.
|
||||||
|
|
||||||
|
. "$PSScriptRoot\..\lib\common.ps1"
|
||||||
|
|
||||||
|
$self = $PSCommandPath
|
||||||
|
Write-LabLog 'ws01: post stage starting'
|
||||||
|
|
||||||
|
try {
|
||||||
|
Wait-ForDomain 600
|
||||||
|
|
||||||
|
# svc_backup becomes a local admin through this domain group.
|
||||||
|
try {
|
||||||
|
Add-LocalGroupMember -Group 'Administrators' -Member '@@NETBIOS@@\WS Admins' -ErrorAction Stop
|
||||||
|
Write-LabLog 'ws01: WS Admins added to local Administrators'
|
||||||
|
} catch {
|
||||||
|
Write-LabLog 'ws01: WS Admins already local admin'
|
||||||
|
}
|
||||||
|
|
||||||
|
$flagDir = 'C:\flag'
|
||||||
|
New-Item -ItemType Directory -Force -Path $flagDir | Out-Null
|
||||||
|
$userFlag = Join-Path $flagDir 'user.txt'
|
||||||
|
if (-not (Test-Path $userFlag)) {
|
||||||
|
Set-Content -Path $userFlag -Value 'NORBOURG{w0rkst4t10n_l4t3r4l_m0v3}' -Encoding ascii
|
||||||
|
}
|
||||||
|
|
||||||
|
$acl = Get-Acl $flagDir
|
||||||
|
$acl.SetAccessRuleProtection($true, $false)
|
||||||
|
foreach ($id in @('BUILTIN\Administrators', 'NT AUTHORITY\SYSTEM')) {
|
||||||
|
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule(
|
||||||
|
$id, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')
|
||||||
|
$acl.AddAccessRule($rule)
|
||||||
|
}
|
||||||
|
Set-Acl -Path $flagDir -AclObject $acl
|
||||||
|
Write-LabLog 'ws01: user.txt in place'
|
||||||
|
|
||||||
|
$null = schtasks.exe /Delete /TN 'NorbourgWsPost' /F
|
||||||
|
Complete-Stage $self 'ok'
|
||||||
|
} catch {
|
||||||
|
Fail-Stage $self $_.Exception.Message
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# Norbourg lab — WS01: domain-joined workstation.
|
||||||
|
# Stage 2 runs after the join reboot because local group membership needs the
|
||||||
|
# domain group to resolve.
|
||||||
|
|
||||||
|
. "$PSScriptRoot\..\lib\common.ps1"
|
||||||
|
|
||||||
|
$self = $PSCommandPath
|
||||||
|
Write-LabLog 'ws01: starting'
|
||||||
|
|
||||||
|
try {
|
||||||
|
$post = Join-Path $PSScriptRoot 'ws01-post.ps1'
|
||||||
|
if (-not (Test-Path $post)) { Fail-Stage $self 'ws01-post.ps1 missing' }
|
||||||
|
|
||||||
|
$null = schtasks.exe /Create /TN 'NorbourgWsPost' /F /SC ONSTART /RU SYSTEM /RL HIGHEST `
|
||||||
|
/TR "powershell.exe -NoProfile -ExecutionPolicy Bypass -File `"$post`""
|
||||||
|
|
||||||
|
$cred = New-Object System.Management.Automation.PSCredential(
|
||||||
|
'@@DOMAIN@@\Administrator',
|
||||||
|
(ConvertTo-SecureString '@@ADMIN_PASSWORD@@' -AsPlainText -Force))
|
||||||
|
|
||||||
|
Write-LabLog 'ws01: joining the domain'
|
||||||
|
Add-Computer -DomainName '@@DOMAIN@@' -Credential $cred `
|
||||||
|
-OUPath 'OU=Ordinateurs,OU=Norbourg,@@BASE_DN@@' -Force
|
||||||
|
|
||||||
|
Complete-Stage $self 'ok reboot'
|
||||||
|
Restart-Computer -Force
|
||||||
|
} catch {
|
||||||
|
Fail-Stage $self $_.Exception.Message
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user