소스 검색

Fix Intel 7265 WiFi RX with software CCMP

The 7265D-29 firmware accepts ADD_STA_KEY but never decrypts RX with the installed PTK/GTK: both report SEC_ENC_ERR while TX (which embeds the TK in TX_CMD) works. Decrypt CCMP RX in software (AES-CCM, RFC 3610) when the firmware reports a failure, keeping the firmware for TX.

Also align the internal station IDs with iwlmvm (aux 1, AP 0), fill the MAC context reciprocals, install the GTK in slot 1, and add diagnostics for the key install, MAC context, RX drops and TX responses.

Keep the PTK and EAPOL replay counter in the kernel and fetch them by connection ID, so the background wifi __keep helper no longer exceeds the 64-byte SYS_SPAWN argument limit. Add BSSID output to wifi scan and an optional BSSID to wifi connect.

Host tests: make test-ccmp covers FIPS-197 AES-128, RFC 3610 and the full 802.11 CCMP vector. Update AGENTS.md and the network, drivers and userland docs.
Johannes Zellner 1 주 전
부모
커밋
fda4ccfe73
13개의 변경된 파일과 775개의 추가작업 그리고 72개의 파일을 삭제
  1. 20 7
      AGENTS.md
  2. 11 2
      Makefile
  3. 226 0
      ccmp.c
  4. 22 0
      ccmp.h
  5. 129 0
      ccmp_test.c
  6. 3 2
      docs/drivers.html
  7. 1 1
      docs/network.html
  8. 1 1
      docs/userland.html
  9. 79 5
      iwl_mvm.c
  10. 7 3
      iwl_mvm.h
  11. 10 0
      syscall.h
  12. 85 34
      ucmd_wifi.c
  13. 181 17
      wifi.c

+ 20 - 7
AGENTS.md

@@ -605,10 +605,10 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   `iwl_mvm.c/h` — firmware commands for the 7265D-29 API: INIT image (BT
   config, NVM HW section -> MAC at word 0x15, TX antennas, PHY config,
   `CALIB_RES_NOTIF_PHY_DB` collection until `INIT_COMPLETE`), runtime image
-  (PHY-DB replay, PHY config, BT config, DQA enable, aux station 0 on queue
+  (PHY-DB replay, PHY config, BT config, DQA enable, aux station 1 on queue
   1, PHY context 0, CAM power, MCC `ZZ`, MAC context 0), LMAC scan
   (`SCAN_OFFLOAD_REQUEST`, wildcard active, 37 channels), connect (PHY
-  context, binding + quota, `SCD_QUEUE_CFG` queue 4, AP station 1, time
+  context, binding + quota, `SCD_QUEUE_CFG` queue 4, AP station 0, time
   event), `ADD_STA_KEY` v1, `TX_CMD` v6 (fixed legacy rates: 1M CCK / 6M
   mgmt, 12M OFDM data), legacy `RX_PHY`/`RX_MPDU` parsing.  `wifi.c/h` —
   802.11 station: beacon/probe parsing (SSID, DS channel, TIM DTIM, RSN with
@@ -616,6 +616,11 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   request (no WMM/HT IEs), Ethernet <-> 802.11 data + LLC/SNAP + host-built
   CCMP header/PN, an EAPOL queue (ethertype 0x888e never reaches
   `net_pump()`), the `wifi` netdev and `SYS_WIFI` (110, multiplexed op).
+  RX CCMP is decrypted in software (`ccmp.c`, AES-CCM, RFC 3610 vector in
+  the host test) when the firmware reports `SEC_ENC_ERR`, because this
+  7265D-29 firmware does not use correctly installed `ADD_STA_KEY` keys for
+  RX even though TX (which embeds the TK in `TX_CMD`) works; there is no
+  software replay window yet.
   The firmware is loaded on the first `wifi` command, not at boot.
   `netdev_shutdown()` always calls `wifi_shutdown()` before a kexec (the RX
   ring would keep writing into reused pages).  The ring-3 side is
@@ -625,6 +630,9 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   test `make test-wpa`).  After the handshake `wifi connect` installs the
   TK/GTK, calls `SYS_WIFI_AUTHORIZE` (data port open + `netdev_select
   ("wifi")`), runs DHCP and leaves `wifi __keep` running for group rekeys.
+  The helper's PTK and EAPOL replay counter are kept in the kernel
+  (`SYS_WIFI_SET_PTK`/`SYS_WIFI_GET_PTK`) and fetched by connection ID, so
+  the 64-byte `SYS_SPAWN` argument limit cannot truncate the rekey state.
   There is no QEMU model: test on the Chromebook over `make net-dev` with
   the RNDIS phone/ASIX dongle as the management link and `make netmon` for
   the `iwl:`/`wifi:` trail.
@@ -1936,8 +1944,13 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     stack call drain it).  The connect and firmware load hold the BKL for up
     to a few seconds.  Group rekeys need the background `wifi __keep` helper
     (it carries the PTK in its argument and memory); if it is killed the link
-    drops at the next rekey.  The SNonce comes from the weak TLS DRBG.  The
-    driver was written against the Linux iwlwifi sources without hardware
-    in the loop; expect bring-up debugging on the Chromebook.  The kernel
-    budget is tight: WiFi added ~20 KB, `_end` is ~0x88750 (31 KB below the
-    `0x90000` wall).
+    drops at the next rekey.  The SNonce comes from the weak TLS DRBG.
+    RX CCMP is decrypted in software (`ccmp.c`) when the firmware reports
+    `SEC_ENC_ERR`: on the tested 7265D-29 the firmware does not use keys that
+    `ADD_STA_KEY` accepted, for either the PTK or the GTK, while TX (where the
+    TK is embedded in `TX_CMD`) works.  The software path has no replay
+    window yet and uses a byte-oriented AES-CCM per frame, so high RX
+    throughput is CPU-bound.  The driver was written against the Linux iwlwifi
+    sources without hardware in the loop; expect bring-up debugging on the
+    Chromebook.  The kernel budget is tight: WiFi added ~20 KB, `_end` is
+    ~0x89710 (27 KB below the `0x90000` wall).

파일 크기가 너무 크기때문에 변경 상태를 표시하지 않습니다.
+ 11 - 2
Makefile


+ 226 - 0
ccmp.c

