采用PowerShell和Windows防火墙规则的RDP暴力保护

时间:2020-01-09 10:46:13  来源:igfitidea点击:

我有一个想法,写一个简单的PowerShell脚本,在Windows防火墙中自动阻止(黑名单)IP地址,在这些地址上检测到RDP暴力尝试或者连续的RDP攻击。其思想如下:PowerShell脚本分析系统事件日志,如果在过去三个小时内从同一IP地址通过RDP进行身份验证的尝试失败次数超过5次,则该IP地址将自动添加到Windows防火墙阻止规则中。

所以,有一个小型的办公网络。要访问它,RDP端口通过NAT通过运行Linux的Internet网关转发到一台办公室计算机(TCP 15221从外部应答,默认的RDP端口3389在内部转发)。由于尝试通过RDP在计算机上进行身份验证失败,因此,有时域密码策略会锁定已知用户帐户。我们的任务是自动阻止用于暴力攻击我们的RDP服务器的IP地址。

首先,在计算机上创建防火墙规则,以阻止来自指定IP地址的入站RDP连接:

New-NetFirewallRule -DisplayName "BlockRDPBruteForce" –RemoteAddress 1.1.1.1 -Direction Inbound -Protocol TCP –LocalPort 3389 -Action Block

我们将进一步将检测到RDP暴力尝试的IP地址添加到这个规则防火墙中。

我们可以编写一个添加的允许规则,这样PowerShell脚本就不会阻止我们需要的IP地址或者子网。

然后,我们必须从Windows事件日志中收集IP地址列表,在过去3小时内,在这些地址上检测到5次以上的失败身份验证尝试。要执行此操作,请在安全日志中找到事件ID为 4625(访问尝试失败- 账户登录失败登录类型=3,请查看文章RDP事件日志取证)。在我们找到的事件中,找到尝试连接的用户的IP地址,并确保它在事件日志中出现了5次以上。

我使用以下PowerShell代码从过去3小时的事件列表中选择攻击者的IP地址(我们可以更改时间段):

$Last_n_Hours = [DateTime]::Now.AddHours(-3)
$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 5} | Select -property Name

要显示找到的IP地址列表,请使用:

$getip

现在将所有找到的攻击者IP地址添加到先前创建的防火墙规则块rdpbruteforce中。为了管理Windows防火墙,我们将使用内置的PowerShell模块NetSecurity 首先,获取当前被阻止的IP地址列表,并向其中添加新地址。

$log = "C:\ps\rdp_blocked_ip.txt"
$current_ips = (Get-NetFirewallRule -DisplayName "BlockRDPBruteForce" | Get-NetFirewallAddressFilter ).RemoteAddress
foreach ($ip in $getip)
{
$current_ips += $ip.name
(Get-Date).ToString() + ' ' + $ip.name + ' The IP address has been blocked due to ' + ($badRDPlogons | where {$_.IpAddress -eq $ip.name}).count + ' attempts for 2 hours'>> $log # writing the IP blocking event to the log file
}
Set-NetFirewallRule -DisplayName "BlockRDPBruteForce" -RemoteAddress $current_ips

确保已将新IP地址添加到Windows Defender防火墙中的阻止规则中。

现在我们只需将这个PowerShell代码复制到文件中

c:\ps\block_rdp_attack.ps1

例如,将其添加到任务调度程序中,使其每2小时运行一次。

我们可以使用PowerShell脚本或者手动创建计划程序任务:

$repeat = (New-TimeSpan -Hours 2)
$duration = ([timeSpan]::maxvalue)
$Trigger= New-ScheduledTaskTrigger -Once -At (Get-Date).Date -RepetitionInterval $repeat -RepetitionDuration $duration
$User= "NT AUTHORITY\SYSTEM"
$Action= New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "C:\PS\block_rdp_attack.ps1"
Register-ScheduledTask -TaskName "BlockRDPBruteForce_PS" -Trigger $Trigger -User $User -Action $Action -RunLevel Highest –Force

或者,如果日志中出现EventID 4625(检查blogpost Windows事件触发器),则可以运行PowerShell脚本,以便更快地响应RDP暴力攻击。

你可以根据需要修改RDP攻击。