Network Traffic Analysis with Wireshark

Network Traffic Analysis with Wireshark

Table of Contents

Overview

A comprehensive SOC Analyst project for analyzing network traffic to detect security threats and understand attack patterns using Wireshark.

Learning Objectives

  • Master Wireshark for network forensics
  • Identify malicious network traffic patterns
  • Analyze encrypted and unencrypted protocols
  • Detect data exfiltration and command & control communications
  • Document network-based security incidents

Project Structure

network-traffic-analysis/
├── sample-captures/
│   ├── legitimate-traffic.pcap
│   ├── malware-c2.pcap
│   ├── data-exfiltration.pcap
│   └── ddos-attack.pcap
├── analysis-scripts/
│   ├── pcap-parser.py
│   ├── flow-analyzer.py
│   └── threat-detector.py
├── filters/
│   ├── common-filters.txt
│   ├── threat-specific-filters.txt
│   └── custom-filters.txt
├── documentation/
│   ├── wireshark-guide.md
│   ├── protocol-reference.md
│   └── analysis-checklist.md
├── reports/
│   └── traffic-analysis-template.md
└── README.md

Tools Required

  • Wireshark 4.x
  • TShark (command-line version)
  • Python 3.8+ with Scapy/PyShark
  • NetworkMiner (Optional)
  • Zeek/Bro (Optional)

Analysis Scenarios

Scenario 1: Malware C2 Communications

  • Identify beaconing patterns
  • Detect DNS tunneling
  • Analyze HTTP/HTTPS communications
  • Identify encoded data exfiltration

Scenario 2: Data Exfiltration Detection

  • Monitor unusual data transfers
  • Identify large file uploads
  • Detect encrypted traffic spikes
  • Analyze FTP/SMTP transfers

Scenario 3: Lateral Movement

  • Detect internal network scanning
  • Identify SMB/RPC exploitation attempts
  • Monitor authentication protocols
  • Track privilege escalation traffic

Scenario 4: DDoS Attack Analysis

  • Identify attack vectors (SYN, UDP, HTTP)
  • Analyze attack patterns and sources
  • Calculate traffic volume and impact
  • Recommend mitigation strategies

Essential Wireshark Filters

General Traffic Analysis

# Show only HTTP traffic
http

# Show only DNS traffic
dns

# Show traffic to/from specific IP
ip.addr == 192.168.1.100

# Show traffic on specific port
tcp.port == 443

# Exclude local network traffic
not ip.addr == 192.168.0.0/16

Security-Focused Filters

# Potential malware beaconing (regular intervals)
frame.time_delta > 300 and frame.time_delta < 400

# Suspicious user agents
http.user_agent contains "curl"

# Large file transfers
http.content_length > 1000000

# PowerShell traffic
tcp.port == 5985 or tcp.port == 5986

# RDP connections
tcp.port == 3389

# SSH connections
tcp.port == 22

Encrypted Traffic Analysis

# TLS/SSL traffic
ssl

# Certificate issues
ssl.alert_message

# Handshake failures
ssl.handshake.type == 0

Sample Analysis Scripts

PCAP Parser with Scapy

from scapy.all import *
import pandas as pd
from collections import Counter

def analyze_pcap(pcap_file):
    """
    Analyze PCAP file for security events
    """
    packets = rdpcap(pcap_file)
    
    analysis = {
        'total_packets': len(packets),
        'protocols': Counter(),
        'top_sources': Counter(),
        'top_destinations': Counter(),
        'top_ports': Counter(),
        'suspicious_patterns': []
    }
    
    for packet in packets:
        # Protocol analysis
        if IP in packet:
            analysis['protocols'][packet[IP].proto] += 1
            analysis['top_sources'][packet[IP].src] += 1
            analysis['top_destinations'][packet[IP].dst] += 1
        
        # Port analysis
        if TCP in packet:
            analysis['top_ports'][packet[TCP].dport] += 1
        elif UDP in packet:
            analysis['top_ports'][packet[UDP].dport] += 1
    
    return analysis

def detect_beaconing(packets, time_threshold=60):
    """
    Detect potential C2 beaconing patterns
    """
    connections = {}
    
    for packet in packets:
        if IP in packet and TCP in packet:
            key = f"{packet[IP].src}:{packet[TCP].sport}-{packet[IP].dst}:{packet[TCP].dport}"
            
            if key not in connections:
                connections[key] = []
            
            connections[key].append(packet.time)
    
    beacons = []
    for conn, timestamps in connections.items():
        if len(timestamps) >= 3:
            intervals = []
            for i in range(1, len(timestamps)):
                intervals.append(timestamps[i] - timestamps[i-1])
            
            # Check for regular intervals
            avg_interval = sum(intervals) / len(intervals)
            variance = sum((x - avg_interval) ** 2 for x in intervals) / len(intervals)
            
            if variance < time_threshold:  # Low variance indicates regular pattern
                beacons.append({
                    'connection': conn,
                    'avg_interval': avg_interval,
                    'packet_count': len(timestamps)
                })
    
    return beacons

Flow Analysis

import pyshark
import socket

