windows-hardening

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Windows Hardening

Windows服务器加固

Secure Windows servers following Microsoft security baselines and CIS benchmarks.
遵循Microsoft安全基线和CIS基准对Windows服务器进行安全加固。

When to Use This Skill

适用场景

Use this skill when:
  • Hardening new Windows Server deployments
  • Implementing CIS benchmarks or Microsoft security baselines
  • Preparing for compliance audits (SOC2, PCI-DSS, HIPAA)
  • Configuring security features after a security incident
  • Setting up Windows Defender and advanced threat protection
  • Establishing Group Policy security standards for a domain
在以下场景中使用本技能:
  • 加固新部署的Windows Server
  • 实施CIS基准或Microsoft安全基线
  • 为合规审计做准备(SOC2、PCI-DSS、HIPAA)
  • 安全事件发生后配置安全功能
  • 配置Windows Defender及高级威胁防护
  • 为域环境制定Group Policy安全标准

Prerequisites

前置条件

  • Windows Server 2019 or later (2022 recommended)
  • Local Administrator or Domain Admin access
  • PowerShell 5.1+ (built into Windows Server)
  • Group Policy Management Console for domain environments
  • Microsoft Security Compliance Toolkit (recommended)
  • Windows Server 2019或更高版本(推荐2022)
  • 本地管理员或域管理员权限
  • PowerShell 5.1及以上版本(Windows Server内置)
  • 域环境下的Group Policy管理控制台
  • Microsoft安全合规工具包(推荐使用)

Security Baseline Deployment

安全基线部署

powershell
undefined
powershell
undefined

Download and apply Microsoft Security Baseline

Download and apply Microsoft Security Baseline

Install Security Compliance Toolkit modules

Install Security Compliance Toolkit modules

Install-Module -Name SecurityPolicyDsc -Force Install-Module -Name AuditPolicyDsc -Force Install-Module -Name PSDesiredStateConfiguration -Force
Install-Module -Name SecurityPolicyDsc -Force Install-Module -Name AuditPolicyDsc -Force Install-Module -Name PSDesiredStateConfiguration -Force

Import and apply a security baseline GPO (from Security Compliance Toolkit)

Import and apply a security baseline GPO (from Security Compliance Toolkit)

Extract the toolkit, then:

Extract the toolkit, then:

Import-Module "$env:USERPROFILE\Downloads\SCT\LGPO.exe"
Import-Module "$env:USERPROFILE\Downloads\SCT\LGPO.exe"

Apply local group policy from baseline

Apply local group policy from baseline

.\LGPO.exe /g ".\GPO{baseline-gpo-guid}"
.\LGPO.exe /g ".\GPO{baseline-gpo-guid}"

Export current security policy for review

Export current security policy for review

secedit /export /cfg C:\SecurityAudit\current-policy.inf
undefined
secedit /export /cfg C:\SecurityAudit\current-policy.inf
undefined

Account Policies

账户策略

powershell
undefined
powershell
undefined

============================================

============================================

Password Policy Configuration

Password Policy Configuration

============================================

============================================

Set password policy via net accounts

Set password policy via net accounts

net accounts /minpwlen:14 /maxpwage:90 /minpwage:1 /uniquepw:24
net accounts /minpwlen:14 /maxpwage:90 /minpwage:1 /uniquepw:24

Or configure via PowerShell DSC

Or configure via PowerShell DSC

Configuration PasswordPolicy { Import-DscResource -ModuleName SecurityPolicyDsc
Node localhost {
    AccountPolicy PasswordPolicy {
        Name                                = "PasswordPolicy"
        Minimum_Password_Length              = 14
        Maximum_Password_Age                = 90
        Minimum_Password_Age                = 1
        Enforce_password_history             = 24
        Password_must_meet_complexity_requirements = "Enabled"
        Store_passwords_using_reversible_encryption = "Disabled"
    }
}
}
Configuration PasswordPolicy { Import-DscResource -ModuleName SecurityPolicyDsc
Node localhost {
    AccountPolicy PasswordPolicy {
        Name                                = "PasswordPolicy"
        Minimum_Password_Length              = 14
        Maximum_Password_Age                = 90
        Minimum_Password_Age                = 1
        Enforce_password_history             = 24
        Password_must_meet_complexity_requirements = "Enabled"
        Store_passwords_using_reversible_encryption = "Disabled"
    }
}
}

============================================

============================================

Account Lockout Policy

Account Lockout Policy

============================================

============================================

net accounts /lockoutthreshold:5 /lockoutwindow:30 /lockoutduration:30
net accounts /lockoutthreshold:5 /lockoutwindow:30 /lockoutduration:30

============================================

============================================

User Account Hardening

User Account Hardening

============================================

============================================

Rename and disable default accounts

Rename and disable default accounts

Rename-LocalUser -Name "Administrator" -NewName "LocalAdmin" Disable-LocalUser -Name "Guest" Disable-LocalUser -Name "DefaultAccount"
Rename-LocalUser -Name "Administrator" -NewName "LocalAdmin" Disable-LocalUser -Name "Guest" Disable-LocalUser -Name "DefaultAccount"

Remove unnecessary local accounts

Remove unnecessary local accounts

$unnecessaryAccounts = Get-LocalUser | Where-Object { $.Enabled -eq $true -and $.Name -notin @("LocalAdmin", "SYSTEM", "NetworkService", "LocalService") } foreach ($account in $unnecessaryAccounts) { Write-Host "Review account: $($account.Name) - Last logon: $($account.LastLogon)" }
$unnecessaryAccounts = Get-LocalUser | Where-Object { $.Enabled -eq $true -and $.Name -notin @("LocalAdmin", "SYSTEM", "NetworkService", "LocalService") } foreach ($account in $unnecessaryAccounts) { Write-Host "Review account: $($account.Name) - Last logon: $($account.LastLogon)" }

