主頁 >  其他 > 如何利用PowerShell完成的Windows服務器系統安全加固實踐和基線檢測

如何利用PowerShell完成的Windows服務器系統安全加固實踐和基線檢測

2022-04-11 11:04:41 其他

0x00 前言簡述

最近單位在做等保測評,由本人從事安全運維方面的作業(PS:曾經做過等保等方面的安全服務),所以自然而然的與信安的測評人員一起對接相關業務系統的檢查,在做主機系統測評檢查時發現了系統中某些配置不符合等保要求,需要對不滿足要求的主機做進一步整改,好在我們眾多的系統基本都是運行在虛擬機上搭建的kubernetes集群中,這樣一來就可以盡可能減少加固系統給應用帶來的影響,我們可以一臺一臺加固更新,

在這樣環境的驅動下不得不將通宵熬夜,我準備好了枸杞和保溫杯,當然也把測驗環境也準備了一套,并將以前寫的安全加固腳本進行重新整理,根據當前業務服務器系統版本進行更新和測驗,(我還年輕,我還可加班!)

我們企業內部主要有WindowsServer2019CentOS7、以及Ubuntu20.04三類作業系統,可以看出作業系統版本都還是比較新的,所以在下面的安全配置核查腳本以及安全加固腳本主要針對上述的三個版本的作業系統,

Linux 系統中采用Shell腳本、WiindowsServer系統中采用的是PowerShell腳本進行撰寫, 注意腳本會有一定更新建議通過下面的專案地址獲取最新的腳本

Github 專案地址: https://github.com/WeiyiGeek/SecOpsDev/blob/master/OS-作業系統 【GitHub Repo stars GitHub forks 】,歡迎大家 Star 與 Fork ,

原文鏈接: 完整的Windows與Linux服務器系統安全加固實踐和基線檢測腳本(等保2.0)( https://mp.weixin.qq.com/s/CDGzTzrAk9vJtbH4BisSlw )


WindowsSever 2019 安全配置策略基線配置核查效果圖

系統基礎資訊

等保主機測評項

系統補丁資訊

系統補丁資訊


WindowsSever2019 主機測評項安全加固效果圖

等保主機測評項

等保主機測評項

主機測評加固


溫馨提示: 下面腳本有點長,需要有一定的耐心喲,


0x01 WindowServer2019 配置核查與安全加固

Windows 加固專案地址: https://github.com/WeiyiGeek/SecOpsDev/tree/master/OS-作業系統/Windows

Windows Server 安全配置策略基線加固項

  • 系統賬號策略
  • 系統事件審核策略
  • 系統組策略安全選項策略
  • 注冊表相關安全策略
  • 防火墻服務相關安全策略
  • 針對于系統暫無辦法通過注冊表以及組策略配置的安全加固項
  • 從微軟安全中心拉取服務器安全補丁串列資訊與本地已打補丁做比較

廢話不多,上才藝(腳本 )

Windows Server 安全配置策略基線檢測腳本
Link: https://github.com/WeiyiGeek/SecOpsDev/blob/master/OS-作業系統/Windows/WindowsSecurityBaseLine.ps1

#######################################################
# @Author: WeiyiGeek
# @Description:  Windows Server 安全配置策略基線檢測腳本
# @Create Time:  2019年5月6日 11:04:42
# @Last Modified time: 2021-11-15 11:06:31
# @E-mail: [email protected]
# @Blog: https://www.weiyigeek.top
# @wechat: WeiyiGeeker
# @Github: https://github.com/WeiyiGeek/SecOpsDev/tree/master/OS-作業系統/Windows/
# @Version: 1.8
# @Runtime: Server 2019 / Windows 10
#######################################################

<#
.SYNOPSIS
Windows Server 安全配置策略基線檢測腳本 (腳本將會在Github上持續更新)

.DESCRIPTION
Windows Server 作業系統配置策略核查 (符合等保3級的關鍵檢查項)

.EXAMPLE
WindowsSecurityBaseLine.ps1 -Executor WeiyiGeek -MsrcUpdate False
- Executor : 腳本執行者
- MsrcUpdate : 是否在線拉取微軟安全中心的服務器安全補丁串列資訊(建議一臺主機拉取好之后將WSUSList.json和WSUSListId.json拷貝到當前腳本同級目錄下)
.NOTES
注意:不同的版本作業系統以下某些關鍵項可能會不存在會有一些警告(需要大家提交issue,共同完成),
#>
[Cmdletbinding()]
param(
  [Parameter(Mandatory=$true)][String]$Executor,
  [Boolean]$MsrcUpdate
)

# * 檔案輸出默認為UTF-8格式
$PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'


################################################################################################################################
# **********************#
# * 全域公用工具依賴函式  *  
# **********************#
Function F_IsCurrentUserAdmin
{ 
<#
.SYNOPSIS
F_IsCurrentUserAdmin 函式:全域公用工具依賴,
.DESCRIPTION
判斷當前運行的powershell終端是否管理員執行,回傳值 true 或者 false
.EXAMPLE
F_IsCurrentUserAdmin
#>
  $user = [Security.Principal.WindowsIdentity]::GetCurrent(); 
  (New-Object Security.Principal.WindowsPrincipal $user).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator) 
} 

function F_Logging {
<#
.SYNOPSIS
F_Logging 日志輸出函式
.DESCRIPTION
用于輸出腳本執行結果并按照不同的日志等級輸出顯示到客戶終端上,
.EXAMPLE
F_Logging -Level [Info|Warning|Error] -Msg "測驗輸出字串"
#>
  param (
    [Parameter(Mandatory=$true)]$Msg,
    [ValidateSet("Info","Warning","Error")]$Level
  )

  switch ($Level) {
    Info { 
      Write-Host "[INFO] ${Msg}" -ForegroundColor Green;
    }
    Warning {
      Write-Host "[WARN] ${Msg}" -ForegroundColor Yellow;
    }
    Error { 
      Write-Host "[ERROR] ${Msg}" -ForegroundColor Red;
    }
    Default {
      Write-Host "[*] F_Logging 日志 Level 等級錯誤`n Useage: F_Logging -Level [Info|Warning|Error] -Msg '測驗輸出字串'" -ForegroundColor Red;
    }
  }
}

function F_Tools {
<#
.SYNOPSIS
F_Tools 檢測對比函式
.DESCRIPTION
驗證判斷傳入的欄位是否與安全加固欄位一致
.EXAMPLE
F_Tools -Key "ItemDemo" -Value "2" -Operator "eq" -DefaultValue "1"  -Msg "對比ItemDemo欄位值與預設值"
#>
  param (
    [Parameter(Mandatory=$true)][String]$Key,
    [Parameter(Mandatory=$true)]$Value,
    [Parameter(Mandatory=$true)]$DefaultValue,
    [String]$Msg,
    [String]$Operator
  )
  
  if ( $Operator -eq  "eq" ) {
    if ( $Value -eq $DefaultValue ) {
      $Result = @{"$($Key)"="[合格項]|$($Value)|$($DefaultValue)|$($Msg)-【符合】等級保護標準."}
      Write-Host "$($Key)"=" [合格項]|$($Value)|$($DefaultValue)|$($Msg)-【符合】等級保護標準." -ForegroundColor White
      return $Result
    } else {
      $Result = @{"$($Key)"="[例外項]|$($Value)|$($DefaultValue)|$($Msg)-【不符合】等級保護標準."}
      Write-Host "$($Key)"=" [例外項]|$($Value)|$($DefaultValue)|$($Msg)-【不符合】等級保護標準." -ForegroundColor red
      return $Result
    }

  } elseif ($Operator -eq  "ne" ) {

    if ( $Value -ne $DefaultValue ) {
      $Result = @{"$($Key)"="[合格項]|$($Value)|$($DefaultValue)|$($Msg)-【符合】等級保護標準."}
      Write-Host "$($Key)"=" [合格項]|$($Value)|$($DefaultValue)|$($Msg)-【符合】等級保護標準." -ForegroundColor White
      return $Result
    } else {
      $Result = @{"$($Key)"="[例外項]|$($Value)|$($DefaultValue)|$($Msg)-【不符合】等級保護標準."}
      Write-Host "$($Key)"=" [例外項]|$($Value)|$($DefaultValue)|$($Msg)-【不符合】等級保護標準." -ForegroundColor red
      return $Result
    }

  } elseif ($Operator -eq  "le") {

    if ( $Value -le $DefaultValue ) {
      $Result = @{"$($Key)"="[合格項]|$($Value)|$($DefaultValue)|$($Msg)-【符合】等級保護標準."}
      Write-Host "$($Key)"=" [合格項]|$($Value)|$($DefaultValue)|$($Msg)-【符合】等級保護標準." -ForegroundColor White
      return $Result
    } else {
      $Result = @{"$($Key)"="[例外項]|$($Value)|$($DefaultValue)|$($Msg)-【不符合】等級保護標準."}
      Write-Host "$($Key)"=" [例外項]|$($Value)|$($DefaultValue)|$($Msg)-【不符合】等級保護標準." -ForegroundColor red
      return $Result
    }

  } elseif ($Operator -eq "ge") {

    if ( $Value -ge $DefaultValue ) {
      $Result =  @{"$($Key)"="[合格項]|$($Value)|$($DefaultValue)|$($Msg)-【符合】等級保護標準."}
      Write-Host "$($Key)"=" [合格項]|$($Value)|$($DefaultValue)|$($Msg)-【符合】等級保護標準." -ForegroundColor White
      return $Result
    } else {
      $Result = @{"$($Key)"="[例外項]|$($Value)|$($DefaultValue)|$($Msg)-【不符合】等級保護標準."}
      Write-Host "$($Key)"=" [例外項]|$($Value)|$($DefaultValue)|$($Msg)-【不符合】等級保護標準." -ForegroundColor red
      return $Result
    }
  }
}

