Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
name: PacketForge checks
on:
push:
pull_request:
permissions:
contents: read
jobs:
build-and-test:
runs-on: ubuntu-latest
strategy:
matrix:
sanitizers: ["OFF", "ON"]
steps:
- uses: actions/checkout@v4
- name: Install build dependencies
run: sudo apt-get update && sudo apt-get install -y build-essential cmake libpcap-dev python3
- name: Configure
run: cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug -DPACKETFORGE_SANITIZERS=${{ matrix.sanitizers }}
- name: Build
run: cmake --build build -j2
- name: Test
env:
ASAN_OPTIONS: detect_leaks=1
UBSAN_OPTIONS: halt_on_error=1
run: ctest --test-dir build --output-on-failure
- name: Confirm deterministic fixtures
run: python3 scripts/generate_fixtures.py && git diff --exit-code -- samples/
7 changes: 6 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
/build*/
/reports/
*.o
*.out
sniffer
/sniffer
/forwarder
/packetforge
__pycache__/
40 changes: 40 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
cmake_minimum_required(VERSION 3.16)
project(PacketForge LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
option(PACKETFORGE_SANITIZERS "Enable AddressSanitizer and UndefinedBehaviorSanitizer" OFF)
if(NOT CMAKE_SYSTEM_NAME STREQUAL "Linux")
message(FATAL_ERROR "PacketForge currently targets Linux, including WSL2")
endif()
find_path(PCAP_INCLUDE_DIR pcap/pcap.h REQUIRED)
find_library(PCAP_LIBRARY pcap REQUIRED)
add_library(packetforge_core src/parsers/packet.cpp src/capture/pcap.cpp src/capture/live.cpp
src/detection/config.cpp src/detection/detection.cpp src/flows/flows.cpp
src/statistics/statistics.cpp src/statistics/analysis.cpp src/reporting/reporting.cpp src/cli.cpp)
target_include_directories(packetforge_core PUBLIC include)
target_include_directories(packetforge_core SYSTEM PUBLIC third_party ${PCAP_INCLUDE_DIR})
target_link_libraries(packetforge_core PUBLIC ${PCAP_LIBRARY})
target_compile_options(packetforge_core PUBLIC -Wall -Wextra -Wpedantic -Wconversion -Wshadow)
if(PACKETFORGE_SANITIZERS)
target_compile_options(packetforge_core PUBLIC -fsanitize=address,undefined -fno-omit-frame-pointer)
target_link_options(packetforge_core PUBLIC -fsanitize=address,undefined)
endif()
add_executable(packetforge src/main.cpp)
target_link_libraries(packetforge PRIVATE packetforge_core)
add_executable(sniffer src/sniffer.cpp)
target_link_libraries(sniffer PRIVATE packetforge_core)
add_executable(forwarder src/forwarder.cpp)
target_link_libraries(forwarder PRIVATE packetforge_core)
include(CTest)
if(BUILD_TESTING)
add_executable(packetforge_tests tests/unit.cpp)
target_link_libraries(packetforge_tests PRIVATE packetforge_core)
add_test(NAME unit COMMAND packetforge_tests)
add_test(NAME interfaces COMMAND packetforge interfaces)
set_tests_properties(interfaces PROPERTIES LABELS "host")
find_package(Python3 COMPONENTS Interpreter REQUIRED)
add_test(NAME integration COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/integration.py $<TARGET_FILE:packetforge> ${CMAKE_SOURCE_DIR})
endif()
install(TARGETS packetforge RUNTIME DESTINATION bin)
install(FILES config/rules.json DESTINATION share/packetforge)
53 changes: 53 additions & 0 deletions PROGRESS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# PacketForge implementation progress

Author: Mayank Kumar Karn. Implemented and locally verified on 2026-10-21.
Baseline GitHub commit: `8fd6286`. Feature branch: `feature/packetforge-analyzer-ids`.

## Completed

- [x] Inspect every original file and Git history; compile both original programs.
- [x] Preserve the original GitHub history and leave the unrelated local copy untouched.
- [x] Record original issues and corrections in docs/AUDIT.md.
- [x] C++17 bounded Ethernet/VLAN/ARP/IPv4/IPv6/TCP/UDP/ICMP parser.
- [x] Shared live AF_PACKET and offline libpcap pipeline, CLI and compatibility wrappers.
- [x] Classic PCAP, stored timestamps, explicit unsupported formats and safe errors.
- [x] Bounded directional flows, idle expiry, statistics and visible capacity counters.
- [x] Five configurable IDS rules, windows, exclusions, cooldowns and structured evidence.
- [x] Accurate Firewall Policy Simulation with WOULD_ALLOW / WOULD_BLOCK.
- [x] JSON, alerts/flows CSV and standalone escaped HTML reports.
- [x] Deterministic synthetic fixtures and documented expected results.
- [x] Clean Release CMake build with GCC 15.2.0; no compiler warnings observed.
- [x] All 3 CTest targets passed on host; 10,153 unit assertions include 10,000 random parser inputs.
- [x] 68 CLI/fixture subprocess checks plus JSON/CSV/HTML/config assertions passed without root.
- [x] ASan/UBSan clean build and offline tests passed; exact leak-check limitation below.
- [x] Real live capture verified in isolated WSL2 user/network namespace: UDP frames,
count and idle-duration limits, Ctrl+C, Ethernet binding and explicit promiscuous membership.
- [x] HTML opened in Chromium and screenshot visually inspected.
- [x] Architecture, protocols, rules, testing and interview documentation.
- [x] Interview preparation: 60-second intro, 3-minute explanation, 5-minute demo,
20 technical questions and implementation challenges.
- [x] Automated GitHub Actions standard/sanitizer workflow added.

## Explicit limits

- LeakSanitizer cannot run under the restricted runner's ptrace; local sanitizer
evidence uses `detect_leaks=0`. AddressSanitizer and UBSan passed. This is not a
claim that leak checking passed.
- Live capture was tested with real kernel frames on private loopback and a private
veth interface, not every physical NIC or Windows-side WSL traffic path.
- No PCAPNG, stream/fragment reassembly, DNS parsing, checksum validation, payload
inspection, firewall enforcement or production throughput guarantee.
- Bounded state may miss evidence; reports disclose dropped/evicted/omitted counts.
- Remote CI status and push evidence are recorded at delivery; a workflow file alone
is not a claim that GitHub Actions ran successfully.

## Evidence and commits

Raw build/test/sanitizer output and a real report screenshot are in `docs/evidence/`.
Working offline reports are generated under ignored `reports/`. Run `scripts/demo.sh`
for a fresh, repeatable demonstration. `docs/TESTING.md` explains each check.

- `42fd73c`: initial audit.
- `fe625f4`: bounded parser and live/offline capture pipeline.
- `7af198a`: IDS, flows, statistics, reports and expanded tests.
- Final documentation/validation commit follows these stages; see Git history.
262 changes: 189 additions & 73 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,73 +1,189 @@
# PacketForge — Linux Network Packet Analyzer & L3 Forwarding Engine

A raw-socket packet analyzer built in C++ that captures live network traffic, parses
Ethernet, IPv4, TCP, UDP, and ARP headers, and includes a rule-based L3 forwarding
engine that filters packets by IP/port — simulating basic firewall/router logic.

## Features
- Raw socket packet capture (AF_PACKET, SOCK_RAW)
- Ethernet header parsing (src/dst MAC, EtherType)
- IPv4 header parsing (src/dst IP, protocol, TTL)
- TCP/UDP header parsing (src/dst ports)
- ARP and ICMP detection
- Rule-based L3 forwarding engine (ALLOW/DROP decisions by IP/port)
- Live packet statistics (total, allowed, dropped)

## Project Structure
PacketForge/
- src/sniffer.cpp -> packet capture + header parsing
- src/forwarder.cpp -> sniffer + rule-based forwarding engine
- include/headers.hpp -> Ethernet/IP/TCP/UDP struct definitions
- include/rules.hpp -> rule table + Action enum

## Build

Sniffer only:
g++ src/sniffer.cpp -o sniffer

Forwarding engine:
g++ src/forwarder.cpp -o forwarder

## Run
Requires root (raw sockets need CAP_NET_RAW):

sudo ./sniffer
sudo ./forwarder

## Example Output — Sniffer
--- Packet (98 bytes) ---
Src MAC: 00:15:5d:6e:42:c7
Dst MAC: 00:15:5d:6e:47:2f
EtherType: 0x0800
Src IP: 192.168.1.10
Dst IP: 142.250.193.14
Protocol: 6 (TCP)
Src Port: 52341
Dst Port: 443

## Forwarding Engine
forwarder.cpp inspects each packet's source/destination IP and port, checks it
against a configurable rule table, and decides ALLOW or DROP.

Rule table example:
- any -> any : port 22 -> DROP (block SSH)
- any -> any : port 445 -> DROP (block SMB)
- any -> any : default -> ALLOW

Example output:
Src: 127.0.0.1 -> Dst: 127.0.0.1:22 | Protocol: 6 | Decision: DROP
Src: 172.31.13.131 -> Dst: 192.178.134.138:80 | Protocol: 6 | Decision: ALLOW

[Stats] Total: 20 | Allowed: 18 | Dropped: 2

## Roadmap (V3)
- IPv6 support
- Multithreaded packet capture
- Real packet retransmission (actual forwarding, not just decision logging)
- DHCP/ARP-based dynamic rule updates

## Tech Stack
C++, POSIX raw sockets, Linux networking stack

## Author
Mayank Kumar Karn
# PacketForge

**A passive C++ network packet analyzer and lightweight, explainable intrusion detection system.**

Author: **Mayank Kumar Karn** · C++17 · Linux / Kali / Ubuntu · CMake

PacketForge captures frames with Linux `AF_PACKET`, reads standard Ethernet PCAP
files with libpcap, decodes protocol metadata safely, tracks directional flows,
and reports suspicious activity using configurable rules. The complete offline
demonstration runs without root or internet access.

This project grew from the original PacketForge raw-socket sniffer and first-match
policy demonstration. The original Git history is preserved; the engineering review
is in [docs/AUDIT.md](docs/AUDIT.md). It is an educational investigation tool, not a
replacement for Wireshark, tcpdump, Snort or Suricata.

## Implemented features

- Bounded Ethernet II, up to two 802.1Q/802.1ad VLAN tags, Ethernet/IPv4 ARP,
IPv4 including options, IPv6 with common extension headers, TCP, UDP, ICMP and
basic ICMPv6 metadata decoding.
- Explicit `ok`, `truncated`, `malformed` and `unsupported` parser results.
Non-initial IP fragments never supply transport ports. No network-buffer struct casts.
- Live interface selection, count/duration limits, Ctrl+C/SIGTERM shutdown,
socket-scoped opt-in promiscuous mode, kernel capture timestamps and drop counters.
- Classic PCAP with microsecond/nanosecond timestamps and either byte order.
PCAPNG, non-Ethernet link types and nonchronological captures are explicitly rejected.
- Bounded directional TCP/UDP five-tuples, packet/byte counts, timestamps, TCP flags,
duration, idle expiry, capacity eviction and visible retention counters.
- Five configurable metadata rules: possible TCP SYN port scans, high SYN rate,
high ICMP echo rate, sensitive service observations and connection concentration.
- Sliding windows, exact-IP exclusions, per-rule severity, thresholds, cooldowns,
deduplication, rule counters and bounded detector state.
- Protocol counts, rates, top talkers/ports, unique and active flows, alert totals.
- Consistent alert evidence, timestamps, limitations, investigation recommendations
and the justified T1046 reference for possible service discovery.
- JSON, alerts/flows CSV, and standalone HTML investigation reports. All generated
reports contain metadata, never packet payloads. HTML is escaped; CSV neutralizes
spreadsheet formulas; existing output files are not overwritten.
- **Firewall Policy Simulation** prints `WOULD_ALLOW` / `WOULD_BLOCK` using the
original first-match concept. It does **not** drop, forward or modify traffic.

## Build on Kali / Ubuntu

```bash
sudo apt update
sudo apt install build-essential cmake libpcap-dev python3 libcap2-bin iproute2
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build -j2
ctest --test-dir build --output-on-failure
```

Python is only used by development tests and fixture generation. Runtime dependencies
are the C++ runtime and libpcap. The MIT-licensed nlohmann JSON header is vendored and
pinned, so CMake never downloads dependencies. To build without development tests,
add `-DBUILD_TESTING=OFF`.

## Five-minute offline demonstration

```bash
./build/packetforge --help
./build/packetforge analyze --pcap samples/demo.pcap
./build/packetforge analyze --pcap samples/portscan.pcap --ids
./build/packetforge analyze --pcap samples/synrate.pcap
./build/packetforge analyze --pcap samples/malformed.pcap --verbose
./build/packetforge analyze --pcap samples/sensitive.pcap --policy
./build/packetforge analyze --pcap samples/mixed.pcap \
--rules config/rules.json --report all --output reports/interview
```

Open `reports/interview.html` in a local browser. The same prefix creates
`interview.json`, `interview-alerts.csv` and `interview-flows.csv`.
Choose a new prefix for a repeat run. Without `--output`, the filename contains a
unique export timestamp. `scripts/demo.sh` creates a new demonstration directory.

Actual default-fixture alert examples:

```text
[MEDIUM] POSSIBLE_TCP_PORT_SCAN | 2023-11-14T22:13:20.550000000Z | 192.0.2.10 -> 198.51.100.20 | observed=12 threshold=12 window=10s
[MEDIUM] HIGH_TCP_SYN_RATE | 2023-11-14T22:13:24.950000000Z | 192.0.2.10 -> 198.51.100.20 | observed=100 threshold=100 window=10s
```

The normal mixed fixture contains 9 packets and raises no default alerts. The SYN
rate fixture intentionally repeats an attempt to distinguish packet rate from
unique connection attempts. These are deterministic synthetic captures using
reserved documentation addresses, with no third-party traffic or credentials.
See [samples/README.md](samples/README.md) for every expected outcome.

## Report preview

![PacketForge standalone investigation report](docs/evidence/report-preview.png)

The preview is rendered from the synthetic mixed-protocol report. No external
fonts, scripts, images, services or internet connection are needed by the HTML.

## Live capture

Only inspect an interface or capture file you are authorized to monitor.

```bash
./build/packetforge interfaces
sudo ./build/packetforge capture --interface eth0 --count 100
sudo ./build/packetforge capture --interface eth0 --duration 30 --report html
```

An alternative to running the application as root on a Linux filesystem is:

```bash
sudo setcap cap_net_raw=ep ./build/packetforge
./build/packetforge capture --interface eth0 --count 100
# Remove the capability when it is no longer needed:
sudo setcap -r ./build/packetforge
```

Do not grant capabilities to a binary that untrusted users can replace. Prefer a
Linux home-directory checkout when using file capabilities; Windows-mounted WSL
filesystems may not support them. Rebuilding/replacing a binary can remove its
capabilities. Native Linux or a Linux VM is recommended for predictable NIC
visibility. WSL2 can capture interfaces in its Linux environment, but this does not
mean it sees every Windows interface or all LAN traffic. Wi-Fi monitor mode is not
implemented. Loopback may expose both outgoing and incoming copies.

No promiscuous mode is requested unless `--promiscuous` is supplied. Capture is
passive: there is no packet injection, retransmission, firewall modification,
NFQUEUE, credential interception, persistence or stealth functionality.

## CLI reference

| Command / flag | Behavior |
| --- | --- |
| `interfaces` | Enumerate Linux interface indices and names |
| `capture --interface NAME` | Start passive AF_PACKET capture |
| `analyze --pcap FILE` | Read chronological classic Ethernet PCAP |
| `--count N` | Stop after N packets; positive integer |
| `--duration SECONDS` | Live-only elapsed-time limit; fractions allowed, maximum 86400 |
| `--ids`, `--no-ids` | IDS is enabled by default; explicitly enable or disable |
| `--rules FILE` | Load validated JSON overrides; built-in defaults otherwise |
| `--policy` | Print Firewall Policy Simulation decisions |
| `--verbose` | Print metadata for each packet; no payloads |
| `--quiet` | Suppress immediate alerts and periodic status; keep summary/reports |
| `--report json\|csv\|html\|all` | Export investigation artifacts |
| `--output PREFIX` | Output path prefix, requires `--report`; refuse existing files |
| `--promiscuous` | Live-only socket membership, released when socket closes |
| `--help` | Full command help |

Exit code 0 means successful analysis or graceful live stop, including suspicious
traffic. Exit code 2 means invalid arguments/configuration or a capture/report error.
Malformed individual packets are counted and analysis continues. Corrupt PCAP
containers cause an error. The application does not silently sort huge captures:
nonchronological files must be sorted externally before use.

The historical `sniffer` and `forwarder` CMake targets remain as compatibility
entry points: `./build/sniffer --interface eth0` and
`./build/forwarder --interface eth0`. The latter enables **simulation**. The old
single-file `g++ src/sniffer.cpp` command is superseded by CMake.

## Rules and limitations

[config/rules.json](config/rules.json) contains demonstration defaults, not universal
attack thresholds. Alerts trigger at **count >= threshold** within `(now-window, now]`.
A port-scan threshold cannot be set below two distinct ports. A sensitive service
observation is informational, and a SYN-rate alert does not confirm denial of service.
Tune using an authorized traffic baseline; see [DETECTION_RULES.md](docs/DETECTION_RULES.md).

There is no TCP stream reconstruction, IP fragment reassembly, DNS query parser,
DNS tunneling detector, payload inspection, decryption, checksum validation or
production throughput claim. DNS traffic is represented as UDP metadata only.
Bounded tables can omit evidence; reports expose dropped rule events/keys,
flow evictions, omitted talker observations and unretained alerts. Unique flow
counts become a labeled lower bound when their identity budget is exhausted.

Protocol counters overlap layers. Byte counts mean captured/observed frame bytes;
wire lengths are tracked separately. Rates cover the first-to-last packet interval
and are undefined for zero-duration observations. Frame check sequences, NIC
segmentation/coalescing offloads, capture loss and capture position affect results.

Reports contain IP addresses, MAC-derived packet metadata and service relationships;
handle them as investigation data. Reports are created with POSIX mode 0600 where
the filesystem supports it. No real packet captures are committed to this repository.

## Engineering documentation

- [Architecture and resource bounds](docs/ARCHITECTURE.md)
- [Protocol decoding and validation](docs/PROTOCOLS.md)
- [Detection algorithms and tuning](docs/DETECTION_RULES.md)
- [Tests, sanitizers and live verification](docs/TESTING.md)
- [Interview explanations and demo](docs/INTERVIEW_PREP.md)
- [Initial audit and corrections](docs/AUDIT.md)
- [Implementation status](PROGRESS.md)
Loading
Loading