Configure Local Administrator Password Solution (LAPS)

Configure Local Administrator Password Solution (LAPS)

Install LAPS module

Install LAPS module

Install-WindowsFeature -Name RSAT-AD-PowerShell Import-Module AdmPwd.PS
Install-WindowsFeature -Name RSAT-AD-PowerShell Import-Module AdmPwd.PS

Configure LAPS for the OU

Configure LAPS for the OU

Set-AdmPwdComputerSelfPermission -OrgUnit "OU=Servers,DC=example,DC=com" Set-AdmPwdReadPasswordPermission -OrgUnit "OU=Servers,DC=example,DC=com" -AllowedPrincipals "Domain Admins"
undefined
Set-AdmPwdComputerSelfPermission -OrgUnit "OU=Servers,DC=example,DC=com" Set-AdmPwdReadPasswordPermission -OrgUnit "OU=Servers,DC=example,DC=com" -AllowedPrincipals "Domain Admins"
undefined

Group Policy Security Settings

Group Policy安全设置

powershell
undefined
powershell
undefined

============================================

============================================

User Rights Assignment (via GPO or local policy)

User Rights Assignment (via GPO or local policy)

============================================

============================================

Restrict remote desktop access

Restrict remote desktop access

Computer Configuration > Policies > Windows Settings > Security Settings > Local Policies > User Rights Assignment

Computer Configuration > Policies > Windows Settings > Security Settings > Local Policies > User Rights Assignment

"Allow log on through Remote Desktop Services" = Administrators, Remote Desktop Users

"Allow log on through Remote Desktop Services" = Administrators, Remote Desktop Users

Deny log on locally for service accounts

Deny log on locally for service accounts

"Deny log on locally" = Service accounts

"Deny log on locally" = Service accounts

Configure via registry (alternative to GPO)

Configure via registry (alternative to GPO)

Restrict anonymous enumeration of SAM accounts

Restrict anonymous enumeration of SAM accounts

Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa" ` -Name "RestrictAnonymousSAM" -Value 1
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa" ` -Name "RestrictAnonymousSAM" -Value 1

Restrict anonymous enumeration of shares

Restrict anonymous enumeration of shares

Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa" ` -Name "RestrictAnonymous" -Value 1
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa" ` -Name "RestrictAnonymous" -Value 1

Do not display last user name

Do not display last user name

Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" ` -Name "DontDisplayLastUserName" -Value 1
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" ` -Name "DontDisplayLastUserName" -Value 1

============================================

============================================

Security Options

Security Options

============================================

============================================

Disable SMBv1 (critical security hardening)

Disable SMBv1 (critical security hardening)

Disable-WindowsOptionalFeature -Online -FeatureName SMB1Protocol -NoRestart Set-SmbServerConfiguration -EnableSMB1Protocol $false -Force
Disable-WindowsOptionalFeature -Online -FeatureName SMB1Protocol -NoRestart Set-SmbServerConfiguration -EnableSMB1Protocol $false -Force

Require SMB signing

Require SMB signing

Set-SmbServerConfiguration -RequireSecuritySignature $true -Force Set-SmbClientConfiguration -RequireSecuritySignature $true -Force
Set-SmbServerConfiguration -RequireSecuritySignature $true -Force Set-SmbClientConfiguration -RequireSecuritySignature $true -Force

Disable LLMNR (prevent credential theft)

Disable LLMNR (prevent credential theft)

New-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\DNSClient" -Force Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\DNSClient" ` -Name "EnableMulticast" -Value 0
New-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\DNSClient" -Force Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\DNSClient" ` -Name "EnableMulticast" -Value 0

Disable NetBIOS over TCP/IP

Disable NetBIOS over TCP/IP

