# Packet Capture: Wireshark and tcpdump

> Chapter 47 of the Courseiva CYSA-PLUS curriculum — https://courseiva.com/learn/cysa-plus/packet-capture-cysa

**Official objective:** 1.3 — Security Operations

## Introduction

In the Security Operations domain of the CS0-003 exam, packet capture analysis using Wireshark and tcpdump is essential for security monitoring and incident response. For the CS0-003 exam, understanding how to capture, filter, and interpret network traffic is critical, as packet analysis questions appear in approximately 15-20% of Security Operations domain questions. Mastering these tools enables you to identify malicious activity, troubleshoot connectivity issues, and perform forensic analysis on network traffic. This chapter provides the deep technical knowledge needed to answer exam questions and apply these skills in real-world security operations.

## Packet Capture as a Flight Data Recorder

Picture yourself as an aviation safety investigator, examining the data after an aircraft incident. The aircraft has a flight data recorder (FDR) that continuously records every parameter—altitude, airspeed, engine RPM, control surface positions, radio communications—at a high sampling rate, but only retains the last 25 hours of data. When you need to investigate, you download the FDR data and use specialized software to replay the flight, searching for anomalies. This is exactly how packet capture works. Wireshark is like the analysis software: it parses the raw binary data, decodes each protocol layer, and presents it in a human-readable format with color-coded packets and filters. tcpdump is like a command-line tool that can dump raw FDR data to a file for later analysis. The capture interface (e.g., promiscuous mode) is like setting the FDR to record all microphones in the cockpit, not just the pilot's headset. Just as an FDR captures every radio transmission, packet capture records every frame that passes through the network interface, including those not addressed to the capturing host. And just as an investigator applies filters to focus on specific parameters (e.g., only altitude changes above 10,000 ft), a security analyst uses display filters in Wireshark to isolate only HTTP traffic or only packets to a specific IP. The analogy is mechanistic: the capture process is passive and non-intrusive, the storage is a ring buffer (like a loop tape), and the analysis requires expertise to interpret the raw data correctly.

## Core explanation

### What Packet Capture Is and Why It Exists

Packet capture (pcap) is the process of intercepting and logging traffic that passes over a computer network or a portion of a network. The primary reason for packet capture is to obtain a raw, unfiltered view of network communications for analysis. Unlike log files that summarize events, a packet capture records every byte of every frame, including headers and payloads. This allows security analysts to reconstruct sessions, extract files, and detect patterns that would be invisible in logs.

### How Packet Capture Works Internally

When a network interface card (NIC) receives a frame, it normally checks the destination MAC address. If the frame is not addressed to the NIC's MAC (or a broadcast/multicast address), the NIC discards it. To capture all traffic, the NIC must be placed into **promiscuous mode**. In promiscuous mode, the NIC passes every received frame to the operating system, regardless of destination MAC. On a wired Ethernet segment, this allows capture of all traffic on that collision domain (e.g., a switch port). On a switched network, traffic not destined to the capturing host is typically not forwarded to that port unless port mirroring (SPAN) or a network tap is used.

Once the OS receives the raw frame, the capture library (libpcap on Unix/Linux, WinPcap/Npcap on Windows) copies the frame from the kernel buffer to user space. This copying is performance-intensive; high-speed capture may require kernel bypass techniques (e.g., PF_RING, DPDK). The capture tool then writes the frame to a file in pcap format, which includes a global header (magic number, version, timezone, timestamp accuracy, snapshot length, link layer type) followed by each packet record (timestamp, captured length, original length, and packet data).

### Key Components, Values, and Defaults

- **Promiscuous mode**: Default off in most OS; must be enabled explicitly. In Wireshark, go to Capture > Options and check "Enable promiscuous mode on all interfaces". In tcpdump, use the `-p` flag to disable promiscuous mode (default is enabled when running as root).
- **Monitor mode**: For wireless captures, the NIC must be in monitor mode to capture all 802.11 frames, not just those associated with the host. This is different from promiscuous mode.
- **Snapshot length (snaplen)**: The maximum number of bytes captured per packet. Default is 65535 bytes (full packet). Use `-s 0` in tcpdump for default, or `-s 256` to capture only headers and save disk space. In Wireshark, set under Capture Options.
- **Buffer size**: Determines how much memory is allocated for kernel buffering. In tcpdump, use `-B` to set buffer size in KiB (default is 2 MiB on Linux). Larger buffers reduce packet loss under high load.
- **Filter expressions**: Capture filters (BPF syntax) are applied at the kernel level to reduce the volume of data copied to user space. Display filters are applied post-capture in Wireshark. The exam tests both types.

