Skip to content

nmap C→Rust (Windows) — Milestone 1: unprivileged TCP connect-scan MVP - #2

Merged
kj299 merged 4 commits into
masterfrom
claude/nmap-c2rust-windows-o7bghe
Jul 9, 2026
Merged

kj299 merged 4 commits into
masterfrom
claude/nmap-c2rust-windows-o7bghe

Conversation

@kj299

@kj299 kj299 commented Jul 9, 2026 •

Copy link
Copy Markdown
Owner

What this is

Milestone 1 (first slice) of the safety-first C→Rust rewrite of nmap (Windows), driven by the c2rust-port Porting Kit. Follows the merged M0 foundation (PR #1). Durable plan of record: nmap-rs/PLAN.md.

Scope target: unprivileged TCP connect scan (-sT) + host discovery + normal/grepable/XML output — no Npcap, no Administrator, no raw packets, ~0 unsafe. This PR lands Phase 0 + the first two core modules; the remaining modules and the differential/fuzz infra continue in the next PR.

Prime directive: the Rust must be safer than the C, not merely equivalent. No C source is modified; the C tree remains the differential oracle.

In this PR

Phase 0 (analysis):

Modules ported (#[forbid(unsafe_code)] core):

  • core::model — faithful port states / protocols / reasons / host+port structs; PortState::as_str matches statenum2str(), discriminants match the PORT_* defines; reason tokens verified against portreasons.cc.
  • core::targets — nmap's target-spec parser (octet ranges, wildcards, CIDR: 10.1.0-5.1-254, 192.168.0.*, 10.0.0.0/24), a direct port of parse_ipv4_ranges / split_netmask / the CIDR bit-mirror. Lazy expansion (a /0 counts as 2³² but never allocates); typed errors, never panics. Review fix: a /mask on a hostname/IPv6 is carried/rejected, not silently dropped.
  • core::ports · [ ] core::timing · [ ] sys::net · [ ] connect_scan · [ ] core::output · [ ] cli (next PR)

Gates: fmt + clippy(-D warnings) + 17 unit tests + unsafe-audit (0 undocumented) + miri + supply-chain, all green. Differential/fuzz gates self-skip until their shared M1 infra + the C-nmap oracle land (next PR).

🤖 Generated with Claude Code

claude added 4 commits July 9, 2026 06:18
Kick off Milestone 1 (unprivileged TCP connect-scan MVP) with the porting-kit
Phase 0 analysis. Writes no Rust; stops for approval on the port order.

- Fix c-flaw-scan harness to scan C++ (.cc/.cpp/...) sources, not just .c/.h.
  nmap's core engine is C++, so the scanner silently reported 0 flaws on 9.4k
  LOC — a scanner that reads nothing is worse than none (kit LESSONS #2/#3).
  Shared C_SOURCE_EXTS constant; self-test + make check-kit still green.
  Candidate LESSONS entry for the M1 retrospective.
- Re-run on the M1 modules: 9 hits (7 unbounded-copy, 2 non-literal format);
  raw output in nmap-rs/m1_cflaw.json.
- Seed nmap-rs/DIVERGENCES.md with the 3 M1-relevant fixes the port closes by
  construction (services path build, protocol strcpy, vfprintf format-string);
  defer 4 osscan-output sites to M5.
- Fill nmap-rs/THREAT-MODEL.md for M1 (untrusted: target/port spec, nmap-services,
  DNS; privilege: none; ~0 unsafe target for sys::net).
- Seed the module progress tracker (nmap-rs/progress.json), leaf-first order.
- Update PLAN.md status: M0 merged (16f8ea1); M1 Phase 0 done, awaiting approval.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JfEzHqD7a7TKDuUs5GwZ2w
…Port/Host)

First module of the Milestone 1 loop. Pure #![forbid(unsafe_code)] types, the
Rust analog of portlist.h/portreasons.h:
- PortState discriminants match the PORT_* defines; as_str() matches
  statenum2str() exactly (open/closed/filtered/...); unit-tested for fidelity.
- Protocol.as_str() matches proto2ascii_lowercase(); Reason tokens match the
  connect-scan subset of reason_codes.
- Port/Host/ScanResults own their data (String/Vec/enum), no raw ptr+len.
- Replace the skeleton key=value placeholder (model/parser); cli reduced to a
  stub until the cli module lands at the end of the loop.

Gates: fmt + clippy(-D warnings) + 5 unit tests green; unsafe-audit 0 undocumented.
progress: model -> ported.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JfEzHqD7a7TKDuUs5GwZ2w
Second M1 module. Rust port of nmap's NetBlock parsing (libnetutil/NetBlock.cc):
- parse_ipv4_ranges: octet ranges/wildcards/comma-lists (10.1.0-5.1-254,
  192.168.0.*), index-safe via b.get(); returns typed error, never panics.
- split_netmask: last-'/' split with a validated /bits mask.
- apply_ipv4_netmask: direct port of the chunk bit-mirror algorithm for CIDR.
- Lazy odometer iterator in nmap's octet order (octet 3 fastest); a /0 is
  counted as 2^32 but never materialized (threat-model: no unbounded alloc).
- IPv6 single-address + hostname classification (resolution deferred to sys).

Bounded index arithmetic uses scoped #[allow(arithmetic_side_effects)] with
justifications; the workspace lint stays active for input-derived size math.

Gates: fmt + clippy(-D warnings) + 10 unit tests (incl. never-panic property)
green; unsafe-audit 0 undocumented. progress: targets -> ported.
Fuzz target + differential vs C oracle wired next (shared M1 infra).

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JfEzHqD7a7TKDuUs5GwZ2w
…IPv6

Code review found a silent-divergence bug in parse_target: a /mask on a
hostname (example.com/24) or IPv6 literal (2001:db8::/64) was parsed by
split_netmask then discarded, so the target silently collapsed to a single
host instead of the intended block — exactly the "never silently diverge"
rule the kit forbids.

- Hostname now carries netmask_bits so sys::net can apply it after resolution
  (matches nmap's NetBlockHostname).
- A non-/128 IPv6 mask returns TargetParseError::Ipv6RangeUnsupported rather
  than silently scanning one address (M1 does not expand IPv6 ranges).
- Documented the pre-trimmed-token contract on parse_target.
- Added two regression tests; reason strings verified against portreasons.cc.

Gates: fmt + clippy(-D) + 17 tests + unsafe-audit 0 undocumented, all green.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JfEzHqD7a7TKDuUs5GwZ2w
@kj299
kj299 marked this pull request as ready for review July 9, 2026 07:14
@kj299
kj299 merged commit 2511c85 into master Jul 9, 2026
12 checks passed
kj299 added a commit that referenced this pull request Jul 10, 2026
The compounding step for Milestone 1 — patch PLAYBOOK/harnesses and append
LESSONS.md with what the nmap MVP taught the kit. Each edit names the failure it
prevents next time.

LESSONS #6 — scan_c_flaws read only .c/.h and reported nmap's ~9.4k LOC of C++
(.cc) as "0 flaws". Extension set widened to cover C++ (fix already in tree from
PR #2); now pinned with a self-test that iter_c_files yields .cc/.cpp/.hpp and
ignores non-source. Phase 0: confirm the scanner reads the target's languages
before believing a low count.

LESSONS #7 — diff_run.py is case-granular, so an MVP that intentionally renders a
subset of C output can't be diffed raw (every case diverges) or ledgered (the
whole case goes blind). Documented the canonical-projection pattern: wrap both
sides in a filter that emits only the semantic result, canonicalizing both
representations so real regressions still break the match. Phase 4 gate 2.

LESSONS #8 — Miri can't execute real I/O (tokio connect aborts under Miri).
Split the pure decision (verdict) from the syscall and cfg(miri)-ignore the I/O
tests, so "Miri can't run this" never becomes "no Miri coverage." Phase 4 gate 4.

LESSONS #9 — the linear six-gate model implies every module needs a fuzz tick,
but fuzzing is threat-model-scoped (parsers, not renderers/models). And
`cargo fuzz run <t> seeds/<t>` writes discovered inputs back into the seeds dir.
gen_fuzz_target.sh guidance now shows corpus/<t> seeds/<t> (writable, read-only)
and scopes the gate. Phase 4 gate 3.

Meta: 3 of 4 are the same shape as winlsof #2-#4 — a control that inspects less
than its green checkmark implies; the defense (retrospective step 0: run every
harness against the real target and eyeball what it inspected) held again.

check-kit: all harness self-tests + skills integrity green.


Claude-Session: https://claude.ai/code/session_01JfEzHqD7a7TKDuUs5GwZ2w

Co-authored-by: Claude <[email protected]>
kj299 added a commit that referenced this pull request Jul 25, 2026
Backlog #2, first sub-slice: scan a whole host group concurrently through ONE
shared capture instead of one host at a time. Ports nmap's ultra_scan host-group
model.

sys::group (0 unsafe): a generic group engine —
- RawScanKind trait factors the scan-type-specific bits (build_probe, match_reply,
  no-response default, BPF filter, protocol) so SYN/UDP/flag share one loop instead
  of near-identical per-host copies (also starts paying down the DRY-the-matchers
  follow-up).
- group_scan drives a per-host HostScheduler + a GroupScheduler bounding total probes
  in flight; one AsyncCapture feeds all hosts, and each reply is demultiplexed to its
  host by SOURCE IP (SynReply now carries src_ip). Every host shares one encoded
  source-port range because the source address disambiguates them.
- group_scan_targets buckets targets by egress route and runs one shared-capture
  group per route.
- SynKind is the first RawScanKind impl; syn_scan_targets now delegates to it.

core: SynReply gains src_ip (read from the reply's IPv4 source); match_syn_response
fills it. Miri-clean.

Verified as root: a two-host loopback group scan demultiplexes correctly (group_e2e),
and the CLI `nmap-rs -sS -Pn -p P1,P2 127.0.0.1 127.0.0.2` reports each host's own
port open and the other's closed — concurrent, one capture, routed by src IP.

Gates: clippy (default + all-features) + fmt on pinned 1.97.0; miri clean;
unsafe-audit 11/11 (no new unsafe); full suite green. Divergences ledgered
(group-scan-shared-capture-demux-by-src, group-scan-per-route-bucketing).
progress.json 34/43 DONE.

Next sub-slices of #2: migrate -sU + flag scans onto this engine (retiring their
per-target loops, DRYing the matchers); then UDP payloads; then SYN/flag ICMP back-fill.


Claude-Session: https://claude.ai/code/session_01JfEzHqD7a7TKDuUs5GwZ2w

Co-authored-by: Claude <[email protected]>
kj299 added a commit that referenced this pull request Jul 25, 2026
* M4 — migrate -sU and the six flag scans onto the group scan engine

Backlog #2, second sub-slice. Every raw scan now runs on the single
multi-host engine introduced for -sS, and the three near-identical
single-host drivers it subsumes are deleted rather than left beside it.

sys::group
  - UdpKind (-sU) and FlagKind (-sA/-sW/-sM/-sF/-sN/-sX) implement
    RawScanKind, joining SynKind. UdpKind's BPF also admits ICMP (an
    error is addressed to our source address, carrying no port of ours);
    its no-response default is open|filtered rather than filtered.
  - The retired drivers' unit tests are ported onto the engine, plus new
    multi-host demux tests for both scan families.

core::udpscan — the matcher is now a pure function of the frame
  - UdpReply gains src_ip: the sender for a direct datagram, or the
    destination of the quoted probe for an ICMP error. UdpMatchCtx.target
    is gone; from_target becomes "the ICMP sender is the host the quoted
    probe was addressed to", computed from the packet alone.
  - This is what lets one matcher serve a whole host group, and it is
    stricter than the C: a host that quotes a probe we sent to a
    different host can no longer have its error counted as an
    authoritative "closed" for that other host. Ledgered as
    udpscan-icmp-attributed-to-quoted-destination.

core::flagscan — FlagReply gains src_ip (the reply's IPv4 source).

sys::{synscan,udpscan,flagscan} shrink to thin entry points that pick the
per-scan keys and delegate to group_scan_targets; the CLI is unchanged.

Gates: fmt + clippy (default and all-features) on pinned 1.97.0; 310 core
tests; miri clean; unsafe-audit 11/11 documented, 0 undocumented (no new
unsafe); cargo deny clean; fuzz smoke match_udp 7.5M / match_flag 2.6M /
match_syn 7.7M runs, no crashes. Privileged as root: all four e2e suites
pass, including the on-the-wire differential gates for SYN, UDP and flag
probes, now exercising the group engine directly. Live multi-host CLI runs
verified for -sU and -sA against 127.0.0.1 + 127.0.0.2.

Ledger: three single-host-first-slice divergences resolved; new entry
group-scan-one-engine-for-every-raw-scan.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JfEzHqD7a7TKDuUs5GwZ2w

* Gate the scan-façade imports on the pcap feature

The three entry-point modules only use IpAddr/TimingTemplate/ScanType
inside their #[cfg(feature = "pcap")] functions, so a default-feature
build saw them as unused imports and CI's -D warnings rejected it.

Caught by CI, not locally: I had linted only --all-features, which turns
pcap on. Both configurations are now verified.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JfEzHqD7a7TKDuUs5GwZ2w

* Note the both-feature-configs lint lesson in the backlog

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JfEzHqD7a7TKDuUs5GwZ2w

---------

Co-authored-by: Claude <[email protected]>
kj299 added a commit that referenced this pull request Jul 25, 2026
Backlog #2: a bare UDP probe only elicits a reply from a service that
answers anything, so most open UDP ports read open|filtered. nmap sends a
protocol-specific payload on well-known ports; this ports that.

The finding that shaped the design: nmap has no payload data file. Modern
payload.cc DERIVES the table from nmap-service-probes — every `Probe UDP`
line not flagged `no-payload` contributes its probe string to each port in
its `ports` directive (probablePorts, not sslports). core::probedb already
parses all of that, including the no-payload flag, so core::payload is a
pure index over data we already parse and fuzz: no new file format, no new
untrusted-input parser.

core::payload
  - from_probe_db mirrors init_payloads(); count/for_port/get reproduce
    udp_payload_count and udp_port2payload (including its index wrap).
  - probe_payloads gives the datagrams for one logical probe — the C's
    MAX(numpayloads, 1) loop.

sys::group
  - RawScanKind::build_probe becomes build_probes -> Vec<Vec<u8>>: a UDP
    probe sends one datagram per registered payload, all from the same
    encoded source port. SYN and flag kinds return a single packet.
  - Because the datagrams share a source port, a reply cannot be tied to a
    particular payload (the C says so too), so the engine keeps one
    outstanding entry per (port, tryno) and matches by port.
  - A payload that cannot be built is skipped rather than suppressing its
    siblings; the probe fails only if nothing could be built.

core::udpscan: build_udp_probe_with takes an explicit payload;
build_udp_probe keeps the bare datagram.

cli: loads the table via the existing nmap-service-probes loader and
degrades to bare datagrams with a notice when it is absent. C nmap fatal()s
there, failing the whole scan over an optional data file.

Verification
  - payload_corpus.rs: over the real 2.5 MB file our table agrees with an
    independent derivation on all 33205 (port, payload) pairs across 33110
    ports, max 4 per port, plus per-port counts and byte-level anchors for
    53/111/123/137/161/500/1900/5353 (DNS header, ASN.1 SEQUENCE on SNMP,
    SSDP M-SEARCH).
  - Unit tests that both payloads for a port reach the wire, and that the
    bare kind attaches nothing.
  - On-the-wire differential extended to payload-carrying datagrams,
    including an odd-length payload (checksum padding path).
  - Live: a responder answering only well-formed queries reads `open` on
    port 53 (all three DNS payloads delivered) and `open|filtered` on 5399
    where no payload is registered — the payload is the whole difference.

Gates: fmt + clippy (default and all-features) on 1.97.0; 318 core tests;
miri clean; unsafe-audit 11/11 documented, 0 undocumented; cargo deny clean;
fuzz services_probes_parse extended to cover the derivation, 356k runs no
crashes; all four privileged e2e suites pass as root.

Ledger: udpscan-empty-payload resolved; new payload-cap-warns-not-fatal
(truncate + report instead of the C's fatal), payload-missing-db-degrades,
payload-one-datagram-per-payload.


Claude-Session: https://claude.ai/code/session_01JfEzHqD7a7TKDuUs5GwZ2w

Co-authored-by: Claude <[email protected]>
kj299 added a commit that referenced this pull request Jul 25, 2026
Backlog #2's last sub-slice. An ICMP destination-unreachable (type 3) or
time-exceeded (type 11) quotes the packet that provoked it, so it can be
matched back to the probe it answers. The UDP scan used this from the
start; core::icmp_quote generalizes the quote parser to TCP and shares it
with -sS and all six flag scans.

This matters most for -sF/-sN/-sX/-sM, whose no-response default is
open|filtered: without ICMP matching those scans could never report a port
as filtered at all.

core::icmp_quote (new)
  - parse_icmp_error yields the three addresses that are NOT interchangeable:
    the sender (may be a router), the quoted source (must be us), and the
    quoted destination (the host the verdict belongs to). from_target is
    then just sender == quoted_dst.
  - icmp_to_reason ports portreasons.cc, including that codes 9/10/13 are
    three distinct reasons in nmap, not one "admin-prohibited".
  - Also now the single home of ipv4_offset, which all three matchers had
    their own copy of — closing the "DRY the scan matchers" follow-up.

core::synscan
  - match_tcp_icmp_error, shared with the flag scans since the quote rules
    are identical. The quote contains our original packet, so unlike a RST
    (which reflects no sequence of ours) the encoded sequence IS present and
    is verified, as the C compares th_seq to probe->tcpseq().
  - SynReply/FlagReply/UdpReply now carry the reason they matched on, so a
    filtered port reports the specific code rather than "no-response".

sys::group
  - MatchParams groups the per-scan match constants and carries our source
    address; the SYN and flag BPF filters now also admit ICMP, without which
    the errors never reach the matcher.

Two findings from reading the C, one of which corrects this port:

1. The #55 ledger claimed attributing an ICMP error to the quoted
   destination was "stricter than the C". That was wrong: the C does the
   same (findHost(&encaps_hdr.dst), then from_target against the outer
   source). Corrected in DIVERGENCES.md — it is a structural note, not a
   hardening. The ledger ships as release notes, so accuracy matters.

2. A real gap in our own UDP path: the C requires the quoted packet's
   source to be our address ("If it didn't come from us, we don't care")
   and we never checked it. All three scans now enforce it, which is why
   every match context carries our_ip.

Gates: fmt + clippy (default and all-features) on 1.97.0; 335 core tests;
miri clean; unsafe-audit 11/11 documented, 0 undocumented; fuzz match_syn
5.0M / match_udp 5.7M / match_flag 1.8M / services_probes_parse 290k runs,
no crashes; all four privileged e2e suites pass as root.

Ledger: synscan-icmp-match-deferred and flagscan-icmp-match-deferred
resolved; udpscan-icmp-attributed-to-quoted-destination corrected; new
icmp-quote-requires-our-source, icmp-quote-verifies-our-sequence,
icmp-reason-fidelity, icmp-bpf-widened-for-tcp-scans.


Claude-Session: https://claude.ai/code/session_01JfEzHqD7a7TKDuUs5GwZ2w

Co-authored-by: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants