Apple's open-source XNU kernel on Android phones: its own loader and drivers, Metal on the Adreno. Runs from RAM; a reboot gives the phone back to Android.
C
Wi-Fi: the phone joins a WPA2 network and iOS is on it through its own radio
vcvkk785d3bef0b7d
diff --git a/README.md b/README.mdindex 9e67f9a..e4cd1fa 100644--- a/README.md+++ b/README.md@@ -25,7 +25,7 @@| Работает | Не работает ||---|---|-| Экран блокировки, разблокировка свайпом, домашний экран с полным набором значков (две страницы), стандартные обои iOS 16 | Звук, сеть (Wi-Fi/сотовая), Bluetooth, камера |+| Экран блокировки, разблокировка свайпом, домашний экран с полным набором значков (две страницы), стандартные обои iOS 16 | Звук, сотовая сеть, Bluetooth, камера || Системные жесты: свайп снизу — «домой» и переключатель приложений, свайп от левого края — «назад», Пункт управления | Без `gpu=1` (программный рендер; в QEMU всегда) часы экрана блокировки просто белые, без «вибрации» под цвет обоев, и верх обоев под ними не затемнён || Запуск приложений: Настройки (вглубь), Часы, Календарь, Фото, Заметки и др.; расширения приложений (виджеты «Погода» и «Календарь» на домашнем экране рисуют своё содержимое — на телефоне; в QEMU им не хватает скорости) | Metal (приложения, рисующие через него сами); отрисовка самим Adreno есть, но пока опытная — см. «GPU» || Сенсорный экран телефона (Goodix GT9916), мультитач, пробуждение касанием | Без `cpus=N` работает одно ядро процессора |@@ -91,6 +91,16 @@ qemu/run-ios.sh 1200 -display gtk > logs/qemu.log # сеанс на 20 миходить на серверы Apple (в первые минуты около 30 МБ данных Карт), а приложения Apple — Погода, App Store,Подкасты — данных всё равно не получают: им нужна служба `fairplayd`, которой в образе нет. В НастройкахWi-Fi остаётся «Выкл.» (это не Wi-Fi). По умолчанию сети нет, и без `QEMU_NET=1` ничего не меняется.+- **Сеть по Wi-Fi телефона (опытно).** Радио телефона подключается к одной сети WPA2 с паролем, и iOS выходит+ через него в интернет: адрес по DHCP, DNS, HTTPS. Нужны прошивка радио в `fw-wifi/` (см. `wifi=N` в таблице+ параметров ядра), адрес радио одной строкой в `fw-wifi/mac` и файл `fw-wifi/network` — имя сети первой строкой,+ пароль второй (оба файла в git не попадают; `userland/build.sh` кладёт второй в малый образ, на командную+ строку ядра он не идёт, в журнал пишутся только длины). Затем `tools/mk-ath11k.sh`, `./xnu-build.sh`,+ `REST=1 userland/build.sh` и запуск с+ `XL_CMDLINE="-v bootcpu=7 wifi=15 wifi_lx=2 wifi_smmu=2 wifi_join=1 wifi_keep=1" ./xl run`. Интерфейс тот же+ `en0`, настроить его нужно так же, как в QEMU (`RC_JOBS=rc.jobs.net` это делает при загрузке). Чего нет:+ выбора сети и пароля в Настройках (там Wi-Fi по-прежнему «Выкл.»), WPA3, открытых сетей, каналов шире 20 МГц,+ экономии энергии; скорость — около 15 Мбит/с.- Несколько QEMU сразу: `QEMU_INSTANCE=1 qemu/run-ios.sh …` (у каждого номера свои порты; `touch.py`,`screendump.sh`, `stop.sh` понимают ту же переменную). `qemu/stop.sh` завершает QEMU досрочно.- Прошивка UEFI для aarch64 ищется там, куда её кладёт Arch. В Debian/Ubuntu (пакет `qemu-efi-aarch64`):@@ -163,7 +173,7 @@ XL_SECS=900 XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7 cpus=4" ./xl run #| `gpu=1` | рисовать графическим процессором телефона (образ с `GL=1`, прошивки в `fw-gpu/`; см. раздел «GPU»). Без него, без прошивок и в QEMU всё рисует программный рендер CoreAnimation || `virtio_net=1` | (QEMU; `QEMU_NET=1` добавляет его сам) сетевой интерфейс `en0` на сетевой карте virtio. `net_names=1` — писать в журнал каждое имя, которое система спрашивает у DNS, и каждое начатое TCP-соединение; `net_trace=N` — строка о каждом из первых N кадров || `adreno=N` | опыт с GPU телефона: первые N шагов его пробуждения (питание, такты, первые регистры), каждый шаг пишет в журнал, что собирается тронуть и что прочёл; шаги и остальные параметры описаны в начале `bsd/dev/redwood_adreno.c` |-| `wifi=N` | опыт с Wi-Fi телефона: первые N шагов. 1–5 только читают (общая память процессоров, почтовый ящик процессора питания, RPMh, шины питания, выводы), 6–11 кладут прошивку процессора Wi-Fi в его память, заводят в общей памяти нашу половину его сигнальных битов (SMP2P) и запускают его через TrustZone, 12–14 поднимают связь с ним (GLINK, канал IPCRTR) и QRTR поверх неё: процессор Wi-Fi объявляет свои службы, среди них службу прошивки Wi-Fi; 15 — разговор с этой службой, какой драйвер ведёт до того, как тронет радио (нужны описания сообщений из ath11k: `tools/mk-wlfw.sh`, затем пересобрать ядро): прошивка принимает сообщения ath11k, файл платы и базу регионов телефона, с `wifi_cal=1` калибруется и через 7 секунд говорит «готова»; с `wifi_mission=1` прошивка получает настройку и переходит в рабочий режим; 16 — чтение нескольких регистров радио (`wifi_radio_read=1`): в рабочем режиме они отвечают, вне его чтение кончается ошибкой шины, и шаг его не делает (`adb pull` файлов `wpss.mdt`, `wpss.b02`…`wpss.b07` из `/vendor/firmware_mnt/image` в каталог `fw-wifi/`; в git они не попадают, `userland/build.sh` кладёт их в малый образ). Каждый шаг пишет в журнал, что собирается тронуть и что прочёл. `wifi_keep=1` оставляет процессор Wi-Fi и связь с ним работать, пока идёт сеанс. С `wifi_lx=1` шаг 15 ведёт уже сам драйвер ath11k из Linux (см. «Драйвер Wi-Fi» ниже; ядро собирается после `tools/mk-ath11k.sh`): его `qmi.c` проходит весь разговор с прошивкой до рабочего режима, со своей настройкой и списком теневых регистров, а регистры радио не трогает. С `wifi_lx=2 wifi_smmu=2` потоку радио в SMMU даётся контекст с нашими таблицами страниц (`wifi_smmu=2` в одиночку — только это, с возвратом как было), `ce.c` и `hal.c` драйвера заводят в регистрах радио кольца его «копировальных машин», `htc.c` подключает по ним службу WMI, и прошивка по WMI рассказывает о радио (одно, две антенные цепи, 2,4 и 5 ГГц) и через четверть секунды после запуска шины сообщает, что готова к командам («unified ready»); собственного адреса у прошивки нет (нули). Прерываний при этом нет: кольца опрашиваются раз в миллисекунду. С `wifi_scan=1` драйвер после этого регистрирует радио, заводит интерфейс в режиме станции и просит прошивку просканировать эфир — только слушая, в эфир ничего не уходит: 26 каналов 2,4 и 5 ГГц за четыре секунды, и в журнале появляются точки доступа вокруг с каналами и уровнем сигнала (имена и адреса чужих сетей — только в журнале запуска на вашей машине). Адрес радио у прошивки свой не записан: он лежит одной строкой в `fw-wifi/mac` (в git не попадает), и `xl run` передаёт его ядру параметром `wifi_mac`. К сети драйвер пока не подключается (тракт данных не собран), после сканирования он в правильном порядке сворачивается: сети нет. Остановленный без спроса (ядро, которое до этого не дошло) второй раз без перезагрузки телефона не запускается — такой запуск сбрасывал телефон, и драйвер от него сам отказывается; шаги и остальные параметры описаны в начале `bsd/dev/redwood_wifi.c` |+| `wifi=N` | опыт с Wi-Fi телефона: первые N шагов. 1–5 только читают (общая память процессоров, почтовый ящик процессора питания, RPMh, шины питания, выводы), 6–11 кладут прошивку процессора Wi-Fi в его память, заводят в общей памяти нашу половину его сигнальных битов (SMP2P) и запускают его через TrustZone, 12–14 поднимают связь с ним (GLINK, канал IPCRTR) и QRTR поверх неё: процессор Wi-Fi объявляет свои службы, среди них службу прошивки Wi-Fi; 15 — разговор с этой службой, какой драйвер ведёт до того, как тронет радио (нужны описания сообщений из ath11k: `tools/mk-wlfw.sh`, затем пересобрать ядро): прошивка принимает сообщения ath11k, файл платы и базу регионов телефона, с `wifi_cal=1` калибруется и через 7 секунд говорит «готова»; с `wifi_mission=1` прошивка получает настройку и переходит в рабочий режим; 16 — чтение нескольких регистров радио (`wifi_radio_read=1`): в рабочем режиме они отвечают, вне его чтение кончается ошибкой шины, и шаг его не делает (`adb pull` файлов `wpss.mdt`, `wpss.b02`…`wpss.b07` из `/vendor/firmware_mnt/image` в каталог `fw-wifi/`; в git они не попадают, `userland/build.sh` кладёт их в малый образ). Каждый шаг пишет в журнал, что собирается тронуть и что прочёл. `wifi_keep=1` оставляет процессор Wi-Fi и связь с ним работать, пока идёт сеанс. С `wifi_lx=1` шаг 15 ведёт уже сам драйвер ath11k из Linux (см. «Драйвер Wi-Fi» ниже; ядро собирается после `tools/mk-ath11k.sh`): его `qmi.c` проходит весь разговор с прошивкой до рабочего режима, со своей настройкой и списком теневых регистров, а регистры радио не трогает. С `wifi_lx=2 wifi_smmu=2` потоку радио в SMMU даётся контекст с нашими таблицами страниц (`wifi_smmu=2` в одиночку — только это, с возвратом как было), `ce.c` и `hal.c` драйвера заводят в регистрах радио кольца его «копировальных машин», `htc.c` подключает по ним службу WMI, и прошивка по WMI рассказывает о радио (одно, две антенные цепи, 2,4 и 5 ГГц) и через четверть секунды после запуска шины сообщает, что готова к командам («unified ready»); собственного адреса у прошивки нет (нули). Прерываний при этом нет: кольца опрашиваются раз в миллисекунду. С `wifi_scan=1` драйвер после этого регистрирует радио, заводит интерфейс в режиме станции и просит прошивку просканировать эфир — только слушая, в эфир ничего не уходит: 26 каналов 2,4 и 5 ГГц за четыре секунды, и в журнале появляются точки доступа вокруг с каналами и уровнем сигнала (имена и адреса чужих сетей — только в журнале запуска на вашей машине). Адрес радио у прошивки свой не записан: он лежит одной строкой в `fw-wifi/mac` (в git не попадает), и `xl run` передаёт его ядру параметром `wifi_mac`. С `wifi_join=1` драйвер подключается к сети из `fw-wifi/network` (WPA2 с паролем): находит её точку доступа, проходит аутентификацию, ассоциацию и четырёхстороннее рукопожатие, отдаёт ключи прошивке и становится тем, что стоит за `en0`; с `wifi_keep=1` он остаётся работать, пока идёт сеанс, без него — сворачивается, когда шаги кончились (`wifi_hold=S` — на S секунд позже). Остановленный без спроса (ядро, которое до этого не дошло) второй раз без перезагрузки телефона не запускается — такой запуск сбрасывал телефон, и драйвер от него сам отказывается; шаги и остальные параметры описаны в начале `bsd/dev/redwood_wifi.c` |Несколько ядер на телефоне проверены (2, 4 и 7 ядер запускаются и чисто возвращаются в загрузчик). Лучшийвариант — **`cpus=4`**: четыре больших ядра (7, 6, 5, 4). На одном и том же сценарии: 929 кадров вместо 671,@@ -359,7 +369,7 @@ Userland не изменён ни в одном байте: всё, чего е| `mkpackfs.py` | сборщик образов packfs (формат описан в `bsd/miscfs/packfs/packfs.h` ядра) || `qemu/` | запуск в QEMU, касания, снимки экрана, разбор стеков || `uefi/`, `mkxnuimg.py` | порт UEFI на redwood и упаковка загрузочного образа для `fastboot boot` |-| `tools/` | `recording.py` (запись экрана → mp4), `update-prebuilt.sh`, `new-workspace.sh` (вторая рабочая копия со своим ядром и QEMU), `mk-zstddec.sh`, `mk-mesa.sh` (Mesa для `GL=1`), `mk-ath11k.sh` (драйвер Wi-Fi для ядра) |+| `tools/` | `recording.py` (запись экрана → mp4), `update-prebuilt.sh`, `new-workspace.sh` (вторая рабочая копия со своим ядром и QEMU), `mk-zstddec.sh`, `mk-mesa.sh` (Mesa для `GL=1`), `mk-ath11k.sh` (драйвер Wi-Fi для ядра), `qmi-test/` и `wpa-test/` (проверки на компьютере) || `wifi/lx/` | прослойка, на которой драйвер Wi-Fi из Linux собирается для нашего ядра (см. «Драйвер Wi-Fi») || `prebuilt/` | собранные ядро, загрузчик, наши программы и куски UEFI |@@ -386,16 +396,20 @@ Userland не изменён ни в одном байте: всё, чего ес которыми FreeBSD собирает драйверы Linux), сверяет контрольные суммы, накладывает `wifi/lx/patches/*.patch` назаголовки FreeBSD и компилирует файлы драйвера без единой правки, как код ядра FreeBSD. Чего заголовкам нехватает и всё, что под ними (блокировки, сон, очереди работ, таймеры, память для радио, буферы, файлы прошивки,-шина радио), — наше, в `wifi/lx/`, и стоит на без малого двух десятках вызовов, которые даёт ядро+шина радио), — наше, в `wifi/lx/`, и стоит на двух с небольшим десятках вызовов, которые даёт ядро(`bsd/sys/redwood_lx.h`, `bsd/dev/redwood_lx.c`). Получается один объектный файл`xnu-deps/build/ath11k/out/ath11k.o` с единственным видимым именем; `xnu-build.sh` линкует его в ядро, если онесть, а без него ядро собирается как раньше и на `wifi_lx` отвечает, что драйвера в нём нет.-Собрано пока одиннадцать файлов драйвера из трёх с лишним десятков (`core`, `hal`, `qmi`, `ce`, `hw`, `fw`, `htc`,-`wmi`, `mac`, `reg`, `peer`); над драйвером вместо mac80211 из Linux стоит наше начало станции-(`wifi/lx/src/lx_80211.c`): регистрация радио, регуляторный домен, один интерфейс и сканирование. Вызовы в-остальные — заглушки, которые пишут своё имя в журнал (список — `out/stubs.txt` после сборки). Что это уже-делает на телефоне, сказано в строке `wifi=N` таблицы параметров ядра.+Собрано восемнадцать файлов драйвера из трёх с лишним десятков — всё, что нужно станции (`core`, `hal`, `qmi`,+`ce`, `hw`, `fw`, `htc`, `wmi`, `mac`, `reg`, `peer`, `dp`, `dp_rx`, `dp_tx`, `hal_rx`, `hal_tx`, `dbring`,+`p2p`); заглушек не осталось (если появятся, их список — `out/stubs.txt` после сборки). Над драйвером вместо+mac80211 из Linux стоит наша станция (`wifi/lx/src/lx_80211.c`): регистрация радио, регуляторный домен, один+интерфейс, сканирование и подключение к сети WPA2 с паролем; арифметика рукопожатия — отдельно, в+`wifi/lx/src/lx_wpa.c`, и проверяется на компьютере (`tools/wpa-test/run.sh`: примеры из стандартов и целые+рукопожатия против точки доступа, написанной на Python). Прерываний радио драйвер не получает: кольца+опрашивает поток, раз в миллисекунду и сразу снова, пока есть работа. Что это делает на телефоне, сказано в+строке `wifi=N` таблицы параметров ядра.## Про файлы Apple и лицензииdiff --git a/tools/mk-ath11k.sh b/tools/mk-ath11k.shindex a806fa3..e087acd 100755--- a/tools/mk-ath11k.sh+++ b/tools/mk-ath11k.sh@@ -20,7 +20,7 @@# (out/stubs.txt lists them), unless wifi/lx/src has one that does more.## Everything is compiled as FreeBSD kernel code for an Apple arm64 kernel and tied into one-# object that shows nothing but its entry point; the kernel links it when it is there+# object that shows nothing but its entry points; the kernel links it when it is there# (xnu-build.sh).## VERSION of Linux. 7.0.14: LinuxKPI's 802.11 headers follow the mac80211 of Linux 7.0, and@@ -114,7 +114,7 @@ if [ ! -d gen ]; thenfi# --- compile: the driver's files that are built so far, and ours-DRIVER="core hal qmi ce hw fw htc wmi mac reg peer"+DRIVER="core hal qmi ce hw fw htc wmi mac reg peer dp dp_rx dp_tx hal_rx hal_tx dbring p2p"CC="clang -target arm64-apple-ios16.5"LD=$ROOT/xnu-deps/host/bin/ld64CFLAGS="-mkernel -mgeneral-regs-only -fno-builtin -fno-common -ffreestanding -fno-strict-aliasing@@ -177,8 +177,8 @@ for s in $(cat out/undefined.txt); dodone[ -z "$missing" ] || exit 1$CC -c out/stubs.s -o out/stubs.o-# one name is shown: where the kernel enters (lx_start() of redwood_lx.h)-echo _lx_start > out/exported.txt+# three names are shown: where the kernel enters (lx_start(), lx_stop() and lx_transmit() of redwood_lx.h)+printf '_lx_start\n_lx_stop\n_lx_transmit\n' > out/exported.txt$LD -r -arch arm64 -exported_symbols_list out/exported.txt out/all.o out/stubs.o -o out/ath11k.o 2> out/ld.err ||{ cat out/ld.err; exit 1; }rm -f out/all.odiff --git a/tools/wpa-test/reference.py b/tools/wpa-test/reference.pynew file mode 100755index 0000000..1a59641--- /dev/null+++ b/tools/wpa-test/reference.py@@ -0,0 +1,91 @@+#!/usr/bin/env python3+# The access point's side of the WPA2 handshake, written against Python's own hashlib and hmac+# and the AES key wrap of the "cryptography" package: an implementation that shares nothing with+# wifi/lx/src/lx_wpa.c. For a number of made-up networks it writes down, as C, the messages an+# access point would send and the answers a correct station gives, byte for byte; test_wpa.c+# has lx_wpa.c answer the same messages and compares. (IEEE 802.11-2020, 12.7.)+import hashlib+import hmac+import random+import struct+import sys++from cryptography.hazmat.primitives.keywrap import aes_key_wrap++rnd = random.Random(int(sys.argv[1]) if len(sys.argv) > 1 else 1)+++def prf(key, label, data, length):+ out = b''+ for i in range((length + 19) // 20):+ out += hmac.new(key, label + b'\0' + data + bytes([i]), hashlib.sha1).digest()+ return out[:length]+++def key_message(version, info, replay, nonce, rsc, data, kck):+ body = struct.pack('>BHH8s32s16s8s8s16sH', 2, info, 16 if info & 0x80 else 0, replay, nonce, bytes(16), rsc, bytes(8),+ bytes(16), len(data)) + data+ frame = bytearray(struct.pack('>BBH', version, 3, len(body)) + body)+ if kck is not None:+ frame[81:97] = hmac.new(kck, bytes(frame), hashlib.sha1).digest()[:16]+ return bytes(frame)+++def c_bytes(name, data):+ return 'static const unsigned char %s[] = { %s };\n' % (name, ', '.join('0x%02x' % b for b in data) or '0')+++def case(n):+ passphrase = bytes(rnd.choice(b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 !#') for _ in+ range(rnd.randint(8, 63)))+ name = bytes(rnd.randrange(32, 127) for _ in range(rnd.randint(1, 32)))+ ap, station = bytes([2] + [rnd.randrange(256) for _ in range(5)]), bytes([2] + [rnd.randrange(256) for _ in range(5)])+ anonce, snonce = rnd.randbytes(32), rnd.randbytes(32)+ rsn = bytes.fromhex('30140100000fac040100000fac040100000fac020000') # CCMP, CCMP, PSK, no capabilities+ group, group_index, group2 = rnd.randbytes(16), rnd.randint(1, 3), rnd.randbytes(16)+ version = rnd.choice([1, 2])+ counter = rnd.randrange(1 << 40)+ replay = lambda k: struct.pack('>Q', counter + k)++ pmk = hashlib.pbkdf2_hmac('sha1', passphrase, name, 4096, 32)+ ptk = prf(pmk, b'Pairwise key expansion', min(ap, station) + max(ap, station) + min(anonce, snonce) + max(anonce, snonce), 48)+ kck, kek, tk = ptk[:16], ptk[16:32], ptk[32:]++ def wrapped(key, index, before=b''):+ # the group key as a "key data encapsulation", padded to a multiple of eight bytes, wrapped with the KEK+ plain = before + bytes([0xdd, 6 + len(key), 0x00, 0x0f, 0xac, 1, index, 0]) + key+ if len(plain) % 8:+ plain += b'\xdd' + bytes(7 - len(plain) % 8)+ return aes_key_wrap(kek, plain)++ rsc = rnd.randbytes(6) + bytes(2)+ m1 = key_message(version, 0x008a, replay(0), anonce, bytes(8), b'', None)+ m2 = key_message(version, 0x010a, replay(0), snonce, bytes(8), rsn, kck)+ m3 = key_message(version, 0x13ca, replay(1), anonce, rsc, wrapped(group, group_index, rsn), kck)+ m4 = key_message(version, 0x030a, replay(1), bytes(32), bytes(8), b'', kck)+ g1 = key_message(version, 0x1382, replay(5), bytes(32), rsc, wrapped(group2, group_index % 3 + 1), kck)+ g2 = key_message(version, 0x0302, replay(5), bytes(32), bytes(8), b'', kck)+ # the same message 3 from an access point that was given another passphrase+ other = hashlib.pbkdf2_hmac('sha1', passphrase + b'x', name, 4096, 32)+ other_ptk = prf(other, b'Pairwise key expansion', min(ap, station) + max(ap, station) + min(anonce, snonce) + max(anonce, snonce), 48)+ m3_wrong = key_message(version, 0x13ca, replay(1), anonce, rsc, aes_key_wrap(other_ptk[16:32], bytes(24)), other_ptk[:16])++ text = ''.join(c_bytes('c%d_%s' % (n, k), v) for k, v in (+ ('passphrase', passphrase), ('name', name), ('ap', ap), ('station', station), ('snonce', snonce), ('rsn', rsn),+ ('pmk', pmk), ('tk', tk), ('group', group), ('group2', group2), ('m1', m1), ('m2', m2), ('m3', m3), ('m4', m4),+ ('g1', g1), ('g2', g2), ('m3_wrong', m3_wrong)))+ entry = '{ %s, %d }' % (', '.join('c%d_%s, sizeof(c%d_%s)' % (n, k, n, k) for k in (+ 'passphrase', 'name', 'ap', 'station', 'snonce', 'rsn', 'pmk', 'tk', 'group', 'group2', 'm1', 'm2', 'm3', 'm4', 'g1',+ 'g2', 'm3_wrong')), group_index)+ return text, entry+++count = 12+cases = [case(n) for n in range(count)]+print(''.join(t for t, _ in cases))+print('static const struct handshake handshakes[] = {\n\t%s\n};' % ',\n\t'.join(e for _, e in cases))++# two things for the pieces on their own, from the same independent implementations+key = bytes(range(32, 48))+print(c_bytes('prf_key', key) + c_bytes('prf_out', prf(key, b'A label', bytes(range(70)), 61)))+print(c_bytes('wrap_kek', key) + c_bytes('wrap_out', aes_key_wrap(key, bytes(range(100, 140)))))diff --git a/tools/wpa-test/run.sh b/tools/wpa-test/run.shnew file mode 100755index 0000000..725489b--- /dev/null+++ b/tools/wpa-test/run.sh@@ -0,0 +1,15 @@+#!/bin/bash+# Build and run the tests of the WPA2 handshake's arithmetic (wifi/lx/src/lx_wpa.c) on this+# machine, under the address and undefined-behaviour sanitizers. Needs Python 3 with the+# "cryptography" package: the access point the handshakes are held with is reference.py.+# usage: tools/wpa-test/run.sh [SEED] another seed, other made-up networks+set -e+HERE=$(cd "$(dirname "$(readlink -f "$0")")" && pwd)+ROOT=$(cd "$HERE/../.." && pwd)+B=$ROOT/xnu-deps/build/wpa-test+rm -rf "$B"+mkdir -p "$B"+"$HERE/reference.py" "${1:-1}" > "$B/cases.inc"+${CC:-cc} -std=gnu11 -O1 -g -Wall -Wextra -Werror -fsanitize=address,undefined -fno-sanitize-recover=all \+ -I"$B" -I"$ROOT/wifi/lx/src" -o "$B/test" "$HERE/test_wpa.c"+"$B/test"diff --git a/tools/wpa-test/test_wpa.c b/tools/wpa-test/test_wpa.cnew file mode 100644index 0000000..78356de--- /dev/null+++ b/tools/wpa-test/test_wpa.c@@ -0,0 +1,218 @@+/*+ * Tests of wifi/lx/src/lx_wpa.c on the machine the kernel is built on.+ *+ * Two kinds. The pieces against the examples their own standards give (they are quoted here with+ * where they are from). And whole handshakes against an access point written in Python on+ * implementations that share nothing with ours (reference.py: hashlib, hmac, the "cryptography"+ * package's AES key wrap): what a correct station answers is known there to the byte.+ */+#include <stdio.h>+#include <stdlib.h>++#include "lx_wpa.c"++static unsigned checks, failed;++static void+check(int good, const char *what, int n)+{+ checks++;+ if (!good) {+ failed++;+ printf("FAILED: %s (%d)\n", what, n);+ }+}++static int+hex_is(const unsigned char *bytes, unsigned length, const char *hex)+{+ for (unsigned i = 0; i < length; i++) {+ unsigned value;++ if (sscanf(hex + 2 * i, "%2x", &value) != 1 || value != bytes[i]) {+ return 0;+ }+ }+ return hex[2 * length] == 0;+}++struct handshake {+ const unsigned char *passphrase; size_t passphrase_length;+ const unsigned char *name; size_t name_length;+ const unsigned char *ap; size_t ap_length;+ const unsigned char *station; size_t station_length;+ const unsigned char *snonce; size_t snonce_length;+ const unsigned char *rsn; size_t rsn_length;+ const unsigned char *pmk; size_t pmk_length;+ const unsigned char *tk; size_t tk_length;+ const unsigned char *group; size_t group_length;+ const unsigned char *group2; size_t group2_length;+ const unsigned char *m1; size_t m1_length;+ const unsigned char *m2; size_t m2_length;+ const unsigned char *m3; size_t m3_length;+ const unsigned char *m4; size_t m4_length;+ const unsigned char *g1; size_t g1_length;+ const unsigned char *g2; size_t g2_length;+ const unsigned char *m3_wrong; size_t m3_wrong_length;+ unsigned group_index;+};++#include "cases.inc"++static void+pieces(void)+{+ unsigned char digest[20], pmk[32], out[80], block[16], round_keys[176];+ struct sha1 s;++ /* FIPS 180-4, the two examples of SHA-1 */+ sha1_begin(&s);+ sha1_more(&s, (const unsigned char *)"abc", 3);+ sha1_end(&s, digest);+ check(hex_is(digest, 20, "a9993e364706816aba3e25717850c26c9cd0d89d"), "SHA-1 of \"abc\"", 0);+ sha1_begin(&s);+ sha1_more(&s, (const unsigned char *)"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", 56);+ sha1_end(&s, digest);+ check(hex_is(digest, 20, "84983e441c3bd26ebaae4aa1f95129e5e54670f1"), "SHA-1 of the 56-byte example", 0);++ /* RFC 2202, HMAC-SHA1 test cases 1, 2 and 6 (a key longer than a block) */+ {+ unsigned char key[80];+ const unsigned char *one[1];+ unsigned length[1];++ memset(key, 0x0b, 20);+ one[0] = (const unsigned char *)"Hi There";+ length[0] = 8;+ hmac_sha1(key, 20, one, length, 1, digest);+ check(hex_is(digest, 20, "b617318655057264e28bc0b6fb378c8ef146be00"), "HMAC-SHA1, RFC 2202 case 1", 0);+ one[0] = (const unsigned char *)"what do ya want for nothing?";+ length[0] = 28;+ hmac_sha1((const unsigned char *)"Jefe", 4, one, length, 1, digest);+ check(hex_is(digest, 20, "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79"), "HMAC-SHA1, RFC 2202 case 2", 0);+ memset(key, 0xaa, 80);+ one[0] = (const unsigned char *)"Test Using Larger Than Block-Size Key - Hash Key First";+ length[0] = 54;+ hmac_sha1(key, 80, one, length, 1, digest);+ check(hex_is(digest, 20, "aa4ae5e15272d00e95705637ce8a3b55ed402112"), "HMAC-SHA1, RFC 2202 case 6", 0);+ }++ /* IEEE 802.11-2020, J.4.2: the three examples of a passphrase's key */+ lx_wpa_pmk((const unsigned char *)"password", 8, (const unsigned char *)"IEEE", 4, pmk);+ check(hex_is(pmk, 32, "f42c6fc52df0ebef9ebb4b90b38a5f902e83fe1b135a70e23aed762e9710a12e"), "PMK, J.4.2 example 1", 0);+ lx_wpa_pmk((const unsigned char *)"ThisIsAPassword", 15, (const unsigned char *)"ThisIsASSID", 11, pmk);+ check(hex_is(pmk, 32, "0dc0d6eb90555ed6419756b9a15ec3e3209b63df707dd508d14581f8982721af"), "PMK, J.4.2 example 2", 0);+ lx_wpa_pmk((const unsigned char *)"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 32, (const unsigned char *)"ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ", 32,+ pmk);+ check(hex_is(pmk, 32, "becb93866bb8c3832cb777c2f559807c8c59afcb6eae734885001300a981cc62"), "PMK, J.4.2 example 3", 0);++ /* FIPS 197, C.1: the example of AES-128, backwards */+ {+ static const unsigned char key[16] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };+ static const unsigned char cipher[16] = { 0x69, 0xc4, 0xe0, 0xd8, 0x6a, 0x7b, 0x04, 0x30, 0xd8, 0xcd, 0xb7, 0x80, 0x70, 0xb4,+ 0xc5, 0x5a };+ /* RFC 3394, 4.1: 128 bits of key data wrapped with a 128-bit key */+ static const unsigned char wrapped[24] = { 0x1f, 0xa6, 0x8b, 0x0a, 0x81, 0x12, 0xb4, 0x47, 0xae, 0xf3, 0x4b, 0xd8, 0xfb,+ 0x5a, 0x7b, 0x82, 0x9d, 0x3e, 0x86, 0x23, 0x71, 0xd2, 0xcf, 0xe5 };+ unsigned char spoiled[24];++ aes_keys(key, round_keys);+ check(hex_is(round_keys + 160, 16, "13111d7fe3944a17f307a78b4d2b30c5"), "AES-128 key schedule, FIPS 197 C.1: the last "+ "round key", 0);+ memcpy(block, cipher, 16);+ aes_decrypt(round_keys, block);+ check(hex_is(block, 16, "00112233445566778899aabbccddeeff"), "AES-128 decryption, FIPS 197 C.1", 0);+ check(aes_unwrap(key, wrapped, 24, out) == 0 && hex_is(out, 16, "00112233445566778899aabbccddeeff"),+ "AES key unwrap, RFC 3394 4.1", 0);+ memcpy(spoiled, wrapped, 24);+ spoiled[17] ^= 1;+ check(aes_unwrap(key, spoiled, 24, out) != 0, "AES key unwrap of spoiled data is refused", 0);+ check(aes_unwrap(key, wrapped, 20, out) != 0, "AES key unwrap of a wrong length is refused", 0);+ }++ /* the PRF and a longer unwrap against the independent implementations */+ {+ unsigned char data[70], plain[40];++ for (unsigned i = 0; i < 70; i++) {+ data[i] = (unsigned char)i;+ }+ prf(prf_key, sizeof(prf_key), "A label", data, 70, out, 61);+ check(memcmp(out, prf_out, 61) == 0, "the PRF, 61 bytes, against Python's hmac", 0);+ check(aes_unwrap(wrap_kek, wrap_out, sizeof(wrap_out), plain) == 0 && plain[0] == 100 && plain[39] == 139,+ "AES key unwrap of 40 bytes against \"cryptography\"", 0);+ }+}++static void+whole(void)+{+ for (unsigned n = 0; n < sizeof(handshakes) / sizeof(handshakes[0]); n++) {+ const struct handshake *h = &handshakes[n];+ unsigned char reply[LX_WPA_REPLY_MOST], spoiled[MESSAGE_MOST];+ unsigned length = 0;+ const char *why = NULL;+ struct lx_wpa wpa;++ memset(&wpa, 0, sizeof(wpa));+ lx_wpa_pmk(h->passphrase, (unsigned)h->passphrase_length, h->name, (unsigned)h->name_length, wpa.pmk);+ check(memcmp(wpa.pmk, h->pmk, 32) == 0, "the PMK against Python's pbkdf2_hmac", (int)n);+ memcpy(wpa.own, h->station, 6);+ memcpy(wpa.peer, h->ap, 6);+ memcpy(wpa.own_nonce, h->snonce, 32);+ wpa.rsn = h->rsn;+ wpa.rsn_length = (unsigned)h->rsn_length;++ /* a signed message before any message 1 */+ check(lx_wpa_message(&wpa, h->m3, (unsigned)h->m3_length, reply, &length, &why) == LX_WPA_BAD, "message 3 first is refused",+ (int)n);+ check(lx_wpa_message(&wpa, h->m1, (unsigned)h->m1_length, reply, &length, &why) == LX_WPA_ANSWER &&+ length == h->m2_length && memcmp(reply, h->m2, length) == 0, "message 2 is the reference's", (int)n);+ check(memcmp(wpa.pairwise, h->tk, 16) == 0, "the pairwise key is the reference's", (int)n);++ /* message 3 from an access point with another passphrase, and one with a bit turned */+ check(lx_wpa_message(&wpa, h->m3_wrong, (unsigned)h->m3_wrong_length, reply, &length, &why) == LX_WPA_BAD &&+ length == 0, "message 3 under another passphrase is refused", (int)n);+ memcpy(spoiled, h->m3, h->m3_length);+ spoiled[AT_DATA + 3] ^= 0x40;+ check(lx_wpa_message(&wpa, spoiled, (unsigned)h->m3_length, reply, &length, &why) == LX_WPA_BAD,+ "message 3 with a bit turned is refused", (int)n);++ check(lx_wpa_message(&wpa, h->m3, (unsigned)h->m3_length, reply, &length, &why) == LX_WPA_KEYS &&+ length == h->m4_length && memcmp(reply, h->m4, length) == 0, "message 4 is the reference's", (int)n);+ check(wpa.group_length == 16 && memcmp(wpa.group, h->group, 16) == 0 && wpa.group_index == h->group_index,+ "the group key and its number are the reference's", (int)n);+ check(memcmp(wpa.group_counter, h->m3 + AT_RSC, 8) == 0, "the group key's packet number is message 3's", (int)n);++ /* message 3 once more: played again */+ check(lx_wpa_message(&wpa, h->m3, (unsigned)h->m3_length, reply, &length, &why) == LX_WPA_BAD,+ "message 3 played again is refused", (int)n);++ /* a new group key later */+ check(lx_wpa_message(&wpa, h->g1, (unsigned)h->g1_length, reply, &length, &why) == LX_WPA_GROUP &&+ length == h->g2_length && memcmp(reply, h->g2, length) == 0, "the answer to a new group key is the reference's",+ (int)n);+ check(memcmp(wpa.group, h->group2, 16) == 0 && wpa.group_index == h->group_index % 3 + 1,+ "the new group key and its number are the reference's", (int)n);++ /* a network that wants another kind of key management says so in the descriptor's version */+ memcpy(spoiled, h->m1, h->m1_length);+ spoiled[AT_INFO + 1] = (unsigned char)((spoiled[AT_INFO + 1] & ~7) | 3);+ check(lx_wpa_message(&wpa, spoiled, (unsigned)h->m1_length, reply, &length, &why) == LX_WPA_BAD && why[0] != 0,+ "a key descriptor of version 3 is refused, with a reason", (int)n);++ /* things that are not key messages, and ones cut short */+ check(lx_wpa_message(&wpa, (const unsigned char *)"\x02\x00\x00\x00", 4, reply, &length, &why) == LX_WPA_NOTHING,+ "an EAPOL frame that is not a key message is left alone", (int)n);+ check(lx_wpa_message(&wpa, h->m1, 60, reply, &length, &why) == LX_WPA_BAD, "a key message cut short is refused", (int)n);+ }+}++int+main(void)+{+ pieces();+ whole();+ printf("%u checks, %u failed\n", checks, failed);+ return failed != 0;+}diff --git a/userland/build.sh b/userland/build.shindex 288b982..7e9794a 100755--- a/userland/build.sh+++ b/userland/build.sh@@ -174,6 +174,10 @@ if [ -f ../fw-wifi/wpss.mdt ]; thenfor f in bd_m20gl.elf regdb_xiaomi.bin; do[ -f ../fw-wifi/qca6750/$f ] && install -m 0644 ../fw-wifi/qca6750/$f root/fw/done+ # the network the radio is to join: its name on the first line, its passphrase on the second. Yours, and+ # so not in the repository; it goes where the firmware goes and the kernel reads it there (wifi_join=1)+ rm -f root/fw/network+ [ -f ../fw-wifi/network ] && install -m 0600 ../fw-wifi/network root/fw/networkfi../mkpackfs.py -o root.packfs rootdiff --git a/wifi/lx/src/lx.h b/wifi/lx/src/lx.hindex 8667c35..bc52286 100644--- a/wifi/lx/src/lx.h+++ b/wifi/lx/src/lx.h@@ -8,5 +8,9 @@ long lx_stub(const char *name); /* lx_base.c: what a function that is not therevoid lx_pause_ms(unsigned ms); /* lx_base.c: sleep */void lx_mark(const char *what); /* lx_base.c: a point reached, said and waited at if the kernel was asked to */int lx_station_scan(void); /* lx_80211.c: an interface in station mode, a scan, what was heard; 0, or an errno */+int lx_station_join(void); /* lx_80211.c: join the network the kernel was given; 0 when frames can pass */+void lx_station_say(void); /* lx_80211.c: what has passed since */+void lx_station_leave(void); /* lx_80211.c: leave it, and the interface down */+int lx_station_send(const unsigned char *frame, unsigned long length); /* lx_80211.c: an Ethernet frame for the network */#endifdiff --git a/wifi/lx/src/lx_80211.c b/wifi/lx/src/lx_80211.cindex 6f3a560..c8213a1 100644--- a/wifi/lx/src/lx_80211.c+++ b/wifi/lx/src/lx_80211.c@@ -2,18 +2,26 @@* Where the driver meets 802.11 itself: under Linux that is mac80211 and cfg80211, under FreeBSD* LinuxKPI's stand-in for them on top of net80211, and here it is ours -- the functions that* LinuxKPI's headers (net/mac80211.h, net/cfg80211.h) declare under linuxkpi_ names, as far as- * the files of the driver that are built call them, and the beginning of a station: the layer- * that asks the driver for things, in mac80211's order (FreeBSD's linux_80211.c shows it).+ * the driver calls them, and a station: the layer that asks the driver for things, in+ * mac80211's order (FreeBSD's linux_80211.c shows it).** What is here: the radio as the driver describes it when it registers; the regulatory domain* the driver hands over, applied to the radio's channels the way cfg80211 applies it; one- * interface in station mode; a scan of every channel the domain allows, which only listens;- * and what the radio then hears -- beacons and answers to others' probes --, kept by sender- * and said when the scan is over. Nothing joins a network yet, and nothing is sent.+ * interface in station mode; a scan of every channel the domain allows; and the joining of one+ * network that is protected with WPA2 and a passphrase -- found by its name, authenticated to+ * (open system), associated with, the keys agreed in the four-way handshake (lx_wpa.c) and+ * given to the driver --, after which Ethernet frames pass between the kernel and the driver+ * (the firmware puts them into 802.11 and ciphers them: the driver's "frame mode" Ethernet).*- * On the phone, 13 October, this scans: 26 channels in 4.1 s, and the access points around are- * heard with their channels and strengths (bsd/dev/redwood_wifi.c, step_driver(), has the- * account). What is said of them names other people's networks: it is for the log of the run.+ * What is not: more than one network, roaming, power saving, 40 MHz and wider channels, HE,+ * protected management frames, and the check of the packet numbers of the group's frames that+ * the driver leaves to this layer.+ *+ * On the phone, 13 October, this scans -- 26 channels in 4.1 s, the access points around heard+ * with their channels and strengths -- and joins: the handshake is through 130 ms after the+ * association, and iOS has the network (bsd/dev/redwood_wifi.c, step_driver(), has the+ * account). What is said of other people's networks names them: it is for the log of the run.+ * The name of the network to join and its passphrase are never said, only their lengths.*/#include <linux/kernel.h>#include <linux/etherdevice.h>@@ -25,10 +33,12 @@#include <lx_os.h>#include "lx.h"+#include "lx_wpa.h"int linuxkpi_debug_80211; /* (which of the headers' own remarks are printed: none) */#define HEARD_MOST 160+#define ELEMENTS_MOST 768/* A network, as its beacons describe it. */struct lx_heard {@@ -42,6 +52,19 @@ struct lx_heard {unsigned times;};+/* The access point of the wanted network that was heard best, with all it says of itself. */+struct lx_target {+ bool found;+ uint8_t address[ETH_ALEN];+ uint16_t frequency, capability, interval;+ int8_t signal;+ unsigned elements_length;+ uint8_t elements[ELEMENTS_MOST];+};++/* What a management frame from the access point has answered (join() waits for these). */+enum { ANSWER_NONE, ANSWER_AUTHENTICATED, ANSWER_ASSOCIATED, ANSWER_REFUSED, ANSWER_GONE };+/* A radio: what stands behind the driver's "hw" and "wiphy". There is one. */struct lx_radio {void *memory; /* all of this was allocated as one piece, which begins here */@@ -54,10 +77,35 @@ struct lx_radio {struct workqueue_struct *work; /* for what the driver has "the stack" run for it */struct linuxkpi_ieee80211_regdomain *regd;struct ieee80211_vif *vif; /* the one interface, while it is up */+ void *vif_memory;+ bool started;++ /* a scan */volatile int scan; /* 0: none, 1: running, 2: over, 3: given up by the driver */unsigned frames, others; /* received in all, and of them neither beacon nor probe response */unsigned heard_count, heard_lost;struct lx_heard heard[HEARD_MOST];+ uint8_t want[32], want_length; /* the name of the network that is wanted ... */+ struct lx_target target; /* ... and the best of it */++ /* the network joined */+ struct ieee80211_sta *sta; /* its access point, as the driver knows it */+ void *sta_memory;+ struct ieee80211_chanctx_conf *channel;+ struct cfg80211_bss bss; /* what the driver may ask of the access point's beacon */+ struct cfg80211_bss_ies bss_elements;+ volatile int answer;+ uint16_t answer_status, aid;+ unsigned answer_length;+ uint8_t answer_elements[ELEMENTS_MOST]; /* of the association response */+ uint8_t rsn[24]; /* our RSN element, as the association request has it */+ struct lx_wpa wpa;+ volatile int handshake; /* the last thing lx_wpa_message() said */+ const char *handshake_why;+ struct work_struct group_work; /* a new group key, later on */+ struct ieee80211_key_conf *pairwise_key, *group_key;+ volatile bool joined; /* keys set: frames pass */+ unsigned sent, sent_lost, received, received_group, eapol;};static struct lx_radio *the_radio;@@ -293,6 +341,12 @@ channel_of(unsigned frequency)(frequency - 5950) / 5);}+uint32_t+linuxkpi_ieee80211_frequency_to_channel(uint32_t frequency, uint32_t flags)+{+ return (channel_of(frequency));+}+/* The channel of that frequency among those the radio was registered with. */struct linuxkpi_ieee80211_channel *linuxkpi_ieee80211_get_channel(struct wiphy *wiphy, uint32_t frequency)@@ -347,23 +401,42 @@ linuxkpi_ieee80211_iterate_chan_contexts(struct ieee80211_hw *hw,{}+/* The one station there can be: the access point of the network being joined. */struct ieee80211_sta *linuxkpi_ieee80211_find_sta(struct ieee80211_vif *vif, const u8 *address){- return (NULL);+ struct lx_radio *radio = the_radio;++ return (radio != NULL && radio->sta != NULL && memcmp(radio->sta->addr, address, ETH_ALEN) == 0 ? radio->sta : NULL);}struct ieee80211_sta *linuxkpi_ieee80211_find_sta_by_ifaddr(struct ieee80211_hw *hw, const uint8_t *address, const uint8_t *own){- return (NULL);+ struct lx_radio *radio = radio_of(hw);++ return (radio->sta != NULL && memcmp(radio->sta->addr, address, ETH_ALEN) == 0 ? radio->sta : NULL);}+/*+ * What a scan has learnt of an access point. The driver asks this of the one it is associating+ * with, to see whether that announces RSN: it then tells the firmware to let nothing but the+ * handshake through until the keys are set (mac.c: ath11k_peer_assoc_h_crypto()).+ */struct cfg80211_bss *linuxkpi_cfg80211_get_bss(struct wiphy *wiphy, struct linuxkpi_ieee80211_channel *channel, const uint8_t *bssid,const uint8_t *ssid, size_t ssid_length, enum ieee80211_bss_type type, enum ieee80211_privacy privacy){- return (NULL);+ struct lx_radio *radio = (struct lx_radio *)wiphy->priv;++ if (!radio->target.found || bssid == NULL || memcmp(radio->target.address, bssid, ETH_ALEN) != 0) {+ return (NULL);+ }+ radio->bss_elements.data = radio->target.elements;+ radio->bss_elements.len = radio->target.elements_length;+ radio->bss.ies = radio->bss.beacon_ies = &radio->bss_elements;+ radio->bss.signal = radio->target.signal * 100;+ return (&radio->bss);}void@@ -393,6 +466,14 @@ linuxkpi_ieee80211_tx_status(struct ieee80211_hw *hw, struct sk_buff *skb)dev_kfree_skb_any(skb);}+void+linuxkpi_ieee80211_tx_status_ext(struct ieee80211_hw *hw, struct ieee80211_tx_status *status)+{+ if (status->skb != NULL) {+ dev_kfree_skb_any(status->skb);+ }+}+voidlinuxkpi_ieee80211_free_txskb(struct ieee80211_hw *hw, struct sk_buff *skb, int status){@@ -417,21 +498,62 @@ linuxkpi_ieee80211_restart_hw(struct ieee80211_hw *hw){}+/* ---- elements --------------------------------------------------------------------------------------- */++/* The element of that number among `length` bytes of elements (number, length, contents; one after another), or NULL. */+static const uint8_t *+element(const uint8_t *elements, unsigned length, unsigned number)+{+ for (unsigned at = 0; at + 2 <= length && at + 2 + elements[at + 1] <= length; at += 2 + elements[at + 1]) {+ if (elements[at] == number) {+ return (elements + at);+ }+ }+ return (NULL);+}++/* A vendor's element (221) that begins with these four bytes. */+static const uint8_t *+vendor_element(const uint8_t *elements, unsigned length, const uint8_t *begins)+{+ for (unsigned at = 0; at + 2 <= length && at + 2 + elements[at + 1] <= length; at += 2 + elements[at + 1]) {+ if (elements[at] == 221 && elements[at + 1] >= 4 && memcmp(elements + at + 2, begins, 4) == 0) {+ return (elements + at);+ }+ }+ return (NULL);+}++static const uint8_t wmm[4] = { 0x00, 0x50, 0xf2, 0x02 }; /* Microsoft's, which is how WMM is announced */+/* ---- what the radio hears -------------------------------------------------------------------------- *//** A beacon or an answer to a probe (IEEE 802.11-2020, 9.3.3): after the 24 bytes every* management frame begins with -- the sender's network is the third address -- a time stamp, the* beacon interval, the capabilities, and then elements, of which the name (0), the channel the- * sender says it is on (3) and whether it announces RSN (48) are taken.+ * sender says it is on (3) and whether it announces RSN (48) are taken. Of the network that is+ * wanted, the access point heard best is kept whole.*/static voidheard(struct lx_radio *radio, const uint8_t *frame, unsigned length, unsigned frequency, int signal){struct lx_heard *network = NULL;- const uint8_t *element = frame + 36, *end = frame + length;+ const uint8_t *elements = frame + 36, *name = element(elements, length - 36, 0);lx_os_lock();+ if (name != NULL && radio->want_length != 0 && name[1] == radio->want_length &&+ memcmp(name + 2, radio->want, radio->want_length) == 0 && (!radio->target.found || signal > radio->target.signal) &&+ length - 36 <= ELEMENTS_MOST && radio->sta == NULL) {+ radio->target.found = true;+ memcpy(radio->target.address, frame + 16, ETH_ALEN);+ radio->target.frequency = (uint16_t)frequency;+ radio->target.interval = (uint16_t)(frame[32] | frame[33] << 8);+ radio->target.capability = (uint16_t)(frame[34] | frame[35] << 8);+ radio->target.signal = (int8_t)signal;+ radio->target.elements_length = length - 36;+ memcpy(radio->target.elements, elements, length - 36);+ }for (unsigned i = 0; i < radio->heard_count && network == NULL; i++) {if (memcmp(radio->heard[i].sender, frame + 16, ETH_ALEN) == 0) {network = &radio->heard[i];@@ -454,35 +576,15 @@ heard(struct lx_radio *radio, const uint8_t *frame, unsigned length, unsigned frnetwork->signal = (int8_t)signal;network->frequency = (uint16_t)frequency;}- for (; element + 2 <= end && element + 2 + element[1] <= end; element += 2 + element[1]) {- if (element[0] == 0 && element[1] <= sizeof(network->name) && (element[1] != 0 || network->name_length == 0)) {- network->name_length = element[1];- memcpy(network->name, element + 2, element[1]);- } else if (element[0] == 3 && element[1] == 1) {- network->says_channel = element[2];- } else if (element[0] == 48) {- network->protected = true;- }+ if (name != NULL && name[1] <= sizeof(network->name) && (name[1] != 0 || network->name_length == 0)) {+ network->name_length = name[1];+ memcpy(network->name, name + 2, name[1]);}- lx_os_unlock();-}--/* A frame the radio has received (the driver has its description behind it: where and how strong). */-void-linuxkpi_ieee80211_rx(struct ieee80211_hw *hw, struct sk_buff *skb, struct ieee80211_sta *sta, struct napi_struct *napi,- struct list_head *list)-{- struct lx_radio *radio = radio_of(hw);- const struct ieee80211_rx_status *status = IEEE80211_SKB_RXCB(skb);-- radio->frames++;- /* (the first byte: 0x80 a beacon, 0x50 an answer to a probe) */- if (skb->len >= 36 && (skb->data[0] == 0x80 || skb->data[0] == 0x50)) {- heard(radio, skb->data, skb->len, status->freq, status->signal);- } else {- radio->others++;+ if (element(elements, length - 36, 3) != NULL && element(elements, length - 36, 3)[1] == 1) {+ network->says_channel = element(elements, length - 36, 3)[2];}- dev_kfree_skb_any(skb);+ network->protected = element(elements, length - 36, 48) != NULL;+ lx_os_unlock();}/* The driver's word that the scan it was asked for is over. */@@ -510,6 +612,7 @@ say_heard(struct lx_radio *radio)const struct lx_heard *network = NULL;char name[33];unsigned which = 0, channel;+ bool wanted;for (unsigned i = 0; i < radio->heard_count; i++) {if (!said[i] && (network == NULL || radio->heard[i].signal > network->signal)) {@@ -531,10 +634,13 @@ say_heard(struct lx_radio *radio)nameless += network->name_length == 0 || network->name[0] == 0;strongest = network->signal > strongest ? network->signal : strongest;weakest = network->signal < weakest ? network->signal : weakest;+ /* (the network that is wanted is the user's own: its name is not said even here) */+ wanted = radio->want_length != 0 && network->name_length == radio->want_length &&+ memcmp(network->name, radio->want, radio->want_length) == 0;printf("lx: heard: channel %3u (%u MHz) %4d dBm %02x:%02x:%02x:%02x:%02x:%02x %s, %u times \"%s\"\n", channel,network->frequency, network->signal, network->sender[0], network->sender[1], network->sender[2], network->sender[3],network->sender[4], network->sender[5], !(network->capability & 0x10) ? "open" : network->protected ? "RSN" :- "protected", network->times, name);+ "protected", network->times, wanted ? "(the network that is wanted)" : name);}for (unsigned channel = 0; channel < nitems(on_channel); channel++) {if (on_channel[channel] != 0) {@@ -547,68 +653,310 @@ say_heard(struct lx_radio *radio)radio->frames, radio->others, radio->heard_lost ? "; MORE WERE HEARD THAN THERE WAS ROOM FOR" : "");}-/* ---- the station ------------------------------------------------------------------------------------ */+/* ---- frames ------------------------------------------------------------------------------------------ */++/* A frame for the driver to send: `length` bytes at the returned place, in a buffer the radio can read. */+static struct sk_buff *+frame_new(struct lx_radio *radio, unsigned length, uint8_t **bytes)+{+ struct sk_buff *skb = dev_alloc_skb(length + 256);+ struct ieee80211_tx_info *info;++ if (skb == NULL) {+ return (NULL);+ }+ skb_reserve(skb, 128); /* (room in front for what the driver puts there) */+ *bytes = skb_put(skb, length);+ info = IEEE80211_SKB_CB(skb);+ bzero(info, sizeof(*info));+ info->control.vif = radio->vif;+ info->band = radio->channel != NULL ? radio->channel->def.chan->band : NL80211_BAND_2GHZ;+ return (skb);+}++static void+frame_send(struct lx_radio *radio, struct sk_buff *skb)+{+ struct ieee80211_tx_control control = { .sta = radio->sta };++ radio->ops->tx(&radio->hw, &control, skb);+}++/* The 24 bytes a management frame to the access point begins with (the kind: 0xb0 authentication, 0x00 association request, ...). */+static uint8_t *+management(struct lx_radio *radio, uint8_t *frame, unsigned kind)+{+ bzero(frame, 24);+ frame[0] = (uint8_t)kind;+ memcpy(frame + 4, radio->target.address, ETH_ALEN);+ memcpy(frame + 10, radio->vif->addr, ETH_ALEN);+ memcpy(frame + 16, radio->target.address, ETH_ALEN);+ return (frame + 24);+}++/* An Ethernet frame, through the driver's data path: the firmware makes 802.11 of it, and ciphers it once there is a key. */+static bool+ethernet_send(struct lx_radio *radio, const uint8_t *frame, unsigned length)+{+ struct sk_buff *skb;+ uint8_t *bytes;++ if (radio->vif == NULL || radio->sta == NULL || (skb = frame_new(radio, length, &bytes)) == NULL) {+ radio->sent_lost++;+ return (false);+ }+ memcpy(bytes, frame, length);+ IEEE80211_SKB_CB(skb)->flags |= IEEE80211_TX_CTL_HW_80211_ENCAP;+ IEEE80211_SKB_CB(skb)->control.hw_key = radio->pairwise_key;+ radio->sent++;+ frame_send(radio, skb);+ return (true);+}/*- * What mac80211 does when an interface in station mode is brought up and asked to scan, as far- * as the driver is concerned: the radio is started, the interface added to it, and a scan- * requested of every channel the regulatory domain allows, with no name to ask for -- which- * makes it a scan that only listens (mac.c: ath11k_mac_op_hw_scan()). When the driver says the- * scan is over, what was heard is said, and the interface and the radio are taken down again.- * 0, or an errno.+ * An 802.11 data frame made into the Ethernet frame it carries, in place: the driver hands two+ * kinds over in 802.11 although the firmware had them as Ethernet -- the handshake's, and what+ * was sent to everybody and deciphered (dp_rx.c: ath11k_dp_rx_h_undecap()). The header is 24+ * bytes, more with a fourth address, the QoS field, the HT field and, if the driver left it+ * there, the cipher's 8 bytes; then 8 bytes of LLC and SNAP whose last two are the type.*/-int-lx_station_scan(void)+static bool+to_ethernet(struct sk_buff *skb, bool cipher_header_gone){- struct lx_radio *radio = the_radio;- struct ieee80211_scan_request *request;+ const uint8_t *f = skb->data;+ unsigned control = f[0] | f[1] << 8, header = 24;+ uint8_t to[ETH_ALEN], from[ETH_ALEN], type[2], *e;++ if ((control & 0x000c) != 0x0008 || skb->len < 32) {+ return (false);+ }+ memcpy(to, control & 0x0100 ? f + 16 : f + 4, ETH_ALEN);+ memcpy(from, (control & 0x0300) == 0x0300 ? f + 24 : control & 0x0200 ? f + 16 : f + 10, ETH_ALEN);+ header += (control & 0x0300) == 0x0300 ? 6 : 0;+ header += control & 0x0080 ? 2 : 0;+ header += (control & 0x8080) == 0x8080 ? 4 : 0;+ header += (control & 0x4000) && !cipher_header_gone ? 8 : 0;+ if (skb->len < header + 8 || f[header] != 0xaa || f[header + 1] != 0xaa || f[header + 2] != 0x03) {+ return (false);+ }+ memcpy(type, f + header + 6, 2);+ e = skb_pull(skb, header + 8 - 14);+ memcpy(e, to, ETH_ALEN);+ memcpy(e + 6, from, ETH_ALEN);+ memcpy(e + 12, type, 2);+ return (true);+}++/* A message of the handshake from the access point: answered at once; the keys are for join() to give to the driver. */+static void+handshake_message(struct lx_radio *radio, const uint8_t *frame, unsigned length)+{+ uint8_t reply[14 + LX_WPA_REPLY_MOST];+ unsigned reply_length = 0;+ const char *why = "";+ int said;++ radio->eapol++;+ if (radio->sta == NULL || memcmp(frame + 6, radio->target.address, ETH_ALEN) != 0) {+ return;+ }+ said = lx_wpa_message(&radio->wpa, frame + 14, length - 14, reply + 14, &reply_length, &why);+ if (reply_length != 0) {+ memcpy(reply, radio->target.address, ETH_ALEN);+ memcpy(reply + 6, radio->vif->addr, ETH_ALEN);+ reply[12] = 0x88;+ reply[13] = 0x8e;+ ethernet_send(radio, reply, 14 + reply_length);+ }+ printf("lx: the handshake: a message of %u bytes from the access point: %s%s\n", length - 14, said == LX_WPA_ANSWER ?+ "its first; answered with ours (message 2)" : said == LX_WPA_KEYS ? "its second, SIGNED WITH THE KEY WE HAVE TOO, and "+ "with the group's key; answered (message 4)" : said == LX_WPA_GROUP ? "a new key for the group; answered" :+ said == LX_WPA_BAD ? "NOT GOOD: " : "not one to answer", why);+ if (said == LX_WPA_GROUP && radio->joined) {+ queue_work(radio->work, &radio->group_work);+ }+ if (said != LX_WPA_NOTHING) {+ lx_os_lock();+ radio->handshake = said;+ radio->handshake_why = why;+ lx_os_wakeup(&radio->handshake);+ lx_os_unlock();+ }+}++/* An Ethernet frame the radio has received. */+static void+ethernet_received(struct lx_radio *radio, struct sk_buff *skb)+{+ if (skb->len >= 14 && skb->data[12] == 0x88 && skb->data[13] == 0x8e) {+ handshake_message(radio, skb->data, skb->len);+ } else if (radio->joined && skb->len >= 14) {+ *(skb->data[0] & 1 ? &radio->received_group : &radio->received) += 1;+ lx_os_net_input(skb->data, skb->len);+ }+}++/* A management frame from the access point of the network being joined. */+static void+management_received(struct lx_radio *radio, const uint8_t *f, unsigned length)+{+ int answer = ANSWER_NONE;+ unsigned status = 0;++ if (radio->sta == NULL || length < 26 || memcmp(f + 10, radio->target.address, ETH_ALEN) != 0 ||+ memcmp(f + 4, radio->vif->addr, ETH_ALEN) != 0) {+ return;+ }+ if (f[0] == 0xb0 && length >= 30) { /* authentication: algorithm, step (2: the answer), status */+ status = f[28] | f[29] << 8;+ answer = (f[26] | f[27] << 8) != 2 ? ANSWER_NONE : status == 0 ? ANSWER_AUTHENTICATED : ANSWER_REFUSED;+ } else if (f[0] == 0x10 && length >= 30) { /* association response: capabilities, status, our number, elements */+ status = f[26] | f[27] << 8;+ answer = status == 0 ? ANSWER_ASSOCIATED : ANSWER_REFUSED;+ lx_os_lock();+ radio->aid = (uint16_t)((f[28] | f[29] << 8) & 0x3fff);+ radio->answer_length = length - 30 < ELEMENTS_MOST ? length - 30 : ELEMENTS_MOST;+ memcpy(radio->answer_elements, f + 30, radio->answer_length);+ lx_os_unlock();+ } else if (f[0] == 0xc0 || f[0] == 0xa0) { /* the access point shows us the door: with a reason */+ status = f[24] | f[25] << 8;+ answer = ANSWER_GONE;+ printf("lx: THE ACCESS POINT %s US, reason %u\n", f[0] == 0xc0 ? "DEAUTHENTICATES" : "DISASSOCIATES", status);+ if (radio->joined) {+ radio->joined = false;+ lx_os_net_link(0);+ }+ }+ if (answer != ANSWER_NONE) {+ lx_os_lock();+ radio->answer = answer;+ radio->answer_status = (uint16_t)status;+ lx_os_wakeup(&radio->answer);+ lx_os_unlock();+ }+}++/*+ * A frame the radio has received, with the driver's description behind it (where, how strong,+ * and in which form: an Ethernet frame, or 802.11 as it was on the air).+ */+void+linuxkpi_ieee80211_rx(struct ieee80211_hw *hw, struct sk_buff *skb, struct ieee80211_sta *sta, struct napi_struct *napi,+ struct list_head *list)+{+ struct lx_radio *radio = radio_of(hw);+ const struct ieee80211_rx_status *status = IEEE80211_SKB_RXCB(skb);++ radio->frames++;+ if (status->flag & RX_FLAG_8023) {+ ethernet_received(radio, skb);+ } else if (skb->len >= 36 && (skb->data[0] == 0x80 || skb->data[0] == 0x50)) { /* a beacon, an answer to a probe */+ heard(radio, skb->data, skb->len, status->freq, status->signal);+ } else if (skb->len >= 24 && (skb->data[0] & 0x0c) == 0x00) {+ radio->others++;+ management_received(radio, skb->data, skb->len);+ } else if (to_ethernet(skb, (status->flag & RX_FLAG_IV_STRIPPED) != 0)) {+ ethernet_received(radio, skb);+ } else {+ radio->others++;+ }+ dev_kfree_skb_any(skb);+}++/* ---- the station: an interface, a scan ---------------------------------------------------------------- */++/* The radio started and an interface in station mode on it, as mac80211 brings one up. 0, or an errno. */+static int+station_up(struct lx_radio *radio)+{+ struct ieee80211_hw *hw = &radio->hw;struct ieee80211_vif *vif;- struct ieee80211_hw *hw;- uint8_t *memory;- unsigned long long began;- int channels = 0, ret;+ int ret;- if (radio == NULL || !radio->registered) {- printf("lx: no radio is registered: nothing to scan with\n");- return (ENXIO);+ if (radio->vif != NULL) {+ return (0);}- hw = &radio->hw;if (is_zero_ether_addr(hw->wiphy->perm_addr)) {printf("lx: THE RADIO HAS NO ADDRESS (the kernel was given none, and the firmware has none): no interface is made\n");return (EADDRNOTAVAIL);}- for (unsigned band = 0; band < NUM_NL80211_BANDS; band++) {- channels += hw->wiphy->bands[band] != NULL ? hw->wiphy->bands[band]->n_channels : 0;- }- memory = kzalloc(64 + sizeof(*vif) + hw->vif_data_size, GFP_KERNEL);- request = kzalloc(sizeof(*request) + channels * sizeof(request->req.channels[0]), GFP_KERNEL);- if (memory == NULL || request == NULL) {+ radio->vif_memory = kzalloc(64 + sizeof(*vif) + hw->vif_data_size, GFP_KERNEL);+ if (radio->vif_memory == NULL) {return (ENOMEM);}- vif = (struct ieee80211_vif *)roundup2((uintptr_t)memory, 64);+ vif = (struct ieee80211_vif *)roundup2((uintptr_t)radio->vif_memory, 64);vif->type = NL80211_IFTYPE_STATION;memcpy(vif->addr, hw->wiphy->perm_addr, ETH_ALEN);memcpy(vif->bss_conf.addr, hw->wiphy->perm_addr, ETH_ALEN);vif->bss_conf.vif = vif;vif->bss_conf.bssid = no_network; /* (the driver compares every beacon's sender with it) */vif->link_conf[0] = &vif->bss_conf;+ /* the firmware is to take Ethernet frames and to give them, if the driver offers that (its frame mode) */+ if (ieee80211_hw_check(hw, SUPPORTS_TX_ENCAP_OFFLOAD)) {+ vif->offload_flags |= IEEE80211_OFFLOAD_ENCAP_ENABLED;+ }+ if (ieee80211_hw_check(hw, SUPPORTS_RX_DECAP_OFFLOAD)) {+ vif->offload_flags |= IEEE80211_OFFLOAD_DECAP_ENABLED;+ }mutex_lock(&hw->wiphy->mtx);ret = radio->ops->start(hw);printf("lx: the radio is started: %d\n", ret);- if (ret != 0) {- mutex_unlock(&hw->wiphy->mtx);- return (-ret);+ if (ret == 0) {+ radio->started = true;+ ret = radio->ops->add_interface(hw, vif);+ printf("lx: an interface in station mode is added to it: %d (Ethernet frames %s the firmware, %s it)\n", ret,+ vif->offload_flags & IEEE80211_OFFLOAD_ENCAP_ENABLED ? "to" : "NOT to", vif->offload_flags &+ IEEE80211_OFFLOAD_DECAP_ENABLED ? "from" : "NOT from");+ if (ret == 0) {+ radio->vif = vif;+ }}- ret = radio->ops->add_interface(hw, vif);- printf("lx: an interface in station mode is added to it: %d\n", ret);- if (ret != 0) {+ mutex_unlock(&hw->wiphy->mtx);+ return (-ret);+}++static void+station_down(struct lx_radio *radio)+{+ struct ieee80211_hw *hw = &radio->hw;++ mutex_lock(&hw->wiphy->mtx);+ if (radio->vif != NULL) {+ radio->ops->remove_interface(hw, radio->vif);+ radio->vif = NULL;+ }+ if (radio->started) {radio->ops->stop(hw, false);- mutex_unlock(&hw->wiphy->mtx);- return (-ret);+ radio->started = false;}- radio->vif = vif;+ mutex_unlock(&hw->wiphy->mtx);+ kfree(radio->vif_memory);+ radio->vif_memory = NULL;+ printf("lx: the interface is removed and the radio stopped\n");+}+/*+ * A scan of every channel the regulatory domain allows. With a name the radio asks for that+ * network on every channel where it may send (a probe request; and the access points that+ * hear it answer); without, it only listens. 0 when the driver has said the scan is over.+ */+static int+station_scan(struct lx_radio *radio, const uint8_t *name, unsigned name_length)+{+ struct ieee80211_hw *hw = &radio->hw;+ struct ieee80211_scan_request *request;+ struct cfg80211_ssid asked;+ unsigned long long began;+ int channels = 0, ret;++ for (unsigned band = 0; band < NUM_NL80211_BANDS; band++) {+ channels += hw->wiphy->bands[band] != NULL ? hw->wiphy->bands[band]->n_channels : 0;+ }+ request = kzalloc(sizeof(*request) + channels * sizeof(request->req.channels[0]), GFP_KERNEL);+ if (request == NULL) {+ return (ENOMEM);+ }request->req.wiphy = hw->wiphy;for (unsigned band = 0; band < NUM_NL80211_BANDS; band++) {struct ieee80211_supported_band *has = hw->wiphy->bands[band];@@ -619,12 +967,21 @@ lx_station_scan(void)}}}+ if (name_length != 0) {+ bzero(&asked, sizeof(asked));+ memcpy(asked.ssid, name, name_length);+ asked.ssid_len = (uint8_t)name_length;+ request->req.ssids = &asked;+ request->req.n_ssids = 1;+ }radio->scan = 1;radio->frames = radio->others = radio->heard_count = radio->heard_lost = 0;began = lx_os_nanoseconds();- ret = radio->ops->hw_scan(hw, vif, request);+ mutex_lock(&hw->wiphy->mtx);+ ret = radio->ops->hw_scan(hw, radio->vif, request);mutex_unlock(&hw->wiphy->mtx);- printf("lx: THE DRIVER IS ASKED TO SCAN %d channels, listening only: %d\n", request->req.n_channels, ret);+ printf("lx: THE DRIVER IS ASKED TO SCAN %d channels, %s: %d\n", request->req.n_channels, name_length != 0 ?+ "asking for the network that is wanted where it may send" : "listening only", ret);if (ret == 0) {lx_os_lock();while (radio->scan == 1 && lx_os_nanoseconds() - began < 40000000000ull) {@@ -634,18 +991,664 @@ lx_station_scan(void)printf("lx: %llu ms later the scan is %s\n", (lx_os_nanoseconds() - began) / 1000000ull, radio->scan == 2 ? "OVER" :radio->scan == 3 ? "GIVEN UP by the driver" : "NOT OVER: the driver has not said so");say_heard(radio);+ if (radio->scan == 1 && radio->ops->cancel_hw_scan != NULL) {+ mutex_lock(&hw->wiphy->mtx);+ radio->ops->cancel_hw_scan(hw, radio->vif);+ mutex_unlock(&hw->wiphy->mtx);+ }}+ kfree(request);+ return (ret != 0 ? -ret : radio->scan == 2 ? 0 : ETIMEDOUT);+}+/* An interface, a scan that only listens, and down again: what the radio hears is said. 0, or an errno. */+int+lx_station_scan(void)+{+ struct lx_radio *radio = the_radio;+ int error;++ if (radio == NULL || !radio->registered) {+ printf("lx: no radio is registered: nothing to scan with\n");+ return (ENXIO);+ }+ if ((error = station_up(radio)) == 0) {+ error = station_scan(radio, NULL, 0);+ }+ station_down(radio);+ return (error);+}++/* ---- the station: joining a network -------------------------------------------------------------------- */++/* Wait for the access point's answer to a management frame: one of the ANSWER_s, or ANSWER_NONE when the time is up. */+static int+answer_wait(struct lx_radio *radio, unsigned ms)+{+ unsigned long long began = lx_os_nanoseconds();+ int answer;++ lx_os_lock();+ while (radio->answer == ANSWER_NONE && lx_os_nanoseconds() - began < ms * 1000000ull) {+ lx_os_sleep(&radio->answer, 20 * 1000000ull);+ }+ answer = radio->answer;+ lx_os_unlock();+ return (answer);+}++/* The rates among `count` bytes of a rates element that the band has, as bits in the band's own order; and the "basic" ones. */+static uint32_t+rates_of(const struct ieee80211_supported_band *band, const uint8_t *rates, unsigned count, uint32_t *basic)+{+ uint32_t has = 0;++ for (unsigned i = 0; i < count; i++) {+ for (int r = 0; r < band->n_bitrates; r++) {+ if (band->bitrates[r].bitrate == (rates[i] & 0x7f) * 5u) { /* (half megabits there, tenths here) */+ has |= 1u << r;+ *basic |= rates[i] & 0x80 ? 1u << r : 0;+ }+ }+ }+ return (has);+}++/*+ * What the access point says it can do, into the form the driver reads it in when it tells the+ * firmware about the peer (mac.c: ath11k_peer_assoc_prepare()): rates, the HT and VHT+ * capabilities, WMM. `elements` are the association response's, or the beacon's before that.+ */+static void+station_abilities(struct lx_radio *radio, const uint8_t *elements, unsigned length)+{+ struct ieee80211_supported_band *band = radio->wiphy->bands[radio->channel->def.chan->band];+ struct ieee80211_sta *sta = radio->sta;+ struct ieee80211_bss_conf *conf = &radio->vif->bss_conf;+ const uint8_t *e;+ uint32_t rates = 0, basic = 0;++ if ((e = element(elements, length, 1)) != NULL) {+ rates |= rates_of(band, e + 2, e[1], &basic);+ }+ if ((e = element(elements, length, 50)) != NULL) {+ rates |= rates_of(band, e + 2, e[1], &basic);+ }+ sta->deflink.supp_rates[band->band] = rates;+ conf->basic_rates = basic;+ sta->wme = conf->qos = vendor_element(elements, length, wmm) != NULL;+ sta->deflink.bandwidth = IEEE80211_STA_RX_BW_20;+ sta->deflink.rx_nss = 1;+ sta->deflink.smps_mode = IEEE80211_SMPS_OFF;+ if ((e = element(elements, length, 45)) != NULL && e[1] >= 26 && band->ht_cap.ht_supported) { /* HT capabilities */+ struct ieee80211_sta_ht_cap *ht = &sta->deflink.ht_cap;++ ht->ht_supported = true;+ /* (without the bits for 40 MHz: the channel asked for is 20 MHz wide) */+ ht->cap = (uint16_t)((e[2] | e[3] << 8) & ~(IEEE80211_HT_CAP_SUP_WIDTH_20_40 | IEEE80211_HT_CAP_SGI_40));+ ht->ampdu_factor = e[4] & 3;+ ht->ampdu_density = e[4] >> 2 & 7;+ memcpy(&ht->mcs, e + 5, sizeof(ht->mcs));+ sta->deflink.rx_nss = ht->mcs.rx_mask[1] != 0 ? 2 : 1;+ }+ if ((e = element(elements, length, 191)) != NULL && e[1] >= 12 && band->vht_cap.vht_supported) { /* VHT capabilities */+ struct ieee80211_sta_vht_cap *vht = &sta->deflink.vht_cap;++ vht->vht_supported = true;+ vht->cap = e[2] | e[3] << 8 | e[4] << 16 | (uint32_t)e[5] << 24;+ memcpy(&vht->vht_mcs, e + 6, sizeof(vht->vht_mcs));+ }+ if ((e = element(elements, length, 61)) != NULL && e[1] >= 22) { /* HT operation: the protection in use */+ conf->ht_operation_mode = (uint16_t)(e[4] | e[5] << 8);+ }+ if ((e = element(elements, length, 5)) != NULL && e[1] >= 2 && e[3] != 0) { /* the TIM: every how many beacons */+ conf->dtim_period = e[3];+ }+}++/*+ * Our association request's elements, after the two fixed fields: the name, our rates, what+ * 802.11h asks of a station where the access point uses it, RSN (what we agree to of what it+ * offers: CCMP between the two, its cipher for the group, a passphrase's key), our HT and VHT+ * capabilities if it has them, and WMM. Returns their length.+ */+static unsigned+request_elements(struct lx_radio *radio, uint8_t *out, unsigned group_cipher)+{+ const struct lx_target *target = &radio->target;+ struct linuxkpi_ieee80211_channel *channel = radio->channel->def.chan;+ struct ieee80211_supported_band *band = radio->wiphy->bands[channel->band];+ uint8_t *at = out;+ int count = band->n_bitrates;++ *at++ = 0;+ *at++ = radio->want_length;+ memcpy(at, radio->want, radio->want_length);+ at += radio->want_length;+ *at++ = 1;+ *at++ = (uint8_t)(count < 8 ? count : 8);+ for (int r = 0; r < count; r++) {+ if (r == 8) {+ *at++ = 50;+ *at++ = (uint8_t)(count - 8);+ }+ *at++ = (uint8_t)(band->bitrates[r].bitrate / 5 | (radio->vif->bss_conf.basic_rates & 1u << r ? 0x80 : 0));+ }+ if (target->capability & 0x0100) { /* spectrum management: the power we can send with, the channels we have */+ *at++ = 33;+ *at++ = 2;+ *at++ = 0;+ *at++ = (uint8_t)channel->max_power;+ *at++ = 36;+ *at++ = 2;+ *at++ = (uint8_t)channel_of(channel->center_freq);+ *at++ = 1;+ }+ radio->rsn[0] = 48;+ radio->rsn[1] = 20;+ memcpy(radio->rsn + 2, "\x01\x00\x00\x0f\xac\x04\x01\x00\x00\x0f\xac\x04\x01\x00\x00\x0f\xac\x02\x00\x00", 20);+ radio->rsn[7] = (uint8_t)group_cipher;+ memcpy(at, radio->rsn, 22);+ at += 22;+ if (element(target->elements, target->elements_length, 45) != NULL && band->ht_cap.ht_supported) {+ uint16_t cap = (uint16_t)(band->ht_cap.cap & ~(IEEE80211_HT_CAP_SUP_WIDTH_20_40 | IEEE80211_HT_CAP_SGI_40));++ *at++ = 45;+ *at++ = 26;+ bzero(at, 26);+ at[0] = (uint8_t)cap;+ at[1] = (uint8_t)(cap >> 8);+ at[2] = (uint8_t)(band->ht_cap.ampdu_factor | band->ht_cap.ampdu_density << 2);+ memcpy(at + 3, &band->ht_cap.mcs, sizeof(band->ht_cap.mcs));+ at += 26;+ }+ if (element(target->elements, target->elements_length, 191) != NULL && band->vht_cap.vht_supported) {+ *at++ = 191;+ *at++ = 12;+ at[0] = (uint8_t)band->vht_cap.cap;+ at[1] = (uint8_t)(band->vht_cap.cap >> 8);+ at[2] = (uint8_t)(band->vht_cap.cap >> 16);+ at[3] = (uint8_t)(band->vht_cap.cap >> 24);+ memcpy(at + 4, &band->vht_cap.vht_mcs, sizeof(band->vht_cap.vht_mcs));+ at += 12;+ }+ if (vendor_element(target->elements, target->elements_length, wmm) != NULL) {+ memcpy(at, "\xdd\x07\x00\x50\xf2\x02\x00\x01\x00", 9);+ at += 9;+ }+ return ((unsigned)(at - out));+}++/*+ * What kind of protection the access point offers (its RSN element: version, the group's+ * cipher, the ciphers and the kinds of key management it takes, capabilities). NULL if we can+ * join it -- CCMP, a passphrase's key (kind 2), management frames unprotected --, and+ * *group_cipher is then what it ciphers frames to everybody with; else what stands in the way.+ */+static const char *+protection(const struct lx_target *target, unsigned *group_cipher)+{+ const uint8_t *rsn = element(target->elements, target->elements_length, 48), *at, *end;+ bool ccmp = false, passphrase = false;+ unsigned count;++ if (rsn == NULL) {+ return (target->capability & 0x10 ? "it is protected by something older than WPA2" : "it is not protected at all: an "+ "open network is not joined by this");+ }+ at = rsn + 2;+ end = at + rsn[1];+ if (end - at < 8 || at[2] != 0x00 || at[3] != 0x0f || at[4] != 0xac) {+ return ("its RSN element is not one this reads");+ }+ *group_cipher = at[5];+ count = at[6] | at[7] << 8;+ at += 8;+ for (; count != 0 && end - at >= 4; count--, at += 4) {+ ccmp |= at[0] == 0x00 && at[1] == 0x0f && at[2] == 0xac && at[3] == 4;+ }+ if (end - at < 2) {+ return ("its RSN element names no kind of key management");+ }+ count = at[0] | at[1] << 8;+ at += 2;+ for (; count != 0 && end - at >= 4; count--, at += 4) {+ passphrase |= at[0] == 0x00 && at[1] == 0x0f && at[2] == 0xac && at[3] == 2;+ }+ if (*group_cipher != 4) {+ return ("it ciphers frames to everybody with something other than CCMP (TKIP, for old stations), which is not done here");+ }+ if (!ccmp) {+ return ("it does not offer CCMP");+ }+ if (!passphrase) {+ return ("it does not take a passphrase's key of the WPA2 kind (WPA3 only, or an enterprise network)");+ }+ if (end - at >= 2 && (at[0] & 0x40)) {+ return ("it requires protected management frames, which are not done here");+ }+ return (NULL);+}++/* A key for the driver to give the firmware: CCMP, for frames between us and the access point or for the group's. */+static struct ieee80211_key_conf *+key_set(struct lx_radio *radio, const uint8_t *key, unsigned index, bool pairwise, int *error)+{+ struct ieee80211_key_conf *conf = kzalloc(sizeof(*conf) + 16, GFP_KERNEL);++ if (conf == NULL) {+ *error = -ENOMEM;+ return (NULL);+ }+ conf->cipher = WLAN_CIPHER_SUITE_CCMP;+ conf->keyidx = (uint8_t)index;+ conf->keylen = 16;+ conf->iv_len = 8;+ conf->icv_len = 8;+ conf->flags = pairwise ? IEEE80211_KEY_FLAG_PAIRWISE : 0;+ conf->link_id = -1;+ memcpy(conf->key, key, 16);+ mutex_lock(&radio->wiphy->mtx);+ *error = radio->ops->set_key(&radio->hw, SET_KEY, radio->vif, pairwise ? radio->sta : NULL, conf);+ mutex_unlock(&radio->wiphy->mtx);+ return (conf);+}++static void+key_drop(struct lx_radio *radio, struct ieee80211_key_conf **conf, bool pairwise)+{+ if (*conf != NULL) {+ mutex_lock(&radio->wiphy->mtx);+ radio->ops->set_key(&radio->hw, DISABLE_KEY, radio->vif, pairwise ? radio->sta : NULL, *conf);+ mutex_unlock(&radio->wiphy->mtx);+ explicit_bzero((*conf)->key, 16);+ kfree(*conf);+ *conf = NULL;+ }+}++/* The access point has changed the group's key (it does every so often): the new one to the driver, the old one gone. */+static void+group_rekey(struct work_struct *work)+{+ struct lx_radio *radio = __containerof(work, struct lx_radio, group_work);+ struct ieee80211_key_conf *old = radio->group_key;+ int error = 0;++ radio->group_key = key_set(radio, radio->wpa.group, radio->wpa.group_index, false, &error);+ printf("lx: the group's new key (number %u) is given to the driver: %d\n", radio->wpa.group_index, error);+ key_drop(radio, &old, false);+}++/* One step of the station's state as the driver is told of it (mac80211: drv_sta_state()). */+static int+station_state(struct lx_radio *radio, enum ieee80211_sta_state from, enum ieee80211_sta_state to)+{+ int ret;++ mutex_lock(&radio->wiphy->mtx);+ ret = radio->ops->sta_state(&radio->hw, radio->vif, radio->sta, from, to);+ mutex_unlock(&radio->wiphy->mtx);+ return (ret);+}++static void+bss_changed(struct lx_radio *radio, u64 what)+{+ mutex_lock(&radio->wiphy->mtx);+ radio->ops->bss_info_changed(&radio->hw, radio->vif, &radio->vif->bss_conf, what);+ mutex_unlock(&radio->wiphy->mtx);+}++/* Everything a join has made, undone in mac80211's order; as far as it got. */+static void+station_leave(struct lx_radio *radio, int state)+{+ struct ieee80211_hw *hw = &radio->hw;+ struct ieee80211_vif *vif = radio->vif;++ if (radio->joined) {+ radio->joined = false;+ lx_os_net_link(0);+ }+ if (radio->sta != NULL && state >= IEEE80211_STA_AUTH && radio->answer != ANSWER_GONE) {+ struct sk_buff *skb;+ uint8_t *frame;++ if ((skb = frame_new(radio, 26, &frame)) != NULL) { /* deauthentication, reason 3: we are leaving */+ frame = management(radio, frame, 0xc0);+ frame[0] = 3;+ frame[1] = 0;+ frame_send(radio, skb);+ lx_pause_ms(50);+ }+ }+ cancel_work_sync(&radio->group_work);+ key_drop(radio, &radio->group_key, false);+ key_drop(radio, &radio->pairwise_key, true);+ explicit_bzero(&radio->wpa, sizeof(radio->wpa));+ for (; radio->sta != NULL && state > IEEE80211_STA_NOTEXIST; state--) {+ station_state(radio, state, state - 1);+ }+ if (vif != NULL && vif->cfg.assoc) {+ vif->cfg.assoc = false;+ vif->cfg.aid = 0;+ bss_changed(radio, BSS_CHANGED_ASSOC);+ }+ if (radio->channel != NULL) {+ mutex_lock(&hw->wiphy->mtx);+ radio->ops->unassign_vif_chanctx(hw, vif, &vif->bss_conf, radio->channel);+ vif->bss_conf.chanctx_conf = NULL;+ radio->ops->remove_chanctx(hw, radio->channel);+ mutex_unlock(&hw->wiphy->mtx);+ kfree(radio->channel);+ radio->channel = NULL;+ }+ if (vif != NULL) {+ vif->bss_conf.bssid = no_network;+ bss_changed(radio, BSS_CHANGED_BSSID);+ }+ kfree(radio->sta_memory);+ radio->sta_memory = radio->sta = NULL;+}++/*+ * Join the network of that name with that passphrase, in the order mac80211 goes through+ * (net/mac80211/mlme.c of Linux: ieee80211_mgd_auth(), ieee80211_mgd_assoc(), and what the+ * supplicant does after them): the access point found by a scan that asks for the network; the+ * channel taken; the access point made a station the driver knows; authentication; association;+ * the handshake; the keys. 0 when frames can pass, or an errno with the reason said.+ */+static int+station_join(struct lx_radio *radio, const uint8_t *name, unsigned name_length, const uint8_t *passphrase,+ unsigned passphrase_length)+{+ struct ieee80211_hw *hw = &radio->hw;+ struct ieee80211_vif *vif;+ struct linuxkpi_ieee80211_channel *channel;+ struct lx_target *target = &radio->target;+ struct sk_buff *skb;+ uint8_t *frame;+ const uint8_t *e;+ const char *obstacle;+ unsigned long long began;+ unsigned group_cipher = 0, length;+ int state = IEEE80211_STA_NOTEXIST, ret, error = 0, answer = ANSWER_NONE;++ INIT_WORK(&radio->group_work, group_rekey);+ memcpy(radio->want, name, name_length);+ radio->want_length = (uint8_t)name_length;+ bzero(target, sizeof(*target));+ if ((ret = station_up(radio)) != 0) {+ return (ret);+ }+ vif = radio->vif;+ for (unsigned attempt = 0; attempt < 3 && !target->found; attempt++) {+ station_scan(radio, name, name_length);+ }+ if (!target->found) {+ printf("lx: THE NETWORK THAT IS WANTED WAS NOT HEARD (a name of %u bytes), in three scans\n", name_length);+ return (ENOENT);+ }+ channel = linuxkpi_ieee80211_get_channel(hw->wiphy, target->frequency);+ if ((e = element(target->elements, target->elements_length, 3)) != NULL && e[1] == 1 && channel != NULL &&+ linuxkpi_ieee80211_get_channel(hw->wiphy, linuxkpi_ieee80211_channel_to_frequency(e[2], channel->band)) != NULL) {+ /* (a beacon can be heard on the channel next to its own: where it says it is counts) */+ channel = linuxkpi_ieee80211_get_channel(hw->wiphy, linuxkpi_ieee80211_channel_to_frequency(e[2], channel->band));+ }+ obstacle = protection(target, &group_cipher);+ printf("lx: the network that is wanted: an access point on channel %u (%u MHz) at %d dBm, capabilities %#x, beacons every "+ "%u units; HT %s, VHT %s, WMM %s; %s%s\n", channel != NULL ? channel_of(channel->center_freq) : 0, channel != NULL ?+ channel->center_freq : 0, target->signal, target->capability, target->interval, element(target->elements,+ target->elements_length, 45) ? "yes" : "no", element(target->elements, target->elements_length, 191) ? "yes" : "no",+ vendor_element(target->elements, target->elements_length, wmm) ? "yes" : "no", obstacle == NULL ? "WPA2 with a "+ "passphrase and CCMP: it can be joined" : "IT CANNOT BE JOINED: ", obstacle == NULL ? "" : obstacle);+ if (obstacle != NULL || channel == NULL || (channel->flags & IEEE80211_CHAN_DISABLED)) {+ return (ENOTSUP);+ }++ /* the key of the name and the passphrase, and what the handshake needs besides */+ began = lx_os_nanoseconds();+ bzero(&radio->wpa, sizeof(radio->wpa));+ lx_wpa_pmk(passphrase, passphrase_length, name, name_length, radio->wpa.pmk);+ memcpy(radio->wpa.own, vif->addr, ETH_ALEN);+ memcpy(radio->wpa.peer, target->address, ETH_ALEN);+ get_random_bytes(radio->wpa.own_nonce, sizeof(radio->wpa.own_nonce));+ radio->wpa.rsn = radio->rsn;+ radio->wpa.rsn_length = 22;+ radio->handshake = LX_WPA_NOTHING;+ printf("lx: the key of the name (%u bytes) and the passphrase (%u bytes) is made: %llu ms\n", name_length, passphrase_length,+ (lx_os_nanoseconds() - began) / 1000000ull);++ /* the access point's address, and its channel, 20 MHz wide */+ vif->bss_conf.bssid = target->address;+ vif->bss_conf.beacon_int = target->interval;+ vif->bss_conf.assoc_capability = target->capability;+ vif->bss_conf.dtim_period = 1;+ vif->bss_conf.use_short_slot = (target->capability & 0x0400) != 0 || channel->band != NL80211_BAND_2GHZ;+ vif->bss_conf.use_short_preamble = (target->capability & 0x0020) != 0;+ memcpy(vif->cfg.ap_addr, target->address, ETH_ALEN);+ memcpy(vif->cfg.ssid, name, name_length);+ vif->cfg.ssid_len = name_length;+ bss_changed(radio, BSS_CHANGED_BSSID);+ radio->channel = kzalloc(sizeof(*radio->channel) + hw->chanctx_data_size + 64, GFP_KERNEL);+ radio->sta_memory = kzalloc(64 + sizeof(*radio->sta) + hw->sta_data_size, GFP_KERNEL);+ if (radio->channel == NULL || radio->sta_memory == NULL) {+ error = ENOMEM;+ goto out;+ }+ radio->channel->def.chan = channel;+ radio->channel->def.width = NL80211_CHAN_WIDTH_20;+ radio->channel->def.center_freq1 = channel->center_freq;+ radio->channel->min_def = radio->channel->def;+ radio->channel->rx_chains_static = radio->channel->rx_chains_dynamic = 2;+ vif->bss_conf.chanreq.oper = radio->channel->def;mutex_lock(&hw->wiphy->mtx);- if (ret == 0 && radio->scan == 1 && radio->ops->cancel_hw_scan != NULL) {- radio->ops->cancel_hw_scan(hw, vif);+ ret = radio->ops->add_chanctx(hw, radio->channel);+ if (ret == 0) {+ vif->bss_conf.chanctx_conf = radio->channel;+ ret = radio->ops->assign_vif_chanctx(hw, vif, &vif->bss_conf, radio->channel);}- radio->ops->remove_interface(hw, vif);- radio->vif = NULL;- radio->ops->stop(hw, false);mutex_unlock(&hw->wiphy->mtx);- printf("lx: the interface is removed and the radio stopped\n");- kfree(request);- kfree(memory);- return (ret != 0 ? -ret : radio->scan == 2 ? 0 : ETIMEDOUT);+ printf("lx: the channel is taken: %d\n", ret);+ if (ret != 0) {+ error = -ret;+ goto out;+ }++ /* the access point as a station of the driver's: the firmware learns of it, and the radio goes to its channel */+ radio->sta = (struct ieee80211_sta *)roundup2((uintptr_t)radio->sta_memory, 64);+ memcpy(radio->sta->addr, target->address, ETH_ALEN);+ memcpy(radio->sta->deflink.addr, target->address, ETH_ALEN);+ radio->sta->deflink.sta = radio->sta;+ radio->sta->link[0] = &radio->sta->deflink;+ station_abilities(radio, target->elements, target->elements_length);+ ret = station_state(radio, IEEE80211_STA_NOTEXIST, IEEE80211_STA_NONE);+ printf("lx: the access point is made known to the driver: %d\n", ret);+ if (ret != 0) {+ kfree(radio->sta_memory);+ radio->sta_memory = radio->sta = NULL;+ error = -ret;+ goto out;+ }+ state = IEEE80211_STA_NONE;++ /* authentication, of the kind that asks nothing ("open system": the passphrase is proved in the handshake) */+ for (unsigned attempt = 0; attempt < 3 && answer == ANSWER_NONE; attempt++) {+ radio->answer = ANSWER_NONE;+ if ((skb = frame_new(radio, 30, &frame)) == NULL) {+ break;+ }+ frame = management(radio, frame, 0xb0);+ memcpy(frame, "\x00\x00\x01\x00\x00\x00", 6); /* algorithm 0, step 1, status 0 */+ frame_send(radio, skb);+ answer = answer_wait(radio, 500);+ }+ printf("lx: AUTHENTICATION: %s (status %u)\n", answer == ANSWER_AUTHENTICATED ? "the access point accepts" : answer ==+ ANSWER_NONE ? "NO ANSWER from the access point to three requests" : "THE ACCESS POINT REFUSES", radio->answer_status);+ if (answer != ANSWER_AUTHENTICATED || (ret = station_state(radio, IEEE80211_STA_NONE, IEEE80211_STA_AUTH)) != 0) {+ error = answer == ANSWER_NONE ? ETIMEDOUT : ECONNREFUSED;+ goto out;+ }+ state = IEEE80211_STA_AUTH;++ /* association: what we can do, and that we want its protection */+ answer = ANSWER_NONE;+ for (unsigned attempt = 0; attempt < 3 && answer == ANSWER_NONE; attempt++) {+ radio->answer = ANSWER_NONE;+ if ((skb = frame_new(radio, 28 + 300, &frame)) == NULL) {+ break;+ }+ frame = management(radio, frame, 0x00);+ /* capabilities: an infrastructure network, protected, and of the access point's own what a station repeats */+ frame[0] = (uint8_t)(0x01 | 0x10 | (target->capability & 0x20));+ frame[1] = (uint8_t)((target->capability & 0x0500) >> 8);+ frame[2] = 10; /* we listen at least every tenth beacon */+ frame[3] = 0;+ length = request_elements(radio, frame + 4, group_cipher);+ skb_trim(skb, 28 + length);+ frame_send(radio, skb);+ answer = answer_wait(radio, 500);+ }+ printf("lx: ASSOCIATION: %s (status %u); we are its station number %u; its answer has %u bytes of elements\n", answer ==+ ANSWER_ASSOCIATED ? "THE ACCESS POINT ACCEPTS" : answer == ANSWER_NONE ? "NO ANSWER from the access point to three "+ "requests" : "THE ACCESS POINT REFUSES", radio->answer_status, radio->aid, radio->answer_length);+ if (answer != ANSWER_ASSOCIATED) {+ error = answer == ANSWER_NONE ? ETIMEDOUT : ECONNREFUSED;+ goto out;+ }+ station_abilities(radio, radio->answer_elements, radio->answer_length);+ radio->sta->aid = radio->aid;+ if ((ret = station_state(radio, IEEE80211_STA_AUTH, IEEE80211_STA_ASSOC)) != 0) {+ error = -ret;+ goto out;+ }+ state = IEEE80211_STA_ASSOC;+ vif->cfg.assoc = true;+ vif->cfg.aid = radio->aid;+ bss_changed(radio, BSS_CHANGED_ASSOC | BSS_CHANGED_BEACON_INT | BSS_CHANGED_ERP_SLOT | BSS_CHANGED_ERP_PREAMBLE |+ BSS_CHANGED_QOS);+ if ((e = vendor_element(radio->answer_elements, radio->answer_length, wmm)) != NULL && e[1] >= 24 && e[6] == 1) {+ /* WMM's parameters: for each of the four classes how long to wait and how long to hold the air */+ mutex_lock(&hw->wiphy->mtx);+ for (unsigned i = 0; i < 4; i++) {+ const uint8_t *record = e + 10 + 4 * i;+ static const uint8_t classes[4] = { IEEE80211_AC_BE, IEEE80211_AC_BK, IEEE80211_AC_VI, IEEE80211_AC_VO };+ struct ieee80211_tx_queue_params params = { .aifs = record[0] & 0x0f, .cw_min = (uint16_t)((1u << (record[1] &+ 0x0f)) - 1), .cw_max = (uint16_t)((1u << (record[1] >> 4)) - 1),+ .txop = (uint16_t)(record[2] | record[3] << 8), .acm = record[0] >> 4 &+ 1 };++ radio->ops->conf_tx(hw, vif, 0, classes[record[0] >> 5 & 3], ¶ms);+ }+ mutex_unlock(&hw->wiphy->mtx);+ }+ printf("lx: the driver is told of the association (rates %#x, HT %s, VHT %s, %u streams)\n",+ radio->sta->deflink.supp_rates[channel->band], radio->sta->deflink.ht_cap.ht_supported ? "yes" : "no",+ radio->sta->deflink.vht_cap.vht_supported ? "yes" : "no", radio->sta->deflink.rx_nss);++ /* the handshake: the access point begins it; its messages come in as frames and are answered where they come in */+ began = lx_os_nanoseconds();+ lx_os_lock();+ while (radio->handshake != LX_WPA_KEYS && radio->handshake != LX_WPA_BAD && radio->answer != ANSWER_GONE &&+ lx_os_nanoseconds() - began < 8000000000ull) {+ lx_os_sleep(&radio->handshake, 20 * 1000000ull);+ }+ lx_os_unlock();+ if (radio->handshake != LX_WPA_KEYS) {+ printf("lx: THE HANDSHAKE DID NOT COME THROUGH in %llu ms: %s%s (%u of its messages came)\n", (lx_os_nanoseconds() - began) /+ 1000000ull, radio->answer == ANSWER_GONE ? "the access point has shown us the door (a wrong passphrase gives this)" :+ radio->handshake == LX_WPA_BAD ? "a message was not good: " : radio->handshake == LX_WPA_ANSWER ? "our message 2 was "+ "not answered (a wrong passphrase gives this)" : "the access point did not begin it", radio->handshake == LX_WPA_BAD ?+ radio->handshake_why : "", radio->eapol);+ error = EAUTH;+ goto out;+ }+ lx_pause_ms(30); /* (for message 4 to have left unciphered, before there is a key to cipher with) */+ radio->pairwise_key = key_set(radio, radio->wpa.pairwise, 0, true, &ret);+ if (ret == 0) {+ radio->group_key = key_set(radio, radio->wpa.group, radio->wpa.group_index, false, &ret);+ }+ printf("lx: THE KEYS ARE GIVEN TO THE DRIVER, %llu ms after the association: ours with the access point, and the group's "+ "(number %u, %u bytes): %d\n", (lx_os_nanoseconds() - began) / 1000000ull, radio->wpa.group_index,+ radio->wpa.group_length, ret);+ if (ret != 0 || (ret = station_state(radio, IEEE80211_STA_ASSOC, IEEE80211_STA_AUTHORIZED)) != 0) {+ error = -ret;+ goto out;+ }+ state = IEEE80211_STA_AUTHORIZED;+ radio->sent = radio->sent_lost = radio->received = radio->received_group = 0;+ radio->joined = true;+ lx_os_net_link(1);+ printf("lx: THE NETWORK IS JOINED: frames can pass\n");+ return (0);+out:+ station_leave(radio, state);+ return (error);+}++/* ---- for the rest of the layer ---------------------------------------------------------------------------- */++/* Join the network the kernel was given the name and passphrase of. 0 when frames can pass, or an errno. */+int+lx_station_join(void)+{+ static uint8_t name[32], passphrase[64];+ struct lx_radio *radio = the_radio;+ unsigned name_length = sizeof(name), passphrase_length = sizeof(passphrase);+ int error;++ if (radio == NULL || !radio->registered) {+ printf("lx: no radio is registered: nothing to join with\n");+ return (ENXIO);+ }+ if (!lx_os_network(name, &name_length, passphrase, &passphrase_length)) {+ return (ENOENT);+ }+ lx_os_net_attach(radio->wiphy->perm_addr);+ error = station_join(radio, name, name_length, passphrase, passphrase_length);+ explicit_bzero(passphrase, sizeof(passphrase));+ return (error);+}++/* What has passed since the network was joined. */+void+lx_station_say(void)+{+ struct lx_radio *radio = the_radio;++ if (radio != NULL) {+ printf("lx: the network is %s: %u frames sent (%u could not be), %u received for us and %u sent to everybody; %u "+ "messages of the handshake\n", radio->joined ? "joined" : "NOT joined", radio->sent, radio->sent_lost, radio->received,+ radio->received_group, radio->eapol);+ }+}++/* Leave the network, if one is joined, and take the interface down. */+void+lx_station_leave(void)+{+ struct lx_radio *radio = the_radio;++ if (radio == NULL || radio->vif == NULL) {+ return;+ }+ lx_station_say();+ if (radio->sta != NULL) {+ station_leave(radio, radio->joined ? IEEE80211_STA_AUTHORIZED : IEEE80211_STA_ASSOC);+ printf("lx: the network is left\n");+ }+ station_down(radio);+}++/* An Ethernet frame from the kernel for the network. 0, or an errno. */+int+lx_station_send(const unsigned char *frame, unsigned long length)+{+ struct lx_radio *radio = the_radio;++ if (radio == NULL || !radio->joined) {+ return (ENETDOWN);+ }+ return (ethernet_send(radio, frame, (unsigned)length) ? 0 : ENOBUFS);}diff --git a/wifi/lx/src/lx_base.c b/wifi/lx/src/lx_base.cindex c97fc67..fe4422c 100644--- a/wifi/lx/src/lx_base.c+++ b/wifi/lx/src/lx_base.c@@ -725,8 +725,8 @@ iounmap(void *address)* or the other way round. The first part of it is handed out for good, a stretch at a time* (rings); the rest is slots of one size, taken and given back (buffers).*/-#define POOL_SIZE (12u << 20)-#define POOL_RINGS (2u << 20)+#define POOL_SIZE (44u << 20)+#define POOL_RINGS (12u << 20) /* (the data path's rings and link descriptors come to about 6 MB) */#define POOL_SLOT 4096u#define POOL_SLOTS ((POOL_SIZE - POOL_RINGS) / POOL_SLOT)@@ -784,6 +784,22 @@ kmem_free(void *address, vm_size_t size)/* (dma_free_coherent() ends here: rings are not given back) */}+/*+ * Linux's memory for a device that need not be coherent: the same piece. (The data path takes a+ * few kilobytes of it for every traffic class of a station it meets, and gives them back when+ * the station goes: here they stay taken, like the rings.)+ */+void *+dma_alloc_noncoherent(struct device *dev, size_t size, dma_addr_t *handle, enum dma_data_direction direction, gfp_t gfp)+{+ return (linux_dma_alloc_coherent(dev, size, handle, gfp));+}++void+dma_free_noncoherent(struct device *dev, size_t size, void *memory, dma_addr_t handle, enum dma_data_direction direction)+{+}+/** FreeBSD's question for the physical address of memory, which LinuxKPI asks before it hands* memory to a device. Here the answer is the radio's address, for memory of the pool; no other@@ -1114,6 +1130,45 @@ rhashtable_remove_fast(struct rhashtable *table, struct rhash_head *head, constreturn (error);}+/* The numbered thing with the lowest number from *id on, and that number; or NULL. */+void *+idr_get_next(struct idr *idr, int *id)+{+ struct lx_ids *ids;+ void *thing = NULL;++ lx_os_lock();+ ids = (struct lx_ids *)idr->top;+ for (int i = *id < 0 ? 0 : *id; ids != NULL && i < ids->size; i++) {+ if (ids->things[i] != NULL) {+ thing = ids->things[i];+ *id = i;+ break;+ }+ }+ lx_os_unlock();+ return (thing);+}++void+explicit_bzero(void *memory, size_t size)+{+ bzero(memory, size);+}++/* FreeBSD's kernel log, which LinuxKPI's rate-limited messages go to. */+void+log(int level, const char *format, ...)+{+ char line[400];+ va_list list;++ va_start(list, format);+ vsnprintf(line, sizeof(line), format, list);+ va_end(list);+ lx_os_print(line);+}+voidarc4random_buf(void *buffer, size_t size){diff --git a/wifi/lx/src/lx_bus.c b/wifi/lx/src/lx_bus.cindex f8a91a3..55275c0 100644--- a/wifi/lx/src/lx_bus.c+++ b/wifi/lx/src/lx_bus.c@@ -10,10 +10,11 @@* in mission mode and has ce.c and hal.c set up the copy engines' rings, htc.c connects its* services over them and wmi.c has the firmware say what the radio is ("service ready") and,* given the driver's configuration, that it is ready for commands ("unified ready"); mac.c- * registers the radio with what stands in for mac80211 (lx_80211.c). What the firmware said is- * then put in the log, with the boot-arg wifi_scan=1 the station of lx_80211.c has the radio- * scan, and the driver is taken down again the way its own removal does it- * (ath11k_core_deinit()). The data path is not built.+ * registers the radio with what stands in for mac80211 (lx_80211.c) and sets the data path's+ * rings up. What the firmware said is then put in the log. With the boot-arg wifi_scan=1 the+ * station of lx_80211.c has the radio scan, and the driver is taken down again the way its own+ * removal does it (ath11k_core_deinit()); with wifi_join=1 the station joins the network the+ * kernel was given, and the driver stays up, carrying the kernel's frames, until lx_stop().** The kernel's boot-arg wifi_lx says how far the radio's registers are touched: 1, not at all* (every write is said and dropped, every read is 0: the driver's own exchange and nothing@@ -52,8 +53,8 @@ static struct {unsigned again; /* ... and how many writes to it in a row have not been said */volatile bool looking; /* the thread that looks at the copy engines is wanted ... */volatile bool looks; /* ... and runs */+ volatile bool data; /* ... and looks at the data path's rings as well */unsigned same; /* it has written a ring's pointer what it held so many times */- unsigned data_path; /* messages for the data path, which is not built */} bus;/* ---- what the driver says ---------------------------------------------------------------------- */@@ -246,10 +247,16 @@ bus_write32(struct ath11k_base *ab, u32 offset, u32 value)}/*- * In place of the copy engines' interrupts: each engine is looked at as its interrupt would have+ * In place of the radio's interrupts: each copy engine is looked at as its interrupt would have* ath11k do (ce.c: ath11k_ce_per_engine_service(), which takes what has been received to its- * owner and posts fresh buffers), once a millisecond, from the bus's start to its stop.+ * owner and posts fresh buffers), and once the driver has "enabled the data path's interrupts"+ * so is each of the groups its rings are in (dp.c: ath11k_dp_service_srng(), which is what the+ * driver's NAPI poll calls: frames received, frames that have been sent, errors, the reorder+ * block's answers). Once a millisecond while nothing comes; again at once while a group has+ * used up what it was allowed in one go.*/+#define DATA_BUDGET 64+static voidbus_looks(void *argument){@@ -257,10 +264,17 @@ bus_looks(void *argument)bus.looks = true;while (bus.looking) {+ bool more = false;+for (unsigned i = 0; i < ab->hw_params.ce_count; i++) {ath11k_ce_per_engine_service(ab, i);}- lx_pause_ms(1);+ for (unsigned i = 0; bus.data && i < ATH11K_EXT_IRQ_GRP_NUM_MAX; i++) {+ more |= ath11k_dp_service_srng(ab, &ab->ext_irq_grp[i], DATA_BUDGET) >= DATA_BUDGET;+ }+ if (!more) {+ lx_pause_ms(1);+ }}bus.looks = false;}@@ -274,6 +288,7 @@ bus_looks(void *argument)static voidbus_quiet(void){+ bus.data = false;bus.looking = false;while (bus.looks) {lx_pause_ms(1);@@ -373,10 +388,15 @@ bus_power_down(struct ath11k_base *ab, bool is_suspend){}+/* pcic.c: ath11k_pcic_ext_irq_enable(): the data path's rings are set up, and are looked at from here on */static voidbus_irq_enable(struct ath11k_base *ab){- /* (the data path's interrupts, when there is a data path) */+ for (unsigned i = 0; i < ATH11K_EXT_IRQ_GRP_NUM_MAX; i++) {+ ab->ext_irq_grp[i].ab = ab;+ ab->ext_irq_grp[i].grp_id = i;+ }+ bus.data = true;}static void@@ -398,23 +418,6 @@ static const struct ath11k_hif_ops bus_ops = {/* (no interrupt vectors are offered: the rings are then set up without any, see ce.c) */};-/* ---- the first things the driver does with parts that are not built -------------------------------- */--/* dp_rx.c's: what a copy engine has received for the data path */-void-ath11k_dp_htt_htc_t2h_msg_handler(struct ath11k_base *ab, struct sk_buff *skb)-{- if (bus.data_path++ < 4) {- char text[3 * 32 + 1] = "";-- for (unsigned i = 0; i < skb->len && i < 32; i++) {- snprintf(text + 3 * i, 4, " %02x", skb->data[i]);- }- printf("lx: a message for the data path, which is not built: %u bytes, beginning%s\n", skb->len, text);- }- dev_kfree_skb_any(skb);-}-/* ---- the device tree, of which there is none ------------------------------------------------------ */int@@ -485,7 +488,9 @@ say_radio(struct ath11k_base *ab)}}-/* ---- the entry ------------------------------------------------------------------------------------ */+/* ---- the entries ---------------------------------------------------------------------------------- */++static struct ath11k_base *volatile driver; /* the driver, while it is up: between lx_start() and lx_stop() */intlx_start(void)@@ -502,7 +507,13 @@ lx_start(void)printf("lx: no thread, or no memory the radio can be given\n");return (ENOMEM);}- ath11k_debug_mask = ATH11K_DBG_QMI | ATH11K_DBG_BOOT | ATH11K_DBG_AHB | ATH11K_DBG_HTC | ATH11K_DBG_WMI | ATH11K_DBG_REG;+ ath11k_debug_mask = ATH11K_DBG_QMI | ATH11K_DBG_BOOT | ATH11K_DBG_AHB | ATH11K_DBG_WMI | ATH11K_DBG_REG | ATH11K_DBG_MAC;+ /*+ * The driver's parameter "frame_mode": Ethernet. The firmware then puts frames into 802.11+ * and takes them out of it, and ciphers them: what passes between the driver and the layer+ * above is what goes over a cable.+ */+ ath11k_frame_mode = ATH11K_HW_TXRX_ETHERNET;device.of_node = &node;device.kobj.name = "wifi";@@ -553,10 +564,39 @@ lx_start(void)lx_pause_ms(1000); /* (for what the firmware says unasked once it is ready) */say_radio(ab);- ret = lx_os_option("wifi_scan") ? lx_station_scan() : 0;+ driver = ab;+ if (lx_os_option("wifi_join")) {+ if ((ret = lx_station_join()) == 0) {+ if (lx_os_option("wifi_hold")) { /* (seconds to stay before returning: to see frames pass) */+ lx_pause_ms(1000 * lx_os_option("wifi_hold"));+ lx_station_say();+ }+ return (0); /* the network is joined, and the driver stays up until lx_stop() */+ }+ } else {+ ret = lx_os_option("wifi_scan") ? lx_station_scan() : 0;+ }+ lx_stop();+ return (ret);+}++/* The network left, and the driver down as its own removal does it (the copy engines are let go of on the way: bus_quiet()). */+void+lx_stop(void)+{+ struct ath11k_base *ab = driver;- /* Down again, as the driver's removal does it (the copy engines are let go of on the way: bus_quiet()). */+ if (ab == NULL) {+ return;+ }+ driver = NULL;+ lx_station_leave();ath11k_core_deinit(ab);printf("lx: the driver is down again\n");- return (ret);+}++int+lx_transmit(const unsigned char *frame, unsigned long length)+{+ return (driver != NULL ? lx_station_send(frame, length) : ENETDOWN);}diff --git a/wifi/lx/src/lx_wpa.c b/wifi/lx/src/lx_wpa.cnew file mode 100644index 0000000..bf33d77--- /dev/null+++ b/wifi/lx/src/lx_wpa.c@@ -0,0 +1,523 @@+/*+ * The arithmetic of WPA2 with a passphrase (lx_wpa.h): SHA-1 and HMAC over it (FIPS 180, RFC+ * 2104), the key of a name and a passphrase (PBKDF2, RFC 8018), the function that makes the+ * handshake's keys out of that key, two addresses and two nonces (IEEE 802.11-2020, 12.7.1.2),+ * AES decryption and the unwrapping of a key with it (FIPS 197, RFC 3394), and the messages of+ * the four-way and the group-key handshake (12.7.6, 12.7.7; figure 12-35 is the layout).+ *+ * Nothing here is taken from another implementation; the tests in tools/wpa-test check it+ * against the standards' own examples and against Python's hashlib and "cryptography".+ * Nothing here is written for speed, and nothing here says a key in a message.+ */+#ifdef _KERNEL+#include <sys/param.h>+#include <sys/systm.h>+#else+#include <stdint.h>+#include <string.h>+#endif++#include "lx_wpa.h"++/* ---- SHA-1 ------------------------------------------------------------------------------------ */++struct sha1 {+ uint32_t h[5];+ uint64_t length; /* bytes so far */+ uint8_t block[64];+};++static uint32_t+rol(uint32_t x, unsigned n)+{+ return (x << n | x >> (32 - n));+}++static void+sha1_block(uint32_t h[5], const uint8_t *p)+{+ uint32_t w[80], a = h[0], b = h[1], c = h[2], d = h[3], e = h[4];++ for (unsigned t = 0; t < 16; t++) {+ w[t] = (uint32_t)p[4 * t] << 24 | (uint32_t)p[4 * t + 1] << 16 | (uint32_t)p[4 * t + 2] << 8 | p[4 * t + 3];+ }+ for (unsigned t = 16; t < 80; t++) {+ w[t] = rol(w[t - 3] ^ w[t - 8] ^ w[t - 14] ^ w[t - 16], 1);+ }+ for (unsigned t = 0; t < 80; t++) {+ uint32_t f = t < 20 ? ((b & c) | (~b & d)) + 0x5a827999 : t < 40 ? (b ^ c ^ d) + 0x6ed9eba1 : t < 60 ?+ ((b & c) | (b & d) | (c & d)) + 0x8f1bbcdc : (b ^ c ^ d) + 0xca62c1d6;+ uint32_t next = rol(a, 5) + f + e + w[t];++ e = d;+ d = c;+ c = rol(b, 30);+ b = a;+ a = next;+ }+ h[0] += a;+ h[1] += b;+ h[2] += c;+ h[3] += d;+ h[4] += e;+}++static void+sha1_begin(struct sha1 *s)+{+ s->h[0] = 0x67452301;+ s->h[1] = 0xefcdab89;+ s->h[2] = 0x98badcfe;+ s->h[3] = 0x10325476;+ s->h[4] = 0xc3d2e1f0;+ s->length = 0;+}++static void+sha1_more(struct sha1 *s, const uint8_t *data, unsigned length)+{+ for (unsigned i = 0; i < length; i++) {+ s->block[s->length++ % 64] = data[i];+ if (s->length % 64 == 0) {+ sha1_block(s->h, s->block);+ }+ }+}++static void+sha1_end(struct sha1 *s, uint8_t digest[20])+{+ uint64_t bits = s->length * 8;+ uint8_t tail[8];++ sha1_more(s, (const uint8_t *)"\x80", 1);+ while (s->length % 64 != 56) {+ sha1_more(s, (const uint8_t *)"", 1);+ }+ for (unsigned i = 0; i < 8; i++) {+ tail[i] = (uint8_t)(bits >> (56 - 8 * i));+ }+ sha1_more(s, tail, 8);+ for (unsigned i = 0; i < 20; i++) {+ digest[i] = (uint8_t)(s->h[i / 4] >> (24 - 8 * (i % 4)));+ }+}++/* HMAC-SHA1 of several pieces in a row. */+static void+hmac_sha1(const uint8_t *key, unsigned key_length, const uint8_t *const pieces[], const unsigned lengths[], unsigned count,+ uint8_t digest[20])+{+ uint8_t pad[64], hashed[20], inner[20];+ struct sha1 s;++ if (key_length > 64) {+ sha1_begin(&s);+ sha1_more(&s, key, key_length);+ sha1_end(&s, hashed);+ key = hashed;+ key_length = 20;+ }+ for (unsigned i = 0; i < 64; i++) {+ pad[i] = (i < key_length ? key[i] : 0) ^ 0x36;+ }+ sha1_begin(&s);+ sha1_more(&s, pad, 64);+ for (unsigned i = 0; i < count; i++) {+ sha1_more(&s, pieces[i], lengths[i]);+ }+ sha1_end(&s, inner);+ for (unsigned i = 0; i < 64; i++) {+ pad[i] ^= 0x36 ^ 0x5c;+ }+ sha1_begin(&s);+ sha1_more(&s, pad, 64);+ sha1_more(&s, inner, 20);+ sha1_end(&s, digest);+ memset(pad, 0, sizeof(pad));+ memset(inner, 0, sizeof(inner));+}++/* ---- the key of a name and a passphrase -------------------------------------------------------- */++/* PBKDF2 with HMAC-SHA1, 4096 rounds, 32 bytes: two blocks of 20, of the second the first 12. */+void+lx_wpa_pmk(const unsigned char *passphrase, unsigned passphrase_length, const unsigned char *name, unsigned name_length,+ unsigned char pmk[32])+{+ for (unsigned block = 1; block <= 2; block++) {+ const uint8_t number[4] = { 0, 0, 0, (uint8_t)block };+ const uint8_t *first[2] = { name, number };+ const unsigned first_lengths[2] = { name_length, 4 };+ uint8_t u[20], sum[20];++ hmac_sha1(passphrase, passphrase_length, first, first_lengths, 2, u);+ memcpy(sum, u, 20);+ for (unsigned round = 1; round < 4096; round++) {+ const uint8_t *again[1] = { u };+ const unsigned again_lengths[1] = { 20 };++ hmac_sha1(passphrase, passphrase_length, again, again_lengths, 1, u);+ for (unsigned i = 0; i < 20; i++) {+ sum[i] ^= u[i];+ }+ }+ memcpy(pmk + 20 * (block - 1), sum, block == 1 ? 20 : 12);+ memset(u, 0, sizeof(u));+ memset(sum, 0, sizeof(sum));+ }+}++/* The standard's PRF: HMAC-SHA1 of (label, a zero byte, data, a counter byte), block after block. */+static void+prf(const uint8_t *key, unsigned key_length, const char *label, const uint8_t *data, unsigned data_length, uint8_t *out,+ unsigned out_length)+{+ uint8_t zero = 0, counter = 0, digest[20];+ const uint8_t *pieces[4] = { (const uint8_t *)label, &zero, data, &counter };+ const unsigned lengths[4] = { (unsigned)strlen(label), 1, data_length, 1 };++ for (unsigned done = 0; done < out_length; done += 20, counter++) {+ hmac_sha1(key, key_length, pieces, lengths, 4, digest);+ memcpy(out + done, digest, out_length - done < 20 ? out_length - done : 20);+ }+ memset(digest, 0, sizeof(digest));+}++/* ---- AES-128, decryption only, and the unwrapping of a key --------------------------------------- */++static uint8_t sbox[256], inverse_sbox[256];++static uint8_t+times(uint8_t a, uint8_t b) /* in GF(2^8) modulo x^8 + x^4 + x^3 + x + 1 */+{+ uint8_t product = 0;++ for (; b != 0; b >>= 1) {+ if (b & 1) {+ product ^= a;+ }+ a = (uint8_t)(a << 1 ^ (a & 0x80 ? 0x1b : 0));+ }+ return (product);+}++/* FIPS 197, 5.1.1: a byte's inverse in the field, then the affine map. */+static void+aes_tables(void)+{+ if (sbox[0] != 0) {+ return;+ }+ for (unsigned x = 0; x < 256; x++) {+ uint8_t inverse = 0, s;++ for (unsigned y = 1; y < 256 && x != 0; y++) {+ if (times((uint8_t)x, (uint8_t)y) == 1) {+ inverse = (uint8_t)y;+ break;+ }+ }+ s = inverse;+ for (unsigned i = 1; i < 5; i++) {+ s ^= (uint8_t)(inverse << i | inverse >> (8 - i));+ }+ s ^= 0x63;+ sbox[x] = s;+ inverse_sbox[s] = (uint8_t)x;+ }+}++static void+aes_keys(const uint8_t key[16], uint8_t round_keys[176])+{+ uint8_t constant = 1;++ aes_tables();+ memcpy(round_keys, key, 16);+ for (unsigned i = 16; i < 176; i += 4) {+ uint8_t word[4];++ memcpy(word, round_keys + i - 4, 4);+ if (i % 16 == 0) {+ uint8_t first = word[0];++ word[0] = sbox[word[1]] ^ constant;+ word[1] = sbox[word[2]];+ word[2] = sbox[word[3]];+ word[3] = sbox[first];+ constant = times(constant, 2);+ }+ for (unsigned j = 0; j < 4; j++) {+ round_keys[i + j] = round_keys[i - 16 + j] ^ word[j];+ }+ }+}++/* FIPS 197, 5.3: the inverse cipher on one block (bytes in column order: byte r of column c is s[4c + r]). */+static void+aes_decrypt(const uint8_t round_keys[176], uint8_t s[16])+{+ for (unsigned i = 0; i < 16; i++) {+ s[i] ^= round_keys[160 + i];+ }+ for (int round = 9; round >= 0; round--) {+ uint8_t t[16];++ for (unsigned c = 0; c < 4; c++) { /* the rows shifted back, and the bytes substituted back */+ for (unsigned r = 0; r < 4; r++) {+ t[4 * ((c + r) % 4) + r] = inverse_sbox[s[4 * c + r]];+ }+ }+ for (unsigned i = 0; i < 16; i++) {+ t[i] ^= round_keys[16 * round + i];+ }+ if (round == 0) {+ memcpy(s, t, 16);+ break;+ }+ for (unsigned c = 0; c < 4; c++) { /* the columns mixed back */+ const uint8_t *a = t + 4 * c;++ s[4 * c + 0] = times(a[0], 14) ^ times(a[1], 11) ^ times(a[2], 13) ^ times(a[3], 9);+ s[4 * c + 1] = times(a[0], 9) ^ times(a[1], 14) ^ times(a[2], 11) ^ times(a[3], 13);+ s[4 * c + 2] = times(a[0], 13) ^ times(a[1], 9) ^ times(a[2], 14) ^ times(a[3], 11);+ s[4 * c + 3] = times(a[0], 11) ^ times(a[1], 13) ^ times(a[2], 9) ^ times(a[3], 14);+ }+ }+}++/*+ * RFC 3394, 2.2.2: `wrapped` is 8 bytes longer than what comes out, which goes to `plain`. 0, or -1+ * if the length is not one a wrapped key has or the check value does not come out.+ */+static int+aes_unwrap(const uint8_t kek[16], const uint8_t *wrapped, unsigned length, uint8_t *plain)+{+ unsigned n = length / 8 - 1;+ uint8_t round_keys[176], a[8], block[16];+ int good = 0;++ if (length % 8 != 0 || length < 24) {+ return (-1);+ }+ aes_keys(kek, round_keys);+ memcpy(a, wrapped, 8);+ memcpy(plain, wrapped + 8, 8 * n);+ for (int j = 5; j >= 0; j--) {+ for (unsigned i = n; i >= 1; i--) {+ uint64_t t = (uint64_t)n * (unsigned)j + i;++ memcpy(block, a, 8);+ for (unsigned k = 0; k < 8; k++) {+ block[7 - k] ^= (uint8_t)(t >> (8 * k));+ }+ memcpy(block + 8, plain + 8 * (i - 1), 8);+ aes_decrypt(round_keys, block);+ memcpy(a, block, 8);+ memcpy(plain + 8 * (i - 1), block + 8, 8);+ }+ }+ for (unsigned i = 0; i < 8; i++) {+ good |= a[i] ^ 0xa6;+ }+ memset(round_keys, 0, sizeof(round_keys));+ memset(block, 0, sizeof(block));+ return (good == 0 ? 0 : -1);+}++/* ---- the handshake -------------------------------------------------------------------------------- */++/*+ * A key message, after the four bytes every EAPOL frame begins with (version, type 3, length):+ * 4 the kind of descriptor (2: RSN) 5 what the message is (bits below) 7 key length+ * 9 replay counter (8) 17 nonce (32) 49 IV (16) 65 RSC (8) 73 reserved (8)+ * 81 MIC (16) 97 length of the key data 99 key data+ */+#define AT_KIND 4+#define AT_INFO 5+#define AT_REPLAY 9+#define AT_NONCE 17+#define AT_RSC 65+#define AT_MIC 81+#define AT_DATA_LENGTH 97+#define AT_DATA 99+#define MESSAGE_MOST 640++#define INFO_VERSION 0x0007 /* 2: HMAC-SHA1 for the MIC, the AES key wrap for the key data */+#define INFO_PAIRWISE 0x0008+#define INFO_INSTALL 0x0040+#define INFO_ACK 0x0080+#define INFO_MIC 0x0100+#define INFO_SECURE 0x0200+#define INFO_ENCRYPTED 0x1000++static void+mic_of(const struct lx_wpa *wpa, const uint8_t *message, unsigned length, uint8_t mic[16])+{+ const uint8_t zeros[16] = { 0 };+ const uint8_t *pieces[3] = { message, zeros, message + AT_MIC + 16 };+ const unsigned lengths[3] = { AT_MIC, 16, length - AT_MIC - 16 };+ uint8_t digest[20];++ hmac_sha1(wpa->kck, 16, pieces, lengths, 3, digest);+ memcpy(mic, digest, 16);+}++/* The keys of the handshake and the pairwise key, from the PMK, both addresses and both nonces. */+static void+derive(struct lx_wpa *wpa)+{+ uint8_t data[76], keys[48];+ int own_first = memcmp(wpa->own, wpa->peer, 6) < 0, own_nonce_first = memcmp(wpa->own_nonce, wpa->peer_nonce, 32) < 0;++ memcpy(data, own_first ? wpa->own : wpa->peer, 6);+ memcpy(data + 6, own_first ? wpa->peer : wpa->own, 6);+ memcpy(data + 12, own_nonce_first ? wpa->own_nonce : wpa->peer_nonce, 32);+ memcpy(data + 44, own_nonce_first ? wpa->peer_nonce : wpa->own_nonce, 32);+ prf(wpa->pmk, 32, "Pairwise key expansion", data, sizeof(data), keys, sizeof(keys));+ memcpy(wpa->kck, keys, 16);+ memcpy(wpa->kek, keys + 16, 16);+ memcpy(wpa->pairwise, keys + 32, 16);+ memset(keys, 0, sizeof(keys));+ wpa->have_keys = 1;+}++/* Our message in answer to `message`: the same counter, our bits, our nonce and key data if any, signed. */+static void+answer(const struct lx_wpa *wpa, const uint8_t *message, unsigned info, const uint8_t *nonce, const uint8_t *data,+ unsigned data_length, uint8_t *reply, unsigned *reply_length)+{+ unsigned length = AT_DATA + data_length;++ memset(reply, 0, length);+ reply[0] = message[0];+ reply[1] = 3;+ reply[2] = (uint8_t)((length - 4) >> 8);+ reply[3] = (uint8_t)(length - 4);+ reply[AT_KIND] = 2;+ reply[AT_INFO] = (uint8_t)(info >> 8);+ reply[AT_INFO + 1] = (uint8_t)info;+ memcpy(reply + AT_REPLAY, message + AT_REPLAY, 8);+ if (nonce != NULL) {+ memcpy(reply + AT_NONCE, nonce, 32);+ }+ reply[AT_DATA_LENGTH] = (uint8_t)(data_length >> 8);+ reply[AT_DATA_LENGTH + 1] = (uint8_t)data_length;+ if (data_length != 0) {+ memcpy(reply + AT_DATA, data, data_length);+ }+ mic_of(wpa, reply, length, reply + AT_MIC);+ *reply_length = length;+}++/* The group key among what message 3 (or a group message) carries: an element 0xdd of the suite 00-0f-ac, kind 1. */+static int+group_key(struct lx_wpa *wpa, const uint8_t *data, unsigned length, const uint8_t *counter)+{+ for (unsigned at = 0; at + 2 <= length && at + 2 + data[at + 1] <= length; at += 2 + data[at + 1]) {+ const uint8_t *e = data + at;++ if (e[0] == 0xdd && e[1] == 0) {+ break; /* (padding from here on) */+ }+ if (e[0] == 0xdd && e[1] >= 6 + 5 && e[2] == 0x00 && e[3] == 0x0f && e[4] == 0xac && e[5] == 1 &&+ e[1] - 6u <= sizeof(wpa->group)) {+ wpa->group_index = e[6] & 3;+ wpa->group_length = e[1] - 6u;+ memcpy(wpa->group, e + 8, wpa->group_length);+ memcpy(wpa->group_counter, counter, 8);+ return (0);+ }+ }+ return (-1);+}++int+lx_wpa_message(struct lx_wpa *wpa, const unsigned char *message, unsigned length, unsigned char *reply, unsigned *reply_length,+ const char **why)+{+ uint8_t mic[16], data[MESSAGE_MOST];+ unsigned info, body, data_length, difference = 0;+ const char *nothing;++ why = why != NULL ? why : ¬hing;+ *why = "";+ *reply_length = 0;+ if (length < 4 || message[1] != 3) {+ return (LX_WPA_NOTHING);+ }+ body = (unsigned)message[2] << 8 | message[3];+ if (length < AT_DATA || 4 + body > length || 4 + body < AT_DATA || 4 + body > MESSAGE_MOST) {+ *why = "its length is not a key message's";+ return (LX_WPA_BAD);+ }+ length = 4 + body;+ info = (unsigned)message[AT_INFO] << 8 | message[AT_INFO + 1];+ data_length = (unsigned)message[AT_DATA_LENGTH] << 8 | message[AT_DATA_LENGTH + 1];+ if (message[AT_KIND] != 2) {+ *why = "it is not an RSN key message (WPA of the first kind?)";+ return (LX_WPA_BAD);+ }+ if ((info & INFO_VERSION) != 2) {+ *why = "its key descriptor is not version 2 (the network wants another kind of key management)";+ return (LX_WPA_BAD);+ }+ if (AT_DATA + data_length > length) {+ *why = "its key data is longer than the message";+ return (LX_WPA_BAD);+ }++ /* message 1: the access point's nonce, unsigned */+ if ((info & (INFO_PAIRWISE | INFO_ACK | INFO_MIC)) == (INFO_PAIRWISE | INFO_ACK)) {+ memcpy(wpa->peer_nonce, message + AT_NONCE, 32);+ derive(wpa);+ answer(wpa, message, 2 | INFO_PAIRWISE | INFO_MIC, wpa->own_nonce, wpa->rsn, wpa->rsn_length, reply, reply_length);+ return (LX_WPA_ANSWER);+ }++ /* everything else is signed, by an access point that has shown it has the key */+ if (!(info & INFO_MIC) || !(info & INFO_ACK)) {+ return (LX_WPA_NOTHING);+ }+ if (!wpa->have_keys) {+ *why = "it is signed, and there has been no message 1 to make the keys from";+ return (LX_WPA_BAD);+ }+ mic_of(wpa, message, length, mic);+ for (unsigned i = 0; i < 16; i++) {+ difference |= mic[i] ^ message[AT_MIC + i];+ }+ if (difference != 0) {+ *why = "its signature is not right (a wrong passphrase gives this)";+ return (LX_WPA_BAD);+ }+ if (wpa->replay_known && memcmp(message + AT_REPLAY, wpa->replay, 8) <= 0) {+ *why = "its counter is not beyond the last one's (a message played again)";+ return (LX_WPA_BAD);+ }+ if ((info & INFO_PAIRWISE) && memcmp(message + AT_NONCE, wpa->peer_nonce, 32) != 0) {+ *why = "its nonce is not message 1's";+ return (LX_WPA_BAD);+ }+ if (!(info & INFO_ENCRYPTED) || aes_unwrap(wpa->kek, message + AT_DATA, data_length, data) != 0) {+ *why = "its key data does not unwrap";+ return (LX_WPA_BAD);+ }+ if (group_key(wpa, data, data_length - 8, message + AT_RSC) != 0) {+ memset(data, 0, sizeof(data));+ *why = "there is no group key in it";+ return (LX_WPA_BAD);+ }+ memset(data, 0, sizeof(data));+ memcpy(wpa->replay, message + AT_REPLAY, 8);+ wpa->replay_known = 1;++ /* message 3 of the four, or message 1 of a new group key */+ if (info & INFO_PAIRWISE) {+ answer(wpa, message, 2 | INFO_PAIRWISE | INFO_MIC | INFO_SECURE, NULL, NULL, 0, reply, reply_length);+ return (LX_WPA_KEYS);+ }+ answer(wpa, message, 2 | INFO_MIC | INFO_SECURE, NULL, NULL, 0, reply, reply_length);+ return (LX_WPA_GROUP);+}diff --git a/wifi/lx/src/lx_wpa.h b/wifi/lx/src/lx_wpa.hnew file mode 100644index 0000000..f5ff673--- /dev/null+++ b/wifi/lx/src/lx_wpa.h@@ -0,0 +1,49 @@+/*+ * WPA2 with a passphrase, as a station sees it: the key a name and a passphrase make, and the+ * four-way handshake in which an access point and a station prove that key to each other and+ * arrive at the keys their frames are ciphered with (IEEE 802.11-2020, 12.7; RSN, AKM "PSK",+ * key descriptor version 2: HMAC-SHA1 and the AES key wrap). lx_wpa.c is the arithmetic and+ * nothing else -- no radio, no kernel --, so that it runs on the machine the kernel is built on+ * (tools/wpa-test) as it runs in the kernel.+ */+#ifndef _LX_WPA_H_+#define _LX_WPA_H_++/* The key ("PMK") of a network's name and passphrase: 32 bytes. Slow on purpose: 8192 rounds of HMAC-SHA1. */+void lx_wpa_pmk(const unsigned char *passphrase, unsigned passphrase_length, const unsigned char *name, unsigned name_length,+ unsigned char pmk[32]);++struct lx_wpa {+ unsigned char pmk[32];+ unsigned char own[6], peer[6]; /* the station's address and the access point's */+ unsigned char own_nonce[32]; /* 32 bytes nobody can guess, fresh for every handshake */+ const unsigned char *rsn; /* the station's RSN element as its association request had it ... */+ unsigned rsn_length; /* ... which goes into message 2 */+ /* from here on: lx_wpa.c's */+ unsigned char peer_nonce[32];+ unsigned char kck[16], kek[16]; /* the keys the handshake's own messages are signed and ciphered with */+ unsigned char replay[8]; /* the counter of the last message accepted */+ int have_keys, replay_known;+ /* what comes out of it */+ unsigned char pairwise[16]; /* the key for frames between the two ("TK", CCMP) */+ unsigned char group[32]; /* the key the access point sends to everybody with ("GTK") ... */+ unsigned group_length, group_index; /* ... its length, and its number (1 to 3) */+ unsigned char group_counter[8]; /* ... and the packet number its frames have got to ("RSC") */+};++/*+ * What a message of the handshake (an EAPOL frame: what follows the Ethernet header of a frame+ * of type 0x888e) calls for. `reply` has room for LX_WPA_REPLY_MOST bytes.+ */+#define LX_WPA_REPLY_MOST 256+enum {+ LX_WPA_BAD = -1, /* not a message that can be answered: *why says what was wrong with it */+ LX_WPA_NOTHING = 0, /* not for us to answer (not a key message) */+ LX_WPA_ANSWER = 1, /* message 1: send the reply (message 2) */+ LX_WPA_KEYS = 2, /* message 3: send the reply (message 4), then both keys are to be used */+ LX_WPA_GROUP = 3, /* a new group key later on: send the reply, then use the new group key */+};+int lx_wpa_message(struct lx_wpa *wpa, const unsigned char *message, unsigned length, unsigned char *reply,+ unsigned *reply_length, const char **why);++#endif