This repository has been archived by the owner on Feb 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathUpdate-FirewallRule.ps1
74 lines (51 loc) · 1.7 KB
/
Update-FirewallRule.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#Requires -RunAsAdministrator
[CmdletBinding()]
param(
[int]$LastHours = 6
)
$ErrorActionPreference = 'Stop'
$blacklistFile = Join-Path $PSScriptRoot 'blacklist.txt'
$whitelistFile = Join-Path $PSScriptRoot 'whitelist.txt'
function Get-FailedIps {
# Get IP addresses with more than 10 failed logon attempts
$ExtraParams = @{}
if ($LastHours -gt 0) {
$ExtraParams = @{LastHours = $LastHours}
}
$getFailedLogons = Join-Path $PSScriptRoot 'Get-FailedLogons.ps1'
$failedIps = @()
& $getFailedLogons @ExtraParams |
ForEach-Object {
$failedIps += $_.Name
}
$failedIps
}
function Get-BlockedIps {
# Get blacklisted IPs (already blocked)
Get-Content -Path $blacklistFile -Encoding Ascii -ErrorAction SilentlyContinue
}
function Get-AllowedIps {
# Get whitelisted IPs
Get-Content -Path $whitelistFile -Encoding Ascii -ErrorAction SilentlyContinue
}
#
# Main
#
$failedIps = Get-FailedIps
$blockedIps = Get-BlockedIps
$allIps = [array]$failedIps + [array]$blockedIps | Select-Object -Unique | Sort-Object
# Update blacklist
$allIps | Out-File -FilePath $blacklistFile -Encoding ascii
# Remove allowed IPs
$allowedIps = Get-AllowedIps
$allIps = $allIps | Where-Object { $_ -notin $allowedIps }
# Update firewall
$ruleName = 'PSFail2Ban-Block-Failed-Logons'
$ruleDisplayName = 'PSFail2Ban: Blocks IP addresses from failed logons'
if (Get-NetFirewallRule -Name $ruleName -ErrorAction SilentlyContinue) {
# Update rule
Set-NetFirewallRule -Name $ruleName -RemoteAddress $allIps
} else {
# Create rule
New-NetFirewallRule -Name $ruleName -DisplayName $ruleDisplayName -Direction Inbound -Action Block -RemoteAddress $allIps
}