Chuyển tới nội dung chính

Hướng Dẫn Cài Đặt và Hardening Windows Server 2022

Giới Thiệu Windows Server 2022

Windows Server 2022 là phiên bản server OS mới nhất của Microsoft với nhiều cải tiến về security, performance và cloud integration. Phiên bản này hỗ trợ đến năm 2031 với mainstream support đến 2026.

Key Features:

  • 🔒 Secured-core server protection
  • 🌐 Enhanced hybrid cloud capabilities
  • 🚀 Improved performance (SMB compression, Storage Replica)
  • 🛡️ Advanced threat protection
  • 📦 Windows Admin Center built-in
  • 🔐 HTTP/3 và TLS 1.3 support

Editions:

EditionUse CaseKey Features
EssentialsSmall business (<25 users)No domain controller, simplified management
StandardGeneral purpose2 VMs, Hyper-V, Storage Replica
DatacenterLarge enterprise, cloudUnlimited VMs, Software Defined Networking

![Windows Server 2022 dashboard - Đặt ảnh tại /static/img/windows/ws2022-dashboard.png]

Thời gian thực hiện: 2-3 giờ
Độ khó: Trung bình đến Nâng cao
Yêu cầu: Windows Server 2022 ISO, 4GB+ RAM, 40GB+ disk

Phần 1: Cài Đặt Windows Server 2022

Yêu Cầu Hệ Thống

Minimum:

  • CPU: 1.4 GHz 64-bit processor
  • RAM: 512 MB (2 GB with Desktop Experience)
  • Disk: 32 GB
  • Network: Gigabit Ethernet adapter

Recommended:

  • CPU: 3.4 GHz or faster multi-core
  • RAM: 16 GB or more
  • Disk: 80 GB SSD or faster
  • Network: Multiple NICs for redundancy

Bước 1: Boot và Chọn Installation Type

  1. Boot từ USB/ISO
  2. Chọn ngôn ngữ, time, keyboard
  3. Click Install now
  4. Enter product key (hoặc skip để dùng trial)
  5. Chọn edition:
    • Windows Server 2022 Standard (Desktop Experience) - Có GUI
    • Windows Server 2022 Standard - Server Core (CLI only)

⚠️ Khuyến nghị: Desktop Experience cho người mới bắt đầu.

Bước 2: Disk Partitioning

Option 1: Simple (Single disk)

  • Chọn disk → Next → Windows tự động partition

Option 2: Custom Partitioning

Partition 1: System Reserved (500 MB)
Partition 2: C:\ - OS (60 GB) - NTFS
Partition 3: D:\ - Data (remaining) - NTFS
  1. Click New → Enter size
  2. Format partition as NTFS
  3. Select OS partition → Next

![Screenshot disk partitioning - Đặt ảnh tại /static/img/windows/ws2022-partition.png]

Bước 3: Installation và Initial Setup

  1. Installation mất 15-30 phút
  2. Server tự động restart
  3. Set Administrator password (phải mạnh: >8 chars, uppercase, lowercase, number, symbol)
Example strong password: P@ssw0rd2024!Server
  1. Press Ctrl+Alt+Delete để login

Bước 4: Initial Configuration Tasks

Sconfig Tool (Server Core) hoặc Server Manager (GUI):

  1. Set Computer Name:
# PowerShell method
Rename-Computer -NewName "SRV-DC01" -Restart

# GUI: Server Manager → Local Server → Computer Name → Change
  1. Configure Network:
# List network adapters
Get-NetAdapter

# Set static IP
New-NetIPAddress -InterfaceAlias "Ethernet" -IPAddress 192.168.1.10 -PrefixLength 24 -DefaultGateway 192.168.1.1

# Set DNS
Set-DnsClientServerAddress -InterfaceAlias "Ethernet" -ServerAddresses 8.8.8.8,8.8.4.4

# Verify
Get-NetIPConfiguration

![Screenshot network configuration - Đặt ảnh tại /static/img/windows/ws2022-network.png]

  1. Set Time Zone:
# List timezones
Get-TimeZone -ListAvailable

# Set timezone
Set-TimeZone -Id "SE Asia Standard Time"

# Verify
Get-TimeZone
  1. Windows Update:
# Install PSWindowsUpdate module
Install-Module PSWindowsUpdate -Force

# Check for updates
Get-WindowsUpdate

# Install updates
Install-WindowsUpdate -AcceptAll -AutoReboot

# Or via GUI: Settings → Windows Update
  1. Enable Remote Desktop:
# Enable RDP
Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server' -Name "fDenyTSConnections" -Value 0

# Enable NLA (Network Level Authentication)
Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp' -Name "UserAuthentication" -Value 1