@@ -0,0 +1,226 @@
+/* Software CCMP (AES-CCM) RX decryption: see ccmp.h.
+ *
+ * Self-contained AES-128 + CCM (RFC 3610, L=2, M=8, 13-byte nonce) for the
+ * 802.11 CCMP frame format.  The firmware normally does this, but the 7265D
+ * path can report SEC_ENC_ERR for both the pairwise and group keys even
+ * though the keys are installed and the same keys encrypt TX correctly. */
+
+#include "ccmp.h"
+
+static void cpy(unsigned char *d, const unsigned char *s, unsigned int n)
+{
+	while (n--)
+		*d++ = *s++;
+}
+
+static void zero(unsigned char *d, unsigned int n)
+{
+	while (n--)
+		*d++ = 0;
+}
+
+static void xorb(unsigned char *d, const unsigned char *s, unsigned int n)
+{
+	while (n--)
+		*d++ ^= *s++;
+}
+
+/* ---- AES-128 ------------------------------------------------------------- */
+static const unsigned char sbox[256] = {
+	0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76,
+	0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0,
+	0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15,
+	0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75,
+	0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84,
+	0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf,
+	0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8,
+	0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2,
+	0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73,
+	0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb,
+	0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79,
+	0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08,
+	0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a,
+	0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e,
+	0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf,
+	0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16,
+};
+
+static unsigned char xt(unsigned char x)
+{
+	return (unsigned char)((x << 1) ^ ((x & 0x80) ? 0x1b : 0));
+}
+
+static void aes_setkey(unsigned char rk[176], const unsigned char key[16])
+{
+	unsigned char rcon = 1;
+	unsigned int i;
+
+	cpy(rk, key, 16);
+	for (i = 16; i < 176; i += 4) {
+		unsigned char t[4];
+
+		cpy(t, rk + i - 4, 4);
+		if (i % 16 == 0) {
+			unsigned char u = t[0];
+
+			t[0] = sbox[t[1]] ^ rcon;
+			t[1] = sbox[t[2]];
+			t[2] = sbox[t[3]];
+			t[3] = sbox[u];
+			rcon = xt(rcon);
+		}
+		rk[i] = rk[i - 16] ^ t[0];
+		rk[i + 1] = rk[i - 15] ^ t[1];
+		rk[i + 2] = rk[i - 14] ^ t[2];
+		rk[i + 3] = rk[i - 13] ^ t[3];
+	}
+}
+
+static void aes_encrypt(const unsigned char rk[176], const unsigned char in[16],
+			unsigned char out[16])
+{
+	unsigned char s[16], t[16];
+	unsigned int r, i, c;
+
+	cpy(s, in, 16);
+	for (i = 0; i < 16; i++)
+		s[i] ^= rk[i];
+	for (r = 1; r <= 10; r++) {
+		for (i = 0; i < 16; i++)                 /* sub + shift rows */
+			t[i] = sbox[s[(i + 4 * (i % 4)) % 16]];
+		if (r < 10) {
+			for (c = 0; c < 4; c++) {        /* mix columns */
+				unsigned char *col = t + 4 * c;
+				unsigned char a0 = col[0], a1 = col[1];
+				unsigned char a2 = col[2], a3 = col[3];
+
+				col[0] = xt(a0) ^ (xt(a1) ^ a1) ^ a2 ^ a3;
+				col[1] = a0 ^ xt(a1) ^ (xt(a2) ^ a2) ^ a3;
+				col[2] = a0 ^ a1 ^ xt(a2) ^ (xt(a3) ^ a3);
+				col[3] = (xt(a0) ^ a0) ^ a1 ^ a2 ^ xt(a3);
+			}
+		}
+		cpy(s, t, 16);
+		for (i = 0; i < 16; i++)
+			s[i] ^= rk[16 * r + i];
+	}
+	cpy(out, s, 16);
+}
+
+/* ---- CCM ----------------------------------------------------------------- */
+/* RFC 3610 CCM with L=2, M=8 and a 13-byte nonce.  `mic` is the encrypted
+ * tag (the last 8 bytes of the CCMP frame). */
+static int ccm_decrypt(const unsigned char key[16],
+		       const unsigned char nonce[13],
+		       const unsigned char *aad, unsigned int alen,
+		       unsigned char *data, unsigned int clen,
+		       const unsigned char *mic)
+{
+	unsigned char rk[176], b0[16], x[16], a[16], s[16], blk[16];
+	unsigned int i, j, n, take;
+
+	if (alen > 0xff00)
+		return -1;
+	aes_setkey(rk, key);
+
+	/* B0: Adata | (M-2)/2 << 3 | L-1, nonce, length (big endian). */
+	b0[0] = 0x59;
+	cpy(b0 + 1, nonce, 13);
+	b0[14] = (unsigned char)(clen >> 8);
+	b0[15] = (unsigned char)clen;
+	aes_encrypt(rk, b0, x);
+
+	/* AAD: 2-byte length prefix, then the bytes, zero padded. */
+	zero(blk, 16);
+	blk[0] = (unsigned char)(alen >> 8);
+	blk[1] = (unsigned char)alen;
+	n = alen < 14 ? alen : 14;
+	cpy(blk + 2, aad, n);
+	xorb(blk, x, 16);
+	aes_encrypt(rk, blk, x);
+	for (i = n; i < alen; i += take) {
+		take = alen - i < 16 ? alen - i : 16;
+		zero(blk, 16);
+		cpy(blk, aad + i, take);
+		xorb(blk, x, 16);
+		aes_encrypt(rk, blk, x);
+	}
+
+	/* CTR decrypt, then CBC-MAC over the plaintext. */
+	for (i = 0; i < clen; i += 16) {
+		take = clen - i < 16 ? clen - i : 16;
+		a[0] = 1;                          /* L-1 */
+		cpy(a + 1, nonce, 13);
+		a[14] = (unsigned char)((i / 16 + 1) >> 8);
+		a[15] = (unsigned char)(i / 16 + 1);
+		aes_encrypt(rk, a, s);
+		for (j = 0; j < take; j++)
+			data[i + j] ^= s[j];
+
+		zero(blk, 16);
+		cpy(blk, data + i, take);
+		xorb(blk, x, 16);
+		aes_encrypt(rk, blk, x);
+	}
+
+	/* T = CBC-MAC, tag = T ^ AES(nonce || counter 0). */
+	a[0] = 1;
+	cpy(a + 1, nonce, 13);
+	a[14] = 0;
+	a[15] = 0;
+	aes_encrypt(rk, a, s);
+	for (j = 0; j < 8; j++)
+		if ((x[j] ^ s[j]) != mic[j])
+			return -1;
+	return 0;
+}
+
+int ccmp_rx_decrypt(unsigned char *f, unsigned int len, unsigned int hdr,
+		    const unsigned char key[16])
+{
+	unsigned char nonce[13], aad[30];
+	unsigned int clen, aad_len, fc, seq;
+
+	if (hdr != 24 && hdr != 26)
+		return -1;                     /* no A4 frames in this driver */
+	if (len < hdr + 16)
+		return -1;
+	clen = len - hdr - 16;                 /* minus CCMP header and MIC */
+
+	/* AAD: FC (mute Retry/PwrMgmt/MoreData, force Protected), A1, A2,
+	 * A3, SC (sequence number zeroed, fragment kept).  The 2-byte
+	 * Duration/ID field is deliberately not part of the AAD. */
+	fc = f[0] | (f[1] << 8);
+	fc &= ~0x3800u;
+	fc |= 0x4000u;
+	aad[0] = (unsigned char)fc;
+	aad[1] = (unsigned char)(fc >> 8);
+	cpy(aad + 2, f + 4, 6);                /* A1 */
+	cpy(aad + 8, f + 10, 6);               /* A2 */
+	cpy(aad + 14, f + 16, 6);              /* A3 */
+	seq = f[22] | (f[23] << 8);
+	seq &= 0x000fu;
+	aad[20] = (unsigned char)seq;
+	aad[21] = (unsigned char)(seq >> 8);
+	aad_len = 22;
+	if (hdr == 26) {
+		/* QoS control: keep TID, clear ack policy/A-MSDU/TXOP. */
+		aad[22] = f[24] & 0x0fu;
+		aad[23] = 0;
+		aad_len = 24;
+	}
+
+	/* CCM nonce: priority/QoS TID, A2, then the PN most significant
+	 * byte first (the CCMP header stores it least significant first). */
+	nonce[0] = hdr == 26 ? (f[24] & 0x0fu) : 0;
+	cpy(nonce + 1, f + 10, 6);             /* A2 */
+	nonce[7] = f[hdr + 7];                 /* PN5 */
+	nonce[8] = f[hdr + 6];                 /* PN4 */
+	nonce[9] = f[hdr + 5];                 /* PN3 */
+	nonce[10] = f[hdr + 4];                /* PN2 */
+	nonce[11] = f[hdr + 1];                /* PN1 */
+	nonce[12] = f[hdr + 0];                /* PN0 */
+
+	return ccm_decrypt(key, nonce, aad, aad_len, f + hdr + 8, clen,
+			   f + len - 8);
+}

+ 22 - 0
ccmp.h

@@ -0,0 +1,22 @@
+/* Software CCMP (AES-CCM) RX decryption: see ccmp.c.
+ *
+ * The 7265D firmware's RX crypto path can fail to use keys that are correctly
+ * installed with ADD_STA_KEY (SEC_ENC_ERR with the matching key ID), while TX
+ * works.  The RX path therefore decrypts the frame in software using the
+ * same TK/GTK. */
+#ifndef CCMP_H
+#define CCMP_H
+
+/* Decrypt one FromDS CCMP-protected MPDU in place.
+ *
+ * frame  the 802.11 MPDU (header, CCMP header, ciphertext, 8-byte MIC)
+ * len    full MPDU length
+ * hdr    802.11 header length (24, or 26 with a QoS control field)
+ * key    16-byte CCMP key (TK for key ID 0, GTK for the group key ID)
+ *
+ * Returns 0 and leaves the plaintext at frame + hdr + 8, or -1 on a MIC
+ * failure or malformed frame. */
+int ccmp_rx_decrypt(unsigned char *frame, unsigned int len, unsigned int hdr,
+		    const unsigned char key[16]);
+
+#endif

