TExcelTAD
Home › Wireless, IoT & Mobile Security › Computing PMK, PTK and MIC in Python

Computing PMK, PTK and MIC in Python

The 4-way handshake is easier to trust, and to audit, once you have computed it yourself. This lesson derives every key of WPA2-Personal from a passphrase, checks the implementation against the test vectors published with the standard, and then plays both sides of message M2: the client computes its MIC, the access point verifies it. Everything runs in your browser with the cryptography package's PBKDF2 and Python's hmac, the building blocks from HMAC and KDFs versus Password Hashes.

The chain

Three functions turn a passphrase into the keys that protect traffic:

PMK=PBKDF2(HMAC-SHA1, passphrase, SSID, 4096, 256 bits)PTK=PRF-384(PMK, "Pairwise key expansion", min⁡(AA,SPA)∥max⁡(AA,SPA)∥min⁡(AN,SN)∥max⁡(AN,SN))MIC=first 128 bits of HMAC-SHA1(KCK, EAPOL frame with a zero MIC field)\begin{aligned} \text{PMK} &= \text{PBKDF2}(\text{HMAC-SHA1},\ \text{passphrase},\ \text{SSID},\ 4096,\ 256\ \text{bits}) \\ \text{PTK} &= \text{PRF-384}(\text{PMK},\ \text{"Pairwise key expansion"},\ \min(AA, SPA) \Vert \max(AA, SPA) \Vert \min(AN, SN) \Vert \max(AN, SN)) \\ \text{MIC} &= \text{first 128 bits of HMAC-SHA1}(\text{KCK},\ \text{EAPOL frame with a zero MIC field}) \end{aligned}
  • The passphrase has 8 to 63 printable ASCII characters; alternatively a 64-hex-digit PSK is used directly as the PMK.
  • The SSID is the salt. That is why the PMK is the same for every network called LabNet with the same passphrase, and why precomputed tables exist for common SSIDs such as default router names.
  • AAAA and SPASPA are the MAC addresses of the access point and the client, ANAN and SNSN the two nonces, and ∥\Vert means concatenation. The min/max ordering makes both sides build the same input.
  • The 384-bit PTK (for CCMP) splits into the KCK (bits 0 to 127), the KEK (128 to 255) and the TK (256 to 383).

The PRF of IEEE 802.11 is HMAC-SHA1 in a counter loop. With Hi=HMAC-SHA1(K, A∥0x00∥B∥i)H_i = \text{HMAC-SHA1}(K,\ A \Vert \texttt{0x00} \Vert B \Vert i),

PRF-n(K,A,B)=the first n bits of H0∥H1∥H2∥⋯\text{PRF-}n(K, A, B) = \text{the first } n \text{ bits of } H_0 \Vert H_1 \Vert H_2 \Vert \cdots

For PRF-384 that is three HMAC-SHA1 outputs of 160 bits each (480 bits), cut to 384.

Step 1: check against the standard's test vectors

The 802.11i amendment published test vectors for the PSK mapping (passphrase and SSID to PMK) and for the PRF. An implementation that doesn't reproduce them is wrong, whatever else it does.

python · try it yourself
import hmac, hashlib
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC

def pmk(passphrase, ssid):            # IEEE 802.11 PSK mapping: PBKDF2-HMAC-SHA1, 4096 iterations, 256 bits
    return PBKDF2HMAC(algorithm=hashes.SHA1(), length=32, salt=ssid, iterations=4096).derive(passphrase)

