本文把一台空白 Windows Server 2025 Core 做成可反复克隆的 AD 模板,后面每道题都在它的克隆上做,既省时间,也避免每台靶机因为手工操作差异出现“这台能打通、那台打不通”的玄学问题。
VMware 控制台带中文时粘贴不了,粘贴命令不要带中文注释!
0. 约定:靶机侧统一使用 C:\ProgramData\Maze
后文所有落在靶机上的脚本、配置,一律放在 C:\ProgramData\Maze 下。原因:
C:\ProgramData默认所有用户可读、管理员可写,SYSTEM 计划任务也能直接访问,权限模型稳定;- 不在
C:\Windows\Temp,第 13 节清临时目录时不会被误删; - 路径固定,克隆出来的每台靶机结构一致,排查问题时不用猜文件在哪。
目录规划:
| 路径 | 用途 |
|---|---|
C:\ProgramData\Maze\ |
靶机侧脚本与配置的根目录 |
C:\ProgramData\Maze\dc-ip-sync.ps1 |
开机同步 IP/DNS 的脚本(常驻) |
C:\ProgramData\Maze\reip.ps1 |
克隆导入后手工换 IP(常驻,可选) |
C:\ProgramData\Maze\logs\ |
开机任务等脚本自己的日志(可选) |
C:\Windows\Temp\ |
仅作为 Send-Guest 一次性投递的落脚点,执行完即弃 |
Send-Guest 默认仍然把文件 scp 到 C:\Windows\Temp,因为那是一次性投递;凡是要常驻的脚本(比如开机任务引用的 dc-ip-sync.ps1、手工换 IP 用的 reip.ps1),必须落到 C:\ProgramData\Maze。第 12 节会显式指定目标目录。
1. 成品规格
先把最终形态定下来,后面所有步骤都是朝这张表收敛。
| 项 | 值 |
|---|---|
| 系统 | Windows Server 2025 Standard Core |
| 主机名 | DC(FQDN DC.maze.sec) |
| 域 / NetBIOS | maze.sec / MAZE |
| 角色 | AD DS、DNS、OpenSSH。AD CS 不进底盘,题目需要见 可复用部署经验.md |
这是模板,不是题目,做完后打快照。新题先克隆,再部署挑战层。
需要特别强调“模板不是题目”这一点:模板里不应该有任何跟具体考题相关的东西——没有 flag、没有题面用户、没有刻意留的漏洞。它只是一台配置正确、状态干净、随时可以克隆的域控。挑战层的东西一律在克隆出来之后再加,这样模板可以反复复用,也不会因为某道题的残留污染下一道题。
2. 准备 ISO 和虚拟机
下载 Windows Server 2025 ISO。新建 VM 时建议:
- 硬件版本 19
- 2 vCPU、4 GB 内存、60 GB 磁盘够用
- 网卡桥接或 NAT
- 光驱挂 ISO,装完再断开
不要在模板上留本机 ISO、声卡、USB,保持干净。这些东西留着不仅占空间,导出时还容易把宿主机路径一起带进 vmx,换台机器就报错。
我的磁盘设的比较小,这样导出靶机零填充空闲空间会快一点。
磁盘小一点的另一个好处是克隆快。模板本身不需要装多少东西,60 GB 对域控来说绰绰有余,真正占空间的是后面的挑战层,那部分在克隆上做,跟模板无关。
3. 安装系统
安装过程略。装完会要求设置 Administrator 密码。
确认密码的选框要用 Tab 切过去,不要按回车。
进入 sconfig 之后按 15,进命令行(PowerShell)。后面控制台命令都在这里敲。
建议把装机密码直接设成实验室默认,后面脚本会再写一遍:
Admin@1234等模板彻底做完、准备出题时,再在挑战层把 Administrator 改成随机口令。
4. 安装 VMware Tools
虚拟机菜单:VM → Install VMware Tools,光驱会出现安装盘。
D:
cd \
dir
setup.exe /S /v "/qn REBOOT=R ADDLOCAL=ALL"
菜单里出现灰色的 Reinstall,说明已经装上。必要时重启一次:
Restart-Computer -ForceVMware Tools 主要是为了让克隆、快照这些虚拟化功能正常工作,网络驱动、优雅关机也都靠它。
5. 关防火墙、装 OpenSSH
这是控制台最后一段。先关防火墙,再装 SSH,并把默认 shell 改成 PowerShell,后面所有操作都走 SSH,方便 AI 操作和复制粘贴。控制台里敲命令太痛苦。
$ErrorActionPreference = 'Stop'
Set-NetFirewallProfile -Profile All -Enabled False
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
Start-Service sshd
Set-Service sshd -StartupType Automatic
Set-Service ssh-agent -StartupType Automatic
Start-Service ssh-agent -ErrorAction SilentlyContinue
New-ItemProperty -Path 'HKLM:\SOFTWARE\OpenSSH' -Name DefaultShell `
-Value 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe' `
-PropertyType String -Force
Get-NetFirewallProfile | Select-Object Name,Enabled
Get-Service sshd | Format-Table Name,Status,StartType
Get-NetIPConfiguration | Format-List InterfaceAlias,IPv4Address,IPv4DefaultGateway
顺手把靶机侧的统一目录建好,后面所有常驻脚本都往这里放:
New-Item -ItemType Directory -Path 'C:\ProgramData\Maze' -Force | Out-Null
New-Item -ItemType Directory -Path 'C:\ProgramData\Maze\logs' -Force | Out-Null6. 本机 SSH 接管
这个脚本主要是方便 AI 连接和操作,自己使用时需要改改。Send-Guest 支持传目标目录,常驻文件显式指定 C:/ProgramData/Maze,一次性脚本保持默认 C:/Windows/Temp。
$IP = '<靶机IP>'
$User = 'administrator'
$env:SSHPASS = 'Admin@1234'
$sshpass = 'D:\Scoop\shims\sshpass.exe'
$opts = @(
'-o','StrictHostKeyChecking=no',
'-o','UserKnownHostsFile=NUL',
'-o','ConnectTimeout=10'
)
$here = 'E:\CODE\靶机出题\windows'
function Send-Guest([string]$File, [string]$RemoteDir = 'C:/Windows/Temp') {
$leaf = Split-Path $File -Leaf
$local = if (Test-Path $File) { $File } else { Join-Path $here $File }
& $sshpass -e scp @opts $local "${User}@${IP}:$RemoteDir/$leaf"
if ($LASTEXITCODE -ne 0) { throw "scp $leaf failed" }
& $sshpass -e ssh @opts "${User}@${IP}" `
"powershell -NoProfile -ExecutionPolicy Bypass -File $($RemoteDir.Replace('/','\'))\$leaf"
}
& $sshpass -e ssh @opts "${User}@${IP}" 'hostname; ipconfig'不要把本机 PowerShell 的 -ErrorAction 塞进远程一行命令,本地解析器会吃掉它。先 scp 成 .ps1,再 -File。
后面每一节都可以:
Send-Guest harden.ps1常驻文件则显式指定目录:
Send-Guest dc-ip-sync.ps1 'C:/ProgramData/Maze'
Send-Guest reip.ps1 'C:/ProgramData/Maze'升域、改名会重启,SSH 掉线是正常的,等 22 再连。
7. 硬化
不改主机名。时区、执行策略、密码、RDP、SSH、关防火墙、关 Defender(含云查询和样本提交)、关遥测/广告、关 Windows Update。
硬化的目的是让模板行为可预测:关掉 Windows Update 防止升域过程中自动更新打断;关掉 Defender 整套(实时、MAPS 云、样本上传、WinDefend 服务)避免脚本被误杀、也避免靶机往外打云;关掉 DiagTrack 和 AllowTelemetry,模板不出网也不该把使用数据交出去;关掉休眠防止磁盘上留 hiberfil.sys,同时加快导出。
$ErrorActionPreference = 'Continue'
Set-TimeZone -Id 'China Standard Time'
Set-ExecutionPolicy RemoteSigned -Scope LocalMachine -Force
Set-LocalUser -Name Administrator -PasswordNeverExpires $true
net user Administrator "Admin@1234"
powercfg -h off
powercfg /setactive SCHEME_MIN
powercfg /change standby-timeout-ac 0
powercfg /change hibernate-timeout-ac 0
powercfg /change monitor-timeout-ac 0
Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server' -Name 'fDenyTSConnections' -Value 0
Set-Service TermService -StartupType Automatic
Start-Service TermService
Set-Service sshd -StartupType Automatic
Start-Service sshd
Set-NetFirewallProfile -Profile Domain,Private,Public -Enabled False
Set-MpPreference -DisableRealtimeMonitoring $true -ErrorAction Continue
Set-MpPreference -MAPSReporting 0 -SubmitSamplesConsent 2 -ErrorAction Continue
Set-MpPreference -DisableBlockAtFirstSeen $true -DisableIOAVProtection $true `
-DisableBehaviorMonitoring $true -DisableScriptScanning $true `
-DisableArchiveScanning $true -DisableIntrusionPreventionSystem $true -ErrorAction Continue
Add-MpPreference -ExclusionPath 'C:\ProgramData\Maze','C:\Windows\Temp' -ErrorAction Continue
$def = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows Defender'
New-Item -Path $def -Force | Out-Null
Set-ItemProperty -Path $def -Name DisableAntiSpyware -Value 1 -Type DWord
New-Item -Path "$def\Real-Time Protection" -Force | Out-Null
Set-ItemProperty -Path "$def\Real-Time Protection" -Name DisableRealtimeMonitoring -Value 1 -Type DWord
New-Item -Path "$def\Spynet" -Force | Out-Null
Set-ItemProperty -Path "$def\Spynet" -Name SpynetReporting -Value 0 -Type DWord
Set-ItemProperty -Path "$def\Spynet" -Name SubmitSamplesConsent -Value 2 -Type DWord
foreach ($svc in @('WinDefend','WdNisSvc','Sense','SecurityHealthService')) {
Stop-Service $svc -Force -ErrorAction SilentlyContinue
Set-Service $svc -StartupType Disabled -ErrorAction SilentlyContinue
}
Uninstall-WindowsFeature -Name Windows-Defender -ErrorAction SilentlyContinue | Out-Null
foreach ($svc in @('DiagTrack','dmwappushservice')) {
Stop-Service $svc -Force -ErrorAction SilentlyContinue
Set-Service $svc -StartupType Disabled -ErrorAction SilentlyContinue
}
$dc = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\DataCollection'
New-Item -Path $dc -Force | Out-Null
Set-ItemProperty -Path $dc -Name AllowTelemetry -Value 0 -Type DWord
$dc2 = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\DataCollection'
New-Item -Path $dc2 -Force | Out-Null
Set-ItemProperty -Path $dc2 -Name AllowTelemetry -Value 0 -Type DWord
$cc = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\CloudContent'
New-Item -Path $cc -Force | Out-Null
Set-ItemProperty -Path $cc -Name DisableWindowsConsumerFeatures -Value 1 -Type DWord
Set-ItemProperty -Path $cc -Name DisableCloudOptimizedContent -Value 1 -Type DWord
$ad = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\AdvertisingInfo'
New-Item -Path $ad -Force | Out-Null
Set-ItemProperty -Path $ad -Name DisabledByGroupPolicy -Value 1 -Type DWord
$ws = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\Windows Search'
New-Item -Path $ws -Force | Out-Null
Set-ItemProperty -Path $ws -Name AllowCortana -Value 0 -Type DWord
Set-ItemProperty -Path $ws -Name AllowCloudSearch -Value 0 -Type DWord
$sqm = 'HKLM:\SOFTWARE\Policies\Microsoft\SQMClient\Windows'
New-Item -Path $sqm -Force | Out-Null
Set-ItemProperty -Path $sqm -Name CEIPEnable -Value 0 -Type DWord
Get-ScheduledTask -ErrorAction SilentlyContinue |
Where-Object { $_.TaskName -match 'Consolidator|UsbCeip|KernelCeip|Microsoft Compatibility Appraiser|ProgramDataUpdater' } |
Disable-ScheduledTask -ErrorAction SilentlyContinue | Out-Null
Set-Service wuauserv -StartupType Disabled
Stop-Service wuauserv -Force -ErrorAction SilentlyContinue
Set-SmbServerConfiguration -EnableSMB1Protocol $false -Force -ErrorAction SilentlyContinue
Set-Service WerSvc -StartupType Disabled -ErrorAction SilentlyContinue
Get-ScheduledTask -TaskName ServerManager -ErrorAction SilentlyContinue |
Disable-ScheduledTask -ErrorAction SilentlyContinue8. 改名 DC
升域前主机名必须是 DC。域控的主机名一旦升域就不能随意改,所以这一步要在升域之前做掉。
Rename-Computer -NewName 'DC' -Force
Restart-Computer -Force改名后要重启。重启后等 SSH:
Test-NetConnection -ComputerName <靶机IP> -Port 22
& $sshpass -e ssh @opts "${User}@${IP}" 'hostname'应输出 DC。
到这一步可以打个快照。
9. 升域
升域前把当前 DHCP 地址钉成静态,DNS 指向自己,并把原来的 DNS 记下来给后面做转发。网卡名按 VMware 默认 Ethernet0。
这一步是整个模板最关键的环节:域控必须有一个稳定的 IP,否则重启后换地址,DNS 记录会失配;DNS 必须指向自己,因为升域时要在本地 DNS 里写 _msdcs、_sites 等记录。原来的 DNS 当场设成转发器,不要写成文件。
$ErrorActionPreference = 'Continue'
$if = 'Ethernet0'
$maze = 'C:\ProgramData\Maze'
New-Item -ItemType Directory -Path $maze -Force | Out-Null
$addr = Get-NetIPAddress -InterfaceAlias $if -AddressFamily IPv4 |
Where-Object { $_.IPAddress -notlike '169.254.*' -and $_.IPAddress -ne '127.0.0.1' } |
Select-Object -First 1
if (-not $addr) { throw 'NO_IPV4' }
$ip = $addr.IPAddress
$prefix = $addr.PrefixLength
$gw = (Get-NetRoute -DestinationPrefix '0.0.0.0/0' -ErrorAction SilentlyContinue |
Select-Object -First 1).NextHop
$origDns = (Get-DnsClientServerAddress -InterfaceAlias $if -AddressFamily IPv4).ServerAddresses |
Where-Object { $_ -and $_ -ne $ip -and $_ -ne '127.0.0.1' }
Set-NetIPInterface -InterfaceAlias $if -Dhcp Disabled
if ($gw) {
New-NetIPAddress -InterfaceAlias $if -IPAddress $ip -PrefixLength $prefix -DefaultGateway $gw -ErrorAction SilentlyContinue
} else {
New-NetIPAddress -InterfaceAlias $if -IPAddress $ip -PrefixLength $prefix -ErrorAction SilentlyContinue
}
Set-DnsClientServerAddress -InterfaceAlias $if -ServerAddresses $ip
Install-WindowsFeature -Name AD-Domain-Services,DNS -IncludeManagementTools
if ($origDns.Count -gt 0) {
Set-DnsServerForwarder -IPAddress $origDns -ErrorAction SilentlyContinue
}
$DSRM = ConvertTo-SecureString 'MazeDsrm!2026' -AsPlainText -Force
Install-ADDSForest `
-DomainName 'maze.sec' `
-DomainNetbiosName 'MAZE' `
-InstallDns `
-SafeModeAdministratorPassword $DSRM `
-ForceInstall-ADDSForest 会自己重启,可能要 5~15 分钟。SSH 掉线后继续探测 22。
DSRM 密码(目录服务还原模式)建议记下来,虽然模板本身用不到,但克隆出来的靶机如果要做 AD 恢复类题目会用得上。
10. 林根 PDC 对时
默认不做。升域后 w32tm /query /source 是 NT5DS,看起来像没对时。实测:只要 VMware Tools 在,暂停再启用虚拟机,客户机时间会对齐宿主机。模板日常靠这个就够,外部 NTP 只在这些情况再配:宿主机自己也不准、需要跟公网时间对齐、或者这台机不跑 VMware Tools。配了 NTP 就要关掉 VMICTimeProvider,避免和 Tools 抢源。
“林根 PDC 对时”指的是:把整个 Active Directory 林最顶层、拥有 PDC 模拟器角色的那台域控制器,配置为从外部 NTP 取时。要做的话,命令如下。
$ntpPeer = 'time.windows.com,0x8'
w32tm /config /manualpeerlist:$ntpPeer /syncfromflags:manual /reliable:yes /update
reg add "HKLM\SYSTEM\CurrentControlSet\Services\W32Time\Config" /v MaxPosPhaseCorrection /t REG_DWORD /d 4294967295 /f
reg add "HKLM\SYSTEM\CurrentControlSet\Services\W32Time\Config" /v MaxNegPhaseCorrection /t REG_DWORD /d 4294967295 /f
Set-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpClient' -Name SpecialPollInterval -Type DWord -Value 300 -Force
Set-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpClient' -Name Enabled -Type DWord -Value 1 -Force
Set-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\W32Time\Parameters' -Name Type -Type String -Value 'NTP' -Force
Set-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\W32Time\Parameters' -Name NtpServer -Type String -Value $ntpPeer -Force
$vmic = 'HKLM:\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\VMICTimeProvider'
if (Test-Path $vmic) {
Set-ItemProperty -Path $vmic -Name Enabled -Type DWord -Value 0 -Force
}
Set-Service w32time -StartupType Automatic
Restart-Service w32time -Force
w32tm /resync /force
w32tm /query /source
w32tm /query /status几个关键点:
MaxPosPhaseCorrection/MaxNegPhaseCorrection设成最大,是为了让暂停一整晚回来这种大偏差能被一次纠正掉,而不是被系统以“差距太大”为由拒绝校时。- 配了外部 NTP 再关
VMICTimeProvider:Tools 和 NTP 会抢源。不配 NTP 就别关,让 Tools 继续在暂停恢复时灌时间。 w32tm /query /source应输出time.windows.com,0x8。若仍是Local CMOS Clock,先确认 DNS 能解析time.windows.com(升域后要有转发器),再w32tm /resync /force。- 跳过本节去第 11 节即可。
11. DNS 指自己和转发器
不装 CA。底盘只要 DNS 客户端指自己;转发器若升域时没带过来,用默认网关。企业根 CA 是挑战层开关,见 可复用部署经验.md 第 2.0 节。
$ErrorActionPreference = 'Continue'
$if = 'Ethernet0'
$addr = Get-NetIPAddress -InterfaceAlias $if -AddressFamily IPv4 |
Where-Object { $_.IPAddress -notlike '169.254.*' -and $_.IPAddress -ne '127.0.0.1' } |
Select-Object -First 1
$ip = $addr.IPAddress
$gw = (Get-NetRoute -DestinationPrefix '0.0.0.0/0' -ErrorAction SilentlyContinue |
Select-Object -First 1).NextHop
$dns = Get-DnsClientServerAddress -InterfaceAlias $if -AddressFamily IPv4
if ($dns.ServerAddresses -notcontains $ip) {
Set-DnsClientServerAddress -InterfaceAlias $if -ServerAddresses $ip
}
$fwd = @()
try { $fwd = @((Get-DnsServerForwarder).IPAddress | ForEach-Object { $_.IPAddressToString }) } catch { }
if ($fwd.Count -eq 0 -and $gw -and $gw -ne $ip) {
Set-DnsServerForwarder -IPAddress $gw
}
Get-DnsClientServerAddress -InterfaceAlias $if -AddressFamily IPv4
Get-DnsServerForwarder | Format-List IPAddress
Get-Service NTDS,DNS,sshd,WinRM | Format-Table Name,Status,StartType
Get-ADDomain | Select-Object DNSRoot,NetBIOSName,DistinguishedName12. 开机同步 IP 和 DNS
DC 克隆到别的网段时,必须把 DNS 指到新 IP,并重注册 A 记录。开机任务默认 DHCP。
这个任务解决的痛点:克隆模板到新环境后,网卡拿到新地址,但 AD 里 DC 的 A 记录还指着旧 IP,DNS 客户端也可能还指着旧的自己,Kerberos、LDAP 全都会出问题。做成开机自动跑,就不用每次克隆完都记得手工改。
12.1 开机自启脚本 C:\ProgramData\Maze\dc-ip-sync.ps1
$ErrorActionPreference = 'Continue'
$maze = 'C:\ProgramData\Maze'
$logDir = Join-Path $maze 'logs'
New-Item -ItemType Directory -Path $logDir -Force | Out-Null
$log = Join-Path $logDir 'dc-ip-sync.log'
"[{0}] start" -f (Get-Date) | Out-File $log -Append -Encoding utf8
# 取第一个 Up 的物理网卡
$if = (Get-NetAdapter | Where-Object { $_.Status -eq 'Up' -and $_.InterfaceDescription -notlike '*Loopback*' } | Select-Object -First 1).Name
# 拿 IP:DHCP 就 renew,静态就跳过
Set-NetIPInterface -InterfaceAlias $if -Dhcp Enabled
ipconfig /renew | Out-Null
$ip = (Get-NetIPAddress -InterfaceAlias $if -AddressFamily IPv4 |
Where-Object { $_.IPAddress -notlike '169.254.*' -and $_.IPAddress -ne '127.0.0.1' } |
Select-Object -First 1).IPAddress
"[{0}] if={1} ip={2}" -f (Get-Date), $if, $ip | Out-File $log -Append -Encoding utf8
# DNS 指向自己 + 重注册
Set-DnsClientServerAddress -InterfaceAlias $if -ServerAddresses $ip
ipconfig /registerdns | Out-Null
nltest /dsregdns
# 清理 DNS 里旧 A 记录,补新 A 记录
Import-Module DnsServer
$zone = (Get-ADDomain).DNSRoot
$name = $env:COMPUTERNAME
Get-DnsServerResourceRecord -ZoneName $zone -Name $name -RRType A |
Where-Object { $_.RecordData.IPv4Address.IPAddressToString -ne $ip } |
ForEach-Object { Remove-DnsServerResourceRecord -ZoneName $zone -Name $name -RRType A -RecordData $_.RecordData -Force }
if (-not (Get-DnsServerResourceRecord -ZoneName $zone -Name $name -RRType A |
Where-Object { $_.RecordData.IPv4Address.IPAddressToString -eq $ip })) {
Add-DnsServerResourceRecordA -ZoneName $zone -Name $name -IPv4Address $ip -CreatePtr
}
"[{0}] done" -f (Get-Date) | Out-File $log -Append -Encoding utf812.2 注册开机任务
任务名与第 14 节校验一致,用 Maze-DC-IP-Sync,动作路径直接指向统一目录。下面这段存成 install-ip-sync.ps1,投递执行:
$ErrorActionPreference = 'Stop'
$base = 'C:\ProgramData\Maze'
New-Item -ItemType Directory -Path $base -Force | Out-Null
$action = New-ScheduledTaskAction -Execute 'powershell.exe' `
-Argument '-NoProfile -ExecutionPolicy Bypass -File "C:\ProgramData\Maze\dc-ip-sync.ps1"'
$trigger = New-ScheduledTaskTrigger -AtStartup
$principal = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest
$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable `
-AllowStartIfOnBatteries -DontStopIfGoingOnBatteries `
-ExecutionTimeLimit (New-TimeSpan -Minutes 15)
Register-ScheduledTask `
-TaskName 'Maze-DC-IP-Sync' `
-Action $action `
-Trigger $trigger `
-Principal $principal `
-Settings $settings `
-Description 'Keep DC IP/DNS/A records in sync at boot' `
-Force | Out-Null
Get-ScheduledTask -TaskName 'Maze-DC-IP-Sync' |
Select-Object TaskName, State |
Format-Table -AutoSize
Get-ScheduledTaskInfo -TaskName 'Maze-DC-IP-Sync' |
Select-Object LastRunTime, LastTaskResult, NextRunTime |
Format-List投递顺序:先把 dc-ip-sync.ps1 scp 到统一目录,再投递并执行 install-ip-sync.ps1。两个文件都落 C:\ProgramData\Maze,避免被第 13 节清 C:\Windows\Temp 时误删:
& $sshpass -e scp @opts (Join-Path $here 'dc-ip-sync.ps1') "${User}@${IP}:C:/ProgramData/Maze/dc-ip-sync.ps1"
Send-Guest install-ip-sync.ps1 'C:/ProgramData/Maze'注册完看输出:State 应为 Ready;LastTaskResult 在还没跑过时通常是 267011(0x41303,表示“任务尚未运行”),这是正常的。等下次开机或手动 Start-ScheduledTask -TaskName 'Maze-DC-IP-Sync' 跑过一次后,再回来看应该是 0。如果一直是 0x41303,说明任务没触发,去事件查看器 Microsoft-Windows-TaskScheduler/Operational 查。
13. 隐私和收尾
关掉 PowerShell 历史、转录、脚本块日志,钉死 Windows Update 策略,清临时文件。
这一步一方面是为了让模板“干净”,另一方面也是为了不让后续出题时的操作留下痕迹干扰选手。
$ErrorActionPreference = 'Continue'
$profilePath = Join-Path $PSHOME 'profile.ps1'
$marker = 'Set-PSReadLineOption -HistorySaveStyle SaveNothing'
if (-not (Test-Path $profilePath)) { New-Item -ItemType File -Path $profilePath -Force | Out-Null }
$profileText = Get-Content $profilePath -Raw -ErrorAction SilentlyContinue
if ($profileText -notmatch [regex]::Escape($marker)) {
Add-Content -Path $profilePath -Value ('if (Get-Module -ListAvailable PSReadLine) { ' + $marker + ' }')
}
$history = Join-Path $env:APPDATA 'Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt'
if (Test-Path $history) { Remove-Item $history -Force -ErrorAction SilentlyContinue }
$policyItems = @(
@{ Path = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\Transcription'
Values = @{ EnableTranscripting = 0; EnableInvocationHeader = 0 } },
@{ Path = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging'
Values = @{ EnableScriptBlockLogging = 0; EnableScriptBlockInvocationLogging = 0 } },
@{ Path = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging'
Values = @{ EnableModuleLogging = 0 } }
)
foreach ($item in $policyItems) {
New-Item -Path $item.Path -Force | Out-Null
foreach ($name in $item.Values.Keys) {
Set-ItemProperty -Path $item.Path -Name $name -Value $item.Values[$name] -Type DWord
}
}
wevtutil cl 'Microsoft-Windows-PowerShell/Operational' 2>$null
wevtutil cl 'Windows PowerShell' 2>$null收尾:
$ErrorActionPreference = 'Continue'
$au = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU'
New-Item -Path $au -Force | Out-Null
Set-ItemProperty -Path $au -Name NoAutoUpdate -Value 1 -Type DWord
Set-ItemProperty -Path $au -Name AUOptions -Value 1 -Type DWord
sc.exe config wuauserv start= disabled | Out-Null
Stop-Service wuauserv -Force -ErrorAction SilentlyContinue
Set-SmbServerConfiguration -EnableSMB1Protocol $false -Force -ErrorAction SilentlyContinue
wevtutil el | ForEach-Object { wevtutil cl "$_" 2>$null }
Remove-Item C:\Windows\Temp\* -Recurse -Force -ErrorAction SilentlyContinue
Remove-Item $env:TEMP\* -Recurse -Force -ErrorAction SilentlyContinue
Remove-Item C:\Windows\SoftwareDistribution\Download\* -Recurse -Force -ErrorAction SilentlyContinue
Clear-RecycleBin -Force -ErrorAction SilentlyContinue注意这里只清 C:\Windows\Temp 和用户 TEMP,不动 C:\ProgramData\Maze。这样开机同步脚本、日志和后续挑战层依赖的文件都保留着。校验脚本要在这之后再拷,因为它走的是 C:\Windows\Temp 一次性投递。
14. 校验
Write-Output ('HOST=' + $env:COMPUTERNAME)
Write-Output ('IP=' + ((Get-NetIPAddress -InterfaceAlias Ethernet0 -AddressFamily IPv4).IPAddress -join ','))
Get-NetIPInterface -InterfaceAlias Ethernet0 -AddressFamily IPv4 | Format-Table InterfaceAlias,Dhcp
Get-DnsClientServerAddress -InterfaceAlias Ethernet0 -AddressFamily IPv4
Get-Service NTDS,DNS,sshd,WinRM | Format-Table Name,Status,StartType
Get-NetFirewallProfile | Format-Table Name,Enabled
Get-NetTCPConnection -State Listen |
Where-Object { $_.LocalPort -in 22,53,88,135,389,445,636,3389,5985 } |
Format-Table LocalAddress,LocalPort
Get-ScheduledTask -TaskName 'Maze-DC-IP-Sync' | Format-Table TaskName,State
Get-ADDomain | Select-Object DNSRoot,NetBIOSName
Import-Module DnsServer
Get-DnsServerResourceRecord -ZoneName maze.sec -Name DC -RRType A
Test-Path 'C:\ProgramData\Maze\dc-ip-sync.ps1'
Test-Path 'C:\ProgramData\Maze\reip.ps1'
Test-Path 'C:\Program Files\VMware\VMware Tools\vmtoolsd.exe'
dcdiag /test:dns /test:advertising
w32tm /query /source
w32tm /query /status过关标准:
- 主机名
DC,域maze.sec NTDS、DNS、sshd在跑;WinRM 保持系统默认- 防火墙全关
- 任务
Maze-DC-IP-Sync在,且C:\ProgramData\Maze\dc-ip-sync.ps1、C:\ProgramData\Maze\reip.ps1都存在 - DNS 里
DC的 A 记录等于当前 IPv4 - VMware Tools 已安装(
vmtoolsd.exe存在) - Defender:实时关、MAPS=0、样本不提交、
WinDefend停;DiagTrack停,AllowTelemetry=0 - 时间:默认不要求外部 NTP。
w32tm /query /source是Local CMOS Clock也算过;暂停再启用后,客户机时间应与宿主机对齐。只有做了第 10 节,才要求源是time.windows.com,0x8
15. 改 IP、克隆、导出
15.1 导入后换 IP
开机任务默认 DHCP。要立刻钉成静态 IP,用 reip.ps1。因为它一跑就把当前连接踢掉,不要在 SSH 里跑,要先 scp 到靶机统一目录,再到控制台或 RDP 执行。
本机投递:
& $sshpass -e scp @opts (Join-Path $here 'reip.ps1') "${User}@${IP}:C:/ProgramData/Maze/reip.ps1"靶机控制台 / RDP:
powershell -ExecutionPolicy Bypass -File C:\ProgramData\Maze\reip.ps1 `
-InterfaceAlias Ethernet0 `
-IPAddress <新IP> `
-PrefixLength 24 `
-Gateway <网关>DHCP:
powershell -ExecutionPolicy Bypass -File C:\ProgramData\Maze\reip.ps1 -InterfaceAlias Ethernet0 -Dhcpreip.ps1 正文:
[CmdletBinding()]
param(
[string]$InterfaceAlias = '',
[string]$IPAddress = '',
[int]$PrefixLength = 24,
[string]$Gateway = '',
[switch]$Dhcp
)
$ErrorActionPreference = 'Stop'
if (-not $InterfaceAlias) {
$InterfaceAlias = (Get-NetAdapter |
Where-Object { $_.Status -eq 'Up' -and $_.InterfaceDescription -notlike '*Loopback*' } |
Select-Object -First 1).Name
}
if (-not $InterfaceAlias) { throw 'No active network adapter found' }
$old = Get-NetIPAddress -InterfaceAlias $InterfaceAlias -AddressFamily IPv4 -ErrorAction SilentlyContinue |
Where-Object { $_.IPAddress -notlike '169.254.*' -and $_.IPAddress -ne '127.0.0.1' }
$oldIPs = @($old | ForEach-Object { $_.IPAddress })
Write-Output ('OLD_IP=' + ($oldIPs -join ','))
if ($Dhcp) {
Set-NetIPInterface -InterfaceAlias $InterfaceAlias -Dhcp Enabled
} else {
if (-not $IPAddress) { throw 'Provide -IPAddress or use -Dhcp' }
Set-NetIPInterface -InterfaceAlias $InterfaceAlias -Dhcp Disabled
Remove-NetIPAddress -InterfaceAlias $InterfaceAlias -AddressFamily IPv4 -Confirm:$false -ErrorAction SilentlyContinue
Remove-NetRoute -InterfaceAlias $InterfaceAlias -Confirm:$false -ErrorAction SilentlyContinue
if ($Gateway) {
New-NetIPAddress -InterfaceAlias $InterfaceAlias -IPAddress $IPAddress -PrefixLength $PrefixLength -DefaultGateway $Gateway | Out-Null
} else {
New-NetIPAddress -InterfaceAlias $InterfaceAlias -IPAddress $IPAddress -PrefixLength $PrefixLength | Out-Null
}
}
Start-Sleep -Seconds 2
$new = Get-NetIPAddress -InterfaceAlias $InterfaceAlias -AddressFamily IPv4 |
Where-Object { $_.IPAddress -notlike '169.254.*' -and $_.IPAddress -ne '127.0.0.1' } |
Select-Object -First 1
if (-not $new) { throw 'No IPv4 after re-IP' }
$newIP = $new.IPAddress
Write-Output ('NEW_IP=' + $newIP)
$isDC = $false
try { Get-ADDomain -ErrorAction Stop | Out-Null; $isDC = $true } catch { $isDC = $false }
if ($isDC) {
Set-DnsClientServerAddress -InterfaceAlias $InterfaceAlias -ServerAddresses $newIP
ipconfig /registerdns | Out-Null
nltest /dsregdns 2>&1 | Out-Null
Start-Sleep -Seconds 3
Import-Module DnsServer -ErrorAction SilentlyContinue
$zone = (Get-ADDomain).DNSRoot
$name = $env:COMPUTERNAME
$records = Get-DnsServerResourceRecord -ZoneName $zone -Name $name -RRType A -ErrorAction SilentlyContinue
foreach ($r in @($records)) {
$addr = $r.RecordData.IPv4Address.IPAddressToString
if ($addr -and $addr -ne $newIP) {
Remove-DnsServerResourceRecord -ZoneName $zone -Name $name -RRType A -RecordData $r.RecordData -Force -ErrorAction SilentlyContinue
Write-Output ('REMOVED_OLD_A=' + $addr)
}
}
$current = Get-DnsServerResourceRecord -ZoneName $zone -Name $name -RRType A -ErrorAction SilentlyContinue |
Where-Object { $_.RecordData.IPv4Address.IPAddressToString -eq $newIP }
if (-not $current) {
Add-DnsServerResourceRecordA -ZoneName $zone -Name $name -IPv4Address $newIP -CreatePtr -ErrorAction SilentlyContinue
Write-Output ('ADDED_A=' + $newIP)
}
dcdiag /test:dns /test:advertising 2>&1 | Select-Object -Last 30
Write-Output '--- AD DOMAIN ---'
Get-ADDomain | Select-Object DNSRoot, NetBIOSName | Format-List
} else {
Write-Output 'NOT_A_DC: IP changed; set DNS/forwarders for this environment as needed'
}行为说明:
- 不传
-InterfaceAlias时自动取第一个 Up 的物理网卡;找不到直接报错。 - 先打印
OLD_IP=,再改地址,再打印NEW_IP=,方便对照。 - 静态模式会先
Remove-NetIPAddress/Remove-NetRoute清掉旧地址和路由,再建新的;-Gateway可省略。 -Dhcp只切回 DHCP,不做后续 AD/DNS 修复。- 脚本自己判断是不是 DC:
Get-ADDomain成功才走 DNS 指自己、registerdns、nltest /dsregdns、删旧 A 补新 A、dcdiag这一段;非 DC 只改 IP,并提示“DNS/转发器按环境自行设置”。 - 所有输出都是
KEY=VALUE形式(OLD_IP、NEW_IP、REMOVED_OLD_A、ADDED_A),控制台跑完直接看得到结果。
域名单不随 IP 变:maze.sec、DC.maze.sec。CA 不进底盘。
15.2 克隆
- 同一二层网络不要同时开两份
maze.sec/DC - 隔离网络可以各自一份
- 新题:克隆模板 → 改 IP → 再部署挑战层
- 不要在模板上直接出题,不要改域名
这两条“不要”是铁律:同时开两份同域 DC 会导致复制冲突;在模板上直接出题会把题目状态固化进母机,下一道题就脏了。
15.3 清理、零填充、压缩
先在客户机里清残留、再用 sdelete -z 把空闲簇写成零,最后关机(不要保存内存),在宿主机上 vmware-vdiskmanager -k 才能把精简磁盘收回来。只跑 sdelete 不压缩,宿主机 vmdk 会先变大。
有快照时 -k 只压当前增量;新模板先做完再打快照。
1. 客户机清理 + 零填充
本机先下 sdelete64.exe,scp 进去再 -File 跑。不要在控制台粘中文。
Invoke-WebRequest -Uri 'https://live.sysinternals.com/sdelete64.exe' `
-OutFile "$env:TEMP\sdelete64.exe" -UseBasicParsing
& $sshpass -e scp @opts "$env:TEMP\sdelete64.exe" "${User}@${IP}:C:/Windows/Temp/sdelete64.exe"客户机脚本(存成 clean-sdelete.ps1,Send-Guest):
$ErrorActionPreference = 'Continue'
Write-Output ('C_BEFORE used={0:N2}GB free={1:N2}GB' -f ((Get-PSDrive C).Used/1GB), ((Get-PSDrive C).Free/1GB))
Get-ChildItem 'C:\Windows\Temp' -Force -ErrorAction SilentlyContinue |
Where-Object { $_.Name -notin @('sdelete64.exe','clean-sdelete.ps1') } |
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
Remove-Item "$env:TEMP\*" -Recurse -Force -ErrorAction SilentlyContinue
Remove-Item 'C:\Windows\SoftwareDistribution\Download\*' -Recurse -Force -ErrorAction SilentlyContinue
Clear-RecycleBin -Force -ErrorAction SilentlyContinue
$hist = Join-Path $env:APPDATA 'Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt'
if (Test-Path $hist) { Remove-Item $hist -Force -ErrorAction SilentlyContinue }
wevtutil el | ForEach-Object { wevtutil cl "$_" 2>$null }
Get-ChildItem 'C:\ProgramData\Maze' -Force -ErrorAction SilentlyContinue |
Where-Object { $_.Name -notin @('dc-ip-sync.ps1','reip.ps1','logs') } |
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
if (Test-Path 'C:\ProgramData\Maze\logs') {
Get-ChildItem 'C:\ProgramData\Maze\logs' -Force -ErrorAction SilentlyContinue |
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
}
$sd = 'C:\Windows\Temp\sdelete64.exe'
& $sd -accepteula -z C:
Write-Output ('SDELETE_EXIT=' + $LASTEXITCODE)
Remove-Item $sd -Force -ErrorAction SilentlyContinue
Write-Output ('C_AFTER used={0:N2}GB free={1:N2}GB' -f ((Get-PSDrive C).Used/1GB), ((Get-PSDrive C).Free/1GB))sdelete -z 只填零,一轮即可,不要 -c(随机填充更慢)。空闲 30 GB 大约十几分钟。SDELETE_EXIT=0 且出现 1 drive cleaned 才算完。
2. 关机
Stop-Computer -ForceVMware 里选 Power Off,不要 Suspend,不要保存内存。光驱断开,去掉本机 ISO,声卡/USB 关掉。
3. 宿主机压缩
VM 必须已关机。-k 作用在当前正在用的 vmdk(有快照则是 xxx-00000N.vmdk,不是底座那个)。
"C:\Program Files (x86)\VMware\VMware Workstation\vmware-vdiskmanager.exe" -k "<当前vmdk路径>"压缩完再打干净快照。单 DC 隔离环境可以回滚;多 DC 不要回滚,会 USN rollback。
原文 https://blog.csdn.net/2301_79518550/article/details/168663308
跳到内容