> This is part 1 of 2 of the full documentation (pages 1–100 of 146).
> The content is paginated: fetch every part to see all of it.
> Next part: https://docs.netcap.io/llms-full.txt/1
> Page index: https://docs.netcap.io/llms.txt

# Netcap

Network traffic analysis, structured evidence and reproducible investigations.

![Netcap — network traffic analysis](https://1185258105-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-La-SRWxzIGdy_3ynMZH-887967055%2Fuploads%2Fgit-blob-2ba78448cd5f33a5126103b6565062ae9af6595b%2Flogo.png?alt=media)

Netcap turns network packets into typed audit records, then connects protocol observations to hosts, services, files, detections and investigation evidence. Use the `net` executable to analyze PCAP/PCAPNG files, inspect a live interface, browse results locally or supply structured evidence to an AI agent.

These docs cover the **public Go implementation**, with executable examples targeting [v0.15.2](https://github.com/dreadl0ck/netcap/releases/tag/v0.15.2). GitBook's `master` variant follows the public repository; historical variants describe older interfaces. Server-side database publication may evolve without changing the signed client protocol.

## Start with a question

| Goal                                                | Guide                                                                                                                                |
| --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| Produce and inspect your first records              | [First capture](/start-here/quickstart)                                                                                              |
| Follow a complete DNS/HTTP/file/alert investigation | [Synthetic transfer lab](/start-here/investigation-walkthrough)                                                                      |
| Explore captures in a browser                       | [Web interface](/capture-and-inspect/web-interface)                                                                                  |
| Identify hosts and observed accounts                | [Hosts and identity](/investigate-evidence/host-identity)                                                                            |
| Explain an alert and recover its evidence           | [Related evidence](/investigate-evidence/evidence)                                                                                   |
| Find unusual connections or learn a baseline        | [Network detections](/investigate-evidence/network-detections), [behavioral monitoring](/investigate-evidence/behavioral-monitoring) |
| Automate analysis with an AI client                 | [MCP](/integrations-and-operations/mcp)                                                                                              |
| Integrate records into another tool                 | [CSV/JSON](/capture-and-inspect/filtering-and-export), [record format](/develop-and-extend/specification)                            |

## From packets to evidence

| Stage       | Result                                                                                                               |
| ----------- | -------------------------------------------------------------------------------------------------------------------- |
| Capture     | Packets from a file or visible interface; optional BPF selection                                                     |
| Decode      | Protocol-specific records and higher-level `Connection`, `Host`, `DeviceProfile`, `Software` and `File` observations |
| Enrich      | Local IANA, OUI, GeoIP, UA, HASSH and NVD data where enabled and available                                           |
| Investigate | Rules, network detections, approved behavioral baselines, identity bindings and related-record pivots                |
| Preserve    | Audit files, capture-health manifests and optional packet/stream evidence                                            |

Local capture normally writes one compressed protobuf file per emitted record type, such as `TCP.ncap.gz`. `dump` reads those files; `triage` reads host-identity reports; `investigate` queries and exports bounded evidence. [Commands](/start-here/commands) explains the division.

## Understand what was observed

A passive capture sees only traffic reaching its input. Packet loss, truncation, encryption and absent handshake data limit interpretation. Protocol recognition does not imply complete application decoding; a CVE match does not prove exploitation; a connection attempt does not establish authentication failure. Health and completeness fields make these limits inspectable.

Netcap's Go runtime and bounded parsers reduce some implementation risks, but native libpcap/DPI/YARA integrations are part of the build-dependent trust boundary. See [installation](/start-here/installation), [capture health](/investigate-evidence/evidence) and [service hosting](/capture-and-inspect/web-interface#hosting-boundary).

## Source and license

The public Go framework is [GPL-3.0-or-later](/reference/license). Dataset and native dependency licenses remain separate. The [public repository](https://github.com/dreadl0ck/netcap) contains source, tests, schemas and release build recipes. This documentation does not describe commercial desktop editions or promise parity with other implementations.


# Installation

These instructions target the public Go release [v0.15.2](https://github.com/dreadl0ck/netcap/releases/tag/v0.15.2). Start with an archive matching your operating system, architecture and native runtime; keep the archive's executable and libraries together.

## Binary Distributions

| Distribution | Runtime requirement                                                                        |
| ------------ | ------------------------------------------------------------------------------------------ |
| Linux libc   | Debian/Ubuntu-compatible runtime; retain `net`, `lib/net.bin` and bundled loader/libraries |
| Linux musl   | Alpine-compatible runtime; use the musl archive rather than the libc archive               |
| macOS DPI    | macOS 26+; retain adjacent `lib/` native libraries                                         |
| macOS nodpi  | macOS 15+; no native DPI classification                                                    |
| Windows      | Match architecture; install compatible Npcap for live capture and BPF-dependent workflows  |

Linux wrappers load their private runtime; they do not install libraries into system directories. macOS libraries use executable-relative install names. Full supplier sources/build recipes accompany the macOS runtime asset.

```sh
net --version
net capture -h
```

Check that `net --version` resolves the intended executable and reports the expected commit/DPI status. A previously installed `net` elsewhere in `PATH` can hide the new archive. Continue with the [synthetic first capture](/start-here/quickstart).

## Homebrew

```sh
brew tap dreadl0ck/formulas
brew install netcap
net --version
```

The formula installs its complete native runtime under `libexec`. The tap may advance beyond the release documented here; record the installed version when reproducing results.

## Go Get

`go get` manages dependencies; it does not install current Go executables. Clone the release and build its embedded browser assets before compiling Go.

## Manual Build

Install the Go version declared in `go.mod`, Node/pnpm for the UI, a C toolchain and libpcap headers. Native DPI and YARA require additional libraries; the following reduced build disables those two optional integrations:

```sh
git clone --branch v0.15.2 https://github.com/dreadl0ck/netcap.git
cd netcap/cmd/capture/webui/frontend
pnpm install --frozen-lockfile
pnpm build
cd ../../../..
GOWORK=off go build -tags nodpi,noyara -o net ./cmd/net
./net --version
```

This is a source build, not the packaged runtime distribution. `nodpi` does not remove libpcap requirements. Run it as `./net` so an older executable in `PATH` cannot be selected accidentally.

## Reproducible Builds via Go Modules

`go.mod`/`go.sum` pin module dependencies. Reproduction also requires a recorded source commit, Go/C toolchains, build tags, embedded UI and native libraries. Use `GOWORK=off` to avoid local workspace replacements. Dependency pinning alone does not prove bit-for-bit reproducibility.

## Development Build

Follow [macOS development](/develop-and-extend/macos-development-setup) for platform tooling and [testing](/develop-and-extend/tests) for scoped verification. Schema generation uses `protoc-gen-gogofaster`; it is unnecessary for an unchanged release checkout.

## Cross Compilation

CGO and native dependencies mean `GOOS`/`GOARCH` alone are insufficient. Use the platform build recipes in `zeus/scripts/` and supply the matching C compiler, headers and runtime. Verify the resulting archive on its target OS.

## Buildsystem

[Zeus](https://github.com/dreadl0ck/zeus) drives builds/releases through `zeus/commands.yml`; the root Makefile provides test entrypoints. Run `zeus` without arguments to inspect available commands.

## Optional enrichment

```sh
net util -download-dbs
net util -update-dbs
```

Signed clients verify publisher metadata. The default data directory is `~/.config/netcap/dbs`; `NC_CONFIG_ROOT` changes its parent. Follow [database updates](/enrichment/database-updates) for trust, source inventory and retired catalogues. Packet-only analysis can proceed without this optional enrichment.


# First capture

Analyze a small, synthetic capture and inspect its records.

This walkthrough uses Go Netcap v0.15.2 and Python 3. It creates two synthetic Ethernet/IPv4/UDP packets on documentation-only addresses: no traffic is sent. Install the appropriate [binary distribution](/start-here/installation) first.

## 1. Verify the executable

```sh
net --version
```

Check the printed version, commit and DPI status. Run commands from a writable working directory. Use a fresh output directory for each analysis.

## 2. Create a benign PCAP

```python
import socket
import struct
from pathlib import Path

def checksum(data):
    if len(data) % 2:
        data += b"\0"
    total = sum(struct.unpack("!%dH" % (len(data) // 2), data))
    while total >> 16:
        total = (total & 65535) + (total >> 16)
    return (~total) & 65535

frames = []
for index in range(2):
    payload = b"netcap documentation fixture"
    udp = struct.pack("!HHHH", 40000, 9999, 8 + len(payload), 0) + payload
    ip = struct.pack("!BBHHHBBH4s4s", 0x45, 0, 20 + len(udp), index,
                     0, 64, 17, 0, socket.inet_aton("192.0.2.10"),
                     socket.inet_aton("192.0.2.20"))
    ip = ip[:10] + struct.pack("!H", checksum(ip)) + ip[12:]
    ethernet = bytes.fromhex("0200000000200200000000100800")
    frames.append(ethernet + ip + udp)

with Path("example.pcap").open("xb") as output:
    output.write(struct.pack("<IHHIIII", 0xa1b2c3d4, 2, 4, 0, 0, 65535, 1))
    for index, frame in enumerate(frames):
        output.write(struct.pack("<IIII", 1700000000 + index, 0,
                                 len(frame), len(frame)))
        output.write(frame)
```

Save as `example.py` and run `python3 example.py`. Exclusive creation refuses to replace an existing `example.pcap`.

## 3. Analyze the file

```sh
net capture -read example.pcap -out example-audit -dpi=false -geoDB=false
```

The process exits after flushing records. `-dpi=false` makes this example usable with nodpi builds; `-geoDB=false` avoids a GeoIP prerequisite. Some other enrichment may report unavailable local data. [Database updates](/enrichment/database-updates) are optional for this packet-only exercise.

Expect `example-audit/UDP.ncap.gz` with two UDP records, along with other enabled record files and health artifacts. Empty protocol files are not proof of a problem: this fixture deliberately has no HTTP, TLS, DNS or credentials.

## 4. Inspect and export

```sh
net dump -read example-audit/UDP.ncap.gz -header
net dump -read example-audit/UDP.ncap.gz -fields
net dump -read example-audit/UDP.ncap.gz -json
net dump -read example-audit/UDP.ncap.gz -csv -sep ',' \
  -select Timestamp,SrcPort,DstPort > udp.csv
```

The header identifies `NC_UDP`. Field discovery prints one protobuf field name per line. JSON mode emits one object per record; the CSV header is `Timestamp,SrcPort,DstPort`. Port values are 40000 → 9999. Timestamp formatting depends on display options; raw record timestamps are Unix nanoseconds.

## 5. Open the local WebUI

Analyze again into another fresh directory:

```sh
net capture -read example.pcap -out example-browser -dpi=false -geoDB=false \
  -http 127.0.0.1:8080
```

Open `http://127.0.0.1:8080`. The explicit HTTP flag keeps the process running; stop it with Ctrl-C when finished. Do not publish this unauthenticated local API directly to the Internet. [Web interface](/capture-and-inspect/web-interface) explains modes and the hosting boundary.

## Next steps

| Question                            | Continue with                                        |
| ----------------------------------- | ---------------------------------------------------- |
| How do I capture an interface?      | [Live capture](/capture-and-inspect/live-collection) |
| How do I select packets or records? | [Filtering](/capture-and-inspect/filtering)          |
| What happened on a connection?      | [Evidence linking](/investigate-evidence/evidence)   |
| Which data enriches an observation? | [Resolvers](/enrichment/resolvers)                   |


# Investigate a synthetic transfer

This lab follows DNS → HTTP → extracted file → rule alert → packet export. Python 3 writes PCAP bytes locally; no packets are transmitted. Use the current repository checkout for `scripts/docs-fixtures.py` and `docs/examples/`, plus the released Go v0.15.2 `net` executable. Run all commands from that checkout's root. The fixture script refuses an existing destination directory.

## Create the evidence

```sh
python3 scripts/docs-fixtures.py
```

| Input                                                          | Expected evidence                                                                                                        |
| -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| `doc-fixtures/investigation.pcap`                              | One DNS A answer for `docs.example.test`, then one HTTP/1 transfer on TCP/8080                                           |
| `doc-fixtures/benign.pcap`                                     | The same benign DNS exchange, with no HTTP transfer                                                                      |
| `doc-fixtures/baseline.pcap`, `unchanged.pcap`, `changed.pcap` | Synthetic ARP observations for the [baseline lab](/investigate-evidence/behavioral-monitoring#reproducible-baseline-lab) |
| `doc-fixtures/client.bin`, `other-client.bin`                  | Seven-byte offline [protocol hypotheses](/investigate-evidence/protocol-experiments#offline-hypotheses-first)            |

The domain is under `.test`; addresses are `192.0.2.10` and `192.0.2.20`. The generated `sensor.key` is public deterministic lab material, never a real sensor credential. Inspect the fixture generator before reusing any bytes.

## Capture and inspect

```sh
net capture -read doc-fixtures/investigation.pcap -out doc-fixtures/audit \
  -rules docs/examples/http-observation.yml -conns -dpi=false -geoDB=false
net dump -read doc-fixtures/audit/DNS.ncap.gz -json > doc-fixtures/dns.ndjson
net dump -read doc-fixtures/audit/HTTP.ncap.gz -json > doc-fixtures/http.ndjson
net dump -read doc-fixtures/audit/File.ncap.gz -json > doc-fixtures/files.ndjson
net dump -read doc-fixtures/audit/Alert.ncap.gz -json > doc-fixtures/alerts.ndjson
```

Expect two DNS messages, one HTTP record with `/fixture.txt`, a `File` record whose stored body is `Netcap synthetic evidence.` followed by a newline, and a `Documentation HTTP Transfer` rule alert. The rule in [`docs/examples/http-observation.yml`](https://github.com/dreadl0ck/netcap/tree/master/docs/examples/http-observation.yml) marks a known fixture; it does not classify the transfer as malicious.

Inspect `IsComplete`, `CompletenessReason` and `Hashes.SHA256` on the file. Its legacy `Hash` field is MD5. Preserve both the source capture and the actual stored bytes; a MIME label or filename is not a content-integrity check.

## Follow the relationship

```sh
net investigate related -read doc-fixtures/audit -type HTTP -ordinal 0 \
  > doc-fixtures/related.json
```

Read relationship labels, scope and limitations in `related.json`. Compare the HTTP record's Community ID with its Connection and DNS evidence. A temporally related DNS answer is a candidate explanation, not causal proof. A returned record ID binds file content; do not reuse it after replacing output.

## Verify a benign control

```sh
net capture -read doc-fixtures/benign.pcap -out doc-fixtures/control \
  -rules docs/examples/http-observation.yml -dpi=false -geoDB=false
```

The control must produce no `Documentation HTTP Transfer` alert. Depending on empty-writer cleanup, `Alert.ncap.gz` can be absent or contain no matching rows. A successful compile alone does not establish that a rule matches the intended traffic or avoids benign input.

## Preserve selected packets

```sh
net investigate packet-evidence -read doc-fixtures/investigation.pcap \
  -bpf 'host 192.0.2.10 and tcp port 8080' -out doc-fixtures/http-evidence.zip
```

The ZIP contains `packets.pcapng` and `manifest.json`. Its selection contains the eight TCP packets, not the two DNS packets. The manifest binds source and output hashes; preserve the original ten-packet capture for the DNS context. Existing ZIP destinations are refused.

## Repeatable checks

`make docs-check NETCAP_BIN=/absolute/path/to/net` runs the marked commands in a temporary workspace and asserts records, file bytes, the positive/benign rule cases and the selected packet count. It also checks links, shell syntax, configuration examples and the baseline lifecycle. It never probes an external target. Source-only features are labeled separately from v0.15.2 examples.

`make docs-source-check` separately checks protobuf excerpts and concrete rule expressions against the checkout's schema/engine.


# Commands

Choose the public Go command for the job.

Go v0.15.2 registers the commands below in `cmd/net/main.go`. Run `net -h` and `net COMMAND -h` for their installed options. The executable is `net`; version inspection is `net --version`, not a `version` subcommand.

| Command       | Job                                                                     | Guide                                                                                            |
| ------------- | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ |
| `capture`     | PCAP/PCAPNG, live packets and local/upload WebUI                        | [Packet collection](/capture-and-inspect/packet-collection)                                      |
| `dump`        | Read audit files, discover fields, filter and emit CSV/JSON             | [Record inspection](/capture-and-inspect/filtering-and-export)                                   |
| `triage`      | Inspect capture-derived `Hosts.json` identities                         | [Hosts and identity](/investigate-evidence/host-identity)                                        |
| `investigate` | Flow queries, related records, evidence exports and bounded experiments | [Evidence](/investigate-evidence/evidence), [flow analysis](/investigate-evidence/flow-analysis) |
| `util`        | Interfaces, schemas, timestamps and database operations                 | [Database updates](/enrichment/database-updates)                                                 |
| `mcp`         | Stdio Model Context Protocol server                                     | [AI agents](/integrations-and-operations/mcp)                                                    |
| `licenses`    | Distribution license/notice information                                 | [License](/reference/license)                                                                    |
| `agent`       | TLS-authenticated remote sensor                                         | [Distributed collection](/integrations-and-operations/distributed-collection)                    |
| `collect`     | Receive agent batches                                                   | [Distributed collection](/integrations-and-operations/distributed-collection)                    |
| `export`      | Prometheus-oriented audit metrics exporter                              | [Metrics](/integrations-and-operations/metrics)                                                  |
| `proxy`       | HTTP/HTTPS reverse proxy records                                        | [HTTP proxy](/integrations-and-operations/http-proxy)                                            |
| `label`       | Suricata/custom mappings for dataset labels                             | [Labeling](/integrations-and-operations/audit-record-labeling)                                   |
| `transform`   | Maltego transform integration                                           | [Maltego](/integrations-and-operations/maltego-integration)                                      |
| `inject`      | Linux NFQueue inline manipulation                                       | [Response actions](/integrations-and-operations/firewall_response_actions)                       |

`split` and `analyze` are not registered v0.15.2 commands. A source directory, legacy completion result or historical README row is not an executable interface.

## Common operations

The [offline grouped rule evaluator](/investigate-evidence/rules_engine#offline-grouped-thresholds) (`investigate rules`) is available in current source after v0.15.2. It is not present in the v0.15.2 release binary. The [sensor bundle commands](/integrations-and-operations/sensor-bundles) are a separate completed-output workflow from live agent transport.

```sh
net util -interfaces
net capture -overview
net capture -read example.pcap -out analysis -dpi=false -geoDB=false
net dump -read analysis/UDP.ncap.gz -fields
net dump -read analysis/UDP.ncap.gz -json
net triage -read analysis -json
net investigate related -read analysis -type Connection -ordinal 0
```

Only query a type/ordinal that exists in your capture. For advanced commands, the [generated MCP catalogue](/integrations-and-operations/tools) is a different interface, not a CLI alias list. The source command/flag registrations are the reference for scripting.


# Configuration

Flags, explicit environment overrides and feature-specific files.

## Command-line options

Each subcommand owns its options. Inspect the installed executable, rather than copying a help listing from a different release:

```sh
net capture -h
net dump -h
net investigate -h
net util -h
```

Use `-flag=false` for Boolean false values. A space-separated `false` can become a positional argument instead of disabling the option.

## Environment overrides

Use the environment variable declared by the flag. Names are not uniformly derived from spelling: `NC_READ` selects capture input, whereas `NETCAP_DBS_URL` selects a database publisher.

```sh
NC_READ=example.pcap net capture -out environment-audit
NC_CONFIG_ROOT=/srv/netcap-config net util -download-dbs
```

Use the same root when capturing. The second command installs into `/srv/netcap-config/dbs`, not directly into `/srv/netcap-config`.

| Setting                                        | Meaning                                                        |
| ---------------------------------------------- | -------------------------------------------------------------- |
| `NC_CONFIG_ROOT`                               | Configuration parent; community data lives in its `dbs/` child |
| `NETCAP_DBS_URL`                               | Optional database publisher URL                                |
| `NC_DBS_APPROVALS` + `NC_DBS_APPROVALS_SHA256` | Paired independent registry override for private publishers    |
| `NC_GEO_PROVIDERS`                             | DB-IP/optional GeoLite2 provider order                         |
| `NETCAP_MCP_ADMIN_TOKEN`                       | HTTP MCP authorization; does not protect general WebUI routes  |

## Feature-specific configuration

| Feature              | File and entry point                                                                 |
| -------------------- | ------------------------------------------------------------------------------------ |
| Detection rules      | YAML supplied with `capture -rules`                                                  |
| Network detections   | JSON supplied with `-network-detection-config`                                       |
| Behavior             | Baseline selected with `-behavior-baseline`; policy selected with `-behavior-policy` |
| Reverse proxy        | YAML supplied with `proxy -proxy-config`                                             |
| Protocol experiments | Versioned JSON passed to the relevant `investigate` command's `-spec`                |

These are separate parsers with separate schemas. Read the corresponding guide before composing a file. A malformed feature file should not be replaced with a generic configuration guessed from another subcommand.

## Generic config compatibility flags

Go v0.15.2 still exposes legacy `-config`/`-gen-config` flags in some help output, but generic generation is unimplemented and a general config-file workflow is not supported by these docs. Earlier instructions recommending `net capture -gen-config > capture.conf` were incorrect. Use verified flags, environment overrides and the feature-specific files above.

## Entry-point behavior

| Invocation                                     | HTTP lifecycle                            |
| ---------------------------------------------- | ----------------------------------------- |
| `capture -read file.pcap`                      | Finishes and exits after analysis         |
| `capture -read file.pcap -http 127.0.0.1:8080` | Keeps the local UI running                |
| `capture -service -http 127.0.0.1:7070`        | Upload/session service                    |
| `mcp`                                          | Stdio MCP plus an internal loopback WebUI |

See [resource budgets](/develop-and-extend/workers) before interpreting per-stream or per-decoder limits as a process-wide memory or disk guarantee.


# Troubleshooting

Start with `net --version`, the exact command, its exit status and the output directory. Preserve the source capture and health artifacts before rerunning into a fresh directory.

## First Aid

| Symptom                    | Check                                                                        |
| -------------------------- | ---------------------------------------------------------------------------- |
| Flag/command missing       | Installed version and `net COMMAND -h`; old `net` earlier in `PATH`          |
| Native library cannot load | Complete matching release archive, including `lib/`; OS/runtime/architecture |
| No interface traffic       | Driver, permissions, interface/network namespace, BPF and observation point  |
| Offline process exits      | Normal without explicit `-http`; records flush before exit                   |
| Local WebUI inaccessible   | Bind address/port, startup errors and process lifetime                       |
| No HTTP/TLS records        | Actual input, encryption, decoder selection and reassembly health            |
| No enrichment              | Database path, signed-source status and data availability                    |
| Few contacts/records       | Sampling/truncation flags, capture drops, parser scope and finalization      |
| Rules return no alerts     | Rule enabled state, record type, expression errors and actual field values   |
| CSV columns unexpected     | `-csv`, separator and field names from `dump -fields`                        |

## Pitfalls

Use explicit boolean values such as `-dpi=false`. Generic `-gen-config` is unimplemented despite appearing in help. `net export` starts a metrics exporter; CSV/JSON conversion uses `net dump`.

## Debug Mode

Use the relevant command's `-debug` option and inspect its actual log paths. Capture outputs can include `errors.log`, debug logs and health sidecars. Avoid posting payloads, credentials or an entire private capture in a public issue. Report version/build tags, input hash, exact error and a minimal reproducer.

## Advanced Debugging

`capture-manifest.json`, `TCPReassemblyHealth.json` and subsystem health files qualify different boundaries. Missing/null counters are unavailable, not zero. Compare a known small synthetic capture before diagnosing a larger corpus. The [evidence guide](/investigate-evidence/evidence) explains completeness witnesses.

## Race Detection Builds

For source-level concurrency bugs, run a scoped `go test -race` with the matching build tags; [testing](/develop-and-extend/tests) lists entrypoints. A goroutine timeout wrapper does not cancel blocked native code, so do not substitute historical timeout helpers as a production fix for a native hang.


# Packet collection

Use a fresh output directory and keep the original capture. Netcap decodes bytes present at its input; it cannot reconstruct packets never captured upstream.

## Offline input

```sh
net capture -read traffic.pcap -out analysis -dpi=false -geoDB=false
net capture -read traffic.pcapng -out analysis-ng -http 127.0.0.1:8080
```

The first command exits after flushing. The second explicitly keeps the browser interface running. `-read` supports the input selection described by its help; quote shell globs when the application, rather than the shell, should expand them.

## Select the observation boundary

| Control                 | Stage                             | Consequence                                                                                            |
| ----------------------- | --------------------------------- | ------------------------------------------------------------------------------------------------------ |
| `-bpf 'udp port 53'`    | Packet selection                  | Nonselected packets never reach decoding; may break stream/handshake context                           |
| `-include` / `-exclude` | Decoder selection                 | Controls emitted record types and downstream inputs                                                    |
| `dump -filter`          | Post-capture record selection     | Preserves source audit files and filters one known type                                                |
| `capture -filter`       | Legacy capture-time record filter | TCP-only compilation and fail-open error behavior in v0.15.2; not a general filtering/privacy boundary |

[Filtering](/capture-and-inspect/filtering) provides examples. Reducing visible traffic changes detector coverage, connection attribution and evidence completeness.

## Output and shutdown

Local protobuf output normally produces `TYPE.ncap.gz`, with a header and framed records. `-json` or `-csv` selects another writer; flags do not imply all formats are emitted simultaneously. Higher-level records may be written only during flush/finalization. Let Ctrl-C complete graceful cleanup before copying output.

| Artifact                   | Purpose                                                                          |
| -------------------------- | -------------------------------------------------------------------------------- |
| `*.ncap.gz`                | Audit records by type                                                            |
| `capture-manifest.json`    | Input/configuration identity, scope and admission/drop observations when enabled |
| `Hosts.json`               | Capture-derived identities for `net triage`                                      |
| `TCPReassemblyHealth.json` | Reassembly policy/rejection evidence where produced                              |
| `stream-evidence/`         | Directional bytes/manifests when connection evidence is enabled                  |

Review actual artifacts before scripting their existence; enabled decoders, traffic and options determine output. [Evidence](/investigate-evidence/evidence) explains scope and health. [Live capture](/capture-and-inspect/live-collection) covers privileges and interfaces.


# Live capture

List visible interfaces before selecting one:

```sh
net util -interfaces
net capture -iface en0 -out live-audit -dpi=false -http 127.0.0.1:8080
```

`en0` is an example, not a portable interface name. Live capture needs the platform driver and sufficient permissions. Unfiltered offline analysis does not require those same live-capture privileges.

| Platform | Capture boundary                                                                             |
| -------- | -------------------------------------------------------------------------------------------- |
| Linux    | libpcap or supported packet-socket path; interface/network namespace and capabilities matter |
| macOS    | BPF device permissions; seeing a local interface does not imply switch-wide visibility       |
| Windows  | Compatible Npcap for live capture/enumeration and BPF-dependent workflows                    |

Promiscuous mode cannot create SPAN/TAP traffic that never reaches the interface. Choose the observation point with network owners; record interface/VLAN, clock, snaplen, BPF and expected traffic before interpreting absence.

## Run and stop

Use a new output directory, monitor health and stop with Ctrl-C so finalization can flush streams and aggregates. Killing the process can leave partial files and unfinalized scope. `-http` explicitly keeps the UI available; bind it to loopback under the [local hosting model](/capture-and-inspect/web-interface#hosting-boundary).

The default live snaplen is 1,514 bytes in this release; larger frames can be truncated unless configured appropriately. Watch application admission/drop counters separately from kernel statistics. Unavailable kernel measurements are not zero drops. Test live loss separately from offline replay throughput.

For remote sensors, use [distributed collection](/integrations-and-operations/distributed-collection). For packet-preserving subsets, use [evidence export](/investigate-evidence/evidence).


# Web interface

The public Go binary embeds a React/Vite interface and HTTP API. It runs locally without a separate Node server. Node/pnpm are needed when rebuilding its assets from source, not to open a released binary's UI.

## Choose a mode

| Mode                   | Command                                                                  | Lifecycle                                          |
| ---------------------- | ------------------------------------------------------------------------ | -------------------------------------------------- |
| One input with browser | `net capture -read traffic.pcap -out browser-audit -http 127.0.0.1:8080` | Analyze then keep serving                          |
| Live interface         | `net capture -iface en0 -out live-audit -http 127.0.0.1:8080`            | Capture until stopped; requires capture privileges |
| Upload workspace       | `net capture -service -http 127.0.0.1:7070`                              | Accept and queue uploaded analyses                 |

Replace interface names using `net util -interfaces`. Service storage, expiry, preloads and helper/embedded processing have their own flags under `capture -h`. Service analyses are queued and processed one at a time; upload acceptance is not analysis completion.

## Explore an analysis

| View                              | Question                                                                  |
| --------------------------------- | ------------------------------------------------------------------------- |
| Hosts / devices                   | Which addresses, bindings and peers were observed?                        |
| Connections / conversations       | Who communicated, which way, and with what visible bytes?                 |
| Protocol records                  | What fields/messages were decoded?                                        |
| Files / authentication / software | Which artifacts and claims have supporting records?                       |
| Alerts / behavior                 | Which detector or approved baseline produced a finding?                   |
| Investigation evidence            | Was capture complete enough, and which records/packets support the claim? |

Select the intended analysis/session before querying. Data loaded in one session is not a global search across every directory on the host. Late aggregate output and postprocessing can change views while analysis is active.

## Hosting boundary

The general public Go WebUI/API is a local-trust interface. Same-origin CORS is not authentication; `NETCAP_MCP_ADMIN_TOKEN` protects HTTP MCP, not every `/api` route. Do not bind to an untrusted network and assume account/tenant isolation. For shared access, provide external authentication, authorization and network isolation appropriate to the actual API before exposing it.

Uploads can contain credentials, personal data, payloads and executables. Review output/retention paths and avoid real captures in public screenshots. Advertised storage quotas are not a guarantee of a hard global disk ceiling; monitor the filesystem and enforce resource boundaries outside the application where needed.

## HTTP API discovery

`cmd/capture/webui/server.go` and `routes_direct.go` define the released routes. Use browser network requests and version-pinned source to establish parameters and response contracts; there is no blanket OpenAPI parity promise.

| Route                                   | Purpose                                                                |
| --------------------------------------- | ---------------------------------------------------------------------- |
| `/api/features`                         | Current feature flags; capture-time changes affect subsequent analyses |
| `/api/evidence/related`                 | Content-bound related-record pivots                                    |
| `/api/flows/query`                      | Bounded Connection rankings                                            |
| `/api/behavior`, `/api/behavior/health` | Baseline state and coverage                                            |
| `/api/alerts/stream`                    | Bounded live alert feed with reconnect/gap semantics                   |

Start integrations with [MCP](/integrations-and-operations/mcp) when its narrower tool contracts cover the task. Query features and capture features have different lifetimes; changing settings does not rewrite historical output.


# Filtering

Choose a filter stage deliberately. BPF selects packets; decoder options select producers; typed expressions select records. These controls are not equivalent.

## Packet filters

```sh
net capture -read traffic.pcap -out dns-audit -bpf 'udp port 53' -dpi=false
```

BPF requires a working platform libpcap/Npcap path. It can remove the SYN, response or handshake a decoder needs. Filtered offline input does not promise the same PCAPNG interface metadata as unfiltered input; inspect scope health.

## Post-capture expressions

Start by discovering fields:

```sh
net dump -read analysis/UDP.ncap.gz -fields
net dump -read analysis/UDP.ncap.gz -filter 'DstPort == 9999' -json
net dump -read analysis/Connection.ncap.gz \
  -filter 'DstPort == "443"' -json
```

`dump` compiles the expression for the file's type. Connection and TCP/UDP ports have different types. Parenthesize combined conditions and quote the whole expression for the shell. Match semantics come from the installed expr-language environment and helpers, not SQL or BPF syntax.

| Expression shape                  | Meaning                                                |
| --------------------------------- | ------------------------------------------------------ |
| `DstPort == 443 && SYN && !ACK`   | TCP packet condition; not proof of a completed session |
| `DstPort == "443"`                | Connection record port equality                        |
| `InSubnet(SrcIP, "192.0.2.0/24")` | Network helper on a record exposing string `SrcIP`     |

Do not reuse fields across record types without checking `dump -fields`. [Rules](/investigate-evidence/rules_engine) use typed record expressions too, but have additional threshold/sequence/action behavior.

## Helper reference

These signatures describe capture-time rules and `dump`'s expr environment, not the separate source-only offline-pack expression subset.

| Helper                                         | Input/result                                  | Example/limit                                                                                         |
| ---------------------------------------------- | --------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
| `InSubnet(ip, cidr)`                           | Strings → bool                                | `InSubnet(SrcIP, "192.0.2.0/24")`                                                                     |
| `IsPrivateIP(ip)`, `IsPublicIP(ip)`            | String → bool                                 | Private includes special-use/documentation ranges, not just RFC1918; it is not a trust decision       |
| `IsApprovedWorkstation(ip)`, `InAllowlist(ip)` | String → bool                                 | Exact loaded IP membership; empty allowlist returns false                                             |
| `ParsePort(port)`                              | String → integer                              | For Connection string ports; validate unexpected input separately                                     |
| `PortInRange(port, start, end)`                | Integers → bool                               | Inclusive bounds; use `ParsePort` on string ports                                                     |
| `TimeInRange(ts, start, end)`                  | Unix-nanosecond integers → bool               | Inclusive bounds; units must match                                                                    |
| `DurationSince(ts)`                            | Unix-nanosecond integer → elapsed nanoseconds | Uses current wall clock; unsuitable for capture-relative replay windows                               |
| `FormatTime(ts, layout)`                       | Timestamp and Go layout → string              | Layout `2006-01-02` is Go syntax, not strftime                                                        |
| `HourOfDay(ts)`, `Weekday(ts)`                 | Timestamp → local hour / weekday              | Process local timezone; weekday 0 is Sunday                                                           |
| `IsBusinessHours(ts, start, end)`              | Timestamp/hour integers → bool                | Mon–Fri, `[start,end)`, process local timezone; set `TZ=UTC` for reproducible UTC policy              |
| `ContainsAny(text, parts...)`                  | String and string arguments → bool            | Literal substring checks                                                                              |
| `MatchesPattern(text, pattern)`                | Strings → bool                                | Regex matching; use `(?i)` for case-insensitivity                                                     |
| `DNSResolutionMatches(...)`                    | Six typed arguments → bool                    | Advanced capture-time DNS context helper; see the signature in `internal/filter/filter.go` before use |

Nested list predicates use expr syntax, for example `len(Questions) > 0 && any(Questions, {.Name == "docs.example.test"})` on DNS. Guard missing nested data. CSV flattening does not make every flattened column a top-level field in every expression environment; inspect the actual schema.

## Capture-time compatibility filter

In Go v0.15.2, `capture -filter` is compiled against TCP. Compilation warns rather than failing the capture, and evaluation errors can pass records through; other record types are not generally filtered. It is **not** an all-record filter or a data-minimization boundary. For a predictable analysis workflow, retain the capture and apply `dump -filter` to an explicit audit type.

## Preserve provenance

Record the input hash, command, expression, version and output hash when sharing an export. A selected record set is not a selected packet capture. Use [packet evidence](/investigate-evidence/evidence) when the recipient needs original packet bytes and a selection manifest.


# CSV, JSON and record inspection

`net dump` reads audit files. It is the command for record inspection and file-format conversion; `net export` is a Prometheus-oriented exporter.

## Inspect before selecting

```sh
net dump -read analysis/UDP.ncap.gz -header
net dump -read analysis/UDP.ncap.gz -fields
net dump -read analysis/UDP.ncap.gz -json
```

`-fields` lists protobuf names one per line. JSON mode emits newline-delimited objects, not one enclosing array. Use the record schema for types and meanings. The structured terminal display is the default; explicitly request CSV or JSON for machine-readable output.

## Export selected columns

```sh
net dump -read analysis/UDP.ncap.gz -csv -sep ',' \
  -select Timestamp,SrcPort,DstPort > udp.csv
```

CSV's default separator is `;`, so pass `-sep ','` when consumers expect commas. `-select` orders/selects fields but does not itself request CSV. Nested records, maps and repeated values require inspection before mapping to a flat table. Treat CSV output as data; spreadsheet tools may interpret cells as formulas.

## Filter records

```sh
net dump -read analysis/UDP.ncap.gz -filter 'DstPort == 9999' -json
```

Expressions are typed against this file's record type. Keep shell quoting around the expression, and check errors rather than treating failure as zero matches. For TCP/UDP numeric ports compare integers; for Connection strings compare quoted strings. See [Filtering](/capture-and-inspect/filtering).

## Time order

Go v0.15.2 enables timestamp ordering for `dump` through `-sort-time`; inspect `dump -h` for overrides. Sorting uses bounded-memory temporary files. Stream completion and concurrent writers mean original file order can differ from capture time. Sorting changes presentation, not the source evidence or packet ordering. UTC/string display is separate from raw nanosecond timestamps.

Use a new destination when preserving a prior export: shell `>` truncates an existing file. This differs from evidence commands that explicitly refuse replacement. For packet-preserving selection and provenance, use [`investigate packet-evidence`](/investigate-evidence/evidence#export-packet-evidence).


# Audit records

Discover record types and distinguish parsing, classification and evidence.

Discover the installed decoder inventory and a file's actual fields:

```sh
net capture -overview
net util -decoders
net dump -read analysis/HTTP.ncap.gz -header
net dump -read analysis/HTTP.ncap.gz -fields
```

The authoritative definitions are the release's [`types/netcap.proto`](https://github.com/dreadl0ck/netcap/blob/v0.15.2/types/netcap.proto). This avoids hand-maintained counts that confuse record types, nested protobuf messages, packet decoders and port registrations.

## Correlation and security outcomes

| Contract                      | Current behavior                                                                                                                                                                                                                           |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| CommunityID                   | Community ID v1, seed 0; TCP/UDP/SCTP use the observed effective transport after IPv6 extensions. Missing transport ports do not become a zero-port TCP tuple. ICMP keeps its specified paired-message mapping.                            |
| Stream records                | Kerberos, TACACS, IPP, Zabbix, Protobuf, OPCUA, S7Comm and PROFINET copy the conversation ID. Their CSV exports, plus HTTP/DNS, append `CommunityID`; existing columns keep their position.                                                |
| Observation scope             | A tuple hash is not a unique session ID. Retain capture RunID, scope/record witnesses and observation boundaries for tuple reuse, VLAN/interface collisions and NAT.                                                                       |
| Protobuf direction            | Response records name the server as sender, with server-side capture time; the generic decoder does not implement HTTP/2 gRPC framing.                                                                                                     |
| RDP requested versus selected | `RequestedProtocolsFlags/Names` describe the offer. `UsesTLS/NLA/CredSSP` describe only an observed server-selected protocol when `NegotiatedSecurityKnown` is true.                                                                       |
| RDP outcomes                  | `NegotiationOutcome` distinguishes accepted, rejected, not-observed, malformed and unavailable-after-capture-loss. `AuthenticationOutcome` remains unknown: this negotiation decoder has no login-result evidence.                         |
| Legacy RDP boolean            | `ConnectionSuccessful` retains its historical negotiation-acceptance meaning for compatibility. It is not proof of a login; new rules/UI should use the explicit outcome fields. Missing new fields on retained output are legacy/unknown. |
| Certificates                  | Capture-time validity, cryptographic self-signature state and actual sender are qualified explicitly; see [certificate assessments](/enrichment/tls-fingerprinting#certificate-observation-and-assessment).                                |

The additive protobuf fields remain readable alongside old records. Append-only CSV evolution still requires position-based consumers and feature matrices to check their exact header/schema before ingestion (`types/netcap.proto`).

## Record families

| Family                | Examples                                                          | Interpretation                                                                 |
| --------------------- | ----------------------------------------------------------------- | ------------------------------------------------------------------------------ |
| Packet layers         | Ethernet, ARP, IPv4/IPv6, TCP, UDP, ICMP, DNS                     | Decoded packet fields; visibility depends on link type and captured bytes      |
| Reassembled protocols | HTTP, TLS, SSH, SMTP/IMAP/POP3, SMB, LDAP, Kerberos, DCE/RPC, FTP | Messages/transactions from streams, with protocol-specific limits              |
| OT and routing        | Modbus, DNP3, S7Comm, CIP/ENIP, OPCUA, PROFINET, BACnet, BGP      | Typed observations, not universal device/model support                         |
| Network summaries     | Connection, Host, DeviceProfile, Service, Software                | Aggregates and derived claims; review scope, timing and provenance             |
| Detection/evidence    | Alert, Vulnerability, Exploit, File, Secret                       | Match or extracted evidence; presence is not an exploitation/execution verdict |

## Important boundaries

| Feature          | What is supported                                                                                                              |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| HTTP             | HTTP/1.0/1.1 message/transaction parsing; do not infer HTTP/2/3 decoding from a port or DPI label                              |
| QUIC             | Recognized Initial packet processing and ClientHello extraction; not arbitrary HTTP/3 plaintext                                |
| TLS              | Handshake/certificate/fingerprint metadata without decryption; supplied secrets plus external `tshark` are a separate workflow |
| Service identity | Bounded SSH/HTTP/SMTP/FTP greeting parsers; IANA port names are a separate lookup                                              |
| Vulnerabilities  | Structured CPE applicability from schema-2 NVD data; unknown prerequisites remain unknown                                      |
| Identity         | Observed host/account facts and conflicts; directory traffic does not automatically identify the server as the subject         |

Packet decoders can be selected with `-include`/`-exclude`; names come from `capture -overview`. Disabling a producer can remove the records downstream enrichment or detection needs. A missing file or empty output does not certify absence of the protocol in truncated, encrypted or unrecognized traffic.

## Fields and timing

Use exact case-sensitive protobuf names from `dump -fields`; do not transpose a TCP field into a Connection rule. For example, TCP ports are numeric while Connection port fields are strings. Raw capture timestamps use Unix nanoseconds; display formatting is separate. Stream records may appear on completion and out of capture-time order. [Dump ordering](/capture-and-inspect/filtering-and-export) and [reassembly](/capture-and-inspect/reassembly) explain the implications.


# TCP reassembly

Application messages can span TCP segments, share one segment or arrive with retransmissions/out-of-order delivery. Netcap assembles directional streams before protocol-specific parsing; a packet boundary is not an HTTP/DNP3/Modbus message boundary.

```sh
net capture -read traffic.pcap -out streams -reassemble-connections=true \
  -conns -dpi=false
```

## Boundaries and missing bytes

| Condition                        | Consequence                                                                                  |
| -------------------------------- | -------------------------------------------------------------------------------------------- |
| Missing SYN/initial payload      | Direction/boundary can be uncertain; inspect parser-specific states                          |
| Known-size gap                   | A parser may have a restricted resynchronization rule                                        |
| Unknown-size gap                 | Parsing may stop rather than guess framing                                                   |
| Retransmission                   | Reassembly suppresses/reconciles bytes according to its policy                               |
| Per-direction buffer limit       | Evidence can be incomplete when bounds are reached                                           |
| Connection finalization          | Stream records and alerts may only become visible on completion/flush                        |
| Reader payload-budget exhaustion | Capture aborts; stream evidence labels local discards separately from network sequence gaps. |

Fallback decoder probing uses `DataFragments.ContiguousBytes()`: deliveries can complete a header only within one observed byte run. Known and unknown gaps cannot join partial signatures into a protocol match. A leading midstream marker still permits probing the first observed run; it does not establish completeness.

Go v0.15.2's default maximum buffered size is 10 MiB per direction. Zero-valued page limits can mean unlimited; [resource budgets](/develop-and-extend/workers) are not a global memory guarantee. Use the installed help and health sidecars for actual policy.

Live collection sends ordered maintenance to every worker once per second, including when no new packets arrive (`internal/collector/live_maintenance.go`). `-live-maintenance-interval` (`NC_LIVE_MAINTENANCE_INTERVAL`) overrides that interval; a negative value disables it. Both directions must be older than `CloseInactiveTimeOut` before an open stream expires. Pending bytes are delivered with gap evidence, and timeout closure is labeled `idle-expired`.

| Maintenance            | Time basis / effect                                                                                                                      |
| ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| Pending-byte deadline  | `FlushOptions.T` releases old sequence heads with gap evidence.                                                                          |
| Closed-state retention | `FlushOptions.TC` removes retained closed connections.                                                                                   |
| Live idle expiry       | Explicit `FlushOptions.TI` closes idle open connections; zero disables it. An opt-in deadline index avoids scanning every active stream. |
| Output snapshots       | `-live-flush-interval` (`NC_LIVE_FLUSH_INTERVAL`) flushes writers/current records; zero disables snapshots. It does not expire streams.  |

Offline collection does not start a wall-clock maintenance timer or enable idle expiry; its existing packet-driven capture-time policy is preserved.

Completed TCP connections finish decoding, conversation persistence and banner extraction before closing/joining both reader tasks. Raw fragment/decoder references are released and reader-registry slots reused (`tcp/tcp_resources.go`); lifetime byte counters and any retained closed-connection FSM metadata remain available. This releases completed-stream state during capture, without claiming a global bound on still-open streams or decoder-owned caches.

## Inspect the evidence

With `-conns`, `stream-evidence/stream-*/` contains `client.bin`, `server.bin` and a manifest recording direction, offsets, times, gaps and UDP boundaries where applicable. The display transcript is separate. Never remove gap markers and pass concatenated bytes to an experiment as if they were contiguous.

Protocol parsers differ. Modbus stops or resynchronizes only at defined points; DNP3 CRC/framing evidence and HTTP recovery have their own limits. Read the protocol-specific guide before interpreting `lost`, `unmatched` or a recovered record as complete coverage.

The HTTP API/view exposes `reassemblyStatus` and string-valued `timestampNs`. Empty reassembly status does not establish completeness; missing capture time stays unavailable. Generic numeric JSON timestamps are not relabeled as exact nanoseconds (`cmd/capture/webui/audit_semantics_test.go`).

`TCPReassemblyHealth.json` qualifies checksum policy and rejections. Malformed input, encrypted payloads and unsupported protocols can all yield no application records. [Capture health](/investigate-evidence/evidence) helps distinguish missing visibility from an observed negative.


# Payload retention

`capture -payload` includes raw payload fields where the selected decoder supports them. It does not decrypt TLS or recover upstream-truncated packets.

```sh
net capture -read traffic.pcap -out payload-audit -payload -dpi=false
net dump -read payload-audit/UDP.ncap.gz -json
```

JSON represents protobuf byte fields as base64. CSV/custom record renderers may use another representation; consult the record schema before interpreting a string as text. Payload field coverage is decoder-specific.

| Option/artifact   | Different purpose                                                 |
| ----------------- | ----------------------------------------------------------------- |
| `-payload`        | Raw bytes in supported audit records                              |
| `-conns`          | Directional stream evidence and conversation output               |
| File extraction   | Reconstruct transferred file artifacts with completeness metadata |
| `-retain-packets` | Rotating PCAPNG packet retention with a manifest                  |

Retained bytes can contain credentials, personal data and executable content. Set collection, access and retention boundaries for the actual output directory. Compression is not anonymization. Preserve the original capture for reruns; missing payloads in an old record require reanalysis from available source bytes.


# File extraction

File extraction reconstructs available transferred content and emits `File` metadata. It is distinct from packet payload retention and complete source-PCAP retention. Encrypted content remains unavailable without a supported plaintext analysis path.

## Bounded extraction and analysis

`-file-config FILE` loads strict YAML over the defaults in `internal/decoder/stream/file/config.go`; invalid or unsupported settings fail instead of silently falling back. Capture admission freezes extraction policy and private analyzer snapshots. Service helper jobs receive an immutable `artifact-config.yml` snapshot.

```yaml
file_extraction:
  size_limits:
    max_file_size: 104857600
    max_inflight_bytes: 268435456
    max_files_per_session: 0
  advanced:
    enable_yara_scanning: true
    yara_rules_path: /absolute/path/to/owned-rules
    enable_magika: false
```

```sh
net capture -read traffic.pcap -out ./audit -fileStorage files \
  -file-config extraction.yml -http ""
```

| Boundary         | Contract                                                                                                                                                                                                                                                                                                                                   |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Buffers          | Raw bodies and each decoded layer use the per-file limit, optional `reassembly.max_buffer_size` ceiling (10 MiB default), and capture-owned in-flight reservations. `max_inflight_bytes` must be at least twice `max_file_size`, at most 1 GiB; `max_file_size` is 1–100 MiB.                                                              |
| Stream limits    | `-max-stream-bytes=0` disables that reassembly-depth limit, not artifact budgets. Compression/storage policy remains separate.                                                                                                                                                                                                             |
| Content fidelity | HTTP files preserve extracted bytes; MIME attachments use structural multipart/base64/quoted-printable parsing. SMTP dot unstuffing and POP3 retained lines preserve binary data/CRLF before extraction. Eight MIME nesting levels and 128 parts are admitted.                                                                             |
| Publication      | Complete blob writes are synced and atomically published without replacing a destination. Duplicate content reuses the blob while retaining File observations.                                                                                                                                                                             |
| YARA-X           | Configured rules must exist and contain enabled rules. Metadata in `yara-rules-meta.json` disables named files. Includes are disabled; independently load bounded sources. Invalid reload retains the previous ruleset and reports failure.                                                                                                |
| Ruleset budget   | At most 1,024 enabled files, 1 MiB/source and 16 MiB total; scan results reject more than 4,096 matches.                                                                                                                                                                                                                                   |
| Magika           | Optional installed executable, bounded by a 60-second context, 1 MiB stdout and 64 KiB stderr. Executable SHA-256 is recorded; changed executable identity fails. Unix cancellation kills the owned process group.                                                                                                                         |
| Workers/cache    | Two capture-owned workers, 32 queued jobs and 256 MiB active/queued content budget. Cache is capture-local, capped at 1,024 entries/16 MiB. Exhaustion is reported as rejection; this version does not evict retained results.                                                                                                             |
| Result identity  | `artifact-analysis.json` version 1 binds capture RunID, config/rules/tool digests and content SHA-256. The YARA Go binding version is recorded; its native-library version is not exposed by the binding.                                                                                                                                  |
| Outcomes         | Disabled, ready, queued, running, completed, failed, timed-out and cancelled are distinct. Completed YARA carries matched/no-match; Magika carries classified. Queue/cache refusal is counted and recorded in extraction issues, never a clean result.                                                                                     |
| Finalization     | Accepted analysis finishes before audit readiness. Analyzer failure preserves the artifact, persists partial coverage and returns an error for requested analysis. Extraction-only partial coverage remains inspectable without converting a successful capture into a scan failure. Result/output persistence failure prevents readiness. |
| Visibility       | Files page and file preview show analysis coverage and transfer occurrences; YARA scan APIs distinguish completed scans from failures. `GET /api/artifact-analysis` supports the same explicit input/session selectors as artifact access. Legacy/missing reports are unavailable, not clean.                                              |

Only regular files inside the selected extraction root can be downloaded, previewed or scanned. Traversal, stored symlinks, nonregular files and unknown capture selectors are rejected (`internal/artifactio`).

`Hashes.SHA256` identifies exact content; legacy `Hash` remains MD5. Analyzer enablement requires SHA-256. `IsComplete`/`CompletenessReason` qualify bytes; `StreamMissingBytes` is unattributed stream loss, not a measured missing-byte count for every file. General archive recursion remains unsupported.

## Usage

```sh
net capture -read traffic.pcap -out file-audit -fileStorage files -dpi=false
net dump -read file-audit/File.ncap.gz -fields
net dump -read file-audit/File.ncap.gz -json
```

Only inspect `File.ncap.gz` when the capture produced file records. The default storage directory is `files` beneath the analysis output; disable extraction with `-fileStorage ''`. Protocol coverage and completeness differ by decoder.

## File Audit Records

| Evidence                        | Interpretation                                          |
| ------------------------------- | ------------------------------------------------------- |
| `Name`, source URL/metadata     | Original advertised name, not a trusted filesystem path |
| `Location`                      | Stored artifact path                                    |
| SHA-256 storage basename        | Content-addressed name with preserved extension         |
| Declared/detected content types | Advertised MIME and classifier result can disagree      |
| Length/hashes/completeness      | Qualify the bytes actually reconstructed                |
| Context/connection reference    | Link back to the observed transfer                      |

Current extraction uses SHA-256-based storage names and can retain multiple hash algorithms. Historical MD5-only examples and connection-derived filenames are obsolete. Inspect `types/netcap.proto` and emitted fields rather than an old copied message definition.

## Inspect a synthetic artifact

The [transfer lab](/start-here/investigation-walkthrough) produces a known text file. Inspect its `Hashes.SHA256`, `IsComplete`, original name and stored `Location`. `Hash` remains legacy MD5; use the explicit SHA-256 field for the content check. Magika, MIME detection, executable/script heuristics and YARA are independent build/configuration-dependent analyses, not interchangeable verdicts.

## YARA workflow

For a YARA-enabled build, keep the local UI running while analyzing a fresh lab copy:

```sh
net capture -read doc-fixtures/investigation.pcap -out doc-fixtures/yara-audit \
  -http 127.0.0.1:8080 -dpi=false -geoDB=false
```

1. Open the YARA page and check engine availability. A `noyara` build cannot scan; an unavailable engine or zero enabled rules is not a clean result.
2. Upload [`docs/examples/synthetic-file.yar`](https://github.com/dreadl0ck/netcap/tree/master/docs/examples/synthetic-file.yar) and enable the rule. It looks only for the synthetic body string.
3. Select the lab analysis and scan its extracted file. Expect `Netcap_Documentation_Fixture`; this match says nothing about malware.
4. Compare a file without that marker and confirm no match, keeping engine/rule status distinct from scan results.

The equivalent local API check, after capture finalization, is below. It creates `negative.txt` only as a labeled scanner control, not as claimed capture evidence:

```sh
curl -fsS http://127.0.0.1:8080/api/yara/status > doc-fixtures/yara-status.json
python3 -c 'import json; assert json.load(open("doc-fixtures/yara-status.json"))["available"], "YARA is unavailable"'
curl -fsS -F file=@docs/examples/synthetic-file.yar \
  http://127.0.0.1:8080/api/yara/rules/upload > doc-fixtures/yara-upload.json
net dump -read doc-fixtures/yara-audit/File.ncap.gz -json > doc-fixtures/yara-files.ndjson
python3 -c 'import json,pathlib; r=json.loads(open("doc-fixtures/yara-files.ndjson").readline()); p=pathlib.Path(r["Location"]).resolve(); base=pathlib.Path("doc-fixtures/yara-audit/files").resolve(); json.dump({"filePath":str(p.relative_to(base))},open("doc-fixtures/yara-request.json","w")); (base/"negative.txt").write_text("Synthetic negative scanner control.\n")'
curl -fsS -H 'Content-Type: application/json' --data-binary @doc-fixtures/yara-request.json \
  http://127.0.0.1:8080/api/yara/scan-file > doc-fixtures/yara-positive.json
curl -fsS -H 'Content-Type: application/json' --data-binary '{"filePath":"negative.txt"}' \
  http://127.0.0.1:8080/api/yara/scan-file > doc-fixtures/yara-negative.json
```

`make docs-check` runs this case when YARA is available and reports an explicit skip otherwise. For native release qualification, require it with `python3 scripts/check-docs.py --net /absolute/path/to/net --require-yara`.

The WebUI API exposes `/api/yara/status`, `/api/yara/rules` and `/api/yara/scan-file`; MCP exposes `get_yara_status`, `list_yara_rules` and `execute_yara_scan`. The latter scans the selected session's files and is synchronous. Use its [generated contract](/integrations-and-operations/tools), not a guessed CLI `-yara` flag. Uploading rules or scanning is separate from capture-time matching.

## Incomplete content

`-writeincomplete` permits supported paths to write incomplete bodies. A stored file is not proof of a complete transfer: inspect gaps, parser state, declared lengths and [stream evidence](/capture-and-inspect/reassembly). Encodings/decompression can make stored bytes differ from their on-wire representation.

Transferred files can be executable or hostile. Retain them as evidence; the fact that Netcap wrote an artifact does not mean it is safe to open. Preserve the source capture/hash for repeat analysis.


# Email extraction

Go Netcap decodes supported plaintext POP3, IMAP and SMTP exchanges. Transaction records, message bodies/attachments and authentication observations are separate outputs; visibility depends on captured bytes and protocol state.

```sh
net capture -read mail.pcap -out mail-audit -dpi=false
```

Inspect files actually emitted, for example:

```sh
net dump -read mail-audit/SMTP.ncap.gz -fields
net dump -read mail-audit/Secret.ncap.gz -json
```

## POP3

Supported retrievals can contain parsed `Mail`/`MailPart` metadata and bodies. A banner-only conversation does not imply a fetched message. Successful STLS ends plaintext parsing; subsequent encrypted bytes are not mail text.

## IMAP

Supported plaintext exchanges expose protocol records. Literal framing, partial responses and missing bytes can limit reconstruction. Successful STARTTLS ends plaintext parsing; the old statement that all IMAP support is future work is obsolete.

## SMTP

SMTP command/response records and LOGIN/PLAIN authentication observations are available. `Secret.Notes` distinguishes observed success, rejection and unknown result. A failed connection or incomplete response is not an authentication failure. Successful STARTTLS ends plaintext parsing.

## Interpretation

Use current record fields from `types/netcap.proto`; historical schema snippets with string timestamps are obsolete. Mail headers are sender-supplied evidence, not verified ownership. Credentials, recipients and attachments require the same access boundaries as the original capture. Follow [file extraction](/capture-and-inspect/file-extraction) and [evidence linking](/investigate-evidence/evidence) to trace reconstructed content.


# USB capture

USB audit records are available for supported USB capture representations. A PCAP link-type name alone does not prove the selected decoder understands that operating system's USB header layout.

## Offline from dumpfile

```sh
net capture -read usb.pcap -out usb-audit -base usb -payload -dpi=false
net dump -read usb-audit/USB.ncap.gz -fields
net dump -read usb-audit/USB.ncap.gz -json
```

Use a small known fixture from the capture tool/platform you intend to support. Check record counts and payload fields against the source. Historical `net.cap -r` examples use an obsolete executable/flag; use `net capture -read`.

## Live Capture

USB interfaces depend on the OS, driver, permissions and capture-tool support. List the interfaces visible to the installed runtime with `net util -interfaces`. Do not assume an `XHC20` interface from older macOS versions exists or can be captured on current macOS. Capture with a compatible platform tool first if the Netcap live driver cannot supply the expected link format.

## Audit Records

| Record                 | Evidence                                                                            |
| ---------------------- | ----------------------------------------------------------------------------------- |
| `USB`                  | Transfer/event metadata, bus/device/endpoint, status, lengths and supported payload |
| `USBRequestBlockSetup` | Setup request type, request, value, index and length                                |

Read `types/netcap.proto` and `dump -fields` for current types; timestamps are integer nanoseconds rather than the historical string schema. `-payload` preserves available supported payload fields but cannot recover bytes omitted by the source capture.


# Hosts and identity

`net triage` presents the capture-derived `Hosts.json` report. It complements packet and DeviceProfile records by distinguishing evidence about a host from directory subjects mentioned in traffic.

```sh
net capture -read traffic.pcap -out identity-audit -dpi=false
net triage -read identity-audit
net triage -read identity-audit -json
```

The report depends on enabled decoders and visible traffic. A capture with no identity-bearing protocols can legitimately have few facts.

## Read claims with their evidence

| Observation                | Interpretation                                                                  |
| -------------------------- | ------------------------------------------------------------------------------- |
| ARP/DHCP/NDP binding       | Address/MAC relationship in the observed scope/time                             |
| DHCP hostname/vendor data  | A client-advertised claim, not authenticated identity                           |
| Kerberos / NTLM            | Visible principals or account claims; retain source and outcome context         |
| LDAP / SAMR / LSA          | Directory subjects and selected RPC identity evidence                           |
| Conflicting bindings/names | Multiple observations to investigate, not a reason to discard contrary evidence |

An account returned by a directory server is not automatically an account on that server. A raw NTLM-shaped byte sequence without a framed owning protocol is not host attribution. Encryption, missing RPC state and unsupported encodings can prevent extraction.

## Investigation sequence

1. Select the host by address and capture scope, not hostname alone.
2. Inspect the binding/name/account state and underlying evidence source.
3. Compare timestamps with DHCP lease changes, NAT and interface/VLAN boundaries.
4. Pivot to [related records](/investigate-evidence/evidence) using exact selectors.
5. Preserve conflicting and incomplete observations in any exported conclusion.

`Hosts.json` schema 1 includes bounded host/account/directory observations and overflow reporting. Overflow limits completeness. Full JSON retains provenance that the compact terminal table cannot show. See [device profiles](/investigate-evidence/device-profiles) for MAC-centered aggregation and [behavior](/investigate-evidence/behavioral-monitoring) for approved baseline state; neither is interchangeable with identity evidence.


# Device profiles

`DeviceProfile` summarizes observed traffic around a MAC address. `Host` and `Connection` describe related address/communication observations. None is an authenticated asset inventory simply because a hostname or manufacturer is shown.

```sh
net capture -read traffic.pcap -out inventory-audit -dpi=false
net dump -read inventory-audit/DeviceProfile.ncap.gz -fields
net dump -read inventory-audit/DeviceProfile.ncap.gz -json
net triage -read inventory-audit -json
```

## Read the layers separately

| Evidence                  | Interpretation                                                                     |
| ------------------------- | ---------------------------------------------------------------------------------- |
| MAC / OUI                 | Observed link-layer address and vendor-table attribution                           |
| Device IPs                | Addresses seen with the device; NAT, relays and lease changes complicate ownership |
| Contacts and counters     | Captured peer/traffic summary, not a complete history of all activity              |
| Applications              | Classifier/decoder output available in this build                                  |
| Hostname/account bindings | Use `Hosts.json` and its provenance/conflicts                                      |
| Behavior baseline         | Explicitly reviewed state, separate from an observed profile                       |

Profiles depend on input link type and observation point. Routed traffic may show a gateway MAC for remote addresses; do not assign all of those addresses to one physical endpoint.

## Timing and bounds

Aggregate records can finalize at shutdown. A still-running capture need not contain every completed profile. DeviceProfile contact sampling and deduplication are bounded: inspect `ContactObservations`, `ContactCountLowerBound` and `ContactsTruncated` rather than equating a displayed list with exact cardinality. The implementation retains at most 4,096 sampled contacts and 65,536 dedup keys.

Use current fields from `types/netcap.proto`; historical `IPProfile` schema snippets do not describe the current Host/Connection model. [Identity](/investigate-evidence/host-identity) and [behavior](/investigate-evidence/behavioral-monitoring) guide the next investigation step.


# Credential observations

`Secret` records retain supported credential/authentication observations from visible traffic. A captured password, challenge/response or token is sensitive evidence; the record's existence does not establish successful authentication.

```sh
net capture -read traffic.pcap -out credential-audit -dpi=false
net dump -read credential-audit/Secret.ncap.gz -fields
net dump -read credential-audit/Secret.ncap.gz -json
```

Only inspect a file the capture produced. No `Secret` records can mean absent plaintext, encryption, unsupported framing, disabled harvesters or insufficient captured bytes. It does not establish that authentication never occurred.

## Review each observation

| Evidence                      | Interpretation                                                                                                    |
| ----------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| Protocol and endpoints        | Identify the owning framed exchange and initiator; raw token-shaped bytes alone do not establish host attribution |
| Credential representation     | Distinguish plaintext, encoded text, challenge/response and hashed material; base64 is encoding, not encryption   |
| `Notes` / protocol response   | Preserve observed success, rejection or unknown result; TCP reset/timeout alone is not an authentication failure  |
| Capture time and stream scope | Join only to the relevant connection and visible exchange                                                         |
| User/account names            | Advertised or observed identities; not proof of the human operator                                                |

SMTP LOGIN/PLAIN results and STARTTLS boundaries are described in [email extraction](/capture-and-inspect/mail-extraction). Windows account/principal evidence and directory subjects are covered by [hosts and identity](/investigate-evidence/host-identity). Encrypted sessions can expose endpoints/timing while hiding the result.

## Configure and qualify harvesters

The [transfer lab](/start-here/investigation-walkthrough) contains a synthetic HTTP Basic header encoding `lab-user:lab-password`. These are fictional values embedded offline, never submitted to a server. Inspect `doc-fixtures/audit/Secret.ncap.gz` and the owning HTTP record; the DNS-only benign control must have no credential observation. The HTTP 200 response alone does not prove which authentication policy a real service applied.

`capture -harvesters-config` loads the feature-specific YAML described by the checkout's `configs/` and harvester implementation. Use the installed help for per-stream byte bounds and selection; `-payload` is not a universal credential enable/disable control. Generic regex harvesting and protocol-specific parsing have different false-positive boundaries.

Test configuration on a synthetic positive exchange and a benign conversation that contains similar text outside an authentication frame. Do not replay real credentials to validate extraction. The WebUI's Credentials view and MCP `list_secrets`/`list_auth_activity` are distinct views; check the [tool reference](/integrations-and-operations/tools) before automation.

## Preserve and share

Limit access to the original capture, `Secret` files and screenshots. Redacting an exported table does not redact retained payloads or other output files. Preserve source references for authorized incident handling; avoid including credential values in rule names, public issues or documentation examples.


# Related evidence and capture health

An audit record is an observation, not a complete reconstruction of a network. Preserve the input, version, configuration and health witnesses needed to explain how it was produced.

## Capture health

`capture -capture-evidence` is enabled by default. `capture-manifest.json` binds input/configuration hashes, RunID, scope and ingress/admission/drop observations. Kernel statistics can be unavailable (`null`); absence is not a measured zero. Partial capture and decoder errors must remain visible in conclusions.

| Artifact                   | What it qualifies                                            |
| -------------------------- | ------------------------------------------------------------ |
| `capture-manifest.json`    | Input identity, scope and capture/admission coverage         |
| `TCPReassemblyHealth.json` | TCP checksum policy and rejection observations               |
| `FTPDataHealth.json`       | Control/data associations and exclusions                     |
| `BehaviorHealth.json`      | Scoped detector/queue/storage state when behavior is enabled |
| `FlowExportsHealth.json`   | Flow-export stream completeness and its record-file hash     |

Artifacts are feature-dependent. Use the WebUI's Investigation Evidence view to inspect those actually produced.

## Link related records

```sh
net investigate related -read analysis -type HTTP -ordinal 0
```

The ordinal is zero-based in that record file. Select an existing target. Alternative selectors include a Connection observation ID or a content-bound ID returned by an earlier query. The API offers `/api/evidence/related`.

| Relationship    | Evidence boundary                                                     |
| --------------- | --------------------------------------------------------------------- |
| Same connection | Community ID and time contained in one Connection observation         |
| Resolved by DNS | Latest qualifying answer for the client/destination within the window |
| Rule alert      | Matched-record evidence associated with a connection                  |
| Fallback flow   | Explicit candidate when no unique containing observation exists       |

DNS temporal proximity is a candidate relationship, not proof that a lookup caused the connection. Network-detection alerts carry different evidence and are not automatically rule-alert links. Packet records and records without a usable Community ID are not all linkable.

| Scope state | Meaning                                               |
| ----------- | ----------------------------------------------------- |
| `verified`  | Unique packet scope established                       |
| `ambiguous` | Multiple interface/VLAN scopes; scoped links withheld |
| `pending`   | Ledger not finalized                                  |
| `overflow`  | Ledger exceeded its bound; scoped claims withheld     |
| `missing`   | No suitable packet-scope witness                      |
| `legacy`    | No ledger; relationships explicitly remain candidates |

Defaults bound indexing to one million records, 500 returned links and 64 MiB accounted index storage. File hashes and scope witnesses bind returned IDs; replacing/extending a file invalidates prior references rather than silently rebinding them.

## Export packet evidence

```sh
net investigate packet-evidence -read traffic.pcapng \
  -bpf 'host 192.0.2.10 and udp port 9999' -out evidence.zip
```

The new ZIP contains `packets.pcapng` and `manifest.json`, including source/output hashes, selection, packet ranges, interface mapping and truncation counts. Existing destinations are refused. Packet options, secrets and source statistics are not copied as if they described the selected subset; keep the original.

| Packet download API               | Required tuple / time selection                                                          |
| --------------------------------- | ---------------------------------------------------------------------------------------- |
| `/api/connections/download-pcap`  | `srcIP`, `srcPort`, `dstIP`, `dstPort`, and explicit `protocol=TCP` or `UDP`.            |
| `/api/http/download-pcap`         | The observed endpoint ports are required, including nonstandard ports; transport is TCP. |
| `/api/certificates/download-pcap` | Endpoint/port pairs are preserved in both directions; transport is TCP.                  |

All three accept paired inclusive `startNs`/`endNs` decimal strings and explicit `inputFile`/`sessionId` capture selection. Without time bounds, a tuple export includes matching reused connections and other transactions; it is not proof of a unique HTTP transaction or certificate occurrence. HTTP exports no longer guess ports 80/443/8080. MCP connection carving requires the observed transport; its `start_ns`/`end_ns` fields preserve nanoseconds as strings.

Explicit `sessionId`/`inputFile` selectors must resolve to a registered capture; unknown selectors return 404, conflicting selectors or stale `runId` return 409, and empty/duplicate selectors return 400. Only requests without selectors may use the active capture. One request keeps one input/output context across active-file changes. Service reads require ownership or a public preloaded capture; configured MCP admin credentials retain administrative access. IDs alone no longer grant cross-owner private reads. The MCP backend client does not forward credentials through redirects or treat a 3xx body as successful API data.

`POST /api/reanalyze` also accepts `runId` in its JSON body. Body and query selectors must agree; a stale generation cannot enqueue work.

## Reanalyze a capture

`POST /api/reanalyze` creates an `analysis-*` sibling directory and a separate queued run. Parent audit records, extracted files, notes and completion state remain available, including when admission or child processing fails. Child jobs require capture-provenance witnesses even when ordinary capture evidence is disabled; their effective capture configuration records that policy.

| Child artifact / field      | Contract                                                                                                                                                                                                                                                                      |
| --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `source/<capture-name>`     | Private copied input; SHA256 calculated during copying. A known parent `inputSHA256` must match or the request returns 409. The copy consumes additional disk space.                                                                                                          |
| `analysis-parent.json`      | Analysis ID, creation time, engine version/commit, parent input/output/session, available parent RunID and manifest SHA256, source SHA256, `whole-capture` selector, requested BPF/DPI and exact artifact-configuration snapshot. Missing legacy parent hashes remain absent. |
| `session.json`              | Service-mode child ownership and `parentSessionId`; a child of a public preloaded capture belongs to its requester.                                                                                                                                                           |
| `/api/files/input` identity | Local children use distinct analysis IDs even when their input hashes match. Content SHA256 alone cannot identify a run.                                                                                                                                                      |
| Rejected queue admission    | HTTP 503; an already registered child is retained as failed. Parent state is untouched.                                                                                                                                                                                       |

Local startup rediscovers owned `analysis-*` directories immediately inside the configured output root or beside it, with parent relationships bound to that root. `analysis-state.json` atomically preserves local outcomes and timing. New children also retain the configured `analysisRoot`, allowing a retained grandchild to reopen after its immediate parent's directory is removed. Completion requires a matching source hash, finalized capture manifest and matching `audit-output-ready.json`; queued/interrupted work becomes a visible failure and is never automatically rerun. Missing/replaced sources remain visible as failed children. Symlinked sources/directories, mismatched IDs and duplicate IDs are rejected. Discovery is capped at 4,096 candidates and 64 MiB accounted metadata; failures are logged.

The PCAP page offers whole-capture and selected-packet child analyses when the backend advertises `childAnalysisVersion: 1`. Selected children show their saved BPF/time bounds and a Parent action; unsupported backends cannot submit the new workflow. Service startup restores owned child sessions from `results/analysis-*` with their original requester, parent reference, expiry and outcome. Interrupted children become failed without requeueing; missing or changed sources cannot remain ready. Child session writes are atomic, and status persistence failures are failures. General non-child session restoration remains disabled; an unavailable parent is not silently rebound to another capture.

For a subset, POST `inputFile` or `sessionId`, the expected parent `runId`, and `selection: {version: 1, sourceSHA256, bpf, startNs?, endNs?, maxPackets?, maxOutputBytes?}` to `/api/reanalyze`. Nanosecond bounds and output bytes are decimal strings. At least a BPF expression or paired inclusive bounds is required. The retained input is `source/selected.pcapng`; `packet-selection.json` binds source/output hashes, normalized selection, packet spans/counts, interface mapping and truncation/metadata limitations; its SHA256 is retained in `analysis-parent.json.packetManifestSHA256` and checked on recovery. `analysis-parent.json.inputSHA256` identifies the derivative, while `packetSelection.sourceSHA256` identifies its parent input.

| Subset limit / failure | Contract                                                                                                                          |
| ---------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| Packets                | Default and maximum 1,000,000; overflow aborts with HTTP 413.                                                                     |
| Request JSON           | At most 64 KiB; unknown fields and trailing JSON are rejected, so a misspelled selection cannot silently rerun the whole capture. |
| Output bytes           | Default 256 MiB; configurable up to 1 GiB; overflow aborts with HTTP 413.                                                         |
| Preparation            | 60-second timeout; cancellation/timeout returns 408.                                                                              |
| Empty / stale          | No matches returns 422; changed source/generation returns 409.                                                                    |
| Failed preparation     | No queued job; unregistered derivative files are removed. Parent output remains intact.                                           |

MCP `reanalyze_session` exposes `run_id`, `source_sha256`, `selection_bpf`, `start_ns`/`end_ns` and subset limits. It verifies backend support first and returns the child identity; polling the original parent cannot track child work. `get_session_info.capture_provenance` supplies the parent binding; unavailable provenance is reported separately as `capture_provenance_error`.

Recovery pitfall: real capture manifests finish with `status: "done"`; the older synthetic `"complete"` spelling is accepted only with the same hash/ready witnesses. A completion flag alone is insufficient.

## Retain packets and directional streams

```sh
net capture -read traffic.pcap -out retained -retain-packets \
  -packet-segment-mb 32 -packet-retention-mb 512 -conns -dpi=false
```

Packet retention rotates PCAPNG segments and records expired segments as tombstones. Connection evidence writes directional byte files and manifests under `stream-evidence/`; TCP gaps and UDP datagram boundaries are explicit. Do not concatenate a `gapped` stream and treat it as contiguous protocol input.

These options retain sensitive content and use disk. A bounded retained subset is not the original complete capture. [Flow analysis](/investigate-evidence/flow-analysis) explains whole-observation counters and estimated rates.


# Flow analysis

Packet-derived `Connection` observations and router-exported flow metadata are different inputs. Choose the query engine that matches the evidence.

## Rank Connection observations

```sh
net investigate flows -read analysis/Connection.ncap.gz \
  -start-ns "$START_NS" -end-ns "$END_NS" \
  -filter 'InSubnet(SrcIP, "192.0.2.0/24")' -group-by srcIP
```

`START_NS`/`END_NS` are inclusive UTC nanosecond integers chosen for your capture. They are not literal shell defaults. Query groups include endpoints, pairs, ports and protocol; sorting includes bytes, packets, peers, duration and rate. Inspect `investigate flows -h` for limits and selectors.

| Field/control                       | Meaning                                                                         |
| ----------------------------------- | ------------------------------------------------------------------------------- |
| `ObservationID`, `SnapshotSequence` | Reconcile cumulative Connection snapshots                                       |
| `-window-mode overlap`              | Include whole observations overlapping the window                               |
| `contained`, `start`, `end`         | Different interval selection semantics                                          |
| `-bucket-ns`                        | Optional uniformly interpolated bins, not observed per-packet timing            |
| Rate                                | Bytes divided by summed observation durations, not necessarily window wall time |

Legacy repeated tuples without snapshot semantics can be ambiguous; the reader does not guess deduplication or invent session counts. Defaults bound frame size, decoded input, records, groups and query duration. Exceeded limits fail instead of producing an unlabeled complete result. `/api/flows/query` uses the same bounded engine.

## Collect flow exports

```sh
mkdir flow-input
net investigate collect-flows -listen 127.0.0.1:2055 -out flow-input -duration 1m
```

This opens a UDP receiver for explicitly configured exporters. It is not a packet capture of arbitrary traffic and does not actively configure routers. Normalized NetFlow v5/v9, IPFIX and sFlow v5 observations, raw datagrams and issue events go to `FlowExports.jsonl`; finalized health binds its hash.

Offline packet capture can enable `-flow-exports` on configured export ports (defaults `2055,4739,6343,9995,9996`). Existing flow-export artifacts are refused.

## Query an exporter/domain

```sh
net investigate exported-flows -read flow-input/FlowExports.jsonl \
  -exporter 192.0.2.10:50000 -format netflow-v9 -domain 7 \
  -start-ns "$START_NS" -end-ns "$END_NS" -time-basis receive
```

Replace exporter, domain, format and time bounds with actual observations.

| Constraint                      | Interpretation                                                         |
| ------------------------------- | ---------------------------------------------------------------------- |
| Templates                       | Exporter/collector/domain scoped, bounded and expiring                 |
| Sampling                        | Keep reported counts; do not silently expand or mix sampling settings  |
| `flow` time                     | Requires exported start/end times                                      |
| `receive` time                  | Datagram capture/receipt time; sFlow does not establish flow start/end |
| Missing templates/sequence gaps | Issue events and partial health                                        |
| Incomplete/cumulative counters  | Excluded and counted explicitly by ranking                             |

Flow exports lack original packet payloads. Use [packet evidence](/investigate-evidence/evidence) when a claim needs bytes, and keep exporter identity and sampling context in any report.


# Rules engine

The NETCAP Rules Engine allows you to define detection rules that automatically generate alerts when specific network patterns are observed. Rules use expr-lang expressions to match audit records and can be configured to detect various attack patterns, anomalies, and policy violations.

## First rule

Create the benign input from [First capture](/start-here/quickstart), then save this as `documentation-rule.yml`:

```yaml
rules:
  - name: Documentation UDP Observation
    description: Match the synthetic walkthrough destination port
    type: UDP
    expression: DstPort == 9999
    severity: low
    tags: [documentation, fixture]
    enabled: true
```

```sh
net capture -read example.pcap -out rule-audit -rules documentation-rule.yml \
  -dpi=false -geoDB=false
net dump -read rule-audit/Alert.ncap.gz -json
```

Inspect `RuleName`, matched-record evidence and record-time timestamps. Alert deduplication can reduce alert count; do not equate alert rows with matched packets. This rule observes a port, not malicious activity. The examples below are hypothesis templates: SYNs are not failed logins, long DNS names are not confirmed tunnels, and a MITRE label/severity does not validate intent.

## Table of Contents

* [Overview](#overview)
* [Rule Configuration](#rule-configuration)
* [Writing Rules](#writing-rules)
* [Alert Structure](#alert-structure)
* [MITRE ATT\&CK Integration](#mitre-attck-integration)
* [Example Rules](#example-rules)
* [Offline grouped thresholds](#offline-grouped-thresholds)
* [Best Practices](#best-practices)

## Overview

### Features

* **Expression-based matching**: Use powerful expr-lang expressions to define detection logic
* **Ordered correlation**: Require an earlier related record before a rule alerts
* **MITRE ATT\&CK mapping**: Associate rules with MITRE ATT\&CK techniques
* **Alert deduplication**: Automatic deduplication within configurable time windows
* **Rate limiting**: Prevent alert flooding with per-rule rate limits
* **Multiple severity levels**: Categorize alerts as low, medium, high, or critical
* **Flexible tagging**: Organize rules with custom tags
* **Audit record output**: Alerts are written as NETCAP audit records for analysis

### Architecture

```
┌──────────────┐
│ Audit Records│
└──────┬───────┘
       │
       ▼
┌──────────────┐
│ Rules Engine │
└──────┬───────┘
       │
       ├─► Alert (if match)
       │
       ▼
┌──────────────┐
│ Alert.ncap.gz│
└──────────────┘
```

## Offline grouped thresholds

Availability: current source after v0.15.2. The v0.15.2 release binary has no `investigate rules` command or audit-readiness marker; build current source to use this section. The capture-time YAML format elsewhere on this page is a separate v0.15.2 interface.

`net investigate rules` evaluates `netcap-offline-rules/v1` packs against completed captures. The separate format rejects actions, sequences and distinct gates; the legacy capture engine rejects offline packs before processing.

```sh
net capture -read sample.pcap -out ./audit -include TCP -context=true \
  -capture-evidence=true -dpi=false -geoDB=false -http ""
net investigate rules -read ./audit -rules grouped.yaml
```

Save this opt-in pack as `grouped.yaml`:

```yaml
format: netcap-offline-rules/v1
rules:
  - id: tcp-syn-volume
    name: Retained TCP SYN volume
    type: TCP
    expression: SYN && !ACK
    severity: medium
    enabled: true
    threshold:
      count: 50
      window: 600s
      group_by: [SrcIP, DstIP, DstPort]
```

This counts stored SYN observations, including retransmissions. It does not establish authentication failure or unique connection attempts.

| Contract      | Behavior                                                                                                                                                                                                                                                   |
| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Admission     | Matching finalized `capture-manifest.json` and `audit-output-ready.json`, one unambiguous completed scope, no scope overflow or offline BPF. Older captures without readiness require recapture; do not manufacture a marker.                              |
| Types         | TCP, UDP, DNS and HTTP. Missing required files produce partial coverage; corrupt input fails before publication.                                                                                                                                           |
| Grouping      | 1–8 unique exact Go scalar field names; strings and integers only. Empty strings withhold observations and mark coverage partial. Numeric zero is valid. Aliases/nested fields are rejected.                                                               |
| Expressions   | Scalar comparisons, boolean operators, `contains`, `startsWith`, `endsWith`, and literal-array `in`. Calls, methods, maps, iteration, arithmetic and regex are rejected, including in disabled rules.                                                      |
| Windows       | Positive capture timestamps; observations sorted by time and canonical content. Inclusive `[t-window,t]`; the Nth match alerts and resets only that group. No wall-clock rate limiting or deduplication.                                                   |
| Configuration | Strict single-document YAML; stable unique IDs, count 2–65,536, positive duration up to 720h (default 60s). At least one rule must be enabled.                                                                                                             |
| Identity      | Event IDs bind canonical retained input, observation policy, normalized pack, group and crossing. Workers/source paths/run IDs remain provenance and do not change semantic identity.                                                                      |
| Output        | Root `Alert.ncap.gz` plus `rule-evaluations/<id>.json`. CLI prints a JSON report; failures and partial coverage return nonzero.                                                                                                                            |
| Evidence      | Trigger JSON and digest remain unchanged. `Notes.netcapOffline` holds grouping, time bounds and up to 16 contributor references, with explicit truncation. Nanoseconds/ordinals/counters are decimal strings; integer groups contain typed decimal values. |
| Concurrency   | Evaluation, alert clearing and reanalysis share an output lease. A stale `.offline-rule-evaluation.lock` needs operator inspection; it is not automatically removed.                                                                                       |

| Default refusal limit         | Value                             |
| ----------------------------- | --------------------------------- |
| Rules / records               | 64 / 100,000 per execution        |
| Frame / decoded bytes         | 4 MiB / 256 MiB                   |
| Sort data / state             | 128 MiB per type / 64 MiB         |
| Groups                        | 4,096 per rule / 16,384 per job   |
| Pending matches               | 65,536 per rule / 262,144 per job |
| Alerts / time                 | 10,000 or 32 MiB / 2 minutes      |
| Group key / execution history | 1,024 bytes / 100 reports         |

Bounds are accounted-storage limits, not an exact process-RSS ceiling. Large inputs refuse rather than spill to disk. Evaluation covers retained audit records; previously filtered/discarded records cannot be recovered.

Publication is durable per alert member, not transactional across the job. `publish-failed` reports record the committed prefix; `committing` after an interruption means unknown publication progress. Inspect the report and alert history before retrying. Explicit reruns append another evaluation.

The WebUI Rules page accepts a YAML upload, validates a read-only preview and executes against the selected completed capture. Alerts expose grouped evidence and incomplete-history warnings. Routes: `GET /api/rules/offline/packs`, `POST /api/rules/offline/validate`, `POST /api/rules/offline/execute`, and `GET /api/rules/offline/evaluations`. POST bodies contain `yaml` plus an optional local `inputFile` or service `sessionId`; unknown selectors never fall back to a different capture. Capability absence disables the panel on older backends.

## Rule Configuration

Rules are defined in YAML files with the following structure:

```yaml
rules:
  - name: Rule_Name
    description: Human-readable description
    type: AuditRecordType  # e.g., TCP, HTTP, DNS
    expression: expr-lang expression
    severity: low|medium|high|critical
    mitre: ["T1XXX.YYY"]  # MITRE ATT&CK IDs
    tags: ["tag1", "tag2"]
    enabled: true|false
```

### Field Reference

#### `name` (required)

Unique identifier for the rule. Used in alert generation and logging.

**Example**: `SSH_Bruteforce_Attempt`

#### `description` (required)

Human-readable explanation of what the rule detects.

**Example**: `Detect high frequency SSH connection attempts indicating possible brute force attack`

#### `type` (required)

The audit record type this rule applies to. Can be specified with or without the `NC_` prefix.

Use actual audit types such as `TCP`, `UDP`, `HTTP`, `DNS`, `TLSClientHello`, `IPv4`, `IPv6` or `ICMPv4`. Generic labels such as `TLS` and `ICMP` are not substitutes for record names. Discover fields with `dump -fields` and check their types in `types/netcap.proto`.

**Examples**:

* `TCP` or `NC_TCP`
* `HTTP` or `NC_HTTP`

#### `expression` (required)

An expr-lang expression that evaluates to true when the rule matches. Has access to all fields of the audit record type.

**Example**: `DstPort == 22 && SYN && !ACK`

#### `severity` (required)

Alert severity level.

**Valid values**: `low`, `medium`, `high`, `critical` (case-insensitive)

#### `mitre` (optional)

Array of MITRE ATT\&CK technique IDs associated with this detection.

**Format**: `["T####.###", ...]`

**Example**: `["T1110.001", "T1021.004"]`

Find technique IDs at: <https://attack.mitre.org/>

#### `tags` (optional)

Custom tags for organizing and categorizing rules.

**Example**: `["ssh", "bruteforce", "authentication"]`

#### `enabled` (required)

Whether the rule is active. Disabled rules are not evaluated.

**Valid values**: `true`, `false`

#### `threshold` / `threshold_window` (optional)

Fire only after `threshold` matches occur within `threshold_window` seconds (default window: 60). These legacy counters are shared by rule name, without entity grouping. They use record timestamps when available but retain arrival-order and wall-clock suppression behavior. Use [offline grouped thresholds](#offline-grouped-thresholds) for deterministic, entity-grouped evaluation of finalized retained records.

#### `distinct_field` / `distinct_threshold` (optional)

Cardinality-based (fan-out) detection. Instead of counting raw matches, the engine counts the number of **distinct values** of `distinct_field` observed **per source IP** within `threshold_window`, and fires when the count reaches `distinct_threshold` (default 2). This expresses "one source touching many distinct destinations" — e.g. an internal host sweeping many controllers:

```yaml
- name: S7comm Horizontal Enumeration
  type: Connection
  expression: DstPort == "102" && !IsApprovedWorkstation(SrcIP)
  distinct_field: DstIP
  distinct_threshold: 5
  threshold_window: 300
  severity: high
  enabled: true
```

#### `sequence` (optional)

Require an earlier **related** record before the rule may alert. This expresses "B after A within a window, for the same group" — for example a write to a register that the same source read minutes earlier.

```yaml
sequence:
  after: <expression identifying the earlier record>
  group_by: [SrcIP, DstIP, UnitID, Bank, Address]
  within: 900   # seconds, default 60
```

* `after` (required) — expression identifying the **earlier** record. It is compiled against the same record type as the rule, so both expressions see the same fields. The rule's own `expression` stays the **trigger**.
* `group_by` (required, at least one field) — top-level record fields whose values must be equal on the earlier and the triggering record.
* `within` (optional) — how many seconds the earlier record stays eligible. Defaults to 60; a negative value is rejected at load time.

Semantics:

* **Gate placement.** The gate runs before `threshold` and `distinct_field` counting, so those only ever see completed sequences and otherwise behave exactly as they do for an ungated rule. Rules without a `sequence` block are completely unaffected and allocate no sequence state.
* **`after` is evaluated on every record of the rule's type**, not only on records that match the trigger expression — the earlier record of a sequence usually does not match the rule's own `expression`.
* **Exact equality only.** `group_by` compares field values for equality (string and integer fields). It cannot express range overlap: grouping on a start address pairs a write with an earlier read of the *same* start address, never with a read whose span merely overlaps the write.
* **No self-satisfaction.** The lookup happens before the current record is recorded, so a record matching both `expression` and `after` can never satisfy its own precondition; it can only gate later records.
* **Complete group keys are required.** If any `group_by` field is empty, or of a kind other than string or integer, the record is not correlated at all — neither as a trigger nor as a precondition.
* **Record-time ordering.** Windows use the record's own timestamp (wall clock only for records that report no time), so offline replay behaves like live capture. A trigger timestamped before its precondition does not match, and a gap of exactly `within` still matches while one second more does not.
* **Evaluation order matters too.** The precondition must have been *seen* by the engine before the trigger. For record types written at stream completion/flush rather than per packet, records from different connections can reach the engine out of timestamp order; such pairs are not matched.
* **Observations are not consumed.** One earlier record can gate every trigger in its group until the window expires, and a newer `after` match refreshes the group's timestamp.
* **State is bounded.** Tracking is per rule and keyed by group. Aged-out groups are reclaimed by periodic sweeps and the number of tracked groups is capped; hitting the cap costs missed correlations, not unbounded memory.
* **Alerts describe the triggering record only.** The earlier record is not attached to the alert — retrieve it from the audit records using the group fields and the window.

The web UI cannot author sequences yet, but it preserves them when saving rules or toggling rule sets.

**Worked example** (shipped disabled in [`internal/rules/examples/modbus_hunt.yml`](https://github.com/dreadl0ck/netcap/blob/v0.15.2/internal/rules/examples/modbus_hunt.yml)):

```yaml
- name: Modbus Write After Read Same Register
  description: A source wrote a holding register it read within the last 15 minutes, on the same destination and unit.
  type: Modbus
  expression: >-
    MessageRole == "request" && ParseStatus == "valid" && !Exception &&
    FunctionCode in [6, 16, 22] && Bank == "holding_registers" && HasAddress
  sequence:
    after: >-
      MessageRole == "request" && ParseStatus == "valid" && !Exception &&
      FunctionCode == 3 && Bank == "holding_registers" && HasAddress
    group_by: [SrcIP, DstIP, UnitID, Bank, Address]
    within: 900
  severity: medium
  tags: [modbus, write, sequence]
  enabled: false
```

Given reads and writes between `192.0.2.10` and `192.0.2.20`, unit 1, bank `holding_registers`:

| Earlier record                | Trigger                                   | Alert?                                                     |
| ----------------------------- | ----------------------------------------- | ---------------------------------------------------------- |
| FC3 read of address 40 at `t` | FC6 write of address 40 at `t+600`        | yes                                                        |
| FC3 read of address 40 at `t` | FC6 write of address 40 at `t+901`        | no — outside `within`                                      |
| FC3 read of address 40 at `t` | FC6 write of address 41 at `t+600`        | no — grouping is equality, even if the read covered 40..45 |
| FC3 read of address 40 at `t` | FC6 write of address 40 by another source | no — `SrcIP` is in `group_by`                              |
| none                          | FC6 write of address 40                   | no                                                         |

### Additional helper functions

Beyond the network/string/time helpers, the following are available in expressions:

* `IsApprovedWorkstation(ip)` / `InAllowlist(ip)` — true if `ip` is in the approved-workstation allowlist loaded via `-approved-workstations` (`net capture`). Negate it (`!IsApprovedWorkstation(SrcIP)`) to escalate activity from non-authorized sources. See [S7 Threat Hunt](/investigate-evidence/s7-threat-hunt-aa26-231a).
* `HourOfDay(ts)` — local hour 0–23 of a nanosecond timestamp.
* `Weekday(ts)` — local weekday 0 (Sun) – 6 (Sat).
* `IsBusinessHours(ts, startHour, endHour)` — true within `[startHour, endHour)` on Mon–Fri. Use `!IsBusinessHours(Timestamp, 8, 18)` for off-hours detection.

## Writing Rules

### Basic Rule Structure

```yaml
rules:
  - name: TCP_443_Observation
    description: Observe TCP records addressed to port 443; protocol not established
    type: TCP
    expression: DstPort == 443
    severity: low
    tags: ["https", "encrypted"]
    enabled: true
```

### Using Helper Functions

Rules have access to all helper functions available in filtering:

```yaml
rules:
  - name: Private_to_Public
    description: Detect outbound traffic from private networks
    type: IPv4
    expression: IsPrivateIP(SrcIP) && IsPublicIP(DstIP)
    severity: low
    tags: ["network", "outbound"]
    enabled: true
```

### Complex Expressions

Combine multiple conditions for sophisticated detections:

```yaml
rules:
  - name: Suspicious_HTTP_Upload
    description: Detect large POST requests with suspicious user agents
    type: HTTP
    expression: |
      Method == "POST" && 
      ReqContentLength > 10000000 && 
      MatchesPattern(UserAgent, "(?i)^(curl/|wget/|python[-/])")
    severity: high
    mitre: ["T1041"]
    tags: ["exfiltration", "http"]
    enabled: true
```

### Field Access

Access nested fields using dot notation:

```yaml
rules:
  - name: DNS_Large_Query
    description: Detect DNS queries with long domain names
    type: DNS
    expression: len(Questions) > 0 && len(Questions[0].Name) > 100
    severity: medium
    mitre: ["T1071.004"]
    tags: ["dns", "tunneling"]
    enabled: true
```

## Alert Structure

When a rule matches, an alert is generated with the following information:

```go
type Alert struct {
    Timestamp      int64    // Matched record time, Unix nanoseconds
    Name           string   // Rule name
    Description    string   // Rule description
    SrcIP          string   // Source IP from matched record
    DstIP          string   // Destination IP from matched record
    SrcPort        string   // Source port from matched record
    DstPort        string   // Destination port from matched record
    MITRE          string   // MITRE ATT&CK IDs (comma-separated)
    RuleName       string   // Rule name (duplicate of Name)
    RecordType     string   // Type of audit record that matched
    Severity       string   // Alert severity level
    Tags           []string // Rule tags
    MatchedRecord  string   // JSON representation of matched record
}
```

Alerts are written to `Alert.ncap.gz` in the output directory and can be analyzed like any other audit record:

The excerpt is not the complete current schema. `DetectedAt` records processing time separately; `TimestampBasis`, `RuleDigest`, `RuleExpression`, threshold configuration and evidence references preserve interpretation/provenance. Read the emitted fields before joining alerts across captures.

```bash
# View all alerts
net dump -read Alert.ncap.gz

# Filter critical alerts
net dump -read Alert.ncap.gz -filter "Severity == 'critical'"

# Find SSH-related alerts
net dump -read Alert.ncap.gz -filter "RuleName in ['SSH_Bruteforce_Attempt', 'SSH_Tunnel_Detection']"
```

## MITRE ATT\&CK Integration

NETCAP rules can be mapped to MITRE ATT\&CK tactics and techniques to provide context about detected threats.

### Common Technique Mappings

| Technique ID | Name                                   | Use Case                          |
| ------------ | -------------------------------------- | --------------------------------- |
| T1046        | Network Service Scanning               | Port scans, service enumeration   |
| T1071.001    | Web Protocols                          | HTTP/HTTPS C2 communication       |
| T1071.004    | DNS                                    | DNS tunneling, exfiltration       |
| T1110        | Brute Force                            | Password guessing attacks         |
| T1190        | Exploit Public-Facing Application      | Web application attacks           |
| T1021.004    | SSH                                    | Remote access via SSH             |
| T1041        | Exfiltration Over C2 Channel           | Data exfiltration                 |
| T1048        | Exfiltration Over Alternative Protocol | Non-standard exfiltration methods |
| T1572        | Protocol Tunneling                     | Encapsulation for evasion         |

### Example with MITRE Mapping

```yaml
rules:
  - name: SQL_Injection_Attempt
    description: Detect SQL injection patterns in HTTP requests
    type: HTTP
    expression: MatchesPattern(URL, "(?i)(union.*select|insert.*into|delete.*from)")
    severity: critical
    mitre: ["T1190"]  # Exploit Public-Facing Application
    tags: ["web", "sql-injection", "injection"]
    enabled: true
```

## Example Rules

### Network Reconnaissance

```yaml
rules:
  # Port Scanning
  - name: TCP_SYN_Observation
    description: Observe an initiating SYN; a single packet is not a scan
    type: TCP
    expression: SYN && !ACK && !RST
    severity: medium
    mitre: ["T1046"]
    tags: ["reconnaissance", "port-scan"]
    enabled: true

  # ICMP Reconnaissance
  - name: ICMP_Echo_Request
    description: Observe an echo request; aggregate distinct destinations to assess a sweep
    type: ICMPv4
    expression: Type == 8
    severity: low
    mitre: ["T1018"]
    tags: ["reconnaissance", "icmp"]
    enabled: true
```

### Data Exfiltration

```yaml
rules:
  # DNS Exfiltration
  - name: DNS_Tunneling
    description: Detect suspiciously large DNS queries
    type: DNS
    expression: len(Questions) > 0 && len(Questions[0].Name) > 100
    severity: high
    mitre: ["T1048.003"]
    tags: ["exfiltration", "dns", "tunneling"]
    enabled: true

  # Large Upload
  - name: Large_HTTP_Upload
    description: Detect large HTTP uploads
    type: HTTP
    expression: Method == "POST" && ReqContentLength > 50000000
    severity: high
    mitre: ["T1041"]
    tags: ["exfiltration", "http"]
    enabled: true
```

### Malware Communication

```yaml
rules:
  # IRC C2
  - name: TCP_IRC_Port_Observation
    description: Observe common IRC destination ports; neither IRC nor C2 is confirmed
    type: TCP
    expression: DstPort >= 6667 && DstPort <= 6669
    severity: low
    tags: ["port-observation", "irc-candidate"]
    enabled: true

  # Suspicious Port
  - name: TCP_31337_Observation
    description: Observe a port associated with some historical tools; no malware verdict
    type: TCP
    expression: DstPort == 31337 || SrcPort == 31337
    severity: low
    tags: ["port-observation"]
    enabled: true
```

### Web Attacks

```yaml
rules:
  # SQL Injection
  - name: SQL_Injection
    description: Detect SQL injection attempts
    type: HTTP
    expression: MatchesPattern(URL, "(?i)(union.*select|insert.*into)")
    severity: critical
    mitre: ["T1190"]
    tags: ["web", "sql-injection"]
    enabled: true

  # Directory Traversal
  - name: Directory_Traversal
    description: Detect path traversal attempts
    type: HTTP
    expression: MatchesPattern(URL, "\\.\\./")
    severity: high
    mitre: ["T1083"]
    tags: ["web", "path-traversal"]
    enabled: true
```

## Best Practices

### Rule Design

1. **Be Specific**: Target specific behaviors rather than broad patterns

   ```yaml
   # Good - specific
   expression: Method == "POST" && DstPort == 80 && ReqContentLength > 10000000

   # Bad - too broad
   expression: ReqContentLength > 0
   ```
2. **Balance False Positives**: Adjust thresholds to minimize false alerts

   ```yaml
   # May generate false positives
   expression: DstPort == 22

   # Better - more specific
   expression: DstPort == 22 && SYN && !ACK && IsPublicIP(SrcIP)
   ```
3. **Use Appropriate Severity**: Match severity to actual threat level
   * `low`: Informational, minor anomalies
   * `medium`: Suspicious activity, requires investigation
   * `high`: Likely malicious activity
   * `critical`: Active attacks, immediate response needed

### Rule Organization

1. **Group Related Rules**: Create separate files for different categories

   ```
   internal/rules/
   ├── reconnaissance.yml
   ├── exfiltration.yml
   ├── malware.yml
   └── web_attacks.yml
   ```
2. **Use Descriptive Names**: Make rule purpose clear from name

   ```yaml
   # Good
   name: SSH_Bruteforce_External_Source

   # Bad
   name: Rule_1
   ```
3. **Add Comprehensive Tags**: Enable filtering and analysis

   ```yaml
   tags: ["protocol:ssh", "attack:bruteforce", "source:external"]
   ```

### Testing Rules

1. **Test Against Known Traffic**: Verify rules work as expected

   ```bash
   # Test rule file
   net capture -read traffic.pcap -rules test_rules.yml -out test_output

   # Check generated alerts
   net dump -read test_output/Alert.ncap.gz
   ```
2. **Monitor Alert Volume**: Ensure rules don't generate excessive alerts

   ```bash
   # Count alerts per rule
    net dump -read Alert.ncap.gz -json | python3 -c 'import collections,json,sys; print(collections.Counter(json.loads(line)["RuleName"] for line in sys.stdin))'
   ```
3. **Review False Positives**: Refine rules based on real-world results

   ```bash
   # Review specific rule alerts
   net dump -read Alert.ncap.gz -filter "RuleName == 'SSH_Bruteforce'"
   ```

### Performance Optimization

1. **Limit Regex Complexity**: Simple patterns are faster

   ```yaml
   # Fast
   expression: Method == "POST"

   # Slower
   expression: MatchesPattern(Method, "^(POST|PUT|DELETE)$")
   ```
2. **Order Conditions**: Place fast checks first

   ```yaml
   # Good - fast check first
   expression: DstPort == 80 && MatchesPattern(URL, "complex_regex")

   # Suboptimal - slow check first
   expression: MatchesPattern(URL, "complex_regex") && DstPort == 80
   ```
3. **Use Helper Functions**: Optimized native implementations

   ```yaml
   # Prefer
   expression: IsPrivateIP(SrcIP)

   # Over
   expression: InSubnet(SrcIP, "10.0.0.0/8") || InSubnet(SrcIP, "172.16.0.0/12")
   ```

## Troubleshooting

### Rule Not Triggering

1. **Check rule is enabled**: `enabled: true`
2. **Verify record type**: Ensure rule type matches audit records
3. **Test expression**: Use filter on dump command to test expression
4. **Check field names**: Use `-fields` flag to see available fields

### Too Many Alerts

1. **Increase specificity**: Add more conditions to reduce false positives
2. **Adjust thresholds**: Increase numeric thresholds
3. **Check deduplication**: Ensure deduplication window is appropriate

### Expression Errors

```bash
# Common errors and solutions

# Error: undefined identifier "InvalidField"
# Solution: Check available fields with -fields flag

# Error: type mismatch
# Solution: Ensure field types match comparison (string vs int)

# Error: invalid regex
# Solution: Test regex pattern separately, escape special characters
```

## Next Steps

* Review [example rules](https://github.com/dreadl0ck/netcap/tree/v0.15.2/internal/rules/examples) for more patterns
* See [FILTERING.md](/capture-and-inspect/filtering) for expression syntax details
* Check the [expr-lang documentation](https://expr-lang.org/docs/language-definition)
* Explore MITRE ATT\&CK framework at <https://attack.mitre.org/>


# Network detections

Go's network-detection engine observes packet and application patterns separately from YAML rules and approved behavioral baselines. `-network-detection` is enabled by default; `-network-detection-config` supplies its JSON policy.

| Mechanism          | Input                                         | Interpretation                               |
| ------------------ | --------------------------------------------- | -------------------------------------------- |
| YAML rules         | Typed audit records                           | Explicit expression/threshold/sequence match |
| Network detections | Packet/application observations               | Pattern, indicator or policy evidence        |
| Behavior           | Scoped facts and explicitly approved baseline | Change/deviation from reviewed state         |

Use the alert's detector identifier, evidence and observation time to decide which mechanism produced it. A benign policy observation is not necessarily an attack; a scan/beacon pattern alone does not prove compromise.

## Investigate a finding

1. Check capture scope, gaps and admission health.
2. Read detector evidence rather than inferring intent from the title.
3. Compare endpoints and time with decoded transactions and connection summaries.
4. Preserve protocol visibility: encrypted traffic can expose timing/edges without exposing authentication or application commands.
5. Add benign controls before changing a threshold or allowlist.

The engine includes scan, DNS, periodic-connection and transfer patterns, plus application-policy observations. Some application findings finalize after record processing; absence before completion is not a negative verdict.

## Indicators and policy

Use the complete minimal example [`docs/examples/network-detection.json`](https://github.com/dreadl0ck/netcap/tree/master/docs/examples/network-detection.json). Omitted thresholds retain the defaults in the released loader; unknown keys are rejected. Times are integer Unix nanoseconds, not seconds.

After creating the [lab fixtures](/start-here/investigation-walkthrough#create-the-evidence):

```sh
net capture -read doc-fixtures/investigation.pcap -out doc-fixtures/policy-audit \
  -network-detection-config docs/examples/network-detection.json \
  -dpi=false -geoDB=false
```

The sample marks a `.test` domain as a synthetic indicator valid only over the fixture's capture-time interval. It is not live threat intelligence. Replace source/version/validity explicitly for real indicators; do not remove those fields to make an expired entry appear current.

The versioned JSON types in [`internal/networkdetect/config.go`](https://github.com/dreadl0ck/netcap/blob/v0.15.2/internal/networkdetect/config.go) define thresholds, approved sources and IP/domain indicators. Indicators require source, version and capture-time validity. There is no bundled live intelligence feed or implicit STIX/TAXII ingestion. Distinguish an indicator match from independently verified malicious activity.

The WebUI's Alerts view displays available evidence. [Related-record linking](/investigate-evidence/evidence) does not automatically treat these alerts as YAML-rule matched records. [Behavioral monitoring](/investigate-evidence/behavioral-monitoring) has a separate learning and approval lifecycle.


# Behavioral monitoring

Behavior observes sensor/interface/VLAN-scoped device facts, service edges and traffic models. It is opt-in: learning is not approval, and new observations do not silently become trusted baseline facts.

```sh
net capture -read traffic.pcap -out behavior-audit -behavior \
  -http 127.0.0.1:8080 -dpi=false
```

Open the Behavior view. Short PCAPs may not meet default learning requirements: seven days of capture-time coverage and 100 observations. A long wall-clock wait does not add capture-time coverage to a short replay.

## Baseline lifecycle

| State/action    | Meaning                                                       |
| --------------- | ------------------------------------------------------------- |
| Learn           | Accumulate bounded candidates in the observed scope           |
| Approve         | Explicitly trust reviewed facts and create a baseline version |
| Monitor         | Compare subsequent facts/models against approved state        |
| Acknowledge     | Record a review without changing baseline trust               |
| Approve changes | Review benign candidates and version the baseline             |
| Suppress        | Explicit exception with retained decision context             |
| Pause/resume    | Control monitoring without inventing new observations         |
| Relearn/reset   | Deliberate baseline maintenance, not routine alert dismissal  |

Use `-behavior-baseline` for an existing baseline path, `-behavior-sensor` for explicit sensor identity and `-behavior-prefix` for configured network CIDRs. Default capture state is under the output directory. The baseline has a single-writer lock; concurrent captures must not mutate one file.

## Reproducible baseline lab

Create the [synthetic fixtures](/start-here/investigation-walkthrough#create-the-evidence). This lab deliberately lowers learning to 1 second / 4 packets; those are test values, not production recommendations. The four baseline ARP packets span six seconds and advertise `192.0.2.10` at `02:00:00:00:00:10`.

In terminal 1, from the checkout root:

```sh
net capture -read doc-fixtures/baseline.pcap -out doc-fixtures/baseline-audit \
  -behavior -behavior-sensor docs-lab -behavior-prefix 192.0.2.0/24 \
  -behavior-learning 1s -behavior-min-samples 4 -dpi=false -geoDB=false \
  -http 127.0.0.1:8080
```

Wait for capture finalization. In terminal 2, inspect the state, create an approval request using its actual version and explicitly approve the lab facts:

```sh
curl -fsS http://127.0.0.1:8080/api/behavior > doc-fixtures/learning.json
python3 -c 'import json; s=json.load(open("doc-fixtures/learning.json")); assert s["mode"] == "learning" and s["samples"] >= 4 and s["observed"]; json.dump({"action":"approve","ids":[],"reason":"Reviewed synthetic ARP lab only","version":s["version"]},open("doc-fixtures/approve.json","w"))'
curl -fsS -H 'Content-Type: application/json' \
  --data-binary @doc-fixtures/approve.json \
  http://127.0.0.1:8080/api/behavior/change > doc-fixtures/approved.json
python3 -c 'import json; s=json.load(open("doc-fixtures/approved.json")); assert s["mode"] == "monitoring" and s["approved"]; print(s["baselineId"],s["version"])'
```

Stop terminal 1 with Ctrl-C before opening the same baseline in another capture. Replay the unchanged and changed fixtures into fresh output directories, keeping the sensor and prefix scope identical:

```sh
net capture -read doc-fixtures/unchanged.pcap -out doc-fixtures/unchanged-audit \
  -behavior-baseline doc-fixtures/baseline-audit/Behavior.json \
  -behavior-sensor docs-lab -behavior-prefix 192.0.2.0/24 -dpi=false -geoDB=false
net capture -read doc-fixtures/changed.pcap -out doc-fixtures/changed-audit \
  -behavior-baseline doc-fixtures/baseline-audit/Behavior.json \
  -behavior-sensor docs-lab -behavior-prefix 192.0.2.0/24 -dpi=false -geoDB=false
net dump -read doc-fixtures/changed-audit/Alert.ncap.gz -json \
  > doc-fixtures/behavior-alerts.ndjson
```

The unchanged replay must produce no baseline-deviation alerts. The changed fixture claims the same IP from `02:00:00:00:00:99` and must produce a baseline change observation. Inspect its fact/evidence, then confirm that the original `baselineId` and approved map did not silently change. An ARP claim alone does not prove an attacker or establish which MAC should be trusted.

The default state file lives in the output directory; this replay explicitly selects the original baseline. Merely choosing a new `-out` without the baseline path would start separate learning. The saved baseline retains its original learning criteria after restart.

## Evidence and limits

| Surface          | Contract                                                                                            |
| ---------------- | --------------------------------------------------------------------------------------------------- |
| Discovery        | ARP/DHCP/NDP bindings, service edges, DNS and learned/configured prefixes                           |
| Lateral patterns | Distinct-target SMB/RDP/SSH relationships and inferred sequences                                    |
| Traffic models   | Frozen packet/byte models learned over multiple windows; approved models do not silently adapt      |
| Bounds           | Default 10,000 facts; visible overflow prevents approving incomplete learning                       |
| Persistence      | Atomic checkpoints and separately durable alert history                                             |
| Health           | Scope, queue/admission/drop observations, storage/detector errors and nullable unavailable counters |

Readable SMB authentication results are distinct from TCP resets, connection attempts or encrypted sessions. A→B→C patterns are evidence hypotheses, not proof of lateral execution. Learned DHCP leases can explain changes, but an unknown DHCP server cannot authorize itself.

## API and live feed

`GET /api/behavior` reads state. `POST /api/behavior/change` uses the versioned `{action, ids, reason, version}` decision contract. `/api/behavior/health` and `BehaviorHealth.json` expose coverage. `/api/alerts/stream` supports durable history cursors and `Last-Event-ID`; slow readers, truncation and replacement produce explicit gaps. It is bounded, not an unbounded lossless queue.

## Recovery and policy

Corrupt snapshots are rejected without replacement. Stop capture, preserve the damaged file and restore a known-good approved copy to a separate writable path. Select it explicitly; without a trusted backup, select a new path and relearn. Do not discard the only copy of approval/history evidence.

`-behavior-policy` supports source-specific maintenance intervals in UTC nanoseconds. Exceptions expire according to capture time. Geographic/admin policies are configuration, not observations. [Distributed sensors](/integrations-and-operations/distributed-collection) add delivery/ACK limits that remain separate from local alert durability.


# Industrial control systems

Passive industrial protocol evidence and its interpretation limits.

## Protocol Support

| Record/protocol          | Typical transport                           | Evidence boundary                                                                      |
| ------------------------ | ------------------------------------------- | -------------------------------------------------------------------------------------- |
| S7Comm / S7CommPlus      | TPKT/COTP TCP/102                           | Classic functions and visible Plus framing; not universal controller/model coverage    |
| Modbus                   | TCP/502; explicitly configured RTU-over-TCP | Per-function requests/responses, correlation and loss markers                          |
| DNP3                     | TCP/20000                                   | Link/application metadata, object headers and group-12 controls                        |
| CIP / ENIP               | TCP/44818, UDP/2222                         | Supported encapsulation/services; inspect selected record type                         |
| OPCUA                    | TCP/4840                                    | Supported visible framing/metadata; encryption limits payload interpretation           |
| PROFINET                 | UDP/34964                                   | Supported CM/DCE-RPC structures                                                        |
| BACnet/IP                | UDP/47808                                   | Supported service/object observations                                                  |
| IEC62351-related decoder | Registered TCP/2404                         | Selected recognized formats; the name does not promise complete IEC 60870/MMS coverage |

Use `net capture -overview` for the installed inventory. A record type, a well-known port and a full protocol implementation are different claims.

## Threat hunting

Collect both directions at an agreed observation point, preserve the original capture and inspect health before interpreting negative results. Analyze a copy; do not replay control messages to validate a passive finding.

| Workflow                                               | Guide and rule pack                                                                                   |
| ------------------------------------------------------ | ----------------------------------------------------------------------------------------------------- |
| S7 functions, workstation baseline and response limits | [S7 hunt](/investigate-evidence/s7-threat-hunt-aa26-231a); `internal/rules/examples/s7comm_hunt.yml`  |
| Modbus writes, banks/ranges and diagnostics            | [Modbus hunt](/investigate-evidence/modbus-threat-hunting); `internal/rules/examples/modbus_hunt.yml` |
| DNP3 controls, SBO and point mapping                   | [DNP3 hunt](/investigate-evidence/dnp3-threat-hunting); `internal/rules/examples/dnp3_hunt.yml`       |

Site-dependent examples require the site's approved initiators, point/register maps and maintenance policy. [Rules](/investigate-evidence/rules_engine) and [filtering](/capture-and-inspect/filtering) explain typed expressions and local-time helpers.

## Decoder selection off the standard port

The selector compares eligible parsers' evidence specificity; ascending registered port order only breaks ties. A weak registered-port signature can lose to stronger protocol evidence. Unknown-port UDP checks are datagram-aware; MQTT-SN's ambiguous short signature is restricted to its registered ports.

DNP3 Secure Authentication can be selected by `dnp3` rather than `iec62351` off-port because DNP3 validates its link CRC. Recognition does not establish cryptographic verification of Secure Authentication. See [selector developer references](/develop-and-extend/internals#decoder-qualification) for the implementation and confusable/reader regression tests.

## Record timing and direction

Readers map a message's first captured byte to its timestamp and observed direction. Stream/transaction records can still be emitted only on completion or flush. Packet timestamps, decoder emission order and transaction orientation must not be treated as interchangeable; inspect each record's contract.

## S7comm

Classic protocol ID `0x32` exposes function/message/error fields. Ack-Data `ErrorClass == 0 && ErrorCode == 0` is header status only. Inspect item results, request/PDU reference and controller/process evidence before claiming success. For responses the initiator is the destination, not the PLC source address.

Plus protocol ID `0x72` exposes supported framing/opcodes. The decoder sets `PayloadObscured`; that is a visibility limitation, not proof that every version uses the same encryption/integrity scheme. [The S7 guide](/investigate-evidence/s7-threat-hunt-aa26-231a) records released-rule limitations separately from source corrections.

## Modbus

The stream decoder distinguishes role, bank, zero-based wire address, quantity, values, exceptions and matched/unmatched/ambiguous responses. RTU endpoints need explicit `-modbus-rtu-endpoints`. Loss markers qualify missing coverage; a reply does not identify a user or independently prove a process effect. Follow the [field-level Modbus guide](/investigate-evidence/modbus-threat-hunting).

## DNP3

Header/data CRCs qualify framing, not authenticated identity. Point indexes need the outstation's device map. Group-12 control blocks are parsed; most other values are stepped over, not interpreted. A successful control response is distinct from independently observed equipment movement. See [DNP3 limits and the v0.15.2 Class 0 correction](/investigate-evidence/dnp3-threat-hunting#reconnaissance).

## CIP

This endpoint excerpt matches the released [`CIP` schema](https://github.com/dreadl0ck/netcap/blob/v0.15.2/types/netcap.proto). It is not a complete message definition:

```proto
message CIP {
  string SrcIP = 9;
  string DstIP = 10;
  int32 SrcPort = 11;
  int32 DstPort = 12;
  string CommunityID = 13;
}
```

## ENIP

The corresponding released endpoint fields are direct fields, not the obsolete `PacketContext Context = 9` from older docs:

```proto
message ENIP {
  string SrcIP = 9;
  string DstIP = 10;
  int32 SrcPort = 11;
  int32 DstPort = 12;
}
```

Generate bindings from the tagged `types/netcap.proto`, never from partial documentation excerpts. `make docs-check` verifies excerpt field numbers/types against that schema.


# Modbus threat hunting

Netcap decodes Modbus into structured audit records: request/response role, per-function addresses, quantities and values, diagnostics, device and server identification, file records, exception codes, request/response correlation, and explicit markers for data it could not decode. Use it for passive inventory and hypothesis-driven triage, then validate candidates against the original capture and the site's register map. A matching record is not proof of an unauthorized command or a process change.

## Capture Safely

1. Agree scope with OT operations: approved hosts, PLCs/gateways, maintenance windows, capture duration and evidence handling.
2. Collect both directions from an approved TAP/SPAN point, without probing, replaying traffic or issuing test writes/diagnostics. Preserve the original PCAP, capture-point details, clock reference and packet-loss statistics.
3. Analyze a copy offline. Retain payloads only under the site's data-handling policy; decoded values and payloads expose process data and settings.

```bash
net capture -read plant.pcap -out modbus-hunt -include Modbus -reassemble-connections=true -payload -compress=true
net dump -read modbus-hunt/Modbus.ncap.gz -json
net dump -read modbus-hunt/Modbus.ncap.gz -fields     # exact field list for this build
```

`Modbus` is the TCP stream decoder and the audit-record name. TCP/502 is conventional, not required: detection is content based, so nonstandard ports are covered. A conversation is only adopted once one complete ADU decodes, because an MBAP header alone is a weak signature — LDAP's BER framing satisfies every field of it. The cost is that a conversation whose first complete ADU never arrives is not claimed. Detection is not a completeness guarantee; missing bytes, partial captures and unsupported traffic leave gaps. No records does not prove no Modbus activity.

The decoder frames each TCP direction independently and timestamps an ADU from its first captured byte. With `-allowmissinginit=true` (the default), an unknown initial boundary is accepted only before any payload has been consumed. Every other interruption emits a `lost` marker record and is handled per direction; the opposite direction continues. After a gap of a **known** size the buffered bytes are discarded and the first byte after the gap is the only resume point: the MBAP header is validated exactly once at that offset, and the decoder never scans forward through a body hunting for a header. If that single attempt fails the direction stays stopped for the rest of the conversation — as it does after an invalid MBAP header or a gap of unknown extent. Incomplete trailing ADUs are still not emitted, but they now leave a marker. **Stream records are written at connection completion/flush**, not when a command arrives — this is not a real-time alerting path.

## Field Reference

| Field(s)                                                                                                            | Meaning and limit                                                                                                                                                                                                                                                                                                                            |
| ------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Timestamp`                                                                                                         | Integer Unix nanoseconds; first captured byte of the ADU.                                                                                                                                                                                                                                                                                    |
| `SrcIP`, `DstIP`, `SrcPort`, `DstPort`, `CommunityID`                                                               | Endpoints and flow ID. Not authenticated identities. Rewritten per direction, so a response has the PLC as `SrcIP`.                                                                                                                                                                                                                          |
| `Transport`                                                                                                         | `tcp` (MBAP) or `rtu_tcp` (RTU frames over TCP, opt-in).                                                                                                                                                                                                                                                                                     |
| `MessageRole`                                                                                                       | `request`, `response`, or `unknown` when stream direction could not be established.                                                                                                                                                                                                                                                          |
| `ParseStatus`, `ParseError`                                                                                         | `valid`, `malformed` (with a reason), `unsupported`, or `lost` on a capture-loss marker. Malformed records carry **no** decoded values — only function code, exception flag and framing metadata.                                                                                                                                            |
| `HasMBAP`, `TransactionID`, `ProtocolID`, `Length`, `UnitID`                                                        | MBAP metadata; `HasMBAP` is false for RTU. `Length` counts the unit byte plus PDU. `UnitID` identifies a unit behind an endpoint, not a user.                                                                                                                                                                                                |
| `Exception`, `ExceptionCode`                                                                                        | Exception bit stripped from the function code, plus the nonzero exception code as sent. Only responses may carry an exception; an exception PDU seen as a request is `malformed`.                                                                                                                                                            |
| `Bank`                                                                                                              | `coils` (FC1/5/15), `discrete_inputs` (FC2), `holding_registers` (FC3/6/16/22/23), `input_registers` (FC4), `file_records` (FC20/21). Empty for FC7, 8, 11, 12, 17, 24 and 43.                                                                                                                                                               |
| `HasAddress`, `Address`, `Quantity`, `Values`                                                                       | Wire (zero-based) start address, count and values for FC1-6, 15, 16, 22. `Values` holds coil bits as 0/1 and registers as 16-bit words; FC23 responses also return their read data in `Values`/`ReadQuantity`.                                                                                                                               |
| `HasReadAddress`, `ReadAddress`, `ReadQuantity` / `HasWriteAddress`, `WriteAddress`, `WriteQuantity`, `WriteValues` | **FC23 only.** No other function populates the `Read*`/`Write*` fields; single/multiple writes use `Address`/`Quantity`/`Values`.                                                                                                                                                                                                            |
| `AndMask`, `OrMask`                                                                                                 | FC22 mask-write operands (`Address` set, `Quantity` 1).                                                                                                                                                                                                                                                                                      |
| `HasDiagnostic`, `DiagnosticSubfunction`, `DiagnosticData`                                                          | FC8 subfunction and its data words.                                                                                                                                                                                                                                                                                                          |
| `Values`, `Quantity` for FC7/11/12                                                                                  | Serial-oriented status replies; all three requests carry no data at all. FC7: one exception-status byte in `Values`. FC11: the status and event-count words. FC12: three header words (status, event count, message count) followed by `Quantity` further entries, each one **raw event byte** — the event codes are not decoded into flags. |
| `HasAddress`, `Address`, `Quantity`, `Values` for FC24                                                              | Request carries only the FIFO pointer in `Address`. Response sets `Quantity` to the FIFO count (max 31) and `Values` to the queued registers.                                                                                                                                                                                                |
| `Quantity`, `Payload` for FC17                                                                                      | Only the framing is checked. `Quantity` is the response byte count; the vendor-defined content after it is deliberately **not parsed** and stays in `Payload` (so it needs `-payload`). No `Values`, no address, no bank.                                                                                                                    |
| `MEIType`, `ReadDeviceIDCode`, `DeviceIDObjectID`                                                                   | FC43 request: MEI type (14 = Read Device Identification) and requested ID code/object. Other MEI types are `unsupported`.                                                                                                                                                                                                                    |
| `DeviceIDObjects`, `DeviceIDConformityLevel`, `DeviceIDMoreFollows`, `DeviceIDNextObjectID`                         | FC43 MEI14 response: vendor/product/revision objects as `{ID, Value}` with `Value` raw bytes (base64 in JSON).                                                                                                                                                                                                                               |
| `FileRecords`                                                                                                       | FC20/21 records as `{ReferenceType, FileNumber, RecordNumber, RecordLength, Values}`. File numbers and record offsets are **not** register addresses.                                                                                                                                                                                        |
| `CorrelationStatus`, `RequestTimestamp`, `ResponseLatency`                                                          | `matched`, `unmatched`, `ambiguous` or `not_applicable`. `RequestTimestamp`/`ResponseLatency` (nanoseconds) are set only on matched responses.                                                                                                                                                                                               |
| `HasChecksum`, `ChecksumValid`, `Broadcast`                                                                         | RTU only. Frames failing CRC are never emitted, so `ChecksumValid` is always true when `HasChecksum` is true. `Broadcast` marks a unit-0 write.                                                                                                                                                                                              |
| `LostBytes`                                                                                                         | Set only on `ParseStatus == "lost"` markers: `> 0` is the gap size reassembly reported, `-1` means the amount is unknown, `0` means the capture was contiguous but framing became unusable. Zero on every decoded record.                                                                                                                    |
| `Payload`                                                                                                           | Raw PDU only (no MBAP, no unit byte, no CRC) when captured with `-payload`; base64 in JSON, hex in CSV.                                                                                                                                                                                                                                      |

Response enrichment on `CorrelationStatus == "matched"`: read responses (FC1-4) inherit `Address`/`Quantity` from their request and coil bit padding is trimmed to the requested quantity; FC23 inherits the request's `Read*`/`Write*` fields; FC20 subresponses inherit `FileNumber`/`RecordNumber`. Unmatched responses lack all of this — an unmatched FC3 response has values but no address.

Classic Modbus has **no protocol user identity and no authentication**. An IP allowlist expresses expected equipment, not which person authorized an operation. Use workstation, access and change logs for attribution.

## Capture Loss

A direction that stops producing evidence emits **exactly one** marker record per loss event: `ParseStatus == "lost"`, `MessageRole == "unknown"`, `CorrelationStatus == "not_applicable"`, `LostBytes` as described above, and `Transport` plus the direction's endpoints and last-seen timestamp. No function code, address or value is set. Further markers are suppressed until that direction decodes a record again. `ParseError` names the cause — `capture gap`, `unusable fragment`, `invalid MBAP header` or `truncated ADU`, and over RTU `unframed bytes discarded` or `unframed trailing bytes`.

```bash
net dump -read modbus-hunt/Modbus.ncap.gz -json -filter 'ParseStatus == "lost"'
```

Correlation does not survive a loss. Requests outstanding when the gap occurred become `ambiguous`, because their response may have passed unseen and a later response reusing the transaction ID would not be evidence of a match; MBAP requests observed after the gap correlate normally, whereas over RTU a loss blocks correlation for the rest of the conversation.

Markers make coverage auditable: **an empty hunt result over a conversation that also produced loss markers is not evidence of absence.** Check for markers on the endpoints and time range in question before reporting a negative finding, and treat every hunt over an affected conversation as incomplete.

## Output Semantics

`net dump -json` emits integer nanosecond timestamps and base64 bytes. The Elasticsearch-oriented `Modbus.JSON()` method converts `Timestamp` — but not `RequestTimestamp` — to milliseconds. CSV renders `Values`, `WriteValues`, `DeviceIDObjects` and `FileRecords` as JSON cells, `Payload`/`DiagnosticData` as hex, and `ResponseLatency` as plain nanoseconds. `-select` is CSV/table projection, not JSON redaction.

Numeric encoding is not an evidence export: strings, byte fields and repeated fields (`Values`, `FileRecords`, `DeviceIDObjects`, `Payload`, `CommunityID`, `Bank`, `MessageRole`, ...) are hashed to the low 16 bits of IEEE CRC32 and then normalized, with no dictionary. Collisions are intentional; these buckets imply neither ordering nor distance and are not anonymization. Use CSV, JSON or protobuf when exact values are required.

The `nc_modbus` Prometheus counter still exposes only `FunctionCode` and `Exception` labels — not roles, addresses, values or endpoints. It counts observed ADUs, including replies and exceptions; these are not successful-write counts.

## Scoped Baseline

Build a known-good baseline per cell/process, endpoint pair and UnitID covering routine polling, startup/shutdown and approved maintenance. Record approved function codes, banks and **complete wire address intervals** — not just start addresses — plus operating windows, and have OT owners confirm exceptions. Compare like capture durations and visibility. One plant-wide allowlist is not a process baseline. Observed peers are baseline candidates, not authorized masters.

Collect the raw request inventory first:

```bash
net dump -read modbus-hunt/Modbus.ncap.gz -json \
  -filter 'MessageRole == "request" && ParseStatus == "valid" && !Exception'
```

## Primary Hunt: Unauthorized Writes

Gate every operational hunt on `MessageRole == "request" && ParseStatus == "valid"`. This excludes echo replies (FC5/6/22 responses are byte-identical to their requests), excludes malformed PDUs whose decoded fields are deliberately suppressed, and excludes midstream `unknown` records.

Approval must contain the **whole written interval**, not the start address, and must be expressed per bank. Note the field split: FC5/6/15/16/22 use `Address`/`Quantity`; FC23 uses `WriteAddress`/`WriteQuantity`.

```bash
net dump -read modbus-hunt/Modbus.ncap.gz -json -filter '
MessageRole == "request" && ParseStatus == "valid" && !Exception &&
FunctionCode in [5, 6, 15, 16, 22, 23] &&
!(SrcIP == "192.0.2.10" && DstIP == "192.0.2.20" && UnitID == 1 &&
  ((FunctionCode in [5, 15] && Bank == "coils" && HasAddress && Quantity > 0 &&
    Address >= 100 && Address <= 199 && Quantity <= 200 - Address) ||
   (FunctionCode in [6, 16, 22] && Bank == "holding_registers" && HasAddress && Quantity > 0 &&
    Address >= 1000 && Address <= 1099 && Quantity <= 1100 - Address) ||
   (FunctionCode == 23 && Bank == "holding_registers" && HasWriteAddress && WriteQuantity > 0 &&
    WriteAddress >= 1000 && WriteAddress <= 1099 && WriteQuantity <= 1100 - WriteAddress)))'
```

The upper-bound check (`Address <= 199`) must precede the span check, both to express containment and to keep the unsigned subtraction from wrapping. An approved master writing outside its ranges still matches — that is the point.

FC21 file writes need their own rule; approve `FileNumber` and the full `RecordNumber`..`RecordNumber + RecordLength` interval of every record. `all()` is vacuously true on an empty list, so guard it: `len(FileRecords) > 0 && all(FileRecords, {.ReferenceType == 6 && .FileNumber == 1 && .RecordNumber >= 100 && .RecordNumber <= 199 && .RecordLength > 0 && .RecordLength <= 200 - .RecordNumber})`.

A match is an **attempted** write. Pair it with the correlated response before claiming effect:

```bash
net dump -read modbus-hunt/Modbus.ncap.gz -json \
  -filter 'MessageRole == "response" && CorrelationStatus == "matched" && FunctionCode in [5, 6, 15, 16, 21, 22, 23]'
```

## Diagnostics And Discovery

```bash
# FC8 subfunctions that can disrupt a device: restart comms (1), force listen-only (4), clear counters (10)
net dump -read modbus-hunt/Modbus.ncap.gz -json \
  -filter 'MessageRole == "request" && ParseStatus == "valid" && FunctionCode == 8 && HasDiagnostic && DiagnosticSubfunction in [1, 4, 10]'

# FC43 MEI14 device identification
net dump -read modbus-hunt/Modbus.ncap.gz -json \
  -filter 'MessageRole == "request" && ParseStatus == "valid" && FunctionCode == 43 && MEIType == 14'

# Harvested identity strings from the responses
net dump -read modbus-hunt/Modbus.ncap.gz -json \
  -filter 'MessageRole == "response" && ParseStatus == "valid" && MEIType == 14 && len(DeviceIDObjects) > 0'

# FC17 Report Server ID, and the serial-oriented status queries FC7/11/12
net dump -read modbus-hunt/Modbus.ncap.gz -json \
  -filter 'MessageRole == "request" && ParseStatus == "valid" && FunctionCode in [7, 11, 12, 17]'
```

FC8 diagnostics are serial-line-oriented; TCP gateways and devices vary in support, and a request is not evidence that disruption occurred. Force listen-only (subfunction 4) has no response, so it is never `matched`. Inventory tools legitimately enumerate identity data, so FC43 and FC17 are triage, not findings. FC17's reply is framed but its vendor content is not decoded — read it out of `Payload` by hand, and do not assume a shared layout across vendors. Never issue any of these to validate a finding on production equipment.

## Exceptions

```bash
# Illegal data address, attributable to a specific initiating master
net dump -read modbus-hunt/Modbus.ncap.gz -json \
  -filter 'MessageRole == "response" && Exception && ExceptionCode == 2 && CorrelationStatus == "matched"'

# All exceptions including those with no recoverable request
net dump -read modbus-hunt/Modbus.ncap.gz -json -filter 'Exception'
```

Common codes: 1 illegal function, 2 illegal data address, 3 illegal data value, 4 device failure, 6 device busy, 10/11 gateway path/target failure. An exception is not a completed write, and the absence of one does not establish execution. On `matched` responses `DstIP` is the initiating master and `RequestTimestamp` and `ResponseLatency` are populated; on `unmatched` responses neither the originating request nor the requested address is recoverable.

## Enumeration

Netcap's rule engine counts distinct values in a time window. Cardinality carries no ordering, so these detect breadth, not a scan pattern; for ordered pairing see [Read-Then-Write Pairing](#read-then-write-pairing) below. Use `distinct_field` with `distinct_threshold` and `threshold_window`:

* `distinct_field: DstIP` — one source touching many controllers.
* `distinct_field: UnitID` scoped to one `DstIP` — unit sweeping behind a gateway.
* `distinct_field: Address` (or `ReadAddress` for FC23) scoped to one destination/unit/bank — register map probing. This counts distinct **start** addresses, not covered addresses.

## Read-Then-Write Pairing

A rule can require an earlier related record before it alerts, so pairing a read with a later write of the same register is a rule, not a post-export step. `internal/rules/examples/modbus_hunt.yml` ships this as `Modbus Write After Read Same Register`, **disabled**:

```yaml
expression: >-
  MessageRole == "request" && ParseStatus == "valid" && !Exception &&
  FunctionCode in [6, 16, 22] && Bank == "holding_registers" && HasAddress
sequence:
  after: >-
    MessageRole == "request" && ParseStatus == "valid" && !Exception &&
    FunctionCode == 3 && Bank == "holding_registers" && HasAddress
  group_by: [SrcIP, DstIP, UnitID, Bank, Address]
  within: 900
```

What it asserts is narrow: the same `SrcIP`/`DstIP`/`UnitID`/`Bank` issued an FC3 read of a start address and then, within 900 seconds, a write to **the same start address**. `group_by` is exact equality, so a write whose span merely overlaps an earlier read is not matched — widen the hunt by dropping `Address` from `group_by` and accept the extra volume. A record missing a group field is not correlated at all, and the write must be timestamped at or after the read; records reaching the engine out of order do not pair. Because records are emitted at connection completion/flush, both halves must have decoded before a pair can form, and a `lost` marker between them means the read may never have been observed.

Read-modify-write masters produce exactly this pattern legitimately and constantly: HMI setpoint edits, controller retuning, and any client that reads a register before writing it back. A match is a candidate for baseline comparison, **not** proof of reconnaissance preceding a change or of staged tampering. Confirm it against the polling baseline and the register map. The alert describes the write only — the earlier read is not attached, so retrieve it from `Modbus.ncap.gz` with the same tuple and window:

```bash
net dump -read modbus-hunt/Modbus.ncap.gz -json -filter '
MessageRole == "request" && ParseStatus == "valid" && FunctionCode == 3 &&
SrcIP == "192.0.2.10" && DstIP == "192.0.2.20" && UnitID == 1 &&
Bank == "holding_registers" && Address == 1000'
```

## Running The Shipped Rules

`internal/rules/examples/modbus_hunt.yml` contains 15 rules: request-level hunt templates, one read-then-write pairing template, enumeration templates, and visibility/coverage triage. Site-dependent rules use documentation IPs and ship `enabled: false`; replace the addresses, units, banks and intervals before enabling. `Modbus Write After Read Same Register` needs no site values but also ships disabled, because read-modify-write masters match it routinely. Six site-independent rules are enabled by default — device identification (FC43 MEI14), server identification (FC17), disruptive diagnostics (FC8 subfunctions 1/4/10), unknown-role triage, parse triage (`malformed`/`unsupported`), and capture loss (`lost`). No rule configures a response action.

```bash
net capture -read plant.pcap -out modbus-hunt -include Modbus \
  -reassemble-connections=true -payload -rules internal/rules/examples/modbus_hunt.yml
net dump -read modbus-hunt/Alert.ncap.gz -json
```

The shipped write template authorizes the `Address`/`Quantity` form and the FC23 `WriteAddress`/`WriteQuantity` form separately, matching what the decoder populates per function code. Keep both clauses when you substitute your own tuples, or approved writes will alert.

The capture-loss rule is coverage evidence, not an attack signal: keep it enabled so that a quiet result set can be told apart from a direction that stopped decoding.

`-approved-workstations` loads an IP list for the `IsApprovedWorkstation()` rule helper if you prefer that to inline addresses. See [Rules Engine](/investigate-evidence/rules_engine) and [Filtering](/capture-and-inspect/filtering).

## RTU Over TCP

RTU framing (unit byte, PDU, CRC16, no MBAP) is decoded only for endpoints you name explicitly:

```bash
net capture -read gateway.pcap -out modbus-hunt -include Modbus \
  -reassemble-connections=true -payload \
  -modbus-rtu-endpoints '192.0.2.30:1502,[2001:db8::1]:502'
```

`net export` accepts the same flag; both read `NC_MODBUS_RTU_ENDPOINTS`. Values are comma-separated `IP:port` or `[IPv6]:port` with a nonzero port; an invalid entry fails decoder initialization. Matching is exact on the server address and port (or the client side when no handshake was observed, since a midstream capture may have its direction reversed) — there is no CIDR, hostname or wildcard form, and no autodetection. Listing an endpoint takes priority over every other decoder and disables MBAP parsing for that conversation, so do not list an MBAP endpoint.

RTU records set `Transport == "rtu_tcp"`, `HasChecksum`, `ChecksumValid` and `UnitID`; `HasMBAP` is false and `TransactionID`/`ProtocolID`/`Length` are zero. Correlation is a single outstanding request per conversation, matched on unit, function code and response shape within 30 seconds; a loss blocks it for the remainder of the conversation. Unit-0 frames are accepted only as write requests and the diagnostics permitted for unit 0, and are marked `Broadcast` with `CorrelationStatus == "not_applicable"`; no response is expected. The four-byte empty-request functions (FC7, 11, 12, 17) and FC24 are framed and correlated here too.

Only frames that pass CRC **and** parse to a valid PDU are emitted, so vendor-specific and unmodelled functions are still not reported as records — but they are no longer invisible: bytes that never framed surface as `unframed bytes discarded` or `unframed trailing bytes` loss markers.

## Manual Payload Evidence

* **Address trap:** `Address` is the zero-based wire offset within the bank the function selects. A holding register labelled `40001` commonly means `Address == 0`; vendor conventions vary. Keep coils, discrete inputs, input registers and holding registers distinct. `UnitID` is not an address. Confirm offset, width, scaling, signedness and multi-register word order against the exact device map before claiming a process meaning for any value.
* **Direction:** field values alone do not prove initiation. FC5/6/22 responses echo their requests byte for byte; `MessageRole` comes from stream direction, so it is only as reliable as the capture.
* **Payload:** byte 0 of `Payload` is the wire function code (exception bit intact); there is no MBAP header or CRC in it. Decode base64 before reading bytes. Missing payloads require reprocessing the retained PCAP with `-payload`.

For escalation, preserve the PCAP/frame references, endpoint pair, UnitID, transaction number, decoded record, correlation status, baseline deviation and the OT owner's assessment.

## Limitations

* **No user identity.** Modbus has no authentication; records attribute to endpoints and units only.
* **`unknown` roles.** Without an observed handshake the direction is unknown. For FC1-4 and FC20, where request and response layouts are both plausible, netcap deliberately emits only `FunctionCode` and `Bank` — no address, quantity or values. Do not count these as writes.
* **Unmatched correlation.** Correlation is per TCP connection, keyed on transaction ID with unit/function/shape checks, a 30-second window and a 1024-pending cap. Duplicate transaction IDs, saturation, or loss mark records `ambiguous`; responses whose request was not seen stay `unmatched`. Never join on transaction ID alone across connections.
* **Gaps end coverage, they do not repair it.** A `lost` marker tells you decoding stopped or resynchronised; it does not recover the missing ADUs. Everything between the marker and the next decoded record is unobserved.
* **Gateway blind spot.** A TCP-to-RTU gateway exposes only its TCP side; `UnitID` gives no visibility into the downstream serial bus or into execution.
* **Batch, not real time.** Stream records and their alerts appear at connection completion/flush, not when a command arrives.
* **Encrypted transport** requires authorized plaintext evidence elsewhere.

## Remaining Gaps

* No native serial capture and no Modbus ASCII framing — only MBAP over TCP and RTU frames carried over TCP.
* Vendor/user-defined function codes (65-72 and 100-110), any other unmodelled code, and FC43 with an MEI type other than 14 produce `ParseStatus == "unsupported"` with no structured fields; over RTU they never frame at all and surface only as loss markers.
* FC17's vendor-defined content is framed but not interpreted, and FC12 event bytes are reported as raw codes rather than decoded events.
* The rule engine's ordered correlation is one precondition grouped by exact field equality. There are no multi-step chains beyond a single earlier record, and no range-overlap join — pairing a write with a read whose span merely covers it still has to be done after export.
* Records are emitted at connection completion/flush, so hunts run on completed conversations.
* `nc_modbus` still carries only `FunctionCode` and `Exception` labels.

See [Filtering](/capture-and-inspect/filtering) for expression syntax and [Industrial Control Systems](/investigate-evidence/industrial-control-systems) for other protocols.


# DNP3 threat hunting

DNP3 / IEEE 1815 threat hunting

Netcap decodes DNP3 (IEEE 1815) into structured audit records: link addresses, link and application function codes, internal indications, object headers with qualifier-driven ranges, decoded Control Relay Output Blocks, Select-Before-Operate correlation, request/response correlation, and explicit markers for data it could not decode. Use it for passive inventory and hypothesis-driven triage, then validate candidates against the original capture and the outstation's device profile. **A matching record is not proof of an unauthorized command or a process change.**

```bash
net capture -read substation.pcap -out dnp3-hunt -include DNP3 \
  -reassemble-connections=true -payload -compress=true -http ""
net dump -read dnp3-hunt/DNP3.ncap.gz -json
net dump -read dnp3-hunt/DNP3.ncap.gz -fields     # exact field list for this build
```

`DNP3` is the TCP stream decoder and the audit-record name. TCP/20000 is conventional, not required: a conversation is claimed when a link header whose **CRC passes** is found, so nonstandard ports are covered and payload bytes that happen to contain `0x05 0x64` are not. The cost is that a capture beginning midstream, where no frame boundary falls inside the inspected bytes, is not claimed. Detection is not a completeness guarantee; no records does not prove no DNP3 activity.

Off-port selection ranks eligible decoders by evidence specificity; registered port order only breaks ties. The old first-match behavior could let a weaker signature shadow DNP3's validated CRC. `SelectDecoder` in `internal/decoder/stream/selection.go` and the selector/confusable tests cover the current behavior. DNP3 Secure Authentication can be claimed by `dnp3` rather than `iec62351` off-port; see [decoder selection](/investigate-evidence/industrial-control-systems#decoder-selection-off-the-standard-port).

## Why the protocol offers nothing to authenticate against

Base DNP3 is cleartext and unauthenticated. Select-Before-Operate is an interlock against a mis-click, not an authorization step, and the same standard ships Direct Operate, which skips it. A control from an address the network accepts is the protocol working as specified, so every detection here starts from behaviour and identity, not from a vulnerability.

Two identities matter and nothing on the wire binds them:

* **The IP**, in `SrcIP` / `DstIP`.
* **The DNP3 link address**, in `Source` / `Destination`.

A rule written on IP alone is watching half the wire. `DirectionMismatch` reports the two disagreeing about direction; see `DNP3 Control From Unapproved Master` in the shipped rules for checking both.

## Capture safely

1. Agree scope with OT operations: approved hosts, outstations, maintenance windows, capture duration and evidence handling.
2. Collect both directions from an approved TAP/SPAN point, without probing, replaying traffic or issuing test controls. Preserve the original PCAP, capture-point details, clock reference and packet-loss statistics.
3. Analyze a copy offline. Decoded values and payloads expose process data.

**Never issue a DNP3 function to validate a finding on production equipment.** An Operate on a live outstation is not a finding, it is a breaker.

## Field reference

| Field(s)                                                   | Meaning and limit                                                                                                                                                                            |
| ---------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Timestamp`                                                | Integer Unix nanoseconds, from the packet carrying the frame's first byte. Not the conversation's start.                                                                                     |
| `SrcIP`, `DstIP`, `SrcPort`, `DstPort`, `CommunityID`      | Endpoints and flow ID, per direction. A response carries the outstation as `SrcIP`. Not authenticated identities.                                                                            |
| `ParseStatus`, `ParseError`                                | `valid`, `malformed` (with a reason), `unsupported`, or `lost` on a capture-loss marker. A malformed record carries framing metadata only.                                                   |
| `LostBytes`                                                | Only on `lost` markers: `> 0` is the gap reassembly reported, `-1` means unknown, `0` means framing rather than the capture became unusable.                                                 |
| `Length`, `Control`                                        | Raw link header fields. `Length` counts control, addresses and user data, excluding every CRC.                                                                                               |
| `IsMaster`, `IsRequest`                                    | The Control field's DIR and PRM bits. What the frame *claims*, not what the network observed.                                                                                                |
| `DirectionMismatch`                                        | DIR disagrees with the observed direction. Set only when a TCP handshake fixed which end is the outstation.                                                                                  |
| `LinkFunctionCode`, `LinkFunctionCodeName`                 | Low nibble of Control. The name depends on PRM: `0x0` is `RESET_LINK_STATES` from a master and `ACK` from an outstation.                                                                     |
| `LinkFCB`, `LinkFCV`, `LinkDFC`                            | Frame count bit; frame count valid on primary frames; data flow control (outstation buffer full) on secondary frames.                                                                        |
| `Source`, `Destination`                                    | 16-bit link addresses. A second identity, independent of the IP.                                                                                                                             |
| `IsBroadcast`, `IsSelfAddress`                             | Destination `0xFFFD`-`0xFFFF`, and `0xFFFC`. A broadcast control reaches every outstation on the link.                                                                                       |
| `TransportSeq`, `TransportFIN`, `TransportFIR`             | Transport header.                                                                                                                                                                            |
| `ApplicationSeq`, `ConfirmRequired`, `Unsolicited`         | Application control. `ApplicationSeq` is **four bits**, so it repeats every sixteen requests.                                                                                                |
| `FunctionCode`, `FunctionCodeName`                         | IEEE 1815 Table 4-1, including 31 `ACTIVATE_CONFIG` and the Secure Authentication codes 32/33/131.                                                                                           |
| `IsCriticalFunction`                                       | Operates the process or the device's availability: 4-14, 16-18, 31. Not `SELECT`, which arms rather than operates.                                                                           |
| `IsConfigChange`                                           | Alters what the outstation is: 2, 19-22 and the file set 25-31.                                                                                                                              |
| `IsAuthentication`                                         | Secure Authentication v5 (32/33/131). **Not** FC29, which authenticates a file transfer.                                                                                                     |
| `InternalIndications` and the 14 `IIN*` flags              | Full 16-bit IIN on responses. Zeek's `iin` column is the second octet only, so a Zeek value of `4` is `0x0400` here.                                                                         |
| `HeaderCRCValid`, `BlockCRCValid`                          | A record only exists if the header CRC passed, so the first is always true on a decoded record. `BlockCRCValid` false means the user data was corrupt and no values were decoded.            |
| `Objects`                                                  | Object headers with `ObjectGroup`, `Variation`, `ObjectName`, `Qualifier`, `PrefixCode`, `RangeSpecifier`, `StartIndex`, `StopIndex`, `Count` (`-1` for "all objects"), and `ControlBlocks`. |
| `ObjectsTruncated`                                         | Parsing stopped before the end of the fragment, so `Objects` is a prefix of what was sent.                                                                                                   |
| `CorrelationStatus`, `RequestTimestamp`, `ResponseLatency` | `matched`, `unmatched`, `ambiguous` or `not_applicable` on responses. The last two are set only on a matched response.                                                                       |
| `SBOStatus`, `SelectTimestamp`, `OperateLatency`           | See [Select-Before-Operate](#select-before-operate).                                                                                                                                         |

`DNP3CROB` carries `Index`, `PointName`, `ControlCode`, `ControlCodeName`, `TripCloseCode` (0 NUL, 1 CLOSE, 2 TRIP), `OperationType`, `Clear`, `Queue`, `Count`, `OnTime`, `OffTime` and `StatusCode`.

## The point index is not an address

Group 12 index 7 is a particular feeder only because that outstation's device profile says so, and two vendors do not share a map. A captured control request does not prove a breaker moved. Interpreting an observed point/status also needs the outstation's point map and relevant process evidence.

Keep the point list with the capture. `-dnp3-point-map` puts it in the evidence:

```bash
net capture -read substation.pcap -out dnp3-hunt -include DNP3 \
  -reassemble-connections=true -payload -dnp3-point-map points.csv -http ""
```

```csv
# outstation,group,index,name
3,12,7,Feeder 4 breaker
3,12,8,Feeder 5 breaker
```

The outstation is the **DNP3 link address**, not an IP: one address can be reached over several paths, and one IP can front several outstations. Matched points appear in `ControlBlocks[].PointName`; unmapped points leave it empty. An unparseable file fails decoder initialisation rather than silently leaving every point unnamed. `net export` takes the same flag; both read `NC_DNP3_POINT_MAP`.

## The primary hunt: the control plane

Start by separating routine telemetry/confirmation functions from other application functions. Compare the remaining controls, configuration, restart and file activity with the site's operating baseline and work orders.

```bash
net dump -read dnp3-hunt/DNP3.ncap.gz -json \
  -filter 'ParseStatus == "valid" && !(FunctionCode in [0, 1, 129, 130])'
```

`CONFIRM` (0) is excluded with the telemetry codes because it is application-layer housekeeping for those same responses; drop the `0` to see it.

High volume is a triage lead, not itself a finding: first account for normal maintenance, capture duration, duplicate observations and the site's protocol use.

These queries identify candidates for site-policy validation:

```bash
# Direct Operate, where the engineering standard says Select-Before-Operate
net dump -read dnp3-hunt/DNP3.ncap.gz -json \
  -filter 'ParseStatus == "valid" && FunctionCode in [5, 6]'

# Disable Unsolicited, which silences the outstation's own event stream
net dump -read dnp3-hunt/DNP3.ncap.gz -json \
  -filter 'ParseStatus == "valid" && FunctionCode == 21'

# A control whose source is not a master you can name, on BOTH identities
net dump -read dnp3-hunt/DNP3.ncap.gz -json -filter '
ParseStatus == "valid" && IsCriticalFunction &&
!((SrcIP == "192.0.2.10" && Source == 4) || (SrcIP == "192.0.2.11" && Source == 5))'
```

## Select-Before-Operate

Selects are paired with Operates within the master's own direction, per outstation link address. `SBOStatus` is one of:

| Value                    | Meaning                                                                                                           |
| ------------------------ | ----------------------------------------------------------------------------------------------------------------- |
| `matched`                | The Operate named what the Select armed, in sequence and in time.                                                 |
| `operate_without_select` | A control with no interlock in front of it.                                                                       |
| `select_never_operated`  | A Select no Operate followed. Routine on an operator cancel.                                                      |
| `sbo_object_mismatch`    | The Operate named different points or control codes than the Select armed.                                        |
| `sbo_sequence_mismatch`  | Objects agree, but the application sequence number is not the Select's plus one.                                  |
| `select_expired`         | Beyond Netcap's ten-second correlation window; the actual outstation timeout needs device configuration evidence. |

A matched Operate is an **attempt**. Pair it with the response before claiming effect; the reply's `StatusCode` in `ControlBlocks` is the outstation's own verdict:

```bash
net dump -read dnp3-hunt/DNP3.ncap.gz -json \
  -filter 'CorrelationStatus == "matched" && FunctionCodeName == "RESPONSE"'
```

Response correlation keys on the application sequence number with the link addresses reversed. That number is four bits, so two requests outstanding on the same value make the reply `ambiguous` rather than guessing.

## Trip or close

The intent is two bits of one octet, and it is the difference between energising and de-energising:

```bash
# Trip
net dump -read dnp3-hunt/DNP3.ncap.gz -json \
  -filter 'ParseStatus == "valid" && any(Objects, {any(.ControlBlocks, {.TripCloseCode == 2})})'

# Close
net dump -read dnp3-hunt/DNP3.ncap.gz -json \
  -filter 'ParseStatus == "valid" && any(Objects, {any(.ControlBlocks, {.TripCloseCode == 1})})'
```

## Reconnaissance

A Class 0 request uses group 60 variation 1, as shown in [opendnp3's group/variation definitions](https://github.com/dnp3/opendnp3/blob/master/cpp/lib/src/gen/GroupVariation.cpp). It requests static class data, not the site's engineering map from point indexes to physical equipment. Polling can be routine; use breadth and the approved baseline to identify inventory candidates:

```bash
net dump -read dnp3-hunt/DNP3.ncap.gz -json -filter '
ParseStatus == "valid" && FunctionCode == 1 &&
any(Objects, {.ObjectGroup == 60 && .Variation == 1})'
```

The v0.15.2 `DNP3 Class 0 Integrity Poll Sweep` rule incorrectly checks variation 0, and `internal/decoder/stream/dnp3/objects.go` incorrectly labels that variation as Class 0. Current source fixes both the names and rule, but the released v0.15.2 executable remains affected. Use the raw `ObjectGroup`/`Variation` fields and a local corrected rule (`Variation == 1`) before relying on this hunt. The v0.15.2 shipped rule's `distinct_field: Destination` over 300 seconds measures breadth, not ordered scanning.

The outstation's own rejections are the other half, and the DNP3 analogue of a Modbus exception code:

```bash
net dump -read dnp3-hunt/DNP3.ncap.gz -json -filter '
ParseStatus == "valid" && (IINNoFuncCodeSupport || IINObjectUnknown || IINParameterError)'
```

## The trust that runs upward

The outstation is a trusted input to the master's parser, and it sits at the least supervised point on the network: a cabinet with a padlock, two site visits a year, over a link the utility frequently does not own. Unsolicited responses mean it initiates. A malformed frame from that direction is the shape of the problem, and it is now a record rather than a silent drop:

```bash
net dump -read dnp3-hunt/DNP3.ncap.gz -json \
  -filter 'ParseStatus == "malformed" && !IsMaster'
```

Decoded malformed-frame records have a passing header CRC. That improves framing confidence but does not authenticate the sender or exclude corruption or an accidental CRC match. `ParseError` names the cause: `length below minimum`, `block CRC failed`, `truncated transport header`, `truncated application header` or `truncated internal indications`.

Ask which of your masters has ever been fuzzed, by anyone, and which published advisories apply to the outstation firmware revision actually in service.

## Capture loss

A direction that stops producing evidence emits **exactly one** marker per loss event: `ParseStatus == "lost"`, `CorrelationStatus == "not_applicable"`, `LostBytes` as described above, and the direction's endpoints and last-seen timestamp. No function code or object is set. `ParseError` names the cause — `capture gap`, `unusable fragment`, `unframed bytes discarded` or `truncated frame`.

```bash
net dump -read dnp3-hunt/DNP3.ncap.gz -json -filter 'ParseStatus == "lost"'
```

**An empty hunt result over a conversation that also produced loss markers is not evidence of absence.** Check for markers on the endpoints and time range in question before reporting a negative finding. A capture that began without a SYN produces one `capture gap` marker per direction with `LostBytes == -1`.

## Running the shipped rules

`internal/rules/examples/dnp3_hunt.yml` contains the hunts above plus availability and visibility triage. Two rules ship **disabled** because they carry documentation addresses and placeholder hours — `DNP3 Control Outside Maintenance Window` and `DNP3 Control From Unapproved Master`. Replace the values before enabling. No rule configures a response action.

```bash
net capture -read substation.pcap -out dnp3-hunt -include DNP3 \
  -reassemble-connections=true -payload -http "" \
  -rules internal/rules/examples/dnp3_hunt.yml
net dump -read dnp3-hunt/Alert.ncap.gz -json
```

Keep `DNP3 Capture Loss` enabled: it is coverage evidence, not an attack signal, and it is what separates a quiet network from a blind one.

## Output semantics

`net dump -json` emits integer nanosecond timestamps. The Elasticsearch-oriented `DNP3.JSON()` method converts `Timestamp` — but not `RequestTimestamp`, `SelectTimestamp`, `OperateLatency` or `ResponseLatency` — to milliseconds. CSV renders `Objects` as a JSON cell. `-select` is CSV/table projection, not JSON redaction.

Numeric encoding is not an evidence export: strings and repeated fields are hashed and normalized, with no dictionary, so collisions are intentional. Use CSV, JSON or protobuf when exact values are required.

The `nc_dnp3` Prometheus counter carries `FunctionCodeName` and `ParseStatus` only. Endpoints, link addresses and object detail are deliberately not labels: one series per address pair over a long capture is a cardinality explosion, and these count observed frames, not executed commands.

## Limitations

* **No user identity.** Base DNP3 has no authentication; records attribute to endpoints and link addresses only. An IP allowlist expresses expected equipment, not who authorized an operation. Use workstation, access and change logs for attribution.
* **The index is not an address.** Without `-dnp3-point-map` or the device profile alongside the capture, a control identifies a point number and not a plant item.
* **Gaps end coverage, they do not repair it.** A `lost` marker says decoding stopped or resynchronised; everything up to the next decoded record is unobserved.
* **Batch, not real time.** Stream records and their alerts appear at connection completion or flush, not when a command arrives.
* **Direction needs a handshake.** Without an observed SYN the client and server assignment may be reversed, so `DirectionMismatch` is not evaluated.
* **Unmodelled objects stop the walk.** A group and variation with no known encoded size cannot be stepped over, so parsing stops and `ObjectsTruncated` is set. The unsizable header itself is **not** reported, because at that point its bytes are as likely to be the previous object's values.
* **Encrypted transport** (Secure Authentication aggressive mode aside, or DNP3 over TLS) requires authorized plaintext evidence elsewhere.

## Remaining gaps

* No DNP3 over UDP, and no native serial capture. Only TCP is framed, though the link framing is identical over both.
* Object **values** are not decoded. Group 12 control blocks are parsed in full; every other group is framed and stepped over, not interpreted, so analog and binary point values are not in the records.
* Secure Authentication v5 is flagged by function code and group 120 is named, but challenge, reply and key-status contents are not parsed, so an authentication failure is not distinguished from a success.
* File transfer (group 70) is flagged by function code; file names and contents are not extracted.
* Select-Before-Operate correlation is per conversation. A Select and an Operate split across two TCP connections do not pair.

See [Filtering](/capture-and-inspect/filtering) for expression syntax and [Industrial Control Systems](/investigate-evidence/industrial-control-systems) for other protocols.


# Siemens S7 threat hunting

This document maps netcap's capabilities to the S7 PLC threat hunt described in CISA Joint Cybersecurity Advisory **AA26-231A** ("Defending Against an Active Threat to Siemens S7 Series PLCs", 19 Aug 2026) and the associated public threat-hunt plan.

The campaign is a **hunting problem, not a patching problem**: there is no CVE. Adversaries use legitimate tooling (snap7 / python-snap7) over the legitimate S7comm protocol on TCP/102, frequently reaching controllers with default or absent credentials. Nothing trips a signature. **Read access is the campaign** — they are mapping process, logic and controllers to pre-position for later write operations. The window to find them is while they are still reading.

netcap contributes on the **network-visibility** side: it parses S7comm at the function-code level and turns it into structured audit records that the rule engine and downstream analytics can hunt over.

***

## Build prerequisites

The S7CommPlus visibility fields (`PayloadObscured`, `S7PlusOpcode`, …) and the GeoIP-on-Connection fields (`SrcGeoLocation`, `DstASN`, …) were added to `types/netcap.proto`. The generated `types/netcap.pb.go` is tracked, but it is **not regenerated by `go build`** — there are no `go:generate` directives, so a proto change only reaches the types package when someone runs protoc. If you edited the schema, regenerate before building or the new fields will not exist:

```bash
# via zeus (preferred)
zeus gen-proto-dev

# or directly (requires protoc + protoc-gen-gogofaster on PATH)
protoc --proto_path=types --gogofaster_out=types/. types/netcap.proto

# then build as usual
go build -o net ./cmd/net/
```

The function-code hunt rules, cardinality detection, approved-workstation allowlist and temporal helpers do **not** depend on the proto regeneration and work against the existing generated types.

***

## Inventory-gate before you hunt

Open every hunt by confirming there is anything to hunt. Process a capture and check whether any `S7Comm` (or other ICS) records are produced:

```bash
# Decode a capture, including S7comm and Connection records
net capture -read plant.pcap -include S7Comm,Connection -out out/

# Are there any S7comm records at all?
net dump -read out/S7Comm.ncap.gz -fields
net dump -read out/S7Comm.ncap.gz -json
```

If no ICS records are produced, record that no supported ICS records were decoded from this input. Validate observation point, enabled decoders, capture loss, truncation and encryption before using that scoped result. `-fields` shows the schema, not whether the file contains any records.

***

## The four hypotheses

The hunt plan orders four hypotheses; the order matters because the first scopes the rest.

### H1 — Are we visible? (external exposure)

Query Shodan, Censys, Netlas for TCP/102 against your own address space, ASNs and certificates — **passively, reading the indices, never probing a controller**.

**netcap scope:** This step is **out of scope for netcap** — netcap is a passive on-wire traffic tool and does not query third-party scan indices. Use netcap for the complementary question "is S7comm actually crossing a boundary on my wire?":

* Port-based external exposure: `ICS S7comm External Connection` (`internal/rules/examples/industrial_ports.yml`) fires on `DstPort == 102 && IsPublicIP(DstIP)`.
* GeoIP-enriched triage: `S7comm External Connection With GeoIP` (`internal/rules/examples/s7comm_hunt.yml`) fires on a public src/dst and attaches `SrcGeoLocation`/`DstGeoLocation`/`SrcASN`/`DstASN` (requires the geolocation resolver).

> **Gap to write down:** netcap cannot tell you whether a controller is indexed in Shodan/Censys. If you have been in a published scan index for months, you have been on a target list for months, and netcap will not show that.

### H2 — Is someone enumerating from inside?

The shape: **one source touching many distinct controllers on TCP/102, once each.** Repeated, frequent pairs are your operational baseline, not a finding.

**netcap:** the rule engine supports **source→distinct-destination cardinality**:

```yaml
rules:
  - name: S7comm Horizontal Enumeration
    description: One unapproved source contacted five distinct TCP/102 destinations
    type: Connection
    expression: DstPort == "102" && !IsApprovedWorkstation(SrcIP)
    distinct_field: DstIP
    distinct_threshold: 5
    threshold_window: 300
    severity: medium
    enabled: true
```

This fires when one source contacts 5+ distinct destinations on TCP/102 within 300 seconds. Tune `distinct_threshold`/`threshold_window` to sit above your baseline.

### H3 — Is there masqueraded tooling?

snap7 loaded on a host that is not an approved engineering workstation; a Python process talking to TCP/102; something called `monitor`/`telemetry`/`collector`/ `watchdog` speaking S7comm.

**netcap scope:** netcap sees the **network**, not host processes. It **cannot** observe "snap7 imported" or "a Python process." What it can do:

* Identify **which host** is speaking S7comm and flag it when the source is not an approved engineering workstation (see the approved-workstation baseline below). Any S7comm from a non-approved source is a lead for host-side triage.
* Surface the DPI application label (`S7COMM`, `S7COMM_PLUS`) on `Connection` records via nDPI (`internal/rules/examples/application_detections.yml`).

> **Gap to write down:** the snap7/Python/process-name discriminators require host telemetry (EDR/endpoint), not netcap. netcap narrows the host set; it does not confirm the tool.

### H4 — Has anything been written?

Separate the request, response header, item results and process effect. `MessageType == 3 && ErrorClass == 0 && ErrorCode == 0` identifies an Ack-Data with no header error; it does not establish that every item succeeded or that the physical process changed. Inspect available `DataItems[].ReturnCode` (`255` denotes item success) and correlate the request/PDU reference. v0.15.2's item parser does not cover every response shape, so an empty item list cannot prove success. Confirm operational effects with controller/process evidence.

netcap parses all of these at the function-code level into `S7Comm` records. The shipped rules (`internal/rules/examples/s7comm_hunt.yml`):

| Rule                                        | Function code(s)                                        | Meaning                                                          |
| ------------------------------------------- | ------------------------------------------------------- | ---------------------------------------------------------------- |
| S7comm Write Operation                      | `0x05` WriteVar                                         | Process manipulation / pre-positioning                           |
| S7comm Logic Download                       | `0x1A–0x1C`                                             | Ladder-logic injection / reprogramming                           |
| S7comm Logic Theft (Upload)                 | `0x1D–0x1F`                                             | Logic exfiltration                                               |
| S7comm PLC Stop                             | `0x29`                                                  | Controller halt / denial of control                              |
| S7comm CPU State Change                     | `0x28` PI service                                       | Cold/warm/hot restart                                            |
| Critical-operation acknowledgment candidate | `MessageType == 3 && ErrorClass == 0 && ErrorCode == 0` | Header result only; inspect item results and request correlation |
| S7comm Read From Non-Approved Source        | `0x04` ReadVar                                          | Reconnaissance of PLC memory                                     |
| S7comm Configuration Enumeration (SZL)      | UserData CPU/ReadSZL                                    | CPU/firmware/config fingerprinting                               |

The decoder also flags `IsCriticalOperation` and `IsSecurityRelevant` on the record, and names cold/warm/hot restart in `SubFunctionName`.

***

## The two things that decide almost every call

### 1. Build the approved-workstation baseline, and negate it

Almost every discriminator reduces to a single question: **does an authorization record exist for this source?** An uncorrelated write, download, upload or CPU-state change is escalated **regardless of how legitimate the source looks** — third-party integrators and managed service providers are explicitly in scope.

netcap wires this in as a first-class rule helper. Provide the approved engineering-workstation IPs in a file (bare IP per line, or `name,ip` CSV):

```bash
net capture -read plant.pcap -include S7Comm,Connection \
  -rules internal/rules/examples/s7comm_hunt.yml \
  -approved-workstations approved-ews.txt \
  -out out/
```

Request records carry the initiator in `SrcIP`; response records carry it in `DstIP`. Negate the approved set on the appropriate endpoint, not always on `SrcIP`. The v0.15.2 acknowledgment rule checks the PLC's source address and misnames the observation as a completed operation. Current source corrects the direction and renames it `S7comm Critical Operation Acknowledgment`; that source change does not alter an already downloaded v0.15.2 binary or its embedded rules. Use a reviewed external rule pack with `-rules` to apply corrections on v0.15.2.

The source request rules now require `MessageType == 1`; the S7CommPlus visibility rule reports both directions without inferring an approved initiator.

> **Do not allowlist by hostname pattern inside the query.** If a compromised approved workstation is your problem, a pattern match hides it. The baseline is built out-of-band (the file) and negated in the rule.

**Service mode:** when running `net capture --service`, rule evaluation happens in the webui/service process (post-hoc over written audit records). Provide the allowlist to that process via the `NC_APPROVED_WORKSTATIONS` environment variable (or the `-approved-workstations` flag on the service invocation), e.g.:

```bash
NC_APPROVED_WORKSTATIONS=approved-ews.txt net capture --service -http 127.0.0.1:8080
```

If the allowlist is not loaded, `IsApprovedWorkstation` returns false for every source, so every negated hunt rule fires on all S7comm traffic — including legitimate engineering-workstation activity. Load it, or expect noise.

### 2. Go find the paperwork

An alert from these rules is a pointer to a question — *is there a change record, a maintenance window, an authorized integrator session for this?* An uncorrelated finding gets escalated. Use the `S7comm Off-Hours Operation` rule (`!IsBusinessHours(Timestamp, 8, 18)`) to pre-filter activity outside the change window.

***

## Say what you couldn't see (named gaps)

The most damaging outcome of an OT hunt is a clean-looking negative that quietly covered half the estate. Name the gaps:

* **S7CommPlus payloads are integrity-obscured.** S7-1200/1500 controllers programmed through TIA Portal speak S7CommPlus (protocol id `0x72`), whose body is protected by session-keyed integrity material. netcap parses the cleartext framing (opcode: Request/Response/Notification) and **explicitly sets `PayloadObscured = true`**, plus fires `S7CommPlus Obscured Payload`. You can prove a connection happened; you often cannot prove which function code it carried. Corroborate with the approved-workstation baseline out-of-band.
* **No full-payload capture on TCP/102 → no function-code analysis.** Segments where only headers/flows are captured support H1/H2 (exposure, fan-out) but **not** H4 (writes/downloads). Confirm your capture has S7comm payloads.
* **Off-network reconnaissance is invisible.** Target selection via Shodan/ Censys/ZoomEye never touches your wire (H1). netcap cannot see it.
* **Host-side masquerading (snap7/Python/process names) needs endpoint telemetry** (H3). netcap narrows the host set but does not confirm the tool.
* **GeoIP requires the resolver and databases.** Country/ASN on `Connection` records is empty when the geolocation resolver is disabled or the address is private/unresolved.
* **Threshold/cardinality windows use the record timestamp** (fixed for offline replay). Ensure capture timestamps are accurate.

***

## Output and downstream hunting

`S7Comm`, `Connection` and `Alert` are all first-class audit records and flow through the standard writers:

* **Protobuf** (default), **CSV**, **JSON** for offline analysis.
* **Elasticsearch** is a separate writer/integration path; `net export` is the Prometheus exporter, not an Elasticsearch export recipe.
* **Alerts** are written to `Alert.ncap.gz` and carry the matched record, MITRE IDs, severity and rule expression for triage.

## Field reference (S7Comm record)

Key fields for hunting (see `types/netcap.proto` `message S7Comm`):

* `FunctionCode` / `FunctionName` — the operation (`0x04` read, `0x05` write, …).
* `MessageType` / `MessageTypeName` — Job (1), Ack (2), Ack-Data (3), UserData (7).
* `ErrorClass` / `ErrorCode` / `ErrorName` — header-level error evidence; zero does not prove item-level success or physical process effect.
* `IsCriticalOperation` / `IsSecurityRelevant` — decoder-computed flags.
* `SubFunctionName` — names cold/warm/hot restart for PI services.
* `UserDataFunctionGroup` / `UserDataSubFunction` — SZL / CPU function enumeration.
* `PayloadObscured`, `S7PlusOpcode`, `S7PlusOpcodeName` — S7CommPlus visibility.

## MITRE ATT\&CK for ICS mapping

T0846 (Remote System Discovery), T0888 (Remote System Information Discovery), T0893 (Data from Local System), T0821 (Modify Controller Tasking), T0843 (Program Download), T0845 (Program Upload/logic theft), T0813/T0816 (Denial of Control / Device Restart-Shutdown), T0885/T0868 (external exposure), plus the enterprise techniques from the advisory: T1587.004, T1588.007, T1596.005, T1694, T0834, T0849.


# Active protocol experiments

`net investigate` includes bounded experiment tools alongside passive evidence queries. Commands that listen or contact endpoints belong in a controlled lab or an explicitly authorized engagement. They are not required for offline PCAP analysis.

| Command                                | Purpose                                                            |
| -------------------------------------- | ------------------------------------------------------------------ |
| `exchange`                             | One bounded TCP/UDP exchange from a versioned JSON specification   |
| `protocol-fields`                      | Test a framing/field hypothesis on contiguous directional bytes    |
| `tls-capture`                          | External `tshark` TLS analysis using supplied session secrets      |
| `protocol-proxy`                       | One framed TCP session, optional TLS termination and bounded edits |
| `protocol-server`                      | Bounded server emulation                                           |
| `protocol-access`                      | Role/state/resource matrix with reset controls                     |
| `protocol-generate`, `protocol-corpus` | Deterministic grammar/field/state/byte cases                       |
| `protocol-fuzz`, `protocol-reproduce`  | Controlled campaigns, minimization and reproduction                |
| `protocol-boundary`                    | Separate target rejection from harness limits/timeouts             |
| `protocol-triage`                      | Import hashed process/debugger evidence; impact remains unverified |

## Offline hypotheses first

Create the [lab fixtures](/start-here/investigation-walkthrough#create-the-evidence), then use the complete version-1 grammar in [`docs/examples/grammar.json`](https://github.com/dreadl0ck/netcap/tree/master/docs/examples/grammar.json). Its fixed seven-byte frame contains version `1`, length `5` and five UTF-8 bytes. `expected` byte assertions use JSON base64 (`AQ==` is one byte with value 1).

```sh
net investigate protocol-fields -spec docs/examples/grammar.json \
  -read doc-fixtures/client.bin -compare doc-fixtures/other-client.bin \
  > doc-fixtures/grammar-comparison.json
```

Expect one frame in each input and a `text` difference from `hello` to `world`. The `size` field is interpreted, not automatically validated against the body; use explicit length/framing constraints when that relationship is part of the hypothesis. Ordinal comparison does not repair insertion/deletion alignment.

Use the versioned grammar types and examples in [`internal/protocoltest`](https://github.com/dreadl0ck/netcap/tree/v0.15.2/internal/protocoltest). `client.bin` must be contiguous evidence; capture gaps cannot be repaired by concatenation. Frame insertion can shift ordinal alignment. A successful parse shows that bytes fit a hypothesis, not that its application semantics are true.

## Supplied TLS secrets

```sh
net investigate tls-capture -read tls.pcapng -key-log secrets.log -stream 0
```

Install compatible `tshark` separately. Provide the correct capture/stream and NSS-format session-secret log; Netcap does not derive TLS secrets from passive traffic. Output binds input, key-log and plaintext hashes to tool version. Secret material is not copied into the report. Endpoint order follows the dissector's output, not a guessed client role.

## Active controls

`exchange -spec exchange.json` and related commands have time, frame, byte and input-size bounds. Byte fields use JSON base64. Configure certificate roots and paired client certificate/key explicitly for mTLS; TLS verification is not disabled merely to make an experiment succeed.

Keep a valid baseline/control case, exact input/output bytes, process context and reproduction steps. A matching marker is not general exploitation proof. A timeout/budget-stop is not target rejection; a debugger artifact is not verified impact. [Packet evidence](/investigate-evidence/evidence) preserves passive source context separately.


# Database updates

Go v0.15.2 installs signed community data using an embedded Ed25519 verification root. No community API key is required.

## Install and Update

```sh
net util -download-dbs
net util -update-dbs
```

Use the same `NC_CONFIG_ROOT` when installing and capturing. Defaults are `~/.config/netcap/dbs`, or `$NC_CONFIG_ROOT/dbs`. Go users can force replacement with `net util -download-dbs -force`.

## Compatibility

| Client/data          | Action                                                                        |
| -------------------- | ----------------------------------------------------------------------------- |
| Signed clients       | Use `/dbs/signed/v1/`; verify signatures, expiry, sequence and hashes         |
| Go v0.14.0           | Frozen `/dbs/v3/` snapshot; upgrade for ongoing refreshes                     |
| Legacy v1/v2 clients | HTTP 410; upgrade the executable                                              |
| SQLite schema 1      | Download schema 2; editing a version field does not migrate tables or queries |
| Private publisher    | Supply both independently verified registry path and SHA-256 pin              |

## Verification

Updates validate complete source/member records through staging. Failure preserves the previous installation. Unchanged verified data can skip archive downloading. Verified installed data remains usable offline after update expiry; expiry prevents accepting an old update as fresh.

Community data contains NVD, DB-IP Lite, IANA, UA-parser and pinned BSD HASSH. It excludes Exploit-DB payloads, Nmap probes, macaddress.io, Alexa, JA3 identification corpora and legacy CMS/DHCP OS catalogues. NVD reference URLs remain metadata; the updater does not fetch their bodies.

## Troubleshooting

| Symptom            | Check                                                                                           |
| ------------------ | ----------------------------------------------------------------------------------------------- |
| HTTP 410           | Upgrade the executable; v1/v2 distribution is retired                                           |
| Expired update     | Check the clock and publisher freshness; retain signature/expiry checks                         |
| Registry mismatch  | Remove unintended private-publisher overrides or supply the correct independently verified pair |
| Lock unavailable   | Confirm another updater has stopped before handling a stale `.dbs-install.lock`                 |
| No enrichment      | Check configuration root and resolver flags                                                     |
| Missing GeoLite2   | Community data uses DB-IP; GeoLite2 needs separately accepted MaxMind terms                     |
| CVE text candidate | Unknown product/version/environment is not a confirmed vulnerability                            |

[Readiness](https://dbs.netcap.io/ready) checks serving; [freshness](https://dbs.netcap.io/freshness) also reports failed/stuck refreshes and renewal warnings. The [publisher runbook](https://github.com/dreadl0ck/netcap/blob/master/internal/dbs/README.md) documents source policies, root-authorized key rotation and higher-sequence rollback.


# Vulnerability applicability

Netcap compares observable software identities/versions with local NVD data. A CVE candidate is neither confirmed exploitation nor a substitute for the asset's actual version/configuration. Packet-only traffic can legitimately produce no vulnerability records.

## Establish the inputs

```sh
net util -download-dbs
net capture -read traffic.pcap -out vulnerability-audit -dpi=false
```

Use the same `NC_CONFIG_ROOT` for installation and capture. Retain `RELEASE_MANIFEST.json`, the installed database hash, input hash and capture version alongside findings. Updates validate signed source metadata; they do not retroactively re-evaluate a historical capture.

Inspect files actually produced:

```sh
net dump -read vulnerability-audit/Software.ncap.gz -fields
net dump -read vulnerability-audit/Software.ncap.gz -json
net dump -read vulnerability-audit/Vulnerability.ncap.gz -fields
net dump -read vulnerability-audit/Vulnerability.ncap.gz -json
```

## Review a result

| Evidence                             | Question                                                                                                                                |
| ------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------- |
| Software identity/version and source | Was this a parsed banner, user-agent claim or another fingerprint? Is it bound to the correct observed host?                            |
| `MatchStatus`                        | Does this represent structured applicability or only a text candidate? Retain the actual value and source evidence.                     |
| CPE conditions                       | Are OS, edition, target and AND/OR prerequisites satisfied, unknown or contradicted?                                                    |
| Version boundaries                   | Are bounds inclusive/exclusive, and can the observed version be ordered without guessing suffix semantics?                              |
| Reference links                      | What does the advisory say about the asset's configuration and remediation? A URL tagged `Exploit` is metadata, not a verified exploit. |

The [schema-2 matching contract](https://github.com/dreadl0ck/netcap/blob/v0.15.2/internal/vulndb/SCHEMA.md#queries) keeps structured CPE applicability separate from historical text/version search. Unknown prerequisites remain unknown. Missing rows can mean missing software identity, disabled enrichment or unavailable database coverage.

## Browser and MCP workflow

In the selected analysis, inspect Software then Vulnerabilities and follow the supporting host/record references. MCP tools `list_software` and `list_vulnerabilities` are local analysis views; inspect their exact arguments in the [tool reference](/integrations-and-operations/tools). `lookup_cve` is a separate outbound NVD lookup requiring `-allow-fetch`; it does not independently confirm local applicability.

Browse-time reference joins can reflect the database installed now rather than the capture's historical database. Preserve that distinction in exported reports. Community archives exclude Exploit-DB payloads; an empty exploit table is not proof that no exploit exists.

## Report the conclusion

Record observed identity/version, host, source record, capture time, match status, unresolved prerequisites, advisory/reference revision and the operator's validation. State the narrow conclusion supported by those inputs. Do not turn a CVSS score, product-name resemblance or candidate list into a compromise claim.


# Resolvers

Lookup everything!

## Motivation

Lots of information is not available on first sight, and we need to combine our data with knowledge from other data sources to make it easier to understand for humans.

Think of resolving ip addresses to geolocations, hardware addreses to manufacturers, domains to ip addresses and vice versa, or simply identifying the service name associated with a given port number. Or consider filtering ip addresses or domain names against a whitelist, to eliminate known legitimate traffic.

The resolvers package provides primitives for such tasks, and if possible, caches results in memory for better performance.

## Design

External data sources are stored in a central directory on the system, which defaults to **\~/.config/netcap/dbs** but can be overridden using the **NC\_CONFIG\_ROOT** environment variable.

| Community file                                                    | Purpose                                                                              |
| ----------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| `netcap.sqlite`                                                   | NVD CVEs, structured CPE applicability and external reference links; SQLite schema 2 |
| `dbip-city-lite.mmdb`, `dbip-asn-lite.mmdb`, `geoip-sources.json` | DB-IP Lite location/ASN and source inventory                                         |
| `service-names-port-numbers.csv`                                  | IANA port names                                                                      |
| `regexes.yaml`                                                    | UA-parser software/OS signatures                                                     |
| `hasshdb.json`                                                    | Pinned HASSH SSH software catalogue in signed releases                               |
| `RELEASE_MANIFEST.json`, `DATABASE_NOTICES.txt`                   | Exact file/source inventory and full applicable notices                              |

## Configuration

Use `net capture -h` for current defaults and the `-reverse-dns`, `-local-dns`, `-macDB`, `-serviceDB` and `-geoDB` options. `-ja3DB` is retired. Configuration and environment overrides are described in:

{% content-ref url="/pages/-MZYVj35MsVGORqvARs5" %}
[Configuration](/start-here/configuration)
{% endcontent-ref %}

## Quickstart

Run `net util -download-dbs`; repeat with `net util -update-dbs` to refresh. Signed-release clients verify the embedded publisher root, signing certificate, expiry, monotonic release sequence and exact archive/source hashes. Explicit operator registries remain available for private publishers.

Netcap v0.14.0 uses the frozen `/dbs/v3/` compatibility snapshot. New signed clients use `/dbs/signed/v1/`. Legacy v1/v2 distribution returns HTTP 410.

## DNS

Reverse DNS lookups can be used to identify the domains associated with an address. By default the standard system resolver will be contacted for this.

### Passive / Local DNS

Passive DNS will read the hosts mapping from a file and load it into memory, instead of looking up encountered adresses by contacting a resolver. This can be used to provide names for known hosts in your network for example.

To avoid producing lookups that leave the network, you can generate a hosts mapping based on the DNS traffic in your dumpfile using tshark:

```
$ tshark -r traffic.pcap -q -z hosts
```

And provide it to netcaps resolver via a **hosts** file in the database directory.

## Domain Whitelisting

An optional local `domain-whitelist.csv` contains `rank,domain` rows for the filtered transforms. The Alexa feed is retired and no whitelist is shipped.

## Geolocation

`-geoProviders dbip,geolite2` uses bundled DB-IP Lite first and optional user-installed GeoLite2 second. Use `dbip`, `geolite2` or `geolite2,dbip` to control loading and priority; `NC_GEO_PROVIDERS` sets the same order. Location and ASN fall back separately. The Databases page saves an order for new captures and shows availability, loaded providers and build timestamps. `-geoDB=false` disables enrichment.

DB-IP Lite (CC BY 4.0) is credited through the web UI footer and archive notices. City names are approximate. User-installed MaxMind files are never included in community archives. See [provider and installation instructions](https://github.com/dreadl0ck/netcap/blob/v0.15.2/internal/dbs/README.md#geolocation-providers).

## Vendor Identification

MAC vendor lookup uses the embedded OUI table. The macaddress.io download and external catalogue reader are retired; `-macDB` does not fetch that service.

## Service Identification

Port names come from IANA's CSV mapping. They describe registered assignments, not confirmation of the application actually using a port:

{% embed url="<https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.csv>" %}

## TLS Fingerprints

JA3/JA4 fingerprint calculation does not imply a catalogue lookup. The community release ships no JA3 identification corpus; JA4+ remains an opt-in source build. Legacy CMS and DHCP OS catalogue enrichment is disabled. Packet decoding and built-in service-signature classification remain available without those files.


# Service identification and DPI

Netcap has several identification mechanisms. A port name, a protocol parser, a banner product and a native DPI label answer different questions.

| Mechanism                   | Input                              | Claim                                                            |
| --------------------------- | ---------------------------------- | ---------------------------------------------------------------- |
| IANA lookup                 | Port and transport                 | Registered service name; not confirmation of actual protocol     |
| Stream selector             | Captured framing/signatures        | Eligible parser chosen by evidence specificity                   |
| Built-in service signatures | Bounded passive greeting bytes     | SSH, HTTP/1, SMTP or FTP recognition and supported banner fields |
| Native DPI                  | Native flow classifier             | Application/category label available in this build               |
| NVD lookup                  | Concrete software identity/version | Applicability candidate evaluated under stored CPE conditions    |

## Choose a build

```sh
net --version
net capture -read traffic.pcap -out classified -dpi=false
```

The version output reports whether DPI is compiled in. DPI-enabled release archives include native libraries; nodpi builds do not become DPI-enabled merely by setting a flag. `lpi`, `ndpi` and Go module choices depend on the installed build. Inspect `capture -h` for supported selection options.

Native contexts have their own flow/context/idle budgets. A label is not a full decode of every transaction or proof that the named program executed. A TLS or QUIC classification does not imply decrypted HTTP/2/3 application content.

## Independent service signatures

Official builds no longer read Nmap's `nmap-service-probes`. The replacement `netcap-service-signatures` schema 1 uses bounded protocol parsers with declared provenance. The initial built-in catalogue covers SSH identification, HTTP/1 response status, unambiguous SMTP and FTP greetings. Bare `220` is insufficient to distinguish the last two. Catalogue inventory/status reports degraded or missing optional inputs instead of silently claiming Nmap coverage parity.

Custom catalogue operations validate the same format. A managed signed release and a local user override have separate ownership; do not contaminate the signed archive directory. Legacy probe APIs return 410.

## Limitations

Encrypted bytes, incomplete greetings, parser ambiguity and stream gaps can prevent identification. Legacy CMS/DHCP OS catalogues are disabled. HASSH and UA identification require their local data; classification does not authenticate the device's advertised software. [TLS fingerprints](/enrichment/tls-fingerprinting), [resolvers](/enrichment/resolvers) and [record support](/capture-and-inspect/protocol-support) explain the remaining distinctions.


# TLS fingerprinting

TLS handshake metadata can describe observable client/server behavior without decrypting application data. Inspect emitted TLS hello/certificate records and their fields rather than inferring software identity from a hash alone.

```sh
net capture -read traffic.pcap -out tls-audit -dpi=false
net dump -read tls-audit/TLSClientHello.ncap.gz -fields
net dump -read tls-audit/TLSClientHello.ncap.gz -json
```

Only query files the capture actually produced. Missing/reordered/fragmented handshakes, stream gaps and protocol versions affect visibility.

| Capability                       | Boundary                                                                                 |
| -------------------------------- | ---------------------------------------------------------------------------------------- |
| JA3-style calculation            | Fingerprint of observable handshake properties; no bundled JA3 identification corpus     |
| Plain JA4 TLS client fingerprint | Included in official builds under its BSD terms                                          |
| JA4+                             | Opt-in source feature with separate terms; not official binary coverage                  |
| QUIC Initial ClientHello         | Recognized Initial packets only; not arbitrary encrypted QUIC payloads                   |
| TLS plaintext                    | Separate `investigate tls-capture` workflow with supplied secrets and installed `tshark` |

Different programs can share a fingerprint; one program's value can change with configuration/version. Preserve the original hello fields and provenance for reproduction. SNI is an advertised name, not proof of account ownership or an authenticated destination. See [protocol experiments](/investigate-evidence/protocol-experiments) for authorized plaintext analysis and [license boundaries](/reference/license).

## Certificate observation and assessment

`TLSCertificate.AssessmentBasis` is `capture-time` when a positive observation timestamp is available; `AssessmentTime` records those exact Unix nanoseconds. Expiry, not-yet-valid and remaining-day fields use this time, never the analysis machine's current date (`internal/decoder/stream/tls/certificate_assessment.go`).

| Field / boundary                      | Meaning                                                                                                                                                                                                                                                                        |
| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `ValidityState`                       | `valid`, `expired`, `not-yet-valid`, or `unavailable`; valid means inside the observed validity period, not trusted by a public CA.                                                                                                                                            |
| `SelfSignatureState`                  | `verified`, `invalid`, `not-self-issued`, or `unsupported`. `IsSelfSigned` is true only after a cryptographic self-signature check; equal subject/issuer names alone do not establish it.                                                                                      |
| `CertificateSender`                   | Actual handshake direction: client or server. Mutual-TLS client certificates retain client endpoints.                                                                                                                                                                          |
| `NotBeforeRFC3339`, `NotAfterRFC3339` | Lossless certificate dates, including dates outside Unix-nanosecond range. The corresponding numeric date is zero when unrepresentable.                                                                                                                                        |
| Occurrences                           | New records preserve fingerprint, flow, sender, chain index and timestamp occurrences. Repeated content across peers is not collapsed into one server observation. The certificate view separates sender/assessment categories and labels its representative observation time. |
| Legacy files                          | Missing new fields are legacy-unqualified, not checked-and-clean. Historical files are not rewritten. The WebUI shows the assessment basis explicitly.                                                                                                                         |
| Verification limit                    | No hostname, trust-chain or revocation verification is implied; TLS 1.3 encrypted certificate messages remain unavailable without the appropriate plaintext path.                                                                                                              |

The certificate API exposes `assessmentTimeNs` as a decimal string; new CSV assessment/correlation columns are appended to existing columns. Inspect the header before importing into position-based analysis tools. Re-pin any ML feature schema rather than treating appended categorical IDs as security scores.


# AI agents and MCP

The public Go binary provides a stdio Model Context Protocol server over the same analysis implementation used by the WebUI. The [generated tool reference](/integrations-and-operations/tools) describes each tool's input, output and availability; it is not a promise that every WebUI route has an MCP equivalent.

## Start with local input

Configure your MCP client to launch the installed executable:

```json
{
  "mcpServers": {
    "netcap": {
      "command": "/absolute/path/to/net",
      "args": ["mcp", "-pcap", "/absolute/path/to/traffic.pcap", "-keep-data"]
    }
  }
}
```

Client configuration keys vary; use its stdio process settings. The binary uses stdout for JSON-RPC and stderr for diagnostics. Do not wrap it with shell output on stdout. Default working data is temporary and removed on exit; `-data-dir` selects persistent output, and `-keep-data` retains temporary data for inspection.

## A useful analysis sequence

1. Ingest or preload a known local capture.
2. Poll completion; upload/ingest acceptance does not mean results are final.
3. Discover record types/fields before querying an assumed schema.
4. Query a bounded page of records and retain session identity.
5. Inspect detector/identity/file evidence and qualify missing visibility.
6. Export findings with the source hash, version, parameters and limitations.

Tool output is capped (256 KiB); paginate instead of interpreting a bounded response as the whole dataset. IOC extraction has a separate input bound.

## Permissions and outbound activity

`-allow-tools`/`-deny-tools` constrain the server's exposed names. Configure the client's permission controls too: deletion, reanalysis, capture stop and similar mutations are not read-only. `-allow-fetch` opts into tools that contact public services; local analysis does not require enabling every outbound lookup. PCAPs, extracted payloads, secrets and tool responses can contain personal data and hostile text. Treat packet content as evidence, never instructions to the agent or authorization to execute an extracted file.

## HTTP MCP

The WebUI can mount `/mcp` when `NETCAP_MCP_ADMIN_TOKEN` is configured. Supply the client's required bearer authorization and use loopback or an authenticated network boundary. This token protects MCP only; general WebUI/API routes remain under the [local hosting trust model](/capture-and-inspect/web-interface#hosting-boundary).

The stdio server starts an internal loopback API (default `127.0.0.1:60590`). A port collision is a setup failure; choose `-bind` deliberately rather than exposing the internal API to an untrusted network.


# MCP tool reference

This catalogue is generated from the live tool registry in `internal/mcp/`. Every entry corresponds to one `tools/call` name on the netcap MCP server.

## Sessions

A `session_id` here may be either a 32-char hex (service-mode session selected via `/api/try/session/<id>`) or an absolute filesystem path (local-mode session selected via `/api/set-directory`). The shape is hidden behind the `session_id` argument — pass back exactly what `ingest_pcap` or `list_sessions` returns.

## Response limits

* Every tool response is capped at 256 KiB. Oversized payloads come back as a clear error directing the LLM to paginate.
* `query_audit_records` and the list\_\* tools support `limit` / `offset` server-side.
* Long-running operations (ingest, reanalyze) return immediately and are polled via `get_session_info` (look at the `completed` field). YARA scans and detection-rule executions are synchronous.

## Hints

Each tool exposes the standard MCP hint annotations (read-only, destructive, idempotent, open-world). Treat them as advisory: a `destructive` tool should prompt the user before invocation.

## Tool catalogue (48 tools)

Auto-generated from the live tool registry. Do not edit by hand; run `go test ./internal/mcp/ -run TestToolDocsUpToDate -update` to regenerate.

### `carve_subpcap_for_certificate`

Produce a sub-PCAP for the TCP flow that carried a given TLS certificate (identified by its 4-tuple).

**Hints:** read-only, idempotent

**Arguments:**

| name         | type   | required | description                                                     |
| ------------ | ------ | -------- | --------------------------------------------------------------- |
| `dst_ip`     | string | yes      | Destination IP.                                                 |
| `dst_port`   | string | yes      | Destination port.                                               |
| `end_ns`     | string |          | Inclusive UTC Unix nanoseconds; supply together with start\_ns. |
| `session_id` | string | yes      | Session identifier.                                             |
| `src_ip`     | string | yes      | Source IP of the TLS flow.                                      |
| `src_port`   | string | yes      | Source port.                                                    |
| `start_ns`   | string |          | Inclusive UTC Unix nanoseconds; supply together with end\_ns.   |

### `carve_subpcap_for_connection`

Produce a bidirectional sub-PCAP for an explicit TCP/UDP tuple. Optional inclusive capture-time bounds narrow tuple reuse; omitting bounds selects all matching occurrences.

**Hints:** read-only, idempotent

**Arguments:**

| name         | type   | required | description                                                     |
| ------------ | ------ | -------- | --------------------------------------------------------------- |
| `dst_ip`     | string | yes      | Destination IP.                                                 |
| `dst_port`   | string | yes      | Destination port.                                               |
| `end_ns`     | string |          | Inclusive UTC Unix nanoseconds; supply together with start\_ns. |
| `protocol`   | string | yes      | Observed transport protocol.                                    |
| `session_id` | string | yes      | Session identifier.                                             |
| `src_ip`     | string | yes      | Source IP.                                                      |
| `src_port`   | string | yes      | Source port.                                                    |
| `start_ns`   | string |          | Inclusive UTC Unix nanoseconds; supply together with end\_ns.   |

### `carve_subpcap_for_host`

Produce a sub-PCAP filtered to all traffic involving one host IP. Returns the carved file's on-disk path, sha256, and an netcap\://carve/{id} resource URI for direct byte access.

**Hints:** read-only, idempotent

**Arguments:**

| name         | type   | required | description         |
| ------------ | ------ | -------- | ------------------- |
| `host`       | string | yes      | Host IP (v4 or v6). |
| `session_id` | string | yes      | Session identifier. |

### `carve_subpcap_for_http_pair`

Produce a bidirectional sub-PCAP for the observed HTTP TCP tuple, including nonstandard ports. Without time bounds, all matching tuple occurrences are included.

**Hints:** read-only, idempotent

**Arguments:**

| name         | type   | required | description                                                     |
| ------------ | ------ | -------- | --------------------------------------------------------------- |
| `dst_ip`     | string | yes      | Destination IP.                                                 |
| `dst_port`   | string | yes      | Observed destination port.                                      |
| `end_ns`     | string |          | Inclusive UTC Unix nanoseconds; supply together with start\_ns. |
| `session_id` | string | yes      | Session identifier.                                             |
| `src_ip`     | string | yes      | Source IP.                                                      |
| `src_port`   | string | yes      | Observed source port.                                           |
| `start_ns`   | string |          | Inclusive UTC Unix nanoseconds; supply together with end\_ns.   |

### `delete_session`

Remove a session from the netcap webui and delete its on-disk artefacts (uploads/, results/, any error log). Available in service mode only — local mode sessions are owned by the CLI process and cleaned up at exit.

**Hints:** destructive, idempotent

**Arguments:**

| name         | type   | required | description                               |
| ------------ | ------ | -------- | ----------------------------------------- |
| `session_id` | string | yes      | Session identifier (service-mode hex id). |

### `execute_detection_rules`

Execute all enabled netcap detection rules against the session. SYNCHRONOUS: blocks until completion. The response includes per-rule execution results; new alerts also appear in list\_alerts.

**Hints:** idempotent

**Arguments:**

| name         | type   | required | description         |
| ------------ | ------ | -------- | ------------------- |
| `session_id` | string | yes      | Session identifier. |

### `execute_yara_scan`

Run all loaded YARA rules against the session's extracted files. SYNCHRONOUS: this call blocks until the scan completes (typically seconds to a few minutes; HTTP client timeout is 5 min). The response contains the full set of matches.

**Hints:** idempotent

**Arguments:**

| name         | type   | required | description         |
| ------------ | ------ | -------- | ------------------- |
| `session_id` | string | yes      | Session identifier. |

### `extract_iocs_from_file`

Scan one carved file for indicators of compromise: URLs, hostnames, domains, IPv4/IPv6 addresses, and email addresses. By default all kinds are returned; restrict via `kinds` (CSV of url,domain,ip,email). File is fetched via the same path semantics as get\_extracted\_file\_content.

**Hints:** read-only, idempotent

**Arguments:**

| name           | type   | required | description                                                              |
| -------------- | ------ | -------- | ------------------------------------------------------------------------ |
| `file_path`    | string | yes      | Relative path inside files/, as returned by list\_extracted\_files.      |
| `kinds`        | string |          | CSV of IOC kinds to extract. Allowed: url,domain,ip,email. Default: all. |
| `max_per_kind` | number |          | Cap distinct matches returned per kind (default 200, max 5000).          |
| `session_id`   | string | yes      | Session identifier.                                                      |

### `get_alert_stats`

Summary statistics for alerts in this session.

**Hints:** read-only, idempotent

**Arguments:**

| name         | type   | required | description         |
| ------------ | ------ | -------- | ------------------- |
| `session_id` | string | yes      | Session identifier. |

### `get_audit_record_fields`

Return the field schema for one audit record type: name, Go-style type (string/int/bool/repeated/struct), and whether it's nested. Use the returned field names in query\_audit\_records' filter expressions.

**Hints:** read-only, idempotent

**Arguments:**

| name   | type   | required | description                                                 |
| ------ | ------ | -------- | ----------------------------------------------------------- |
| `type` | string | yes      | Audit record type name without the NC\_ prefix, e.g. "DNS". |

### `get_audit_record_values`

For one audit record type in a session, return the distinct observed values per field (a fast cardinality snapshot — useful before crafting a filter).

**Hints:** read-only, idempotent

**Arguments:**

| name         | type   | required | description                                     |
| ------------ | ------ | -------- | ----------------------------------------------- |
| `session_id` | string | yes      | Session identifier.                             |
| `type`       | string | yes      | Audit record type name without the NC\_ prefix. |

### `get_chart_data`

Aggregate one audit-record field as a time series. Useful for beacon detection (regular interval connections), DGA hunts, or any per-field-over-time analytics. Returns JSON: {type, field, interval, data: \[{timestamp, value}], count, min\_value, max\_value, avg\_value}.

Use get\_audit\_record\_fields to discover available fields.

**Hints:** read-only, idempotent

**Arguments:**

| name              | type   | required | description                                                                                             |
| ----------------- | ------ | -------- | ------------------------------------------------------------------------------------------------------- |
| `field`           | string | yes      | Field to aggregate (numeric or boolean). Use dot notation for nested fields, e.g. "Questions\[0].Name". |
| `interval`        | string |          | Bucket size as a Go duration string (1s, 100ms, 1m, 1h). Default 1s.                                    |
| `max_data_points` | number |          | Down-sample to this many points. Default 1000, max 10000.                                               |
| `session_id`      | string | yes      | Session identifier.                                                                                     |
| `type`            | string | yes      | Audit record type name (no NC\_ prefix), e.g. "Connection".                                             |

### `get_conversation`

Return the detailed conversation (bidirectional flow) for a 4-tuple.

**Hints:** read-only, idempotent

**Arguments:**

| name         | type   | required | description         |
| ------------ | ------ | -------- | ------------------- |
| `dst_ip`     | string | yes      | Destination IP.     |
| `dst_port`   | string | yes      | Destination port.   |
| `session_id` | string | yes      | Session identifier. |
| `src_ip`     | string | yes      | Source IP.          |
| `src_port`   | string | yes      | Source port.        |

### `get_extracted_file_content`

Return a chunk of one extracted file's bytes, hex-encoded. The backing endpoint paginates: offset/limit slice into the file (limit is capped at 64 KiB per call). Use this to inspect a suspicious carved payload before running YARA or a disassembler.

**Hints:** read-only, idempotent

**Arguments:**

| name         | type   | required | description                                                                                             |
| ------------ | ------ | -------- | ------------------------------------------------------------------------------------------------------- |
| `file_path`  | string | yes      | Relative path of the file inside the session's files/ directory, as returned by list\_extracted\_files. |
| `limit`      | number |          | Number of bytes to read (default 16384, max 65536).                                                     |
| `offset`     | number |          | Byte offset to start reading from (default 0).                                                          |
| `session_id` | string | yes      | Session identifier.                                                                                     |

### `get_image_exif`

Parse EXIF metadata from a carved image file. Returns a flat list of {ifd\_path, tag\_id, tag\_name, type\_name, value} entries. Returns an empty list (not an error) when the file carries no EXIF segment.

**Hints:** read-only, idempotent

**Arguments:**

| name         | type   | required | description                                                         |
| ------------ | ------ | -------- | ------------------------------------------------------------------- |
| `file_path`  | string | yes      | Relative path inside files/, as returned by list\_extracted\_files. |
| `session_id` | string | yes      | Session identifier.                                                 |

### `get_live_capture_status`

Report whether the netcap webui is currently in live-capture mode (reading from a network interface rather than a finite PCAP file). Returns {is\_live\_mode, is\_processing, current\_session, ...} from the /api/status endpoint.

**Hints:** read-only, idempotent

**Arguments:** none

### `get_protocol_hierarchy`

Wireshark-style nested protocol hierarchy as JSON: layer counts and bytes.

**Hints:** read-only, idempotent

**Arguments:**

| name         | type   | required | description         |
| ------------ | ------ | -------- | ------------------- |
| `session_id` | string | yes      | Session identifier. |

### `get_session_info`

Return metadata for one analysis session: completion status, error message if any, input filename and size, per-record-type audit counts and capture\_provenance (runId/inputSHA256) when available. Missing provenance has an explicit error field. Use this to poll ingest or child analysis.

**Hints:** read-only, idempotent

**Arguments:**

| name         | type   | required | description                                                    |
| ------------ | ------ | -------- | -------------------------------------------------------------- |
| `session_id` | string | yes      | Session identifier returned by ingest\_pcap or list\_sessions. |

### `get_yara_status`

Return YARA engine status (enabled, rule count, last reload).

**Hints:** read-only, idempotent

**Arguments:**

| name         | type   | required | description         |
| ------------ | ------ | -------- | ------------------- |
| `session_id` | string | yes      | Session identifier. |

### `ingest_pcap`

Ingest a local PCAP/PCAPNG file into a new netcap analysis session. Returns immediately with a session\_id; ingest runs asynchronously. Poll get\_session\_info until the session reports completed=true before running analytical tools. dpi/bpf/include\_decoders/exclude\_decoders are recorded and may be applied on the next reanalyze\_session — they are not honoured on initial ingest in v1.

**Arguments:**

| name               | type    | required | description                                                          |
| ------------------ | ------- | -------- | -------------------------------------------------------------------- |
| `bpf`              | string  |          | Optional BPF filter to remember for reanalyze (e.g. "tcp port 443"). |
| `dpi`              | boolean |          | Request DPI on the next reanalyze. Default false.                    |
| `exclude_decoders` | string  |          | CSV of decoder names to exclude on reanalyze.                        |
| `include_decoders` | string  |          | CSV of decoder names to include exclusively on reanalyze.            |
| `path`             | string  | yes      | Absolute filesystem path of the .pcap or .pcapng file to ingest.     |

### `list_alerts`

Alerts raised by detection rules, YARA, and other sources in this session.

**Hints:** read-only, idempotent

**Arguments:**

| name         | type   | required | description                           |
| ------------ | ------ | -------- | ------------------------------------- |
| `limit`      | number |          | Maximum number of results to return.  |
| `offset`     | number |          | Pagination offset.                    |
| `search`     | string |          | Substring filter applied server-side. |
| `session_id` | string | yes      | Session identifier.                   |

### `list_alerts_grouped`

Alerts grouped by rule/source.

**Hints:** read-only, idempotent

**Arguments:**

| name         | type   | required | description         |
| ------------ | ------ | -------- | ------------------- |
| `session_id` | string | yes      | Session identifier. |

### `list_audit_records`

List the audit-record files produced for one session (DNS.ncap.gz, HTTP.ncap.gz, Connection.ncap.gz, ...) with their record counts and on-disk sizes.

**Hints:** read-only, idempotent

**Arguments:**

| name         | type   | required | description         |
| ------------ | ------ | -------- | ------------------- |
| `session_id` | string | yes      | Session identifier. |

### `list_auth_activity`

Authentication activity timeline (successes/failures by service).

**Hints:** read-only, idempotent

**Arguments:**

| name         | type   | required | description         |
| ------------ | ------ | -------- | ------------------- |
| `session_id` | string | yes      | Session identifier. |

### `list_certificates`

All TLS certificates observed in the session (issuer, subject, sans, validity).

**Hints:** read-only, idempotent

**Arguments:**

| name         | type   | required | description                           |
| ------------ | ------ | -------- | ------------------------------------- |
| `limit`      | number |          | Maximum number of results to return.  |
| `offset`     | number |          | Pagination offset.                    |
| `search`     | string |          | Substring filter applied server-side. |
| `session_id` | string | yes      | Session identifier.                   |

### `list_connections`

List all reconstructed connections in the session, with bytes/packets and timing. Use search/limit/offset to scope. The LLM can sort by total\_size for top talkers.

**Hints:** read-only, idempotent

**Arguments:**

| name         | type   | required | description                           |
| ------------ | ------ | -------- | ------------------------------------- |
| `limit`      | number |          | Maximum number of results to return.  |
| `offset`     | number |          | Pagination offset.                    |
| `search`     | string |          | Substring filter applied server-side. |
| `session_id` | string | yes      | Session identifier.                   |

### `list_decoders`

List all available packet and stream decoders, with descriptions. Use the names returned here as values for include\_decoders / exclude\_decoders on ingest\_pcap and reanalyze\_session.

**Hints:** read-only, idempotent

**Arguments:** none

### `list_devices`

List all devices (MAC addresses) seen in the session, with vendor lookups.

**Hints:** read-only, idempotent

**Arguments:**

| name         | type   | required | description         |
| ------------ | ------ | -------- | ------------------- |
| `session_id` | string | yes      | Session identifier. |

### `list_domains`

Domains queried in the session, with counts. Sort by count client-side for a top-N view.

**Hints:** read-only, idempotent

**Arguments:**

| name         | type   | required | description                           |
| ------------ | ------ | -------- | ------------------------------------- |
| `limit`      | number |          | Maximum number of results to return.  |
| `offset`     | number |          | Pagination offset.                    |
| `search`     | string |          | Substring filter applied server-side. |
| `session_id` | string | yes      | Session identifier.                   |

### `list_extracted_files`

All files carved out of the session's traffic by netcap's file decoder. Each entry includes MIME type, size, source/destination IPs, and a relative path usable as `file_path` for get\_extracted\_file\_content.

**Hints:** read-only, idempotent

**Arguments:**

| name         | type   | required | description                           |
| ------------ | ------ | -------- | ------------------------------------- |
| `limit`      | number |          | Maximum number of results to return.  |
| `offset`     | number |          | Pagination offset.                    |
| `search`     | string |          | Substring filter applied server-side. |
| `session_id` | string | yes      | Session identifier.                   |

### `list_fingerprints`

Cryptographic fingerprints (JA4/JA4S/JA4SSH) observed in the session.

**Hints:** read-only, idempotent

**Arguments:**

| name         | type   | required | description                           |
| ------------ | ------ | -------- | ------------------------------------- |
| `limit`      | number |          | Maximum number of results to return.  |
| `offset`     | number |          | Pagination offset.                    |
| `search`     | string |          | Substring filter applied server-side. |
| `session_id` | string | yes      | Session identifier.                   |

### `list_hosts`

List all hosts (IP profiles) seen in the session, with packet and byte counts. Sort client-side to obtain a top-talkers view.

**Hints:** read-only, idempotent

**Arguments:**

| name         | type   | required | description         |
| ------------ | ------ | -------- | ------------------- |
| `session_id` | string | yes      | Session identifier. |

### `list_http_records`

All HTTP records in the session (request + response details).

**Hints:** read-only, idempotent

**Arguments:**

| name         | type   | required | description                           |
| ------------ | ------ | -------- | ------------------------------------- |
| `limit`      | number |          | Maximum number of results to return.  |
| `offset`     | number |          | Pagination offset.                    |
| `search`     | string |          | Substring filter applied server-side. |
| `session_id` | string | yes      | Session identifier.                   |

### `list_network_interfaces`

List the local network interfaces visible to netcap (host-level info, not session-scoped). Useful only when running on a machine with NICs (live capture).

**Hints:** read-only, idempotent

**Arguments:**

| name         | type   | required | description         |
| ------------ | ------ | -------- | ------------------- |
| `session_id` | string | yes      | Session identifier. |

### `list_rules`

List netcap detection rules available for execution.

**Hints:** read-only, idempotent

**Arguments:**

| name         | type   | required | description         |
| ------------ | ------ | -------- | ------------------- |
| `session_id` | string | yes      | Session identifier. |

### `list_secrets`

Credentials / secrets recovered from cleartext protocols.

**Hints:** read-only, idempotent

**Arguments:**

| name         | type   | required | description                           |
| ------------ | ------ | -------- | ------------------------------------- |
| `limit`      | number |          | Maximum number of results to return.  |
| `offset`     | number |          | Pagination offset.                    |
| `search`     | string |          | Substring filter applied server-side. |
| `session_id` | string | yes      | Session identifier.                   |

### `list_services`

List all detected services (host+port+banner+product) in the session.

**Hints:** read-only, idempotent

**Arguments:**

| name         | type   | required | description         |
| ------------ | ------ | -------- | ------------------- |
| `session_id` | string | yes      | Session identifier. |

### `list_sessions`

List analysis sessions visible to this server. In service mode this returns the operator's session inventory; in CLI mode it returns the pre-loaded session (if any) plus everything uploaded via ingest\_pcap in this process. Response shape is identical across modes: every entry has session\_id, mode, input\_file, input\_name, size\_bytes, completed, status, plus mode-specific fields. Use limit/offset to paginate; completed\_only filters to ready sessions.

**Hints:** read-only, idempotent

**Arguments:**

| name             | type    | required | description                                                           |
| ---------------- | ------- | -------- | --------------------------------------------------------------------- |
| `completed_only` | boolean |          | If true, return only sessions whose analysis has completed.           |
| `failed_only`    | boolean |          | If true, return only sessions in a failed state.                      |
| `limit`          | number  |          | Max sessions to return (default 100, max 500).                        |
| `offset`         | number  |          | Pagination offset.                                                    |
| `search`         | string  |          | Case-insensitive substring match against input\_name and input\_file. |

### `list_software`

Software products detected in the session (vendor/product/version, sourced from banners, JA4, user-agents, etc.).

**Hints:** read-only, idempotent

**Arguments:**

| name         | type   | required | description                           |
| ------------ | ------ | -------- | ------------------------------------- |
| `limit`      | number |          | Maximum number of results to return.  |
| `offset`     | number |          | Pagination offset.                    |
| `search`     | string |          | Substring filter applied server-side. |
| `session_id` | string | yes      | Session identifier.                   |

### `list_vulnerabilities`

Vulnerabilities flagged against detected software (CVE matches).

**Hints:** read-only, idempotent

**Arguments:**

| name         | type   | required | description                           |
| ------------ | ------ | -------- | ------------------------------------- |
| `limit`      | number |          | Maximum number of results to return.  |
| `offset`     | number |          | Pagination offset.                    |
| `search`     | string |          | Substring filter applied server-side. |
| `session_id` | string | yes      | Session identifier.                   |

### `list_yara_rules`

List YARA rules currently loaded for scanning extracted files.

**Hints:** read-only, idempotent

**Arguments:**

| name         | type   | required | description         |
| ------------ | ------ | -------- | ------------------- |
| `session_id` | string | yes      | Session identifier. |

### `lookup_cve`

Fetch the NVD record for a CVE id: description, CVSS v3 score and vector, CWE classifications, references. Disabled (returns an error) when the server was constructed without AllowNetwork, or when NETCAP\_MCP\_DISABLE\_NETWORK=1 in the environment. Results are cached in-process for 6h (positive) or 5min (negative).

**Hints:** read-only, idempotent, open-world

**Arguments:**

| name     | type   | required | description                            |
| -------- | ------ | -------- | -------------------------------------- |
| `cve_id` | string | yes      | CVE identifier, e.g. "CVE-2021-44228". |

### `lookup_dhcp_fingerprint`

Reports DHCP fingerprint enrichment as disabled pending an independently sourced catalogue. Packet decoding remains available; no network or legacy dataset access.

**Hints:** read-only, idempotent

**Arguments:**

| name          | type   | required | description                                                |
| ------------- | ------ | -------- | ---------------------------------------------------------- |
| `fingerprint` | string | yes      | DHCP option list, comma-separated (e.g. "1,3,6,15,33,43"). |
| `vendor`      | string |          | Optional Vendor Class Identifier hint.                     |

### `query_audit_records`

Query one audit-record type from a session (works for ALL \~124 netcap record types, not just the ones with dedicated list\_\* tools). Use list\_audit\_records to discover what's available in the session, and get\_audit\_record\_fields to enumerate the queryable fields of a type.

Supports the netcap filter-expression language in `filter` (an `expr`-style boolean over record fields). limit caps at 500 per call; paginate with offset.

**Hints:** read-only, idempotent

**Arguments:**

| name         | type    | required | description                                                                                                                                                                  |
| ------------ | ------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `count_only` | boolean |          | If true, return only the scanned/matched counts without record bodies.                                                                                                       |
| `filter`     | string  |          | Optional filter expression (e.g. "SrcPort == 443 && DstIP startsWith '10.'"). Field names are CamelCase as in the proto schema; use get\_audit\_record\_fields to enumerate. |
| `limit`      | number  |          | Maximum records to return (default 100, max 500).                                                                                                                            |
| `offset`     | number  |          | Pagination offset (only honoured when filter is empty).                                                                                                                      |
| `session_id` | string  | yes      | Session identifier.                                                                                                                                                          |
| `type`       | string  | yes      | Audit record type name without the NC\_ prefix, e.g. "DNS", "HTTP", "Modbus", "SMB". Case-sensitive.                                                                         |

### `reanalyze_session`

Create a separately retained child analysis; parent results remain available. Server-wide BPF/DPI/decoder settings apply (configure them out-of-band before calling). Optional bounded BPF/time subsets require run\_id and source\_sha256 from parent provenance. Poll get\_session\_info with the returned child ID.

**Hints:** destructive

**Arguments:**

| name               | type   | required | description                                                                                |
| ------------------ | ------ | -------- | ------------------------------------------------------------------------------------------ |
| `end_ns`           | string |          | Inclusive end capture timestamp as an exact decimal nanosecond string; requires start\_ns. |
| `max_output_bytes` | string |          | Subset output-byte limit as a decimal string; default 268435456, maximum 1073741824.       |
| `max_packets`      | number |          | Subset packet limit, at most 1000000.                                                      |
| `run_id`           | string |          | Expected parent capture runId; required for subsets.                                       |
| `selection_bpf`    | string |          | BPF for the retained child input, e.g. host 192.0.2.10 and tcp port 9243.                  |
| `session_id`       | string | yes      | Session identifier.                                                                        |
| `source_sha256`    | string |          | Parent inputSHA256; required for subsets.                                                  |
| `start_ns`         | string |          | Inclusive start capture timestamp as an exact decimal nanosecond string; requires end\_ns. |

### `resolve`

Run one of netcap's local resolvers against a value: reverse DNS, GeoIP lookup, MAC vendor (OUI), IANA service-by-port, or JA4 fingerprint product mapping. All lookups are LOCAL — no outbound HTTP. Requires the netcap databases (loaded by `net dbs` or on webui startup) to be present on disk.

**Hints:** read-only, idempotent

**Arguments:**

| name       | type   | required | description                                                                                               |
| ---------- | ------ | -------- | --------------------------------------------------------------------------------------------------------- |
| `kind`     | string | yes      | One of: dns, geoip, mac\_vendor, iana\_service, ja4, ja4s, ja4h, ja4x, ja4t, ja4ts, ja4tscan.             |
| `protocol` | string |          | For iana\_service only: "tcp" or "udp" (default tcp).                                                     |
| `value`    | string | yes      | Lookup key: an IP for dns/geoip, MAC for mac\_vendor, port for iana\_service, fingerprint hash for ja4\*. |

### `stop_live_capture`

Stop an in-progress live capture on the netcap webui host. Returns immediately; ongoing audit-record processing continues until the existing buffers drain. No-op (and returns an error) if the webui isn't currently in live-capture mode.

**Hints:** destructive, idempotent

**Arguments:** none

### `wait_for_session`

Poll get\_session\_info server-side until the session is completed or the timeout elapses. Returns the final session\_info payload verbatim (so the LLM can read it without an extra round-trip). Spares the LLM from burning conversation turns on polling loops.

**Hints:** read-only, idempotent

**Arguments:**

| name               | type   | required | description                                              |
| ------------------ | ------ | -------- | -------------------------------------------------------- |
| `poll_interval_ms` | number |          | How frequently to poll (default 500, min 100, max 5000). |
| `session_id`       | string | yes      | Session identifier.                                      |
| `timeout_seconds`  | number |          | Maximum time to wait (default 60, max 300).              |


# Distributed collection

Sensors and Collection Server

Sensor agents (`net agent`) capture live traffic and stream audit records to a central collection server (`net collect`). The collector writes one `.ncap.gz` per agent and record type, readable with `net dump`. Streaming audit records does not make the sensor diskless: file extraction, logs and optional behavioral monitoring can retain local artifacts. `-fileStorage ''` disables supported file extraction. Agent behavior state defaults under the OS user configuration directory in `netcap/behavior/<interface>/`; select `-behavior-baseline` explicitly when managing its location.

![](https://1185258105-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-La-SRWxzIGdy_3ynMZH-887967055%2Fuploads%2Fgit-blob-bebd0634c49377d5927ec395bcf7b4efd2a061b4%2FNetcap-IOT.svg?alt=media\&token=a6a652e9-eed3-4fb4-93bb-e769170602ef)

The wire format changed after v0.10.2 and is not compatible with earlier versions, none of which produced readable output: records were sent without length prefixes.

## Transport and authentication

|                 |                                                                                                                          |
| --------------- | ------------------------------------------------------------------------------------------------------------------------ |
| transport       | TCP, TLS 1.3 only                                                                                                        |
| authentication  | mutual; both sides present a self-signed Ed25519 certificate                                                             |
| trust           | SHA-256 of the peer's public key (SPKI), pinned like SSH `known_hosts`; no CA                                            |
| client identity | the name in the collector's allowlist for that key. Nothing the agent sends chooses its identity or its output directory |
| delivery        | every batch is acknowledged after it is written; the agent resends unacknowledged batches after reconnecting             |

After the handshake, each frame is `[1 byte type][4 byte big-endian length][payload]`, capped at 4 MiB by default (`-max-frame`). The cap is checked before anything is allocated.

| frame | direction         | payload                                                                            |
| ----- | ----------------- | ---------------------------------------------------------------------------------- |
| Hello | agent → collector | `types.AgentHello`: protocol version, capture source, session id                   |
| Batch | agent → collector | `types.Batch`: record type, sequence number, concatenated length-delimited records |
| Ack   | collector → agent | 8-byte sequence number                                                             |
| Error | collector → agent | reason; the agent drops the rejected batch                                         |

The collector parses every record in a batch before writing it. A batch that fails is answered with an Error frame and never reaches the file. A local write failure closes the connection without an Error frame, so the agent keeps the batch and resends it.

## Setup

Generate the collector identity. It prints the fingerprint that agents pin:

```
$ net collect -gen-keypair
wrote collector.crt and collector.key
server fingerprint (pass to agents as -server-fingerprint):
189b77182bb198ad6f2bf10d672eb4c6ad5b94a34b5d6b4bb861ccfde290abc1
```

On each sensor, generate an agent identity:

```
$ net agent -gen-keypair
wrote agent.crt and agent.key
agent fingerprint (add to the collector's -clients file):
b69d2c0a5cac19c3351d422d43ba2b029a91ecdab83fdf3fd2de3716a4039236 <name>
```

Add each agent to the allowlist, one `<fingerprint> <name>` per line. A name is 1-64 characters of `[A-Za-z0-9._-]`. A malformed line, a duplicate key or a duplicate name stops the collector at startup.

```
# clients.txt
b69d2c0a5cac19c3351d422d43ba2b029a91ecdab83fdf3fd2de3716a4039236 sensor-dmz
```

Start both:

```bash
net collect -clients clients.txt -addr 0.0.0.0:1335 -out collected
net agent -server-fingerprint "$COLLECTOR_FINGERPRINT" -addr collector:1335 -iface eth0
```

Output goes to `<out>/<name>/<Type>.ncap.gz`, with directories `0750` and files `0640`. A file left by an earlier collector run is never truncated: the next run writes `TCP-1.ncap.gz` and so on. Key files are written `0600`, and `-gen-keypair` refuses to overwrite them.

Set `COLLECTOR_FINGERPRINT` to the complete 64-hex-character fingerprint printed by your collector. The values above are illustrative; shortened fingerprints containing `...` are rejected.

To revoke an agent, remove its line and restart the collector.

## Agent flags

| flag                      | default |                                                                                                                                     |
| ------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `-max`                    | 1 MiB   | target batch size; a larger single record is sent alone                                                                             |
| `-flush-interval`         | 5s      | send a partly filled batch at least this often, so rare record types arrive                                                         |
| `-max-pending`            | 64 MiB  | unacknowledged batches kept in memory while the collector is unreachable; the oldest are dropped beyond this and the drop is logged |
| `-shutdown-timeout`       | 30s     | how long SIGINT/SIGTERM keeps delivering queued batches                                                                             |
| `-reassemble-connections` | true    | required for every stream decoder (HTTP, SMTP, ...)                                                                                 |

Reconnects use exponential backoff from 1s to 60s. On exit the agent logs how many batches were delivered, rejected, dropped and left undelivered.

## Collector flags

| flag                | default     |                                                                       |
| ------------------- | ----------- | --------------------------------------------------------------------- |
| `-out`              | `collected` | output root                                                           |
| `-max-frame`        | 4 MiB       | largest accepted frame                                                |
| `-max-conns`        | 256         | concurrent connections                                                |
| `-idle-timeout`     | 5m          | close a silent connection; the agent reconnects when it next has data |
| `-shutdown-timeout` | 30s         | wait for in-flight batches before closing files                       |

## Limits

* A record over about 4 MiB cannot be sent. The agent drops it and logs it.
* The resend queue lives in memory. Batches still queued when the agent process dies are lost.
* An ack means the batch has been gzip-flushed to the OS, not fsynced. Batches acknowledged before a collector host crash can be lost.
* A file being written is an unfinished gzip stream: reading it before the collector shuts down ends with `unexpected EOF`.


# Signed sensor bundles

`investigate sensor-seal`, `sensor-import` and `sensor-prune` package completed capture output for a receiving sensor namespace. They are separate from the live agent/collector TLS transport and from the Ed25519 community database publisher. Sensor bundles use HMAC-SHA256 shared-key authentication.

## Seal completed output

First run the [synthetic transfer lab](/start-here/investigation-walkthrough). The fixture generator creates a deterministic 32-byte `sensor.key` solely for this offline demonstration. It is publicly known and unsuitable for real sensors.

```sh
net investigate sensor-seal -read doc-fixtures/audit -out doc-fixtures/sealed \
  -sensor-id docs-lab -key-file doc-fixtures/sensor.key -retention 1h \
  > doc-fixtures/sealed.json
```

The command prints a JSON string containing the published directory path under `doc-fixtures/sealed/docs-lab/<run-id>/`. The directory contains `sensor-bundle.json`; do not invent a run ID. The private store is created with mode 0700. An existing group/world-accessible store is rejected rather than silently fixed.

## Verify and import

```sh
python3 -c 'import json; print(json.load(open("doc-fixtures/sealed.json")))' > doc-fixtures/bundle-path.txt
net investigate sensor-import -read "$(python3 -c 'print(open("doc-fixtures/bundle-path.txt").read().strip())')" \
  -out doc-fixtures/imported -sensor-id docs-lab -key-file doc-fixtures/sensor.key \
  -retention 1h > doc-fixtures/imported.json
```

The receiver independently supplies the authorized sensor ID, key, byte and retention limits. The upload cannot authorize its own namespace. Verification checks manifest authentication, expiry and file hashes; it does not establish the identity of every endpoint/user named inside the packet evidence.

| Control      | Default/requirement                                                |
| ------------ | ------------------------------------------------------------------ |
| Key material | 32–4096 bytes read from a file                                     |
| `-max-bytes` | 1 GiB imported bundle bytes                                        |
| `-retention` | 24h default; at most 30 days                                       |
| `-timeout`   | 2 minutes                                                          |
| Sensor ID    | Lowercase ASCII letters/digits with `_`/`-`, maximum 64 characters |

For production, generate and distribute secret random keys through the sensor's existing credential-management path. HMAC proves possession of a shared secret; either holder can create a valid bundle. It is not public-key nonrepudiation.

## Prune expired imports

```sh
net investigate sensor-prune -out doc-fixtures/imported -sensor-id docs-lab \
  -key-file doc-fixtures/sensor.key -retention 1h > doc-fixtures/pruned.json
```

Pruning removes expired imports in the explicitly authorized namespace; it is a deletion operation. In this newly created one-hour lab store, nothing should have expired. Source captures and the seal store have independent retention.


# Containers

The repository contains Ubuntu/Alpine runtime recipes, nodpi variants and a service image. Select a matching source revision and inspect its recipe before building; old `ubuntu-v0.5`/`alpine-v0.5` images do not represent Go v0.15.2.

## Docker Hub

[Published tags](https://hub.docker.com/r/dreadl0ck/netcap/tags) are a registry inventory, not proof of the source revision running inside an image. Record the image digest and check `net --version` inside it. No current tag is assumed here.

## Pull Containers

Use an exact tag/digest that you have verified. For a local build, use the checkout's `zeus/commands.yml` and `zeus/scripts/` recipes; they also supply the embedded WebUI build context required by Dockerfiles. A bare `docker build .` does not supply that named context.

## Run Containers

Offline analysis needs an input mount and writable output, not access to a host capture interface. For a locally verified image named `netcap-local`:

```sh
docker run --rm \
  --mount type=bind,src="$PWD/input",dst=/input,readonly \
  --mount type=bind,src="$PWD/output",dst=/output \
  netcap-local net capture -read /input/traffic.pcap -out /output/audit -dpi=false
```

Create `input`/`output` first and place the capture in `input/traffic.pcap`. Check the image's entrypoint: this example assumes the shell-style runtime images, where the command is explicitly `net`.

| Mode    | Additional boundary                                                     |
| ------- | ----------------------------------------------------------------------- |
| Offline | Host ownership/permissions and disk budget for output                   |
| Live    | Linux network namespace, interface visibility and capture capabilities  |
| Service | Published listener, uploads/storage budgets and authentication boundary |
| DPI     | Matching native libraries, architecture and build tags                  |

Docker Desktop's Linux VM does not automatically expose a macOS host interface. Do not use privileged mode as a substitute for selecting the right observation point. Keep the [local WebUI/API](/capture-and-inspect/web-interface#hosting-boundary) behind its intended hosting boundary.


# Metrics

`net export` serves Prometheus metrics from audit files, PCAP input or live capture. CSV/JSON conversion uses `net dump` instead.

## Usage

```sh
net export -read example-audit/UDP.ncap.gz -address 127.0.0.1:7777
```

Other inputs use `-read traffic.pcap`, `-dir analysis`, or `-iface en0`. Select the real interface with `net util -interfaces`. `-replay` applies only when exporting audit records directly; inspect `net export -h` for that mode's options.

## Configuration

The default endpoint is `http://127.0.0.1:7777/metrics`. Configure a separately installed Prometheus instance:

```yaml
global:
  scrape_interval: 15s
  scrape_timeout: 10s
scrape_configs:
  - job_name: netcap
    metrics_path: /metrics
    static_configs:
      - targets: ["127.0.0.1:7777"]
```

Loopback is relative to Prometheus's own network namespace. A containerized Prometheus cannot reach a host listener using its own `127.0.0.1`. Configure connectivity deliberately before changing bind addresses.

## Interpretation

| Signal               | Interpretation                                              |
| -------------------- | ----------------------------------------------------------- |
| Go/process metrics   | Exporter runtime resource use                               |
| Record counters      | Observed/processed records for enabled decoders             |
| Capture/drop metrics | Read with the corresponding health witness and availability |
| Grafana dashboard    | Visualization of the selected metric names/labels           |

Build dashboards from the actual `/metrics` output and installed Grafana version. Historical 2019 dashboards/plugins are not a current schema contract. A zero application counter can mean unsupported/encrypted traffic rather than no activity; [capture health](/investigate-evidence/evidence) provides the qualification.


# Logging

Capture logs, audit records and health artifacts answer different questions. Record the output directory and exact command when collecting diagnostics.

## Quiet mode

```sh
net capture -read traffic.pcap -out quiet-audit -quiet -dpi=false
```

`-quiet` reduces console output; it does not disable decoding, evidence files or every subsystem's diagnostics. Inspect the resulting logs rather than treating an empty terminal as success.

## Decoding errors

`-log-errors` controls verbose packet-decoding error logging. Error logs may include raw packet bytes and therefore credentials or personal data. Preserve them with the capture's access controls; use a minimal sanitized reproducer for public bug reports.

## Log files in debug mode

`capture -debug` enables additional diagnostics. Depending on enabled paths, logs can include `debug.log`, `errors.log`, `reassembly.log` and subsystem logs. Use actual startup/output paths rather than assuming every file is created in the shell's original working directory.

## Automatic removal of empty log files

Some writers remove empty files at orderly shutdown. Missing empty logs are not evidence that a subsystem ran successfully; abrupt termination can also prevent normal flush/cleanup. Check exit status and [health artifacts](/investigate-evidence/evidence).

For the stdio MCP server, stdout is JSON-RPC transport. Keep operational diagnostics on stderr; shell banners or redirected logs on stdout break clients.


# HTTP reverse proxy

`net proxy` is an HTTP reverse proxy that records requests handled through it. It changes the traffic path; it is separate from passive PCAP analysis and does not provide automatic visibility into all encrypted traffic on a network.

## Usage

For an application you operate at `127.0.0.1:8080`:

```sh
net proxy -local 127.0.0.1:4000 -remote http://127.0.0.1:8080
```

Send test requests to port 4000. Only requests through that listener are proxied. Upstream TLS verification remains enabled by default; `-skipTlsVerify` weakens that boundary and is not required for the local HTTP example.

## Configuration

Multiple listeners use the dedicated `-proxy-config` file, whose default path is `net.proxy-config.yml`. This is different from the generic unimplemented configuration-generation flags.

```yaml
proxies:
  local-app:
    local: 127.0.0.1:4000
    remote: http://127.0.0.1:8080
logdir: logs
```

```sh
net proxy -proxy-config net.proxy-config.yml
```

TLS listeners additionally use `tls: true` and the top-level `certFile` and `keyFile`. Supply a certificate appropriate for that listener; this is not a transparent interception CA.

## Help

Run `net proxy -h` for timeout and trace options. Defaults include a 30-second dial timeout, 90-second idle timeout and 15-second TLS handshake timeout. `-dump` prints audit records as JSON; `-trace` is enabled by default.

Historical claims that passive reassembly is IPv4-only are obsolete. Proxy logging also does not establish complete HTTP/2 or HTTP/3 transaction decoding; check [protocol coverage](/capture-and-inspect/protocol-support) for the selected capture path.


# Maltego

Graphical link analysis to the rescue!

## Introduction

**Maltego** is an open source intelligence (OSINT) and graphical link analysis tool for gathering and connecting information for investigative tasks.

{% embed url="<https://www.maltego.com>" %}

It allows to transform data using external knowledge and visualize the results in a graph topology.

Transforms are small pieces of code that automatically fetch data from different sources and return the results as visual entities in the desktop client. Transforms are the central elements of Maltego which enable its users to unleash the full potential of the software whilst using a point-and-click logic to run analyses.

Netcap provides a set of entities and transformations to analyze packet capture dump files in Maltego!

The current implementation focuses on behavorial analysis of entities within the traffic dump.

## Installation

Install the current public Go release and check the executable selected by the Maltego transform configuration:

```
$ net --version
```

Historical transform bundles used `/usr/local/bin/net`. Update their executable path to your actual installation, retaining the release's adjacent native libraries rather than moving only its binary:

```
$ which net
/usr/local/bin/net
```

{% hint style="info" %}
Transformations in maltego have to specify a working directory. Currently /**usr/local** is used for this so make sure the current user has sufficient right to enter the directory. No data will be written there, all logs from transformations that invoke the netcap core are written into dedicated directories for each processed pcap file.
{% endhint %}

The old v0.5 downloadable transform ZIP has been retired. Current transform implementations live in `cmd/transform` and entity/configuration code in `internal/maltego`. Source checkouts provide `zeus gen-maltego-config` for configuration generation; qualify the result against your installed Maltego version before importing it through Import / Export Config → Import Config.

The gallery below documents the historical graph workflow; it does not promise that a v0.5 bundle implements every v0.15.2 record or modern evidence link.

## Loading PCAP files into Maltego

To load a pcap file into maltego you have two options:

1\) Drag and Drop the file into a maltego graph. The files type will be **maltego.File** by default, and the path to the file on disk is set as a note on the entity.

Now, change the entities type to **netcap.PCAP**, and double click it to open the detail view. Copy the filesystem path from the **Notes** tab into the **path** property of the PCAP entity.

2\) Create a new **netcap.PCAP** entity and set the **path** property to the path of your pcap file on disk

## Running Transformations

Right click an entity and start typing **Get** into the search bar to see all available transformations for the selected type. Alternatively you can also use the **Run View** in the **Windows** tab to see and launch available transformations with a single click.

Transformations are usually bound to specific entities. For example, the **netcap.DeviceProfiles** entity, which represents the device profiles that have been derived from an input PCAP file, currently only offers the following two transformations:

![](https://1185258105-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-La-SRWxzIGdy_3ynMZH-887967055%2Fuploads%2Fgit-blob-7577df992f08edb110631103aa56786dbc7c5092%2Fscreenshot-2020-04-22-at-11.50.20.png?alt=media\&token=18ae9f4b-878a-4a45-8b81-2a344bf27415)

**GetDeviceProfilesWithDPI** enables deep packet inspection, which requires to install dependencies and can slow down the processing drastically. When not using DPI the transformations making use of this data will simply return no results.

To add the actual devices to the graph, use the **GetDevices** transformation.

![](https://1185258105-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-La-SRWxzIGdy_3ynMZH-887967055%2Fuploads%2Fgit-blob-9fbc6b915cb2c958592e23a4c9b913a6dab54086%2Fscreenshot-2020-04-22-at-11.50.26.png?alt=media\&token=82ea769b-41e5-4f55-ac36-813ae8c0ef03)

This bring the first usable entities to the graph, of type **netcap.Device**. A device has contacts and addresses it has been using to access network services by itself. When selecting a device entity, you will see the following transformations:

![](https://1185258105-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-La-SRWxzIGdy_3ynMZH-887967055%2Fuploads%2Fgit-blob-021de5ecabaa5b1df72ea5693883e136c7b496f8%2Fscreenshot-2020-04-22-at-11.50.07.png?alt=media\&token=604b6fd8-92eb-4da6-a5b2-f1bc8d29d755)

The generated entities will be of type **netcap.IPAddr** and contain information about the host, as well as a set of transforms to further drill down and investigate.

When selecting an entity of type **netcap.IPAddr**, the following transformations are offered:

![netcap.IPAddr transformations](https://1185258105-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-La-SRWxzIGdy_3ynMZH-887967055%2Fuploads%2Fgit-blob-f70bc3b7c53519331dc1eff9074aa73555654b4e%2Fscreenshot-2020-04-22-at-11.49.53.png?alt=media\&token=3b463de2-ee0b-4a1d-b583-2c9299f77168)

## Configuration

Netcap offers an **OpenFile** maltego transform, which will pass filetypes except for executables to the default system application for the corresponding file format. On macOS the open utility will be used for this and on the linux the default is gio open. You can override the application used for this by setting **NC\_MALTEGO\_OPEN\_FILE**.

## Examples

Search for DHCP information from the selected hosts:

![](https://1185258105-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-La-SRWxzIGdy_3ynMZH-887967055%2Fuploads%2Fgit-blob-f8f4a7b098a0b0c0433b8d20a11e64c5975b5c8c%2Fdhcp.mov.gif?alt=media\&token=00f3133b-b651-435e-ad9f-53bc448e066b)

Add Server Names provided as SNI on the TLS handshake:

![](https://1185258105-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-La-SRWxzIGdy_3ynMZH-887967055%2Fuploads%2Fgit-blob-1740ef84b26561a3c2e10d95650e6c9b3e110b84%2Fsnis.mov.gif?alt=media\&token=7fa83640-abea-454e-8a3c-6708884ce7c7)

Use Deep Packet Inspection to list all identified application categories:

![](https://1185258105-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-La-SRWxzIGdy_3ynMZH-887967055%2Fuploads%2Fgit-blob-8fea62e90888622ee6cdf33221e19abba88cf692%2Fdpicategories2.mov.gif?alt=media\&token=67b7e889-511d-44d5-9825-d589f80e616b)

Extraction of a POP3 authentication token:

![](https://1185258105-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-La-SRWxzIGdy_3ynMZH-887967055%2Fuploads%2Fgit-blob-17138c51e4fc2ef6a40d2a4f35c6553e5a3e0a79%2Fmailtoken.mov.gif?alt=media\&token=0d0053a9-9bf7-4603-bfa0-a7251498692a)

## Gallery

When working with larger amount of nodes, the organic topology can be useful:

![Graph during an investigation (organic topology)](https://1185258105-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-La-SRWxzIGdy_3ynMZH-887967055%2Fuploads%2Fgit-blob-4b22592a510ab980954590bb953d6615266d0795%2Fscreenshot-2020-03-25-at-01.22.54.png?alt=media\&token=3dc75bfa-63b4-4fb3-a08c-363f04555814)

Example of interaction with a PHP webshell:

![PHP webshell interaction](https://1185258105-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-La-SRWxzIGdy_3ynMZH-887967055%2Fuploads%2Fgit-blob-749db3dddf55a9b44a2955e86a9c9fe28a0d1ebb%2Fscreenshot-2020-03-25-at-15.00.45.png?alt=media\&token=037df535-8096-4b78-895f-969ec11ed838)

Example of an exploit abusing a HTTP parameter command injection vulnerability:

![HTTP parameter command injection](https://1185258105-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-La-SRWxzIGdy_3ynMZH-887967055%2Fuploads%2Fgit-blob-b389ee07e30c0d338e9f3b2714b7d973241164cd%2Fscreenshot-2020-03-25-at-15.00.55.png?alt=media\&token=9cd37772-da47-4214-a0d9-3880b97e1264)

Graph during an investigation where the attacker has been identified and further information is gathered:

![Dataset investigation](https://1185258105-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-La-SRWxzIGdy_3ynMZH-887967055%2Fuploads%2Fgit-blob-f3632bcbfdba33a2ca8892f70adabefb5e7ef19f%2Fscreenshot-2020-03-25-at-00.20.06.png?alt=media\&token=b693658e-f0c0-497b-967f-54b66f2061b9)

![Dataset investigation](https://1185258105-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-La-SRWxzIGdy_3ynMZH-887967055%2Fuploads%2Fgit-blob-22bfad8715962d498d2b648fd3b60b8b64fae85c%2Ffiles.png?alt=media\&token=edfbc535-5e99-4373-bc28-6b49970c52d6)

![Flow Graph](https://1185258105-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-La-SRWxzIGdy_3ynMZH-887967055%2Fuploads%2Fgit-blob-0e5783ce8848966bcdb6528d568c5d21b5bbb18e%2Fscreenshot-2020-03-25-at-20.19.15.png?alt=media\&token=1bf82b17-7207-4010-a23d-147d38c1da9d)

## Detail Views

![](https://1185258105-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-La-SRWxzIGdy_3ynMZH-887967055%2Fuploads%2Fgit-blob-37ab047c66f814485befeb404814c0fefda34928%2Fscreenshot-2020-04-22-at-11.54.48.png?alt=media\&token=054cc443-1706-4bee-98e0-603e43886879)

![](https://1185258105-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-La-SRWxzIGdy_3ynMZH-887967055%2Fuploads%2Fgit-blob-fc3495f79948313316c8b850aaa26e0675270bac%2Fscreenshot-2020-04-22-at-12.01.05.png?alt=media\&token=c0a00427-7960-437f-a703-61669e5ac369)

![](https://1185258105-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-La-SRWxzIGdy_3ynMZH-887967055%2Fuploads%2Fgit-blob-0e9aa42bc91fa538b48a90479fa30900ee04af5a%2Fscreenshot-2020-04-22-at-12.04.55.png?alt=media\&token=7364d56f-2835-46dd-a4c7-b6ba8e9a4155)

![](https://1185258105-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-La-SRWxzIGdy_3ynMZH-887967055%2Fuploads%2Fgit-blob-3a483706ddc3c60034df5d89b7759e16a50228fd%2Fscreenshot-2020-04-22-at-12.02.08.png?alt=media\&token=877ca9c3-0f6d-4e96-a22f-7ef2607d23e6)

![](https://1185258105-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-La-SRWxzIGdy_3ynMZH-887967055%2Fuploads%2Fgit-blob-86b79d6665dc6ffd9616dd16feb88f745cdb3a08%2Fscreenshot-2020-04-22-at-12.02.03.png?alt=media\&token=2bf86d47-39ad-4f47-87ef-c13452950eb4)

![](https://1185258105-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-La-SRWxzIGdy_3ynMZH-887967055%2Fuploads%2Fgit-blob-22b59fd68b0857731cf78cf548199e209df0141e%2Fscreenshot-2020-04-22-at-12.03.33.png?alt=media\&token=5abdc7ce-a3d0-4ce1-8f27-e3d8f614fed3)


# Labeling datasets

`net label` joins Suricata alerts or custom mappings to existing audit records and produces labeled CSV datasets. A generated label is a mapping result, not independent ground truth about compromise.

## Suricata workflow

Install Suricata and configure its rules before running this example. Keep a working copy of the audit output: labeling writes dataset files into `-out`.

```sh
net capture -read traffic.pcap -out labeling-audit -dpi=false
net label -read traffic.pcap -out labeling-audit \
  -suricata-config /usr/local/etc/suricata/suricata.yaml
```

The configuration path is an example; use the installed Suricata configuration. `-read` is the PCAP scanned by Suricata; `-out` also identifies the existing audit directory. Preserve the PCAP hash, Netcap/Suricata versions and ruleset revision beside the dataset.

| Flag              | Meaning                                                    |
| ----------------- | ---------------------------------------------------------- |
| `-description`    | Use alert description rather than classification           |
| `-strict`         | Fail on duplicate alert timestamps                         |
| `-collect`        | Append classifications for duplicate timestamps            |
| `-exclude`        | Exclude selected Suricata classifications                  |
| `-disable-layers` | Disable layer mapping by timestamp                         |
| `-sep`            | CSV separator, default comma for this command              |
| `-custom`         | Load a custom mapping instead of running the Suricata path |

## Dataset interpretation

Custom mapping output uses `TYPE_labeled.csv.gz` and a `result` column. An unmatched custom mapping becomes `normal` in `internal/label/custom.go`; that spelling means no matching label, not proof of benign traffic. Timestamp collisions, capture loss and rule coverage can change label quality.

Inspect `internal/label/manager` before defining custom mappings; do not assume an arbitrary two-column CSV is accepted. Verify a small known fixture before labeling a large corpus. Split train/test sets by capture or host/time context where appropriate to avoid leaking duplicate conversations across both sets.


# Firewall response actions

Go v0.15.2 contains Linux firewall-manager and rule-action implementations, but the public capture CLI does not construct or attach a firewall manager. Adding `iptables_block` to a YAML rule alone does not enable blocking: the executor returns `firewall manager not configured` without an attached manager.

## Overview

| Capability                          | v0.15.2 boundary                                                      |
| ----------------------------------- | --------------------------------------------------------------------- |
| Detection alerts                    | Available through the normal rules engine                             |
| `iptables_block`, `iptables_reject` | Require explicitly integrated Linux manager                           |
| `iptables_log`                      | Diagnostic logging, not a complete iptables LOG-target implementation |
| `iptables_rate_limit`               | Placeholder; not an enforced traffic-rate control                     |
| Firewall manager                    | Internal Go package, not a public importable SDK                      |

This corrects the old guide's implication that ordinary CLI capture automatically blocks matches. `internal/rules/engine.go` exposes `SetFirewallManager`, but the released command paths do not call it.

## Requirements

An application integrating `internal/firewall` within this module needs Linux, iptables/ip6tables, suitable network-administration privileges and the intended network namespace. Non-Linux implementations return an unsupported error. Detecting packets on a SPAN sensor does not place that sensor in the forwarding path of the observed hosts.

## Architecture

`Engine` evaluates a rule, generates an alert and dispatches configured actions. An explicitly attached manager owns a custom chain (default `NETCAP`), active block state, allowlist and expiration cleanup. Setup inserts jumps from INPUT, FORWARD and OUTPUT in that namespace; this is a real policy change even before the first block action.

## Configuration

The internal integration points are:

| File                           | Contract                               |
| ------------------------------ | -------------------------------------- |
| `internal/firewall/config.go`  | Manager defaults/configuration         |
| `internal/firewall/manager.go` | Linux setup, block/unblock and cleanup |
| `internal/rules/engine.go`     | Manager attachment and action dispatch |
| `internal/rules/rule.go`       | Action configuration/validation        |

Use `DryRun` for a manager integration test and inspect its actual initialization requirements; it is not a documented `capture` CLI flag. Allowlist and expiration behavior must be verified for the chosen policy and address family.

## Response Action Types

The following disabled rule illustrates action syntax for a custom integration:

```yaml
rules:
  - name: Lab TCP Policy Candidate
    description: Observe a destination port explicitly prohibited by lab policy
    type: TCP
    expression: DstPort == 9999 && SYN && !ACK
    severity: low
    enabled: false
    actions:
      - type: iptables_block
        config:
          target: source
          duration: 5m
```

`target` selects the matched record's source/destination address. `duration` accepts supported duration strings; inspect the executor for numeric handling. Missing/ambiguous endpoints are not permission to substitute another address.

## Rule Examples

Use [rules](/investigate-evidence/rules_engine) and [network detections](/investigate-evidence/network-detections) to collect candidates first. SYN counts do not prove SSH authentication failures; long DNS names do not establish tunneling; a port number does not establish malware. Response policy needs validated evidence beyond those heuristics.

## Firewall Manager API

For development inside this module, inspect `NewManager`, `BlockIP`, `BlockCIDR`, `UnblockIP`, `UnblockCIDR` and `Close`. Handle errors and close orderly. External Go modules cannot directly import this repository's `internal/firewall` package.

## Safety Features

Allowlist checks, bounded-duration blocks and orderly cleanup are implementation mechanisms, not an independent recovery guarantee. A crash can prevent cleanup; an IPv6 initialization warning does not prove IPv6 enforcement is active.

## Monitoring & Statistics

Check action errors separately from alert creation. An `Alert.ncap.gz` entry does not prove an action succeeded or traffic was blocked. Compare manager state with the real ruleset in the intended namespace when qualifying an integration.

## Best Practices

Keep detection-only rules separate from enabled response policy, test on an isolated Linux fixture, and verify expiration/unblock and failure paths before relying on automation. Preserve administrative recovery access independently of the policy being tested.

## Troubleshooting

| Symptom                           | Check                                                       |
| --------------------------------- | ----------------------------------------------------------- |
| `firewall manager not configured` | Released CLI has no manager wiring; YAML does not create it |
| Unsupported platform              | Linux-only implementation                                   |
| Permission/chain errors           | Capabilities, binary availability and network namespace     |
| Alert but no block                | Action error, allowlist, dry-run and manager attachment     |
| No rate limit                     | Placeholder action does not enforce one                     |


# Application firewall

`cmd/netcap-firewall` serves the HTTP WAF, protocol gateways, scoped Linux packet firewall, fleet controller and shared counters. The rootless WAF needs no capture device or host privileges. Linux enforcement is a separate opt-in package. Direct origin traffic bypasses the WAF; protect the origin independently.

## Scope and delivery phases

| Surface               | Shipped boundary                                                                                                                                                                                  |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| HTTP                  | `serve`, `validate`, `healthcheck`; native expr policies and optional embedded Coraza 3.8.1 / CRS 4.25.0                                                                                          |
| Messages / HTTP/3     | `serve --websocket --grpc`, optional `--http3-listen`; shipping image builds `-tags coraza,http3`; listeners remain opt-in                                                                        |
| Policy ownership      | File rollout, managed single-target SQLite, or explicitly enrolled external fleet; managed and fleet ownership cannot overlap                                                                     |
| Shared rates          | `sharedstate` plus `--shared-rate-config`; separate fixed-window guard, mutually exclusive with the native authority client                                                                       |
| Native rule authority | `policy-state` plus `--policy-state-config`; scoped/revision-pinned native thresholds, sliding/distinct windows, tuples and sequences shared across data-plane replicas                           |
| Gateways              | `gateway --protocol` supports `modbus`, `dns`, `dns-tcp`, `dns-tls`, `redis`, `postgres`, `mysql`, `smtp`, `dnp3`, `smb`, `ftp`; explicit termination, bounded parsers                            |
| Linux                 | `network` produces NFQUEUE verdicts; `enforcer` owns finite nft leases; both require an existing named namespace and reject the default namespace                                                 |
| Decoder bridge        | Full capture CLI `--firewall-policy`, `--firewall-effects-config`, `--firewall-schema`; retrospective bindings for all 220 compiled protobuf messages, not interception of completed transactions |

## Build and local verification

Run from the repository root with Go 1.27.0, Docker Compose, Helm 3, Python 3, PyYAML, OpenSSL and kind v0.27.0 available. Store reports outside the repository. Capture tests need libpcap headers; CI selects `nodpi,noyara` to avoid DPI/YARA dependencies.

```bash
GOWORK=off CGO_ENABLED=0 go build -tags coraza,http3 ./cmd/netcap-firewall
python3 examples/firewall/full_stack_smoke.py --binary ./netcap-firewall --output "$TMPDIR/firewall-full-stack.json"
GOWORK=off CGO_ENABLED=1 go test -race -tags coraza,http3 ./cmd/netcap-firewall ./cmd/firewall ./internal/waf ./internal/firewalltransport
docker build -f docker/firewall/Dockerfile -t netcap-firewall:0.1.0-local .
SKIP_BUILD=1 bash examples/firewall/smoke.sh
python3 docker/firewall/check-image.py
python3 examples/firewall/gateway_smoke.py ./netcap-firewall
python3 charts/netcap-firewall/tests/test_render.py
python3 charts/netcap-firewall-control/tests/test_render.py
python3 charts/netcap-enforcer/tests/test_render.py
python3 examples/firewall/enforcer_lab.py
python3 examples/firewall/network_lab.py
python3 examples/firewall/kind_smoke.py
python3 examples/firewall/cni_qualification.py --output "$TMPDIR/firewall-cni.json"
python3 examples/firewall/control_smoke.py --output "$TMPDIR/firewall-control.json"
python3 examples/firewall/postgres_ha.py --package-tests --output "$TMPDIR/firewall-postgres-ha.json"
python3 examples/firewall/policy_state_smoke.py --package-tests --output "$TMPDIR/firewall-policy-state.json"
python3 examples/firewall/restore_drill.py --output "$TMPDIR/firewall-restore.json"
python3 examples/firewall/spool_smoke.py --output "$TMPDIR/firewall-spool.json"
python3 examples/firewall/benchmark.py --rate 50 --duration 20 --output "$TMPDIR/firewall-benchmark.json"
```

`docker/firewall/Dockerfile` pins the Go image digest, builds only the standalone binary with `CGO_ENABLED=0 GOWORK=off`, and ships `scratch` as UID/GID 10001. `/legal/BUILD_MODULES.txt`, module license files and notices accompany the binary. `check-image.py` checks linked Coraza/QUIC metadata and `version.http3 == true`. The linked Postgres driver is `github.com/lib/pq v1.12.3`, with its license retained. `version` includes `mysql`, `dnp3` and `network`; `full_stack_smoke.py` checks that inventory. The Dockerfile-specific allowlist excludes workspaces, secrets, captures and docs.

`smoke.sh` uses a unique Compose project, validates configuration, and checks allowed traffic plus traversal, CRS SQL injection and a denial marker arriving after 32 KiB of chunked body. Denied markers must be absent from origin logs. Only `127.0.0.1:${FIREWALL_PORT:-18080}` is published; the backend is on an internal origin network. `FIREWALL_IMAGE` and `SKIP_BUILD=1` select a built image.

## Runtime and policy contract

| Configuration                      | Shipping default / limit                                                                                                              |
| ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `listen`, `adminListen`            | `:8080`, `:9090`; separate listeners                                                                                                  |
| `upstream`                         | Explicit HTTP(S) origin; no credentials, path prefix, query or fragment                                                               |
| `maxBodyBytes`, `maxResponseBytes` | 67108864 each; schema accepts 1 byte through 64 MiB; response limit applies to opted-in body inspection                               |
| `maxBufferedBytes`                 | 67108864 aggregate budget; schema accepts 1 byte through 1 GiB; copies, gzip, spools, Coraza and message allocations share the budget |
| `maxConcurrent`, `bodyTimeout`     | 32 and `15s`; runtime bounds 1..4096 and at most 5 minutes                                                                            |
| `inspectResponse`, `corazaCRS`     | `false`, `true` in examples/chart; CRS is embedded and its file audit/debug sinks are disabled                                        |
| TLS                                | Paired `tlsCert`/`tlsKey`; upstream CA/name overrides require an HTTPS upstream                                                       |
| `trustedProxyCIDRs`                | Empty; configure only actual ingress/LB ranges before trusting forwarded client addresses                                             |

Bodies spill above 64 KiB into private temporary files (`internal/waf/body.go`). The chart uses disk-backed `emptyDir`, bounded by `spool.size: 256Mi`; Compose uses a 256 MiB tmpfs charged to the container's 256 MiB memory limit. The aggregate 64 MiB budget is admission control, not a promise that every 64 MiB request fits with all inspection copies. Exhaustion fails closed with 503 and releases on close.

Body-dependent native policies still require the full body inside `NativeBodyBytes`, below the 2 MiB event ceiling; they reject larger bodies rather than inspect a truncated projection. JSON/XML/form scalar projection is bounded; multipart files can spill independently. The demonstration Compose policy includes a `Body` rule, so its effective native limit is smaller than the configured ceiling. `spool_smoke.py` uses a body-independent policy for its large-file profile.

| HTTP mode               | Coverage                                                                                                                                                                                                                                                                |
| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Base requests           | Complete bounded request before forwarding; both wire/expanded gzip bytes bounded; nesting 64, arguments/parts 1000                                                                                                                                                     |
| Base responses          | Status/headers checked before final headers; body/trailers stream without inspection by default                                                                                                                                                                         |
| `inspectResponse: true` | Complete bounded response buffering; no unbounded streaming or upgrades                                                                                                                                                                                                 |
| `--websocket`           | Per-message gates, 1 MiB wire/expanded message bound; optional RFC 7692 `permessage-deflate` with both `server_no_context_takeover` and `client_no_context_takeover`; decoded messages forwarded uncompressed, RSV1 permitted only on negotiated initial data fragments |
| `--grpc`                | HTTP/2 message gates with identity/gzip encoding; rejected messages do not release their frame headers                                                                                                                                                                  |
| `--http3-listen`        | QUIC/TLS termination with runtime TLS certificate/key; no 0-RTT; `--grpc` enables an HTTP/3 message-envelope ingress profile bridged to an HTTP/2 origin, including duplex bodies and gated trailers; not a standardized gRPC-over-HTTP/3 claim                         |

Policies use `netcap-policy/v1`, with typed HTTP, `Network`, `TLS`, `DNS`, `Modbus` and protocol-adapter fields (`internal/policy/model.go`). The literal traversal example is not an encoding/canonicalization defense. Validate the exact mounted files with `netcap-firewall validate`; Helm does not compile expressions.

## Kubernetes

Routed runtime composition is implemented in `internal/waf/routes.go` and `internal/waf/messages.go`:

| Binding                            | Contract                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| HTTP, WS compression, gRPC, HTTP/3 | Each route uses the same immutable origin, transport and policy; route reload rebuilds all enabled adapters together. HTTP/3 gRPC is a bounded envelope-to-HTTP/2-origin profile, not standard gRPC-over-HTTP/3.                                                                                                                                                                                                                                                                                                      |
| API validation                     | Each route declares `descriptorPath`, `descriptorSHA256` and optional `apiValidateResponse`; only listener `bootstrapDir` is inherited. No global or neighboring descriptor fallback. WS requires explicit API passthrough.                                                                                                                                                                                                                                                                                           |
| Managed console/MCP                | `--route-id=<bootstrap ID>` selects one `RouteTarget`; policy bundle ID is checked on stage, activation and recovery. Helm uses `routeID`. Global activation cannot update tenant routes.                                                                                                                                                                                                                                                                                                                             |
| TLS reload                         | `SIGHUP` stages listener/client identity for all bindings before publication, then atomically reloads local route policies while retaining the selected attachment's externally owned policy. Inflight requests keep their policy/API snapshot; existing TLS connections retain handshake identity.                                                                                                                                                                                                                   |
| CRS exclusions                     | `crsProfile.exclusions` supports exact `path`/`method` with existing owner/reason/expiry. `parameter` uses Coraza ARGS names, including `json.text`. Legacy `crsTargetExclusions` enters the same registry, mapping `argument` to `parameter`, preserving exact path/method and no-expiry semantics. API, native and structural gates remain active.                                                                                                                                                                  |
| Routed CLI adapters                | `--route-id=<bootstrap ID>` binds fleet, shared-rate, native-state and effects to one immutable attachment. Private router context selects the evaluator, never headers or bundle ID alone. Fleet checks bundle ID before persistence/ack. Only the selected route admits effect rules when a broker exists; other routes compile without effect admission. Root readiness includes the attachment's dependencies; cold/drained/revoked/unavailable attachment rejects its own data without draining local neighbors. |
| Helm API artifacts                 | `apiArtifactsConfigMap` mounts reviewed declarations and artifacts read-only at `/etc/api-bootstrap`; `apiContract` (or each route's `apiContract`) supplies relative `descriptorPath`, required 64-hex `descriptorSHA256` and optional `apiValidateResponse`. Missing mount references, traversal and unpinned declarations are rejected. Declare artifact paths relative to that same bootstrap root; provision the ConfigMap before installation.                                                                  |

`charts/netcap-firewall` requires Kubernetes 1.25+ and an explicit `upstream`. Defaults are a two-replica file-mode Deployment, immutable content-addressed ConfigMap and ClusterIP Service. There are no CRDs, RBAC grants or mounted service account tokens. `0.1.0-local` denotes a local build, not a published release.

```bash
helm upgrade --install firewall charts/netcap-firewall -n firewall --create-namespace \
  --set upstream=http://backend.application.svc.cluster.local:8080 \
  --set image.repository=registry.example.org/netcap-firewall \
  --set image.digest=sha256:<reviewed-64-hex-digest> --wait --timeout 180s
```

| Feature               | Values / contract                                                                                                                                                                                                  |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Rootless bounds       | UID/GID 10001, all capabilities dropped, read-only root, RuntimeDefault seccomp; writable disk-backed `/tmp`, default 256Mi                                                                                        |
| Messages              | `websocket: true`, `grpc: true` pass the actual CLI flags; both default false                                                                                                                                      |
| HTTP/3                | `http3.enabled: true`, optional `http3.port` (8443); requires `tls.secretName`; adds UDP container/Service/NetworkPolicy ingress alongside TCP                                                                     |
| Ingress / direct TLS  | `ingress.*` and `tls.secretName`; configure an ingress-specific HTTPS backend annotation separately when the WAF terminates TLS                                                                                    |
| Admin                 | Existing bearer `adminTokenSecret.name/key` requires `adminTLS.secretName`; optional separate `adminService.enabled`; never on application Ingress                                                                 |
| Probes                | `/readyz` and `/livez` on admin port 9090, HTTPS when admin TLS is configured; no bearer needed for health routes                                                                                                  |
| Origin TLS            | `upstreamTLS.caSecretName` (`ca.crt`) and optional `serverName`; HTTPS upstream required                                                                                                                           |
| Shared guard          | `sharedRate.configSecretName` (`config.json`, optional CA/client cert files) and `credentialsSecretName` (`tokenEnv` entries); both references required together                                                   |
| Native rule authority | `policyState.configSecretName` (`config.json`, CA/client TLS files) and `credentialsSecretName`; mounts `/etc/policy-state` read-only and passes `--policy-state-config`; rejects mixed `sharedRate` configuration |
| Fleet targets         | `mode: fleet` uses a fixed-replica StatefulSet, headless target Service and per-pod cache PVC; `fleet.configSecretName` and `credentialsSecretName` required                                                       |
| Availability          | File mode permits HPA/PDB; managed mode is one replica with Recreate; fleet mode rejects HPA because target enrollment is explicit                                                                                 |

Secret contents are never generated from plaintext token values. Secret changes require an intentional restart; ConfigMap hashing covers only runtime/policy data. For fleet release `targets`, mount `targets-netcap-firewall-0.json`, `…-1.json`, etc. from the configuration Secret. Kubernetes expands `$(POD_NAME)` in the CLI argument; each JSON must declare its own enrolled `targetID`, `tokenEnv`, scope, controller URL and `/var/lib/netcap-firewall/agent` cache directory. `ca.crt` may share the Secret. Replicas share the app's target-token Secret, never operator credentials. Random Deployment pod names are not enrollment identities.

### Network boundary

`networkPolicy.enabled` requires explicit `dnsPeers`, `upstreamEgress` and actual `ingressPeers`; empty ingress peers deny application traffic. DNS permits TCP/UDP 53. Add control-service destinations to egress when using fleet/shared rates. The chart selects WAF pods only; install a separate origin-side policy allowing only the WAF. Policies are additive, and a supporting CNI is required.

`cni_qualification.py` disables kind's default CNI, installs Cilium chart 1.17.2, and proves a previously working direct-origin probe times out while allowed WAF traffic returns 200. It checks attacker/admin isolation and restricted admission. Metrics Server chart 3.12.2 supplies real CPU metrics for a bounded 3→4 HPA test; its temporary 1% target is a lab setting. Both kind scripts use private kubeconfigs and delete only their own digest-pinned Kubernetes 1.32.2 clusters.

## Policy control and replica state

`serve --auth-config /etc/firewall/auth.json` exposes authenticated `/mcp` and `/api/v1/policy/*` on the admin listener. File/fleet policy ownership remains read-only. `mcp --config … --auth-config …` runs an isolated read-only stdio session with explicit `stdio` grants; it does not connect to a running WAF.

| Single-target lifecycle     | MCP tool                                                                                                   |
| --------------------------- | ---------------------------------------------------------------------------------------------------------- |
| Capabilities / revision     | `get_policy_capabilities`, `get_policy_revision`                                                           |
| Validate / stage            | `check_policy_bundle`, `stage_policy_revision`                                                             |
| Compare / simulate          | `diff_policy_revisions`, `explain_policy_decision`                                                         |
| Activate / rollback         | `activate_policy_deployment`, `rollback_policy_deployment`; expected revision and idempotency key required |
| Successful mutation history | `query_policy_audit`                                                                                       |

### Identity and authorization

`internal/firewallauth` enforces one grant across `tenant`, `app`, `environment`, `target` and operation at REST, MCP and underlying operation boundaries. Empty dimensions match only empty dimensions; `*` must be explicit in a grant. Policy/enforcer scope is bootstrap-bound. Fleet admin requests name tenant/app; job transitions authorize every stored job target. Workload `desired`/`ack` requires the principal ID to equal an enrolled target ID and a `lease` grant. Shared/native state derives a single unambiguous tenant/app binding from grants.

| Action               | Operations                                                                                                       |
| -------------------- | ---------------------------------------------------------------------------------------------------------------- |
| `read`               | Capabilities, revisions, diff, status, lease listing, state health                                               |
| `author`             | Check/stage bundles                                                                                              |
| `evaluate`           | Synthetic replay; shared counters/native state evaluation                                                        |
| `deploy`             | Activate/promote/rollout; drain/revoke/resume targets                                                            |
| `rollback`           | Rollback; process-owned fleet maintenance uses a bootstrap supervisor                                            |
| `lease`              | Create/revoke leases; enrolled target desired/ack                                                                |
| `audit`              | Mutation audit queries and `audit_export`                                                                        |
| `prune`              | `retention_preview`, `prune`, `audit_ack`; read-only audit grants cannot delete retained records                 |
| `metrics`            | `/metrics`, fleet REST `metrics` and MCP `fleet_metrics`; aggregate fleet metrics require environment-wide scope |
| `approve`            | Issue receipts, also requiring the approved action's grant                                                       |
| `manage-credentials` | Revoke fingerprints with an authority-wide empty-scope grant                                                     |

Example strict JSON for `--auth-config`; service bootstrap files reference the same file with `authConfig`. Secrets are environment references, never JSON values:

```json
{
  "stateDir": "/var/lib/firewall/identity",
  "scope": {"tenant":"lab","app":"web","environment":"test","target":"edge"},
  "origin": "https://console.example",
  "static": [{"tokenEnv":"FIREWALL_READER_TOKEN","principal":{
    "id":"reader","grants":[{"scope":{"tenant":"lab","app":"web","environment":"test","target":"edge"},"actions":["read"]}]
  }}]
}
```

| Bootstrap field                       | Contract                                                                                                                                                                         |
| ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `providers`                           | Operator-pinned `issuer`, `audience`, `jwksURL`, and `subjects` map from subject to local principal/grants; token claims cannot assign roles or select key URLs                  |
| Provider time limits                  | Integer nanoseconds: `ttl` defaults to 60s (1–300s), `maxLifetime` to 900s (1–3600s), `clockSkew` to 0 (0–60s); JWT requires `exp`, `iat`, bound subject, issuer and audience    |
| JWKS                                  | RS256/ES256/EdDSA only, public signing keys, nonempty bounded `kid`; HTTPS or literal loopback HTTP, no redirects; 32 keys/256KiB, one refresh/second/provider, no per-kid cache |
| `stateDir`                            | Private 0700 directory with 0600 `identity.sqlite`; durable fingerprint revocation and unique approval consumption; retain alongside policy state                                |
| `databaseURLEnv`, `databaseNamespace` | Shared PostgreSQL identity ledger; mutually exclusive with `stateDir`; use one dedicated schema for every owner and retain it with service state                                 |
| `approvalKeyEnv`, `protected`         | Base64 64-byte Ed25519 private key and action/scope rules for `deploy`, `rollback`, `lease`; both require durable identity state                                                 |
| `stdio`                               | Explicit local principal; absent grants confer no privileges                                                                                                                     |
| `origin`                              | Optional exact first-party HTTP(S) origin; no wildcard, path, credentials or CORS headers                                                                                        |

`POST /api/v1/auth/revoke {"fingerprint":"<SHA-256 hex of bearer>"}` and MCP `revoke_firewall_credential` permanently reject that token, including after restart. Without an identity ledger these calls fail closed. Rotate static tokens, issuer trust, subject grants and `revokedIDs` through trusted config and restart (embedded callers can use `Authority.Reload`). Removed JWKS keys cease working after cache expiry, at most 300s. Bearers are accepted only in the Authorization header, never a URL.

Protected policy/fleet writes take `receipt`. Obtain it from `POST /api/v1/policy/approval`, `POST /api/v1/fleet/approval`, or MCP `issue_policy_approval` / `fleet_approval`: `approval` contains `actor`, `action`, `scope`, `digest`. Use the package's `ApprovalDigest(operation, Request)` to bind the complete request, including CAS, revisions, targets and idempotency key. Fleet approval scope is the enclosing tenant/app/environment; stored job targets determine whether protection applies. Enforcer uses `POST /v1/approval` or MCP `issue_lease_approval`, `ActionApprovalDigest` / `DeleteApprovalDigest`, and a `receipt` create argument or `X-Firewall-Approval` header (DELETE uses the header). The signing principal must differ from `actor`; receipts expire after 300s and are consumed durably once. A failed operation may consume its receipt. Ordinary delegated operations outside `protected` rules need no receipt or human prompt.

`firewallauth.OpenShared` uses `firewallstate.Database` namespace transaction locks for revocation reads/writes and one-use approval consumption across processes. PostgreSQL service owners require this shared ledger. Its bootstrap fingerprint pins normalized grants, provider policy, approval public key and protection rules; JWKS caches and private signing keys stay process-local. Shared policy changes require coordinated bootstrap migration; `Authority.Reload` refuses them. `TestSharedPostgresIdentityProcesses` verifies fake-provider authentication, cross-process replay/revocation and mismatched tenant policy rejection.

The embedded `/console/` preserves `Origin` in identity mode and requires the configured exact first-party origin for browser API requests; bearers remain in browser memory. `ActionApprovalDigest` binds action kind, profile and exact flow; `CreateApprovalDigest` remains the legacy default-action helper. Legacy `serve`/`enforcer` tokens require `--legacy-admin`; Helm requires `legacyAdmin: true` plus `adminTokenSecret` (enforcer: `tokenSecret`) to select that compatibility mode. Legacy service `tokenEnv`/`identities`/`principals` remain explicit compatibility bootstrap and cannot be mixed with `authConfig` identities.

| Packaging integration      | Contract                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Role bootstrap             | `examples/firewall/managed-values.yaml` selects `authConfigSecret` and individual `tokenEnvironment` Secret keys; `examples/firewall/auth.json` grants reader `read,metrics` and operator `read,author,evaluate,deploy,rollback` only for `example/web/lab/edge`. Replace synthetic scope/origin before use. No default unrestricted bearer is generated.                                                                                                     |
| All three charts           | `authConfigSecret: {name: firewall-auth, key: auth.json}` mounts `/etc/firewall-auth/auth.json` read-only. WAF passes `--auth-config`; the enforcer entrypoint uses `ENFORCER_AUTH_CONFIG`; fleet-controller's existing `config.json` must reference `"authConfig":"/etc/firewall-auth/auth.json"`. `sharedstate` and `policy-state` use their own scoped principal bootstrap, not fleet auth fields.                                                         |
| Console origin             | Set JSON `origin` to the exact externally used scheme/host/port with no path. Browser `Origin` must also equal the listener's scheme and HTTP Host; forwarded headers cannot redefine it (`firewallui.WrapOrigin`). CLI bearer requests can omit `Origin`.                                                                                                                                                                                                    |
| Durable approvals          | Auth `stateDir` must be inside a writable persistent mount (`/var/lib/netcap-firewall/identity`, `/var/lib/control/identity`, or `/var/lib/netcap-enforcer/identity`). PostgreSQL uses dedicated `databaseURLEnv`/`databaseNamespace` instead of `stateDir`; mixing these fields is a CLI error, not a Helm rewrite. `approvalKeyEnv` is a Secret-backed Ed25519 private key; protected deploy/rollback/lease actions use the typed receipts described above. |
| Local proof                | `roles_smoke.py` tests actual shipping Compose TLS APIs: reader/foreign stage and activation return 403; operator activates with revision CAS; embedded `/console/` is present. `kind_smoke.py` repeats role denials through the Helm-installed service and verifies PVC recovery.                                                                                                                                                                            |
| Kubernetes authority proof | `cni_qualification.py` installs all three charts in a disposable kind/Cilium lab: enforcer reader/foreign lease creation returns 403 while the operator creates a timed rule; fleet viewer/foreign rollout returns 403. Inspect timed rules using the shipping image's pinned `nft`; kind node `nft` exited 139 on that fixture.                                                                                                                              |
| CI surfaces                | `.github/workflows/firewall.yml` includes auth/UI/API contracts/appliance/protocol/routing/metrics packages, release-tool tests and qualification negative-control tests. Manual `browser: true` installs `@playwright/test@1.51.1` and drives actual local API fixtures. Publication and production pilot approval remain separate.                                                                                                                          |

Pitfalls: shared-identity lease/status reads never reconcile or deploy; the process-owned maintenance loops do that. Fleet authority enrollment omits `tokenEnv` and matches the enrolled ID; legacy target-token fallback is disabled. Retained SQLite state pins identity mode and resource binding; changing tenant, environment or target, or downgrading to legacy, requires separately provisioned state. Rotating credentials does not change this pin (`firewallauth.PinState`).

`appliance plan --manifest ...` supports `mode: production` with `targetID`. Production `apply`/`recover`/`remove`/`status` additionally require `--auth-config`, `--operator-token-env` and `--reviewed-plan-digest` equal to the plan's `digest`; the bootstrap scope's target must equal `targetID` and grant `deploy` over all four scope dimensions. Named-namespace, private-prefix, ownership and recovery fences remain enforced. Configured protection requires `--approval-receipt-env` with a one-use receipt binding `appliance.ApprovalDigest(planDigest, operation)`. `mode: lab` still requires `NETCAP_APPLIANCE_LAB=1` and Docker. `TestApplianceProductionLab` exercises the production gate only inside the disposable Docker lab.

### Managed singleton

`mode: managed` passes `--managed --state-dir /var/lib/netcap-firewall/managed`, requires one replica, disables HPA and sets Recreate. A retained ReadWriteOnce PVC or `managed.existingClaim` supplies storage; UID 10001 creates a private 0700 subdirectory, preserved by `fsGroupChangePolicy: OnRootMismatch`. First bootstrap imports the file policy; subsequent Helm changes do not replace SQLite activation. `kind_smoke.py` qualifies TLS API activation, PVC restart recovery and rollback.

### Fleet and shared services

`charts/netcap-firewall-control` is disabled by default. Install one release per service with `enabled=true`, `service=fleet-controller|sharedstate|policy-state`, existing `configSecretName`, `credentialsSecretName`, and `tlsSecretName`. Both backends use rootless TLS ClusterIP port 9092. TCP readiness proves a listening socket; authoritative API/guard probes additionally verify database availability.

| `persistence.backend` | Control chart contract                                                                                                                            |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `sqlite` (default)    | `replicaCount: 1` only, Recreate, retained PVC; bootstrap `stateDir: /var/lib/control/state`                                                      |
| `postgres`            | `replicaCount >= 2`, RollingUpdate, no local state mount/PVC; requires external database URL environment reference and dedicated schema namespace |

Postgres values declare `persistence.postgres.databaseURLEnv` and `databaseNamespace`; they must match the authoritative bootstrap Secret's JSON fields. `credentialsSecretName` supplies the URL environment key; **no database URL or password belongs in Helm values**. PostgreSQL bootstrap omits `stateDir`; the CLI rejects mixed SQLite/Postgres configuration and literal `databaseURL`. All replicas of one service share a namespace and identical bootstrap identities; fleet and counters use distinct namespaces. Non-loopback DB URLs require `sslmode=verify-full`; mount the CA alongside bootstrap JSON. The chart declares the expected environment key/namespace but cannot inspect a Secret during offline rendering.

```bash
helm upgrade --install fleet charts/netcap-firewall-control -n firewall \
  --set enabled=true --set service=fleet-controller --set persistence.backend=postgres \
  --set replicaCount=2 --set configSecretName=fleet-bootstrap \
  --set credentialsSecretName=fleet-credentials --set tlsSecretName=fleet-tls \
  --set persistence.postgres.databaseURLEnv=CONTROL_DATABASE_URL \
  --set persistence.postgres.databaseNamespace=ncf_fleet --wait
```

Controller bootstrap explicitly lists scoped `identities` and `targets`. Shared-state bootstrap lists scoped `principals`. Agent/rate JSON durations are integer nanoseconds, not duration strings. A shared guard example is:

```json
{"url":"https://sc-control:9092","tokenEnv":"STATE_TOKEN","ca":"/etc/shared-rate/ca.crt","window":3600000000000,"limit":3,"group_by":"Path","id":"app-rate","unit":"request"}
```

The fleet REST read URL is `https://fc-control:9092/api/v1/fleet/status?tenant=lab&app=example` for the example Helm release. Other reads are GET `audit` and `capabilities` under `/api/v1/fleet/`. Scoped identities may omit their bound scope. Writes are POST `stage`, `rollout`, `activate`, `promote`, `rollback`, `drain`, `revoke`, `resume`. Targets use GET `desired` and POST `ack`; their attachment identity is derived from the bearer, never a query parameter. Rollouts CAS per-target generations and wait for observed acknowledgments; they are not atomic fleet-wide cutovers. Native thresholds/sequences are local by default; `--policy-state-config` instead evaluates them at the authority below. The external shared-rate guard remains a separate fixed-window feature.

### Distributed native rule state

`policy-state-bootstrap.json`, `policy-state-client.json` and the corresponding `policy-state-values.yaml` / `policy-state-waf-values.yaml` show the exact strict JSON and Secret-reference contracts. Install the control example as release `native` so the client URL `https://native-control:9092` matches its Service. Bootstrap accepts `principals`, `allowEffects`, `maxRevisions`, `maxStateBytes` and either private `stateDir` or `databaseURLEnv`/`databaseNamespace`; unlike fleet bootstrap it does not accept `identities`/`targets`, or shared-rate `maxKeys`. Authority credentials contain DB URL/principal tokens; caller credentials contain only their `tokenEnv`. SQLite uses one fenced WAL owner; PG replicas share one dedicated namespace and identical principals, limits and effect-admission settings.

Client JSON accepts `url`, `tokenEnv`, `ca`, optional `cert`/`key`, and integer nanosecond `requestTimeout` (default 5s, maximum 10s). The example selects 1s. Time windows use the authority's clock, with the PG database clock and a persisted monotonic watermark; callers cannot provide a clock. New revisions have independent state, not a global reset; rolling back/rejoining a retained revision can resume its live windows. Process restart does not reset committed native state.

`policy-state` health is authenticated GET `/api/v1/policy-state/health`, not the fleet `/health` route. Optional `healthProbe.enabled` adds a pinned rootless curl sidecar: `authorizationSecretName` holds a complete `Authorization: Bearer …` line under key `authorization`; `caSecretName` holds `ca.crt`. It verifies TLS using the Service name (or `serverName`) but connects to this pod's loopback, and requires HTTP 200. The example has a separate health principal. Without this option the control chart retains its socket-only probe; WAF readiness still uses authenticated authority probes whenever the native client is configured.

HTTP/gateway events, WebSocket/gRPC messages and network packets incur a remote evaluation and transactional state cost; this is not a line-rate/capacity claim. Timeout, overload, unavailable/ambiguous commit or authority loss fail closed, with no local fallback or automatic evaluation retry. Network mode additionally requires `failure-verdict=deny`, no missing-listener bypass and no overflow fail-open; size the RPC timeout and queue deadline for the deployment's latency. Both WAF and network enforcer charts accept the Secret-reference client settings.

The authority receives projected events, including bounded HTTP bodies/headers, in plaintext inside the trusted process after TLS termination. SQL retains scoped policy artifacts, state digests and timing metadata, not raw per-event bodies or datagrams. Group hashes are not a promise of anonymity. Effect policies require both authority `allowEffects` and the caller's explicit broker admission. The direct capture audit bridge remains retrospective; these runtime flags do not make it inline prevention or automatically wire its observer to the authority.

```bash
python3 examples/firewall/control_smoke.py --output "$TMPDIR/firewall-control.json"
```

The runner generates private per-role env files and short-lived TLS under a temporary directory, starts `control-compose.yaml` with two explicitly enrolled WAFs, and proves scoped policy push plus a shared three-request limit. It stops each control owner, runs the real `backup`/`restore` CLI into new directories, and verifies retained generations/counters. `control_k8s.py`, invoked by the CNI lab, tests SQLite control releases and a two-target StatefulSet under restricted admission, including stable identity/policy after pod replacement.

`control-postgres-compose.yaml` and `postgres_ha.py` qualify Postgres-backed HA: two fleet replicas, two counter replicas, TLS-passthrough frontend and two fixed target agents. Generated DB passwords, DSNs and role tokens pass only through subprocess/container environment; no credential env files are written. The runner verifies the pinned Postgres 17.11 digest and running version, crosses replicas for stage/rollout/ activation and counters, then kills one replica of each service while leaving the DB running. A separate DB kill/restart checks fail-closed readiness and WAL-backed generation/counter preservation. `--package-tests` runs the real Postgres race, multi-process, CAS and crash tests using `NETCAP_POSTGRES_TEST_URL` and the uniquely labeled loopback `NETCAP_POSTGRES_TEST_CONTAINER`. No existing database is targeted.

### Backup and restore drill

| Store                     | Operator path                                                                                                                                                                                             |
| ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| SQLite control services   | Stop/fence the old owner; select `--service fleet`, `sharedstate` or `policy-state` for `netcap-firewall backup --config … --output /absolute/private/snapshot.sqlite`; restore into a new empty StateDir |
| Postgres control services | Optional schema-dump/Restic CronJob below; database-operator roles/WAL/PITR and restore procedure remain separate; SQLite backup CLI rejects Postgres                                                     |
| Managed policycontrol     | `managed_snapshot.py` with `backup` or `restore`, `--state-dir /absolute/state --snapshot /absolute/private/snapshot.sqlite`; Python SQLite backup API uses the same lifetime ownership lock              |

Snapshots contain sensitive revisions/audit/counters and use private directories and 0600 files. Restore requires an empty destination and does not fence another host automatically. SQLite is one authoritative owner. Postgres permits active-active application replicas against one writable primary; **primary election, fencing, replication durability and DB failover are database-operator responsibilities**. `restore_drill.py` checks managed live-owner/corrupt/existing-destination refusal, then restored revision/audit/idempotency receipts and deny→rollback→allow traffic. `control_smoke.py` separately checks SQLite fleet/shared-state CLI recovery.

### Scheduled Postgres backups

`charts/netcap-firewall-control` adds no backup resources by default. Enable `backup.enabled` only with Postgres, Kubernetes 1.27+, a unique cluster/operator `backup.scope` and pre-provisioned Secrets. `examples/firewall/backup-values.yaml` shows the opt-in values; it contains no repository URL or credentials.

| Backup input / bound          | Contract                                                                                                                                                                                                                               |
| ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `backup.databaseSecretName`   | `pg_service.conf` with service `[backup]`, host/port/dbname/user/password and `sslrootcert=/db/ca.crt`; include `ca.crt` in that Secret. `pg_dump` forces `sslmode=verify-full`; no password/DSN in argv                               |
| `backup.repositorySecretName` | `RESTIC_REPOSITORY` and backend-auth environment entries; optional config/CA files mount read-only at `/repository`, with `ca.crt` used automatically. Keep authentication out of the repository URI                                   |
| `backup.passwordSecretName`   | Separate Restic password file, key `password` unless `passwordSecretKey` overrides it; repository must already be initialized by its operator                                                                                          |
| Dump stage                    | Digest-pinned Postgres 17.11 `pg_dump`, consistent custom-format archive of the configured service schema; 64 MiB default hard file limit, 5s lock wait, private 0600 files; failed/oversize dumps never become upload inputs          |
| Encryption stage              | Separate digest-pinned Restic 0.18.1 image; no runtime installer, repository initialization, Kubernetes API mutation or application pause                                                                                              |
| Retention                     | Daily 7 / weekly 4 / monthly 3; forget always selects both stable host and tag, including scope/namespace/release/service. `prune: false` by default; optional prune performs repository-wide unreferenced-blob GC after scoped forget |
| Job bounds                    | Forbid overlap, 900s deadline, one retry, 3600s finished-Job TTL; rootless 10001, dropped capabilities, read-only root, no service-account token; bounded work/cache volumes and ephemeral-storage limits                              |

Backups cover all tenants in that service schema, not a tenant-scoped API export. Repository provisioning, access policy, key rotation and backup-success alerting remain operator work. Logical snapshot retention does not bound physical repository bytes while prune is disabled. Work holds plaintext only in the private ephemeral volume; the upload stage removes the archive on ordinary exit, with pod/Job cleanup covering failed startup or forced termination. No automatic SQLite stop/scale procedure is installed.

```bash
helm upgrade --install fleet charts/netcap-firewall-control -n firewall -f examples/firewall/backup-values.yaml
python3 examples/firewall/postgres_ha.py --backup-restore --output "$TMPDIR/firewall-backup.json"
```

The local drill runs the exact chart scripts against a disposable encrypted Docker volume, verifies restored fleet generation/counter values, refuses bad CA/password and oversize dumps, and preserves foreign host/tag snapshots through scoped prune. Restic networking is disabled in the drill. Off-host delivery and production schedule execution require separate qualification; no estate/cloud resources were used. The local drill passes `PGPASSWORD` through process environment and pipes the Restic password into container tmpfs. Both PostgreSQL/backup runners check their host fixture directories for generated password/token leakage; only non-secret connection settings and TLS certificate/key fixtures remain in those directories.

## Protocol gateways and optional enforcer

`redirect` places an already-running TCP message gateway on an explicitly scoped routed service path. Start the gateway inside its named namespace, then install the redirect from outside it:

```bash
ip netns exec firewall-router netcap-firewall gateway --protocol redis \
  --listen 10.90.0.1:16379 --upstream 10.91.0.2:6379 \
  --allow-client 10.90.0.0/24 --policy /etc/netcap-firewall/redis.yaml
# Separate process; SIGTERM removes only this redirect's owned table.
netcap-firewall redirect --namespace firewall-router --interface g0 \
  --service-cidr 10.91.0.2/32 --service-port 6379 --gateway-port 16379 \
  --protocol redis --tls-mode plaintext
```

The gateway must be listening before activation. `--tls-mode terminated` records an operator assertion; the gateway still needs its TLS certificates and explicit termination configuration. Opaque TLS is rejected. Placement applies to new conntrack sessions and one configured fixed upstream. `transparent_lab.py` verifies real shipping Redis/DNP3 gateways and redirect processes on IPv4/IPv6, source identity, denial before origin receipt, management exemptions, and SIGTERM cleanup, without changing the default namespace.

| Example under `examples/firewall/`           | Contract                                                                                                                                                                                      |
| -------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `network-policy.yaml`                        | Default-deny packet policy with explicit `Protocol == "network"`, bidirectional service selectors, visible-SNI denial and an explicit allow for unclassified TCP/443                          |
| `advanced-policy.yaml`                       | Sliding counts, distinct paths/ports, grouping tuples and a named login→export sequence; local by default, or authoritative per scope/revision with `--policy-state-config`                   |
| `effects-policy.yaml`, `effects-config.json` | HTTP-path or SMTP-RCPT denial emits a bounded `block_source` intent; operator bootstrap fixes HTTPS endpoint, `LAB_ENFORCER_TOKEN`, CA and future TCP/8080 scope; no policy-supplied endpoint |
| `audit-smb-policy.yaml`                      | `Protocol == "audit"`, `RecordType == "SMB"`, `Fields["ShareName"] == "ADMIN$"`; only an explicitly admitted live capture can request a future lease                                          |

For packet mode select `--inspect-tls`. `TLS.Encrypted` indicates available visible ClientHello metadata; false is unknown, including SYN/incomplete/missing metadata, not proof of plaintext. The example allows that unknown case so handshakes can progress. ECH can hide the real SNI; no rule here decrypts application payloads. `effects-config.json` expects `lab-enforcer.crt` in the process working directory and a TLS enforcer at `127.0.0.1:19091`; JSON `retention` uses nanoseconds. Its fixed lease destination is `198.51.100.0/24`, interface `lab0`, forward/TCP/8080, protected `192.0.2.0/24`. The SMTP trigger requests that same future scope, not a global or SMTP-wide ban.

`full_stack_smoke.py` compiles these exact files with the CLI, verifies effect policies are rejected without broker admission, and reuses existing integration tests: `TestEffectsBrokerShippingDryRunLease` proves trusted-proxy HTTP traffic creates an actual TLS-authenticated dry-run lease; `TestLiveBrokerAndReplayAreSeparated` and `TestCaptureMultiFileReplayNeverContactsEnforcer` prove native audit/live/replay boundaries. It generates temporary CA/token material and changes no host rules. SMTP is compiled here; this runner does not claim SMTP effect-traffic qualification.

Gateway defaults are 64 connections, 1 MiB messages, 5-second IO and 5-minute sessions, with `--max-state-entries=128`; inspect `gateway --help` for explicit client/ upstream TLS flags. `gateway_smoke.py` provides origin-evidence fixtures for the DNS/Modbus examples. Additional bounded parsers are in `internal/gateway`; their existence does not imply support for every protocol extension. Modbus writes must be denied in the request phase; response denial cannot undo a write.

| Additional gateway            | Covered profile / exclusions                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| MySQL                         | Protocol 4.1 auth relay and independently negotiated TLS legs; QUERY/INIT\_DB/PING and bounded prepared-statement lifecycle; query metadata gates execution. Rejects multipart 0xffffff packets, compression, LOCAL INFILE, multi-results, long-data/cursors and unsupported capabilities (`mysql_wire.go`, `mysql.go`)                                                                                                                                                                                                                                                                                                                 |
| DNP3                          | CRC-validated link frames, confirmed/unconfirmed transport, sequence-bounded reassembly and explicit object profiles for READ/WRITE/SELECT/OPERATE/restart functions. One request APDU per authorization, configured message/state bounds; unsolicited and unknown profiles rejected (`dnp3_wire.go`, `dnp3.go`)                                                                                                                                                                                                                                                                                                                        |
| SMB2/3 plaintext              | Direct TCP length/header/compound bounds; entire request compound authorized before forwarding. `smb.command`, raw UTF-16 `smb.path`/`smb.share`, session/tree-scoped file handles, CREATE access/disposition/options, READ/WRITE length/offset; WRITE content and successful READ response content gated. Authentication opaque; signed bytes unchanged and unverified, denial closes without forging a reply. SMB1, encrypted/compressed transforms, async, IOCTL, SET\_INFO, locks, leases/create contexts rejected (`smb.go`). Qualification is the owned disk-effect emulator in `smb_test.go`, not Samba/Windows interoperability |
| FTP                           | Bounded CRLF commands and RFC 959 multiline replies; EPSV data listener bound to the control listener's local address, data client must match control client, origin data target pinned to the control peer with port 1024..65535. STOR fully buffered and body-gated before origin command/data connection; RETR/LIST/NLST fully buffered before downstream release. Implicit TLS configuration, active PORT/EPRT, PASV, AUTH/PBSZ/PROT upgrades, APPE, MODE/STRU, SITE and unknown commands rejected (`ftp.go`). Raw `ftp.path`/`ftp.argument` are not canonical filesystem identities                                                |
| Existing extension exclusions | Redis RESP3/HELLO, transactions and pub/sub remain rejected (`redis.go`); Postgres COPY remains unsupported (`postgres.go`); SMTP STARTTLS/BDAT/BURL remain rejected, with implicit TLS available (`smtp.go`). These modes do not become opaque passthrough                                                                                                                                                                                                                                                                                                                                                                             |

`TestFTPPyftpdlibPreventiveUploadsAndCommands` requires `NETCAP_FTP_PYTHON` pointing to Python with `pyftpdlib==2.1.0`; `TestWSDeflateRealPythonClient` requires `NETCAP_WS_PYTHON` with `websockets==15.0.1`. Both use owned loopback endpoints and skip explicitly when unset. `go test -race -tags http3 ./internal/gateway ./internal/firewalltransport ./internal/waf ./cmd/firewall` includes real QUIC duplex/trailer-denial and stream-limit/recovery tests, file-side-effect checks, fragmentation, decompression bombs, buffer-capacity and cancellation checks. FTP transfers are limited to `--max-message-bytes`; a synthetic `150` permits buffering before STOR authorization. The alternate-loopback FTP peer test skips on macOS without `127.0.0.2`; it passes in the isolated `alpine:3.23.2` Linux fixture. SMB qualification uses the owned SMB2 HMAC-SHA256 disk emulator; SMB3 signing algorithms and Samba interoperability are not qualified.

### Decoder audit bridge

The full `net` capture binary accepts `capture --firewall-schema` to enumerate the versioned registry of all 220 compiled protobuf message types, field sensitivity and projection bounds. `capture --read fixture.pcap --firewall-policy examples/firewall/capture-policy.yaml` evaluates existing decoder records retrospectively; replay never contacts an enforcer. Live `--iface` additionally requires explicit `--firewall-effects-config` to admit source-attributed, bounded future response actions. Service/upload mode is unsupported. Existing record rules bind through `RecordType`, typed `Fields` and `audit.schema_version`; a retrospective `deny` is an observation, not a packet drop. This does not turn all 220 decoder bindings into inline prevention. Projection bounds are 128 fields, 1024 bytes/value, four collection entries, depth six and 4096 traversal nodes (`internal/firewallaudit/schema.go`).

`enforcer` provides bearer-protected `/v1/leases` and `/mcp`, at most 1000 leases and 15-minute TTL. Select `--dry-run` explicitly for previews; its CLI default is live. The canonical shared `/run/netcap-enforcer` lock coordinates namespace/table ownership. Named namespace inode checks reject current/default namespace aliases.

### Enforcer package

`docker/enforcer/Dockerfile` pins Alpine 3.23.2, `iproute2-minimal=6.17.0-r0` and `nftables=1.1.5-r2`; BusyBox supplies `nsenter`. Installed package versions and Go licenses are retained. Default `--help` is inert; live scope must be explicit.

| `charts/netcap-enforcer` | Contract                                                                                                                                                                                 |
| ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Enablement               | Disabled by default; dedicated lab `nodeSelector` and existing named namespace/interface required                                                                                        |
| Root privileges          | Drop all, add only NET\_ADMIN/SYS\_ADMIN; no blanket privileged mode; read-only root; seccomp/AppArmor Unconfined for setns/unshare/mount                                                |
| Host visibility          | Host network makes default-namespace identity checks cover the node network; private PID namespace avoids host PID 1 access                                                              |
| Mounts                   | Existing `/run/netns` read-only/HostToContainer, shared private `/run/netcap-enforcer`, node-local state directory; creates no host namespace or route                                   |
| `mode: leases`           | Existing bearer Secret; explicit destination/protocol/port; loopback API only, no Service/Ingress                                                                                        |
| `mode: network`          | Explicit `scope.protectedCIDRs` select protected traffic; optional management exemptions; immutable policy ConfigMap; queue/deadline/failure/TLS-metadata values map to actual CLI flags |
| Native network authority | `policyState` Secret references pass the client config; renderer and CLI reject fail-open queue/deadline settings when it is enabled                                                     |
| Network failure policy   | Queue 100, length 1024, deadline 100ms, failure verdict deny; no-listener bypass and overflow fail-open default false                                                                    |
| Updates                  | OnDelete requires deliberate pod replacement; network table is fixed by the runtime; lease table remains independently scoped                                                            |

`network_lab.py` runs `TestRoutedLab` and the standalone network CLI against disposable named client/router/origin namespaces: 8080 allowed, 8081 dropped, traffic restored on shutdown. Both network/enforcer runners reject skipped or missing required tests and compare the default namespace nft ruleset before/after. They have no host mounts; NET\_RAW is added only to the crafted-packet test fixture. The CNI lab also starts both DaemonSet modes against an existing named lab namespace.

### Infrastructure qualification

| Evidence runner                   | Verified boundary                                                                                                                                                                                |
| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `kind_smoke.py`                   | File install/upgrade/Helm rollback; managed TLS activation, PVC restart, policy rollback                                                                                                         |
| `cni_qualification.py`            | Cilium origin/client/admin isolation, restricted admission, local counters, real HPA 3→4, optional enforcer modes, both control charts and stable fleet targets                                  |
| `control_smoke.py`                | Scoped TLS services, two-target policy push, shared count, offline fleet/state CLI recovery                                                                                                      |
| `postgres_ha.py --package-tests`  | Active-active control/counter processes, surviving application replicas, DB outage/WAL recovery and real Postgres package race/crash tests                                                       |
| `postgres_ha.py --backup-restore` | Pinned rootless dump/encryption scripts; local encrypted restore to separate databases; scoped retention/prune and negative credential/size tests; no off-host claim                             |
| `policy_state_smoke.py`           | Two WAFs/two PG authorities; shared native sliding/distinct/sequence state, authority loss, revision isolation, authenticated health, DB outage/recovery and no raw event marker in stored state |
| `spool_smoke.py`                  | Three 8 MiB multipart files with CRS off and on; late-body denial absent at origin; retained-body quota exhaustion yields 503 and recovers on close; 1 CPU/256 MiB container                     |
| `benchmark.py`                    | Standard-library bounded open-loop load; offered/completed counts, generator drops/lag, scheduling-inclusive p50/p95/p99, image/config hashes and raw cgroup CPU/memory counters                 |

`benchmark.py --body-bytes 2097152 --rate 1 --duration 5` measures multipart file traffic using a body-independent policy; `--no-coraza` selects the other profile. `buffered-nginx.conf` consumes the complete body before returning success; `X-Origin-Request-Bytes` is asserted against the offered file size. The late-body policy is checked after load. Multipart file acceptance does not prove file-content inspection or acceptance of arbitrary opaque bodies by CRS. The 64 MiB runtime ceiling is not a measured production capacity guarantee.

Local qualification on 2026-11-07 used native ARM64 Docker Desktop Linux. Native AMD64/ARM64 deployment, capture-bridge and Kubernetes jobs passed at `bbc20a6` ([run 42333924481](https://github.com/dreadl0ck/netcap/actions/runs/42333924481)). No emulated result counts as native qualification. Reports live in `$TMPDIR`/CI artifacts, not git.

### Local sustained qualification

`examples/firewall/qualification/` supplies a loopback-only open-loop runner and JSON receipts. Build tags are `coraza,http3,nodpi,noyara`; `runner.py` starts a detached owned process and records its birth/command identity, binary/source SHA-256, Go dependency versions, hardware and checkpoint. Evidence stays outside git. The supervisor defaults to 128 bounded generator workers; raw runner `-workers` defaults to 32. Scheduling-inclusive latency still counts generator pauses.

| Profile               | Exercised wire subset                                                                                                      |
| --------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| HTTP/1.1, H2, H3      | Native/CRS × 0/10/100/1000 filler rules: 24 profiles, each with a marker-denial rule                                       |
| Local evaluator state | One additional HTTP profile exercises a one-second sliding window and asserts zero groups/entries after expiry/maintenance |
| WebSocket / gRPC      | RFC 6455 uncompressed masked text/echo; identity unary gRPC over verified TLS H2                                           |
| DNS / Redis           | UDP A question/compressed A answer; RESP2 SET and denied FLUSHALL                                                          |
| Postgres / MySQL      | Protocol 3.0 startup/simple query; protocol-10 scripted greeting/4.1 handshake/COM\_QUERY                                  |
| Modbus / DNP3 / SMTP  | TCP FC3/FC6; unconfirmed single-fragment read/CROB; EHLO/envelope/whole DATA                                               |

The nine non-HTTP peers are owned scripted fixtures, not vendor-server version qualification. `protocols.py` separately requires every named integration test, every requested repetition and zero skips; these bounded tests cover additional prepared-statement, fragmentation, replay, authentication and dependency cases.

| Local gate       | Requirement                                                                                                                                                                             |
| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Load             | Allowed and denied operations on all 34 profiles; zero errors, generator drops, false blocks, forbidden origin bytes/requests and forbidden fixture effects; scheduled-arrival p99 ≤2 s |
| Resources        | Five-second whole-process samples: Go heap ≤1 GiB, RSS ≤2 GiB, descriptors/goroutines ≤4096, owned scratch ≤64 MiB; current/highwater/recovery plus local evaluator state are recorded  |
| Lifecycle        | Owned origin 503, policy reload, in-process proxy/listener restart and a changed TLS certificate SHA-256; allow/deny and released buffers are checked after recovery                    |
| Corpus           | Calibration/held-out business routes and attack controls require exact status and independent origin deltas; critical false blocks must equal 0                                         |
| FTW              | Immutable Apache-2.0 CRS source/license hashes; reviewed 941100 cases 2/4 over HTTP/1.1/H2/H3; four other upstream cases remain excluded                                                |
| Negative control | `-inject-leak` sends directly to the owned origin and must exit 1; `audit.py` repeats it against the measured binary                                                                    |
| Pilot            | `pilot.py` accepts only a finite allowlisted local fake plan; absent production authorization is recorded as unrun, not a code failure                                                  |

```bash
go test -race -tags coraza,http3,nodpi,noyara ./examples/firewall/qualification ./internal/waf
python3 -m unittest discover -s examples/firewall/qualification -v
ROOT=$(mktemp -d "${TMPDIR:-/tmp}/netcap-qualification.XXXXXX")
go build -tags coraza,http3,nodpi,noyara -o "$ROOT/qualify" ./examples/firewall/qualification
mkdir "$ROOT/run"
python3 examples/firewall/qualification/runner.py start "$ROOT/run" --binary "$ROOT/qualify" --duration 86400 --rate 50
python3 examples/firewall/qualification/runner.py monitor "$ROOT/run"
python3 examples/firewall/qualification/runner.py resume "$ROOT/run"
python3 examples/firewall/qualification/runner.py stop "$ROOT/run"
```

`resume` observes the same verified process/checkpoint; it never credits downtime or relaunches a dead process. `stop` refuses an unverified owner. A 24-hour request does not establish 24-hour evidence: only a completed `soak_24h_pass: true` does. OS-process/external-state disruptions under sustained load, vendor-server matrices and external UDP ingress/LB/NAT/CNI paths remain separate gates.

The measured baseline password false positive was CRS `942100`. Qualification uses exactly `crsTargetExclusions: [{path: /api/account, method: POST, argument: password, ruleID: 942100}]`; the original password case is calibration and a new password case remains held out. `coraza_exclusions_test.go` checks that XSS on that field, other fields/routes/methods and native denials remain enforced. Exclusions accept at most 32 literal scopes and only application-attack rule IDs.

For shorter evidence use `--duration 1800`; direct `-quick -mixed -duration 30s` is a quick check. Run `-ftw-only`, `protocols.py --repetitions 2` and `pilot.py --execute-local-fake` into fresh evidence directories, then join them with `audit.py --run R --ftw F --protocols P --pilot L --output A`. `qualification.json` distinguishes the local pass from every unrun deployment gate.

The native ARM64 sample on Apple M5 Max/Go 1.27.0 completed 1,800 seconds at 50 offers/s with 128 workers: 90,000 offers across 34 profiles, 71,980 allowed, 18,020 denied, zero errors/drops/false blocks/forbidden origin bytes or fixture effects. All 179 fault cycles recovered; maximum profile p99 was bounded by 256 ms. The 288 corpus rows and six FTW wire cases passed with zero protocol skips. `topic-owned-final-audit/qualification.json` records the joined local pass; the load receipt SHA-256 is `1915bf55ce55bcca6a23cbc0c478b3e4c98f316f0f5e103a980a61bde2c2123e`. This is 30-minute evidence; `soak_24h_pass` remains false.

## Rollout and rollback

### Versioned release candidates

`.github/workflows/firewall-release.yml` builds independent firewall candidates; `.goreleaser-firewall.yml` disables GoReleaser publication. The existing `.goreleaser.yml` and main Netcap release workflow retain their own release path. `firewall-v<SemVer>` is the firewall tag namespace. No script creates a tag, GitHub release or PR, or changes a cluster.

| Artifact / gate      | Contract                                                                                                                                                                                                                                                                                                                                                                           |
| -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Trust policy         | `scripts/firewall-release-policy.json`: issuer, exact workflow/tag identity, supported config/policy schemas, pinned tools, required qualifications and 3 external review slots                                                                                                                                                                                                    |
| Native build         | `firewall_release_build.py native`: clean committed checkout; native Linux runner and matching Docker architecture; GoReleaser WAF (`coraza,http3`) and enforcer binaries copied into release Dockerfiles once                                                                                                                                                                     |
| Version evidence     | `version` retains config/policy versions and adds `releaseVersion` / `commit`; `version-smoke` checks both runtime images, embedded version/commit and HTTP/3 build feature                                                                                                                                                                                                        |
| Qualification        | Each named policy qualification has a hashed log per architecture; Linux amd64 and arm64 receipts bind the same source commit/version to the shipped image digests; lab overlays add test tools and retain the shipped binary bytes                                                                                                                                                |
| Final candidate soak | `assemble --qualification-run <run>` validates a completed 24h mixed run, copies hashed receipts and binds them to both index digests. Publication rejects missing soak evidence, old commits, dirty binaries and changed before/after inputs. `check-qualification <run> --commit <full-SHA>` checks eligibility without publication                                              |
| Images               | OCI layouts preserve platform manifests; assembly creates 2 indexes containing exactly the tested amd64/arm64 children; promotion uses `crane copy`, never rebuilds                                                                                                                                                                                                                |
| Helm 3               | Packages all 3 charts with matching `version`, `appVersion`, image tag, repository and index digest; lint/render precede packaging; OCI promotion preserves the chart manifest digest                                                                                                                                                                                              |
| Offline assets       | Each architecture includes binaries, OCI archives, pinned Syft SPDX, source/license inventory and corresponding-source export; source includes the committed tree, vendored Go modules and Go toolchain source; checksum/signature bundles cover the complete directory                                                                                                            |
| Source inventory     | Every SPDX package needs a resolved license plus hashed license text and source export. Missing Alpine/base-image sources or unresolved Go licenses block validation; `blockers.json` lists supplemental work. `supplements.json` maps `name@version` to `license`, `source` and `licenseFile` paths beneath its own directory                                                     |
| Signatures           | Opt-in publication uses cosign keyless, exact GitHub OIDC issuer and workflow/tag identity; SLSA v1 predicates bind commit/version and digest, without claiming a SLSA assurance level. Per-platform SPDX is attested separately                                                                                                                                                   |
| Offline verification | `firewall_release.py verify` checks candidate/checksum signatures, all files, archive blob hashes/platform/labels/binary bytes, chart metadata, OCI chart layer hashes and all 9 signed provenance subjects. Supply an independently pinned Sigstore trusted root; never trust a root merely because it accompanies a download                                                     |
| Rehearsal            | `make firewall-release-rehearsal` creates isolated loopback registry fixtures, temporary keys and a no-services signing config; copies 4 image manifests, 2 indexes and 3 charts to another local repository and verifies signatures/attestations. Fixture receipts say `qualificationMode: rehearsal`, `native: false`; publication and ordinary release verification reject them |

Install the policy-pinned tools into an external directory, placing it first on `PATH`. `firewall_release_tools.py` downloads Syft, GoReleaser and Helm from their upstream release endpoints and checks upstream SHA256 files. Install crane/cosign with the exact Go module versions in the JSON policy. Current pins were checked against official GitHub releases and Helm's distribution endpoint on 2026-11-07; action commit pins match their official version refs.

```bash
make firewall-release-test
make firewall-release-rehearsal
make firewall-release-build FIREWALL_RELEASE_VERSION=0.1.0-rc.1 FIREWALL_RELEASE_OUTPUT="$TMPDIR/firewall-build"
# On each native Linux architecture; start a loopback-only registry first.
python3 scripts/firewall_release_build.py native --version 0.1.0-rc.1 --arch arm64 --output "$TMPDIR/candidate/arm64"
# Combine both architecture directories under one candidate root.
python3 scripts/firewall_release_build.py assemble --version 0.1.0-rc.1 --output "$TMPDIR/candidate"
python3 scripts/firewall_release.py validate "$TMPDIR/candidate"
# Published bundle verification uses no registry; root is provisioned independently.
python3 scripts/firewall_release.py verify ./candidate --offline --trust-root /trusted/sigstore-root.json
```

**Publication requires a separate manual decision.** PRs, tag pushes and the default `workflow_dispatch` produce candidates and loopback rehearsals only. The `publish` job requires `dryRun: false`, a matching existing firewall tag, matching commit and approval of the `firewall-release` environment. Configure that environment with required human reviewers and tag restrictions before use. Set `candidateRun` to the successful same-commit manual/tag candidate run and `inputsRun` to the review artifact run. The publication dispatch skips native builds/assembly, authenticates the candidate run's repository/workflow/commit, verifies its rehearsal bundle, attaches digest-bound reviews, then signs and copies those exact artifacts. A PR run cannot be used as a publication candidate.

| Manual release input   | Required evidence                                                                                                                                                                                                                                                                      |
| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Native qualification   | Successful same-commit Linux amd64/arm64 receipts; emulated or synthetic tests cannot satisfy this gate                                                                                                                                                                                |
| Soak input             | `firewall-release-inputs/qualification/` contains `manifest.json` and all named receipts from the final clean merged commit. Build the runner with VCS stamping enabled; keep source and binary unchanged until completion. The pre-UI `b2b72450` run cannot qualify a later candidate |
| External reviews       | `security`, `license-and-corresponding-source`, `operations`; each needs `decision: approved`, identified reviewer, HTTPS review URI, hashed evidence file, matching commit/version and both index digests; generated slots remain `pending`                                           |
| Input transport        | Same-repository `inputsRun` artifact named `firewall-release-inputs`; native jobs optionally read supplements; publication requires `reviews.json` and its hashed evidence files, copied by `apply-reviews` after verification of the original bundle                                  |
| Registry authorization | Publication job alone gets `packages: write` / `id-token: write`, with `contents: read`; optional short-lived `FIREWALL_REGISTRY_TOKEN` must be scoped to the intended repository/packages, otherwise job-scoped `GITHUB_TOKEN`; no contents write or repository-wide PAT              |
| Release storage        | Upload-artifact bundles are retained for 30/90 days; an operator must retain the approved offline bundle and independently pinned trust root in durable release storage                                                                                                                |

There is no external approval or production qualification supplied by the local rehearsal. `candidate-checklist.json` reports `publicationApproved: false`.

`scripts/firewall-integration-gates.json` records branch dependencies and external gates. The qualification runner requires `waf.Config.CRSTargetExclusions` and `waf.CRSTargetExclusion` from the web integration branch (`41535d61`); until that merge, its Go build fails rather than substituting an exception stub. The bounded pilot CLI remains local-only because no production target authorization exists.

### Verified upgrade planning

`scripts/firewall_release.py plan-upgrade` verifies both signed offline manifests before creating a mode-0600 state archive. It rejects unsupported config/policy schema versions, config/policy files outside the backup tree, symlinks, existing backup/output files and implicit downgrades. Configuration validation and Helm diff remain operator gates; the planner executes only fixed verification tools, never deployment commands or manifest-supplied commands.

```bash
# Stop/quiesce writers first; include configuration, policy and consistent state.
python3 scripts/firewall_release.py plan-upgrade \
  --current ./current --candidate ./candidate --offline --trust-root /trusted/sigstore-root.json \
  --state /private/firewall-state --config /private/firewall-state/config.yaml \
  --policy /private/firewall-state/policy.yaml --backup /private/backups/pre-upgrade.tar.gz \
  --output /private/backups/upgrade-plan.json --quiesced
```

For rollback, select the previous signed bundle as `--candidate` and add `--allow-downgrade`. The plan records source/target manifest hashes, exact image digests, schemas, configuration/policy hashes and backup hash; it never changes live state. Validate a restore and use the deployment-specific procedure below.

| Step             | Check                                                                                                                       |
| ---------------- | --------------------------------------------------------------------------------------------------------------------------- |
| Prepare          | Build shipping tags, validate exact configuration/policy, review image digest and Secret bootstrap identities               |
| Preview          | Helm schema/render tests, Compose origin-evidence checks, dedicated CNI/control qualification                               |
| Route            | Ingress only to WAF; separate origin policy; allowed and denied traffic with origin evidence                                |
| Observe          | Private readiness/metrics and bounded redacted audit; shared-guard/fleet readiness is a dependency boundary                 |
| File rollback    | `helm rollback firewall <revision> -n firewall --wait`; recheck traffic; rolling pods can briefly serve different revisions |
| Managed rollback | Single-target policy API restores SQLite activation; Helm rollback does not restore managed state                           |
| Fleet rollback   | Controller rollback with expected job phase/generations; verify acknowledgments and live target traffic                     |

No mode automatically routes clients directly to the origin on WAF failure. Retain prior image digests, values and consistent state snapshots.

## Deferred roadmap

| Remaining gate           | Exact boundary                                                                                                                                                                                                                                                      |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Production qualification | Passing native/cluster CI does not qualify another CNI, storage provider, traffic mix or external HTTP/3 UDP ingress/LB/NAT path                                                                                                                                    |
| HA / state loss          | SQLite remains singleton; Postgres application replicas are active-active, but primary fencing and DB HA remain database-operator responsibilities; stale-snapshot recovery is not lossless                                                                         |
| Distributed semantics    | Native thresholds/sequences are authoritative when configured; default local mode and the separate fixed-window guard retain their documented semantics; fleet acknowledgments are not an atomic cutover                                                            |
| Protocol extensions      | No encrypted passthrough payload decryption, WebSocket context takeover/window-size negotiation, HTTP/3 origin message transport, broad SMB interoperability or FTP active/PASV modes; gateway parsers cover the explicit subsets above                             |
| Storage / capacity       | Optional PG schema backup/encrypted upload/scoped retention is implemented; production repository provisioning, off-host restore/schedule qualification, SQLite offline automation and deployment-specific sizing remain; 64 MiB bounds do not establish throughput |

## Verification pitfalls

| Symptom                                                               | Correction                                                                                                                                             |
| --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Helm 3.8 templates as Kubernetes 1.23                                 | Pass `--kube-version 1.25.0` or newer; do not count version rejection as a schema negative test                                                        |
| Compose says `invalid mount path: nodev`                              | Quote the entire comma-containing tmpfs string in flow lists                                                                                           |
| Client gets 403 but origin saw the request                            | Require origin-log evidence, as `smoke.sh` does                                                                                                        |
| kind import fails on fixture archive                                  | Pull the digest-pinned backend in-cluster; load only locally built application images                                                                  |
| Managed StateDir is not 0700                                          | Use a private subdirectory beneath the PVC mount and preserve ownership across mounts                                                                  |
| Enforcer cannot stat host PID 1 namespace                             | Keep private PID visibility; host networking already identifies the node default network without SYS\_PTRACE                                           |
| `rollout status` rejects OnDelete                                     | Delete the selected pod deliberately, wait for its replacement and verify the actual API/table                                                         |
| Large-file test gets origin 413                                       | Raise the lab nginx `client_max_body_size`; its default is independent of WAF limits                                                                   |
| CRS rejects opaque upload fixture                                     | Use an explicitly typed multipart fixture for file-spooling qualification; do not report it as arbitrary opaque-body or file-content inspection        |
| Postgres crash test interrupts another package                        | Run the two PG packages with `-p 1` against their shared disposable DB; concurrency inside each test remains enabled                                   |
| Default-deny routed policy breaks allowed TCP                         | Match protected service replies explicitly; NFQUEUE covers both directions, not only client destination ports                                          |
| CodeQL `py/clear-text-storage-sensitive-data` on PG fixture env files | Keep generated DB passwords/DSNs in process environment; Restic's local fixture password file belongs only in container tmpfs, populated through stdin |
| HTTP/3 request trailers disappear after `WithContext`                 | quic-go v0.65.0 replaces `Request.Trailer` at EOF; retain the server-owned request for trailer inspection (`internal/firewalltransport/transport.go`)  |
| cosign v3 rejects `--offline` on `verify-blob`                        | Supply the independently pinned `--trusted-root` and complete v3 bundles; that command has no `--offline` flag                                         |
| Syft SPDX creator index 0 is an organization                          | Match the exact `Tool: syft-<pinned version>` entry anywhere in `creationInfo.creators`                                                                |
| Helm 3.22 schema diagnostics use `/runtime/field`                     | Negative render tests accept slash or dot field paths while still requiring schema rejection                                                           |
| BuildKit adds unknown-platform attestation children                   | Release runtime builds disable BuildKit provenance/SBOM; the release pipeline creates its own verified cosign/Syft attestations after qualification    |


# Architecture

The public Go executable is a concurrent packet-to-record pipeline with optional enrichment, detectors and evidence retention. Its internal packages are not a stable public Go SDK merely because their source is available.

| Stage           | Code                                                              | Responsibility                                                |
| --------------- | ----------------------------------------------------------------- | ------------------------------------------------------------- |
| CLI             | `cmd/net`, `cmd/capture`                                          | Registered commands, options and lifecycle                    |
| Collection      | `internal/collector`                                              | Read input, account for admission, dispatch work and finalize |
| Packet decoding | `internal/decoder/packet`                                         | Typed layer/protocol records                                  |
| Stream assembly | `internal/reassembly`, `internal/decoder/stream`                  | Directional TCP/UDP conversations and application parsers     |
| Enrichment      | `internal/resolvers`, `internal/vulndb`                           | Local source lookup and structured applicability              |
| Detectors       | `internal/rules`, `internal/networkdetect`, `internal/behavior`   | Expressions, pattern evidence and approved baseline changes   |
| Persistence     | `internal/netio`, `types`                                         | Record framing, output writers and schemas                    |
| Investigation   | `internal/evidence`, `internal/evidencelink`, `internal/identity` | Source/scope witnesses, links and host/account provenance     |
| Interfaces      | `cmd/capture/webui`, `internal/mcp`                               | Embedded browser/API and MCP tools                            |

## Ownership and timing

Packet admission, worker execution, stream completion and postprocessing are different lifecycle phases. Stream/aggregate records can be emitted after later packets have already produced packet records. `dump` sorting does not alter this execution history. Capture-time correlation and browse-time evidence linking therefore have different guarantees.

Flow-aware dispatch keeps related traffic together where its key is available. Native DPI contexts and pending queues are separately bounded. Backpressure and capture loss are observations to inspect, not conditions a generic concurrency diagram can rule out. [Workers](/develop-and-extend/workers) lists practical budgets.

## Data contracts

| Contract                      | Reference                                                                |
| ----------------------------- | ------------------------------------------------------------------------ |
| Audit wire format             | [Specification](/develop-and-extend/specification), `types/netcap.proto` |
| NVD SQLite                    | `internal/vulndb/SCHEMA.md`, schema 2                                    |
| Source/signature verification | [Database updates](/enrichment/database-updates)                         |
| Capture/stream scope          | [Evidence](/investigate-evidence/evidence)                               |
| Typed rule expressions        | [Rules engine](/investigate-evidence/rules_engine)                       |

Build tags change native integrations and available paths. Separate the public Go release contract from source-only experimental code and from another implementation's API. [Adding decoders](/develop-and-extend/extension) covers extension points.

## Decoder qualification

| Reference                                                          | What it checks                                                             |
| ------------------------------------------------------------------ | -------------------------------------------------------------------------- |
| `internal/decoder/stream/selection.go`                             | Evidence-specificity ranking and transport/port eligibility                |
| `decoder_matching_test.go`, `confusable_test.go` in that directory | Competing decoder signatures and their specificity margins                 |
| `reader_hygiene_test.go` in that directory                         | Emission, captured-fragment timing and direction across registered readers |
| `internal/decoder/core` fragment index                             | Map byte offsets back to captured fragments                                |
| Collector corpus/regression tests                                  | Record output and worker/replay invariance                                 |

Selector history and earlier before/after measurements remain in Git history. Current fixes must preserve stronger-signature selection and message provenance; a microfixture pass is not a complete protocol-conformance claim. See [testing](/develop-and-extend/tests) for corpus prerequisites and skip handling.


# Workers and resource budgets

Go v0.15.2 defaults capture workers to `max(1, GOMAXPROCS)`. Dispatch uses a symmetric flow key where possible, with a fallback when no suitable key exists; it is not simply round-robin for every packet.

```sh
net capture -read traffic.pcap -out four-workers -workers 4 -dpi=false
```

More workers do not guarantee more throughput: disk, parsing, native analyzers, input locality and aggregation can dominate. Benchmark identical input/options and compare output witnesses as well as elapsed time and memory.

| Budget/default                              | Scope                                                                                               |
| ------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| Packet buffer: 1,000 entries                | Per configured worker queue                                                                         |
| Writer buffer: 64 KiB                       | Per decoder writer, not total process memory                                                        |
| Reassembly maximum buffered size: 10 MiB    | Per stream direction; zero means unlimited                                                          |
| Out-of-order page pressure thresholds: zero | Per worker/connection; unlimited unless configured, not a global RAM cap                            |
| Retained TCP payload: zero                  | `-max-retained-tcp-bytes` bounds reader-owned payload copies across all workers; zero is unlimited. |
| DPI automatic contexts                      | Up to 8; distinct from protocol workers                                                             |
| Evidence index                              | 64 MiB accounted storage plus record/link bounds                                                    |
| Optional packet retention                   | Default selected budgets: 32 MiB segments / 512 MiB retained                                        |
| Service upload                              | Default 100 MiB per file; not a hard global filesystem ceiling                                      |

Out-of-order page caches allocate lazily (`internal/reassembly/memory.go`). `BenchmarkPageCacheInitialization`, Darwin/arm64 Apple M5 Max, 3 runs at 100 ms:

| Page-cache instances | Before, bytes/op | Lazy, bytes/op |
| -------------------- | ---------------: | -------------: |
| 1                    |        2,057,561 |             88 |
| 2                    |        4,115,121 |            176 |
| 4                    |        8,230,240 |            352 |
| 8                    |       16,460,483 |            704 |

These are initialization allocations, not whole-capture RSS. In-order streams allocate no out-of-order pages; the first queued segment initializes the existing 1,024-page cache. Aggregate reassembly/parser memory still needs separate bounds.

Check `capture -h` for the exact option names and installed defaults. Queue occupancy/drop counters, `capture-manifest.json`, reassembly health and behavioral health report different layers. A null kernel counter is unavailable, not zero.

```sh
net capture -read traffic.pcap -out bounded -workers 8 \
  -max-retained-tcp-bytes 67108864 -dpi=false
```

This configures 64 MiB across all eight workers, also available through `NC_MAX_RETAINED_TCP_BYTES`. Completed connections return their reservations. Exhaustion cancels collection, returns a nonzero CLI result, records `capture-manifest.json` status `error`, and withholds `audit-output-ready.json`. `TCPReassemblyHealth.json.retainedPayload` records the limit, peak, current and rejected bytes; a shutdown current value of zero means released storage.

With `-conns`, per-stream manifests preserve `locally-truncated` status and quoted `discardedBytes`/`discardReason` spans, including loss-only streams with empty raw files. These local omissions do not increment network `missingBytes`.

The bound excludes assembler pages, connection/fragment metadata, decoder-owned caches and process RSS. Existing page thresholds remain per-worker pressure controls. A budget-aborted output is partial evidence, not a finalized analysis.

## Operational tuning

1. Measure the input packet rate and required decoder/enrichment set.
2. Retain a representative benign fixture and expected output counts/hashes.
3. Change one budget at a time; replay the same capture into fresh directories.
4. Inspect error/drop/completeness witnesses and native context statistics.
5. Validate live behavior separately: offline file throughput does not measure kernel drops, capture privileges or a production SPAN path.

Do not disable bounds or silently drop record families to produce a faster benchmark. [Testing](/develop-and-extend/tests) explains worker-invariance qualification.


# Record format

Netcap audit files contain a protobuf Header followed by length-delimited protobuf messages of the header's record type. An optional gzip stream wraps that content. A `.ncap` file is not one giant protobuf object, and a `.ncap.gz` file must be decompressed before reading its message framing.

| Layer              | Contract                                                                       |
| ------------------ | ------------------------------------------------------------------------------ |
| Compression        | Optional gzip; preserve CRC/truncation errors                                  |
| Framing            | Varint length, then that many encoded message bytes                            |
| First message      | Header identifies record type, creation/build information and payload presence |
| Following messages | Instances of the declared record schema                                        |

Use the release's [`types/netcap.proto`](https://github.com/dreadl0ck/netcap/blob/v0.15.2/types/netcap.proto) and generated bindings. Raw capture timestamps are integer Unix nanoseconds; some exporter-oriented methods/display modes deliberately convert units. Verify the particular interface instead of assuming every numeric time is milliseconds.

## Inspect a file

```sh
net dump -read analysis/UDP.ncap.gz -header
net dump -read analysis/UDP.ncap.gz -fields
net dump -read analysis/UDP.ncap.gz -json
```

Header/field discovery is preferable to stale schema excerpts. Preserve unknown protobuf fields where an integration supports round-tripping. Field additions do not authorize renumbering or reinterpreting historical fields.

## Implement a reader

1. Detect compression from the actual input, not an assumption about its name.
2. Read one bounded varint-delimited Header.
3. Resolve the record type using bindings from a known schema revision.
4. Iterate bounded frames; distinguish clean EOF from a partial varint/message.
5. Surface gzip checksum errors and unsupported schemas instead of silently accepting partial evidence.

The Go reader is in `internal/netio`; framing code is in `internal/delimited`. These internal packages are implementation references, not unrestricted import paths for external Go modules. [Python readers](/develop-and-extend/python-integration) and [compression](/develop-and-extend/data-compression) cover integration details.

NCAP audit records, NVD's SQLite schema 2 and `Hosts.json` are separate contracts. Do not infer their version numbers or encoding from one another.


# Compression

Local protobuf capture output normally uses gzip (`TYPE.ncap.gz`). Disable it explicitly when needed:

```sh
net capture -read traffic.pcap -out plain-audit -compress=false -dpi=false
net dump -read plain-audit/UDP.ncap -json
```

`-compress` is the current flag; historical `-comp` examples are obsolete. The buffered/parallel gzip implementation trades CPU, buffers and I/O differently for each workload. Local writer concurrency and distributed collector gzip are not one universal configuration.

| Concern                  | Guidance                                                                      |
| ------------------------ | ----------------------------------------------------------------------------- |
| Storage                  | Measure on representative records; there is no universal percentage reduction |
| Streaming readers        | Consume complete framed messages and report gzip integrity failures           |
| Truncated capture/output | Decompression success alone does not prove full analysis completion           |
| Evidence                 | Record source/output hashes and keep the original compressed file             |

Compression is neither encryption nor anonymization. Payloads and credentials remain sensitive after gzip compression. [Record format](/develop-and-extend/specification) explains the framing inside the stream.


# Packet contexts

`PacketContext` carries related IP/port information on supported audit records. It allows a transport or application record to retain endpoints that otherwise belong to another decoded layer. Capture enables `-context` by default.

```sh
net capture -read traffic.pcap -out context-audit -context=true -dpi=false
net dump -read context-audit/UDP.ncap.gz -fields
net dump -read context-audit/UDP.ncap.gz -json
```

Use [the synthetic capture](/start-here/quickstart) for a known UDP example. CSV rendering flattens supported context fields into columns such as `SrcIP` and `DstIP`; `dump -fields` prints one selectable field per line. Duplicate transport fields need not be repeated in context.

| Context                | Boundary                                                          |
| ---------------------- | ----------------------------------------------------------------- |
| Packet endpoints       | Observed addresses/ports, not authenticated asset identity        |
| Connection orientation | Can differ from an individual packet's direction                  |
| Community ID           | Cross-tool flow correlation, not a globally unique observation id |
| Evidence link          | Scoped reference plus provenance, beyond merely sharing endpoints |

Read the current schema in `types/netcap.proto`. A historical four-field excerpt is not the full contract for every record. Disabling context reduces information available for later joins; it does not anonymize retained payloads. See [hosts and identity](/investigate-evidence/host-identity) and [evidence linking](/investigate-evidence/evidence).


# Python readers

For current Go records, the simplest Python boundary is `net dump -json`: one JSON object per record, with schema-specific fields and base64 byte values. This avoids coupling a Python reader to stale generated protobuf bindings.

## Usage

```sh
net dump -read example-audit/UDP.ncap.gz -json > udp.ndjson
```

```python
import json

with open("udp.ndjson", encoding="utf-8") as source:
    for line in source:
        record = json.loads(line)
        print(record.get("SrcPort"), record.get("DstPort"))
```

Use [the first capture](/start-here/quickstart) to create this input. Inspect the emitted JSON before selecting names: JSON naming comes from the record's renderer and can differ from protobuf/CSV field names.

### Read into pandas dataframe

```python
import pandas as pd

frame = pd.read_json("udp.ndjson", lines=True)
print(frame.columns)
```

Pandas is optional and installed separately. Preserve nanosecond integer times without converting through floating point; large integers can lose precision.

## Source Code

The separate [pynetcap repository](https://github.com/dreadl0ck/pynetcap) contains an NCAP reader and DataFrame helpers. Its existence is not a compatibility guarantee with every record in Go v0.15.2. Verify its generated schemas and a known fixture before using it for current evidence.

For a direct reader, follow the [record framing](/develop-and-extend/specification), generate Python bindings from the matching `types/netcap.proto`, and distinguish clean EOF from a truncated frame or gzip integrity failure.


# Adding decoders

Add public Go decoders under `internal/decoder/packet` or `internal/decoder/stream`. Use the matching v0.15.2 implementation as the API reference; historical `CreateLayerEncoder` examples no longer describe the current decoder constructors.

## Protocol Buffer Definitions

Extend `types/netcap.proto` with a message and, when needed, a unique `NC_` type enumeration. Preserve existing field/enum numbers and reserve removed ones. Timestamps use `int64` Unix nanoseconds, not the old string representation.

Generate with the project's `gogofaster` plugin:

```sh
zeus gen-proto-dev
```

The underlying invocation is `protoc --proto_path=types --gogofaster_out=types/. types/netcap.proto`. Use the generator version pinned by the checkout's tooling/dependencies and review the generated diff; `--gogo_out` is not interchangeable.

## Encoder Implementation

| Decoder kind            | Current example                         | Registration/behavior to inspect                             |
| ----------------------- | --------------------------------------- | ------------------------------------------------------------ |
| Packet layer            | `internal/decoder/packet/arp.go`        | `newGoPacketDecoder`, typed handler, registered layer/type   |
| Custom packet/aggregate | `internal/decoder/packet/connection.go` | Initialization, concurrency, bounded state and finalization  |
| TCP/UDP stream          | `internal/decoder/stream/`              | Selector specificity, framing, directions, gaps and teardown |

For ARP, `decodeARP(*layers.ARP, int64)` returns a protobuf message. The current imports use `github.com/gopacket/gopacket` and `github.com/gogo/protobuf/proto`. Do not copy obsolete examples importing the historical gopacket fork.

Stream parsers must bound buffered lengths before allocation, distinguish unsupported content from malformed framing, and retain gap/completeness semantics. A port number alone is not sufficient evidence to select an ambiguous protocol parser.

## Audit Record Interface Implementation

Implement the actual `types.AuditRecord` interface in `types/audit_record.go`: CSV header/values, `Time() int64`, endpoints, metrics, JSON, packet context, encoding, analysis and `NetcapType()`. Keep display and wire timestamp units explicit.

Ensure CSV headers match values, nested fields render consistently, byte fields have a defined representation and `SetPacketContext` updates the record pointer.

## Add Initializer

Register the message in `internal/netio.InitRecord` and the relevant decoder registry. Confirm `dump -header`, `-fields`, `-json` and selected CSV all work on a generated fixture. Add browser/API rendering only where that record is exposed.

## Verification

Add meaningful tests for valid input, partial framing, oversized lengths, retransmissions/gaps and unsupported cases. Assert records/health artifacts, not merely absence of a panic. Run affected packages and relevant [capture regressions](/develop-and-extend/tests), including worker invariance for shared state.


# Testing

The root `Makefile` defines test entrypoints; build tags and native dependencies must match the feature being tested. List targets with `make test-help`.

## Prerequisites

Use the Go version in `go.mod` and install native dependencies as described in [installation](/start-here/installation). Integration/corpus tests may need external captures. A skipped corpus test is not evidence that its assertions passed.

## Unit Tests

```sh
make test-unit
make test-pkg PKG=./internal/collector/
```

`test-unit` runs `go test -short -race -coverprofile=coverage.out ./...`. For a reduced native-dependency build, choose explicit tags:

```sh
GOWORK=off go test -tags nodpi,noyara ./internal/delimited ./types
```

Run the affected package and meaningful regression fixtures before broadening the suite. Review the actual assertions and skip messages; historical pasted test output does not describe the current suite.

## Documentation qualification

```sh
make docs-check NETCAP_BIN=/absolute/path/to/net
```

Python 3 and Bash are required. The checker reads runnable blocks directly from the [investigation](/start-here/investigation-walkthrough) and baseline guides, creates offline fixtures in a fresh temporary workspace, and checks positive and benign rule cases, extracted bytes, evidence export, configuration parsing and baseline approval/restart. It also validates navigation, Markdown targets and shell syntax. It never sends captured packets.

`make docs-source-check` checks protobuf field excerpts, compiles concrete YAML examples without overriding their `enabled` state and tests representative positive/negative expressions. Run source checks with the build tags appropriate for the installed libraries. `make test-golden-update` is retired: no golden-update suite exists, and the target now fails explicitly instead of printing a misleading success message.

`.github/workflows/documentation.yml` runs these contracts and the marked lab on documentation/source changes. It builds current source with optional native analyzers disabled; release qualification additionally uses the actual release binary through `NETCAP_BIN`.

## Capture regressions

| Command                 | Scope                                                               |
| ----------------------- | ------------------------------------------------------------------- |
| `make test-all`         | Unit, integration and regression entrypoints                        |
| `make test-e2e`         | Tagged CLI workflow tests                                           |
| `make test-determinism` | Required Ultimate PCAP worker-count invariance and repeatability    |
| `make test-wireshark`   | Checksum-pinned Wireshark corpus; NetMon conversion needs `editcap` |

Determinism checks compare complete output, not just total record counts. Use `NETCAP_REQUIRE_ULTIMATE_PCAP=1` (as the determinism target does) when a missing fixture must fail qualification instead of skip. Fetch recipes live in `scripts/` and `zeus/`; do not substitute an unverified capture with the same name.

## Benchmarks

```sh
GOWORK=off go test -tags nodpi,noyara -run '^$' -bench '^BenchmarkInitRecord' -benchmem ./internal/netio
```

Expect `BenchmarkInitRecordFirst` and `BenchmarkInitRecordLast` measurements. `internal/delimited` currently has no benchmarks; an exit-zero command with no `Benchmark…` rows is not a measurement. Record hardware, Go version, build tags and corpus hash. A record-initializer microbenchmark is not end-to-end live capture capacity. Compare completeness and resource use alongside throughput.

## Race Detection Tests

```sh
make test-race
```

Race instrumentation changes timing and memory demand. Native analyzers may need separate sanitizer qualification; a Go race pass covers only exercised instrumented paths.


# macOS development

Build the public Go checkout with the Go version in `go.mod`, Xcode command-line tools, libpcap headers and the embedded browser assets. Prebuilt release runtime requirements are listed in [installation](/start-here/installation).

## Prerequisites

With Homebrew already installed:

```sh
brew install go libpcap node pnpm
go version
pnpm --version
```

Confirm the Go version satisfies `go.mod`; the old “Go 1.21 or later” minimum does not describe v0.15.2. Use the checkout's declared package-manager version when building the UI.

## Clone and Build Netcap

Follow the tagged [manual build](/start-here/installation#manual-build) to build the UI and a `nodpi,noyara` executable. Those tags disable optional native DPI/YARA, not libpcap. Building full DPI requires the matching native runtime dependencies and recipes in `zeus/scripts/`.

Use `./net --version` to inspect the resulting binary. A build to the project directory does not replace another `net` already installed in `PATH`.

## Generate Protocol Buffers

An unchanged checkout includes generated Go bindings. Only install generators when changing `types/netcap.proto`:

```sh
brew install protobuf
go install github.com/gogo/protobuf/protoc-gen-gogofaster@v1.3.2
export PATH="$(go env GOPATH)/bin:$PATH"
protoc --version
protoc --proto_path=types --gogofaster_out=types/. types/netcap.proto
```

Check the checkout's gogo version with `go list -m github.com/gogo/protobuf` before changing generator pins. `zeus gen-proto-dev` wraps Go generation. Swift/JavaScript plugins are only needed when deliberately generating those bindings; they are not prerequisites for a normal Go build.

## Environment Variables

Use `GOWORK=off` for release-like builds. A local `go.work` can silently replace the pinned go-dpi module with a sibling checkout. `NC_CONFIG_ROOT` controls local runtime data separately; see [configuration](/start-here/configuration).

## Troubleshooting

| Error                           | Check                                                                |
| ------------------------------- | -------------------------------------------------------------------- |
| Missing embedded frontend files | Build `cmd/capture/webui/frontend` first                             |
| `pcap.h` or linker error        | C toolchain/libpcap and matching architecture                        |
| `protoc-gen-gogofaster` missing | Go binary directory in `PATH`                                        |
| Unexpected large generated diff | Generator version/options; use `gogofaster`, not `gogo`              |
| Linter refuses Go version       | Linter was built with an older Go toolchain than the module requires |

Run [scoped tests](/develop-and-extend/tests); format only changed Go files. Follow [extension](/develop-and-extend/extension) for decoder registration and schema contracts.


# Contributing

Contributing to the Netcap project

Contributions welcome! If you have an idea or questions, please feel free to reach out!

## Development Setup

Before contributing, make sure to set up your development environment:

* **macOS**: See the [macOS Development Setup](/develop-and-extend/macos-development-setup) guide for complete installation instructions, including Protocol Buffer plugins
* **Linux/Windows**: See the [Installation](/start-here/installation) guide and ensure you have Protocol Buffers compiler and plugins installed

## Issues & Bug Reports

Please include the Netcap version, the exact error messages and as much log output as possible!

Try to answer these questions in your Bug Report:

* What version of Netcap, which OS, which version of OS did you use?
* What did you want to do?
* What happened instead?
* What output did you get?

## Contributor License Agreement (CLA)

All contributors must sign our Contributor License Agreement before their contributions can be accepted. This ensures we can continue to offer NETCAP under both open-source (GPLv3) and commercial licenses.

### For Individual Contributors

When you submit a pull request, our CLA Assistant bot will automatically check if you have signed the CLA. If not, it will ask you to sign by commenting:

```
I have read and agree to the NETCAP Individual CLA Version 1.1
```

Read the full [Individual CLA](https://github.com/dreadl0ck/netcap/blob/master/.github/CLA-INDIVIDUAL.md) before signing.

### For Corporate/Entity Contributors

If you are contributing on behalf of your employer or another organization, please complete the [Entity CLA](https://github.com/dreadl0ck/netcap/blob/master/.github/CLA-ENTITY.md) and send it to the project maintainers before submitting contributions.

## Pull Requests

Before submitting your pull request please make sure:

1. The unit tests execute without errors
2. You have signed the CLA (or will sign it when the bot prompts you)

## Feature Requests

You have an idea for a new feature? Create a feature draft and open an issue to discuss it.


# FAQ

## What can I use this for?

The public Go framework turns live packets or PCAP/PCAPNG files into structured records, browser investigations and reproducible evidence. Start with the [synthetic capture](/start-here/quickstart) and [protocol coverage](/capture-and-inspect/protocol-support).

## Does a protocol label mean the payload was decoded?

No. Port names, DPI labels, handshake metadata and complete application parsing are different capabilities. [Service identification](/enrichment/deep-packet-inspection) describes their boundaries; encrypted payloads need separately supplied plaintext or secrets for supported experiments.

## Does an alert prove compromise?

No. A rule match, behavioral deviation or NVD applicability candidate needs validation against its source, scope and asset context. [Evidence](/investigate-evidence/evidence) and [network detections](/investigate-evidence/network-detections) show that workflow.

## Can I expose the WebUI publicly?

The local UI/API is unauthenticated. Keep it on loopback or place an appropriate authenticated hosting boundary in front of it. An MCP token protects `/mcp`, not every `/api` route; see [Web interface](/capture-and-inspect/web-interface#hosting-boundary).

## How do I export CSV or JSON?

Use `net dump`, not the Prometheus `net export` command. Follow [record inspection](/capture-and-inspect/filtering-and-export).

## How can I contribute to the project?

See [contributing](/develop-and-extend/contributing) for the CLA, development setup and tests.

## I have a question, how can I reach you?

Open an issue at [dreadl0ck/netcap](https://github.com/dreadl0ck/netcap/issues) with version, exact command and error. The maintainer address is `dreadl0ck [at] protonmail [dot] ch`.


# Shell completion

The repository ships `scripts/completions/net.bash`, a Bash completion adapter that calls the executable's legacy `-previous`, `-current` and `-full` interface. Completion suggestions are convenience output; `net COMMAND -h` and the [registered command inventory](/start-here/commands) define the executable interface.

## Installation

For Bash, source the reviewed script from your checkout:

```sh
source scripts/completions/net.bash
```

Add it to the startup configuration of the shell you actually use if desired. System completion directories vary by distribution and Homebrew prefix; do not assume `/usr/local` on Apple Silicon.

For Zsh's Bash compatibility layer:

```sh
autoload -U +X compinit
compinit
autoload -U +X bashcompinit
bashcompinit
source scripts/completions/net.bash
```

Verify a known current command and flag after sourcing. Historical suggestions may include `split` or other stale interfaces; a suggested token does not make it a registered command in v0.15.2.


# Downloads

A collection of cheatsheets and useful resources

## Releases

You can find the latest release on the releases page on GitHub:

{% embed url="<https://github.com/dreadl0ck/netcap/releases>" %}

## Publications

In this paper, we explore Graph based analysis using Maltego to visualise data from NETCAP during a forensic investigation:

### Thesis

{% file src="/files/-MZYVqd634CRbvNe2lsc" %}
Implementation and Evaluation of secure and scalable anomaly-based Network Intrusion Detection
{% endfile %}

### Thesis Presentation

### SecurIT Cup 2018 Presentation

## External Publications

The authors used the framework to process their recorded PCAP dumps:

{% embed url="<https://easychair.org/publications/preprint/36pZ>" %}

## Cheatsheets

The PDFs below are historical publications, not the v0.15.2 command/schema reference. Use [commands](/start-here/commands), [record inspection](/capture-and-inspect/filtering-and-export) and `net COMMAND -h` for current executable examples.

### List of all supported protocols and fields

{% file src="/files/SCeOZ6EBiFVnaMpwU8aa" %}

### Command Cheatsheet

{% file src="/files/J6ITgt9CEUck9rxcyBog" %}


# Releases and migration

Detailed Version History Information

## Source-only corrections

These changes follow v0.15.2; they do not change an existing release archive.

| Change                                                                           | Migration/qualification                                                                              |
| -------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| S7 requests gated by message role; response allowlist uses destination initiator | “Completed” rule renamed to acknowledgment; no header-only execution claim                           |
| DNP3 group 60 variation 1 mapped to Class 0; 2–4 to classes 1–3                  | Corrected integrity-poll rule; released binaries need an external corrected pack or a future release |
| Grouped offline rules and audit readiness                                        | Source-only `investigate rules`; separate pack format and finalized-capture requirements             |
| Documentation contracts                                                          | `make docs-check` runs published lab commands; `make docs-source-check` checks schema/rule examples  |

## v0.15.2

The [binary release](https://github.com/dreadl0ck/netcap/releases/tag/v0.15.2) ships signed community database installation and qualified native runtimes. v0.15.0/v0.15.1 were runtime-qualification candidates.

| Area         | Released change                                                                                         |
| ------------ | ------------------------------------------------------------------------------------------------------- |
| Updates      | Embedded Ed25519 verification root, expiring signed releases, monotonic sequence/epoch and exact hashes |
| Data         | NVD SQLite schema 2, DB-IP City/ASN, IANA, UA-parser and pinned BSD HASSH                               |
| Installation | Cross-process update lock, staged activation and preservation on failure                                |
| Linux        | Embed the actual built WebUI through an explicit Docker build context                                   |
| macOS        | Relocated bundled native libraries; DPI macOS 26+, nodpi macOS 15+                                      |
| Provenance   | Native-runtime hashes, package notices and corresponding source assets                                  |
| Windows      | Qualified signed download/update and structured CVE lookup                                              |

### Migration checklist

| Previous workflow                          | Current workflow                                                                                 |
| ------------------------------------------ | ------------------------------------------------------------------------------------------------ |
| Old executable/CLI recipes                 | `net --version`, [command inventory](/start-here/commands) and installed help                    |
| CSV through `export`                       | `dump -csv`; `export` serves Prometheus metrics                                                  |
| Generic generated config                   | Explicit supported flags/env; `-gen-config` remains unimplemented                                |
| v0.14.0 community snapshot                 | Frozen `/dbs/v3/`; upgrade for signed refreshes                                                  |
| v1/v2 database endpoint or SQLite schema 1 | Upgrade client and download schema 2; do not edit a version field                                |
| Nmap/CMS/DHCP OS/JA3 catalogue assumptions | [Current source inventory](/enrichment/database-updates) and bounded built-in service signatures |
| Older `agent`/`collect` wire format        | Upgrade both ends; see distributed collection below                                              |

Publisher policy/source-provenance changes after the v0.15.2 tag are source/server changes, not additional features of that binary. The remaining sections retain historical release context; use the current topic guides for executable recipes.

## v0.13.0

The v0.13.0 notes recorded 524 passing tests in affected Go packages. [Release notes](https://github.com/dreadl0ck/netcap/blob/v0.13.0/RELEASE_NOTES.md) describe the evidence-linking and capture-time DNS features.

| Change                                                                                                               | Evidence                                                                                                        |
| -------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- |
| Scoped cross-protocol linking, immutable audit references, capture-time DNS context and independent feature switches | `29464936`, [release notes](https://github.com/dreadl0ck/netcap/blob/v0.13.0/RELEASE_NOTES.md#hunting-evidence) |
| Shared UI 0.13.0, including related evidence and tagless-alert rendering                                             | `cmd/capture/webui/frontend/packages/netcap-ui/package.json`                                                    |

## v0.10.3

### Native DPI

`go-dpi v1.5.0` adds worker-owned native contexts and incremental flow state. Inspection stops after 10 observations; consecutive duplicate enrichment calls share progress. `-dpi-workers` / `NC_DPI_WORKERS` selects the context count; `1` minimizes native context memory.

| DPI microbenchmark                           | replay baseline    | incremental integration |
| -------------------------------------------- | ------------------ | ----------------------- |
| LPI + nDPI, 10 unidentified packets          | 98.75 µs/flow      | 17.42 µs/flow           |
| LPI + nDPI, 100 unidentified packets         | 1,395.57 µs/flow   | 40.53 µs/flow           |
| 32,768 single-packet flows, one nDPI context | 109.1 MiB peak RSS | 64.7 MiB peak RSS       |

Measured on Apple M5 Max, Go 1.27.0, nDPI 4.14.0. These are DPI microbenchmarks; whole-capture throughput depends on the workload. Eight contexts used 126.2 MiB in the single-packet probe. Small unidentified first packets are replayed once when promoted to persistent native state. Samples and reproduction commands: `internal/dpi/performance-results.json` and `zeus/scripts/benchmark-c-dpi.sh`.

### Geolocation

`net util -download-dbs` bundles DB-IP Lite City geolocation. `-geoProviders` selects the providers; `docs/resolvers.md` records attribution and configuration. Installs upgraded from the bleve layout are prompted to download `netcap.sqlite`.

### Distributed collection

The `net agent` / `net collect` wire format is new and incompatible with v0.10.2 and earlier. Nothing working depended on the old one: **no earlier release produced readable output.** It sent records without length prefixes, so every `.ncap.gz` after the header was unreadable. Setup: [distributed-collection.md](/integrations-and-operations/distributed-collection).

| v0.10.2 and earlier                                                                                         | now                                                                           |
| ----------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
| records sent without length prefixes                                                                        | each record length-delimited, and validated before it is written              |
| first batch per file dropped                                                                                | written                                                                       |
| unlocked shared file map, concurrent gzip writes                                                            | one locked writer per client and type                                         |
| 10 KiB UDP receive buffer; a full batch, or any short or forged datagram, panicked the collector            | TCP frames up to 4 MiB; malformed input closes that connection only           |
| UDP + NaCl box, no reconnect or delivery guarantee                                                          | TLS 1.3, acknowledged batches, reconnect with backoff, in-memory resend queue |
| any client key accepted; client-chosen `ClientID` used as a directory (`../`, absolute paths)               | allowlist of pinned agent keys; the directory is the allowlist name           |
| stream and abstract decoders never drained, so they blocked once their channel filled; no stream reassembly | all decoders drained; `-reassemble-connections` on by default                 |
| partial batches never sent, nothing sent on exit                                                            | `-flush-interval`, and delivery of queued batches on SIGINT/SIGTERM           |
| agent panicked on teardown (`NumStreamWorkers` 0)                                                           | agent starts from the decoder defaults                                        |

Removed flags: `-pubkey` (agent), `-privkey`, `-membuf-size` (collector), `-config` and `-gen-config` on both (they were never implemented). `types.Batch.ClientID` is reserved.

## v0.5 - April 2020

### Fixed

* multiple bugs in the stream reassembly
* several panics during parsing in gopacket

### Changed

* CLI interface refactored: single binary app with subcommands, stripped size \~**17MB**
* Updated units tests
* Documentation updates
* Updated Docker containers for **Ubuntu** and **Alpine**
* Compiled with **Go 1.14.2**
* removed custom audit records Link-, Network- and TransportFlow

### New Features

* **Maltego** integration
* **File** audit records
* **Diameter** protocol audit records
* **SMTP** audit records
* **POP3** support for extracting Mails
* **JA3S** support and separate audit record for **TLSServerHello**
* New configuration options: via **environment variables** or **configuration** file
* Resolvers package for **Geolocation**, **DNS** and **Service** lookups and **whitelisting**
* Deep Packet Inspection via **nDPI** and **libprotoident**
* **DeviceProfile** Audit records, to capture the behavior of a single device within a traffic dump
* Added an integration for **bash-completion** support


# License

## GNU General Public License v3.0

The public Go Netcap source is GPL-3.0-or-later. GPL is a strong-copyleft license; the historical description of it as “very permissive” was incorrect. See the [project LICENSE](https://github.com/dreadl0ck/netcap/blob/v0.15.2/LICENSE) and source-file notices for the actual terms.

## Third-party components and data

| Material                   | Applicable inventory                                       |
| -------------------------- | ---------------------------------------------------------- |
| Go/native dependencies     | Release `legal/` notices and bundled source assets         |
| Native runtime             | `native-runtime-inventory.json` and runtime source archive |
| Enrichment datasets        | `DATABASE_NOTICES.txt` and `RELEASE_MANIFEST.json`         |
| Plain JA4 TLS fingerprint  | BSD terms included with the implementation                 |
| Optional JA4+ source build | Separate opt-in terms; excluded from official binaries     |

`net licenses -h` describes the executable's license inspection commands. A license for Netcap does not replace third-party data/runtime obligations. [Database updates](/enrichment/database-updates) records source provenance and retired catalogues.

## Commercial License

An alternative commercial license is available for covered Netcap code. The [commercial agreement](https://github.com/dreadl0ck/netcap/tree/master/docs/COMMERCIAL-LICENSE.md) is a template with placeholders; it does not itself grant rights until the parties agree and execute it. Its third-party component exclusions still apply.

## Usage Disclaimer

The GPL warranty disclaimer applies. Qualify the release, enabled features and capture completeness for your use case with [tests](/develop-and-extend/tests) and [health evidence](/investigate-evidence/evidence). An alert, software fingerprint or reconstructed file is evidence to evaluate rather than a guarantee of compromise or safety.


# Overview

A brief overview

![](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-M4pSNPzDQ4fdRNfV8Xd%2F-M4pSO6i5GQOHGNfVsY6%2Fscreenshot-2019-05-05-at-13.41.40%20\(1\).png?generation=1586813573243887\&alt=media)

The *Netcap* (NETwork CAPture) framework efficiently converts a stream of network packets into platform neutral type-safe structured audit records that represent specific protocols or custom abstractions. These audit records can be stored on disk or exchanged over the network, and are well suited as a data source for machine learning algorithms. Since parsing of untrusted input can be dangerous and network data is potentially malicious, implementation was performed in a programming language that provides a garbage collected memory safe runtime.

It was developed for a series of experiments in my bachelor thesis: *Implementation and evaluation of secure and scalable anomaly-based network intrusion detection*. The thesis is included at the root of this repository (file: [mied18.pdf](https://github.com/dreadl0ck/netcap/blob/master/mied18.pdf)) and can be used as an introduction to the framework, its philosophy and architecture. However, be aware that the command-line interface was refactored heavily and the thesis examples refer to very early versions. This documentation contains the latest API and usage examples. Slides from my presentation at the Leibniz Supercomputing Centre of the Bavarian Academy of Sciences and Humanities are available on [researchgate](https://www.researchgate.net/project/Anomaly-based-Network-Security-Monitoring).

The project won the 2nd Place at Kaspersky Labs SecurIT Cup 2018 in Budapest.

*Netcap* uses Google's Protocol Buffers to encode its output, which allows accessing it across a wide range of programming languages. Alternatively, output can be emitted as comma separated values, which is a common input format for data analysis tools and systems. The tool is extensible and provides multiple ways of adding support for new protocols, while implementing the parsing logic in a memory safe way. It provides high dimensional data about observed traffic and allows the researcher to focus on experimenting with novel approaches for detecting malicious behavior in network environments, instead of fiddling with data collection mechanisms and post processing steps. It has a concurrent design that makes use of multi-core architectures. The name *Netcap* was chosen to be simple and descriptive. The command-line tool was designed with usability and readability in mind, and displays progress when processing packets. The latest version offers 66 audit record types of which 55 are protocol specific and 8 are custom abstractions, such as flows or transferred files.

## Design Goals

* memory safety when parsing untrusted input
* ease of extension
* output format interoperable with many different programming languages
* concurrent design
* output with small storage footprint on disk
* gather everything, separate what can be understood from what can't
* allow implementation of custom abstractions
* rich platform and architecture support

## Framework Components

The framework consists of 9 logically separate tools compiled into a single binary:

* capture (capture audit records live or from dumpfiles)
* dump (dump with audit records in various formats)
* label (tool for creating labeled CSV datasets from netcap data)
* collect (collection server for distributed collection)
* agent (sensor agent for distributed collection)
* proxy (http reverse proxy for capturing traffic from web services)
* util (utility tool for validating audit records and converting timestamps)
* export (exporter for prometheus metrics)
* transform (maltego transformation plugin)

## Use Cases

* monitoring honeypots
* monitoring medical / industrial devices
* research on anomaly-based detection mechanisms
* Forensic data analysis

## Demos

A simple demonstration of generating audit records from a PCAP dump file, querying and displaying the collected information in various ways

{% embed url="<https://asciinema.org/a/Mw2PldBOcPZeTOeN8XTKxFA5h>" %}
Working with PCAPs
{% endembed %}

And live operation decoding traffic from my wireless network interface, while I am surfing the web

{% embed url="<https://asciinema.org/a/hOkjEZlTR4C9FRZ9ky7RTt2nA>" %}
Live Capture
{% endembed %}

Exploring HTTP audit records

{% embed url="<https://asciinema.org/a/P5hwb7YzMer4CHrF6Q6NP1WjF>" %}
HTTP Audit Records
{% endembed %}

### Deep Learning

Watch a quick demo of the deep neural network for classification of malicious behavior, on a small PCAP dump file with traffic from the LOKI Bot. First, the PCAP file is parsed with [netcap](https://github.com/dreadl0ck/netcap-tf-dnn/blob/master/github.com/dreadl0ck/netcap), in order to get audit records that will be labeled afterwards with the [netlabel](https://github.com/dreadl0ck/netcap#netlabel-command-line-tool) tool. The labeled CSV data for the TCP audit record type is then used for training (75%) and evaluation (25%) of the classification accuracy provided by the deep neural network.

{% embed url="<https://asciinema.org/a/WnnLCsPUcBWatb2ddf0xK1pmJ>" %}
Deep Learning with Tensorflow
{% endembed %}

## License

Netcap is licensed under the GNU General Public License v3, which is a very permissive open source license, that allows others to do almost anything they want with the project, except to distribute closed source versions. This license type was chosen with Netcaps research purpose in mind, and in the hope that it leads to further improvements and new capabilities contributed by other researchers on the long term. For more infos refer to the License page.

## Source Code Stats

Stats for netcap v0.5, generated with cloc version 1.80

> $ zeus cloc

```
     444 text files.
     444 unique files.                                          
     158 files ignored.

github.com/AlDanial/cloc v 1.84  T=0.26 s (1090.4 files/s, 116481.5 lines/s)
-------------------------------------------------------------------------------
Language                     files          blank        comment           code
-------------------------------------------------------------------------------
Go                             277           4191           4788          21031
Markdown                         9            123              0            503
YAML                             1              5              4             14
-------------------------------------------------------------------------------
SUM:                           287           4319           4792          21548
-------------------------------------------------------------------------------
```


# Audit Records

An overview of supported protocols and available fields

The following markdown overview was generated using:

```
$ net capture -overview
```

## NETCAP Overview v0.5

> Documentation: [docs.netcap.io](https://docs.netcap.io)
>
> ### LayerEncoders

| Name                        | NumFields | Fields                                                                                                                                                                                                                                                                                                                |
| --------------------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| TCP                         | 25        | Timestamp, SrcPort, DstPort, SeqNum, AckNum, DataOffset, FIN, SYN, RST, PSH, ACK, URG, ECE, CWR, NS, Window, Checksum, Urgent, Padding, Options, PayloadEntropy, PayloadSize, Payload, SrcIP, DstIP                                                                                                                   |
| UDP                         | 10        | Timestamp, SrcPort, DstPort, Length, Checksum, PayloadEntropy, PayloadSize, Payload, SrcIP, DstIP                                                                                                                                                                                                                     |
| IPv4                        | 17        | Timestamp, Version, IHL, TOS, Length, Id, Flags, FragOffset, TTL, Protocol, Checksum, SrcIP, DstIP, Padding, Options, PayloadEntropy, PayloadSize                                                                                                                                                                     |
| IPv6                        | 12        | Timestamp, Version, TrafficClass, FlowLabel, Length, NextHeader, HopLimit, SrcIP, DstIP, PayloadEntropy, PayloadSize, HopByHop                                                                                                                                                                                        |
| DHCPv4                      | 20        | Timestamp, Operation, HardwareType, HardwareLen, HardwareOpts, Xid, Secs, Flags, ClientIP, YourClientIP, NextServerIP, RelayAgentIP, ClientHWAddr, ServerName, File, Options, SrcIP, DstIP, SrcPort, DstPort                                                                                                          |
| DHCPv6                      | 11        | Timestamp, MsgType, HopCount, LinkAddr, PeerAddr, TransactionID, Options, SrcIP, DstIP, SrcPort, DstPort                                                                                                                                                                                                              |
| ICMPv4                      | 7         | Timestamp, TypeCode, Checksum, Id, Seq, SrcIP, DstIP                                                                                                                                                                                                                                                                  |
| ICMPv6                      | 5         | Timestamp, TypeCode, Checksum, SrcIP, DstIP                                                                                                                                                                                                                                                                           |
| ICMPv6Echo                  | 5         | Timestamp, Identifier, SeqNumber, SrcIP, DstIP                                                                                                                                                                                                                                                                        |
| ICMPv6NeighborSolicitation  | 5         | Timestamp, TargetAddress, Options, SrcIP, DstIP                                                                                                                                                                                                                                                                       |
| ICMPv6RouterSolicitation    | 4         | Timestamp, Options, SrcIP, DstIP                                                                                                                                                                                                                                                                                      |
| DNS                         | 22        | Timestamp, ID, QR, OpCode, AA, TC, RD, RA, Z, ResponseCode, QDCount, ANCount, NSCount, ARCount, Questions, Answers, Authorities, Additionals, SrcIP, DstIP, SrcPort, DstPort                                                                                                                                          |
| ARP                         | 10        | Timestamp, AddrType, Protocol, HwAddressSize, ProtAddressSize, Operation, SrcHwAddress, SrcProtAddress, DstHwAddress, DstProtAddress                                                                                                                                                                                  |
| Ethernet                    | 6         | Timestamp, SrcMAC, DstMAC, EthernetType, PayloadEntropy, PayloadSize                                                                                                                                                                                                                                                  |
| Dot1Q                       | 5         | Timestamp, Priority, DropEligible, VLANIdentifier, Type                                                                                                                                                                                                                                                               |
| Dot11                       | 14        | Timestamp, Type, Proto, Flags, DurationID, Address1, Address2, Address3, Address4, SequenceNumber, FragmentNumber, Checksum, QOS, HTControl                                                                                                                                                                           |
| NTP                         | 19        | Timestamp, LeapIndicator, Version, Mode, Stratum, Poll, Precision, RootDelay, RootDispersion, ReferenceID, ReferenceTimestamp, OriginTimestamp, ReceiveTimestamp, TransmitTimestamp, ExtensionBytes, SrcIP, DstIP, SrcPort, DstPort                                                                                   |
| SIP                         | 11        | Timestamp, Version, Method, Headers, IsResponse, ResponseCode, ResponseStatus, SrcIP, DstIP, SrcPort, DstPort                                                                                                                                                                                                         |
| IGMP                        | 15        | Timestamp, Type, MaxResponseTime, Checksum, GroupAddress, SupressRouterProcessing, RobustnessValue, IntervalTime, SourceAddresses, NumberOfGroupRecords, NumberOfSources, GroupRecords, Version, SrcIP, DstIP                                                                                                         |
| LLC                         | 6         | Timestamp, DSAP, IG, SSAP, CR, Control                                                                                                                                                                                                                                                                                |
| IPv6HopByHop                | 4         | Timestamp, Options, SrcIP, DstIP                                                                                                                                                                                                                                                                                      |
| SCTP                        | 7         | Timestamp, SrcPort, DstPort, VerificationTag, Checksum, SrcIP, DstIP                                                                                                                                                                                                                                                  |
| SNAP                        | 3         | Timestamp, OrganizationalCode, Type                                                                                                                                                                                                                                                                                   |
| LinkLayerDiscovery          | 5         | Timestamp, ChassisID, PortID, TTL, Values                                                                                                                                                                                                                                                                             |
| ICMPv6NeighborAdvertisement | 6         | Timestamp, Flags, TargetAddress, Options, SrcIP, DstIP                                                                                                                                                                                                                                                                |
| ICMPv6RouterAdvertisement   | 9         | Timestamp, HopLimit, Flags, RouterLifetime, ReachableTime, RetransTimer, Options, SrcIP, DstIP                                                                                                                                                                                                                        |
| EthernetCTP                 | 2         | Timestamp, SkipCount                                                                                                                                                                                                                                                                                                  |
| EthernetCTPReply            | 4         | Timestamp, Function, ReceiptNumber, Data                                                                                                                                                                                                                                                                              |
| LinkLayerDiscoveryInfo      | 8         | Timestamp, PortDescription, SysName, SysDescription, SysCapabilities, MgmtAddress, OrgTLVs, Unknown                                                                                                                                                                                                                   |
| IPSecAH                     | 7         | Timestamp, Reserved, SPI, Seq, AuthenticationData, SrcIP, DstIP                                                                                                                                                                                                                                                       |
| IPSecESP                    | 6         | Timestamp, SPI, Seq, LenEncrypted, SrcIP, DstIP                                                                                                                                                                                                                                                                       |
| Geneve                      | 12        | Timestamp, Version, OptionsLength, OAMPacket, CriticalOption, Protocol, VNI, Options, SrcIP, DstIP, SrcPort, DstPort                                                                                                                                                                                                  |
| IPv6Fragment                | 9         | Timestamp, NextHeader, Reserved1, FragmentOffset, Reserved2, MoreFragments, Identification, SrcIP, DstIP                                                                                                                                                                                                              |
| VXLAN                       | 9         | Timestamp, ValidIDFlag, VNI, GBPExtension, GBPDontLearn, GBPApplied, GBPGroupPolicyID, SrcIP, DstIP                                                                                                                                                                                                                   |
| USB                         | 20        | Timestamp, ID, EventType, TransferType, Direction, EndpointNumber, DeviceAddress, BusID, TimestampSec, TimestampUsec, Setup, Data, Status, UrbLength, UrbDataLength, UrbInterval, UrbStartFrame, UrbCopyOfTransferFlags, IsoNumDesc, Payload                                                                          |
| LCM                         | 13        | Timestamp, Magic, SequenceNumber, PayloadSize, FragmentOffset, FragmentNumber, TotalFragments, ChannelName, Fragmented, SrcIP, DstIP, SrcPort, DstPort                                                                                                                                                                |
| MPLS                        | 7         | Timestamp, Label, TrafficClass, StackBottom, TTL, SrcIP, DstIP                                                                                                                                                                                                                                                        |
| Modbus                      | 12        | Timestamp, TransactionID, ProtocolID, Length, UnitID, Payload, Exception, FunctionCode, SrcIP, DstIP, SrcPort, DstPort                                                                                                                                                                                                |
| OSPF                        | 16        | Timestamp, Version, Type, PacketLength, RouterID, AreaID, Checksum, AuType, Authentication, LSAs, LSU, LSR, DbDesc, HelloV2, SrcIP, DstIP                                                                                                                                                                             |
| OSPF                        | 16        | Timestamp, Version, Type, PacketLength, RouterID, AreaID, Checksum, Instance, Reserved, Hello, DbDesc, LSR, LSU, LSAs, SrcIP, DstIP                                                                                                                                                                                   |
| BFD                         | 21        | Timestamp, Version, Diagnostic, State, Poll, Final, ControlPlaneIndependent, AuthPresent, Demand, Multipoint, DetectMultiplier, MyDiscriminator, YourDiscriminator, DesiredMinTxInterval, RequiredMinRxInterval, RequiredMinEchoRxInterval, AuthHeader, SrcIP, DstIP, SrcPort, DstPort                                |
| GRE                         | 21        | Timestamp, ChecksumPresent, RoutingPresent, KeyPresent, SeqPresent, StrictSourceRoute, AckPresent, RecursionControl, Flags, Version, Protocol, Checksum, Offset, Key, Seq, Ack, Routing, SrcIP, DstIP, SrcPort, DstPort                                                                                               |
| FDDI                        | 5         | Timestamp, FrameControl, Priority, SrcMAC, DstMAC                                                                                                                                                                                                                                                                     |
| EAP                         | 6         | Timestamp, Code, Id, Length, Type, TypeData                                                                                                                                                                                                                                                                           |
| VRRP                        | 12        | Timestamp, Version, Type, VirtualRtrID, Priority, CountIPAddr, AuthType, AdverInt, Checksum, IPAdresses, SrcIP, DstIP                                                                                                                                                                                                 |
| EAPOL                       | 4         | Timestamp, Version, Type, Length                                                                                                                                                                                                                                                                                      |
| EAPOLKey                    | 22        | Timestamp, KeyDescriptorType, KeyDescriptorVersion, KeyType, KeyIndex, Install, KeyACK, KeyMIC, Secure, MICError, Request, HasEncryptedKeyData, SMKMessage, KeyLength, ReplayCounter, Nonce, IV, RSC, ID, MIC, KeyDataLength, EncryptedKeyData                                                                        |
| CiscoDiscovery              | 5         | Timestamp, Version, TTL, Checksum, Values                                                                                                                                                                                                                                                                             |
| CiscoDiscoveryInfo          | 27        | Timestamp, CDPHello, DeviceID, Addresses, PortID, Capabilities, Version, Platform, IPPrefixes, VTPDomain, NativeVLAN, FullDuplex, VLANReply, VLANQuery, PowerConsumption, MTU, ExtendedTrust, UntrustedCOS, SysName, SysOID, MgmtAddresses, Location, PowerRequest, PowerAvailable, SparePairPoe, EnergyWise, Unknown |
| USBRequestBlockSetup        | 6         | Timestamp, RequestType, Request, Value, Index, Length                                                                                                                                                                                                                                                                 |
| NortelDiscovery             | 7         | Timestamp, IPAddress, SegmentID, Chassis, Backplane, State, NumLinks                                                                                                                                                                                                                                                  |
| CIP                         | 12        | Timestamp, Response, ServiceID, ClassID, InstanceID, Status, AdditionalStatus, Data, SrcIP, DstIP, SrcPort, DstPort                                                                                                                                                                                                   |
| Ethernet/IP                 | 12        | Timestamp, Command, Length, SessionHandle, Status, SenderContext, Options, CommandSpecific, SrcIP, DstIP, SrcPort, DstPort                                                                                                                                                                                            |
| SMTP                        | 9         | Timestamp, IsEncrypted, IsResponse, ResponseLines, Command, SrcIP, DstIP, SrcPort, DstPort                                                                                                                                                                                                                            |
| Diameter                    | 13        | Timestamp, Version, Flags, MessageLen, CommandCode, ApplicationID, HopByHopID, EndToEndID, AVPs, SrcIP, DstIP, SrcPort, DstPort                                                                                                                                                                                       |

> ### CustomEncoders

| Name           | NumFields | Fields                                                                                                                                                                                                                                                                                                                                                     |
| -------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| TLSClientHello | 27        | Timestamp, Type, Version, MessageLen, HandshakeType, HandshakeLen, HandshakeVersion, Random, SessionIDLen, SessionID, CipherSuiteLen, ExtensionLen, SNI, OSCP, CipherSuites, CompressMethods, SignatureAlgs, SupportedGroups, SupportedPoints, ALPNs, Ja3, SrcIP, DstIP, SrcMAC, DstMAC, SrcPort, DstPort                                                  |
| TLSServerHello | 27        | Timestamp, Version, Random, SessionID, CipherSuite, CompressionMethod, NextProtoNeg, NextProtos, OCSPStapling, TicketSupported, SecureRenegotiationSupported, SecureRenegotiation, AlpnProtocol, Ems, SupportedVersion, SelectedIdentityPresent, SelectedIdentity, Cookie, SelectedGroup, Extensions, SrcIP, DstIP, SrcMAC, DstMAC, SrcPort, DstPort, Ja3S |
| HTTP           | 18        | Timestamp, Proto, Method, Host, UserAgent, Referer, ReqCookies, ResCookies, ReqContentLength, URL, ResContentLength, ContentType, StatusCode, SrcIP, DstIP, ReqContentEncoding, ResContentEncoding, ServerName                                                                                                                                             |
| Flow           | 17        | TimestampFirst, LinkProto, NetworkProto, TransportProto, ApplicationProto, SrcMAC, DstMAC, SrcIP, SrcPort, DstIP, DstPort, TotalSize, AppPayloadSize, NumPackets, UID, Duration, TimestampLast                                                                                                                                                             |
| Connection     | 17        | TimestampFirst, LinkProto, NetworkProto, TransportProto, ApplicationProto, SrcMAC, DstMAC, SrcIP, SrcPort, DstIP, DstPort, TotalSize, AppPayloadSize, NumPackets, UID, Duration, TimestampLast                                                                                                                                                             |
| DeviceProfile  | 7         | Timestamp, MacAddr, DeviceManufacturer, NumDeviceIPs, NumContacts, NumPackets, Bytes                                                                                                                                                                                                                                                                       |
| File           | 12        | Timestamp, Name, Length, Hash, Location, Ident, Source, ContentType, SrcIP, DstIP, SrcPort, DstPort                                                                                                                                                                                                                                                        |
| POP3           | 7         | Timestamp, Client, Server, AuthToken, User, Pass, NumMails                                                                                                                                                                                                                                                                                                 |


# Specification

The Netcap audit record format

*Netcap* files have the file extension **.ncap** or **.ncap.gz** if compressed with gzip and contain serialized protocol buffers of one type. Naming of each file happens according to the naming in the [gopacket](https://godoc.org/github.com/google/gopacket) library: a short uppercase letter representation for common protocols, and a camel case version full word version for less common protocols. Audit records are modeled as protocol buffers. Each file contains a header that specifies which type of audit records is inside the file, what version of *Netcap* was used to generate it, what input source was used and what time it was created. Each audit record should be tagged with the timestamp the packet was seen, in the format *seconds.microseconds*. Output is written to a file that represents each data structure from the protocol buffers definition, i.e. *TCP.ncap*, *UDP.ncap*. For this purpose, the audit records are written as length delimited records into the file.

## Delimited Protocol Buffer Records

The data format on disk consists of gzipped length-delimited byte records. Each delimited Protocol Buffer record is preceded by a variable-length encoded integer (varint) that specifies the length of the serialized protocol buffer record in bytes. A stream consists of a sequence of such records packed consecutively without additional padding. There are no checksums or compression involved in this processing step.

![Delimited protocol buffers](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-LqkPR4DukbeBJnAbdn3%2F-LqkPRrpLszNUluCwxRj%2Fnetcap-delimited.svg?generation=1570622788967863\&alt=media)

## Data Compression

Encoding the output as protocol buffers does not help much with reducing the size, compared to the CSV format. To further reduce the disk size required for storage, the data is gzipped prior to writing it into the file. This makes the resulting files around 70% smaller. Gzip is a common and well supported format, support for decoding it exists in almost every programming language. If this is not desired for e.g. direct access to the stored data, this can be toggled with the **-comp** command-line flag.

## Audit Records

A piece of information produced by Netcap is called an audit record. Audit records are type safe structured data, encoded as protocol buffers. An audit record can describe a specific protocol, or other abstractions built on top of observations from the analyzed traffic. Netcap does currently not enforce the presence of any special fields for each audit record, however by convention each audit record should have a timestamp with microsecond precision. A record file contains a header followed by a list of length-delimited serialized audit records. Naming of the audit record file happens according to the encoder name and should signal whether the file contents are compressed by adding the .gz extension.

![](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-LqkPR4DukbeBJnAbdn3%2F-LqkPRrrtMgACgP3sxdO%2Fnetcap-audit-record.svg?generation=1570622788846187\&alt=media)


# Installation

Setup instructions

## Binary Distributions

Compiled versions for macOS, Linux and Windows are available on GitHub:

{% embed url="<https://github.com/dreadl0ck/netcap/releases>" %}
NETCAP GitHub Releases Page
{% endembed %}

## Go Get

Installation via go get:

```
$ go get -u github.com/dreadl0ck/netcap/...
```

## Manual Build

```
$ go build -ldflags "-s -w" -o /usr/local/bin/net -i github.com/dreadl0ck/netcap/cmd
```

## Reproducible Builds via Go Modules

In order to provide stable and reproducible builds, Go modules are used to pin the versions of source code dependencies to specific versions.

Go has included support for versioned modules as proposed [here](https://golang.org/design/24301-versioned-go) since `1.11`. The initial prototype `vgo` was [announced](https://research.swtch.com/vgo) in February 2018. In July 2018, versioned modules [landed](https://groups.google.com/d/msg/golang-dev/a5PqQuBljF4/61QK4JdtBgAJ) in the main Go repository. They are used by default by the go toolchain starting from version `1.13` .

You can read about Go modules here:

{% embed url="<https://github.com/golang/go/wiki/Modules>" %}

{% embed url="<https://blog.golang.org/using-go-modules>" %}

## Development Build

To install the command-line tool:

```
$ go build -o /usr/local/bin/net -i github.com/dreadl0ck/netcap/cmd
```

## Cross Compilation

To cross compile for other architectures, set the *GOARCH* and *GOOS* environment variables. For example to cross compile a binary for *linux amd64*:

```
$ GOARCH=amd64 GOOS=linux go build -o bin/net -i github.com/dreadl0ck/netcap/cmd
```

## Homebrew

On macOS, you can install the *netcap* command-line tool with Homebrew:

```
$ brew tap dreadl0ck/formulas
$ brew install netcap
```

## Buildsystem

*Netcap* uses the [zeus](https://github.com/dreadl0ck/zeus) build system, it can be found on GitHub along with installation instructions:

{% embed url="<https://github.com/dreadl0ck/zeus>" %}
ZEUS Build System GitHub
{% endembed %}

To install the *Netcap* and *Netlabel* command-line tool and the library with zeus, run:

```
$ zeus install
```


# Kali Linux

Installing NETCAP on Kali

## Prepare Kali Image

This part covers basic setup of Kali Linux, you can skip this if you already have a configured installation.

Grab a fresh Kali image from: <https://www.kali.org/downloads/>

> Be careful with old kali images where you log in as the root user, and your default shell is still bash and not zshell, you will need to adjust the commands slightly.

If you are using a virtual machine, make sure to supply sufficient resources. Maltego and Netcap are both resource intensive programs, so plan accordingly. It is possible to run on smaller files (10-50MB) and analyse simple graphs with a two core / 2GB RAM VM, but its not a pleasant experience and might crash if you run a larger set of transforms at the same time. I recommend at least 4 cores and 4-8GB RAM, but avoid allocating more than half of your host system resources.&#x20;

After logging in with the default user **kali** and password **kali**, open a terminal prompt.

Set language for your keyboard (add to \~/.zshrc to persist), I've chosen the German layout here:

```
$ setxkbmap de
```

Update to latest version of Kali:

```
$ apt update
$ apt upgrade -y
```

In case you are using a VMWare machine, ensure to update **open-vm-tools-desktop** and **fuse**, so that the shared clipboard and mounting volumes works:

```
$ sudo apt update
$ sudo apt install -y --reinstall open-vm-tools-desktop fuse
$ sudo reboot -f
```

Configure any volumes you want to mount and use the script provided by the kali authors to mount it:

```
$ cat <<EOF | sudo tee /usr/local/sbin/mount-shared-folders
#!/bin/sh
vmware-hgfsclient | while read folder; do
  vmwpath="/mnt/hgfs/\${folder}"
  echo "[i] Mounting \${folder}   (\${vmwpath})"
  sudo mkdir -p "\${vmwpath}"
  sudo umount -f "\${vmwpath}" 2>/dev/null
  sudo vmhgfs-fuse -o allow_other -o auto_unmount ".host:/\${folder}" "\${vmwpath}"
done
sleep 2s
EOF
$ sudo chmod +x /usr/local/sbin/mount-shared-folders
$ sudo mount-shared-folders
[i] Mounting PCAPs   (/mnt/hgfs/PCAPs)
```

## Install NETCAP

You have two options: install a binary release, or compile from source.

### Install binary release

Download the latest release: <https://github.com/dreadl0ck/netcap/releases>&#x20;

### Compile from source

#### Install Go

I recommend to install Go via snap on debian systems, the aptitude packages are often outdated.

```
# install snap package manager
$ sudo apt install snapd
$ sudo systemctl start snapd
$ sudo systemctl enable snapd

# install go
$ sudo snap install go --classic

# ensure apparmor service is running and will be restarted automatically
# to prevent errors when running binaries installed via snap after reboot
$ sudo systemctl start apparmor
$ sudo systemctl enable apparmor
```

add the following directories as a **prefix** to your PATH in the **\~/.zshrc** file (optionally as well to **/root/.zshrc**):

```
export PATH="/home/kali/go/bin:/snap/bin:/usr/local/bin:$PATH"
```

Optional: To have the correct PATH with all binaries produced by the go compiler and netcap when using sudo as well, update the **secure\_path** override using:

```
$ sudo visudo
...
Defaults    secure_path="/home/kali/go/bin:/snap/bin:/usr/local/bin:<original-path>"
```

Source the rc file and verify the go compiler binary is found by the shell:

```
$ source ~/.zshrc
$ go version
go version go1.16.3 linux/amd64
```

#### Install Dependencies

We need the libpcap development headers:

```
$ sudo apt install libpcap-dev
```

now its time to fetch the NETCAP source code and use the build scripts to compile.

```
$ mkdir -p /home/kali/go/src/github.com/dreadl0ck
$ cd /home/kali/go/src/github.com/dreadl0ck
$ git clone https://github.com/dreadl0ck/netcap
```

You have two options again: Build with bindings for DPI or compile without.

Compiling with the DPI bindings will dynamilly load libndpi and libprotoident at runtime, and therefore these have to be installed on the system.

If you do not need the DPI functioniality for now, you can simply compile netcap without.

The scripts will also invoke setcap to give the netcap binary permissions to attach to a network interface for live capture.

#### Compile with DPI

```
$ cd /home/kali/go/src/github.com/dreadl0ck/netcap
$ zeus/scripts/install-debian.sh
```

This will fetch and compile libprotoident and DPI, and then compile NETCAP. The DPI libs are pretty big and compilation will take 10-20mins depending on your hardware. Time to get a coffee.

#### Compile without DPI

```
$ cd /home/kali/go/src/github.com/dreadl0ck/netcap
$ zeus/generated/install-linux-nodpi.sh
```

Either way, you should now have the **net** binary in your PATH, verify by running:

```
$ net
                       / |
 _______    ______   _10 |_     _______   ______    ______
/     / \  /    / \ / 01/  |   /     / | /    / \  /    / \
0010100 /|/011010 /|101010/   /0101010/  001010  |/100110  |
01 |  00 |00    00 |  10 | __ 00 |       /    10 |00 |  01 |
10 |  01 |01001010/   00 |/  |01 \_____ /0101000 |00 |__10/|
10 |  00 |00/    / |  10  00/ 00/    / |00    00 |00/   00/
00/   10/  0101000/    0010/   0010010/  0010100/ 1010100/
                                                  00 |
Network Protocol Analysis Framework               00 |
created by Philipp Mieden, 2018                   00/
v0.5.13

available subcommands:
  > capture       capture audit records
  > util          general util toool
  > proxy         http proxy
  > label         apply labels to audit records
  > export        exports audit records
  > dump          utility to read audit record files
  > collect       collector for audit records from agents
  > transform     maltego plugin
  > help          display this help

usage: ./net <subcommand> [flags]
or: ./net <subcommand> [-h] to get help for the subcommand
```

### Tab completion

Run the following to install the tab completion on your system and enable it for the current shell:

```
# step into the cloned repository
$ cd /home/kali/go/src/github.com/dreadl0ck/netcap

$ sudo mkdir -p /usr/local/etc/bash_completion.d
$ autoload -U +X compinit && compinit
$ autoload -U +X bashcompinit && bashcompinit
$ sudo cp cmd/net /usr/local/etc/bash_completion.d/net
$ sudo chown -R kali /usr/local/etc/bash_completion.d
$ . /usr/local/etc/bash_completion.d/net
```

To persist it, append the following **at the end** of your **\~/.zshrc** and **/root/.zshrc** files:

```
autoload -U +X compinit && compinit
autoload -U +X bashcompinit && bashcompinit
. /usr/local/etc/bash_completion.d/net
```

### Databases

To fetch the netcap databases for data enrichment, first install the git large file storage extension:

```
$ sudo apt install git-lfs
```

Create the filesystem path and ensure the permissions are correct for the kali user:

```
$ sudo mkdir -p /usr/local/etc/netcap
$ sudo chown -R kali /usr/local/etc/netcap
```

Now you can use the following command to clone the latest version of the database repository from <https://github.com/dreadl0ck/netcap-dbs> to the correct place on the filesystem. The tool will ask for confirmation before starting the download and displays the expected file size:

```
$ net util -clone-dbs
This will fetch 3.3 GB of data. Proceed? [Y/n]: 
Cloning into '/usr/local/etc/netcap'...
remote: Enumerating objects: 1031, done.
remote: Counting objects: 100% (252/252), done.
remote: Compressing objects: 100% (152/152), done.
remote: Total 1031 (delta 77), reused 252 (delta 77), pack-reused 779
Receiving objects: 100% (1031/1031), 510.95 MiB | 9.35 MiB/s, done.
Resolving deltas: 100% (325/325), done.
cloned netcap-dbs repository to /usr/local/etc/netcap
done! Downloaded databases to /usr/local/etc/netcap/
```

Now that you have the databases, you are good to go.

Remember you can update them using the following command, from any location on the filesystem:

```
$ net util -update-dbs
Already up to date.
```

The databases are rebuilt from their sources daily at midnight.

You can read more about the resolvers that make use of the DBs here:&#x20;

{% content-ref url="/pages/-M4pSNs9Ewumxyv3nEjO" %}
[Resolvers](/v0.5/resolvers)
{% endcontent-ref %}

### Maltego

Start Maltego, register an account for the community edition and authenticate.

Next, load the netcap configuration for Maltego, by switching to the **Import | Export** Tab and hit **Import Config**

![Import Config](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-MaE3IfgSexf-x2xbyc_%2F-MaEAhJfI86sU-aGB2Hf%2FScreenshot%202021-05-21%20at%2015.46.10.png?alt=media\&token=d71d6bf9-0145-4c81-a96b-9abcc3ffbf90)

If you installed from source, navigate to the following path and load the **maltego.mtz** configuration archive: **/home/kali/go/src/github.com/dreadl0ck/netcap/maltego**

Otherwise, just download the latest version from github.com: <https://github.com/dreadl0ck/netcap/raw/master/maltego/netcap.mtz>

![Load netcap.mtz config](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-MaE3IfgSexf-x2xbyc_%2F-MaE9kl8aOnf55GKQrkk%2FScreenshot%202021-05-21%20at%2015.40.47.png?alt=media\&token=368b2015-4c4f-4af3-96d8-ee9a0ff31d02)

![Confirm import](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-MaE3IfgSexf-x2xbyc_%2F-MaE9xaANpoltu9TKdIG%2FScreenshot%202021-05-21%20at%2015.41.02.png?alt=media\&token=506dece9-cc98-4d38-9079-67ffd891de2f)

![Successful import](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-MaE3IfgSexf-x2xbyc_%2F-MaE9sK8OFKJr162f-FE%2FScreenshot%202021-05-21%20at%2015.41.18.png?alt=media\&token=dce9645a-b656-48e4-a98d-d72603158cc5)

### Configuring the file type matcher preference

In order for Maltego to sucessfully detect the type of files you copy and paste into it, we need to disable using the generic **maltego.Phrase** matcher, because it will always match first. Select **Manage Entities**, search for the Phrase entity, edit it by clicking on the three little dots and deselect the shown checkbox in the **Advanced Settings**:

![Search Phrase entity](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-MaELioMhc6c6lcbJ_ZD%2F-MaES-WdUUreQSyaKZlp%2FScreenshot%202021-05-21%20at%2016.48.25.png?alt=media\&token=40abf323-3969-4864-9103-24d97541463b)

![Disable use of regex converter for Phrase entity](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-MaELioMhc6c6lcbJ_ZD%2F-MaESCxuWIRLdKuHlfRZ%2FScreenshot%202021-05-21%20at%2016.48.17.png?alt=media\&token=a20cff76-7022-47bc-8b23-08b82f4392d2)

Make sure the changes are saved by hitting **OK**. Now you should be able to copy and paste files into Maltego as described below.

#### Importing PCAP or audit record files via Copy and Paste

Drag and Drop of entities does not seem possible for Maltego on Kali yet (it works on macOS), so the most convenient way to load a PCAP file into Maltego is by selecting the file in the file explorer, hit Ctrl-C or CMD-C (VMWare on macOS) to copy the path to the clipboard, and then paste that path directly into a Maltego graph.

The NETCAP configuration registered regular expressions to handle files that end on pcap or pcapng, so these should be detected as a **netcap.PCAP** entity automatically. The same should work as well for .ncap and .ncap.gz audit record files.

If sucessful, the imported entity should look like this:

![PCAP imported into Maltego](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-MaELioMhc6c6lcbJ_ZD%2F-MaERCCIzQ5G06StYavN%2Fimage.png?alt=media\&token=2448f589-e2f9-469a-ae3c-36ec3dc8e8f8)

#### Importing PCAP files into Maltego manually

Alternatively to importing files by copy and paste, you can add new entity of type netcap.PCAP to the graph manually, then double click it and set the mandatory field containing the path of the PCAP file on disk.

![Windows > Entity Palette > Search: PCAP > Drag and Drop entity into graph](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-MaELioMhc6c6lcbJ_ZD%2F-MaEThS1mmTq-0zDHVbZ%2FScreenshot%202021-05-21%20at%2017.10.11.png?alt=media\&token=fbd77055-e26b-4019-8a3b-0f2012247e10)

Double click the file, switch to the Properties Tab and set a name and file path:

![Populate netcap.PCAP entity information manually](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-MaELioMhc6c6lcbJ_ZD%2F-MaEU8_-ibwzZRuKX4dh%2Fimage.png?alt=media\&token=2ceb088c-d657-40d7-970a-2f194a77917b)

Either way, after importing the file executing a right click should show you the following NETCAP transforms:

![Transforms available on netcap.PCAP](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-MaELioMhc6c6lcbJ_ZD%2F-MaEUWnZ1VJSDQhJjsD2%2Fimage.png?alt=media\&token=a46c45f9-4ecd-4d61-a453-1332c09af8fb)

Running the **To Audit Records \[NETCAP]** transform will start NETCAP to process the pcap file!

Afterwards, you should see audit records in Maltego:

![Audit records in Maltego](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-MaE_k_cG7bG60DgjWSC%2F-MaE_veFx7Li2iM3kHzR%2Fimage.png?alt=media\&token=6aa63695-3b32-4fd2-a64f-3bfba6d63e21)

Clone the exploitdb repository, so the transforms for opening them work:

```
$ cd /usr/local/etc/netcap
$ git clone https://github.com/offensive-security/exploitdb.git
```

### Installing IDA

For the '**Open File in Disassembler**' transform to open extracted binary files in the IDA dissassembler to work, we need to install IDA, or move your existing installation to the expected place on the filesystem.

To install, grab a download link from: <https://hex-rays.com/ida-free/#download>

At the time of this writing it is: <https://out7.hex-rays.com/files/idafree76_linux.run>

```
$ wget https://out7.hex-rays.com/files/idafree76_linux.run
$ chmod +x idafree76_linux.run
$ ./idafree76_linux.run
[click Next in graphical installer]
```

Next, add **/usr/local/bin/ida** to your PATH in **\~/.zshrc**:

```
export PATH="/usr/local/bin/ida:$PATH"
```

Move the downloaded files there and source the **\~/.zshrc**:

```
$ sudo mv /usr/local/bin/idafree-7.6 /usr/local/bin/ida  
$ source ~/.zshrc

# confirm that you can open ida
$ ida64
[launches gui]
```

### Utils

Optional, but very useful to inspect data generated by netcap on the commandline are **tree** and **batcat**, you can install them with:

```
$ sudo snap install batcat
$ sudo apt install tree
```

For example, you can inspect extracted TCP streams with ANSI colors using batcat. Everything that is colored in red has been transferred by the client, everything in blue is from the server, just like in wireshark.

Enter a directory with netcap audit records where the capture tool was executed the **-conns** flag (enabled by default) and run:

```
$ batcat tcp/world-wide-web-http/*
```

![Batcat: like cat, just with wings](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-MaE3IfgSexf-x2xbyc_%2F-MaEF5vY7ZrLe5ILT1_y%2Fimage.png?alt=media\&token=11a2a2ff-d6e3-41f9-bbae-a47138ca369d)

> Tip: use batcat -A to view binary connection data in the terminal

Lets examine the tree command output to understand what files and directories are produced by NETCAP. Move into a directory that was created as output by the capture tool (**-out** flag, defaults to current directory) and run:

```
$ tree -h .
```

![Tree of NETCAP output](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-MaE3IfgSexf-x2xbyc_%2F-MaEG6Y2u9ycpRxwd2MB%2Fimage.png?alt=media\&token=55cbbbe2-e302-4df9-8510-aa5cd914f05a)

You can see there are two different file types on the top level:

* .log

Log files from different components of NETCAP, for diagnostic purposes. The main log file **netcap.log** always contains the log output that was written to the console when the NETCAP engine was executed.

* .ncap.gz

NETCAP audit records compressed with gzip. In order to read them, you need to use the **net dump** sub command, e.g:

![Reading NETCAP audit records](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-MaE3IfgSexf-x2xbyc_%2F-MaEHA1jfCgS5bA69xOY%2Fimage.png?alt=media\&token=be810783-dca2-4045-9293-f6a49a567f5a)

The following directories can be generated, depending on the configuration:

* files (or custom name, provided via **-fileStorage** flag, default name is files)

The output directory of the files extracted from network connections, structured according to the detected content MIME type.

* tcp (generated when **-conns** flag is set, enabled by default)

Extracted **TCP** connection data, structured based on the service names obtained by looking up the used port numbers in the IANA database. Colorized with ANSI escape sequences, red is client, blue is server.

* udp (generated when **-conns** flag is set, enabled by default)

Extracted **UDP** connection data, structured based on the service names obtained by looking up the used port numbers in the IANA database. Colorized with ANSI escape sequences, red is client, blue is server.

Also **codium** is a nice IDE and text editor to inspect source code:

```
$ sudo snap install codium
```


# Quickstart

For those who can't wait to get their hands dirty.

## Capture traffic to create audit records

Read traffic live from interface, stop with *Ctrl-C* (*SIGINT*):

```
$ net capture -iface eth0
```

Read traffic from a dump file (supports PCAP or PCAPNG):

```
$ net capture -read traffic.pcap
```

## Read audit records

Read a netcap dumpfile and print to stdout as CSV:

```
$ net dump -read TCP.ncap.gz
```

Show the available fields for a specific Netcap dump file:

```
$ net dump -fields -read TCP.ncap.gz
```

Print only selected fields and output as CSV:

```
$ net dump -read TCP.ncap.gz -select Timestamp,SrcPort,DstPort
```

Save CSV output to file:

```
$ net dump -read TCP.ncap.gz -select Timestamp,SrcPort,DstPort > tcp.csv
```

Print output separated with tabs:

```
$ net dump -read TPC.ncap.gz -tsv
```

Run with 24 workers and disable gzip compression and buffering:

```
$ net capture -workers 24 -buf false -comp false -read traffic.pcapng
```

Parse pcap and write all data to output directory (will be created if it does not exist):

```
$ net capture -read traffic.pcap -out traffic_ncap
```

Convert timestamps to UTC:

```
$ net dump -read TCP.ncap.gz -select Timestamp,SrcPort,Dstport -utc
```

## Show Audit Record File Header

To display the header of the supplied audit record file, the -header flag can be used:

```
$ net capture -read TCP.ncap.gz -header

+----------+---------------------------------------+
|  Field   |                Value                  |
+----------+---------------------------------------+
| Created  | 2018-11-15 04:42:22.411785 +0000 UTC  |
| Source   | Wednesday-WorkingHours.pcap           |
| Version  | v0.3.3                                |
| Type     | NC_TCP                                |
+----------+---------------------------------------+
```

## Print Structured Audit Records

Audit records can be printed structured, this makes use of the *proto.MarshalTextString()* function. This is sometimes useful for debugging, but very verbose.

```
$ net dump -read TCP.ncap.gz -struc
...
NC_TCP
Timestamp: "1499255023.848884"
SrcPort: 80
DstPort: 49472
SeqNum: 1959843981
AckNum: 3666268230
DataOffset: 5
ACK: true
Window: 1025
Checksum: 2348
PayloadEntropy: 7.836586993143013
PayloadSize: 1460
...
```

## Print as CSV

This is the default behavior. First line contains all field names.

```
$ net dump -read TCP.ncap.gz
Timestamp,SrcPort,DstPort,SeqNum,AckNum,DataOffset,FIN,SYN,RST,PSH,ACK,URG,...
1499254962.234259,443,49461,1185870107,2940396492,5,false,false,false,true,true,false,...
1499254962.282063,49461,443,2940396492,1185870976,5,false,false,false,false,true,false,...
...
```

## Print as Tab Separated Values

To use a tab as separator, the *-tsv* flag can be supplied:

```
$ net dump -read TCP.ncap.gz -tsv
Timestamp               SrcPort DstPort Length  Checksum PayloadEntropy  PayloadSize
1499254962.084372       49792   1900    145     34831    5.19616448      137
1499254962.084377       49792   1900    145     34831    5.19616448      137
1499254962.084378       49792   1900    145     34831    5.19616448      137
1499254962.084379       49792   1900    145     34831    5.19616448      137
...
```

## Print as Table

The *-table* flag can be used to print output as a table. Every 100 entries the table is printed to stdout.

```
$ net dump -read UDP.ncap.gz -table -select Timestamp,SrcPort,DstPort,Length,Checksum
+--------------------+----------+----------+---------+-----------+
|     Timestamp      | SrcPort  | DstPort  | Length  | Checksum  |
+--------------------+----------+----------+---------+-----------+
| 1499255691.722212  | 62109    | 53       | 43      | 38025     |
| 1499255691.722216  | 62109    | 53       | 43      | 38025     |
| 1499255691.722363  | 53       | 62109    | 59      | 37492     |
| 1499255691.722366  | 53       | 62109    | 59      | 37492     |
| 1499255691.723146  | 56977    | 53       | 43      | 7337      |
| 1499255691.723149  | 56977    | 53       | 43      | 7337      |
| 1499255691.723283  | 53       | 56977    | 59      | 6804      |
| 1499255691.723286  | 53       | 56977    | 59      | 6804      |
| 1499255691.723531  | 63427    | 53       | 43      | 17441     |
| 1499255691.723534  | 63427    | 53       | 43      | 17441     |
| 1499255691.723682  | 53       | 63427    | 87      | 14671     |
...
```

## Print with Custom Separator

Output can also be generated with a custom separator:

```
$ net dump -read TCP.ncap.gz -sep ";"
Timestamp;SrcPort;DstPort;Length;Checksum;PayloadEntropy;PayloadSize
1499254962.084372;49792;1900;145;34831;5.19616448;137
1499254962.084377;49792;1900;145;34831;5.19616448;137
1499254962.084378;49792;1900;145;34831;5.19616448;137
...
```

## Validate generated CSV output

To ensure values in the generated CSV would not contain the separator string, the *-check* flag can be used.

This will determine the expected number of separators for the audit record type, and print all lines to stdout that do not have the expected number of separator symbols. The separator symbol will be colored red with ansi escape sequences and each line is followed by the number of separators in red color.

The *-sep* flag can be used to specify a custom separator.

```
$ net util -read TCP.ncap.gz -check
$ net util -read TCP.ncap.gz -check -sep=";"
```


# Configuration

Adjusting framework parameters

## Command-line Flags

Each subcommand has a dedicated set of flags for configuration.

List the flag names, a short description and their default values with:

```
$ net <subcommand> -h
```

## Environment

All default values for flags can be overriden via environment variables, by using the flag name and prefixing it with "NC\_", for example lets overwrite the **-read** flag from net capture:

```
$ NC_READ=/home/user/traffic.pcap net capture
```

Since the provide the value via the environment, passing it via flag is no longer necessary. This is generally useful to enable or disable features globally on your system.

## Configuration File

Additionally, the configuration can be provided as a config file via the **-config** flag.

To retrieve a sane default configuration for the subcommand you want to execute, use the **-gen-config** flag and redirect the output into a file:

```
$ net capture -gen-config > capture.conf
```

The config file will look something like this, using the **name value** syntax to set values:

```bash
...
# toggle promiscous mode for live capture
promisc true

# don't print infos to stdout
quiet false

# reassemble TCP connections
reassemble-connections true

# resolve ips to domains via the operating systems default dns resolver
reverse-dns false

# use serviceDB for device profiling
serviceDB false

# configure snaplen for live capture from interface
snaplen 1514

# print netcap package version and exit
version false

# wait for all connections to finish processing before cleanup
wait-conns true

# number of workers
workers 12

# write incomplete response
writeincomplete false
...
```

> Lines starting with # are treated as comments, blank lines are being ignored.

Adjust the parameters of interest and pass the config file:

```
$ net capture -config capture.conf
```

## Resolver Database

The environment variable **NC\_DATABASE\_SOURCE** can be used to overwrite the default path for the resolver databases **/usr/local/etc/netcap/db**. Read more about the resolvers package here:

{% content-ref url="/pages/-M4pSNs9Ewumxyv3nEjO" %}
[Resolvers](/v0.5/resolvers)
{% endcontent-ref %}


# Bash Completion

Tab completion for the shell

## Installation

Completions for the command-line is provided via the bash-completion package which is available for most linux distros and macOS.

On macOS you can install it with brew:

```
$ brew install bash-completion
```

on linux use the package manager of your distro.

Then add the completion file **cmd/net** to:

* macOS: /usr/local/etc/bash\_completion.d/
* Linux: /etc/bash\_completion.d/

and source it with:

* macOS: . /usr/local/etc/bash\_completion.d/net
* Linux: . /etc/bash\_completion.d/net

If you use zeus, simply execute the following in the project root to install the completion script:

```
$ zeus install-completions
```

or move and source the file manually from the project root:

```
$ cp cmd/net /usr/local/etc/bash_completion.d/net && . /usr/local/etc/bash_completion.d/net
```

Afterwards you should receive predictions when hitting tab in the shell, for subcommands and flags. For flags that expect a path on the filesystem, path completion is available and will only display files with the expected datatype (based on the file extension).

To use completion with **zsh** run the following:

```
autoload -U +X compinit && compinit
autoload -U +X bashcompinit && bashcompinit
cp cmd/net /usr/local/etc/bash_completion.d/net && . /usr/local/etc/bash_completion.d/net
```


# Packet Collection

This section focuses on gathering network packet information with netcap

Packets are fetched from an input source (offline dump file or live from an interface) and distributed via round-robin to a pool of workers. Each worker dissects all layers of a packet and writes the generated *protobuf* audit records to the corresponding file. By default, the data is compressed with *gzip* to save storage space and buffered to avoid an overhead due to excessive *syscalls* for writing data to disk.

![Packet collection process](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-M4zJ9Rxct4unAoDuU99%2F-M4zJRRXSeaBZOlGLN8w%2Fnetcap.svg?alt=media\&token=4ac23a75-ed88-45c2-9735-266dc1e909e0)

## Encoders

Encoders take care of converting decoded packet data into protocol buffers for the audit records. Two types of encoders exist: the [Layer Encoder](https://github.com/dreadl0ck/netcap/blob/master/encoder/layerEncoder.go), which operates on *gopacket* layer types, and the [Custom Encoder](https://github.com/dreadl0ck/netcap/blob/master/encoder/customEncoder.go), for which any desired logic can be implemented, including decoding application layer protocols that are not yet supported by gopacket or protocols that require stream reassembly.

## Unknown Protocols

Protocols that cannot be decoded will be dumped in the unknown.pcap file for later analysis, as this contains potentially interesting traffic that is not represented in the generated output. Separating everything that could not be understood makes it easy to reveal hidden communication channels, which are based on custom protocols.

## Error Log

Errors that happen in the gopacket lib due to malformed packets or implementation errors are written to disk in the errors.log file, and can be checked by the analyst later. Each packet that had a decoding error on at least one layer will be added to the errors.pcap. An entry to the error log has the following format:

```
<UTC Timestamp>
Error: <Description>
Packet:
<full packet hex dump with layer information>
```

At the end of the error log, a summary of all errors and the number of their occurrences will be appended.

```
...
<error name>: <number of occurrences>
...
```

## Inclusion and Exclusion of Encoders

The *-encoders* flag can be used to list all available encoders. In case not all of them are desired, selective inclusion and exclusion is possible, by using the *-include* and *-exclude* flags.

List all encoders:

```
$ net capture -encoders
custom: 11
+ TLSClientHello
+ TLSServerHello
+ LinkFlow
+ NetworkFlow
+ TransportFlow
+ HTTP
+ Flow
+ Connection
+ DeviceProfile
+ File
+ POP3
layer: 55
+ TCP
+ UDP
+ IPv4
+ IPv6
+ DHCPv4
+ DHCPv6
+ ICMPv4
+ ICMPv6
+ ICMPv6Echo
+ ICMPv6NeighborSolicitation
+ ICMPv6RouterSolicitation
+ DNS
+ ARP
+ Ethernet
+ Dot1Q
+ Dot11
+ NTP
+ SIP
+ IGMP
+ LLC
+ IPv6HopByHop
+ SCTP
+ SNAP
+ LinkLayerDiscovery
+ ICMPv6NeighborAdvertisement
+ ICMPv6RouterAdvertisement
+ EthernetCTP
+ EthernetCTPReply
+ LinkLayerDiscoveryInfo
+ IPSecAH
+ IPSecESP
+ Geneve
+ IPv6Fragment
+ VXLAN
+ USB
+ LCM
+ MPLS
+ Modbus
+ OSPF
+ OSPF
+ BFD
+ GRE
+ FDDI
+ EAP
+ VRRP
+ EAPOL
+ EAPOLKey
+ CiscoDiscovery
+ CiscoDiscoveryInfo
+ USBRequestBlockSetup
+ NortelDiscovery
+ CIP
+ Ethernet/IP
+ SMTP
+ Diameter
...
```

Include specific encoders (only those named will be used):

```
$ net capture -read traffic.pcap -include Ethernet,Dot1Q,IPv4,IPv6,TCP,UDP,DNS
```

Exclude encoders (this will prevent decoding of layers encapsulated by the excluded ones):

```
$ net capture -read traffic.pcap -exclude TCP,UDP
```

## Applying Berkeley Packet Filters

*Netcap* will decode all traffic it is exposed to, therefore it might be desired to set a berkeley packet filter, to reduce the workload imposed on *Netcap*. This is possible for both live and offline operation. In case a [BPF](https://www.kernel.org/doc/Documentation/networking/filter.txt) should be set for offline use, the [gopacket/pcap](https://godoc.org/github.com/google/gopacket/pcap) package with bindings to the *libpcap* will be used, since setting BPF filters is not yet supported by the native [pcapgo](https://godoc.org/github.com/google/gopacket/pcapgo) package.

When capturing live from an interface:

```
$ net capture -iface en0 -bpf "host 192.168.1.1"
```

When reading offline dump files:

```
$ net capture -read traffic.pcap -bpf "host 192.168.1.1"
```


# Audit Record Labeling

Label audit records for supervised machine learning

## Introduction

The term labeling refers to the procedure of adding classification information to each audit record. For the purpose of intrusion detection this is usually a label stating whether the record is normal or malicious. This is called binary classification, since there are just two choices for the label (good / bad). Another option is to use multi-class labels which could represent attack names or categories. Efficient and precise creation of labeled datasets is important for supervised machine learning techniques. To create labeled data, Netcap parses logs produced by suricata and extracts information for each alert. The quality of labels therefore depends on the quality of the used ruleset. In the next step it iterates over the data generated by itself and maps each alert to the corresponding packets, connections or flows. This takes into account all available information on the audit records and alerts. More details on the mapping logic can be found in the implementation chapter. While labeling is usually performed by marking all packets of a known malicious IP address, Netcap implements a more granular and thus more precise approach of mapping labels for each record. Labeling happens asynchronously for each audit record type in a separate goroutine.

![Labeling audit records with alerts from suricata](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-LqkPR4DukbeBJnAbdn3%2F-LqkPRsCaCdoXS5F4nTq%2Flabels.svg?generation=1570622788233041\&alt=media)

## Labeling with Suricata

For labeling with suricata please install suricata first and make sure it can be found in your **$PATH**.

The installation guide can be found here:

{% embed url="<https://suricata.readthedocs.io/en/suricata-5.0.2/quickstart.html#installation>" %}

The suricata config file is expected by default at **/usr/local/etc/suricata/suricata.yaml**, but you can overwrite this path with the **-suricata-config** flag.

```go
// SuricataAlert is a summary structure for an alert
type SuricataAlert struct {
   Timestamp      string
   Proto          string
   SrcIP          string
   SrcPort        int
   DstIP          string
   DstPort        int
   Classification string
   Description    string
}
```

The label tool expects being passed a packet capture dump with the **-read** flag, which will then be scanned with suricata to retrieve the alerts from the suricata **fast.log** file with regular expressions.

> Future versions could use the eve.json log for this.

Inside of the provided output directory (**-out** or current directory by default) the audit records generated for the provided PCAP file are expected to be present. That means you need to generate them first before using the label tool.

When running the tool, labeled CSV files will be created for the alerts produced by suricata, adding the attack class or description (depending on the configuration), as a last element to every line.

## Labeling with custom attack information

Custom attack information can be loaded as a CSV file. The data is expected to have the following fields:

```go
type AttackInfo struct {
	Num      int       `csv:"num"`
	Name     string    `csv:"name"`
	Start    time.Time `csv:"start"`
	End      time.Time `csv:"end"`
	IPs      []string  `csv:"ips"`
	Proto    string    `csv:"proto"`
	Notes    string    `csv:"notes"`
	Category string    `csv:"category"`
}
```

The time format for the start and end markers is:

```
2006/1/2 15:04:05
```

Audit records will be labeled as a part of an attack if all of the following conditions are met:

* at least one of the ips from the attackinfo is either source or destination of the audit record
* the audit record has a timestamp within the attack period or matches it exactly

This specification resulted from a specific dataset from a research project and can be easily updated if you have different requirements or different data.

## Usage

Scan input pcap and create labeled csv files by mapping audit records in the current directory:

```
$ net label -read traffic.pcap
```

Scan input pcap and create output files by mapping audit records from the output directory:

```
$ net label -read traffic.pcap -out output_dir
```

Abort if there is more than one alert for the same timestamp:

```
$ net label -read taffic.pcap -strict
```

Display progress bar while processing input (experimental):

```
$ net label -read taffic.pcap -progress
```

Append classifications for duplicate labels:

```
$ net label -read taffic.pcap -collect
```


# HTTP Proxy

Inspect traffic to web applications with a HTTP reverse proxy

## Motivation

The **proxy** tool allows to quickly spin up monitoring of web applications and retrieving netcap audit records.

Since currently, TCP stream reassembly is only supported for IPv4, netcap misses HTTP traffic over IPv6 when decoding traffic from raw packets. Also there is currently no support implemented for decoding HTTP2 over TCP or QUIC.

By using a simple reverse proxy for HTTP traffic, the operating system handles the stream reassembly and we can make sure no IPv6 and / or HTTP2 traffic is missed.

## Usage

Spin up a single proxy instance from the commandline:

`$ net proxy -local 127.0.0.1:4000 -remote http://google.com`

Specifiy a custom config file for proxying multiple services with the **-proxy-config** flag:

```
$ net proxy -proxy-config example_config.yml
```

The default config path is **net.proxy-config.yml**, so if this file exists in the folder where you execute the proxy, you do not need to specify it on the commandline.

## Configuration

For proxying several services, you need to provide a config file, here is a simple example:

```yaml
# Proxies map holds all reverse proxies
proxies:
  service1:
    local: 127.0.0.1:443
    remote: http://127.0.0.1:8080
    tls: true

  service2:
    local: 127.0.0.1:9999
    remote: http://192.168.1.20

  service3:
    local: 127.0.0.1:7000
    remote: https://google.com

# CertFile for TLS secured connections
certFile: "certs/cert.crt"

# KeyFile for TLS secured connections
keyFile: "certs/cert.key"

# Logdir is used as destination for the logfile
logdir: "logs"
```

## Help

```erlang
Usage of net proxy:
  -version bool
        print netcap package version and exit
  -config string
        set config file path (default "net.proxy-config.yml")
  -debug
        set debug mode
  -dialTimeout int
        seconds until dialing to the backend times out (default 30)
  -idleConnTimeout int
        seconds until a connection times out (default 90)
  -local string
        set local endpoint
  -maxIdle int
        maximum number of idle connections (default 120)
  -remote string
        set remote endpoint
  -skipTlsVerify
        skip TLS verification
  -tlsTimeout int
        seconds until a TLS handshake times out (default 15)
```


# USB Capture

Capture traffic sent via Universal Serial Bus (USB) protocol

## Live Capture

USB live capture is now possible, currently the following Audit Records exist: USB and USBRequestBlockSetup.

To capture USB traffic live on macOS, install wireshark and bring up the USB interface:

```
$ sudo ifconfig XHC20 up
```

Now attach netcap and set baselayer to USB:

```
$ net.cap -iface XHC20 -base usb
```

## Offline from dumpfile

To read offline USB traffic from a PCAP file use:

```
$ net.cap -r usb.pcap -base usb
```

Don't forget to set the **-payload** flag if you want to preserve the data being transmitted!

## Audit Records

The **USB** and **USBRequestBlockSetup** audit records contain the following fields:

```erlang
message USB {
    string      Timestamp                 = 1;
    uint64      ID                        = 2;
    int32       EventType                 = 3;
    int32       TransferType              = 4;           
    int32       Direction                 = 5;           
    int32       EndpointNumber            = 6;
    int32       DeviceAddress             = 7;
    int32       BusID                     = 8; 
    int64       TimestampSec              = 9; 
    int32       TimestampUsec             = 10;
    bool        Setup                     = 11;
    bool        Data                      = 12;
    int32       Status                    = 13;
    uint32      UrbLength                 = 14;
    uint32      UrbDataLength             = 15;
    uint32      UrbInterval               = 16;
    uint32      UrbStartFrame             = 17;
    uint32      UrbCopyOfTransferFlags    = 18;
    uint32      IsoNumDesc                = 19;
    bytes       Payload                   = 20;
}

message USBRequestBlockSetup {
    string Timestamp   = 1; 
    int32  RequestType = 2;
    int32  Request     = 3;
    int32  Value       = 4;
    int32  Index       = 5;
    int32  Length      = 6;
}
```

�


# Payload Capture

Capture full packet payloads

It is now possible to capture payload data for the following protocols: **TCP, UDP, ModbusTCP, USB**

This can be enabled with the **-payload** flag:

```
$ net capture -read traffic.pcap -payload
```

Setting the flag works for both live and offlline capture, afterwards the raw payload bytes are stored in the **Payload** field of the audit records.

You can use the **-struc** flag with the **dump** tool to see the payload in the command-line:

```
$ net dump -read TCP.ncap.gz -struc
```


# Distributed Collection

Sensors and Collection Server

## Collection Server

Using Netcap as a data collection mechanism, sensor agents can be deployed to export the traffic they see to a central collection server. This is especially interesting for internet of things (IoT) applications, since these devices are placed inside isolated networks and thus the operator does not have any information about the traffic the device sees. Although Go was not specifically designed for this application, it is an interesting language for embedded systems. Each binary contains the complete runtime, which increases the binary size but requires no installation of dependencies on the device itself. Data exporting currently takes place in batches over UDP sockets. Transferred data is compressed in transit and encrypted with the public key of the collection server. Asymmetric encryption was chosen, to avoid empowering an attacker who compromised a sensor, to decrypt traffic of all sensors communicating with the collection server. To increase the performance, in the future this could be replaced with using a symmetric cipher, together with a solid concept for key rotation and distribution. Sensor agents do not write any data to disk and instead keep it in memory before exporting it.

![](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-M4zJi_caU09BtCoXems%2F-M4zJvVWwpzXy0DInGoO%2Fnetcap-iot.svg?alt=media\&token=cf0db9b6-fbbf-4af7-8cda-c18254ef5097)

As described in the concept chapter, sensors and the collection server use UDP datagrams for communication. Network communication was implemented using the go standard library. This section will focus on the procedure of encrypting the communication between sensor and collector. For encryption and decryption, cryptographic primitives from the [golang.org/x/crypto/nacl/box](https://godoc.org/golang.org/x/crypto/nacl/box) package are used. The NaCl (pronounced 'Salt') toolkit was developed by the reowned cryptographer Daniel J. Bernstein. The box package uses *Curve25519*, *XSalsa20* and *Poly1305* to encrypt and authenticate messages.

It is important to note that the length of messages is not hidden. Netcap uses a thin wrapper around the functionality provided by the nacl package, the wrapper has been published here: [github.com/dreadl0ck/cryptoutils](https://www.github.com/dreadl0ck/cryptoutils).

## Batch Encryption

The collection server generates a keypair, consisting of two 32 byte (256bit) keys, hex encodes them and writes the keys to disk. The created files are named *pub.key* and *priv.key*. Now, the servers public key can be shared with sensors. Each sensor also needs to generate a keypair, in order to encrypt messages to the collection server with their private key and the public key of the server. To allow the server to decrypt and authenticate the message, the sensor prepends its own public key to each message.

![NETCAP batch encryption](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-LqkPR4DukbeBJnAbdn3%2F-LqkPS5QAwJ9Oe_AWWAC%2Fnetcap-sensors.svg?generation=1570622790036362\&alt=media)

## Batch Decryption

When receiving an encrypted batch from a sensor, the server needs to trim off the first 32 bytes, to get the public key of the sensor. Now the message can be decrypted, and decompressed. The resulting bytes are serialized data for a batch protocol buffer. After unmarshalling them into the batch structure, the server can append the serialized audit records carried by the batch, into the corresponding audit record file for the provided client identifier.

![](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-M4zJi_caU09BtCoXems%2F-M4zJzA2Mfa_lRQXuU1q%2Fnetcap-batch.svg?alt=media\&token=02c10739-3eb0-432d-94d6-0cabe60e545c)

## Usage

Both sensor and client can be configured by using the *-addr* flag to specify an IP address and port. To generate a keypair for the server, the *-gen-keypair* flag must be used:

```
$ net collect -gen-keypair 
wrote keys
$ ls
priv.key pub.key
```

Now, the server can be started, the location of the file containing the private key must be supplied:

```bash
$ net collect -privkey priv.key -addr 127.0.0.1:4200
```

The server will now be listening for incoming messages. Next, the sensor must be configured. The keypair for the sensor will be generated on startup, but the public key of the server must be provided:

```
$ net agent -pubkey pub.key -addr 127.0.0.1:4200
got 126 bytes of type NC_ICMPv6RouterAdvertisement expected [126] got size [73] for type NC_Ethernet
got 73 bytes of type NC_Ethernet expected [73]
got size [27] for type NC_ICMPv6
got size [126] for type NC_ICMPv6RouterAdvertisement
got 126 bytes of type NC_ICMPv6RouterAdvertisement expected [126] got size [75] for type NC_IPv6
got 75 bytes of type NC_IPv6 expected [75]
got 27 bytes of type NC_ICMPv6 expected [27]
```

The client will now collect the traffic live from the specified interface, and send it to the configured server, once a batch for an audit record type is complete. The server will log all received messages:

```
$ net collect -privkey priv.key -addr 127.0.0.1:4200 
packet-received: bytes=2412 from=127.0.0.1:57368 decoded batch NC_Ethernet from client xyz
new file xyz/Ethernet.ncap
packet-received: bytes=2701 from=127.0.0.1:65050 decoded batch NC_IPv4 from client xyz
new file xyz/IPv4.ncap
...
```

When stopping the server with a *SIGINT* (Ctrl-C), all audit record file handles will be flushed and closed properly.

The agent uses the **$USER** environment variable to identify the workstation where the audit records are created. This will be replaced with a unique identifier in a future release.


# Workers

This is where the magic happens

## Introduction

To make use of multi-core processors, processing of packets should happen in an asynchronous way. Since Netcap should be usable on a stream of packets, fetching of packets has to happen sequentially, but decoding them can be parallelized. The packets read from the input data source (PCAP file or network interface) are assigned to a configurable number of workers routines via round-robin. Each of those worker routines operates independently, and has all selected encoders loaded. It decodes all desired layers of the packet, and writes the encoded data into a buffer that will be flushed to disk after reaching its capacity.

## Worker

[Workers](https://github.com/dreadl0ck/netcap/blob/master/collector/worker.go) are a core concept of *Netcap*, as they handle the actual task of decoding each packet. *Netcap* can be configured to run with the desired amount of workers, the default is 1000, since this configuration has shown the best results on the development machine. Increasing the number of workers also increases the number of runtime operations for goroutine scheduling, thus performance might decrease with a huge amount of workers. It is recommended to experiment with different configurations on the target system, and choose the one that performs best. Packet data fetched from the input source is distributed to a worker pool for decoding in round robin style. Each worker decodes all layers of a packet and calls all available custom encoders. After decoding of each layer, the generated protocol buffer instance is written into the *Netcap* data pipe. Packets that produced an error in the decoding phase or carry an unknown protocol are being written in the corresponding logs and dumpfiles.

> Note: by default the number of workers is set to the numbers of cores of your machine!  You can use the **-workers** flag to overwrite this value.

![NETCAP worker](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-LqkPR4DukbeBJnAbdn3%2F-LqkPRrbQWfbxaDAhIFd%2Fnetcap-worker.svg?generation=1570622788380628\&alt=media)

## Buffering

Each worker receives its data from an input channel. This channel can be buffered, by default the buffer size is 100, also because this configuration has shown the best results on the development machine. When the buffer size is set to zero, the operation of writing a packet into the channel blocks, until the goroutine behind it is ready for consumption. That means, the goroutine must finish the currently processed packet, until a new packet can be accepted. By configuring the buffer size for all routines to a specific number of packets, distributing packets among workers can continue even if a worker is not finished yet when new data arrives. New packets will be queued in the channel buffer, and writing in the channels will only block if the buffer is full.

![NETCAP buffered workers](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-LqkPR4DukbeBJnAbdn3%2F-LqkPRrd4dG9z5cIPNiA%2Fbuffered-workers.svg?generation=1570622788159362\&alt=media)

## Data Pipe

The Netcap data pipe describes the way from a network packet that has been processed in a worker routine, to a serialized, delimited and compressed record into a file on disk.

![](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-LqkPR4DukbeBJnAbdn3%2F-LqkPRrgBVB27j8Y3Ppw%2Fnetcap-pipe.svg?generation=1570622788093150\&alt=media)


# Filtering and Export

Process Netcap audit records and extract the data you are interested in

## Exporting Data with net dump

Netcap offers a simple interface to filter for specific fields and select only those of interest. Filtering and exporting specific fields can be performed with all available audit record types, over a uniform command-line interface. By default, output is generated as CSV with the field names added as first line. It is also possible to use a custom separator string. Fields are exported in the order they are named in the select statement. Sub structures of audit records (for example IPv4Options from an IPv4 packet), are converted to a human readable string representation. More examples for using this feature on the command-line can be found in the usage section.

![](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-M4zPG7otyZL7a6ISUed%2F-M4zf-fqn5vKXXSv1SAY%2FNetcap-Export.svg?alt=media\&token=067b6be8-6b38-4bad-80b0-203eccf6a802)

Netcap offers a simple command-line interface to select fields of interest from the gathered audit records.

## Examples

Show available header fields:

```
$ net dump -read UDP.ncap.gz -fields
Timestamp,SrcPort,DstPort,Length,Checksum,PayloadEntropy,PayloadSize
```

Print all fields for the supplied audit record:

```
$ net dump -read UDP.ncap.gz
1331904607.100000,53,42665,120,41265,4.863994469989251,112 
1331904607.100000,42665,53,53,1764,4.0625550894074385,45 
1331904607.290000,51190,53,39,22601,3.1861758166070766,31 
1331904607.290000,56434,53,39,37381,3.290856864924384,31 
1331904607.330000,137,137,58,64220,3.0267194361875682,50
...
```

Selecting fields will also define their order:

```
$ net dump -read UDP.ncap.gz -select Length,SrcPort,DstPort,Timestamp 
Length,SrcPort,DstPort,Timestamp
145,49792,1900,1499254962.084372
145,49792,1900,1499254962.084377
145,49792,1900,1499254962.084378
145,49792,1900,1499254962.084379 
145,49792,1900,1499254962.084380 
...
```

Print selection in the supplied order and convert timestamps to UTC time:

```
$ net dump -read UDP.ncap.gz -select Timestamp,SrcPort,DstPort,Length -utc
2012-03-16 13:30:07.1 +0000 UTC,53,42665,120
2012-03-16 13:30:07.1 +0000 UTC,42665,53,53
2012-03-16 13:30:07.29 +0000 UTC,51190,53,39
2012-03-16 13:30:07.29 +0000 UTC,56434,53,39
2012-03-16 13:30:07.33 +0000 UTC,137,137,58
...
```

To save the output into a new file, simply redirect the standard output:

```
$ net dump -read UDP.ncap.gz -select Timestamp,SrcPort,DstPort,Length -utc > UDP.csv
```


# Data Compression

Save storage space

To reduce the amount of disk space used for storing the audit records, netcap compresses them by default with **gzip**. Compressed files have the extension **.ncap.gz.**

For this purpose Netcap currently uses the following gzip implementation:

{% embed url="<https://github.com/klauspost/pgzip>" %}

This implementation will split the data into blocks that are compressed in parallel, which can be useful for compressing big amounts of data. The output is a standard gzip file.

The gzip decompression is modified so it decompresses ahead of the current reader. This means that reads will be non-blocking and CRC calculation also takes place in a separate goroutine.

This design implements input buffering to the compressor which has a nice performance effect: writes to the compressor only block if the compressor is already compressing the number of blocks specified. This reduces waiting time for the workers which they can instead use to decode packets.

To get any performance gains, you should at least be compressing more than 1 megabyte of data at the time.

You should at least have a block size of 100k and at least a number of blocks that match the number of cores your would like to utilize, but about twice the number of blocks would be the best.

The default configuration uses 1MB block size and 2x NumCPUs as the number of blocks.

Netcap only uses the parallel gzip implementation for reading and writing audit records, as only there the required amounts of data are reached to allow a speedup. For tasks where the data size can vary heavily, such as decompressing HTTP requests and responses, the standard library **compress/gzip** is used instead.


# Internals

Framework inner workings and Implementation details

## Packages

You can browse the source and sub packages on GoDev:

<https://pkg.go.dev/github.com/dreadl0ck/netcap?tab=subdirectories>

### cmd

The cmd package contains the command-line application. It receives configuration parameters from command-line flags, creates and configures a collector instance, and then starts collecting data from the desired source.

#### label

[https://pkg.go.dev/github.com/dreadl0ck/netcap@v0.5/l](https://pkg.go.dev/github.com/dreadl0ck/netcap@v0.4.7/collector)abel

The label package contains the code for creating labeled datasets. For now, the suricata IDS / IPS engine is used to scan the input PCAP and generate alerts. In the future, support could also be added for using YARA. Alerts are then parsed with regular expressions and transformed into the **label.SuricataAlert** type. This could also be replaced by parsing suricatas eve.json event logs in upcoming versions. A suricata alert contains the following information:

```go
// SuricataAlert is a summary structure of an alerts contents
type SuricataAlert struct {
    Timestamp   string
    Proto          string
    SrcIP          string
    SrcPort        int
    DstIP          string
    DstPort        int
    Classification string
    Description    string
}
```

In the next iteration, the gathered alerts are mapped onto the collected data. For layer types which are not handled separately, this is currently by using solely the timestamp of the packet, since this is the only field required by Netcap, however multiple alerts might exist for the same timestamp. To detect this and throw an error, the **-strict** flag can be used. The default is to ignore duplicate alerts for the same timestamp, use the first encountered label and ignore the rest. Another option is to collect all labels that match the timestamp, and append them to the final label with the **-collect** flag. To allow filtering out classifications that shall be excluded, the **-excluded** flag can be used. Alerts matching the excluded classi- fication will then be ignored when collecting the generated alerts. Flow, Connection, HTTP and TLS records mapping logic also takes source and destination information into consider- ation. The created output files follow the naming convention: **\<NetcapType>\_labeled.csv**.

### types

[https://pkg.go.dev/github.com/dreadl0ck/netcap@v0.5/t](https://pkg.go.dev/github.com/dreadl0ck/netcap@v0.4.7/collector)ypes

The types package contains types.AuditRecord interface implementations for each supported protocol, to enable converting data to the CSV format. For this purpose, each protocol must provide a CSVRecord() \[]string and a CSVHeader() \[]string function. Additionally, a NetcapTimestamp() string function that returns the Netcap timestamp must be implemented.

### encoder

[https://pkg.go.dev/github.com/dreadl0ck/netcap@v0.5/e](https://pkg.go.dev/github.com/dreadl0ck/netcap@v0.4.7/collector)ncoder

The encoder package implements conversion of decoded network protocols to protocol buffers. This has to be defined for each supported protocol. Two types of encoders exist: The LayerEncoder and the CustomEncoder.

#### Layer Encoder

A LayerEncoder operates on a gopacket.Layer and has to provide the gopacket.LayerType constant, as well a handler function to receive the layer and the timestamp and convert it into a protocol buffer.

#### Custom Encoder

A CustomEncoder operates on a gopacket.Packet and is used to decode traffic into abstrac- tions such as Flows or Connections. To create it a name has to be supplied among three different handler functions to control initialization, decoding and deinitialization. Its handler function receives a gopacket.Packet interface type and returns a proto.Message. The postinit function is called after the initial initialization has taken place, the deinit function is used to teardown any additionally created structures for a clean exit. Both functions are optional and can be omitted by supplying nil as value.

### resolvers

[https://pkg.go.dev/github.com/dreadl0ck/netcap@v0.5/r](https://pkg.go.dev/github.com/dreadl0ck/netcap@v0.4.7/collector)esolvers

Resolvers for lookup of various external information, such as geolocation, domain names, hardware addresses, port numbers etc

### dpi

[https://pkg.go.dev/github.com/dreadl0ck/netcap@v0.5/d](https://pkg.go.dev/github.com/dreadl0ck/netcap@v0.4.7/collector)pi

Deep Packet Inspection integration, using a fork of **mushorg/go-dpi** that was extended to identify the full range of protocols offered by **nDPI** and **libprotoident**. Both libraries are loaded dynamically at runtime and is invoked via C bindings.

The fork can be found here:

{% embed url="<https://github.com/dreadl0ck/go-dpi>" %}
Deep Packet Inspection Package
{% endembed %}

### delimited

[https://pkg.go.dev/github.com/dreadl0ck/netcap@v0.5/d](https://pkg.go.dev/github.com/dreadl0ck/netcap@v0.4.7/collector)elimited

Primitives for reading and writing length delimited binary data

### utils

[https://pkg.go.dev/github.com/dreadl0ck/netcap@v0.5/u](https://pkg.go.dev/github.com/dreadl0ck/netcap@v0.4.7/collector)tils

The utils package contains shared utility functions used by several other packages.

### collector

[https://pkg.go.dev/github.com/dreadl0ck/netcap@v0.5/collector](https://pkg.go.dev/github.com/dreadl0ck/netcap@v0.4.7/collector)

The collector package provides an interface for fetching packets from a data source, this can either be a PCAP / PCAPNG file or directly from a named network interface. It is used to implement the command-line interface for Netcap.

{% hint style="info" %}
Warning: Do not use multiple instances of a collector in parallel! This is not supported yet. Once it is possible, this warning will be removed.
{% endhint %}

### io

[https://pkg.go.dev/github.com/dreadl0ck/netcap@v0.5/io](https://pkg.go.dev/github.com/dreadl0ck/netcap@v0.4.7/collector)

Primitives for atomic maps and write operations

## Caveats

Protocol buffers have a few caveats that developers and researchers should be aware of. First, there are no types for 16 bit signed (int16) and unsigned (uint16) integers in protobuf, also there is no type for unsigned 8 bit integers (uint8). This data type is seen a lot in network protocols, so the question arises how to represent it in protocol buffers. The non-fixed integer types use variable length encoding, so int32 is used instead. The variable-length encoding will take care of not sending the bytes that are not being used. Unfortunately, the mu type is too short for this purpose. Second, protocol buffers require all strings to be encoded as valid UTF-8, otherwise encoding to proto will fail. This means all input data that will be encoded as a string in protobuf must be checked to contain valid UTF-8, or they will create an error upon serialization and end up in the errors.pcap file. If this behavior is not desired strings must be filtered prior to setting them on the protocol buffer instances. Another thing that has to be kept in mind is that Netcap processes packets in parallel, thus the order in which packets are written to the dump file is not guaranteed. In experiments, no mixup was detected, and records were tracked in the correct order. However, under heavy load conditions or with a high number of workers, this might be different. Because of this caveat, the Netcap specification requires each record to preserve the timestamp, in order to allow sorting the packets afterwards, if required.

## Data Race Detection Builds

In concurrent programming, shared resources need to be synchronized, in order to guarantee their state when modifying or reading them. If access is not synchronized, race conditions occur, which will lead to faulty program behavior. To avoid this and detect race conditions early in the development cycle, the go toolchain offers compiling the program with the race detector enabled. This will let the application crash with stack traces to assist the developer in debugging, if a data race occurs. Programs with active race detection are slower by the factor of 10 to 100. To compile a Go program with the race detection enabled the **-race** flag must be added to the compilation command.

To compile a netcap binary with the race detection enabled use:

```
$ zeus install-race
```


# Metrics

Prometheus Metrics

## Introduction

Netcap now supports exporting prometheus metrics about its go runtime, the collection process and the audit records itself. These data points can be used to gain insights about the collection performance or discover security related events.

[Prometheus](https://github.com/prometheus) is an open-source systems monitoring and alerting toolkit originally built at [SoundCloud](https://soundcloud.com/). Since its inception in 2012, many companies and organizations have adopted Prometheus, and the project has a very active developer and user [community](https://prometheus.io/community). It is now a standalone open source project and maintained independently of any company.

{% embed url="<https://prometheus.io>" %}
Prometheus Homepage
{% endembed %}

To visualize the captured data I recomment the open source analytics and monitoring solution Grafana:

{% embed url="<https://grafana.com/grafana/>" %}
Grafana Homepage
{% endembed %}

This feature can be used with the **export** tool, which behaves similar to **capture** but is able to operate on pcaps, audit records and network interfaces.

## Configuration

Metrics are served by default on [**127.0.0.1:7777/metrics**](http://127.0.0.1:7777/metrics). Configure a prometheus instance to scrape it:

```yaml
# reference: https://prometheus.io/docs/prometheus/latest/configuration/configuration/

global:
  scrape_interval: 15s
  scrape_timeout: 15s
  #evaluation_interval: 15s

scrape_configs:
  # process_ metrics
  - job_name: netcap
    metrics_path: /metrics
    scheme: http
    static_configs:
      - targets:
        - 127.0.0.1:7777
```

{% hint style="info" %}
Tip: The latest prometheus config documentation can be found at: [https://prometheus.io/docs/prometheus/latest/configuration/configuration](https://prometheus.io/docs/prometheus/latest/configuration/configuration/)
{% endhint %}

Run the export tool to capture live from an interface:

```
net export -iface en0
```

{% hint style="info" %}
Tip: Use `$ net capture -interfaces` to get a list of available interfaces to choose from
{% endhint %}

Go to <http://localhost:9090> or to the port you configured alternatively, to check if your prometheus instance is scraping data correctly. Now that we have some data at hands, lets use Grafana to visualize it!

You can setup Grafana on macOS via brew:

```
$ brew install grafana
```

{% hint style="info" %}
Tip: On macOS, Grafanas default config is at **/usr/local/etc/grafana/grafana.ini** and installed plugins are stored at **/usr/local/opt/grafana/share/grafana/data/plugins**.
{% endhint %}

Start the prometheus server and pass the previously created config:

```
$ prometheus --config.file prometheus/prometheus.yml
```

You need to install the pie chart plugin for grafana:

```
$ cd /usr/local/opt/grafana/share/grafana/data/plugins
$ git clone https://github.com/grafana/piechart-panel.git --branch release-1.4.0
```

Start the grafana server:

```
$ grafana-server --homepath /usr/local/opt/grafana/share/grafana
```

Now download the NETCAP Dashboard and import it into Grafana:

{% file src="/files/-M5bLwIZdA6CfbX1Q1mP" %}

Go to **Settings > Datasources** and a prometheus datasource, either with the default port 9090 or the one you choose in the config.

You should be good to go!

## Usage

Export a PCAP dumpfile and serve metrics .

```
$ net export -read 2017-09-19-traffic-analysis-exercise.pcap
```

Capture and export traffic live from the named interface:

```
$ net export -iface en0
```

Export a specific audit record file:

```
$ net export -read HTTP.ncap.gz
```

Export all audit record files in the current directory:

```
$ net export .
```

## Overview Dashboard Preview

![Grafana Dashboard Overview](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-LqkPR4DukbeBJnAbdn3%2F-LqkPRu3NbjO2GXz3Jei%2Fscreenshot-2019-05-04-at-23.39.19.png?generation=1570622789111658\&alt=media)

## TCP Dashboard Preview

![Grafana Dashboard TCP](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-LqkPR4DukbeBJnAbdn3%2F-LqkPRu5fN9Ey985AMOD%2Fscreenshot-2019-05-04-at-23.39.41.png?generation=1570622789205206\&alt=media)

## HTTP Dashboard Preview

![Grafana Dashboard HTTP](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-LqkPR4DukbeBJnAbdn3%2F-LqkPRu7v-GhYWl_OOHq%2Fscreenshot-2019-05-04-at-23.40.05.png?generation=1570622789228247\&alt=media)


# Resolvers

Historical v0.5 resolver documentation; legacy database distribution retired

This is the historical Netcap v0.5 documentation. Its bundled resolver ZIP and legacy v1/v2 database distribution are retired. Do not use historical archives or third-party download instructions from older copies of this page.

## Current Installation

Upgrade using [Netcap Go releases](https://github.com/dreadl0ck/netcap/releases/latest) or [Netcap Rust releases](https://github.com/dreadl0ck/netcap-rs/releases/latest), then follow the [current resolver guide](https://docs.netcap.io/resolvers) and [current installation guide](https://docs.netcap.io/installation).

```sh
net util -download-dbs
net util -update-dbs
```

These commands require a signed-update-capable client (Go v0.15.2 / Rust v0.1.9 or compatible newer versions). They are not upgrade instructions for the v0.5 executable. Current data defaults to `~/.config/netcap/dbs`, with `NC_CONFIG_ROOT` selecting its parent.

| Historical data source                     | Current replacement/status                                                        |
| ------------------------------------------ | --------------------------------------------------------------------------------- |
| MaxMind bundled geolocation                | DB-IP Lite community City/ASN; optional user-supplied GeoLite2 has separate terms |
| macaddress.io vendor database              | Embedded OUI table                                                                |
| Alexa domain whitelist                     | Retired; no community whitelist distributed                                       |
| Trisul/ja3er JA3 identification catalogues | Not shipped                                                                       |
| Nmap service-probe catalogue               | Reader retired; bounded built-in protocol signatures                              |
| Legacy CMS/DHCP OS catalogues              | Enrichment disabled; packet decoding remains                                      |
| CVE data                                   | NVD-only SQLite schema 2 with structured applicability and reference URLs         |

## Historical Configuration

The v0.5 flags and paths are historical interfaces. Consult the installed executable's help and the [v0.5 source tag](https://github.com/dreadl0ck/netcap/tree/v0.5) when investigating old captures. A historical source reference does not establish redistribution permission for its former third-party data.

Passive DNS and system reverse-DNS resolution remain distinct: reverse lookups can generate network traffic. For current options and file ownership, use the current resolver guide rather than placing user files into a managed signed release.


# TLS Fingerprinting

Identify client and server that are using encrypted connections

## TLS Audit Records

Watch a quick demo of creating and exploring the **TLSClientHello** audit records on the command-line

{% embed url="<https://asciinema.org/a/KfhJRM3P4b0GsMtVCtelzWMbK>" %}

## JA3

JA3 is a technique developed by Salesforce, to fingerprint the TLS client and server hellos.

The official python implementation can be found [here](https://github.com/salesforce/ja3).

More details can be found in their blog post:

{% embed url="<https://engineering.salesforce.com/open-sourcing-ja3-92c9e53c3c41>" %}
JA3 blog post from salesforce
{% endembed %}

Support for JA3 and JA3S in netcap is implemented via:

{% embed url="<https://github.com/dreadl0ck/ja3>" %}
JA3(S) go package
{% endembed %}

The *TLSClientHello* and *TLSServerHello* audit records, as well as the *DeviceProfiles* provide JA3 hashes.

## JA3 Details

JA3 gathers the decimal values of the bytes for the following fields: **SSL Version, Accepted Ciphers, List of Extensions, Elliptic Curves, and Elliptic Curve Formats**.

It then concatenates those values together in order, using a “,” to delimit each field and a “-” to delimit each value in each field.

**The field order is as follows:**

```
SSLVersion,Ciphers,Extensions,EllipticCurves,EllipticCurvePointFormats
```

**Example:**

```
769,47–53–5–10–49161–49162–49171–49172–50–56–19–4,0–10–11,23–24–25,0
```

If there are no SSL Extensions in the Client Hello, the fields are left empty.

**Example:**

```
769,4–5–10–9–100–98–3–6–19–18–99,,,
```

These strings are then MD5 hashed to produce an easily consumable and shareable 32 character fingerprint.

This is the JA3 SSL Client Fingerprint.

JA3 is a much more effective way to detect malicious activity over SSL than IP or domain based IOCs. Since JA3 detects the client application, it doesn’t matter if malware uses DGA (Domain Generation Algorithms), or different IPs for each C2 host, or even if the malware uses Twitter for C2, JA3 can detect the malware itself based on how it communicates rather than what it communicates to.

JA3 is also an excellent detection mechanism in locked-down environments where only a few specific applications are allowed to be installed. In these types of environments one could build a whitelist of expected applications and then alert on any other JA3 hits.

For more details on what you can see and do with JA3 and JA3S, please see this Shmoocon 2018 talk: <https://youtu.be/oprPu7UIEuk?t=6m44s>

### Client Hello Audit Record

```erlang
message TLSClientHello {
    string Timestamp                  = 1;
    int32  Type                       = 2;
    int32  Version                    = 3;
    int32  MessageLen                 = 4;
    int32  HandshakeType              = 5;
    uint32 HandshakeLen               = 6;
    int32  HandshakeVersion           = 7;
    bytes  Random                     = 8;
    uint32 SessionIDLen               = 9;
    bytes  SessionID                  = 10;
    int32  CipherSuiteLen             = 11;
    int32  ExtensionLen               = 12;
    string SNI                        = 13;
    bool   OSCP                       = 14;
    repeated int32 CipherSuites       = 15;
    repeated int32 CompressMethods    = 16;
    repeated int32 SignatureAlgs      = 17;
    repeated int32 SupportedGroups    = 18;
    repeated int32 SupportedPoints    = 19;
    repeated string ALPNs             = 20;
    string Ja3                        = 21;
    string SrcIP                      = 22;
    string DstIP                      = 23;
    string SrcMAC                     = 24;
    string DstMAC                     = 25;
    int32 SrcPort                     = 26;
    int32 DstPort                     = 27;
    repeated int32 Extensions         = 28;
}
```

## JA3S Details

JA3S is JA3 for the Server side of the SSL/TLS communication and fingerprints how servers respond to particular clients.

JA3S uses the following field order:

```
SSLVersion,Cipher,SSLExtension
```

With JA3S it is possible to fingerprint the entire cryptographic negotiation between client and it's server by combining JA3 + JA3S. That is because servers will respond to different clients differently but will always respond to the same client the same.

For the Trickbot example:

```
JA3 = 6734f37431670b3ab4292b8f60f29984 ( Fingerprint of Trickbot )
JA3S = 623de93db17d313345d7ea481e7443cf ( Fingerprint of Command and Control Server Response )
```

For the Emotet example:

```
JA3 = 4d7a28d6f2263ed61de88ca66eb011e3 ( Fingerprint of Emotet )
JA3S = 80b3a14bccc8598a1f3bbe83e71f735f ( Fingerprint of Command and Control Server Response )
```

In these malware examples, the command and control server always responds to the malware client in exactly the same way, it does not deviate. So even though the traffic is encrypted and one may not know the command and control server's IPs or domains as they are constantly changing, we can still identify, with reasonable confidence, the malicious communication by fingerprinting the TLS negotiation between client and server. Again, please be aware that these are examples, not indicative of all versions ever, and are intended to illustrate what is possible.

### Server Hello Audit Record

```erlang
message TLSServerHello {
    string Timestamp                   = 1;
    int32  Version                     = 2;
    bytes  Random                      = 3;
    bytes  SessionID                   = 4;
    int32  CipherSuite                 = 5;
    int32  CompressionMethod           = 6;
    bool NextProtoNeg                  = 7;
    repeated string NextProtos         = 8;
    bool OCSPStapling                  = 9;
    bool TicketSupported               = 10;
    bool SecureRenegotiationSupported  = 11;
    bytes SecureRenegotiation          = 12;
    string AlpnProtocol                = 13;
    bool Ems                           = 14;
    repeated bytes Scts                = 15;
    int32 SupportedVersion             = 16;
    bool SelectedIdentityPresent       = 18;
    int32 SelectedIdentity             = 19;
    bytes Cookie                       = 20;
    int32 SelectedGroup                = 21;
    repeated int32 Extensions          = 22;
    string SrcIP                       = 23;
    string DstIP                       = 24;
    string SrcMAC                      = 25;
    string DstMAC                      = 26;
    int32 SrcPort                      = 27;
    int32 DstPort                      = 28;
    string Ja3s                        = 29;
}
```


# Reassembly

TCP stream reassembly

## Implementation

For reassembling TCP streams the gopacket/reassembly implementation is used. This allows to parse application layer protocols such as HTTP and POP3. The reassembly package currrently only implements reassembling stream over IPv4. To overcome this limitation for HTTP capture, you can use the **proxy** tool.

{% content-ref url="/pages/-Ld3UN5WUZqlTlm2MG5s" %}
[HTTP Proxy](/v0.5/http-proxy)
{% endcontent-ref %}

## Architecture

The gopacket reassembly implementation leaves several options for using it.

Netcap currently uses one dedicated assembler for each worker and a single shared connection pool for all streams.

Another option would be using a dedicated assembler for each worker for each L7 protocol with a shared stream pool for that specific protocol. This would potentially decrease lock contention for the reassembly, and might be implemented to improve performance in future versions.

## Configuration

The following fields of the **encoder.Config** affect the TCP stream reassembly:

```go
// Interval to apply connection flushes
FlushEvery         int

// Do not use IPv4 defragger
NoDefrag           bool

// Dont verify the packet checksums
Checksum           bool

// Dont check TCP options
NoOptCheck         bool

// Ignore TCP state machine errors
IgnoreFSMerr       bool

// TCP state machine allow missing init in three way handshake
AllowMissingInit   bool

// Toggle debug mode
Debug              bool

// Dump packet contents as hex for debugging
HexDump            bool

// Wait until all connections finished processing when receiving shutdown signal
WaitForConnections bool

// Write incomplete HTTP responses to disk when extracting files
WriteIncomplete    bool
```

## Debugging

To see debug output for the reassembly, run with the **-debug** flag and check the **reassembly.log** file.

For more general troubleshooting advice, please refer to the Troubleshooting page:

{% content-ref url="/pages/-M4pSNs8UVjcQS6cDVc-" %}
[Troubleshooting](/v0.5/troubleshooting)
{% endcontent-ref %}


# Deep Packet Inspection

Identify applications and categories

## Libprotoident

NETCAP has support for using **libprotoident** (v[2.0.14](https://github.com/wanduow/libprotoident/releases/tag/2.0.14-1)), to identify 45 application categories and 500+ applications and protocols!

The full list of supported protocols can be found here:

{% embed url="<https://github.com/wanduow/libprotoident/wiki/SupportedProtocols>" %}
Libprotoident Supported Protocols
{% endembed %}

**libprotoident** is maintained by the WAND group, you can download and install the library here:

{% embed url="<https://github.com/wanduow/libprotoident>" %}
Libprotoident Source Code
{% endembed %}

## nDPI

Furthermore **nDPI** (v3.0) can be used to identify 244 applications, they are listed here:

{% embed url="<https://github.com/ntop/nDPI/wiki/Supported-Protocols>" %}
nDPI Supported Protocols
{% endembed %}

**nDPI** is mainted by **ntop**, and can be downloaded here:

{% embed url="<https://github.com/ntop/nDPI>" %}
nDPI Source Code
{% endembed %}

The results from all heuristic engines (lPI, nDPI and go heuristics) get dedpulicated automatically. Future versions could create a certainity score based on the number of votes from different heuristics.

DPI is currently used to indicate which applications have been seen for which **IPProfile**, when using the **DeviceProfile** encoder.

Read more about DeviceProfiles here:

{% content-ref url="/pages/-M4zgij9Nh\_pcelAun7g" %}
[Device Profiles](/v0.5/device-profiles)
{% endcontent-ref %}

## Platform Support

NETCAPs DPI integration is currently only available on linux and macOS.


# Live Capture

Capture from a network interface

To capture packets live, simple use the **-iface** flag:

```
$ net capture -iface en0
```

Use the **-interfaces** flag to list all available intefaces and their MTUs:

```
$ net capture -interfaces
┌───────┬─────────┬───────────────────────────┬───────────────────┬───────┐
│ Index │  Name   │           Flags           │   HardwareAddr    │  MTU  │
├───────┼─────────┼───────────────────────────┼───────────────────┼───────┤
│ 1     │ lo0     │ up|loopback|multicast     │                   │ 16384 │
│ 2     │ gif0    │ pointtopoint|multicast    │                   │ 1280  │
│ 3     │ stf0    │ 0                         │                   │ 1280  │
│ 4     │ en5     │ up|broadcast|multicast    │ XX:XX:XX:XX:XX:XX │ 1500  │
│ 5     │ ap1     │ broadcast|multicast       │ XX:XX:XX:XX:XX:XX │ 1500  │
│ 6     │ en0     │ up|broadcast|multicast    │ XX:XX:XX:XX:XX:XX │ 1500  │
│ 7     │ en4     │ up|broadcast|multicast    │ XX:XX:XX:XX:XX:XX │ 1500  │
│ 8     │ en1     │ up|broadcast|multicast    │ XX:XX:XX:XX:XX:XX │ 1500  │
│ 9     │ en2     │ up|broadcast|multicast    │ XX:XX:XX:XX:XX:XX │ 1500  │
│ 10    │ en3     │ up|broadcast|multicast    │ XX:XX:XX:XX:XX:XX │ 1500  │
│ 11    │ bridge0 │ up|broadcast|multicast    │ XX:XX:XX:XX:XX:XX │ 1500  │
│ 12    │ p2p0    │ up|broadcast|multicast    │ XX:XX:XX:XX:XX:XX │ 2304  │
│ 13    │ awdl0   │ up|broadcast|multicast    │ XX:XX:XX:XX:XX:XX │ 1484  │
│ 14    │ llw0    │ up|broadcast|multicast    │ XX:XX:XX:XX:XX:XX │ 1500  │
│ 15    │ utun0   │ up|pointtopoint|multicast │                   │ 1380  │
│ 16    │ utun1   │ up|pointtopoint|multicast │                   │ 2000  │
│ 17    │ utun2   │ up|pointtopoint|multicast │                   │ 1380  │
│ 18    │ utun3   │ up|pointtopoint|multicast │                   │ 1380  │
│ 19    │ utun4   │ up|pointtopoint|multicast │                   │ 1380  │
│ 20    │ utun5   │ up|pointtopoint|multicast │                   │ 1380  │
│ 21    │ utun6   │ up|pointtopoint|multicast │                   │ 1380  │
│ 22    │ utun7   │ up|pointtopoint|multicast │                   │ 1380  │
└───────┴─────────┴───────────────────────────┴───────────────────┴───────┘
```

## Promiscous Mode

Netcap uses promiscous mode by default, which requires root permissions. You can toggle this behavior with the **-promisc** flag:

```
$ net capture -iface en0 -promisc=false
```

## Windows

For windows, things work a little bit different.

First, download & install the latest version of **WinPcap**:

{% embed url="<https://www.winpcap.org/install/>" %}

Next, open a CMD prompt and run:

```aspnet
C:\>getmac /fo csv /v
"Connection Name","Network Adapter","Physical Address","Transport Name"
"Ethernet0","Intel(R) PRO/1000 MT Network Connection","00-0C-29-BB-EC-9B","\Device\Tcpip_{B1B1E59F-FA8F-4A7B-B28C-7A26F6E00F5A}"
```

Note down the Identifier for your adapter of interest (here: **Ethernet0**), in this example the identifier is:

```aspnet
\Device\Tcpip_{B1B1E59F-FA8F-4A7B-B28C-7A26F6E00F5A}
```

To capture traffic on the interface,&#x20;

you must prefix the interface **ID ({B1B1E59F-FA8F-4A7B-B28C-7A26F6E00F5A})** with **\Device\NPF\_**

This leaves us with the final command:

```aspnet
net.exe capture -iface \Device\NPF_{B1B1E59F-FA8F-4A7B-B28C-7A26F6E00F5A}
```

{% hint style="info" %}
Info: When you stop the packet capture on windows with ctrl-C you will see several errors of the format:

`failed to remove file remove XXXXX.ncap.gz: The process cannot access the file because it is being used by another process.`&#x20;

This happens because NETCAP creates and opens files for all supported audit records types on startup, and closes them when packet capture is finished or interrupted. Since it often happens that not all supported protocols appeared in the data stream, NETCAP opens the audit record files after closing again, to check if they are empty (=only contain the NETCAP header), and if so, removes the empty audit record files.

Unfortunately, windows does not allow closing and opening a file from the same process within such small time interval, which leads to the shown error. As a consequence, empty audit record files are not removed automatically on windows.

If you know a workaround for this, please let me know.
{% endhint %}


# Maltego Integration

Graphical link analysis to the rescue!

## Introduction

**Maltego** is an open source intelligence (OSINT) and graphical link analysis tool for gathering and connecting information for investigative tasks.

{% embed url="<https://www.maltego.com>" %}

It allows to transform data using external knowledge and visualize the results in a graph topology.

Transforms are small pieces of code that automatically fetch data from different sources and return the results as visual entities in the desktop client. Transforms are the central elements of Maltego which enable its users to unleash the full potential of the software whilst using a point-and-click logic to run analyses.

Netcap provides a set of entities and transformations to analyze packet capture dump files in Maltego!

The current implementation focuses on behavorial analysis of entities within the traffic dump.

## Installation

Ensure netcap **>= v0.5** is installed and can be found in **$PATH**:

```
$ net -version
v0.5
```

Ensure the **net** binary is placed in **/usr/local/bin**:

```
$ which net
/usr/local/bin/net
```

{% hint style="info" %}
Transformations in maltego have to specify a working directory. Currently /**usr/local** is used for this so make sure the current user has sufficient right to enter the directory. No data will be written there, all logs from transformations that invoke the netcap core are written into dedicated directories for each processed pcap file.
{% endhint %}

Next, download install the maltego transformations and enities for netcap:

Currently there are **20 entities** and **42 transformations** implemented. You can download them here:

{% file src="/files/-M5WMXmGHlrZKgvb0PLA" %}

Import them into Maltego in the "**Import / Export Config**" tab under "**Import Config**".

## Loading PCAP files into Maltego

To load a pcap file into maltego you have two options:

1\) Drag and Drop the file into a maltego graph. The files type will be **maltego.File** by default, and the path to the file on disk is set as a note on the entity.

Now, change the entities type to **netcap.PCAP**, and double click it to open the detail view. Copy the filesystem path from the **Notes** tab into the **path** property of the PCAP entity.

2\) Create a new **netcap.PCAP** entity and set the **path** property to the path of your pcap file on disk

## Running Transformations

Right click an entity and start typing **Get** into the search bar to see all available transformations for the selected type. Alternatively you can also use the **Run View** in the **Windows** tab to see and launch available transformations with a single click.

Transformations are usually bound to specific entities. For example, the **netcap.DeviceProfiles** entity, which represents the device profiles that have been derived from an input PCAP file, currently only offers the following two transformations:

![](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-M5XD2kpH4yKjc6gO7FF%2F-M5Xfon6c4TAO_Kbh1IN%2FScreenshot%202020-04-22%20at%2011.50.20.png?alt=media\&token=976aeee8-59c2-492f-ae58-cc4e0136ccf8)

**GetDeviceProfilesWithDPI** enables deep packet inspection, which requires to install dependencies and can slow down the processing drastically. When not using DPI the transformations making use of this data will simply return no results.

To add the actual devices to the graph, use the **GetDevices** transformation.

![](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-M5XD2kpH4yKjc6gO7FF%2F-M5XenFiN06my_CIY5Mu%2FScreenshot%202020-04-22%20at%2011.50.26.png?alt=media\&token=68241782-d6ca-44cb-8b42-30a01004acf9)

This bring the first usable entities to the graph, of type **netcap.Device**. A device has contacts and addresses it has been using to access network services by itself. When selecting a device entity, you will see the following transformations:

![](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-M5XD2kpH4yKjc6gO7FF%2F-M5XfSCvVACoq0Ki1VfO%2FScreenshot%202020-04-22%20at%2011.50.07.png?alt=media\&token=d23176db-7d49-426b-b3f3-da6215f6a93f)

The generated entities will be of type **netcap.IPAddr** and contain information about the host, as well as a set of transforms to further drill down and investigate.

When selecting an entity of type **netcap.IPAddr**, the following transformations are offered:

![netcap.IPAddr transformations](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-M5XD2kpH4yKjc6gO7FF%2F-M5XdRgKRJe1lBrsszv-%2FScreenshot%202020-04-22%20at%2011.49.53.png?alt=media\&token=d22caf3e-84c1-4777-a780-1fa1619d406d)

## Configuration

Netcap offers an **OpenFile** maltego transform, which will pass filetypes except for executables to the default system application for the corresponding file format. On macOS the open utility will be used for this and on the linux the default is gio open. You can override the application used for this by setting **NC\_MALTEGO\_OPEN\_FILE**.

## Examples

Search for DHCP information from the selected hosts:

![](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-M5Xh6xSqodfmoX_fH7i%2F-M5XhHXTxQ-07HJGtQLH%2Fdhcp.mov.gif?alt=media\&token=845f7d08-120a-40f4-93d6-6d8bfaa7b6f3)

Add Server Names provided as SNI on the TLS handshake:

![](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-M5XhNNG6azBoZB58X4x%2F-M5Xhaq2Un74mbFGA4tD%2Fsnis.mov.gif?alt=media\&token=d58d97a6-a9e8-401b-82bc-632dc5bed942)

Use Deep Packet Inspection to list all identified application categories:

![](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-M5XhNNG6azBoZB58X4x%2F-M5XhpGDioQY16Px9mQd%2FdpiCategories2.mov.gif?alt=media\&token=c82f5118-18a3-4d18-bc40-603d729dd727)

Extraction of a POP3 authentication token:

![](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-M5XlkVYIeMq16dnJ9-G%2F-M5XmdbCPzyLQcI9jkm8%2FmailToken.mov.gif?alt=media\&token=803c8bf6-c0f1-48cd-92cd-2400466670c9)

## Gallery

When working with larger amount of nodes, the organic topology can be useful:&#x20;

![Graph during an investigation (organic topology)](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-M4pT3gid3DGbx3WBNAB%2F-M4pT4QzVTRyAYY_MIhK%2Fscreenshot-2020-03-25-at-01.22.54.png?generation=1586813755426131\&alt=media)

Example of interaction with a PHP webshell:

![PHP webshell interaction](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-M4pT3gid3DGbx3WBNAB%2F-M4pT4R0oxG4V3OIhy5P%2Fscreenshot-2020-03-25-at-15.00.45%20\(1\).png?generation=1586813755697939\&alt=media)

Example of an exploit abusing a HTTP parameter command injection vulnerability:

![HTTP parameter command injection](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-M4pT3gid3DGbx3WBNAB%2F-M4pT4R2VkF2sr1iKZSE%2Fscreenshot-2020-03-25-at-15.00.55.png?generation=1586813755109325\&alt=media)

Graph during an investigation where the attacker has been identified and further information is gathered:

![Dataset investigation](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-M4zi4EuuxESi0rl7ybp%2F-M4zlcbKtUlsLz79kL2e%2FScreenshot%202020-03-25%20at%2000.20.06.png?alt=media\&token=b2339db3-8f70-44b5-ac66-d985f0f14c44)

![Dataset investigation](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-M4zi4EuuxESi0rl7ybp%2F-M4zm2PH-Rh4-kt99rX5%2FScreenshot%202020-03-24%20at%2023.52.23.png?alt=media\&token=521f5aaa-5ae0-4e1e-914d-4ee32682fae8)

![Flow Graph](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-M4zi4EuuxESi0rl7ybp%2F-M4zloIdCPwzDrcwoYtu%2FScreenshot%202020-03-25%20at%2020.19.15.png?alt=media\&token=af1d4501-31a5-4767-bcbb-2a3aa3b634ac)

## Detail Views

![](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-M5XD2kpH4yKjc6gO7FF%2F-M5Xh0dpS4dTdt0bzCF-%2FScreenshot%202020-04-22%20at%2011.54.48.png?alt=media\&token=3019f4a1-1469-4460-ad18-092f49dcc932)

![](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-M5Xi8v3ibRXDunBi3nl%2F-M5XiU2R3LIJMsfM4GOX%2FScreenshot%202020-04-22%20at%2012.01.05.png?alt=media\&token=e06c5b29-fcd0-43ad-97fb-b00ed8326a3c)

![](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-M5Xi8v3ibRXDunBi3nl%2F-M5XimlxAjqbP6NdGMv0%2FScreenshot%202020-04-22%20at%2012.04.55.png?alt=media\&token=7ccea911-600a-4695-bc46-7ee3b4c838aa)

![](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-M5Xi8v3ibRXDunBi3nl%2F-M5XipirHhG9fK26tfBE%2FScreenshot%202020-04-22%20at%2012.02.08.png?alt=media\&token=69e58de9-be4c-46bb-b8c2-44942c13a960)

![](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-M5Xi8v3ibRXDunBi3nl%2F-M5XiuwQt33Bk69C3g6r%2FScreenshot%202020-04-22%20at%2012.02.03.png?alt=media\&token=ce2400e5-04fd-42d1-b658-ed1fd3a35830)

![](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-M5Xi8v3ibRXDunBi3nl%2F-M5Xj0MFh3cX41uaEuLY%2FScreenshot%202020-04-22%20at%2012.03.33.png?alt=media\&token=6226d7d6-b69e-4779-bff4-9e58160eb532)


# Logging

Logging options

## Quiet mode

Netcap writes a general summary to stdout, if you wish to disable output entirely use the **-quiet** flag:

```
$ net capture -quiet
```

When the quiet mode is used, the output is instead written into the **netcap.log** file in the directory where netcap is executed from.

## Decoding errors

Errors when parsing packets are logged by default into the **errors.log** file in the current directory.

Each log entry contains a hex dump of the entire packet and the error message or stack trace.

## Log files in debug mode

The following log file are produced when running with the **-debug** flag:

* debug.log: general debug messages
* reassembly.log: tcp stream reassembly debug logs


# Packet Contexts

Preserve information about other layers on audit records

Netcap v0.4.3 added PacketContexts, a new feature to preserve additional information on audit records.

This need originates from a core concept of Netcap: separating the results based on the different protocols, which results in audit records like TCP not providing any IP address information, since they only provide information about the TCP protocol which operates at the Transport Layer.

A packet context looks as follows:

```erlang
message PacketContext {
    string SrcIP    = 1;
    string DstIP    = 2;
    string SrcPort  = 3;
    string DstPort  = 4;
}
```

Many audit record types (e.g: IPv4, IPv6, TCP, UDP, ICMPv4, ICMPv6, SCTP, DNS, DHCP, SIP etc) now have an addional field called context, which will contain a PacketContext that describes the flow where the packet originated from, if context capture is enabled.

When generating a CSV representation the fields from the PacketContext are flattened, which means they will be shown as if they are direct member of the dumped audit record, e.g:

```
$ net dump -read UDP.ncap.gz -fields
Timestamp,SrcPort,DstPort,Length,Checksum,PayloadEntropy,PayloadSize,Payload,SrcIP,DstIP
```

If the audit record already has information that would be duplicated by the PacketContext (for example Port information for UDP), this information is cleared on the context to avoid repetition.

Context capture is enabled by default and can be controlled using the **-context** flag.


# Industrial Control Systems

ICS / SCADA threat hunting

## Protocol Support

Netcap offers audit records for the following protocols seen in industrial control systems:

* Ethernet/IP
* CIP - Common Industrial Protocol
* Modbus / ModbusTCP

The encoders are enabled by default.

## Modbus

```erlang
message Modbus {
    string Timestamp     = 1;
    int32  TransactionID = 2; // Identification of a MODBUS Request/Response transaction
    int32  ProtocolID    = 3; // It is used for intra-system multiplexing
    int32  Length        = 4; // Number of following bytes (includes 1 byte for UnitIdentifier + Modbus data length
    int32  UnitID        = 5; // Identification of a remote slave connected on a serial line or on other buses
    bytes  Payload       = 6;
    bool   Exception     = 7;
    int32  FunctionCode  = 8;
    
    PacketContext Context = 9;
}
```

## CIP

```erlang
message CIP {
    string          Timestamp        = 1;
    bool            Response         = 2; // false if request, true if response
    int32           ServiceID        = 3; // The service specified for the request
    uint32          ClassID          = 4; // request only
    uint32          InstanceID       = 5; // request only
    int32           Status           = 6; // Response only
    repeated uint32 AdditionalStatus = 7; // Response only
    bytes           Data             = 8; // Command data for request, reply data for response
    PacketContext   Context          = 9;
}
```

## ENIP

```erlang
message ENIP {
    string                  Timestamp        = 1;
    uint32                  Command          = 2; 
    uint32                  Length           = 3;
    uint32                  SessionHandle    = 4;
    uint32                  Status           = 5;
    bytes                   SenderContext    = 6;
    uint32                  Options          = 7;
    ENIPCommandSpecificData CommandSpecific  = 8;
    PacketContext           Context          = 9;
}
```


# File Extraction

Extract transferred files and save them to disk

## Introduction

Various protocols allow transferring files (e.g: HTTP, POP3) and some are made for the sole purpose of transferring files (FTP, SMB etc).

From a network security monitoring perspective, transferred files are interesting because they can contain malicious software or prohibited content.

Netcap extracts files from HTTP and saves them to disk, for both HTTP responses and HTTP requests.

It uses the **File** audit record type to model the extracted information.

> Future versions will add file extraction support for other protocols as well.

## File Audit Records

The audit record definition for a file looks like this:

```erlang
message File {
    string        Timestamp   = 1;
    string        Name        = 2;
    int64         Length      = 3;
    string        Hash        = 4;
    string        Location    = 5;
    string        Ident       = 6;
    string        Source      = 7;
    string        ContentType = 8;
    PacketContext Context     = 9;
    string        Host        = 10;
    string        ContentTypeDetected = 11;
}
```

As can be seen, the content type indicated by the HTTP header is included, as well as the content type that was detected. In addition, the source of the File is specified (e.g: from HTTP, Mail attachment etc), as well the identifier of the connection where it originated from.

The Hash field currently holds an MD5 hash of the file, Location points to the path on disk where the file is stored.

> This will likely be replaced with a stronger hash function in the future.

## Usage

To enable file capture, set the **-fileStorage** flag and supply a path to store the files to (will be created if it does not exist):

```
$ net capture -read traffic.pcap -fileStorage files
```

After capturing, lets inspect the directory contents:

```
$ tree files
files
├── application
│   └── x-gzip
│       └── unknown-193.24.227.12->216.66.80.30-80->60075.gz
├── image
│   └── x-icon
│       └── favicon.ico-193.24.227.12->216.66.80.30-80->60076.ico
└── text
    └── html
        ├── unknown-193.24.227.12->216.66.80.30-80->55031.html
        ├── unknown-193.24.227.12->216.66.80.30-80->55032.html
        ├── unknown-193.24.227.12->216.66.80.30-80->55033.html
        └── unknown-80.237.133.136->192.168.110.10-80->1152.html

6 directories, 6 files
```

As you can see, files are sorted by their MIME types retrieved from classifying them using the go standard library and named after the TCP connection they originated from.

By default, only complete requests and responses are captured, if you also want to extract incomplete data, use the **-writeincomplete** flag:

```
$ net capture -read traffic.pcap -fileStorage files -writeincomplete
```

Dumping a File on the commandline looks like this:

```
$ net dump -read File.ncap.gz -struc
NC_File
Timestamp: "2015-03-08 14:05:29.664213 +0000 UTC"
Name: "ads.bmp"
Length: 126
Hash: "2d5a035011854b04a456b244b15a583b"
Location: "files/image/bmp/ads.bmp-80.239.178.178->192.168.0.51-80->41214.bmp"
Ident: "80.239.178.178->192.168.0.51-80->41214"
Source: "HTTP RESPONSE from /ads.bmp"
Context: <
  SrcIP: "192.168.0.51"
  DstIP: "80.239.178.178"
  SrcPort: "41214"
  DstPort: "80"
>
ContentTypeDetected: "image/bmp"
...
```

For properly exploring files for each host I recommend using the Maltego Integration:

{% content-ref url="/pages/-M4pT434l2NNMvO9nGCE" %}
[Maltego Integration](/v0.5/maltego-integration)
{% endcontent-ref %}

![](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-M5kwOcXgkbeTC-uSGUK%2F-M5ky4VdFrnqCMdYGA2l%2Ffiles.png?alt=media\&token=aa2d450c-3c07-4d3a-84e4-c0e9a157c046)


# Email Extraction

Extract transferred emails

## Motivation

Emails are a key communication mechanism that holds plenty of digital evidence, starting from Mail header information about the sender and route, to transferred files via attachments.

Netcap currently extracts Email fetched over POP3 and support IMAP is in the making.

## POP3

A POP3 audit record contains information about the addresses involved, as well as authentication information. The fetched mails are provided as an array of **Mail** instances.

```erlang
message POP3 {
    string           Timestamp              = 1;
    string           ClientIP               = 2;
    string           ServerIP               = 3;
    string           AuthToken              = 4;
    string           User                   = 5;
    string           Pass                   = 6;
    repeated Mail    Mails                  = 7;
}
```

A Mail instance has the following fields:

```erlang
message Mail {
    string            ReturnPath            = 1;
    string            DeliveryDate          = 2;
    string            From                  = 3;
    string            To                    = 4;
    string            CC                    = 5;
    string            Subject               = 6;
    string            Date                  = 7;
    string            MessageID             = 8;
    string            References            = 9;
    string            InReplyTo             = 10;
    string            ContentLanguage       = 11;
    bool              HasAttachments        = 12;
    string            XOriginatingIP        = 13;
    string            ContentType           = 14;
    string            EnvelopeTo            = 15;
    repeated MailPart Body                  = 16;
}
```

For exploring captured emails, the Maltego Integration can be used:

{% content-ref url="/pages/-M4pT434l2NNMvO9nGCE" %}
[Maltego Integration](/v0.5/maltego-integration)
{% endcontent-ref %}

![](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-M5kwOcXgkbeTC-uSGUK%2F-M5kyIbH_wnm4b1scsMm%2Fmails1.png?alt=media\&token=6684e982-2edb-4b22-a290-0ba33eb7df33)

![](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-M5kwOcXgkbeTC-uSGUK%2F-M5kyNom5uMyxBCOnl-H%2Fmails2.png?alt=media\&token=73ab5273-1216-4c35-b53b-dfa5df839bcf)

## SMTP

For SMTP an audit record is also available, though mail extraction has not been implemented yet:

```erlang
message SMTP {
    string                 Timestamp     = 1;
    bool                   IsEncrypted   = 2;
    bool                   IsResponse    = 3;
    repeated SMTPResponse  ResponseLines = 4;
    SMTPCommand            Command       = 5;
    PacketContext          Context       = 6;
}
```


# Device Profiles

Behavorial Profiling with Netcap

## Motivation

Which device on the network uses which IP address? Which addresses / devices did it contact?

How are devices related to each other, how does communication flow?

Identifying devices within a network is a good starting point for any investigation and helps to understand complex situations and relations quickly. The **DeviceProfile** custom encoder implements exactly this, and is enabled from v0.5 on by default.

> Note: DeviceProfile currently get written when processing all traffic is done - that means when using live capture, the profiles will be available when processing stopped. Future versions will implement a flushing mechanism similar  to the one for Flows / Connections.

DeviceProfiles rely heavily on local resolvers to be set up and configured. You can use the **DeviceProfile** audit records without resolvers, but you will get less information. Read more about the resolvers here:

{% content-ref url="/pages/-M4pSNs9Ewumxyv3nEjO" %}
[Resolvers](/v0.5/resolvers)
{% endcontent-ref %}

Analyzing DeviceProfiles can be done using Maltego, for example:

{% content-ref url="/pages/-M4pT434l2NNMvO9nGCE" %}
[Maltego Integration](/v0.5/maltego-integration)
{% endcontent-ref %}

![DeviceProfiles and their used IP addresses from an industrial automation system](https://3338746466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La-SRWxzIGdy_3ynMZH%2F-M5lE9k6zhQnU2Zl0uvy%2F-M5lEVm_iZaECOSQ137P%2FScreenshot%202020-04-22%20at%2016.20.57.png?alt=media\&token=d3a5b530-d460-4779-a616-4c77511c42bf)

## DeviceProfile Audit Records

Lets look at the protocol buffer definition for a device profile:

```erlang
message DeviceProfile {
    string             MacAddr            = 1;
    string             DeviceManufacturer = 2;
    repeated IPProfile DeviceIPs          = 3;
    repeated IPProfile Contacts           = 4;
    int64              NumPackets         = 5;
    string             Timestamp          = 6; // first seen
    uint64             Bytes              = 7;
}
```

As you can see, a DeviceProfile is a summary structure built around the hardware address of a physical device. It captures the addresses that have been used, as well as the contacted addresses in form of IPProfiles, among other meta information, like the number of packets or the hardware manufacturer.

Lets take a closer look at an IPProfile:

```erlang
message IPProfile {
    string                 Addr            = 1;
    int64                  NumPackets      = 2;
    string                 Geolocation     = 3;
    repeated string        DNSNames        = 4;
    string                 TimestampFirst  = 5;
    string                 TimestampLast   = 6;
    repeated string        Applications    = 7;
    map<string, string>    Ja3             = 8; // ja3 to lookup
    map<string, Protocol>  Protocols       = 9;
    uint64                 Bytes           = 10;
    map<string, Port>      DstPorts        = 11; // Ports to bytes
    map<string, Port>      SrcPorts        = 12; // Ports to bytes
    map<string, int64>     SNIs            = 13;
}
```

This is the information associated with a single ip address. Note how in addition to general meta data like the number of packets, bytes and timestamps, there is also information retrieved from the new resolvers API, namely the geolocation and dns names.

Additionally, the results from Deep Packet Inspection for all flows seen from or towards this IP are added as well, in addition to the Server Name Indicators seen and flow statistics for each seen port number from this address.

To enhance encrypted telemetry, Ja3 fingerprints seen for this host are mapped to lookup results from the  Ja3 database.


# Python Integration

Read Netcap Audit records from Python

## Source Code

The Python library for interacting with netcap audit records has been published here:

{% embed url="<https://github.com/dreadl0ck/pynetcap>" %}

## Usage

### Read into python dictionary

Currently it is possible to retrieve the audit records as python dictionary:

```python
#!/usr/bin/python

import pynetcap as nc

reader = nc.NCReader('pcaps/HTTP.ncap.gz')

reader.read(dataframe=False)
print("RECORDS:")
print(reader.records)
```

### Read into pandas dataframe

Retrieving the audit records as pandas dataframe:

```python
#!/usr/bin/python

import pynetcap as nc

reader = nc.NCReader('pcaps/HTTP.ncap.gz')

reader.read(dataframe=True)
print("[INFO] completed reading the audit record file:", reader.filepath)
print("DATAFRAME:")
print(reader.df)
```


# Changelog

Detailed Version History Information

## v0.5 - April 2020

### Fixed

* multiple bugs in the stream reassembly
* several panics during parsing in gopacket&#x20;

### Changed

* CLI interface refactored: single binary app with subcommands, stripped size \~**17MB**
* Updated units tests
* Documentation updates
* Updated Docker containers for **Ubuntu** and **Alpine**
* Compiled with **Go 1.14.2**
* removed custom audit records Link-, Network- and TransportFlow

### New Features

* **Maltego** integration
* **File** audit records
* **Diameter** protocol audit records
* **SMTP** audit records
* **POP3** support for extracting Mails
* **JA3S** support and separate audit record for **TLSServerHello**
* New configuration options: via **environment variables** or **configuration** file
* Resolvers package for **Geolocation**, **DNS** and **Service** lookups and **whitelisting**
* Deep Packet Inspection via **nDPI** and **libprotoident**
* **DeviceProfile** Audit records, to capture the behavior of a single device within a traffic dump
* Added an integration for **bash-completion** support


# Troubleshooting

Look behind the curtain

## First Aid

* are all files in place?
* does the current user have sufficient rights to access them?
* does the current user have sufficient rights to access the current working directory?

## Pitfalls

* the go flag package implementation only allows to set boolean value using the **-name=value** syntax (e.g: **-debug=true**), but strings can be set also using a space instead with the **-name value** syntax (e.g: **-read traffic.pcap**)

## Debug Mode

Use the **-debug** flag to generate debug logs. The files will be created in the directory from which the netcap process has been started. The reassembly engine logs data into **reassembly.log** and all other debug messages go into **debug.log.**

> Remember that netcap logs packet decoding errors into **errors.log!**

## Advanced Debugging

In order to use advanced debugging features, you will need to recompile the code and make a few changes. Some primitives in the core library have a second implementation that spawns an additional goroutine for each invocation to time out the call. This is useful to debug hangs in the reassembly or due to invocation of external code, for example the DPI integration of **nDPI** and **libprotoident**.

List of \*Timeout primitives:

* handlePacketTimeout(p \*packet) in collector.go
* AssembleWithContextTimeout(...) in tcpConnection.go
* GetProtocolsTimeout(packet gopacket.Packet) in dpi.go

Simply replace the calls to the original versions with the \*Timeout primitives, and if one of those will block for longer than the configured thresholds, the call will be interrupted and an error logged.

## Race Detection Builds

To debug synchronization problems and data races you can compile a version with the **-race** flag set for the go compiler and see if the program crashes due to a race condition.

There is a command implemented for that in the build scripts:

```
$ zeus install-race
```


# Unit Tests

Netcap has tests for its core functionality

## Prerequisites

Some of the tests operate on a dump file that is not in the repository.

You can download it with:

```
$ zeus download-test-pcap
```

which will basically just invoke:

```
wget https://weberblog.net/wp-content/uploads/2020/02/The-Ultimate-PCAP.7z
```

Now unpack the file and move it to the tests folder in the project root.

## Unit Tests

Unit tests have been implemented for parts of the core functionality. Currently there are basic tests for reading pcap data from files and traffic live from an interface, as well as tests and benchmarks for common utility functions, such progress displaying and time conversions.&#x20;

The tests and benchmarks can be executed from the repository root by executing the following from the project root:

```
$ go test -v ./...
=== RUN   TestCountRecords
--- PASS: TestCountRecords (0.18s)
=== RUN   TestReader
--- PASS: TestReader (0.01s)
=== RUN   TestWriter
--- PASS: TestWriter (0.06s)
PASS
ok  	github.com/dreadl0ck/netcap	0.862s
?   	github.com/dreadl0ck/netcap/cmd	[no test files]
?   	github.com/dreadl0ck/netcap/cmd/agent	[no test files]
?   	github.com/dreadl0ck/netcap/cmd/capture	[no test files]
?   	github.com/dreadl0ck/netcap/cmd/collect	[no test files]
?   	github.com/dreadl0ck/netcap/cmd/dump	[no test files]
?   	github.com/dreadl0ck/netcap/cmd/export	[no test files]
?   	github.com/dreadl0ck/netcap/cmd/label	[no test files]
?   	github.com/dreadl0ck/netcap/cmd/proxy	[no test files]
?   	github.com/dreadl0ck/netcap/cmd/split	[no test files]
?   	github.com/dreadl0ck/netcap/cmd/transform	[no test files]
?   	github.com/dreadl0ck/netcap/cmd/util	[no test files]
=== RUN   TestCollectPCA
done in 2.595847118s
--- PASS: TestCollectPCAP (2.60s)
PASS
ok  	github.com/dreadl0ck/netcap/collector	3.242s
=== RUN   TestCorruptedWriter
    TestCorruptedWriter: delimited_test.go:46: Put record returned expected error: BAD
--- PASS: TestCorruptedWriter (0.00s)
=== RUN   TestGoodWriter
--- PASS: TestGoodWriter (0.00s)
=== RUN   TestCorruptedReader
    TestCorruptedReader: delimited_test.go:87: Next record returned expected error: unexpected EOF
--- PASS: TestCorruptedReader (0.00s)
=== RUN   TestGoodReader
--- PASS: TestGoodReader (0.00s)
=== RUN   TestRoundTrip
    TestRoundTrip: delimited_test.go:136: After writing: buffer="\x04Some\x02of\x04what\x01a\x04fool\x06thinks\x05often\bremains." len=42
--- PASS: TestRoundTrip (0.00s)
PASS
ok  	github.com/dreadl0ck/netcap/delimited	0.526s
?   	github.com/dreadl0ck/netcap/dpi	[no test files]
?   	github.com/dreadl0ck/netcap/encoder	[no test files]
?   	github.com/dreadl0ck/netcap/io	[no test files]
?   	github.com/dreadl0ck/netcap/label	[no test files]
?   	github.com/dreadl0ck/netcap/maltego	[no test files]
?   	github.com/dreadl0ck/netcap/metrics	[no test files]
?   	github.com/dreadl0ck/netcap/resolvers	[no test files]
=== RUN   TestMarshal
--- PASS: TestMarshal (0.00s)
PASS
ok  	github.com/dreadl0ck/netcap/types	0.668s
=== RUN   TestTimeToString
--- PASS: TestTimeToString (0.00s)
=== RUN   TestStringToTime
--- PASS: TestStringToTime (0.00s)
PASS
ok  	github.com/dreadl0ck/netcap/utils	0.932s
```

## Benchmarks

Run the benchmarks using:

```
$ go test -bench=. ./... | grep -E "Bench|pkg"
pkg: github.com/dreadl0ck/netcap/collector
BenchmarkReadPcapNG-12            	 1265539	       844 ns/op	    1249 B/op	       1 allocs/op
BenchmarkReadPcapNGZeroCopy-12    	 2028283	       640 ns/op	       0 B/op	       0 allocs/op
BenchmarkReadPcap-12              	 7557667	       137 ns/op	     106 B/op	       1 allocs/op
pkg: github.com/dreadl0ck/netcap/types
BenchmarkMarshal-12      	 9817819	       110 ns/op	      64 B/op	       1 allocs/op
BenchmarkUnmarshal-12    	 8703766	       134 ns/op	      40 B/op	       2 allocs/op
pkg: github.com/dreadl0ck/netcap/utils
BenchmarkTimeToStringOld-12           	 5283726	       229 ns/op	      64 B/op	       4 allocs/op
BenchmarkTimeToString-12              	 8273997	       136 ns/op	      80 B/op	       3 allocs/op
BenchmarkStringToTime-12              	 8842005	       137 ns/op	      32 B/op	       1 allocs/op
BenchmarkStringToTimeFieldsFunc-12    	 6809409	       185 ns/op	      32 B/op	       1 allocs/op
BenchmarkProgressOld-12               	54425902	        21.0 ns/op	       0 B/op	       0 allocs/op
BenchmarkProgress-12                  	23389420	        45.9 ns/op	      16 B/op	       2 allocs/op
```

## Race Detection Tests

Run the tests with race detection enabled:

```
$ go test -race -v ./...
```


# Extension

Implementing new audit records and features

To add support for a new protocol or custom abstraction the following steps need to be performed.&#x20;

## Protocol Buffer Definitions

First, a type definition of the new audit record type must be added to the AuditRecord protocol buffers definitions, as well as a **Type enumeration** following the naming convention with the **NC prefix**.&#x20;

First, make sure you have code generator plugin(s) that NETCAP is using to accelerate the protocol buffer en- and decoding. Get the plugins with:

```go
$ go get github.com/gogo/protobuf/...
```

The framework for this can be found here:

{% embed url="<https://github.com/gogo/protobuf>" %}

Recompile the protocol buffers with:

```go
$ zeus gen-proto-dev
```

This will create the type definitions for your new audit record in the **types** package.

## Encoder Implementation

After recompiling the protocol buffers, a file for the new encoder named after the protocol must be created in the encoder package. The new file must contain a variable created with **CreateLayerEncoder** or **CreateCustomEncoder** depending on the desired encoder type.&#x20;

Lets take a brief look at a very simple **LayerEncoder**, for example for the ARP protocol:

```go
package encoder

import (
   "github.com/dreadl0ck/gopacket"
   "github.com/dreadl0ck/gopacket/layers"
   "github.com/dreadl0ck/netcap/types"
   "github.com/golang/protobuf/proto"
)

var arpEncoder = CreateLayerEncoder(
   types.Type_NC_ARP, 
   layers.LayerTypeARP, 
   func(layer gopacket.Layer, timestamp string) proto.Message {
      if arp, ok := layer.(*layers.ARP); ok {
         return &types.ARP{
            Timestamp:       timestamp,
            AddrType:        int32(arp.AddrType),
            Protocol:        int32(arp.Protocol),
            HwAddressSize:   int32(arp.HwAddressSize),
            ProtAddressSize: int32(arp.ProtAddressSize),
            Operation:       int32(arp.Operation),
            SrcHwAddress:    arp.SourceHwAddress,
            SrcProtAddress:  arp.SourceProtAddress,
            DstHwAddress:    arp.DstHwAddress,
            DstProtAddress:  arp.DstProtAddress,
         }
      }
      return nil
   }
)
```

�Since **ARP** can be decoded by **gopacket** already, all we have to do is check if the packet has the **ARP** layer, and if yes, convert it to the **types.ARP** audit record and return it.

The constructor for a **LayerEncoder** needs the type enumeration for the new audit record, as well as the **gopacket.LayerType**, followed by the actual encoder function. This function will be called for every network packet.

As you can see, **LayerEncoders** are tied to **gopacket**. If you want to implement custom decoding logic or support for a new protocol, you essentially have two options:

* implement protocol decoding in **gopacket**, then use a **LayerEncoder** in netcap
* implement protocol decoding in a **CustomEncoder**

A **CustomEncoder** works the same way but offers more flexibility for the implementation, like functions for initialisation and teardown. The CustomEncoder constructor signature looks as follows:

```go
func CreateCustomEncoder(
    t types.Type, 
    name string, 
    postinit func(*CustomEncoder) error, 
    handler CustomEncoderHandler, 
    deinit func(*CustomEncoder) error
) *CustomEncoder
```

The **CustomEncoderHandler** will simply receive the raw **gopacket.Packet** and return a **proto.Message**:

```go
CustomEncoderHandler = func(p gopacket.Packet) proto.Message
```

Depending on the choice of the encoder type, the new variable must be added to the customEncoderSlice in **encoder/customEncoder.go** or layerEncoderSlice in **encoder/layerEncoder.go**.&#x20;

## Audit Record Interface Implementation

Next, the interface for conversion to CSV and JSON and exporting metrics must be implemented in the types package, by creating a new file with the protocol name and implementing the **types.AuditRecord** interface:

```go
// AuditRecord is the interface for basic operations with NETCAP audit records
// this includes dumping as CSV or JSON or prometheus metrics
// and provides access to the timestamp of the audit record
type AuditRecord interface {

   // returns CSV values
   CSVRecord() []string

   // returns CSV header fields
   CSVHeader() []string

   // used to retrieve the timestamp of the audit record for labeling
   Time() string

   // Src returns the source of an audit record
   // for Layer 2 records this shall be the MAC address
   // for Layer 3+ records this shall be the IP address
   Src() string

   // Dst returns the source of an audit record
   // for Layer 2 records this shall be the MAC address
   // for Layer 3+ records this shall be the IP address
   Dst() string

   // increments the metric for the audit record
   Inc()

   // returns the audit record as JSON
   JSON() (string, error)

   // can be implemented to set additional information for each audit record
   // important:
   //  - MUST be implemented on a pointer of an instance
   //  - the passed in packet context MUST be set on the Context field of the current audit record
   SetPacketContext(ctx *PacketContext)
}
```

If the new protocol contains sub-structures, functions to convert them to strings need to be implemented as well. Take a look at other encoders that have lots of substructures, for example **DNS**.

## Add Initializer

Finally, the **InitRecord(typ types.Type) (record proto.Message)** function in netcap.go needs to be updated, to initialize the structure for the new type.


# Downloads

A collection of cheatsheets and useful resources

## Releases

You can find the latest release on the releases page on GitHub:

{% embed url="<https://github.com/dreadl0ck/netcap/releases>" %}
NETCAP GitHub Releases Page
{% endembed %}

## Publications

In this paper, we explore Graph based analysis using Maltego to visualise data from NETCAP during a forensic investigation:

{% file src="/files/-M5lnlgF79aR3khnqCiy" %}
Behavorial Profiling From Network Packet Captures
{% endfile %}

### Thesis

{% file src="/files/-M5lnKCoA1AP7qKlW\_Zb" %}
Implementation and Evaluation of secure and scalable anomaly-based Network Intrusion Detection
{% endfile %}

### Thesis Presentation

{% file src="/files/-M0KJn1Kokg4BOxvWSjZ" %}

### SecurIT Cup 2018 Presentation

{% file src="/files/-M5ln9oeQgK7N1WcV6Rz" %}

## External Publications

The authors used the framework to process their recorded PCAP dumps:

{% embed url="<https://easychair.org/publications/preprint/36pZ>" %}

## Cheatsheets

### List of all supported protocols and fields

{% file src="/files/-M60zpQQtkygr86V87Bh" %}

### Command Cheatsheet

{% file src="/files/-M5loDsA\_HO6ISWg-Bis" %}




---

[Next Page](https://docs.netcap.io/llms-full.txt/1)

