flowmask 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
flowmask/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """flowmask: replace client IP addresses in a text log and its capture, with one mapping."""
2
+
3
+ __version__ = "0.1.0"
flowmask/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from flowmask.cli import main
4
+
5
+ sys.exit(main())
flowmask/addresses.py ADDED
@@ -0,0 +1,302 @@
1
+ """Which addresses are clients, and the one mapping from real to dummy addresses.
2
+
3
+ A run builds the mapping in two steps. First every input is scanned and each
4
+ address seen is passed to ``Mapping.observe``, which remembers clients in order
5
+ of first appearance and every other address so that no dummy can equal one of
6
+ them. Then ``Mapping.assign`` hands out dummy addresses in that order.
7
+
8
+ Device names are kept in the same mapping, numbered in order of first
9
+ appearance; a name's dummy follows from its number and length (see names.py).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import ipaddress
15
+ import json
16
+ import os
17
+ from collections.abc import Iterable, Iterator
18
+ from dataclasses import dataclass, field
19
+ from pathlib import Path
20
+
21
+ from flowmask.names import NameMasker, acceptable, dummy_name
22
+
23
+ IPAddress = ipaddress.IPv4Address | ipaddress.IPv6Address
24
+ IPNetwork = ipaddress.IPv4Network | ipaddress.IPv6Network
25
+
26
+ # Private and local ranges: the default answer to "which addresses are clients".
27
+ DEFAULT_CLIENT_NETS = (
28
+ "10.0.0.0/8", # private (RFC 1918)
29
+ "172.16.0.0/12", # private (RFC 1918)
30
+ "192.168.0.0/16", # private (RFC 1918)
31
+ "100.64.0.0/10", # shared address space, carrier-grade NAT (RFC 6598)
32
+ "169.254.0.0/16", # link-local (RFC 3927)
33
+ "127.0.0.0/8", # loopback
34
+ "fc00::/7", # unique local (RFC 4193)
35
+ "fe80::/10", # link-local
36
+ "::1/128", # loopback
37
+ )
38
+
39
+ # Ranges reserved for documentation: where dummy addresses come from.
40
+ DOC_NETS_V4 = ("192.0.2.0/24", "198.51.100.0/24", "203.0.113.0/24") # RFC 5737
41
+ DOC_NETS_V6 = ("2001:db8::/32",) # RFC 3849
42
+
43
+ MAP_FORMAT = "flowmask-map"
44
+ MAP_VERSION = 2 # 2 added device names; version 1 files are still read
45
+ MAP_WARNING = "This file contains real client addresses and device names. Keep it private."
46
+
47
+
48
+ class MappingError(Exception):
49
+ """The mapping cannot be built. The message says why."""
50
+
51
+
52
+ def parse_net(text: str) -> IPNetwork:
53
+ try:
54
+ return ipaddress.ip_network(text.strip(), strict=False)
55
+ except ValueError:
56
+ raise MappingError(f"{text!r} is not an address range such as 10.0.0.0/8") from None
57
+
58
+
59
+ def _never_client(address: IPAddress) -> bool:
60
+ """Addresses that name no single device: never treated as a client."""
61
+ if address.is_multicast or address.is_unspecified:
62
+ return True
63
+ return address.version == 4 and address == ipaddress.IPv4Address("255.255.255.255")
64
+
65
+
66
+ def unmap(address: IPAddress) -> IPAddress:
67
+ """An IPv4-mapped IPv6 address (::ffff:a.b.c.d) is judged and mapped as a.b.c.d."""
68
+ if address.version == 6 and address.ipv4_mapped is not None:
69
+ return address.ipv4_mapped
70
+ return address
71
+
72
+
73
+ class Pool:
74
+ """Dummy addresses of one family, in order, skipping any that are taken."""
75
+
76
+ def __init__(self, nets: Iterable[IPNetwork]) -> None:
77
+ self.nets = list(nets)
78
+
79
+ def size(self) -> int:
80
+ return sum(self._usable(net) for net in self.nets)
81
+
82
+ @staticmethod
83
+ def _usable(net: IPNetwork) -> int:
84
+ count = net.num_addresses
85
+ if net.version == 4 and net.prefixlen < 31:
86
+ return count - 2 # no network or broadcast address
87
+ if net.version == 6 and net.prefixlen < 127:
88
+ return count - 1 # no subnet-router anycast address (all zeros)
89
+ return count
90
+
91
+ def addresses(self) -> Iterator[IPAddress]:
92
+ for net in self.nets:
93
+ first = int(net.network_address)
94
+ last = int(net.broadcast_address)
95
+ if net.version == 4 and net.prefixlen < 31:
96
+ first, last = first + 1, last - 1
97
+ elif net.version == 6 and net.prefixlen < 127:
98
+ first += 1
99
+ cls = ipaddress.IPv4Address if net.version == 4 else ipaddress.IPv6Address
100
+ for value in range(first, last + 1):
101
+ yield cls(value)
102
+
103
+
104
+ @dataclass
105
+ class Mapping:
106
+ """Clients, the addresses that are not clients, and real-to-dummy pairs."""
107
+
108
+ client_nets: list[IPNetwork] = field(
109
+ default_factory=lambda: [parse_net(n) for n in DEFAULT_CLIENT_NETS]
110
+ )
111
+ dummy_nets_v4: list[IPNetwork] = field(
112
+ default_factory=lambda: [parse_net(n) for n in DOC_NETS_V4]
113
+ )
114
+ dummy_nets_v6: list[IPNetwork] = field(
115
+ default_factory=lambda: [parse_net(n) for n in DOC_NETS_V6]
116
+ )
117
+ pairs: dict[IPAddress, IPAddress] = field(default_factory=dict)
118
+ clients: list[IPAddress] = field(default_factory=list) # first appearance order
119
+ loaded: int = 0 # pairs that came from --map-in
120
+ names: list[bytes] = field(default_factory=list) # device names, first appearance order
121
+ names_loaded: int = 0
122
+ names_skipped: set[bytes] = field(default_factory=set) # too short or generic
123
+ _name_keys: dict[bytes, int] = field(default_factory=dict) # lower-case name -> number
124
+ _client_set: set[IPAddress] = field(default_factory=set)
125
+ _others: set[IPAddress] = field(default_factory=set)
126
+
127
+ # Classification ----------------------------------------------------------
128
+
129
+ def is_client(self, address: IPAddress) -> bool:
130
+ address = unmap(address)
131
+ if _never_client(address):
132
+ return False
133
+ return any(address in net for net in self.client_nets if net.version == address.version)
134
+
135
+ # Scanning ----------------------------------------------------------------
136
+
137
+ def observe(self, address: IPAddress) -> None:
138
+ address = unmap(address)
139
+ if address in self._client_set or address in self._others:
140
+ return
141
+ if self.is_client(address):
142
+ self._client_set.add(address)
143
+ self.clients.append(address)
144
+ else:
145
+ self._others.add(address)
146
+
147
+ def observe_name(self, name: bytes | None, given: bool = False) -> None:
148
+ if name is None:
149
+ return
150
+ name = name.strip(b"\0 .")
151
+ if not name:
152
+ return
153
+ key = name.lower()
154
+ if key in self._name_keys:
155
+ return
156
+ if len(key) == 15 and any(k[:15] == key for k in self._name_keys if len(k) > 15):
157
+ return # the 15-character form NetBIOS cuts a known name to
158
+ if not acceptable(name, given):
159
+ self.names_skipped.add(key)
160
+ return
161
+ self.names.append(name)
162
+ self._name_keys[key] = len(self.names)
163
+
164
+ def name_masker(self) -> NameMasker:
165
+ return NameMasker((name, number) for number, name in enumerate(self.names, 1))
166
+
167
+ # Assigning ---------------------------------------------------------------
168
+
169
+ def assign(self) -> None:
170
+ """Give every client seen a dummy address, in order of first appearance."""
171
+ taken = set(self.pairs.values()) | self._others | self._client_set
172
+ for version, nets in ((4, self.dummy_nets_v4), (6, self.dummy_nets_v6)):
173
+ wanted = [c for c in self.clients if c.version == version and c not in self.pairs]
174
+ if not wanted:
175
+ continue
176
+ pool = Pool(nets)
177
+ free = pool.size() - self._overlap(nets)
178
+ free -= sum(
179
+ 1
180
+ for a in taken
181
+ if a.version == version and any(a in n for n in nets) and not self.is_client(a)
182
+ )
183
+ if len(wanted) > free:
184
+ ranges = ", ".join(str(n) for n in nets)
185
+ raise MappingError(
186
+ f"{len(wanted)} IPv{version} clients need dummy addresses, but only "
187
+ f"{max(free, 0)} are free in {ranges}. Give a larger range with --dummy-net."
188
+ )
189
+ addresses = pool.addresses()
190
+ for client in wanted:
191
+ for candidate in addresses:
192
+ if candidate not in taken and not self.is_client(candidate):
193
+ self.pairs[client] = candidate
194
+ taken.add(candidate)
195
+ break
196
+ else: # pragma: no cover - guarded by the count above
197
+ raise MappingError(f"ran out of IPv{version} dummy addresses")
198
+
199
+ def _overlap(self, nets: list[IPNetwork]) -> int:
200
+ """Usable pool addresses that lie in client ranges (and so are never handed out)."""
201
+ total = 0
202
+ for net in nets:
203
+ for client in self.client_nets:
204
+ if client.version != net.version:
205
+ continue
206
+ if net.subnet_of(client):
207
+ total += Pool._usable(net)
208
+ elif client.subnet_of(net):
209
+ total += client.num_addresses
210
+ return total
211
+
212
+ # Lookup ------------------------------------------------------------------
213
+
214
+ def dummy_for(self, address: IPAddress) -> IPAddress | None:
215
+ """The dummy for a client address, keeping the IPv4-mapped form; else None."""
216
+ inner = unmap(address)
217
+ dummy = self.pairs.get(inner)
218
+ if dummy is None:
219
+ return None
220
+ if inner is not address: # ::ffff:a.b.c.d stays IPv4-mapped
221
+ return ipaddress.IPv6Address(b"\0" * 10 + b"\xff\xff" + dummy.packed)
222
+ return dummy
223
+
224
+ def dummy_bytes(self, packed: bytes) -> bytes | None:
225
+ """Packed address in, packed dummy out (same length), or None."""
226
+ address: IPAddress
227
+ if len(packed) == 4:
228
+ address = ipaddress.IPv4Address(packed)
229
+ elif len(packed) == 16:
230
+ address = ipaddress.IPv6Address(packed)
231
+ else:
232
+ return None
233
+ dummy = self.dummy_for(address)
234
+ return None if dummy is None else dummy.packed
235
+
236
+ def label(self, address: IPAddress) -> str:
237
+ """How a client is named in reports: by its dummy, never by its real address."""
238
+ dummy = self.pairs.get(unmap(address))
239
+ return f"the client masked as {dummy}" if dummy else "an unmapped client"
240
+
241
+ # Map files ---------------------------------------------------------------
242
+
243
+ def load(self, path: Path) -> None:
244
+ try:
245
+ data = json.loads(path.read_text(encoding="utf-8"))
246
+ except OSError as error:
247
+ raise MappingError(f"cannot read {path}: {error.strerror}") from None
248
+ except ValueError:
249
+ raise MappingError(f"{path} is not a flowmask map file") from None
250
+ if not isinstance(data, dict) or data.get("format") != MAP_FORMAT:
251
+ raise MappingError(f"{path} is not a flowmask map file")
252
+ if data.get("version") not in (1, MAP_VERSION):
253
+ raise MappingError(f"{path} has map version {data.get('version')!r}; expected 2")
254
+ entries = data.get("map")
255
+ if not isinstance(entries, dict):
256
+ raise MappingError(f"{path} has no map")
257
+ used: set[IPAddress] = set()
258
+ for real_text, dummy_text in entries.items():
259
+ try:
260
+ real = unmap(ipaddress.ip_address(real_text))
261
+ dummy = ipaddress.ip_address(dummy_text)
262
+ except ValueError:
263
+ raise MappingError(f"{path}: an entry is not a pair of addresses") from None
264
+ if real.version != dummy.version:
265
+ raise MappingError(f"{path}: an entry maps IPv{real.version} to IPv{dummy.version}")
266
+ if dummy in used or self.is_client(dummy):
267
+ raise MappingError(f"{path}: dummy {dummy} is used twice or is itself a client")
268
+ used.add(dummy)
269
+ self.pairs[real] = dummy
270
+ self.loaded = len(self.pairs)
271
+ names = data.get("names", [])
272
+ if not isinstance(names, list) or not all(
273
+ isinstance(e, dict) and isinstance(e.get("name"), str) for e in names
274
+ ):
275
+ raise MappingError(f"{path}: the names list is not readable")
276
+ for entry in names: # in order: a name's number decides its dummy
277
+ self.observe_name(entry["name"].encode("utf-8", "surrogateescape"), given=True)
278
+ self.names_loaded = len(self.names)
279
+
280
+ def save(self, path: Path) -> None:
281
+ data = {
282
+ "format": MAP_FORMAT,
283
+ "version": MAP_VERSION,
284
+ "warning": MAP_WARNING,
285
+ "map": {str(real): str(dummy) for real, dummy in self.pairs.items()},
286
+ "names": [
287
+ {
288
+ "name": name.decode("utf-8", "surrogateescape"),
289
+ "dummy": dummy_name(number, len(name)),
290
+ }
291
+ for number, name in enumerate(self.names, 1)
292
+ ],
293
+ }
294
+ text = json.dumps(data, indent=2) + "\n"
295
+ try:
296
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
297
+ except FileExistsError:
298
+ raise MappingError(f"{path} already exists; flowmask does not overwrite") from None
299
+ except OSError as error:
300
+ raise MappingError(f"cannot create {path}: {error.strerror}") from None
301
+ with open(fd, "w", encoding="utf-8") as handle:
302
+ handle.write(text)
flowmask/captures.py ADDED
@@ -0,0 +1,382 @@
1
+ """Capture files, classic pcap and pcapng, read as chunks that are written back byte for byte.
2
+
3
+ A ``Chunk`` is a piece of the file: a header, a packet record or a pcapng
4
+ block. Each keeps its exact bytes. Packets are rewritten in place and every
5
+ address has the same size before and after, so no length, block size or
6
+ timestamp ever changes.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import ipaddress
12
+ import struct
13
+ import zlib
14
+ from collections import Counter
15
+ from collections.abc import Callable, Iterator
16
+ from dataclasses import dataclass, field
17
+ from pathlib import Path
18
+
19
+ from flowmask import names
20
+ from flowmask.addresses import Mapping
21
+ from flowmask.packets import (
22
+ LINKTYPE_ETHERNET,
23
+ Slot,
24
+ rewrite,
25
+ walk,
26
+ )
27
+
28
+ PCAP_MAGICS = {
29
+ b"\xd4\xc3\xb2\xa1": "<", # microseconds, little-endian
30
+ b"\x4d\x3c\xb2\xa1": "<", # nanoseconds, little-endian
31
+ b"\xa1\xb2\xc3\xd4": ">",
32
+ b"\xa1\xb2\x3c\x4d": ">",
33
+ }
34
+ PCAPNG_MAGIC = b"\x0a\x0d\x0d\x0a"
35
+ BLOCK_NAMES = {
36
+ 0x0A0D0D0A: "section header",
37
+ 1: "interface description",
38
+ 2: "packet (obsolete)",
39
+ 3: "simple packet",
40
+ 4: "name resolution",
41
+ 5: "interface statistics",
42
+ 6: "enhanced packet",
43
+ 10: "decryption secrets",
44
+ }
45
+
46
+
47
+ class CaptureError(Exception):
48
+ """A capture file cannot be read. The message says why."""
49
+
50
+
51
+ def detect(path: Path) -> str:
52
+ """'pcap', 'pcapng' or 'text', from the first bytes of the file."""
53
+ with open(path, "rb") as handle:
54
+ magic = handle.read(4)
55
+ if magic in PCAP_MAGICS:
56
+ return "pcap"
57
+ if magic == PCAPNG_MAGIC:
58
+ return "pcapng"
59
+ return "text"
60
+
61
+
62
+ @dataclass
63
+ class Chunk:
64
+ raw: bytearray
65
+ span: tuple[int, int] | None = None # the packet's bytes within raw
66
+ linktype: int = -1
67
+ fcs: int = 0 # bytes of frame check sequence at the end of the frame, if known
68
+ complete: bool = True # captured length equals the length on the wire
69
+ number: int = 0 # packet number, counted from 1
70
+ meta: list[Slot] = field(default_factory=list) # addresses in file metadata
71
+ label: str = ""
72
+ problem: str = ""
73
+
74
+
75
+ # Reading ------------------------------------------------------------------------
76
+
77
+
78
+ def chunks(path: Path) -> Iterator[Chunk]:
79
+ kind = detect(path)
80
+ with open(path, "rb") as handle:
81
+ if kind == "pcap":
82
+ yield from _pcap(handle)
83
+ elif kind == "pcapng":
84
+ yield from _pcapng(handle)
85
+ else:
86
+ raise CaptureError(f"{path} is not a capture file")
87
+
88
+
89
+ def _pcap(handle) -> Iterator[Chunk]:
90
+ header = handle.read(24)
91
+ if len(header) < 24:
92
+ raise CaptureError("the pcap file header is cut short")
93
+ endian = PCAP_MAGICS[header[:4]]
94
+ network = struct.unpack(endian + "I", header[20:24])[0]
95
+ linktype = network & 0xFFFF
96
+ fcs = ((network >> 28) & 0xF) * 2 if network & 0x04000000 else 0
97
+ yield Chunk(bytearray(header), label="pcap file header")
98
+ number = 0
99
+ while True:
100
+ record = handle.read(16)
101
+ if not record:
102
+ return
103
+ if len(record) < 16:
104
+ yield Chunk(
105
+ bytearray(record),
106
+ label="end of file",
107
+ problem="a record header is cut short at the end of the file",
108
+ )
109
+ return
110
+ caplen, wirelen = struct.unpack(endian + "II", record[8:16])
111
+ data = handle.read(caplen)
112
+ number += 1
113
+ problem = ""
114
+ if len(data) < caplen:
115
+ problem = f"packet {number} is cut short at the end of the file"
116
+ raw = bytearray(record + data)
117
+ yield Chunk(
118
+ raw,
119
+ (16, len(raw)),
120
+ linktype,
121
+ fcs,
122
+ caplen == wirelen and not problem,
123
+ number,
124
+ label=f"packet {number}",
125
+ problem=problem,
126
+ )
127
+ if problem:
128
+ return
129
+
130
+
131
+ def _options(raw, start: int, end: int, endian: str) -> Iterator[tuple[int, int, int]]:
132
+ """(code, value offset, value length) for each pcapng option in raw[start:end]."""
133
+ position = start
134
+ while position + 4 <= end:
135
+ code, length = struct.unpack(endian + "HH", raw[position : position + 4])
136
+ if code == 0:
137
+ return
138
+ value = position + 4
139
+ if value + length > end:
140
+ return
141
+ yield code, value, length
142
+ position = value + ((length + 3) & ~3)
143
+
144
+
145
+ def _pcapng(handle) -> Iterator[Chunk]:
146
+ endian = ""
147
+ interfaces: list[tuple[int, int, int]] = [] # (linktype, fcs bytes, snaplen)
148
+ number = 0
149
+ index = 0
150
+ while True:
151
+ head = handle.read(8)
152
+ if not head:
153
+ return
154
+ index += 1
155
+ if len(head) < 8:
156
+ yield Chunk(
157
+ bytearray(head),
158
+ label="end of file",
159
+ problem="a block is cut short at the end of the file",
160
+ )
161
+ return
162
+ if head[:4] == PCAPNG_MAGIC:
163
+ order = handle.read(4)
164
+ if order == b"\x4d\x3c\x2b\x1a":
165
+ endian = "<"
166
+ elif order == b"\x1a\x2b\x3c\x4d":
167
+ endian = ">"
168
+ else:
169
+ rest = handle.read()
170
+ yield Chunk(
171
+ bytearray(head + order + rest),
172
+ label=f"block {index}",
173
+ problem="a section header has an unknown byte order",
174
+ )
175
+ return
176
+ total = struct.unpack(endian + "I", head[4:8])[0]
177
+ rest = handle.read(max(0, total - 12))
178
+ raw = bytearray(head + order + rest)
179
+ interfaces = []
180
+ btype = 0x0A0D0D0A
181
+ else:
182
+ if not endian:
183
+ raise CaptureError("the pcapng file does not start with a section header")
184
+ btype, total = struct.unpack(endian + "II", head)
185
+ if total < 12 or total % 4:
186
+ rest = handle.read()
187
+ yield Chunk(
188
+ bytearray(head + rest),
189
+ label=f"block {index}",
190
+ problem=f"block {index} has an impossible length {total}",
191
+ )
192
+ return
193
+ rest = handle.read(total - 8)
194
+ raw = bytearray(head + rest)
195
+ name = BLOCK_NAMES.get(btype, f"type 0x{btype:08x}")
196
+ label = f"{name} block (block {index})"
197
+ if len(raw) < total:
198
+ yield Chunk(raw, label=label, problem=f"{label} is cut short at the end of the file")
199
+ return
200
+ end = total - 4 # before the trailing length
201
+ if btype == 1 and total >= 20:
202
+ linktype = struct.unpack(endian + "H", raw[8:10])[0]
203
+ snaplen = struct.unpack(endian + "I", raw[12:16])[0]
204
+ fcs = 0
205
+ meta = []
206
+ for code, value, length in _options(raw, 16, end, endian):
207
+ if code == 4 and length >= 8:
208
+ meta.append(Slot(value, 4, "interface IPv4 address option"))
209
+ elif code == 5 and length >= 17:
210
+ meta.append(Slot(value, 16, "interface IPv6 address option"))
211
+ elif code == 13 and length >= 1:
212
+ fcs = raw[value]
213
+ interfaces.append((linktype, fcs, snaplen))
214
+ yield Chunk(raw, linktype=linktype, meta=meta, label=label)
215
+ elif btype in (6, 2) and total >= 32:
216
+ if btype == 6:
217
+ interface = struct.unpack(endian + "I", raw[8:12])[0]
218
+ else:
219
+ interface = struct.unpack(endian + "H", raw[8:10])[0]
220
+ caplen, wirelen = struct.unpack(endian + "II", raw[20:28])
221
+ stop = 28 + min(caplen, end - 28)
222
+ number += 1
223
+ problem = ""
224
+ if interface >= len(interfaces):
225
+ problem = f"packet {number} names interface {interface}, which is not described"
226
+ linktype, fcs = -1, 0
227
+ else:
228
+ linktype, fcs, _ = interfaces[interface]
229
+ yield Chunk(
230
+ raw,
231
+ (28, stop),
232
+ linktype,
233
+ fcs,
234
+ caplen == wirelen,
235
+ number,
236
+ label=f"packet {number}",
237
+ problem=problem,
238
+ )
239
+ elif btype == 3 and total >= 16:
240
+ wirelen = struct.unpack(endian + "I", raw[8:12])[0]
241
+ linktype, fcs, snaplen = interfaces[0] if interfaces else (-1, 0, 0)
242
+ caplen = min(wirelen, end - 12, snaplen or wirelen)
243
+ number += 1
244
+ yield Chunk(
245
+ raw,
246
+ (12, 12 + caplen),
247
+ linktype,
248
+ fcs,
249
+ caplen == wirelen,
250
+ number,
251
+ label=f"packet {number}",
252
+ )
253
+ elif btype == 4:
254
+ meta = []
255
+ position = 8
256
+ while position + 4 <= end:
257
+ rtype, length = struct.unpack(endian + "HH", raw[position : position + 4])
258
+ value = position + 4
259
+ if rtype == 0:
260
+ position = value
261
+ break
262
+ if rtype == 1 and length >= 4:
263
+ meta.append(Slot(value, 4, "name resolution record (IPv4)"))
264
+ elif rtype == 2 and length >= 16:
265
+ meta.append(Slot(value, 16, "name resolution record (IPv6)"))
266
+ position = value + ((length + 3) & ~3)
267
+ for code, value, length in _options(raw, position, end, endian):
268
+ if code == 3 and length >= 4:
269
+ meta.append(Slot(value, 4, "name resolution DNS server option"))
270
+ elif code == 4 and length >= 16:
271
+ meta.append(Slot(value, 16, "name resolution DNS server option"))
272
+ yield Chunk(raw, meta=meta, label=label)
273
+ else:
274
+ yield Chunk(raw, label=label)
275
+
276
+
277
+ # Scanning and masking -----------------------------------------------------------
278
+
279
+
280
+ def _frame(chunk: Chunk) -> tuple[bytearray, bytes, bool]:
281
+ """The packet without its FCS, the FCS, and whether that FCS was correct."""
282
+ assert chunk.span is not None
283
+ data = bytearray(chunk.raw[chunk.span[0] : chunk.span[1]])
284
+ size = chunk.fcs
285
+ if chunk.linktype == LINKTYPE_ETHERNET and size == 4 and chunk.complete and len(data) > 4:
286
+ body, fcs = data[:-4], bytes(data[-4:])
287
+ return body, fcs, zlib.crc32(body).to_bytes(4, "little") == fcs
288
+ return data, b"", False
289
+
290
+
291
+ def scan(path: Path, mapping: Mapping, learn_names: bool = True) -> None:
292
+ for chunk in chunks(path):
293
+ for slot in chunk.meta:
294
+ _observe(chunk.raw, slot, mapping)
295
+ if chunk.span is not None:
296
+ body, _, _ = _frame(chunk)
297
+ layout = walk(body, chunk.linktype)
298
+ for slot in layout.slots:
299
+ _observe(body, slot, mapping)
300
+ if learn_names:
301
+ names.learn(body, layout, mapping.is_client, mapping.observe_name)
302
+
303
+
304
+ def _observe(buf, slot: Slot, mapping: Mapping) -> None:
305
+ packed = bytes(buf[slot.offset : slot.offset + slot.size])
306
+ if len(packed) == slot.size:
307
+ mapping.observe(ipaddress.ip_address(packed))
308
+
309
+
310
+ def replacer(mapping: Mapping) -> Callable[[bytes, int], bytes | None]:
311
+ """Packed address in, dummy bytes out. A cut-off address gets the dummy's first bytes."""
312
+
313
+ def replace(packed: bytes, size: int) -> bytes | None:
314
+ if len(packed) == size:
315
+ return mapping.dummy_bytes(packed)
316
+ for real, dummy in mapping.pairs.items():
317
+ if len(real.packed) == size and real.packed.startswith(packed):
318
+ return dummy.packed[: len(packed)]
319
+ return None
320
+
321
+ return replace
322
+
323
+
324
+ @dataclass
325
+ class CaptureStats:
326
+ packets: int = 0
327
+ packets_changed: int = 0
328
+ replaced: int = 0
329
+ partial: int = 0
330
+ sums_changed: int = 0
331
+ names: int = 0
332
+ fcs_fixed: int = 0
333
+ meta_replaced: int = 0
334
+ meta_names: int = 0
335
+ problems: list[str] = field(default_factory=list)
336
+ notes: Counter = field(default_factory=Counter)
337
+
338
+
339
+ def mask(source: Path, handle, mapping: Mapping, masker=None) -> CaptureStats:
340
+ """Write a masked copy of ``source`` to the open binary file ``handle``.
341
+
342
+ ``masker`` (a names.NameMasker) also replaces device names, in packets and
343
+ in pcapng metadata (options, name resolution records).
344
+ """
345
+ stats = CaptureStats()
346
+ replace = replacer(mapping)
347
+ pcapng = detect(source) == "pcapng"
348
+ for chunk in chunks(source):
349
+ if masker and pcapng and not chunk.problem and len(chunk.raw) >= 12:
350
+ if chunk.span is None:
351
+ stats.meta_names += masker.mask_bytes(chunk.raw, 8, len(chunk.raw) - 4)
352
+ else:
353
+ stats.meta_names += masker.mask_bytes(chunk.raw, chunk.span[1], len(chunk.raw) - 4)
354
+ if chunk.problem:
355
+ stats.problems.append(chunk.problem)
356
+ for slot in chunk.meta:
357
+ old = bytes(chunk.raw[slot.offset : slot.offset + slot.size])
358
+ new = replace(old, slot.size)
359
+ if new is not None:
360
+ chunk.raw[slot.offset : slot.offset + slot.size] = new
361
+ stats.meta_replaced += 1
362
+ if chunk.span is not None:
363
+ stats.packets += 1
364
+ body, fcs, fcs_ok = _frame(chunk)
365
+ layout = walk(body, chunk.linktype)
366
+ for note in layout.notes:
367
+ stats.notes[note] += 1
368
+ edits = masker.edits(body) if masker else ()
369
+ result = rewrite(body, layout, replace, edits)
370
+ if result.replaced or result.names:
371
+ stats.packets_changed += 1
372
+ stats.replaced += result.replaced
373
+ stats.names += result.names
374
+ stats.partial += result.partial
375
+ stats.sums_changed += result.sums_changed
376
+ if fcs_ok:
377
+ fcs = zlib.crc32(body).to_bytes(4, "little")
378
+ stats.fcs_fixed += 1
379
+ start, stop = chunk.span
380
+ chunk.raw[start:stop] = body + fcs
381
+ handle.write(chunk.raw)
382
+ return stats