git clone https://garage44.eu/jeroen/pinnacle.gitcartopolis-agent · 2026-11-30T14:07:48Z
feat(wifi): WPA2-Personal's handshake, for a radio that leaves it to the host Intel's Wi-Fi is a "soft MAC": the host does the 4-way handshake. wifi::wpa is the device's half as a pure state machine: the PSK from the password and network name, the PTK (PRF-SHA-1 for AKM 2, KDF-SHA-256 for AKM 6), message 2 and 4 with their MIC (HMAC-SHA-1 or AES-CMAC), message 3's key data unwrapped, the group key handshake. It refuses a replayed counter, a MIC that is not the PTK's (a wrong password), a changed ANonce, and an RSN element in message 3 other than the beacon's (a downgrade). crypto gains what that needs: SHA-1 (only for HMAC and PBKDF2), HMAC-SHA-1, PBKDF2 with SHA-1 and SHA-256, AES decryption in software and AES key wrap (RFC 3394). Tests on the host: FIPS 180 and 197, RFC 2202 and 3394, IEEE 802.11 J.4's password keys; message 2's MIC and the PTK against Python's hashlib/hmac for the same inputs; a full handshake and rekey against a test authenticator; a wrong password, a downgrade and a forged frame refused.
Cargo.lock | 3 +
crypto/src/aes.rs | 129 ++++++++++++
crypto/src/lib.rs | 4 +-
crypto/src/sha1.rs | 154 ++++++++++++++
crypto/src/tests.rs | 61 ++++++
wifi/Cargo.toml | 3 +
wifi/src/lib.rs | 4 +
wifi/src/wpa.rs | 590 ++++++++++++++++++++++++++++++++++++++++++++++++++++
8 files changed, 947 insertions(+), 1 deletion(-)
diff --git a/Cargo.lock b/Cargo.lock
index 51fa384..7abe575 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -293,6 +293,9 @@ dependencies = [
[[package]]
name = "pinnacle-wifi"
version = "0.1.0"
+dependencies = [
+ "pinnacle-crypto",
+]
[[package]]
name = "pinnacle-workbench"
diff --git a/crypto/src/aes.rs b/crypto/src/aes.rs
index ebec0ce..83eb986 100644
--- a/crypto/src/aes.rs
+++ b/crypto/src/aes.rs
@@ -161,6 +161,135 @@ impl Aes {
}
}
+/// The inverse S-box, from the S-box when compiling.
+const INV_SBOX: [u8; 256] = {
+ let mut inv = [0u8; 256];
+ let mut x = 0;
+ while x < 256 {
+ inv[SBOX[x] as usize] = x as u8;
+ x += 1;
+ }
+ inv
+};
+
+/// `INV_SBOX[x]`, read by scanning all of it.
+fn inv_sub_byte(x: u8) -> u8 {
+ let mut out = 0u8;
+ for (i, &s) in INV_SBOX.iter().enumerate() {
+ let same = ((((i as u32) ^ u32::from(x)).wrapping_sub(1)) >> 31) as u8;
+ out |= s & 0u8.wrapping_sub(same);
+ }
+ out
+}
+
+/// GF(2^8) multiplication in constant time, for the inverse mix.
+fn mul(a: u8, b: u8) -> u8 {
+ let (mut a, mut product) = (a, 0u8);
+ for i in 0..8 {
+ product ^= a & 0u8.wrapping_sub((b >> i) & 1);
+ a = xtime(a);
+ }
+ product
+}
+
+impl Aes {
+ /// Decrypts whole 16-byte blocks in place, in software (FIPS 197's
+ /// inverse cipher): what AES key unwrap needs, a few blocks at a time,
+ /// never a stream.
+ pub fn decrypt_blocks(&self, blocks: &mut [u8]) {
+ for state in blocks.as_chunks_mut::<16>().0 {
+ let rounds = self.count - 1;
+ add(state, &self.keys[rounds]);
+ for round in (0..rounds).rev() {
+ // Row r moves r columns right.
+ let old = *state;
+ for c in 0..4 {
+ for r in 0..4 {
+ state[((c + r) % 4) * 4 + r] = old[c * 4 + r];
+ }
+ }
+ for b in state.iter_mut() {
+ *b = inv_sub_byte(*b);
+ }
+ add(state, &self.keys[round]);
+ if round != 0 {
+ for column in state.as_chunks_mut::<4>().0 {
+ let [a, b, c, d] = *column;
+ column[0] = mul(a, 14) ^ mul(b, 11) ^ mul(c, 13) ^ mul(d, 9);
+ column[1] = mul(a, 9) ^ mul(b, 14) ^ mul(c, 11) ^ mul(d, 13);
+ column[2] = mul(a, 13) ^ mul(b, 9) ^ mul(c, 14) ^ mul(d, 11);
+ column[3] = mul(a, 11) ^ mul(b, 13) ^ mul(c, 9) ^ mul(d, 14);
+ }
+ }
+ }
+ }
+ }
+}
+
+/// AES key wrap's default initial value (RFC 3394, 2.2.3.1).
+const WRAP_IV: [u8; 8] = [0xa6; 8];
+
+/// Wraps `key` (a multiple of 8 bytes, at least 16) under `kek` (RFC
+/// 3394) into `out`, which is 8 bytes longer. False for wrong lengths.
+pub fn wrap(kek: &[u8], key: &[u8], out: &mut [u8]) -> bool {
+ let Some(aes) = Aes::new(kek) else { return false };
+ if key.len() % 8 != 0 || key.len() < 16 || out.len() != key.len() + 8 {
+ return false;
+ }
+ let n = key.len() / 8;
+ let (a, r) = out.split_at_mut(8);
+ a.copy_from_slice(&WRAP_IV);
+ r.copy_from_slice(key);
+ for j in 0..6 {
+ for i in 0..n {
+ let mut b = [0u8; 16];
+ b[..8].copy_from_slice(a);
+ b[8..].copy_from_slice(&r[i * 8..i * 8 + 8]);
+ aes.encrypt_blocks(&mut b);
+ let t = (n * j + i + 1) as u64;
+ for (x, (y, z)) in a.iter_mut().zip(b[..8].iter().zip(t.to_be_bytes())) {
+ *x = y ^ z;
+ }
+ r[i * 8..i * 8 + 8].copy_from_slice(&b[8..]);
+ }
+ }
+ true
+}
+
+/// Unwraps what [`wrap`] made into `out` (8 bytes shorter): false when
+/// its integrity check fails (the wrong key encryption key, or the bytes
+/// changed), `out` then zeroed.
+pub fn unwrap(kek: &[u8], wrapped: &[u8], out: &mut [u8]) -> bool {
+ let Some(aes) = Aes::new(kek) else { return false };
+ if wrapped.len() % 8 != 0 || wrapped.len() < 24 || out.len() + 8 != wrapped.len() {
+ return false;
+ }
+ let n = out.len() / 8;
+ let mut a: [u8; 8] = wrapped[..8].try_into().unwrap();
+ out.copy_from_slice(&wrapped[8..]);
+ for j in (0..6).rev() {
+ for i in (0..n).rev() {
+ let t = (n * j + i + 1) as u64;
+ for (x, y) in a.iter_mut().zip(t.to_be_bytes()) {
+ *x ^= y;
+ }
+ let mut b = [0u8; 16];
+ b[..8].copy_from_slice(&a);
+ b[8..].copy_from_slice(&out[i * 8..i * 8 + 8]);
+ aes.decrypt_blocks(&mut b);
+ a.copy_from_slice(&b[..8]);
+ out[i * 8..i * 8 + 8].copy_from_slice(&b[8..]);
+ }
+ }
+ // In constant time: whether the check value came back.
+ if !crate::equal(&a, &WRAP_IV) {
+ out.fill(0);
+ return false;
+ }
+ true
+}
+
+
fn add(state: &mut [u8; 16], key: &[u8; 16]) {
for (s, k) in state.iter_mut().zip(key) {
*s ^= k;
diff --git a/crypto/src/lib.rs b/crypto/src/lib.rs
index 7e53de8..1c53b61 100644
--- a/crypto/src/lib.rs
+++ b/crypto/src/lib.rs
@@ -1,7 +1,8 @@
//! Pinnacle's cryptography, written here and checked against the standards'
//! test vectors: SHA-256 and SHA-512 (FIPS 180-4), HMAC and HKDF (RFC 2104,
//! RFC 5869), ChaCha20-Poly1305 (RFC 8439), X25519 (RFC 7748) and Ed25519
-//! (RFC 8032); AES with GCM, CCM, CMAC and SIV; P-256 ECDH.
+//! (RFC 8032); AES with GCM, CCM, CMAC and SIV, and key wrap (RFC 3394);
+//! P-256 ECDH; SHA-1 only for HMAC and PBKDF2, as WPA2 needs.
//!
//! Secret-dependent work avoids secret-dependent branches and memory
//! indices: the field and scalar arithmetic selects with masks. P-256 is
@@ -23,6 +24,7 @@ pub mod hw;
pub mod p256;
pub mod rsa;
mod scalar;
+pub mod sha1;
pub mod sha2;
pub mod x25519;
diff --git a/crypto/src/sha1.rs b/crypto/src/sha1.rs
new file mode 100644
index 0000000..98bb6ce
--- /dev/null
+++ b/crypto/src/sha1.rs
@@ -0,0 +1,154 @@
+//! SHA-1 (FIPS 180-4), HMAC-SHA-1 (RFC 2104) and PBKDF2 (RFC 8018):
+//! what WPA2 is built on (a network's password made its key, IEEE 802.11
+//! J.4; the handshake's keys and checks, 12.7.1). SHA-1 is broken for
+//! collisions, not as HMAC's hash: here it is only HMAC's, because the
+//! standard says so.
+
+use crate::sha2;
+
+/// SHA-1, a message at a time or in parts.
+#[derive(Clone)]
+pub struct Sha1 {
+ state: [u32; 5],
+ block: [u8; 64],
+ used: usize,
+ length: u64,
+}
+
+impl Default for Sha1 {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl Sha1 {
+ pub fn new() -> Sha1 {
+ Sha1 {
+ state: [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0],
+ block: [0; 64],
+ used: 0,
+ length: 0,
+ }
+ }
+
+ pub fn digest(data: &[u8]) -> [u8; 20] {
+ let mut h = Sha1::new();
+ h.update(data);
+ h.finish()
+ }
+
+ pub fn update(&mut self, mut data: &[u8]) {
+ self.length += data.len() as u64;
+ while !data.is_empty() {
+ let take = (64 - self.used).min(data.len());
+ self.block[self.used..self.used + take].copy_from_slice(&data[..take]);
+ self.used += take;
+ data = &data[take..];
+ if self.used == 64 {
+ let block = self.block;
+ self.compress(&block);
+ self.used = 0;
+ }
+ }
+ }
+
+ pub fn finish(mut self) -> [u8; 20] {
+ let bits = self.length * 8;
+ self.update(&[0x80]);
+ while self.used != 56 {
+ self.update(&[0]);
+ }
+ self.update(&bits.to_be_bytes());
+ let mut out = [0u8; 20];
+ for (o, s) in out.chunks_mut(4).zip(self.state) {
+ o.copy_from_slice(&s.to_be_bytes());
+ }
+ out
+ }
+
+ fn compress(&mut self, block: &[u8; 64]) {
+ let mut w = [0u32; 80];
+ for (i, word) in block.chunks(4).enumerate() {
+ w[i] = u32::from_be_bytes(word.try_into().unwrap());
+ }
+ for i in 16..80 {
+ w[i] = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]).rotate_left(1);
+ }
+ let [mut a, mut b, mut c, mut d, mut e] = self.state;
+ for (i, &wi) in w.iter().enumerate() {
+ let (f, k) = match i {
+ 0..20 => ((b & c) | (!b & d), 0x5a827999),
+ 20..40 => (b ^ c ^ d, 0x6ed9eba1),
+ 40..60 => ((b & c) | (b & d) | (c & d), 0x8f1bbcdc),
+ _ => (b ^ c ^ d, 0xca62c1d6),
+ };
+ let t = a
+ .rotate_left(5)
+ .wrapping_add(f)
+ .wrapping_add(e)
+ .wrapping_add(k)
+ .wrapping_add(wi);
+ e = d;
+ d = c;
+ c = b.rotate_left(30);
+ b = a;
+ a = t;
+ }
+ for (s, v) in self.state.iter_mut().zip([a, b, c, d, e]) {
+ *s = s.wrapping_add(v);
+ }
+ }
+}
+
+/// HMAC-SHA-1 over the concatenation of `parts`.
+pub fn hmac(key: &[u8], parts: &[&[u8]]) -> [u8; 20] {
+ let mut k = [0u8; 64];
+ if key.len() > 64 {
+ k[..20].copy_from_slice(&Sha1::digest(key));
+ } else {
+ k[..key.len()].copy_from_slice(key);
+ }
+ let mut inner = Sha1::new();
+ inner.update(&k.map(|b| b ^ 0x36));
+ for p in parts {
+ inner.update(p);
+ }
+ let mut outer = Sha1::new();
+ outer.update(&k.map(|b| b ^ 0x5c));
+ outer.update(&inner.finish());
+ outer.finish()
+}
+
+/// PBKDF2 with HMAC-SHA-1: `out.len()` bytes from `password` and `salt`
+/// after `rounds` iterations. WPA2's key from a password and the
+/// network's name is `pbkdf2_sha1(password, ssid, 4096, 32 bytes)`.
+pub fn pbkdf2_sha1(password: &[u8], salt: &[u8], rounds: u32, out: &mut [u8]) {
+ for (i, chunk) in out.chunks_mut(20).enumerate() {
+ let index = (i as u32 + 1).to_be_bytes();
+ let mut u = hmac(password, &[salt, &index]);
+ let mut t = u;
+ for _ in 1..rounds {
+ u = hmac(password, &[&u]);
+ for (x, y) in t.iter_mut().zip(u) {
+ *x ^= y;
+ }
+ }
+ chunk.copy_from_slice(&t[..chunk.len()]);
+ }
+}
+
+/// PBKDF2 with HMAC-SHA-256, for what asks it.
+pub fn pbkdf2_sha256(password: &[u8], salt: &[u8], rounds: u32, out: &mut [u8]) {
+ for (i, chunk) in out.chunks_mut(32).enumerate() {
+ let index = (i as u32 + 1).to_be_bytes();
+ let mut u = sha2::hmac(password, &[salt, &index]);
+ let mut t = u;
+ for _ in 1..rounds {
+ u = sha2::hmac(password, &[&u]);
+ for (x, y) in t.iter_mut().zip(u) {
+ *x ^= y;
+ }
+ }
+ chunk.copy_from_slice(&t[..chunk.len()]);
+ }
+}
diff --git a/crypto/src/tests.rs b/crypto/src/tests.rs
index b5c8d86..dcb8bc0 100644
--- a/crypto/src/tests.rs
+++ b/crypto/src/tests.rs
@@ -539,3 +539,64 @@ fn aes_siv_rfc5297() {
assert!(siv.open(&[&ad, b"nonce"], &mut long, &iv));
assert_eq!(long, hex("00112233445566778899aabbccddeeff0011"));
}
+
+#[test]
+fn sha1_hmac_and_wpa2s_password_key() {
+ assert_eq!(sha1::Sha1::digest(b"abc").to_vec(), hex("a9993e364706816aba3e25717850c26c9cd0d89d"));
+ let long = [b'a'; 1000];
+ let mut h = sha1::Sha1::new();
+ for _ in 0..1000 {
+ h.update(&long);
+ }
+ // FIPS 180's million a's.
+ assert_eq!(h.finish().to_vec(), hex("34aa973cd4c4daa4f61eeb2bdbad27316534016f"));
+ // RFC 2202, case 1.
+ assert_eq!(
+ sha1::hmac(&[0x0b; 20], &[b"Hi There"]).to_vec(),
+ hex("b617318655057264e28bc0b6fb378c8ef146be00")
+ );
+ // IEEE 802.11-2020, J.4.2: a network's key from its password and name.
+ let mut psk = [0u8; 32];
+ sha1::pbkdf2_sha1(b"password", b"IEEE", 4096, &mut psk);
+ assert_eq!(psk.to_vec(), hex("f42c6fc52df0ebef9ebb4b90b38a5f902e83fe1b135a70e23aed762e9710a12e"));
+ sha1::pbkdf2_sha1(b"ThisIsAPassword", b"ThisIsASSID", 4096, &mut psk);
+ assert_eq!(psk.to_vec(), hex("0dc0d6eb90555ed6419756b9a15ec3e3209b63df707dd508d14581f8982721af"));
+ sha1::pbkdf2_sha256(b"password", b"salt", 2, &mut psk);
+ assert_eq!(psk.to_vec(), hex("ae4d0c95af6b46d32d0adff928f06dd02a303f8ef3c251dfd6e2d85a95474c43"));
+}
+
+#[test]
+fn aes_decrypts_and_wraps_keys() {
+ detect();
+ // FIPS 197, C.1 and C.3, back again.
+ let a = aes::Aes::new(&hex("000102030405060708090a0b0c0d0e0f")).unwrap();
+ let mut block = hex("69c4e0d86a7b0430d8cdb78070b4c55a");
+ a.decrypt_blocks(&mut block);
+ assert_eq!(block, hex("00112233445566778899aabbccddeeff"));
+ let a = aes::Aes::new(&hex("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f")).unwrap();
+ let mut block = hex("8ea2b7ca516745bfeafc49904b496089");
+ a.decrypt_blocks(&mut block);
+ assert_eq!(block, hex("00112233445566778899aabbccddeeff"));
+ // RFC 3394, 4.1 and 4.6.
+ let kek = hex("000102030405060708090a0b0c0d0e0f");
+ let key = hex("00112233445566778899aabbccddeeff");
+ let mut wrapped = [0u8; 24];
+ assert!(aes::wrap(&kek, &key, &mut wrapped));
+ assert_eq!(wrapped.to_vec(), hex("1fa68b0a8112b447aef34bd8fb5a7b829d3e862371d2cfe5"));
+ let mut back = [0u8; 16];
+ assert!(aes::unwrap(&kek, &wrapped, &mut back));
+ assert_eq!(back.to_vec(), key);
+ let kek = hex("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f");
+ let key = hex("00112233445566778899aabbccddeeff000102030405060708090a0b0c0d0e0f");
+ let mut wrapped = [0u8; 40];
+ assert!(aes::wrap(&kek, &key, &mut wrapped));
+ assert_eq!(
+ wrapped.to_vec(),
+ hex("28c9f404c4b810f4cbccb35cfb87f8263f5786e2d80ed326cbc7f0e71a99f43bfb988b9b7a02dd21")
+ );
+ // A changed byte fails the check, and gives nothing.
+ wrapped[5] ^= 1;
+ let mut back = [0xffu8; 32];
+ assert!(!aes::unwrap(&kek, &wrapped, &mut back));
+ assert_eq!(back, [0; 32]);
+}
diff --git a/wifi/Cargo.toml b/wifi/Cargo.toml
index 69cb812..d07bb4f 100644
--- a/wifi/Cargo.toml
+++ b/wifi/Cargo.toml
@@ -8,3 +8,6 @@ publish.workspace = true
[lib]
doctest = false
+
+[dependencies]
+pinnacle-crypto = { path = "../crypto" }
diff --git a/wifi/src/lib.rs b/wifi/src/lib.rs
index 9de9a93..5ae217f 100644
--- a/wifi/src/lib.rs
+++ b/wifi/src/lib.rs
@@ -13,6 +13,9 @@
//! and is told whether it got on. The password is not kept on the radio
//! (`AT+SYSSTORE=0`): the service keeps the networks joined, in the data
//! vault. Carrying the network's packets is not here yet.
+//!
+//! [`wpa`] is WPA2-Personal's handshake for a radio that leaves it to the
+//! host (Intel's), as a state machine of its own.
#![no_std]
@@ -21,6 +24,7 @@ extern crate alloc;
pub mod host;
pub mod protocol;
pub mod sim;
+pub mod wpa;
pub use host::{Event, Failure, Network, Security, Wifi};
diff --git a/wifi/src/wpa.rs b/wifi/src/wpa.rs
new file mode 100644
index 0000000..4d00d3a
--- /dev/null
+++ b/wifi/src/wpa.rs
@@ -0,0 +1,590 @@
+//! WPA2-Personal as the device does its half (IEEE 802.11-2020, 12.7):
+//! the network's key from its password and name, then the 4-way handshake
+//! that makes the keys this connection's traffic is sealed with, and the
+//! group key handshake that renews the key for what is sent to all.
+//!
+//! For a radio that leaves this to the host ("soft MAC", as Intel's Wi-Fi
+//! does): EAPOL-Key frames from the access point go into
+//! [`Supplicant::receive`], and what comes out is a frame to send back and
+//! keys for the radio to install. A pure state machine: no time, no I/O,
+//! the nonce given by the caller.
+//!
+//! What it checks before it believes a frame: the replay counter only goes
+//! up, the MIC is the pairwise key's, message 3's ANonce is message 1's,
+//! and the access point's RSN element in message 3 is the one its beacon
+//! showed (a downgrade attempt otherwise).
+
+use alloc::vec;
+use alloc::vec::Vec;
+use pinnacle_crypto::{aes, sha1, sha2};
+
+/// Which key management the network uses (the AKM suite, 00-0F-AC-n).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Akm {
+ /// 2: PSK, keys by HMAC-SHA-1 (key descriptor version 2).
+ Psk,
+ /// 6: PSK with SHA-256 (key descriptor version 3, AES-CMAC).
+ PskSha256,
+}
+
+impl Akm {
+ fn suite(self) -> u8 {
+ match self {
+ Akm::Psk => 2,
+ Akm::PskSha256 => 6,
+ }
+ }
+
+ fn version(self) -> u16 {
+ match self {
+ Akm::Psk => 2,
+ Akm::PskSha256 => 3,
+ }
+ }
+}
+
+/// The network's key from its password and name (802.11 J.4).
+pub fn psk(passphrase: &str, ssid: &[u8]) -> [u8; 32] {
+ let mut pmk = [0u8; 32];
+ sha1::pbkdf2_sha1(passphrase.as_bytes(), ssid, 4096, &mut pmk);
+ pmk
+}
+
+/// Our RSN element, as the association request carries it: version 1,
+/// CCMP for group and pairwise, one AKM, no capabilities asked.
+pub fn rsn_element(akm: Akm) -> Vec<u8> {
+ let mut e = vec![48, 20, 1, 0];
+ e.extend_from_slice(&[0x00, 0x0f, 0xac, 4]);
+ e.extend_from_slice(&[1, 0, 0x00, 0x0f, 0xac, 4]);
+ e.extend_from_slice(&[1, 0, 0x00, 0x0f, 0xac, akm.suite()]);
+ e.extend_from_slice(&[0, 0]);
+ e
+}
+
+/// What an access point's RSN element offers, as far as joining goes.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Rsn {
+ pub group_ccmp: bool,
+ pub pairwise_ccmp: bool,
+ pub akms: Vec<u8>,
+ /// Management frames protected: required (MFPR), capable (MFPC).
+ pub mfp_required: bool,
+ pub mfp_capable: bool,
+}
+
+impl Rsn {
+ /// Reads an RSN element (its ID 48 and length first).
+ pub fn parse(e: &[u8]) -> Option<Rsn> {
+ if e.first() != Some(&48) || e.len() < 2 + usize::from(e[1]) || e.len() < 8 {
+ return None;
+ }
+ let body = &e[2..2 + usize::from(e[1])];
+ let mut at = 2;
+ let suite = |b: &[u8], at: usize| -> Option<u8> {
+ let s = b.get(at..at + 4)?;
+ (s[..3] == [0x00, 0x0f, 0xac]).then_some(s[3])
+ };
+ let group = suite(body, at);
+ at += 4;
+ let count = |b: &[u8], at: usize| b.get(at..at + 2).map(|c| usize::from(u16::from_le_bytes([c[0], c[1]])));
+ let n = count(body, at)?;
+ at += 2;
+ let pairwise: Vec<Option<u8>> = (0..n).map(|i| suite(body, at + 4 * i)).collect();
+ at += 4 * n;
+ let n = count(body, at)?;
+ at += 2;
+ let akms = (0..n).filter_map(|i| suite(body, at + 4 * i)).collect();
+ at += 4 * n;
+ let caps = count(body, at).unwrap_or(0);
+ Some(Rsn {
+ group_ccmp: group == Some(4),
+ pairwise_ccmp: pairwise.contains(&Some(4)),
+ akms,
+ mfp_required: caps & 0x40 != 0,
+ mfp_capable: caps & 0x80 != 0,
+ })
+ }
+
+ /// The key management this device would use with it, WPA2-Personal
+ /// only (SHA-256 first): None for WPA3-only, Enterprise, or no CCMP.
+ pub fn choose(&self) -> Option<Akm> {
+ if !self.pairwise_ccmp {
+ return None;
+ }
+ if self.akms.contains(&6) {
+ Some(Akm::PskSha256)
+ } else if self.akms.contains(&2) && !self.mfp_required {
+ Some(Akm::Psk)
+ } else {
+ None
+ }
+ }
+}
+
+/// Key Information's bits (12.7.2).
+const PAIRWISE: u16 = 1 << 3;
+const INSTALL: u16 = 1 << 6;
+const ACK: u16 = 1 << 7;
+const MIC: u16 = 1 << 8;
+const SECURE: u16 = 1 << 9;
+const ENCRYPTED: u16 = 1 << 12;
+
+/// Where an EAPOL-Key frame's fields are, from the EAPOL header on.
+const INFO: usize = 5;
+const REPLAY: usize = 9;
+const NONCE: usize = 17;
+const RSC: usize = 65;
+const MIC_AT: usize = 81;
+const DATA_LEN: usize = 97;
+const DATA: usize = 99;
+
+/// The pairwise transient key: confirmation, encryption, and the
+/// temporal key the radio seals traffic with.
+#[derive(Clone)]
+struct Ptk {
+ kck: [u8; 16],
+ kek: [u8; 16],
+ tk: [u8; 16],
+}
+
+/// What the supplicant wants done.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum Action {
+ /// An EAPOL frame to send to the access point (EtherType 0x888e).
+ Send(Vec<u8>),
+ /// The pairwise key to install for the access point, CCMP.
+ Pairwise([u8; 16]),
+ /// A group key to install, its index and its receive sequence counter.
+ Group { index: u8, key: Vec<u8>, rsc: u64 },
+ /// The handshake is done: traffic may flow.
+ Connected,
+}
+
+/// Why a frame was not believed.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Refused {
+ Malformed,
+ /// Its replay counter is not above the last one.
+ Replayed,
+ /// Its MIC is not the pairwise key's: the wrong password, mostly.
+ Mic,
+ /// Message 3's ANonce is not message 1's.
+ Nonce,
+ /// The access point's RSN element changed between its beacon and
+ /// message 3.
+ Downgrade,
+ /// Its key data did not unwrap.
+ KeyData,
+ /// A message out of its turn.
+ Unexpected,
+}
+
+/// The device's half of WPA2-Personal, for one association.
+pub struct Supplicant {
+ pmk: [u8; 32],
+ akm: Akm,
+ own: [u8; 6],
+ ap: [u8; 6],
+ /// Our RSN element, as sent in the association request.
+ ours: Vec<u8>,
+ /// The access point's, as its beacon or probe response showed it.
+ theirs: Vec<u8>,
+ snonce: [u8; 32],
+ anonce: Option<[u8; 32]>,
+ ptk: Option<Ptk>,
+ replay: Option<u64>,
+ connected: bool,
+}
+
+impl Supplicant {
+ /// For joining the access point at `ap` from `own` with the network's
+ /// key `pmk` ([`psk`]); `theirs` the RSN element its beacon carried;
+ /// `snonce` 32 random bytes.
+ pub fn new(pmk: [u8; 32], akm: Akm, own: [u8; 6], ap: [u8; 6], theirs: &[u8], snonce: [u8; 32]) -> Supplicant {
+ Supplicant {
+ pmk,
+ akm,
+ own,
+ ap,
+ ours: rsn_element(akm),
+ theirs: theirs.to_vec(),
+ snonce,
+ anonce: None,
+ ptk: None,
+ replay: None,
+ connected: false,
+ }
+ }
+
+ /// The RSN element to put in the association request.
+ pub fn element(&self) -> &[u8] {
+ &self.ours
+ }
+
+ pub fn connected(&self) -> bool {
+ self.connected
+ }
+
+ /// An EAPOL frame from the access point.
+ pub fn receive(&mut self, frame: &[u8]) -> Result<Vec<Action>, Refused> {
+ // EAPOL: version, type 3 (Key), length; then descriptor type 2.
+ if frame.len() < DATA || frame[1] != 3 || frame[4] != 2 {
+ return Err(Refused::Malformed);
+ }
+ let length = usize::from(u16::from_be_bytes([frame[2], frame[3]]));
+ let frame = frame.get(..4 + length).ok_or(Refused::Malformed)?;
+ let data_len = usize::from(u16::from_be_bytes([frame[DATA_LEN], frame[DATA_LEN + 1]]));
+ let data = frame.get(DATA..DATA + data_len).ok_or(Refused::Malformed)?;
+ let info = u16::from_be_bytes([frame[INFO], frame[INFO + 1]]);
+ let replay = u64::from_be_bytes(frame[REPLAY..REPLAY + 8].try_into().unwrap());
+ if self.replay.is_some_and(|last| replay <= last) {
+ return Err(Refused::Replayed);
+ }
+ if info & ACK == 0 {
+ return Err(Refused::Unexpected);
+ }
+ let nonce: [u8; 32] = frame[NONCE..NONCE + 32].try_into().unwrap();
+ match (info & PAIRWISE != 0, info & MIC != 0) {
+ // Message 1: the ANonce; the keys follow from it.
+ (true, false) => {
+ let ptk = self.derive(&nonce);
+ self.anonce = Some(nonce);
+ self.replay = Some(replay);
+ let reply = self.frame(PAIRWISE | MIC, replay, &self.snonce, &self.ours.clone(), &ptk);
+ self.ptk = Some(ptk);
+ Ok(vec![Action::Send(reply)])
+ }
+ // Message 3: the group key, and install.
+ (true, true) => {
+ let ptk = self.ptk.clone().ok_or(Refused::Unexpected)?;
+ self.check_mic(frame, &ptk)?;
+ if Some(nonce) != self.anonce {
+ return Err(Refused::Nonce);
+ }
+ if info & INSTALL == 0 {
+ return Err(Refused::Unexpected);
+ }
+ let data = self.key_data(info, data, &ptk)?;
+ let rsn = elements(&data).find(|e| e[0] == 48).ok_or(Refused::Downgrade)?;
+ if rsn != self.theirs.as_slice() {
+ return Err(Refused::Downgrade);
+ }
+ self.replay = Some(replay);
+ let rsc = u64::from_le_bytes(frame[RSC..RSC + 8].try_into().unwrap());
+ let reply = self.frame(PAIRWISE | MIC | SECURE, replay, &[0; 32], &[], &ptk);
+ let mut actions = vec![Action::Send(reply), Action::Pairwise(ptk.tk)];
+ actions.extend(group(&data, rsc));
+ self.connected = true;
+ actions.push(Action::Connected);
+ Ok(actions)
+ }
+ // The group key handshake's first message: a new group key.
+ (false, true) => {
+ let ptk = self.ptk.clone().ok_or(Refused::Unexpected)?;
+ self.check_mic(frame, &ptk)?;
+ let data = self.key_data(info, data, &ptk)?;
+ self.replay = Some(replay);
+ let rsc = u64::from_le_bytes(frame[RSC..RSC + 8].try_into().unwrap());
+ let reply = self.frame(MIC | SECURE, replay, &[0; 32], &[], &ptk);
+ let mut actions = vec![Action::Send(reply)];
+ actions.extend(group(&data, rsc));
+ Ok(actions)
+ }
+ (false, false) => Err(Refused::Unexpected),
+ }
+ }
+
+ /// The PTK from the PMK, both addresses and both nonces (12.7.1.3).
+ fn derive(&self, anonce: &[u8; 32]) -> Ptk {
+ let (a1, a2) = if self.own < self.ap { (self.own, self.ap) } else { (self.ap, self.own) };
+ let (n1, n2) = if self.snonce[..] < anonce[..] {
+ (self.snonce, *anonce)
+ } else {
+ (*anonce, self.snonce)
+ };
+ let mut context = Vec::with_capacity(76);
+ context.extend_from_slice(&a1);
+ context.extend_from_slice(&a2);
+ context.extend_from_slice(&n1);
+ context.extend_from_slice(&n2);
+ let mut out = [0u8; 48];
+ let label = b"Pairwise key expansion";
+ match self.akm {
+ Akm::Psk => prf_sha1(&self.pmk, label, &context, &mut out),
+ Akm::PskSha256 => kdf_sha256(&self.pmk, label, &context, &mut out),
+ }
+ Ptk {
+ kck: out[..16].try_into().unwrap(),
+ kek: out[16..32].try_into().unwrap(),
+ tk: out[32..].try_into().unwrap(),
+ }
+ }
+
+ fn mic(&self, frame: &[u8], ptk: &Ptk) -> [u8; 16] {
+ match self.akm {
+ Akm::Psk => sha1::hmac(&ptk.kck, &[frame])[..16].try_into().unwrap(),
+ Akm::PskSha256 => aes::cmac(&ptk.kck, frame),
+ }
+ }
+
+ fn check_mic(&self, frame: &[u8], ptk: &Ptk) -> Result<(), Refused> {
+ let mut zeroed = frame.to_vec();
+ zeroed[MIC_AT..MIC_AT + 16].fill(0);
+ if !pinnacle_crypto::equal(&self.mic(&zeroed, ptk), &frame[MIC_AT..MIC_AT + 16]) {
+ return Err(Refused::Mic);
+ }
+ Ok(())
+ }
+
+ /// Key data, unwrapped when it is encrypted.
+ fn key_data(&self, info: u16, data: &[u8], ptk: &Ptk) -> Result<Vec<u8>, Refused> {
+ if info & ENCRYPTED == 0 {
+ return Ok(data.to_vec());
+ }
+ if data.len() < 24 || data.len() % 8 != 0 {
+ return Err(Refused::KeyData);
+ }
+ let mut out = vec![0u8; data.len() - 8];
+ if !aes::unwrap(&ptk.kek, data, &mut out) {
+ return Err(Refused::KeyData);
+ }
+ Ok(out)
+ }
+
+ /// An EAPOL-Key frame of ours, its MIC filled in.
+ fn frame(&self, bits: u16, replay: u64, nonce: &[u8; 32], data: &[u8], ptk: &Ptk) -> Vec<u8> {
+ let mut f = vec![0u8; DATA + data.len()];
+ f[0] = 2; // 802.1X-2004
+ f[1] = 3;
+ f[2..4].copy_from_slice(&((DATA - 4 + data.len()) as u16).to_be_bytes());
+ f[4] = 2;
+ f[INFO..INFO + 2].copy_from_slice(&(bits | self.akm.version()).to_be_bytes());
+ f[REPLAY..REPLAY + 8].copy_from_slice(&replay.to_be_bytes());
+ f[NONCE..NONCE + 32].copy_from_slice(nonce);
+ f[DATA_LEN..DATA_LEN + 2].copy_from_slice(&(data.len() as u16).to_be_bytes());
+ f[DATA..].copy_from_slice(data);
+ let mic = self.mic(&f, ptk);
+ f[MIC_AT..MIC_AT + 16].copy_from_slice(&mic);
+ f
+ }
+}
+
+/// IEEE 802.11's PRF with HMAC-SHA-1 (12.7.1.2): `out.len()` bytes.
+pub fn prf_sha1(key: &[u8], label: &[u8], data: &[u8], out: &mut [u8]) {
+ for (i, chunk) in out.chunks_mut(20).enumerate() {
+ let block = sha1::hmac(key, &[label, &[0], data, &[i as u8]]);
+ chunk.copy_from_slice(&block[..chunk.len()]);
+ }
+}
+
+/// IEEE 802.11's KDF with HMAC-SHA-256 (12.7.1.6.2): `out.len()` bytes.
+pub fn kdf_sha256(key: &[u8], label: &[u8], context: &[u8], out: &mut [u8]) {
+ let bits = ((out.len() * 8) as u16).to_le_bytes();
+ for (i, chunk) in out.chunks_mut(32).enumerate() {
+ let counter = (i as u16 + 1).to_le_bytes();
+ let block = sha2::hmac(key, &[&counter, label, context, &bits]);
+ chunk.copy_from_slice(&block[..chunk.len()]);
+ }
+}
+
+/// The elements and KDEs in key data, each from its type byte on; padding
+/// (0xdd with length 0) ends it.
+fn elements(data: &[u8]) -> impl Iterator<Item = &[u8]> {
+ let mut at = 0;
+ core::iter::from_fn(move || {
+ let kind = *data.get(at)?;
+ let len = usize::from(*data.get(at + 1)?);
+ if kind == 0xdd && len == 0 {
+ return None;
+ }
+ let e = data.get(at..at + 2 + len)?;
+ at += 2 + len;
+ Some(e)
+ })
+}
+
+/// The group key in key data's GTK KDE (00-0F-AC type 1), if there is one.
+fn group(data: &[u8], rsc: u64) -> Option<Action> {
+ let kde = elements(data).find(|e| e[0] == 0xdd && e.len() >= 8 && e[2..6] == [0x00, 0x0f, 0xac, 1])?;
+ Some(Action::Group {
+ index: kde[6] & 3,
+ key: kde[8..].to_vec(),
+ rsc,
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const OWN: [u8; 6] = [2, 0, 0, 0, 0, 1];
+ const AP: [u8; 6] = [2, 0, 0, 0, 0, 2];
+ const ANONCE: [u8; 32] = [0x11; 32];
+ const SNONCE: [u8; 32] = [0x22; 32];
+ const GTK: [u8; 16] = [0x77; 16];
+
+ fn hex(s: &str) -> Vec<u8> {
+ (0..s.len())
+ .step_by(2)
+ .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())
+ .collect()
+ }
+
+ /// The access point's RSN element: CCMP, PSK.
+ fn theirs() -> Vec<u8> {
+ rsn_element(Akm::Psk)
+ }
+
+ /// The access point's half, as far as the tests need it: its frames,
+ /// sealed with the PTK it derives the same way.
+ struct Authenticator {
+ ptk: [u8; 48],
+ }
+
+ impl Authenticator {
+ fn new(password: &str) -> Authenticator {
+ let pmk = psk(password, b"IEEE");
+ let mut context = Vec::new();
+ context.extend_from_slice(&OWN);
+ context.extend_from_slice(&AP);
+ context.extend_from_slice(&ANONCE);
+ context.extend_from_slice(&SNONCE);
+ let mut ptk = [0u8; 48];
+ prf_sha1(&pmk, b"Pairwise key expansion", &context, &mut ptk);
+ Authenticator { ptk }
+ }
+
+ fn frame(&self, info: u16, replay: u64, nonce: &[u8; 32], plain: &[u8]) -> Vec<u8> {
+ let data = if info & ENCRYPTED != 0 {
+ let mut padded = plain.to_vec();
+ if padded.len() % 8 != 0 || padded.len() < 16 {
+ padded.push(0xdd);
+ }
+ while padded.len() % 8 != 0 || padded.len() < 16 {
+ padded.push(0);
+ }
+ let mut out = vec![0u8; padded.len() + 8];
+ assert!(aes::wrap(&self.ptk[16..32], &padded, &mut out));
+ out
+ } else {
+ plain.to_vec()
+ };
+ let mut f = vec![0u8; DATA + data.len()];
+ f[0] = 2;
+ f[1] = 3;
+ f[2..4].copy_from_slice(&((DATA - 4 + data.len()) as u16).to_be_bytes());
+ f[4] = 2;
+ f[INFO..INFO + 2].copy_from_slice(&(info | 2).to_be_bytes());
+ f[REPLAY..REPLAY + 8].copy_from_slice(&replay.to_be_bytes());
+ f[NONCE..NONCE + 32].copy_from_slice(nonce);
+ f[RSC..RSC + 8].copy_from_slice(&5u64.to_le_bytes());
+ f[DATA_LEN..DATA_LEN + 2].copy_from_slice(&(data.len() as u16).to_be_bytes());
+ f[DATA..].copy_from_slice(&data);
+ if info & MIC != 0 {
+ let mic = sha1::hmac(&self.ptk[..16], &[&f]);
+ f[MIC_AT..MIC_AT + 16].copy_from_slice(&mic[..16]);
+ }
+ f
+ }
+
+ fn message1(&self) -> Vec<u8> {
+ self.frame(PAIRWISE | ACK, 1, &ANONCE, &[])
+ }
+
+ fn message3(&self, replay: u64, rsn: &[u8]) -> Vec<u8> {
+ let mut data = rsn.to_vec();
+ data.extend_from_slice(&[0xdd, 22, 0x00, 0x0f, 0xac, 1, 0x01, 0]);
+ data.extend_from_slice(>K);
+ self.frame(PAIRWISE | ACK | MIC | INSTALL | SECURE | ENCRYPTED, replay, &ANONCE, &data)
+ }
+
+ fn checks(&self, frame: &[u8]) -> bool {
+ let mut zeroed = frame.to_vec();
+ zeroed[MIC_AT..MIC_AT + 16].fill(0);
+ sha1::hmac(&self.ptk[..16], &[&zeroed])[..16] == frame[MIC_AT..MIC_AT + 16]
+ }
+ }
+
+ fn supplicant(password: &str) -> Supplicant {
+ Supplicant::new(psk(password, b"IEEE"), Akm::Psk, OWN, AP, &theirs(), SNONCE)
+ }
+
+ #[test]
+ fn the_4_way_handshake() {
+ let ap = Authenticator::new("password");
+ let mut s = supplicant("password");
+ let Ok(actions) = s.receive(&ap.message1()) else { panic!() };
+ let [Action::Send(message2)] = actions.as_slice() else { panic!("{actions:?}") };
+ // Its MIC as Python's hmac and hashlib make it, for these inputs.
+ assert_eq!(message2[MIC_AT..MIC_AT + 16], hex("688787e519a79f7230dac64e7f72e155"));
+ assert!(ap.checks(message2));
+ assert_eq!(&message2[DATA..], theirs().as_slice(), "our RSN element in message 2");
+
+ let actions = s.receive(&ap.message3(2, &theirs())).unwrap();
+ let tk = hex("5b88694a8268c05bfe4c53de87b97d81");
+ assert_eq!(actions[1], Action::Pairwise(tk.try_into().unwrap()));
+ assert_eq!(
+ actions[2],
+ Action::Group {
+ index: 1,
+ key: GTK.to_vec(),
+ rsc: 5
+ }
+ );
+ assert_eq!(actions[3], Action::Connected);
+ let Action::Send(message4) = &actions[0] else { panic!() };
+ assert!(ap.checks(message4));
+ assert_eq!(u16::from_be_bytes([message4[INFO], message4[INFO + 1]]), PAIRWISE | MIC | SECURE | 2);
+ assert!(s.connected());
+
+ // A new group key, later.
+ let mut data = vec![0xdd, 22, 0x00, 0x0f, 0xac, 1, 0x02, 0];
+ data.extend_from_slice(&[0x88; 16]);
+ let rekey = ap.frame(ACK | MIC | SECURE | ENCRYPTED, 3, &[0; 32], &data);
+ let actions = s.receive(&rekey).unwrap();
+ assert!(matches!(&actions[0], Action::Send(f) if ap.checks(f)));
+ assert_eq!(
+ actions[1],
+ Action::Group {
+ index: 2,
+ key: vec![0x88; 16],
+ rsc: 5
+ }
+ );
+ // The same frame again is a replay.
+ assert_eq!(s.receive(&rekey), Err(Refused::Replayed));
+ }
+
+ #[test]
+ fn a_wrong_password_a_downgrade_and_a_forged_frame_are_refused() {
+ let ap = Authenticator::new("password");
+ let mut s = supplicant("not the password");
+ s.receive(&ap.message1()).unwrap();
+ assert_eq!(s.receive(&ap.message3(2, &theirs())), Err(Refused::Mic));
+
+ let mut s = supplicant("password");
+ s.receive(&ap.message1()).unwrap();
+ // The beacon said CCMP and PSK; message 3 says only TKIP.
+ let mut weaker = theirs();
+ weaker[7] = 2;
+ assert_eq!(s.receive(&ap.message3(2, &weaker)), Err(Refused::Downgrade));
+
+ let mut forged = ap.message3(3, &theirs());
+ forged[DATA + 3] ^= 1;
+ assert_eq!(s.receive(&forged), Err(Refused::Mic));
+ assert!(!s.connected());
+ }
+
+ #[test]
+ fn what_a_network_offers() {
+ let wpa2 = Rsn::parse(&theirs()).unwrap();
+ assert_eq!(wpa2.choose(), Some(Akm::Psk));
+ // WPA3-only (SAE, 8) with protected management frames required.
+ let mut wpa3 = rsn_element(Akm::Psk);
+ wpa3[19] = 8;
+ wpa3[20] = 0xc0;
+ let wpa3 = Rsn::parse(&wpa3).unwrap();
+ assert!(wpa3.mfp_required);
+ assert_eq!(wpa3.choose(), None);
+ }
+}