+ 129 - 0
ccmp_test.c

@@ -0,0 +1,129 @@
+/* Host vectors for the software CCMP RX helper (ccmp.c):
+ * FIPS-197 AES-128 and RFC 3610 CCM packet vector #1. */
+#include <stdio.h>
+#include <string.h>
+
+#include "ccmp.c"
+
+static void hex(const unsigned char *p, int n, char *out)
+{
+	int i;
+
+	for (i = 0; i < n; i++)
+		sprintf(out + 2 * i, "%02x", p[i]);
+}
+
+static void unhex(const char *s, unsigned char *out, int n)
+{
+	int i;
+
+	for (i = 0; i < n; i++) {
+		unsigned int v;
+
+		sscanf(s + 2 * i, "%2x", &v);
+		out[i] = (unsigned char)v;
+	}
+}
+
+int main(void)
+{
+	unsigned char key[16], pt[16], ct[16], ccmout[23];
+	char h[64];
+	int failed = 0;
+
+	/* FIPS-197 AES-128 */
+	unhex("000102030405060708090a0b0c0d0e0f", key, 16);
+	unhex("00112233445566778899aabbccddeeff", pt, 16);
+	{
+		unsigned char rk[176];
+
+		aes_setkey(rk, key);
+		aes_encrypt(rk, pt, ct);
+	}
+	hex(ct, 16, h);
+	if (strcmp(h, "69c4e0d86a7b0430d8cdb78070b4c55a")) {
+		printf("FAIL aes-128 %s\n", h);
+		failed = 1;
+	} else {
+		printf("ok   aes-128\n");
+	}
+
+	/* RFC 3610 packet vector #1 (L=2, 13-byte nonce, M=8) */
+	{
+		const char *k = "c0c1c2c3c4c5c6c7c8c9cacbcccdcecf";
+		const char *n = "00000003020100a0a1a2a3a4a5";
+		const char *a = "0001020304050607";
+		const char *p = "08090a0b0c0d0e0f101112131415161718191a1b1c1d1e";
+		const char *c = "588c979a61c663d2f066d0c2c0f989806d5f6b61dac384";
+		const char *t = "17e8d12cfdf926e0";
+		unsigned char kk[16], nn[13], aa[8], pp[23], cc[23], tt[8];
+
+		unhex(k, kk, 16);
+		unhex(n, nn, 13);
+		unhex(a, aa, 8);
+		unhex(p, pp, 23);
+		unhex(c, cc, 23);
+		unhex(t, tt, 8);
+		memcpy(ccmout, cc, 23);
+		if (ccm_decrypt(kk, nn, aa, 8, ccmout, 23, tt) < 0 ||
+		    memcmp(ccmout, pp, 23)) {
+			printf("FAIL ccm\n");
+			failed = 1;
+		} else {
+			printf("ok   ccm\n");
+		}
+		memcpy(ccmout, cc, 23);
+		tt[0] ^= 1;
+		if (ccm_decrypt(kk, nn, aa, 8, ccmout, 23, tt) >= 0) {
+			printf("FAIL ccm bad tag accepted\n");
+			failed = 1;
+		} else {
+			printf("ok   ccm bad tag\n");
+		}
+	}
+
+	/* 802.11 CCMP test vector (P802.11i/D7.0 I.7.4, MPDU 1).  The header
+	 * has Retry set and a nonzero sequence number, exercising the AAD
+	 * masking and the PN byte order. */
+	{
+		static const unsigned char enc[] = {
+			0x08, 0x48, 0xc3, 0x2c, 0x0f, 0xd2, 0xe1, 0x28,
+			0xa5, 0x7c, 0x50, 0x30, 0xf1, 0x84, 0x44, 0x08,
+			0xab, 0xae, 0xa5, 0xb8, 0xfc, 0xba, 0x80, 0x33,
+			0x0c, 0xe7, 0x00, 0x20, 0x76, 0x97, 0x03, 0xb5,
+			0xf3, 0xd0, 0xa2, 0xfe, 0x9a, 0x3d, 0xbf, 0x23,
+			0x42, 0xa6, 0x43, 0xe4, 0x32, 0x46, 0xe8, 0x0c,
+			0x3c, 0x04, 0xd0, 0x19, 0x78, 0x45, 0xce, 0x0b,
+			0x16, 0xf9, 0x76, 0x23,
+		};
+		static const unsigned char tk[16] = {
+			0xc9, 0x7c, 0x1f, 0x67, 0xce, 0x37, 0x11, 0x85,
+			0x51, 0x4a, 0x8a, 0x19, 0xf2, 0xbd, 0xd5, 0x2f,
+		};
+		static const unsigned char plain[20] = {
+			0xf8, 0xba, 0x1a, 0x55, 0xd0, 0x2f, 0x85, 0xae,
+			0x96, 0x7b, 0xb6, 0x2f, 0xb6, 0xcd, 0xa8, 0xeb,
+			0x7e, 0x78, 0xa0, 0x50,
+		};
+		unsigned char frame[sizeof(enc)];
+
+		memcpy(frame, enc, sizeof(frame));
+		if (ccmp_rx_decrypt(frame, sizeof(frame), 24, tk) < 0 ||
+		    memcmp(frame + 32, plain, sizeof(plain))) {
+			printf("FAIL ccmp rx vector\n");
+			failed = 1;
+		} else {
+			printf("ok   ccmp rx vector\n");
+		}
+		memcpy(frame, enc, sizeof(frame));
+		frame[sizeof(frame) - 1] ^= 1;
+		if (ccmp_rx_decrypt(frame, sizeof(frame), 24, tk) >= 0) {
+			printf("FAIL ccmp rx bad tag accepted\n");
+			failed = 1;
+		} else {
+			printf("ok   ccmp rx bad tag\n");
+		}
+	}
+
+	return failed;
+}

+ 3 - 2
docs/drivers.html

@@ -392,7 +392,7 @@
 			<li><strong>Firmware.</strong> <code>iwlwifi-7265D-29.ucode</code> ships in the command pack as <code>firmware/iwlwifi-7265D-29.ucode</code> (1,036,312 bytes). It is a single-CPU image with LMAC scan, DQA queues and the old station API. <span class="file">iwl_mvm.c</span> runs the INIT image (NVM read for the MAC address, calibration, PHY-DB collection), then the runtime image (PHY-DB replay, DQA, aux station, PHY context, CAM power, MCC <code>ZZ</code>, station MAC context).</li>
 			<li><strong>Queues.</strong> Command queue 0 (FIFO 7), aux queue 1 (scan probes), BSS queue 4 for the AP station (management and data, BE FIFO).</li>
 			<li><strong>Station.</strong> <span class="file">wifi.c</span> builds open-system authentication and the association request itself, without WMM or HT IEs, so data frames are plain non-QoS 802.11 + LLC/SNAP. Management frames go at 1 Mb/s CCK (6 Mb/s on 5 GHz), data at a fixed 12 Mb/s OFDM (no rate scaling table yet).</li>
