summaryrefslogtreecommitdiffstats
path: root/src/detection/wifi/wifi_linux.c
blob: 6f761590debdd6c8b68099df408561248005470b (plain) (blame)
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
#include "wifi.h"
#include "common/io.h"
#include "common/debug.h"
#include "common/strutil.h"

#include <sys/time.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <net/if.h>
#include <linux/wireless.h>
#include <unistd.h>

#if !__BIG_ENDIAN__
    #include <linux/genetlink.h>
    #include <linux/nl80211.h>

    // Silence warning of `NLA_HDRLEN` and `NLA_ALIGN`
    #pragma GCC diagnostic ignored "-Wsign-conversion"

typedef struct FFWifiNlContext {
    int sockFd;
    uint16_t nl80211FamilyId;
    uint32_t portId;
    uint32_t seq;
} FFWifiNlContext;

typedef struct FFWifiSecurityFlags {
    bool privacy : 1;
    bool wep : 1;
    bool wpa : 1;
    bool wpa2 : 1;
    bool wpa3 : 1;
    bool owe : 1;
    bool eap : 1;
} FFWifiSecurityFlags;

static inline double rssiToSignalQuality(int rssi) {
    return (double) (rssi >= -50 ? 100 : rssi <= -100 ? 0
                                                      : (rssi + 100) * 2);
}

static inline uint32_t ffWifiGetNetlinkPortId(int sockFd) {
    struct sockaddr_nl addr = {};
    socklen_t addrLen = sizeof(addr);
    if (getsockname(sockFd, (struct sockaddr*) &addr, &addrLen) < 0) {
        FF_DEBUG("Failed to query netlink socket address (use PID instead): %s", strerror(errno));
        return instance.state.platform.pid;
    }

    return addr.nl_pid;
}

static inline bool ffWifiNlAttrOk(const struct nlattr* attr, size_t remaining) {
    return remaining >= sizeof(*attr) &&
        attr->nla_len >= sizeof(*attr) &&
        attr->nla_len <= remaining;
}

static const struct nlattr* ffWifiNlAttrNext(const struct nlattr* attr, size_t* remaining) {
    size_t alignedLen = NLA_ALIGN(attr->nla_len);
    if (alignedLen > *remaining) {
        *remaining = 0;
        return NULL;
    }

    *remaining -= alignedLen;
    return (const struct nlattr*) ((const char*) attr + alignedLen);
}

static inline size_t ffWifiNlAttrPayload(const struct nlattr* attr) {
    return attr->nla_len > NLA_HDRLEN ? attr->nla_len - NLA_HDRLEN : 0;
}

static inline const void* ffWifiNlAttrData(const struct nlattr* attr) {
    // Big endian?
    return (const uint8_t*) attr + NLA_HDRLEN;
}

static bool ffWifiNlAppendAttr(struct nlmsghdr* nlh, size_t maxLen, uint16_t type, const void* data, uint16_t dataLen) {
    size_t offset = NLMSG_ALIGN(nlh->nlmsg_len);
    size_t attrLen = NLA_HDRLEN + dataLen;
    size_t alignedLen = NLA_ALIGN(attrLen);
    size_t newLen = offset + alignedLen;
    if (newLen > maxLen || attrLen > UINT16_MAX || newLen > UINT32_MAX) {
        return false;
    }

    struct nlattr* attr = (struct nlattr*) ((char*) nlh + offset);
    attr->nla_type = type;
    attr->nla_len = (uint16_t) attrLen;
    memcpy((char*) attr + NLA_HDRLEN, data, dataLen);
    memset((char*) attr + attrLen, 0, alignedLen - attrLen);
    nlh->nlmsg_len = (uint32_t) newLen;
    return true;
}