function F_GetRegPropertyValue {
  param (
    [Parameter(Mandatory=$true)][String]$Key,
    [Parameter(Mandatory=$true)][String]$Name,
    [Parameter(Mandatory=$true)][String]$Operator,
    [Parameter(Mandatory=$true)]$DefaultValue,
    [Parameter(Mandatory=$true)][String]$Msg
  )

  try {
    $Value = https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/Get-ItemPropertyValue -Path"Registry::$Key" -ErrorAction Ignore -WarningAction Ignore -Name $Name
    $Result = F_Tools -Key "Registry::$($Name)" -Value $Value -Operator $Operator -DefaultValue $DefaultValue  -Msg $Msg
    return $Result
  } catch {
   $Result = @{"Registry::$($Name)"="[例外項]|$($Key)中$($Name)不存在該項|$($DefaultValue)|$($Msg)"}
   Write-Host $Result.Values -ForegroundColor Red
   return $Result
  }
}

Function F_UrlRequest {
  param (
    [Parameter(Mandatory=$true)][String]$Msrc_api
  )
  Write-Host "[-] $($Msrc_api)" -ForegroundColor Gray
  $Response=Invoke-WebRequest -Uri "$($Msrc_api)"
  Return ConvertFrom-Json -InputObject $Response
}

################################################################################################################################
#
# * 作業系統基礎資訊記錄函式 * #
#
# - 系統資訊記錄函式 - #
$SysInfo = @{}
# - Get-Computer 命令使用 
# Tips :在 Server 2019 以及 Windows 10 以下系統無該命令
# $Item = 'WindowsProductName','WindowsEditionId','WindowsInstallationType','WindowsCurrentVersion','WindowsVersion','WindowsProductId','BiosManufacturer','BiosFirmwareType','BiosName','BiosVersion','BiosBIOSVersion','BiosSeralNumber','CsBootupState','OsBootDevice','BiosReleaseDate','CsName','CsAdminPasswordStatus','CsManufacturer','CsModel','OsName','OsType','OsProductType','OsServerLevel','OsArchitecture','CsSystemType','OsOperatingSystemSKU','OsVersion','OsBuildNumber','OsSerialNumber','OsInstallDate','OsSystemDevice','OsSystemDirectory','OsCountryCode','OsCodeSet','OsLocaleID','OsCurrentTimeZone','TimeZone','OsLanguage','OsLocalDateTime','OsLastBootUpTime','CsProcessors','OsBuildType','CsNumberOfProcessors','CsNumberOfLogicalProcessors','OsMaxNumberOfProcesses','OsTotalVisibleMemorySize','OsFreePhysicalMemory','OsTotalVirtualMemorySize','OsFreeVirtualMemory','OsInUseVirtualMemory','OsMaxProcessMemorySize','CsNetworkAdapters','OsHotFixes'
# - Systeminfo 命令使用(通用-推薦)
$Item = 'Hostname','OSName','OSVersion','OSManufacturer','OSConfiguration','OS Build Type','RegisteredOwner','RegisteredOrganization','Product ID','Original Install Date','System Boot Time','System Manufacturer','System Model','System Type','Processor(s)','BIOS Version','Windows Directory','System Directory','Boot Device','System Locale','Input Locale','Time Zone','Total Physical Memory','Available Physical Memory','Virtual Memory: Max Size','Virtual Memory: Available','Virtual Memory: In Use','Page File Location(s)','Domain','Logon Server','Hotfix(s)','Network Card(s)'
Function F_SysInfo {
  # - 當前系統及計算機相關資訊 (Primary)
  # Server 2019 以及 Windows 10 適用
  # $Computer = Get-ComputerInfo
  $Computer = systeminfo.exe /FO CSV /S $env:COMPUTERNAME |Select-Object -Skip 1 | ConvertFrom-CSV -Header $Item
  foreach( $key in $Item) {
    $SysInfo += @{"$($key)"=$Computer.$key}
  }
  # - 通用設定針對采用`systeminfo.exe`命令方式
  $SysInfo += @{"WindowsProductName"="$($SysInfo.OSName)"}
  $SysInfo.OsVersion=($Sysinfo.OSVersion -split " ")[0]
  $SysInfo += @{"CsSystemType"=($Sysinfo."System Type" -split " ")[0]}

  # - 當前系統 PowerShell 版本資訊以及是否為虛擬機
  $SysInfo += @{"PSVersion"=$PSVersionTable.PSEdition+"-"+$PSVersionTable.PSVersion}

  # - 驗證當前計算機產品及其版本 (Primary)
  $Flag = $SysInfo.WindowsProductName -match  "Windows 8.1|Windows 10|Server 2008|Server 2012|Server 2016|Server 2019"
  $ProductName = "$($Matches.Values)"
  if ( $ProductName.Contains("Windows")) {
    $SysInfo += @{"ProductType"="Client"}
    $SysInfo += @{"ProductName"=$ProductName}
    $SysInfo += @{"WindowsVersion"=Get-ItemPropertyValue -Path 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -Name ReleaseId}
  } else {
    $SysInfo += @{"ProductType"="Server"}
    $SysInfo += @{"ProductName"=$ProductName}
  }

  # - 驗證當前計算機產品是是物理機還是虛擬機 (Primary)
  $ComputerType = get-wmiobject win32_computersystem
  if ($ComputerType.Manufacturer -match "VMware"){
    $SysInfo += @{"ComputerType"="虛擬機 - $($ComputerType.Model)"}
  } else {
    $SysInfo += @{"ComputerType"="物理機 - $($ComputerType.Model)"}
  }
  
  # # - 當前計算機溫度值資訊記錄 (WINDOWSERVER2019支持)
  # Get-CimInstance -Namespace ROOT/WMI -Class MSAcpi_ThermalZoneTemperature | % { 
  #   $currentTempKelvin = $_.CurrentTemperature / 10 
  #   $currentTempCelsius = $currentTempKelvin - 273.15 
  #   $currentTempFahrenheit = (9/5) * $currentTempCelsius + 32 
  #   $Temperature += "InstanceName: " + $_.InstanceName+ " ==>> " +  $currentTempCelsius.ToString() + " 攝氏度(C);  " + $currentTempFahrenheit.ToString() + " 華氏度(F) ; " + $currentTempKelvin + "開氏度(K) `n" 
  # }
  # $SysInfo += @{"Temperature"=$Temperature}

  return $SysInfo
}


