top of page

About

PCAP analysis with Powershell - Note that I am not a guru but know enough to create my own tools.

​

#Requires -Modules NetTCPIP # Implicitly needed for potential IP address manipulation if added later
#Requires -Version 5.1 # For newer syntax and features if used

<#
.SYNOPSIS
Analyzes a PCAP file using TShark to extract various network traffic statistics and potential indicators of compromise or interest.

.DESCRIPTION
This script prompts the user for a PCAP file path, an internal IP address range (CIDR), and an output directory name.
It then uses TShark (the command-line version of Wireshark) to perform several analyses:
- Basic I/O Statistics
- Protocol Hierarchy
- DNS Queries
- HTTP Traffic Summary
- Potentially Suspicious File Downloads (HTTP GET requests for .exe/.zip)
- TCP Stream ASCII Payloads (can be very large)
- Potential Beaconing Behavior (basic check)
- ICMP Traffic
- Large Outbound Data Transfers (from the specified internal range)
- Malformed Packets

Results are saved into separate text files within a specified directory inside C:\temp\. Each file includes a definition explaining the data.

.NOTES
- Requires TShark to be installed and accessible in the system's PATH. Install Wireshark (which includes TShark) from https://www.wireshark.org/.
- The accuracy of some analyses (like beaconing) depends on the complexity of the traffic and the chosen parameters.
- TCP Stream output can be very large for captures with significant TCP traffic.
- Ensure you have read permissions for the PCAP file and write permissions for the C:\temp\ directory and its subdirectories.

.EXAMPLE
.\Analyze-Pcap.ps1
# The script will then prompt for PCAP file path, internal IP range, and output directory name. Output will be in C:\temp\<output_dir_name>\
#>

# --- Helper Function ---
Function Invoke-TSharkAnalysis {
  param(
       [Parameter(Mandatory=$true)]
       [string]$PcapFilePath,

       [Parameter(Mandatory=$true)]
       [string]$OutputFilePath,

       [Parameter(Mandatory=$true)]
       [string]$DefinitionText,

       [Parameter(Mandatory=$true)]
       [string[]]$TSharkArguments, # Array of arguments for tshark

       [Parameter(Mandatory=$true)]
       [string]$AnalysisName # For logging/error messages
  )

  Write-Host "Extracting $($AnalysisName)..."
  try {
       # Write the definition header to the output file
       Set-Content -Path $OutputFilePath -Value $DefinitionText -Encoding UTF8

       # Run TShark and append its output
       # Using Start-Process to handle redirection and potential errors more robustly
       $processInfo = New-Object System.Diagnostics.ProcessStartInfo
       $processInfo.FileName = "tshark.exe"
       $processInfo.Arguments = "-r `"$PcapFilePath`" $($TSharkArguments -join ' ')"
       $processInfo.RedirectStandardError = $true
       $processInfo.RedirectStandardOutput = $true
       $processInfo.UseShellExecute = $false
       $processInfo.CreateNoWindow = $true

       $process = New-Object System.Diagnostics.Process
       $process.StartInfo = $processInfo
       $process.Start() | Out-Null

       # Append stdout to the file
       $process.StandardOutput.ReadToEnd() | Add-Content -Path $OutputFilePath -Encoding UTF8

       # Check for errors written to stderr
       $stderrOutput = $process.StandardError.ReadToEnd()
       if (-not [string]::IsNullOrWhiteSpace($stderrOutput)) {
           Write-Warning "TShark STDERR output for '$($AnalysisName)' (check results):`n$stderrOutput"
           # Optionally append stderr to the file as well or a separate error log
           # Add-Content -Path $OutputFilePath -Value "`n--- TSHARK STDERR ---`n$stderrOutput" -Encoding UTF8
       }

       $process.WaitForExit()

       if ($process.ExitCode -ne 0) {
           Write-Error "TShark process for '$($AnalysisName)' exited with code $($process.ExitCode)."
           # Stderr might have already captured the error, but this indicates a non-zero exit
       }

  } catch {
       Write-Host "Error during '$($AnalysisName)' extraction: $($_.Exception.Message)" -ForegroundColor Red
       # Log the error details if needed
       # Add-Content -Path $OutputFilePath -Value "`n--- SCRIPT ERROR ---`n$($_.Exception.ToString())" -Encoding UTF8
  }
}

# --- Main Script Logic ---

