function Send-Slack-Alert { param ( $message ) $uriSlack = "https://hooks.slack.com/services/<>" $body = ConvertTo-Json @{ text = $message } Invoke-RestMethod -uri $uriSlack -Method Post -body $body -ContentType 'application/json' | Out-Null } # Create 'RDP Block' firewall rule if it does not exist if (-Not (Get-NetFirewallRule -DisplayName "RDP Block" -ErrorAction SilentlyContinue)) { New-NetFirewallRule -DisplayName 'RDP Block' ` -Description "Rule to dynamically block access to RDP service by external IPs that fail authentication" ` -Profile @('Domain', 'Private', 'Public') ` -Enabled True -Direction Inbound -Action Block ` -Protocol TCP -Service TermService -RemoteAddress 1.1.1.1 | Out-Null } # Track if block IP was added by this script $block = $false # Retrieve current Local and Remote Blocked IPs within the 'RDP Block' firewall rule $rule = Get-NetFirewallRule -DisplayName "RDP Block" | Get-NetFirewallAddressFilter # Traverse each failed login log generated within the past 5 minutes ForEach ($event in Get-WinEvent -FilterHashtable @{logname='security'; id=4625; starttime=(Get-Date).AddMinutes(-5)} -ErrorAction SilentlyContinue) { # If logon attempt is a network event if ('3' -eq $event.Properties[10].Value) { # Get user ID within failed logon event log $user = $event.Properties[5].Value # Get source IP address within failed logon event log $ip = $event.Properties[19].Value # If the failed login is not from internal network if ( -Not $ip.Contains("192.168") -And -Not $ip.Contains("127.0.0") ) { # Set $block to TRUE to signify a blocked IP was added to firewall rule $block = $true # If external IP does not already exist in the firewall rule if ($null -eq (Get-NetFirewallRule -displayname "RDP Block" | Get-NetFirewallAddressFilter | ` Where-Object -FilterScript { $_.RemoteAddress -eq $ip })) { # Read existing Blocked Remote IPs into an array $ips = @($rule.RemoteAddress) # Add the external IP to the Blocked Remote IPs array $ips += "$ip" # Add the updated Blocked Remote IPs (array) to the firewall rule Set-NetFirewallRule -DisplayName "RDP Block" -RemoteAddress $ips # Set $block to TRUE to signify a blocked IP was added to firewall rule $block = $true # Create an alert message to send via Slack $alert = "Failed External Logon Attempt`nBlocked:" + $ip + "`nUser:" + $user # Send the Slack alert message Send-Slack-Alert $alert } } } } # Initialize the Blocked Remote IPs (list) if no new IPs were added and the list is greater than one; at least one IP must exist by default (1.1.1.1) if (($block -eq $false) -And ($rule.RemoteAddress.Count -gt 1)) { Set-NetFirewallRule -DisplayName "RDP Block" -RemoteAddress "1.1.1.1" }