#
# * - 計算機Mac及IP地址資訊函式 * #
#
#  * 系統網路及配接器資訊變數 * #
$SysNetAdapter = @{}
function F_SysNetAdapter {
  # - 計算機Mac及IP地址資訊
  $Adapter = Get-NetAdapter | Sort-Object -Property LinkSpeed
  foreach ( $Item in $Adapter) {
    $IPAddress = (Get-NetIPAddress -AddressFamily IPv4 -InterfaceIndex $Item.ifIndex).IPAddress
    $SysNetAdapter += @{"$($Item.MacAddress)"="$($Item.Status) | $($Item.Name) | $($IPAddress) | $($Item.LinkSpeed) | $($Item.InterfaceDescription)"}
  }
  return $SysNetAdapter
}


#
# * - 計算機系統磁盤與空間剩余查詢函式 * #
#
# - 系統磁盤與空間剩余資訊 - #
$SysDisk = @{}
function F_SysDisk {
  # - 計算機磁盤資訊
  $Disk = Get-Disk
  foreach ( $Item in $Disk) {
    $SysDisk += @{"$($Item.SerialNumber)"="$($Item.Number) | $($Item.FriendlyName) | $($Item.HealthStatus)| $($Item.Size / [math]::Pow(1024,3)) GB | $($Item.PartitionStyle) |$($Item.OperationalStatus)"}
  }
  $Drive = Get-PSDrive -PSProvider FileSystem | Sort-Object -Property Name
  $Drive | % {
    $Free = [Math]::Round( $_.Free / [math]::pow(1024,3),2 )
    $Used = [Math]::Round( $_.Used / [math]::pow(1024,3),2 )
    $Total = [Math]::Ceiling($Free + $Used)
    $SysDisk += @{"FileSystem::$($_.Name)"="$($_.Name) | Free: $($Free) GB | Used: $($Used) GB | Total: $($Total) GB"}
  }
  return $SysDisk
}


#
# * 系統賬號檢查函式  * #
#
# - 系統賬戶資訊變數 - # 
$SysAccount = @{}
Function F_SysAccount {
  # - 賬戶檢查
  $Account = Get-WmiObject -Class Win32_UserAccount | Select-Object Name,AccountType,Caption,SID
  Write-Host "* 當前系統存在的 $($Account.Length) 名賬戶 : $($Account.Name)" -ForegroundColor Green
  if($Acount.Length -ge 4 -and ($Account.sid  | Select-String -Pattern "^((?!(-500|-501|-503|-504)).)*$")) {
    $Result = @{"SysAccount"="[例外項]-系統中存在其他賬號請檢查: $($Account.Name)"}
    $SysAccount += $Result
  }else{
    $Result = @{"SysAccount"="[合格項]-系統中無多余其他賬號";}
    $SysAccount += $Result
  }
  return $SysAccount
}

#
# * 系統賬號策略配置核查函式  * #
#
# - 系統賬號策略 - #
$SysAccountPolicy = @{
  # + 密碼最短留存期
  "MinimumPasswordAge" = @{operator="le";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/1;msg="密碼最短留存期"}
  # + 密碼最長留存期
  "MaximumPasswordAge" = @{operator="le";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/90;msg="密碼最長留存期"}
  # + 密碼長度最小值
  "MinimumPasswordLength" = @{operator="ge";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/14;msg="密碼長度最小值"}
  # + 密碼必須符合復雜性要求
  "PasswordComplexity" = @{operator="eq";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/1;msg="密碼必須符合復雜性要求策略"}
  # + 強制密碼歷史 N個記住的密碼
  "PasswordHistorySize" = @{operator="ge";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/3;msg="強制密碼歷史個記住的密碼"}
  # + 賬戶登錄失敗鎖定閾值N次數
  "LockoutBadCount" = @{operator="le";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/6;msg="賬戶登錄失敗鎖定閾值次數"}
  # + 賬戶鎖定時間(分鐘)
  "ResetLockoutCount" = @{operator="ge";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/15;msg="賬戶鎖定時間(分鐘)"}
  # + 復位賬戶鎖定計數器時間(分鐘)
  "LockoutDuration" = @{operator="ge";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/15;msg="復位賬戶鎖定計數器時間(分鐘)"}
  # + 下次登錄必須更改密碼
  "RequireLogonToChangePassword" = @{operator="eq";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/0;msg="下次登錄必須更改密碼"}
  # + 強制過期
  "ForceLogoffWhenHourExpire" = @{operator="eq";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/0;msg="強制過期"}
  # + 當前管理賬號登陸名稱
  "NewAdministratorName" = @{operator="ne";value='"Administrator"';msg="當前系統默認管理賬號登陸名稱策略"}
  # + 當前來賓用戶登陸名稱
  "NewGuestName" = @{operator="ne";value='"Guest"';msg="當前系統默認來賓用戶登陸名稱策略"}
  # + 管理員是否被啟用
  "EnableAdminAccount" = @{operator="eq";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/1;msg="管理員賬戶停用與啟用策略"}
  # + 來賓用戶是否啟用
  "EnableGuestAccount" = @{operator="eq";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/0;msg="來賓賬戶停用與啟用策略"}
  # + 指示是否使用可逆加密來存盤密碼一般禁用(除非應用程式要求超過保護密碼資訊的需要)
  "ClearTextPassword" = @{operator="eq";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/0;msg="指示是否使用可逆加密來存盤密碼 (除非應用程式要求超過保護密碼資訊的需要)"}
  # + 啟用時此設定允許匿名用戶查詢本地LSA策略(0關閉)
  "LSAAnonymousNameLookup" = @{operator="eq";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/0;msg="啟用時此設定允許匿名用戶查詢本地LSA策略 (0關閉)"}
  # + 檢查結果存放的空陣列
  "CheckResults" = @()
  }
Function F_SysAccountPolicy {
  $Count = $Config.Count
  for ($i=0;$i -lt $Count; $i++){
    $Line = $Config[$i] -split " = "
    if ($SysAccountPolicy.ContainsKey("$($Line[0])")) {
      $Result = F_Tools -Key "SysAccountPolicy::$($Line[0])" -Value $Line[1] -Operator $SysAccountPolicy["$($Line[0])"].Operator -DefaultValue $SysAccountPolicy["$($Line[0])"].Value  -Msg "系統賬號策略配置-$($SysAccountPolicy["$($Line[0])"].Msg)"
      $SysAccountPolicy['CheckResults'] += $Result
    }
    if ( $Line[0] -eq "[Event Audit]" ) { break;}
  }
  return $SysAccountPolicy['CheckResults']
}



#
# * 系統事件審核策略配置核查函式  * #
#
# - 系統事件審核策略 - #
$SysEventAuditPolicy  = @{
  # + 審核系統事件(0) [成功(1)、失敗(2)] (3)
  AuditSystemEvents = @{operator="eq";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/3;msg="審核系統事件"}
  # + 審核登錄事件 成功、失敗
  AuditLogonEvents = @{operator="eq";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/3;msg="審核登錄事件"}
  # + 審核物件訪問 成功、失敗
  AuditObjectAccess = @{operator="eq";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/3;msg="審核物件訪問"}
  # + 審核特權使用 失敗
  AuditPrivilegeUse = @{operator="ge";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/2;msg="審核特權使用"}
  # + 審核策略更改 成功、失敗
  AuditPolicyChange = @{operator="eq";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/3;msg="審核策略更改"}
  # + 審核賬戶管理 成功、失敗
  AuditAccountManage = @{operator="eq";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/3;msg="審核賬戶管理"}
  # + 審核程序追蹤 失敗
  AuditProcessTracking = @{operator="ge";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/2;msg="審核程序追蹤"}
  # + 審核目錄服務訪問 失敗
  AuditDSAccess = @{operator="ge";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/2;msg="審核目錄服務訪問"}
  # + 審核賬戶登錄事件 成功、失敗
  AuditAccountLogon = @{operator="eq";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/3;msg="審核賬戶登錄事件"}
  # + 檢查結果存放的空陣列
  CheckResults = @()
}
function F_SysEventAuditPolicy {
  $Count = $Config.Count
  for ($i=0;$i -lt $Count; $i++){
    $Line = $Config[$i] -split " = "
    if ( $Line[0] -eq "[Registry Values]" ) { break;}
    if ($SysEventAuditPolicy.ContainsKey("$($Line[0])")) {
      $Result = F_Tools -Key "SysEventAuditPolicy::$($Line[0])" -Value $Line[1] -Operator $SysEventAuditPolicy["$($Line[0])"].Operator -DefaultValue $SysEventAuditPolicy["$($Line[0])"].Value  -Msg "系統賬號策略配置-$($SysEventAuditPolicy["$($Line[0])"].Msg)"
      $SysEventAuditPolicy['CheckResults'] += $Result
    }
  }

  return $SysEventAuditPolicy['CheckResults']
}

