Skip to content

How-To: Packet Shapes and a Classifier That Admits Ignorance

A ruleset that drops a UID's UDP to port 53 may still let through:

  • a fragment that carries no UDP header;
  • a datagram behind an IPv6 extension header;
  • a TCP segment with flags no handshake uses;
  • a protocol it never mentions.

Testing that takes three things, all opt-in:

  1. shape stimuli: those packets, built whole and sent through a raw socket by a process running as the identity under test;
  2. nse.classify(): it reads what a captured packet is, and says unparsed when it cannot tell;
  3. a positive control for each shape: proof that the shape was produced, captured and classified as itself, required before its absence can mean anything.

A worked example: does a port rule stop fragments?

import asyncio

from nse import PCAPAsserter, check_shape, shape_absent, stimuli
from nse.models.process import ProcessIdentity

USER = ProcessIdentity(uid=1000, gid=1000, capabilities={"net_raw"})
OTHER = ProcessIdentity(uid=1001, gid=1001, capabilities={"net_raw"})  # spared by the rules

async def send(sandbox, stimulus, identity):
    capture = PCAPAsserter(iface=sandbox.ext_iface, netns=sandbox.ext_netns)
    await capture.start()
    result = await stimulus.run(sandbox, identity=identity)
    await asyncio.sleep(0.3)
    packets = await capture.stop()
    return result, packets, await capture.stop_report()

shape = stimuli.fragments("198.51.100.7", 53, only="non_first")

# 1. The positive control: the shape leaves, and is read as itself.
result, packets, _ = await send(sandbox, shape, OTHER)
control = check_shape(result, packets).require()   # AssertionError if not

# 2. The claim: the same shape, as the identity the rules are about.
result, packets, report = await send(sandbox, shape, USER)
verdict = shape_absent(result, packets, control=control, capture=report)
assert verdict.absent is True, verdict.describe()

A rule written as meta skuid 1000 udp dport 53 drop fails this test. A fragment past the first holds no UDP header, so udp dport never matches it. NSE's own integration suite shows exactly that.


The shapes

Each one builds whole IP packets in the sending process and sends them through a raw socket (IPPROTO_RAW). The output hook therefore sees the packets as that process's, with its UID, GID and cgroup. The identity needs CAP_NET_RAW (capabilities={"net_raw"}), and the UID stays the one under test. Without the capability the result is could_not_run at socket: no packet was produced.

Constructor What it sends
fragments(host, port) A UDP datagram in two fragments: IPv4 fragment offsets, or an IPv6 Fragment header
fragments(..., overlapping=True) The second fragment rewrites the last 16 bytes of the first
fragments(..., only="first") Only the first fragment; only="non_first" sends only the other one
ipv6_extension_header(host, port, header) UDP behind hop_by_hop, destination_options (each with a PadN option) or routing (type 0, no segments left)
tcp_flags(host, port, flags) One TCP segment with exactly flags set, as letters of FSRPAUEC: "" (none), "FPU", "SF", ...
sctp(host, port) SCTP (132): a common header and a DATA chunk, with a valid CRC-32C
gre(host) GRE (47) with a bare header
ip_protocol(host, number) Any other protocol number, carrying just the probe ID

ip_protocol refuses the numbers that have a constructor of their own:

  • TCP, UDP, ICMP and ICMPv6;
  • the IPv6 extension headers, including AH, which a classifier would read as a header.

The source address is the one the kernel would choose for the destination. A shape is sent once: StimulusStream refuses one.

Every packet carries the probe ID, both fragments included. So requests_in() (and the controls below) find a shape's packets wherever they went and however they are cut. A packet that carries the ID back to the sender's own address is a reply, not a request. The first fragment is never smaller than the second, so a sender that reassembles and fragments again (a local conntrack) cuts the datagram the same way.


classify()

from nse import classify

shape = classify(packet)                 # a Scapy packet from a capture, or bytes
shape = classify(raw, link_type=101)     # bytes from a raw-IP capture

It returns a PacketClass:

Field What it holds
kind tcp, udp, icmp, icmpv6, sctp, gre, ip_protocol, arp, beacon, or unparsed
reason Why an unparsed frame could not be read
family, source, destination The IP version and addresses
protocol The upper-layer protocol number, after any IPv6 extension headers
extension_headers The IPv6 extension headers, in order (fragment included)
fragment first or non_first, with fragment_id, fragment_offset, fragment_length and more_fragments
source_port, destination_port For TCP, UDP and SCTP, unless the packet is a non-first fragment
tcp_flags, icmp_type, gre_protocol Where the packet holds them
vlan_ids 802.1Q and 802.1ad tags it read through

A non-first fragment has kind set to its protocol, but no ports and no flags, because its bytes are data. Scapy's dissection decodes them as a header; classify() reads the bytes itself and does not. fragments_overlap(classes) says whether fragments of one datagram cover the same bytes.

Unparsed means inconclusive

classify() returns kind="unparsed" with a reason for anything it cannot read:

  • a header cut by the snap length;
  • a malformed IPv4 or IPv6 header;
  • an extension chain that is cut, too long, or holds two fragment headers;
  • a first fragment too short for its transport header, the classic filter evasion;
  • an EtherType it does not decode, which could carry IP;
  • a link type it does not decode.

The fields read before the problem are still filled in.

A caller must treat unparsed as inconclusive, never as "not a leak". shape_absent() does so: a single unparsed packet anywhere in the capture makes the absence of every shape unproven. That packet could be the shape.

It decodes Ethernet (VLAN tags included), raw IP (link types 101, 228 and 229) and Linux cooked captures (113 and 276). By default the link type comes from a Scapy packet's first layer, and is Ethernet for bytes. With from_pcap, pass link_type=report.link_type.


The positive control, then the claim

check_shape(result, packets) checks the control: the shape sent where nothing blocks it. It returns a ShapeCheck whose classified is True only when:

  • the stimulus was sent;
  • its packets are in the capture;
  • none of them is unparsed;
  • they read as the shape: the right family, protocol, ports, flags and extension headers. Fragments must be a first and a non-first sharing one ID, overlapping exactly when asked for. Any other shape must not be fragmented.

Each failure is in problems. require() returns the check, or raises AssertionError with them.

shape_absent(result, packets, control=..., capture=...) returns a ShapeAbsence:

  • absent=False when the shape's packets are on the wire, in found. That is a finding even from a broken capture;
  • absent=True only when none is there, and all of these hold:
  • the control was classified;
  • the stimulus ran (sent or refused);
  • the capture is healthy with a complete window;
  • no captured packet is unparsed;
  • absent=None (inconclusive) otherwise, with the reasons in problems.

The control must be the same shape and family as the result, or shape_absent raises ValueError.


The broken instruments, and what they give

Broken instrument What says so
No CAP_NET_RAW could_not_run at socket: no packet produced, and no absence proven
A capture on the wrong interface the control is not classified, so absent is None
A shape the network rewrote (reassembled, refragmented, flags changed) the control is not classified, and problems names what differs
A cut or undecodable packet in the capture unparsed, so absent is None
A capture that dropped packets window_complete is not True, so absent is None