-			<li><strong>Security.</strong> WPA2-PSK with CCMP only. The 4-way and group handshakes run in ring 3 (<span class="file">wpa.c</span>); the kernel queues EAPOL frames, installs the TK/GTK with <code>ADD_STA_KEY</code>, and the firmware does CCMP. The host builds the 8-byte CCMP header and its packet number.</li>
+			<li><strong>Security.</strong> WPA2-PSK with CCMP only. The 4-way and group handshakes run in ring 3 (<span class="file">wpa.c</span>); the kernel queues EAPOL frames and installs the TK/GTK with <code>ADD_STA_KEY</code>. TX uses the firmware's CCMP engine with the key embedded in <code>TX_CMD</code>; the host builds the 8-byte CCMP header and its packet number. On the tested 7265D-29 the firmware does not use the installed keys for RX and reports <code>SEC_ENC_ERR</code>, so RX CCMP is decrypted in software by <span class="file">ccmp.c</span> (AES-CCM, RFC 3610) with the same TK/GTK. There is no software replay window yet.</li>
 			<li><strong>Bring-up on first use.</strong> The boot probe only finds the PCI function. The firmware is loaded by the first <code>wifi</code> command, so boot time and RAM do not change when WiFi is unused. The netdev reports <code>link_up() = 0</code> until it is connected, so the boot DHCP is skipped.</li>
 			<li><strong>kexec.</strong> <code>netdev_shutdown()</code> always stops the card through <code>wifi_shutdown()</code>, even when it is not the active netdev, because its RX ring would keep writing into pages the next kernel reuses.</li>
 		</ul>
@@ -575,7 +575,7 @@
 			<li><strong>eMMC.</strong> Polled 1-bit/25 MHz PIO; no DMA, IRQ, CMD6 bus-width/high-speed/DDR switch or hotplug. Only the eMMC function is driven; the SDIO/SD functions and SD card reader are not.</li>
 			<li><strong>Storage serialization.</strong> A FAT/floppy operation sets <code>sys_fs_busy</code> and stalls process switching for its duration; the PIT keeps ticking.</li>
 			<li><strong>EC.</strong> The Chrome EC path uses the ACPI v2 memmap only: no MEC host-command interface, EC SCI events, charger current/voltage, charging limit or EC firmware version. The ThinkPad H8 path is limited to its page-selected battery window and has no SCI handler. Battery/AC is polled by the WM once a second.</li>
-			<li><strong>WiFi.</strong> Intel 7265 rev D and 3165 only (the 7265D firmware); WPA2-PSK/CCMP and open networks, no WPA3/SAE, 802.1X, TKIP or WEP. No roaming, power save, background scan, HT/VHT, aggregation or rate scaling. Group rekeys need the background <code>wifi __keep</code> helper running.</li>
+			<li><strong>WiFi.</strong> Intel 7265 rev D and 3165 only (the 7265D firmware); WPA2-PSK/CCMP and open networks, no WPA3/SAE, 802.1X, TKIP or WEP. No roaming, power save, background scan, HT/VHT, aggregation or rate scaling. Group rekeys need the background <code>wifi __keep</code> helper running. RX CCMP falls back to the byte-oriented software AES-CCM path when the firmware rejects the installed keys, so it has no replay window and is CPU-bound at high RX rates.</li>
 			<li><strong>Suspend.</strong> There is no S0ix/suspend path; package C-states and the EC sleep handshake remain firmware-managed.</li>
 		</ul>
 	</section>
@@ -595,6 +595,7 @@
 			<li><code>iwl_trans.c</code>, <code>iwl_trans.h</code> — Intel 7265D/3165 PCIe transport</li>
 			<li><code>iwl_mvm.c</code>, <code>iwl_mvm.h</code> — WiFi firmware commands</li>
 			<li><code>wifi.c</code>, <code>wifi.h</code> — 802.11 station, <code>wifi</code> netdev, <code>SYS_WIFI</code></li>
+			<li><code>ccmp.c</code>, <code>ccmp.h</code> — software CCMP RX fallback (AES-CCM)</li>
 			<li><code>install.c</code> — live-image clone installer</li>
 			<li><code>usbhid.c</code>, <code>mouse.c</code>, <code>io.c</code> — input</li>
 			<li><code>i2c.c</code>, <code>i2c.h</code> — DesignWare/LPSS I2C master</li>

+ 1 - 1
docs/network.html

@@ -416,7 +416,7 @@
 					<tr><td>TLS DRBG</td><td>Weak (RDTSC/ticks/MAC)</td><td>Not suitable for high-value secrets.</td></tr>
 					<tr><td>WebDAV</td><td>No authentication</td><td>Anyone on the LAN can read mounts and write <code>/share</code>.</td></tr>
 					<tr><td>Chat session</td><td>Cookie saved in <code>/share/chat.cfg</code></td><td>A bearer credential in RAM until sign-out; the password is sent over unverified TLS and never stored.</td></tr>
-					<tr><td>WiFi WPA2</td><td>PSK/CCMP, handshake in ring 3</td><td>The SNonce comes from the weak TLS DRBG. The PTK lives in the <code>wifi __keep</code> helper's memory (and its argument) for group rekeys; no WPA3/PMF.</td></tr>
+					<tr><td>WiFi WPA2</td><td>PSK/CCMP, handshake in ring 3</td><td>The SNonce comes from the weak TLS DRBG. The PTK/replay are kept in the kernel (<code>SYS_WIFI_SET_PTK</code>/<code>SYS_WIFI_GET_PTK</code>) and fetched by the <code>wifi __keep</code> helper by connection ID for group rekeys; no WPA3/PMF.</td></tr>
 					<tr><td>NTP</td><td>Unauthenticated SNTP</td><td>Anyone who can answer for the server name can set the clock.</td></tr>
 					<tr><td>NIC ownership</td><td>Raw lease for packet commands; shared TCP client table</td><td>Raw commands are mutually exclusive; up to twelve processes can hold one TCP connection each.  A killed owner is force-released.</td></tr>
 					<tr><td>Kernel/user isolation</td><td>None (identity map)</td><td>A ring-3 bug can reach any mapped kernel page.</td></tr>

+ 1 - 1
docs/userland.html

@@ -226,7 +226,7 @@
 					<tr><td>Window &amp; WM</td><td>55, 57–72, 80, 83–87, 109</td><td>key poll, WM attach/info/map/present/create_term, window create/present/input/resize/scroll</td></tr>
 					<tr><td>Process &amp; memory</td><td>73–79, 81, 88–90, 108</td><td>TTY, spawn, getpid, alive, kill, chdir, scheduler info, heap alloc/grow/free</td></tr>
 					<tr><td>TCP server</td><td>93–97, 99–101</td><td>listen, accept, server recv/send/close, peer, speed, MAC set</td></tr>
-					<tr><td>WiFi</td><td>110</td><td><code>SYS_WIFI(op, a2, a3)</code>: up, status, scan/results, connect/disconnect, EAPOL RX/TX, set key, authorize (<span class="file">wifi.c</span>)</td></tr>
+					<tr><td>WiFi</td><td>110</td><td><code>SYS_WIFI(op, a2, a3)</code>: up, status, scan/results, connect/disconnect, EAPOL RX/TX, set key, authorize, set/get PTK for the rekey helper (<span class="file">wifi.c</span>)</td></tr>
 				</tbody>
 			</table>
 		</div>

+ 79 - 5
iwl_mvm.c

@@ -91,8 +91,8 @@ struct mac_ctx_cmd {                 /* MAC_CONTEXT_CMD_API_S_VER_1 */
 	/* struct iwl_mac_data_sta (+ p2p ctwin padding of the union) */
 	unsigned int is_assoc, dtim_time;
 	unsigned int dtim_tsf_lo, dtim_tsf_hi;
-	unsigned int bi, res2, dtim_interval, data_policy, listen_interval;
-	unsigned int assoc_id, assoc_beacon_arrive_time;
+	unsigned int bi, bi_reciprocal, dtim_interval, dtim_reciprocal;
+	unsigned int listen_interval, assoc_id, assoc_beacon_arrive_time;
 	unsigned int union_pad;
 } PACKED;
 
@@ -177,8 +177,18 @@ struct scan_chan_lmac {
 } PACKED;
 
 typedef char chk1[sizeof(struct mac_ctx_cmd) == 148 ? 1 : -1];