#
# * 作業系統用戶權限管理策略檢查  * #
#
# - 組策略用戶權限管理策略 - #
$SysUserPrivilegePolicy = @{
# + 作業系統本地關機策略安全
SeShutdownPrivilege = @{operator="eq";value='https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/*S-1-5-32-544';msg="作業系統本地關機策略"}
# + 作業系統遠程關機策略安全
SeRemoteShutdownPrivilege = @{operator="eq";value='https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/*S-1-5-32-544';msg="作業系統遠程關機策略"}
# + 取得檔案或其他物件的所有權限策略
SeProfileSingleProcessPrivilege = @{operator="eq";value='https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/*S-1-5-32-544';msg="取得檔案或其他物件的所有權限策略"}
# + 從網路訪問此計算機策略
SeNetworkLogonRight = @{operator="eq";value='https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/*S-1-5-32-544,*S-1-5-32-545,*S-1-5-32-551';msg="從網路訪問此計算機策略"}
CheckResults = @()
}

Function F_SysUserPrivilegePolicy {
  # - 策略組用戶權限配置
  $Hash = $SysUserPrivilegePolicy.Clone()  # 巨坑之處
  foreach ( $Name in $Hash.keys) {
    if ( $Name.Equals("CheckResults")){ continue; }
    $Line = ($Config | Select-String $Name.toString()) -split " = "
    $Result = F_Tools -Key "SysUserPrivilegePolicy::$($Line[0])" -Value $Line[1] -Operator $SysUserPrivilegePolicy["$($Line[0])"].Operator -DefaultValue $SysUserPrivilegePolicy["$($Line[0])"].Value  -Msg "策略組用戶權限配置-$($SysUserPrivilegePolicy["$($Line[0])"].Msg)"
    $SysUserPrivilegePolicy['CheckResults'] += $Result
  }
  return $SysUserPrivilegePolicy['CheckResults']
}

#
# * 作業系統策略組安全選項權限配置檢查 * #
# 
# - 組策略安全選項策略 - #
$SysSecurityOptionPolicy = @{
  # - 帳戶:使用空密碼的本地帳戶只允許進行控制臺登錄(啟用),注意此設定不影響使用域帳戶的登錄,(0禁用|1啟用)
  LimitBlankPasswordUse = @{operator="eq";value="https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/MACHINE/System/CurrentControlSet/Control/Lsa/LimitBlankPasswordUse=4,1";msg="帳戶-使用空密碼的本地帳戶只允許進行控制臺登錄(啟用)"}
  
  # - 互動式登錄: 不顯示上次登錄用戶名值(啟用)
  DontDisplayLastUserName = @{operator="eq";value="https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/MACHINE/Software/Microsoft/Windows/CurrentVersion/Policies/System/DontDisplayLastUserName=4,1";msg="互動式登錄-不顯示上次登錄用戶名值(啟用)"}
  # - 互動式登錄: 登錄時不顯示用戶名
  DontDisplayUserName = @{operator="eq";value="https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/MACHINE/Software/Microsoft/Windows/CurrentVersion/Policies/System/DontDisplayUserName=4,1";msg="互動式登錄: 登錄時不顯示用戶名"}
  # - 互動式登錄: 鎖定會話時顯示用戶資訊(不顯示任何資訊)
  DontDisplayLockedUserId = @{operator="eq";value="https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/MACHINE/Software/Microsoft/Windows/CurrentVersion/Policies/System/DontDisplayLockedUserId=4,3";msg="互動式登錄: 鎖定會話時顯示用戶資訊(不顯示任何資訊)"}
  # - 互動式登錄: 無需按 CTRL+ALT+DEL(禁用)
  DisableCAD = @{operator="eq";value="https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/MACHINE/Software/Microsoft/Windows/CurrentVersion/Policies/System/DisableCAD=4,0";msg="互動式登錄-無需按CTRL+ALT+DEL值(禁用)"}
  # - 互動式登錄:計算機不活動限制值為600秒或更少
  InactivityTimeoutSecs = @{operator="le";value="https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/MACHINE/Software/Microsoft/Windows/CurrentVersion/Policies/System/InactivityTimeoutSecs=4,600";msg="互動式登錄-計算機不活動限制值為600秒或更少"}
  # - 互動式登錄: 計算機帳戶閾值此策略設定確定可導致計算機重啟的失敗登錄嘗試次數
  MaxDevicePasswordFailedAttempts = @{operator="le";value="https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/MACHINE/Software/Microsoft/Windows/CurrentVersion/Policies/System/MaxDevicePasswordFailedAttempts=4,10";msg="互動式登錄: 此策略設定確定可導致計算機重啟的失敗登錄嘗試次數"}
  # - 互動式登錄: 試圖登錄的用戶的訊息標題
  LegalNoticeCaption = @{operator="eq";value='https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/MACHINE/Software/Microsoft/Windows/CurrentVersion/Policies/System/LegalNoticeCaption=1,"安全登陸"';msg="互動式登錄: 試圖登錄的用戶的訊息標題"}
  # - 互動式登錄: 試圖登錄的用戶的訊息文本
  LegalNoticeText = @{operator="eq";value='https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/MACHINE/Software/Microsoft/Windows/CurrentVersion/Policies/System/LegalNoticeText=7,請謹慎的操作服務器中資料,您所有操作將被記錄審計';msg="互動式登錄: 試圖登錄的用戶的訊息文本"}
  
  # - Microsoft網路客戶端: 將未加密的密碼發送到第三方 SMB 服務器(禁用)
  EnablePlainTextPassword = @{operator="eq";value="https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/MACHINE/System/CurrentControlSet/Services/LanmanWorkstation/Parameters/EnablePlainTextPassword=4,0";msg="Microsoft網路客戶端-將未加密的密碼發送到第三方 SMB 服務器(禁用)"}
  # - Microsoft網路服務器:暫停會話前所需的空閑時間數量值為15分鐘或更少但不為0
  AutoDisconnect = @{operator="eq";value="https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/MACHINE/System/CurrentControlSet/Services/LanManServer/Parameters/AutoDisconnect=4,15";msg="Microsoft網路服務器-暫停會話前所需的空閑時間數量值為15分鐘"}
  
  # - 網路安全: 再下一次改變密碼時不存盤LAN管理器哈希值(啟用)
  NoLMHash = @{operator="eq";value="https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/MACHINE/System/CurrentControlSet/Control/Lsa/NoLMHash=4,1";msg="網路安全-在下一次改變密碼時不存盤LAN管理器哈希值(啟用)"}
  
  # - 網路訪問: 不允許SAM賬戶的匿名列舉值為(啟用)
  RestrictAnonymousSAM = @{operator="eq";value="https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/MACHINE/System/CurrentControlSet/Control/Lsa/RestrictAnonymousSAM=4,1";msg="網路訪問-不允許SAM賬戶的匿名列舉值為(啟用)"}
  # - 網路訪問:不允許SAM賬戶和共享的匿名列舉值為(啟用)
  RestrictAnonymous = @{operator="eq";value="https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/MACHINE/System/CurrentControlSet/Control/Lsa/RestrictAnonymous=4,1";msg="網路訪問-不允許SAM賬戶和共享的匿名列舉值為(啟用)"}
  
  # - 關機:設定確定是否可以在無需登錄 Windows 的情況下關閉計算機(禁用)
  ClearPageFileAtShutdown = @{operator="eq";value="https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/MACHINE/System/CurrentControlSet/Control/Session Manager/Memory Management/ClearPageFileAtShutdown=4,0";msg="關機-設定確定是否可以在無需登錄 Windows 的情況下關閉計算機(禁用)"}
  
  "CheckResults" = @()
}
Function F_SysSecurityOptionPolicy {
  $Hash = $SysSecurityOptionPolicy.Clone()  # 巨坑之處
  foreach ( $Name in $Hash.keys) {
    if ( $Name.Equals("CheckResults")){ continue; }
    $Flag = $Config | Select-String $Name.toString() 
    $Value = https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/$SysSecurityOptionPolicy["$($Name)"].Value -split ","
    if ( $Flag ) {
      $Line = $Flag -split ","
      $Result = F_Tools -Key "SysSecurityOptionPolicy::$($Name)" -Value $Line[1] -Operator $SysSecurityOptionPolicy["$($Name)"].Operator -DefaultValue $Value[1] -Msg "策略組安全選項配置-$($SysSecurityOptionPolicy["$($Name)"].Msg)"
      $SysSecurityOptionPolicy['CheckResults'] += $Result
    } else {
      $Result = @{"SysSecurityOptionPolicy::$($Name)"="[例外項]|未配置|$($Value[1])|策略組安全選項配置-$($SysSecurityOptionPolicy["$($Name)"].Msg)-【不符合】等級保護標準."}
      $SysSecurityOptionPolicy['CheckResults'] += $Result
    }
  }
  return $SysSecurityOptionPolicy['CheckResults']
}


