在ISO27001的附錄控制項要求,系統日誌的保存、異常監控及審查一直是一個重要議題:
以下以Windows O.S.為例,在不引進第三方工具的方法上,如何簡單地自動化實施自動化監控機制:只要偵測到 Windows 有登入失敗事件(Event ID 4625),系統就會自動寄出警告信。
建立 PowerShell 腳本:負責寄信。
在「事件檢視器」中建立觸發器:只要出現 4625,就自動執行此腳本。
# 檔名:C:\Scripts\SendFailedLoginAlert.ps1
$From = "syslog@company.com"
$To = "admin@company.com"
$Subject = "Windows Log Alert: Failed login detected on $(hostname)"
$SMTPServer = "smtp.company.com"
# 取得最新登入失敗事件的摘要內容
$Event = Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4625} -MaxEvents 1
$Body = "A failed login attempt was detected.`n`n" +
"Computer: $(hostname)`n" +
"Time: $($Event.TimeCreated)`n" +
"Account: $($Event.Properties[5].Value)`n" +
"IP Address: $($Event.Properties[18].Value)`n"
# 寄送通知郵件
Send-MailMessage -From $From -To $To -Subject $Subject -Body $Body -SmtpServer $SMTPServer
C:\Scripts\SendFailedLoginAlert.ps1
如果沒有這個資料夾,請先建立。
Set-ExecutionPolicy RemoteSigned
taskschd.msc
開啟「工作排程器 (Task Scheduler)」。
在右側選「建立工作 (Create Task...)」(不是基本工作)。
一般頁籤 (General):
觸發條件 (Triggers):
在事件發生時 (On an event)
powershell.exe
-ExecutionPolicy Bypass -File "C:\Scripts\SendFailedLoginAlert.ps1"
Windows Log Alert: Failed login detected on COMPUTERNAME
的郵件。
可改成這個版本(支援 TLS 與登入):
$Credential = New-Object System.Management.Automation.PSCredential("syslog@company.com", (ConvertTo-SecureString "yourpassword" -AsPlainText -Force))
Send-MailMessage -From $From -To $To -Subject $Subject -Body $Body `
-SmtpServer "smtp.company.com" -UseSsl -Port 587 -Credential $Credential
若你擔心有惡意攻擊造成短時間大量登入失敗事件,可在腳本中加入時間檢查機制:
# 僅在過去5分鐘內未寄過信才寄送
$LogFile = "C:\Scripts\SendFailedLoginAlert.log"
$Now = Get-Date
if (Test-Path $LogFile) {
$LastRun = Get-Content $LogFile | Get-Date
if (($Now - $LastRun).TotalMinutes -lt 5) { exit } # 5分鐘內不再寄信
}
$Now.ToString() | Out-File $LogFile