Metadata-Version: 2.2
Name: fastpcap
Version: 0.1.0
Summary: Fast, memory-safe pcap/pcapng analysis: C++ core, NumPy columns, flows and statistics
Keywords: pcap,pcapng,network,packet,security,dns,tls,ja3,netflow
License: MIT
Classifier: Programming Language :: C++
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: System :: Networking :: Monitoring
Classifier: Topic :: Security
Requires-Python: >=3.9
Requires-Dist: numpy>=1.22
Provides-Extra: pandas
Requires-Dist: pandas; extra == "pandas"
Provides-Extra: test
Requires-Dist: pytest; extra == "test"
Description-Content-Type: text/markdown

<div align="center">

<img src="https://i.hizliresim.com/ltefwh5k.png" alt="fastpcap" width="100%"/>

<br/>

[![C++17](https://img.shields.io/badge/C%2B%2B-17-00599C?style=for-the-badge&logo=cplusplus&logoColor=white)](#-build-from-source)
[![Python](https://img.shields.io/badge/Python-3.9%2B-3776AB?style=for-the-badge&logo=python&logoColor=white)](#-quick-start)
[![NumPy](https://img.shields.io/badge/NumPy-columns-013243?style=for-the-badge&logo=numpy&logoColor=white)](#-column-reference)
[![License: MIT](https://img.shields.io/badge/License-MIT-22c55e?style=for-the-badge)](LICENSE)

[![Platforms](https://img.shields.io/badge/Linux%20%7C%20Windows%20%7C%20macOS-supported-8b5cf6?style=flat-square)](#-releasing)
[![Fuzzed](https://img.shields.io/badge/fuzzed-ASan%20%2B%20UBSan-ef4444?style=flat-square)](#-robustness)
[![pybind11](https://img.shields.io/badge/bindings-pybind11-0ea5e9?style=flat-square)](#-project-layout)
[![Stars](https://img.shields.io/github/stars/qntsoftware/fastpcap?style=flat-square&logo=github)](https://github.com/qntsoftware/fastpcap/stargazers)
[![Issues](https://img.shields.io/github/issues/qntsoftware/fastpcap?style=flat-square)](https://github.com/qntsoftware/fastpcap/issues)

**[Quick start](#-quick-start)** · **[Features](#-features)** · **[Protocols](#-supported-protocols)** · **[Statistics](#-statistics)** · **[API](#-api)** · **[Robustness](#-robustness)** · **[Build](#-build-from-source)**

</div>

---

## ⚡ Why fastpcap

Python packet libraries are convenient, but parsing millions of packets in pure Python is slow. fastpcap moves the heavy work into a **C++17 core** and returns **NumPy columns**, so you can filter, group and plot a whole capture with vectorized code.

<div align="center">
<img src="https://i.hizliresim.com/wou9rkl5.png" alt="fastpcap pipeline" width="100%"/>
</div>

- 🚀 **One pass** gives you packets, bidirectional flows and capture statistics
- 🧵 **GIL released** while parsing, so other Python threads keep running
- 🛡️ **Hostile-input safe**: all reads are bounds-checked and the parser is fuzzed
- 📊 **Analysis built in**: entropy, jitter, RTT, retransmissions, beaconing and scan detection
- 🔌 **No C++ to write**: `import fastpcap` and work with arrays

## 📦 Installation

```bash
pip install fastpcap
```

> The package is not on PyPI until the first release is published. Until then, use [Build from source](#-build-from-source).

## 🚀 Quick start

```python
import fastpcap

cap = fastpcap.read("capture.pcap")
print(cap)   # <fastpcap.Capture pcap-usec packets=... flows=... duration=...s>

# 📈 capture-level statistics
s = cap.summary
print(s["packets"], s["bytes"], s["duration"])
print(s["packet_size"]["mean"], s["packet_size"]["skew"])
print(s["l7_counts"])            # {'dns': 120, 'tls': 4031, ...}
print(s["top_src"][:3])          # top talkers by bytes

# 🧮 per-packet NumPy columns
p = cap.packets
https = (p["proto"] == 6) & (p["dport"] == 443)
print(p["ts_ns"][https][:5])
print(fastpcap.ips(p, "src")[:3])

# 🔀 bidirectional flows
f = cap.flows
print(f["bps"].max(), f["retransmissions"].sum())

# 🕵️ security helpers
print(fastpcap.beacon_candidates(f))      # suspiciously regular flows
print(fastpcap.port_scan_candidates(f))   # sources touching many targets
```

<details>
<summary><b>Memory-friendly modes for huge files</b></summary>

```python
fastpcap.summary("huge.pcap")                # statistics only
fastpcap.read_flows("huge.pcap")             # flows only, no per-packet columns
fastpcap.read("huge.pcap", packets=False)    # same idea, full Capture object
```

</details>

<details>
<summary><b>Command line and pandas</b></summary>

```bash
python -m fastpcap capture.pcap              # human readable report
python -m fastpcap capture.pcap --json       # machine readable
python -m fastpcap capture.pcap --checksums  # also verify IPv4/TCP/UDP/ICMP checksums
```

pandas is optional:

```python
df = cap.to_pandas("packets")   # or "flows"
```

</details>

### Example output

Output of the standalone C++ tool (`fp_dump`) on a small synthetic capture generated by `tests/pcapgen.py`:

```text
$ ./fp_dump sample.pcap --flows --checksums
format=pcap-usec linktype=1 records=13 truncated=0 malformed=0
packets=13 bytes=1050 undecoded=0 ipv4=11 ipv6=1 arp=1 frag=0
duration=0.600000 size_mean=80.769 size_std=35.586 size_skew=0.8596 size_kurt=-0.1242
l7 dns=2
l7 http=3
l7 tls=1
l7 arp=1
flow 10.0.0.2:40000 <-> 93.184.216.34:80 p=6 pk=4/2 by=348/154 dur=0.030000 rtt=10000000 retr=1 l7=http info=example.com
flow 10.0.0.2:40001 <-> 93.184.216.34:443 p=6 pk=1/0 by=161/0 dur=0.000000 rtt=-1 retr=0 l7=tls info=example.org
```

## ✨ Features

| | Feature | Details |
|---|---|---|
| 📂 | **Containers** | pcap (usec/nsec, little/big endian), pcapng (SHB, IDB, EPB, SPB, `if_tsresol`) |
| 🧱 | **Zero-copy reading** | `mmap` on Linux/macOS, whole-file read on Windows |
| 🔍 | **Deep decoding** | Ethernet to application layer, in a single pass |
| 🔀 | **Flow table** | bidirectional 5-tuple flows with optional idle timeout |
| 🧮 | **Streaming statistics** | Welford/Pébay moments, Shannon entropy, jitter, RTT |
| 🧪 | **Checksum verification** | RFC 1071 with IPv4 and IPv6 pseudo headers |
| 🕵️ | **Detection helpers** | beaconing, port scans, top talkers |
| 🔐 | **TLS fingerprinting** | SNI, version, JA3 MD5 |

## 🌐 Supported protocols

| Layer | Protocols |
|---|---|
| **Container** | pcap (usec/nsec, little/big endian), pcapng |
| **L2** | Ethernet, 802.1Q/QinQ, Linux SLL/SLL2, BSD loopback, raw IP, MPLS, PPPoE |
| **L3** | IPv4 (fragments, header checksum), IPv6 (extension headers, fragments), ARP |
| **L4** | TCP (flags, seq/ack, MSS, window scale), UDP, ICMP, ICMPv6, SCTP ports, IGMP |
| **L7** | DNS (compression, A/AAAA answers), HTTP/1.x, TLS (SNI, version, JA3), DHCP, SSH banner, NTP, QUIC long header |

> **Not supported yet:** TCP stream reassembly, IP defragmentation, tunnels (GRE, VXLAN, IPsec), HTTP/2, QUIC decryption, TLS handshakes split across segments.
> For full protocol dissection, use Wireshark/tshark. fastpcap is built for fast statistics and triage over large captures.

## 📐 Statistics

| Area | What you get |
|---|---|
| **Moments** | one-pass mean, standard deviation, skewness, excess kurtosis, coefficient of variation for packet sizes and inter-arrival times (per flow and per capture) |
| **Entropy** | Shannon entropy of payload bytes per flow, and of source, destination and port distributions per capture |
| **Timing** | inter-arrival jitter (RFC 3550 smoothing), periodicity score `1 / (1 + CV)`, packets and bits per second |
| **TCP** | handshake RTT, retransmissions (safe across 32-bit sequence wraparound), flag counts, MSS, window scale |
| **Integrity** | IPv4, TCP, UDP, ICMP and ICMPv6 checksum verification |

## 🧰 API

| Function | Purpose |
|---|---|
| `read(path, packets=True, flows=True, l7=True, verify_checksums=False, entropy=True, max_packets=0, flow_timeout=0.0)` | Parse a file, returns `Capture` |
| `read_bytes(data, ...)` | Same for in-memory captures |
| `read_flows(path, ...)` / `summary(path, ...)` | Flows only / statistics only |
| `iter_packets(path)` / `read_pcap(path)` | Convenience `Packet` tuples (slower, fine for small files) |
| `beacon_candidates(flows, min_packets=8, max_cv=0.25, min_interval=0.5)` | Regular-interval flows |
| `port_scan_candidates(flows, min_targets=20)` | Scan-like sources |
| `top_talkers(flows, n=10)` | Initiators ranked by bytes |
| `entropy(data)` / `checksum16(data)` | Byte entropy / RFC 1071 checksum |

`flow_timeout` (seconds) splits a 5-tuple into separate flows after that much idle time. `0` disables it.

## 📚 Column reference

<details>
<summary><b>Packet columns</b></summary>

`ts_ns, wirelen, caplen, ethertype, vlan, ip_ver, proto, ttl, tos, ip_id, src, dst, sport, dport, tcp_flags, seq, ack, window, tcp_mss, tcp_wscale, payload_len, frag, ip_csum, l4_csum, icmp_type, icmp_code, l7, app_code, info, extra`

`src` and `dst` are `(n, 16)` uint8 arrays. IPv4 is stored as `::ffff:a.b.c.d`. Use `fastpcap.ips()` for text.

| `l7` | `app_code` | `info` | `extra` |
|---|---|---|---|
| dns | query type | query name | flags, rcode, answer IPs |
| http | status (0 for requests) | Host header | first line |
| tls | version (`0x0304` = 1.3) | SNI | JA3 MD5 |
| dhcp | message type | hostname | request / reply |
| ssh | | banner | |
| ntp | mode | | version |
| quic | version | | |
| arp | opcode | sender MAC | target MAC |

Checksum columns: `1` ok, `0` bad, `2` not checked. Captures taken on a NIC with checksum offload often show bad TCP/UDP checksums on outgoing packets. That is normal.

</details>

<details>
<summary><b>Flow columns</b></summary>

`src, dst, sport, dport, proto, start_ns, end_ns, duration, fwd_packets, bwd_packets, fwd_bytes, bwd_bytes, fwd_payload, bwd_payload, size_mean, size_std, size_min, size_max, size_skew, size_kurtosis, iat_mean, iat_std, iat_cv, iat_min, iat_max, jitter, periodicity, pps, bps, payload_entropy, syn, synack, fin, rst, psh, urg, tcp_flags_or, retransmissions, rtt, ttl, window, mss, wscale, l7, app_code, info, extra`

`rtt` is `NaN` when no handshake was seen.

</details>

## 🛡️ Robustness

Network data is untrusted input, so the parser itself is an attack surface.

- Every byte is read through a **bounds-checked view** that returns `0` instead of touching memory out of range
- Malformed or truncated files stop cleanly and set `cap.meta["malformed"]` or `cap.meta["truncated"]`
- `fuzz/fuzz_reader.cpp` is a **libFuzzer** entry point and a standalone mutation fuzzer
- CI runs the fuzzer under **AddressSanitizer + UBSan** on every push

```bash
python3 tests/make_seeds.py /tmp/seeds
g++ -std=c++17 -O1 -g -DFP_STANDALONE -fsanitize=address,undefined \
    -fno-sanitize-recover=undefined fuzz/fuzz_reader.cpp -o fuzz_sa
./fuzz_sa /tmp/seeds/usec_le.pcap 100000
```

## 🔧 Build from source

```bash
# Debian / Ubuntu / Kali
sudo apt install build-essential cmake

git clone https://github.com/qntsoftware/fastpcap
cd fastpcap
pip install -e .
pytest tests -q
```

**Standalone C++ tool** (no Python needed, the core is header-only):

```bash
g++ -std=c++17 -O3 -o fp_dump tools/fp_dump.cpp
./fp_dump capture.pcap --packets 20 --flows --checksums
```

## 🗂️ Project layout

```text
fastpcap/
├── src/
│   ├── util.hpp        bounds-checked Span, addresses, statistics, MD5
│   ├── reader.hpp      mmap + pcap/pcapng reader
│   ├── decode.hpp      L2 to L7 decoder
│   ├── analyze.hpp     flow table, columns, capture summary
│   └── bindings.cpp    pybind11 module
├── python/fastpcap/    Python API, analysis helpers, CLI
├── tests/              pytest suite and pure-Python packet builder
├── fuzz/               libFuzzer / standalone mutation fuzzer
└── tools/fp_dump.cpp   standalone CLI
```

## 🚢 Releasing

```bash
git tag v0.1.0 && git push --tags
```

`.github/workflows/wheels.yml` builds wheels for Linux, Windows and macOS with cibuildwheel and publishes to PyPI via Trusted Publishing, so no API token is stored in the repo.

## 🗺️ Roadmap

- [ ] TCP stream reassembly
- [ ] IP defragmentation
- [ ] Tunnel decapsulation (GRE, VXLAN)
- [ ] HTTP/2 and DNS-over-TLS awareness
- [ ] Streaming iterator API for captures larger than memory

## 🤝 Contributing

Issues and pull requests are welcome. Please run `pytest tests -q` and the fuzzer before opening a PR, and include a small capture (or the `pcapgen.py` code that builds it) for any decoder change.

## ⚖️ Responsible use

fastpcap analyzes captures. Only analyze traffic you own or are authorized to inspect, and follow the privacy laws that apply to you.

## 📄 License

[MIT](LICENSE)

<div align="center">

Made with C++ and curiosity. If fastpcap is useful to you, a ⭐ helps others find it.

</div>
