Files
pentest.intro/session1/content/windows/roles/dc01-post.ps1
T
quoije 59e2594c1e dc01: make the delegated ACL the only way out, and stabilise the state
Three shortcuts and one race made the lab either easier than documented or
non-deterministic:

- Serveurs-Admins was nested in BUILTIN\Administrators on the DC, so
  m.legault was a de-facto domain-controller admin (C$, NTDS.dit) and the
  whole ACL lesson could be skipped. It also made SDProp treat her as
  protected: an hour after provisioning, the intended GenericAll ACE was
  wiped. Removed the nesting; adminCount is explicitly reset.
- the t.smith decoy ACE gave a working path to Domain Admin until SDProp
  ran (up to an hour after a fresh build). The role now grants it and
  revokes it immediately, so the state is deterministic.
- the replication-rights grant stacked duplicate ACEs on every re-run; it
  now removes its own ACEs first.
- up/reset/save returned as soon as WinRM answered, while the directory
  was still starting; doctor right after could report a missing ACE and
  missing replication rights on a healthy lab. They now wait for
  Get-ADDomain on dc01.

doctor: a decoy ACE that is still present is now a failure, not a success.
The deck's wording matches the new behaviour.
2026-10-25 14:05:55 -04:00

264 lines
13 KiB
PowerShell

