Network Connection Monitoring Made Easy: A PowerShell Script to Identify Suspicious Connections
Nitesh Bhat
Software Engineer at Heart | Passionate about Cybersecurity, AI, IAM & PAM | Proficient in PowerShell & Python | SailPoint Advocate | Driving Innovation in Identity Governance and Automation
As a cybersecurity enthusiast, I'm excited to share a powerful PowerShell script that helps identify suspicious network connections on your system. This script is designed to provide a comprehensive overview of established connections, including the IP address, company name, process ID, and process name.
What the Script Does
The script uses the netstat command to extract IP addresses and process IDs of established connections. It then performs a WHOIS lookup to retrieve the company name associated with each IP address. The results are displayed in a user-friendly GUI, making it easy to identify potential security threats.
Key Features
How the Script Works
领英推荐
Benefits
Conclusion
This PowerShell script is a valuable tool for network administrators and cybersecurity enthusiasts. Its ability to identify suspicious network connections and provide a comprehensive overview of established connections makes it an essential tool for maintaining network security. Try it out today and see how it can help you improve your network security!
Example Use Case
Here's an example of how the script can be used:
Code
# Load necessary assemblies for Windows Forms
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
# Extract IP addresses and PIDs from netstat output for established connections
$connections = netstat -ano | Select-String 'ESTABLISHED|TIME_WAIT' | ForEach-Object {
$parts = $_ -split '\s+'
$foreignAddress = $parts[3] -split ':' | Select-Object -First 1
$processId = $parts[5]
[PSCustomObject]@{
IPAddress = $foreignAddress
ProcessId = $processId
}
}
# Define the WHOIS server to query
$whoisServer = 'whois.arin.net'
# Function to perform WHOIS lookup for a given IP address
function Get-CompanyNameFromIP {
param (
[string]$IpAddress
)
$tcpClient = New-Object System.Net.Sockets.TcpClient
try {
$tcpClient.Connect($whoisServer, 43)
$stream = $tcpClient.GetStream()
$writer = New-Object System.IO.StreamWriter($stream)
$writer.WriteLine($IpAddress)
$writer.Flush()
# Read the response from the WHOIS server
$reader = New-Object System.IO.StreamReader($stream)
$response = $reader.ReadToEnd()
# Extract the company name from the response using regex
if ($response -match 'OrgName:\s*(.*)') {
return $matches[1].Trim()
} else {
return 'Company Name not found.'
}
}
catch {
Write-Output "Error connecting to WHOIS server for IP $IpAddress"
return 'Error'
}
finally {
# Ensure the connection is closed
if ($tcpClient.Connected) {
$tcpClient.Close()
}
}
}
# Prepare output in a table format
$results = [System.Collections.Generic.List[Object]]::new()
$unknownCompanies = [System.Collections.Generic.List[Object]]::new()
# Loop through each connection and perform the WHOIS lookup
foreach ($connection in $connections) {
$ipAddress = $connection.IPAddress
$processId = $connection.ProcessId
# Get the process name from the ProcessId
$processName = (Get-Process -Id $processId -ErrorAction SilentlyContinue).ProcessName
if (-not $processName) { $processName = 'Unknown Process' }
# Perform WHOIS lookup to get the company name
$companyName = Get-CompanyNameFromIP -IpAddress $ipAddress
# Add the result to the collection
$results.Add([PSCustomObject]@{
'IP Address' = $ipAddress
'Company Name' = $companyName
'Process ID' = $processId
'Process Name' = $processName
})
# Collect unknown company names for notification
if ($companyName -eq 'Company Name not found.') {
$unknownCompanies.Add([PSCustomObject]@{
'IP Address' = $ipAddress
'Company Name' = $companyName
'Process ID' = $processId
'Process Name' = $processName
})
}
}
# Function to create a custom icon with the letter "S"
function Create-LetterSIcon {
$bitmap = New-Object System.Drawing.Bitmap(32, 32)
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
# Fill the background with a gradient
$graphics.Clear([System.Drawing.Color]::White)
# Draw the letter "S"
$font = New-Object System.Drawing.Font('Arial', 15, [System.Drawing.FontStyle]::Bold)
$brush = [System.Drawing.Brushes]::Red
$graphics.DrawString('S', $font, $brush, 0, 0)
# Convert the bitmap to an icon
$iconHandle = $bitmap.GetHicon()
$icon = [System.Drawing.Icon]::FromHandle($iconHandle)
# Clean up
$graphics.Dispose()
$bitmap.Dispose()
return $icon
}
# Function to draw a custom logo on a PictureBox with static red background and white text
function Draw-CompanyLogo {
param ($pictureBox)
# Create a bitmap to draw on and Graphics object once
$bitmap = New-Object System.Drawing.Bitmap($pictureBox.Width, $pictureBox.Height)
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
$graphics.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::AntiAlias
# Draw a red square for the logo background
$graphics.FillRectangle([System.Drawing.Brushes]::Red, 0, 0, $pictureBox.Width, $pictureBox.Height)
# Draw the company name "NiteshBhat" in white color
$font = New-Object System.Drawing.Font('Arial', 20, [System.Drawing.FontStyle]::Bold)
$textBrush = [System.Drawing.Brushes]::White
$stringFormat = New-Object System.Drawing.StringFormat
$stringFormat.Alignment = [System.Drawing.StringAlignment]::Center
$stringFormat.LineAlignment = [System.Drawing.StringAlignment]::Center
$graphics.DrawString('PortCheck', $font, $textBrush, $bitmap.Width / 2, $bitmap.Height / 2, $stringFormat)
# Set the PictureBox image to the drawn bitmap
$pictureBox.Image = $bitmap
# Clean up graphics object to prevent memory leaks
$graphics.Dispose()
}
# Function to display results and unknown companies in a combined form with a DataGridView and ListView
function Show-NetworkConnectionsForm {
param (
[System.Collections.ArrayList]$Results,
[System.Collections.ArrayList]$UnknownCompanies
)
# Create a new form
$form = New-Object Windows.Forms.Form
$form.Text = 'Identified Suspicious Connections'
$form.Size = New-Object Drawing.Size(1050, 500)
$form.StartPosition = 'CenterScreen'
$form.BackColor = [System.Drawing.Color]::White # White background
$form.FormBorderStyle = 'FixedDialog'
$form.MaximizeBox = $false
# Add an icon to the form
$form.Icon = Create-LetterSIcon
# Add a PictureBox for the company logo and draw the logo
$pictureBox = New-Object Windows.Forms.PictureBox
$pictureBox.SizeMode = [Windows.Forms.PictureBoxSizeMode]::StretchImage
$pictureBox.Location = New-Object Drawing.Point(10, 10)
$pictureBox.Size = New-Object Drawing.Size(250, 40)
Draw-CompanyLogo -pictureBox $pictureBox # Draw the logo
$form.Controls.Add($pictureBox)
# Add a Label for company details
$companyLabel = New-Object Windows.Forms.Label
$companyLabel.Text = "Nitesh Bhat`n 79 whiteman,`nMelbourne VIC-300"
$companyLabel.Location = New-Object Drawing.Point(810, 10)
$companyLabel.Size = New-Object Drawing.Size(200, 50)
$companyLabel.ForeColor = [System.Drawing.Color]::Red # Red text
$companyLabel.Font = New-Object Drawing.Font('Arial', 6, [System.Drawing.FontStyle]::Bold)
$form.Controls.Add($companyLabel)
# Add DataGridView for "Port Check"
$dataGridView = New-Object Windows.Forms.DataGridView
$dataGridView.Size = New-Object Drawing.Size(560, 310)
$dataGridView.Location = New-Object Drawing.Point(20, 80)
$dataGridView.AutoSizeColumnsMode = 'Fill'
$dataGridView.BackgroundColor = [System.Drawing.Color]::White
$dataGridView.DefaultCellStyle.ForeColor = [System.Drawing.Color]::Green
$dataGridView.DefaultCellStyle.BackColor = [System.Drawing.Color]::White
$dataGridView.ColumnHeadersDefaultCellStyle.BackColor = [System.Drawing.Color]::Green
$dataGridView.ColumnHeadersDefaultCellStyle.ForeColor = [System.Drawing.Color]::White
$dataGridView.EnableHeadersVisualStyles = $false
$dataGridView.ReadOnly = $true
# Define columns for DataGridView
$dataGridView.Columns.Add('IP Address', 'IP Address') | Out-Null
$dataGridView.Columns.Add('Company Name', 'Company Name') | Out-Null
$dataGridView.Columns.Add('Process ID', 'Process ID') | Out-Null
$dataGridView.Columns.Add('Process Name', 'Process Name') | Out-Null
# Populate DataGridView with data
foreach ($result in $Results) {
$row = $dataGridView.Rows.Add()
$dataGridView.Rows[$row].Cells[0].Value = $result.'IP Address'
$dataGridView.Rows[$row].Cells[1].Value = $result.'Company Name'
$dataGridView.Rows[$row].Cells[2].Value = $result.'Process ID'
$dataGridView.Rows[$row].Cells[3].Value = $result.'Process Name'
}
$form.Controls.Add($dataGridView)
# Add DataGridView for "Unknown"
$unknownDataGridView = New-Object Windows.Forms.DataGridView
$unknownDataGridView.Size = New-Object Drawing.Size(400, 310)
$unknownDataGridView.Location = New-Object Drawing.Point(600, 80)
$unknownDataGridView.AutoSizeColumnsMode = 'Fill'
$unknownDataGridView.BackgroundColor = [System.Drawing.Color]::White
$unknownDataGridView.DefaultCellStyle.ForeColor = [System.Drawing.Color]::Red
$unknownDataGridView.DefaultCellStyle.BackColor = [System.Drawing.Color]::White
$unknownDataGridView.ColumnHeadersDefaultCellStyle.BackColor = [System.Drawing.Color]::Red
$unknownDataGridView.ColumnHeadersDefaultCellStyle.ForeColor = [System.Drawing.Color]::White
$unknownDataGridView.EnableHeadersVisualStyles = $false
$unknownDataGridView.ReadOnly = $true
# Define columns for Unknown DataGridView
$unknownDataGridView.Columns.Add('IP Address', 'IP Address') | Out-Null
$unknownDataGridView.Columns.Add('Company Name', 'Company Name') | Out-Null
$unknownDataGridView.Columns.Add('Process ID', 'Process ID') | Out-Null
$unknownDataGridView.Columns.Add('Process Name', 'Process Name') | Out-Null
# Populate the DataGridView with unknown company data
foreach ($unknown in $UnknownCompanies) {
$row = $unknownDataGridView.Rows.Add()
$unknownDataGridView.Rows[$row].Cells[0].Value = $unknown.'IP Address'
$unknownDataGridView.Rows[$row].Cells[1].Value = $unknown.'Company Name'
$unknownDataGridView.Rows[$row].Cells[2].Value = $unknown.'Process ID'
$unknownDataGridView.Rows[$row].Cells[3].Value = $unknown.'Process Name'
}
$form.Controls.Add($unknownDataGridView)
# Add "OK" Button
$okButton = New-Object Windows.Forms.Button
$okButton.Text = 'OK'
$okButton.Location = New-Object Drawing.Point(850, 400)
$okButton.Size = New-Object Drawing.Size(100, 30)
$okButton.BackColor = [System.Drawing.Color]::Red
$okButton.ForeColor = [System.Drawing.Color]::White
$okButton.FlatStyle = 'Flat'
$okButton.Font = New-Object Drawing.Font('Arial', 10, [System.Drawing.FontStyle]::Bold)
# Create a Tooltip
$toolTip = New-Object Windows.Forms.ToolTip
$toolTip.SetToolTip($okButton, 'It will close the form')
# Mouse events for color change
$okButton.Add_MouseHover({
$okButton.BackColor = [System.Drawing.Color]::DarkRed
})
$okButton.Add_MouseLeave({
$okButton.BackColor = [System.Drawing.Color]::Red
})
# On Click Event
$okButton.Add_Click({
$okButton.BackColor = [System.Drawing.Color]::DarkRed
Start-Sleep -Milliseconds 200
$form.Close()
})
$form.Controls.Add($okButton)
# Show the form
$form.ShowDialog()
}
# Call the function with the data
Show-NetworkConnectionsForm -Results $results -UnknownCompanies $unknownCompanies