static bool ffWifiNlGetFamilyId(FFWifiNlContext* ctx) {
    struct {
        struct nlmsghdr nlh;
        struct genlmsghdr genl;
        char attrs[64];
    } req = {
        .nlh = {
            .nlmsg_len = NLMSG_LENGTH(sizeof(struct genlmsghdr)),
            .nlmsg_type = GENL_ID_CTRL,
            .nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK,
            .nlmsg_seq = ++ctx->seq,
            .nlmsg_pid = ctx->portId,
        },
        .genl = {
            .cmd = CTRL_CMD_GETFAMILY,
            .version = 1, // generic netlink control protocol version
        },
    };

    if (!ffWifiNlAppendAttr(&req.nlh, sizeof(req), CTRL_ATTR_FAMILY_NAME, "nl80211", sizeof("nl80211"))) {
        FF_DEBUG("Failed to append CTRL_ATTR_FAMILY_NAME attribute");
        return false;
    }

    struct sockaddr_nl addr = {
        .nl_family = AF_NETLINK,
    };

    ssize_t sent = sendto(ctx->sockFd, &req, req.nlh.nlmsg_len, 0, (struct sockaddr*) &addr, sizeof(addr));
    if (sent != (ssize_t) req.nlh.nlmsg_len) {
        FF_DEBUG("Failed to send nl80211 family request: sent=%zd expected=%u", sent, req.nlh.nlmsg_len);
        return false;
    }

    uint8_t buffer[8192];
    while (true) {
        ssize_t received = recvfrom(ctx->sockFd, buffer, sizeof(buffer), 0, NULL, NULL);
        if (received < 0) {
            FF_DEBUG("Failed to receive nl80211 family reply: %s", strerror(errno));
            return false;
        }

        for (const struct nlmsghdr* nlh = (const struct nlmsghdr*) buffer;
            NLMSG_OK(nlh, received);
            nlh = NLMSG_NEXT(nlh, received)) {
            if (nlh->nlmsg_seq != req.nlh.nlmsg_seq) {
                continue;
            }

            if (nlh->nlmsg_type == NLMSG_ERROR) {
                const struct nlmsgerr* err = (const struct nlmsgerr*) NLMSG_DATA(nlh);
                if (err->error != 0) {
                    FF_DEBUG("nl80211 family query failed: %s", strerror(-err->error));
                    return false;
                }
                continue;
            }

            if (nlh->nlmsg_type != GENL_ID_CTRL) {
                continue;
            }

            const struct genlmsghdr* genl = (const struct genlmsghdr*) NLMSG_DATA(nlh);
            if (genl->cmd != CTRL_CMD_NEWFAMILY) {
                continue;
            }

            size_t attrRemaining = nlh->nlmsg_len - NLMSG_HDRLEN - GENL_HDRLEN;
            for (const struct nlattr* attr = (const struct nlattr*) ((const char*) genl + GENL_HDRLEN);
                ffWifiNlAttrOk(attr, attrRemaining);
                attr = ffWifiNlAttrNext(attr, &attrRemaining)) {
                if ((attr->nla_type & NLA_TYPE_MASK) != CTRL_ATTR_FAMILY_ID || ffWifiNlAttrPayload(attr) < sizeof(uint16_t)) {
                    continue;
                }

                ctx->nl80211FamilyId = *(const uint16_t*) ffWifiNlAttrData(attr);
                return true;
            }
        }
    }
}

static bool ffWifiNlInit(FFWifiNlContext* ctx) {
    FF_AUTO_CLOSE_FD int _ = ctx->sockFd = socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_GENERIC);
    if (ctx->sockFd < 0) {
        FF_DEBUG("Failed to create generic netlink socket: %s", strerror(errno));
        return false;
    }

    struct sockaddr_nl addr = {
        .nl_family = AF_NETLINK,
    };

    if (bind(ctx->sockFd, (struct sockaddr*) &addr, sizeof(addr)) < 0) {
        FF_DEBUG("Failed to bind generic netlink socket: %s", strerror(errno));
        return false;
    }

    if (setsockopt(
            ctx->sockFd,
            SOL_SOCKET,
            SO_RCVTIMEO,
            &(struct timeval){ .tv_sec = 0, .tv_usec = 250000 }, // 250 ms recv timeout
            sizeof(struct timeval)) < 0) {
        FF_DEBUG("Failed to set netlink receive timeout: %s", strerror(errno));
        return false;
    }

    ctx->portId = ffWifiGetNetlinkPortId(ctx->sockFd);
    if (!ffWifiNlGetFamilyId(ctx)) {
        return false;
    }

    _ = -1; // We are ok now
    return true;
}

static double ffWifiParseBitrateFromRateInfo(const struct nlattr* rateAttr, FFstrbuf* protocol) {
    double rate = -DBL_MAX;
    size_t remaining = ffWifiNlAttrPayload(rateAttr);

    for (const struct nlattr* info = (const struct nlattr*) ffWifiNlAttrData(rateAttr);
        ffWifiNlAttrOk(info, remaining);
        info = ffWifiNlAttrNext(info, &remaining)) {
        uint16_t type = (uint16_t) (info->nla_type & NLA_TYPE_MASK);
        size_t payload = ffWifiNlAttrPayload(info);

        switch (type) {
            case 30 /* NL80211_RATE_INFO_UHR_MCS */:
                ffStrbufSetStatic(protocol, "802.11bn (Wi-Fi 8)");
                break;
            case 23 /* NL80211_RATE_INFO_S1G_MCS */:
                ffStrbufSetStatic(protocol, "802.11ah (Wi-Fi HaLow)");
                break;
            case 19 /* NL80211_RATE_INFO_EHT_MCS */:
                ffStrbufSetStatic(protocol, "802.11be (Wi-Fi 7)");
                break;
            case 13 /* NL80211_RATE_INFO_HE_MCS */:
                ffStrbufSetStatic(protocol, "802.11ax (Wi-Fi 6)");
                break;
            case NL80211_RATE_INFO_VHT_MCS:
                ffStrbufSetStatic(protocol, "802.11ac (Wi-Fi 5)");
                break;
            case NL80211_RATE_INFO_MCS:
                ffStrbufSetStatic(protocol, "802.11n (Wi-Fi 4)");
                break;
            case NL80211_RATE_INFO_BITRATE32:
                if (payload >= sizeof(uint32_t)) {
                    rate = *(uint32_t*) ffWifiNlAttrData(info) / 10.0; // nl80211 bitrate unit: 100 kbps => Mbps
                }
                break;
            case NL80211_RATE_INFO_BITRATE:
                if (payload >= sizeof(uint16_t) && rate == -DBL_MAX) {
                    rate = *(uint16_t*) ffWifiNlAttrData(info) / 10.0; // nl80211 bitrate unit: 100 kbps => Mbps
                }
                break;
        }
    }

    return rate;
}

static void ffWifiApplySecurityFlags(FFWifiResult* item, const FFWifiSecurityFlags* sec) {
    ffStrbufClear(&item->conn.security);

    if (sec->wep) {
        ffStrbufAppendS(&item->conn.security, "WEP/");
    }
    if (sec->wpa) {
        ffStrbufAppendS(&item->conn.security, "WPA/");
    }
    if (sec->wpa2) {
        ffStrbufAppendS(&item->conn.security, "WPA2/");
    }
    if (sec->wpa3) {
        ffStrbufAppendS(&item->conn.security, "WPA3/");
    }
    if (sec->owe) {
        ffStrbufAppendS(&item->conn.security, "OWE/");
    }
    if (sec->eap) {
        ffStrbufAppendS(&item->conn.security, "802.1X/");
    }

    if (!item->conn.security.length) {
        if (sec->privacy) {
            ffStrbufSetStatic(&item->conn.security, "WEP");
        } else {
            ffStrbufSetStatic(&item->conn.security, "Insecure");
        }
    } else {
        ffStrbufTrimRight(&item->conn.security, '/');
    }
}

static void ffWifiParseRsnIe(const uint8_t* ie, size_t len, FFWifiSecurityFlags* sec) {
    if (len < 8) { // version(2) + group cipher suite(4) + pairwise count(2)
        return;
    }

    sec->wpa2 = true;
    size_t pos = 0;

    pos += 2; // RSN version field length
    if (pos + 4 > len) { // group cipher suite selector length
        return;
    }
    pos += 4; // skip group cipher suite selector

    if (pos + 2 > len) { // pairwise cipher suite count field length
        return;
    }
    uint16_t pairwiseCount = *(uint16_t*) (ie + pos);
    pos += 2; // skip pairwise cipher suite count field

    size_t pairwiseLen = (size_t) pairwiseCount * 4; // each suite selector is 4 bytes
    if (pos + pairwiseLen > len) {
        return;
    }
    pos += pairwiseLen;

    if (pos + 2 > len) { // AKM suite count field length
        return;
    }
    uint16_t akmCount = *(uint16_t*) (ie + pos);
    pos += 2; // skip AKM suite count field

    for (uint16_t i = 0; i < akmCount && pos + 4 <= len; ++i, pos += 4) { // each AKM suite selector is 4 bytes
        const uint8_t* akm = ie + pos;
        if (akm[0] != 0x00 || akm[1] != 0x0f || akm[2] != 0xac) { // RSN OUI 00:0f:ac
            continue;
        }

        switch (akm[3]) {
            case 1:  // 802.1X
            case 5:  // FT/802.1X
            case 11: // 802.1X-SHA256
            case 12: // FT/802.1X-SHA384 (suite selector value)
                sec->eap = true;
                break;
            case 8:  // SAE (WPA3-Personal)
                sec->wpa3 = true;
                break;
            case 18: // OWE
                sec->owe = true;
                break;
            default:
                break;
        }
    }

    if (sec->owe) {
        sec->wpa2 = false;
    }
}

static void ffWifiParseWpaVendorIe(const uint8_t* ie, size_t len, FFWifiSecurityFlags* sec) {
    if (len < 8) { // OUI+type(4) + version(2) + multicast cipher suite(4) starts here
        return;
    }

    if (!(ie[0] == 0x00 && ie[1] == 0x50 && ie[2] == 0xf2 && ie[3] == 0x01)) { // Microsoft WPA OUI/type
        return;
    }

    sec->wpa = true;

    size_t pos = 4; // WPA vendor OUI/type selector length
    if (pos + 2 > len) { // WPA version field length
        return;
    }
    pos += 2; // skip WPA version

    if (pos + 4 > len) { // multicast cipher suite selector length
        return;
    }
    pos += 4; // skip multicast cipher suite selector

    if (pos + 2 > len) { // unicast cipher suite count field length
        return;
    }
    uint16_t pairwiseCount = *(uint16_t*) (ie + pos);
    pos += 2 + (size_t) pairwiseCount * 4; // count field(2) + N unicast suite selectors(4 each)

    if (pos + 2 > len) { // AKM suite count field length
        return;
    }
    uint16_t akmCount = *(uint16_t*) (ie + pos);
    pos += 2; // skip AKM suite count field

    for (uint16_t i = 0; i < akmCount && pos + 4 <= len; ++i, pos += 4) { // each AKM suite selector is 4 bytes
        const uint8_t* akm = ie + pos;
        if (!(akm[0] == 0x00 && akm[1] == 0x50 && akm[2] == 0xf2)) { // WPA vendor OUI 00:50:f2
            continue;
        }
        if (akm[3] == 1) { // WPA Enterprise (802.1X)
            sec->eap = true;
        }
    }
}

