Skip to content

Instantly share code, notes, and snippets.

@mguinness
Created December 24, 2020 23:06
Show Gist options
  • Save mguinness/e8e1cbf99d2596f37d7c7b9909ca88f0 to your computer and use it in GitHub Desktop.
Save mguinness/e8e1cbf99d2596f37d7c7b9909ca88f0 to your computer and use it in GitHub Desktop.
Auto block IPv4 addresses in IIS from suspect log entries
<#
Uses Microsoft Log Parser (https://en.wikipedia.org/wiki/Logparser) to parse IIS logs for given criteria and both auto
blocks the IP in IIS (under IP Address and Domain Restrictions) and also reports to AbuseIPDB (IP Address Blacklist).
Modify site, dir & query variables to suit your specific site requirements. Run script in Task Scheduler every 15 mins.
Log Parser Component Object Model (COM) must be registered in Windows and script should be run with suitable permissions.
#>
$utc = (Get-Date).ToUniversalTime()
$mins = -15
$site = "Default Web Site"
#If run at midnight UTC then all IP restrictions are cleared
if ($utc.Hour -eq 0 -and $utc.Minute -eq 0)
{
Clear-WebConfiguration -Location $site -Filter /system.webServer/security/ipSecurity
}
else
{
$existing = Get-WebConfiguration -Location $site -Filter /system.webServer/security/ipSecurity | Select -Expand collection | Select -ExpandProperty ipAddress
}
$dir = "C:\inetpub\logs\LogFiles\W3SVC1"
$file = "u_ex{0:yyMMdd}.log" -f $utc
$path = Join-Path $dir $file
if (Test-Path $path)
{
$logParser = New-Object -com MSUtil.LogQuery
$inputFormat = New-Object -com MSUtil.LogQuery.IISW3CInputFormat
$time = "{0:HH:mm:ss}" -f $utc.AddMinutes($mins)
$query = "SELECT c-ip, MAX(STRCAT(cs-uri-stem, REPLACE_IF_NOT_NULL(cs-uri-query, STRCAT('?', cs-uri-query)))) AS uri
FROM $path WHERE time >= '$time' AND c-ip NOT LIKE '%::%' AND sc-status = 404
AND (cs-uri-stem = '/etc/passwd' OR cs-uri-stem = '/remote/login' OR cs-uri-stem = '/user/login')
GROUP BY c-ip"
$recordSet = $logParser.Execute($query, $inputFormat)
for(; !$recordSet.atEnd(); $recordSet.moveNext())
{
$record = $recordSet.getRecord()
$ip = $record.getValue("c-ip")
if ($existing -eq $null -or !$existing.Contains($ip))
{
"Blocking $ip"
Add-WebConfiguration -Location $site -Filter /system.webServer/security/ipSecurity -Value @{ipAddress="$ip"; allowed="false"}
$ip >> blocked.log
$body = @{"ip"=$ip; "categories"=21; "comment"="Automatic report - Vulnerability scan`n$($record.getValue("uri"))"}
$headers = @{"Accept"="application/json"; "Key"="Your Key Here"} #Use key from https://www.abuseipdb.com/account/api
$response = Invoke-RestMethod -Uri https://api.abuseipdb.com/api/v2/report -Headers $headers -Body $body -Method POST
}
}
$recordSet.Close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment