Network Connection Monitoring Made Easy: A PowerShell Script to Identify Suspicious Connections

Network Connection Monitoring Made Easy: A PowerShell Script to Identify Suspicious Connections


PortCheck

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

  • Network Connection Monitoring: The script monitors established connections on your system, providing a list of IP addresses, company names, process IDs, and process names.
  • WHOIS Lookup: The script performs a WHOIS lookup to retrieve the company name associated with each IP address.
  • GUI Display: The results are displayed in a user-friendly GUI, making it easy to identify potential security threats.
  • Customizable: The script can be customized to suit your specific needs, including changing the WHOIS server and modifying the GUI layout.

How the Script Works

  1. The script uses the netstat command to extract IP addresses and process IDs of established connections.
  2. It then performs a WHOIS lookup to retrieve the company name associated with each IP address.
  3. The results are stored in a custom object, which is then displayed in a GUI.
  4. The GUI includes two DataGridViews: one for identified connections and another for unknown companies.

Benefits

  • Improved Network Security: The script helps identify potential security threats by providing a comprehensive overview of established connections.
  • Easy to Use: The GUI display makes it easy to identify suspicious connections, even for non-technical users.
  • Customizable: The script can be customized to suit your specific needs, making it a valuable tool for network administrators.

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:

  • Run the script on a system with multiple established connections.
  • The script will display a GUI with two DataGridViews: one for identified connections and another for unknown companies.
  • Review the results to identify potential security threats.
  • Use the information to take corrective action, such as blocking suspicious IP addresses or investigating unknown companies.

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
        

要查看或添加评论,请登录

Nitesh Bhat的更多文章

  • Copy of How We Uncovered and Stopped a Cyber Intrusion with Just a Few Mins ??

    Copy of How We Uncovered and Stopped a Cyber Intrusion with Just a Few Mins ??

    (If you're concerned about suspicious activities on your device, this is a must-read.) A friend recently reached out…

  • Common Password Attacks and How to Protect Against Them

    Common Password Attacks and How to Protect Against Them

    Below are common password attacks and how to protect against them when an incident occurs because of them: 1. Brute…

  • STAY SAFE FROM CYBER ATTACKS

    STAY SAFE FROM CYBER ATTACKS

    Recently, Iranian nation-state hackers, known as MuddyWater, have been observed using a new backdoor called BugSleep…

  • Security Concept for My Dearest Wife

    Security Concept for My Dearest Wife

    Wifey (Daulat Bika), Let's understand the important concept of security by taking the example of our sweet home, which…

  • CyberArk Bot

    CyberArk Bot

    ?? Exciting News! ?? I'm thrilled to share that I've created a CyberArk bot to streamline my learning journey with this…

    1 条评论
  • Comparing HashiCorp Vault and CyberArk Secret Manager

    Comparing HashiCorp Vault and CyberArk Secret Manager

    Introduction In the world of secret management, HashiCorp Vault and CyberArk Secret Manager are two prominent tools…

  • AWS Terraform Generator Using React From.

    AWS Terraform Generator Using React From.

    In my previous article Generating-Terraform-files-from-Json-using-Powershell, I demonstrated how to generate Terraform…

  • ??HashiCorp - HCP Vault Radar

    ??HashiCorp - HCP Vault Radar

    I am studying HashiCorp Vault to understand the technology they are implementing and to prepare for the second…

  • GitGuardian Honeytoken: A Digital "Honey Trap"

    GitGuardian Honeytoken: A Digital "Honey Trap"

    Securing Your Company Environment by The Honey Trap Approach ?? Securing the DevOps Pipeline, Infrastructure…

  • Generating Terraform Files from JSON Using PowerShell

    Generating Terraform Files from JSON Using PowerShell

    Infrastructure as Code (IaC) is a crucial practice for modern DevOps and system administration. Terraform is a popular…

    1 条评论

社区洞察

其他会员也浏览了