# Allow RDP through firewall
Enable-NetFirewallRule -DisplayGroup "Remote Desktop"

# Verify
Get-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server' -Name "fDenyTSConnections"

Phần 2: Active Directory Domain Services

Install AD DS Role

Method 1: Server Manager (GUI)

  1. Server Manager → ManageAdd Roles and Features
  2. Select Role-based installation
  3. Select local server
  4. Check Active Directory Domain Services
  5. Add required features → Next → Install

Method 2: PowerShell

# Install AD DS role
Install-WindowsFeature -Name AD-Domain-Services -IncludeManagementTools

# Verify installation
Get-WindowsFeature -Name AD-Domain-Services

Promote Server to Domain Controller

# Import module
Import-Module ADDSDeployment

# Create new forest and domain
Install-ADDSForest `
-DomainName "example.local" `
-DomainNetbiosName "EXAMPLE" `
-DomainMode "WinThreshold" `
-ForestMode "WinThreshold" `
-InstallDns:$true `
-CreateDnsDelegation:$false `
-DatabasePath "C:\Windows\NTDS" `
-LogPath "C:\Windows\NTDS" `
-SysvolPath "C:\Windows\SYSVOL" `
-NoRebootOnCompletion:$false `
-Force:$true

Parameters explained:

  • DomainMode/ForestMode: WinThreshold = Windows Server 2016+ functional level
  • InstallDns: Cài DNS server (required cho AD)
  • Server sẽ restart sau khi complete

Post-Installation Verification:

# Check domain controller
Get-ADDomainController

# Check forest
Get-ADForest

# Check domain
Get-ADDomain

# List domain users
Get-ADUser -Filter *

Create Organizational Units (OUs)

# Create OUs
New-ADOrganizationalUnit -Name "Departments" -Path "DC=example,DC=local"
New-ADOrganizationalUnit -Name "IT" -Path "OU=Departments,DC=example,DC=local"
New-ADOrganizationalUnit -Name "Sales" -Path "OU=Departments,DC=example,DC=local"
New-ADOrganizationalUnit -Name "Servers" -Path "DC=example,DC=local"
New-ADOrganizationalUnit -Name "Workstations" -Path "DC=example,DC=local"

# Verify
Get-ADOrganizationalUnit -Filter * | Format-Table Name, DistinguishedName

Create Users và Groups

# Create security group
New-ADGroup -Name "IT-Admins" -GroupScope Global -GroupCategory Security -Path "OU=IT,OU=Departments,DC=example,DC=local"

# Create user
New-ADUser -Name "John Doe" `
-GivenName "John" `
-Surname "Doe" `
-SamAccountName "jdoe" `
-UserPrincipalName "[email protected]" `
-Path "OU=IT,OU=Departments,DC=example,DC=local" `
-AccountPassword (ConvertTo-SecureString "P@ssw0rd123!" -AsPlainText -Force) `
-Enabled $true `
-ChangePasswordAtLogon $true

# Add user to group
Add-ADGroupMember -Identity "IT-Admins" -Members "jdoe"

# Verify
Get-ADGroupMember -Identity "IT-Admins"

Bulk User Creation từ CSV:

# users.csv format:
# FirstName,LastName,Username,OU
# John,Doe,jdoe,IT
# Jane,Smith,jsmith,Sales

Import-Csv "C:\users.csv" | ForEach-Object {
New-ADUser -Name "$($_.FirstName) $($_.LastName)" `
-GivenName $_.FirstName `
-Surname $_.LastName `
-SamAccountName $_.Username `
-UserPrincipalName "$($_.Username)@example.local" `
-Path "OU=$($_.OU),OU=Departments,DC=example,DC=local" `
-AccountPassword (ConvertTo-SecureString "TempPass123!" -AsPlainText -Force) `
-Enabled $true `
-ChangePasswordAtLogon $true
}

Phần 3: Group Policy Management

# Import Group Policy module
Import-Module GroupPolicy

# Create GPO
New-GPO -Name "Security-Baseline-Servers" -Comment "Security hardening for servers"

# Link GPO to OU
New-GPLink -Name "Security-Baseline-Servers" -Target "OU=Servers,DC=example,DC=local"

# List all GPOs
Get-GPO -All | Format-Table DisplayName, GpoStatus

Common Group Policies

1. Password Policy:

# Via GPO Editor: Computer Configuration → Policies → Windows Settings → Security Settings → Account Policies → Password Policy

# Or via PowerShell (for Default Domain Policy)
Set-ADDefaultDomainPasswordPolicy -Identity example.local `
-MinPasswordLength 12 `
-PasswordHistoryCount 24 `
-MaxPasswordAge 90.00:00:00 `
-MinPasswordAge 1.00:00:00 `
-ComplexityEnabled $true `
-LockoutThreshold 5 `
-LockoutDuration 00:30:00 `
-LockoutObservationWindow 00:30:00

2. Disable Guest Account:

# GPO: Computer Configuration → Windows Settings → Security Settings → Local Policies → Security Options
# "Accounts: Guest account status" → Disabled

3. Windows Firewall:

# GPO: Computer Configuration → Policies → Windows Settings → Security Settings → Windows Defender Firewall with Advanced Security

# Enable firewall for all profiles
Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled True

# Block inbound by default
Set-NetFirewallProfile -Profile Domain,Public,Private -DefaultInboundAction Block -DefaultOutboundAction Allow

4. Audit Policy:

# GPO: Computer Configuration → Policies → Windows Settings → Security Settings → Advanced Audit Policy Configuration

# Enable audit policies
auditpol /set /subcategory:"Logon" /success:enable /failure:enable
auditpol /set /subcategory:"Account Lockout" /success:enable /failure:enable
auditpol /set /subcategory:"User Account Management" /success:enable /failure:enable
auditpol /set /subcategory:"Security Group Management" /success:enable /failure:enable

# View current settings
auditpol /get /category:*

5. Disable USB Storage:

# GPO: Computer Configuration → Policies → Administrative Templates → System → Removable Storage Access
# "All Removable Storage: Deny all access" → Enabled

Force GPO Update:

# On client
gpupdate /force

# Remote update
Invoke-GPUpdate -Computer "CLIENT01" -Force

# Verify applied GPOs
gpresult /r
gpresult /h C:\gpreport.html

![Screenshot Group Policy editor - Đặt ảnh tại /static/img/windows/ws2022-gpo.png]

Phần 4: Remote Desktop Hardening

1. Change RDP Port

# Change port to 3390
Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp' -Name "PortNumber" -Value 3390

# Restart Terminal Services
Restart-Service TermService -Force

# Update firewall rule
New-NetFirewallRule -DisplayName "RDP-Custom-Port" -Direction Inbound -LocalPort 3390 -Protocol TCP -Action Allow

# Disable old rule
Disable-NetFirewallRule -DisplayName "Remote Desktop*"

Connect với custom port:

mstsc /v:server-ip:3390

2. Require Network Level Authentication (NLA)

# Enable NLA
Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp' -Name "UserAuthentication" -Value 1

# Require TLS 1.2+
Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp' -Name "SecurityLayer" -Value 2
Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp' -Name "MinEncryptionLevel" -Value 3

3. Configure RDP Timeout

# Set idle timeout (15 minutes = 900000 ms)
Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp' -Name "MaxIdleTime" -Value 900000

# Set session timeout (2 hours = 7200000 ms)
Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp' -Name "MaxConnectionTime" -Value 7200000

4. Restrict RDP Access

# Allow only specific users/groups
Add-LocalGroupMember -Group "Remote Desktop Users" -Member "example\IT-Admins"

# Remove default groups if needed
Remove-LocalGroupMember -Group "Remote Desktop Users" -Member "example\Domain Users"

# List current RDP users
Get-LocalGroupMember -Group "Remote Desktop Users"

5. Enable RDP Logging

# Enable detailed RDP logging
wevtutil sl Microsoft-Windows-TerminalServices-LocalSessionManager/Operational /e:true /ms:52428800

# View RDP login events (Event ID 21, 23, 24, 25)
Get-WinEvent -LogName "Microsoft-Windows-TerminalServices-LocalSessionManager/Operational" | Where-Object {$_.Id -eq 21 -or $_.Id -eq 25} | Format-List TimeCreated, Message

Phần 5: Windows Firewall Configuration

Basic Firewall Rules

# Enable firewall for all profiles
Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled True

# Block all inbound by default
Set-NetFirewallProfile -Profile Domain,Public,Private -DefaultInboundAction Block

# Allow essential services
New-NetFirewallRule -DisplayName "ICMP-Allow" -Direction Inbound -Protocol ICMPv4 -Action Allow
New-NetFirewallRule -DisplayName "HTTP" -Direction Inbound -LocalPort 80 -Protocol TCP -Action Allow
New-NetFirewallRule -DisplayName "HTTPS" -Direction Inbound -LocalPort 443 -Protocol TCP -Action Allow
New-NetFirewallRule -DisplayName "DNS" -Direction Inbound -LocalPort 53 -Protocol UDP -Action Allow

# Allow RDP from specific subnet
New-NetFirewallRule -DisplayName "RDP-Allow-Subnet" -Direction Inbound -LocalPort 3389 -Protocol TCP -RemoteAddress 192.168.1.0/24 -Action Allow

# Block specific IP
New-NetFirewallRule -DisplayName "Block-Malicious-IP" -Direction Inbound -RemoteAddress 203.0.113.10 -Action Block

# List all rules
Get-NetFirewallRule | Format-Table DisplayName, Enabled, Direction, Action

# Export rules
Get-NetFirewallRule | Export-Csv C:\firewall-rules.csv

# Disable rule
Disable-NetFirewallRule -DisplayName "Remote Desktop*"

Advanced Firewall with Logging

# Enable firewall logging
Set-NetFirewallProfile -Profile Domain -LogFileName "C:\Windows\System32\LogFiles\Firewall\pfirewall-domain.log" -LogMaxSizeKilobytes 4096 -LogAllowed True -LogBlocked True

# View blocked connections
Select-String -Path "C:\Windows\System32\LogFiles\Firewall\pfirewall-domain.log" -Pattern "DROP"

Phần 6: Security Hardening

1. Disable Unnecessary Services

# List services
Get-Service | Where-Object {$_.Status -eq "Running"} | Format-Table Name, DisplayName

# Disable services (examples - verify before disabling!)
$servicesToDisable = @(
"TabletInputService", # Touch Keyboard and Handwriting Panel
"Fax",
"XblAuthManager", # Xbox Live
"XblGameSave",
"XboxNetApiSvc"
)

foreach ($service in $servicesToDisable) {
Stop-Service $service -Force -ErrorAction SilentlyContinue
Set-Service $service -StartupType Disabled -ErrorAction SilentlyContinue
}

2. Enable Windows Defender

# Check Windows Defender status
Get-MpComputerStatus

# Enable real-time protection
Set-MpPreference -DisableRealtimeMonitoring $false

# Update definitions
Update-MpSignature

# Run quick scan
Start-MpScan -ScanType QuickScan

# Schedule scan
Set-MpPreference -ScanScheduleDay Everyday -ScanScheduleTime 02:00:00

# Enable cloud protection
Set-MpPreference -MAPSReporting Advanced
Set-MpPreference -SubmitSamplesConsent SendAllSamples

# Exclusions (nếu cần)
Add-MpPreference -ExclusionPath "C:\App\Data"

3. BitLocker Drive Encryption

# Check BitLocker status
Get-BitLockerVolume

# Enable BitLocker on C:
Enable-BitLocker -MountPoint "C:" -EncryptionMethod XtsAes256 -UsedSpaceOnly -RecoveryPasswordProtector

# Save recovery key
(Get-BitLockerVolume -MountPoint "C:").KeyProtector | Out-File C:\bitlocker-recovery.txt

# Verify
Get-BitLockerVolume -MountPoint "C:"

4. Security Baselines từ Microsoft

# Download Security Compliance Toolkit
# https://www.microsoft.com/en-us/download/details.aspx?id=55319

# Import GPO backups
Import-GPO -BackupId "{GUID}" -TargetName "MS-Security-Baseline-WS2022" -Path "C:\SecurityBaselines\GPOs"

# Link to domain
New-GPLink -Name "MS-Security-Baseline-WS2022" -Target "DC=example,DC=local" -Enforced Yes

5. Windows Update Automation

# Configure automatic updates
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "NoAutoUpdate" -Value 0
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "AUOptions" -Value 4 # Auto download and schedule install

# Or use PowerShell module
Install-Module PSWindowsUpdate -Force
Add-WUServiceManager -ServiceID 7971f918-a847-4430-9279-4a52d1efe18d # Microsoft Update

# Auto-install updates
Install-WindowsUpdate -MicrosoftUpdate -AcceptAll -AutoReboot -IgnoreReboot

Phần 7: Backup và Disaster Recovery

Windows Server Backup

# Install backup feature
Install-WindowsFeature Windows-Server-Backup -IncludeManagementTools

# Configure backup policy
$policy = New-WBPolicy

# Add C: drive
$volume = Get-WBVolume -VolumePath "C:"
Add-WBVolume -Policy $policy -Volume $volume

# Add system state
Add-WBSystemState -Policy $policy

# Set backup target (external drive)
$target = New-WBBackupTarget -VolumePath "E:"
Add-WBBackupTarget -Policy $policy -Target $target

# Schedule backup (daily at 2 AM)
Set-WBSchedule -Policy $policy -Schedule 02:00

# Set retention
Set-WBPolicy -Policy $policy

# Start backup now
Start-WBBackup -Policy $policy

# List backups
Get-WBBackupSet

System State Backup

# Backup system state
wbadmin start systemstatebackup -backupTarget:E: -quiet

# Restore system state
wbadmin start systemstaterecovery -version:12/19/2025-02:00 -backupTarget:E: -machine:SRV-DC01

Phần 8: Monitoring và Logging

Event Viewer Monitoring

# Critical events to monitor
$events = @{
"Security" = @(4624, 4625, 4648, 4720, 4726) # Logon/Logoff, Account creation/deletion
"System" = @(1074, 6005, 6006, 6008) # Shutdown/Startup, Unexpected shutdown
"Application" = @(1000, 1001, 1002) # Application errors
}

# Get recent security events
Get-WinEvent -FilterHashtable @{LogName='Security'; ID=4625; StartTime=(Get-Date).AddDays(-1)} | Format-Table TimeCreated, Message -AutoSize

# Export events
Get-WinEvent -FilterHashtable @{LogName='Security'; StartTime=(Get-Date).AddDays(-7)} | Export-Csv C:\Logs\security-events.csv

# Clear event log (after backup!)
wevtutil cl Security /bu:C:\Logs\Security-Backup.evtx

Performance Monitoring

# Create data collector set
$collector = New-Object -ComObject Pla.DataCollectorSet
$collector.DisplayName = "Server-Performance"
$collector.Duration = 3600 # 1 hour

# Add performance counters
$counters = @(
"\Processor(_Total)\% Processor Time",
"\Memory\Available MBytes",
"\PhysicalDisk(_Total)\Disk Bytes/sec",
"\Network Interface(*)\Bytes Total/sec"
)

# Start collection
logman create counter "Server-Performance" -c $counters -f csv -o "C:\PerfLogs\server-perf.csv" -si 5

logman start "Server-Performance"

Testing và Verification

Security Audit Script

# security-audit.ps1

Write-Host "=== Windows Server Security Audit ===" -ForegroundColor Green

# Check Windows Defender
Write-Host "`n1. Windows Defender Status:" -ForegroundColor Yellow
Get-MpComputerStatus | Select-Object AntivirusEnabled, RealTimeProtectionEnabled, IoavProtectionEnabled