$adapters = Get-WmiObject Win32_NetworkAdapterConfiguration | Where-Object { $_.IPEnabled -eq $true } foreach ($adapter in $adapters) { $adapter.SetTcpipNetbios(2) # 2 = Disable }
$adapters = Get-WmiObject Win32_NetworkAdapterConfiguration | Where-Object { $_.IPEnabled -eq $true } foreach ($adapter in $adapters) { $adapter.SetTcpipNetbios(2) # 2 = Disable }

Disable WDigest (prevent plaintext password caching)

Disable WDigest (prevent plaintext password caching)

Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest" ` -Name "UseLogonCredential" -Value 0
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest" ` -Name "UseLogonCredential" -Value 0

Enable LSA Protection

Enable LSA Protection

Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa" ` -Name "RunAsPPL" -Value 1
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa" ` -Name "RunAsPPL" -Value 1

Configure UAC

Configure UAC

Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System"
    -Name "EnableLUA" -Value 1 Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System"
-Name "ConsentPromptBehaviorAdmin" -Value 2 Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" ` -Name "PromptOnSecureDesktop" -Value 1
undefined
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System"
    -Name "EnableLUA" -Value 1 Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System"
-Name "ConsentPromptBehaviorAdmin" -Value 2 Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" ` -Name "PromptOnSecureDesktop" -Value 1
undefined

Windows Firewall Configuration

Windows防火墙配置

powershell
undefined
powershell
undefined

============================================

============================================

Enable Windows Firewall on all profiles

Enable Windows Firewall on all profiles

============================================

============================================

Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled True
Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled True

Default deny inbound, allow outbound

Default deny inbound, allow outbound

Set-NetFirewallProfile -Profile Domain -DefaultInboundAction Block -DefaultOutboundAction Allow Set-NetFirewallProfile -Profile Public -DefaultInboundAction Block -DefaultOutboundAction Allow Set-NetFirewallProfile -Profile Private -DefaultInboundAction Block -DefaultOutboundAction Allow
Set-NetFirewallProfile -Profile Domain -DefaultInboundAction Block -DefaultOutboundAction Allow Set-NetFirewallProfile -Profile Public -DefaultInboundAction Block -DefaultOutboundAction Allow Set-NetFirewallProfile -Profile Private -DefaultInboundAction Block -DefaultOutboundAction Allow

Enable logging

Enable logging

Set-NetFirewallProfile -Profile Domain -LogAllowed True -LogBlocked True
    -LogFileName "%SystemRoot%\System32\LogFiles\Firewall\pfirewall.log"
-LogMaxSizeKilobytes 32768
Set-NetFirewallProfile -Profile Domain -LogAllowed True -LogBlocked True
    -LogFileName "%SystemRoot%\System32\LogFiles\Firewall\pfirewall.log"
-LogMaxSizeKilobytes 32768

============================================

============================================

Inbound Rules

Inbound Rules

============================================

============================================

Allow RDP from management network only

Allow RDP from management network only

New-NetFirewallRule -DisplayName "Allow RDP - Management"
    -Direction Inbound -Protocol TCP -LocalPort 3389
-RemoteAddress 10.0.100.0/24 -Action Allow -Profile Domain
New-NetFirewallRule -DisplayName "Allow RDP - Management"
    -Direction Inbound -Protocol TCP -LocalPort 3389
-RemoteAddress 10.0.100.0/24 -Action Allow -Profile Domain

Allow WinRM from management network

Allow WinRM from management network

New-NetFirewallRule -DisplayName "Allow WinRM - Management"
    -Direction Inbound -Protocol TCP -LocalPort 5985,5986
-RemoteAddress 10.0.100.0/24 -Action Allow -Profile Domain
New-NetFirewallRule -DisplayName "Allow WinRM - Management"
    -Direction Inbound -Protocol TCP -LocalPort 5985,5986
-RemoteAddress 10.0.100.0/24 -Action Allow -Profile Domain

Allow ICMP from internal networks

Allow ICMP from internal networks

New-NetFirewallRule -DisplayName "Allow ICMP - Internal"
    -Direction Inbound -Protocol ICMPv4 -IcmpType 8
-RemoteAddress 10.0.0.0/8 -Action Allow
New-NetFirewallRule -DisplayName "Allow ICMP - Internal"
    -Direction Inbound -Protocol ICMPv4 -IcmpType 8
-RemoteAddress 10.0.0.0/8 -Action Allow

Allow specific application

Allow specific application

New-NetFirewallRule -DisplayName "Allow IIS HTTPS"
    -Direction Inbound -Protocol TCP -LocalPort 443
-Action Allow -Profile Domain,Private
New-NetFirewallRule -DisplayName "Allow IIS HTTPS"
    -Direction Inbound -Protocol TCP -LocalPort 443
-Action Allow -Profile Domain,Private

Block all other inbound by default (already set above)

Block all other inbound by default (already set above)

============================================

============================================

Outbound Rules (optional - restrict egress)

Outbound Rules (optional - restrict egress)

============================================

============================================

Allow DNS

Allow DNS

New-NetFirewallRule -DisplayName "Allow DNS"
    -Direction Outbound -Protocol UDP -RemotePort 53
-Action Allow
New-NetFirewallRule -DisplayName "Allow DNS"
    -Direction Outbound -Protocol UDP -RemotePort 53
-Action Allow

Allow HTTPS for updates

Allow HTTPS for updates

New-NetFirewallRule -DisplayName "Allow HTTPS Out"
    -Direction Outbound -Protocol TCP -RemotePort 443
-Action Allow
New-NetFirewallRule -DisplayName "Allow HTTPS Out"
    -Direction Outbound -Protocol TCP -RemotePort 443
-Action Allow

Allow NTP

Allow NTP

New-NetFirewallRule -DisplayName "Allow NTP"
    -Direction Outbound -Protocol UDP -RemotePort 123
-Action Allow
New-NetFirewallRule -DisplayName "Allow NTP"
    -Direction Outbound -Protocol UDP -RemotePort 123
-Action Allow

============================================

============================================

Firewall Audit

Firewall Audit

============================================

============================================

List all enabled firewall rules

List all enabled firewall rules

Get-NetFirewallRule -Enabled True | Format-Table DisplayName, Direction, Action, Profile
Get-NetFirewallRule -Enabled True | Format-Table DisplayName, Direction, Action, Profile

Export firewall rules

Export firewall rules

netsh advfirewall export "C:\SecurityAudit\firewall-rules.wfw"
netsh advfirewall export "C:\SecurityAudit\firewall-rules.wfw"

Find overly permissive rules

Find overly permissive rules

Get-NetFirewallRule -Enabled True -Direction Inbound | Where-Object { $.RemoteAddress -eq "Any" -and $.Action -eq "Allow" } | Format-Table DisplayName, LocalPort, RemoteAddress, Profile
undefined
Get-NetFirewallRule -Enabled True -Direction Inbound | Where-Object { $.RemoteAddress -eq "Any" -and $.Action -eq "Allow" } | Format-Table DisplayName, LocalPort, RemoteAddress, Profile
undefined

Audit Policy Configuration

审计策略配置

powershell
undefined
powershell
undefined

============================================

============================================

Advanced Audit Policy

Advanced Audit Policy

============================================

============================================

Account Logon

Account Logon

auditpol /set /subcategory:"Credential Validation" /success:enable /failure:enable auditpol /set /subcategory:"Kerberos Authentication Service" /success:enable /failure:enable auditpol /set /subcategory:"Kerberos Service Ticket Operations" /success:enable /failure:enable
auditpol /set /subcategory:"Credential Validation" /success:enable /failure:enable auditpol /set /subcategory:"Kerberos Authentication Service" /success:enable /failure:enable auditpol /set /subcategory:"Kerberos Service Ticket Operations" /success:enable /failure:enable

Account Management

Account Management

auditpol /set /subcategory:"Computer Account Management" /success:enable auditpol /set /subcategory:"Security Group Management" /success:enable auditpol /set /subcategory:"User Account Management" /success:enable /failure:enable
auditpol /set /subcategory:"Computer Account Management" /success:enable auditpol /set /subcategory:"Security Group Management" /success:enable auditpol /set /subcategory:"User Account Management" /success:enable /failure:enable

Logon/Logoff

Logon/Logoff

auditpol /set /subcategory:"Logon" /success:enable /failure:enable auditpol /set /subcategory:"Logoff" /success:enable auditpol /set /subcategory:"Account Lockout" /success:enable /failure:enable auditpol /set /subcategory:"Special Logon" /success:enable
auditpol /set /subcategory:"Logon" /success:enable /failure:enable auditpol /set /subcategory:"Logoff" /success:enable auditpol /set /subcategory:"Account Lockout" /success:enable /failure:enable auditpol /set /subcategory:"Special Logon" /success:enable

Object Access

Object Access

auditpol /set /subcategory:"File System" /success:enable /failure:enable auditpol /set /subcategory:"Registry" /success:enable /failure:enable auditpol /set /subcategory:"SAM" /success:enable /failure:enable
auditpol /set /subcategory:"File System" /success:enable /failure:enable auditpol /set /subcategory:"Registry" /success:enable /failure:enable auditpol /set /subcategory:"SAM" /success:enable /failure:enable

Policy Change

Policy Change

auditpol /set /subcategory:"Audit Policy Change" /success:enable /failure:enable auditpol /set /subcategory:"Authentication Policy Change" /success:enable auditpol /set /subcategory:"Authorization Policy Change" /success:enable
auditpol /set /subcategory:"Audit Policy Change" /success:enable /failure:enable auditpol /set /subcategory:"Authentication Policy Change" /success:enable auditpol /set /subcategory:"Authorization Policy Change" /success:enable

Privilege Use

Privilege Use

auditpol /set /subcategory:"Sensitive Privilege Use" /success:enable /failure:enable
auditpol /set /subcategory:"Sensitive Privilege Use" /success:enable /failure:enable

System

System

auditpol /set /subcategory:"Security State Change" /success:enable /failure:enable auditpol /set /subcategory:"Security System Extension" /success:enable /failure:enable auditpol /set /subcategory:"System Integrity" /success:enable /failure:enable
auditpol /set /subcategory:"Security State Change" /success:enable /failure:enable auditpol /set /subcategory:"Security System Extension" /success:enable /failure:enable auditpol /set /subcategory:"System Integrity" /success:enable /failure:enable

Verify audit policy

Verify audit policy

auditpol /get /category:*
auditpol /get /category:*

Export audit policy

Export audit policy

auditpol /backup /file:C:\SecurityAudit\audit-policy.csv
auditpol /backup /file:C:\SecurityAudit\audit-policy.csv

============================================

============================================

PowerShell Logging (Critical for forensics)

PowerShell Logging (Critical for forensics)

============================================

============================================

Enable Script Block Logging

Enable Script Block Logging

New-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" -Force Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" ` -Name "EnableScriptBlockLogging" -Value 1
New-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" -Force Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" ` -Name "EnableScriptBlockLogging" -Value 1

Enable Module Logging

Enable Module Logging

New-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging" -Force Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging"
    -Name "EnableModuleLogging" -Value 1 New-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging\ModuleNames" -Force Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging\ModuleNames"
-Name "" -Value ""
New-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging" -Force Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging"
    -Name "EnableModuleLogging" -Value 1 New-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging\ModuleNames" -Force Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging\ModuleNames"
-Name "" -Value ""

Enable Transcription Logging

Enable Transcription Logging

New-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\Transcription" -Force Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\Transcription"
    -Name "EnableTranscripting" -Value 1 Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\Transcription"
-Name "OutputDirectory" -Value "C:\PSLogs" Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\Transcription" ` -Name "EnableInvocationHeader" -Value 1
New-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\Transcription" -Force Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\Transcription"
    -Name "EnableTranscripting" -Value 1 Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\Transcription"
-Name "OutputDirectory" -Value "C:\PSLogs" Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\Transcription" ` -Name "EnableInvocationHeader" -Value 1

Configure Windows Event Forwarding (WEF) for centralized logging

Configure Windows Event Forwarding (WEF) for centralized logging

wecutil qc /q
undefined
wecutil qc /q
undefined

Windows Defender Configuration

Windows Defender配置

powershell
undefined
powershell
undefined

============================================

============================================

Real-time Protection

Real-time Protection

============================================

============================================

Set-MpPreference -DisableRealtimeMonitoring $false Set-MpPreference -DisableBehaviorMonitoring $false Set-MpPreference -DisableIOAVProtection $false Set-MpPreference -DisableScriptScanning $false
Set-MpPreference -DisableRealtimeMonitoring $false Set-MpPreference -DisableBehaviorMonitoring $false Set-MpPreference -DisableIOAVProtection $false Set-MpPreference -DisableScriptScanning $false

============================================

============================================

Cloud Protection

Cloud Protection

============================================

============================================

Set-MpPreference -MAPSReporting Advanced Set-MpPreference -SubmitSamplesConsent SendAllSamples Set-MpPreference -CloudBlockLevel High Set-MpPreference -CloudExtendedTimeout 50
Set-MpPreference -MAPSReporting Advanced Set-MpPreference -SubmitSamplesConsent SendAllSamples Set-MpPreference -CloudBlockLevel High Set-MpPreference -CloudExtendedTimeout 50

============================================

============================================

Scan Configuration

Scan Configuration

============================================

============================================

Set-MpPreference -ScanScheduleDay Everyday Set-MpPreference -ScanScheduleTime 02:00:00 Set-MpPreference -ScanParameters FullScan
Set-MpPreference -ScanScheduleDay Everyday Set-MpPreference -ScanScheduleTime 02:00:00 Set-MpPreference -ScanParameters FullScan

Quick scan daily, full scan weekly

Quick scan daily, full scan weekly

Set-MpPreference -ScanScheduleQuickScanTime 12:00:00
Set-MpPreference -ScanScheduleQuickScanTime 12:00:00

Scan removable drives

Scan removable drives

Set-MpPreference -DisableRemovableDriveScanning $false
Set-MpPreference -DisableRemovableDriveScanning $false

Scan network files

Scan network files

Set-MpPreference -DisableScanningNetworkFiles $false
Set-MpPreference -DisableScanningNetworkFiles $false

============================================

============================================

Attack Surface Reduction (ASR) Rules

Attack Surface Reduction (ASR) Rules

============================================

============================================

Block executable content from email and webmail

Block executable content from email and webmail

Add-MpPreference -AttackSurfaceReductionRules_Ids BE9BA2D9-53EA-4CDC-84E5-9B1EEEE46550 ` -AttackSurfaceReductionRules_Actions Enabled
Add-MpPreference -AttackSurfaceReductionRules_Ids BE9BA2D9-53EA-4CDC-84E5-9B1EEEE46550 ` -AttackSurfaceReductionRules_Actions Enabled

Block Office applications from creating child processes

Block Office applications from creating child processes

Add-MpPreference -AttackSurfaceReductionRules_Ids D4F940AB-401B-4EFC-AADC-AD5F3C50688A ` -AttackSurfaceReductionRules_Actions Enabled
Add-MpPreference -AttackSurfaceReductionRules_Ids D4F940AB-401B-4EFC-AADC-AD5F3C50688A ` -AttackSurfaceReductionRules_Actions Enabled

Block credential stealing from LSASS

Block credential stealing from LSASS

Add-MpPreference -AttackSurfaceReductionRules_Ids 9E6C4E1F-7D60-472F-BA1A-A39EF669E4B2 ` -AttackSurfaceReductionRules_Actions Enabled
Add-MpPreference -AttackSurfaceReductionRules_Ids 9E6C4E1F-7D60-472F-BA1A-A39EF669E4B2 ` -AttackSurfaceReductionRules_Actions Enabled

Block process creations from PSExec and WMI commands

Block process creations from PSExec and WMI commands

Add-MpPreference -AttackSurfaceReductionRules_Ids D1E49AAC-8F56-4280-B9BA-993A6D77406C ` -AttackSurfaceReductionRules_Actions Enabled
Add-MpPreference -AttackSurfaceReductionRules_Ids D1E49AAC-8F56-4280-B9BA-993A6D77406C ` -AttackSurfaceReductionRules_Actions Enabled

Block JavaScript and VBScript from launching downloaded content

Block JavaScript and VBScript from launching downloaded content

Add-MpPreference -AttackSurfaceReductionRules_Ids D3E037E1-3EB8-44C8-A917-57927947596D ` -AttackSurfaceReductionRules_Actions Enabled
Add-MpPreference -AttackSurfaceReductionRules_Ids D3E037E1-3EB8-44C8-A917-57927947596D ` -AttackSurfaceReductionRules_Actions Enabled

Block Office macros from calling Win32 API

Block Office macros from calling Win32 API

Add-MpPreference -AttackSurfaceReductionRules_Ids 92E97FA1-2EDF-4476-BDD6-9DD0B4DDDC7B ` -AttackSurfaceReductionRules_Actions Enabled
Add-MpPreference -AttackSurfaceReductionRules_Ids 92E97FA1-2EDF-4476-BDD6-9DD0B4DDDC7B ` -AttackSurfaceReductionRules_Actions Enabled

View ASR rule status

View ASR rule status

Get-MpPreference | Select-Object -ExpandProperty AttackSurfaceReductionRules_Ids Get-MpPreference | Select-Object -ExpandProperty AttackSurfaceReductionRules_Actions
Get-MpPreference | Select-Object -ExpandProperty AttackSurfaceReductionRules_Ids Get-MpPreference | Select-Object -ExpandProperty AttackSurfaceReductionRules_Actions

============================================

============================================

Exclusions (minimize these)

Exclusions (minimize these)

============================================

============================================

Only add exclusions when absolutely necessary and document the reason

Only add exclusions when absolutely necessary and document the reason

Add-MpPreference -ExclusionPath "C:\AppData\SpecificApp" # Reason: false positive on app binary
Add-MpPreference -ExclusionPath "C:\AppData\SpecificApp" # Reason: false positive on app binary

Review current exclusions

Review current exclusions

Get-MpPreference | Select-Object -ExpandProperty ExclusionPath Get-MpPreference | Select-Object -ExpandProperty ExclusionProcess Get-MpPreference | Select-Object -ExpandProperty ExclusionExtension
Get-MpPreference | Select-Object -ExpandProperty ExclusionPath Get-MpPreference | Select-Object -ExpandProperty ExclusionProcess Get-MpPreference | Select-Object -ExpandProperty ExclusionExtension

Update definitions manually

Update definitions manually

Update-MpSignature
undefined
Update-MpSignature
undefined

BitLocker Drive Encryption

BitLocker驱动器加密

powershell
undefined
powershell
undefined

============================================

============================================

Enable BitLocker on OS drive with TPM

Enable BitLocker on OS drive with TPM

============================================

============================================

Check TPM status

Check TPM status

Get-Tpm
Get-Tpm

Enable BitLocker with TPM protector

Enable BitLocker with TPM protector

Enable-BitLocker -MountPoint "C:" -TpmProtector -EncryptionMethod XtsAes256
Enable-BitLocker -MountPoint "C:" -TpmProtector -EncryptionMethod XtsAes256

Add recovery password protector

Add recovery password protector

Add-BitLockerKeyProtector -MountPoint "C:" -RecoveryPasswordProtector
Add-BitLockerKeyProtector -MountPoint "C:" -RecoveryPasswordProtector

Backup recovery key to Active Directory

Backup recovery key to Active Directory

Backup-BitLockerKeyProtector -MountPoint "C:" -KeyProtectorId ( (Get-BitLockerVolume -MountPoint "C:").KeyProtector | Where-Object { $_.KeyProtectorType -eq "RecoveryPassword" } ).KeyProtectorId
Backup-BitLockerKeyProtector -MountPoint "C:" -KeyProtectorId ( (Get-BitLockerVolume -MountPoint "C:").KeyProtector | Where-Object { $_.KeyProtectorType -eq "RecoveryPassword" } ).KeyProtectorId

Enable BitLocker on data drives

Enable BitLocker on data drives

Enable-BitLocker -MountPoint "D:" -RecoveryPasswordProtector -EncryptionMethod XtsAes256 -Password ( Read-Host -AsSecureString "Enter BitLocker password for D:" )
Enable-BitLocker -MountPoint "D:" -RecoveryPasswordProtector -EncryptionMethod XtsAes256 -Password ( Read-Host -AsSecureString "Enter BitLocker password for D:" )

Check BitLocker status

Check BitLocker status

Get-BitLockerVolume | Format-Table MountPoint, VolumeStatus, EncryptionMethod, ProtectionStatus
Get-BitLockerVolume | Format-Table MountPoint, VolumeStatus, EncryptionMethod, ProtectionStatus

Configure BitLocker via Group Policy

Configure BitLocker via Group Policy

Computer Configuration > Administrative Templates > Windows Components > BitLocker Drive Encryption

Computer Configuration > Administrative Templates > Windows Components > BitLocker Drive Encryption

- Require additional authentication at startup: Enabled (Allow BitLocker without a compatible TPM: unchecked)

- Require additional authentication at startup: Enabled (Allow BitLocker without a compatible TPM: unchecked)

- Choose drive encryption method: XTS-AES 256-bit

- Choose drive encryption method: XTS-AES 256-bit

undefined
undefined

Credential Guard

Credential Guard配置

powershell
undefined
powershell
undefined

============================================

============================================

Enable Windows Credential Guard

Enable Windows Credential Guard

============================================

============================================

Check hardware compatibility

Check hardware compatibility

Requires: UEFI, Secure Boot, TPM 2.0, VBS-compatible CPU

Requires: UEFI, Secure Boot, TPM 2.0, VBS-compatible CPU

systeminfo | findstr /i "Hyper-V"
systeminfo | findstr /i "Hyper-V"

Enable via registry

Enable via registry

Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\DeviceGuard"
    -Name "EnableVirtualizationBasedSecurity" -Value 1 Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\DeviceGuard"
-Name "RequirePlatformSecurityFeatures" -Value 3 # 3 = Secure Boot + DMA Protection Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa" ` -Name "LsaCfgFlags" -Value 1 # 1 = Enabled with UEFI lock
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\DeviceGuard"
    -Name "EnableVirtualizationBasedSecurity" -Value 1 Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\DeviceGuard"
-Name "RequirePlatformSecurityFeatures" -Value 3 # 3 = Secure Boot + DMA Protection Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa" ` -Name "LsaCfgFlags" -Value 1 # 1 = Enabled with UEFI lock

Verify Credential Guard status

Verify Credential Guard status

Get-CimInstance -ClassName Win32_DeviceGuard -Namespace root\Microsoft\Windows\DeviceGuard | Select-Object SecurityServicesRunning, VirtualizationBasedSecurityStatus
undefined
Get-CimInstance -ClassName Win32_DeviceGuard -Namespace root\Microsoft\Windows\DeviceGuard | Select-Object SecurityServicesRunning, VirtualizationBasedSecurityStatus
undefined

AppLocker Configuration

AppLocker配置

powershell
undefined
powershell
undefined

============================================

============================================

Configure AppLocker for application whitelisting

Configure AppLocker for application whitelisting

============================================

============================================

Generate default rules

Generate default rules

Computer Configuration > Policies > Windows Settings > Security Settings > Application Control Policies > AppLocker

Computer Configuration > Policies > Windows Settings > Security Settings > Application Control Policies > AppLocker

Create default executable rules via PowerShell

Create default executable rules via PowerShell

$ruleCollection = @" <AppLockerPolicy Version="1"> <RuleCollection Type="Exe" EnforcementMode="AuditOnly"> <FilePathRule Id="921cc481-6e17-4653-8f75-050b80acca20" Name="Allow Program Files" Description="" UserOrGroupSid="S-1-1-0" Action="Allow"> <Conditions> <FilePathCondition Path="%PROGRAMFILES%\*"/> </Conditions> </FilePathRule> <FilePathRule Id="a61c8b2c-a319-4cd0-9690-d2177cad7b51" Name="Allow Windows" Description="" UserOrGroupSid="S-1-1-0" Action="Allow"> <Conditions> <FilePathCondition Path="%WINDIR%\*"/> </Conditions> </FilePathRule> <FilePublisherRule Id="b7af7102-efde-4369-8a89-7a6a392d1473" Name="Allow signed by Microsoft" Description="" UserOrGroupSid="S-1-1-0" Action="Allow"> <Conditions> <FilePublisherCondition PublisherName="O=MICROSOFT CORPORATION*" ProductName="*" BinaryName="*"> <BinaryVersionRange LowSection="*" HighSection="*"/> </FilePublisherCondition> </Conditions> </FilePublisherRule> </RuleCollection> </AppLockerPolicy> "@
$ruleCollection = @" <AppLockerPolicy Version="1"> <RuleCollection Type="Exe" EnforcementMode="AuditOnly"> <FilePathRule Id="921cc481-6e17-4653-8f75-050b80acca20" Name="Allow Program Files" Description="" UserOrGroupSid="S-1-1-0" Action="Allow"> <Conditions> <FilePathCondition Path="%PROGRAMFILES%\*"/> </Conditions> </FilePathRule> <FilePathRule Id="a61c8b2c-a319-4cd0-9690-d2177cad7b51" Name="Allow Windows" Description="" UserOrGroupSid="S-1-1-0" Action="Allow"> <Conditions> <FilePathCondition Path="%WINDIR%\*"/> </Conditions> </FilePathRule> <FilePublisherRule Id="b7af7102-efde-4369-8a89-7a6a392d1473" Name="Allow signed by Microsoft" Description="" UserOrGroupSid="S-1-1-0" Action="Allow"> <Conditions> <FilePublisherCondition PublisherName="O=MICROSOFT CORPORATION*" ProductName="*" BinaryName="*"> <BinaryVersionRange LowSection="*" HighSection="*"/> </FilePublisherCondition> </Conditions> </FilePublisherRule> </RuleCollection> </AppLockerPolicy> "@

Start AppLocker service

Start AppLocker service

Set-Service -Name AppIDSvc -StartupType Automatic Start-Service AppIDSvc
Set-Service -Name AppIDSvc -StartupType Automatic Start-Service AppIDSvc

Set to Audit mode first, then switch to Enforce after tuning

Set to Audit mode first, then switch to Enforce after tuning

Review logs: Event Viewer > Applications and Services Logs > Microsoft > Windows > AppLocker

Review logs: Event Viewer > Applications and Services Logs > Microsoft > Windows > AppLocker

undefined
undefined

Security Audit Script

安全审计脚本

powershell
undefined
powershell
undefined

windows-security-audit.ps1 - Comprehensive security audit

windows-security-audit.ps1 - Comprehensive security audit

Write-Host "=== Windows Security Audit Report ===" -ForegroundColor Cyan Write-Host "Date: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss UTC' -AsUTC)" Write-Host "Host: $env:COMPUTERNAME" Write-Host ""
Write-Host "=== Windows Security Audit Report ===" -ForegroundColor Cyan Write-Host "Date: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss UTC' -AsUTC)" Write-Host "Host: $env:COMPUTERNAME" Write-Host ""

OS Info

OS Info

Write-Host "--- OS Information ---" -ForegroundColor Yellow Get-CimInstance Win32_OperatingSystem | Format-Table Caption, Version, BuildNumber, OSArchitecture
Write-Host "--- OS Information ---" -ForegroundColor Yellow Get-CimInstance Win32_OperatingSystem | Format-Table Caption, Version, BuildNumber, OSArchitecture

Firewall status

Firewall status

Write-Host "--- Firewall Status ---" -ForegroundColor Yellow Get-NetFirewallProfile | Format-Table Name, Enabled, DefaultInboundAction, DefaultOutboundAction
Write-Host "--- Firewall Status ---" -ForegroundColor Yellow Get-NetFirewallProfile | Format-Table Name, Enabled, DefaultInboundAction, DefaultOutboundAction

SMBv1 status

SMBv1 status

Write-Host "--- SMB Status ---" -ForegroundColor Yellow $smb1 = Get-SmbServerConfiguration | Select-Object EnableSMB1Protocol if ($smb1.EnableSMB1Protocol) { Write-Host "WARNING: SMBv1 is ENABLED" -ForegroundColor Red } else { Write-Host "OK: SMBv1 is disabled" -ForegroundColor Green }
Write-Host "--- SMB Status ---" -ForegroundColor Yellow $smb1 = Get-SmbServerConfiguration | Select-Object EnableSMB1Protocol if ($smb1.EnableSMB1Protocol) { Write-Host "WARNING: SMBv1 is ENABLED" -ForegroundColor Red } else { Write-Host "OK: SMBv1 is disabled" -ForegroundColor Green }

Windows Defender status

Windows Defender status

Write-Host "--- Windows Defender ---" -ForegroundColor Yellow Get-MpComputerStatus | Format-Table AMServiceEnabled, RealTimeProtectionEnabled, AntivirusSignatureLastUpdated
Write-Host "--- Windows Defender ---" -ForegroundColor Yellow Get-MpComputerStatus | Format-Table AMServiceEnabled, RealTimeProtectionEnabled, AntivirusSignatureLastUpdated

BitLocker status

BitLocker status

Write-Host "--- BitLocker ---" -ForegroundColor Yellow Get-BitLockerVolume | Format-Table MountPoint, ProtectionStatus, EncryptionMethod
Write-Host "--- BitLocker ---" -ForegroundColor Yellow Get-BitLockerVolume | Format-Table MountPoint, VolumeStatus, EncryptionMethod, ProtectionStatus

Open ports

Open ports

Write-Host "--- Listening Ports ---" -ForegroundColor Yellow Get-NetTCPConnection -State Listen | Sort-Object LocalPort | Format-Table LocalAddress, LocalPort, OwningProcess, @{N="Process";E={(Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue).Name}}
Write-Host "--- Listening Ports ---" -ForegroundColor Yellow Get-NetTCPConnection -State Listen | Sort-Object LocalPort | Format-Table LocalAddress, LocalPort, OwningProcess, @{N="Process";E={(Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue).Name}}

Local administrators

Local administrators

Write-Host "--- Local Administrators ---" -ForegroundColor Yellow Get-LocalGroupMember -Group "Administrators" | Format-Table Name, ObjectClass, PrincipalSource
Write-Host "--- Local Administrators ---" -ForegroundColor Yellow Get-LocalGroupMember -Group "Administrators" | Format-Table Name, ObjectClass, PrincipalSource

Pending updates

Pending updates

Write-Host "--- Windows Update ---" -ForegroundColor Yellow $updateSession = New-Object -ComObject Microsoft.Update.Session $updateSearcher = $updateSession.CreateUpdateSearcher() $pendingUpdates = $updateSearcher.Search("IsInstalled=0") Write-Host "Pending updates: $($pendingUpdates.Updates.Count)"
Write-Host "--- Windows Update ---" -ForegroundColor Yellow $updateSession = New-Object -ComObject Microsoft.Update.Session $updateSearcher = $updateSession.CreateUpdateSearcher() $pendingUpdates = $updateSearcher.Search("IsInstalled=0") Write-Host "Pending updates: $($pendingUpdates.Updates.Count)"

Audit policy

Audit policy

Write-Host "--- Audit Policy ---" -ForegroundColor Yellow auditpol /get /category:* | Select-String "Success|Failure|No Auditing"
Write-Host "`n=== Audit Complete ===" -ForegroundColor Cyan
undefined
Write-Host "--- Audit Policy ---" -ForegroundColor Yellow auditpol /get /category:* | Select-String "Success|Failure|No Auditing"
Write-Host "`n=== Audit Complete ===" -ForegroundColor Cyan
undefined

Troubleshooting

故障排查

ProblemCauseSolution
GPO not applyingGPO not linked or filteredRun
gpresult /r
; check OU linking and security filtering
BitLocker fails to enableTPM not present or enabledCheck BIOS/UEFI for TPM; run
manage-bde -status
AppLocker blocks legitimate appsRules too restrictiveStart in Audit mode; review AppLocker event logs; add exceptions
Credential Guard breaks appsLegacy auth protocols blockedIdentify apps using NTLM/CredSSP; migrate to Kerberos/modern auth
SMBv1 removal breaks legacy devicesOld devices require SMBv1Isolate legacy devices; plan migration; document risk acceptance
Windows Defender exclusions too broadPerformance tuning added wide pathsReview and narrow exclusions; document business justification
Audit logs filling diskToo many audit eventsIncrease log size; configure log forwarding to SIEM; tune audit categories
Firewall rules not persistingRules created without -PolicyStoreUse
-PolicyStore PersistentStore
; verify with
Get-NetFirewallRule
问题原因解决方案
GPO未生效GPO未链接或被过滤运行
gpresult /r
;检查OU链接和安全过滤
BitLocker启用失败TPM未存在或未启用检查BIOS/UEFI中的TPM设置;运行
manage-bde -status
AppLocker阻止合法应用规则过于严格先使用审计模式;查看AppLocker事件日志;添加例外
Credential Guard导致应用故障旧版认证协议被阻止识别使用NTLM/CredSSP的应用;迁移至Kerberos/现代认证
移除SMBv1导致旧设备故障旧设备需要SMBv1隔离旧设备;制定迁移计划;记录风险接受文档
Windows Defender排除范围过宽性能调优添加了宽泛路径审查并缩小排除范围;记录业务合理性
审计日志占满磁盘审计事件过多增大日志容量;配置日志转发至SIEM;调整审计类别
防火墙规则不持久未使用-PolicyStore创建规则使用
-PolicyStore PersistentStore
;通过
Get-NetFirewallRule
验证

Best Practices

最佳实践

  • Apply Microsoft security baselines as a starting point
  • Disable SMBv1 on all systems (no exceptions without documented risk acceptance)
  • Enable Credential Guard on all compatible hardware
  • Configure AppLocker in audit mode first, then enforce after tuning
  • Enable all recommended audit subcategories and forward to SIEM
  • Enable PowerShell script block and module logging on all servers
  • Implement LAPS for local administrator password management
  • Enable BitLocker on all drives with TPM and recovery key backup
  • Apply Attack Surface Reduction rules in Windows Defender
  • Perform monthly security audits with the audit script
  • Keep Windows fully patched with automated update management
  • Disable unnecessary services and features to reduce attack surface
  • Use Windows Firewall with explicit allow rules per application
  • 以Microsoft安全基线为起点进行配置
  • 在所有系统上禁用SMBv1(无书面风险接受则不允许例外)
  • 在所有兼容硬件上启用Credential Guard
  • 先将AppLocker配置为审计模式,调试后再切换为强制模式
  • 启用所有推荐的审计子类别并转发至SIEM
  • 在所有服务器上启用PowerShell脚本块和模块日志
  • 实施LAPS进行本地管理员密码管理
  • 在所有带TPM的驱动器上启用BitLocker并备份恢复密钥
  • 在Windows Defender中应用攻击面缩减规则
  • 使用审计脚本每月执行安全审计
  • 通过自动化更新管理保持Windows系统完全打补丁
  • 禁用不必要的服务和功能以减少攻击面
  • 使用Windows防火墙并为每个应用配置明确的允许规则

Related Skills

相关技能

  • cis-benchmarks - Compliance scanning
  • windows-server - Server administration
  • linux-hardening - Linux security hardening
  • cis-benchmarks - 合规扫描
  • windows-server - 服务器管理
  • linux-hardening - Linux安全加固