### Capture Filter Syntax (BPF)

Berkeley Packet Filter (BPF) expressions are used in tcpdump and can be used in Wireshark capture options. Common primitives:

- `host 10.0.0.1` - traffic to/from IP
- `src host 10.0.0.1` - traffic from IP
- `dst host 10.0.0.1` - traffic to IP
- `net 10.0.0.0/24` - traffic to/from subnet
- `port 80` - traffic with port 80 (TCP or UDP)
- `tcp port 80` - TCP port 80 only
- `icmp` - ICMP packets
- `arp` - ARP packets
- `vlan` - VLAN-tagged frames
- `not arp and not icmp` - negation and combination

Operators: `and` (&&), `or` (||), `not` (!), parentheses for grouping.

Example: `tcpdump -i eth0 -w capture.pcap host 192.168.1.100 and port 443`

### Display Filters in Wireshark

Display filters are more powerful and use a different syntax. They are applied after capture and can filter on any field in the protocol tree. Common examples:

- `ip.addr == 10.0.0.1` - any packet with IP address 10.0.0.1 as source or destination
- `tcp.port == 80` - TCP packets with port 80
- `http.request` - only HTTP request packets
- `dns.flags.response == 1` - DNS responses
- `tcp.flags.syn == 1 and tcp.flags.ack == 0` - SYN packets (new connections)
- `!arp` - exclude ARP packets

Display filters can use comparison operators: `==`, `!=`, `>`, `<`, `>=`, `<=`, and `contains`. They also support logical operators: `and`, `or`, `not`, and parentheses.

### How to Use tcpdump

Basic syntax: `tcpdump [options] [filter]`

Common options:
- `-i <interface>` : specify interface (e.g., eth0, any)
- `-w <file>` : write raw packets to file
- `-r <file>` : read packets from file
- `-v`, `-vv`, `-vvv` : verbose output
- `-n` : don't convert addresses to names (faster, avoids DNS)
- `-nn` : don't convert protocol and port numbers to names
- `-c <count>` : capture only <count> packets then exit
- `-s <snaplen>` : snapshot length
- `-e` : print link-level header (MAC addresses)
- `-X` : print hex and ASCII of packet payload
- `-A` : print only ASCII of packet payload
- `-q` : quick (less verbose) output

Example: `tcpdump -i eth0 -c 100 -nn -X port 53` captures 100 DNS packets with hex dump.

### How to Use Wireshark

Wireshark provides a graphical interface. Key features:
- **Capture dialog**: Select interface, set capture filter, start capture.
- **Packet list pane**: Shows summary of each packet (time, source, destination, protocol, length, info).
- **Packet details pane**: Hierarchical protocol tree for the selected packet.
- **Packet bytes pane**: Hex and ASCII dump of the selected packet.
- **Display filter bar**: Enter display filter expressions.
- **Statistics menu**: Access to protocol hierarchy, conversations, endpoints, IO graphs, etc.
- **Follow TCP stream**: Reassembles TCP stream and shows the application data.
- **Export objects**: Extract files transferred over HTTP, SMB, etc.

### How Packet Capture Interacts with Related Technologies

- **SPAN/Port Mirroring**: On Cisco switches, configure a SPAN session to copy traffic from one or more source ports to a destination port where the capture device is connected. Example: `monitor session 1 source interface Gi0/1 both` and `monitor session 1 destination interface Gi0/2`.
- **Network TAP**: A hardware device that provides a passive copy of traffic without introducing a point of failure. TAPs are preferred for forensic-quality captures because they do not drop packets even under high load.
- **SSL/TLS Decryption**: Wireshark can decrypt TLS traffic if you have the private key or use a man-in-the-middle proxy. This is essential for inspecting encrypted malicious traffic.
- **NetFlow**: Flow records (NetFlow, sFlow, IPFIX) provide metadata about flows, not full packet captures. They are useful for trend analysis but cannot replace pcap for deep inspection.
- **IDS/IPS**: Systems like Snort and Suricata use packet capture and pattern matching to detect intrusions. They often output alerts with pcap attachments for forensic analysis.

## Real-world context

### Enterprise Scenario 1: Incident Response on a Compromised Web Server

A security team receives an alert that a web server is communicating with a known C2 server. The team uses tcpdump to capture all traffic from the server's primary interface (`eth0`) with a capture filter for the suspicious IP: `tcpdump -i eth0 -w webserver_c2.pcap host 203.0.113.5`. The capture runs for 30 minutes. The analyst then opens the pcap in Wireshark, applies a display filter `ip.addr == 203.0.113.5`, and follows the TCP streams. They see HTTP POST requests with encrypted payloads. Using Wireshark's Export Objects > HTTP, they extract a malicious DLL. The capture also reveals beaconing intervals of exactly 60 seconds, which helps confirm the C2 pattern. The team uses this evidence to block the IP at the firewall and clean the server.

