├── README.md └── honeyport.ps1 /README.md: -------------------------------------------------------------------------------- 1 | .SYNOPSIS 2 | Block IP Addresses that connect to specified TCP ports. 3 | 4 | .DESCRIPTION 5 | Listens on TCP ports, logging connections and optionally blocking suspicious IPs via Windows Firewall. 6 | Includes detailed logging, proper firewall rule creation verification, and improved error handling. 7 | 8 | .PARAMETER Ports 9 | List of TCP ports to monitor for connections. 10 | 11 | .PARAMETER WhiteList 12 | List of IP Addresses that should not be blocked. 13 | 14 | .PARAMETER Block 15 | If specified, blocks the connecting IP addresses. 16 | 17 | .PARAMETER LogPath 18 | Optional path for logs. Defaults to "C:\HoneyPort_Logs". 19 | 20 | .EXAMPLE 21 | PS C:\> .\honeyport.ps1 -Ports 22,23,1001 -Block -Verbose 22 | -------------------------------------------------------------------------------- /honeyport.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | Block IP Addresses that connect to specified TCP ports. 4 | 5 | .DESCRIPTION 6 | Listens on TCP ports, logging connections and optionally blocking suspicious IPs via Windows Firewall. 7 | Includes detailed logging, proper firewall rule creation verification, and improved error handling. 8 | 9 | .PARAMETER Ports 10 | List of TCP ports to monitor for connections. 11 | 12 | .PARAMETER WhiteList 13 | List of IP Addresses that should not be blocked. 14 | 15 | .PARAMETER Block 16 | If specified, blocks the connecting IP addresses. 17 | 18 | .PARAMETER LogPath 19 | Optional path for logs. Defaults to "C:\HoneyPort_Logs". 20 | 21 | .EXAMPLE 22 | PS C:\> .\honeyport.ps1 -Ports 22,23,1001 -Block -Verbose 23 | #> 24 | 25 | [CmdletBinding()] 26 | param( 27 | [Parameter(Mandatory = $true, ValueFromPipeline = $true)] 28 | [Alias("PortNumber")] 29 | [int32[]]$Ports, 30 | 31 | [string[]]$WhiteList = @(), 32 | 33 | [switch]$Block, 34 | 35 | [string]$LogPath = "C:\HoneyPort_Logs" 36 | ) 37 | 38 | function Show-BlueShellAsciiArt { 39 | Write-Host "`n" 40 | Write-Host " .: " 41 | Write-Host " ....: " 42 | Write-Host " :....:-- " 43 | Write-Host " ::..::-- " 44 | Write-Host " -:::::--== " 45 | Write-Host " ======+++++* " 46 | Write-Host " :.::::: *#######****#####**** " 47 | Write-Host " ::..::::--+****####%%*=++***#######* :: " 48 | Write-Host " -:::.::::--=+******##@##**########%%#=:::- " 49 | Write-Host " -:::::::---=*******%@#*********##%####*-= " 50 | Write-Host " ----------=***++++*%%*++++++=====+++####*+ " 51 | Write-Host " ==-----=+++++++=+*%#+=++-::.....:-*=###-:::.......: " 52 | Write-Host " ....-++===+**+++====-=#%+===-:::..::-==*#+##=:......::== " 53 | Write-Host " :::-+******+++===--=*%%%=--=--:::::-===##**#*-:::::-== " 54 | Write-Host " -++++****++==--+##+-=#*--===-----===+#%#+#**=-==+= " 55 | Write-Host " ............--=#%#+=---*%=-==++==++++*#%%%**####*+= " 56 | Write-Host " .....................:=#**+%*====++++**######%******#=- " 57 | Write-Host "...........................:=+**+++++++******##########+== " 58 | Write-Host ":::::::.........................:=###*******##+**#####*::-= " 59 | Write-Host ":::------::::........................:-=+*##%**###%#+-:::::- " 60 | Write-Host "--===++=*%@#==-::::.........................::::::::::::::-- " 61 | Write-Host " =======*@@@@@@*==---:::::...................::::::::::::--= " 62 | Write-Host " ==-.:*@@@@@@=::=+*+===--:::::::::........:::::::::::--=== " 63 | Write-Host " :..-%@@@@%:..:-++=#@%#*+===-----::::::::::::::---===- " 64 | Write-Host " :::=%@@@=..::-=--#@@@@@@@%#+====================-- " 65 | Write-Host " ::::---::::-===::+@@@@@@@@@@*-==============--- " 66 | Write-Host " -:::::::-==++::::-#@@@@@@%+================- " 67 | Write-Host " ---====+=-:::::::------================- " 68 | Write-Host " -=====---::---=-:-----=============-- " 69 | Write-Host " ============--================--- " 70 | Write-Host " =======================---- " 71 | Write-Host " =-=============---- " 72 | 73 | Write-Host "`n ╔══════════════════════════════════════════╗" 74 | Write-Host " ║ HoneyPort TCP Listener & IP Blocker ║" 75 | Write-Host " ║ Coming for unauthorized connections... ║" 76 | Write-Host " ╚══════════════════════════════════════════╝`n" 77 | } 78 | 79 | # Create log directory if it doesn't exist 80 | if (!(Test-Path -Path $LogPath)) { 81 | New-Item -ItemType Directory -Force -Path $LogPath | Out-Null 82 | Write-Verbose "Created log directory: $LogPath" 83 | } 84 | 85 | $ActivityLogFile = Join-Path -Path $LogPath -ChildPath "HoneyPort_Activity.log" 86 | $FirewallLogFile = Join-Path -Path $LogPath -ChildPath "HoneyPort_Firewall.log" 87 | 88 | # Creating empty log files if they don't exist 89 | if (!(Test-Path -Path $ActivityLogFile)) { 90 | New-Item -ItemType File -Force -Path $ActivityLogFile | Out-Null 91 | } 92 | if (!(Test-Path -Path $FirewallLogFile)) { 93 | New-Item -ItemType File -Force -Path $FirewallLogFile | Out-Null 94 | } 95 | 96 | function Write-CustomLog { 97 | param( 98 | [string]$Message, 99 | [string]$LogFile, 100 | [string]$Level = "INFO" 101 | ) 102 | 103 | $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss" 104 | "$timestamp [$Level] $Message" | Out-File -Append -FilePath $LogFile 105 | 106 | if ($Level -eq "ERROR") { 107 | Write-Error $Message 108 | } elseif ($VerbosePreference -eq 'Continue' -or $Level -eq "WARNING") { 109 | Write-Verbose $Message 110 | } 111 | } 112 | 113 | function Test-Admin { 114 | $currentUser = [Security.Principal.WindowsIdentity]::GetCurrent() 115 | $principal = New-Object Security.Principal.WindowsPrincipal($currentUser) 116 | return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) 117 | } 118 | 119 | function Initialize-EventLog { 120 | try { 121 | # Check if the event log exists 122 | $eventLogExists = [System.Diagnostics.EventLog]::Exists("HoneyPort") 123 | 124 | if (-not $eventLogExists) { 125 | try { 126 | # Create the new event log 127 | New-EventLog -LogName HoneyPort -Source BlueKit | Out-Null 128 | Write-CustomLog -Message "HoneyPort event log created successfully." -LogFile $ActivityLogFile 129 | } catch { 130 | # If New-EventLog fails, attempt an alternative method 131 | try { 132 | # Using WMI to create the event log 133 | $logCreation = @" 134 | $ErrorActionPreference = 'Stop' 135 | $log = New-Object System.Diagnostics.Diagnostics.EventLog("HoneyPort") 136 | $log.Source = "BlueKit" 137 | "@ 138 | powershell.exe -Command $logCreation 139 | Write-CustomLog -Message "HoneyPort event log created using alternative method." -LogFile $ActivityLogFile 140 | } catch { 141 | # Log the error but don't stop script execution 142 | Write-CustomLog -Message "Failed to create HoneyPort event log: $_" -LogFile $ActivityLogFile -Level "ERROR" 143 | Write-Warning "Could not create HoneyPort event log. Logging to Windows Event Log will be skipped." 144 | } 145 | } 146 | } else { 147 | Write-CustomLog -Message "HoneyPort event log already exists." -LogFile $ActivityLogFile 148 | } 149 | } catch { 150 | Write-CustomLog -Message "Error checking HoneyPort event log existence: $_" -LogFile $ActivityLogFile -Level "ERROR" 151 | Write-Warning "Unable to verify or create HoneyPort event log." 152 | } 153 | } 154 | 155 | function Get-SystemIPs { 156 | try { 157 | $systemIPs = Get-CimInstance Win32_NetworkAdapterConfiguration -Filter "IPEnabled=True" | 158 | ForEach-Object { 159 | $_.IPAddress + $_.DNSServerSearchOrder + $_.WINSPrimaryServer + 160 | $_.WINSSecondaryServer + $_.DHCPServer 161 | } | 162 | Where-Object { $_ -match '^\d+\.\d+\.\d+\.\d+$' } | 163 | Select-Object -Unique 164 | 165 | # Always include localhost 166 | $systemIPs += @("127.0.0.1", "::1") 167 | 168 | return $systemIPs 169 | } catch { 170 | Write-Error "Error collecting system IPs: $_" 171 | return @("127.0.0.1", "::1") # Return at least localhost if we fail 172 | } 173 | } 174 | 175 | # Test if Windows Firewall is properly accessible 176 | function Test-FirewallAccess { 177 | try { 178 | # Try to list firewall rules to ensure we have access 179 | $testRules = Get-NetFirewallRule -ErrorAction Stop | Select-Object -First 1 180 | Write-CustomLog -Message "Firewall access verified successfully." -LogFile $FirewallLogFile 181 | return $true 182 | } catch { 183 | Write-Error "Firewall access test failed: $_" 184 | Write-Error "Make sure Windows Firewall service is running and you have admin rights." 185 | return $false 186 | } 187 | } 188 | 189 | # Display the cool ASCII art 190 | Show-BlueShellAsciiArt 191 | 192 | # Main script execution 193 | Write-CustomLog -Message "HoneyPort script started. Version 1.2" -LogFile $ActivityLogFile 194 | 195 | # Check admin privileges 196 | if (-not (Test-Admin)) { 197 | throw "This script requires Administrator privileges. Please restart as Administrator." 198 | } 199 | 200 | # Test firewall access 201 | $firewallAccessible = Test-FirewallAccess 202 | if (-not $firewallAccessible) { 203 | Write-Host "WARNING: Windows Firewall appears to be inaccessible. Blocking functionality may not work." -ForegroundColor Yellow 204 | } 205 | 206 | # Initialize Event Log 207 | Initialize-EventLog 208 | 209 | # Add system IPs to whitelist 210 | $systemIPs = Get-SystemIPs 211 | $WhiteList += $systemIPs 212 | $WhiteList = $WhiteList | Select-Object -Unique 213 | 214 | Write-CustomLog -Message "Whitelist configured with $($WhiteList.Count) IPs" -LogFile $ActivityLogFile 215 | 216 | # Start a listener job for each port 217 | foreach ($port in $Ports) { 218 | Write-CustomLog -Message "Starting job for port $port" -LogFile $ActivityLogFile 219 | 220 | Start-Job -Name "HoneyPort_$port" -ScriptBlock { 221 | param($Port, $WhiteList, $Block, $ActivityLog, $FirewallLog) 222 | 223 | # Define all functions directly within the job scope 224 | function Write-CustomLog { 225 | param( 226 | [string]$Message, 227 | [string]$LogFile, 228 | [string]$Level = "INFO" 229 | ) 230 | 231 | $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss" 232 | "$timestamp [$Level] $Message" | Out-File -Append -FilePath $LogFile 233 | 234 | if ($Level -eq "ERROR") { 235 | Write-Error $Message 236 | } elseif ($VerbosePreference -eq 'Continue' -or $Level -eq "WARNING") { 237 | Write-Verbose $Message 238 | } 239 | } 240 | 241 | function New-HoneyPortFirewallRule { 242 | param( 243 | [string]$IP, 244 | [int]$Port 245 | ) 246 | 247 | $ruleName = "HoneyPort_Block_$IP" 248 | Write-CustomLog -Message "Creating firewall rule: $ruleName" -LogFile $FirewallLog 249 | 250 | try { 251 | # Check if rule already exists 252 | $existingRule = Get-NetFirewallRule -DisplayName $ruleName -ErrorAction SilentlyContinue 253 | 254 | if ($existingRule) { 255 | Write-CustomLog -Message "Firewall rule for $IP already exists. Rule ID: $($existingRule.Name)" -LogFile $FirewallLog 256 | return $true 257 | } 258 | 259 | # Create the rule with specific parameters - Use full cmdlet name and capture output 260 | $newRule = New-NetFirewallRule -DisplayName $ruleName -Direction Inbound -Action Block -RemoteAddress $IP -Protocol TCP -Enabled True -Description "Created by HoneyPort script on $(Get-Date) for port $Port" -ErrorAction Stop 261 | 262 | # Log rule details 263 | Write-CustomLog -Message "Rule created: $ruleName" -LogFile $FirewallLog 264 | 265 | # Verify rule exists now 266 | Start-Sleep -Seconds 2 267 | $verifyRule = Get-NetFirewallRule -DisplayName $ruleName -ErrorAction SilentlyContinue 268 | 269 | if ($verifyRule) { 270 | Write-CustomLog -Message "Successfully verified creation of firewall rule: $ruleName" -LogFile $FirewallLog 271 | return $true 272 | } else { 273 | Write-CustomLog -Message "Failed to verify firewall rule creation for $IP" -LogFile $FirewallLog -Level "ERROR" 274 | 275 | # Try an alternate method to check 276 | $altCheck = Get-NetFirewallRule | Where-Object { $_.DisplayName -like "*$IP*" } 277 | if ($altCheck) { 278 | Write-CustomLog -Message "Alternative check: Found rule with IP in name: $($altCheck.DisplayName)" -LogFile $FirewallLog 279 | return $true 280 | } 281 | 282 | return $false 283 | } 284 | } catch { 285 | Write-CustomLog -Message "Error creating firewall rule for $IP`: $_" -LogFile $FirewallLog -Level "ERROR" 286 | 287 | # Try direct command to see if it works via cmd 288 | try { 289 | $cmdOutput = & netsh advfirewall firewall add rule name="HoneyPort_Block_$IP" dir=in action=block remoteip=$IP 290 | Write-CustomLog -Message "Fallback method (netsh) output: $cmdOutput" -LogFile $FirewallLog 291 | 292 | # Check if rule was created with netsh 293 | $netshCheck = Get-NetFirewallRule | Where-Object { $_.DisplayName -eq "HoneyPort_Block_$IP" } 294 | if ($netshCheck) { 295 | Write-CustomLog -Message "Fallback method successful: Rule created via netsh" -LogFile $FirewallLog 296 | return $true 297 | } else { 298 | Write-CustomLog -Message "Fallback method failed: Rule not created via netsh" -LogFile $FirewallLog -Level "ERROR" 299 | } 300 | } catch { 301 | Write-CustomLog -Message "Fallback method error: $_" -LogFile $FirewallLog -Level "ERROR" 302 | } 303 | 304 | return $false 305 | } 306 | } 307 | 308 | function Start-HoneyPortListener { 309 | param( 310 | [int]$Port, 311 | [string[]]$WhiteList, 312 | [bool]$ShouldBlock, 313 | [string]$ActivityLog, 314 | [string]$FirewallLog 315 | ) 316 | 317 | Write-CustomLog -Message "Starting listener on port $Port" -LogFile $ActivityLog 318 | 319 | try { 320 | $listener = New-Object System.Net.Sockets.TcpListener([System.Net.IPAddress]::Any, $Port) 321 | $listener.Start() 322 | 323 | Write-CustomLog -Message "Listener successfully started on port $Port" -LogFile $ActivityLog 324 | 325 | while ($true) { 326 | try { 327 | if ($listener.Pending()) { 328 | $client = $listener.AcceptTcpClient() 329 | $IP = $client.Client.RemoteEndPoint.Address.ToString() 330 | 331 | Write-CustomLog -Message "Connection detected from $IP on port $Port" -LogFile $ActivityLog 332 | 333 | if ($WhiteList -notcontains $IP) { 334 | # Log to Windows Event Log 335 | try { 336 | Write-EventLog -LogName HoneyPort -Source BlueKit -EventId 1002 -EntryType Information -Message "Connection from $IP detected on port $Port at $(Get-Date)" 337 | } catch { 338 | Write-Error "Failed to write to Event Log: $_" 339 | } 340 | 341 | if ($ShouldBlock) { 342 | Write-CustomLog -Message "Attempting to block IP: $IP on port $Port" -LogFile $ActivityLog 343 | 344 | $ruleCreated = New-HoneyPortFirewallRule -IP $IP -Port $Port 345 | 346 | if ($ruleCreated) { 347 | Write-CustomLog -Message "Successfully blocked IP $IP" -LogFile $ActivityLog 348 | } else { 349 | Write-CustomLog -Message "Failed to block IP $IP" -LogFile $FirewallLog -Level "ERROR" 350 | } 351 | } 352 | } else { 353 | Write-CustomLog -Message "IP $IP is in whitelist - connection allowed" -LogFile $ActivityLog 354 | } 355 | 356 | # Close the connection regardless 357 | $client.Close() 358 | } 359 | } catch { 360 | Write-Error "Error in connection handling: $_" 361 | } 362 | 363 | # Small sleep to prevent high CPU usage 364 | Start-Sleep -Milliseconds 100 365 | } 366 | } catch { 367 | Write-Error "Error in port $Port listener: $_" 368 | } finally { 369 | if ($listener) { 370 | $listener.Stop() 371 | Write-CustomLog -Message "Listener on port $Port has been stopped" -LogFile $ActivityLog 372 | } 373 | } 374 | } 375 | 376 | # Start the listener with the parameters 377 | Start-HoneyPortListener -Port $Port -WhiteList $WhiteList -ShouldBlock $Block -ActivityLog $ActivityLog -FirewallLog $FirewallLog 378 | 379 | } -ArgumentList $port, $WhiteList, $Block, $ActivityLogFile, $FirewallLogFile 380 | 381 | Write-CustomLog -Message "Job started for port $port" -LogFile $ActivityLogFile 382 | } 383 | 384 | # Create a simple test rule to verify firewall functionality 385 | $testRuleName = "HoneyPort_TestRule" 386 | Write-CustomLog -Message "Creating test firewall rule to verify functionality..." -LogFile $FirewallLogFile 387 | 388 | try { 389 | # Remove test rule if it already exists 390 | Get-NetFirewallRule -DisplayName $testRuleName -ErrorAction SilentlyContinue | Remove-NetFirewallRule -ErrorAction SilentlyContinue 391 | 392 | # Create test rule 393 | $testRule = New-NetFirewallRule -DisplayName $testRuleName -Direction Inbound -Action Block -RemoteAddress "10.255.255.254" -Protocol TCP -Enabled True -Description "Test rule for HoneyPort script" 394 | 395 | if ($testRule) { 396 | Write-CustomLog -Message "Test rule created successfully. Firewall blocking functionality appears to be working." -LogFile $FirewallLogFile 397 | Write-Host "Firewall functionality verified successfully." -ForegroundColor Green 398 | 399 | # Clean up test rule 400 | $testRule | Remove-NetFirewallRule -ErrorAction SilentlyContinue 401 | } else { 402 | Write-CustomLog -Message "Failed to create test rule. Firewall blocking functionality may not work." -LogFile $FirewallLogFile -Level "WARNING" 403 | Write-Host "WARNING: Failed to verify firewall functionality. IP blocking may not work." -ForegroundColor Yellow 404 | } 405 | } catch { 406 | Write-CustomLog -Message "Error testing firewall functionality: $_" -LogFile $FirewallLogFile -Level "ERROR" 407 | Write-Host "ERROR: Firewall test failed. Please check the $FirewallLogFile for details." -ForegroundColor Red 408 | } 409 | 410 | Write-Host "HoneyPort script is now running. Monitoring ports: $($Ports -join ', ')" -ForegroundColor Cyan 411 | Write-Host "Activity logs are being saved to $ActivityLogFile" -ForegroundColor White 412 | Write-Host "Firewall logs are being saved to $FirewallLogFile" -ForegroundColor White 413 | Write-Host "To test if blocking works, connect to one of the ports from a non-whitelisted IP, then check:" 414 | Write-Host " - Get-NetFirewallRule -DisplayName 'HoneyPort_Block_*'" -ForegroundColor Yellow 415 | Write-Host " - View the $FirewallLogFile file" -ForegroundColor Yellow 416 | Write-Host "Use Get-Job to view job status. Use Stop-Job -Name 'HoneyPort_*' to stop monitoring." 417 | --------------------------------------------------------------------------------