Could you hire me? Contact me if you like what I’ve done in this article and think I can create value for your company with my skills.

April 7, 2021 / by Zsolt Soczó

RDP Brute Force Protection with PowerShell and Windows Firewall Rules

Az ötlet innen jött. Kicsit átírtam a kódot, mert az eredeti minden egyes kitiltott IP-t egyesével appendelte a log fájlhoz, ami nagyon lassúvá tette, valamint nem kezelte a duplikát bejegyzéseket.

Íme az átírt verzió:

$Last_n_Hours = [DateTime]::Now.AddHours(-24)
$badRDPlogons = Get-EventLog -LogName 'Security' -after $Last_n_Hours -InstanceId 4625 | ?{$_.Message -match 'logon type:\s+(3)\s'} | Select-Object @{n='IpAddress';e={$_.ReplacementStrings[-2]} }
$getip = $badRDPlogons | group-object -property IpAddress | where {$_.Count -gt 10} | Select -property Name

$uniqueIps = @{}

$current_ips = (Get-NetFirewallRule -DisplayName "BlockRDPBruteForce" | Get-NetFirewallAddressFilter ).RemoteAddress

foreach ($ip in $current_ips)
{
    $uniqueIps[$ip] = $true
}

foreach ($ip in $getip)
{
    $uniqueIps[$ip.Name] = $true
}

$finalBlockedIps = $uniqueIps.Keys | Sort-Object

Set-NetFirewallRule -DisplayName "BlockRDPBruteForce" -RemoteAddress $finalBlockedIps

Write-Output "Blocked addresses:"
$finalBlockedIps 

Write-Output "Blocked address count:"
$finalBlockedIps.Count

$log = "C:\ware\secu\rdp_blocked_ip.txt"
$finalBlockedIps | Select-Object {(Get-Date).ToString() + ' ' + $_} | Out-File $log

Itt látható, hogy 1 nap után már 260 címet tiltott ki.

Could you hire me? Contact me if you like what I’ve done in this article and think I can create value for your company with my skills.