每 60 秒检测 ID4625 日志攻击 IP ,超过 3 次失败,添加到系统防火墙中禁止访问。并实现白名单、控制台输出登录失败 IP 及登录成功 IP
Write-Host -ForegroundColor Green "========================================================================"
Write-Host -ForegroundColor Cyan " RDP login failure monitoring script has been started"
" This script checks for RDP login failures every minute and blocks IP that have failed more than 3 times."
Write-Host -ForegroundColor Green "========================================================================"
$ErrorActionPreference = "SilentlyContinue"
$LogName = "Security"
$EventID = 4625,4624
$TimeSleepSeconds = 60
$FailedAttempsLimit = 3
$WhiteListIPs = @("127.0.0.1", "172.16.0.110")
$FirewallRuleName = "BlockedRDPAttempt_IPs"
$newBlockIPs = @()
$FailedIPs = @{}
$startTime = (Get-Date).Add(-(New-TimeSpan -Hours 1))
$endTime = Get-Date
while ($true) {
$TimeSpan = $endTime - $startTime
$startTime = Get-Date
$Events = Get-WinEvent -FilterHashtable @{
LogName = $LogName
ID = $EventID
StartTime = (Get-Date).Add(-$TimeSpan)
}
foreach ($event in $Events) {
$IpAddress = $event.Properties[19].Value
if ((![string]::IsNullOrEmpty($IpAddress)) -and ($IpAddress -ne "-") -and ($IpAddress -ne "0")) {
$FailedIPs[$IpAddress] = $FailedIPs[$IpAddress] + 1
Write-Host -ForegroundColor Yellow "$(Get-Date) Detected failed login from: $IpAddress at $($event.TimeCreated)"
}
}
foreach ($event in $Events) {
$SuccessIpAddress = $event.Properties[18].Value
if ((![string]::IsNullOrEmpty($SuccessIpAddress)) -and ($SuccessIpAddress -ne "-") -and ($SuccessIpAddress -ne "0") -and ($event.Properties[8].Value -eq 3)) {
Write-Host -ForegroundColor Green "$(Get-Date) Detected successful login from: $SuccessIpAddress at $($event.TimeCreated)"
}
}
$BlockedIPs = $FailedIPs.Keys | Where-Object { $FailedIPs[$_] -ge $FailedAttempsLimit }
$BlockedIPs = $BlockedIPs | Where-Object { $_ -notin $WhiteListIPs }
if (Compare-Object -ReferenceObject $BlockedIPs -DifferenceObject $newBlockIPs -PassThru) {
foreach ($ip in $BlockedIPs) {
$ruleExists = Get-NetFirewallRule -DisplayName $FirewallRuleName -ErrorAction SilentlyContinue
if (-not $ruleExists) {
New-NetFirewallRule -DisplayName $FirewallRuleName -Direction Inbound -Action Block -RemoteAddress $ip -Protocol TCP -LocalPort 3389
Write-Host -ForegroundColor Blue "$(Get-Date) Created new Firewall rule for IP: $ip"
} else {
$existingBlockIPs = (Get-NetFirewallRule -DisplayName $FirewallRuleName | Get-NetFirewallAddressFilter).RemoteAddress
$newBlockIPs = @()
$newBlockIPs += $existingBlockIPs
if ($newBlockIPs -notcontains $ip) {
$newBlockIPs += $ip
Write-Host -ForegroundColor Red "$(Get-Date) Detected IP with multiple RDP failures: $ip"
}
Set-NetFirewallRule -DisplayName $FirewallRuleName -RemoteAddress $newBlockIPs
}
}
if (![string]::IsNullOrEmpty($newBlockIPs)) {
Write-Host -ForegroundColor Red "$(Get-Date) Updated Firewall rule to add IP: $newBlockIPs"
}
}
Start-Sleep -Seconds $TimeSleepSeconds
$endTime = Get-Date
}