### Enterprise Scenario 2: Network Performance Troubleshooting

Users report slow application performance. The network team deploys a temporary TAP on the core switch and captures traffic for 1 hour using `tcpdump -i tap0 -s 256 -w perf_capture.pcap` (snaplen 256 to save space). In Wireshark, they use Statistics > IO Graph to visualize throughput. They notice periodic spikes to 95% utilization. Using Conversations, they identify a single host generating massive UDP traffic to a non-standard port. Further inspection reveals a misconfigured backup agent flooding the network. The team throttles the backup agent, and performance normalizes. The capture helped pinpoint the issue without affecting production.

### Scenario 3: Malware Analysis in a Sandbox

A SOC analyst receives a suspicious email attachment. Before detonating it in a sandbox, they set up a packet capture on the sandbox's virtual interface: `tcpdump -i eth0 -w malware_run.pcap host not 192.168.1.1` (exclude the gateway to reduce noise). After execution, they analyze the pcap in Wireshark. They look for DNS queries to domains that don't exist (NXDOMAIN responses), which may indicate DGA. They also check for HTTP User-Agent strings that are unusual. The capture reveals a callback to a domain registered 2 days ago. The analyst extracts the full HTTP request and payload, which is used to update IDS signatures. This real-world workflow is exactly what the CS0-003 exam expects you to understand.

## Exam focus

### What CS0-003 Tests on This Topic

The exam objectives under Security Operations (Domain 1) include "Given a scenario, analyze data from packet captures" (Objective 1.3). You must be able to interpret packet captures to identify malicious activity, understand the difference between capture and display filters, and know common tcpdump and Wireshark commands. The exam does not require memorizing every Wireshark menu item, but you must know how to apply filters, follow streams, and interpret protocol fields.

### Common Wrong Answers and Why Candidates Choose Them

1. **Confusing capture filters with display filters**: The exam may present a scenario where you need to filter traffic during capture. Candidates often choose a display filter syntax (e.g., `ip.addr == 10.0.0.1`) instead of the correct BPF syntax (`host 10.0.0.1`). Remember: capture filters use BPF and are applied at the kernel level; display filters are applied after capture and use Wireshark's syntax.
2. **Choosing "promiscuous mode" when monitor mode is needed for wireless**: For capturing 802.11 frames, promiscuous mode alone is insufficient. Monitor mode must be enabled. The exam might describe a scenario involving wireless capture; candidates who pick promiscuous mode miss the requirement for monitor mode.
3. **Assuming all packets are captured**: Candidates forget that switches isolate traffic. If you capture on a host in a switched network without SPAN or a TAP, you only see broadcast traffic and traffic to/from that host. The exam may test this by asking why you didn't capture traffic between two other hosts.
4. **Misinterpreting TCP flags**: A common question asks which flags indicate a new connection (SYN=1, ACK=0). Candidates often confuse SYN-ACK (response) with SYN. Know that a SYN with ACK=0 initiates a connection; SYN-ACK is the second step.

### Specific Numbers, Values, and Terms on the Exam

- Default snaplen: 65535 bytes (full packet). Using `-s 0` in tcpdump sets default.
- Default buffer size: 2 MiB (Linux). `-B` option sets buffer size in KiB.
- Common ports for filtering: 80 (HTTP), 443 (HTTPS), 53 (DNS), 22 (SSH), 3389 (RDP).
- BPF syntax: `host`, `port`, `src`, `dst`, `net`, `vlan`, `tcp`, `udp`, `icmp`.
- Wireshark display filter operators: `==`, `!=`, `contains`, `matches`.
- "Follow TCP Stream" is the Wireshark feature to reassemble application data.

### Edge Cases and Exceptions

- **Fragmented packets**: Wireshark can reassemble IP fragments, but capture filters may miss fragments if the filter uses `port` (which is in the first fragment only). Use `ip` or `host` instead.
- **VLAN tagging**: Packets with VLAN tags have a 4-byte header. Capture filters can filter on VLAN ID using `vlan vlan_id`. Display filter: `vlan.id == 100`.
- **Capture on multiple interfaces**: tcpdump can capture on any interface; use `-i any` to capture on all interfaces (Linux only).
- **Timestamps**: Capture timestamps are from the capturing host's clock. Inconsistent clocks can confuse timeline analysis.

