feat(drivers): add WPA3-Personal SAE over P-256 with hunting-and-pecking and hash-to-element and key AKM 8 handshakes

This commit is contained in:
Tyler Smith committed 2026-10-28 11:38:18 +00:00
1 parent 2636824751
commit c1be4dc4ff
8 files changed
+856 -8

No files matched your search

Generated
+1
View File
@@ -1792,6 +1792,7 @@ dependencies = [
"hmac",
"libc",
"object",
"p256",
"sha1",
"sha2",
"subtle",
+1
View File
@@ -584,6 +584,7 @@ dependencies = [
"hmac",
"libc",
"object",
"p256",
"sha1",
"sha2",
"subtle",
+2
View File
@@ -33,6 +33,8 @@ metal = []
aes = { version = "0.8", default-features = false, features = ["zeroize"] }
# WPA2-Personal: PBKDF2/PRF/MIC over HMAC-SHA1 and HMAC-SHA256.
hmac = { version = "0.12", default-features = false }
# WPA3-Personal: SAE over P-256, hash-to-element through its simplified SWU map.
p256 = { version = "0.13", default-features = false, features = ["arithmetic", "expose-field", "hash2curve"] }
sha1 = { version = "0.10", default-features = false }
sha2 = { version = "0.10", default-features = false }
# Cryptographic MIC comparison retains an explicit optimization barrier.
+1
View File
@@ -11,6 +11,7 @@ pub mod intel;
pub mod mediatek;
pub mod realtek;
pub mod regulatory;
pub mod sae;
pub mod scan;
pub mod security;
pub mod station;
+609
View File
@@ -0,0 +1,609 @@
// SPDX-License-Identifier: GPL-2.0-only
// Copyright (c) 2026 Stela contributors
//! WPA3-Personal Simultaneous Authentication of Equals over the NIST P-256
//! group 19 (IEEE 802.11-2020 12.4): the password element by hunting and
//! pecking (12.4.4.2.2) or hash-to-element (12.4.4.2.3), the commit and
//! confirm exchange (12.4.5, 12.4.7) and the PMK and PMKID it yields, in the
//! order hostapd's `sae_prepare_commit`, `sae_process_commit` and
//! `sae_check_confirm` take them. The station's frames travel through
//! [`Station::external_authentication_transmit`] and the AP's arrive from
//! [`Station::receive_external_authentication`] as transaction, status and
//! data; the PMK then keys the 4-way handshake of
//! [`Supplicant`](super::supplicant::Supplicant) under [`Akm::Sae`].
//!
//! [`Station::external_authentication_transmit`]: super::station::Station::external_authentication_transmit
//! [`Station::receive_external_authentication`]: super::station::Station::receive_external_authentication
//! [`Akm::Sae`]: super::supplicant::Akm::Sae
use super::{
station::external::{Received, Session},
supplicant::{hmac_sha256, kdf_sha256},
};
use crate::net::Mac;
use alloc::vec::Vec;
use p256::{
AffinePoint, EncodedPoint, FieldBytes, FieldElement, NistP256, ProjectivePoint, Scalar, U256,
elliptic_curve::{
Curve, Field, PrimeField,
bigint::Encoding,
generic_array::GenericArray,
hash2curve::{FromOkm, MapToCurve},
point::DecompressPoint,
sec1::{FromEncodedPoint, ToEncodedPoint},
subtle::{Choice, ConditionallySelectable, ConstantTimeEq},
},
};
use zeroize::{Zeroize, Zeroizing};
/// The SAE authentication algorithm number.
pub const ALGORITHM: u16 = 3;
/// The finite cyclic group: 256-bit random ECP group (NIST P-256).
pub const GROUP: u16 = 19;
/// WLAN_STATUS_ANTI_CLOG_REQUIRED.
pub const STATUS_ANTI_CLOGGING: u16 = 76;
/// WLAN_STATUS_SAE_HASH_TO_ELEMENT: the status of every hash-to-element
/// commit.
pub const STATUS_HASH_TO_ELEMENT: u16 = 126;
const COMMIT: u16 = 1;
const CONFIRM: u16 = 2;
/// hostapd's `k`: hunting and pecking runs at least this many rounds,
/// whichever round finds the element, so its time does not reveal which.
const ROUNDS: u8 = 40;
const MAX_ROUNDS: u8 = 200;
const ELEMENT_BYTES: usize = 64;
const SCALAR_BYTES: usize = 32;
/// Element ID Extension and its password identifier and anti-clogging token
/// container IDs.
const EXTENSION: u8 = 255;
const PASSWORD_IDENTIFIER: u8 = 33;
const TOKEN_CONTAINER: u8 = 93;
/// The P-256 prime, the context of the hunting-and-pecking KDF.
const PRIME: [u8; 32] = [
0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
];
/// The RSNXE a station's association request carries after a
/// hash-to-element exchange: SAE-H2E set, so the AP sees no downgrade.
pub const H2E_RSNXE: [u8; 3] = [244, 1, SAE_H2E];
/// RSNXE capability bit 5, WLAN_RSNX_CAPAB_SAE_H2E.
const SAE_H2E: u8 = 1 << 5;
/// How the password element comes from the password.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Derivation {
/// Hunting and pecking, status 0 commits.
HuntingAndPecking,
/// Hash-to-element, status 126 commits, for an AP whose RSNXE sets
/// SAE-H2E.
HashToElement,
}
impl Derivation {
/// The derivation for an AP's RSNXE body: hash-to-element when it sets
/// SAE-H2E, as wpa_supplicant's `sae_pwe` 2 picks it.
pub fn for_rsnxe(rsnxe: Option<&[u8]>) -> Self {
match rsnxe.and_then(<[u8]>::first) {
Some(capabilities) if capabilities & SAE_H2E != 0 => Self::HashToElement,
_ => Self::HuntingAndPecking,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Error {
/// The peer used a group other than 19.
Group,
/// A length or field the frame does not hold.
Malformed,
/// The peer's scalar is not in (1, r).
Scalar,
/// The peer's element is not a point of the curve.
Element,
/// The peer sent the station's own scalar and element back.
Reflection,
/// The shared secret is the point at infinity.
Secret,
/// The peer's confirm does not verify under the KCK.
Confirm,
/// The AP ended the exchange with this status code.
Status(u16),
/// A frame out of the exchange's order.
Sequence,
/// No round of hunting and pecking found an element.
Exhausted,
/// The random source gave no usable scalar.
Random,
}
/// The larger then the smaller address, as 12.4.4.2 orders them.
fn addresses(a: Mac, b: Mac) -> [u8; 12] {
let (high, low) = if a.0 > b.0 { (a, b) } else { (b, a) };
let mut out = [0; 12];
out[..6].copy_from_slice(&high.0);
out[6..].copy_from_slice(&low.0);
out
}
/// The password element by hunting and pecking: the first `pwd-value` below
/// p that is the x of a curve point, with the y whose parity is the
/// `pwd-seed`'s (12.4.4.2.2).
fn hunt_and_peck(password: &[u8], a: Mac, b: Mac) -> Result<ProjectivePoint, Error> {
let base = addresses(a, b);
let mut found = Choice::from(0);
let mut element = AffinePoint::IDENTITY;
let mut counter = 1u8;
while counter <= ROUNDS || !bool::from(found) {
if counter > MAX_ROUNDS {
return Err(Error::Exhausted);
}
let seed = Zeroizing::new(hmac_sha256(&base, &[password, &[counter]]));
let value = kdf_sha256(&seed[..], b"SAE Hunting and Pecking", &PRIME, 32);
let candidate =
AffinePoint::decompress(FieldBytes::from_slice(&value), Choice::from(seed[31] & 1));
let take = candidate.is_some() & !found;
element = AffinePoint::conditional_select(
&element,
&candidate.unwrap_or(AffinePoint::IDENTITY),
take,
);
found |= take;
counter += 1;
}
Ok(element.into())
}
/// The password element template of hash-to-element (12.4.4.2.3): the sum
/// of the simplified SWU images of two hashes of the password, its optional
/// identifier and the SSID. A station keeps it per network and password.
pub struct Template(ProjectivePoint);
impl core::fmt::Debug for Template {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("Template")
}
}
impl Drop for Template {
fn drop(&mut self) {
self.0.zeroize();
}
}
impl Template {
pub fn derive(ssid: &[u8], password: &[u8], identifier: Option<&[u8]>) -> Self {
// pwd-seed = HKDF-Extract(ssid, password [|| identifier])
let mut secret = Zeroizing::new(password.to_vec());
secret.extend_from_slice(identifier.unwrap_or_default());
let seed = Zeroizing::new(hmac_sha256(ssid, &[&secret]));
let map = |info: &[u8]| {
// pwd-value = HKDF-Expand(pwd-seed, info, len(p) + len(p) / 2)
let first = Zeroizing::new(hmac_sha256(&seed[..], &[info, &[1]]));
let second = Zeroizing::new(hmac_sha256(&seed[..], &[&first[..], info, &[2]]));
let mut value = Zeroizing::new([0; 48]);
value[..32].copy_from_slice(&first[..]);
value[32..].copy_from_slice(&second[..16]);
FieldElement::from_okm(GenericArray::from_slice(&value[..])).map_to_curve()
};
Self(map(b"SAE Hash to Element u1 P1") + map(b"SAE Hash to Element u2 P2"))
}
/// The password element of the exchange between `a` and `b`:
/// `((H(0, MAX || MIN) mod (r - 1)) + 1) * PT`.
pub fn element(&self, a: Mac, b: Mac) -> ProjectivePoint {
let value = U256::from_be_slice(&hmac_sha256(&[0; 32], &[&addresses(a, b)]));
let order = NistP256::ORDER.wrapping_sub(&U256::ONE);
// A 256-bit value is below 2(r - 1), so one subtraction reduces it.
let reduced = if value >= order {
value.wrapping_sub(&order)
} else {
value
};
let scale = Scalar::from_repr(reduced.wrapping_add(&U256::ONE).to_be_bytes().into())
.expect("a value at most r - 1 is a scalar");
self.0 * scale
}
}
/// An SAE frame's transaction, status and data after the algorithm number.
#[derive(Clone, PartialEq, Eq)]
pub struct Frame {
pub transaction: u16,
pub status: u16,
pub data: Vec<u8>,
}
impl core::fmt::Debug for Frame {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("Frame")
.field("transaction", &self.transaction)
.field("status", &self.status)
.field("length", &self.data.len())
.finish()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum State {
/// The station's commit is out.
Committed,
/// The station's confirm is out.
Confirmed,
/// The AP's confirm verified.
Accepted,
}
/// The keys of an exchange whose commits both arrived.
struct Keys {
kck: Zeroizing<[u8; 32]>,
pmk: Zeroizing<[u8; 32]>,
pmkid: [u8; 16],
}
/// The station's side of one SAE exchange with one AP.
pub struct Exchange {
derivation: Derivation,
identifier: Option<Vec<u8>>,
element: ProjectivePoint,
random: Scalar,
own_scalar: Scalar,
own_element: AffinePoint,
/// The token of the AP's last anti-clogging request.
token: Option<Vec<u8>>,
peer: Option<(Scalar, AffinePoint)>,
keys: Option<Keys>,
/// The send-confirm counter of the station's last confirm.
send_confirm: u16,
state: State,
}
impl Drop for Exchange {
fn drop(&mut self) {
self.element.zeroize();
self.random.zeroize();
}
}
impl core::fmt::Debug for Exchange {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("Exchange")
.field("derivation", &self.derivation)
.field("state", &self.state)
.finish_non_exhaustive()
}
}
/// A scalar in (1, r) from `random`, as `sae_get_rand` draws them.
fn random_scalar(random: &mut dyn FnMut() -> [u8; 32]) -> Result<Scalar, Error> {
for _ in 0..MAX_ROUNDS {
let bytes = Zeroizing::new(random());
let scalar = Option::<Scalar>::from(Scalar::from_repr(*FieldBytes::from_slice(&bytes[..])));
if let Some(scalar) = scalar.filter(|scalar| !small(scalar)) {
return Ok(scalar);
}
}
Err(Error::Random)
}
/// Whether a scalar is 0 or 1.
fn small(scalar: &Scalar) -> bool {
bool::from(scalar.is_zero() | scalar.ct_eq(&Scalar::ONE))
}
fn encode(scalar: &Scalar, element: &AffinePoint, out: &mut Vec<u8>) {
out.extend_from_slice(&scalar.to_repr());
let point = element.to_encoded_point(false);
out.extend_from_slice(point.x().expect("an element is a finite point"));
out.extend_from_slice(point.y().expect("an element is a finite point"));
}
impl Exchange {
/// Begin the exchange of `own` with `peer` and write its first commit.
/// `template` serves [`Derivation::HashToElement`]; hunting and pecking
/// derives the element from `password`.
pub fn new(
derivation: Derivation,
password: &[u8],
template: Option<&Template>,
identifier: Option<&[u8]>,
own: Mac,
peer: Mac,
random: &mut dyn FnMut() -> [u8; 32],
) -> Result<Self, Error> {
let element = match (derivation, template) {
(Derivation::HashToElement, Some(template)) => template.element(own, peer),
(Derivation::HashToElement, None) => return Err(Error::Sequence),
(Derivation::HuntingAndPecking, _) => hunt_and_peck(password, own, peer)?,
};
let random_value = random_scalar(random)?;
let mut mask = random_scalar(random)?;
let mut exchange = Self::with_secrets(derivation, element, random_value, &mask);
// sae_derive_commit draws again when rand + mask mod r is below 2.
while small(&exchange.own_scalar) {
mask = random_scalar(random)?;
exchange = Self::with_secrets(derivation, element, random_scalar(random)?, &mask);
}
mask.zeroize();
exchange.identifier = identifier.map(<[u8]>::to_vec);
Ok(exchange)
}
/// Begin the exchange of an external authentication session: its
/// station, AP and, for hash-to-element, SSID. The frames go out
/// through [`Station::external_authentication_transmit`] under the same
/// session.
///
/// [`Station::external_authentication_transmit`]: super::station::Station::external_authentication_transmit
pub fn for_session(
session: &Session,
derivation: Derivation,
password: &[u8],
identifier: Option<&[u8]>,
random: &mut dyn FnMut() -> [u8; 32],
) -> Result<Self, Error> {
let template = (derivation == Derivation::HashToElement)
.then(|| Template::derive(session.ssid(), password, identifier));
Self::new(
derivation,
password,
template.as_ref(),
identifier,
session.local(),
session.peer(),
random,
)
}
/// Take the AP's frame of the session, as
/// [`Station::receive_external_authentication`] passed it on.
///
/// [`Station::receive_external_authentication`]: super::station::Station::receive_external_authentication
pub fn receive_from(&mut self, received: &Received) -> Result<Option<Frame>, Error> {
self.receive(received.transaction(), received.status(), received.data())
}
/// commit-scalar = (rand + mask) mod r, COMMIT-ELEMENT = -(mask * PWE).
fn with_secrets(
derivation: Derivation,
element: ProjectivePoint,
random: Scalar,
mask: &Scalar,
) -> Self {
Self {
derivation,
identifier: None,
element,
random,
own_scalar: random + mask,
own_element: (-(element * mask)).to_affine(),
token: None,
peer: None,
keys: None,
send_confirm: 0,
state: State::Committed,
}
}
/// The station's commit: the group, the anti-clogging token the AP
/// asked for, the scalar and the element, and for hash-to-element the
/// password identifier and the token in its container (12.4.7.4).
pub fn commit(&self) -> Frame {
let mut data = Vec::with_capacity(2 + SCALAR_BYTES + ELEMENT_BYTES);
data.extend_from_slice(&GROUP.to_le_bytes());
let h2e = self.derivation == Derivation::HashToElement;
if let (false, Some(token)) = (h2e, &self.token) {
data.extend_from_slice(token);
}
encode(&self.own_scalar, &self.own_element, &mut data);
if let Some(identifier) = &self.identifier {
data.extend_from_slice(&[EXTENSION, identifier.len() as u8 + 1, PASSWORD_IDENTIFIER]);
data.extend_from_slice(identifier);
}
if let (true, Some(token)) = (h2e, &self.token) {
data.extend_from_slice(&[EXTENSION, token.len() as u8 + 1, TOKEN_CONTAINER]);
data.extend_from_slice(token);
}
Frame {
transaction: COMMIT,
status: self.commit_status(),
data,
}
}
const fn commit_status(&self) -> u16 {
match self.derivation {
Derivation::HuntingAndPecking => 0,
Derivation::HashToElement => STATUS_HASH_TO_ELEMENT,
}
}
/// Whether the AP's confirm verified.
pub fn accepted(&self) -> bool {
self.state == State::Accepted
}
/// The PMK once the AP's confirm verified.
pub fn pmk(&self) -> Option<Zeroizing<[u8; 32]>> {
self.keys
.as_ref()
.filter(|_| self.accepted())
.map(|keys| keys.pmk.clone())
}
/// The PMKID once the AP's confirm verified.
pub fn pmkid(&self) -> Option<[u8; 16]> {
self.keys
.as_ref()
.filter(|_| self.accepted())
.map(|keys| keys.pmkid)
}
/// Take one SAE frame from the AP: the frame the station sends next, if
/// any. An error ends the exchange.
pub fn receive(
&mut self,
transaction: u16,
status: u16,
data: &[u8],
) -> Result<Option<Frame>, Error> {
match (transaction, status) {
(COMMIT, STATUS_ANTI_CLOGGING) if self.state == State::Committed => {
self.anti_clogging(data)?;
Ok(Some(self.commit()))
}
(COMMIT, status) if status == self.commit_status() => match self.state {
State::Committed => {
self.peer_commit(data)?;
self.state = State::Confirmed;
Ok(Some(self.confirm()))
}
// The AP sent its commit again: it lost the confirm.
State::Confirmed if self.peer == Some(parse_commit(data)?) => {
Ok(Some(self.confirm()))
}
_ => Err(Error::Sequence),
},
(CONFIRM, 0) if self.state == State::Confirmed => {
self.peer_confirm(data)?;
self.state = State::Accepted;
Ok(None)
}
(COMMIT | CONFIRM, 0) => Err(Error::Sequence),
(COMMIT | CONFIRM, status) => Err(Error::Status(status)),
_ => Err(Error::Sequence),
}
}
/// Keep the token of an anti-clogging request for the next commit.
fn anti_clogging(&mut self, data: &[u8]) -> Result<(), Error> {
let (group, token) = data.split_at_checked(2).ok_or(Error::Malformed)?;
if u16::from_le_bytes([group[0], group[1]]) != GROUP {
return Err(Error::Group);
}
let token = match self.derivation {
Derivation::HuntingAndPecking => token,
Derivation::HashToElement => match token {
[EXTENSION, length, TOKEN_CONTAINER, rest @ ..]
if usize::from(*length) == rest.len() + 1 =>
{
rest
}
_ => return Err(Error::Malformed),
},
};
if token.is_empty() || token.len() > 254 {
return Err(Error::Malformed);
}
self.token = Some(token.to_vec());
Ok(())
}
/// `sae_process_commit`: the shared secret k = F(rand * (peer-scalar *
/// PWE + PEER-ELEMENT)), keyseed = H(0, k), KCK || PMK = KDF-512(keyseed,
/// "SAE KCK and PMK", (scalar + peer-scalar) mod r) and the PMKID.
fn peer_commit(&mut self, data: &[u8]) -> Result<(), Error> {
let (scalar, element) = parse_commit(data)?;
if scalar == self.own_scalar && element == self.own_element {
return Err(Error::Reflection);
}
let secret = ((self.element * scalar + element) * self.random).to_affine();
if bool::from(secret.is_identity()) {
return Err(Error::Secret);
}
let point = secret.to_encoded_point(false);
let shared = Zeroizing::new(*point.x().ok_or(Error::Secret)?);
let keyseed = Zeroizing::new(hmac_sha256(&[0; 32], &[&shared[..]]));
let sum = (self.own_scalar + scalar).to_repr();
let keys = kdf_sha256(&keyseed[..], b"SAE KCK and PMK", &sum, 64);
self.keys = Some(Keys {
kck: Zeroizing::new(keys[..32].try_into().unwrap()),
pmk: Zeroizing::new(keys[32..].try_into().unwrap()),
pmkid: sum[..16].try_into().unwrap(),
});
self.peer = Some((scalar, element));
Ok(())
}
/// CN(KCK, send-confirm, scalar, element, peer-scalar, peer-element).
fn confirm_value(
&self,
send_confirm: u16,
first: (&Scalar, &AffinePoint),
second: (&Scalar, &AffinePoint),
) -> [u8; 32] {
let keys = self.keys.as_ref().expect("both commits arrived");
let mut message = Vec::with_capacity(2 + 2 * (SCALAR_BYTES + ELEMENT_BYTES));
message.extend_from_slice(&send_confirm.to_le_bytes());
encode(first.0, first.1, &mut message);
encode(second.0, second.1, &mut message);
hmac_sha256(&keys.kck[..], &[&message])
}
/// The station's confirm under the next send-confirm.
fn confirm(&mut self) -> Frame {
self.send_confirm = self.send_confirm.saturating_add(1);
let (scalar, element) = self.peer.expect("the peer committed");
let value = self.confirm_value(
self.send_confirm,
(&self.own_scalar, &self.own_element),
(&scalar, &element),
);
let mut data = Vec::with_capacity(34);
data.extend_from_slice(&self.send_confirm.to_le_bytes());
data.extend_from_slice(&value);
Frame {
transaction: CONFIRM,
status: 0,
data,
}
}
/// `sae_check_confirm`: the AP's confirm over its commit then the
/// station's.
fn peer_confirm(&self, data: &[u8]) -> Result<(), Error> {
let [low, high, value @ ..] = data else {
return Err(Error::Malformed);
};
if value.len() != 32 {
return Err(Error::Malformed);
}
let (scalar, element) = self.peer.ok_or(Error::Sequence)?;
let expected = self.confirm_value(
u16::from_le_bytes([*low, *high]),
(&scalar, &element),
(&self.own_scalar, &self.own_element),
);
if bool::from(expected.ct_eq(value)) {
Ok(())
} else {
Err(Error::Confirm)
}
}
}
/// A commit's scalar in (1, r) and its element on the curve; elements after
/// the element are the AP's and carry nothing the station checks.
fn parse_commit(data: &[u8]) -> Result<(Scalar, AffinePoint), Error> {
let fixed = data
.get(..2 + SCALAR_BYTES + ELEMENT_BYTES)
.ok_or(Error::Malformed)?;
if u16::from_le_bytes([fixed[0], fixed[1]]) != GROUP {
return Err(Error::Group);
}
let scalar = Option::<Scalar>::from(Scalar::from_repr(*FieldBytes::from_slice(
&fixed[2..2 + SCALAR_BYTES],
)))
.filter(|scalar| !small(scalar))
.ok_or(Error::Scalar)?;
let coordinates = &fixed[2 + SCALAR_BYTES..];
let point = EncodedPoint::from_affine_coordinates(
FieldBytes::from_slice(&coordinates[..32]),
FieldBytes::from_slice(&coordinates[32..]),
false,
);
let element = Option::<AffinePoint>::from(AffinePoint::from_encoded_point(&point))
.ok_or(Error::Element)?;
Ok((scalar, element))
}
#[cfg(test)]
mod tests;
+223
View File
@@ -0,0 +1,223 @@
// SPDX-License-Identifier: GPL-2.0-only
// Copyright (c) 2026 Stela contributors
//! SAE against the IEEE 802.11-2020 Annex J.10 vectors hostapd's
//! `sae_tests` checks, and between two exchanges.
use super::*;
fn hex(text: &str) -> Vec<u8> {
(0..text.len())
.step_by(2)
.map(|at| u8::from_str_radix(&text[at..at + 2], 16).unwrap())
.collect()
}
fn scalar(text: &str) -> Scalar {
Scalar::from_repr(*FieldBytes::from_slice(&hex(text))).unwrap()
}
const PASSWORD: &[u8] = b"mekmitasdigoat";
const OWN: Mac = Mac([0x4d, 0x3f, 0x2f, 0xff, 0xe3, 0x87]);
const PEER: Mac = Mac([0xa5, 0xd8, 0xaa, 0x95, 0x8e, 0x3c]);
/// Distinct scalars below r from a counter.
fn counter() -> impl FnMut() -> [u8; 32] {
let mut next = 0u8;
move || {
next += 1;
[next; 32]
}
}
#[test]
fn hunting_and_pecking_commits_and_derives_the_annex_j_keys() {
let element = hunt_and_peck(PASSWORD, OWN, PEER).unwrap();
let mask = scalar("9507a90f777a044d6a0830b91ea3d5dd70bece44e1acffb86983b5e1bf9fb322");
let mut exchange = Exchange::with_secrets(
Derivation::HuntingAndPecking,
element,
scalar("992465fd3daa3c60aa6565b7f62a2a7f2e12dd12f198faf4fbed89d7ff1ace94"),
&mask,
);
let commit = exchange.commit();
assert_eq!((commit.transaction, commit.status), (1, 0));
assert_eq!(
commit.data,
hex(concat!(
"13002e2c0f0db52440ad146d967114ce005ce1eab0aa2c2e5c2871b774f6c257",
"5c65d5ad9e00829707aa36ba8b859738fc961d08243505f47c035376d7ac4bc8",
"d7b95083bf43827d0fc31ed778dd3671fd21a46d1091d64b6f9a1e1272621325",
"dbe1"
))
);
let peer = hex(concat!(
"1300591b96f3397fb945100848e7b550543b6720d88337ee93fc49fd6df7e08b",
"5223e71b9bb048d3873f20556953a96c91536fd8ee6ca9b4a68a148b056a909b",
"e03e83ae208f60f8ef5537858074db06687032399862999b511e0a1552a5fea3",
"17c2"
));
let confirm = exchange.receive(1, 0, &peer).unwrap().unwrap();
assert_eq!((confirm.transaction, confirm.status), (2, 0));
assert_eq!(confirm.data[..2], [1, 0]);
let keys = exchange.keys.as_ref().unwrap();
assert_eq!(
keys.kck[..],
hex("1e733f6d9bd53256287304338831b09a39406d121017073a5c30db36f36cb81a")
);
assert_eq!(
keys.pmk[..],
hex("4e4dfab1a2dd8ac1a91790f953faaa452ae5c6873ab75b63605ba663f8a7fe59")
);
assert_eq!(keys.pmkid[..], hex("8747a600eea3f9f22475df58ca1e5498"));
// The PMK stays the exchange's until the AP's confirm verifies.
assert!(exchange.pmk().is_none());
}
#[test]
fn hash_to_element_derives_the_annex_j_password_element() {
let template = Template::derive(b"byteme", PASSWORD, Some(b"psk4internet"));
let element = template
.element(
Mac([0x00, 0x09, 0x5b, 0x66, 0xec, 0x1e]),
Mac([0x00, 0x0b, 0x6b, 0xd9, 0x02, 0x46]),
)
.to_affine()
.to_encoded_point(false);
assert_eq!(
element.x().unwrap()[..],
hex("c93049b9e64000f848201649e999f2b5c22dea69b5632c9df4d633b8aa1f6c1e")
);
assert_eq!(
element.y().unwrap()[..],
hex("73634e94b53d82e7383a8d258199d9dc1a5ee8269d060382ccbf33e614ff59a0")
);
}
fn pair(derivation: Derivation) -> (Exchange, Exchange) {
let template = Template::derive(b"byteme", PASSWORD, None);
let template = (derivation == Derivation::HashToElement).then_some(&template);
let mut random = counter();
let station = Exchange::new(derivation, PASSWORD, template, None, OWN, PEER, &mut random);
let ap = Exchange::new(derivation, PASSWORD, template, None, PEER, OWN, &mut random);
(station.unwrap(), ap.unwrap())
}
#[test]
fn both_derivations_agree_on_the_pmk_and_pmkid_between_station_and_ap() {
for derivation in [Derivation::HuntingAndPecking, Derivation::HashToElement] {
let (mut station, mut ap) = pair(derivation);
let (station_commit, ap_commit) = (station.commit(), ap.commit());
let ap_confirm = ap
.receive(1, station_commit.status, &station_commit.data)
.unwrap()
.unwrap();
let station_confirm = station
.receive(1, ap_commit.status, &ap_commit.data)
.unwrap()
.unwrap();
assert_eq!(station.receive(2, 0, &ap_confirm.data), Ok(None));
assert_eq!(ap.receive(2, 0, &station_confirm.data), Ok(None));
assert!(station.accepted() && ap.accepted());
assert_eq!(station.pmk().unwrap()[..], ap.pmk().unwrap()[..]);
assert_eq!(station.pmkid(), ap.pmkid());
}
}
#[test]
fn a_repeated_ap_commit_gets_the_confirm_again_with_the_next_send_confirm() {
let (mut station, ap) = pair(Derivation::HuntingAndPecking);
let commit = ap.commit();
let first = station.receive(1, 0, &commit.data).unwrap().unwrap();
let again = station.receive(1, 0, &commit.data).unwrap().unwrap();
assert_eq!(
(&first.data[..2], &again.data[..2]),
(&[1, 0][..], &[2, 0][..])
);
}
#[test]
fn a_wrong_confirm_a_reflected_commit_and_a_denial_end_the_exchange() {
let (mut station, ap) = pair(Derivation::HuntingAndPecking);
let own = station.commit();
assert_eq!(station.receive(1, 0, &own.data), Err(Error::Reflection));
station.receive(1, 0, &ap.commit().data).unwrap();
let mut forged = [0u8; 34];
forged[0] = 1;
assert_eq!(station.receive(2, 0, &forged), Err(Error::Confirm));
assert!(!station.accepted() && station.pmk().is_none());
let (mut station, _) = pair(Derivation::HuntingAndPecking);
assert_eq!(station.receive(1, 77, &[19, 0]), Err(Error::Status(77)));
assert_eq!(station.receive(2, 0, &[0; 34]), Err(Error::Sequence));
// A hash-to-element commit answers a hunting-and-pecking one only with
// its own status.
assert_eq!(
station.receive(1, STATUS_HASH_TO_ELEMENT, &ap.commit().data),
Err(Error::Status(STATUS_HASH_TO_ELEMENT))
);
}
#[test]
fn a_commit_outside_the_group_or_curve_is_refused() {
let (mut station, ap) = pair(Derivation::HuntingAndPecking);
let mut commit = ap.commit().data;
commit[0] = 20;
assert_eq!(station.receive(1, 0, &commit), Err(Error::Group));
let mut commit = ap.commit().data;
commit[2..34].fill(0);
assert_eq!(station.receive(1, 0, &commit), Err(Error::Scalar));
let mut commit = ap.commit().data;
commit[97] ^= 1;
assert_eq!(station.receive(1, 0, &commit), Err(Error::Element));
assert_eq!(station.receive(1, 0, &commit[..50]), Err(Error::Malformed));
}
#[test]
fn an_rsnxe_with_sae_h2e_picks_hash_to_element() {
assert_eq!(
Derivation::for_rsnxe(Some(&H2E_RSNXE[2..])),
Derivation::HashToElement
);
assert_eq!(
Derivation::for_rsnxe(Some(&[0x01])),
Derivation::HuntingAndPecking
);
assert_eq!(Derivation::for_rsnxe(None), Derivation::HuntingAndPecking);
}
#[test]
fn an_anti_clogging_token_goes_after_the_group_or_in_its_container() {
let (mut station, _) = pair(Derivation::HuntingAndPecking);
let retry = station
.receive(1, 76, &[19, 0, 0xaa, 0xbb])
.unwrap()
.unwrap();
assert_eq!((retry.transaction, retry.status), (1, 0));
assert_eq!(retry.data[..4], [19, 0, 0xaa, 0xbb]);
assert_eq!(retry.data.len(), 4 + 96);
let template = Template::derive(b"byteme", PASSWORD, Some(b"id"));
let mut station = Exchange::new(
Derivation::HashToElement,
PASSWORD,
Some(&template),
Some(b"id"),
OWN,
PEER,
&mut counter(),
)
.unwrap();
assert_eq!(
station.receive(1, 76, &[19, 0, 0xaa]),
Err(Error::Malformed)
);
let retry = station
.receive(1, 76, &[19, 0, 255, 3, 93, 0xaa, 0xbb])
.unwrap()
.unwrap();
assert_eq!(retry.status, STATUS_HASH_TO_ELEMENT);
assert_eq!(retry.data[..2], [19, 0]);
assert_eq!(
retry.data[98..],
[255, 3, 33, b'i', b'd', 255, 3, 93, 0xaa, 0xbb]
);
}
@@ -3,8 +3,9 @@
//! WPA2-Personal key management for one station: the PSK from a passphrase
//! (IEEE 802.11-2020 J.4.1), the pairwise key hierarchy (12.7.1) and the
//! supplicant side of the EAPOL-Key 4-way and group key handshakes (12.7.6,
//! 12.7.7) for AKM 00-0F-AC:2 (PSK, HMAC-SHA1 MIC) and 00-0F-AC:6
//! (PSK-SHA256, AES-128-CMAC MIC), in the order wpa_supplicant's
//! 12.7.7) for AKM 00-0F-AC:2 (PSK, HMAC-SHA1 MIC), 00-0F-AC:6
//! (PSK-SHA256, AES-128-CMAC MIC) and 00-0F-AC:8 (SAE, whose PMK
//! [`sae`](super::sae) derives; AES-128-CMAC MIC), in the order wpa_supplicant's
//! `wpa_sm_rx_eapol` checks them. The suites come from the association's
//! [`pmf::Selection`] or its RSN key ciphers; the keys it yields are the
//! arguments of [`KeySlot::begin_install`] and the IGTK's of
@@ -68,6 +69,9 @@ pub enum Akm {
Psk,
/// 00-0F-AC:6, key descriptor version 3.
PskSha256,
/// 00-0F-AC:8, key descriptor version 0: the AKM defines the SHA-256
/// KDF and AES-128-CMAC MIC.
Sae,
}
impl Akm {
@@ -77,6 +81,7 @@ impl Akm {
match suite {
2 => Some(Self::Psk),
6 => Some(Self::PskSha256),
8 => Some(Self::Sae),
_ => None,
}
}
@@ -84,6 +89,7 @@ impl Akm {
match self {
Self::Psk => 2,
Self::PskSha256 => 3,
Self::Sae => 0,
}
}
}
@@ -115,7 +121,7 @@ impl Suites {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Error {
/// An AKM or cipher this supplicant does not derive keys for: AKMs
/// other than 2 and 6, a TKIP or WEP pairwise cipher, a WEP group.
/// other than 2, 6 and 8, a TKIP or WEP pairwise cipher, a WEP group.
Unsupported,
/// Not an EAPOL-Key frame with the RSN descriptor.
NotKey,
@@ -150,7 +156,7 @@ fn hmac_sha1(key: &[u8], parts: &[&[u8]]) -> [u8; 20] {
mac.finalize().into_bytes().into()
}
fn hmac_sha256(key: &[u8], parts: &[&[u8]]) -> [u8; 32] {
pub(super) fn hmac_sha256(key: &[u8], parts: &[&[u8]]) -> [u8; 32] {
let mut mac =
<Hmac<Sha256> as KeyInit>::new_from_slice(key).expect("HMAC takes any key length");
for part in parts {
@@ -191,7 +197,12 @@ fn prf_sha1(key: &[u8], label: &[u8], data: &[u8], bytes: usize) -> Zeroizing<Ve
}
/// The SHA-256 KDF (12.7.1.7.2): `bytes` of output.
fn kdf_sha256(key: &[u8], label: &[u8], context: &[u8], bytes: usize) -> Zeroizing<Vec<u8>> {
pub(super) fn kdf_sha256(
key: &[u8],
label: &[u8],
context: &[u8],
bytes: usize,
) -> Zeroizing<Vec<u8>> {
let mut out = Zeroizing::new(Vec::with_capacity(bytes + 32));
let length = ((bytes * 8) as u16).to_le_bytes();
let mut counter = 1u16;
@@ -331,7 +342,7 @@ impl Ptk {
let label = b"Pairwise key expansion";
Self(match suites.akm {
Akm::Psk => prf_sha1(pmk, label, &data, bytes),
Akm::PskSha256 => kdf_sha256(pmk, label, &data, bytes),
Akm::PskSha256 | Akm::Sae => kdf_sha256(pmk, label, &data, bytes),
})
}
fn kck(&self) -> &[u8; 16] {
@@ -349,7 +360,7 @@ impl Ptk {
fn mic(akm: Akm, kck: &[u8; 16], frame: &[u8]) -> [u8; 16] {
match akm {
Akm::Psk => hmac_sha1(kck, &[frame])[..16].try_into().unwrap(),
Akm::PskSha256 => cmac(kck, frame),
Akm::PskSha256 | Akm::Sae => cmac(kck, frame),
}
}
@@ -217,7 +217,7 @@ fn random() -> [u8; 32] {
#[test]
fn four_way_and_group_handshakes_install_the_authenticators_keys() {
for akm in [Akm::Psk, Akm::PskSha256] {
for akm in [Akm::Psk, Akm::PskSha256, Akm::Sae] {
let (mut ap, mut station) = begun(suites(akm));
assert!(!station.established());
let step = station.receive(&ap.message_3(&RSN), &mut random).unwrap();