#
# * 作業系統注冊表相關配置檢查函式  * #
#
# - 注冊表相關安全策略  -
$SysRegistryPolicy = @{
# + 螢屏自動保護程式
ScreenSaveActive = @{regname="HKEY_CURRENT_USER\Control Panel\Desktop";name="ScreenSaveActive";operator="eq";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/1;msg="系統基配核查-螢屏自動保護程式策略"}
# + 螢屏恢復時使用密碼保護
ScreenSaverIsSecure = @{regname="HKEY_CURRENT_USER\Control Panel\Desktop";name="ScreenSaverIsSecure";operator="eq";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/1;msg="系統基配核查-螢屏恢復時使用密碼保護策略"}
# + 螢屏保護程式啟動時間
ScreenSaveTimeOut = @{regname="HKEY_CURRENT_USER\Control Panel\Desktop";name="ScreenSaveTimeOut";operator="le";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/600;msg="系統基配核查-螢屏保護程式啟動時間策略"}

# + 禁止全部驅動器自動播放
DisableAutoplay  = @{regname="HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer";name="DisableAutoplay";regtype="DWord";operator="eq";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/1;msg="禁止全部驅動器自動播放"}
NoDriveTypeAutoRun = @{regname="HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer";name="NoDriveTypeAutoRun";regtype="DWord";operator="eq";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/255;msg="禁止全部驅動器自動播放"}

# - 檢查關閉默認共享盤
restrictanonymous = @{regname="HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa";name="restrictanonymous";operator="eq";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/1;msg="系統網路基配核查-關閉默認共享盤策略"}
restrictanonymoussam = @{regname="HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa";name="restrictanonymoussam";regtype="DWord";operator="eq";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/1;msg="不允許SAM賬戶的匿名列舉值為(啟用)"}

# - 禁用磁盤共享(SMB)
AutoShareWks = @{regname="HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\lanmanserver\parameters";name="AutoShareWks";regtype="DWord";operator="eq";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/0;msg="關閉禁用默認共享策略-Server2012"}
AutoShareServer = @{regname="HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\lanmanserver\parameters";name="AutoShareServer";regtype="DWord";operator="eq";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/0;msg="關閉禁用默認共享策略-Server2012"}

# - 系統、應用、安全、PS日志查看器大小設定(此處設定默認的兩倍配置-建議一定通過日志采集平臺采集系統日志比如ELK)
EventlogSystemMaxSize = @{regname="HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\System";name="MaxSize";operator="ge";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/41943040;msg="系統基日志配核查-系統日志查看器大小設定策略"}
EventlogApplicationMaxSize = @{regname="HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\Application";name="MaxSize";operator="ge";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/41943040;msg="系統日志基配核查-應用日志查看器大小設定策略"}
EventlogSecurityMaxSize = @{regname="HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\Security";name="MaxSize";operator="ge";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/41943040;msg="系統日志基配核查-安全日志查看器大小設定策略"}
EventlogPSMaxSize = @{regname="HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\Windows PowerShell";name="MaxSize";operator="ge";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/31457280;msg="系統日志基配核查-PS日志查看器大小設定策略"}

# - 防火墻相關操作設定(開啟、協議、服務)
DomainEnableFirewall  = @{regname='HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\DomainProfile';name='EnableFirewall';regtype="DWord";operator="eq";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/1;msg="開啟域網路防火墻"}
StandardEnableFirewall = @{regname='HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\SharedAccess\Parameters\FirewallPolicy\StandardProfile';name='EnableFirewall';regtype="DWord";operator="eq";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/1;msg="開啟專用網路防火墻"}
PPEnableFirewall = @{regname='HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\SharedAccess\Parameters\FirewallPolicy\PublicProfile';name='EnableFirewall';regtype="DWord";operator="eq";value=https://www.cnblogs.com/WeiyiGeek/archive/2022/04/11/1;msg="開啟公用網路防火墻"}


# - 結果存盤
CheckResults=@()
}
Function F_SysRegistryPolicy { 
  $Registry=  $SysRegistryPolicy.Clone()
  foreach ( $item in $Registry.keys) {
    if ( $item -eq "CheckResults" ){ continue;}
    $Result = F_GetRegPropertyValue -Key $SysRegistryPolicy.$item.regname -Name $SysRegistryPolicy.$item.name -Operator $SysRegistryPolicy.$item.operator -DefaultValue $SysRegistryPolicy.$item.value -Msg $SysRegistryPolicy.$item.msg
    $SysRegistryPolicy['CheckResults'] += $Result
  }
  return $SysRegistryPolicy['CheckResults']
}

#
# * 作業系統服務及運行程式檢查函式  * #
#
$SysProcessServicePolicy = @{"CheckResults"=@()}
function F_SysProcessServicePolicy {
  # + 檢測系統及用戶開機啟動項
  $SysAutoStart = Get-Item -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run'
  $SysAutoStart.GetValueNames() | % { 
    $res += "$($_)#$($SysAutoStart.GetValue($_)) "
  }
  $Result = @{"SysProcessServicePolicy::SysAutoStart"=$res}
  $SysProcessServicePolicy['CheckResults'] += $Result

  $UserAutoStart = Get-Item -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run'
  $UserAutoStart.GetValueNames() | % { 
    $res += "$($_)#$($SysAutoStart.GetValue($_)) "
  }
  $Result = @{"SysProcessServicePolicy::UserAutoStart"=$res}
  $SysProcessServicePolicy['CheckResults'] += $Result

  # + 否啟用遠程桌面服務
  $RDPStatus = (Get-Service -Name "TermService").Status
  # if ($RDP -eq "0" -and $RDPStatus -eq "Running" ) {
  #   $Result = @{"SysProcessServicePolicy::RDPStatus"="當前系統【已啟用】遠程桌面服務."}
  # } else {
  #   $Result = @{"SysProcessServicePolicy::RDPStatus"="當前系統【未啟用】遠程桌面服務."}
  # }
  if ($RDPStatus -eq "Running" ) {
    $Result = F_GetRegPropertyValue -Key 'HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Terminal Server' -Name 'fDenyTSConnections' -Operator "eq" -DefaultValue 0 -Msg "是否將遠程桌面服務禁用"
  } else {
    $Result = @{"SysProcessServicePolicy::RDPStatus"="當前系統【未啟用】遠程桌面服務."}
  }
  $SysProcessServicePolicy['CheckResults'] += $Result
  # - 否啟用NTP服務來同步時鐘
  # $NTP = F_GetReg -Key 'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpServer' -Name 'Enabled'
  # if ( $NTP -eq "1") {
  #   $Result = @{"SysProcessServicePolicy::NtpServerEnabled"="[合格項]|$NTP|1|系統基礎配置核查-啟用NTP服務同步時鐘策略-【符合】等級保護標準."}
  # } else {
  #   $Result = @{"SysProcessServicePolicy::NtpServerEnabled"="[例外項]|$NTP|1|系統基礎配置核查-啟用NTP服務同步時鐘策略-【不符合】等級保護標準."}
  # }
  $Result = F_GetRegPropertyValue -Key 'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpServer' -Name 'Enabled' -Operator "eq" -DefaultValue 1 -Msg "是否啟用NTP服務同步時鐘策略"
  $SysProcessServicePolicy['CheckResults'] += $Result
  

  # - 是否修改默認的遠程桌面埠
  $RDP1 = Get-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp\' | % {$_.GetValue("PortNumber")}
  $RDP2 = Get-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\Wds\rdpwd\Tds\tcp\' | % {$_.GetValue("PortNumber")} 
  if ( $RDP1 -eq $RDP2 -and $RDP2 -ne "3389") {
    $Result = @{"SysProcessServicePolicy::RDPPort"="[合格項]|$RDP1|除3389以外的埠|系統基礎配置核查-默認的遠程桌面埠已修改-【符合】等級保護標準."}
  } else {
    $Result = @{"SysProcessServicePolicy::RDPPort"="[例外項]|$RDP1|除3389以外的埠|系統基礎配置核查-默認的遠程桌面埠未修改-【不符合】等級保護標準."}
  }
  $SysProcessServicePolicy['CheckResults'] += $Result
}


#
# * 作業系統安全檢測函式 * 
#
# * 微軟Windows服務器安全補丁串列資訊 * #
$Msrc_api = "https://api.msrc.microsoft.com/sug/v2.0/zh-CN/affectedProduct?%24orderBy=releaseDate+desc&%24filter=productFamilyId+in+%28%27100000010%27%29+and+severityId+in+%28%27100000000%27%2C%27100000001%27%29+and+%28releaseDate+gt+2020-01-14T00%3A00%3A00%2B08%3A00%29+and+%28releaseDate+lt+2021-05-22T23%3A59%3A59%2B08%3A00%29"
$SysWSUSList = @{}
$SysWSUSListId = @()
$AvailableWSUSList = @{}
function F_SysSecurityPolicy {

  # - 系統補丁驗證
  if ( $MsrcUpdate -or ! (Test-Path -Path .\WSUSList.json) ) {
    $MSRC_JSON = F_UrlRequest -Msrc_api $Msrc_api
    $MSRC_JSON.value | % { 
      $id = $_.id;
      $product = $_.product;
      $articleName = $_.kbArticles.articleName | Get-Unique;
      $fixedBuildNumber = $_.kbArticles.fixedBuildNumber | Get-Unique;
      $severity = $_.severity;
      $impact = $_.impact;
      $baseScore = $_.baseScore;
      $cveNumber = $_.cveNumber | Get-Unique;
      $releaseDate = $_.releaseDate
      $SysWSUSList += @{"$($id)"=@{"product"=$product;"articleName"=$articleName;"fixedBuildNumber"=$fixedBuildNumber;"severity"=$severity;"impact"=$impact;"baseScore"=$baseScore;"cveNumber"=$cveNumber;"releaseDate"=$releaseDate}}
    }
    while ($MSRC_JSON.'@odata.nextLink'.length) {
      $MSRC_JSON = F_UrlRequest -Msrc_api $MSRC_JSON.'@odata.nextLink'
      $MSRC_JSON.value | % { 
        $id = $_.id;
        $product = $_.product;
        $articleName = $_.kbArticles.articleName | Get-Unique;
        $fixedBuildNumber = $_.kbArticles.fixedBuildNumber | Get-Unique;
        $severity = $_.severity;
        $impact = $_.impact;
        $baseScore = $_.baseScore;
        $cveNumber = $_.cveNumber | Get-Unique;
        $releaseDate = $_.releaseDate
        $SysWSUSList += @{"$($id)"=@{"product"=$product;"articleName"=$articleName;"fixedBuildNumber"=$fixedBuildNumber;"severity"=$severity;"impact"=$impact;"baseScore"=$baseScore;"cveNumber"=$cveNumber;"releaseDate"=$releaseDate }}
      }
    }
    Write-Host "[-] 已從 Microsoft 安全回應中心獲取更新 $($MSRC_JSON.'@odata.count') 條補丁資訊!" -ForegroundColor Green
    Write-Host "[-] 正在將獲取的更新 $($MSRC_JSON.'@odata.count') 條補丁資訊寫入到本地 WSUSList.json 檔案之中!" -ForegroundColor Green
    $SysWSUSList | ConvertTo-Json | Out-File WSUSList.json -Encoding utf8
    $SysWSUSListId = $SysWSUSList.keys
    $SysWSUSList.keys | ConvertTo-Json | Out-File WSUSListId.json -Encoding utf8
  } else {
    # 從本地讀取JSON檔案存盤的補丁資訊,
    if (Test-Path -Path .\WSUSList.json) {
      $SysWSUSList = Get-Content -Raw -Encoding UTF8 .\WSUSList.json | ConvertFrom-Json
      $SysWSUSListId  = Get-Content -Raw -Encoding UTF8 .\WSUSListId.json | ConvertFrom-Json
      Write-Host "[-] 已從本地 WSUSList.json 檔案獲得 $($SysWSUSListId.count) 條補丁資訊!" -ForegroundColor Green
    } else {
      Write-Host "[-] 本地未能找到存放補丁資訊的 WSUSList.json 檔案! 請采用 -Update True 標記從Microsoft 安全回應中心獲取更新" -ForegroundColor Red
      break
      exit
    }
  }
 
  # 獲取當前系統版本可用的補丁串列
  $AvailableWSUSListId = @() 
  if ($SysInfo.ProductType -eq "Client") {
    Write-Host "[-] Desktop Client" -ForegroundColor Gray
    foreach ($KeyName in $SysWSUSListId) {
      if(($SysWSUSList."$KeyName".product -match $SysInfo.ProductName) -and ($SysWSUSList."$KeyName".product -match $SysInfo.WindowsVersion) -and ($SysWSUSList."$KeyName".product -match ($SysInfo.CsSystemType -split " ")[0])) {
        if (($SysWSUSList."$KeyName".fixedBuildNumber -match $SysInfo.OsVersion) -or ($SysWSUSList."$KeyName".fixedBuildNumber.length -eq 0 )) {
          $AvailableWSUSList."$KeyName" = $SysWSUSList."$KeyName"
          $AvailableWSUSListId += "$KeyName"
        }
      }
    }
  } else {
    Write-Host "[-] Windows Server" -ForegroundColor Gray
    foreach ($KeyName in $SysWSUSListId) {
      if(($SysWSUSList."$KeyName".product -match $SysInfo.ProductName) -and ($SysWSUSList."$KeyName".product -match $SysInfo.ProductName)) {
        $AvailableWSUSList."$KeyName" = $SysWSUSList."$KeyName"
        $AvailableWSUSListId += "$KeyName"
      }
    }
  }
  Write-Host $SysInfo.ProductName $SysInfo.WindowsVersion ($SysInfo.CsSystemType -split " ")[0] $SysInfo.OsVersion
  Write-Host "[-] 已從梳理出適用于當前 $($SysInfo.ProductType) 系統版本的 $($AvailableWSUSList.count) 條補丁資訊!`n" -ForegroundColor Green

  # 已安裝的補丁
  $InstallWSUSList = @{}
  $msg = @()
  foreach ($id in $AvailableWSUSListId) {
    if( $SysInfo.'Hotfix(s)' -match $AvailableWSUSList."$id".articleName ) {
      $InstallWSUSList."$id" = $SysWSUSList."$id"
      $msg += "[+]" + $SysWSUSList."$id".product + $SysWSUSList."$id".fixedBuildNumber + " " +  $SysWSUSList."$id".articleName + "(" + $SysWSUSList."$id".cveNumber   + ")" + $SysWSUSList."$id".severity  + $SysWSUSList."$id".baseScore + "`n"
    } 
  }
  Write-Host "[-] $($SysInfo.'Hotfix(s)') ,共 $($AvailableWSUSList.count) 條漏洞補丁資訊!`n$($msg)" -ForegroundColor Green

  # 未安裝的補丁
  $NotInstallWSUSList = @{}
  $msg = @()
  foreach ($id in $AvailableWSUSListId) {
    if(-not($InstallWSUSList."$id")) {
     $NotInstallWSUSList."$id" = $SysWSUSList."$id"
     $msg += "[+]" + $SysWSUSList."$id".product + $SysWSUSList."$id".fixedBuildNumber + " " + $SysWSUSList."$id".articleName + "(" + $SysWSUSList."$id".cveNumber + ")" + $SysWSUSList."$id".severity + $SysWSUSList."$id".baseScore + "`n"
    }
  }
  Write-Host "[-] 未安裝 $($NotInstallWSUSList.count) 條漏洞補丁資訊,共 $($AvailableWSUSList.count) 條漏洞補丁資訊!`n$($msg)" -ForegroundColor red
}

#
# * 雜類檢測函式 * 
#
$OtherCheck = @{}
function F_OtherCheckPolicy {
  # - 當前系統已安裝的軟體
  $Product = Get-WmiObject -Class Win32_Product | Select-Object -Property Name,Version,IdentifyingNumber | Sort-Object Name | Out-String
  $OtherCheck += @{"Product"="$($Product)"}

  # - 當前系統最近訪問檔案或者目錄
  $Recent = (Get-ChildItem ~\AppData\Roaming\Microsoft\Windows\Recent).Name
  $OtherCheck += @{"Recent"="$($Recent)"}
  return $OtherCheck
}


function Main() {
<#
.SYNOPSIS
main 函式程式執行入口
.DESCRIPTION
呼叫上述撰寫的相關檢測腳本
.EXAMPLE
main
#>

$ScanStartTime = Get-date -Format 'yyyy-M-d H:m:s'
F_Logging -Level Info -Msg "#################################################################################"
F_Logging -Level Info -Msg "- @Desc: Windows Server 安全配置策略基線檢測腳本  [將會在Github上持續更新-star]"
F_Logging -Level Info -Msg "- @Author: WeiyiGeek"
F_Logging -Level Info -Msg "- @Blog: https://www.weiyigeek.top"
F_Logging -Level Info -Msg "- @Github: https://github.com/WeiyiGeek/SecOpsDev/tree/master/OS-作業系統/Windows"
F_Logging -Level Info -Msg "#################################################################################`n"

F_Logging -Level Info -Msg "[*] Windows Server 安全配置策略基線檢測腳本已啟動."
F_Logging -Level Info -Msg "[*] 腳本執行: $($Executor), 是否在線拉取微軟安全中心的服務器安全補丁串列資訊: $($MsrcUpdate)`n"
# 1.判斷當前運行的powershell終端是否管理員執行
F_Logging -Level Info -Msg "[-] 正在檢測當前運行的PowerShell終端是否管理員權限...`n"
$flag = F_IsCurrentUserAdmin
if (!($flag)) {
  F_Logging -Level Error -Msg "[*] 腳本執行發生錯誤,請使用管理員權限運行該腳本..例如: Start-Process powershell -Verb runAs...."
  F_Logging -Level Warning -Msg "[*] 正在退出執行該腳本......"
  return
}
F_Logging -Level Info -Msg "[*] PowerShell 管理員權限檢查通過...`n"

# 2.當前系統策略組態檔匯出 (注意必須系統管理員權限運行) 
F_Logging -Level Info -Msg "[-] 正在匯出當前系統策略組態檔 config.cfg......`n"
secedit /export /cfg config.cfg /quiet
start-sleep 3
if ( -not(Test-Path -Path config.cfg)) {
  F_Logging -Level Error -Msg "[*] 當前系統策略組態檔 config.cfg 不存在,請檢查......`n"
  F_Logging -Level Warning -Msg "[*] 正在退出執行該腳本......"
  return
} else { 
  Copy-Item -Path config.cfg -Destination config.cfg.bak -Force
}
$Config = Get-Content -path config.cfg

# 3.系統相關資訊以及系統安全組策略檢測
F_Logging -Level Info -Msg "[-] 當前系統資訊一覽"
$SysInfo = F_SysInfo
$SysInfo

F_Logging -Level Info -Msg "[-] 當前系統網路資訊一覽"
$SysNetAdapter = F_SysNetAdapter
$SysNetAdapter

F_Logging -Level Info -Msg "[-] 當前系統磁盤資訊一覽"
$SysDisk = F_SysDisk
$SysDisk

F_Logging -Level Info -Msg "[-] 當前系統賬戶資訊一覽"
$SysAccount = F_SysAccount
$SysAccount

F_Logging -Level Info -Msg "[-] 當前系統安全策略資訊一覽"
$SysAccountPolicy.CheckResults = F_SysAccountPolicy
$SysEventAuditPolicy.CheckResults = F_SysEventAuditPolicy
$SysUserPrivilegePolicy.CheckResults = F_SysUserPrivilegePolicy
$SysSecurityOptionPolicy.CheckResults = F_SysSecurityOptionPolicy
$SysRegistryPolicy.CheckResults = F_SysRegistryPolicy
$SysProcessServicePolicy.CheckResults = F_SysProcessServicePolicy

F_Logging -Level Info -Msg "[-] 當前系統雜類資訊一覽"
$OtherCheck = F_OtherCheckPolicy
$OtherCheck.Values

F_Logging -Level Info -Msg "[-] 當前系統安全補丁情況資訊一覽"
F_SysSecurityPolicy

# 4.程式執行完畢
$ScanEndTime = Get-date -Format 'yyyy-M-d H:m:s'
F_Logging -Level Info -Msg "- Windows Server 安全配置策略基線檢測腳本已執行完畢......`n開始時間:${ScanStartTime}`n完成時間: ${ScanEndTime}"
}
Main

Windows Server 安全配置策略基線加固腳本
Link: https://github.com/WeiyiGeek/SecOpsDev/blob/master/OS-作業系統/Windows/WindowsSecurityReinforce.ps1
至此,Windows 安全基線配置核查和安全加固腳本分享完畢,

文章來源:
原創首發平臺地址: https://www.anquanke.com/post/id/259603

博客地址: Linux與Windows服務器作業系統安全防御實踐指南 ( https://blog.weiyigeek.top/2020/10-13-585.html )

文章書寫不易,如果您覺得這篇文章還不錯的,請給這篇專欄 【點個贊、投個幣、收個藏、關個注,轉個發】(人間五大情),這將對我的肯定,謝謝!,

本文章來源 我的Blog站點 或 WeiyiGeek 公眾賬號 以及 我的BiliBili專欄 (技術交流、友鏈交換請郵我喲),謝謝支持!(?′?‵?) ?
歡迎各位志同道合的朋友一起學習交流,如文章有誤請留下您寶貴的知識建議,通過郵箱【master#weiyigeek.top】聯系我喲!

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/457960.html

標籤:其他

上一篇:無碼間串擾——部分回應模擬實驗

下一篇:bp驗證碼爆破插件二改

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 網閘典型架構簡述

    網閘架構一般分為兩種:三主機的三系統架構網閘和雙主機的2+1架構網閘。 三主機架構分別為內端機、外端機和仲裁機。三機無論從軟體和硬體上均各自獨立。首先從硬體上來看,三機都用各自獨立的主板、記憶體及存盤設備。從軟體上來看,三機有各自獨立的作業系統。這樣能達到完全的三機獨立。對于“2+1”系統,“2”分為 ......

    uj5u.com 2020-09-10 02:00:44 more
  • 如何從xshell上傳檔案到centos linux虛擬機里

    如何從xshell上傳檔案到centos linux虛擬機里及:虛擬機CentOs下執行 yum -y install lrzsz命令,出現錯誤:鏡像無法找到軟體包 前言 一、安裝lrzsz步驟 二、上傳檔案 三、遇到的問題及解決方案 總結 前言 提示:其實很簡單,往虛擬機上安裝一個上傳檔案的工具 ......

    uj5u.com 2020-09-10 02:00:47 more
  • 一、SQLMAP入門

    一、SQLMAP入門 1、判斷是否存在注入 sqlmap.py -u 網址/id=1 id=1不可缺少。當注入點后面的引數大于兩個時。需要加雙引號, sqlmap.py -u "網址/id=1&uid=1" 2、判斷文本中的請求是否存在注入 從文本中加載http請求,SQLMAP可以從一個文本檔案中 ......

    uj5u.com 2020-09-10 02:00:50 more
  • Metasploit 簡單使用教程

    metasploit 簡單使用教程 浩先生, 2020-08-28 16:18:25 分類專欄: kail 網路安全 linux 文章標簽: linux資訊安全 編輯 著作權 metasploit 使用教程 前言 一、Metasploit是什么? 二、準備作業 三、具體步驟 前言 Msfconsole ......

    uj5u.com 2020-09-10 02:00:53 more
  • 游戲逆向之驅動層與用戶層通訊

    驅動層代碼: #pragma once #include <ntifs.h> #define add_code CTL_CODE(FILE_DEVICE_UNKNOWN,0x800,METHOD_BUFFERED,FILE_ANY_ACCESS) /* 更多游戲逆向視頻www.yxfzedu.com ......

    uj5u.com 2020-09-10 02:00:56 more
  • 北斗電力時鐘(北斗授時服務器)讓網路資料更精準

    北斗電力時鐘(北斗授時服務器)讓網路資料更精準 北斗電力時鐘(北斗授時服務器)讓網路資料更精準 京準電子科技官微——ahjzsz 近幾年,資訊技術的得了快速發展,互聯網在逐漸普及,其在人們生活和生產中都得到了廣泛應用,并且取得了不錯的應用效果。計算機網路資訊在電力系統中的應用,一方面使電力系統的運行 ......

    uj5u.com 2020-09-10 02:01:03 more
  • 【CTF】CTFHub 技能樹 彩蛋 writeup

    ?碎碎念 CTFHub:https://www.ctfhub.com/ 筆者入門CTF時時剛開始刷的是bugku的舊平臺,后來才有了CTFHub。 感覺不論是網頁UI設計,還是題目質量,賽事跟蹤,工具軟體都做得很不錯。 而且因為獨到的金幣制度的確讓人有一種想去刷題賺金幣的感覺。 個人還是非常喜歡這個 ......

    uj5u.com 2020-09-10 02:04:05 more
  • 02windows基礎操作

    我學到了一下幾點 Windows系統目錄結構與滲透的作用 常見Windows的服務詳解 Windows埠詳解 常用的Windows注冊表詳解 hacker DOS命令詳解(net user / type /md /rd/ dir /cd /net use copy、批處理 等) 利用dos命令制作 ......

    uj5u.com 2020-09-10 02:04:18 more
  • 03.Linux基礎操作

    我學到了以下幾點 01Linux系統介紹02系統安裝,密碼啊破解03Linux常用命令04LAMP 01LINUX windows: win03 8 12 16 19 配置不繁瑣 Linux:redhat,centos(紅帽社區版),Ubuntu server,suse unix:金融機構,證券,銀 ......

    uj5u.com 2020-09-10 02:04:30 more
  • 05HTML

    01HTML介紹 02頭部標簽講解03基礎標簽講解04表單標簽講解 HTML前段語言 js1.了解代碼2.根據代碼 懂得挖掘漏洞 (POST注入/XSS漏洞上傳)3.黑帽seo 白帽seo 客戶網站被黑帽植入劫持代碼如何處理4.熟悉html表單 <html><head><title>TDK標題,描述 ......

    uj5u.com 2020-09-10 02:04:36 more
最新发布
  • 2023年最新微信小程式抓包教程

    01 開門見山 隔一個月發一篇文章,不過分。 首先回顧一下《微信系結手機號資料庫被脫庫事件》,我也是第一時間得知了這個訊息,然后跟蹤了整件事情的經過。下面是這起事件的相關截圖以及近日流出的一萬條資料樣本: 個人認為這件事也沒什么,還不如關注一下之前45億快遞資料查詢渠道疑似在近日復活的訊息。 訊息是 ......

    uj5u.com 2023-04-20 08:48:24 more
  • web3 產品介紹:metamask 錢包 使用最多的瀏覽器插件錢包

    Metamask錢包是一種基于區塊鏈技術的數字貨幣錢包,它允許用戶在安全、便捷的環境下管理自己的加密資產。Metamask錢包是以太坊生態系統中最流行的錢包之一,它具有易于使用、安全性高和功能強大等優點。 本文將詳細介紹Metamask錢包的功能和使用方法。 一、 Metamask錢包的功能 數字資 ......

    uj5u.com 2023-04-20 08:47:46 more
  • vulnhub_Earth

    前言 靶機地址->>>vulnhub_Earth 攻擊機ip:192.168.20.121 靶機ip:192.168.20.122 參考文章 https://www.cnblogs.com/Jing-X/archive/2022/04/03/16097695.html https://www.cnb ......

    uj5u.com 2023-04-20 07:46:20 more
  • 從4k到42k,軟體測驗工程師的漲薪史,給我看哭了

    清明節一過,盲猜大家已經無心上班,在數著日子準備過五一,但一想到銀行卡里的余額……瞬間心情就不美麗了。最近,2023年高校畢業生就業調查顯示,本科畢業月平均起薪為5825元。調查一出,便有很多同學表示自己又被平均了。看著這一資料,不免讓人想到前不久中國青年報的一項調查:近六成大學生認為畢業10年內會 ......

    uj5u.com 2023-04-20 07:44:00 more
  • 最新版本 Stable Diffusion 開源 AI 繪畫工具之中文自動提詞篇

    🎈 標簽生成器 由于輸入正向提示詞 prompt 和反向提示詞 negative prompt 都是使用英文,所以對學習母語的我們非常不友好 使用網址:https://tinygeeker.github.io/p/ai-prompt-generator 這個網址是為了讓大家在使用 AI 繪畫的時候 ......

    uj5u.com 2023-04-20 07:43:36 more
  • 漫談前端自動化測驗演進之路及測驗工具分析

    隨著前端技術的不斷發展和應用程式的日益復雜,前端自動化測驗也在不斷演進。隨著 Web 應用程式變得越來越復雜,自動化測驗的需求也越來越高。如今,自動化測驗已經成為 Web 應用程式開發程序中不可或缺的一部分,它們可以幫助開發人員更快地發現和修復錯誤,提高應用程式的性能和可靠性。 ......

    uj5u.com 2023-04-20 07:43:16 more
  • CANN開發實踐:4個DVPP記憶體問題的典型案例解讀

    摘要:由于DVPP媒體資料處理功能對存放輸入、輸出資料的記憶體有更高的要求(例如,記憶體首地址128位元組對齊),因此需呼叫專用的記憶體申請介面,那么本期就分享幾個關于DVPP記憶體問題的典型案例,并給出原因分析及解決方法。 本文分享自華為云社區《FAQ_DVPP記憶體問題案例》,作者:昇騰CANN。 DVPP ......

    uj5u.com 2023-04-20 07:43:03 more
  • msf學習

    msf學習 以kali自帶的msf為例 一、msf核心模塊與功能 msf模塊都放在/usr/share/metasploit-framework/modules目錄下 1、auxiliary 輔助模塊,輔助滲透(埠掃描、登錄密碼爆破、漏洞驗證等) 2、encoders 編碼器模塊,主要包含各種編碼 ......

    uj5u.com 2023-04-20 07:42:59 more
  • Halcon軟體安裝與界面簡介

    1. 下載Halcon17版本到到本地 2. 雙擊安裝包后 3. 步驟如下 1.2 Halcon軟體安裝 界面分為四大塊 1. Halcon的五個助手 1) 影像采集助手:與相機連接,設定相機引數,采集影像 2) 標定助手:九點標定或是其它的標定,生成標定檔案及內參外參,可以將像素單位轉換為長度單位 ......

    uj5u.com 2023-04-20 07:42:17 more
  • 在MacOS下使用Unity3D開發游戲

    第一次發博客,先發一下我的游戲開發環境吧。 去年2月份買了一臺MacBookPro2021 M1pro(以下簡稱mbp),這一年來一直在用mbp開發游戲。我大致分享一下我的開發工具以及使用體驗。 1、Unity 官網鏈接: https://unity.cn/releases 我一般使用的Apple ......

    uj5u.com 2023-04-20 07:40:19 more