# 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
if (-not (Enter-StageLock $self)) {
Write-LabLog 'stage already running on this guest; duplicate start ignored'
return
}
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='Maple2024!'; OU='TI'; Title='Directrice des TI' }
@{ Sam='s.bergeron'; Given='Sophie'; Surname='Bergeron'; Pwd='Nuage2024!'; 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='Riviere2023!'; OU='Utilisateurs'; Title='Comptabilite' }
@{ Sam='p.roy'; Given='Pierre'; Surname='Roy'; Pwd='Foret2022!'; OU='Utilisateurs'; Title='Analyste, operations' }
)
foreach ($u in $users) {
if (Get-ADUser -Filter "SamAccountName -eq '$($u.Sam)'" -ErrorAction SilentlyContinue) {
# An interrupted first run can leave an account disabled: repair it.
Enable-ADAccount -Identity $u.Sam -ErrorAction SilentlyContinue
Set-ADAccountPassword -Identity $u.Sam -Reset `
-NewPassword (ConvertTo-SecureString $u.Pwd -AsPlainText -Force)
Write-LabLog "dc01: user $($u.Sam) exists (repaired)"
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')
'Sauvegarde-AD' = @('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. SDProp resets a
# protected object's ACL within the hour, so the lab grants the ACE and
# revokes it immediately: a participant who finds it in the first hour
# could reset a Domain Admin's password and skip the intended path.
# dsacls is used instead of the .NET ACL API, which returns success but
# does not persist the ACE through the AD provider.
$targetDn = (Get-ADUser 't.smith').DistinguishedName
$null = dsacls.exe $targetDn /G '@@NETBIOS@@\svc_backup:GA'
Write-LabLog 'dc01: GenericAll granted to svc_backup over t.smith (decoy)'
$null = dsacls.exe $targetDn /R '@@NETBIOS@@\svc_backup'
Write-LabLog 'dc01: decoy ACE on t.smith revoked (SDProp would do it within the hour)'
# The backup product needs directory replication rights for AD-aware
# backups. That is what makes m.legault reach the DC without being in a
# protected group — so the GenericAll above is never rewritten by SDProp.
$svcGroup = Get-ADGroup 'Sauvegarde-AD'
$domainAcl = [ADSI]("LDAP://$base")
$sd = $domainAcl.ObjectSecurity
$rightGuids = @('1131f6aa-9c07-11d1-f79f-00c04fc2dcd2',
'1131f6ad-9c07-11d1-f79f-00c04fc2dcd2')
$sidText = $svcGroup.SID.Value
$nameText = '@@NETBIOS@@\Sauvegarde-AD'
# Idempotent: a re-run must not stack duplicate ACEs on the domain.
foreach ($ace in @($sd.Access)) {
if ($ace.IsInherited) { continue }
$trustee = $ace.IdentityReference.Value
if (($trustee -eq $sidText -or $trustee -eq $nameText) -and
($rightGuids -contains $ace.ObjectType.Guid.ToString())) {
[void]$sd.RemoveAccessRule($ace)
}
}
foreach ($rightGuid in $rightGuids) {
$rule = New-Object System.DirectoryServices.ActiveDirectoryAccessRule(
$svcGroup.SID,
[System.DirectoryServices.ActiveDirectoryRights]::ExtendedRight,
[System.Security.AccessControl.AccessControlType]::Allow,
[Guid]$rightGuid)
$sd.AddAccessRule($rule)
}
$domainAcl.ObjectSecurity = $sd
$domainAcl.CommitChanges()
Write-LabLog 'dc01: Sauvegarde-AD granted replication rights'
# Set-ADObject does not resolve a sAMAccountName reliably (it raises
# ADIdentityNotFoundException), so resolve the DN once and use it below.
$plainDn = (Get-ADUser 'm.legault').DistinguishedName
# m.legault must not carry a stale adminCount flag from an earlier design,
# or SDProp would keep treating the account as protected and wipe the ACE.
Set-ADObject -Identity $plainDn -Replace @{ adminCount = 0 } -ErrorAction SilentlyContinue
# Realistic delegation: the service account manages a plain user who is a
# member of the server-admin group. m.legault is NOT in a protected group,
# so SDProp leaves this ACE alone — unlike the Domain Admin target above.
if (-not (dsacls.exe $plainDn | Select-String 'svc_backup')) {
$null = dsacls.exe $plainDn /G '@@NETBIOS@@\svc_backup:GA'
Write-LabLog 'dc01: GenericAll granted to svc_backup over m.legault'
}
# Deliberately NOT added to BUILTIN\Administrators: a local admin on the
# DC can read C$ and NTDS.dit, which is a shortcut around the whole ACL
# path. The lab's lesson is the delegated ACE plus the replication right,
# not "the account happens to be a domain-controller admin".
# ------------------------------------------------------------ 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'
}
# Easter egg: discoverable with nslookup -type=TXT yourlove.norbourg.lab
try {
Add-DnsServerResourceRecord -ZoneName '@@DOMAIN@@' -Name 'yourlove' -Txt `
-DescriptiveText 'The Outfield - Your Love (1985)' -ErrorAction Stop
Write-LabLog 'dc01: yourlove TXT record created'
} catch {
Write-LabLog 'dc01: yourlove TXT record already present'
}
# ------------------------------------------------------------ flag
# The server flag sits in the backup staging folder: the agent's group can
# read it, so a plain account can prove it reached the DC.
$flagDir = 'C:\Sauvegarde'
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
}
$acl = Get-Acl $flagDir
$acl.SetAccessRuleProtection($true, $false)
foreach ($id in @('BUILTIN\Administrators', 'NT AUTHORITY\SYSTEM')) {
$acl.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule(
$id, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')))
}
$acl.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule(
'@@NETBIOS@@\Sauvegarde-AD', 'Read', 'ContainerInherit,ObjectInherit', 'None', 'Allow')))
Set-Acl -Path $flagDir -AclObject $acl
if (-not (Get-SmbShare -Name 'Sauvegarde$' -ErrorAction SilentlyContinue)) {
New-SmbShare -Name 'Sauvegarde$' -Path $flagDir `
-ReadAccess '@@NETBIOS@@\Sauvegarde-AD' | Out-Null
}
Write-LabLog 'dc01: root.txt in the backup share'
# The GenericAll path ends in a password reset; the default one-day
# minimum password age blocks it, and it is a plausible weak setting.
Set-ADDefaultDomainPasswordPolicy -Identity '@@DOMAIN@@' -MinPasswordAge '00:00:00'
Write-LabLog 'dc01: minimum password age set to zero'
# ------------------------------------------------------------ dhcp
# Lets anything plugged into the lab bridge configure itself: the Kali
# attacker VM, an instructor laptop. No router option on purpose — the lab
# is isolated, so clients must not think they have a way out.
if (-not (Get-WindowsFeature -Name DHCP).Installed) {
$null = Install-WindowsFeature -Name DHCP -IncludeManagementTools
Write-LabLog 'dc01: DHCP role installed'
}
try { Add-DhcpServerInDC -DnsName "dc01.@@DOMAIN@@" -IPAddress '@@LAB_DC_IP@@' -ErrorAction Stop }
catch { Write-LabLog 'dc01: DHCP already authorized' }
if (-not (Get-DhcpServerv4Scope -ScopeId '10.10.10.0' -ErrorAction SilentlyContinue)) {
Add-DhcpServerv4Scope -Name 'Norbourg lab' -StartRange '10.10.10.100' `
-EndRange '10.10.10.200' -SubnetMask '255.255.255.0' -State Active
Write-LabLog 'dc01: DHCP scope 10.10.10.100-200 created'
}
Set-DhcpServerv4OptionValue -ScopeId '10.10.10.0' `
-DnsServer '@@LAB_DC_IP@@' -DnsDomain '@@DOMAIN@@'
# Fixed address for the attacker VM: the documented .101 must never move.
$reservation = Get-DhcpServerv4Reservation -ScopeId '10.10.10.0' -ErrorAction SilentlyContinue |
Where-Object { $_.IPAddress -eq '10.10.10.101' }
if (-not $reservation) {
Add-DhcpServerv4Reservation -ScopeId '10.10.10.0' -IPAddress '10.10.10.101' `
-ClientId '52-54-00-0a-65-00' -Name 'kali' -Description 'attacker VM'
Write-LabLog 'dc01: DHCP reservation 10.10.10.101 created'
}
Set-Service -Name DHCPServer -StartupType Automatic -ErrorAction SilentlyContinue
Start-Service -Name DHCPServer -ErrorAction SilentlyContinue
# ------------------------------------------------------------ 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'
Complete-Stage $self 'ok'
} catch {
Fail-Stage $self $_.Exception.Message
} finally {
Exit-StageLock $self
}