static void ffWifiParseInformationElements(const uint8_t* ies, size_t length, FFWifiResult* item, FFWifiSecurityFlags* sec) {
    size_t pos = 0;
    while (pos + 2 <= length) {
        uint8_t id = ies[pos];
        uint8_t len = ies[pos + 1];
        pos += 2;
        if (pos + len > length) {
            break;
        }

        const uint8_t* ie = ies + pos;
        if (id == 0) { // SSID element ID
            ffStrbufSetNS(&item->conn.ssid, len, (const char*) ie);
        } else if (id == 48) { // RSN element ID
            ffWifiParseRsnIe(ie, len, sec);
        } else if (id == 221) { // vendor-specific element ID (WPA IE lives here)
            ffWifiParseWpaVendorIe(ie, len, sec);
        }

        pos += len;
    }
}

static bool ffWifiIsBssAssociated(const struct nlattr* bssAttr) {
    size_t remaining = ffWifiNlAttrPayload(bssAttr);
    for (const struct nlattr* attr = (const struct nlattr*) ffWifiNlAttrData(bssAttr);
        ffWifiNlAttrOk(attr, remaining);
        attr = ffWifiNlAttrNext(attr, &remaining)) {
        uint16_t type = (uint16_t) (attr->nla_type & NLA_TYPE_MASK);
        size_t payload = ffWifiNlAttrPayload(attr);

        if (type == NL80211_BSS_STATUS && payload >= sizeof(uint32_t)) {
            return *(uint32_t*) ffWifiNlAttrData(attr) == NL80211_BSS_STATUS_ASSOCIATED;
        }
    }

    return false;
}