def analyze_flows(pcap_file):
    """
    Analyze network flows for anomalies
    """
    cap = pyshark.FileCapture(pcap_file)
    
    flows = {}
    for packet in cap:
        try:
            if hasattr(packet, 'ip') and hasattr(packet, 'tcp'):
                src_ip = packet.ip.src
                dst_ip = packet.ip.dst
                src_port = packet.tcp.srcport
                dst_port = packet.tcp.dstport
                
                flow_key = f"{src_ip}:{src_port}-{dst_ip}:{dst_port}"
                
                if flow_key not in flows:
                    flows[flow_key] = {
                        'packet_count': 0,
                        'bytes_total': 0,
                        'start_time': float(packet.sniff_timestamp),
                        'end_time': float(packet.sniff_timestamp),
                        'flags': set()
                    }
                
                flows[flow_key]['packet_count'] += 1
                flows[flow_key]['end_time'] = float(packet.sniff_timestamp)
                
                if hasattr(packet, 'tcp'):
                    flows[flow_key]['flags'].add(packet.tcp.flags)
                
                # Calculate bytes (simplified)
                flows[flow_key]['bytes_total'] += int(packet.length)
                
        except AttributeError:
            continue
    
    return flows

def detect_anomalous_flows(flows):
    """
    Identify suspicious network flows
    """
    anomalies = []
    
    for flow_key, flow_data in flows.items():
        # Long-lived connections
        duration = flow_data['end_time'] - flow_data['start_time']
        if duration > 3600:  # More than 1 hour
            anomalies.append({
                'flow': flow_key,
                'type': 'long_connection',
                'duration': duration,
                'details': flow_data
            })
        
        # High byte transfers
        if flow_data['bytes_total'] > 100000000:  # More than 100MB
            anomalies.append({
                'flow': flow_key,
                'type': 'large_transfer',
                'bytes': flow_data['bytes_total'],
                'details': flow_data
            })
        
        # Frequent small packets (potential beaconing)
        if flow_data['packet_count'] > 1000 and flow_data['bytes_total'] < 10000:
            anomalies.append({
                'flow': flow_key,
                'type': 'frequent_small_packets',
                'packet_count': flow_data['packet_count'],
                'details': flow_data
            })
    
    return anomalies

Analysis Workflow

1. Initial Triage

  • Basic traffic overview (protocols, volume)
  • Timeline establishment
  • Identify key conversations
  • Flag suspicious protocols/ports

2. Deep Dive Analysis

  • Extract file transfers
  • Analyze HTTP/HTTPS requests
  • Decode encrypted protocols when possible
  • Identify data encoding methods

3. Threat Hunting

  • Search for known malicious patterns
  • Identify zero-day attack indicators
  • Correlate with threat intelligence
  • Build attack timeline

4. Documentation

  • Create visual traffic maps
  • Document all findings
  • Provide IOC extraction
  • Recommend detection rules

Common Attack Patterns

DNS Tunneling Detection

# Look for long DNS queries
dns.qry.name contains "很长" or dns.flags.rcode == 3

# High volume of DNS queries to single domain
dns and frame.time_delta < 0.1

PowerShell Remoting

# WinRM traffic
tcp.port == 5985 or tcp.port == 5986

# PowerShell Web Access
http.request.uri contains "/powershell"

Data Exfiltration

# Large HTTP POST requests
http.request.method == POST and http.content_length > 1000000

# FTP uploads
ftp and ftp.request.command == "STOR"

Sample Analysis Findings

C2 Beacon Detection

Flow Analysis Results:
- Connection: 192.168.1.50:54321-185.14.28.100:443
- Average interval: 301 seconds (5 minutes)
- Packet count: 47 connections
- Pattern: Regular HTTPS beacon with POST data
- Assessment: High confidence C2 communication

Data Exfiltration

Anomaly Detected:
- Flow: 10.0.0.15:5555-203.0.113.10:21
- Transfer size: 250MB
- Duration: 2 minutes
- Protocol: FTP
- Files: customer_data_2026.zip
- Assessment: Potential data exfiltration

Expected Deliverables

  1. Completed traffic analysis reports
  2. Extracted IOCs and artifacts
  3. Network traffic visualizations
  4. Detection signatures/rules
  5. Blog post documentation

Extension Ideas

  • Automated threat detection pipeline
  • Integration with Suricata/Snort
  • Real-time traffic monitoring dashboard
  • Machine learning for anomaly detection

Resources

Safety Notes

  • Work in isolated network environment
  • Sanitize sensitive data before sharing
  • Follow legal and ethical guidelines
  • Use legitimate data for practice
Share :
comments powered by Disqus

Related Posts

SOC Analyst Projects

SOC Analyst Projects

Welcome to a comprehensive collection of hands-on SOC Analyst projects designed to build practical cybersecurity skills.

Read More
SIEM Rule Creation and Testing

SIEM Rule Creation and Testing

Overview Develop and test SIEM detection rules to enhance SOC monitoring capabilities and improve threat detection across multiple attack vectors.

Read More
Malware Analysis Sandbox Setup

Malware Analysis Sandbox Setup

Overview Build a secure malware analysis environment for SOC Analysts to safely analyze malicious samples and extract threat intelligence.

Read More