# Check Firewall
Write-Host "`n2. Firewall Status:" -ForegroundColor Yellow
Get-NetFirewallProfile | Select-Object Name, Enabled

# Check RDP Settings
Write-Host "`n3. RDP Configuration:" -ForegroundColor Yellow
$rdp = Get-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server'
Write-Host "RDP Enabled: $($rdp.fDenyTSConnections -eq 0)"
Write-Host "NLA Required: $((Get-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp').UserAuthentication -eq 1)"

# Check Updates
Write-Host "`n4. Windows Updates:" -ForegroundColor Yellow
$updates = Get-HotFix | Sort-Object -Property InstalledOn -Descending | Select-Object -First 5
$updates | Format-Table HotFixID, Description, InstalledOn

# Check Failed Logins
Write-Host "`n5. Recent Failed Login Attempts:" -ForegroundColor Yellow
Get-WinEvent -FilterHashtable @{LogName='Security'; ID=4625; StartTime=(Get-Date).AddDays(-1)} | Select-Object -First 10 | Format-Table TimeCreated, Message

# Check Admin Users
Write-Host "`n6. Local Administrators:" -ForegroundColor Yellow
Get-LocalGroupMember -Group "Administrators" | Format-Table Name, PrincipalSource

Write-Host "`n=== Audit Complete ===" -ForegroundColor Green

Tài Liệu Tham Khảo

Kết Luận

Bạn đã hoàn thành việc cài đặt và hardening Windows Server 2022 production-ready. Server này có thể:

✅ Function như Active Directory Domain Controller
✅ Quản lý users và groups với AD
✅ Enforce security policies via GPO
✅ Secure Remote Desktop access
✅ Monitor và audit system events
✅ Tự động backup và disaster recovery

Checklist bảo mật:

☐ Strong password policies enforced
☐ RDP hardened (custom port, NLA, logging)
☐ Firewall configured và tested
☐ Windows Defender enabled và updated
☐ Audit logging configured
☐ Regular backups scheduled
☐ Security baselines applied
☐ Unnecessary services disabled
☐ Group policies enforced
☐ Monitoring alerts configured

Maintenance Tasks:

  • Weekly: Review event logs
  • Monthly: Check Windows Updates
  • Quarterly: Security audit
  • Yearly: Disaster recovery test

Tags: #windows-server #windows-server-2022 #active-directory #group-policy #rdp-security #powershell #server-hardening

Cập nhật lần cuối: 19/12/2025
Tác giả: BacPV Docs Team