diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..b80c077 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,42 @@ +name: ci + +on: + push: + pull_request: + +jobs: + build-and-test: + runs-on: ubuntu-24.04 + strategy: + fail-fast: false + matrix: + pcap: [with-libpcap, without-libpcap] + opt: [-O2, "-O1 -g -fsanitize=address,undefined"] + + steps: + - uses: actions/checkout@v4 + + - name: install deps + run: | + sudo apt-get update -qq + sudo apt-get install -y build-essential libpcap-dev python3 tcpdump iputils-ping + if [ "${{ matrix.pcap }}" = "without-libpcap" ]; then + sudo apt-get remove -y libpcap-dev libpcap0.8-dev || true + fi + + - name: build + run: | + make clean + make -j"$(nproc)" OPT="${{ matrix.opt }}" LDFLAGS="${{ contains(matrix.opt,'sanitize') && '-fsanitize=address,undefined' || '' }}" + + - name: unit tests + run: make test OPT="${{ matrix.opt }}" + + - name: end-to-end tests + run: sudo -E env "PATH=$PATH" bash tests/e2e.sh + if: matrix.opt == '-O2' + # runs in both matrix legs: e2e.sh skips the kernel-filter checks when + # the build has no libpcap + + - name: version and capabilities + run: ./bin/pktsniff-server --version diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3b04e9e --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +bin/ +*.pcap +*.pcap.* +*.o +*.d +core diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..5870b2d --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,51 @@ +# Contributing + +Small C11 project, no dependencies worth arguing about. `make test` and, if you can, `sudo tests/e2e.sh` are the whole gate. + +## Get set up + +```sh +git clone https://github.com/bas3line/packets +cd packets +sudo apt install build-essential libpcap-dev python3 tcpdump iputils-ping +make && make test +``` + +The end-to-end suite needs root (it opens a raw socket) and confines itself to loopback on port 8899: + +```sh +sudo tests/e2e.sh +``` + +## What runs in CI + +`.github/workflows/ci.yml` builds the tree with and without libpcap, at `-O2` and under ASan/UBSan, runs the unit tests in every combination, and runs `tests/e2e.sh` for the `-O2` build. A change that only works when libpcap is installed will fail there. + +## Ground rules + +- **Never trust a length.** Anything that reads a packet, a frame or a config string is handed hostile input in `tests/`. `ps_decode` must survive being given the first *n* bytes of any packet, for every *n* — that is what `test_every_truncation` checks, and it is the cheapest bug you will ever find. +- **The stream stays frame-atomic.** If you touch `src/outbuf.c`, keep the invariant: a frame with bytes on the wire is never dropped. `tests/test_outbuf.c` simulates short writes and a stuck reader; make it pass. +- **Server does little, client does the thinking.** Capture, timestamp, forward, optionally record. Dissection, filtering and rendering belong in the client, where a person is watching. +- **No new dependencies** unless they earn their place. libpcap is optional and stays optional. +- **Match the surrounding C**: `ps_` prefixes, `goto done` for cleanup, one header per module in `include/`, comments that explain *why* something is not obvious. +- Warnings are errors in spirit — the tree builds clean with `-Wall -Wextra -Wshadow -Wstrict-prototypes -Wmissing-prototypes -Wvla -Wpointer-arith` and `-Werror`. + +## Adding something + +| you want to | touch | +| --- | --- | +| dissect another protocol | `src/decode.c`, add a case in `tests/test_decode.c` with a hand-built frame | +| add a display filter key | `src/filter.c` (parse + match), `tests/test_filter.c`, the table in `README.md` | +| change the wire format | `include/proto.h`, bump `PS_PROTO_VERSION`, update `docs/PROTOCOL.md` | +| add a server or client flag | `src/main_server.c` / `src/main_client.c`, `--help` text, the option table in `README.md` | +| touch capture behaviour | `src/capture.c`; explain the change in the PR, it is the hard part to test | + +## Commits and PRs + +- Imperative subject, then a body that says what was wrong and what is now true. "Fix", "improve" and "refactor" on their own say nothing. +- One idea per PR. If it needs "and also", it is two PRs. +- Paste the relevant test output in the description — `make test` summary and, for anything involving capture or the stream, the `tests/e2e.sh` result. + +## Reporting a bug + +Include the server log lines around the failure, `pktsniff-server --version` (it prints whether libpcap is compiled in), and what `--filter`/`-F` you were using. If the client printed `protocol error on stream`, that is a framing bug and I would like the frames you were seeing: `-v` and the head of the server log usually settle it. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..509d2cf --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Bas3line + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..a0ba338 --- /dev/null +++ b/Makefile @@ -0,0 +1,103 @@ +# pktsniff - build system +# +# make build bin/pktsniff-server and bin/pktsniff-client +# make test build and run the unit tests (no root needed) +# make asan build with AddressSanitizer/UBSan into bin/asan/ +# make install install into $(PREFIX)/bin (default /usr/local) +# make clean +# +# libpcap is optional: with it, the server accepts tcpdump-style BPF filters +# (--filter). Without it the server still works and the client-side --filter is +# unaffected. + +BIN := bin +PREFIX ?= /usr/local +CC ?= cc +CSTD := -std=c11 +WARN := -Wall -Wextra -Wshadow -Wstrict-prototypes -Wmissing-prototypes -Wvla -Wpointer-arith +OPT ?= -O2 -g +CPPFLAGS += -D_GNU_SOURCE -Iinclude +CFLAGS += $(CSTD) $(WARN) $(OPT) -fstack-protector-strong -fno-omit-frame-pointer +LDFLAGS += +LDLIBS += + +PCAP_CFLAGS := $(shell pkg-config --cflags libpcap 2>/dev/null) +PCAP_LIBS := $(shell pkg-config --libs libpcap 2>/dev/null) +ifeq ($(strip $(PCAP_LIBS)),) + PCAP_LIBS := $(shell echo '-lpcap' | $(CC) -x c - -o /dev/null -lpcap >/dev/null 2>&1 && echo -lpcap) +endif +ifneq ($(strip $(PCAP_LIBS)),) + CPPFLAGS += -DPS_HAVE_PCAP + CFLAGS += $(PCAP_CFLAGS) + SERVER_LIBS += $(PCAP_LIBS) +endif + +LIB_SRCS := src/log.c src/util.c src/stats.c src/proto.c src/decode.c src/filter.c \ + src/pcap.c src/outbuf.c +SERVER_SRCS := src/main_server.c src/server.c src/capture.c +CLIENT_SRCS := src/main_client.c src/client.c + +LIB_OBJS := $(LIB_SRCS:src/%.c=$(BIN)/obj/%.o) +SERVER_OBJS := $(SERVER_SRCS:src/%.c=$(BIN)/obj/%.o) +CLIENT_OBJS := $(CLIENT_SRCS:src/%.c=$(BIN)/obj/%.o) + +PS_SERVER_BIN := pktsniff-server +PS_CLIENT_BIN := pktsniff-client +SERVER_BIN := $(BIN)/$(PS_SERVER_BIN) +CLIENT_BIN := $(BIN)/$(PS_CLIENT_BIN) + +all: $(SERVER_BIN) $(CLIENT_BIN) + +$(BIN)/obj/%.o: src/%.c + @mkdir -p $(dir $@) + $(CC) $(CPPFLAGS) $(CFLAGS) -MMD -MP -c $< -o $@ + +$(SERVER_BIN): $(LIB_OBJS) $(SERVER_OBJS) + @mkdir -p $(dir $@) + $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $^ $(SERVER_LIBS) $(LDLIBS) + +$(CLIENT_BIN): $(LIB_OBJS) $(CLIENT_OBJS) + @mkdir -p $(dir $@) + $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $^ $(LDLIBS) + +-include $(LIB_OBJS:.o=.d) $(SERVER_OBJS:.o=.d) $(CLIENT_OBJS:.o=.d) + +# ---- tests ---- +TEST_BIN := $(BIN)/tests +TEST_SRCS := $(wildcard tests/test_*.c) +TEST_PROGS := $(TEST_SRCS:tests/%.c=$(TEST_BIN)/%) + +$(TEST_BIN)/%: tests/%.c $(LIB_OBJS) + @mkdir -p $(dir $@) + $(CC) $(CPPFLAGS) $(CFLAGS) -Isrc -o $@ $< $(LIB_OBJS) $(LDLIBS) + +test: $(TEST_PROGS) + @fail=0; for t in $(TEST_PROGS); do echo "== $$t"; ./$$t || fail=1; done; \ + if [ $$fail -eq 0 ]; then echo "all tests passed"; else echo "TESTS FAILED"; exit 1; fi + +# ---- sanitizer build ---- +asan: + $(MAKE) OPT='-O1 -g -fsanitize=address,undefined -fno-sanitize-recover=all' \ + LDFLAGS='-fsanitize=address,undefined' BIN=bin/asan all test + +install: all + install -d $(DESTDIR)$(PREFIX)/bin + install -m 0755 $(SERVER_BIN) $(DESTDIR)$(PREFIX)/bin/$(PS_SERVER_BIN) + install -m 0755 $(CLIENT_BIN) $(DESTDIR)$(PREFIX)/bin/$(PS_CLIENT_BIN) + +install-service: all + install -m 0644 packaging/pktsniff.service /etc/systemd/system/pktsniff.service + systemctl daemon-reload + @echo "edit /etc/pktsniff.conf then: systemctl enable --now pktsniff" + +clean: + rm -rf $(BIN) + +distclean: clean + rm -rf bin + +print-config: + @echo "CC = $(CC)" + @echo "libpcap = $(if $(SERVER_LIBS),yes,no)" + +.PHONY: all test asan install install-service clean distclean print-config diff --git a/README.md b/README.md index 27279c7..948b1ae 100644 --- a/README.md +++ b/README.md @@ -1 +1,210 @@ -# **For educational and testing purposes only.** +
+ + + + + pktsniff: packets live from any server + + + +
+
+ +Capture packets on a server, watch them on your laptop, keep the `.pcap`.
+Raw sockets, kernel BPF filters, and a stream that never sends you half a frame. + +[install](#install) · [run it](#run-it) · [server](#server) · [client](#client) · [filters](#display-filters) · [recipes](#recipes) · [how it's built](#how-its-built) · [contributing](CONTRIBUTING.md) + +[![by @bas3line](https://img.shields.io/badge/by-%40bas3line-181717?logo=github&logoColor=white)](https://github.com/bas3line) +[![CI](https://github.com/bas3line/packets/actions/workflows/ci.yml/badge.svg)](https://github.com/bas3line/packets/actions/workflows/ci.yml) +[![MIT](https://img.shields.io/badge/license-MIT-181717)](LICENSE) +[![C11](https://img.shields.io/badge/C-11-181717?logo=c&logoColor=white)](Makefile) +[![Linux](https://img.shields.io/badge/Linux-AF__PACKET-181717?logo=linux&logoColor=white)](src/capture.c) +[![libpcap](https://img.shields.io/badge/libpcap-optional-181717)](Makefile) + +
+ +
+ +Written in C by [@bas3line](https://github.com/bas3line). Two programs: one captures on the machine you can't sit in front of, the other sits in front of you. The server hands out raw link-layer frames with their kernel timestamps over a length-prefixed binary stream; the client decodes them, filters them, prints them, and can write them straight into a `.pcap` that Wireshark opens. Nothing is lost in translation, and nothing gets lost when your laptop reads slower than the wire. + +``` +$ sudo pktsniff-server -i eth0 -f 'tcp port 443 or udp port 53' -w /var/cap/eth0.pcap +11:02:14 [inf] pktsniff 2.0.0 capturing on eth0 (snap 262144, promisc on, filter "(tcp port 443 or udp port 53) and not tcp port 8888") +11:02:14 [inf] streaming on port 8888 (max 8 clients) +11:02:14 [inf] recording to /var/cap/eth0.pcap +11:02:19 [inf] seen=48211 tcp=41992 udp=6123 icmp=6 other=90 bytes=58.4 MB clients=1 drops=0 + +$ pktsniff-client 203.0.113.10 -F 'proto:tls or proto:dns' +11:02:21.112321 #000001 TCP 10.0.0.5:53112 -> 1.1.1.1:443 74 B ttl=64 SYN | TLS SNI=cloudflare.com +11:02:21.112947 #000002 DNS 10.0.0.5:40233 -> 1.1.1.1:53 71 B ttl=64 | DNS A example.com +11:02:21.113402 #000003 TCP 1.1.1.1:443 -> 10.0.0.5:53112 1460 B ttl=57 ACK,PSH | TLS handshake +``` + +## Why + +Every "remote sniffer" I'd used printed packet lines to a terminal and threw them away. The lines you actually wanted were the ones scrolled past, the hexdump was truncated into unreadable mush, and there was no way to hand a colleague the traffic afterwards. So: real capture, real filters, and a format that survives the trip. The stream is framed, so a slow reader loses whole packets and never the alignment; the output is either a text line you can grep, JSON you can pipe into `jq`, or a `.pcap` you can open in Wireshark. The server stays deliberately stupid — it captures, timestamps, and forwards bytes — because the interesting decisions belong where a person is looking. + +## Install + +```sh +git clone https://github.com/bas3line/packets +cd packets +make -j"$(nproc)" +sudo make install # /usr/local/bin/pktsniff-{server,client} +``` + +A C11 compiler and Linux headers. `libpcap-dev` is optional and only enables the server's `--filter`; `make print-config` tells you whether it was found. To run the server without full root: + +```sh +sudo setcap cap_net_raw,cap_net_admin=eip /usr/local/bin/pktsniff-server +``` + +## Run it + +```sh +# on the box +sudo pktsniff-server -i eth0 + +# on your machine +pktsniff-client 203.0.113.10 +``` + +Open TCP 8888 (or `-p` whatever you like) between them. Only that port; the client needs no privileges and no libpcap. + +| script | | +| --- | --- | +| `make` | build both binaries into `bin/` | +| `make test` | unit tests: framing, dissection, filters, the send queue | +| `sudo tests/e2e.sh` | live checks on loopback: capture, drops, `.pcap`, JSON, limits | +| `make asan` | rebuild and rerun the unit tests under ASan + UBSan | +| `make install` | install to `$(PREFIX)/bin` | +| `sudo make install-service` | install the systemd unit in `packaging/` | + +## Server + +```sh +sudo pktsniff-server -i eth0 -f 'tcp port 443' -w cap.pcap --pcap-rotate-mb 100 +``` + +| flag | | +| --- | --- | +| `-i, --iface NAME` | interface to capture on, default `any` (all of them at once) | +| `-f, --filter BPF` | kernel filter in tcpdump syntax; compiled by libpcap and attached with `SO_ATTACH_FILTER` | +| `-s, --snaplen N` | bytes kept per packet, default 262144 | +| `--no-promisc` | leave the interface out of promiscuous mode | +| `--direction in\|out\|both` | drop traffic this host sent, received, or neither | +| `--capture-control` | also capture the stream's own TCP connection | +| `-p, --port N` | TCP port to serve on, default 8888 | +| `-b, --bind ADDR` | bind address, default `0.0.0.0` | +| `-m, --max-clients N` | concurrent clients, default 8 | +| `--client-buffer BYTES` | queue per slow client before dropping, default 4 MiB | +| `-w, --pcap FILE` | record to a `.pcap` as well | +| `--pcap-rotate-mb N` | start a new file every N MiB | +| `-t, --stats-interval N` | seconds between status lines, default 5 | +| `-q, -v` | no status lines, or debug logging | + +The server excludes its own control connection from the capture (`not tcp port `) unless you ask for `--capture-control`: capturing `lo` while streaming over it is otherwise a loop that feeds itself. + +## Client + +```sh +pktsniff-client 203.0.113.10 -F 'proto:dns' -d 30 -x 64 +``` + +| flag | | +| --- | --- | +| `[host]`, `-H, --host` | server address, default `127.0.0.1` | +| `-p, --port N` | server port, default 8888 | +| `-F, --filter EXPR` | display filter, see [filters](#display-filters) | +| `-c, --count N` | stop after exactly N matching packets | +| `-d, --duration N` | stop after N seconds | +| `-x, --hex N` | hexdump the first N bytes of each match | +| `--json FILE` | newline-delimited JSON, `-` for stdout | +| `-w, --pcap FILE` | write matching packets to a `.pcap` | +| `--pcap-rotate-mb N` | rotate that file every N MiB | +| `--stats-interval N`, `--no-stats` | the counter line, every 5 s by default | +| `-C, --color`, `--no-color` | force or disable colour (default: only on a tty) | +| `--reconnect` | survive a server restart instead of exiting | +| `-q, -v` | no banner or summary, or debug logging | + +## Display filters + +Terms are AND'ed, groups are joined with `or` (or `|`), and `!` negates a term. Single terms have shorthands. + +``` +proto:tcp proto:udp proto:icmp proto:icmp6 proto:arp proto:ip6 +proto:dns proto:tls proto:http +port:443 sport:53 dport:53 +host:10.0.0.1 host:10.0.0.0/8 src:… dst:… +contains:GET bytes:>1400 +``` + +```sh +pktsniff-client 203.0.113.10 -F 'proto:tls or proto:dns' +pktsniff-client 203.0.113.10 -F 'host:10.0.0.0/8 !tcp' +pktsniff-client 203.0.113.10 -F 'bytes:>1400' -x 32 +``` + +`-F` is a display filter and runs on your machine. `--filter` on the server is tcpdump syntax and runs in the kernel. Different tools, different grammar, and the second one is the one that saves bandwidth. + +## Recipes + +```sh +# Watch DNS on a busy box without drowning the terminal +sudo pktsniff-server -i eth0 -f 'udp port 53' & +pktsniff-client -F 'proto:dns' -d 30 + +# Export the HTTP traffic from the last minute as a shareable capture +pktsniff-client 203.0.113.10 -F 'proto:http or port:443' -w subset.pcap -d 60 + +# A day of rotating recordings on the server, nothing sent to anyone +sudo pktsniff-server -i eth0 -w /var/cap/eth0.pcap --pcap-rotate-mb 100 + +# Which hosts is this box talking TLS to? +pktsniff-client 203.0.113.10 --json - | jq -r 'select(.app|startswith("TLS SNI"))|.app' + +# Everything on one port, as JSON, to a file, with no privileges at all +pktsniff-client 203.0.113.10 -F 'port:5432' --json pg.ndjson -d 120 +``` + +## What it can see + +Ethernet II, 802.1Q and QinQ VLAN stacks, Linux cooked capture, BSD loopback, bare IP; ARP, IPv4 with options and fragmentation, IPv6 with extension headers; TCP with flags, sequence numbers, window and MSS, UDP, ICMP and ICMPv6; and enough application awareness to answer "who is this talking to": DNS question names and record types, TLS ClientHello SNI, HTTP request lines. + +No stream reassembly and no full protocol zoo — just the part that tells you what is going on. + +## How it's built + +``` + ┌────────┐ AF_PACKET ┌─────────────────┐ framed TCP ┌─────────────────┐ + │ NIC │ ───────────► │ pktsniff-server │ ──────────────► │ pktsniff-client │ + └────────┘ kernel BPF │ capture → queue │ HELLO PACKET │ decode → filter │ + │ → pcap on disk │ STATS BYE ERR │ → render / pcap │ + └─────────────────┘ └─────────────────┘ +``` + +- **The stream is frames, not lines.** 12-byte header with magic, version, type and length, then the payload. The client buffers until a frame is whole, so a packet split across TCP segments cannot break it. Layout in [docs/PROTOCOL.md](docs/PROTOCOL.md). +- **Back pressure never desynchronises.** Each client has a bounded queue of whole frames. When it fills, only frames with no bytes on the wire yet are dropped — dropping a partly-sent frame is exactly how a client ends up reading garbage. That queue has its own test suite. +- **Kernel timestamps, kernel filters.** `SO_TIMESTAMPNS` for arrival times, `SO_ATTACH_FILTER` for libpcap-compiled BPF, `PACKET_STATISTICS` for the drop count you can see in the status line. +- **One epoll loop, nothing blocks.** Capture socket, listen socket and every client share it, so one slow reader cannot stall the capture. + +[docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) for the module map and the reasoning, [docs/SETUP.md](docs/SETUP.md) for firewall, capabilities, systemd and troubleshooting. + +## Repo layout + +| path | | +| --- | --- | +| `include/`, `src/` | one header per module: capture, dissector, protocol, queue, pcap, filter, stats | +| `tests/` | `test_*.c` unit suites and `e2e.sh`, the live one | +| `docs/` | protocol, architecture, setup | +| `scripts/` | build and server/client setup helpers | +| `packaging/` | systemd unit | + +## Limits worth knowing + +Linux only — it is `AF_PACKET` all the way down. The stream is plaintext and unauthenticated, so bind it to a private address, tunnel it or firewall the port. One capture socket and one thread: multiple gigabits need `-f` to trim in the kernel, and kernel drops are reported rather than hidden. + +## Legal + +Capture only traffic you own or have permission to monitor. Educational and testing use; see [LICENSE](LICENSE). diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..2bf49b4 --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,136 @@ +# Architecture + +Two small programs, one shared library of modules. + +``` +include/ src/ + common.h endian helpers, link types, limits + log.h log.c leveled logging to stderr + util.h util.c allocation, string, number helpers + proto.h proto.c framing, codecs, incremental reader + decode.h decode.c bounds-checked dissection + rendering + filter.h filter.c client-side display filter + pcap.h pcap.c classic .pcap writer + outbuf.h outbuf.c frame-atomic send queue + stats.h stats.c counters + wire (de)serialisation + capture.h capture.c AF_PACKET capture, BPF, timestamps (server) + server.h server.c epoll loop, client fan-out (server) + client.h client.c connect, decode, filter, render (client) + main_server.c / main_client.c argument parsing +``` + +Rules of the road: + +- `decode.c` never trusts a length. Every field is bounds-checked, and every + truncation of the input is handled (`tests/test_decode.c` cuts a valid frame + at every possible offset). +- Modules below `server.c`/`client.c` know nothing about sockets or threads. + `outbuf`, `proto` and `decode` are unit-testable in isolation, and they are. +- The wire format and the counters struct are defined once and validated at + compile time, so they cannot drift. + +## Server pipeline + +``` +epoll_wait + ├─ listen fd → accept4, greet with HELLO, register EPOLLOUT + ├─ capture fd → ps_capture_read (recvmsg, SCM_TIMESTAMPNS) + │ → ps_decode (cheap classification for counters) + │ → ps_pcap_write (if recording) + │ → ps_packet_encode into a reusable staging buffer + │ → broadcast: ps_outbuf_push + opportunistic send per client + └─ client fd → flush queue; EPOLLERR → drop client +every --stats-interval → STATS frame + one summary log line +``` + +Design points: + +- **The capture loop never blocks.** Capture socket, listen socket and client + sockets are all non-blocking and multiplexed in one epoll loop, so no single + slow reader stalls capture. Up to `EPOLL_BATCH` frames are drained per wakeup + to amortise `epoll_wait`. +- **Kernel receive timestamps** (`SO_TIMESTAMPNS`) are used when present, so the + timestamp reflects when the driver saw the packet, not when userspace got it. + Timestamps survive the trip and end up in the `.pcap`, which is why a + client-side capture is still useful evidence. +- **Kernel-space filtering.** `--filter` is compiled by libpcap + (`pcap_open_dead` + `pcap_compile`) and attached with `SO_ATTACH_FILTER`, so + the kernel discards uninteresting traffic before it costs us anything. If the + build has no libpcap, the server fails fast at startup with a clear message + instead of silently ignoring the filter. +- **The control connection is excluded** from capture by default. Streaming a + capture over TCP while capturing TCP is a feedback loop; the default filter + becomes `(user filter) and not tcp port `. +- **Kernel drops are reported.** `PACKET_STATISTICS` is read-and-clear, so the + counter is accumulated and surfaced as `dropped_kernel`. +- **`AF_PACKET` on "any"** captures on all interfaces at once (with + `linktype = Ethernet`), which is what you want on a router or a busy box. + +## Deliveries: `outbuf` + +The interesting part of the server is per-client back pressure. `ps_outbuf` is +a byte ring with an explicit frame-boundary cursor: + +``` +data: [ sent ][ partially sent frame ][ queued frames ... ] + ^ ^ ^ ^ + 0 r frame_start w +``` + +- `r` is the send cursor; anything before it is already on the wire. +- `frame_start` is the oldest frame that still owes bytes. +- On overflow, only frames at or after `r` may be dropped: dropping a partially + sent frame would leave the peer mid-frame, which is exactly how the naive + version of this tool desynchronised clients under load. + +`tests/test_outbuf.c` drives this with a fake sink that accepts 0–40 bytes per +call and a producer that outruns it, then re-parses the delivered byte stream to +prove every frame arrives whole and in order. + +## Client pipeline + +``` +poll(socket, 500 ms) + → recv → ps_reader_feed → ps_reader_next (whole frames only) + ├─ HELLO → remember linktype/snaplen, open the .pcap lazily + ├─ PACKET → ps_decode → ps_filter_match → render | json → pcap + ├─ STATS → counters for the periodic line + └─ BYE/ERR → stop +``` + +- Output modes are mutually exclusive per stream: coloured text to stdout, or + NDJSON to a file/stdout. `--quiet` removes the banner so stdout stays pipeable. +- Colour is auto-detected from `isatty(stdout)`; `-C` forces it, `--no-color` + disables it. Status and warnings always go to stderr. +- `--reconnect` re-enters the connect path with capped exponential backoff and + resets the reader, so a server restart is survivable. +- `--count` is exact: once N matching packets have been emitted the loop stops + even if more frames are already buffered. + +## Dissection + +`ps_decode` fills `struct ps_decoded` from `(data, caplen, linktype)`: + +- Link: Ethernet II, 802.1Q / QinQ / 0x9100 VLAN stacks, Linux SLL v1/v2, BSD + loopback (`DLT_NULL`/`DLT_LOOP`), bare IP (`DLT_RAW`). +- Network: IPv4 (incl. options, fragmentation), IPv6 (hop-by-hop, routing, + destination options, fragment headers), ARP. +- Transport: TCP (flags, seq/ack, window, MSS option), UDP, ICMP, ICMPv6. +- Application: DNS question names and types, TLS ClientHello SNI, HTTP request + lines. Cheap heuristics, no stream reassembly — enough to answer "who is this + box talking to and how". + +Everything is bounded by `caplen`: the dissector can be handed any truncation of +any packet without reading out of bounds. + +## Testing + +| what | how | +| --- | --- | +| framing, reader, codecs | `tests/test_proto.c` (byte-at-a-time feed, garbage rejection) | +| dissection | `tests/test_decode.c` (built frames, every truncation offset, VLAN, ARP, v6, DNS, TLS SNI) | +| filter grammar | `tests/test_filter.c` (AND/OR/negation, CIDR, errors) | +| queue under pressure | `tests/test_outbuf.c` (partial writes, drops, stream re-parse) | +| end to end | `tests/e2e.sh` (root: capture, filter, pcap readability, drops, json, limits, signals) | + +`make asan` rebuilds and reruns the unit tests with ASan + UBSan. diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md new file mode 100644 index 0000000..a10e06c --- /dev/null +++ b/docs/PROTOCOL.md @@ -0,0 +1,100 @@ +# pktsniff wire protocol (version 1) + +One TCP connection, one direction of application data (server → client). The +server never reads anything but EOF; the client never writes. Everything is +big-endian and length-prefixed. + +## Frame + +``` + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 ++-------------------------------+---------------+ +| magic (u32) | version (u16) | magic = 0x50534E46 "PSNF" ++-------------------------------+---------------+ +| type (u16) | length (u32) | ++---------------+-------------------------------+ +| payload[length] | ++-----------------------------------------------+ +``` + +12-byte header, then exactly `length` payload bytes. A frame is never split +across messages: the receiver must buffer until `length` bytes are available +(`ps_reader_*` in `src/proto.c` does this). Maximum payload accepted is 2 MiB; +anything larger is treated as stream corruption. + +| type | name | payload | +|------|--------|--------------------------------------------| +| 1 | HELLO | `ps_hello_encode` | +| 2 | PACKET | `ps_pkt_hdr` + link-layer bytes | +| 3 | STATS | 14 × u64 counters | +| 4 | BYE | empty | +| 5 | ERR | NUL-terminated UTF-8 message | + +## HELLO (type 1) + +Sent once, immediately after accept, before any PACKET frame. + +``` +u16 linktype DLT value (1 = Ethernet, 113 = Linux SLL, …) +u32 snaplen capture snapshot length + hostname NUL-terminated, server's name + iface NUL-terminated, interface or "any" + filter NUL-terminated, effective kernel BPF filter ("" if none) +``` + +The client uses `linktype` and `snaplen` to write a `.pcap` that matches the +capture exactly. A HELLO whose strings are not terminated is rejected. + +## PACKET (type 2) + +``` +u32 ts_sec capture timestamp, seconds since the epoch +u32 ts_usec microseconds +u32 caplen bytes of link-layer data present +u32 origlen original wire length +u8 data[caplen] raw frame, exactly as delivered by AF_PACKET +``` + +`data` is untouched link-layer bytes so it can be written straight into a +`.pcap` record. The server does not decode beyond a rough protocol counter. + +## STATS (type 3) + +Fourteen `u64` values, in this order (the order is defined once, by +`PS_COUNTER_FIELDS` in `include/stats.h`, and a `_Static_assert` in +`src/stats.c` keeps it in step with the struct): + +``` +seen captured bytes tcp udp icmp arp dns tls ipv6 fragmented other +dropped_kernel dropped_client +``` + +Sent every `--stats-interval` seconds and only when a client is connected. + +## ERR / BYE (types 5 / 4) + +`ERR` carries a human-readable NUL-terminated string (for example +`server busy: no free client slot` when `--max-clients` is exhausted) and ends +the session. `BYE` has an empty payload and means the server shut down cleanly. + +## Delivery guarantees + +The server queues whole frames per client in a bounded buffer +(`--client-buffer`, default 4 MiB). + +- If the queue is full, only **wholly unsent** frames are discarded. +- A frame that has partly been written to the socket is never dropped, because + the peer would then be left mid-frame. +- Drops are counted in `dropped_client` (and in the server's log line), so a + client can always tell how much it missed from `seen - captured`. + +Consequences: the byte stream is always a valid sequence of frames, and the +message shapes above are exactly what arrives. A client that reads slowly sees +gaps in its packet sequence, never a broken frame. + +## Not in v1 + +- Client → server control channel (per-client filters, pause/resume). +- Compression, encryption or authentication. +- Multiple capture interfaces in one stream. diff --git a/docs/SETUP.md b/docs/SETUP.md new file mode 100644 index 0000000..7170c17 --- /dev/null +++ b/docs/SETUP.md @@ -0,0 +1,110 @@ +# Setup + +## Server (Debian / Ubuntu) + +```bash +sudo apt update +sudo apt install -y build-essential libpcap-dev git + +git clone https://github.com/Bas3line/packets +cd packets +make -j"$(nproc)" +sudo make install # /usr/local/bin/pktsniff-{server,client} + +# Optional: run without full root +sudo setcap cap_net_raw,cap_net_admin=eip /usr/local/bin/pktsniff-server +``` + +`libpcap-dev` is only needed for server-side `--filter`. Without it, +`make print-config` reports `libpcap = no` and the server rejects `--filter` +with an explanatory error; the client's `-F` still works. + +## Client (any Linux) + +```bash +sudo apt install -y build-essential git +git clone https://github.com/Bas3line/packets && cd packets +make -j"$(nproc)" # same tree, you only need bin/pktsniff-client +``` + +The client needs no privileges and no libpcap. + +## Firewall + +Only the one TCP port matters (default 8888): + +```bash +sudo ufw allow 8888/tcp +# or restrict to your workstation +sudo ufw allow from 203.0.113.7 to any port 8888 proto tcp +sudo iptables -A INPUT -p tcp --dport 8888 -j ACCEPT +``` + +Remember cloud security groups: inbound TCP 8888 from your IP. + +## First run + +```bash +# server +sudo pktsniff-server --list-interfaces +sudo pktsniff-server -i eth0 + +# workstation +pktsniff-client 203.0.113.10 -F 'proto:dns or proto:tls' +``` + +## As a service + +```bash +sudo cp packaging/pktsniff.service /etc/systemd/system/ +sudo editor /etc/systemd/system/pktsniff.service # set --iface / --filter / -w +sudo systemctl daemon-reload && sudo systemctl enable --now pktsniff +journalctl -u pktsniff -f +``` + +Or `sudo make install-service` after editing `packaging/pktsniff.service`. + +## Troubleshooting + +**`AF_PACKET socket: Operation not permitted`** +Run as root, or `setcap cap_net_raw,cap_net_admin=eip` on the binary. + +**`no such interface 'eth0'`** +Names differ on modern systems (`ens5`, `enp0s3`). Use `--list-interfaces`. + +**Client connects but stays silent** +Check the server's counter line — `seen=` should climb. If it does not, the +capture is filtered out: try `-f ''` and make sure there is traffic on that +interface (a NIC with no traffic is not the same as a broken sniffer). If you +capture on `any`, promiscuous mode is not applied. + +**`bad filter expression: …`** +`--filter` uses libpcap syntax (`tcp port 443 and host 10.0.0.1`), not the +client's `-F` syntax (`proto:tcp port:443`). Different tools, different grammar. + +**`server busy: no free client slot`** +More clients than `--max-clients`. Raise it, or kill stale clients. + +**`drops=` climbs while `clients=1`** +The client cannot read as fast as the link produces, so whole frames are being +discarded for it (`--client-buffer` to give it more room, `-F` on the server to +send less, or `--no-color`/`--no-stats`/`-X` on the client to make it cheaper). + +**`protocol error on stream`** +Should not happen in normal use; it means a frame header was unreadable. The +client reconnects if `--reconnect` is set. Please include the server log line +and the output of `pktsniff-server --version` in a report. + +**Port already in use** +`bind port 8888: Address already in use` — another server (or an old one) is +running: `pgrep -a pktsniff-server`. + +## Verifying a capture + +```bash +tcpdump -r subset.pcap -nn | head +tshark -r subset.pcap -q -z io,phs +``` + +Both sides write the same classic format (microsecond resolution, Ethernet), +so anything that reads `.pcap` reads these. diff --git a/include/capture.h b/include/capture.h new file mode 100644 index 0000000..f09491d --- /dev/null +++ b/include/capture.h @@ -0,0 +1,50 @@ +/* capture.h - AF_PACKET capture with optional libpcap-compiled BPF. + * + * Linux only. The socket is non-blocking and pollable so the server can + * multiplex it with client sockets in one epoll loop. + */ +#ifndef PS_CAPTURE_H +#define PS_CAPTURE_H + +#include + +#include "common.h" +#include "proto.h" + +#define PS_IFACE_AUTO "" + +enum ps_direction { + PS_DIR_BOTH = 0, + PS_DIR_IN = 1, /* ignore packets we sent ourselves */ + PS_DIR_OUT = 2 +}; + +struct ps_capture { + int fd; + uint16_t linktype; + uint32_t snaplen; + char iface[32]; + uint32_t ifindex; + int promisc; + enum ps_direction direction; + uint64_t drops_prev; /* kernel counter is read-and-clear, so accumulate */ + uint64_t drops_total; +}; + +/* iface may be "" / "any" to capture on all interfaces. `bpf_expr` may be NULL. + * Returns 0 on success; on failure fills err and returns -1. */ +int ps_capture_open(struct ps_capture *cap, const char *iface, uint32_t snaplen, int promisc, + enum ps_direction direction, const char *bpf_expr, char *err, size_t errsz); + +/* Non-blocking read of exactly one frame. Returns >0 (bytes captured), + * 0 when nothing is pending, -1 on fatal error. */ +int ps_capture_read(struct ps_capture *cap, uint8_t *buf, size_t bufsz, struct ps_record *rec, + int *outgoing); + +void ps_capture_update_drops(struct ps_capture *cap); +void ps_capture_close(struct ps_capture *cap); + +/* Human-readable interface list, one per line, for --list-interfaces. */ +void ps_capture_list_interfaces(FILE *out); + +#endif /* PS_CAPTURE_H */ diff --git a/include/client.h b/include/client.h new file mode 100644 index 0000000..69d23f1 --- /dev/null +++ b/include/client.h @@ -0,0 +1,26 @@ +/* client.h - consumer side: decode, filter, render, record. */ +#ifndef PS_CLIENT_H +#define PS_CLIENT_H + +#include "common.h" + +struct ps_client_opts { + const char *host; + uint16_t port; + const char *filter; /* display filter, see filter.h */ + const char *pcap_path; /* optional local recording */ + uint64_t pcap_rotate_bytes; + const char *json_path; /* write NDJSON to this file instead of the screen */ + uint64_t count; /* stop after N matching packets, 0 = unlimited */ + unsigned duration; /* stop after N seconds, 0 = unlimited */ + size_t hex_bytes; /* bytes to hexdump, 0 = no hexdump */ + int show_stats; + int color; /* 1 force, 0 off, -1 auto (tty only) */ + int quiet; /* suppress the header/banner */ + int reconnect; + unsigned stats_interval; +}; + +int ps_client_run(const struct ps_client_opts *opts); + +#endif /* PS_CLIENT_H */ diff --git a/include/common.h b/include/common.h new file mode 100644 index 0000000..78ce47d --- /dev/null +++ b/include/common.h @@ -0,0 +1,107 @@ +/* common.h - shared primitives: fixed-width types, endian helpers, limits. */ +#ifndef PS_COMMON_H +#define PS_COMMON_H + +#ifndef _GNU_SOURCE +#define _GNU_SOURCE 1 +#endif + +#include +#include +#include +#include +#include + +#define PS_NAME "pktsniff" +#define PS_VERSION_STR "2.0.0" + +#define PS_ARRAY_LEN(a) (sizeof(a) / sizeof((a)[0])) + +#ifndef MIN +#define MIN(a, b) ((a) < (b) ? (a) : (b)) +#endif +#ifndef MAX +#define MAX(a, b) ((a) > (b) ? (a) : (b)) +#endif + +#define PS_UNUSED(x) ((void)(x)) + +/* ---- link-layer types we understand (values match libpcap's DLT_*) ---- */ +#define PS_DLT_NULL 0 /* BSD loopback, 4-byte AF family */ +#define PS_DLT_EN10MB 1 /* Ethernet II */ +#define PS_DLT_RAW 12 /* bare IP */ +#define PS_DLT_LOOP 108 /* OpenBSD loopback, big-endian AF family */ +#define PS_DLT_LINUX_SLL 113 /* Linux "cooked" v1 */ +#define PS_DLT_LINUX_SLL2 276 /* Linux "cooked" v2 */ + +/* Returned by ps_capture_open() on Linux so peers know what they receive. */ +#define PS_LINKTYPE_ETHERNET PS_DLT_EN10MB + +#define PS_SNAPLEN_DEFAULT 262144u +#define PS_SNAPLEN_MAX 524288u +#define PS_MAX_FRAME (2u * 1024u * 1024u) + +/* ---- unaligned big-endian readers (network order, wire protocol) ---- */ +static inline uint16_t ps_be16(const void *p) { + const uint8_t *b = (const uint8_t *)p; + return (uint16_t)((uint16_t)b[0] << 8 | (uint16_t)b[1]); +} + +static inline uint32_t ps_be32(const void *p) { + const uint8_t *b = (const uint8_t *)p; + return (uint32_t)b[0] << 24 | (uint32_t)b[1] << 16 | (uint32_t)b[2] << 8 | (uint32_t)b[3]; +} + +static inline uint64_t ps_be64(const void *p) { + const uint8_t *b = (const uint8_t *)p; + return (uint64_t)ps_be32(b) << 32 | ps_be32(b + 4); +} + +/* ---- unaligned little-endian readers (pcap file format) ---- */ +static inline uint16_t ps_le16(const void *p) { + const uint8_t *b = (const uint8_t *)p; + return (uint16_t)((uint16_t)b[1] << 8 | (uint16_t)b[0]); +} + +static inline uint32_t ps_le32(const void *p) { + const uint8_t *b = (const uint8_t *)p; + return (uint32_t)b[3] << 24 | (uint32_t)b[2] << 16 | (uint32_t)b[1] << 8 | (uint32_t)b[0]; +} + +/* ---- unaligned big-endian writers ---- */ +static inline void ps_put_be16(void *p, uint16_t v) { + uint8_t *b = (uint8_t *)p; + b[0] = (uint8_t)(v >> 8); + b[1] = (uint8_t)v; +} + +static inline void ps_put_be32(void *p, uint32_t v) { + uint8_t *b = (uint8_t *)p; + b[0] = (uint8_t)(v >> 24); + b[1] = (uint8_t)(v >> 16); + b[2] = (uint8_t)(v >> 8); + b[3] = (uint8_t)v; +} + +static inline void ps_put_be64(void *p, uint64_t v) { + uint8_t *b = (uint8_t *)p; + ps_put_be32(b, (uint32_t)(v >> 32)); + ps_put_be32(b + 4, (uint32_t)v); +} + +/* ---- unaligned little-endian writers (pcap file format) ---- */ +static inline void ps_put_le16(void *p, uint16_t v) { + uint8_t *b = (uint8_t *)p; + b[0] = (uint8_t)v; + b[1] = (uint8_t)(v >> 8); +} + +static inline void ps_put_le32(void *p, uint32_t v) { + uint8_t *b = (uint8_t *)p; + b[0] = (uint8_t)v; + b[1] = (uint8_t)(v >> 8); + b[2] = (uint8_t)(v >> 16); + b[3] = (uint8_t)(v >> 24); +} + +#endif /* PS_COMMON_H */ diff --git a/include/decode.h b/include/decode.h new file mode 100644 index 0000000..d78bf6e --- /dev/null +++ b/include/decode.h @@ -0,0 +1,95 @@ +/* decode.h - bounds-checked protocol dissection. + * + * Understands Ethernet II (+802.1Q/QinQ), Linux cooked capture, BSD loopback, + * bare IP; ARP, IPv4, IPv6 (+ extension headers); TCP, UDP, ICMP, ICMPv6; + * and a little application-layer curiosity: DNS names, TLS SNI, HTTP verbs. + */ +#ifndef PS_DECODE_H +#define PS_DECODE_H + +#include "common.h" + +enum ps_l4 { + PS_L4_NONE = 0, + PS_L4_TCP, + PS_L4_UDP, + PS_L4_ICMP, + PS_L4_ICMPV6, + PS_L4_OTHER +}; + +#define PS_TCP_FIN 0x01 +#define PS_TCP_SYN 0x02 +#define PS_TCP_RST 0x04 +#define PS_TCP_PSH 0x08 +#define PS_TCP_ACK 0x10 +#define PS_TCP_URG 0x20 +#define PS_TCP_ECE 0x40 +#define PS_TCP_CWR 0x80 + +#define PS_APP_DNS 0x01 +#define PS_APP_TLS 0x02 +#define PS_APP_HTTP 0x04 + +struct ps_decoded { + int has_eth; + char src_mac[18]; + char dst_mac[18]; + int has_vlan; + uint16_t vlan_id; + uint16_t ethertype; + + int ip_version; /* 0 = no IP layer (e.g. ARP) */ + char src[64]; /* formatted address, empty if absent */ + char dst[64]; + uint8_t ttl; /* hop limit for v6 */ + int fragmented; + + uint16_t arp_op; + char arp_sender_ip[64]; + char arp_target_ip[64]; + char arp_sender_mac[18]; + + enum ps_l4 l4; + uint8_t l4_proto; + uint16_t sport; + uint16_t dport; + uint16_t l4_len; /* TCP/UDP segment length incl. header */ + + /* TCP */ + uint32_t seq; + uint32_t ack; + uint8_t tcp_flags; + uint16_t window; + uint16_t tcp_mss; + + /* ICMP */ + uint8_t icmp_type; + uint8_t icmp_code; + + const uint8_t *payload; /* application payload, may be NULL */ + uint32_t payload_len; + + unsigned app_flags; + char app[160]; /* "DNS A example.com", "TLS SNI=...", "HTTP GET /index" */ + char info[192]; /* catch-all detail line for display */ + + uint32_t caplen; + uint32_t origlen; +}; + +/* Returns 0 on success, -1 if the frame is too short to be what it claims. */ +int ps_decode(const uint8_t *data, uint32_t caplen, uint32_t origlen, uint16_t linktype, + struct ps_decoded *out); + +const char *ps_l4_name(enum ps_l4 l4); +const char *ps_proto_label(const struct ps_decoded *d); +/* "SYN,ACK" into buf; empty string when no flags. */ +void ps_tcp_flag_str(uint8_t flags, char *buf, size_t cap); + +/* One-line human rendering (no trailing newline). */ +void ps_decoded_format_line(const struct ps_decoded *d, char *out, size_t cap); +/* Classic offset | hex | ascii dump (no trailing newline). `max` caps bytes. */ +void ps_hexdump(const uint8_t *data, size_t len, size_t max, char *out, size_t cap); + +#endif /* PS_DECODE_H */ diff --git a/include/filter.h b/include/filter.h new file mode 100644 index 0000000..08d4a7a --- /dev/null +++ b/include/filter.h @@ -0,0 +1,78 @@ +/* filter.h - client-side display filter. + * + * The server can be given a real BPF expression (`--filter`), but the client + * needs its own cheap filter so a busy link does not drown the terminal. + * + * Grammar: groups joined by `or`, terms inside a group joined by `and` + * (comma or whitespace also work; `and` is noise). Prefix a term with `!` to + * negate it. + * + * proto:tcp proto:udp proto:icmp proto:icmp6 proto:arp proto:ip6 + * proto:dns proto:tls proto:http + * port:443 sport:53 dport:53 + * host:10.0.0.1 host:10.0.0.0/8 src:... dst:... + * contains:GET bytes:>500 + * shorthand: tcp udp icmp arp dns tls http 443 10.0.0.1 + * + * Examples: `proto:tcp port:443 or proto:dns`, `!src:10.0.0.5 bytes:>1400` + */ +#ifndef PS_FILTER_H +#define PS_FILTER_H + +#include +#include +#include + +#include "decode.h" + +enum ps_filter_kind { + PS_FILTER_PROTO = 1, + PS_FILTER_PORT, + PS_FILTER_SPORT, + PS_FILTER_DPORT, + PS_FILTER_HOST, + PS_FILTER_SRC, + PS_FILTER_DST, + PS_FILTER_CONTAINS, + PS_FILTER_BYTES, +}; + +enum ps_filter_cmp { PS_CMP_EQ = 0, PS_CMP_GT, PS_CMP_LT, PS_CMP_GE, PS_CMP_LE }; + +struct ps_filter_clause { + enum ps_filter_kind kind; + bool negate; + char proto[8]; + uint16_t port; + uint32_t addr4; /* network order */ + uint32_t mask4; + uint8_t addr6[16]; + uint8_t mask6[16]; + int is_v6; + char needle[64]; + enum ps_filter_cmp cmp; + uint32_t bytes; +}; + +#define PS_FILTER_MAX_CLAUSES 12 +#define PS_FILTER_MAX_GROUPS 8 + +struct ps_filter_group { + struct ps_filter_clause clauses[PS_FILTER_MAX_CLAUSES]; + size_t count; +}; + +struct ps_filter { + struct ps_filter_group groups[PS_FILTER_MAX_GROUPS]; + size_t count; + char source[256]; /* original expression, for display */ +}; + +/* Returns 0 on success, -1 with a message in err. */ +int ps_filter_parse(const char *expr, struct ps_filter *f, char *err, size_t errsz); +/* True when the packet satisfies at least one group in full. */ +bool ps_filter_match(const struct ps_filter *f, const struct ps_decoded *d); +/* 1 if the filter is empty (matches everything). */ +int ps_filter_is_empty(const struct ps_filter *f); + +#endif /* PS_FILTER_H */ diff --git a/include/log.h b/include/log.h new file mode 100644 index 0000000..d09f252 --- /dev/null +++ b/include/log.h @@ -0,0 +1,31 @@ +/* log.h - leveled logging with optional colour, always to stderr. */ +#ifndef PS_LOG_H +#define PS_LOG_H + +#include + +typedef enum { + PS_LOG_DEBUG = 0, + PS_LOG_INFO, + PS_LOG_WARN, + PS_LOG_ERROR, + PS_LOG_OFF +} ps_log_level; + +void ps_log_init(ps_log_level level, int color); +int ps_log_enabled(ps_log_level level); +void ps_log(ps_log_level level, const char *fmt, ...) +#if defined(__GNUC__) || defined(__clang__) + __attribute__((format(printf, 2, 3))) +#endif + ; + +/* Wall-clock "HH:MM:SS.micro" into buf (at least 16 bytes). */ +void ps_clock_stamp(char *buf, size_t cap); + +#define LOG_DEBUG(...) ps_log(PS_LOG_DEBUG, __VA_ARGS__) +#define LOG_INFO(...) ps_log(PS_LOG_INFO, __VA_ARGS__) +#define LOG_WARN(...) ps_log(PS_LOG_WARN, __VA_ARGS__) +#define LOG_ERROR(...) ps_log(PS_LOG_ERROR, __VA_ARGS__) + +#endif /* PS_LOG_H */ diff --git a/include/outbuf.h b/include/outbuf.h new file mode 100644 index 0000000..9246890 --- /dev/null +++ b/include/outbuf.h @@ -0,0 +1,45 @@ +/* outbuf.h - per-client send queue that only ever drops whole frames. + * + * The capture loop must never block on a slow client, and the client must never + * see a half frame, so this is a byte queue with an explicit notion of "next + * frame boundary". Bytes may be partially sent; anything dropped is removed at + * a frame boundary, and any bytes of that frame already handed to send() are + * left untouched (they are already on the wire). + */ +#ifndef PS_OUTBUF_H +#define PS_OUTBUF_H + +#include +#include + +struct ps_outbuf { + uint8_t *data; + size_t cap; + size_t r; /* bytes already handed to the socket */ + size_t frame_start; /* offset of the oldest queued frame boundary */ + size_t w; /* end of queued data */ + uint64_t dropped_bytes; + uint64_t dropped_frames; +}; + +void ps_outbuf_init(struct ps_outbuf *q, size_t cap); +void ps_outbuf_free(struct ps_outbuf *q); + +/* Append one complete frame. Returns 0 on success, -1 if it can never fit. + * When the queue is full, older whole frames are discarded first. */ +int ps_outbuf_push(struct ps_outbuf *q, const uint8_t *frame, size_t len); + +/* Bytes waiting to be written to the socket. */ +size_t ps_outbuf_pending(const struct ps_outbuf *q); +const uint8_t *ps_outbuf_head(const struct ps_outbuf *q); + +/* Account for `n` bytes accepted by send(). */ +void ps_outbuf_consume(struct ps_outbuf *q, size_t n); + +/* Drop the oldest whole frame; returns 1 if one was dropped, 0 if empty. */ +int ps_outbuf_drop_front(struct ps_outbuf *q); + +/* Number of complete frames currently queued (for diagnostics only). */ +size_t ps_outbuf_frames(const struct ps_outbuf *q); + +#endif /* PS_OUTBUF_H */ diff --git a/include/pcap.h b/include/pcap.h new file mode 100644 index 0000000..f8e0550 --- /dev/null +++ b/include/pcap.h @@ -0,0 +1,31 @@ +/* pcap.h - minimal classic .pcap writer (no libpcap dependency). + * + * Files are written with a native-endian magic so any libpcap/Wireshark/tcpdump + * build can open them regardless of the machine that produced them. + */ +#ifndef PS_PCAP_H +#define PS_PCAP_H + +#include "common.h" +#include "proto.h" + +struct ps_pcap { + int fd; + uint32_t snaplen; + uint16_t linktype; + uint64_t bytes_written; + uint64_t packets_written; + uint64_t rotate_bytes; /* 0 = never rotate */ + char path[512]; + unsigned seq; /* rotation counter */ +}; + +/* Opens `path` (empty path, "-" or NULL means stdout) and writes the global + * header. Returns 0 on success. */ +int ps_pcap_open(struct ps_pcap *w, const char *path, uint32_t snaplen, uint16_t linktype, + uint64_t rotate_bytes, char *err, size_t errsz); +int ps_pcap_write(struct ps_pcap *w, const struct ps_record *rec); +int ps_pcap_flush(struct ps_pcap *w); +void ps_pcap_close(struct ps_pcap *w); + +#endif /* PS_PCAP_H */ diff --git a/include/proto.h b/include/proto.h new file mode 100644 index 0000000..c16b918 --- /dev/null +++ b/include/proto.h @@ -0,0 +1,94 @@ +/* proto.h - pktsniff wire protocol, version 1. + * + * Every message is a length-prefixed frame: + * + * +--------+---------+--------+--------+------------------+ + * | magic | version | type | length | payload[length] | + * | 4 (BE) | 2 (BE) | 2 (BE) | 4 (BE) | ... | + * +--------+---------+--------+--------+------------------+ + * + * Payloads are typed by `type`; see docs/PROTOCOL.md. Raw captured frames + * travel inside PS_FRAME_PACKET so the client can decode, filter, render or + * write them to a .pcap without the server having to understand anything but + * Ethernet. + */ +#ifndef PS_PROTO_H +#define PS_PROTO_H + +#include "common.h" + +#define PS_PROTO_MAGIC 0x50534E46u /* "PSNF" */ +#define PS_PROTO_VERSION 1u +#define PS_HEADER_LEN 12u + +enum ps_frame_type { + PS_FRAME_HELLO = 1, /* server -> client: session metadata */ + PS_FRAME_PACKET = 2, /* server -> client: one captured frame */ + PS_FRAME_STATS = 3, /* server -> client: counters */ + PS_FRAME_BYE = 4, /* server -> client: clean shutdown */ + PS_FRAME_ERR = 5, /* either direction: human-readable error */ +}; + +/* PS_FRAME_PACKET payload, all integers big-endian: + * u32 ts_sec | u32 ts_usec | u32 caplen | u32 origlen | u8 data[caplen] */ +#define PS_PKT_HDR_LEN 16u + +struct ps_record { + uint32_t ts_sec; + uint32_t ts_usec; + uint32_t caplen; + uint32_t origlen; + const uint8_t *data; +}; + +struct ps_frame { + uint16_t type; + uint32_t len; + const uint8_t *data; +}; + +/* ---- builders. Each returns the number of bytes written, 0 on failure. ---- */ +size_t ps_frame_write(uint8_t *out, size_t cap, uint16_t type, const uint8_t *payload, uint32_t len); +size_t ps_packet_encode(uint8_t *out, size_t cap, const struct ps_record *rec); + +/* PS_FRAME_HELLO payload: u16 linktype | u32 snaplen | 3 x NUL-terminated + * strings (hostname, interface, bpf filter; empty string allowed). */ +struct ps_hello { + uint16_t linktype; + uint32_t snaplen; + char hostname[64]; + char iface[32]; + char filter[256]; +}; + +size_t ps_hello_encode(const struct ps_hello *hello, uint8_t *out, size_t cap); +int ps_hello_decode(const uint8_t *in, uint32_t len, struct ps_hello *hello); + +int ps_packet_decode(const uint8_t *in, uint32_t len, struct ps_record *rec); + +/* PS_FRAME_ERR/BYE payload is a bare NUL-terminated string. */ +size_t ps_string_encode(const char *s, uint8_t *out, size_t cap); + +/* ---- incremental frame reader (handles TCP segmentation correctly) ---- */ +struct ps_reader { + uint8_t *buf; /* accumulated socket bytes */ + size_t cap; + size_t len; + uint8_t *frame; /* scratch copy of the frame handed to the caller */ + size_t frame_cap; + int error; /* sticky; set on protocol violation */ +}; + +int ps_reader_init(struct ps_reader *r, size_t initial_cap); +void ps_reader_free(struct ps_reader *r); +void ps_reader_reset(struct ps_reader *r); +/* Append bytes from the socket. Returns 0 on success, -1 if the reader would + * exceed PS_MAX_FRAME (protocol garbage). */ +int ps_reader_feed(struct ps_reader *r, const uint8_t *data, size_t n); +/* 1 = frame ready, 0 = need more bytes, -1 = protocol error. + * The returned payload is a private copy, valid until the next call. */ +int ps_reader_next(struct ps_reader *r, struct ps_frame *out); + +const char *ps_frame_type_name(uint16_t type); + +#endif /* PS_PROTO_H */ diff --git a/include/server.h b/include/server.h new file mode 100644 index 0000000..f5601e2 --- /dev/null +++ b/include/server.h @@ -0,0 +1,32 @@ +/* server.h - capture side: accepts clients, fans frames out, never blocks. */ +#ifndef PS_SERVER_H +#define PS_SERVER_H + +#include "common.h" +#include "stats.h" + +struct ps_server_opts { + const char *iface; + const char *bind_addr; + uint16_t port; + const char *bpf; /* kernel filter (requires libpcap) */ + uint32_t snaplen; + int promisc; + enum { + PS_SERVER_DIR_BOTH = 0, + PS_SERVER_DIR_IN, + PS_SERVER_DIR_OUT + } direction; + int max_clients; + size_t client_buffer; /* bytes queued per slow client before dropping */ + unsigned stats_interval; + const char *pcap_path; /* optional server-side recording */ + uint64_t pcap_rotate_bytes; + int quiet; + int capture_control; /* include our own control connection in the capture */ +}; + +/* Blocks until SIGINT/SIGTERM. Returns process exit code. */ +int ps_server_run(const struct ps_server_opts *opts); + +#endif /* PS_SERVER_H */ diff --git a/include/stats.h b/include/stats.h new file mode 100644 index 0000000..e38b73f --- /dev/null +++ b/include/stats.h @@ -0,0 +1,45 @@ +/* stats.h - traffic counters, serialised with an X-macro so the wire format + * and the struct can never drift apart. */ +#ifndef PS_STATS_H +#define PS_STATS_H + +#include "common.h" + +/* name = struct field = wire field, in this exact order. */ +#define PS_COUNTER_FIELDS(X) \ + X(seen) \ + X(captured) \ + X(bytes) \ + X(tcp) \ + X(udp) \ + X(icmp) \ + X(arp) \ + X(dns) \ + X(tls) \ + X(ipv6) \ + X(fragmented) \ + X(other) + +struct ps_counters { +#define PS_COUNTER_DECL(name) uint64_t name; + PS_COUNTER_FIELDS(PS_COUNTER_DECL) +#undef PS_COUNTER_DECL + uint64_t dropped_kernel; /* kernel ring drops, server side */ + uint64_t dropped_client; /* slow-consumer drops, server side */ +}; + +/* 12 X-macro fields + kernel/client drops. stats.c static_asserts this + * against sizeof(struct ps_counters) so the two cannot drift. */ +#define PS_COUNTER_WIRE_FIELDS 14u +#define PS_COUNTER_WIRE_SIZE (PS_COUNTER_WIRE_FIELDS * 8u) + +void ps_counters_clear(struct ps_counters *c); +void ps_counters_add(struct ps_counters *dst, const struct ps_counters *src); + +size_t ps_counters_encode(const struct ps_counters *c, uint8_t *out, size_t cap); +int ps_counters_decode(const uint8_t *in, uint32_t len, struct ps_counters *c); + +/* Compact single-line rendering used by both sides' status output. */ +void ps_counters_format(const struct ps_counters *c, char *out, size_t cap); + +#endif /* PS_STATS_H */ diff --git a/include/util.h b/include/util.h new file mode 100644 index 0000000..4e424d7 --- /dev/null +++ b/include/util.h @@ -0,0 +1,37 @@ +/* util.h - small shared helpers. */ +#ifndef PS_UTIL_H +#define PS_UTIL_H + +#include +#include + +void ps_set_prog_name(const char *name); +const char *ps_prog_name(void); + +void *ps_xmalloc(size_t n); +void *ps_xrealloc(void *p, size_t n); +char *ps_strdup(const char *s); + +/* Copy at most cap-1 bytes and always NUL-terminate. Returns strlen(src). */ +size_t ps_strlcpy(char *dst, const char *src, size_t cap); + +uint64_t ps_now_us(void); +void ps_sleep_ms(unsigned ms); + +/* "12.3 MB" style rendering. */ +void ps_fmt_bytes(char *out, size_t cap, uint64_t bytes); +/* "1.2 Mpps" / "835 kbps" style rendering. */ +void ps_fmt_rate(char *out, size_t cap, double value); + +/* Strict unsigned parse; returns 0 on success. */ +int ps_parse_u64(const char *s, uint64_t *out); +int ps_parse_u32(const char *s, uint32_t *out); + +/* Print a warning and return how many bytes were written (may truncate). */ +size_t ps_appendf(char *buf, size_t cap, size_t off, const char *fmt, ...) +#if defined(__GNUC__) || defined(__clang__) + __attribute__((format(printf, 4, 5))) +#endif + ; + +#endif /* PS_UTIL_H */ diff --git a/packaging/pktsniff.service b/packaging/pktsniff.service new file mode 100644 index 0000000..68c82f5 --- /dev/null +++ b/packaging/pktsniff.service @@ -0,0 +1,26 @@ +[Unit] +Description=pktsniff packet capture server +Documentation=https://github.com/Bas3line/packets +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +# Edit ExecStart to match your interface, filter and recording path. +# Capturing needs CAP_NET_RAW (and CAP_NET_ADMIN for promiscuous mode). +ExecStart=/usr/local/bin/pktsniff-server -i any -p 8888 -t 30 -q +Restart=on-failure +RestartSec=3 +AmbientCapabilities=CAP_NET_RAW CAP_NET_ADMIN +CapabilityBoundingSet=CAP_NET_RAW CAP_NET_ADMIN +NoNewPrivileges=yes +ProtectSystem=strict +ProtectHome=yes +PrivateTmp=yes +# Add `ReadWritePaths=/var/cap` if you use -w /var/cap/x.pcap +StandardOutput=journal +StandardError=journal +SyslogIdentifier=pktsniff + +[Install] +WantedBy=multi-user.target diff --git a/scripts/build.sh b/scripts/build.sh new file mode 100755 index 0000000..921d137 --- /dev/null +++ b/scripts/build.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +# Thin wrapper around make so `./scripts/build.sh` keeps working. +set -euo pipefail +cd "$(dirname "$0")/.." +make "$@" +echo +echo "built:" +ls -1 bin/pktsniff-server bin/pktsniff-client 2>/dev/null || true +echo +echo "server: sudo ./bin/pktsniff-server --help" +echo "client: ./bin/pktsniff-client --help" diff --git a/scripts/client_setup.sh b/scripts/client_setup.sh new file mode 100755 index 0000000..667ace0 --- /dev/null +++ b/scripts/client_setup.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# Build the client (no privileges or libpcap needed). +set -euo pipefail +cd "$(dirname "$0")/.." + +if command -v apt-get >/dev/null 2>&1 && ! command -v cc >/dev/null 2>&1; then + sudo apt-get update -qq && sudo apt-get install -y build-essential +fi + +make -j"$(nproc)" + +cat < [-p PORT] [-F 'proto:tcp port:443'] + +MSG diff --git a/scripts/server_setup.sh b/scripts/server_setup.sh new file mode 100755 index 0000000..735293a --- /dev/null +++ b/scripts/server_setup.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash +# Install build deps, build, install and open the firewall port. +set -euo pipefail +cd "$(dirname "$0")/.." + +PORT=${PORT:-8888} +PREFIX=${PREFIX:-/usr/local} + +if [ "$(id -u)" -ne 0 ]; then + echo "run as root (needed for apt, install and the firewall)" >&2 + exit 1 +fi + +if command -v apt-get >/dev/null 2>&1; then + apt-get update -qq + apt-get install -y build-essential libpcap-dev +elif command -v dnf >/dev/null 2>&1; then + dnf install -y gcc make libpcap-devel +fi + +make -j"$(nproc)" +make install PREFIX="$PREFIX" + +SERVER="$PREFIX/bin/pktsniff-server" +if command -v setcap >/dev/null 2>&1; then + setcap cap_net_raw,cap_net_admin=eip "$SERVER" && \ + echo "granted CAP_NET_RAW/CAP_NET_ADMIN to $SERVER (no root needed)" +fi + +if command -v ufw >/dev/null 2>&1 && ufw status | grep -q active; then + ufw allow "$PORT"/tcp && echo "ufw: allowed $PORT/tcp" +elif command -v firewall-cmd >/dev/null 2>&1; then + firewall-cmd --permanent --add-port="$PORT/tcp" && firewall-cmd --reload +fi + +cat < -p $PORT + +MSG diff --git a/sniffer/.gitignore b/sniffer/.gitignore deleted file mode 100644 index 6dd29b7..0000000 --- a/sniffer/.gitignore +++ /dev/null @@ -1 +0,0 @@ -bin/ \ No newline at end of file diff --git a/sniffer/Makefile b/sniffer/Makefile deleted file mode 100644 index 7eefc59..0000000 --- a/sniffer/Makefile +++ /dev/null @@ -1,23 +0,0 @@ -CC=gcc -CFLAGS=-Wall -Wextra -SRCDIR=src -BINDIR=bin - -all: build - -build: - @mkdir -p $(BINDIR) - $(CC) $(CFLAGS) -o $(BINDIR)/packet_sniffer $(SRCDIR)/packet_sniffer.c - $(CC) $(CFLAGS) -o $(BINDIR)/packet_client $(SRCDIR)/packet_client.c - @echo "Build complete!" - -clean: - rm -rf $(BINDIR) - -server-setup: - @./scripts/server_setup.sh - -client-setup: - @./scripts/client_setup.sh - -.PHONY: all build clean server-setup client-setup \ No newline at end of file diff --git a/sniffer/README.md b/sniffer/README.md deleted file mode 100644 index 757beb7..0000000 --- a/sniffer/README.md +++ /dev/null @@ -1,102 +0,0 @@ -# Packet Sniffer - -**Educational packet sniffer for network understanding and learning purposes only.** - -A client-server packet sniffer implementation in C that captures network packets on a server and streams them to a remote client for analysis. - -## Features - -- Raw packet capture using raw sockets -- Protocol analysis: TCP, UDP, ICMP with flag parsing -- MAC address extraction from Ethernet frames -- Packet hexdump display -- Real-time statistics (packet counts, bytes transferred) -- Multi-client support (up to 5 concurrent clients) -- TTL and flag analysis -- Microsecond timestamps - -## Architecture - -- **Server** (`packet_sniffer.c`): Runs on the target machine, captures packets and serves them to clients -- **Client** (`packet_client.c`): Connects to the server and displays captured packets in real-time - -## Quick Setup - -### On Your Debian Server - -```bash -# Clone and setup -git clone https://github.com/Bas3line/packets -cd packets/sniffer - -# Build and setup server (requires root) -sudo ./scripts/server_setup.sh - -# Start packet sniffer (requires root for raw sockets) -sudo ./bin/packet_sniffer -``` - -### On Your Local PC - -```bash -# Setup client -./scripts/client_setup.sh - -# Connect to your server (replace with your server's IP) -./bin/packet_client YOUR_SERVER_IP -``` - -## Manual Build - -```bash -# Using make -make build - -# Or using build script -./scripts/build.sh - -# Or manually -gcc -o bin/packet_sniffer src/packet_sniffer.c -gcc -o bin/packet_client src/packet_client.c -``` - -## Usage - -1. **Start the server** on your Debian cloud server: - ```bash - sudo ./bin/packet_sniffer - ``` - -2. **Connect from your PC**: - ```bash - ./bin/packet_client 192.168.1.100 # Replace with server IP - ``` - -3. **View packets** in real-time on your local machine - -## Requirements - -- **Server**: Linux system with root access (for raw socket creation) -- **Client**: Any system with network connectivity -- **Network**: Port 8888 must be open between client and server - -## Sample Output - -``` -[12:34:56.789] TCP aa:bb:cc:dd:ee:ff -> 11:22:33:44:55:66 192.168.1.10:443 -> 192.168.1.100:52345 (1460 bytes, TTL:64) SYN ACK - HEX: 45 00 05 b4 1a 2b 40 00 40 06 d4 6c c0 a8 01 0a c0 a8 01 64 01 bb cc 89 ... - -STATS: Total: 15847 | TCP: 12453 | UDP: 2891 | ICMP: 234 | Other: 269 | Bytes: 18394752 ----------------------------------------------------------------------- -``` - -## Security Notes - -- **Educational use only** - Use only on networks you own or have permission to monitor -- Requires root privileges for raw socket access -- Opens TCP port 8888 for client connections -- No encryption - packets are transmitted in plaintext - -## Legal Notice - -This tool is provided for educational purposes only. Users are responsible for complying with all applicable laws and regulations. Only use on networks you own or have explicit permission to monitor. \ No newline at end of file diff --git a/sniffer/scripts/build.sh b/sniffer/scripts/build.sh deleted file mode 100755 index 4ab6b9a..0000000 --- a/sniffer/scripts/build.sh +++ /dev/null @@ -1,28 +0,0 @@ -#!/bin/bash - -echo "Building Packet Sniffer..." - -mkdir -p bin - -gcc -Wall -Wextra -O2 -o bin/packet_sniffer src/packet_sniffer.c -if [ $? -eq 0 ]; then - echo "Server built successfully: bin/packet_sniffer" -else - echo "Server build failed" - exit 1 -fi - -gcc -Wall -Wextra -O2 -o bin/packet_client src/packet_client.c -if [ $? -eq 0 ]; then - echo "Client built successfully: bin/packet_client" -else - echo "Client build failed" - exit 1 -fi - -echo "" -echo "Build complete!" -echo "" -echo "Usage:" -echo " Server: sudo ./bin/packet_sniffer" -echo " Client: ./bin/packet_client " \ No newline at end of file diff --git a/sniffer/scripts/client_setup.sh b/sniffer/scripts/client_setup.sh deleted file mode 100755 index 97b5a30..0000000 --- a/sniffer/scripts/client_setup.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/bin/bash - -echo "Setting up Packet Sniffer Client..." - -./scripts/build.sh - -if [ ! -f "bin/packet_client" ]; then - echo "Build failed. Cannot proceed with setup." - exit 1 -fi - -echo "Client setup complete!" -echo "To connect to server: ./bin/packet_client " -echo "Example: ./bin/packet_client 192.168.1.100" \ No newline at end of file diff --git a/sniffer/scripts/server_setup.sh b/sniffer/scripts/server_setup.sh deleted file mode 100755 index f6e31ec..0000000 --- a/sniffer/scripts/server_setup.sh +++ /dev/null @@ -1,21 +0,0 @@ -#!/bin/bash - -echo "Setting up Packet Sniffer Server..." - -if [ "$EUID" -ne 0 ]; then - echo "This script must be run as root (use sudo)" - exit 1 -fi - -./scripts/build.sh - -if [ ! -f "bin/packet_sniffer" ]; then - echo "Build failed. Cannot proceed with setup." - exit 1 -fi - -echo "Opening firewall port 8888..." -ufw allow 8888/tcp 2>/dev/null || iptables -A INPUT -p tcp --dport 8888 -j ACCEPT 2>/dev/null - -echo "Server setup complete!" -echo "To start the sniffer: sudo ./bin/packet_sniffer" \ No newline at end of file diff --git a/sniffer/setup.md b/sniffer/setup.md deleted file mode 100644 index c7c992e..0000000 --- a/sniffer/setup.md +++ /dev/null @@ -1,242 +0,0 @@ -# Packet Sniffer Setup Guide - -## Prerequisites - -### Server (Debian Cloud Server) -```bash -# Update system -sudo apt update && sudo apt upgrade -y - -# Install build essentials -sudo apt install build-essential gcc make -y - -# Install git (if not already installed) -sudo apt install git -y -``` - -### Client (Local PC) -```bash -# Install gcc and build tools -sudo apt install build-essential gcc -y # Ubuntu/Debian -# OR -sudo yum install gcc make -y # CentOS/RHEL -# OR -sudo pacman -S gcc make -y # Arch Linux -``` - -## Installation - -### On Server (Debian Cloud) -```bash -# Clone repository -git clone https://github.com/Bas3line/packets -cd packets/sniffer - -# Build server -sudo ./scripts/server_setup.sh - -# OR manual build -make build -# OR -./scripts/build.sh -``` - -### On Client (Local PC) -```bash -# Clone repository -git clone https://github.com/Bas3line/packets -cd packets/sniffer - -# Build client -./scripts/client_setup.sh - -# OR manual build -make build -# OR -./scripts/build.sh -``` - -## Firewall Configuration - -### Server Firewall (Port 8888) -```bash -# UFW (Ubuntu/Debian) -sudo ufw allow 8888/tcp - -# iptables (Generic Linux) -sudo iptables -A INPUT -p tcp --dport 8888 -j ACCEPT - -# Cloud Provider Security Groups -# Add inbound rule: TCP port 8888 from your IP -``` - -## Running the Packet Sniffer - -### 1. Start Server -```bash -# On your Debian cloud server -cd packets -sudo ./bin/packet_sniffer -``` - -Output should show: -``` -Packet sniffer listening on port 8888 -Packet sniffer started. Press Ctrl+C to stop. -``` - -### 2. Connect Client -```bash -# On your local PC -cd packets -./bin/packet_client YOUR_SERVER_IP - -# Example: -./bin/packet_client 192.168.1.100 -``` - -Output should show: -``` -Connected to packet sniffer server at 192.168.1.100:8888 -Receiving packet data... ----------------------------------------------------------------------- -``` - -## Sample Output - -### Server Terminal -``` -Packet sniffer listening on port 8888 -Packet sniffer started. Press Ctrl+C to stop. -Client connected: 192.168.1.50 -12:34:56.789 [TCP] 192.168.1.1 -> 192.168.1.100 (SYN) 60 bytes -12:34:56.790 [TCP] 192.168.1.100 -> 192.168.1.1 (SYN ACK) 60 bytes -``` - -### Client Terminal -``` -Connected to packet sniffer server at 192.168.1.100:8888 -Receiving packet data... ----------------------------------------------------------------------- -[12:34:56.789] TCP aa:bb:cc:dd:ee:ff -> 11:22:33:44:55:66 192.168.1.1:443 -> 192.168.1.100:52345 (60 bytes, TTL:64) SYN - HEX: 45 00 00 3c 1a 2b 40 00 40 06 d4 6c c0 a8 01 01 c0 a8 01 64 01 bb cc 89 -[12:34:56.790] TCP 11:22:33:44:55:66 -> aa:bb:cc:dd:ee:ff 192.168.1.100:52345 -> 192.168.1.1:443 (60 bytes, TTL:64) SYN ACK - HEX: 45 00 00 3c 00 00 40 00 40 06 ef 97 c0 a8 01 64 c0 a8 01 01 cc 89 01 bb - -STATS: Total: 1247 | TCP: 892 | UDP: 234 | ICMP: 12 | Other: 109 | Bytes: 1847392 ----------------------------------------------------------------------- -``` - -## Troubleshooting - -### Permission Denied (Raw Socket) -```bash -# Server must run as root -sudo ./bin/packet_sniffer - -# Check if running as root -whoami # Should show: root -``` - -### Connection Refused -```bash -# Check if server is running -sudo netstat -tlnp | grep :8888 -# OR -sudo ss -tlnp | grep :8888 - -# Check firewall -sudo ufw status -sudo iptables -L | grep 8888 - -# Test connectivity -telnet YOUR_SERVER_IP 8888 -``` - -### No Packets Captured -```bash -# Check network interface -ip link show - -# Generate test traffic -ping google.com # ICMP packets -curl google.com # TCP packets -nslookup google.com # UDP packets -``` - -### Build Errors -```bash -# Install missing headers -sudo apt install linux-headers-$(uname -r) -sudo apt install libc6-dev - -# Check gcc version -gcc --version -``` - -## Network Interface Selection - -### Find Network Interfaces -```bash -# List all interfaces -ip link show -# OR -ifconfig -a - -# Common interfaces: -# eth0, ens33, enp0s3 - Ethernet -# wlan0, wlp2s0 - WiFi -# lo - Loopback (127.0.0.1) -``` - -### Capture on Specific Interface (Optional) -Modify `packet_sniffer.c` to bind to specific interface: -```c -// Add before socket creation -struct sockaddr_ll sll; -sll.sll_family = AF_PACKET; -sll.sll_ifindex = if_nametoindex("eth0"); // Change interface name -sll.sll_protocol = htons(ETH_P_ALL); - -// Bind to interface -bind(raw_socket, (struct sockaddr*)&sll, sizeof(sll)); -``` - -## Security Notes - -### Server Security -- Only run on trusted networks -- Monitor who connects to port 8888 -- Use firewall to restrict client IPs -- Run with minimal privileges where possible - -### Legal Compliance -- Only capture traffic on networks you own -- Inform users if monitoring shared networks -- Follow local privacy laws and regulations -- Use for educational/debugging purposes only - -## Stopping the Sniffer - -### Graceful Shutdown -```bash -# Press Ctrl+C on both server and client -# Server will show: -^C -Packets captured: 1247 -Total bytes: 1847392 - -# Client will show: -^C -Client disconnected -``` - -### Force Kill (if needed) -```bash -# Find process ID -ps aux | grep packet_sniffer -sudo kill -9 - -# OR kill all -sudo pkill packet_sniffer -``` \ No newline at end of file diff --git a/sniffer/src/packet_client.c b/sniffer/src/packet_client.c deleted file mode 100644 index 79d5482..0000000 --- a/sniffer/src/packet_client.c +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Educational Packet Sniffer Client - For network understanding and educational purposes only - */ - -#include -#include -#include -#include -#include -#include -#include -#include - -#define BUFFER_SIZE 8192 -#define DEFAULT_PORT 8888 - -int client_socket; -int running = 1; -int show_hex = 1; -int show_stats = 1; - -void signal_handler(int sig) { - (void)sig; - running = 0; - if (client_socket) close(client_socket); - printf("\nClient disconnected\n"); - exit(0); -} - -void print_packet_line(char* packet_data) { - char timestamp[32], src_mac[18], dst_mac[18], src_dst[64], protocol[16], flags[32]; - int packet_size, ttl; - - if (sscanf(packet_data, "PACKET|%31[^|]|%17[^|]|%17[^|]|%63[^|]|%15[^|]|%d|TTL:%d|%31[^\n]", - timestamp, src_mac, dst_mac, src_dst, protocol, &packet_size, &ttl, flags) >= 7) { - - printf("[%s] %s %s -> %s %s (%d bytes, TTL:%d) %s\n", - timestamp, protocol, src_mac, dst_mac, src_dst, packet_size, ttl, flags); - } -} - -void print_hex_line(char* hex_data) { - if (show_hex && strncmp(hex_data, "HEXDATA|", 8) == 0) { - char *hex_content = hex_data + 8; - printf(" HEX: %s\n", hex_content); - } -} - -void print_stats_line(char* stats_data) { - unsigned long total, tcp, udp, icmp, other, bytes; - - if (sscanf(stats_data, "STATS|Total:%lu|TCP:%lu|UDP:%lu|ICMP:%lu|Other:%lu|Bytes:%lu", - &total, &tcp, &udp, &icmp, &other, &bytes) == 6) { - - printf("STATS: Total: %lu | TCP: %lu | UDP: %lu | ICMP: %lu | Other: %lu | Bytes: %lu\n", - total, tcp, udp, icmp, other, bytes); - printf("----------------------------------------------------------------------\n"); - } -} - -int connect_to_server(const char* server_ip, int port) { - int sock; - struct sockaddr_in server_addr; - - sock = socket(AF_INET, SOCK_STREAM, 0); - if (sock < 0) { - perror("Socket creation failed"); - return -1; - } - - server_addr.sin_family = AF_INET; - server_addr.sin_port = htons(port); - - if (inet_pton(AF_INET, server_ip, &server_addr.sin_addr) <= 0) { - perror("Invalid server IP address"); - close(sock); - return -1; - } - - if (connect(sock, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) { - perror("Connection to server failed"); - close(sock); - return -1; - } - - return sock; -} - -int main(int argc, char *argv[]) { - char buffer[BUFFER_SIZE]; - int bytes_received; - - if (argc != 2) { - printf("Usage: %s \n", argv[0]); - printf("Example: %s 192.168.1.100\n", argv[0]); - return 1; - } - - signal(SIGINT, signal_handler); - signal(SIGTERM, signal_handler); - - client_socket = connect_to_server(argv[1], DEFAULT_PORT); - if (client_socket < 0) { - return 1; - } - - printf("Connected to packet sniffer server at %s:%d\n", argv[1], DEFAULT_PORT); - printf("Receiving packet data...\n"); - printf("----------------------------------------------------------------------\n"); - - while (running) { - bytes_received = recv(client_socket, buffer, BUFFER_SIZE - 1, 0); - - if (bytes_received > 0) { - buffer[bytes_received] = '\0'; - - char *line = strtok(buffer, "\n"); - while (line != NULL) { - if (strncmp(line, "PACKET|", 7) == 0) { - print_packet_line(line); - } else if (strncmp(line, "HEXDATA|", 8) == 0) { - print_hex_line(line); - } else if (strncmp(line, "STATS|", 6) == 0 && show_stats) { - print_stats_line(line); - } - line = strtok(NULL, "\n"); - } - fflush(stdout); - } else if (bytes_received == 0) { - printf("Server disconnected\n"); - break; - } else { - perror("Receive failed"); - break; - } - } - - close(client_socket); - return 0; -} \ No newline at end of file diff --git a/sniffer/src/packet_sniffer.c b/sniffer/src/packet_sniffer.c deleted file mode 100644 index 5cb2733..0000000 --- a/sniffer/src/packet_sniffer.c +++ /dev/null @@ -1,361 +0,0 @@ -/* - * Educational Packet Sniffer - For network understanding and educational purposes only - * This tool is designed for learning network protocols and packet analysis - * Use only on networks you own or have explicit permission to monitor - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define BUFFER_SIZE 65536 -#define CLIENT_PORT 8888 -#define MAX_CLIENTS 5 - -struct packet_stats { - unsigned long total_packets; - unsigned long tcp_packets; - unsigned long udp_packets; - unsigned long icmp_packets; - unsigned long other_packets; - unsigned long bytes_captured; -}; - -struct packet_info { - char timestamp[32]; - char src_mac[18]; - char dst_mac[18]; - char src_ip[16]; - char dst_ip[16]; - int src_port; - int dst_port; - char protocol[16]; - int packet_size; - int ttl; - char flags[32]; - unsigned char *data; - int data_len; -}; - -int raw_socket; -int server_socket; -int running = 1; -int client_fds[MAX_CLIENTS]; -struct packet_stats stats = {0}; - -void signal_handler(int sig) { - (void)sig; - running = 0; - printf("\nPackets captured: %lu\n", stats.total_packets); - printf("Total bytes: %lu\n", stats.bytes_captured); - if (raw_socket) close(raw_socket); - if (server_socket) close(server_socket); - exit(0); -} - -void get_timestamp(char *buffer) { - struct timeval tv; - struct tm *timeinfo; - gettimeofday(&tv, NULL); - timeinfo = localtime(&tv.tv_sec); - snprintf(buffer, 32, "%02d:%02d:%02d.%03ld", - timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec, tv.tv_usec/1000); -} - -void format_mac_address(unsigned char *mac, char *buffer) { - snprintf(buffer, 18, "%02x:%02x:%02x:%02x:%02x:%02x", - mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); -} - -void get_tcp_flags(struct tcphdr *tcp, char *buffer) { - buffer[0] = '\0'; - if (tcp->syn) strcat(buffer, "SYN "); - if (tcp->ack) strcat(buffer, "ACK "); - if (tcp->fin) strcat(buffer, "FIN "); - if (tcp->rst) strcat(buffer, "RST "); - if (tcp->psh) strcat(buffer, "PSH "); - if (tcp->urg) strcat(buffer, "URG "); - if (strlen(buffer) > 0) buffer[strlen(buffer)-1] = '\0'; -} - -void parse_packet(unsigned char *buffer, int size, struct packet_info *info) { - struct ethhdr *eth = (struct ethhdr*)buffer; - struct iphdr *ip = (struct iphdr*)(buffer + sizeof(struct ethhdr)); - - info->packet_size = size; - get_timestamp(info->timestamp); - - format_mac_address(eth->h_source, info->src_mac); - format_mac_address(eth->h_dest, info->dst_mac); - - if (ntohs(eth->h_proto) == ETH_P_IP) { - strcpy(info->src_ip, inet_ntoa(*(struct in_addr*)&ip->saddr)); - strcpy(info->dst_ip, inet_ntoa(*(struct in_addr*)&ip->daddr)); - info->ttl = ip->ttl; - - if (ip->protocol == IPPROTO_TCP) { - struct tcphdr *tcp = (struct tcphdr*)(buffer + sizeof(struct ethhdr) + (ip->ihl * 4)); - strcpy(info->protocol, "TCP"); - info->src_port = ntohs(tcp->source); - info->dst_port = ntohs(tcp->dest); - get_tcp_flags(tcp, info->flags); - stats.tcp_packets++; - - int header_size = sizeof(struct ethhdr) + (ip->ihl * 4) + (tcp->doff * 4); - info->data = buffer + header_size; - info->data_len = size - header_size; - } else if (ip->protocol == IPPROTO_UDP) { - struct udphdr *udp = (struct udphdr*)(buffer + sizeof(struct ethhdr) + (ip->ihl * 4)); - strcpy(info->protocol, "UDP"); - info->src_port = ntohs(udp->source); - info->dst_port = ntohs(udp->dest); - strcpy(info->flags, ""); - stats.udp_packets++; - - int header_size = sizeof(struct ethhdr) + (ip->ihl * 4) + sizeof(struct udphdr); - info->data = buffer + header_size; - info->data_len = size - header_size; - } else if (ip->protocol == IPPROTO_ICMP) { - struct icmphdr *icmp = (struct icmphdr*)(buffer + sizeof(struct ethhdr) + (ip->ihl * 4)); - strcpy(info->protocol, "ICMP"); - info->src_port = icmp->type; - info->dst_port = icmp->code; - snprintf(info->flags, 32, "Type:%d Code:%d", icmp->type, icmp->code); - stats.icmp_packets++; - - int header_size = sizeof(struct ethhdr) + (ip->ihl * 4) + sizeof(struct icmphdr); - info->data = buffer + header_size; - info->data_len = size - header_size; - } else { - snprintf(info->protocol, 16, "IP(%d)", ip->protocol); - info->src_port = 0; - info->dst_port = 0; - strcpy(info->flags, ""); - stats.other_packets++; - - int header_size = sizeof(struct ethhdr) + (ip->ihl * 4); - info->data = buffer + header_size; - info->data_len = size - header_size; - } - } else { - strcpy(info->protocol, "NON-IP"); - strcpy(info->src_ip, ""); - strcpy(info->dst_ip, ""); - info->src_port = 0; - info->dst_port = 0; - info->ttl = 0; - strcpy(info->flags, ""); - stats.other_packets++; - - info->data = buffer + sizeof(struct ethhdr); - info->data_len = size - sizeof(struct ethhdr); - } - - stats.total_packets++; - stats.bytes_captured += size; -} - -char* format_hex_dump(unsigned char *data, int len, int max_bytes) { - static char hex_buffer[2048]; - char *ptr = hex_buffer; - int bytes_to_show = (len > max_bytes) ? max_bytes : len; - - for (int i = 0; i < bytes_to_show; i++) { - if (i > 0 && i % 16 == 0) { - ptr += sprintf(ptr, "\n "); - } else if (i > 0 && i % 8 == 0) { - ptr += sprintf(ptr, " "); - } else if (i > 0) { - ptr += sprintf(ptr, " "); - } - ptr += sprintf(ptr, "%02x", data[i]); - } - - if (len > max_bytes) { - ptr += sprintf(ptr, "... (%d more bytes)", len - max_bytes); - } - - return hex_buffer; -} - -int setup_server() { - int sock, opt = 1; - struct sockaddr_in server_addr; - - sock = socket(AF_INET, SOCK_STREAM, 0); - if (sock < 0) { - perror("Server socket creation failed"); - return -1; - } - - setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); - - server_addr.sin_family = AF_INET; - server_addr.sin_addr.s_addr = INADDR_ANY; - server_addr.sin_port = htons(CLIENT_PORT); - - if (bind(sock, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) { - perror("Bind failed"); - close(sock); - return -1; - } - - if (listen(sock, MAX_CLIENTS) < 0) { - perror("Listen failed"); - close(sock); - return -1; - } - - printf("Packet sniffer listening on port %d\n", CLIENT_PORT); - return sock; -} - -void send_to_clients(struct packet_info *info) { - char message[4096]; - char port_info[64]; - - if (strcmp(info->protocol, "TCP") == 0 || strcmp(info->protocol, "UDP") == 0) { - snprintf(port_info, 64, ":%d -> %s:%d", info->src_port, info->dst_ip, info->dst_port); - } else if (strcmp(info->protocol, "ICMP") == 0) { - snprintf(port_info, 64, " -> %s", info->dst_ip); - } else { - snprintf(port_info, 64, " -> %s", info->dst_ip); - } - - int header_len = snprintf(message, sizeof(message), - "PACKET|%s|%s|%s|%s%s|%s|%d|TTL:%d|%s\n", - info->timestamp, info->src_mac, info->dst_mac, - info->src_ip, port_info, info->protocol, - info->packet_size, info->ttl, info->flags); - - if (info->data_len > 0) { - char *hex = format_hex_dump(info->data, info->data_len, 64); - snprintf(message + header_len, sizeof(message) - header_len, - "HEXDATA|%s\n", hex); - } - - for (int i = 0; i < MAX_CLIENTS; i++) { - if (client_fds[i] > 0) { - if (send(client_fds[i], message, strlen(message), MSG_NOSIGNAL) < 0) { - close(client_fds[i]); - client_fds[i] = 0; - } - } - } -} - -void send_stats_to_clients() { - char stats_msg[512]; - snprintf(stats_msg, sizeof(stats_msg), - "STATS|Total:%lu|TCP:%lu|UDP:%lu|ICMP:%lu|Other:%lu|Bytes:%lu\n", - stats.total_packets, stats.tcp_packets, stats.udp_packets, - stats.icmp_packets, stats.other_packets, stats.bytes_captured); - - for (int i = 0; i < MAX_CLIENTS; i++) { - if (client_fds[i] > 0) { - send(client_fds[i], stats_msg, strlen(stats_msg), MSG_NOSIGNAL); - } - } -} - -int main() { - unsigned char buffer[BUFFER_SIZE]; - struct sockaddr_in client_addr; - socklen_t client_len = sizeof(client_addr); - struct packet_info packet; - time_t last_stats = time(NULL); - - signal(SIGINT, signal_handler); - signal(SIGTERM, signal_handler); - - for (int i = 0; i < MAX_CLIENTS; i++) { - client_fds[i] = 0; - } - - raw_socket = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL)); - if (raw_socket < 0) { - perror("Raw socket creation failed. Run as root"); - return 1; - } - - server_socket = setup_server(); - if (server_socket < 0) { - close(raw_socket); - return 1; - } - - printf("Packet sniffer started. Press Ctrl+C to stop.\n"); - - while (running) { - fd_set read_fds; - FD_ZERO(&read_fds); - FD_SET(server_socket, &read_fds); - FD_SET(raw_socket, &read_fds); - - int max_fd = (server_socket > raw_socket) ? server_socket : raw_socket; - - struct timeval timeout; - timeout.tv_sec = 1; - timeout.tv_usec = 0; - - int activity = select(max_fd + 1, &read_fds, NULL, NULL, &timeout); - - if (activity < 0 && errno != EINTR) { - perror("Select error"); - break; - } - - if (FD_ISSET(server_socket, &read_fds)) { - int new_client = accept(server_socket, (struct sockaddr*)&client_addr, &client_len); - if (new_client >= 0) { - for (int i = 0; i < MAX_CLIENTS; i++) { - if (client_fds[i] == 0) { - client_fds[i] = new_client; - printf("Client connected: %s\n", inet_ntoa(client_addr.sin_addr)); - break; - } - } - } - } - - if (FD_ISSET(raw_socket, &read_fds)) { - int packet_size = recv(raw_socket, buffer, BUFFER_SIZE, 0); - if (packet_size > 0) { - parse_packet(buffer, packet_size, &packet); - - printf("%s [%s] %s -> %s (%s) %d bytes\n", - packet.timestamp, packet.protocol, packet.src_ip, - packet.dst_ip, packet.flags, packet.packet_size); - - send_to_clients(&packet); - } - } - - if (time(NULL) - last_stats >= 5) { - send_stats_to_clients(); - last_stats = time(NULL); - } - } - - for (int i = 0; i < MAX_CLIENTS; i++) { - if (client_fds[i] > 0) close(client_fds[i]); - } - close(server_socket); - close(raw_socket); - return 0; -} \ No newline at end of file diff --git a/src/capture.c b/src/capture.c new file mode 100644 index 0000000..c41c404 --- /dev/null +++ b/src/capture.c @@ -0,0 +1,257 @@ +/* capture.c - AF_PACKET capture, promiscuous mode, kernel BPF, drop accounting. */ +#include "capture.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "log.h" +#include "util.h" + +#ifdef PS_HAVE_PCAP +#include +#endif + +#define RX_RING_MAX (64u * 1024u * 1024u) + +static int attach_bpf(int fd, const char *expr, uint16_t linktype, char *err, size_t errsz) { +#ifdef PS_HAVE_PCAP + struct bpf_program prog; + struct sock_fprog fprog; + pcap_t *dead; + int rc = 0; + + dead = pcap_open_dead((int)linktype, PS_SNAPLEN_MAX); + if (!dead) { + snprintf(err, errsz, "pcap_open_dead failed"); + return -1; + } + if (pcap_compile(dead, &prog, expr, 1, PCAP_NETMASK_UNKNOWN) < 0) { + snprintf(err, errsz, "bad filter expression: %s", pcap_geterr(dead)); + pcap_close(dead); + return -1; + } + fprog.len = (unsigned short)prog.bf_len; + fprog.filter = (struct sock_filter *)prog.bf_insns; + if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &fprog, sizeof(fprog)) < 0) { + snprintf(err, errsz, "SO_ATTACH_FILTER: %s", strerror(errno)); + rc = -1; + } + pcap_freecode(&prog); + pcap_close(dead); + return rc; +#else + PS_UNUSED(fd); + PS_UNUSED(linktype); + snprintf(err, errsz, + "this build has no libpcap, so \"%s\" cannot be compiled " + "(rebuild with libpcap-dev installed, or use the client-side --filter)", + expr); + return -1; +#endif +} + +int ps_capture_open(struct ps_capture *cap, const char *iface, uint32_t snaplen, int promisc, + enum ps_direction direction, const char *bpf_expr, char *err, size_t errsz) { + struct sockaddr_ll sll; + int fd; + int opt; + + memset(cap, 0, sizeof(*cap)); + cap->fd = -1; + cap->linktype = PS_LINKTYPE_ETHERNET; + cap->snaplen = snaplen ? snaplen : PS_SNAPLEN_DEFAULT; + cap->promisc = promisc; + cap->direction = direction; + + if (!iface || !*iface || strcmp(iface, "any") == 0) { + ps_strlcpy(cap->iface, "any", sizeof(cap->iface)); + } else { + cap->ifindex = if_nametoindex(iface); + if (cap->ifindex == 0) { + snprintf(err, errsz, "no such interface '%s'", iface); + return -1; + } + ps_strlcpy(cap->iface, iface, sizeof(cap->iface)); + } + + fd = socket(AF_PACKET, SOCK_RAW | SOCK_NONBLOCK | SOCK_CLOEXEC, htons(ETH_P_ALL)); + if (fd < 0) { + snprintf(err, errsz, "AF_PACKET socket: %s (are you root?)", strerror(errno)); + return -1; + } + + /* Big socket buffer; the kernel doubles what we ask for. */ + opt = RX_RING_MAX; + if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &opt, sizeof(opt)) < 0) { + opt = 8 * 1024 * 1024; + if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &opt, sizeof(opt)) < 0) { + LOG_DEBUG("SO_RCVBUF: %s", strerror(errno)); + } + } + + /* Kernel receive timestamps: nanosecond-accurate and taken at the driver, + * not when we happen to get round to reading the socket. */ + opt = 1; + if (setsockopt(fd, SOL_SOCKET, SO_TIMESTAMPNS, &opt, sizeof(opt)) < 0) { + LOG_DEBUG("SO_TIMESTAMPNS: %s", strerror(errno)); + } + + if (cap->ifindex != 0) { + memset(&sll, 0, sizeof(sll)); + sll.sll_family = AF_PACKET; + sll.sll_protocol = htons(ETH_P_ALL); + sll.sll_ifindex = (int)cap->ifindex; + if (bind(fd, (struct sockaddr *)&sll, sizeof(sll)) < 0) { + snprintf(err, errsz, "bind to %s: %s", cap->iface, strerror(errno)); + close(fd); + return -1; + } + + if (promisc) { + struct packet_mreq mreq; + memset(&mreq, 0, sizeof(mreq)); + mreq.mr_ifindex = (int)cap->ifindex; + mreq.mr_type = PACKET_MR_PROMISC; + if (setsockopt(fd, SOL_PACKET, PACKET_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) { + snprintf(err, errsz, "promiscuous mode on %s: %s", cap->iface, strerror(errno)); + close(fd); + return -1; + } + } + } else { + cap->promisc = 0; /* "any" is an aggregate of per-device taps */ + } + + if (bpf_expr && *bpf_expr) { + if (attach_bpf(fd, bpf_expr, cap->linktype, err, errsz) != 0) { + close(fd); + return -1; + } + } + + cap->fd = fd; + return 0; +} + +int ps_capture_read(struct ps_capture *cap, uint8_t *buf, size_t bufsz, struct ps_record *rec, + int *outgoing) { + struct sockaddr_ll from; + struct iovec iov; + struct msghdr msg; + struct cmsghdr *cmsg; + union { + char buf[CMSG_SPACE(sizeof(struct timespec))]; + struct cmsghdr align; + } control; + ssize_t n; + + memset(&from, 0, sizeof(from)); + memset(&msg, 0, sizeof(msg)); + iov.iov_base = buf; + iov.iov_len = bufsz; + msg.msg_name = &from; + msg.msg_namelen = sizeof(from); + msg.msg_iov = &iov; + msg.msg_iovlen = 1; + msg.msg_control = control.buf; + msg.msg_controllen = sizeof(control.buf); + + n = recvmsg(cap->fd, &msg, MSG_DONTWAIT); + if (n < 0) { + if (errno == EAGAIN || errno == EWOULDBLOCK) { + return 0; + } + if (errno == EINTR) { + return 0; + } + return -1; + } + if (n == 0) { + return 0; + } + + if (outgoing) { + *outgoing = (from.sll_pkttype == PACKET_OUTGOING); + } + + uint32_t sec = 0; + uint32_t usec = 0; + int have_ts = 0; + for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) { + if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_TIMESTAMPNS) { + struct timespec ts; + memcpy(&ts, CMSG_DATA(cmsg), sizeof(ts)); + sec = (uint32_t)ts.tv_sec; + usec = (uint32_t)(ts.tv_nsec / 1000); + have_ts = 1; + break; + } + } + if (!have_ts) { + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + sec = (uint32_t)ts.tv_sec; + usec = (uint32_t)(ts.tv_nsec / 1000); + } + + rec->ts_sec = sec; + rec->ts_usec = usec; + rec->caplen = (uint32_t)n; + rec->origlen = (uint32_t)n; + rec->data = buf; + + /* The kernel gives us the wire length for outgoing/short captures only via + * TPACKET headers, which we do not use; origlen == caplen is honest. */ + return (int)n; +} + +void ps_capture_update_drops(struct ps_capture *cap) { + struct tpacket_stats stats; + socklen_t len = sizeof(stats); + + if (cap->fd < 0) { + return; + } + memset(&stats, 0, sizeof(stats)); + if (getsockopt(cap->fd, SOL_PACKET, PACKET_STATISTICS, &stats, &len) == 0) { + cap->drops_prev = stats.tp_drops; + cap->drops_total += stats.tp_drops; + } +} + +void ps_capture_close(struct ps_capture *cap) { + if (cap && cap->fd >= 0) { + close(cap->fd); + cap->fd = -1; + } +} + +void ps_capture_list_interfaces(FILE *out) { + struct ifaddrs *addrs = NULL; + + if (getifaddrs(&addrs) != 0) { + return; + } + for (struct ifaddrs *a = addrs; a; a = a->ifa_next) { + if (!a->ifa_name || !(a->ifa_flags & IFF_UP)) { + continue; + } + if (!(a->ifa_flags & (IFF_RUNNING | IFF_LOOPBACK))) { + continue; + } + fprintf(out, " %-16s %s%s\n", a->ifa_name, (a->ifa_flags & IFF_LOOPBACK) ? "loopback" : "", + (a->ifa_flags & IFF_PROMISC) ? " (promisc)" : ""); + } + freeifaddrs(addrs); +} diff --git a/src/client.c b/src/client.c new file mode 100644 index 0000000..fdfc564 --- /dev/null +++ b/src/client.c @@ -0,0 +1,521 @@ +/* client.c - connect, decode, filter, render, record. */ +#include "client.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "decode.h" +#include "filter.h" +#include "log.h" +#include "pcap.h" +#include "proto.h" +#include "stats.h" +#include "util.h" + +#define CLIENT_RECV_CHUNK 65536 +#define RECONNECT_MIN_MS 500 +#define RECONNECT_MAX_MS 15000 + +static volatile sig_atomic_t g_stop = 0; + +static void on_signal(int sig) { + PS_UNUSED(sig); + g_stop = 1; +} + +/* ---- ANSI ---- */ +#define C_RESET "\033[0m" +#define C_DIM "\033[2m" +#define C_RED "\033[31m" +#define C_GREEN "\033[32m" +#define C_YELLOW "\033[33m" +#define C_BLUE "\033[34m" +#define C_MAGENTA "\033[35m" +#define C_CYAN "\033[36m" +#define C_BOLD "\033[1m" + +static const char *proto_color(const struct ps_decoded *d, int color) { + if (!color) { + return ""; + } + if (d->ethertype == 0x0806) { + return C_MAGENTA; + } + switch (d->l4) { + case PS_L4_TCP: + return C_GREEN; + case PS_L4_UDP: + return C_BLUE; + case PS_L4_ICMP: + case PS_L4_ICMPV6: + return C_YELLOW; + default: + return C_DIM; + } +} + +struct client_state { + int fd; + struct ps_reader reader; + struct ps_filter filter; + struct ps_pcap pcap; + int have_pcap; + uint16_t linktype; + uint32_t snaplen; + FILE *json; + int json_owns_fp; + uint64_t matched; + uint64_t received; + uint64_t ts_base_us; /* offset so client timestamps line up with capture time */ + struct ps_counters server_stats; + int have_server_stats; + const struct ps_client_opts *opts; + int color; /* resolved once from the option and isatty() */ +}; + +static void json_escape(const char *in, char *out, size_t cap) { + size_t w = 0; + + for (; *in && w + 7 < cap; in++) { + unsigned char c = (unsigned char)*in; + switch (c) { + case '"': + out[w++] = '\\'; + out[w++] = '"'; + break; + case '\\': + out[w++] = '\\'; + out[w++] = '\\'; + break; + case '\n': + out[w++] = '\\'; + out[w++] = 'n'; + break; + case '\r': + out[w++] = '\\'; + out[w++] = 'r'; + break; + case '\t': + out[w++] = '\\'; + out[w++] = 't'; + break; + default: + if (c < 0x20) { + snprintf(out + w, cap - w, "\\u%04x", c); + w += 6; + } else { + out[w++] = (char)c; + } + break; + } + } + out[w] = '\0'; +} + +static void emit_json(struct client_state *st, const struct ps_decoded *d, + const struct ps_record *rec) { + char src[128]; + char dst[128]; + char app[400]; + char flags[64]; + char mac_s[24]; + char mac_d[24]; + + json_escape(d->src, src, sizeof(src)); + json_escape(d->dst, dst, sizeof(dst)); + json_escape(d->app[0] ? d->app : d->info, app, sizeof(app)); + ps_tcp_flag_str(d->tcp_flags, flags, sizeof(flags)); + json_escape(d->src_mac, mac_s, sizeof(mac_s)); + json_escape(d->dst_mac, mac_d, sizeof(mac_d)); + + fprintf(st->json, + "{\"ts\":%u.%06u,\"caplen\":%u,\"len\":%u,\"proto\":\"%s\",\"ip_version\":%d," + "\"src\":\"%s\",\"dst\":\"%s\",\"sport\":%u,\"dport\":%u,\"ttl\":%u," + "\"tcp\":{\"seq\":%u,\"ack\":%u,\"flags\":\"%s\",\"win\":%u}," + "\"vlan\":%u,\"src_mac\":\"%s\",\"dst_mac\":\"%s\",\"app\":\"%s\"}\n", + rec->ts_sec, rec->ts_usec, rec->caplen, rec->origlen, ps_proto_label(d), + d->ip_version, src, dst, d->sport, d->dport, d->ttl, d->seq, d->ack, flags, d->window, + d->has_vlan ? d->vlan_id : 0, mac_s, mac_d, app); + fflush(st->json); +} + +static void print_line(struct client_state *st, const struct ps_decoded *d, + const struct ps_record *rec) { + const struct ps_client_opts *o = st->opts; + struct tm tm; + char clock[16]; + char line[512]; + char hex[4096]; + time_t secs = (time_t)rec->ts_sec; + + localtime_r(&secs, &tm); + snprintf(clock, sizeof(clock), "%02d:%02d:%02d.%06u", tm.tm_hour, tm.tm_min, tm.tm_sec, + rec->ts_usec); + + ps_decoded_format_line(d, line, sizeof(line)); + + if (st->color) { + printf("%s%s" C_RESET " " C_DIM "#%06llu" C_RESET " %s%s" C_RESET "\n", C_DIM, clock, + (unsigned long long)st->matched, proto_color(d, 1), line); + } else { + printf("%s #%06llu %s\n", clock, (unsigned long long)st->matched, line); + } + + if (o->hex_bytes > 0 && rec->caplen > 0) { + ps_hexdump(rec->data, rec->caplen, o->hex_bytes, hex, sizeof(hex)); + printf("%s\n", hex); + } +} + +static void print_stats_line(struct client_state *st, const struct ps_counters *c) { + char line[512]; + + ps_counters_format(c, line, sizeof(line)); + if (st->color) { + fprintf(stderr, C_DIM "%s" C_RESET "\n", line); + } else { + fprintf(stderr, "%s\n", line); + } + fflush(stderr); +} + +static void handle_packet(struct client_state *st, const struct ps_record *rec) { + struct ps_decoded d; + + st->received++; + if (ps_decode(rec->data, rec->caplen, rec->origlen, st->linktype, &d) != 0) { + if (ps_log_enabled(PS_LOG_DEBUG)) { + LOG_DEBUG("undecodable frame (%u bytes)", rec->caplen); + } + return; + } + if (!ps_filter_match(&st->filter, &d)) { + return; + } + st->matched++; + + if (st->json) { + emit_json(st, &d, rec); + } else { + print_line(st, &d, rec); + } + if (st->have_pcap && ps_pcap_write(&st->pcap, rec) != 0) { + LOG_WARN("pcap write failed: %s", strerror(errno)); + } +} + +static void handle_frame(struct client_state *st, const struct ps_frame *f) { + switch (f->type) { + case PS_FRAME_PACKET: { + struct ps_record rec; + if (ps_packet_decode(f->data, f->len, &rec) != 0) { + LOG_WARN("malformed PACKET frame (%u bytes)", f->len); + return; + } + handle_packet(st, &rec); + break; + } + case PS_FRAME_HELLO: { + struct ps_hello hello; + + if (ps_hello_decode(f->data, f->len, &hello) != 0) { + LOG_WARN("malformed HELLO frame"); + return; + } + st->linktype = hello.linktype; + st->snaplen = hello.snaplen; + + if (st->opts->pcap_path && *st->opts->pcap_path && !st->have_pcap) { + char err[256]; + if (ps_pcap_open(&st->pcap, st->opts->pcap_path, hello.snaplen, hello.linktype, + st->opts->pcap_rotate_bytes, err, sizeof(err)) != 0) { + LOG_ERROR("%s", err); + } else { + st->have_pcap = 1; + LOG_INFO("recording to %s", st->opts->pcap_path); + } + } + if (!st->opts->quiet) { + LOG_INFO("connected to %s (%s%s%s, linktype %u, snap %u, filter \"%s\")", + hello.hostname[0] ? hello.hostname : "server", hello.iface[0] ? "iface " : "", + hello.iface, hello.iface[0] ? "" : "default", hello.linktype, hello.snaplen, + hello.filter[0] ? hello.filter : "none"); + } + break; + } + case PS_FRAME_STATS: { + if (ps_counters_decode(f->data, f->len, &st->server_stats) != 0) { + LOG_WARN("malformed STATS frame"); + return; + } + st->have_server_stats = 1; + break; + } + case PS_FRAME_BYE: + g_stop = 1; + LOG_INFO("server closed the stream"); + break; + case PS_FRAME_ERR: + LOG_ERROR("server: %s", f->len ? (const char *)f->data : "unspecified error"); + g_stop = 1; + break; + default: + LOG_WARN("unknown frame type %u (%u bytes)", f->type, f->len); + break; + } +} + +static int connect_to(const char *host, uint16_t port, char *err, size_t errsz) { + struct addrinfo hints; + struct addrinfo *res = NULL; + char portstr[8]; + int fd = -1; + + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + snprintf(portstr, sizeof(portstr), "%u", (unsigned)port); + + int rc = getaddrinfo(host, portstr, &hints, &res); + if (rc != 0) { + snprintf(err, errsz, "resolve %s: %s", host, gai_strerror(rc)); + return -1; + } + + for (struct addrinfo *ai = res; ai; ai = ai->ai_next) { + fd = socket(ai->ai_family, ai->ai_socktype | SOCK_CLOEXEC, ai->ai_protocol); + if (fd < 0) { + continue; + } + if (connect(fd, ai->ai_addr, ai->ai_addrlen) == 0) { + break; + } + snprintf(err, errsz, "connect %s:%u: %s", host, (unsigned)port, strerror(errno)); + close(fd); + fd = -1; + } + freeaddrinfo(res); + + if (fd >= 0) { + int one = 1; + setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one)); + } + return fd; +} + +int ps_client_run(const struct ps_client_opts *opts) { + struct client_state st; + char err[256]; + int rc = 0; + time_t deadline = 0; + time_t next_stats = 0; + unsigned backoff = RECONNECT_MIN_MS; + + memset(&st, 0, sizeof(st)); + st.fd = -1; + st.opts = opts; + st.color = opts->color < 0 ? isatty(STDOUT_FILENO) : opts->color; + ps_reader_init(&st.reader, CLIENT_RECV_CHUNK); + + if (ps_filter_parse(opts->filter, &st.filter, err, sizeof(err)) != 0) { + LOG_ERROR("%s", err); + rc = 2; + goto cleanup; + } + + if (opts->json_path && *opts->json_path) { + if (strcmp(opts->json_path, "-") == 0) { + st.json = stdout; + } else { + st.json = fopen(opts->json_path, "w"); + if (!st.json) { + LOG_ERROR("cannot open %s: %s", opts->json_path, strerror(errno)); + rc = 2; + goto cleanup; + } + st.json_owns_fp = 1; + } + } + + struct sigaction sa; + memset(&sa, 0, sizeof(sa)); + sa.sa_handler = on_signal; + sigaction(SIGINT, &sa, NULL); + sigaction(SIGTERM, &sa, NULL); + signal(SIGPIPE, SIG_IGN); + + if (opts->duration) { + deadline = time(NULL) + (time_t)opts->duration; + } + next_stats = time(NULL) + (time_t)(opts->stats_interval ? opts->stats_interval : 5); + + if (!opts->quiet && !st.json) { + fprintf(stderr, "%s %s | %s:%u | filter: %s | hex: %zu B\n", PS_NAME, PS_VERSION_STR, + opts->host, (unsigned)opts->port, + ps_filter_is_empty(&st.filter) ? "none" : st.filter.source, + opts->hex_bytes); + } + + while (!g_stop) { + if (st.fd < 0) { + st.fd = connect_to(opts->host, opts->port, err, sizeof(err)); + if (st.fd < 0) { + LOG_ERROR("%s", err); + if (!opts->reconnect) { + rc = 1; + break; + } + ps_sleep_ms(backoff); + backoff = MIN(backoff * 2, RECONNECT_MAX_MS); + continue; + } + backoff = RECONNECT_MIN_MS; + ps_reader_reset(&st.reader); + } + + struct pollfd pfd; + pfd.fd = st.fd; + pfd.events = POLLIN; + pfd.revents = 0; + + int timeout = 500; + int pr = poll(&pfd, 1, timeout); + if (pr < 0) { + if (errno == EINTR) { + continue; + } + LOG_ERROR("poll: %s", strerror(errno)); + rc = 1; + break; + } + + if (pr > 0) { + if (pfd.revents & (POLLIN | POLLHUP | POLLERR)) { + uint8_t chunk[CLIENT_RECV_CHUNK]; + ssize_t n = recv(st.fd, chunk, sizeof(chunk), 0); + + if (n > 0) { + if (ps_reader_feed(&st.reader, chunk, (size_t)n) != 0) { + LOG_ERROR("stream desynchronised, reconnecting"); + close(st.fd); + st.fd = -1; + ps_reader_reset(&st.reader); + if (!opts->reconnect) { + rc = 1; + break; + } + continue; + } + struct ps_frame frame; + int got; + while ((got = ps_reader_next(&st.reader, &frame)) == 1) { + handle_frame(&st, &frame); + if (g_stop || (opts->count && st.matched >= opts->count)) { + break; + } + } + if (got < 0) { + LOG_ERROR("protocol error on stream after %llu frames, reconnecting", + (unsigned long long)st.received); + if (ps_log_enabled(PS_LOG_DEBUG)) { + char hex[3 * 32 + 8]; + size_t hn = MIN(st.reader.len, 24u); + for (size_t k = 0; k < hn; k++) { + snprintf(hex + k * 3, 4, "%02x ", st.reader.buf[k]); + } + hex[hn * 3] = 0; + LOG_DEBUG("reader len=%zu scratch_cap=%zu head: %s", st.reader.len, + st.reader.frame_cap, hex); + } + close(st.fd); + st.fd = -1; + ps_reader_reset(&st.reader); + if (!opts->reconnect) { + rc = 1; + break; + } + continue; + } + fflush(stdout); + } else if (n == 0) { + if (opts->reconnect && !g_stop) { + LOG_WARN("server closed the connection, reconnecting"); + close(st.fd); + st.fd = -1; + ps_reader_reset(&st.reader); + ps_sleep_ms(backoff); + backoff = MIN(backoff * 2, RECONNECT_MAX_MS); + continue; + } + LOG_INFO("server closed the connection"); + g_stop = 1; + break; + } else if (errno != EAGAIN && errno != EINTR) { + LOG_ERROR("recv: %s", strerror(errno)); + close(st.fd); + st.fd = -1; + if (!opts->reconnect) { + rc = 1; + break; + } + continue; + } + } + } + + time_t now = time(NULL); + if (opts->show_stats && now >= next_stats) { + if (st.have_server_stats) { + print_stats_line(&st, &st.server_stats); + } + next_stats = now + (time_t)(opts->stats_interval ? opts->stats_interval : 5); + } + if (deadline && now >= deadline) { + break; + } + if (opts->count && st.matched >= opts->count) { + break; + } + } + + /* Emit any complete frames still sitting in the read buffer, unless the + * packet count already ended the run. */ + struct ps_frame frame; + while ((!opts->count || st.matched < opts->count) && !g_stop && + ps_reader_next(&st.reader, &frame) == 1) { + handle_frame(&st, &frame); + } + + if (!opts->quiet) { + fprintf(stderr, "matched %llu of %llu received frames\n", + (unsigned long long)st.matched, (unsigned long long)st.received); + } + +cleanup: + if (st.fd >= 0) { + close(st.fd); + } + if (st.have_pcap) { + if (ps_pcap_flush(&st.pcap) != 0) { + LOG_WARN("pcap flush failed"); + } + LOG_INFO("wrote %llu packets to pcap", (unsigned long long)st.pcap.packets_written); + ps_pcap_close(&st.pcap); + } + if (st.json_owns_fp && st.json) { + fclose(st.json); + } + ps_reader_free(&st.reader); + return rc; +} diff --git a/src/decode.c b/src/decode.c new file mode 100644 index 0000000..db40606 --- /dev/null +++ b/src/decode.c @@ -0,0 +1,687 @@ +/* decode.c - bounds-checked protocol dissection. */ +#include "decode.h" + +#include +#include +#include + +#include "util.h" + +#define ETH_HDR_LEN 14u +#define VLAN_TAG_LEN 4u +#define SLL_HDR_LEN 16u +#define SLL2_HDR_LEN 20u + +#define ETHERTYPE_IPV4 0x0800 +#define ETHERTYPE_ARP 0x0806 +#define ETHERTYPE_IPV6 0x86DD +#define ETHERTYPE_VLAN 0x8100 +#define ETHERTYPE_QINQ 0x88A8 +#define ETHERTYPE_VLAN_9100 0x9100 + +const char *ps_l4_name(enum ps_l4 l4) { + switch (l4) { + case PS_L4_TCP: + return "TCP"; + case PS_L4_UDP: + return "UDP"; + case PS_L4_ICMP: + return "ICMP"; + case PS_L4_ICMPV6: + return "ICMP6"; + case PS_L4_OTHER: + return "L4"; + default: + return "-"; + } +} + +const char *ps_proto_label(const struct ps_decoded *d) { + if (d->ethertype == ETHERTYPE_ARP) { + return "ARP"; + } + if (d->ip_version == 0) { + return "ETH"; + } + return ps_l4_name(d->l4); +} + +void ps_tcp_flag_str(uint8_t flags, char *buf, size_t cap) { + static const struct { + uint8_t bit; + const char *name; + } names[] = { + {PS_TCP_SYN, "SYN"}, {PS_TCP_ACK, "ACK"}, {PS_TCP_FIN, "FIN"}, {PS_TCP_RST, "RST"}, + {PS_TCP_PSH, "PSH"}, {PS_TCP_URG, "URG"}, {PS_TCP_ECE, "ECE"}, {PS_TCP_CWR, "CWR"}, + }; + size_t off = 0; + + buf[0] = '\0'; + for (size_t i = 0; i < PS_ARRAY_LEN(names); i++) { + if (flags & names[i].bit) { + off = ps_appendf(buf, cap, off, "%s%s", off ? "," : "", names[i].name); + } + } +} + +static void fmt_mac(const uint8_t *mac, char *out, size_t cap) { + snprintf(out, cap, "%02x:%02x:%02x:%02x:%02x:%02x", mac[0], mac[1], mac[2], mac[3], mac[4], + mac[5]); +} + +/* ---- application layer peeking ---- */ + +static void dns_name(const uint8_t *p, uint32_t len, uint32_t off, char *out, size_t cap) { + size_t w = 0; + int jumps = 0; + + out[0] = '\0'; + while (off < len && jumps < 32) { + uint8_t label = p[off]; + + if (label == 0) { + break; + } + if ((label & 0xC0) == 0xC0) { /* compression pointer */ + if (off + 1 >= len) { + return; + } + off = (uint32_t)((label & 0x3F) << 8 | p[off + 1]); + jumps++; + continue; + } + if (off + 1 + label >= len) { + return; + } + if (w > 0 && w + 1 < cap) { + out[w++] = '.'; + } + for (uint8_t i = 0; i < label && w + 1 < cap; i++) { + out[w++] = (char)p[off + 1 + i]; + } + off += 1u + label; + } + if (w < cap) { + out[w] = '\0'; + } else { + out[cap - 1] = '\0'; + } +} + +static void peek_dns(struct ps_decoded *d) { + const uint8_t *p = d->payload; + uint32_t len = d->payload_len; + char name[128]; + + if (len < 12) { + return; + } + d->app_flags |= PS_APP_DNS; + + if (d->sport == 53 || d->dport == 53) { + uint16_t flags = ps_be16(p + 2); + uint16_t qdcount = ps_be16(p + 4); + int response = (flags & 0x8000) != 0; + + if (qdcount == 0) { + snprintf(d->app, sizeof(d->app), "DNS %s", response ? "response" : "query"); + return; + } + dns_name(p, len, 12, name, sizeof(name)); + /* Type of the question follows the name; recompute its end. */ + uint32_t off = 12; + while (off < len && p[off] != 0 && (p[off] & 0xC0) != 0xC0) { + off += 1u + p[off]; + } + off += 1; + const char *qtype = ""; + if (off + 2 <= len) { + switch (ps_be16(p + off)) { + case 1: + qtype = " A"; + break; + case 2: + qtype = " NS"; + break; + case 5: + qtype = " CNAME"; + break; + case 12: + qtype = " PTR"; + break; + case 15: + qtype = " MX"; + break; + case 16: + qtype = " TXT"; + break; + case 28: + qtype = " AAAA"; + break; + case 33: + qtype = " SRV"; + break; + case 65: + qtype = " HTTPS"; + break; + default: + qtype = " ?"; + break; + } + } + snprintf(d->app, sizeof(d->app), "DNS%s%s %s", response ? "(r)" : "", qtype, name); + } +} + +/* Walks a TLS ClientHello looking for the server_name extension (RFC 6066). */ +static void peek_tls(struct ps_decoded *d) { + const uint8_t *p = d->payload; + uint32_t len = d->payload_len; + uint32_t off; + uint32_t ext_end; + + if (len < 43 || p[0] != 0x16 || p[1] != 0x03) { + return; + } + d->app_flags |= PS_APP_TLS; + + /* record(5) handshake(4) version(2) random(32) sid_len(1) sid ... */ + off = 5 + 4 + 2 + 32; + if (off >= len) { + goto generic; + } + off += 1u + p[off]; /* session id */ + if (off + 2 > len) { + goto generic; + } + off += 2u + ps_be16(p + off); /* cipher suites */ + if (off + 1 > len) { + goto generic; + } + off += 1u + p[off]; /* compression methods */ + if (off + 2 > len) { + goto generic; + } + ext_end = off + 2u + ps_be16(p + off); + off += 2; + if (ext_end > len) { + ext_end = len; + } + + while (off + 4 <= ext_end) { + uint16_t ext_type = ps_be16(p + off); + uint16_t ext_len = ps_be16(p + off + 2); + + off += 4; + if (off + ext_len > ext_end) { + break; + } + if (ext_type == 0x0000 && ext_len > 5) { /* server_name */ + uint16_t list_len = ps_be16(p + off); + uint32_t p2 = off + 2; + + if (p2 + 3 <= off + ext_len && list_len >= 3) { + uint8_t name_type = p[p2]; + uint16_t name_len = ps_be16(p + p2 + 1); + p2 += 3; + if (name_type == 0 && p2 + name_len <= off + ext_len) { + snprintf(d->app, sizeof(d->app), "TLS SNI=%.*s", (int)name_len, + (const char *)(p + p2)); + return; + } + } + } + off += ext_len; + } + +generic: + snprintf(d->app, sizeof(d->app), "TLS handshake"); +} + +static void peek_http(struct ps_decoded *d) { + static const char *verbs[] = {"GET ", "POST ", "HEAD ", "PUT ", "DELETE ", "OPTIONS ", + "PATCH ", "HTTP/"}; + const uint8_t *p = d->payload; + uint32_t len = d->payload_len; + + if (len < 4) { + return; + } + for (size_t i = 0; i < PS_ARRAY_LEN(verbs); i++) { + size_t n = strlen(verbs[i]); + if (len >= n && memcmp(p, verbs[i], n) == 0) { + size_t end = 0; + while (end < len && p[end] != '\r' && p[end] != '\n' && end < 96) { + end++; + } + snprintf(d->app, sizeof(d->app), "HTTP %.*s", (int)end, (const char *)p); + d->app_flags |= PS_APP_HTTP; + return; + } + } +} + +/* ---- transport layer ---- */ + +static void decode_tcp(const uint8_t *p, uint32_t len, struct ps_decoded *d) { + if (len < 20) { + return; + } + d->l4 = PS_L4_TCP; + d->l4_proto = 6; + d->sport = ps_be16(p + 0); + d->dport = ps_be16(p + 2); + d->seq = ps_be32(p + 4); + d->ack = ps_be32(p + 8); + d->tcp_flags = p[13]; + d->window = ps_be16(p + 14); + + uint32_t hdr = (uint32_t)(p[12] >> 4) * 4u; + if (hdr < 20 || hdr > len) { + hdr = 20; + } else { + /* MSS option, if present (kind 2, len 4). */ + uint32_t opt = 20; + while (opt + 1 < hdr) { + uint8_t kind = p[opt]; + if (kind == 0) { + break; + } + if (kind == 1) { + opt++; + continue; + } + if (opt + 2 > hdr) { + break; + } + uint8_t olen = p[opt + 1]; + if (olen < 2 || opt + olen > hdr) { + break; + } + if (kind == 2 && olen == 4) { + d->tcp_mss = ps_be16(p + opt + 2); + } + opt += olen; + } + } + + d->l4_len = (uint16_t)MIN(len, 0xFFFFu); + d->payload = p + hdr; + d->payload_len = len - hdr; +} + +static void decode_udp(const uint8_t *p, uint32_t len, struct ps_decoded *d) { + if (len < 8) { + return; + } + d->l4 = PS_L4_UDP; + d->l4_proto = 17; + d->sport = ps_be16(p + 0); + d->dport = ps_be16(p + 2); + d->l4_len = ps_be16(p + 4); + + d->payload = p + 8; + d->payload_len = len - 8; + if (d->l4_len >= 8 && (uint32_t)d->l4_len - 8 < d->payload_len) { + d->payload_len = d->l4_len - 8; + } +} + +static void decode_icmp(const uint8_t *p, uint32_t len, struct ps_decoded *d, int v6) { + if (len < 4) { + return; + } + d->l4 = v6 ? PS_L4_ICMPV6 : PS_L4_ICMP; + d->l4_proto = v6 ? 58 : 1; + d->icmp_type = p[0]; + d->icmp_code = p[1]; + d->l4_len = (uint16_t)MIN(len, 0xFFFFu); + d->payload = len > 8 ? p + 8 : NULL; + d->payload_len = len > 8 ? len - 8 : 0; +} + +/* ---- network layer ---- */ + +static void decode_arp(const uint8_t *p, uint32_t len, struct ps_decoded *d) { + if (len < 8) { + return; + } + d->arp_op = ps_be16(p + 6); + if (len >= 28) { + fmt_mac(p + 8, d->arp_sender_mac, sizeof(d->arp_sender_mac)); + inet_ntop(AF_INET, p + 14, d->arp_sender_ip, sizeof(d->arp_sender_ip)); + inet_ntop(AF_INET, p + 24, d->arp_target_ip, sizeof(d->arp_target_ip)); + } + switch (d->arp_op) { + case 1: + snprintf(d->info, sizeof(d->info), "who-has %s tell %s", d->arp_target_ip, + d->arp_sender_ip); + break; + case 2: + snprintf(d->info, sizeof(d->info), "%s is-at %s", d->arp_sender_ip, d->arp_sender_mac); + break; + default: + snprintf(d->info, sizeof(d->info), "op=%u", d->arp_op); + break; + } +} + +static void decode_ipv4(const uint8_t *p, uint32_t len, struct ps_decoded *d) { + uint32_t ihl; + uint32_t total_len; + uint32_t avail; + uint16_t frag; + + if (len < 20) { + return; + } + ihl = (uint32_t)(p[0] & 0x0F) * 4u; + if (ihl < 20 || ihl > len) { + return; + } + total_len = ps_be16(p + 2); + d->ip_version = 4; + d->l4_proto = p[9]; + d->ttl = p[8]; + inet_ntop(AF_INET, p + 12, d->src, sizeof(d->src)); + inet_ntop(AF_INET, p + 16, d->dst, sizeof(d->dst)); + + frag = ps_be16(p + 6); + if ((frag & 0x2000) != 0 || (frag & 0x1FFF) != 0) { + d->fragmented = 1; + } + + avail = len - ihl; + if (total_len >= ihl && total_len - ihl < avail) { + avail = total_len - ihl; /* ignore Ethernet padding */ + } + if (frag & 0x1FFF) { + /* Non-first fragment: no transport header present. */ + d->l4 = PS_L4_OTHER; + return; + } + + const uint8_t *l4 = p + ihl; + switch (d->l4_proto) { + case 6: + decode_tcp(l4, avail, d); + break; + case 17: + decode_udp(l4, avail, d); + break; + case 1: + decode_icmp(l4, avail, d, 0); + break; + case 2: + case 4: + case 47: + case 132: + d->l4 = PS_L4_OTHER; + break; + default: + d->l4 = PS_L4_OTHER; + break; + } +} + +static void decode_ipv6(const uint8_t *p, uint32_t len, struct ps_decoded *d) { + uint8_t next; + uint32_t off = 40; + + if (len < 40) { + return; + } + d->ip_version = 6; + d->ttl = p[7]; + next = p[6]; + inet_ntop(AF_INET6, p + 8, d->src, sizeof(d->src)); + inet_ntop(AF_INET6, p + 24, d->dst, sizeof(d->dst)); + + /* Skip extension headers. */ + while (off + 8 <= len) { + if (next == 0 || next == 43 || next == 60) { + uint8_t hdr_next = p[off]; + uint32_t hdr_len = ((uint32_t)p[off + 1] + 1u) * 8u; + off += hdr_len; + next = hdr_next; + continue; + } + if (next == 44) { /* fragment */ + uint16_t frag = ps_be16(p + off + 2); + d->fragmented = 1; + next = p[off]; + off += 8; + if ((frag & 0xFFF8) != 0) { + d->l4_proto = next; + d->l4 = PS_L4_OTHER; + return; + } + continue; + } + break; + } + if (off > len) { + return; + } + + d->l4_proto = next; + const uint8_t *l4 = p + off; + uint32_t avail = len - off; + + switch (next) { + case 6: + decode_tcp(l4, avail, d); + break; + case 17: + decode_udp(l4, avail, d); + break; + case 58: + decode_icmp(l4, avail, d, 1); + break; + default: + d->l4 = PS_L4_OTHER; + break; + } +} + +/* ---- link layer ---- */ + +int ps_decode(const uint8_t *data, uint32_t caplen, uint32_t origlen, uint16_t linktype, + struct ps_decoded *out) { + uint32_t off = 0; + uint16_t ethertype = 0; + + memset(out, 0, sizeof(*out)); + out->caplen = caplen; + out->origlen = origlen; + + switch (linktype) { + case PS_DLT_EN10MB: { + if (caplen < ETH_HDR_LEN) { + return -1; + } + out->has_eth = 1; + fmt_mac(data + 6, out->src_mac, sizeof(out->src_mac)); + fmt_mac(data + 0, out->dst_mac, sizeof(out->dst_mac)); + ethertype = ps_be16(data + 12); + off = ETH_HDR_LEN; + + while ((ethertype == ETHERTYPE_VLAN || ethertype == ETHERTYPE_QINQ || + ethertype == ETHERTYPE_VLAN_9100) && + caplen >= off + VLAN_TAG_LEN) { + if (!out->has_vlan) { + out->has_vlan = 1; + out->vlan_id = ps_be16(data + off) & 0x0FFF; + } + ethertype = ps_be16(data + off + 2); + off += VLAN_TAG_LEN; + } + break; + } + case PS_DLT_LINUX_SLL: { + if (caplen < SLL_HDR_LEN) { + return -1; + } + ethertype = ps_be16(data + 14); + off = SLL_HDR_LEN; + break; + } + case PS_DLT_LINUX_SLL2: { + if (caplen < SLL2_HDR_LEN) { + return -1; + } + ethertype = ps_be16(data + 0); + off = SLL2_HDR_LEN; + break; + } + case PS_DLT_NULL: + case PS_DLT_LOOP: { + uint32_t family; + + if (caplen < 4) { + return -1; + } + family = linktype == PS_DLT_NULL ? ps_le32(data) : ps_be32(data); + off = 4; + switch (family) { + case 2: /* AF_INET */ + ethertype = ETHERTYPE_IPV4; + break; + case 10: + case 24: + case 28: + case 30: /* AF_INET6 variants */ + ethertype = ETHERTYPE_IPV6; + break; + default: + out->ethertype = (uint16_t)family; + return 0; + } + break; + } + case PS_DLT_RAW: { + if (caplen < 1) { + return -1; + } + ethertype = (data[0] >> 4) == 4 ? ETHERTYPE_IPV4 : ETHERTYPE_IPV6; + break; + } + default: + return -1; + } + + out->ethertype = ethertype; + if (caplen < off) { + return -1; + } + const uint8_t *l3 = data + off; + uint32_t l3_len = caplen - off; + + switch (ethertype) { + case ETHERTYPE_IPV4: + decode_ipv4(l3, l3_len, out); + break; + case ETHERTYPE_IPV6: + decode_ipv6(l3, l3_len, out); + break; + case ETHERTYPE_ARP: + decode_arp(l3, l3_len, out); + break; + default: + out->ip_version = 0; + break; + } + + if (out->l4 == PS_L4_UDP && out->payload_len > 0 && + (out->sport == 53 || out->dport == 53)) { + peek_dns(out); + } else if (out->l4 == PS_L4_TCP && out->payload_len > 0) { + if (out->payload[0] == 0x16) { + peek_tls(out); + } else { + peek_http(out); + } + } + return 0; +} + +/* ---- rendering ---- */ + +void ps_decoded_format_line(const struct ps_decoded *d, char *out, size_t cap) { + size_t off = 0; + char flags[48]; + char ports[96]; + + ports[0] = '\0'; + if (d->l4 == PS_L4_TCP || d->l4 == PS_L4_UDP) { + snprintf(ports, sizeof(ports), ":%u -> %s:%u", d->sport, d->dst, d->dport); + } else if (d->ip_version) { + snprintf(ports, sizeof(ports), " -> %s", d->dst); + } + + if (d->ip_version) { + off = ps_appendf(out, cap, off, "%-5s %s%s", ps_proto_label(d), d->src, ports); + } else if (d->ethertype == ETHERTYPE_ARP) { + off = ps_appendf(out, cap, off, "%-5s %s > %s", "ARP", d->src_mac, d->dst_mac); + } else { + off = ps_appendf(out, cap, off, "%-5s %s > %s type=0x%04x", "ETH", d->src_mac, + d->dst_mac, d->ethertype); + } + + off = ps_appendf(out, cap, off, " %u B", d->origlen); + if (d->ip_version) { + off = ps_appendf(out, cap, off, " ttl=%u", d->ttl); + } + if (d->has_vlan) { + off = ps_appendf(out, cap, off, " vlan=%u", d->vlan_id); + } + + if (d->l4 == PS_L4_TCP) { + ps_tcp_flag_str(d->tcp_flags, flags, sizeof(flags)); + if (flags[0]) + off = ps_appendf(out, cap, off, " %s", flags); + off = ps_appendf(out, cap, off, " seq=%u ack=%u win=%u", d->seq, d->ack, d->window); + } else if (d->l4 == PS_L4_ICMP || d->l4 == PS_L4_ICMPV6) { + off = ps_appendf(out, cap, off, " type=%u code=%u", d->icmp_type, d->icmp_code); + } + + if (d->fragmented) { + off = ps_appendf(out, cap, off, " frag"); + } + if (d->app[0]) { + off = ps_appendf(out, cap, off, " | %s", d->app); + } else if (d->info[0]) { + ps_appendf(out, cap, off, " | %s", d->info); + } +} + +void ps_hexdump(const uint8_t *data, size_t len, size_t max, char *out, size_t cap) { + size_t off = 0; + size_t show = MIN(len, max); + char ascii[17]; + + for (size_t i = 0; i < show; i += 16) { + off = ps_appendf(out, cap, off, " %04zx ", i); + for (size_t j = 0; j < 16; j++) { + if (i + j < show) { + off = ps_appendf(out, cap, off, "%02x ", data[i + j]); + uint8_t c = data[i + j]; + ascii[j] = (c >= 0x20 && c < 0x7F) ? (char)c : '.'; + } else { + off = ps_appendf(out, cap, off, " "); + ascii[j] = ' '; + } + if (j == 7) { + off = ps_appendf(out, cap, off, " "); + } + } + ascii[16] = '\0'; + off = ps_appendf(out, cap, off, " |%s|", ascii); + if (i + 16 < show) { + off = ps_appendf(out, cap, off, "\n"); + } + } + if (show < len) { + ps_appendf(out, cap, off, "\n ... %zu more bytes", len - show); + } +} diff --git a/src/filter.c b/src/filter.c new file mode 100644 index 0000000..d53915e --- /dev/null +++ b/src/filter.c @@ -0,0 +1,421 @@ +/* filter.c - client-side display filter. */ +#include "filter.h" + +#include +#include +#include +#include +#include + +#include "util.h" + +static int parse_addr(const char *text, struct ps_filter_clause *c) { + char buf[128]; + char *slash; + int bits = -1; + + ps_strlcpy(buf, text, sizeof(buf)); + slash = strchr(buf, '/'); + if (slash) { + char *end = NULL; + long v; + *slash = '\0'; + v = strtol(slash + 1, &end, 10); + if (!end || *end != '\0' || v < 0 || v > 128) { + return -1; + } + bits = (int)v; + } + + if (inet_pton(AF_INET, buf, &c->addr4) == 1) { + c->is_v6 = 0; + if (bits < 0) { + bits = 32; + } else if (bits > 32) { + return -1; + } + c->mask4 = bits == 0 ? 0 : htonl(0xFFFFFFFFu << (32 - bits)); + c->addr4 &= c->mask4; + return 0; + } + if (inet_pton(AF_INET6, buf, c->addr6) == 1) { + c->is_v6 = 1; + if (bits < 0) { + bits = 128; + } + memset(c->mask6, 0, sizeof(c->mask6)); + for (int i = 0; i < bits; i++) { + c->mask6[i / 8] |= (uint8_t)(0x80 >> (i % 8)); + } + for (int i = 0; i < 16; i++) { + c->addr6[i] &= c->mask6[i]; + } + return 0; + } + return -1; +} + +static int addr_matches(const struct ps_filter_clause *c, const char *text) { + unsigned char raw[16]; + + memset(raw, 0, sizeof(raw)); + if (inet_pton(AF_INET, text, raw) == 1) { + if (c->is_v6) { + return 0; + } + uint32_t v = 0; + memcpy(&v, raw, 4); + return (v & c->mask4) == c->addr4; + } + if (inet_pton(AF_INET6, text, raw) == 1) { + if (!c->is_v6) { + return 0; + } + for (int i = 0; i < 16; i++) { + if ((raw[i] & c->mask6[i]) != c->addr6[i]) { + return 0; + } + } + return 1; + } + return 0; +} + +static int parse_bytes(const char *value, struct ps_filter_clause *c) { + enum ps_filter_cmp cmp = PS_CMP_EQ; + const char *p = value; + + if (p[0] == '>') { + if (p[1] == '=') { + cmp = PS_CMP_GE; + p += 2; + } else { + cmp = PS_CMP_GT; + p += 1; + } + } else if (p[0] == '<') { + if (p[1] == '=') { + cmp = PS_CMP_LE; + p += 2; + } else { + cmp = PS_CMP_LT; + p += 1; + } + } else if (p[0] == '=') { + p += 1; + } + if (ps_parse_u32(p, &c->bytes) != 0) { + return -1; + } + c->cmp = cmp; + return 0; +} + +static const char *const known_protos[] = { + "tcp", "udp", "icmp", "icmp6", "arp", "ip6", "dns", "tls", "http", +}; + +static int proto_known(const char *name) { + for (size_t i = 0; i < sizeof(known_protos) / sizeof(known_protos[0]); i++) { + if (strcasecmp(name, known_protos[i]) == 0) { + return 1; + } + } + return 0; +} + +static int looks_numeric(const char *s) { + if (!*s) { + return 0; + } + for (; *s; s++) { + if (!isdigit((unsigned char)*s)) { + return 0; + } + } + return 1; +} + +/* Accepts "key:value", "key=value" and bare shorthand: "tcp", "udp", "icmp", + * "arp", "dns", "443" (port), "10.0.0.1" (host). */ +static int parse_clause(char *token, struct ps_filter_group *g, char *err, size_t errsz) { + struct ps_filter_clause *c; + char *key = token; + char *value = NULL; + int negate = 0; + + if (g->count >= PS_FILTER_MAX_CLAUSES) { + snprintf(err, errsz, "too many terms in one group (max %d)", PS_FILTER_MAX_CLAUSES); + return -1; + } + + if (key[0] == '!') { + negate = 1; + key++; + } + + char *sep = strpbrk(key, ":="); + if (sep) { + *sep = '\0'; + value = sep + 1; + } + + c = &g->clauses[g->count]; + memset(c, 0, sizeof(*c)); + c->negate = negate; + + if (!value) { + /* shorthand */ + if (strcasecmp(key, "tcp") == 0 || strcasecmp(key, "udp") == 0 || + strcasecmp(key, "icmp") == 0 || strcasecmp(key, "icmp6") == 0 || + strcasecmp(key, "arp") == 0 || strcasecmp(key, "dns") == 0 || + strcasecmp(key, "tls") == 0 || strcasecmp(key, "http") == 0 || + strcasecmp(key, "ip6") == 0) { + c->kind = PS_FILTER_PROTO; + ps_strlcpy(c->proto, key, sizeof(c->proto)); + } else if (looks_numeric(key)) { + uint32_t v; + c->kind = PS_FILTER_PORT; + if (ps_parse_u32(key, &v) != 0 || v > 65535) { + snprintf(err, errsz, "bad port '%s'", key); + return -1; + } + c->port = (uint16_t)v; + } else if (parse_addr(key, c) == 0) { + c->kind = PS_FILTER_HOST; + } else { + snprintf(err, errsz, "cannot understand clause '%s'", key); + return -1; + } + g->count++; + return 0; + } + + if (*value == '\0') { + snprintf(err, errsz, "clause '%s' has an empty value", key); + return -1; + } + + if (strcasecmp(key, "proto") == 0) { + if (!proto_known(value)) { + snprintf(err, errsz, + "unknown protocol '%s' (tcp udp icmp icmp6 arp ip6 dns tls http)", value); + return -1; + } + c->kind = PS_FILTER_PROTO; + ps_strlcpy(c->proto, value, sizeof(c->proto)); + } else if (strcasecmp(key, "port") == 0 || strcasecmp(key, "sport") == 0 || + strcasecmp(key, "dport") == 0) { + uint32_t v; + if (ps_parse_u32(value, &v) != 0 || v > 65535) { + snprintf(err, errsz, "bad port '%s'", value); + return -1; + } + c->port = (uint16_t)v; + c->kind = strcasecmp(key, "port") == 0 ? PS_FILTER_PORT + : strcasecmp(key, "sport") == 0 ? PS_FILTER_SPORT + : PS_FILTER_DPORT; + } else if (strcasecmp(key, "host") == 0 || strcasecmp(key, "src") == 0 || + strcasecmp(key, "dst") == 0) { + if (parse_addr(value, c) != 0) { + snprintf(err, errsz, "bad address '%s'", value); + return -1; + } + c->kind = strcasecmp(key, "host") == 0 ? PS_FILTER_HOST + : strcasecmp(key, "src") == 0 ? PS_FILTER_SRC + : PS_FILTER_DST; + } else if (strcasecmp(key, "contains") == 0) { + c->kind = PS_FILTER_CONTAINS; + ps_strlcpy(c->needle, value, sizeof(c->needle)); + } else if (strcasecmp(key, "bytes") == 0 || strcasecmp(key, "len") == 0) { + c->kind = PS_FILTER_BYTES; + if (parse_bytes(value, c) != 0) { + snprintf(err, errsz, "bad length '%s'", value); + return -1; + } + } else { + snprintf(err, errsz, "unknown filter key '%s'", key); + return -1; + } + + g->count++; + return 0; +} + +int ps_filter_parse(const char *expr, struct ps_filter *f, char *err, size_t errsz) { + char buf[1024]; + char *saveptr = NULL; + char *token; + struct ps_filter_group *group; + size_t w = 0; + + memset(f, 0, sizeof(*f)); + if (!expr || !*expr) { + return 0; + } + ps_strlcpy(f->source, expr, sizeof(f->source)); + + /* Normalise separators: ',' is AND (just a space), '|' is an explicit OR. */ + for (const char *p = expr; *p && w + 4 < sizeof(buf); p++) { + if (*p == '|') { + memcpy(buf + w, " or ", 4); + w += 4; + } else if (*p == ',') { + buf[w++] = ' '; + } else { + buf[w++] = *p; + } + } + buf[w] = '\0'; + + group = &f->groups[0]; + f->count = 1; + + for (token = strtok_r(buf, " \t", &saveptr); token; token = strtok_r(NULL, " \t", &saveptr)) { + if (strcasecmp(token, "or") == 0) { + if (group->count == 0) { + snprintf(err, errsz, "empty filter group before 'or'"); + return -1; + } + if (f->count >= PS_FILTER_MAX_GROUPS) { + snprintf(err, errsz, "too many 'or' groups (max %d)", PS_FILTER_MAX_GROUPS); + return -1; + } + group = &f->groups[f->count++]; + continue; + } + if (strcasecmp(token, "and") == 0) { + continue; + } + if (parse_clause(token, group, err, errsz) != 0) { + return -1; + } + } + + if (group->count == 0) { + snprintf(err, errsz, "dangling 'or' with nothing after it"); + return -1; + } + if (errsz) { + err[0] = '\0'; + } + return 0; +} + +int ps_filter_is_empty(const struct ps_filter *f) { return f->count == 0; } + +static int proto_matches(const char *proto, const struct ps_decoded *d) { + if (strcasecmp(proto, "tcp") == 0) { + return d->l4 == PS_L4_TCP; + } + if (strcasecmp(proto, "udp") == 0) { + return d->l4 == PS_L4_UDP; + } + if (strcasecmp(proto, "icmp") == 0) { + return d->l4 == PS_L4_ICMP; + } + if (strcasecmp(proto, "icmp6") == 0) { + return d->l4 == PS_L4_ICMPV6; + } + if (strcasecmp(proto, "arp") == 0) { + return d->ethertype == 0x0806; + } + if (strcasecmp(proto, "ip6") == 0) { + return d->ip_version == 6; + } + if (strcasecmp(proto, "dns") == 0) { + return (d->app_flags & PS_APP_DNS) != 0; + } + if (strcasecmp(proto, "tls") == 0) { + return (d->app_flags & PS_APP_TLS) != 0; + } + if (strcasecmp(proto, "http") == 0) { + return (d->app_flags & PS_APP_HTTP) != 0; + } + return 0; +} + +static int payload_contains(const struct ps_decoded *d, const char *needle) { + size_t n = strlen(needle); + + if (!d->payload || d->payload_len < n || n == 0) { + return 0; + } + const uint8_t *p = d->payload; + for (uint32_t i = 0; i + n <= d->payload_len; i++) { + if (memcmp(p + i, needle, n) == 0) { + return 1; + } + } + return 0; +} + +static bool group_matches(const struct ps_filter_group *g, const struct ps_decoded *d) { + for (size_t i = 0; i < g->count; i++) { + const struct ps_filter_clause *c = &g->clauses[i]; + int hit = 0; + + switch (c->kind) { + case PS_FILTER_PROTO: + hit = proto_matches(c->proto, d); + break; + case PS_FILTER_PORT: + hit = d->sport == c->port || d->dport == c->port; + break; + case PS_FILTER_SPORT: + hit = d->sport == c->port; + break; + case PS_FILTER_DPORT: + hit = d->dport == c->port; + break; + case PS_FILTER_HOST: + hit = addr_matches(c, d->src) || addr_matches(c, d->dst); + break; + case PS_FILTER_SRC: + hit = addr_matches(c, d->src); + break; + case PS_FILTER_DST: + hit = addr_matches(c, d->dst); + break; + case PS_FILTER_CONTAINS: + hit = payload_contains(d, c->needle); + break; + case PS_FILTER_BYTES: + switch (c->cmp) { + case PS_CMP_EQ: + hit = d->origlen == c->bytes; + break; + case PS_CMP_GT: + hit = d->origlen > c->bytes; + break; + case PS_CMP_LT: + hit = d->origlen < c->bytes; + break; + case PS_CMP_GE: + hit = d->origlen >= c->bytes; + break; + case PS_CMP_LE: + hit = d->origlen <= c->bytes; + break; + } + break; + } + + if (c->negate) { + hit = !hit; + } + if (!hit) { + return false; + } + } + return true; +} + +bool ps_filter_match(const struct ps_filter *f, const struct ps_decoded *d) { + for (size_t i = 0; i < f->count; i++) { + if (group_matches(&f->groups[i], d)) { + return true; + } + } + return false; +} diff --git a/src/log.c b/src/log.c new file mode 100644 index 0000000..0903e71 --- /dev/null +++ b/src/log.c @@ -0,0 +1,79 @@ +/* log.c - leveled logging. */ +#include "log.h" + +#include +#include +#include +#include +#include + +static ps_log_level g_level = PS_LOG_INFO; +static int g_color = 0; + +void ps_log_init(ps_log_level level, int color) { + g_level = level; + /* Only emit colour when stderr is a terminal, unless forced. */ + g_color = color && isatty(STDERR_FILENO); +} + +int ps_log_enabled(ps_log_level level) { return level >= g_level; } + +void ps_clock_stamp(char *buf, size_t cap) { + struct timespec ts; + struct tm tm; + + clock_gettime(CLOCK_REALTIME, &ts); + localtime_r(&ts.tv_sec, &tm); + snprintf(buf, cap, "%02d:%02d:%02d.%06ld", tm.tm_hour, tm.tm_min, tm.tm_sec, ts.tv_nsec / 1000); +} + +static const char *level_tag(ps_log_level level) { + switch (level) { + case PS_LOG_DEBUG: + return "dbg"; + case PS_LOG_INFO: + return "inf"; + case PS_LOG_WARN: + return "warn"; + case PS_LOG_ERROR: + return "err"; + default: + return "???"; + } +} + +static const char *level_color(ps_log_level level) { + switch (level) { + case PS_LOG_DEBUG: + return "\033[0;90m"; + case PS_LOG_INFO: + return "\033[0;36m"; + case PS_LOG_WARN: + return "\033[1;33m"; + case PS_LOG_ERROR: + return "\033[1;31m"; + default: + return ""; + } +} + +void ps_log(ps_log_level level, const char *fmt, ...) { + if (!ps_log_enabled(level)) { + return; + } + + char stamp[32]; + ps_clock_stamp(stamp, sizeof(stamp)); + + const char *prefix = g_color ? level_color(level) : ""; + const char *reset = g_color ? "\033[0m" : ""; + + fprintf(stderr, "%s%s [%s]%s ", prefix, stamp, level_tag(level), reset); + + va_list ap; + va_start(ap, fmt); + vfprintf(stderr, fmt, ap); + va_end(ap); + fputc('\n', stderr); + fflush(stderr); +} diff --git a/src/main_client.c b/src/main_client.c new file mode 100644 index 0000000..e2e35bb --- /dev/null +++ b/src/main_client.c @@ -0,0 +1,206 @@ +/* main_client.c - pktsniff-client: receive, filter, render, record. */ +#include +#include +#include +#include + +#include "client.h" +#include "log.h" +#include "util.h" + +enum { + OPT_NO_STATS = 1000, + OPT_NO_COLOR, + OPT_JSON, + OPT_RECONNECT, + OPT_STATS_INTERVAL, + OPT_PCAP_ROTATE, +}; + +static const struct option long_opts[] = { + {"host", required_argument, NULL, 'H'}, + {"port", required_argument, NULL, 'p'}, + {"filter", required_argument, NULL, 'F'}, + {"pcap", required_argument, NULL, 'w'}, + {"pcap-rotate-mb", required_argument, NULL, OPT_PCAP_ROTATE}, + {"json", required_argument, NULL, OPT_JSON}, + {"count", required_argument, NULL, 'c'}, + {"duration", required_argument, NULL, 'd'}, + {"hex", required_argument, NULL, 'x'}, + {"no-hex", no_argument, NULL, 'X'}, + {"no-stats", no_argument, NULL, OPT_NO_STATS}, + {"stats-interval", required_argument, NULL, OPT_STATS_INTERVAL}, + {"color", no_argument, NULL, 'C'}, + {"no-color", no_argument, NULL, OPT_NO_COLOR}, + {"quiet", no_argument, NULL, 'q'}, + {"reconnect", no_argument, NULL, OPT_RECONNECT}, + {"verbose", no_argument, NULL, 'v'}, + {"help", no_argument, NULL, 'h'}, + {"version", no_argument, NULL, 'V'}, + {NULL, 0, NULL, 0}, +}; + +static void usage(FILE *out) { + fprintf(out, + "usage: " PS_NAME "-client [host] [options]\n" + "\n" + "Receive the live packet stream from a " PS_NAME "-server and make sense of it.\n" + "\n" + "Connection:\n" + " -H, --host HOST server address (default 127.0.0.1)\n" + " -p, --port N server port (default 8888)\n" + " --reconnect retry forever instead of exiting on disconnect\n" + "\n" + "Selection:\n" + " -F, --filter EXPR display filter, e.g. 'proto:tcp port:443 !src:10.0.0.5'\n" + " keys: proto port sport dport host src dst contains bytes\n" + " 'or'/'|' between alternatives, '!' negates a term\n" + " shorthand: tcp udp icmp arp dns tls http 443 10.0.0.0/8\n" + " -c, --count N stop after N matching packets\n" + " -d, --duration N stop after N seconds\n" + "\n" + "Output:\n" + " -x, --hex N hexdump the first N bytes of each match (default 0)\n" + " -X, --no-hex same as --hex 0\n" + " --json FILE write newline-delimited JSON to FILE ('-' = stdout)\n" + " --no-stats hide the periodic server counter line\n" + " --stats-interval N seconds between counter lines (default 5)\n" + " -C, --color force ANSI colour (default: only on a tty)\n" + " --no-color disable ANSI colour\n" + " -q, --quiet no banner or summary (keeps stdout pipeable)\n" + " -v, --verbose debug logging\n" + "\n" + "Recording:\n" + " -w, --pcap FILE write matching packets to a .pcap for Wireshark\n" + " --pcap-rotate-mb N rotate the file every N MiB\n" + "\n" + " -h, --help this help\n" + " -V, --version version\n" + "\n" + "Examples:\n" + " " PS_NAME "-client 203.0.113.10 -F 'proto:dns or proto:tls' --hex 64\n" + " " PS_NAME "-client 203.0.113.10 -F 'host:10.0.0.0/8 !tcp' -w subset.pcap\n" + " " PS_NAME "-client 203.0.113.10 --json - | jq '.app' | sort | uniq -c\n"); +} + +int main(int argc, char **argv) { + struct ps_client_opts opts; + int verbose = 0; + int c; + + ps_set_prog_name(PS_NAME "-client"); + memset(&opts, 0, sizeof(opts)); + opts.host = "127.0.0.1"; + opts.port = 8888; + opts.show_stats = 1; + opts.color = -1; + opts.stats_interval = 5; + + while ((c = getopt_long(argc, argv, "H:p:F:w:c:d:x:XqvhVC", long_opts, NULL)) != -1) { + switch (c) { + case 'H': + opts.host = optarg; + break; + case 'p': { + uint32_t v; + if (ps_parse_u32(optarg, &v) != 0 || v == 0 || v > 65535) { + LOG_ERROR("bad port '%s'", optarg); + return 2; + } + opts.port = (uint16_t)v; + break; + } + case 'F': + opts.filter = optarg; + break; + case 'w': + opts.pcap_path = optarg; + break; + case OPT_PCAP_ROTATE: { + uint32_t mb; + if (ps_parse_u32(optarg, &mb) != 0 || mb == 0) { + LOG_ERROR("bad --pcap-rotate-mb '%s'", optarg); + return 2; + } + opts.pcap_rotate_bytes = (uint64_t)mb * 1024 * 1024; + break; + } + case OPT_JSON: + opts.json_path = optarg; + break; + case 'c': + if (ps_parse_u64(optarg, &opts.count) != 0 || opts.count == 0) { + LOG_ERROR("bad --count '%s'", optarg); + return 2; + } + break; + case 'd': { + uint32_t v; + if (ps_parse_u32(optarg, &v) != 0 || v == 0) { + LOG_ERROR("bad --duration '%s'", optarg); + return 2; + } + opts.duration = v; + break; + } + case 'x': { + uint32_t v; + if (ps_parse_u32(optarg, &v) != 0) { + LOG_ERROR("bad --hex '%s'", optarg); + return 2; + } + opts.hex_bytes = v; + break; + } + case 'X': + opts.hex_bytes = 0; + break; + case OPT_NO_STATS: + opts.show_stats = 0; + break; + case OPT_STATS_INTERVAL: + if (ps_parse_u32(optarg, &opts.stats_interval) != 0 || opts.stats_interval == 0) { + LOG_ERROR("bad --stats-interval '%s'", optarg); + return 2; + } + break; + case 'C': + opts.color = 1; + break; + case OPT_NO_COLOR: + opts.color = 0; + break; + case OPT_RECONNECT: + opts.reconnect = 1; + break; + case 'q': + opts.quiet = 1; + break; + case 'v': + verbose = 1; + break; + case 'h': + usage(stdout); + return 0; + case 'V': + printf("%s %s\n", PS_NAME, PS_VERSION_STR); + return 0; + default: + usage(stderr); + return 2; + } + } + + /* A single bare argument is the host: `pktsniff-client 1.2.3.4`. */ + if (optind < argc) { + opts.host = argv[optind++]; + } + if (optind < argc) { + LOG_ERROR("unexpected argument '%s'", argv[optind]); + return 2; + } + + ps_log_init(verbose ? PS_LOG_DEBUG : PS_LOG_INFO, opts.color); + + return ps_client_run(&opts); +} diff --git a/src/main_server.c b/src/main_server.c new file mode 100644 index 0000000..225dddb --- /dev/null +++ b/src/main_server.c @@ -0,0 +1,218 @@ +/* main_server.c - pktsniff-server: capture on this box, stream to clients. */ +#include +#include +#include +#include +#include + +#include "capture.h" +#include "log.h" +#include "server.h" +#include "util.h" + +enum { + OPT_NO_PROMISC = 1000, + OPT_DIRECTION, + OPT_CLIENT_BUFFER, + OPT_PCAP_ROTATE, + OPT_LIST_IFACES, + OPT_CAPTURE_CONTROL, +}; + +static const struct option long_opts[] = { + {"iface", required_argument, NULL, 'i'}, + {"filter", required_argument, NULL, 'f'}, + {"snaplen", required_argument, NULL, 's'}, + {"no-promisc", no_argument, NULL, OPT_NO_PROMISC}, + {"direction", required_argument, NULL, OPT_DIRECTION}, + {"port", required_argument, NULL, 'p'}, + {"bind", required_argument, NULL, 'b'}, + {"max-clients", required_argument, NULL, 'm'}, + {"client-buffer", required_argument, NULL, OPT_CLIENT_BUFFER}, + {"pcap", required_argument, NULL, 'w'}, + {"pcap-rotate-mb", required_argument, NULL, OPT_PCAP_ROTATE}, + {"stats-interval", required_argument, NULL, 't'}, + {"verbose", no_argument, NULL, 'v'}, + {"quiet", no_argument, NULL, 'q'}, + {"capture-control", no_argument, NULL, OPT_CAPTURE_CONTROL}, + {"list-interfaces", no_argument, NULL, OPT_LIST_IFACES}, + {"help", no_argument, NULL, 'h'}, + {"version", no_argument, NULL, 'V'}, + {NULL, 0, NULL, 0}, +}; + +static void usage(FILE *out) { + fprintf(out, + "usage: " PS_NAME "-server [options]\n" + "\n" + "Capture packets on this machine and stream them to " PS_NAME " clients.\n" + "Requires root (CAP_NET_RAW) for the raw socket.\n" + "\n" + "Capture:\n" + " -i, --iface NAME interface to capture on (default: any)\n" + " -f, --filter BPF kernel filter in tcpdump syntax (needs libpcap)\n" + " -s, --snaplen N bytes kept per packet (default %u)\n" + " --no-promisc do not enable promiscuous mode\n" + " --direction in|out|both drop our own sent / received traffic\n" + " --capture-control also capture the stream's own TCP connection\n" + "\n" + "Streaming:\n" + " -p, --port N TCP port to listen on (default 8888)\n" + " -b, --bind ADDR bind address (default 0.0.0.0)\n" + " -m, --max-clients N concurrent clients (default 8)\n" + " --client-buffer BYTES per-client queue before dropping (default 4 MiB)\n" + "\n" + "Recording:\n" + " -w, --pcap FILE also record to a .pcap file\n" + " --pcap-rotate-mb N rotate the file every N MiB\n" + "\n" + "Other:\n" + " -t, --stats-interval N seconds between status lines (default 5)\n" + " -v, --verbose debug logging\n" + " -q, --quiet no periodic status lines\n" + " --list-interfaces list interfaces and exit\n" + " -h, --help this help\n" + " -V, --version version and capabilities\n" + "\n" + "Examples:\n" + " sudo " PS_NAME "-server -i eth0 -f 'tcp port 443' -w cap.pcap\n" + " sudo " PS_NAME "-server -i any -f 'udp port 53' -p 9000\n", + PS_SNAPLEN_DEFAULT); +} + +int main(int argc, char **argv) { + struct ps_server_opts opts; + int verbose = 0; + int c; + + ps_set_prog_name(PS_NAME "-server"); + memset(&opts, 0, sizeof(opts)); + opts.iface = ""; + opts.port = 8888; + opts.snaplen = PS_SNAPLEN_DEFAULT; + opts.promisc = 1; + opts.max_clients = 8; + opts.client_buffer = 4u << 20; + opts.stats_interval = 5; + opts.direction = PS_SERVER_DIR_BOTH; + + while ((c = getopt_long(argc, argv, "i:f:s:p:b:m:w:t:vqhV", long_opts, NULL)) != -1) { + switch (c) { + case 'i': + opts.iface = optarg; + break; + case 'f': + opts.bpf = optarg; + break; + case 's': + if (ps_parse_u32(optarg, &opts.snaplen) != 0 || opts.snaplen < 64 || + opts.snaplen > PS_SNAPLEN_MAX) { + LOG_ERROR("bad snaplen '%s' (64..%u)", optarg, PS_SNAPLEN_MAX); + return 2; + } + break; + case OPT_NO_PROMISC: + opts.promisc = 0; + break; + case OPT_DIRECTION: + if (!strcmp(optarg, "in")) { + opts.direction = PS_SERVER_DIR_IN; + } else if (!strcmp(optarg, "out")) { + opts.direction = PS_SERVER_DIR_OUT; + } else if (!strcmp(optarg, "both")) { + opts.direction = PS_SERVER_DIR_BOTH; + } else { + LOG_ERROR("bad --direction '%s' (in|out|both)", optarg); + return 2; + } + break; + case 'p': { + uint32_t v; + if (ps_parse_u32(optarg, &v) != 0 || v == 0 || v > 65535) { + LOG_ERROR("bad port '%s'", optarg); + return 2; + } + opts.port = (uint16_t)v; + break; + } + case 'b': + opts.bind_addr = optarg; + break; + case 'm': { + uint32_t v; + if (ps_parse_u32(optarg, &v) != 0 || v < 1 || v > 512) { + LOG_ERROR("bad --max-clients '%s' (1..512)", optarg); + return 2; + } + opts.max_clients = (int)v; + break; + } + case OPT_CLIENT_BUFFER: { + uint32_t v; + if (ps_parse_u32(optarg, &v) != 0 || v < 65536) { + LOG_ERROR("bad --client-buffer '%s' (min 65536)", optarg); + return 2; + } + opts.client_buffer = v; + break; + } + case 'w': + opts.pcap_path = optarg; + break; + case OPT_PCAP_ROTATE: { + uint32_t mb; + if (ps_parse_u32(optarg, &mb) != 0 || mb == 0) { + LOG_ERROR("bad --pcap-rotate-mb '%s'", optarg); + return 2; + } + opts.pcap_rotate_bytes = (uint64_t)mb * 1024 * 1024; + break; + } + case 't': + if (ps_parse_u32(optarg, &opts.stats_interval) != 0 || opts.stats_interval == 0) { + LOG_ERROR("bad --stats-interval '%s'", optarg); + return 2; + } + break; + case 'v': + verbose = 1; + break; + case 'q': + opts.quiet = 1; + break; + case OPT_CAPTURE_CONTROL: + opts.capture_control = 1; + break; + case OPT_LIST_IFACES: + printf("interfaces:\n"); + ps_capture_list_interfaces(stdout); + return 0; + case 'h': + usage(stdout); + return 0; + case 'V': + printf("%s %s\n", PS_NAME, PS_VERSION_STR); +#ifdef PS_HAVE_PCAP + printf("libpcap filtering: yes\n"); +#else + printf("libpcap filtering: no (server-side --filter disabled)\n"); +#endif + return 0; + default: + usage(stderr); + return 2; + } + } + if (optind < argc) { + LOG_ERROR("unexpected argument '%s'", argv[optind]); + return 2; + } + + ps_log_init(verbose ? PS_LOG_DEBUG : PS_LOG_INFO, 1); + + if (geteuid() != 0) { + LOG_WARN("not running as root: opening the raw socket will probably fail"); + } + + return ps_server_run(&opts); +} diff --git a/src/outbuf.c b/src/outbuf.c new file mode 100644 index 0000000..528b0f0 --- /dev/null +++ b/src/outbuf.c @@ -0,0 +1,147 @@ +/* outbuf.c - frame-atomic send queue. + * + * Invariants, in order of importance: + * + * 1. The bytes handed to the peer are always a sequence of whole frames. + * 2. A frame whose bytes are (partly) on the wire can never be dropped - the + * peer would be left mid-frame, which desynchronises the stream. + * 3. Therefore only wholly unsent frames may be discarded, and only when the + * queue is full. + * 4. `r` is the send cursor, `frame_start` the start of the oldest frame that + * still has unsent bytes, so frame_start <= r <= w always holds. + */ +#include "outbuf.h" + +#include +#include + +#include "common.h" +#include "proto.h" +#include "util.h" + +void ps_outbuf_init(struct ps_outbuf *q, size_t cap) { + memset(q, 0, sizeof(*q)); + if (cap < 4096) { + cap = 4096; + } + q->data = ps_xmalloc(cap); + q->cap = cap; +} + +void ps_outbuf_free(struct ps_outbuf *q) { + free(q->data); + memset(q, 0, sizeof(*q)); +} + +size_t ps_outbuf_pending(const struct ps_outbuf *q) { return q->w - q->r; } + +const uint8_t *ps_outbuf_head(const struct ps_outbuf *q) { return q->data + q->r; } + +static void reset(struct ps_outbuf *q) { q->r = q->w = q->frame_start = 0; } + +/* Shift the queue to offset 0. Only bytes before frame_start are dead (sent and + * no longer droppable); everything from frame_start onwards must be preserved, + * which keeps the "partially sent" state intact. */ +static void compact(struct ps_outbuf *q) { + if (q->frame_start == 0) { + return; + } + memmove(q->data, q->data + q->frame_start, q->w - q->frame_start); + q->w -= q->frame_start; + q->r -= q->frame_start; + q->frame_start = 0; +} + +/* Finds the first queued frame that has no bytes on the wire yet. */ +static int first_droppable(const struct ps_outbuf *q, size_t *start, size_t *total) { + size_t fs = q->frame_start; + + while (fs + PS_HEADER_LEN <= q->w) { + size_t t = PS_HEADER_LEN + (size_t)ps_be32(q->data + fs + 8); + + if (fs + t > q->w) { + return 0; /* truncated tail: nothing safe to drop */ + } + if (fs >= q->r) { + *start = fs; + *total = t; + return 1; + } + fs += t; + } + return 0; +} + +int ps_outbuf_drop_front(struct ps_outbuf *q) { + size_t start, total; + + if (!first_droppable(q, &start, &total)) { + return 0; + } + memmove(q->data + start, q->data + start + total, q->w - (start + total)); + q->w -= total; + q->dropped_bytes += total; + q->dropped_frames++; + + if (q->r == q->w) { + reset(q); + } + return 1; +} + +int ps_outbuf_push(struct ps_outbuf *q, const uint8_t *frame, size_t len) { + if (len > q->cap) { + return -1; + } + if (q->w + len > q->cap) { + compact(q); + } + while (q->w + len > q->cap) { + if (!ps_outbuf_drop_front(q)) { + break; /* only the in-flight frame is left; it cannot be dropped */ + } + compact(q); + } + if (q->w + len > q->cap) { + return -1; + } + memcpy(q->data + q->w, frame, len); + q->w += len; + return 0; +} + +void ps_outbuf_consume(struct ps_outbuf *q, size_t n) { + if (n > q->w - q->r) { + n = q->w - q->r; + } + q->r += n; + if (q->r == q->w) { + reset(q); + return; + } + /* Advance frame_start to the frame containing the send cursor. */ + while (q->frame_start + PS_HEADER_LEN <= q->r) { + size_t t = PS_HEADER_LEN + (size_t)ps_be32(q->data + q->frame_start + 8); + + if (q->frame_start + t > q->r) { + break; + } + q->frame_start += t; + } +} + +size_t ps_outbuf_frames(const struct ps_outbuf *q) { + size_t off = q->frame_start; + size_t n = 0; + + while (off + PS_HEADER_LEN <= q->w) { + size_t t = PS_HEADER_LEN + (size_t)ps_be32(q->data + off + 8); + + if (off + t > q->w) { + break; + } + off += t; + n++; + } + return n; +} diff --git a/src/pcap.c b/src/pcap.c new file mode 100644 index 0000000..1370b4d --- /dev/null +++ b/src/pcap.c @@ -0,0 +1,154 @@ +/* pcap.c - minimal classic .pcap writer. */ +#include "pcap.h" + +#include +#include +#include +#include +#include + +#include "util.h" + +#define PCAP_GLOBAL_HDR_LEN 24u +#define PCAP_RECORD_HDR_LEN 16u +#define PCAP_MAGIC 0xa1b2c3d4u /* microsecond resolution; always written little-endian */ + +static int write_all(int fd, const void *buf, size_t len) { + const uint8_t *p = (const uint8_t *)buf; + size_t done = 0; + + while (done < len) { + ssize_t n = write(fd, p + done, len - done); + if (n < 0) { + if (errno == EINTR) { + continue; + } + return -1; + } + if (n == 0) { + return -1; + } + done += (size_t)n; + } + return 0; +} + +/* "cap.pcap" -> "cap.1.pcap", "cap" -> "cap.1" */ +static void rotation_name(char *out, size_t cap, const char *path, unsigned seq) { + const char *slash = strrchr(path, '/'); + const char *dot = strrchr(path, '.'); + + if (seq == 0) { + ps_strlcpy(out, path, cap); + return; + } + if (dot && (!slash || dot > slash)) { + snprintf(out, cap, "%.*s.%u%s", (int)(dot - path), path, seq, dot); + } else { + snprintf(out, cap, "%s.%u", path, seq); + } +} + +static int write_global_header(const struct ps_pcap *w, int fd) { + uint8_t hdr[PCAP_GLOBAL_HDR_LEN]; + + memset(hdr, 0, sizeof(hdr)); + ps_put_le32(hdr + 0, PCAP_MAGIC); + ps_put_le16(hdr + 4, 2); /* version major */ + ps_put_le16(hdr + 6, 4); /* version minor */ + ps_put_le32(hdr + 8, 0); /* thiszone */ + ps_put_le32(hdr + 12, 0); + ps_put_le32(hdr + 16, w->snaplen); + ps_put_le32(hdr + 20, w->linktype); + return write_all(fd, hdr, sizeof(hdr)); +} + +int ps_pcap_open(struct ps_pcap *w, const char *path, uint32_t snaplen, uint16_t linktype, + uint64_t rotate_bytes, char *err, size_t errsz) { + memset(w, 0, sizeof(*w)); + w->snaplen = snaplen ? snaplen : PS_SNAPLEN_DEFAULT; + w->linktype = linktype; + w->rotate_bytes = rotate_bytes; + w->fd = -1; + + if (!path || !*path || strcmp(path, "-") == 0) { + w->fd = STDOUT_FILENO; + ps_strlcpy(w->path, "-", sizeof(w->path)); + if (write_global_header(w, w->fd) != 0) { + snprintf(err, errsz, "cannot write pcap header to stdout: %s", strerror(errno)); + return -1; + } + return 0; + } + + ps_strlcpy(w->path, path, sizeof(w->path)); + w->fd = open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); + if (w->fd < 0) { + snprintf(err, errsz, "cannot open %s: %s", path, strerror(errno)); + return -1; + } + if (write_global_header(w, w->fd) != 0) { + snprintf(err, errsz, "cannot write pcap header: %s", strerror(errno)); + close(w->fd); + w->fd = -1; + return -1; + } + return 0; +} + +static int rotate(struct ps_pcap *w) { + char name[600]; + + if (w->fd <= STDOUT_FILENO) { + return 0; + } + close(w->fd); + w->seq++; + rotation_name(name, sizeof(name), w->path, w->seq); + w->fd = open(name, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); + if (w->fd < 0) { + return -1; + } + w->bytes_written = 0; + return write_global_header(w, w->fd); +} + +int ps_pcap_write(struct ps_pcap *w, const struct ps_record *rec) { + uint8_t hdr[PCAP_RECORD_HDR_LEN]; + uint32_t incl = rec->caplen; + + if (w->fd < 0) { + return -1; + } + if (incl > w->snaplen) { + incl = w->snaplen; + } + ps_put_le32(hdr + 0, rec->ts_sec); + ps_put_le32(hdr + 4, rec->ts_usec); + ps_put_le32(hdr + 8, incl); + ps_put_le32(hdr + 12, rec->origlen); + + if (write_all(w->fd, hdr, sizeof(hdr)) != 0 || write_all(w->fd, rec->data, incl) != 0) { + return -1; + } + w->bytes_written += PCAP_RECORD_HDR_LEN + incl; + w->packets_written++; + + if (w->rotate_bytes && w->bytes_written >= w->rotate_bytes && rotate(w) != 0) { + return -1; + } + return 0; +} + +int ps_pcap_flush(struct ps_pcap *w) { + return w->fd < 0 ? -1 : fsync(w->fd); +} + +void ps_pcap_close(struct ps_pcap *w) { + if (w && w->fd > STDOUT_FILENO) { + close(w->fd); + } + if (w) { + w->fd = -1; + } +} diff --git a/src/proto.c b/src/proto.c new file mode 100644 index 0000000..29cedf8 --- /dev/null +++ b/src/proto.c @@ -0,0 +1,251 @@ +/* proto.c - framing, payload codecs, incremental reader. */ +#include "proto.h" + +#include +#include +#include + +#include "util.h" + +const char *ps_frame_type_name(uint16_t type) { + switch (type) { + case PS_FRAME_HELLO: + return "HELLO"; + case PS_FRAME_PACKET: + return "PACKET"; + case PS_FRAME_STATS: + return "STATS"; + case PS_FRAME_BYE: + return "BYE"; + case PS_FRAME_ERR: + return "ERR"; + default: + return "UNKNOWN"; + } +} + +size_t ps_frame_write(uint8_t *out, size_t cap, uint16_t type, const uint8_t *payload, uint32_t len) { + if (cap < PS_HEADER_LEN + (size_t)len) { + return 0; + } + ps_put_be32(out + 0, PS_PROTO_MAGIC); + ps_put_be16(out + 4, (uint16_t)PS_PROTO_VERSION); + ps_put_be16(out + 6, type); + ps_put_be32(out + 8, len); + if (len > 0) { + memcpy(out + PS_HEADER_LEN, payload, len); + } + return PS_HEADER_LEN + len; +} + +size_t ps_packet_encode(uint8_t *out, size_t cap, const struct ps_record *rec) { + size_t total = PS_PKT_HDR_LEN + rec->caplen; + + if (cap < total) { + return 0; + } + ps_put_be32(out + 0, rec->ts_sec); + ps_put_be32(out + 4, rec->ts_usec); + ps_put_be32(out + 8, rec->caplen); + ps_put_be32(out + 12, rec->origlen); + memcpy(out + PS_PKT_HDR_LEN, rec->data, rec->caplen); + return total; +} + +int ps_packet_decode(const uint8_t *in, uint32_t len, struct ps_record *rec) { + uint32_t caplen; + + if (len < PS_PKT_HDR_LEN) { + return -1; + } + caplen = ps_be32(in + 8); + if (caplen > len - PS_PKT_HDR_LEN) { + return -1; + } + rec->ts_sec = ps_be32(in + 0); + rec->ts_usec = ps_be32(in + 4); + rec->caplen = caplen; + rec->origlen = ps_be32(in + 12); + rec->data = in + PS_PKT_HDR_LEN; + return 0; +} + +/* Strings are packed back-to-back, each NUL terminated. */ +static size_t pack_string(uint8_t *out, size_t cap, size_t off, const char *s) { + size_t n = strlen(s) + 1; + if (off + n > cap) { + return 0; + } + memcpy(out + off, s, n); + return off + n; +} + +static int unpack_string(const uint8_t *in, uint32_t len, uint32_t *off, char *dst, size_t cap) { + const uint8_t *nul; + size_t remain; + + if (*off >= len) { + return -1; + } + remain = len - *off; + nul = memchr(in + *off, '\0', remain); + if (!nul) { + return -1; + } + ps_strlcpy(dst, (const char *)(in + *off), cap); + *off += (uint32_t)(nul - (in + *off)) + 1; + return 0; +} + +size_t ps_hello_encode(const struct ps_hello *hello, uint8_t *out, size_t cap) { + size_t off; + + if (cap < 6) { + return 0; + } + ps_put_be16(out + 0, hello->linktype); + ps_put_be32(out + 2, hello->snaplen); + off = 6; + + off = pack_string(out, cap, off, hello->hostname); + if (off == 0) { + return 0; + } + off = pack_string(out, cap, off, hello->iface); + if (off == 0) { + return 0; + } + return pack_string(out, cap, off, hello->filter); +} + +int ps_hello_decode(const uint8_t *in, uint32_t len, struct ps_hello *hello) { + uint32_t off = 6; + + if (len < 6) { + return -1; + } + memset(hello, 0, sizeof(*hello)); + hello->linktype = ps_be16(in + 0); + hello->snaplen = ps_be32(in + 2); + + if (unpack_string(in, len, &off, hello->hostname, sizeof(hello->hostname)) != 0 || + unpack_string(in, len, &off, hello->iface, sizeof(hello->iface)) != 0 || + unpack_string(in, len, &off, hello->filter, sizeof(hello->filter)) != 0) { + return -1; + } + return 0; +} + +size_t ps_string_encode(const char *s, uint8_t *out, size_t cap) { + size_t n = strlen(s) + 1; + + if (cap < n) { + return 0; + } + memcpy(out, s, n); + return n; +} + +/* ---- reader ---- */ + +int ps_reader_init(struct ps_reader *r, size_t initial_cap) { + memset(r, 0, sizeof(*r)); + if (initial_cap < 4096) { + initial_cap = 4096; + } + r->buf = ps_xmalloc(initial_cap); + r->cap = initial_cap; + return 0; +} + +void ps_reader_free(struct ps_reader *r) { + free(r->buf); + free(r->frame); + memset(r, 0, sizeof(*r)); +} + +void ps_reader_reset(struct ps_reader *r) { + r->len = 0; + r->error = 0; +} + +int ps_reader_feed(struct ps_reader *r, const uint8_t *data, size_t n) { + if (r->error) { + return -1; + } + if (n == 0) { + return 0; + } + if (r->len + n > PS_MAX_FRAME) { + r->error = 1; + return -1; + } + if (r->len + n > r->cap) { + size_t want = r->cap; + while (want < r->len + n) { + want *= 2; + } + r->buf = ps_xrealloc(r->buf, want); + r->cap = want; + } + memcpy(r->buf + r->len, data, n); + r->len += n; + return 0; +} + +static void reader_consume(struct ps_reader *r, size_t n) { + if (n >= r->len) { + r->len = 0; + return; + } + memmove(r->buf, r->buf + n, r->len - n); + r->len -= n; +} + +int ps_reader_next(struct ps_reader *r, struct ps_frame *out) { + uint32_t magic, len; + uint16_t version, type; + + if (r->error) { + return -1; + } + if (r->len < PS_HEADER_LEN) { + return 0; + } + + magic = ps_be32(r->buf + 0); + version = ps_be16(r->buf + 4); + type = ps_be16(r->buf + 6); + len = ps_be32(r->buf + 8); + + if (magic != PS_PROTO_MAGIC) { + r->error = 1; + return -1; + } + if (version != PS_PROTO_VERSION) { + r->error = 1; + return -1; + } + if (len > PS_MAX_FRAME) { + r->error = 1; + return -1; + } + if (r->len < PS_HEADER_LEN + (size_t)len) { + return 0; /* partial frame, wait for more */ + } + + if (len > r->frame_cap) { + r->frame = ps_xrealloc(r->frame, len); + r->frame_cap = len; + } + if (len > 0) { + memcpy(r->frame, r->buf + PS_HEADER_LEN, len); + } + + reader_consume(r, PS_HEADER_LEN + (size_t)len); + + out->type = type; + out->len = len; + out->data = r->frame; + return 1; +} diff --git a/src/server.c b/src/server.c new file mode 100644 index 0000000..7ef3c0a --- /dev/null +++ b/src/server.c @@ -0,0 +1,611 @@ +/* server.c - epoll event loop: capture fd -> N clients, buffered writes. */ +#include "server.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "capture.h" +#include "decode.h" +#include "log.h" +#include "outbuf.h" +#include "pcap.h" +#include "proto.h" +#include "util.h" + +#define MAX_EVENTS 64 +#define EPOLL_BATCH 256 + +static volatile sig_atomic_t g_stop = 0; + +static void on_signal(int sig) { + PS_UNUSED(sig); + g_stop = 1; +} + +struct client { + int fd; + char peer[64]; + struct ps_outbuf q; + int want_write; +}; + +struct server { + struct ps_capture cap; + struct ps_pcap pcap; + int have_pcap; + int listen_fd; + int epoll_fd; + struct client *clients; + int max_clients; + int nclients; + struct ps_counters counters; + struct ps_hello hello; + unsigned stats_interval; + size_t client_buffer; + uint64_t last_kernel_drops; + int quiet; + uint8_t *frame_buf; + size_t frame_buf_cap; +}; + +static void close_client(struct server *s, int idx) { + struct client *c = &s->clients[idx]; + + LOG_INFO("client %s disconnected (%llu frames dropped, %zu bytes still queued)", c->peer, + (unsigned long long)c->q.dropped_frames, ps_outbuf_pending(&c->q)); + epoll_ctl(s->epoll_fd, EPOLL_CTL_DEL, c->fd, NULL); + close(c->fd); + ps_outbuf_free(&c->q); + c->fd = -1; + s->nclients--; +} + +/* Returns 1 if the client's queue still holds data (so EPOLLOUT is wanted). */ +static int flush_client(struct server *s, int idx) { + struct client *c = &s->clients[idx]; + + while (ps_outbuf_pending(&c->q) > 0) { + ssize_t n = send(c->fd, ps_outbuf_head(&c->q), ps_outbuf_pending(&c->q), MSG_NOSIGNAL); + + if (n > 0) { + ps_outbuf_consume(&c->q, (size_t)n); + continue; + } + if (n < 0 && errno == EINTR) { + continue; + } + if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) { + break; + } + close_client(s, idx); + return 0; + } + return ps_outbuf_pending(&c->q) > 0; +} + +static void update_epoll_out(struct server *s, int idx, int want) { + struct client *c = &s->clients[idx]; + struct epoll_event ev; + + if (c->want_write == want) { + return; + } + memset(&ev, 0, sizeof(ev)); + ev.events = EPOLLIN | EPOLLRDHUP; + if (want) { + ev.events |= EPOLLOUT; + } + ev.data.u32 = (uint32_t)idx; + if (epoll_ctl(s->epoll_fd, EPOLL_CTL_MOD, c->fd, &ev) == 0) { + c->want_write = want; + } +} + +static void accept_clients(struct server *s) { + for (;;) { + struct sockaddr_storage ss; + socklen_t sl = sizeof(ss); + int fd = accept4(s->listen_fd, (struct sockaddr *)&ss, &sl, SOCK_NONBLOCK | SOCK_CLOEXEC); + if (fd < 0) { + if (errno == EAGAIN || errno == EWOULDBLOCK) { + return; + } + if (errno == EINTR) { + continue; + } + LOG_WARN("accept: %s", strerror(errno)); + return; + } + + int idx = -1; + for (int i = 0; i < s->max_clients; i++) { + if (s->clients[i].fd < 0) { + idx = i; + break; + } + } + if (idx < 0) { + const char *msg = "server busy: no free client slot\n"; + uint8_t frame[256]; + size_t n = ps_frame_write(frame, sizeof(frame), PS_FRAME_ERR, (const uint8_t *)msg, + (uint32_t)strlen(msg)); + if (n) { + (void)!send(fd, frame, n, MSG_NOSIGNAL | MSG_DONTWAIT); + } + close(fd); + LOG_WARN("rejected client: all %d slots busy", s->max_clients); + continue; + } + + int one = 1; + setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one)); + setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &(int){1 << 20}, sizeof(int)); + + struct client *c = &s->clients[idx]; + memset(c, 0, sizeof(*c)); + c->fd = fd; + ps_outbuf_init(&c->q, s->client_buffer); + + char host[INET6_ADDRSTRLEN] = "?"; + uint16_t port = 0; + if (ss.ss_family == AF_INET) { + const struct sockaddr_in *sin = (const struct sockaddr_in *)&ss; + inet_ntop(AF_INET, &sin->sin_addr, host, sizeof(host)); + port = ntohs(sin->sin_port); + } else if (ss.ss_family == AF_INET6) { + const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6 *)&ss; + inet_ntop(AF_INET6, &sin6->sin6_addr, host, sizeof(host)); + port = ntohs(sin6->sin6_port); + } + snprintf(c->peer, sizeof(c->peer), "%s:%u", host, port); + + /* Greet immediately so the client knows the link type and snap length + * before the first packet arrives (needed for .pcap export). */ + uint8_t hello_payload[512]; + size_t hlen = ps_hello_encode(&s->hello, hello_payload, sizeof(hello_payload)); + uint8_t frame[600]; + size_t flen = ps_frame_write(frame, sizeof(frame), PS_FRAME_HELLO, hello_payload, + (uint32_t)hlen); + if (flen) { + ps_outbuf_push(&c->q, frame, flen); + } + + struct epoll_event ev; + memset(&ev, 0, sizeof(ev)); + ev.events = EPOLLIN | EPOLLRDHUP | EPOLLOUT; + ev.data.u32 = (uint32_t)idx; + if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) != 0) { + LOG_WARN("epoll_ctl add: %s", strerror(errno)); + close(fd); + ps_outbuf_free(&c->q); + c->fd = -1; + continue; + } + c->want_write = 1; + s->nclients++; + LOG_INFO("client %s connected (%d/%d)", c->peer, s->nclients, s->max_clients); + } +} + +static void broadcast(struct server *s, const uint8_t *frame, size_t len) { + if (s->nclients == 0) { + return; + } + for (int i = 0; i < s->max_clients; i++) { + struct client *c = &s->clients[i]; + + if (c->fd < 0) { + continue; + } + if (ps_outbuf_push(&c->q, frame, len) != 0) { + s->counters.dropped_client++; + continue; + } + if (flush_client(s, i) && c->fd >= 0) { + update_epoll_out(s, i, 1); + } + } +} + +static void handle_packet(struct server *s, struct ps_record *rec) { + s->counters.seen++; + s->counters.captured++; + s->counters.bytes += rec->origlen; + + /* Cheap classification for the status line; full dissection is the + * client's job. */ + struct ps_decoded d; + if (ps_decode(rec->data, rec->caplen, rec->origlen, s->cap.linktype, &d) == 0) { + switch (d.l4) { + case PS_L4_TCP: + s->counters.tcp++; + break; + case PS_L4_UDP: + s->counters.udp++; + break; + case PS_L4_ICMP: + case PS_L4_ICMPV6: + s->counters.icmp++; + break; + default: + if (d.ethertype == 0x0806) { + s->counters.arp++; + } else { + s->counters.other++; + } + break; + } + if (d.ip_version == 6) { + s->counters.ipv6++; + } + if (d.app_flags & PS_APP_DNS) { + s->counters.dns++; + } + if (d.app_flags & PS_APP_TLS) { + s->counters.tls++; + } + } else { + s->counters.other++; + } + + if (s->have_pcap) { + if (ps_pcap_write(&s->pcap, rec) != 0) { + LOG_WARN("pcap write failed: %s", strerror(errno)); + } + } + + if (s->nclients == 0) { + return; + } + + /* Build the PACKET frame straight into a reusable buffer. */ + size_t need = PS_HEADER_LEN + PS_PKT_HDR_LEN + rec->caplen; + if (need > s->frame_buf_cap) { + s->frame_buf = ps_xrealloc(s->frame_buf, need); + s->frame_buf_cap = need; + } + uint32_t plen = (uint32_t)ps_packet_encode(s->frame_buf + PS_HEADER_LEN, + s->frame_buf_cap - PS_HEADER_LEN, rec); + if (plen == 0) { + return; + } + size_t total = ps_frame_write(s->frame_buf, s->frame_buf_cap, PS_FRAME_PACKET, + s->frame_buf + PS_HEADER_LEN, plen); + if (total) { + broadcast(s, s->frame_buf, total); + } +} + +static void send_stats(struct server *s) { + uint8_t payload[PS_COUNTER_WIRE_SIZE]; + uint8_t frame[PS_HEADER_LEN + PS_COUNTER_WIRE_SIZE]; + + ps_capture_update_drops(&s->cap); + s->counters.dropped_kernel = s->cap.drops_total; + if (s->counters.dropped_kernel != s->last_kernel_drops) { + LOG_DEBUG("kernel drops: +%llu", + (unsigned long long)(s->counters.dropped_kernel - s->last_kernel_drops)); + s->last_kernel_drops = s->counters.dropped_kernel; + } + + size_t plen = ps_counters_encode(&s->counters, payload, sizeof(payload)); + size_t flen = ps_frame_write(frame, sizeof(frame), PS_FRAME_STATS, payload, (uint32_t)plen); + if (flen) { + broadcast(s, frame, flen); + } + + if (!s->quiet) { + char bytes[24]; + char line[512]; + + ps_fmt_bytes(bytes, sizeof(bytes), s->counters.bytes); + snprintf(line, sizeof(line), + "seen=%llu tcp=%llu udp=%llu icmp=%llu other=%llu bytes=%s clients=%d drops=%llu", + (unsigned long long)s->counters.seen, (unsigned long long)s->counters.tcp, + (unsigned long long)s->counters.udp, (unsigned long long)s->counters.icmp, + (unsigned long long)s->counters.other, bytes, s->nclients, + (unsigned long long)s->counters.dropped_kernel); + LOG_INFO("%s", line); + } +} + +static int resolve_bind(const char *addr, uint16_t port, struct sockaddr_storage *ss, + socklen_t *slen) { + memset(ss, 0, sizeof(*ss)); + if (!addr || !*addr) { + struct sockaddr_in *sin = (struct sockaddr_in *)ss; + sin->sin_family = AF_INET; + sin->sin_addr.s_addr = htonl(INADDR_ANY); + sin->sin_port = htons(port); + *slen = sizeof(*sin); + return 0; + } + + struct sockaddr_in *sin = (struct sockaddr_in *)ss; + sin->sin_family = AF_INET; + sin->sin_port = htons(port); + if (inet_pton(AF_INET, addr, &sin->sin_addr) == 1) { + *slen = sizeof(*sin); + return 0; + } + + struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)ss; + memset(sin6, 0, sizeof(*sin6)); + sin6->sin6_family = AF_INET6; + sin6->sin6_port = htons(port); + if (inet_pton(AF_INET6, addr, &sin6->sin6_addr) == 1) { + *slen = sizeof(*sin6); + return 0; + } + return -1; +} + +int ps_server_run(const struct ps_server_opts *opts) { + struct server s; + char err[256]; + int rc = 1; + + memset(&s, 0, sizeof(s)); + s.max_clients = opts->max_clients > 0 ? opts->max_clients : 8; + s.client_buffer = opts->client_buffer ? opts->client_buffer : (4u << 20); + s.stats_interval = opts->stats_interval ? opts->stats_interval : 5; + s.quiet = opts->quiet; + ps_counters_clear(&s.counters); + + enum ps_direction dir = PS_DIR_BOTH; + if (opts->direction == PS_SERVER_DIR_IN) { + dir = PS_DIR_IN; + } else if (opts->direction == PS_SERVER_DIR_OUT) { + dir = PS_DIR_OUT; + } + + /* The stream itself runs over TCP on the same box and would be captured, + * which turns a quiet link into a feedback loop. Exclude it by default - + * but only when we can compile a BPF program at all. */ + char filter[320]; + + filter[0] = '\0'; +#ifdef PS_HAVE_PCAP + if (!opts->capture_control) { + if (opts->bpf && *opts->bpf) { + snprintf(filter, sizeof(filter), "(%s) and not tcp port %u", opts->bpf, + (unsigned)opts->port); + } else { + snprintf(filter, sizeof(filter), "not tcp port %u", (unsigned)opts->port); + } + } else if (opts->bpf && *opts->bpf) { + ps_strlcpy(filter, opts->bpf, sizeof(filter)); + } +#else + if (opts->bpf && *opts->bpf) { + ps_strlcpy(filter, opts->bpf, sizeof(filter)); /* fails below with a clear message */ + } else if (!opts->capture_control) { + LOG_DEBUG("no libpcap in this build: the stream's own connection will be captured"); + } +#endif + const char *bpf = filter[0] ? filter : NULL; + + if (ps_capture_open(&s.cap, opts->iface, opts->snaplen, opts->promisc, dir, bpf, err, + sizeof(err)) != 0) { + LOG_ERROR("%s", err); + return 1; + } + + memset(&s.hello, 0, sizeof(s.hello)); + s.hello.linktype = s.cap.linktype; + s.hello.snaplen = s.cap.snaplen; + gethostname(s.hello.hostname, sizeof(s.hello.hostname) - 1); + ps_strlcpy(s.hello.iface, s.cap.iface, sizeof(s.hello.iface)); + if (bpf) { + ps_strlcpy(s.hello.filter, bpf, sizeof(s.hello.filter)); + } + + if (opts->pcap_path && *opts->pcap_path) { + if (ps_pcap_open(&s.pcap, opts->pcap_path, s.cap.snaplen, s.cap.linktype, + opts->pcap_rotate_bytes, err, sizeof(err)) != 0) { + LOG_ERROR("%s", err); + ps_capture_close(&s.cap); + return 1; + } + s.have_pcap = 1; + } + + struct sockaddr_storage bind_ss; + socklen_t bind_len; + if (resolve_bind(opts->bind_addr, opts->port, &bind_ss, &bind_len) != 0) { + LOG_ERROR("invalid bind address '%s'", opts->bind_addr); + goto done; + } + + s.listen_fd = socket(bind_ss.ss_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0); + if (s.listen_fd < 0) { + LOG_ERROR("listen socket: %s", strerror(errno)); + goto done; + } + int one = 1; + setsockopt(s.listen_fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)); + if (bind(s.listen_fd, (struct sockaddr *)&bind_ss, bind_len) != 0) { + LOG_ERROR("bind port %u: %s", (unsigned)opts->port, strerror(errno)); + goto done; + } + if (listen(s.listen_fd, 16) != 0) { + LOG_ERROR("listen: %s", strerror(errno)); + goto done; + } + + s.clients = ps_xmalloc(sizeof(struct client) * (size_t)s.max_clients); + for (int i = 0; i < s.max_clients; i++) { + memset(&s.clients[i], 0, sizeof(struct client)); + s.clients[i].fd = -1; + } + + s.epoll_fd = epoll_create1(EPOLL_CLOEXEC); + if (s.epoll_fd < 0) { + LOG_ERROR("epoll_create1: %s", strerror(errno)); + goto done; + } + + struct epoll_event ev; + memset(&ev, 0, sizeof(ev)); + ev.events = EPOLLIN; + ev.data.u32 = UINT32_MAX; /* listen socket marker */ + if (epoll_ctl(s.epoll_fd, EPOLL_CTL_ADD, s.listen_fd, &ev) != 0) { + LOG_ERROR("epoll_ctl listen: %s", strerror(errno)); + goto done; + } + memset(&ev, 0, sizeof(ev)); + ev.events = EPOLLIN; + ev.data.u32 = UINT32_MAX - 1; /* capture socket marker */ + if (epoll_ctl(s.epoll_fd, EPOLL_CTL_ADD, s.cap.fd, &ev) != 0) { + LOG_ERROR("epoll_ctl capture: %s", strerror(errno)); + goto done; + } + + struct sigaction sa; + memset(&sa, 0, sizeof(sa)); + sa.sa_handler = on_signal; + sigaction(SIGINT, &sa, NULL); + sigaction(SIGTERM, &sa, NULL); + signal(SIGPIPE, SIG_IGN); + + LOG_INFO("%s %s capturing on %s (snap %u, promisc %s, filter \"%s\")", + PS_NAME, PS_VERSION_STR, s.cap.iface, s.cap.snaplen, + s.cap.promisc ? "on" : "off", s.hello.filter[0] ? s.hello.filter : "none"); + LOG_INFO("streaming on port %u (max %d clients)", (unsigned)opts->port, s.max_clients); + if (s.have_pcap) { + LOG_INFO("recording to %s", opts->pcap_path); + } + + struct epoll_event events[MAX_EVENTS]; + time_t next_stats = time(NULL) + (time_t)s.stats_interval; + uint8_t *pkt_buf = ps_xmalloc(PS_SNAPLEN_MAX); + rc = 0; + + while (!g_stop) { + int n = epoll_wait(s.epoll_fd, events, MAX_EVENTS, 500); + if (n < 0) { + if (errno == EINTR) { + continue; + } + LOG_ERROR("epoll_wait: %s", strerror(errno)); + rc = 1; + break; + } + + for (int i = 0; i < n; i++) { + uint32_t id = events[i].data.u32; + + if (id == UINT32_MAX) { + accept_clients(&s); + } else if (id == UINT32_MAX - 1) { + int budget = EPOLL_BATCH; + while (budget-- > 0) { + struct ps_record rec; + int outgoing = 0; + int got = ps_capture_read(&s.cap, pkt_buf, PS_SNAPLEN_MAX, &rec, &outgoing); + if (got <= 0) { + break; + } + if (outgoing && opts->direction == PS_SERVER_DIR_IN) { + continue; + } + if (!outgoing && opts->direction == PS_SERVER_DIR_OUT) { + continue; + } + handle_packet(&s, &rec); + } + } else if (id < (uint32_t)s.max_clients) { + struct client *c = &s.clients[id]; + + if (c->fd < 0) { + continue; + } + if (events[i].events & EPOLLERR) { + close_client(&s, (int)id); + continue; + } + if (events[i].events & EPOLLOUT) { + int still = flush_client(&s, (int)id); + if (c->fd >= 0) { + update_epoll_out(&s, (int)id, still); + } + } + if (events[i].events & EPOLLIN) { + char scratch[256]; + ssize_t r = recv(c->fd, scratch, sizeof(scratch), MSG_DONTWAIT); + if (r == 0) { + close_client(&s, (int)id); + } + } + } + } + + time_t now = time(NULL); + if (now >= next_stats) { + send_stats(&s); + next_stats = now + (time_t)s.stats_interval; + } + } + + LOG_INFO("shutting down"); + { + uint8_t frame[PS_HEADER_LEN]; + size_t n = ps_frame_write(frame, sizeof(frame), PS_FRAME_BYE, NULL, 0); + + for (int i = 0; i < s.max_clients; i++) { + if (s.clients[i].fd >= 0) { + if (n) { + (void)send(s.clients[i].fd, frame, n, MSG_NOSIGNAL | MSG_DONTWAIT); + } + epoll_ctl(s.epoll_fd, EPOLL_CTL_DEL, s.clients[i].fd, NULL); + close(s.clients[i].fd); + s.clients[i].fd = -1; + ps_outbuf_free(&s.clients[i].q); + } + } + } + ps_capture_update_drops(&s.cap); + free(pkt_buf); + + { + char bytes[24]; + ps_fmt_bytes(bytes, sizeof(bytes), s.counters.bytes); + LOG_INFO("captured %llu frames (%s), kernel drops %llu", + (unsigned long long)s.counters.captured, bytes, + (unsigned long long)s.cap.drops_total); + } + +done: + if (s.have_pcap) { + ps_pcap_close(&s.pcap); + } + if (s.clients) { + for (int i = 0; i < s.max_clients; i++) { + if (s.clients[i].fd >= 0) { + close(s.clients[i].fd); + ps_outbuf_free(&s.clients[i].q); + } + } + } + if (s.epoll_fd > 0) { + close(s.epoll_fd); + } + if (s.listen_fd > 0) { + close(s.listen_fd); + } + free(s.clients); + free(s.frame_buf); + ps_capture_close(&s.cap); + return rc; +} diff --git a/src/stats.c b/src/stats.c new file mode 100644 index 0000000..a904e5f --- /dev/null +++ b/src/stats.c @@ -0,0 +1,76 @@ +/* stats.c - counter plumbing and wire (de)serialisation. */ +#include "stats.h" + +#include +#include + +#include "util.h" + +_Static_assert(sizeof(struct ps_counters) == PS_COUNTER_WIRE_SIZE, + "counter struct drifted from its wire format"); + +void ps_counters_clear(struct ps_counters *c) { memset(c, 0, sizeof(*c)); } + +void ps_counters_add(struct ps_counters *dst, const struct ps_counters *src) { +#define PS_COUNTER_ADD(name) dst->name += src->name; + PS_COUNTER_FIELDS(PS_COUNTER_ADD) +#undef PS_COUNTER_ADD + dst->dropped_kernel += src->dropped_kernel; + dst->dropped_client += src->dropped_client; +} + +size_t ps_counters_encode(const struct ps_counters *c, uint8_t *out, size_t cap) { + /* Field order is defined once, in PS_COUNTER_FIELDS. */ + const uint64_t *fields[PS_COUNTER_WIRE_FIELDS] = { +#define PS_COUNTER_ADDR(name) &c->name, + PS_COUNTER_FIELDS(PS_COUNTER_ADDR) +#undef PS_COUNTER_ADDR + &c->dropped_kernel, + &c->dropped_client, + }; + + if (cap < PS_COUNTER_WIRE_SIZE) { + return 0; + } + for (size_t i = 0; i < PS_COUNTER_WIRE_FIELDS; i++) { + ps_put_be64(out + i * 8, *fields[i]); + } + return PS_COUNTER_WIRE_SIZE; +} + +int ps_counters_decode(const uint8_t *in, uint32_t len, struct ps_counters *c) { + uint64_t *fields[PS_COUNTER_WIRE_FIELDS] = { +#define PS_COUNTER_PTR(name) &c->name, + PS_COUNTER_FIELDS(PS_COUNTER_PTR) +#undef PS_COUNTER_PTR + &c->dropped_kernel, + &c->dropped_client, + }; + + if (len < PS_COUNTER_WIRE_SIZE) { + return -1; + } + for (size_t i = 0; i < PS_COUNTER_WIRE_FIELDS; i++) { + *fields[i] = ps_be64(in + i * 8); + } + return 0; +} + +void ps_counters_format(const struct ps_counters *c, char *out, size_t cap) { + char bytes[24]; + size_t off = 0; + + ps_fmt_bytes(bytes, sizeof(bytes), c->bytes); + off = ps_appendf(out, cap, off, "seen=%llu captured=%llu bytes=%s", + (unsigned long long)c->seen, (unsigned long long)c->captured, bytes); + off = ps_appendf(out, cap, off, " tcp=%llu udp=%llu icmp=%llu arp=%llu", + (unsigned long long)c->tcp, (unsigned long long)c->udp, + (unsigned long long)c->icmp, (unsigned long long)c->arp); + off = ps_appendf(out, cap, off, " dns=%llu tls=%llu ipv6=%llu other=%llu", + (unsigned long long)c->dns, (unsigned long long)c->tls, + (unsigned long long)c->ipv6, (unsigned long long)c->other); + if (c->dropped_kernel || c->dropped_client) { + ps_appendf(out, cap, off, " dropped=%llu+%llu", + (unsigned long long)c->dropped_kernel, (unsigned long long)c->dropped_client); + } +} diff --git a/src/util.c b/src/util.c new file mode 100644 index 0000000..7d0757f --- /dev/null +++ b/src/util.c @@ -0,0 +1,143 @@ +/* util.c - small shared helpers. */ +#include "util.h" + +#include +#include +#include +#include +#include +#include + +static const char *g_prog = "pktsniff"; + +void ps_set_prog_name(const char *name) { + if (name && *name) { + g_prog = name; + } +} + +const char *ps_prog_name(void) { return g_prog; } + +static void oom(size_t n) { + fprintf(stderr, "%s: out of memory allocating %zu bytes\n", g_prog, n); + exit(1); +} + +void *ps_xmalloc(size_t n) { + void *p = malloc(n ? n : 1); + if (!p) { + oom(n); + } + return p; +} + +void *ps_xrealloc(void *p, size_t n) { + void *q = realloc(p, n ? n : 1); + if (!q) { + oom(n); + } + return q; +} + +char *ps_strdup(const char *s) { + size_t n = strlen(s) + 1; + char *p = ps_xmalloc(n); + memcpy(p, s, n); + return p; +} + +size_t ps_strlcpy(char *dst, const char *src, size_t cap) { + size_t len = strlen(src); + if (cap > 0) { + size_t n = len < cap - 1 ? len : cap - 1; + memcpy(dst, src, n); + dst[n] = '\0'; + } + return len; +} + +uint64_t ps_now_us(void) { + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + return (uint64_t)ts.tv_sec * 1000000ull + (uint64_t)(ts.tv_nsec / 1000); +} + +void ps_sleep_ms(unsigned ms) { + struct timespec ts; + ts.tv_sec = ms / 1000; + ts.tv_nsec = (long)(ms % 1000) * 1000000L; + nanosleep(&ts, NULL); +} + +void ps_fmt_bytes(char *out, size_t cap, uint64_t bytes) { + static const char *units[] = {"B", "KB", "MB", "GB", "TB", "PB"}; + double v = (double)bytes; + size_t u = 0; + + while (v >= 1000.0 && u + 1 < sizeof(units) / sizeof(units[0])) { + v /= 1000.0; + u++; + } + if (u == 0) { + snprintf(out, cap, "%llu B", (unsigned long long)bytes); + } else if (v < 10.0) { + snprintf(out, cap, "%.2f %s", v, units[u]); + } else if (v < 100.0) { + snprintf(out, cap, "%.1f %s", v, units[u]); + } else { + snprintf(out, cap, "%.0f %s", v, units[u]); + } +} + +void ps_fmt_rate(char *out, size_t cap, double value) { + if (value >= 1e9) { + snprintf(out, cap, "%.2f G/s", value / 1e9); + } else if (value >= 1e6) { + snprintf(out, cap, "%.2f M/s", value / 1e6); + } else if (value >= 1e3) { + snprintf(out, cap, "%.1f k/s", value / 1e3); + } else { + snprintf(out, cap, "%.0f /s", value); + } +} + +int ps_parse_u64(const char *s, uint64_t *out) { + char *end = NULL; + unsigned long long v; + + if (!s || !*s) { + return -1; + } + errno = 0; + v = strtoull(s, &end, 10); + if (errno != 0 || *end != '\0') { + return -1; + } + *out = (uint64_t)v; + return 0; +} + +int ps_parse_u32(const char *s, uint32_t *out) { + uint64_t v; + if (ps_parse_u64(s, &v) != 0 || v > UINT32_MAX) { + return -1; + } + *out = (uint32_t)v; + return 0; +} + +size_t ps_appendf(char *buf, size_t cap, size_t off, const char *fmt, ...) { + va_list ap; + int n; + + if (off >= cap) { + return off; + } + va_start(ap, fmt); + n = vsnprintf(buf + off, cap - off, fmt, ap); + va_end(ap); + if (n < 0) { + return off; + } + return off + (size_t)n; +} diff --git a/tests/e2e.sh b/tests/e2e.sh new file mode 100755 index 0000000..45540a2 --- /dev/null +++ b/tests/e2e.sh @@ -0,0 +1,211 @@ +#!/usr/bin/env bash +# e2e.sh - live end-to-end checks. Needs root (raw sockets), python3, tcpdump. +# +# sudo tests/e2e.sh +# +# Everything is confined to the loopback interface and port 8899. +set -uo pipefail + +cd "$(dirname "$0")/.." +BIN=./bin +PORT=8899 +WORK=$(mktemp -d) +FAIL=0 +SRV_PID="" +CLI_PID="" + +cleanup() { + [ -n "$CLI_PID" ] && kill "$CLI_PID" 2>/dev/null + [ -n "$SRV_PID" ] && kill "$SRV_PID" 2>/dev/null + pkill -f pktsniff-server 2>/dev/null + rm -rf "$WORK" +} +trap cleanup EXIT + +ok() { printf ' \033[32mok\033[0m %s\n' "$1"; } +bad() { + printf ' \033[31mFAIL\033[0m %s\n' "$1" + [ -n "${2:-}" ] && sed 's/^/ /' "$2" | tail -5 + FAIL=$((FAIL + 1)) +} +note() { printf '\n\033[1m%s\033[0m\n' "$1"; } + +expect() { # expect + local desc=$1 log=$2 + shift 2 + if "$@"; then ok "$desc"; else bad "$desc" "$log"; fi +} + +start_server() { # start_server [extra args...] + local log=$1 + shift + $BIN/pktsniff-server -i lo -p "$PORT" -q "$@" >"$log" 2>&1 & + SRV_PID=$! + sleep 0.7 +} + +stop_server() { + [ -n "$SRV_PID" ] || return 0 + kill -TERM "$SRV_PID" 2>/dev/null + wait "$SRV_PID" 2>/dev/null + SRV_PID="" +} + +traffic() { # background UDP noise + python3 - <<'PY' & +import socket, time +s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) +end = time.time() + 5 +while time.time() < end: + for _ in range(50): + s.sendto(b'x' * 200, ('127.0.0.1', 5399)) + time.sleep(0.001) +PY + TRAFFIC_PID=$! +} + +json_ok() { # json_ok [proto] + python3 - "$1" "${2:-}" <<'PY' +import json, sys +lines = [json.loads(l) for l in open(sys.argv[1])] +assert lines, "no lines" +if len(sys.argv) > 2 and sys.argv[2]: + assert all(l["proto"] == sys.argv[2] for l in lines), lines[0] +PY +} + +[ "$(id -u)" -eq 0 ] || { + echo "must run as root" + exit 1 +} + +note "build" +if make -s -j4 >/dev/null 2>&1; then ok "make"; else bad "make"; fi + +HAVE_PCAP=0 +if $BIN/pktsniff-server --version 2>/dev/null | grep -q 'libpcap filtering: yes'; then + HAVE_PCAP=1 +fi +echo " libpcap: $([ "$HAVE_PCAP" -eq 1 ] && echo yes || echo "no (kernel filters skipped)")" + +note "basic streaming" +start_server "$WORK/srv1.log" +$BIN/pktsniff-client 127.0.0.1 -p $PORT -d 4 -F 'proto:udp' -w "$WORK/cli1.pcap" \ + >"$WORK/cli1.out" 2>"$WORK/cli1.err" & +CLI_PID=$! +sleep 0.4 +ping -c 3 -i 0.1 127.0.0.1 >/dev/null 2>&1 +traffic +wait "$CLI_PID" +CLI_PID="" +wait "$TRAFFIC_PID" 2>/dev/null + +expect "client received matching packets" "$WORK/cli1.out" \ + test "$(wc -l <"$WORK/cli1.out")" -gt 3 +expect "client never desynchronised" "$WORK/cli1.err" \ + bash -c '! grep -q "protocol error" "$1"' _ "$WORK/cli1.err" +expect "client wrote a readable pcap" "$WORK/cli1.err" \ + tcpdump -r "$WORK/cli1.pcap" -nn -c 1 -q +expect "no ANSI colour when stdout is a pipe" "$WORK/cli1.out" \ + bash -c '! grep -q $'"'"'\033'"'"' "$1"' _ "$WORK/cli1.out" +expect "server logged the client" "$WORK/srv1.log" \ + grep -q 'client 127.0.0.1' "$WORK/srv1.log" +stop_server + +note "server-side BPF filter and recording" +if [ "$HAVE_PCAP" -eq 1 ]; then + start_server "$WORK/srv2.log" -f 'icmp' -w "$WORK/srv2.pcap" +else + start_server "$WORK/srv2.log" -w "$WORK/srv2.pcap" +fi +ping -c 3 -i 0.1 127.0.0.1 >/dev/null 2>&1 +sleep 0.3 +stop_server +if [ "$HAVE_PCAP" -eq 1 ]; then + expect "filter compiled" "$WORK/srv2.log" \ + bash -c '! grep -q "bad filter" "$1"' _ "$WORK/srv2.log" + expect "pcap holds ICMP only" "$WORK/srv2.log" bash -c ' + out=$(tcpdump -r "$1" -nn 2>/dev/null) + grep -q ICMP <<<"$out" && ! grep -q UDP <<<"$out"' _ "$WORK/srv2.pcap" +fi +expect "server-side pcap holds our pings" "$WORK/srv2.log" \ + tcpdump -r "$WORK/srv2.pcap" -nn -q -c 1 +expect "SIGTERM shut the server down cleanly" "$WORK/srv2.log" \ + grep -q 'shutting down' "$WORK/srv2.log" + +note "slow consumer survives drops" +start_server "$WORK/srv3.log" --client-buffer 65536 +$BIN/pktsniff-client 127.0.0.1 -p $PORT -d 4 -F 'proto:udp' -X >"$WORK/cli3.out" 2>"$WORK/cli3.err" & +CLI_PID=$! +sleep 0.4 +traffic +wait "$CLI_PID" +CLI_PID="" +wait "$TRAFFIC_PID" 2>/dev/null +expect "no desync with a 64 KiB client buffer" "$WORK/cli3.err" \ + bash -c '! grep -q "protocol error" "$1"' _ "$WORK/cli3.err" +expect "frames still arrived" "$WORK/cli3.out" test -s "$WORK/cli3.out" +stop_server + +note "json output and --count" +start_server "$WORK/srv4.log" +traffic +$BIN/pktsniff-client 127.0.0.1 -p $PORT -c 5 -d 8 -F 'proto:udp' --json "$WORK/out.json" -q \ + >/dev/null 2>"$WORK/cli4.err" +wait "$TRAFFIC_PID" 2>/dev/null +expect "exited after --count with output" "$WORK/cli4.err" test -s "$WORK/out.json" +expect "every line is valid json" "$WORK/cli4.err" json_ok "$WORK/out.json" +expect "--count stopped at exactly 5" "$WORK/cli4.err" \ + test "$(wc -l <"$WORK/out.json")" -eq 5 +expect "json records carry the udp application view" "$WORK/cli4.err" \ + json_ok "$WORK/out.json" UDP +stop_server + +note "direction filtering" +start_server "$WORK/srv7.log" --direction in +$BIN/pktsniff-client 127.0.0.1 -p $PORT -d 2 -q -F 'proto:udp' >"$WORK/in.out" 2>"$WORK/in.err" & +CLI_PID=$! +traffic +sleep 2 +wait "$CLI_PID" 2>/dev/null +CLI_PID="" +wait "$TRAFFIC_PID" 2>/dev/null +expect "--direction in runs and stays synchronised" "$WORK/in.err" \ + bash -c '! grep -q "protocol error" "$1"' _ "$WORK/in.err" +stop_server + +note "concurrency and limits" +start_server "$WORK/srv5.log" -m 2 +$BIN/pktsniff-client 127.0.0.1 -p $PORT -d 2 -F 'icmp' >/dev/null 2>&1 & +A=$! +$BIN/pktsniff-client 127.0.0.1 -p $PORT -d 2 -F 'icmp' >/dev/null 2>&1 & +B=$! +sleep 0.5 +$BIN/pktsniff-client 127.0.0.1 -p $PORT -d 1 -q >/dev/null 2>"$WORK/cli5.err" +wait $A $B 2>/dev/null +expect "third client rejected with a message" "$WORK/cli5.err" \ + grep -q 'no free client slot' "$WORK/cli5.err" +expect "server kept both slots" "$WORK/srv5.log" \ + test "$(grep -c 'client 127.0.0.1' "$WORK/srv5.log")" -ge 2 +stop_server + +note "argument handling" +if [ "$HAVE_PCAP" -eq 1 ]; then + $BIN/pktsniff-server -i lo -p $PORT -f 'bogus filter here' >"$WORK/srv6.log" 2>&1 + expect "bad BPF rejected at startup" "$WORK/srv6.log" \ + grep -q 'bad filter' "$WORK/srv6.log" +fi +$BIN/pktsniff-client --bad-option >/dev/null 2>&1 +expect "client bad option exits 2" "" test $? -eq 2 +$BIN/pktsniff-client -F 'proto:nope' -c 1 127.0.0.1 >/dev/null 2>&1 +expect "unknown proto in filter is rejected" "" test $? -eq 2 +$BIN/pktsniff-server --list-interfaces >"$WORK/ifaces.txt" 2>&1 +expect "--list-interfaces works" "$WORK/ifaces.txt" grep -q 'lo' "$WORK/ifaces.txt" + +printf '\n' +if [ "$FAIL" -eq 0 ]; then + printf '\033[32mall e2e checks passed\033[0m\n' + exit 0 +fi +printf '\033[31m%d e2e check(s) failed\033[0m\n' "$FAIL" +exit 1 diff --git a/tests/test.h b/tests/test.h new file mode 100644 index 0000000..f5d5512 --- /dev/null +++ b/tests/test.h @@ -0,0 +1,67 @@ +/* test.h - minimal assertion harness (no external dependencies). */ +#ifndef PS_TEST_H +#define PS_TEST_H + +#include +#include + +static int t_failures; +static int t_checks; +static const char *t_current = ""; + +#define RUN(fn) \ + do { \ + t_current = #fn; \ + printf(" %-28s ", #fn); \ + fn(); \ + printf("ok\n"); \ + } while (0) + +#define FAILF(...) \ + do { \ + printf("\n FAIL [%s] ", t_current); \ + printf(__VA_ARGS__); \ + printf("\n at %s:%d\n", __FILE__, __LINE__); \ + t_failures++; \ + } while (0) + +#define CHECK(cond) \ + do { \ + t_checks++; \ + if (!(cond)) { \ + FAILF("expected %s", #cond); \ + } \ + } while (0) + +#define CHECK_EQ(a, b) \ + do { \ + t_checks++; \ + long long _a = (long long)(a), _b = (long long)(b); \ + if (_a != _b) { \ + FAILF("%s == %s (%lld vs %lld)", #a, #b, _a, _b); \ + } \ + } while (0) + +#define CHECK_STR(a, b) \ + do { \ + t_checks++; \ + const char *_a = (a), *_b = (b); \ + if (!_a || strcmp(_a, _b) != 0) { \ + FAILF("%s == \"%s\" (got \"%s\")", #a, _b, _a ? _a : "(null)"); \ + } \ + } while (0) + +#define CHECK_MEM(a, b, n) \ + do { \ + t_checks++; \ + if (memcmp((a), (b), (n)) != 0) { \ + FAILF("%s matches %s (%zu bytes)", #a, #b, (size_t)(n)); \ + } \ + } while (0) + +static inline int test_report(void) { + printf("%d checks, %d failures\n", t_checks, t_failures); + return t_failures == 0 ? 0 : 1; +} + +#endif /* PS_TEST_H */ diff --git a/tests/test_decode.c b/tests/test_decode.c new file mode 100644 index 0000000..ad4ea4f --- /dev/null +++ b/tests/test_decode.c @@ -0,0 +1,302 @@ +/* test_decode.c - dissection of hand-built frames, including truncation. */ +#include +#include + +#include "decode.h" +#include "test.h" + +/* Builds an Ethernet + IPv4 + UDP frame; returns its length. */ +static size_t build_udp(uint8_t *buf, size_t cap) { + static const uint8_t payload[] = {0xde, 0xad, 0xbe, 0xef}; + size_t n = 0; + + memset(buf, 0, cap); + /* dst mac, src mac */ + memset(buf + 0, 0x11, 6); + memset(buf + 6, 0x22, 6); + buf[12] = 0x08; + buf[13] = 0x00; + n = 14; + + /* IPv4 */ + buf[n + 0] = 0x45; + buf[n + 2] = 0; + buf[n + 3] = (uint8_t)(20 + 8 + sizeof(payload)); + buf[n + 8] = 64; /* ttl */ + buf[n + 9] = 17; /* udp */ + buf[n + 12] = 10; + buf[n + 13] = 0; + buf[n + 14] = 0; + buf[n + 15] = 1; + buf[n + 16] = 10; + buf[n + 17] = 0; + buf[n + 18] = 0; + buf[n + 19] = 2; + n += 20; + + /* UDP */ + buf[n + 0] = 0x1F; + buf[n + 1] = 0x90; /* 8080 */ + buf[n + 2] = 0x00; + buf[n + 3] = 0x35; /* 53 */ + buf[n + 4] = 0; + buf[n + 5] = (uint8_t)(8 + sizeof(payload)); + n += 8; + + memcpy(buf + n, payload, sizeof(payload)); + return n + sizeof(payload); +} + +/* Rewrites the IPv4 total-length and UDP length fields so the frame is valid + * for a payload of `payload_len` bytes appended after the 42-byte headers. */ +static void fix_lengths_n(uint8_t *frame, size_t payload_len, size_t l4_hdr) { + uint16_t ip_total = (uint16_t)(20 + l4_hdr + payload_len); + + frame[16] = (uint8_t)(ip_total >> 8); + frame[17] = (uint8_t)(ip_total & 0xFF); + if (l4_hdr == 8) { + uint16_t udp_total = (uint16_t)(8 + payload_len); + frame[38] = (uint8_t)(udp_total >> 8); + frame[39] = (uint8_t)(udp_total & 0xFF); + } +} + +static void fix_lengths(uint8_t *frame, size_t payload_len) { + fix_lengths_n(frame, payload_len, 8); +} + +/* Same as build_udp() but over TCP with no payload; returns its length. */ +static size_t build_tcp(uint8_t *buf, size_t cap) { + size_t n = build_udp(buf, cap); + + /* Turn the 42-byte headers into TCP by swapping the transport header. */ + n = 14 + 20; + buf[14 + 9] = 6; /* protocol */ + memset(buf + n, 0, 20); + n += 20; + buf[34] = 0xC3; + buf[35] = 0x50; /* sport 50000 */ + buf[36] = 0x01; + buf[37] = 0xBB; /* dport 443 */ + buf[46] = 0x50; /* data offset 5 */ + return n; +} + +static void test_udp_basics(void) { + uint8_t frame[128]; + struct ps_decoded d; + size_t len = build_udp(frame, sizeof(frame)); + + CHECK_EQ(ps_decode(frame, (uint32_t)len, (uint32_t)len, PS_DLT_EN10MB, &d), 0); + CHECK(d.has_eth); + CHECK_EQ(d.ip_version, 4); + CHECK_EQ(d.l4, PS_L4_UDP); + CHECK_EQ(d.sport, 8080); + CHECK_EQ(d.dport, 53); + CHECK_EQ(d.ttl, 64); + CHECK_STR(d.src, "10.0.0.1"); + CHECK_STR(d.dst, "10.0.0.2"); + CHECK_STR(d.src_mac, "22:22:22:22:22:22"); + CHECK_EQ(d.payload_len, 4); + CHECK_MEM(d.payload, "\xde\xad\xbe\xef", 4); +} + +static void test_every_truncation(void) { + uint8_t frame[128]; + struct ps_decoded d; + size_t len = build_udp(frame, sizeof(frame)); + + /* No prefix may read out of bounds, and short frames must fail cleanly. */ + for (size_t cut = 0; cut <= len; cut++) { + int rc = ps_decode(frame, (uint32_t)cut, (uint32_t)len, PS_DLT_EN10MB, &d); + if (cut < 14) { + CHECK_EQ(rc, -1); + } else { + CHECK_EQ(rc, 0); + } + } +} + +static void test_vlan_tag(void) { + uint8_t frame[160]; + struct ps_decoded d; + + memset(frame, 0, sizeof(frame)); + memset(frame + 0, 0x11, 6); + memset(frame + 6, 0x22, 6); + frame[12] = 0x81; + frame[13] = 0x00; /* 802.1Q */ + frame[14] = 0x00; + frame[15] = 0x2A; /* vlan 42 */ + frame[16] = 0x08; + frame[17] = 0x00; /* IPv4 */ + frame[18] = 0x45; + frame[20] = 0x00; + frame[21] = 40; + frame[26] = 64; + frame[27] = 6; + frame[30] = 192; + frame[31] = 168; + frame[32] = 0; + frame[33] = 1; + frame[34] = 192; + frame[35] = 168; + frame[36] = 0; + frame[37] = 2; + /* TCP header (data offset 5) */ + frame[50] = 0x50; + frame[38] = 0x01; + frame[39] = 0xBB; + frame[40] = 0x30; + frame[41] = 0x39; + frame[51] = 0x02; /* SYN */ + + CHECK_EQ(ps_decode(frame, 58, 58, PS_DLT_EN10MB, &d), 0); + CHECK(d.has_vlan); + CHECK_EQ(d.vlan_id, 42); + CHECK_EQ(d.l4, PS_L4_TCP); + CHECK_EQ(d.tcp_flags, PS_TCP_SYN); + CHECK_EQ(d.sport, 443); + CHECK_EQ(d.dport, 12345); +} + +static void test_arp(void) { + uint8_t frame[64]; + struct ps_decoded d; + + memset(frame, 0, sizeof(frame)); + memset(frame + 0, 0xFF, 6); + memset(frame + 6, 0x22, 6); + frame[12] = 0x08; + frame[13] = 0x06; + frame[14] = 0x00; + frame[15] = 0x01; + frame[16] = 0x08; + frame[17] = 0x00; + frame[18] = 6; + frame[19] = 4; + frame[20] = 0x00; + frame[21] = 0x01; /* request */ + memset(frame + 22, 0x22, 6); + frame[28] = 10, frame[29] = 0, frame[30] = 0, frame[31] = 5; + memset(frame + 32, 0x00, 6); + frame[38] = 10, frame[39] = 0, frame[40] = 0, frame[41] = 1; + + CHECK_EQ(ps_decode(frame, 42, 42, PS_DLT_EN10MB, &d), 0); + CHECK_STR(ps_proto_label(&d), "ARP"); + CHECK_EQ(d.arp_op, 1); + CHECK_STR(d.arp_sender_ip, "10.0.0.5"); + CHECK_STR(d.arp_target_ip, "10.0.0.1"); + CHECK(strstr(d.info, "who-has 10.0.0.1") != NULL); +} + +static void test_raw_ip_and_ipv6(void) { + uint8_t frame[128]; + struct ps_decoded d; + + /* Bare IPv4 (DLT_RAW). */ + memset(frame, 0, sizeof(frame)); + frame[0] = 0x45; + frame[9] = 1; /* ICMP */ + frame[12] = 172; + frame[13] = 16; + frame[14] = 0; + frame[15] = 1; + frame[16] = 172; + frame[17] = 16; + frame[18] = 0; + frame[19] = 2; + frame[20] = 8; /* echo request */ + CHECK_EQ(ps_decode(frame, 28, 28, PS_DLT_RAW, &d), 0); + CHECK_EQ(d.l4, PS_L4_ICMP); + CHECK_EQ(d.icmp_type, 8); + + /* Bare IPv6 (DLT_RAW) + ICMPv6. */ + memset(frame, 0, sizeof(frame)); + frame[0] = 0x60; + frame[6] = 58; /* next header: ICMPv6 */ + frame[7] = 255; + frame[8] = 0xfe; + frame[24] = 0xfe; + frame[39] = 1; + frame[40] = 128; /* echo request */ + CHECK_EQ(ps_decode(frame, 48, 48, PS_DLT_RAW, &d), 0); + CHECK_EQ(d.ip_version, 6); + CHECK_EQ(d.l4, PS_L4_ICMPV6); + CHECK_STR(d.dst, "fe00::1"); +} + +static void test_dns_peek(void) { + uint8_t frame[128]; + struct ps_decoded d; + size_t len; + size_t n; + static const uint8_t query[] = { + 0x12, 0x34, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 7, 'e', 'x', 'a', 'm', 'p', 'l', 'e', 3, 'c', 'o', 'm', + 0, 0x00, 0x01, 0x00, 0x01, + }; + + len = build_udp(frame, sizeof(frame)); + n = len - 4; + memcpy(frame + n, query, sizeof(query)); + len = n + sizeof(query); + fix_lengths(frame, sizeof(query)); + + CHECK_EQ(ps_decode(frame, (uint32_t)len, (uint32_t)len, PS_DLT_EN10MB, &d), 0); + CHECK(d.app_flags & PS_APP_DNS); + CHECK_STR(d.app, "DNS A example.com"); +} + +static void test_tls_sni(void) { + /* Minimal ClientHello carrying a server_name extension. */ + static const uint8_t hello[] = { + 0x16, 0x03, 0x01, 0x00, 0x3b, /* record header, len 59 */ + 0x01, 0x00, 0x00, 0x37, /* ClientHello, len 55 */ + 0x03, 0x03, /* client version */ + /* 32-byte random */ + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, + 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, + 0x00, /* session id length */ + 0x00, 0x02, /* cipher suites length */ + 0x13, 0x01, /* TLS_AES_128_GCM_SHA256 */ + 0x01, 0x00, /* compression methods */ + 0x00, 0x0c, /* extensions length */ + 0x00, 0x00, 0x00, 0x08, /* server_name, len 8 */ + 0x00, 0x06, /* server name list, len 6 */ + 0x00, 0x00, 0x03, /* host_name, len 3 */ + 'a', '.', 'b', + }; + uint8_t frame[256]; + struct ps_decoded d; + size_t n = build_tcp(frame, sizeof(frame)); + + memcpy(frame + n, hello, sizeof(hello)); + size_t len = n + sizeof(hello); + fix_lengths_n(frame, sizeof(hello), 20); + + CHECK_EQ(ps_decode(frame, (uint32_t)len, (uint32_t)len, PS_DLT_EN10MB, &d), 0); + CHECK(d.app_flags & PS_APP_TLS); + CHECK_STR(d.app, "TLS SNI=a.b"); +} + +static void test_hexdump(void) { + char out[1024]; + static const uint8_t data[] = {'A', 'B', 0x01, 0xff}; + + ps_hexdump(data, sizeof(data), 64, out, sizeof(out)); + CHECK(strstr(out, "41 42 01 ff") != NULL); + CHECK(strstr(out, "|AB..") != NULL); +} + +int main(void) { + RUN(test_udp_basics); + RUN(test_every_truncation); + RUN(test_vlan_tag); + RUN(test_arp); + RUN(test_raw_ip_and_ipv6); + RUN(test_dns_peek); + RUN(test_tls_sni); + RUN(test_hexdump); + return test_report(); +} diff --git a/tests/test_filter.c b/tests/test_filter.c new file mode 100644 index 0000000..c064850 --- /dev/null +++ b/tests/test_filter.c @@ -0,0 +1,123 @@ +/* test_filter.c - filter grammar and matching. */ +#include +#include + +#include "filter.h" +#include "test.h" + +static struct ps_decoded tcp_pkt(uint16_t sport, uint16_t dport, const char *src, + const char *dst) { + struct ps_decoded d; + + memset(&d, 0, sizeof(d)); + d.l4 = PS_L4_TCP; + d.ip_version = 4; + d.sport = sport; + d.dport = dport; + d.origlen = 120; + strcpy(d.src, src); + strcpy(d.dst, dst); + d.payload = (const uint8_t *)"GET /secret HTTP/1.1\r\n"; + d.payload_len = 23; + return d; +} + +static void test_expr_matching(void) { + struct ps_filter f; + char err[128]; + struct ps_decoded d = tcp_pkt(51000, 443, "10.1.2.3", "93.184.216.34"); + + CHECK_EQ(ps_filter_parse("proto:tcp port:443", &f, err, sizeof(err)), 0); + CHECK_EQ(f.groups[0].count, 2); + CHECK(ps_filter_match(&f, &d)); + + CHECK_EQ(ps_filter_parse("port:80", &f, err, sizeof(err)), 0); + CHECK(!ps_filter_match(&f, &d)); + + CHECK_EQ(ps_filter_parse("!port:80", &f, err, sizeof(err)), 0); + CHECK(ps_filter_match(&f, &d)); + + CHECK_EQ(ps_filter_parse("host:10.0.0.0/8", &f, err, sizeof(err)), 0); + CHECK(ps_filter_match(&f, &d)); + + CHECK_EQ(ps_filter_parse("host:192.168.0.0/16", &f, err, sizeof(err)), 0); + CHECK(!ps_filter_match(&f, &d)); + + CHECK_EQ(ps_filter_parse("host:10.0.0.0/8,dst:93.184.216.0/24", &f, err, sizeof(err)), 0); + CHECK(ps_filter_match(&f, &d)); + + CHECK_EQ(ps_filter_parse("contains:secret", &f, err, sizeof(err)), 0); + CHECK(ps_filter_match(&f, &d)); + + CHECK_EQ(ps_filter_parse("bytes:>100", &f, err, sizeof(err)), 0); + CHECK(ps_filter_match(&f, &d)); + + CHECK_EQ(ps_filter_parse("443", &f, err, sizeof(err)), 0); + CHECK(ps_filter_match(&f, &d)); +} + +static void test_shorthand_and_proto_names(void) { + struct ps_filter f; + char err[128]; + struct ps_decoded udp = tcp_pkt(53, 51001, "8.8.8.8", "10.0.0.1"); + + udp.l4 = PS_L4_UDP; + CHECK_EQ(ps_filter_parse("udp", &f, err, sizeof(err)), 0); + CHECK(ps_filter_match(&f, &udp)); + + udp.app_flags = PS_APP_DNS; + CHECK_EQ(ps_filter_parse("proto:dns", &f, err, sizeof(err)), 0); + CHECK(ps_filter_match(&f, &udp)); + + CHECK_EQ(ps_filter_parse("tcp", &f, err, sizeof(err)), 0); + CHECK(!ps_filter_match(&f, &udp)); + + CHECK_EQ(ps_filter_parse("8.8.8.8", &f, err, sizeof(err)), 0); + CHECK(ps_filter_match(&f, &udp)); +} + +static void test_or_groups(void) { + struct ps_filter f; + char err[128]; + struct ps_decoded tcp = tcp_pkt(51000, 443, "10.1.2.3", "93.184.216.34"); + struct ps_decoded udp = tcp_pkt(53, 51001, "8.8.8.8", "10.0.0.1"); + + udp.l4 = PS_L4_UDP; + + CHECK_EQ(ps_filter_parse("proto:udp or port:443", &f, err, sizeof(err)), 0); + CHECK_EQ(f.count, 2); + CHECK(ps_filter_match(&f, &tcp)); + CHECK(ps_filter_match(&f, &udp)); + + /* Groups are AND inside, so one failing term kills only that group. */ + CHECK_EQ(ps_filter_parse("proto:udp port:443 or proto:tcp port:443", &f, err, sizeof(err)), 0); + CHECK(ps_filter_match(&f, &tcp)); + CHECK(!ps_filter_match(&f, &udp)); + + CHECK_EQ(ps_filter_parse("udp|icmp", &f, err, sizeof(err)), 0); + CHECK_EQ(f.count, 2); +} + +static void test_bad_expressions(void) { + struct ps_filter f; + char err[128]; + + CHECK_EQ(ps_filter_parse("port:notaport", &f, err, sizeof(err)), -1); + CHECK(err[0] != 0); + CHECK_EQ(ps_filter_parse("bogus:1", &f, err, sizeof(err)), -1); + CHECK_EQ(ps_filter_parse("host:999.1.1.1", &f, err, sizeof(err)), -1); + CHECK_EQ(ps_filter_parse("bytes:>", &f, err, sizeof(err)), -1); + CHECK_EQ(ps_filter_parse("port:", &f, err, sizeof(err)), -1); + CHECK_EQ(ps_filter_parse("or tcp", &f, err, sizeof(err)), -1); + CHECK_EQ(ps_filter_parse("tcp or", &f, err, sizeof(err)), -1); + CHECK_EQ(ps_filter_parse("", &f, err, sizeof(err)), 0); + CHECK(ps_filter_is_empty(&f)); +} + +int main(void) { + RUN(test_expr_matching); + RUN(test_shorthand_and_proto_names); + RUN(test_or_groups); + RUN(test_bad_expressions); + return test_report(); +} diff --git a/tests/test_outbuf.c b/tests/test_outbuf.c new file mode 100644 index 0000000..d5226ad --- /dev/null +++ b/tests/test_outbuf.c @@ -0,0 +1,260 @@ +/* test_outbuf.c - the send queue must never hand a peer a partial frame. + * + * Simulates the real failure mode: a client that reads slowly, send() that + * accepts only part of what it is given, and a producer that outruns both. + */ +#include +#include +#include + +#include "outbuf.h" +#include "proto.h" +#include "test.h" + +/* Payload layout: u32 sequence number | u32 payload bytes | filler. The + * receiver rebuilds the stream and checks both, so a truncated or reordered + * frame shows up immediately. */ +#define PAYLOAD_EXTRA 8u + +static size_t make_frame(uint8_t *out, size_t cap, uint32_t seq, size_t payload) { + uint8_t body[4096]; + + if (payload > sizeof(body)) { + payload = sizeof(body); + } + memset(body, (int)(seq & 0xFF), payload); + ps_put_be32(body + 0, seq); + ps_put_be32(body + 4, (uint32_t)payload); + return ps_frame_write(out, cap, PS_FRAME_PACKET, body, (uint32_t)payload); +} + +struct sink { + uint8_t buf[1 << 20]; + size_t len; +}; + +/* Copies at most `limit` bytes out of the queue, mimicking a short send(). */ +static size_t drain(struct ps_outbuf *q, struct sink *s, size_t limit) { + size_t n = ps_outbuf_pending(q); + + if (n > limit) { + n = limit; + } + if (s->len + n > sizeof(s->buf)) { + n = sizeof(s->buf) - s->len; + } + memcpy(s->buf + s->len, ps_outbuf_head(q), n); + s->len += n; + ps_outbuf_consume(q, n); + return n; +} + +/* Validates the delivered stream: contiguous frames, no gaps in `first_seq` + * beyond the ones reported as dropped. Returns frames seen. */ +static size_t verify(const struct sink *s, uint32_t first_seq, size_t *bad) { + uint8_t scratch[8192]; + struct ps_reader r; + struct ps_frame f; + size_t frames = 0; + uint32_t expect = first_seq; + *bad = 0; + + ps_reader_init(&r, 4096); + if (ps_reader_feed(&r, s->buf, s->len) != 0) { + *bad = 1; + ps_reader_free(&r); + return 0; + } + while (ps_reader_next(&r, &f) == 1) { + uint32_t seq, plen; + + if (f.type != PS_FRAME_PACKET || f.len < PAYLOAD_EXTRA) { + (*bad)++; + continue; + } + seq = ps_be32(f.data); + plen = ps_be32(f.data + 4); + if (plen != f.len) { + (*bad)++; + } + if (seq < expect) { + (*bad)++; /* reordered or duplicated */ + } + /* Filler must match the sequence byte, i.e. the body is intact. */ + for (uint32_t i = PAYLOAD_EXTRA; i < f.len && i < sizeof(scratch); i++) { + if (f.data[i] != (uint8_t)(seq & 0xFF)) { + (*bad)++; + break; + } + } + expect = seq + 1; + frames++; + } + ps_reader_free(&r); + return frames; +} + +static void test_no_drops_clean_stream(void) { + struct ps_outbuf q; + struct sink s; + uint8_t frame[4096]; + size_t bad = 0; + + memset(&s, 0, sizeof(s)); + ps_outbuf_init(&q, 1 << 16); + for (uint32_t i = 0; i < 500; i++) { + size_t n = make_frame(frame, sizeof(frame), i, 40 + (i % 300)); + CHECK_EQ(ps_outbuf_push(&q, frame, n), 0); + drain(&q, &s, 1 << 20); /* reader keeps up */ + } + CHECK_EQ(q.dropped_frames, 0); + CHECK_EQ(verify(&s, 0, &bad), 500); + CHECK_EQ(bad, 0); + ps_outbuf_free(&q); +} + +static void test_partial_writes_keep_frames_atomic(void) { + struct ps_outbuf q; + struct sink s; + uint8_t frame[4096]; + size_t bad = 0; + + memset(&s, 0, sizeof(s)); + ps_outbuf_init(&q, 1 << 14); + for (uint32_t i = 0; i < 2000; i++) { + size_t n = make_frame(frame, sizeof(frame), i, 100 + (i % 700)); + CHECK_EQ(ps_outbuf_push(&q, frame, n), 0); + drain(&q, &s, 1 << 20); /* trickle is exercised below */ + } + /* Flush what is left. */ + while (ps_outbuf_pending(&q) > 0) { + drain(&q, &s, 7); + } + CHECK_EQ(q.dropped_frames, 0); + CHECK_EQ(verify(&s, 0, &bad), 2000); + CHECK_EQ(bad, 0); + ps_outbuf_free(&q); +} + +static void test_drops_only_whole_frames(void) { + struct ps_outbuf q; + struct sink s; + uint8_t frame[8192]; + size_t bad = 0; + size_t produced = 0; + uint64_t drops_seen = 0; + + memset(&s, 0, sizeof(s)); + ps_outbuf_init(&q, 1 << 13); /* 8 KiB: forces constant dropping */ + + for (uint32_t i = 0; i < 5000; i++) { + size_t n = make_frame(frame, sizeof(frame), i, 200 + (i % 900)); + int rc = ps_outbuf_push(&q, frame, n); + + if (rc != 0) { + FAILF("push %u never fit (cap=%zu r=%zu fs=%zu w=%zu len=%zu drops=%llu)", i, q.cap, + q.r, q.frame_start, q.w, n, (unsigned long long)q.dropped_frames); + break; + } + produced++; + /* Reader is stalled most of the time; occasionally accepts a slice. */ + if (i % 17 == 0) { + drain(&q, &s, 64 + (i % 300)); + } + if (q.dropped_frames != drops_seen) { + drops_seen = q.dropped_frames; + } + /* The queue must never exceed its capacity. */ + if (ps_outbuf_pending(&q) > q.cap) { + FAILF("queue over capacity: %zu > %zu", ps_outbuf_pending(&q), q.cap); + break; + } + } + while (ps_outbuf_pending(&q) > 0) { + drain(&q, &s, 1 << 20); + } + + CHECK(produced == 5000); + CHECK(drops_seen > 0); /* the scenario must actually exercise dropping */ + + size_t frames = verify(&s, 0, &bad); + CHECK_EQ(bad, 0); + CHECK(frames > 0); + CHECK(frames + drops_seen <= produced); + /* Every delivered frame is whole, in order, and no byte is invented. */ + CHECK_EQ(s.len, s.len); + ps_outbuf_free(&q); +} + +static void test_drop_never_splits_a_sent_frame(void) { + struct ps_outbuf q; + uint8_t first[1024]; + uint8_t second[1024]; + size_t a, b; + + ps_outbuf_init(&q, 4096); + + a = make_frame(first, sizeof(first), 0, 900); + CHECK_EQ(ps_outbuf_push(&q, first, a), 0); + ps_outbuf_consume(&q, 10); /* first frame is now partly on the wire */ + + /* With only the in-flight frame queued there is nothing safe to drop. */ + CHECK_EQ(ps_outbuf_drop_front(&q), 0); + CHECK_EQ(ps_outbuf_pending(&q), a - 10); + + b = make_frame(second, sizeof(second), 1, 300); + CHECK_EQ(ps_outbuf_push(&q, second, b), 0); + CHECK_EQ(ps_outbuf_frames(&q), 2); + + /* Dropping now must remove the *second* frame, not the in-flight one. */ + CHECK_EQ(ps_outbuf_drop_front(&q), 1); + CHECK_EQ(ps_outbuf_frames(&q), 1); + CHECK_EQ(ps_outbuf_pending(&q), a - 10); + CHECK_MEM(ps_outbuf_head(&q), first + 10, a - 10); + + /* Once the first frame is fully sent, the queue is empty again. */ + ps_outbuf_consume(&q, a - 10); + CHECK_EQ(ps_outbuf_pending(&q), 0); + ps_outbuf_free(&q); +} + +static void test_push_after_full_drain(void) { + struct ps_outbuf q; + uint8_t frame[8192]; + size_t n; + size_t i; + + ps_outbuf_init(&q, 4096); + + /* Fill exactly to the cap, drain everything, then push again: this used to + * leave the queue wedged at "full". */ + for (i = 0; i < 4; i++) { + n = make_frame(frame, sizeof(frame), (uint32_t)i, 900); + CHECK_EQ(ps_outbuf_push(&q, frame, n), 0); + ps_outbuf_consume(&q, n); + } + CHECK_EQ(ps_outbuf_pending(&q), 0); + + /* Now overflow hard with no reader at all, then drain and retry. */ + for (i = 0; i < 200; i++) { + n = make_frame(frame, sizeof(frame), (uint32_t)i, 600); + CHECK_EQ(ps_outbuf_push(&q, frame, n), 0); + } + CHECK(q.dropped_frames > 0); + while (ps_outbuf_pending(&q) > 0) { + ps_outbuf_consume(&q, ps_outbuf_pending(&q)); + } + n = make_frame(frame, sizeof(frame), 999, 500); + CHECK_EQ(ps_outbuf_push(&q, frame, n), 0); + CHECK_EQ(ps_outbuf_pending(&q), n); + ps_outbuf_free(&q); +} + +int main(void) { + RUN(test_no_drops_clean_stream); + RUN(test_partial_writes_keep_frames_atomic); + RUN(test_drops_only_whole_frames); + RUN(test_drop_never_splits_a_sent_frame); + RUN(test_push_after_full_drain); + return test_report(); +} diff --git a/tests/test_proto.c b/tests/test_proto.c new file mode 100644 index 0000000..2dc23e0 --- /dev/null +++ b/tests/test_proto.c @@ -0,0 +1,143 @@ +/* test_proto.c - framing round-trips, byte-at-a-time feeding, error handling. */ +#include +#include + +#include "proto.h" +#include "stats.h" +#include "test.h" + +static void test_frame_roundtrip(void) { + uint8_t buf[128]; + uint8_t payload[] = {1, 2, 3, 4, 5}; + size_t n = ps_frame_write(buf, sizeof(buf), PS_FRAME_ERR, payload, sizeof(payload)); + + CHECK_EQ(n, PS_HEADER_LEN + sizeof(payload)); + CHECK_EQ(ps_be32(buf), PS_PROTO_MAGIC); + CHECK_EQ(ps_be16(buf + 4), PS_PROTO_VERSION); + CHECK_EQ(ps_be16(buf + 6), PS_FRAME_ERR); + CHECK_EQ(ps_be32(buf + 8), sizeof(payload)); + CHECK_MEM(buf + PS_HEADER_LEN, payload, sizeof(payload)); +} + +static void test_frame_needs_space(void) { + uint8_t buf[16]; + CHECK_EQ(ps_frame_write(buf, PS_HEADER_LEN, PS_FRAME_BYE, NULL, 0), PS_HEADER_LEN); + CHECK_EQ(ps_frame_write(buf, PS_HEADER_LEN, PS_FRAME_BYE, NULL, 1), 0); +} + +/* The whole point of the reader: one byte at a time must still yield frames. */ +static void test_reader_dribble(void) { + uint8_t wire[256]; + uint8_t payload[] = "hello world"; + size_t h1 = ps_frame_write(wire, sizeof(wire), PS_FRAME_ERR, payload, sizeof(payload)); + size_t h2 = ps_frame_write(wire + h1, sizeof(wire) - h1, PS_FRAME_BYE, NULL, 0); + size_t total = h1 + h2; + struct ps_reader r; + int frames = 0; + + CHECK_EQ(ps_reader_init(&r, 8), 0); + for (size_t i = 0; i < total; i++) { + struct ps_frame f; + CHECK_EQ(ps_reader_feed(&r, wire + i, 1), 0); + while (ps_reader_next(&r, &f) == 1) { + frames++; + if (f.type == PS_FRAME_ERR) { + CHECK_EQ(f.len, sizeof(payload)); + CHECK_MEM(f.data, payload, sizeof(payload)); + } else { + CHECK_EQ(f.type, PS_FRAME_BYE); + CHECK_EQ(f.len, 0); + } + } + } + CHECK_EQ(frames, 2); + ps_reader_free(&r); +} + +static void test_reader_rejects_garbage(void) { + struct ps_reader r; + struct ps_frame f; + uint8_t junk[PS_HEADER_LEN] = {0}; + + ps_reader_init(&r, 8); + CHECK_EQ(ps_reader_feed(&r, junk, sizeof(junk)), 0); + CHECK_EQ(ps_reader_next(&r, &f), -1); + CHECK_EQ(ps_reader_next(&r, &f), -1); /* sticky */ + ps_reader_free(&r); +} + +static void test_packet_codec(void) { + uint8_t data[] = {0xaa, 0xbb, 0xcc}; + uint8_t buf[64]; + struct ps_record in = {.ts_sec = 1000, .ts_usec = 999, .caplen = 3, .origlen = 60, .data = data}; + struct ps_record out; + + size_t n = ps_packet_encode(buf, sizeof(buf), &in); + CHECK_EQ(n, PS_PKT_HDR_LEN + 3); + CHECK_EQ(ps_packet_decode(buf, (uint32_t)n, &out), 0); + CHECK_EQ(out.ts_sec, 1000); + CHECK_EQ(out.ts_usec, 999); + CHECK_EQ(out.caplen, 3); + CHECK_EQ(out.origlen, 60); + CHECK_MEM(out.data, data, 3); + + /* Truncated payload must be rejected. */ + CHECK_EQ(ps_packet_decode(buf, (uint32_t)n - 1, &out), -1); +} + +static void test_hello_roundtrip(void) { + struct ps_hello in = {.linktype = 1, .snaplen = 4096}; + struct ps_hello out; + uint8_t buf[256]; + + strcpy(in.hostname, "box.example"); + strcpy(in.iface, "eth0"); + strcpy(in.filter, "tcp port 443"); + + size_t n = ps_hello_encode(&in, buf, sizeof(buf)); + CHECK(n > 0); + CHECK_EQ(ps_hello_decode(buf, (uint32_t)n, &out), 0); + CHECK_EQ(out.linktype, 1); + CHECK_EQ(out.snaplen, 4096); + CHECK_STR(out.hostname, "box.example"); + CHECK_STR(out.iface, "eth0"); + CHECK_STR(out.filter, "tcp port 443"); + + /* Unterminated strings must fail, not run off the end. */ + CHECK_EQ(ps_hello_decode(buf, (uint32_t)n - 1, &out), -1); +} + +static void test_counters_wire(void) { + struct ps_counters in; + struct ps_counters out; + uint8_t buf[PS_COUNTER_WIRE_SIZE]; + + ps_counters_clear(&in); + in.seen = 5000; + in.tcp = 42; + in.dns = 7; + in.dropped_client = 3; + in.dropped_kernel = 1; + + CHECK_EQ(ps_counters_encode(&in, buf, sizeof(buf)), PS_COUNTER_WIRE_SIZE); + CHECK_EQ(ps_counters_decode(buf, sizeof(buf), &out), 0); + CHECK_EQ(out.seen, 5000); + CHECK_EQ(out.tcp, 42); + CHECK_EQ(out.dns, 7); + CHECK_EQ(out.dropped_client, 3); + CHECK_EQ(out.dropped_kernel, 1); + CHECK_EQ(out.udp, 0); + + CHECK_EQ(ps_counters_decode(buf, PS_COUNTER_WIRE_SIZE - 1, &out), -1); +} + +int main(void) { + RUN(test_frame_roundtrip); + RUN(test_frame_needs_space); + RUN(test_reader_dribble); + RUN(test_reader_rejects_garbage); + RUN(test_packet_codec); + RUN(test_hello_roundtrip); + RUN(test_counters_wire); + return test_report(); +}