+typedef char chk1a[__builtin_offsetof(struct mac_ctx_cmd, filter_flags) == 52
+		   ? 1 : -1];
+typedef char chk1b[__builtin_offsetof(struct mac_ctx_cmd, is_assoc) == 100
+		   ? 1 : -1];
 typedef char chk2[sizeof(struct add_sta_cmd) == 44 ? 1 : -1];
+typedef char chk2a[__builtin_offsetof(struct add_sta_cmd, addr) == 8 ? 1 : -1];
+typedef char chk2b[__builtin_offsetof(struct add_sta_cmd, tfd_queue_msk) == 40
+		   ? 1 : -1];
 typedef char chk3[sizeof(struct sta_key_cmd) == 64 ? 1 : -1];
+typedef char chk3a[__builtin_offsetof(struct sta_key_cmd, key_flags) == 2
+		   ? 1 : -1];
+typedef char chk3b[__builtin_offsetof(struct sta_key_cmd, key) == 4 ? 1 : -1];
 typedef char chk4[sizeof(struct tx_cmd) == 56 ? 1 : -1];
 typedef char chk5[sizeof(struct scan_req_lmac) == 764 ? 1 : -1];
 typedef char chk6[sizeof(struct phy_ctx_cmd) == 36 ? 1 : -1];
@@ -206,6 +216,7 @@ static struct {
 	int te_started;
 	unsigned char tk[16];
 	int have_tk;
+	int tx_log;                  /* first few TX responses go to serial */
 	unsigned int valid_tx_ant, valid_rx_ant;
 } M;
 
@@ -214,6 +225,23 @@ static void logs(const char *s)
 	iwl_log(s);
 }
 
+static void log_mac(const char *tag, const unsigned char *m)
+{
+	static const char hx[] = "0123456789abcdef";
+	unsigned int i;
+
+	serial_puts(SERIAL_COM1, "iwl: ");
+	serial_puts(SERIAL_COM1, tag);
+	serial_puts(SERIAL_COM1, " ");
+	for (i = 0; i < 6; i++) {
+		if (i)
+			serial_putc(SERIAL_COM1, ':');
+		serial_putc(SERIAL_COM1, hx[m[i] >> 4]);
+		serial_putc(SERIAL_COM1, hx[m[i] & 15]);
+	}
+	serial_puts(SERIAL_COM1, "\n");
+}
+
 static void put16(unsigned char *p, unsigned int v)
 {
 	p[0] = v; p[1] = v >> 8;
@@ -386,6 +414,16 @@ static void rx_handler(const struct iwl_pkt *pkt)
 			serial_puts(SERIAL_COM1, " retries ");
 			serial_putdec(SERIAL_COM1, d[3]);
 			serial_puts(SERIAL_COM1, "\n");
+		} else if (n >= 38 && ((pkt->seq >> 8) & 0x1f) == IWL_Q_BSS &&
+			   M.tx_log < 8) {
+			M.tx_log++;
+			serial_puts(SERIAL_COM1, "iwl: tx ok q");
+			serial_putdec(SERIAL_COM1, (pkt->seq >> 8) & 0x1f);
+			serial_puts(SERIAL_COM1, " status ");
+			serial_puthex(SERIAL_COM1, get16(d + 36));
+			serial_puts(SERIAL_COM1, " retries ");
+			serial_putdec(SERIAL_COM1, d[3]);
+			serial_puts(SERIAL_COM1, "\n");
 		}
 		break;
 	case SCAN_OFFLOAD_COMPLETE:
@@ -676,7 +714,10 @@ static void fill_mac(struct mac_ctx_cmd *c, unsigned int action, int assoc,
 		c->filter_flags |= (1u << 6);   /* IN_BEACON */
 	}
 	c->bi = bi;
+	c->bi_reciprocal = bi ? 0xffffffffu / bi : 0;
 	c->dtim_interval = bi * (dtim ? dtim : 1);
+	c->dtim_reciprocal = c->dtim_interval ?
+			     0xffffffffu / c->dtim_interval : 0;
 	c->listen_interval = 10;
 }
 
@@ -684,9 +725,21 @@ static int mac_ctx(unsigned int action, int assoc, unsigned short aid,
 		   unsigned int bi, unsigned int dtim)
 {
 	struct mac_ctx_cmd c;
+	unsigned int status = 0;
 
 	fill_mac(&c, action, assoc, aid, bi, dtim);
-	return cmd(MAC_CONTEXT_CMD, &c, sizeof(c));
+	if (cmd_status(MAC_CONTEXT_CMD, &c, sizeof(c), &status) < 0)
+		return -1;
+	serial_puts(SERIAL_COM1, "iwl: mac_ctx action ");
+	serial_putdec(SERIAL_COM1, action);
+	serial_puts(SERIAL_COM1, " assoc ");
+	serial_putdec(SERIAL_COM1, assoc);
+	serial_puts(SERIAL_COM1, " ff ");
+	serial_puthex(SERIAL_COM1, c.filter_flags);
+	serial_puts(SERIAL_COM1, " status ");
+	serial_puthex(SERIAL_COM1, status);
+	serial_puts(SERIAL_COM1, "\n");
+	return 0;
 }
 
 static int run_rt_image(void)
@@ -944,7 +997,10 @@ static int add_ap_sta(int modify, unsigned short aid)
 	c.station_flags_msk = (3u << 26) | (3u << 28) | (1u << 17);
 	c.tfd_queue_msk = 1u << IWL_Q_BSS;
 	c.assoc_id = aid;
-	return add_sta(&c);
+	if (add_sta(&c) < 0)
+		return -1;
+	log_mac(modify ? "ap_sta mod" : "ap_sta add", c.addr);
+	return 0;
 }
 
 static int remove_sta(unsigned int id)