### How to Eliminate Wrong Answers Using Underlying Mechanism

If a question asks why you can't see traffic between two other hosts when capturing on a third host, the mechanism is that switches forward frames only to the destination port. The only way to see that traffic is to capture on one of the communicating hosts, use a SPAN port, or use a TAP. Eliminate answers that suggest enabling promiscuous mode alone, because promiscuous mode only affects what the NIC accepts, not what the switch forwards.

## Step by step

1. **Identify Capture Point and Interface** — Determine where to capture traffic. For a host under investigation, capture directly on that host. For network-wide visibility, use a SPAN port or TAP. In Wireshark, the Capture Options dialog lists available interfaces with real-time traffic graphs. In tcpdump, use `tcpdump -D` to list interfaces. Choose an interface that sees the relevant traffic. For example, on a Linux server, `eth0` is the primary interface. On a Windows system, Wireshark shows interfaces like 'Ethernet' or 'Wi-Fi'. Ensure the interface is in promiscuous mode (default for tcpdump as root; enable in Wireshark).
2. **Apply Capture Filter to Reduce Volume** — To avoid capturing irrelevant traffic, apply a BPF capture filter. This is critical in high-traffic environments to prevent buffer overflow and packet loss. For example, to capture only HTTP traffic to/from a specific server: `tcpdump -i eth0 host 192.168.1.10 and port 80`. In Wireshark, enter the filter in the Capture Filter field before starting. Capture filters use BPF syntax and are applied at the kernel level, so they are efficient. Common filters include `host`, `port`, `net`, and `vlan`. Remember: capture filters cannot use Wireshark display filter syntax.
3. **Start Capture and Monitor Buffer Status** — Begin capturing. In tcpdump, use `-w file.pcap` to write to file. In Wireshark, click the Start button. Monitor the capture for buffer drops. In tcpdump, you can check for dropped packets by watching the count displayed when stopping capture (e.g., 'dropped by kernel' vs 'captured'). In Wireshark, the status bar shows packet count and elapsed time. If packets are being dropped, increase the kernel buffer size (tcpdump `-B` option, e.g., `-B 4096` for 4 MiB) or reduce the capture filter to fewer packets. On high-speed links (>1 Gbps), consider using hardware acceleration or dedicated capture appliances.
4. **Stop Capture and Save to File** — Stop the capture when sufficient data has been collected. In tcpdump, press Ctrl+C. The file is already written. In Wireshark, click the Stop button. Save the capture in pcap format (default). Use descriptive filenames with timestamps, e.g., `incident_20231027.pcap`. For long-term storage, consider compressing pcap files (gzip) as they can be large. Wireshark also supports pcapng format, which can store multiple interfaces and comments. For exam purposes, know that pcapng is the default in newer Wireshark versions and is backward-compatible with pcap.
5. **Analyze with Display Filters and Statistics** — Open the capture file in Wireshark or use tcpdump with `-r` to read. Apply display filters to isolate suspicious traffic. For example, to find all DNS queries for a suspicious domain: `dns.qry.name contains "malware.com"`. Use Wireshark's Statistics menu: Protocol Hierarchy shows traffic breakdown; Conversations lists all flows; IO Graph shows traffic patterns over time. Follow TCP streams to read unencrypted application data. Export objects (HTTP, SMB, etc.) to extract files. For tcpdump, you can filter with BPF syntax when reading: `tcpdump -r capture.pcap port 80 -X` to print HTTP payloads. Document findings with screenshots of packet details.

## Comparisons

### Wireshark vs tcpdump

**Wireshark:**
- Graphical user interface with color coding and protocol decoding.
- Supports complex display filters with syntax highlighting.
- Allows interactive analysis like Follow TCP Stream and Export Objects.
- Provides extensive statistics (IO Graph, Protocol Hierarchy, Conversations).
- Higher resource usage; may struggle on very high-speed links.

**tcpdump:**
- Command-line interface, lightweight and scriptable.
- Uses BPF capture filters; display filtering is limited (uses BPF when reading with -r).
- Best for remote captures and automation (SSH, cron jobs).
- Minimal statistics; output is text-based with options like -X for hex dump.
- Very efficient; can capture at high speeds with minimal overhead.

## Common misconceptions

