Repository navigation
Expand file tree
/
Copy pathprobe.c
More file actions
1351 lines (1245 loc) · 60.1 KB
/
Copy pathprobe.c
File metadata and controls
1351 lines (1245 loc) · 60.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifdef WITH_PCAP
#include <stdio.h>
#include <stdlib.h> /* malloc/free for the #92 dispatch seam */
#include <string.h>
#include <stdint.h>
#include <time.h>
#include <pthread.h>
#include <pcap.h>
#include "sloth.h"
#include "capture/probe.h"
#include "capture/capture.h" /* capture_classify_exit / stats accounting (#91) */
#include "sensor_health.h" /* probe-client eviction tally (#91) */
#include "evidence_ring.h" /* bounded raw-frame evidence ring (#92) */
#include "dot11_frame.h" /* one decode per frame (#122) */
#include "capture/frame_edge.h" /* the pcap-edge gate (#141) */
#include "dot11_ie.h" /* dot11_ie_ssid (#127) */
#include "radiotap.h"
#include "df.h" /* radio 0 of the direction-finding table */
#include "mon_radios.h" /* several sensor radios: de-duplication */
#include "radio_noise.h"
#include "capture/probe_internal.h"
#include "rf_quality.h"
#include "rf_distance.h"
#include "beacon_snoop.h"
#include "deauth_snoop.h"
#include "flood_window.h"
#include "sloth_clock.h"
#include "probe_pnl.h"
#include "karma_detect.h" /* directed probe-response forgery (#187 S2) */
#include "probe_latency.h" /* probe-response latency, observation only (#187 S3) */
#include "eapol_log.h"
#include "cov_interval_capture.h" /* frame classes (#242 item 2) */
#include "fragattack.h"
#include "pm_forge.h"
#include "queue_evict.h"
#include "seqnum_track.h"
#include "assoc_track.h"
#include "auth_track.h"
#include "action_snoop.h"
#include "worker_thread.h" /* signal-blocked worker creation (#95) */
#include "ctrl_frames.h"
#include "mle.h"
#include "ble_hci.h" /* raw HCI device refusal (#144 slice 2) */
#ifdef PLATFORM_LINUX
# include <dirent.h>
# include <limits.h> /* PATH_MAX for the sysfs seam */
# include <sys/stat.h>
#endif
/* ── Internal client table ───────────────────────────────── */
static probe_client_t g_clients[MAX_PROBE_CLIENTS];
static int g_count = 0;
static pthread_mutex_t g_mu = PTHREAD_MUTEX_INITIALIZER;
/* ── Raw 802.11 frame ring (monitor packets band) ────────── */
static mon_frame_t g_frames[MAX_MON_FRAMES];
static int g_frame_head;
static int g_frame_count;
static uint64_t g_frame_total; /* cumulative frames ever seen (#28 sensor) */
static uint64_t g_bad_clock_total; /* capture ts <= 0 (#92) */
static uint64_t g_radiotap_rejects; /* radiotap_parse() refused (#123) */
/* Per-stream freshness (#91), under g_frame_mu like the frame tally. */
static time_t g_last_frame_ts; /* the frame's own clock */
static time_t g_last_frame_wall; /* host clock at arrival, 0 = never */
static pthread_mutex_t g_frame_mu = PTHREAD_MUTEX_INITIALIZER;
/* Frames by coverage class (#242 item 2), lifetime, under g_frame_mu
* with the tally they partition: mon_frame_record() takes the lock
* already, so the count costs an increment and no lock of its own.
* Radio 0's newest frequency beside them, for a radio that is not
* retuned (the coverage record's channel for it). */
static uint64_t g_frame_class[COV_FC_N];
static int g_radio0_freq;
uint64_t mon_bad_clock_total(void) {
pthread_mutex_lock(&g_frame_mu);
uint64_t t = g_bad_clock_total;
pthread_mutex_unlock(&g_frame_mu);
return t;
}
uint64_t mon_radiotap_reject_total(void) {
pthread_mutex_lock(&g_frame_mu);
uint64_t t = g_radiotap_rejects;
pthread_mutex_unlock(&g_frame_mu);
return t;
}
void mon_frame_class_totals(uint64_t out[COV_FC_N]) {
if (!out) return;
pthread_mutex_lock(&g_frame_mu);
memcpy(out, g_frame_class, sizeof(g_frame_class));
pthread_mutex_unlock(&g_frame_mu);
}
int mon_radio0_freq_mhz(void) {
pthread_mutex_lock(&g_frame_mu);
int f = g_radio0_freq;
pthread_mutex_unlock(&g_frame_mu);
return f;
}
void mon_radio0_freq_reset(void) {
pthread_mutex_lock(&g_frame_mu);
g_radio0_freq = 0;
pthread_mutex_unlock(&g_frame_mu);
}
uint64_t mon_frame_total(void) {
pthread_mutex_lock(&g_frame_mu);
uint64_t t = g_frame_total;
pthread_mutex_unlock(&g_frame_mu);
return t;
}
/* Human subtype label for a frame's (type, subtype). */
static const char *frame_label(uint8_t type, uint8_t sub) {
if (type == 0) { /* management */
switch (sub) {
case 0: return "AssocReq"; case 1: return "AssocRsp";
case 2: return "ReassoReq"; case 3: return "ReassoRsp";
case 4: return "ProbeReq"; case 5: return "ProbeRsp";
case 8: return "Beacon"; case 10: return "Disassoc";
case 11: return "Auth"; case 12: return "Deauth";
case 13: return "Action"; default: return "Mgmt";
}
}
if (type == 1) { /* control */
switch (sub) {
case 9: return "BlockAck"; case 11: return "RTS";
case 12: return "CTS"; case 13: return "ACK";
default: return "Ctrl";
}
}
if (type == 2) return (sub & 0x08) ? "QoSData" : "Data";
return "Ext";
}
/* Record one captured 802.11 frame (called under no lock from the pcap
* thread). a1/a2 may be NULL for short frames. */
static void mon_frame_record(uint8_t type, uint8_t sub,
const uint8_t *a1, const uint8_t *a2,
uint16_t len, int8_t signal, time_t ts,
int cov_class) {
pthread_mutex_lock(&g_frame_mu);
if (cov_class >= 0 && cov_class < COV_FC_N) g_frame_class[cov_class]++;
mon_frame_t *f = &g_frames[g_frame_head];
f->ts = ts;
f->signal_dbm = signal;
f->len = len;
f->type = type;
f->subtype = sub;
if (a1) memcpy(f->addr1, a1, 6); else memset(f->addr1, 0, 6);
if (a2) memcpy(f->addr2, a2, 6); else memset(f->addr2, 0, 6);
snprintf(f->label, sizeof(f->label), "%s", frame_label(type, sub));
g_frame_head = (g_frame_head + 1) % MAX_MON_FRAMES;
if (g_frame_count < MAX_MON_FRAMES) g_frame_count++;
g_frame_total++;
pthread_mutex_unlock(&g_frame_mu);
}
void mon_frame_snapshot(sloth_state_t *s) {
pthread_mutex_lock(&g_frame_mu);
int n = g_frame_count;
for (int i = 0; i < n; i++) { /* newest first */
int idx = (g_frame_head - 1 - i + MAX_MON_FRAMES) % MAX_MON_FRAMES;
s->mon_frames[i] = g_frames[idx];
}
s->mon_frame_count = n;
pthread_mutex_unlock(&g_frame_mu);
}
/* ── Thread state ────────────────────────────────────────── */
static capture_run_flag_t g_running = CAPTURE_RUN_FLAG_INIT; /* #95 */
static pthread_t g_thread;
static pcap_t *g_ph = NULL;
static sloth_state_t *g_state = NULL;
/* ── Monitor interface discovery ─────────────────────────── */
/* --monitor-iface NAME: the operator's declaration of which radio is
* the sensor. Without it, find_monitor_iface() takes the first type-803
* netdev in readdir order, which is not a stable order and on a host
* with a second radio in monitor mode (a bench attacker beside the
* sensor) may be the wrong one. File-static, not a sloth_state_t field:
* that struct sits within a few hundred bytes of the test stack limit,
* and nothing but this file reads it.
*
* This is NOT the --iface allow-list. The owner ruled on 2026-10-04
* that the monitor stream stays outside --iface; this flag names the
* radio, it does not scope the IP stream, and an absent pin keeps the
* discovery behaviour unchanged. */
static char g_pin_iface[16];
/* Test seam: where the netdev type files are read from. A test points
* it at a temp tree so the selection logic runs with no radio. */
static const char *g_sysfs_net = "/sys/class/net";
void probe_set_monitor_pin(const char *name) {
snprintf(g_pin_iface, sizeof(g_pin_iface), "%s", name ? name : "");
}
const char *probe_monitor_pin(void) { return g_pin_iface; }
void probe_test_set_sysfs_net(const char *root) {
g_sysfs_net = root ? root : "/sys/class/net";
}
#ifdef PLATFORM_LINUX
/* ARPHRD_* of a netdev from <root>/<name>/type: the type, -1 when the
* netdev does not exist, -2 when it exists but the type is unreadable. */
int probe_iface_type(const char *name) {
char path[PATH_MAX];
/* %.15s: kernel names are under IFNAMSIZ, and every caller has
* already bounded the name. The precision restates that guard at
* the call site: at -O0 gcc cannot propagate a guard from the
* caller, and -Wformat-truncation fails the build — which is how
* the #95 capture-path target found the same pattern here before. */
int n = snprintf(path, sizeof(path), "%s/%.15s", g_sysfs_net, name);
if (n < 0 || (size_t)n >= sizeof(path)) return -1;
struct stat st;
if (stat(path, &st) != 0) return -1;
snprintf(path, sizeof(path), "%s/%.15s/type", g_sysfs_net, name);
FILE *f = fopen(path, "r");
if (!f) return -2;
int type = 0;
int ok = fscanf(f, "%d", &type) == 1;
fclose(f);
return ok ? type : -2;
}
static int find_monitor_iface(char *buf, int sz) {
DIR *d = opendir(g_sysfs_net);
if (!d) return 0;
struct dirent *e;
while ((e = readdir(d))) {
if (e->d_name[0] == '.') continue;
/* Linux iface names are IFNAMSIZ-1 = 15 chars max. Anything
* longer can't be a real interface and would also bust the
* snprintf buffers below. */
size_t nlen = strlen(e->d_name);
if (nlen >= 16) continue;
if (probe_iface_type(e->d_name) == 803) { /* ARPHRD_IEEE80211_RADIOTAP */
snprintf(buf, sz, "%s", e->d_name);
closedir(d);
return 1;
}
}
closedir(d);
return 0;
}
#else
int probe_iface_type(const char *name) { (void)name; return -1; }
static int find_monitor_iface(char *buf, int sz) { (void)buf; (void)sz; return 0; }
#endif
/* The radio probe_open() will open: the pin when one is set, and then
* only the pin — a pinned radio that is missing or not in monitor mode
* is an error, never a reason to go and find another, because the one
* found could be exactly the radio the operator pinned against. With
* no pin, discovery as before. 1 with buf set, or 0 with err set. */
static int select_monitor_iface(char *buf, int sz, char *err, size_t errsz) {
if (g_pin_iface[0]) {
int type = probe_iface_type(g_pin_iface);
if (type == -1) {
snprintf(err, errsz, "monitor iface %.15s not found", g_pin_iface);
return 0;
}
if (type == -2) {
snprintf(err, errsz, "monitor iface %.15s: type unreadable",
g_pin_iface);
return 0;
}
if (type != 803) {
snprintf(err, errsz,
"monitor iface %.15s is not in monitor mode (type %d)",
g_pin_iface, type);
return 0;
}
snprintf(buf, sz, "%s", g_pin_iface);
return 1;
}
if (!find_monitor_iface(buf, sz)) {
snprintf(err, errsz, "no monitor-mode iface found (need type 803)");
return 0;
}
return 1;
}
/* Radiotap decoding lives in src/radiotap.c so it can be unit-tested —
* this file is compiled only under WITH_PCAP and is not in the test
* build, so a parser living here had no coverage. See radiotap.h. */
/* ── Client table update (caller holds g_mu) ─────────────── */
/* Append an observation to a client's RSSI ring (#53). The ring is what
* lets presence_classify() tell a device that drove past from one that
* is sitting in the building — dwell alone cannot, because channel
* hopping makes a resident heard once look brief. Mirrors
* beacon_snoop's rssi_ring_push; the projection fields that one derives
* are AP-only and not needed here. */
static void client_rssi_push(probe_client_t *c, int8_t signal, time_t now,
wifi_band_t band) {
rssi_ring_t *r = &c->rssi_ring;
r->dbm[r->head] = signal;
r->ts [r->head] = now;
r->head = (r->head + 1) % RSSI_WIN_SAMPLES;
if (r->count < RSSI_WIN_SAMPLES) r->count++;
/* The distance data point. A probe request carries no TPC Report,
* Country element or anything else naming its power, so P_tx is
* always the assumed client default. The band is the radiotap
* frequency's (#149): a 6 GHz channel number read alone is a
* 2.4 or 5 GHz one, or nothing. */
rf_ctx_t ctx;
rf_ctx_assumed(&ctx, c->channel, band, RF_PTX_STA_ASSUMED);
rf_track_observe(&c->dist, signal, now, &ctx);
}
static void record_probe(const uint8_t *mac, const char *ssid,
int8_t signal, int channel, wifi_band_t band) {
time_t now = sloth_wall();
uint64_t now_ms = sloth_mono_ms();
/* find existing entry */
for (int i = 0; i < g_count; i++) {
if (memcmp(g_clients[i].mac, mac, 6) == 0) {
g_clients[i].signal_dbm = signal;
g_clients[i].channel = channel;
g_clients[i].last_seen = now;
g_clients[i].frame_count++;
client_rssi_push(&g_clients[i], signal, now, band);
probe_flood_note(&g_clients[i], now_ms, now);
if (ssid[0]) /* prefer named probe over wildcard */
snprintf(g_clients[i].ssid, sizeof(g_clients[i].ssid),
"%s", ssid);
return;
}
}
/* New entry. Append while there is room; evict the least recently
* seen only when there is not.
*
* The fullness test is on the count BEFORE the append, which is the
* fix for a boundary defect (#91): it used to read
* `if (g_count == MAX_PROBE_CLIENTS)` after `g_count++`, so the
* arrival that filled the last slot also ran the eviction scan over
* the slot it had just allocated. In a fresh table that slot is
* zeroed, so last_seen 0 made it the oldest and the scan chose it
* back — invisible. After an ageing pass it is not: probe_snapshot()
* compacts with `g_clients[i] = g_clients[--g_count]`, which leaves
* the vacated index holding a copy of a live entry, so the scan
* could prefer an older LIVE slot, overwrite that one, and leave
* the stale copy inside g_count — an aged-out client resurrected as
* current, with someone else's row destroyed to do it.
*
* Counting belongs here and not inside the scan for the same
* reason: an append is not an eviction, and a tally that said
* otherwise would report loss on a table that was merely filling. */
int full = (g_count == MAX_PROBE_CLIENTS);
int slot;
if (!full) {
slot = g_count++;
} else {
slot = 0;
time_t oldest_ts = g_clients[0].last_seen;
for (int i = 1; i < g_count; i++) {
if (g_clients[i].last_seen < oldest_ts) {
oldest_ts = g_clients[i].last_seen;
slot = i;
}
}
sh_evict_note(SH_EVICT_PROBE_CLIENT);
}
/* Full reset: the slot may be a recycled eviction, and a stale RSSI
* ring would attribute the previous device's trajectory to this
* one — a wrong presence verdict rather than a missing one. */
memset(&g_clients[slot], 0, sizeof(g_clients[slot]));
memcpy(g_clients[slot].mac, mac, 6);
snprintf(g_clients[slot].ssid, sizeof(g_clients[slot].ssid), "%s", ssid);
g_clients[slot].signal_dbm = signal;
g_clients[slot].channel = channel;
g_clients[slot].first_seen = now;
g_clients[slot].last_seen = now;
g_clients[slot].frame_count = 1;
client_rssi_push(&g_clients[slot], signal, now, band);
probe_flood_note(&g_clients[slot], now_ms, now);
}
/* ── pcap callback ───────────────────────────────────────── */
/* Which sensor radio a frame came from rides in pcap's `user` pointer:
* 0 (NULL) is the radio this file opens, 1.. are mon_radio.c's. */
static void on_radio_frame(int radio, const struct pcap_pkthdr *hdr,
const u_char *data) {
/* ── The pcap-edge gate (#141) ──────────────────────────────
*
* Before anything reads `data`: caplen bounded by our snaplen and
* checked against the wire length, the timestamp's microseconds in
* range. This callback used to cast hdr->caplen to int unchecked and
* read hdr->len separately for the FCS strip — safe only because
* libpcap caps a record and the kernel does not lie, which is an
* assumption about the producer rather than a check (CWE-1284).
* Everything below reads the view, never hdr. */
frame_view_t fv;
if (!frame_view_init(&fv, data, hdr->caplen, hdr->len,
(long)hdr->ts.tv_sec, (long)hdr->ts.tv_usec,
DLT_IEEE802_11_RADIO)) {
sh_parse_fault_note(SH_PF_FRAME_EDGE);
return;
}
/* ── One radiotap gate (#123) ────────────────────────────────
*
* radiotap_parse()'s verdict is the gate, the same one capture.c's
* DLT_IEEE802_11_RADIO arm applies. This callback used to read
* it_len itself, check only `it_len < caplen`, and discard the
* parser's return — so an it_len below the 8-octet fixed header
* (which the parser rejects) was accepted here, and the "802.11
* frame" began inside the radiotap present bitmap. Two monitor
* entry points, two definitions of a valid header.
*
* A refusal is counted, not just dropped: a radio delivering frames
* that all fail here looks exactly like a quiet one otherwise. The
* tally reaches the operator through probe_health_poll().
*
* Since #141 the gate is frame_view_radiotap(), which capture.c's
* DLT_IEEE802_11_RADIO arm calls too — one function, not two copies
* of the same rule. It also takes the FCS trailer off (#122) and
* applies the 802.11 minimum, both decided below. */
radiotap_info_t rt;
const uint8_t *dot11 = NULL;
int dot11_len = 0;
const frame_rt_verdict_t rtv = frame_view_radiotap(&fv, &rt,
&dot11, &dot11_len);
if (rtv == FRAME_RT_BAD) {
pthread_mutex_lock(&g_frame_mu);
if (g_radiotap_rejects < UINT64_MAX) g_radiotap_rejects++;
pthread_mutex_unlock(&g_frame_mu);
/* Also into the sensor-wide parse-fault tally (#126), which is
* what reaches a JSONL consumer; the per-stream count above
* stays the iface view's figure. */
sh_parse_fault_note(SH_PF_RADIOTAP_BAD);
return;
}
int8_t signal = rt.signal_dbm;
int channel = rt.channel;
/* Band from the radio's own frequency, never from a channel number
* alone (#149: 5 GHz and 6 GHz channel numbers overlap). */
const wifi_band_t band = radiotap_freq_to_band(rt.freq_mhz);
/* ── One clock for this frame (#92) ──────────────────────────
*
* Every observer below is stamped from the frame's own capture
* timestamp, not from the wall clock. Nine sites used to read the wall
* clock while eapol_observe_dot11() alone took hdr->ts, so one frame
* could be stamped two different seconds depending on scheduling,
* and a correlation window built from those stamps was not
* reproducible from the capture it came from. For an evidence tool
* that is the difference between a record and an anecdote.
*
* No fallback, deliberately. Substituting the wall clock for a
* timestamp that looks wrong would reintroduce exactly the
* non-reproducibility this removes — and "looks wrong" is not
* decidable: a capture replayed from another host legitimately
* carries clocks far from this one's. A frame is stamped with what
* the capture says, always.
*
* What IS tracked is how often that value is unusable: ts <= 0 is
* the epoch or before it, which no live kernel produces. The count
* is published so an operator can tell "quiet" from "this capture's
* clock is broken", the same distinction the #91 health fields
* exist to make. Nothing is substituted on the strength of it. */
const time_t fts = fv.ts_sec;
if (fts <= 0) {
pthread_mutex_lock(&g_frame_mu);
if (g_bad_clock_total < UINT64_MAX) g_bad_clock_total++;
pthread_mutex_unlock(&g_frame_mu);
}
/* 802.11 frame starts after radiotap. When radiotap says the FCS
* is present, its four octets are a trailer and not frame (#122):
* every parser below used to see them as four extra body bytes,
* which an IE walker reads as one more element. frame_view_radiotap()
* has already taken it off, against the original length, so a
* capture cut by snaplen strips only what it holds.
*
* Minimum framing to read the Frame Control + addr1 (RA): FC(2) +
* duration(2) + addr1(6) = FRAME_DOT11_MIN. Control frames like
* ACK/CTS are exactly this size. */
if (rtv != FRAME_RT_OK) {
/* Counted (#126): a radio delivering only runts reads as a quiet
* one otherwise. */
sh_parse_fault_note(SH_PF_DOT11_RUNT);
return;
}
/* ── One decode for this frame (#122, #130) ─────────────────
*
* Type, subtype, flags, header length, body offset and the address
* roles are read once here, and every observer below takes this
* view rather than the bytes. Until #130 each observer re-decoded
* the frame from (dot11, len), through the dot11_data wrappers or
* with its own Frame Control arithmetic — three styles, and the
* Protected decision made per file. Their (dot11, len) entry points
* remain as wrappers for the tests and fuzz harnesses; this
* callback calls none of them. tests/test_dot11_frame.c counts
* dot11_frame_decode() calls per dispatched frame and holds it at
* one. */
const dot11_rt_hints_t hints = { rt.fcs_present, rt.datapad, rt.bad_fcs };
dot11_frame_t fr;
const int full = dot11_frame_decode(dot11, dot11_len, &hints, &fr);
const uint8_t type = fr.type;
const uint8_t sub = fr.subtype;
/* The noise floor this radio reports, if its driver does
* (radio_noise.h). Ahead of the de-duplication below: it is this
* radio's figure whichever radio's copy is delivered. --replay comes
* this way too and feeds radio 0. */
radio_noise_frame(RADIO_NOISE_SENSOR, radio, &rt, sloth_mono_ms());
/* Direction finding (df.h): with a --df-iface radio beside this one,
* the level this radio heard the transmitter at is radio 0's
* reading. A frame that failed its FCS names nobody reliably. The
* host's clock, as the other radios' notes (df_radio.c). */
if (radio == 0 && df_active() && !rt.bad_fcs) {
uint8_t df_ta[6];
if (df_frame_ta(dot11, dot11_len, df_ta))
df_note(0, df_ta, signal, channel, sloth_wall());
}
/* Several sensor radios (mon_radios.h): a frame another radio has
* already delivered stops here, counted against this radio, before
* any counter, ring, parser or detector below can see it twice.
* After the direction-finding note on purpose: the level radio 0
* heard a transmitter at is radio 0's reading whichever radio's
* copy was delivered, and the other SENSOR radios are not in that
* table at all - under --hop they sit on other channels, where a
* level is not comparable with radio 0's. With one radio this call
* returns 1 and touches nothing. */
if (!mon_radio_frame(radio, dot11, dot11_len,
fts > 0 ? (int64_t)fts * 1000000 + (int64_t)fv.ts_usec : 0,
rt.freq_mhz))
return;
/* Per-channel RF quality (roadmap B3). The retry bit is Frame
* Control byte 1 bit 3; the FCS-failed flag came from radiotap.
* Counted for every frame type including control frames, because
* channel health is about the air, not about what the frame said —
* and a frame that failed its FCS is still evidence the channel is
* struggling even though its contents are untrustworthy. */
rf_quality_observe(channel, band, fr.retry ? 1 : 0, rt.bad_fcs, fts);
/* Probe-response latency (#187 S3). Shown every frame, ahead of the
* FCS gate, because it numbers dwells from the radio frequency of
* all of them; it pairs only good-FCS Probe Request / Response.
* TSFT when radiotap carries it, the pcap stamp otherwise. */
/* Radio 0's frames only: the module numbers dwells from the order
* frequencies change in and times a pair on one radio's TSFT, and
* neither means anything across radios on different channels with
* unrelated clocks. A pair another radio heard is not measured. */
if (radio == 0) {
const plat_clock_t pclk = { rt.freq_mhz, rt.has_tsft, rt.tsft_us,
(long)fv.ts_sec, (long)fv.ts_usec };
probe_latency_observe(&fr, &pclk);
}
/* Log every frame for the monitor packets band, before the per-type
* dispatch. The view hands out addr2 only where the frame has one —
* ACK/CTS carry addr1 only, so it is NULL there whatever follows. */
/* Its coverage class (#242) rides the same lock as the tally: one
* class per recorded frame, so the classes sum to the frames. A
* frame radiotap marked FCS-failed is counted as that, not by a
* type its damaged octets may misstate. */
mon_frame_record(type, sub, fr.a1, fr.a2,
(uint16_t)dot11_len, signal, fts,
cov_frame_class(&fr, rt.bad_fcs));
/* Freshness for this stream (#91). Recorded here, with the frame
* tally, so it counts exactly the frames that cleared the framing
* guards — a runt the callback refused is not evidence the radio is
* delivering anything usable.
*
* Two clocks on purpose: fts is the frame's own capture timestamp,
* sloth_wall() is when it reached us. Age has to come from the
* second, because an offline replay carries timestamps far from now
* and deriving staleness from the first would call a healthy stream
* dead. sloth_wall() rather than a libc read keeps it injectable and
* keeps this callback free of the wall-clock read #92 removed. */
/* Radio 0's alone: `monitor` in sensor_health is that radio's
* health, and another radio still delivering must not make a dead
* radio 0 read as fresh. The others' state is in mon_radios. */
if (radio == 0) {
pthread_mutex_lock(&g_frame_mu);
g_last_frame_ts = fts;
g_last_frame_wall = sloth_wall();
if (rt.freq_mhz > 0) g_radio0_freq = rt.freq_mhz;
pthread_mutex_unlock(&g_frame_mu);
}
/* Retain the whole frame for evidence (#92). `data`, not `dot11`:
* the radiotap header is part of the record — it carries the
* frequency, the FCS verdict and the signal an analyst needs to
* judge the frame, and the general packet ring's min(caplen, 64)
* often holds little else.
*
* Placed with mon_frame_record() and therefore BEHIND the framing
* guards above, not in front of them. A frame too short to parse
* cannot be cited by any alert, and admitting runts would let an
* attacker flush the whole evidence ring with 10-byte garbage —
* cheap for them, and it would evict the frames that actually
* triggered something.
*
* The event ID is kept: it is how a detector cites this frame. 0
* means nothing was retained (ring down, or an empty frame), and a
* citation of 0 is never stored.
*
* Stamped on the frame view so the observers that take `fr` read it
* from there (pm_forge, queue_evict, action_snoop's BTM and SA Query
* paths, the assoc-request flood window); the ones that take bare
* fields get it as an argument below — deauth_record() through
* df.event_id, beacon_record_ev(), auth_observe_ev() and
* queue_evict_note_session_change_ev(). */
/* The radio that brought it rides along (#246): a finding's
* corroboration is the count of radios its cited frames came from. */
const uint64_t ev = evidence_ring_note_radio(
fv.data, (uint32_t)fv.caplen, fv.origlen,
fts, (long)fv.ts_usec,
(uint16_t)(rt.freq_mhz > 0 && rt.freq_mhz <= 0xFFFF
? rt.freq_mhz : 0),
signal, radio);
fr.event_id = ev;
fr.band = (int)band;
/* A frame radiotap marked FCS-failed is retained as evidence above
* (mon_frame_record, the freshness clock, the evidence ring,
* rf_quality) but its content is not trustworthy enough to feed a
* content parser — a bit error can turn a real SSID into a handful
* of near-random octets that beacon_parse_frame() would record as a
* seen name (#178). #123 deferred this decision on purpose; this is
* it, resolved. */
if (fr.bad_fcs) {
sh_parse_fault_note(SH_PF_FCS_FAILED);
return;
}
if (type == 1) {
/* Control frames (#64). Dispatched *above* the 24-byte guard
* below: a CTS or ACK is 14 bytes and an RTS is 20, so every
* control frame there is would be dropped by a check written
* for management headers. Parsing lives in ctrl_frames.c
* because this file is absent from TEST_SRCS. */
ctrl_observe_frame(&fr, channel, fts);
return;
}
/* The detailed per-type parsers below assume a full management header. */
if (dot11_len < 24) return;
/* Data frames (type 2). eapol_observe_dot11 rejects anything that
* is not an EAPOL-Key frame internally, so the cost of
* unconditional dispatch is just the LLC SNAP check inside.
*
* frag_observe (#75) needs the *encrypted* ones too — the whole
* FragAttacks family is about frames on a protected network — so it
* runs on every data frame, before any payload check. */
if (type == 2) {
/* DATAPAD (#123). The data-frame observers below take a bare
* (dot11, len) frame and place the body at the MAC header's
* end, as the clause lays it out. A driver that sets
* RT_F_DATAPAD has inserted up to 3 alignment octets there, so
* every one of them read LLC/SNAP early — a 26-octet QoS header
* put the pad where "AA AA 03" should be — and an EAPOL
* handshake on such a driver was silently missed.
*
* The pad is taken out here, once, rather than taught to each
* observer: what they receive is then the frame that was on the
* air, which is also what the EAPOL collector writes verbatim
* into a DLT_IEEE802_11 handshake pcap, where pad octets would
* be misread by every tool that opens the file. The evidence
* ring above keeps the capture as delivered, pad included.
*
* Static, not automatic: this callback runs under g_dispatch_mu
* (one frame at a time, whichever radio's thread brought it),
* and a 64 KiB stack buffer per frame buys nothing.
*
* dot11_frame_depad() moves the view onto the copy rather than
* decoding the copy again (#130): the header is unchanged by
* dropping pad that follows it, so only the pointers move. With
* no pad, or no readable header, `fr` is left as decoded. */
static uint8_t depad[65536];
dot11_frame_depad(&fr, depad, sizeof depad, &fr);
/* Capture time, not processing time: the handshake pcap's
* record headers carry it (#92). */
eapol_observe_frame(&fr, signal, channel, fts, (long)fv.ts_usec);
frag_observe_frame(&fr, fts);
pm_forge_observe_frame(&fr, fts, (long)fv.ts_usec);
/* #107 shape B. Only counts against a (BSSID, STA) some session
* change already opened a window for, so the common case —
* every data frame on the air — costs one direction test. */
queue_evict_observe_downlink_frame(&fr, fts, (long)fv.ts_usec);
return;
}
if (type != 0) return; /* management frames only beyond this point */
/* Per-BSSID Multi-Link advertisement (#104 slice 6): Beacons and
* Probe Responses both, before either branch can return. */
if (sub == 8 || sub == 5) mle_bss_observe_frame(&fr, fts);
if (sub == 8) {
/* Beacon frame — passive AP discovery */
char ssid[33]; uint8_t bssid[6]; int channel; char enc[10]; uint16_t bms;
beacon_rsn_t rsn;
if (beacon_parse_frame(&fr, signal, ssid, bssid, &channel,
enc, &bms, &rsn)) {
beacon_record_ev(bssid, ssid, signal, channel, enc, bms, &rsn, ev);
/* A CSA in a beacon is broadcast to every associated client
* at once (#63). addr2 is passed separately from addr3 even
* though a beacon's are normally identical — a forged one
* is where they differ, and that is the whole signal. */
/* An AP's own Multi-Link Element (#67) — the AP-side MLD.
* The client side arrives via assoc_request_parse. */
int have_mld = 0;
sloth_mld_t mld;
if (rsn.mle_body && rsn.mle_len > 0) {
if (mle_parse(rsn.mle_body, rsn.mle_len, &mld)) {
mle_observe(&mld, fts);
have_mld = 1;
}
}
/* The same identity, bound to the BSSID that sent it, for
* the FragAttacks rules' "is this the AP?" (#180). A beacon
* without an MLE is recorded too - it says the BSS is not an
* AP MLD - but only when it could have shown one: a capture
* cut short by its snaplen may have lost the MLE off the
* tail, and a Basic MLE mle_parse() refused is still one.
* Neither is evidence of absence, and recording either as
* "not an MLD" would bar the sibling fallback on exactly
* the AP it exists for. */
if (have_mld)
frag_note_beacon(bssid, mld.mld_mac, fts);
else if (!rsn.mle_body && (uint32_t)fv.caplen >= fv.origlen)
frag_note_beacon(bssid, NULL, fts);
if (rsn.csa_present)
csa_observe(fr.bssid, fr.sa,
rsn.csa_new_channel, rsn.csa_new_op_class,
rsn.csa_switch_mode, rsn.csa_switch_count,
CSA_SRC_BEACON, channel, fts);
}
return;
}
/* Probe-response (5), Association-response (1), Reassoc-response (3)
* — all carry the real SSID even when the AP's beacon hides it.
* Assoc/reassoc responses additionally carry a status code that
* tells us whether the STA actually joined; if so, feed the
* association tracker. */
if (sub == 1 || sub == 3 || sub == 5) {
/* AP -> STA: DA (= STA) is addr1, BSSID is addr3 (§9.3.3.1). */
const uint8_t *sta_p = fr.da;
const uint8_t *bssid_p = fr.bssid;
/* Status code lives in the assoc/reassoc-resp fixed body:
* caps(2) + status(2) + aid(2). probe-resp doesn't have one. */
int status_ok = 1;
int fixed = (sub == 5) ? 12 : 6;
/* The body is where the view says it starts — 24 or 28 octets
* in, datapad-rounded when radiotap says so — and the only
* length floor is the fixed part itself. A stale
* `dot11_len < 36` guard sat here until #122 and dropped every
* 30–35-octet (re)association response, which is a legal frame:
* header + 6 fixed octets + a 2-octet Supported Rates element
* is 34. A Protected body (ciphertext) is refused outright. */
const uint8_t *body; int blen;
if (!full || !dot11_frame_body(&fr, &body, &blen) || blen < fixed)
return;
if (sub == 1 || sub == 3) {
uint16_t status = (uint16_t)(body[2] | ((uint16_t)body[3] << 8));
status_ok = (status == 0);
}
/* The walk ends at the SSID, normally the first element, so
* only a stop before it is reachable — and counted (#126). An
* oversize SSID is clamped to 32 here and has no counter on
* this path; beacons carry the per-BSSID one. */
char ssid[33];
dot11_ie_ssid(body + fixed, blen - fixed, ssid, NULL);
if (ssid[0]) beacon_reveal_hidden_ssid(bssid_p, ssid);
/* After the reveal, so a hidden AP's answer for its own name
* reads as its own name (#187 S2). */
if (sub == 5) karma_observe_frame(&fr, ssid);
/* The WSC element (#82). A probe response carries the full one —
* the vendor strings and UUID-E many beacons omit — and until
* this line only its SSID was read. Parsing lives in
* beacon_snoop.c for the testability reason given above. The
* capability field is fixed-body octets 10..11 (§9.3.3.10);
* Privacy is bit 4. */
if (sub == 5)
beacon_note_probe_resp_ies(bssid_p, body + fixed, blen - fixed,
(body[10] & 0x10) ? 1 : 0, fts);
if (status_ok && (sub == 1 || sub == 3)) {
int src = (sub == 1) ? ASSOC_SRC_ASSOC : ASSOC_SRC_REASSOC;
assoc_observe(bssid_p, sta_p, ssid[0] ? ssid : NULL,
src, signal, channel, band);
/* frag_note_association (#75 slice 2): the fragment cache
* should be cleared at exactly this event. Fed from the
* same status-0 evidence as assoc_observe, not its result —
* a station demoted by a later EAPOL-ranked entry still
* really did (re)associate at this moment. */
frag_note_association(bssid_p, sta_p, fts);
/* #107 shape B: a granted (re)association is the moment an
* AP may hand over frames it buffered under the *previous*
* security context. Fed from the same status-0 evidence as
* assoc_observe, for the same reason frag_note_association
* is. */
queue_evict_note_session_change_ev(
bssid_p, sta_p,
(sub == 3) ? QUEUE_EVICT_SRC_REASSOC
: QUEUE_EVICT_SRC_ASSOC,
fts, (long)fv.ts_usec, ev);
}
return;
}
if (sub == 10 || sub == 12) {
/* Disassoc (10) or Deauth (12) */
deauth_frame_t df;
if (deauth_parse_frame(&fr, &df)) {
/* Stamped here, not inside the parser: deauth_parse()
* memsets its output, so a stamp before the call is erased
* and one after the record is too late. */
df.event_id = ev;
deauth_record(&df);
}
/* Drop the association for this (BSSID, STA) — either side
* could be initiating, so try both directions. */
if (fr.a1 && fr.a2 && fr.a3) {
const uint8_t *a1 = fr.a1;
const uint8_t *a2 = fr.a2;
assoc_forget(a1, a2);
assoc_forget(a2, a1);
/* #107 shape B, the other route to the same buffer: an AP
* whose key store has already dropped the station can
* still transmit what it queued for it. addr3 is the BSSID
* for a management frame in either direction (§9.3.3.1),
* so the station is whichever of addr1/addr2 is not it —
* which attributes the event correctly whether the AP or
* the station sent the frame. A broadcast deauth lands on
* ff:ff:ff:ff:ff:ff and queue_evict rejects it. */
const uint8_t *bss_p = fr.a3;
queue_evict_note_session_change_ev(
bss_p, memcmp(a1, bss_p, 6) == 0 ? a2 : a1,
QUEUE_EVICT_SRC_DISCONNECT, fts, (long)fv.ts_usec, ev);
}
return;
}
if (sub == 11) {
/* Authentication frame (open / shared-key / SAE / OWE / FILS).
* We don't decode the algorithm here — the flood signal is the
* per-AP rate. addr3 (dot11+16) is the BSSID being authenticated
* to; a burst there means an association-table exhaustion DoS. */
auth_observe_ev(fr.bssid, fts, ev);
return;
}
if (sub == 0 || sub == 2) {
/* Association / reassociation request — #60. The client's side
* of the exchange: what it asked for, versus what assoc_observe
* records the AP granting. Parsing lives in assoc_track.c for
* the same testability reason as the Action dispatch below. */
assoc_req_t req;
if (assoc_request_parse_frame(&fr, &req))
assoc_request_observe(&req, signal, channel);
return;
}
if (sub == 13) {
/* Action frame (802.11k/v/r) — #59. The whole management
* surface behind this subtype was previously labelled and
* dropped. Parsing lives in action_snoop.c rather than here:
* this file is compiled only under WITH_PCAP and is absent from
* TEST_SRCS, so logic placed here cannot be tested. */
action_observe_frame(&fr, fts);
return;
}
if (sub != 4) return; /* only probe requests beyond this point */
/* Source Address (addr2 in a management frame). */
const uint8_t *sa = fr.sa;
/* Sequence Number: feed the seqnum tracker so we can correlate
* randomised probe MACs back to the same physical radio across MAC
* changes. -1 means the frame did not reach Sequence Control. */
if (fr.seq_num >= 0)
seqnum_track_observe(sa, (uint16_t)fr.seq_num);
/* Parse SSID information element (tag 0).
*
* A probe request is a management frame, so +HTC/Order puts an HT
* Control field ahead of the body and the IEs start at 28. A fixed
* 24 walked into HT Control — and the SSIDs this walk extracts are
* the client's preferred-network list, which is what the KARMA
* correlation is built on. */
const uint8_t *ie_start; int ie_total;
if (!full || !dot11_frame_body(&fr, &ie_start, &ie_total)) return;
/* The fingerprint and PHY walks below cover the same list and
* count their own stops; the tally counts walks (#126). */
char ssid[33];
dot11_ie_ssid(ie_start, ie_total, ssid, NULL);
pthread_mutex_lock(&g_mu);
record_probe(sa, ssid, signal, channel, band);
pthread_mutex_unlock(&g_mu);
/* The directed probe a forged answer pairs with (#187 S2). */
karma_observe_frame(&fr, ssid);
/* OS fingerprint from vendor-specific IEs (strong-signal only). */
const char *fp = probe_pnl_fingerprint_ies(ie_start, ie_total);
/* PHY tier from HT / VHT / HE / EHT IEs. */
const char *phy = probe_pnl_phy_ies(ie_start, ie_total);
/* Feed the PNL aggregator — outside the probe-list mutex since
* probe_pnl_observe takes its own lock. Wildcard probes are dropped
* inside observe() since they leak no preferred-network info. */
probe_pnl_observe(sa, ssid, fp, phy);
}
/* One frame at a time (several sensor radios, mon_radios.h). The path
* above was written for one thread: the frame ring's neighbours, the
* depad buffer, and every observer's assumption that frames arrive in
* sequence. Each radio has its own reader thread, so the whole callback
* runs under this lock - taken first, before any module's own lock, and
* by nothing but the capture callbacks. Uncontended with one radio. */
static pthread_mutex_t g_dispatch_mu = PTHREAD_MUTEX_INITIALIZER;
void probe_radio_frame(u_char *user, const struct pcap_pkthdr *hdr,
const u_char *data) {
pthread_mutex_lock(&g_dispatch_mu);
on_radio_frame((int)(intptr_t)user, hdr, data);
pthread_mutex_unlock(&g_dispatch_mu);
}
static void on_probe_frame(u_char *user, const struct pcap_pkthdr *hdr,
const u_char *data) {
probe_radio_frame(user, hdr, data);
}
/* ── Capture thread ──────────────────────────────────────── */
/* Why the monitor worker left its loop (#91 slice 2). Same publication
* pattern as the data-stream worker in capture.c — see the note there.
* This is the stream where confusing "quiet channel" with "dead thread"
* costs most: on a hopping radio an empty dwell is normal. */
static int g_exit_reason = CAPTURE_EXIT_NONE;
static char g_exit_detail[80];
static void *probe_thread(void *arg) {
(void)arg;
int r = 0;
while (capture_run_flag_get(&g_running)) {
r = pcap_dispatch(g_ph, 32, on_probe_frame, NULL);
if (r < 0) break;
}
const char *err = (r < 0 && g_ph) ? pcap_geterr(g_ph) : "";
/* The run-flag mutex is a leaf: read it before taking g_mu. */
int stop_requested = !capture_run_flag_get(&g_running);
/* Published under the client-table mutex, as in capture.c: a torn
* read of the error string is worse than no string at all. */
pthread_mutex_lock(&g_mu);
snprintf(g_exit_detail, sizeof(g_exit_detail), "%s", err ? err : "");
g_exit_reason = (int)capture_classify_exit(r, stop_requested, g_exit_detail);
pthread_mutex_unlock(&g_mu);
return NULL;
}
void probe_health_poll(capture_health_t *h) {
if (!h) return;
h->open = g_ph != NULL;
pthread_mutex_lock(&g_mu);
h->exit_reason = g_exit_reason;
snprintf(h->exit_detail, sizeof(h->exit_detail), "%s", g_exit_detail);
int reason = g_exit_reason;
pthread_mutex_unlock(&g_mu);
h->running = capture_run_flag_get(&g_running) && reason == CAPTURE_EXIT_NONE;
pthread_mutex_lock(&g_frame_mu);
time_t fts = g_last_frame_ts, fwall = g_last_frame_wall;
pthread_mutex_unlock(&g_frame_mu);
h->last_frame_ts = fts;
h->stale_secs = fwall ? (int)(sloth_wall() - fwall) : -1;
h->parse_rejects = mon_radiotap_reject_total();
/* Set BEFORE the early return below: a radio whose handle has gone
* still has a last-frame time worth reporting, and returning first
* would leave the caller's struct carrying whatever it held. */
if (!g_ph) return;
struct pcap_stat ps;