garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /wifi/src/wpa.rs

raw

//! 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().is_multiple_of(8) {
            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().is_multiple_of(8) || padded.len() < 16 {
                    padded.push(0xdd);
                }
                while !padded.len().is_multiple_of(8) || 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(&GTK);
            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);
    }
}