@@ -1097,9 +1153,14 @@ int iwl_mvm_set_key(int pairwise, int keyidx, const unsigned char key[16],
 
 	if (!M.ap_sta)
 		return -1;
+	/* iwlmvm allocates the PTK the first free key slot (0) and the GTK the
+	 * next one (1); the real key ID carried in the frame's CCMP header
+	 * lives in the key flags.  This holds for every group key ID, also
+	 * after an AP rekey (the key ID is 2 in the captured msg3), and the
+	 * D3 firmware path hardcodes the non-PTK key to offset 1 as well. */
 	iwl_memzero(&c, sizeof(c));
 	c.sta_id = IWL_STA_AP;
-	c.key_offset = pairwise ? 0 : (unsigned char)(1 + (keyidx & 3));
+	c.key_offset = pairwise ? 0 : 1;
 	c.key_flags = (unsigned short)(((keyidx & 3) << 8) | (1u << 3) | 2u);
 	if (!pairwise)
 		c.key_flags |= 1u << 14;         /* STA_KEY_MULTICAST */
@@ -1116,6 +1177,19 @@ int iwl_mvm_set_key(int pairwise, int keyidx, const unsigned char key[16],
 		iwl_loghex("ADD_STA_KEY failed, status", status);
 		return -1;
 	}
+	serial_puts(SERIAL_COM1, "iwl: key ");
+	serial_puts(SERIAL_COM1, pairwise ? "pair" : "group");
+	serial_puts(SERIAL_COM1, " sta ");
+	serial_putdec(SERIAL_COM1, IWL_STA_AP);
+	serial_puts(SERIAL_COM1, " off ");
+	serial_putdec(SERIAL_COM1, c.key_offset);
+	serial_puts(SERIAL_COM1, " idx ");
+	serial_putdec(SERIAL_COM1, keyidx & 3);
+	serial_puts(SERIAL_COM1, " flags ");
+	serial_puthex(SERIAL_COM1, c.key_flags);
+	serial_puts(SERIAL_COM1, " status ");
+	serial_puthex(SERIAL_COM1, status);
+	serial_puts(SERIAL_COM1, "\n");
 	if (pairwise) {
 		iwl_memcpy(M.tk, key, 16);
 		M.have_tk = 1;

+ 7 - 3
iwl_mvm.h

@@ -1,12 +1,16 @@
 /* Intel 7265D/3165 firmware command layer ("mvm"): see iwl_mvm.c.
  *
  * One station interface: MAC context 0, PHY context 0 (= binding 0), the aux
- * station 0 for scan probes and the AP station 1 on TX queue 4. */
+ * station 1 for scan probes and the AP station 0 on TX queue 4. */
 #ifndef IWL_MVM_H
 #define IWL_MVM_H
 
-#define IWL_STA_AUX 0
-#define IWL_STA_AP  1
+/* Station IDs follow iwlmvm's iwl_mvm_find_free_sta_id(): the aux station
+ * (added first, NL80211_IFTYPE_UNSPECIFIED) reserves ID 0, so it gets 1,
+ * and the BSS/AP station gets 0.  The firmware's RX/decrypt path expects
+ * the BSS station there. */
+#define IWL_STA_AUX 1
+#define IWL_STA_AP  0
 
 /* RX MPDU status bits (fw/api/rx.h). */
 #define IWL_RX_CRC_OK        (1u << 0)

+ 10 - 0
syscall.h

@@ -178,6 +178,9 @@
 #define SYS_WIFI_SET_KEY     8  /* (const struct sys_wifi_key *) -> 0/-1 */
 #define SYS_WIFI_AUTHORIZE   9  /* () -> 0/-1: open the data port and make
 				   the WiFi card the active netdev */
+#define SYS_WIFI_SET_PTK    10  /* (const struct sys_wifi_ptk *) -> 0/-1 */
+#define SYS_WIFI_GET_PTK    11  /* (struct sys_wifi_ptk *out, conn_id) ->
+				   0/-1: the background rekey helper */
 
 #define SYS_WIFI_SEC_OPEN    0
 #define SYS_WIFI_SEC_PSK     1  /* RSN, PSK AKM, CCMP pairwise + group */
@@ -494,6 +497,13 @@ struct sys_wifi_key {
 	unsigned char rsc[8];          /* GTK receive sequence counter */
 };
 
+/* The PTK and EAPOL replay counter kept for the `wifi __keep` helper. */
+struct sys_wifi_ptk {
+	unsigned int conn_id;
+	unsigned char ptk[48];
+	unsigned char replay[8];
+};
+
 int syscall_dispatch(int num, int a1, int a2, int a3);
 
 #endif

+ 85 - 34
ucmd_wifi.c

@@ -3,8 +3,10 @@
  *   wifi                         status
  *   wifi up                      load the firmware, show the MAC address
  *   wifi scan                    list networks (strongest first)
- *   wifi connect <ssid> [pass]   join an open or WPA2-PSK (CCMP) network,
- *                                run DHCP; quote an SSID with spaces
+ *   wifi connect <ssid> [pass] [bssid]
+ *                                join an open or WPA2-PSK (CCMP) network,
+ *                                run DHCP; quote an SSID with spaces; a
+ *                                BSSID picks one of several APs
  *   wifi disconnect
  *
  * The WPA2 handshake (wpa.c) runs here; a small background copy of this
@@ -190,6 +192,8 @@ static int cmd_scan(void)
 	if (n == 0)
 		u_puts("no networks found\n");
 	for (i = 0; i < n; i++) {
+		u_put_mac(bss[i].bssid);
+		u_puts("  ");
 		put_dbm(bss[i].rssi);
 		u_puts(bss[i].channel < 10 ? "  ch   " :
 		       bss[i].channel < 100 ? "  ch  " : "  ch ");
@@ -308,25 +312,31 @@ static int handshake(struct wpa_sm *sm)
 
 static void spawn_keeper(struct wpa_sm *sm, unsigned int conn_id)
 {
-	static char arg[8 + 96 + 16 + 12 + 4];
-	char *p = arg;
+	static char arg[16];
+	struct sys_wifi_ptk p;
+	unsigned char id[4];
+	char *q = arg;
 	unsigned int i;
 
-	for (i = 0; "__keep "[i]; i++)
-		*p++ = "__keep "[i];
-	tohex(sm->ptk, 48, p);
-	p += 96;
-	*p++ = ' ';
-	tohex(sm->replay, 8, p);
-	p += 16;
-	*p++ = ' ';
-	{
-		unsigned char id[4] = { conn_id >> 24, conn_id >> 16,
-					conn_id >> 8, conn_id };
-		tohex(id, 4, p);
-		p += 8;
+	p.conn_id = conn_id;
+	for (i = 0; i < 48; i++)
+		p.ptk[i] = sm->ptk[i];
+	for (i = 0; i < 8; i++)
+		p.replay[i] = sm->replay[i];
+	if (wifi(SYS_WIFI_SET_PTK, (int)&p, 0) < 0) {
+		u_puts("wifi: note: could not store rekey state; the link will "
+		       "drop at the next group rekey\n");
+		return;
 	}
-	*p = 0;
+	for (i = 0; "__keep "[i]; i++)
+		*q++ = "__keep "[i];
+	id[0] = conn_id >> 24;
+	id[1] = conn_id >> 16;
+	id[2] = conn_id >> 8;
+	id[3] = conn_id;
+	tohex(id, 4, q);
+	q += 8;
+	*q = 0;
 	if (u_spawn("/ramfs/bin/wifi", arg, 0, "/") < 0)
 		u_puts("wifi: note: rekey helper did not start; the link will "
 		       "drop at the next group rekey\n");
@@ -334,17 +344,26 @@ static void spawn_keeper(struct wpa_sm *sm, unsigned int conn_id)
 
 static int cmd_connect(const char *args)
 {
-	char ssid[33], pass[80];
+	char ssid[33], pass[80], bssid_s[13];
 	struct sys_wifi_connect c;
 	struct sys_wifi_status st;
 	static struct wpa_sm sm;
-	unsigned char pmk[32];
+	unsigned char pmk[32], want_bssid[6];
 	struct sys_wifi_bss *b = 0;
-	int n, i, r;
+	int n, i, r, have_bssid = 0;
 	unsigned int ssid_len;
 
 	args = word(args, ssid, sizeof(ssid));
-	word(args, pass, sizeof(pass));
+	args = word(args, pass, sizeof(pass));
+	if (*skip_ws(args)) {
+		word(args, bssid_s, sizeof(bssid_s));
+		if (slen(bssid_s) != 12 ||
+		    unhex(bssid_s, want_bssid, 6) < 0) {
+			u_puts("wifi: BSSID must be 12 hex digits\n");
+			return 1;
+		}
+		have_bssid = 1;
+	}
 	ssid_len = (unsigned int)slen(ssid);
 	if (!ssid_len) {
 		u_puts("usage: wifi connect <ssid> [passphrase]\n");
@@ -362,6 +381,12 @@ static int cmd_connect(const char *args)
 
 		if (bss[i].ssid_len != ssid_len)
 			continue;
+		if (have_bssid) {
+			for (j = 0; j < 6 && bss[i].bssid[j] == want_bssid[j]; j++)
+				;
+			if (j != 6)
+				continue;
+		}
 		for (j = 0; j < ssid_len && bss[i].ssid[j] == (unsigned char)ssid[j]; j++)
 			;
 		if (j == ssid_len) {
@@ -441,29 +466,55 @@ static int keeper(const char *args)
 	static struct wpa_sm sm;
 	static unsigned char frame[1024], reply[256];
 	struct sys_wifi_status st;
+	struct sys_wifi_ptk p;
 	unsigned char id[4];
-	unsigned int conn_id, rlen;
+	unsigned int conn_id, rlen, i;
 
 	args = skip_ws(args);
-	if (slen(args) < 96 + 1 + 16 + 1 + 8 ||
-	    unhex(args, sm.ptk, 48) < 0 ||
-	    unhex(args + 97, sm.replay, 8) < 0 ||
-	    unhex(args + 114, id, 4) < 0)
+	if (slen(args) < 8 || unhex(args, id, 4) < 0) {
+		u_puts("wifi: keeper: bad state argument\n");
+		return 1;
+	}
+	conn_id = ((unsigned int)id[0] << 24) | (id[1] << 16) |
+		  (id[2] << 8) | id[3];
+	if (wifi(SYS_WIFI_GET_PTK, (int)&p, (int)conn_id) < 0 ||
+	    p.conn_id != conn_id) {
+		u_puts("wifi: keeper: no key state for this connection\n");
 		return 1;
-	conn_id = ((unsigned int)id[0] << 24) | (id[1] << 16) | (id[2] << 8) | id[3];
+	}
+	for (i = 0; i < 48; i++)
+		sm.ptk[i] = p.ptk[i];
+	for (i = 0; i < 8; i++)
+		sm.replay[i] = p.replay[i];
 	sm.have_replay = 1;
 	sm.ptk_ok = 1;
+	u_puts("wifi: keeper running\n");
 	for (;;) {
-		int n;
+		int n, r;
 
 		if (wifi(SYS_WIFI_STATUS, (int)&st, 0) < 0 ||
 		    st.conn_id != conn_id || st.state < SYS_WIFI_ST_ASSOC)
 			return 0;
 		n = wifi(SYS_WIFI_EAPOL_RX, (int)frame, sizeof(frame));
-		if (n > 0 && wpa_rx(&sm, frame, (unsigned int)n, reply, &rlen,
-				    tls_random) == WPA_GTK) {
-			wifi(SYS_WIFI_EAPOL_TX, (int)reply, (int)rlen);
-			set_gtk(&sm);
+		if (n > 0) {
+			r = wpa_rx(&sm, frame, (unsigned int)n, reply, &rlen,
+				   tls_random);
+			u_puts("wifi: keeper eapol ");
+			u_putdec((unsigned int)n);
+			u_puts(" -> ");
+			u_putdec((unsigned int)r);
+			u_puts("\n");
+			if (r == WPA_GTK) {
+				wifi(SYS_WIFI_EAPOL_TX, (int)reply, (int)rlen);
+				u_puts("wifi: keeper gtk ");
+				u_putdec((unsigned int)sm.gtk_idx);
+				u_puts(set_gtk(&sm) == 0 ? " installed\n"
+							 : " install failed\n");
+			} else if (r == WPA_ERR) {
+				u_puts("wifi: keeper error: ");
+				u_puts(sm.error ? sm.error : "?");
+				u_puts("\n");
+			}
 		}
 		u_sleep_ms(200);
 	}
@@ -490,7 +541,7 @@ void _start(const char *arg)
 		wifi(SYS_WIFI_DISCONNECT, 0, 0);
 		u_puts("wifi: disconnected\n");
 	} else {
-		u_puts("usage: wifi [up|scan|connect <ssid> [pass]|disconnect]\n");
+		u_puts("usage: wifi [up|scan|connect <ssid> [pass] [bssid]|disconnect]\n");
 		r = 1;
 	}
 	u_exit(r);

+ 181 - 17
wifi.c

@@ -11,6 +11,7 @@
  * Page-allocated buffers only: the kernel image must stay below 0x90000. */
 
 #include "wifi.h"
+#include "ccmp.h"
 #include "iwl_mvm.h"
 #include "iwl_trans.h"
 #include "io.h"
@@ -57,7 +58,16 @@ static struct {
 	unsigned int eapq_head, eapq_tail;
 	unsigned char *txbuf;         /* one 2 KB frame build buffer */
 	unsigned int rx_frames, tx_frames, rx_dropped;
+	unsigned int rx_logged_grp, rx_logged_uni;
+	int beacon_log;
+	unsigned char tk[16], gtk[16];  /* software CCMP RX keys */
+	int have_tk, have_gtk;
+	unsigned int gtk_idx;
+	int sw_rx_log, sw_fail_log;
 	unsigned int conn_id;
+	unsigned char ptk[48];
+	unsigned char ptk_replay[8];
+	unsigned int ptk_conn;
 	const char *detail;
 } W;
 
@@ -258,20 +268,66 @@ static void queue_eapol(const unsigned char *p, unsigned int len)
 	W.eapq_head = (W.eapq_head + 1) % EAPOLQ_SLOTS;
 }
 
-/* First few data-path drops go to serial/netmon with the reason and the
- * firmware RX status (decrypt result in bits 8..10, MIC_OK bit 6). */
-static void rx_drop(const char *why, const unsigned char *f,
+static void puthex2(unsigned int v)
+{
+	static const char hx[] = "0123456789abcdef";
+
+	serial_putc(SERIAL_COM1, hx[(v >> 4) & 15]);
+	serial_putc(SERIAL_COM1, hx[v & 15]);
+}
+
+static void putmac(const unsigned char *m)
+{
+	unsigned int i;
+
+	for (i = 0; i < 6; i++) {
+		if (i)
+			serial_putc(SERIAL_COM1, ':');
+		puthex2(m[i]);
+	}
+}
+
+/* First few data-path drops of each kind (group and unicast) go to
+ * serial/netmon with the reason, address, CCMP key ID and the firmware RX
+ * status (decrypt result in bits 8..10, MIC_OK bit 6, replay bit 7,
+ * DEC_DONE bit 11). */
+static void rx_drop(const char *why, const unsigned char *f, unsigned int len,
 		    unsigned int status)
 {
+	unsigned int hdr = 24 + (((f[0] >> 4) & 0xf) & 8 ? 2 : 0);
+	int grp = f[4] & 1;
+
 	W.rx_dropped++;
-	if (W.rx_dropped > 12)
-		return;
+	if (grp) {
+		if (W.rx_logged_grp++ >= 8)
+			return;
+	} else {
+		if (W.rx_logged_uni++ >= 8)
+			return;
+	}
 	serial_puts(SERIAL_COM1, "wifi: rx drop ");
 	serial_puts(SERIAL_COM1, why);
 	serial_puts(SERIAL_COM1, " fc ");
 	serial_puthex(SERIAL_COM1, f[0] | (f[1] << 8));
-	serial_puts(SERIAL_COM1, " da ");
-	serial_puthex(SERIAL_COM1, (f[4] << 8) | f[5]);
+	serial_puts(SERIAL_COM1, " len ");
+	serial_putdec(SERIAL_COM1, len);
+	serial_puts(SERIAL_COM1, " a1 ");
+	putmac(f + 4);
+	serial_puts(SERIAL_COM1, " a2 ");
+	putmac(f + 10);
+	serial_puts(SERIAL_COM1, " ccmp ");
+	serial_putdec(SERIAL_COM1, len >= hdr + 8 ? (f[hdr + 3] >> 6) & 3
+						   : 0xff);
+	serial_puts(SERIAL_COM1, " sec ");
+	serial_putdec(SERIAL_COM1, (status >> 8) & 7);
+	serial_puts(SERIAL_COM1, " kv ");
+	serial_putdec(SERIAL_COM1, (status >> 3) & 1);
+	serial_puts(SERIAL_COM1, " mic ");
+	serial_putdec(SERIAL_COM1, (status >> 6) & 1);
+	serial_puts(SERIAL_COM1, " dec ");
+	serial_putdec(SERIAL_COM1, (status >> 11) & 1);
+	serial_puts(SERIAL_COM1, " rep ");
+	serial_putdec(SERIAL_COM1, (status >> 7) & 1);
 	serial_puts(SERIAL_COM1, " status ");
 	serial_puthex(SERIAL_COM1, status);
 	serial_puts(SERIAL_COM1, "\n");
@@ -295,10 +351,63 @@ static void rx_data(const unsigned char *f, unsigned int len,
 	if (stype & 8)
 		hdr += 2;                            /* QoS control */
 	if (prot) {
-		if ((status & IWL_RX_SEC_MSK) != IWL_RX_SEC_CCM ||
-		    !(status & IWL_RX_MIC_OK)) {
-			rx_drop("not decrypted", f, status);
-			return;
+		unsigned int kid = (f[hdr + 3] >> 6) & 3;
+		const unsigned char *key = 0;
+		int fw_ok = (status & IWL_RX_SEC_MSK) == IWL_RX_SEC_CCM &&
+			    (status & IWL_RX_MIC_OK);
+
+		/* The firmware sometimes does the AES-CTR step in place but
+		 * still reports a failed MIC/decrypt status.  The SNAP header
+		 * in the clear is a reliable sign that the payload is already
+		 * plaintext. */
+		if (!fw_ok && len >= hdr + 16 &&
+		    meq(f + hdr + 8, snap, 6)) {
+			if (W.sw_rx_log < 4) {
+				W.sw_rx_log++;
+				serial_puts(SERIAL_COM1,
+					    "wifi: fw plaintext id ");
+				serial_putdec(SERIAL_COM1, kid);
+				serial_puts(SERIAL_COM1, "\n");
+			}
+			fw_ok = 1;
+		}
+		if (!fw_ok) {
+			/* The firmware's RX crypto path sometimes reports
+			 * SEC_ENC_ERR for keys it has installed.  Decrypt in
+			 * software with the same TK/GTK; TX proves they are
+			 * correct. */
+			if (f[4] & 1) {
+				if (W.have_gtk && kid == W.gtk_idx)
+					key = W.gtk;
+			} else if (kid == 0 && W.have_tk) {
+				key = W.tk;
+			}
+			if (!key) {
+				rx_drop("no key", f, len, status);
+				return;
+			}
+			if (ccmp_rx_decrypt((unsigned char *)f, len, hdr,
+					    key) < 0) {
+				if (W.sw_fail_log < 3 && len >= hdr + 16) {
+					unsigned int z;
+
+					W.sw_fail_log++;
+					serial_puts(SERIAL_COM1,
+						    "wifi: sw ccmp failed payload ");
+					for (z = 0; z < 8; z++)
+						puthex2(f[hdr + 8 + z]);
+					serial_puts(SERIAL_COM1, "\n");
+				}
+				rx_drop("sw ccmp failed", f, len, status);
+				return;
+			}
+			if (W.sw_rx_log < 4) {
+				W.sw_rx_log++;
+				serial_puts(SERIAL_COM1,
+					    "wifi: sw ccmp ok id ");
+				serial_putdec(SERIAL_COM1, kid);
+				serial_puts(SERIAL_COM1, "\n");
+			}
 		}
 		hdr += 8;                            /* CCMP header */
 		if (len < hdr + 8)
@@ -306,7 +415,7 @@ static void rx_data(const unsigned char *f, unsigned int len,
 		len -= 8;                            /* MIC */
 	}
 	if (len < hdr + 8 || !meq(f + hdr, snap, 6)) {
-		rx_drop("no LLC/SNAP", f, status);
+		rx_drop("no LLC/SNAP", f, len, status);
 		return;
 	}
 	type = (f[hdr + 6] << 8) | f[hdr + 7];
@@ -319,12 +428,13 @@ static void rx_data(const unsigned char *f, unsigned int len,
 	/* Before the keys are in, or unprotected after: drop. */
 	if (W.state != SYS_WIFI_ST_LINK || (W.protect && !prot)) {
 		rx_drop(W.state != SYS_WIFI_ST_LINK ? "port closed"
-						      : "unprotected", f, status);
+						      : "unprotected", f, len,
+			status);
 		return;
 	}
 	if (plen + 14 > RXQ_FRAME ||
 	    ((W.rxq_head + 1) % RXQ_SLOTS) == W.rxq_tail) {
-		rx_drop("queue full", f, status);
+		rx_drop("queue full", f, len, status);
 		return;
 	}
 	s = &W.rxq[W.rxq_head];
@@ -341,11 +451,23 @@ static void rx_data(const unsigned char *f, unsigned int len,
 void wifi_rx_frame(const unsigned char *frame, unsigned int len, int rssi,
 		   unsigned int status, unsigned int channel)
 {
-	unsigned int type;
+	unsigned int type, stype;
 
 	if (len < 24)
 		return;
 	type = (frame[0] >> 2) & 3;
+	stype = (frame[0] >> 4) & 0xf;
+	if (W.state >= SYS_WIFI_ST_ASSOC && type == 0 && stype == 8 &&
+	    W.beacon_log < 3) {
+		W.beacon_log++;
+		serial_puts(SERIAL_COM1, "wifi: beacon status ");
+		serial_puthex(SERIAL_COM1, status);
+		serial_puts(SERIAL_COM1, " srcfound ");
+		serial_putdec(SERIAL_COM1, (status >> 2) & 1);
+		serial_puts(SERIAL_COM1, " staid ");
+		serial_putdec(SERIAL_COM1, (status >> 24) & 0x1f);
+		serial_puts(SERIAL_COM1, "\n");
+	}
 	if (type == 0)
 		rx_mgmt(frame, len, rssi, channel);
 	else if (type == 2)
@@ -460,6 +582,11 @@ static int do_connect(const struct sys_wifi_connect *c)
 	W.eapq_head = W.eapq_tail = 0;
 	W.rxq_head = W.rxq_tail = 0;
 	W.rx_dropped = 0;
+	W.rx_logged_grp = W.rx_logged_uni = 0;
+	W.beacon_log = 0;
+	W.have_tk = W.have_gtk = 0;
+	W.sw_rx_log = W.sw_fail_log = 0;
+	W.ptk_conn = 0;
 
 	if (iwl_mvm_prepare_connect(c->bssid, c->channel, W.cur.beacon_int) < 0) {
 		W.detail = "firmware connect setup failed";
@@ -538,6 +665,8 @@ static void do_disconnect(void)
 {
 	static const unsigned char reason[2] = { 3, 0 };   /* leaving */
 
+	W.have_tk = W.have_gtk = 0;
+	W.ptk_conn = 0;
 	if (W.state >= SYS_WIFI_ST_ASSOC) {
 		tx_mgmt_frame(12, reason, 2);
 		iwl_mvm_poll();
@@ -806,12 +935,47 @@ int sys_wifi(int op, int a2, int a3)
 	}
 	case SYS_WIFI_SET_KEY: {
 		struct sys_wifi_key k;
+		int r;
 
 		if (W.state < SYS_WIFI_ST_ASSOC || !user_ok(a2, sizeof(k), 0))
 			return -1;
 		wmemcpy(&k, (const void *)a2, sizeof(k));
-		return iwl_mvm_set_key(k.pairwise, k.keyidx, k.key,
-				       k.pairwise ? 0 : k.rsc);
+		r = iwl_mvm_set_key(k.pairwise, k.keyidx, k.key,
+				    k.pairwise ? 0 : k.rsc);
+		if (r == 0) {
+			if (k.pairwise) {
+				wmemcpy(W.tk, k.key, 16);
+				W.have_tk = 1;
+			} else {
+				wmemcpy(W.gtk, k.key, 16);
+				W.gtk_idx = k.keyidx & 3;
+				W.have_gtk = 1;
+			}
+		}
+		return r;
+	}
+	case SYS_WIFI_SET_PTK: {
+		struct sys_wifi_ptk p;
+
+		if (W.state < SYS_WIFI_ST_ASSOC || !user_ok(a2, sizeof(p), 0))
+			return -1;
+		wmemcpy(&p, (const void *)a2, sizeof(p));
+		wmemcpy(W.ptk, p.ptk, 48);
+		wmemcpy(W.ptk_replay, p.replay, 8);
+		W.ptk_conn = p.conn_id;
+		return 0;
+	}
+	case SYS_WIFI_GET_PTK: {
+		struct sys_wifi_ptk p;
+
+		if (!W.ptk_conn || (unsigned int)a3 != W.ptk_conn ||
+		    !user_ok(a2, sizeof(p), 1))
+			return -1;
+		p.conn_id = W.ptk_conn;
+		wmemcpy(p.ptk, W.ptk, 48);
+		wmemcpy(p.replay, W.ptk_replay, 8);
+		wmemcpy((void *)a2, &p, sizeof(p));
+		return 0;
 	}
 	case SYS_WIFI_AUTHORIZE:
 		if (W.state < SYS_WIFI_ST_ASSOC)

이 변경점에서 너무 많은 파일들이 변경되어 몇몇 파일들은 표시되지 않았습니다.