# Check if TShark is installed and in PATH
if (-not (Get-Command "tshark" -ErrorAction SilentlyContinue)) {
  Write-Host "ERROR: TShark is not installed or not found in the system's PATH." -ForegroundColor Red
  Write-Host "Please install Wireshark (which includes TShark) from https://www.wireshark.org/ and ensure tshark.exe is in your PATH."
  exit 1 # Exit script if TShark is missing
} else {
  Write-Host "TShark found at: $((Get-Command tshark).Source)" -ForegroundColor Green
}


# Main loop to allow multiple PCAP analyses
do {
  # Prompt for PCAP file
  $pcapFile = Read-Host "Enter the path to the PCAP file to analyze (or press Enter to exit)"

  # Check if the user wants to exit
  if ([string]::IsNullOrWhiteSpace($pcapFile)) {
       Write-Host "Exiting..."
       break # Exit the loop
  }

  # Validate PCAP file path
  if (-not (Test-Path $pcapFile -PathType Leaf)) {
       Write-Host "Error: PCAP file not found at '$pcapFile'." -ForegroundColor Red
       continue # Go to the next iteration of the loop
  }

  # Prompt for internal IP address range
  $internalIP = Read-Host "Enter your internal IP address range in CIDR notation (e.g., 192.168.1.0/24)"

  # Validate that the input is not empty (Basic Check)
  if ([string]::IsNullOrWhiteSpace($internalIP)) {
       Write-Host "Error: Internal IP address range cannot be empty." -ForegroundColor Red
       continue # Go to the next iteration of the loop
  }
  # Optional: Add more robust CIDR validation here if needed

  # Prompt for output directory name
  $outputDirName = Read-Host "Enter a name for the output subdirectory within C:\temp\ (e.g., pcap_analysis_results)"

  # Validate output directory name (Basic Check for emptiness and invalid chars)
  if ([string]::IsNullOrWhiteSpace($outputDirName)) {
       Write-Host "Error: Output directory name cannot be empty." -ForegroundColor Red
       continue # Go to the next iteration of the loop
  }
  # Remove potentially problematic leading/trailing whitespace
  $outputDirName = $outputDirName.Trim()
  # Check for invalid path characters
  $invalidPathChars = [System.IO.Path]::GetInvalidPathChars() -join ''
  if ($outputDirName -match "[$([regex]::Escape($invalidPathChars))]") {
        Write-Host "Error: Output directory name contains invalid characters." -ForegroundColor Red
        continue
  }
  # Check for invalid *file* name characters as well, as they often overlap and are good practice
  $invalidFileChars = [System.IO.Path]::GetInvalidFileNameChars() -join ''
  if ($outputDirName -match "[$([regex]::Escape($invalidFileChars))]") {
       Write-Host "Error: Output directory name contains invalid characters." -ForegroundColor Red
       continue
  }


  # Create an output directory for results inside C:\temp\
  # --- THIS IS THE MODIFIED LINE ---
  $outputDir = Join-Path -Path "C:\temp" -ChildPath $outputDirName
  # --- END OF MODIFICATION ---

  try {
       # Ensure C:\temp exists, create if not (though it usually does)
       if (-not (Test-Path "C:\temp" -PathType Container)) {
           Write-Host "Creating C:\temp directory..." -ForegroundColor Yellow
           New-Item -ItemType Directory -Path "C:\temp" -ErrorAction Stop | Out-Null
       }

       if (-not (Test-Path $outputDir -PathType Container)) {
           New-Item -ItemType Directory -Path $outputDir -ErrorAction Stop
           Write-Host "Created output directory: $outputDir" -ForegroundColor Cyan
       } else {
           Write-Host "Output directory already exists: $outputDir" -ForegroundColor Yellow
       }
  } catch {
       Write-Host "Error creating output directory '$outputDir': $($_.Exception.Message)" -ForegroundColor Red
       Write-Host "Please ensure you have write permissions in C:\temp\" -ForegroundColor Yellow
       continue # Cannot proceed without output directory
  }

  Write-Host "`nStarting analysis of '$pcapFile'..." -ForegroundColor Green
  Write-Host "Internal IP Range specified: $internalIP"
  Write-Host "Results will be saved to: $outputDir"

  # --- Analysis Definitions (Remain the same) ---

  $def_BasicStats = @"
=========================
Basic I/O Statistics
=========================
Definition: Provides a summary of the traffic captured in the PCAP file, broken down by protocol and showing total frames, bytes, and average packet size.
Relevance: Helps understand the overall composition of the traffic and identify dominant protocols. High traffic volumes or unexpected protocols might warrant further investigation.

TShark Command: tshark -r <pcap> -q -z io,stat,0

--- TShark Output Below ---

"@

  $def_ProtoHierarchy = @"
=========================
Protocol Hierarchy Statistics
=========================
Definition: Shows the distribution of protocols within the capture file, hierarchically. For example, it shows how much TCP traffic is carrying HTTP.
Relevance: Useful for understanding protocol encapsulation and identifying the specific applications riding over common transport protocols (TCP/UDP). Can reveal unexpected or tunneled traffic.

TShark Command: tshark -r <pcap> -q -z io,phs

--- TShark Output Below ---

"@

  $def_DnsQueries = @"
=========================
DNS Queries
=========================
Definition: Lists all Domain Name System (DNS) query requests found in the capture. Shows the frame number, source IP, destination IP (DNS server), and the queried domain name.
Relevance: Crucial for identifying domains contacted by internal hosts. Suspicious or unknown domains can indicate malware command-and-control (C2) communication, phishing attempts, or connections to malicious infrastructure.

TShark Command: tshark -r <pcap> -Y "dns.flags.response == 0" -T fields -e frame.number -e ip.src -e ip.dst -e dns.qry.name

--- TShark Output Below ---

"@

  $def_HttpTraffic = @"
=========================
HTTP Traffic Summary
=========================
Definition: Lists Hypertext Transfer Protocol (HTTP) requests, including frame number, source IP, destination IP, HTTP method (GET, POST, etc.), requested host, and the URI path.
Relevance: Shows web browsing activity. Useful for identifying visits to potentially malicious websites, attempts to download files, or data exfiltration via POST requests. Note: This only captures unencrypted HTTP traffic (port 80 typically). HTTPS (port 443) traffic is encrypted and its contents are not visible here beyond the initial TLS handshake.

TShark Command: tshark -r <pcap> -Y "http.request" -T fields -e frame.number -e ip.src -e ip.dst -e http.request.method -e http.host -e http.request.uri

--- TShark Output Below ---

"@

  $def_SuspiciousDownloads = @"
=========================
Potential Suspicious File Downloads (HTTP)
=========================
Definition: Lists HTTP GET requests where the requested URI contains common executable or archive file extensions (.exe, .zip). Shows frame number, source IP, destination IP, and the full request URI.
Relevance: Highlights potential downloads of malicious software or compressed files that might contain malware. This is a basic check and might include legitimate downloads. Requires further context and investigation. Only applies to unencrypted HTTP traffic.

TShark Command: tshark -r <pcap> -Y "http.request.method == GET and (http.request.uri contains \".exe\" or http.request.uri contains \".zip\")" -T fields -e frame.number -e ip.src -e ip.dst -e http.request.uri

--- TShark Output Below ---

"@

  $def_TcpStreams = @"
=========================
TCP Streams (ASCII Payload)
=========================
Definition: Reassembles and displays the ASCII content of TCP sessions between two endpoints. Each stream starts with a header indicating the hosts and ports involved.
Relevance: Allows inspection of the actual data exchanged over unencrypted protocols running on TCP (like HTTP, FTP, Telnet, SMTP). Can reveal credentials, commands, transferred files, or other sensitive information.
WARNING: This output can be VERY LARGE for captures with significant TCP traffic. Review selectively. Encrypted traffic (like HTTPS/TLS) will appear as garbled text.

TShark Command: tshark -r <pcap> -q -z follow,tcp,ascii,0

--- TShark Output Below ---

"@

  $def_Beaconing = @"
=========================
Potential Beaconing Behavior (Basic)
=========================
Definition: Lists destination IP addresses that received packets from the same source IP address more than 10 times in this capture. It shows the destination IP and the count of packets sent to it from various sources.
Relevance: Malware often uses 'beaconing' - periodically contacting a command-and-control (C2) server. This basic check looks for destinations receiving repeated connections, which *could* indicate beaconing activity.
Limitation: This is a very basic check based only on packet count per destination IP across all sources. True beaconing analysis requires examining timing intervals and source-destination pairs. High counts could also be legitimate traffic (e.g., DNS server, update server). Requires careful interpretation.

TShark Command: tshark -r <pcap> -T fields -e ip.src -e ip.dst | Sort-Object -Property @{Expression={$_.Split("`t")[1]}}, @{Expression={$_.Split("`t")[0]}} | Group-Object -Property @{Expression={$_.Split("`t")[1]}} | Where-Object { $_.Count -gt 10 } | Select-Object Name, Count

--- TShark Output Below ---

"@

  $def_IcmpTraffic = @"
=========================
ICMP Traffic
=========================
Definition: Lists Internet Control Message Protocol (ICMP) packets, including frame number, source IP, destination IP, and ICMP type/code.
Relevance: ICMP is used for network diagnostics (like 'ping' - Echo Request/Reply, Type 8/0) and error reporting (e.g., Destination Unreachable - Type 3). Excessive ICMP traffic, particularly from one source to many destinations (ping sweep) or unusual ICMP types, can indicate network scanning, reconnaissance, or specific attack techniques (e.g., ICMP tunnel).

TShark Command: tshark -r <pcap> -Y "icmp" -T fields -e frame.number -e ip.src -e ip.dst -e icmp.type -e icmp.code

--- TShark Output Below ---

"@

  $def_LargeOutbound = @"
=========================
Large Outbound Data Transfers
=========================
Definition: Lists packets originating from the specified internal IP range ($internalIP) that have a frame length greater than 1000 bytes. Shows frame number, source IP, destination IP, and frame length.
Relevance: Large outbound transfers can indicate data exfiltration - the unauthorized removal of data from the network. While large packets can be legitimate (file transfers, backups), unusually large or frequent transfers to external destinations warrant investigation. The threshold (1000 bytes) is arbitrary and may need adjustment.

TShark Command: tshark -r <pcap> -Y "frame.len > 1000 and ip.src == $internalIP" -T fields -e frame.number -e ip.src -e ip.dst -e frame.len

--- TShark Output Below ---

"@

  $def_Malformed = @"
=========================
Malformed Packets
=========================
Definition: Lists packets that Wireshark/TShark identified as 'malformed' based on protocol dissection rules. Shows frame number, source IP, destination IP, and summary information.
Relevance: Malformed packets can indicate network problems, faulty hardware/drivers, or potentially malicious activity like attempts to evade detection, crash systems, or exploit vulnerabilities through crafted packets.

TShark Command: tshark -r <pcap> -Y "_ws.malformed" -T fields -e frame.number -e ip.src -e ip.dst -e _ws.col.Info

--- TShark Output Below ---

"@

  # --- Execute Analyses (Function calls remain the same, using $outputDir) ---

  # Basic Statistics
  Invoke-TSharkAnalysis -PcapFilePath $pcapFile -OutputFilePath (Join-Path $outputDir "basic_statistics.txt") -DefinitionText $def_BasicStats -TSharkArguments "-q", "-z", "io,stat,0" -AnalysisName "Basic Statistics"

  # Protocol Hierarchy
  Invoke-TSharkAnalysis -PcapFilePath $pcapFile -OutputFilePath (Join-Path $outputDir "protocol_hierarchy.txt") -DefinitionText $def_ProtoHierarchy -TSharkArguments "-q", "-z", "io,phs" -AnalysisName "Protocol Hierarchy"

  # DNS Queries
  Invoke-TSharkAnalysis -PcapFilePath $pcapFile -OutputFilePath (Join-Path $outputDir "dns_queries.txt") -DefinitionText $def_DnsQueries -TSharkArguments "-Y", '"dns.flags.response == 0"', "-T", "fields", "-e", "frame.number", "-e", "ip.src", "-e", "ip.dst", "-e", "dns.qry.name" -AnalysisName "DNS Queries"

  # HTTP Traffic
  Invoke-TSharkAnalysis -PcapFilePath $pcapFile -OutputFilePath (Join-Path $outputDir "http_traffic.txt") -DefinitionText $def_HttpTraffic -TSharkArguments "-Y", '"http.request"', "-T", "fields", "-e", "frame.number", "-e", "ip.src", "-e", "ip.dst", "-e", "http.request.method", "-e", "http.host", "-e", "http.request.uri" -AnalysisName "HTTP Traffic"

  # Suspicious File Downloads (HTTP GET for .exe/.zip)
  Invoke-TSharkAnalysis -PcapFilePath $pcapFile -OutputFilePath (Join-Path $outputDir "suspicious_file_downloads.txt") -DefinitionText $def_SuspiciousDownloads -TSharkArguments "-Y", '"http.request.method == GET and (http.request.uri contains \".exe\" or http.request.uri contains \".zip\")"', "-T", "fields", "-e", "frame.number", "-e", "ip.src", "-e", "ip.dst", "-e", "http.request.uri" -AnalysisName "Suspicious File Downloads"

  # TCP Streams (ASCII) - This can take time and produce large files
  Invoke-TSharkAnalysis -PcapFilePath $pcapFile -OutputFilePath (Join-Path $outputDir "tcp_streams.txt") -DefinitionText $def_TcpStreams -TSharkArguments "-q", "-z", "follow,tcp,ascii,0" -AnalysisName "TCP Streams"

  # Potential Beaconing Behavior (Basic)
  # Note: This uses PowerShell for post-processing after TShark extracts the relevant fields
  $beaconingOutputFile = Join-Path $outputDir "beaconing_behavior.txt"
  Write-Host "Extracting Potential Beaconing Behavior (Basic)..."
  try {
       Set-Content -Path $beaconingOutputFile -Value $def_Beaconing -Encoding UTF8
       $beaconData = tshark -r $pcapFile -T fields -e ip.src -e ip.dst -e frame.time_relative 2>&1 # Keep time for potential future enhancement
       # Process the data in PowerShell
       $beaconCounts = $beaconData | Select-Object -Skip 1 | # Skip potential header/blank line if any
         Where-Object { $_ -match '\S+\s+\S+' } | # Basic validation: ensure two columns exist
         ForEach-Object {
           $src, $dst, $time = $_ -split "`t"
           [PSCustomObject]@{ Source = $src; Destination = $dst }
         } | Group-Object -Property Destination | Where-Object { $_.Count -gt 10 } |
         Select-Object @{Name='DestinationIP'; Expression={$_.Name}}, Count |
         Sort-Object Count -Descending

       $beaconCounts | Format-Table -AutoSize | Out-String | Add-Content -Path $beaconingOutputFile -Encoding UTF8
  } catch {
       Write-Host "Error during 'Potential Beaconing Behavior' extraction: $($_.Exception.Message)" -ForegroundColor Red
       Add-Content -Path $beaconingOutputFile -Value "`n--- SCRIPT ERROR during Beaconing Processing ---`n$($_.Exception.ToString())" -Encoding UTF8
  }


  # ICMP Traffic
  Invoke-TSharkAnalysis -PcapFilePath $pcapFile -OutputFilePath (Join-Path $outputDir "icmp_traffic.txt") -DefinitionText $def_IcmpTraffic -TSharkArguments "-Y", '"icmp"', "-T", "fields", "-e", "frame.number", "-e", "ip.src", "-e", "ip.dst", "-e", "icmp.type", "-e", "icmp.code" -AnalysisName "ICMP Traffic"

  # Large Outbound Data Transfers
  # Ensure the internal IP CIDR variable is correctly interpreted by TShark within the filter string
  $largeTransferFilter = "frame.len > 1000 and ip.src == $internalIP"
  Invoke-TSharkAnalysis -PcapFilePath $pcapFile -OutputFilePath (Join-Path $outputDir "large_outbound_transfers.txt") -DefinitionText $def_LargeOutbound -TSharkArguments "-Y", $largeTransferFilter, "-T", "fields", "-e", "frame.number", "-e", "ip.src", "-e", "ip.dst", "-e", "frame.len" -AnalysisName "Large Outbound Transfers"

  # Malformed Packets
  Invoke-TSharkAnalysis -PcapFilePath $pcapFile -OutputFilePath (Join-Path $outputDir "malformed_packets.txt") -DefinitionText $def_Malformed -TSharkArguments "-Y", '"_ws.malformed"', "-T", "fields", "-e", "frame.number", "-e", "ip.src", "-e", "ip.dst", "-e", "_ws.col.Info" -AnalysisName "Malformed Packets"

  Write-Host "`nAnalysis complete for '$pcapFile'." -ForegroundColor Green
  Write-Host "Results saved to directory: $outputDir"

  # Prompt for another scan
  $continue = Read-Host "Do you want to analyze another PCAP file? (yes/no)"

} while ($continue -eq "yes")

Write-Host "`nScript finished." -ForegroundColor Green

 

 

cybersecurity.jpg
cybersecurity 2.jpg
  • Facebook - Black Circle
  • Twitter - Black Circle

© 2023 by IT SERVICES.  Proudly created with Wix.com

bottom of page