- **Misconception:** Promiscuous mode allows capturing all traffic on a switched network. **Reality:** Promiscuous mode only causes the NIC to accept all frames it receives, but a switch will not forward frames destined to other hosts to the capture port. To capture all traffic on a switched network, you must use a SPAN port (port mirroring) or a network TAP.
- **Misconception:** Capture filters and display filters use the same syntax. **Reality:** Capture filters use Berkeley Packet Filter (BPF) syntax (e.g., `host 10.0.0.1`), while display filters use Wireshark's own syntax (e.g., `ip.addr == 10.0.0.1`). They are not interchangeable.
- **Misconception:** tcpdump can only capture on Ethernet interfaces. **Reality:** tcpdump can capture on any interface that supports packet capture, including loopback (lo), wireless (wlan0), and virtual interfaces (tun, tap).
- **Misconception:** Wireshark can decrypt all encrypted traffic automatically. **Reality:** Wireshark can decrypt TLS/SSL traffic only if you provide the private key or use a pre-master secret key from the client. It cannot decrypt traffic without these keys.
- **Misconception:** A capture filter 'port 80' captures all HTTP traffic. **Reality:** A filter 'port 80' captures all TCP and UDP traffic with port 80. HTTP typically uses TCP port 80, but the filter does not check the protocol type. Also, it will not capture traffic on other ports that may carry HTTP (e.g., 8080).

## Key takeaways

- Packet capture uses promiscuous mode to capture all frames received by the NIC, but on switched networks, additional measures (SPAN/TAP) are needed to see traffic between other hosts.
- Capture filters use BPF syntax (e.g., `host`, `port`, `src`, `dst`) and are applied at the kernel level; display filters use Wireshark syntax (e.g., `ip.addr ==`, `tcp.port`) and are applied post-capture.
- Default snaplen is 65535 bytes; use `-s 256` in tcpdump to capture only headers and save disk space.
- To capture wireless 802.11 frames, the NIC must be in monitor mode, not just promiscuous mode.
- tcpdump options: `-i` interface, `-w` write file, `-r` read file, `-n` no name resolution, `-X` hex+ASCII dump, `-c` count.
- Wireshark's "Follow TCP Stream" reassembles application-layer data from a TCP connection.
- SPAN (port mirroring) configuration: `monitor session 1 source interface Gi0/1 both` and `monitor session 1 destination interface Gi0/2`.
- Always verify capture buffer drops; increase kernel buffer size with `-B` in tcpdump if packets are being dropped.

## FAQ

**What is the difference between a capture filter and a display filter in Wireshark?**

A capture filter is applied before packets are captured, using BPF syntax (e.g., `host 10.0.0.1`), and it reduces the amount of data stored. A display filter is applied after capture, using Wireshark's own syntax (e.g., `ip.addr == 10.0.0.1`), and it only hides packets from view without deleting them. On the exam, remember that capture filters are set in the Capture Options dialog, while display filters are typed in the filter toolbar.

**How do I capture all traffic on a switch port?**

You cannot capture all traffic simply by connecting a laptop to a switch port because the switch only forwards unicast traffic to the destination port. To capture all traffic, you must configure port mirroring (SPAN) on the switch to copy traffic from the source port(s) to the port where your capture device is connected. Alternatively, use a network TAP inline between devices.

**What command would I use to capture only DNS traffic on interface eth0 and save to a file?**

Use tcpdump: `tcpdump -i eth0 -w dns.pcap port 53`. This captures all UDP and TCP traffic on port 53 (DNS). To capture only UDP DNS, use `tcpdump -i eth0 -w dns.pcap udp port 53`.

**How can I view the payload of a TCP stream in Wireshark?**

Right-click on any packet in the TCP stream and select "Follow" > "TCP Stream". Wireshark will reassemble the entire stream and display the application data in a separate window. You can choose to show the data in ASCII, hex, or raw format. This is useful for extracting files or reading unencrypted protocols like HTTP.

**Why does my packet capture show only broadcast traffic when I capture on a switch?**

This is because the switch forwards unicast traffic only to the destination port. If your capture device is connected to a port that is not the destination for any unicast traffic, you will only see broadcast and multicast frames. To see all traffic, use a SPAN port or a TAP.

**What is the default snapshot length in tcpdump?**

The default snapshot length is 65535 bytes, which captures the entire packet. You can change it with the `-s` option. For example, `-s 256` captures only the first 256 bytes, which is enough for headers and saves disk space.

**How do I capture traffic on a wireless network in monitor mode?**

First, enable monitor mode on the wireless interface using `iwconfig wlan0 mode monitor` (Linux) or through the OS settings. Then use tcpdump: `tcpdump -i wlan0 -w wifi.pcap`. In Wireshark, select the wireless interface in capture options and ensure monitor mode is enabled. Note that monitor mode requires driver support and root privileges.

---

Interactive version with quiz and diagrams: https://courseiva.com/learn/cysa-plus/packet-capture-cysa