static void ffWifiParseBssAttr(const struct nlattr* bssAttr, FFWifiResult* item) {
    FFWifiSecurityFlags sec = {};
    size_t remaining = ffWifiNlAttrPayload(bssAttr);

    for (const struct nlattr* attr = (const struct nlattr*) ffWifiNlAttrData(bssAttr);
        ffWifiNlAttrOk(attr, remaining);
        attr = ffWifiNlAttrNext(attr, &remaining)) {
        uint16_t type = (uint16_t) (attr->nla_type & NLA_TYPE_MASK);
        size_t payload = ffWifiNlAttrPayload(attr);

        if (type == NL80211_BSS_BSSID && payload >= 6) {
            const uint8_t* mac = (const uint8_t*) ffWifiNlAttrData(attr);
            ffStrbufSetF(&item->conn.bssid, "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
        } else if (type == NL80211_BSS_FREQUENCY && payload >= sizeof(uint32_t)) {
            item->conn.frequency = (uint16_t) *(uint32_t*) ffWifiNlAttrData(attr);
            item->conn.channel = ffWifiFreqToChannel(item->conn.frequency);
        } else if (type == NL80211_BSS_SIGNAL_MBM && payload >= sizeof(int32_t)) {
            int rssi = *(int32_t*) ffWifiNlAttrData(attr) / 100; // mBm (100 * dBm) => dBm
            item->conn.signalQuality = rssiToSignalQuality(rssi);
        } else if (type == NL80211_BSS_CAPABILITY && payload >= sizeof(uint16_t)) {
            uint16_t capability = *(uint16_t*) ffWifiNlAttrData(attr);
            sec.privacy = (capability & (1u << 4u)) != 0; // IEEE 802.11 capability bit 4: privacy
        } else if (type == NL80211_BSS_INFORMATION_ELEMENTS || type == NL80211_BSS_BEACON_IES) {
            ffWifiParseInformationElements((const uint8_t*) ffWifiNlAttrData(attr), payload, item, &sec);
        }
    }

    ffWifiApplySecurityFlags(item, &sec);
    return;
}

static bool ffWifiFetchScanInfo(FFWifiNlContext* ctx, FFWifiResult* item, uint32_t ifIndex) {
    struct {
        struct nlmsghdr nlh;
        struct genlmsghdr genl;
        char attrs[32];
    } req = {
        .nlh = {
            .nlmsg_len = NLMSG_LENGTH(sizeof(struct genlmsghdr)),
            .nlmsg_type = ctx->nl80211FamilyId,
            .nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP | NLM_F_ACK,
            .nlmsg_seq = ++ctx->seq,
            .nlmsg_pid = ctx->portId,
        },
        .genl = {
            .cmd = NL80211_CMD_GET_SCAN,
            .version = 0, // nl80211 command version
        },
    };

    if (!ffWifiNlAppendAttr(&req.nlh, sizeof(req), NL80211_ATTR_IFINDEX, &ifIndex, sizeof(ifIndex))) {
        FF_DEBUG("Failed to build nl80211 scan request");
        return false;
    }

    struct sockaddr_nl addr = {
        .nl_family = AF_NETLINK,
    };

    ssize_t sent = sendto(ctx->sockFd, &req, req.nlh.nlmsg_len, 0, (struct sockaddr*) &addr, sizeof(addr));
    if (sent != (ssize_t) req.nlh.nlmsg_len) {
        FF_DEBUG("Failed to send nl80211 scan request");
        return false;
    }

    uint8_t buffer[1024 * 16];
    while (true) {
        ssize_t received = recvfrom(ctx->sockFd, buffer, sizeof(buffer), 0, NULL, NULL);
        if (received < 0) {
            FF_DEBUG("Failed to receive nl80211 scan reply: %s", strerror(errno));
            return false;
        }

        for (const struct nlmsghdr* nlh = (const struct nlmsghdr*) buffer;
            NLMSG_OK(nlh, received);
            nlh = NLMSG_NEXT(nlh, received)) {
            if (nlh->nlmsg_seq != req.nlh.nlmsg_seq) {
                continue;
            }

            if (nlh->nlmsg_type == NLMSG_DONE) {
                return false;
            }

            if (nlh->nlmsg_type == NLMSG_ERROR) {
                const struct nlmsgerr* err = (const struct nlmsgerr*) NLMSG_DATA(nlh);
                if (err->error == 0) {
                    continue;
                }
                FF_DEBUG("nl80211 scan request failed: %s", strerror(-err->error));
                return false;
            }

            if (nlh->nlmsg_type != ctx->nl80211FamilyId) {
                continue;
            }

            const struct genlmsghdr* genl = (const struct genlmsghdr*) NLMSG_DATA(nlh);
            size_t attrRemaining = nlh->nlmsg_len - NLMSG_HDRLEN - GENL_HDRLEN;
            for (const struct nlattr* attr = (const struct nlattr*) ((const char*) genl + GENL_HDRLEN);
                ffWifiNlAttrOk(attr, attrRemaining);
                attr = ffWifiNlAttrNext(attr, &attrRemaining)) {
                if ((attr->nla_type & NLA_TYPE_MASK) != NL80211_ATTR_BSS) {
                    continue;
                }

                if (!ffWifiIsBssAssociated(attr)) {
                    continue;
                }

                ffWifiParseBssAttr(attr, item);
                ffStrbufSetStatic(&item->conn.status, "connected");
                return true;
            }
        }
    }

    return false;
}

static void ffWifiParseStationInfo(const struct nlattr* staInfoAttr, FFWifiResult* item) {
    size_t remaining = ffWifiNlAttrPayload(staInfoAttr);
    for (const struct nlattr* attr = (const struct nlattr*) ffWifiNlAttrData(staInfoAttr);
        ffWifiNlAttrOk(attr, remaining);
        attr = ffWifiNlAttrNext(attr, &remaining)) {
        uint16_t type = (uint16_t) (attr->nla_type & NLA_TYPE_MASK);
        size_t payload = ffWifiNlAttrPayload(attr);

        if (type == NL80211_STA_INFO_SIGNAL && payload >= sizeof(uint8_t) && item->conn.signalQuality == -DBL_MAX) {
            int rssi = (int8_t) *(const uint8_t*) ffWifiNlAttrData(attr);
            item->conn.signalQuality = rssiToSignalQuality(rssi);
        } else if (type == NL80211_STA_INFO_TX_BITRATE && item->conn.txRate == -DBL_MAX) {
            double tx = ffWifiParseBitrateFromRateInfo(attr, &item->conn.protocol);
            if (tx != -DBL_MAX) {
                item->conn.txRate = tx;
            }
        } else if (type == NL80211_STA_INFO_RX_BITRATE && item->conn.rxRate == -DBL_MAX) {
            double rx = ffWifiParseBitrateFromRateInfo(attr, &item->conn.protocol);
            if (rx != -DBL_MAX) {
                item->conn.rxRate = rx;
            }
        }
    }
}

static bool ffWifiFetchStationInfo(FFWifiNlContext* ctx, FFWifiResult* item, uint32_t ifIndex) {
    struct {
        struct nlmsghdr nlh;
        struct genlmsghdr genl;
        char attrs[32];
    } req = {
        .nlh = {
            .nlmsg_len = NLMSG_LENGTH(sizeof(struct genlmsghdr)),
            .nlmsg_type = ctx->nl80211FamilyId,
            .nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP | NLM_F_ACK,
            .nlmsg_seq = ++ctx->seq,
            .nlmsg_pid = ctx->portId,
        },
        .genl = {
            .cmd = NL80211_CMD_GET_STATION,
            .version = 0, // nl80211 command version
        },
    };

    if (!ffWifiNlAppendAttr(&req.nlh, sizeof(req), NL80211_ATTR_IFINDEX, &ifIndex, sizeof(ifIndex))) {
        FF_DEBUG("Failed to build nl80211 station request");
        return false;
    }

    struct sockaddr_nl addr = {
        .nl_family = AF_NETLINK,
    };

    ssize_t sent = sendto(ctx->sockFd, &req, req.nlh.nlmsg_len, 0, (struct sockaddr*) &addr, sizeof(addr));
    if (sent != (ssize_t) req.nlh.nlmsg_len) {
        FF_DEBUG("Failed to send nl80211 station request");
        return false;
    }

    uint8_t buffer[8192];
    bool gotStation = false;
    while (true) {
        ssize_t received = recvfrom(ctx->sockFd, buffer, sizeof(buffer), 0, NULL, NULL);
        if (received < 0) {
            FF_DEBUG("Failed to receive nl80211 station reply: %s", strerror(errno));
            return gotStation;
        }

        for (const struct nlmsghdr* nlh = (const struct nlmsghdr*) buffer;
            NLMSG_OK(nlh, received);
            nlh = NLMSG_NEXT(nlh, received)) {
            if (nlh->nlmsg_seq != req.nlh.nlmsg_seq) {
                continue;
            }

            if (nlh->nlmsg_type == NLMSG_DONE) {
                return gotStation;
            }

            if (nlh->nlmsg_type == NLMSG_ERROR) {
                const struct nlmsgerr* err = (const struct nlmsgerr*) NLMSG_DATA(nlh);
                if (err->error != 0) {
                    FF_DEBUG("nl80211 station request failed: %s", strerror(-err->error));
                }
                return gotStation;
            }

            if (nlh->nlmsg_type != ctx->nl80211FamilyId) {
                continue;
            }

            const struct genlmsghdr* genl = (const struct genlmsghdr*) NLMSG_DATA(nlh);
            size_t attrRemaining = nlh->nlmsg_len - NLMSG_HDRLEN - GENL_HDRLEN;
            for (const struct nlattr* attr = (const struct nlattr*) ((const char*) genl + GENL_HDRLEN);
                ffWifiNlAttrOk(attr, attrRemaining);
                attr = ffWifiNlAttrNext(attr, &attrRemaining)) {
                if ((attr->nla_type & NLA_TYPE_MASK) != NL80211_ATTR_STA_INFO) {
                    continue;
                }

                ffWifiParseStationInfo(attr, item);
                gotStation = true;
            }
        }
    }
}

static const char* detectWithNetlink(FFWifiNlContext* ctx, FFWifiResult* item, uint32_t ifIndex) {
    if (ctx->sockFd < 0) {
        if (ctx->sockFd == -1) {
            if (!ffWifiNlInit(ctx)) {
                FF_DEBUG("Failed to initialize netlink context, skipping");
                ctx->sockFd = -2; // sentinel: permanent netlink failure, don't retry
                return "Netlink initialization failed";
            }
        } else {
            FF_DEBUG("Netlink socket is not available, skipping");
            return "Netlink socket unavailable";
        }
    }

    FF_DEBUG("Starting netlink wifi detection for interface %s", item->inf.description.chars);
    if (ffWifiFetchScanInfo(ctx, item, ifIndex)) {
        FF_DEBUG("found associated BSS: %s", item->conn.ssid.chars);
        ffStrbufSetStatic(&item->conn.status, "connected");
        ffWifiFetchStationInfo(ctx, item, ifIndex);
        if (!item->conn.protocol.length && item->conn.txRate != -DBL_MAX) {
            FF_DEBUG("nl80211 station info did not include MCS family fields");
        }
    } else {
        FF_DEBUG("No associated BSS found");
        ffStrbufSetStatic(&item->conn.status, "disconnected");
    }

    FF_DEBUG("Netlink wifi detection completed");
    return NULL;
}
#endif

typedef struct FFWifiIcContext {
    int sockFd;
} FFWifiIcContext;

static const char* detectWithIoctl(FFWifiIcContext* ctx, FFWifiResult* item, char ifName[static IFNAMSIZ]) {
    int sock = -1;
    if (ctx->sockFd < 0) {
        if (ctx->sockFd == -1) {
            sock = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
            if (sock < 0) {
                FF_DEBUG("Failed to initialize ioctl context, skipping: %s", strerror(errno));
                ctx->sockFd = -2; // sentinel: permanent ioctl failure, don't retry
                return "socket() failed";
            }
            ctx->sockFd = sock;
        } else {
            FF_DEBUG("Ioctl socket is not available, skipping");
            return "ioctl socket unavailable";
        }
    } else {
        sock = ctx->sockFd;
    }

    FF_DEBUG("Starting ioctl wifi detection for interface %s", ifName);
    struct iwreq iwr = {};
    strcpy(iwr.ifr_name, ifName);

    if (!item->conn.ssid.length) {
        FF_DEBUG("Getting SSID via ioctl");
        ffStrbufEnsureFree(&item->conn.ssid, IW_ESSID_MAX_SIZE);
        iwr.u.essid.pointer = (caddr_t) item->conn.ssid.chars;
        iwr.u.essid.length = IW_ESSID_MAX_SIZE + 1;
        iwr.u.essid.flags = 0;
        if (ioctl(sock, SIOCGIWESSID, &iwr) >= 0) {
            ffStrbufSetStatic(&item->conn.status, "connected");
            ffStrbufRecalculateLength(&item->conn.ssid);
            FF_DEBUG("SSID: %s", item->conn.ssid.chars);
        } else {
            FF_DEBUG("Failed to get SSID via ioctl: %s", strerror(errno));
        }
    }

    if (!item->conn.protocol.length) {
        FF_DEBUG("Getting protocol name via ioctl");
        if (ioctl(sock, SIOCGIWNAME, &iwr) >= 0) {
            char* token = iwr.u.name;
            if (ffStrStartsWithIgnCase(iwr.u.name, "IEEE ")) {
                token += strlen("IEEE ");
            }
            if (ffStrStartsWith(token, "802.11")) {
                token += strlen("802.11");
                if (*token) {
                    if (*token == ' ') {
                        token++;
                    }
                    for (char* c = token; *c; ++c) {
                        if (*c >= 'A' && *c <= 'Z') {
                            *c += 'a' - 'A';
                        }
                    }
                    if (ffStrEquals(token, "n")) {
                        ffStrbufSetStatic(&item->conn.protocol, "802.11n (Wi-Fi 4)");
                    } else if (ffStrEquals(token, "ac")) {
                        ffStrbufSetStatic(&item->conn.protocol, "802.11ac (Wi-Fi 5)");
                    } else if (ffStrEquals(token, "ax")) {
                        ffStrbufSetStatic(&item->conn.protocol, "802.11ax (Wi-Fi 6)");
                    } else if (ffStrEquals(token, "be")) {
                        ffStrbufSetStatic(&item->conn.protocol, "802.11be (Wi-Fi 7)");
                    } else if (ffStrEquals(token, "bn")) {
                        ffStrbufSetStatic(&item->conn.protocol, "802.11bn (Wi-Fi 8)");
                    } else {
                        ffStrbufSetStatic(&item->conn.protocol, "802.11");
                        ffStrbufAppendS(&item->conn.protocol, token);
                    }
                }
            }
            FF_DEBUG("Protocol: %s", item->conn.protocol.length ? item->conn.protocol.chars : "(unknown)");
        } else {
            FF_DEBUG("Failed to get protocol name via ioctl: %s", strerror(errno));
        }
    }

    if (!item->conn.bssid.length) {
        FF_DEBUG("Getting BSSID via ioctl");
        if (ioctl(sock, SIOCGIWAP, &iwr) >= 0) {
            for (int i = 0; i < 6; ++i) {
                ffStrbufAppendF(&item->conn.bssid, "%.2X:", (uint8_t) iwr.u.ap_addr.sa_data[i]);
            }
            ffStrbufTrimRight(&item->conn.bssid, ':');
            FF_DEBUG("BSSID: %s", item->conn.bssid.chars);
        } else {
            FF_DEBUG("Failed to get BSSID via ioctl: %s", strerror(errno));
        }
    }

    if (item->conn.txRate == -DBL_MAX) {
        FF_DEBUG("Getting bitrate via ioctl");
        if (ioctl(sock, SIOCGIWRATE, &iwr) >= 0) {
            if (iwr.u.bitrate.value > 0) {
                item->conn.txRate = iwr.u.bitrate.value / 1000000.; // bps => Mbps
                FF_DEBUG("TX bitrate: %.2f Mbps", item->conn.txRate);
            } else {
                FF_DEBUG("Bitrate value is zero or negative, ignoring");
            }
        } else {
            FF_DEBUG("Failed to get bitrate via ioctl: %s", strerror(errno));
        }
    }

    if (item->conn.frequency == 0 && item->conn.channel == 0) {
        FF_DEBUG("Getting frequency via ioctl");
        if (ioctl(sock, SIOCGIWFREQ, &iwr) >= 0) {
            if (iwr.u.freq.e == 0 && iwr.u.freq.m <= 1000) { // kernel may return direct channel number
                item->conn.channel = (uint16_t) iwr.u.freq.m;
                FF_DEBUG("Direct channel value: %u", item->conn.channel);
            } else {
                // convert it to MHz
                while (iwr.u.freq.e < 6) { // normalize exponent to 10^6 (MHz)
                    iwr.u.freq.m /= 10;
                    iwr.u.freq.e++;
                }
                while (iwr.u.freq.e > 6) { // normalize exponent to 10^6 (MHz)
                    iwr.u.freq.m *= 10;
                    iwr.u.freq.e--;
                }
                item->conn.frequency = (uint16_t) iwr.u.freq.m;
                item->conn.channel = ffWifiFreqToChannel(item->conn.frequency);
                FF_DEBUG("Frequency: %u MHz, Channel: %u", item->conn.frequency, item->conn.channel);
            }
        } else {
            FF_DEBUG("Failed to get frequency via ioctl: %s", strerror(errno));
        }
    }

    if (item->conn.signalQuality == -DBL_MAX) {
        FF_DEBUG("Getting signal stats via ioctl");
        struct iw_statistics stats;
        iwr.u.data.pointer = &stats;
        iwr.u.data.length = sizeof(stats);
        iwr.u.data.flags = 0;

        if (ioctl(sock, SIOCGIWSTATS, &iwr) >= 0) {
            int8_t level = (int8_t) stats.qual.level;
            item->conn.signalQuality = level >= -50 ? 100 : level <= -100 ? 0
                                                                          : (level + 100) * 2;
            FF_DEBUG("Signal level: %d dBm, quality: %.0f%%", level, item->conn.signalQuality);
        } else {
            FF_DEBUG("Failed to get signal stats via ioctl: %s", strerror(errno));
        }
    }

    if (!item->conn.security.length) {
        FF_DEBUG("Getting security info via ioctl");
        struct iw_encode_ext iwe;
        iwr.u.data.pointer = &iwe;
        iwr.u.data.length = sizeof(iwe);
        iwr.u.data.flags = 0;
        if (ioctl(sock, SIOCGIWENCODEEXT, &iwr) >= 0) {
            switch (iwe.alg) {
                case IW_ENCODE_ALG_WEP:
                    ffStrbufAppendS(&item->conn.security, "WEP");
                    FF_DEBUG("Security: WEP");
                    break;
                case IW_ENCODE_ALG_TKIP:
                    ffStrbufAppendS(&item->conn.security, "TKIP");
                    FF_DEBUG("Security: TKIP");
                    break;
                case IW_ENCODE_ALG_CCMP:
                    ffStrbufAppendS(&item->conn.security, "CCMP");
                    FF_DEBUG("Security: CCMP");
                    break;
                case IW_ENCODE_ALG_PMK:
                    ffStrbufAppendS(&item->conn.security, "PMK");
                    FF_DEBUG("Security: PMK");
                    break;
                case IW_ENCODE_ALG_AES_CMAC:
                    ffStrbufAppendS(&item->conn.security, "CMAC");
                    FF_DEBUG("Security: CMAC");
                    break;
                default:
                    ffStrbufAppendF(&item->conn.security, "Unknown (%d)", (int) iwe.alg);
                    FF_DEBUG("Security: Unknown (%d)", (int) iwe.alg);
                    break;
            }
        } else {
            FF_DEBUG("Failed to get security info via ioctl: %s", strerror(errno));
        }
    }

    FF_DEBUG("Ioctl wifi detection completed");
    return NULL;
}

const char* ffDetectWifi(FFlist* result) {
    FF_DEBUG("Starting wifi detection");

    struct if_nameindex* infs = if_nameindex();
    if (!infs) {
        FF_DEBUG("if_nameindex failed: %s", strerror(errno));
        return "if_nameindex() failed";
    }

#if !__BIG_ENDIAN__
    FFWifiNlContext nl = { .sockFd = -1 };
#endif
    FFWifiIcContext ic = { .sockFd = -1 };

    FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate();

    for (struct if_nameindex* i = infs; !(i->if_index == 0 && i->if_name == NULL); ++i) {
        FF_DEBUG("Checking interface: %s (index: %u)", i->if_name, i->if_index);
        ffStrbufSetF(&buffer, "/sys/class/net/%s/phy80211/", i->if_name);
        if (!ffPathExists(buffer.chars, FF_PATHTYPE_DIRECTORY)) {
            FF_DEBUG("Not a wifi interface (no phy80211 directory)");
            continue;
        }

        FFWifiResult* item = FF_LIST_ADD(FFWifiResult, *result);
        ffStrbufInitS(&item->inf.description, i->if_name);
        ffStrbufInit(&item->inf.status);
        ffStrbufInit(&item->conn.status);
        ffStrbufInit(&item->conn.ssid);
        ffStrbufInit(&item->conn.bssid);
        ffStrbufInit(&item->conn.protocol);
        ffStrbufInit(&item->conn.security);
        item->conn.signalQuality = -DBL_MAX;
        item->conn.rxRate = -DBL_MAX;
        item->conn.txRate = -DBL_MAX;
        item->conn.channel = 0;
        item->conn.frequency = 0;

        char operstate;
        ffStrbufSetF(&buffer, "/sys/class/net/%s/operstate", i->if_name);
        if (!ffReadFileData(buffer.chars, 1, &operstate)) {
            ffStrbufSetStatic(&item->inf.status, "unknown");
            ffStrbufSetStatic(&item->conn.status, "disconnected");
            continue;
        }

        if (operstate == 'u') {
            ffStrbufSetStatic(&item->inf.status, "up");

#if !__BIG_ENDIAN__
            detectWithNetlink(&nl, item, i->if_index);
#endif
            detectWithIoctl(&ic, item, i->if_name);
        } else {
            ffStrbufSetStatic(&item->conn.status, "disconnected");

            ffStrbufSetF(&buffer, "/sys/class/net/%s/flags", i->if_name);
            char flags[16];
            ssize_t len = ffReadFileData(buffer.chars, sizeof(flags) - 1, flags);
            if (len <= 0) {
                ffStrbufSetStatic(&item->inf.status, "unknown");
                continue;
            }
            flags[len] = '\0';

            unsigned flagsVal = (unsigned) strtoul(flags, NULL, 16); // parse /sys flags as hexadecimal
            if (flagsVal & IFF_UP) {
                ffStrbufSetStatic(&item->inf.status, "up");
            } else {
                ffStrbufSetStatic(&item->inf.status, "down");
            }
        }
    }

    if_freenameindex(infs);
#if !__BIG_ENDIAN__
    if (nl.sockFd >= 0) {
        close(nl.sockFd);
    }
#endif
    if (ic.sockFd >= 0) {
        close(ic.sockFd);
    }

    FF_DEBUG("Wifi detection completed, found %u wifi interfaces", result->length);
    return NULL;
}