def prf(key, label, data, bits):      # IEEE 802.11 PRF-n: HMAC-SHA1(K, A || 0x00 || B || i), i = 0, 1, ...
    out, i = b"", 0
    while len(out) * 8 < bits:
        out += hmac.new(key, label + b"\x00" + data + bytes([i]), hashlib.sha1).digest()
        i += 1
    return out[:bits // 8]

# Published test vectors (IEEE 802.11i-2004 Annex H, now an annex of IEEE 802.11)
vectors = [(b"password", b"IEEE", "f42c6fc52df0ebef9ebb4b90b38a5f902e83fe1b135a70e23aed762e9710a12e"),
           (b"ThisIsAPassword", b"ThisIsASSID", "0dc0d6eb90555ed6419756b9a15ec3e3209b63df707dd508d14581f8982721af"),
           (b"a" * 32, b"Z" * 32, "becb93866bb8c3832cb777c2f559807c8c59afcb6eae734885001300a981cc62")]
for pw, ssid, expected in vectors:
    got = pmk(pw, ssid).hex()
    print(f"PMK({pw.decode()[:15]:15}, {ssid.decode()[:11]:11}) = {got[:16]}...  matches: {got == expected}")
got = prf(b"\x0b" * 20, b"prefix", b"Hi There", 192).hex()
print("PRF-192 test vector matches:", got == "bcd4c650b30b9684951829e0d75f9d54b862175ed9f00606")
PMK(password       , IEEE       ) = f42c6fc52df0ebef...  matches: True
PMK(ThisIsAPassword, ThisIsASSID) = 0dc0d6eb90555ed6...  matches: True
PMK(aaaaaaaaaaaaaaa, ZZZZZZZZZZZ) = becb93866bb8c383...  matches: True
PRF-192 test vector matches: True

Pyodide has no hashlib.pbkdf2_hmac, so the example uses PBKDF2HMAC from cryptography; on a normal CPython both give the same bytes.

Step 2: the handshake keys and the MIC of M2

Now a full M2 on the lab network. The passphrase, the MAC addresses and the nonces are fixed so the output is stable; in a real handshake the nonces are fresh 32-byte values from a cryptographically secure generator. The client derives the PTK, builds M2 with a zero MIC field, computes the MIC with its KCK and writes it into the frame. The access point, which holds the same PMK, recomputes the MIC and compares in constant time.

python · try it yourself
import hmac, hashlib, struct
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC

def pmk(passphrase, ssid):
    return PBKDF2HMAC(algorithm=hashes.SHA1(), length=32, salt=ssid, iterations=4096).derive(passphrase)
def prf(key, label, data, bits):
    out, i = b"", 0
    while len(out) * 8 < bits:
        out += hmac.new(key, label + b"\x00" + data + bytes([i]), hashlib.sha1).digest()
        i += 1
    return out[:bits // 8]
def eapol_key(key_info, replay, nonce, mic=bytes(16), key_data=b""):
    body = struct.pack(">BHH", 2, key_info, 16) + struct.pack(">Q", replay) + nonce
    body += bytes(32) + mic + struct.pack(">H", len(key_data)) + key_data
    return struct.pack(">BBH", 2, 3, len(body)) + body
MIC_AT = slice(81, 97)                                     # where the 16-byte MIC sits in the frame

# The lab network: fixed inputs so the output is stable (real nonces are fresh CSPRNG values)
AA, SPA = bytes.fromhex("020000000a01"), bytes.fromhex("020000000a05")   # AP and client MACs
ANONCE = hashlib.sha256(b"lab ANonce").digest()
SNONCE = hashlib.sha256(b"lab SNonce").digest()
PMK = pmk(b"correct horse lab staple", b"LabNet")

# Client: derive the PTK and send M2 with a MIC over the whole frame (MIC field zero while computing)
data = min(AA, SPA) + max(AA, SPA) + min(ANONCE, SNONCE) + max(ANONCE, SNONCE)
ptk = prf(PMK, b"Pairwise key expansion", data, 384)
kck, kek, tk = ptk[:16], ptk[16:32], ptk[32:]
print("PMK ", PMK.hex())
print("KCK ", kck.hex(), "| KEK", kek.hex(), "| TK", tk.hex())
m2 = eapol_key(0x010a, 1, SNONCE, key_data=bytes.fromhex("30140100000fac040100000fac040100000fac020000"))
mic = hmac.new(kck, m2, hashlib.sha1).digest()[:16]       # descriptor version 2: HMAC-SHA1, first 128 bits
m2 = m2[:MIC_AT.start] + mic + m2[MIC_AT.stop:]
print("M2 MIC", mic.hex())

# AP: it knows the PMK too; it derives the same PTK and checks the MIC
def ap_check(frame, pmk_ap):
    k = prf(pmk_ap, b"Pairwise key expansion", data, 384)[:16]
    zeroed = frame[:MIC_AT.start] + bytes(16) + frame[MIC_AT.stop:]
    return hmac.compare_digest(hmac.new(k, zeroed, hashlib.sha1).digest()[:16], frame[MIC_AT])
print("AP with the right PMK accepts M2:", ap_check(m2, PMK))
print("AP configured with another passphrase:", ap_check(m2, pmk(b"correct horse lab stapler", b"LabNet")))
PMK  8645fb2441df1bd7775a3790a7c19d6ab54970b3a28b61975cd2704f619ce56c
KCK  2b2c03785148a8a2802db2eab4f33394 | KEK 13e52206065b3a4514fbf663c2867c67 | TK a94472bf31a98b7444b3df754f11cc2d
M2 MIC 8c6c03a6a3167719244c9ff09a83bdf8
AP with the right PMK accepts M2: True
AP configured with another passphrase: False

Changing one character of the passphrase changes the PMK completely, so the AP's KCK differs and the MIC check fails. This is the whole authentication of WPA2-Personal: the MIC proves that the sender knows the PMK.

What follows from the computation

The MIC check is also an offline test. Every input to the check except the PMK is in the clear in M1 and M2: the SSID, both MACs, both nonces, the frame and its MIC. Whoever records M1 and M2 can run the same function with guessed passphrases on their own hardware, and the AP never sees an attempt. The cost per guess is fixed by the design: PBKDF2 needs two 160-bit HMAC-SHA1 blocks to make 256 bits, each with 4,096 iterations, so

2×4096=8192 HMAC-SHA1 operations per guessed passphrase2 \times 4096 = 8192 \ \text{HMAC-SHA1 operations per guessed passphrase}

plus a few more for the PRF and the MIC. That is slow compared with one hash and fast compared with a modern password hash (compare Password Hashing). The next lesson works out what it means for passphrase strength.

The PMKID. Access points that cache PMKs for fast roaming may put a PMKID in M1:

PMKID=first 128 bits of HMAC-SHA1(PMK, "PMK Name"∥AA∥SPA)\text{PMKID} = \text{first 128 bits of HMAC-SHA1}(\text{PMK},\ \text{"PMK Name"} \Vert AA \Vert SPA)

Published in 2018 as a way to get a guess-testing value from the access point alone, without waiting for a client to connect, it makes the same offline test possible with less effort. The defence is the same: a strong passphrase, or SAE.

Same SSID, same PMK. Because the SSID is the salt, two networks with the same name and passphrase share a PMK. A unique SSID (not the router's default name) stops precomputed tables from helping.

How weak configurations are detected

  • Configuration review: PSK networks with short or dictionary passphrases, default SSIDs, PSKs reused across sites, passphrases printed on stickers or shared in chat.
  • Passphrase checks in your own tooling: test the configured passphrase against length rules and breached-password lists in the configuration pipeline, before deployment, instead of attacking captures.
  • Beacon audit: AKM 2 (PSK) without AKM 8 (SAE) means the network has no protection against offline guessing.

How it is fixed

  • Prefer WPA3-SAE (no offline test) or Enterprise (per-user credentials).
  • Where WPA2-PSK must stay: a generated passphrase of 20 or more random characters (or a long Diceware phrase), a non-default SSID, PMF enabled, and a rotation plan for when people leave.
  • Per-device PSKs (offered by many enterprise controllers under names such as "private PSK") limit the damage of one leaked passphrase.

Pitfalls

  • Computing the PMK with SHA-256 or forgetting the 4,096 iterations: the test vectors catch both.
  • Comparing MICs with == in your own tools instead of hmac.compare_digest.
  • Forgetting the min/max ordering, which makes the two sides derive different PTKs.

Practice

1. Which line of the first output is the PMK for passphrase password and SSID IEEE, and why is it the same on every network with that SSID and passphrase?

The first line, f42c6fc5.... The PMK depends only on the passphrase and the SSID (the salt), not on the access point or the client.

2. In the second program, swap the AP and client MAC addresses. Does the PTK change? Why?

No. The PRF input uses min⁡(AA,SPA)\min(AA, SPA) and max⁡(AA,SPA)\max(AA, SPA), so the order of the two addresses doesn't matter; the same holds for the nonces.

3. How many HMAC-SHA1 operations does PRF-384 need, and why is that negligible compared with the PMK?

Three (480 bits of output cut to 384). The PMK needs about 8,192, so the PBKDF2 step dominates the cost of each guess.

Test yourself

What acts as the salt in the WPA2 PSK mapping?

  1. The BSSID
  2. The SSID
  3. The ANonce
  4. A fresh 16-byte value

Which part of the PTK keys the MIC in EAPOL-Key frames?

  1. TK
  2. KEK
  3. KCK
  4. GTK

Why does a recorded M1 + M2 allow testing passphrase guesses offline?

  1. The passphrase is sent in M2
  2. All MIC inputs except the PMK are in the clear, so a guess can be checked by recomputing the MIC
  3. The PMK is sent in M1
  4. The AP answers every guess

About how many HMAC-SHA1 operations does one WPA2 PMK computation take?

  1. 1
  2. 4,096
  3. 8,192
  4. 600,000