1# WPA2-Personal tests
2# Copyright (c) 2014, Qualcomm Atheros, Inc.
3#
4# This software may be distributed under the terms of the BSD license.
5# See README for more details.
6
7from remotehost import remote_compatible
8import binascii
9from Crypto.Cipher import AES
10import hashlib
11import hmac
12import logging
13logger = logging.getLogger()
14import os
15import re
16import socket
17import struct
18import subprocess
19import time
20
21import hostapd
22from utils import *
23import hwsim_utils
24from wpasupplicant import WpaSupplicant
25from tshark import run_tshark
26from wlantest import WlantestCapture, Wlantest
27
28def check_mib(dev, vals):
29    mib = dev.get_mib()
30    for v in vals:
31        if mib[v[0]] != v[1]:
32            raise Exception("Unexpected {} = {} (expected {})".format(v[0], mib[v[0]], v[1]))
33
34@remote_compatible
35def test_ap_wpa2_psk(dev, apdev):
36    """WPA2-PSK AP with PSK instead of passphrase"""
37    ssid = "test-wpa2-psk"
38    passphrase = 'qwertyuiop'
39    psk = '602e323e077bc63bd80307ef4745b754b0ae0a925c2638ecd13a794b9527b9e6'
40    params = hostapd.wpa2_params(ssid=ssid)
41    params['wpa_psk'] = psk
42    hapd = hostapd.add_ap(apdev[0], params)
43    key_mgmt = hapd.get_config()['key_mgmt']
44    if key_mgmt.split(' ')[0] != "WPA-PSK":
45        raise Exception("Unexpected GET_CONFIG(key_mgmt): " + key_mgmt)
46    dev[0].connect(ssid, raw_psk=psk, scan_freq="2412")
47    dev[1].connect(ssid, psk=passphrase, scan_freq="2412")
48
49    sig = dev[0].request("SIGNAL_POLL").splitlines()
50    pkt = dev[0].request("PKTCNT_POLL").splitlines()
51    if "FREQUENCY=2412" not in sig:
52        raise Exception("Unexpected SIGNAL_POLL value: " + str(sig))
53    if "TXBAD=0" not in pkt:
54        raise Exception("Unexpected TXBAD value: " + str(pkt))
55
56def test_ap_wpa2_psk_file(dev, apdev):
57    """WPA2-PSK AP with PSK from a file"""
58    ssid = "test-wpa2-psk"
59    passphrase = 'qwertyuiop'
60    psk = '602e323e077bc63bd80307ef4745b754b0ae0a925c2638ecd13a794b9527b9e6'
61    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
62    params['wpa_psk_file'] = 'hostapd.wpa_psk'
63    hostapd.add_ap(apdev[0], params)
64    dev[1].connect(ssid, psk="very secret", scan_freq="2412", wait_connect=False)
65    dev[2].connect(ssid, raw_psk=psk, scan_freq="2412")
66    dev[2].request("REMOVE_NETWORK all")
67    dev[0].connect(ssid, psk="very secret", scan_freq="2412")
68    dev[0].request("REMOVE_NETWORK all")
69    dev[2].connect(ssid, psk="another passphrase for all STAs", scan_freq="2412")
70    dev[0].connect(ssid, psk="another passphrase for all STAs", scan_freq="2412")
71    ev = dev[1].wait_event(["WPA: 4-Way Handshake failed"], timeout=10)
72    if ev is None:
73        raise Exception("Timed out while waiting for failure report")
74    dev[1].request("REMOVE_NETWORK all")
75
76def check_no_keyid(hapd, dev):
77    addr = dev.own_addr()
78    ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=1)
79    if ev is None:
80        raise Exception("No AP-STA-CONNECTED indicated")
81    if addr not in ev:
82        raise Exception("AP-STA-CONNECTED for unexpected STA")
83    if "keyid=" in ev:
84        raise Exception("Unexpected keyid indication")
85
86def check_keyid(hapd, dev, keyid):
87    addr = dev.own_addr()
88    ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=1)
89    if ev is None:
90        raise Exception("No AP-STA-CONNECTED indicated")
91    if addr not in ev:
92        raise Exception("AP-STA-CONNECTED for unexpected STA")
93    if "keyid=" + keyid not in ev:
94        raise Exception("Incorrect keyid indication")
95    sta = hapd.get_sta(addr)
96    if 'keyid' not in sta or sta['keyid'] != keyid:
97        raise Exception("Incorrect keyid in STA output")
98    dev.request("REMOVE_NETWORK all")
99
100def check_disconnect(dev, expected):
101    for i in range(2):
102        if expected[i]:
103            dev[i].wait_disconnected()
104            dev[i].request("REMOVE_NETWORK all")
105        else:
106            ev = dev[i].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=0.1)
107            if ev is not None:
108                raise Exception("Unexpected disconnection")
109            dev[i].request("REMOVE_NETWORK all")
110            dev[i].wait_disconnected()
111
112def test_ap_wpa2_psk_file_keyid(dev, apdev, params):
113    """WPA2-PSK AP with PSK from a file (keyid and reload)"""
114    psk_file = os.path.join(params['logdir'], 'ap_wpa2_psk_file_keyid.wpa_psk')
115    with open(psk_file, 'w') as f:
116        f.write('00:00:00:00:00:00 secret passphrase\n')
117        f.write('02:00:00:00:00:00 very secret\n')
118        f.write('00:00:00:00:00:00 another passphrase for all STAs\n')
119    ssid = "test-wpa2-psk"
120    params = hostapd.wpa2_params(ssid=ssid, passphrase='qwertyuiop')
121    params['wpa_psk_file'] = psk_file
122    hapd = hostapd.add_ap(apdev[0], params)
123
124    dev[0].connect(ssid, psk="very secret", scan_freq="2412")
125    check_no_keyid(hapd, dev[0])
126
127    dev[1].connect(ssid, psk="another passphrase for all STAs",
128                   scan_freq="2412")
129    check_no_keyid(hapd, dev[1])
130
131    dev[2].connect(ssid, psk="qwertyuiop", scan_freq="2412")
132    check_no_keyid(hapd, dev[2])
133
134    with open(psk_file, 'w') as f:
135        f.write('00:00:00:00:00:00 secret passphrase\n')
136        f.write('02:00:00:00:00:00 very secret\n')
137        f.write('00:00:00:00:00:00 changed passphrase\n')
138    if "OK" not in hapd.request("RELOAD_WPA_PSK"):
139        raise Exception("RELOAD_WPA_PSK failed")
140
141    check_disconnect(dev, [False, True, False])
142
143    with open(psk_file, 'w') as f:
144        f.write('00:00:00:00:00:00 secret passphrase\n')
145        f.write('keyid=foo 02:00:00:00:00:00 very secret\n')
146        f.write('keyid=bar 00:00:00:00:00:00 another passphrase for all STAs\n')
147    if "OK" not in hapd.request("RELOAD_WPA_PSK"):
148        raise Exception("RELOAD_WPA_PSK failed")
149
150    dev[0].connect(ssid, psk="very secret", scan_freq="2412")
151    check_keyid(hapd, dev[0], "foo")
152
153    dev[1].connect(ssid, psk="another passphrase for all STAs",
154                   scan_freq="2412")
155    check_keyid(hapd, dev[1], "bar")
156
157    dev[2].connect(ssid, psk="qwertyuiop", scan_freq="2412")
158    check_no_keyid(hapd, dev[2])
159
160    dev[0].wait_disconnected()
161    dev[0].connect(ssid, psk="secret passphrase", scan_freq="2412")
162    check_no_keyid(hapd, dev[0])
163
164    with open(psk_file, 'w') as f:
165        f.write('# empty\n')
166    if "OK" not in hapd.request("RELOAD_WPA_PSK"):
167        raise Exception("RELOAD_WPA_PSK failed")
168
169    check_disconnect(dev, [True, True, False])
170
171    with open(psk_file, 'w') as f:
172        f.write('broken\n')
173    if "FAIL" not in hapd.request("RELOAD_WPA_PSK"):
174        raise Exception("RELOAD_WPA_PSK succeeded with invalid file")
175
176@remote_compatible
177def test_ap_wpa2_psk_mem(dev, apdev):
178    """WPA2-PSK AP with passphrase only in memory"""
179    try:
180        _test_ap_wpa2_psk_mem(dev, apdev)
181    finally:
182        dev[0].request("SCAN_INTERVAL 5")
183        dev[1].request("SCAN_INTERVAL 5")
184
185def _test_ap_wpa2_psk_mem(dev, apdev):
186    ssid = "test-wpa2-psk"
187    passphrase = 'qwertyuiop'
188    psk = '602e323e077bc63bd80307ef4745b754b0ae0a925c2638ecd13a794b9527b9e6'
189    params = hostapd.wpa2_params(ssid=ssid)
190    params['wpa_psk'] = psk
191    hapd = hostapd.add_ap(apdev[0], params)
192
193    dev[0].connect(ssid, mem_only_psk="1", scan_freq="2412", wait_connect=False)
194    dev[0].request("SCAN_INTERVAL 1")
195    ev = dev[0].wait_event(["CTRL-REQ-PSK_PASSPHRASE"], timeout=10)
196    if ev is None:
197        raise Exception("Request for PSK/passphrase timed out")
198    id = ev.split(':')[0].split('-')[-1]
199    dev[0].request("CTRL-RSP-PSK_PASSPHRASE-" + id + ':"' + passphrase + '"')
200    dev[0].wait_connected(timeout=10)
201
202    dev[1].connect(ssid, mem_only_psk="1", scan_freq="2412", wait_connect=False)
203    dev[1].request("SCAN_INTERVAL 1")
204    ev = dev[1].wait_event(["CTRL-REQ-PSK_PASSPHRASE"], timeout=10)
205    if ev is None:
206        raise Exception("Request for PSK/passphrase timed out(2)")
207    id = ev.split(':')[0].split('-')[-1]
208    dev[1].request("CTRL-RSP-PSK_PASSPHRASE-" + id + ':' + psk)
209    dev[1].wait_connected(timeout=10)
210
211@remote_compatible
212def test_ap_wpa2_ptk_rekey(dev, apdev):
213    """WPA2-PSK AP and PTK rekey enforced by station"""
214    ssid = "test-wpa2-psk"
215    passphrase = 'qwertyuiop'
216    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
217    hapd = hostapd.add_ap(apdev[0], params)
218
219    Wlantest.setup(hapd)
220    wt = Wlantest()
221    wt.flush()
222    wt.add_passphrase(passphrase)
223
224    dev[0].connect(ssid, psk=passphrase, wpa_ptk_rekey="1", scan_freq="2412")
225    ev = dev[0].wait_event(["WPA: Key negotiation completed",
226                            "CTRL-EVENT-DISCONNECTED"])
227    if ev is None:
228        raise Exception("PTK rekey timed out")
229    if "CTRL-EVENT-DISCONNECTED" in ev:
230       raise Exception("Disconnect instead of rekey")
231    hwsim_utils.test_connectivity(dev[0], hapd)
232
233def test_ap_wpa2_ptk_rekey_blocked_ap(dev, apdev):
234    """WPA2-PSK AP and PTK rekey enforced by station and AP blocking it"""
235    ssid = "test-wpa2-psk"
236    passphrase = 'qwertyuiop'
237    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
238    params['wpa_deny_ptk0_rekey'] = "2"
239    hapd = hostapd.add_ap(apdev[0], params)
240    conf = hapd.request("GET_CONFIG").splitlines()
241    if "wpa_deny_ptk0_rekey=2" not in conf:
242        raise Exception("wpa_deny_ptk0_rekey value not in GET_CONFIG")
243    dev[0].connect(ssid, psk=passphrase, wpa_ptk_rekey="1", scan_freq="2412")
244    ev = dev[0].wait_event(["WPA: Key negotiation completed",
245                            "CTRL-EVENT-DISCONNECTED"])
246    if ev is None:
247        raise Exception("PTK rekey timed out")
248    if "WPA: Key negotiation completed" in ev:
249        raise Exception("No disconnect, PTK rekey succeeded")
250    ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=1)
251    if ev is None:
252        raise Exception("Reconnect too slow")
253
254def test_ap_wpa2_ptk_rekey_blocked_sta(dev, apdev):
255    """WPA2-PSK AP and PTK rekey enforced by station while also blocking it"""
256    ssid = "test-wpa2-psk"
257    passphrase = 'qwertyuiop'
258    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
259    hapd = hostapd.add_ap(apdev[0], params)
260    dev[0].connect(ssid, psk=passphrase, wpa_ptk_rekey="1", scan_freq="2412",
261                   wpa_deny_ptk0_rekey="2")
262    ev = dev[0].wait_event(["WPA: Key negotiation completed",
263                            "CTRL-EVENT-DISCONNECTED"])
264    if ev is None:
265        raise Exception("PTK rekey timed out")
266    if "WPA: Key negotiation completed" in ev:
267        raise Exception("No disconnect, PTK rekey succeeded")
268    ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=1)
269    if ev is None:
270        raise Exception("Reconnect too slow")
271
272def test_ap_wpa2_ptk_rekey_anonce(dev, apdev):
273    """WPA2-PSK AP and PTK rekey enforced by station and ANonce change"""
274    ssid = "test-wpa2-psk"
275    passphrase = 'qwertyuiop'
276    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
277    hapd = hostapd.add_ap(apdev[0], params)
278    dev[0].connect(ssid, psk=passphrase, wpa_ptk_rekey="1", scan_freq="2412")
279    dev[0].dump_monitor()
280    anonce1 = dev[0].request("GET anonce")
281    if "OK" not in dev[0].request("KEY_REQUEST 0 1"):
282        raise Exception("KEY_REQUEST failed")
283    ev = dev[0].wait_event(["WPA: Key negotiation completed"])
284    if ev is None:
285        raise Exception("PTK rekey timed out")
286    anonce2 = dev[0].request("GET anonce")
287    if anonce1 == anonce2:
288        raise Exception("AP did not update ANonce in requested PTK rekeying")
289    hwsim_utils.test_connectivity(dev[0], hapd)
290
291@remote_compatible
292def test_ap_wpa2_ptk_rekey_ap(dev, apdev):
293    """WPA2-PSK AP and PTK rekey enforced by AP"""
294    ssid = "test-wpa2-psk"
295    passphrase = 'qwertyuiop'
296    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
297    params['wpa_ptk_rekey'] = '2'
298    hapd = hostapd.add_ap(apdev[0], params)
299    dev[0].connect(ssid, psk=passphrase, scan_freq="2412")
300    ev = dev[0].wait_event(["WPA: Key negotiation completed"])
301    if ev is None:
302        raise Exception("PTK rekey timed out")
303    hwsim_utils.test_connectivity(dev[0], hapd)
304
305@remote_compatible
306def test_ap_wpa2_sha256_ptk_rekey(dev, apdev):
307    """WPA2-PSK/SHA256 AKM AP and PTK rekey enforced by station"""
308    ssid = "test-wpa2-psk"
309    passphrase = 'qwertyuiop'
310    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
311    params["wpa_key_mgmt"] = "WPA-PSK-SHA256"
312    hapd = hostapd.add_ap(apdev[0], params)
313    dev[0].connect(ssid, psk=passphrase, key_mgmt="WPA-PSK-SHA256",
314                   wpa_ptk_rekey="1", scan_freq="2412")
315    ev = dev[0].wait_event(["WPA: Key negotiation completed"])
316    if ev is None:
317        raise Exception("PTK rekey timed out")
318    hwsim_utils.test_connectivity(dev[0], hapd)
319    check_mib(dev[0], [("dot11RSNAAuthenticationSuiteRequested", "00-0f-ac-6"),
320                       ("dot11RSNAAuthenticationSuiteSelected", "00-0f-ac-6")])
321
322@remote_compatible
323def test_ap_wpa2_sha256_ptk_rekey_ap(dev, apdev):
324    """WPA2-PSK/SHA256 AKM AP and PTK rekey enforced by AP"""
325    ssid = "test-wpa2-psk"
326    passphrase = 'qwertyuiop'
327    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
328    params["wpa_key_mgmt"] = "WPA-PSK-SHA256"
329    params['wpa_ptk_rekey'] = '2'
330    hapd = hostapd.add_ap(apdev[0], params)
331    dev[0].connect(ssid, psk=passphrase, key_mgmt="WPA-PSK-SHA256",
332                   scan_freq="2412")
333    ev = dev[0].wait_event(["WPA: Key negotiation completed"])
334    if ev is None:
335        raise Exception("PTK rekey timed out")
336    hwsim_utils.test_connectivity(dev[0], hapd)
337    check_mib(dev[0], [("dot11RSNAAuthenticationSuiteRequested", "00-0f-ac-6"),
338                       ("dot11RSNAAuthenticationSuiteSelected", "00-0f-ac-6")])
339
340@remote_compatible
341def test_ap_wpa_ptk_rekey(dev, apdev):
342    """WPA-PSK/TKIP AP and PTK rekey enforced by station"""
343    skip_with_fips(dev[0])
344    skip_without_tkip(dev[0])
345    ssid = "test-wpa-psk"
346    passphrase = 'qwertyuiop'
347    params = hostapd.wpa_params(ssid=ssid, passphrase=passphrase)
348    hapd = hostapd.add_ap(apdev[0], params)
349    dev[0].connect(ssid, psk=passphrase, wpa_ptk_rekey="1", scan_freq="2412")
350    if "[WPA-PSK-TKIP]" not in dev[0].request("SCAN_RESULTS"):
351        raise Exception("Scan results missing WPA element info")
352    ev = dev[0].wait_event(["WPA: Key negotiation completed"])
353    if ev is None:
354        raise Exception("PTK rekey timed out")
355    hwsim_utils.test_connectivity(dev[0], hapd)
356
357@remote_compatible
358def test_ap_wpa_ptk_rekey_ap(dev, apdev):
359    """WPA-PSK/TKIP AP and PTK rekey enforced by AP"""
360    skip_with_fips(dev[0])
361    skip_without_tkip(dev[0])
362    ssid = "test-wpa-psk"
363    passphrase = 'qwertyuiop'
364    params = hostapd.wpa_params(ssid=ssid, passphrase=passphrase)
365    params['wpa_ptk_rekey'] = '2'
366    hapd = hostapd.add_ap(apdev[0], params)
367    dev[0].connect(ssid, psk=passphrase, scan_freq="2412")
368    ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
369    if ev is None:
370        raise Exception("PTK rekey timed out")
371    hwsim_utils.test_connectivity(dev[0], hapd)
372
373@remote_compatible
374def test_ap_wpa_ccmp(dev, apdev):
375    """WPA-PSK/CCMP"""
376    ssid = "test-wpa-psk"
377    passphrase = 'qwertyuiop'
378    params = hostapd.wpa_params(ssid=ssid, passphrase=passphrase)
379    params['wpa_pairwise'] = "CCMP"
380    hapd = hostapd.add_ap(apdev[0], params)
381    dev[0].connect(ssid, psk=passphrase, scan_freq="2412")
382    hapd.wait_sta()
383    hwsim_utils.test_connectivity(dev[0], hapd)
384    check_mib(dev[0], [("dot11RSNAConfigGroupCipherSize", "128"),
385                       ("dot11RSNAGroupCipherRequested", "00-50-f2-4"),
386                       ("dot11RSNAPairwiseCipherRequested", "00-50-f2-4"),
387                       ("dot11RSNAAuthenticationSuiteRequested", "00-50-f2-2"),
388                       ("dot11RSNAGroupCipherSelected", "00-50-f2-4"),
389                       ("dot11RSNAPairwiseCipherSelected", "00-50-f2-4"),
390                       ("dot11RSNAAuthenticationSuiteSelected", "00-50-f2-2"),
391                       ("dot1xSuppSuppControlledPortStatus", "Authorized")])
392
393def test_ap_wpa2_psk_file_errors(dev, apdev):
394    """WPA2-PSK AP with various PSK file error and success cases"""
395    addr0 = dev[0].own_addr()
396    addr1 = dev[1].own_addr()
397    addr2 = dev[2].own_addr()
398    ssid = "psk"
399    pskfile = "/tmp/ap_wpa2_psk_file_errors.psk_file"
400    try:
401        os.remove(pskfile)
402    except:
403        pass
404
405    params = {"ssid": ssid, "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
406              "rsn_pairwise": "CCMP", "wpa_psk_file": pskfile}
407
408    try:
409        # missing PSK file
410        hapd = hostapd.add_ap(apdev[0], params, no_enable=True)
411        if "FAIL" not in hapd.request("ENABLE"):
412            raise Exception("Unexpected ENABLE success")
413        hapd.request("DISABLE")
414
415        # invalid MAC address
416        with open(pskfile, "w") as f:
417            f.write("\n")
418            f.write("foo\n")
419        if "FAIL" not in hapd.request("ENABLE"):
420            raise Exception("Unexpected ENABLE success")
421        hapd.request("DISABLE")
422
423        # no PSK on line
424        with open(pskfile, "w") as f:
425            f.write("00:11:22:33:44:55\n")
426        if "FAIL" not in hapd.request("ENABLE"):
427            raise Exception("Unexpected ENABLE success")
428        hapd.request("DISABLE")
429
430        # invalid PSK
431        with open(pskfile, "w") as f:
432            f.write("00:11:22:33:44:55 1234567\n")
433        if "FAIL" not in hapd.request("ENABLE"):
434            raise Exception("Unexpected ENABLE success")
435        hapd.request("DISABLE")
436
437        # empty token at the end of the line
438        with open(pskfile, "w") as f:
439            f.write("=\n")
440        if "FAIL" not in hapd.request("ENABLE"):
441            raise Exception("Unexpected ENABLE success")
442        hapd.request("DISABLE")
443
444        # valid PSK file
445        with open(pskfile, "w") as f:
446            f.write("00:11:22:33:44:55 12345678\n")
447            f.write(addr0 + " 123456789\n")
448            f.write(addr1 + " 123456789a\n")
449            f.write(addr2 + " 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\n")
450        if "FAIL" in hapd.request("ENABLE"):
451            raise Exception("Unexpected ENABLE failure")
452
453        dev[0].connect(ssid, psk="123456789", scan_freq="2412")
454        dev[1].connect(ssid, psk="123456789a", scan_freq="2412")
455        dev[2].connect(ssid, raw_psk="0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", scan_freq="2412")
456
457    finally:
458        try:
459            os.remove(pskfile)
460        except:
461            pass
462
463@remote_compatible
464def test_ap_wpa2_psk_wildcard_ssid(dev, apdev):
465    """WPA2-PSK AP and wildcard SSID configuration"""
466    ssid = "test-wpa2-psk"
467    passphrase = 'qwertyuiop'
468    psk = '602e323e077bc63bd80307ef4745b754b0ae0a925c2638ecd13a794b9527b9e6'
469    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
470    hapd = hostapd.add_ap(apdev[0], params)
471    dev[0].connect("", bssid=apdev[0]['bssid'], psk=passphrase,
472                   scan_freq="2412")
473    dev[1].connect("", bssid=apdev[0]['bssid'], raw_psk=psk, scan_freq="2412")
474
475@remote_compatible
476def test_ap_wpa2_gtk_rekey(dev, apdev):
477    """WPA2-PSK AP and GTK rekey enforced by AP"""
478    ssid = "test-wpa2-psk"
479    passphrase = 'qwertyuiop'
480    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
481    params['wpa_group_rekey'] = '1'
482    hapd = hostapd.add_ap(apdev[0], params)
483    dev[0].connect(ssid, psk=passphrase, scan_freq="2412")
484    ev = dev[0].wait_event(["WPA: Group rekeying completed"], timeout=2)
485    if ev is None:
486        raise Exception("GTK rekey timed out")
487    hwsim_utils.test_connectivity(dev[0], hapd)
488
489def test_ap_wpa2_gtk_rekey_request(dev, apdev):
490    """WPA2-PSK AP and GTK rekey by AP request"""
491    ssid = "test-wpa2-psk"
492    passphrase = 'qwertyuiop'
493    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
494    hapd = hostapd.add_ap(apdev[0], params)
495    dev[0].connect(ssid, psk=passphrase, scan_freq="2412")
496    if "OK" not in hapd.request("REKEY_GTK"):
497        raise Exception("REKEY_GTK failed")
498    ev = dev[0].wait_event(["WPA: Group rekeying completed"], timeout=2)
499    if ev is None:
500        raise Exception("GTK rekey timed out")
501    hwsim_utils.test_connectivity(dev[0], hapd)
502
503def test_ap_wpa2_gtk_rekey_failure(dev, apdev):
504    """WPA2-PSK AP and GTK rekey failure"""
505    ssid = "test-wpa2-psk"
506    passphrase = 'qwertyuiop'
507    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
508    hapd = hostapd.add_ap(apdev[0], params)
509    dev[0].connect(ssid, psk=passphrase, scan_freq="2412")
510    with fail_test(hapd, 1, "wpa_group_config_group_keys"):
511        if "OK" not in hapd.request("REKEY_GTK"):
512            raise Exception("REKEY_GTK failed")
513        wait_fail_trigger(hapd, "GET_FAIL")
514    ev = dev[0].wait_event(["WPA: Group rekeying completed"], timeout=2)
515    if ev is None:
516        raise Exception("GTK rekey timed out")
517    dev[0].wait_disconnected()
518
519def test_ap_wpa2_gtk_rekey_request(dev, apdev):
520    """WPA2-PSK AP and GTK rekey request from multiple stations"""
521    ssid = "test-wpa2-psk"
522    passphrase = 'qwertyuiop'
523    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
524    hapd = hostapd.add_ap(apdev[0], params)
525    for i in range(3):
526        dev[i].connect(ssid, psk=passphrase, scan_freq="2412")
527        hapd.wait_sta()
528    for i in range(3):
529        if "OK" not in dev[i].request("KEY_REQUEST 0 0"):
530            raise Exception("KEY_REQUEST failed")
531    for i in range(3):
532        ev = dev[i].wait_event(["WPA: Group rekeying completed"], timeout=2)
533        if ev is None:
534            raise Exception("GTK rekey timed out")
535    time.sleep(1)
536    for i in range(3):
537        hwsim_utils.test_connectivity(dev[i], hapd)
538
539@remote_compatible
540def test_ap_wpa_gtk_rekey(dev, apdev):
541    """WPA-PSK/TKIP AP and GTK rekey enforced by AP"""
542    skip_with_fips(dev[0])
543    skip_without_tkip(dev[0])
544    ssid = "test-wpa-psk"
545    passphrase = 'qwertyuiop'
546    params = hostapd.wpa_params(ssid=ssid, passphrase=passphrase)
547    params['wpa_group_rekey'] = '1'
548    hapd = hostapd.add_ap(apdev[0], params)
549    dev[0].connect(ssid, psk=passphrase, scan_freq="2412")
550    ev = dev[0].wait_event(["WPA: Group rekeying completed"], timeout=2)
551    if ev is None:
552        raise Exception("GTK rekey timed out")
553    hwsim_utils.test_connectivity(dev[0], hapd)
554
555@remote_compatible
556def test_ap_wpa2_gmk_rekey(dev, apdev):
557    """WPA2-PSK AP and GMK and GTK rekey enforced by AP"""
558    ssid = "test-wpa2-psk"
559    passphrase = 'qwertyuiop'
560    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
561    params['wpa_group_rekey'] = '1'
562    params['wpa_gmk_rekey'] = '2'
563    hapd = hostapd.add_ap(apdev[0], params)
564    dev[0].connect(ssid, psk=passphrase, scan_freq="2412")
565    for i in range(0, 3):
566        ev = dev[0].wait_event(["WPA: Group rekeying completed"], timeout=2)
567        if ev is None:
568            raise Exception("GTK rekey timed out")
569    hwsim_utils.test_connectivity(dev[0], hapd)
570
571@remote_compatible
572def test_ap_wpa2_strict_rekey(dev, apdev):
573    """WPA2-PSK AP and strict GTK rekey enforced by AP"""
574    ssid = "test-wpa2-psk"
575    passphrase = 'qwertyuiop'
576    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
577    params['wpa_strict_rekey'] = '1'
578    hapd = hostapd.add_ap(apdev[0], params)
579    dev[0].connect(ssid, psk=passphrase, scan_freq="2412")
580    dev[1].connect(ssid, psk=passphrase, scan_freq="2412")
581    dev[1].request("DISCONNECT")
582    ev = dev[0].wait_event(["WPA: Group rekeying completed"], timeout=2)
583    if ev is None:
584        raise Exception("GTK rekey timed out")
585    hwsim_utils.test_connectivity(dev[0], hapd)
586
587@remote_compatible
588def test_ap_wpa2_bridge_fdb(dev, apdev):
589    """Bridge FDB entry removal"""
590    hapd = None
591    try:
592        ssid = "test-wpa2-psk"
593        passphrase = "12345678"
594        params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
595        params['bridge'] = 'ap-br0'
596        hapd = hostapd.add_ap(apdev[0], params)
597        hapd.cmd_execute(['brctl', 'setfd', 'ap-br0', '0'])
598        hapd.cmd_execute(['ip', 'link', 'set', 'dev', 'ap-br0', 'up'])
599        dev[0].connect(ssid, psk=passphrase, scan_freq="2412",
600                       bssid=apdev[0]['bssid'])
601        dev[1].connect(ssid, psk=passphrase, scan_freq="2412",
602                       bssid=apdev[0]['bssid'])
603        hapd.wait_sta()
604        hapd.wait_sta()
605        addr0 = dev[0].p2p_interface_addr()
606        hwsim_utils.test_connectivity_sta(dev[0], dev[1])
607        err, macs1 = hapd.cmd_execute(['brctl', 'showmacs', 'ap-br0'])
608        hapd.cmd_execute(['brctl', 'setageing', 'ap-br0', '1'])
609        dev[0].request("DISCONNECT")
610        dev[1].request("DISCONNECT")
611        time.sleep(1)
612        err, macs2 = hapd.cmd_execute(['brctl', 'showmacs', 'ap-br0'])
613
614        addr1 = dev[1].p2p_interface_addr()
615        if addr0 not in macs1 or addr1 not in macs1:
616            raise Exception("Bridge FDB entry missing")
617        if addr0 in macs2 or addr1 in macs2:
618            raise Exception("Bridge FDB entry was not removed")
619    finally:
620        hostapd.cmd_execute(apdev[0], ['ip', 'link', 'set', 'dev', 'ap-br0',
621                                       'down'])
622        hostapd.cmd_execute(apdev[0], ['brctl', 'delbr', 'ap-br0'])
623
624@remote_compatible
625def test_ap_wpa2_already_in_bridge(dev, apdev):
626    """hostapd behavior with interface already in bridge"""
627    ifname = apdev[0]['ifname']
628    br_ifname = 'ext-ap-br0'
629    try:
630        ssid = "test-wpa2-psk"
631        passphrase = "12345678"
632        hostapd.cmd_execute(apdev[0], ['brctl', 'addbr', br_ifname])
633        hostapd.cmd_execute(apdev[0], ['brctl', 'setfd', br_ifname, '0'])
634        hostapd.cmd_execute(apdev[0], ['ip', 'link', 'set', 'dev', br_ifname,
635                                       'up'])
636        hostapd.cmd_execute(apdev[0], ['iw', ifname, 'set', 'type', '__ap'])
637        hostapd.cmd_execute(apdev[0], ['brctl', 'addif', br_ifname, ifname])
638        params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
639        hapd = hostapd.add_ap(apdev[0], params)
640        if hapd.get_driver_status_field('brname') != br_ifname:
641            raise Exception("Bridge name not identified correctly")
642        dev[0].connect(ssid, psk=passphrase, scan_freq="2412")
643    finally:
644        hostapd.cmd_execute(apdev[0], ['ip', 'link', 'set', 'dev', br_ifname,
645                                       'down'])
646        hostapd.cmd_execute(apdev[0], ['brctl', 'delif', br_ifname, ifname])
647        hostapd.cmd_execute(apdev[0], ['iw', ifname, 'set', 'type', 'station'])
648        hostapd.cmd_execute(apdev[0], ['brctl', 'delbr', br_ifname])
649
650@remote_compatible
651def test_ap_wpa2_in_different_bridge(dev, apdev):
652    """hostapd behavior with interface in different bridge"""
653    ifname = apdev[0]['ifname']
654    br_ifname = 'ext-ap-br0'
655    try:
656        ssid = "test-wpa2-psk"
657        passphrase = "12345678"
658        hostapd.cmd_execute(apdev[0], ['brctl', 'addbr', br_ifname])
659        hostapd.cmd_execute(apdev[0], ['brctl', 'setfd', br_ifname, '0'])
660        hostapd.cmd_execute(apdev[0], ['ip', 'link', 'set', 'dev', br_ifname,
661                                       'up'])
662        hostapd.cmd_execute(apdev[0], ['iw', ifname, 'set', 'type', '__ap'])
663        hostapd.cmd_execute(apdev[0], ['brctl', 'addif', br_ifname, ifname])
664        time.sleep(0.5)
665        params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
666        params['bridge'] = 'ap-br0'
667        hapd = hostapd.add_ap(apdev[0], params)
668        hostapd.cmd_execute(apdev[0], ['brctl', 'setfd', 'ap-br0', '0'])
669        hostapd.cmd_execute(apdev[0], ['ip', 'link', 'set', 'dev', 'ap-br0',
670                                       'up'])
671        brname = hapd.get_driver_status_field('brname')
672        if brname != 'ap-br0':
673            raise Exception("Incorrect bridge: " + brname)
674        dev[0].connect(ssid, psk=passphrase, scan_freq="2412")
675        hapd.wait_sta()
676        hwsim_utils.test_connectivity_iface(dev[0], hapd, "ap-br0")
677        if hapd.get_driver_status_field("added_bridge") != "1":
678            raise Exception("Unexpected added_bridge value")
679        if hapd.get_driver_status_field("added_if_into_bridge") != "1":
680            raise Exception("Unexpected added_if_into_bridge value")
681        dev[0].request("DISCONNECT")
682        hapd.disable()
683    finally:
684        hostapd.cmd_execute(apdev[0], ['ip', 'link', 'set', 'dev', br_ifname,
685                                       'down'])
686        hostapd.cmd_execute(apdev[0], ['brctl', 'delif', br_ifname, ifname,
687                                       "2>", "/dev/null"], shell=True)
688        hostapd.cmd_execute(apdev[0], ['brctl', 'delbr', br_ifname])
689
690@remote_compatible
691def test_ap_wpa2_ext_add_to_bridge(dev, apdev):
692    """hostapd behavior with interface added to bridge externally"""
693    ifname = apdev[0]['ifname']
694    br_ifname = 'ext-ap-br0'
695    try:
696        ssid = "test-wpa2-psk"
697        passphrase = "12345678"
698        params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
699        hapd = hostapd.add_ap(apdev[0], params)
700
701        hostapd.cmd_execute(apdev[0], ['brctl', 'addbr', br_ifname])
702        hostapd.cmd_execute(apdev[0], ['brctl', 'setfd', br_ifname, '0'])
703        hostapd.cmd_execute(apdev[0], ['ip', 'link', 'set', 'dev', br_ifname,
704                                       'up'])
705        hostapd.cmd_execute(apdev[0], ['brctl', 'addif', br_ifname, ifname])
706        dev[0].connect(ssid, psk=passphrase, scan_freq="2412")
707        if hapd.get_driver_status_field('brname') != br_ifname:
708            raise Exception("Bridge name not identified correctly")
709    finally:
710        hostapd.cmd_execute(apdev[0], ['ip', 'link', 'set', 'dev', br_ifname,
711                                       'down'])
712        hostapd.cmd_execute(apdev[0], ['brctl', 'delif', br_ifname, ifname])
713        hostapd.cmd_execute(apdev[0], ['brctl', 'delbr', br_ifname])
714
715def setup_psk_ext(dev, apdev, wpa_ptk_rekey=None):
716    ssid = "test-wpa2-psk"
717    passphrase = 'qwertyuiop'
718    psk = '602e323e077bc63bd80307ef4745b754b0ae0a925c2638ecd13a794b9527b9e6'
719    params = hostapd.wpa2_params(ssid=ssid)
720    params['wpa_psk'] = psk
721    if wpa_ptk_rekey:
722        params['wpa_ptk_rekey'] = wpa_ptk_rekey
723    hapd = hostapd.add_ap(apdev, params)
724    hapd.request("SET ext_eapol_frame_io 1")
725    dev.request("SET ext_eapol_frame_io 1")
726    dev.connect(ssid, psk=passphrase, scan_freq="2412", wait_connect=False)
727    return hapd
728
729def ext_4way_hs(hapd, dev):
730    bssid = hapd.own_addr()
731    addr = dev.own_addr()
732    first = None
733    last = None
734    while True:
735        ev = hapd.wait_event(["EAPOL-TX", "AP-STA-CONNECTED"], timeout=15)
736        if ev is None:
737            raise Exception("Timeout on EAPOL-TX from hostapd")
738        if "AP-STA-CONNECTED" in ev:
739            dev.wait_connected(timeout=15)
740            break
741        if not first:
742            first = ev.split(' ')[2]
743        last = ev.split(' ')[2]
744        res = dev.request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
745        if "OK" not in res:
746            raise Exception("EAPOL_RX to wpa_supplicant failed")
747        ev = dev.wait_event(["EAPOL-TX", "CTRL-EVENT-CONNECTED"], timeout=15)
748        if ev is None:
749            raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
750        if "CTRL-EVENT-CONNECTED" in ev:
751            break
752        res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
753        if "OK" not in res:
754            raise Exception("EAPOL_RX to hostapd failed")
755    return first, last
756
757def test_ap_wpa2_psk_ext(dev, apdev):
758    """WPA2-PSK AP using external EAPOL I/O"""
759    hapd = setup_psk_ext(dev[0], apdev[0])
760    ext_4way_hs(hapd, dev[0])
761
762def test_ap_wpa2_psk_unexpected(dev, apdev):
763    """WPA2-PSK and supplicant receiving unexpected EAPOL-Key frames"""
764    hapd = setup_psk_ext(dev[0], apdev[0])
765    first, last = ext_4way_hs(hapd, dev[0])
766
767    # Not associated - Delay processing of received EAPOL frame (state=COMPLETED
768    # bssid=02:00:00:00:03:00)
769    other = "02:11:22:33:44:55"
770    res = dev[0].request("EAPOL_RX " + other + " " + first)
771    if "OK" not in res:
772        raise Exception("EAPOL_RX to wpa_supplicant failed")
773
774    # WPA: EAPOL-Key Replay Counter did not increase - dropping packet
775    bssid = hapd.own_addr()
776    res = dev[0].request("EAPOL_RX " + bssid + " " + last)
777    if "OK" not in res:
778        raise Exception("EAPOL_RX to wpa_supplicant failed")
779
780    # WPA: Invalid EAPOL-Key MIC - dropping packet
781    msg = last[0:18] + '01' + last[20:]
782    res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
783    if "OK" not in res:
784        raise Exception("EAPOL_RX to wpa_supplicant failed")
785
786    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=12)
787    if ev is not None:
788        raise Exception("Unexpected disconnection")
789
790def test_ap_wpa2_psk_ext_retry_msg_3(dev, apdev):
791    """WPA2-PSK AP using external EAPOL I/O and retry for EAPOL-Key msg 3/4"""
792    hapd = setup_psk_ext(dev[0], apdev[0])
793    bssid = apdev[0]['bssid']
794    addr = dev[0].p2p_interface_addr()
795
796    # EAPOL-Key msg 1/4
797    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
798    if ev is None:
799        raise Exception("Timeout on EAPOL-TX from hostapd")
800    res = dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
801    if "OK" not in res:
802        raise Exception("EAPOL_RX to wpa_supplicant failed")
803
804    # EAPOL-Key msg 2/4
805    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
806    if ev is None:
807        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
808    res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
809    if "OK" not in res:
810        raise Exception("EAPOL_RX to hostapd failed")
811
812    # EAPOL-Key msg 3/4
813    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
814    if ev is None:
815        raise Exception("Timeout on EAPOL-TX from hostapd")
816    res = dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
817    if "OK" not in res:
818        raise Exception("EAPOL_RX to wpa_supplicant failed")
819
820    # EAPOL-Key msg 4/4
821    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
822    if ev is None:
823        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
824    # Do not send to the AP
825    dev[0].wait_connected(timeout=15)
826
827    # EAPOL-Key msg 3/4 (retry)
828    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
829    if ev is None:
830        raise Exception("Timeout on EAPOL-TX from hostapd")
831    res = dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
832    if "OK" not in res:
833        raise Exception("EAPOL_RX to wpa_supplicant failed")
834
835    # EAPOL-Key msg 4/4
836    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
837    if ev is None:
838        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
839    res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
840    if "OK" not in res:
841        raise Exception("EAPOL_RX to hostapd failed")
842
843    ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=15)
844    if ev is None:
845        raise Exception("Timeout on AP-STA-CONNECTED from hostapd")
846
847    hwsim_utils.test_connectivity(dev[0], hapd)
848
849def test_ap_wpa2_psk_ext_retry_msg_3b(dev, apdev):
850    """WPA2-PSK AP using external EAPOL I/O and retry for EAPOL-Key msg 3/4 (b)"""
851    hapd = setup_psk_ext(dev[0], apdev[0])
852    bssid = apdev[0]['bssid']
853    addr = dev[0].p2p_interface_addr()
854
855    # EAPOL-Key msg 1/4
856    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
857    if ev is None:
858        raise Exception("Timeout on EAPOL-TX from hostapd")
859    res = dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
860    if "OK" not in res:
861        raise Exception("EAPOL_RX to wpa_supplicant failed")
862
863    # EAPOL-Key msg 2/4
864    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
865    if ev is None:
866        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
867    res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
868    if "OK" not in res:
869        raise Exception("EAPOL_RX to hostapd failed")
870
871    # EAPOL-Key msg 3/4
872    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
873    if ev is None:
874        raise Exception("Timeout on EAPOL-TX from hostapd")
875    # Do not send the first msg 3/4 to the STA yet; wait for retransmission
876    # from AP.
877    msg3_1 = ev
878
879    # EAPOL-Key msg 3/4 (retry)
880    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
881    if ev is None:
882        raise Exception("Timeout on EAPOL-TX from hostapd")
883    msg3_2 = ev
884
885    # Send the first msg 3/4 to STA
886    res = dev[0].request("EAPOL_RX " + bssid + " " + msg3_1.split(' ')[2])
887    if "OK" not in res:
888        raise Exception("EAPOL_RX to wpa_supplicant failed")
889
890    # EAPOL-Key msg 4/4
891    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
892    if ev is None:
893        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
894    res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
895    if "OK" not in res:
896        raise Exception("EAPOL_RX to hostapd failed")
897    dev[0].wait_connected(timeout=15)
898    ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=15)
899    if ev is None:
900        raise Exception("Timeout on AP-STA-CONNECTED from hostapd")
901
902    hwsim_utils.test_connectivity(dev[0], hapd)
903
904    # Send the second msg 3/4 to STA
905    res = dev[0].request("EAPOL_RX " + bssid + " " + msg3_2.split(' ')[2])
906    if "OK" not in res:
907        raise Exception("EAPOL_RX to wpa_supplicant failed")
908    # EAPOL-Key msg 4/4
909    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
910    if ev is None:
911        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
912    # Do not send the second msg 4/4 to the AP
913
914    hwsim_utils.test_connectivity(dev[0], hapd)
915
916def test_ap_wpa2_psk_ext_retry_msg_3c(dev, apdev):
917    """WPA2-PSK AP using external EAPOL I/O and retry for EAPOL-Key msg 3/4 (c)"""
918    hapd = setup_psk_ext(dev[0], apdev[0])
919    bssid = apdev[0]['bssid']
920    addr = dev[0].p2p_interface_addr()
921
922    # EAPOL-Key msg 1/4
923    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
924    if ev is None:
925        raise Exception("Timeout on EAPOL-TX from hostapd")
926    msg1 = ev.split(' ')[2]
927    res = dev[0].request("EAPOL_RX " + bssid + " " + msg1)
928    if "OK" not in res:
929        raise Exception("EAPOL_RX to wpa_supplicant failed")
930
931    # EAPOL-Key msg 2/4
932    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
933    if ev is None:
934        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
935    res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
936    if "OK" not in res:
937        raise Exception("EAPOL_RX to hostapd failed")
938
939    # EAPOL-Key msg 3/4
940    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
941    if ev is None:
942        raise Exception("Timeout on EAPOL-TX from hostapd")
943    res = dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
944    if "OK" not in res:
945        raise Exception("EAPOL_RX to wpa_supplicant failed")
946
947    # EAPOL-Key msg 4/4
948    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
949    if ev is None:
950        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
951    msg4 = ev.split(' ')[2]
952    # Do not send msg 4/4 to hostapd to trigger retry
953
954    # STA believes everything is ready
955    dev[0].wait_connected()
956
957    # EAPOL-Key msg 3/4 (retry)
958    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
959    if ev is None:
960        raise Exception("Timeout on EAPOL-TX from hostapd")
961    msg3 = ev.split(' ')[2]
962
963    # Send a forged msg 1/4 to STA (update replay counter)
964    msg1b = msg1[0:18] + msg3[18:34] + msg1[34:]
965    # and replace nonce (this results in "WPA: ANonce from message 1 of
966    # 4-Way Handshake differs from 3 of 4-Way Handshake - drop packet" when
967    # wpa_supplicant processed msg 3/4 afterwards)
968    #msg1b = msg1[0:18] + msg3[18:34] + 32*"ff" + msg1[98:]
969    res = dev[0].request("EAPOL_RX " + bssid + " " + msg1b)
970    if "OK" not in res:
971        raise Exception("EAPOL_RX to wpa_supplicant failed")
972    # EAPOL-Key msg 2/4
973    ev = dev[0].wait_event(["EAPOL-TX"], timeout=1)
974    if ev is None:
975        # wpa_supplicant seems to have ignored the forged message. This means
976        # the attack would fail.
977        logger.info("wpa_supplicant ignored forged EAPOL-Key msg 1/4")
978        return
979    # Do not send msg 2/4 to hostapd
980
981    # Send previously received msg 3/4 to STA
982    res = dev[0].request("EAPOL_RX " + bssid + " " + msg3)
983    if "OK" not in res:
984        raise Exception("EAPOL_RX to wpa_supplicant failed")
985
986    # EAPOL-Key msg 4/4
987    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
988    if ev is None:
989        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
990    res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
991    if "OK" not in res:
992        raise Exception("EAPOL_RX to hostapd failed")
993
994    ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=15)
995    if ev is None:
996        raise Exception("Timeout on AP-STA-CONNECTED from hostapd")
997
998    hwsim_utils.test_connectivity(dev[0], hapd)
999
1000def test_ap_wpa2_psk_ext_retry_msg_3d(dev, apdev):
1001    """WPA2-PSK AP using external EAPOL I/O and retry for EAPOL-Key msg 3/4 (d)"""
1002    hapd = setup_psk_ext(dev[0], apdev[0])
1003    bssid = apdev[0]['bssid']
1004    addr = dev[0].p2p_interface_addr()
1005
1006    # EAPOL-Key msg 1/4
1007    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
1008    if ev is None:
1009        raise Exception("Timeout on EAPOL-TX from hostapd")
1010    msg1 = ev.split(' ')[2]
1011    res = dev[0].request("EAPOL_RX " + bssid + " " + msg1)
1012    if "OK" not in res:
1013        raise Exception("EAPOL_RX to wpa_supplicant failed")
1014
1015    # EAPOL-Key msg 2/4
1016    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
1017    if ev is None:
1018        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
1019    res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
1020    if "OK" not in res:
1021        raise Exception("EAPOL_RX to hostapd failed")
1022
1023    # EAPOL-Key msg 3/4
1024    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
1025    if ev is None:
1026        raise Exception("Timeout on EAPOL-TX from hostapd")
1027    res = dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
1028    if "OK" not in res:
1029        raise Exception("EAPOL_RX to wpa_supplicant failed")
1030
1031    # EAPOL-Key msg 4/4
1032    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
1033    if ev is None:
1034        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
1035    msg4 = ev.split(' ')[2]
1036    # Do not send msg 4/4 to hostapd to trigger retry
1037
1038    # STA believes everything is ready
1039    dev[0].wait_connected()
1040
1041    # EAPOL-Key msg 3/4 (retry)
1042    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
1043    if ev is None:
1044        raise Exception("Timeout on EAPOL-TX from hostapd")
1045    msg3 = ev.split(' ')[2]
1046
1047    # Send a forged msg 1/4 to STA (update replay counter)
1048    msg1b = msg1[0:18] + msg3[18:34] + msg1[34:]
1049    res = dev[0].request("EAPOL_RX " + bssid + " " + msg1b)
1050    if "OK" not in res:
1051        raise Exception("EAPOL_RX to wpa_supplicant failed")
1052    # EAPOL-Key msg 2/4
1053    ev = dev[0].wait_event(["EAPOL-TX"], timeout=1)
1054    if ev is None:
1055        # wpa_supplicant seems to have ignored the forged message. This means
1056        # the attack would fail.
1057        logger.info("wpa_supplicant ignored forged EAPOL-Key msg 1/4")
1058        return
1059    # Do not send msg 2/4 to hostapd
1060
1061    # EAPOL-Key msg 3/4 (retry 2)
1062    # New one needed to get the correct Replay Counter value
1063    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
1064    if ev is None:
1065        raise Exception("Timeout on EAPOL-TX from hostapd")
1066    msg3 = ev.split(' ')[2]
1067
1068    # Send msg 3/4 to STA
1069    res = dev[0].request("EAPOL_RX " + bssid + " " + msg3)
1070    if "OK" not in res:
1071        raise Exception("EAPOL_RX to wpa_supplicant failed")
1072
1073    # EAPOL-Key msg 4/4
1074    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
1075    if ev is None:
1076        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
1077    res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
1078    if "OK" not in res:
1079        raise Exception("EAPOL_RX to hostapd failed")
1080
1081    ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=15)
1082    if ev is None:
1083        raise Exception("Timeout on AP-STA-CONNECTED from hostapd")
1084
1085    hwsim_utils.test_connectivity(dev[0], hapd)
1086
1087def test_ap_wpa2_psk_ext_retry_msg_3e(dev, apdev):
1088    """WPA2-PSK AP using external EAPOL I/O and retry for EAPOL-Key msg 3/4 (e)"""
1089    hapd = setup_psk_ext(dev[0], apdev[0])
1090    bssid = apdev[0]['bssid']
1091    addr = dev[0].p2p_interface_addr()
1092
1093    # EAPOL-Key msg 1/4
1094    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
1095    if ev is None:
1096        raise Exception("Timeout on EAPOL-TX from hostapd")
1097    msg1 = ev.split(' ')[2]
1098    res = dev[0].request("EAPOL_RX " + bssid + " " + msg1)
1099    if "OK" not in res:
1100        raise Exception("EAPOL_RX to wpa_supplicant failed")
1101
1102    # EAPOL-Key msg 2/4
1103    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
1104    if ev is None:
1105        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
1106    res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
1107    if "OK" not in res:
1108        raise Exception("EAPOL_RX to hostapd failed")
1109
1110    # EAPOL-Key msg 3/4
1111    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
1112    if ev is None:
1113        raise Exception("Timeout on EAPOL-TX from hostapd")
1114    res = dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
1115    if "OK" not in res:
1116        raise Exception("EAPOL_RX to wpa_supplicant failed")
1117
1118    # EAPOL-Key msg 4/4
1119    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
1120    if ev is None:
1121        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
1122    msg4 = ev.split(' ')[2]
1123    # Do not send msg 4/4 to hostapd to trigger retry
1124
1125    # STA believes everything is ready
1126    dev[0].wait_connected()
1127
1128    # EAPOL-Key msg 3/4 (retry)
1129    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
1130    if ev is None:
1131        raise Exception("Timeout on EAPOL-TX from hostapd")
1132    msg3 = ev.split(' ')[2]
1133
1134    # Send a forged msg 1/4 to STA (update replay counter and replace ANonce)
1135    msg1b = msg1[0:18] + msg3[18:34] + 32*"ff" + msg1[98:]
1136    res = dev[0].request("EAPOL_RX " + bssid + " " + msg1b)
1137    if "OK" not in res:
1138        raise Exception("EAPOL_RX to wpa_supplicant failed")
1139    # EAPOL-Key msg 2/4
1140    ev = dev[0].wait_event(["EAPOL-TX"], timeout=1)
1141    if ev is None:
1142        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
1143    # Do not send msg 2/4 to hostapd
1144
1145    # Send a forged msg 1/4 to STA (back to previously used ANonce)
1146    msg1b = msg1[0:18] + msg3[18:34] + msg1[34:]
1147    res = dev[0].request("EAPOL_RX " + bssid + " " + msg1b)
1148    if "OK" not in res:
1149        raise Exception("EAPOL_RX to wpa_supplicant failed")
1150    # EAPOL-Key msg 2/4
1151    ev = dev[0].wait_event(["EAPOL-TX"], timeout=1)
1152    if ev is None:
1153        # wpa_supplicant seems to have ignored the forged message. This means
1154        # the attack would fail.
1155        logger.info("wpa_supplicant ignored forged EAPOL-Key msg 1/4")
1156        return
1157    # Do not send msg 2/4 to hostapd
1158
1159    # EAPOL-Key msg 3/4 (retry 2)
1160    # New one needed to get the correct Replay Counter value
1161    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
1162    if ev is None:
1163        raise Exception("Timeout on EAPOL-TX from hostapd")
1164    msg3 = ev.split(' ')[2]
1165
1166    # Send msg 3/4 to STA
1167    res = dev[0].request("EAPOL_RX " + bssid + " " + msg3)
1168    if "OK" not in res:
1169        raise Exception("EAPOL_RX to wpa_supplicant failed")
1170
1171    # EAPOL-Key msg 4/4
1172    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
1173    if ev is None:
1174        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
1175    res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
1176    if "OK" not in res:
1177        raise Exception("EAPOL_RX to hostapd failed")
1178
1179    ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=15)
1180    if ev is None:
1181        raise Exception("Timeout on AP-STA-CONNECTED from hostapd")
1182
1183    hwsim_utils.test_connectivity(dev[0], hapd)
1184
1185def test_ap_wpa2_psk_ext_delayed_ptk_rekey(dev, apdev):
1186    """WPA2-PSK AP using external EAPOL I/O and delayed PTK rekey exchange"""
1187    hapd = setup_psk_ext(dev[0], apdev[0], wpa_ptk_rekey="3")
1188    bssid = apdev[0]['bssid']
1189    addr = dev[0].p2p_interface_addr()
1190
1191    # EAPOL-Key msg 1/4
1192    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
1193    if ev is None:
1194        raise Exception("Timeout on EAPOL-TX from hostapd")
1195    res = dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
1196    if "OK" not in res:
1197        raise Exception("EAPOL_RX to wpa_supplicant failed")
1198
1199    # EAPOL-Key msg 2/4
1200    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
1201    if ev is None:
1202        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
1203    msg2 = ev.split(' ')[2]
1204    # Do not send this to the AP
1205
1206    # EAPOL-Key msg 1/4 (retry)
1207    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
1208    if ev is None:
1209        raise Exception("Timeout on EAPOL-TX from hostapd")
1210    res = dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
1211    if "OK" not in res:
1212        raise Exception("EAPOL_RX to wpa_supplicant failed")
1213
1214    # EAPOL-Key msg 2/4
1215    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
1216    if ev is None:
1217        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
1218    res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
1219    if "OK" not in res:
1220        raise Exception("EAPOL_RX to hostapd failed")
1221
1222    # EAPOL-Key msg 3/4
1223    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
1224    if ev is None:
1225        raise Exception("Timeout on EAPOL-TX from hostapd")
1226    res = dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
1227    if "OK" not in res:
1228        raise Exception("EAPOL_RX to wpa_supplicant failed")
1229
1230    # EAPOL-Key msg 4/4
1231    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
1232    if ev is None:
1233        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
1234    msg4 = ev.split(' ')[2]
1235    # Do not send msg 4/4 to AP
1236
1237    # EAPOL-Key msg 3/4 (retry)
1238    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
1239    if ev is None:
1240        raise Exception("Timeout on EAPOL-TX from hostapd")
1241    res = dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
1242    if "OK" not in res:
1243        raise Exception("EAPOL_RX to wpa_supplicant failed")
1244
1245    # EAPOL-Key msg 4/4
1246    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
1247    if ev is None:
1248        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
1249    msg4b = ev.split(' ')[2]
1250    # Do not send msg 4/4 to AP
1251
1252    # Send the previous EAPOL-Key msg 4/4 to AP
1253    res = hapd.request("EAPOL_RX " + addr + " " + msg4)
1254    if "OK" not in res:
1255        raise Exception("EAPOL_RX to hostapd failed")
1256
1257    ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=15)
1258    if ev is None:
1259        raise Exception("Timeout on AP-STA-CONNECTED from hostapd")
1260
1261    # Wait for PTK rekeying to be initialized
1262    # EAPOL-Key msg 1/4
1263    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
1264    if ev is None:
1265        raise Exception("Timeout on EAPOL-TX from hostapd")
1266
1267    # EAPOL-Key msg 2/4 from the previous 4-way handshake
1268    # hostapd is expected to ignore this due to unexpected Replay Counter
1269    res = hapd.request("EAPOL_RX " + addr + " " + msg2)
1270    if "OK" not in res:
1271        raise Exception("EAPOL_RX to hostapd failed")
1272
1273    # EAPOL-Key msg 3/4 (actually, this ends up being retransmitted 1/4)
1274    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
1275    if ev is None:
1276        raise Exception("Timeout on EAPOL-TX from hostapd")
1277    keyinfo = ev.split(' ')[2][10:14]
1278    if keyinfo != "008a":
1279        raise Exception("Unexpected key info when expected msg 1/4:" + keyinfo)
1280
1281    # EAPOL-Key msg 4/4 from the previous 4-way handshake
1282    # hostapd is expected to ignore this due to unexpected Replay Counter
1283    res = hapd.request("EAPOL_RX " + addr + " " + msg4b)
1284    if "OK" not in res:
1285        raise Exception("EAPOL_RX to hostapd failed")
1286
1287    # Check if any more EAPOL-Key frames are seen. If the second 4-way handshake
1288    # was accepted, there would be no more EAPOL-Key frames. If the Replay
1289    # Counters were rejected, there would be a retransmitted msg 1/4 here.
1290    ev = hapd.wait_event(["EAPOL-TX"], timeout=1.1)
1291    if ev is None:
1292        raise Exception("Did not see EAPOL-TX from hostapd in the end (expected msg 1/4)")
1293    keyinfo = ev.split(' ')[2][10:14]
1294    if keyinfo != "008a":
1295        raise Exception("Unexpected key info when expected msg 1/4:" + keyinfo)
1296
1297def parse_eapol(data):
1298    (version, type, length) = struct.unpack('>BBH', data[0:4])
1299    payload = data[4:]
1300    if length > len(payload):
1301        raise Exception("Invalid EAPOL length")
1302    if length < len(payload):
1303        payload = payload[0:length]
1304    eapol = {}
1305    eapol['version'] = version
1306    eapol['type'] = type
1307    eapol['length'] = length
1308    eapol['payload'] = payload
1309    if type == 3:
1310        # EAPOL-Key
1311        (eapol['descr_type'],) = struct.unpack('B', payload[0:1])
1312        payload = payload[1:]
1313        if eapol['descr_type'] == 2 or eapol['descr_type'] == 254:
1314            # RSN EAPOL-Key
1315            (key_info, key_len) = struct.unpack('>HH', payload[0:4])
1316            eapol['rsn_key_info'] = key_info
1317            eapol['rsn_key_len'] = key_len
1318            eapol['rsn_replay_counter'] = payload[4:12]
1319            eapol['rsn_key_nonce'] = payload[12:44]
1320            eapol['rsn_key_iv'] = payload[44:60]
1321            eapol['rsn_key_rsc'] = payload[60:68]
1322            eapol['rsn_key_id'] = payload[68:76]
1323            eapol['rsn_key_mic'] = payload[76:92]
1324            payload = payload[92:]
1325            (eapol['rsn_key_data_len'],) = struct.unpack('>H', payload[0:2])
1326            payload = payload[2:]
1327            eapol['rsn_key_data'] = payload
1328    return eapol
1329
1330def build_eapol(msg):
1331    data = struct.pack(">BBH", msg['version'], msg['type'], msg['length'])
1332    if msg['type'] == 3:
1333        data += struct.pack('>BHH', msg['descr_type'], msg['rsn_key_info'],
1334                            msg['rsn_key_len'])
1335        data += msg['rsn_replay_counter']
1336        data += msg['rsn_key_nonce']
1337        data += msg['rsn_key_iv']
1338        data += msg['rsn_key_rsc']
1339        data += msg['rsn_key_id']
1340        data += msg['rsn_key_mic']
1341        data += struct.pack('>H', msg['rsn_key_data_len'])
1342        data += msg['rsn_key_data']
1343    else:
1344        data += msg['payload']
1345    return data
1346
1347def sha1_prf(key, label, data, outlen):
1348    res = b''
1349    counter = 0
1350    while outlen > 0:
1351        m = hmac.new(key, label.encode(), hashlib.sha1)
1352        m.update(struct.pack('B', 0))
1353        m.update(data)
1354        m.update(struct.pack('B', counter))
1355        counter += 1
1356        hash = m.digest()
1357        if outlen > len(hash):
1358            res += hash
1359            outlen -= len(hash)
1360        else:
1361            res += hash[0:outlen]
1362            outlen = 0
1363    return res
1364
1365def pmk_to_ptk(pmk, addr1, addr2, nonce1, nonce2):
1366    if addr1 < addr2:
1367        data = binascii.unhexlify(addr1.replace(':', '')) + binascii.unhexlify(addr2.replace(':', ''))
1368    else:
1369        data = binascii.unhexlify(addr2.replace(':', '')) + binascii.unhexlify(addr1.replace(':', ''))
1370    if nonce1 < nonce2:
1371        data += nonce1 + nonce2
1372    else:
1373        data += nonce2 + nonce1
1374    label = "Pairwise key expansion"
1375    ptk = sha1_prf(pmk, label, data, 48)
1376    kck = ptk[0:16]
1377    kek = ptk[16:32]
1378    return (ptk, kck, kek)
1379
1380def eapol_key_mic(kck, msg):
1381    msg['rsn_key_mic'] = binascii.unhexlify('00000000000000000000000000000000')
1382    data = build_eapol(msg)
1383    m = hmac.new(kck, data, hashlib.sha1)
1384    msg['rsn_key_mic'] = m.digest()[0:16]
1385
1386def rsn_eapol_key_set(msg, key_info, key_len, nonce, data):
1387    msg['rsn_key_info'] = key_info
1388    msg['rsn_key_len'] = key_len
1389    if nonce:
1390        msg['rsn_key_nonce'] = nonce
1391    else:
1392        msg['rsn_key_nonce'] = binascii.unhexlify('0000000000000000000000000000000000000000000000000000000000000000')
1393    if data:
1394        msg['rsn_key_data_len'] = len(data)
1395        msg['rsn_key_data'] = data
1396        msg['length'] = 95 + len(data)
1397    else:
1398        msg['rsn_key_data_len'] = 0
1399        msg['rsn_key_data'] = b''
1400        msg['length'] = 95
1401
1402def recv_eapol(hapd):
1403    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
1404    if ev is None:
1405        raise Exception("Timeout on EAPOL-TX from hostapd")
1406    eapol = binascii.unhexlify(ev.split(' ')[2])
1407    return parse_eapol(eapol)
1408
1409def send_eapol(hapd, addr, data):
1410    res = hapd.request("EAPOL_RX " + addr + " " + binascii.hexlify(data).decode())
1411    if "OK" not in res:
1412        raise Exception("EAPOL_RX to hostapd failed")
1413
1414def reply_eapol(info, hapd, addr, msg, key_info, nonce, data, kck):
1415    logger.info("Send EAPOL-Key msg " + info)
1416    rsn_eapol_key_set(msg, key_info, 0, nonce, data)
1417    eapol_key_mic(kck, msg)
1418    send_eapol(hapd, addr, build_eapol(msg))
1419
1420def eapol_test(apdev, dev, wpa2=True, ieee80211w=0):
1421    bssid = apdev['bssid']
1422    if wpa2:
1423        ssid = "test-wpa2-psk"
1424    else:
1425        ssid = "test-wpa-psk"
1426    psk = '602e323e077bc63bd80307ef4745b754b0ae0a925c2638ecd13a794b9527b9e6'
1427    pmk = binascii.unhexlify(psk)
1428    if wpa2:
1429        params = hostapd.wpa2_params(ssid=ssid)
1430    else:
1431        params = hostapd.wpa_params(ssid=ssid)
1432    params['wpa_psk'] = psk
1433    params['ieee80211w'] = str(ieee80211w)
1434    hapd = hostapd.add_ap(apdev, params)
1435    hapd.request("SET ext_eapol_frame_io 1")
1436    dev.request("SET ext_eapol_frame_io 1")
1437    dev.connect(ssid, raw_psk=psk, scan_freq="2412", wait_connect=False,
1438                ieee80211w=str(ieee80211w))
1439    addr = dev.p2p_interface_addr()
1440    if wpa2:
1441        if ieee80211w == 2:
1442            rsne = binascii.unhexlify('30140100000fac040100000fac040100000fac02cc00')
1443        else:
1444            rsne = binascii.unhexlify('30140100000fac040100000fac040100000fac020000')
1445    else:
1446        rsne = binascii.unhexlify('dd160050f20101000050f20201000050f20201000050f202')
1447    snonce = binascii.unhexlify('1111111111111111111111111111111111111111111111111111111111111111')
1448    return (bssid, ssid, hapd, snonce, pmk, addr, rsne)
1449
1450@remote_compatible
1451def test_ap_wpa2_psk_ext_eapol(dev, apdev):
1452    """WPA2-PSK AP using external EAPOL supplicant"""
1453    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
1454
1455    msg = recv_eapol(hapd)
1456    anonce = msg['rsn_key_nonce']
1457    logger.info("Replay same data back")
1458    send_eapol(hapd, addr, build_eapol(msg))
1459
1460    (ptk, kck, kek) = pmk_to_ptk(pmk, addr, bssid, snonce, anonce)
1461
1462    logger.info("Truncated Key Data in EAPOL-Key msg 2/4")
1463    rsn_eapol_key_set(msg, 0x0101, 0, snonce, rsne)
1464    msg['length'] = 95 + 22 - 1
1465    send_eapol(hapd, addr, build_eapol(msg))
1466
1467    reply_eapol("2/4", hapd, addr, msg, 0x010a, snonce, rsne, kck)
1468
1469    msg = recv_eapol(hapd)
1470    if anonce != msg['rsn_key_nonce']:
1471        raise Exception("ANonce changed")
1472    logger.info("Replay same data back")
1473    send_eapol(hapd, addr, build_eapol(msg))
1474
1475    reply_eapol("4/4", hapd, addr, msg, 0x030a, None, None, kck)
1476    hapd.wait_sta(timeout=15)
1477
1478@remote_compatible
1479def test_ap_wpa2_psk_ext_eapol_retry1(dev, apdev):
1480    """WPA2 4-way handshake with EAPOL-Key 1/4 retransmitted"""
1481    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
1482
1483    msg1 = recv_eapol(hapd)
1484    anonce = msg1['rsn_key_nonce']
1485
1486    msg2 = recv_eapol(hapd)
1487    if anonce != msg2['rsn_key_nonce']:
1488        raise Exception("ANonce changed")
1489
1490    (ptk, kck, kek) = pmk_to_ptk(pmk, addr, bssid, snonce, anonce)
1491
1492    logger.info("Send EAPOL-Key msg 2/4")
1493    msg = msg2
1494    rsn_eapol_key_set(msg, 0x010a, 0, snonce, rsne)
1495    eapol_key_mic(kck, msg)
1496    send_eapol(hapd, addr, build_eapol(msg))
1497
1498    msg = recv_eapol(hapd)
1499    if anonce != msg['rsn_key_nonce']:
1500        raise Exception("ANonce changed")
1501
1502    reply_eapol("4/4", hapd, addr, msg, 0x030a, None, None, kck)
1503    hapd.wait_sta(timeout=15)
1504
1505@remote_compatible
1506def test_ap_wpa2_psk_ext_eapol_retry1b(dev, apdev):
1507    """WPA2 4-way handshake with EAPOL-Key 1/4 and 2/4 retransmitted"""
1508    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
1509
1510    msg1 = recv_eapol(hapd)
1511    anonce = msg1['rsn_key_nonce']
1512    msg2 = recv_eapol(hapd)
1513    if anonce != msg2['rsn_key_nonce']:
1514        raise Exception("ANonce changed")
1515
1516    (ptk, kck, kek) = pmk_to_ptk(pmk, addr, bssid, snonce, anonce)
1517    reply_eapol("2/4 (a)", hapd, addr, msg1, 0x010a, snonce, rsne, kck)
1518    reply_eapol("2/4 (b)", hapd, addr, msg2, 0x010a, snonce, rsne, kck)
1519
1520    msg = recv_eapol(hapd)
1521    if anonce != msg['rsn_key_nonce']:
1522        raise Exception("ANonce changed")
1523
1524    reply_eapol("4/4", hapd, addr, msg, 0x030a, None, None, kck)
1525    hapd.wait_sta(timeout=15)
1526
1527@remote_compatible
1528def test_ap_wpa2_psk_ext_eapol_retry1c(dev, apdev):
1529    """WPA2 4-way handshake with EAPOL-Key 1/4 and 2/4 retransmitted and SNonce changing"""
1530    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
1531
1532    msg1 = recv_eapol(hapd)
1533    anonce = msg1['rsn_key_nonce']
1534
1535    msg2 = recv_eapol(hapd)
1536    if anonce != msg2['rsn_key_nonce']:
1537        raise Exception("ANonce changed")
1538    (ptk, kck, kek) = pmk_to_ptk(pmk, addr, bssid, snonce, anonce)
1539    reply_eapol("2/4 (a)", hapd, addr, msg1, 0x010a, snonce, rsne, kck)
1540
1541    snonce2 = binascii.unhexlify('2222222222222222222222222222222222222222222222222222222222222222')
1542    (ptk, kck, kek) = pmk_to_ptk(pmk, addr, bssid, snonce2, anonce)
1543    reply_eapol("2/4 (b)", hapd, addr, msg2, 0x010a, snonce2, rsne, kck)
1544
1545    msg = recv_eapol(hapd)
1546    if anonce != msg['rsn_key_nonce']:
1547        raise Exception("ANonce changed")
1548    reply_eapol("4/4", hapd, addr, msg, 0x030a, None, None, kck)
1549    hapd.wait_sta(timeout=15)
1550
1551@remote_compatible
1552def test_ap_wpa2_psk_ext_eapol_retry1d(dev, apdev):
1553    """WPA2 4-way handshake with EAPOL-Key 1/4 and 2/4 retransmitted and SNonce changing and older used"""
1554    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
1555
1556    msg1 = recv_eapol(hapd)
1557    anonce = msg1['rsn_key_nonce']
1558    msg2 = recv_eapol(hapd)
1559    if anonce != msg2['rsn_key_nonce']:
1560        raise Exception("ANonce changed")
1561
1562    (ptk, kck, kek) = pmk_to_ptk(pmk, addr, bssid, snonce, anonce)
1563    reply_eapol("2/4 (a)", hapd, addr, msg1, 0x010a, snonce, rsne, kck)
1564
1565    snonce2 = binascii.unhexlify('2222222222222222222222222222222222222222222222222222222222222222')
1566    (ptk2, kck2, kek2) = pmk_to_ptk(pmk, addr, bssid, snonce2, anonce)
1567
1568    reply_eapol("2/4 (b)", hapd, addr, msg2, 0x010a, snonce2, rsne, kck2)
1569    msg = recv_eapol(hapd)
1570    if anonce != msg['rsn_key_nonce']:
1571        raise Exception("ANonce changed")
1572    reply_eapol("4/4", hapd, addr, msg, 0x030a, None, None, kck)
1573    hapd.wait_sta(timeout=15)
1574
1575@remote_compatible
1576def test_ap_wpa2_psk_ext_eapol_type_diff(dev, apdev):
1577    """WPA2 4-way handshake using external EAPOL supplicant"""
1578    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
1579
1580    msg = recv_eapol(hapd)
1581    anonce = msg['rsn_key_nonce']
1582
1583    (ptk, kck, kek) = pmk_to_ptk(pmk, addr, bssid, snonce, anonce)
1584
1585    # Incorrect descriptor type (frame dropped)
1586    msg['descr_type'] = 253
1587    rsn_eapol_key_set(msg, 0x010a, 0, snonce, rsne)
1588    eapol_key_mic(kck, msg)
1589    send_eapol(hapd, addr, build_eapol(msg))
1590
1591    # Incorrect descriptor type, but with a workaround (frame processed)
1592    msg['descr_type'] = 254
1593    rsn_eapol_key_set(msg, 0x010a, 0, snonce, rsne)
1594    eapol_key_mic(kck, msg)
1595    send_eapol(hapd, addr, build_eapol(msg))
1596
1597    msg = recv_eapol(hapd)
1598    if anonce != msg['rsn_key_nonce']:
1599        raise Exception("ANonce changed")
1600    logger.info("Replay same data back")
1601    send_eapol(hapd, addr, build_eapol(msg))
1602
1603    reply_eapol("4/4", hapd, addr, msg, 0x030a, None, None, kck)
1604    hapd.wait_sta(timeout=15)
1605
1606@remote_compatible
1607def test_ap_wpa_psk_ext_eapol(dev, apdev):
1608    """WPA2-PSK AP using external EAPOL supplicant"""
1609    skip_without_tkip(dev[0])
1610    (bssid, ssid, hapd, snonce, pmk, addr, wpae) = eapol_test(apdev[0], dev[0],
1611                                                              wpa2=False)
1612
1613    msg = recv_eapol(hapd)
1614    anonce = msg['rsn_key_nonce']
1615    logger.info("Replay same data back")
1616    send_eapol(hapd, addr, build_eapol(msg))
1617    logger.info("Too short data")
1618    send_eapol(hapd, addr, build_eapol(msg)[0:98])
1619
1620    (ptk, kck, kek) = pmk_to_ptk(pmk, addr, bssid, snonce, anonce)
1621    msg['descr_type'] = 2
1622    reply_eapol("2/4(invalid type)", hapd, addr, msg, 0x010a, snonce, wpae, kck)
1623    msg['descr_type'] = 254
1624    reply_eapol("2/4", hapd, addr, msg, 0x010a, snonce, wpae, kck)
1625
1626    msg = recv_eapol(hapd)
1627    if anonce != msg['rsn_key_nonce']:
1628        raise Exception("ANonce changed")
1629    logger.info("Replay same data back")
1630    send_eapol(hapd, addr, build_eapol(msg))
1631
1632    reply_eapol("4/4", hapd, addr, msg, 0x030a, None, None, kck)
1633    hapd.wait_sta(timeout=15)
1634
1635@remote_compatible
1636def test_ap_wpa2_psk_ext_eapol_key_info(dev, apdev):
1637    """WPA2-PSK 4-way handshake with strange key info values"""
1638    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
1639
1640    msg = recv_eapol(hapd)
1641    anonce = msg['rsn_key_nonce']
1642
1643    (ptk, kck, kek) = pmk_to_ptk(pmk, addr, bssid, snonce, anonce)
1644    rsn_eapol_key_set(msg, 0x0000, 0, snonce, rsne)
1645    send_eapol(hapd, addr, build_eapol(msg))
1646    rsn_eapol_key_set(msg, 0xffff, 0, snonce, rsne)
1647    send_eapol(hapd, addr, build_eapol(msg))
1648    # SMK M1
1649    rsn_eapol_key_set(msg, 0x2802, 0, snonce, rsne)
1650    send_eapol(hapd, addr, build_eapol(msg))
1651    # SMK M3
1652    rsn_eapol_key_set(msg, 0x2002, 0, snonce, rsne)
1653    send_eapol(hapd, addr, build_eapol(msg))
1654    # Request
1655    rsn_eapol_key_set(msg, 0x0902, 0, snonce, rsne)
1656    send_eapol(hapd, addr, build_eapol(msg))
1657    # Request
1658    rsn_eapol_key_set(msg, 0x0902, 0, snonce, rsne)
1659    tmp_kck = binascii.unhexlify('00000000000000000000000000000000')
1660    eapol_key_mic(tmp_kck, msg)
1661    send_eapol(hapd, addr, build_eapol(msg))
1662
1663    reply_eapol("2/4", hapd, addr, msg, 0x010a, snonce, rsne, kck)
1664
1665    msg = recv_eapol(hapd)
1666    if anonce != msg['rsn_key_nonce']:
1667        raise Exception("ANonce changed")
1668
1669    # Request (valic MIC)
1670    rsn_eapol_key_set(msg, 0x0902, 0, snonce, rsne)
1671    eapol_key_mic(kck, msg)
1672    send_eapol(hapd, addr, build_eapol(msg))
1673    # Request (valid MIC, replayed counter)
1674    rsn_eapol_key_set(msg, 0x0902, 0, snonce, rsne)
1675    eapol_key_mic(kck, msg)
1676    send_eapol(hapd, addr, build_eapol(msg))
1677
1678    reply_eapol("4/4", hapd, addr, msg, 0x030a, None, None, kck)
1679    hapd.wait_sta(timeout=15)
1680
1681def build_eapol_key_1_4(anonce, replay_counter=1, key_data=b'', key_len=16):
1682    msg = {}
1683    msg['version'] = 2
1684    msg['type'] = 3
1685    msg['length'] = 95 + len(key_data)
1686
1687    msg['descr_type'] = 2
1688    msg['rsn_key_info'] = 0x8a
1689    msg['rsn_key_len'] = key_len
1690    msg['rsn_replay_counter'] = struct.pack('>Q', replay_counter)
1691    msg['rsn_key_nonce'] = anonce
1692    msg['rsn_key_iv'] = binascii.unhexlify('00000000000000000000000000000000')
1693    msg['rsn_key_rsc'] = binascii.unhexlify('0000000000000000')
1694    msg['rsn_key_id'] = binascii.unhexlify('0000000000000000')
1695    msg['rsn_key_mic'] = binascii.unhexlify('00000000000000000000000000000000')
1696    msg['rsn_key_data_len'] = len(key_data)
1697    msg['rsn_key_data'] = key_data
1698    return msg
1699
1700def build_eapol_key_3_4(anonce, kck, key_data, replay_counter=2,
1701                        key_info=0x13ca, extra_len=0, descr_type=2, key_len=16):
1702    msg = {}
1703    msg['version'] = 2
1704    msg['type'] = 3
1705    msg['length'] = 95 + len(key_data) + extra_len
1706
1707    msg['descr_type'] = descr_type
1708    msg['rsn_key_info'] = key_info
1709    msg['rsn_key_len'] = key_len
1710    msg['rsn_replay_counter'] = struct.pack('>Q', replay_counter)
1711    msg['rsn_key_nonce'] = anonce
1712    msg['rsn_key_iv'] = binascii.unhexlify('00000000000000000000000000000000')
1713    msg['rsn_key_rsc'] = binascii.unhexlify('0000000000000000')
1714    msg['rsn_key_id'] = binascii.unhexlify('0000000000000000')
1715    msg['rsn_key_data_len'] = len(key_data)
1716    msg['rsn_key_data'] = key_data
1717    eapol_key_mic(kck, msg)
1718    return msg
1719
1720def aes_wrap(kek, plain):
1721    n = len(plain) // 8
1722    a = 0xa6a6a6a6a6a6a6a6
1723    enc = AES.new(kek).encrypt
1724    r = [plain[i * 8:(i + 1) * 8] for i in range(0, n)]
1725    for j in range(6):
1726        for i in range(1, n + 1):
1727            b = enc(struct.pack('>Q', a) + r[i - 1])
1728            a = struct.unpack('>Q', b[:8])[0] ^ (n * j + i)
1729            r[i - 1] = b[8:]
1730    return struct.pack('>Q', a) + b''.join(r)
1731
1732def pad_key_data(plain):
1733    pad_len = len(plain) % 8
1734    if pad_len:
1735        pad_len = 8 - pad_len
1736        plain += b'\xdd'
1737        pad_len -= 1
1738        plain += pad_len * b'\x00'
1739    return plain
1740
1741def test_ap_wpa2_psk_supp_proto(dev, apdev):
1742    """WPA2-PSK 4-way handshake protocol testing for supplicant"""
1743    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
1744
1745    # Wait for EAPOL-Key msg 1/4 from hostapd to determine when associated
1746    msg = recv_eapol(hapd)
1747    dev[0].dump_monitor()
1748
1749    # Build own EAPOL-Key msg 1/4
1750    anonce = binascii.unhexlify('2222222222222222222222222222222222222222222222222222222222222222')
1751    counter = 1
1752    msg = build_eapol_key_1_4(anonce, replay_counter=counter)
1753    counter += 1
1754    send_eapol(dev[0], bssid, build_eapol(msg))
1755    msg = recv_eapol(dev[0])
1756    snonce = msg['rsn_key_nonce']
1757
1758    (ptk, kck, kek) = pmk_to_ptk(pmk, addr, bssid, snonce, anonce)
1759
1760    logger.debug("Invalid AES wrap data length 0")
1761    dev[0].dump_monitor()
1762    msg = build_eapol_key_3_4(anonce, kck, b'', replay_counter=counter)
1763    counter += 1
1764    send_eapol(dev[0], bssid, build_eapol(msg))
1765    ev = dev[0].wait_event(["WPA: Unsupported AES-WRAP len 0"])
1766    if ev is None:
1767        raise Exception("Unsupported AES-WRAP len 0 not reported")
1768
1769    logger.debug("Invalid AES wrap data length 1")
1770    dev[0].dump_monitor()
1771    msg = build_eapol_key_3_4(anonce, kck, b'1', replay_counter=counter)
1772    counter += 1
1773    send_eapol(dev[0], bssid, build_eapol(msg))
1774    ev = dev[0].wait_event(["WPA: Unsupported AES-WRAP len 1"])
1775    if ev is None:
1776        raise Exception("Unsupported AES-WRAP len 1 not reported")
1777
1778    logger.debug("Invalid AES wrap data length 9")
1779    dev[0].dump_monitor()
1780    msg = build_eapol_key_3_4(anonce, kck, b'123456789', replay_counter=counter)
1781    counter += 1
1782    send_eapol(dev[0], bssid, build_eapol(msg))
1783    ev = dev[0].wait_event(["WPA: Unsupported AES-WRAP len 9"])
1784    if ev is None:
1785        raise Exception("Unsupported AES-WRAP len 9 not reported")
1786
1787    logger.debug("Invalid AES wrap data payload")
1788    dev[0].dump_monitor()
1789    msg = build_eapol_key_3_4(anonce, kck, b'12345678', replay_counter=counter)
1790    # do not increment counter to test replay protection
1791    send_eapol(dev[0], bssid, build_eapol(msg))
1792    ev = dev[0].wait_event(["WPA: AES unwrap failed"])
1793    if ev is None:
1794        raise Exception("AES unwrap failure not reported")
1795
1796    logger.debug("Replay Count not increasing")
1797    dev[0].dump_monitor()
1798    msg = build_eapol_key_3_4(anonce, kck, b'12345678', replay_counter=counter)
1799    counter += 1
1800    send_eapol(dev[0], bssid, build_eapol(msg))
1801    ev = dev[0].wait_event(["WPA: EAPOL-Key Replay Counter did not increase"])
1802    if ev is None:
1803        raise Exception("Replay Counter replay not reported")
1804
1805    logger.debug("Missing Ack bit in key info")
1806    dev[0].dump_monitor()
1807    msg = build_eapol_key_3_4(anonce, kck, b'12345678', replay_counter=counter,
1808                              key_info=0x134a)
1809    counter += 1
1810    send_eapol(dev[0], bssid, build_eapol(msg))
1811    ev = dev[0].wait_event(["WPA: No Ack bit in key_info"])
1812    if ev is None:
1813        raise Exception("Missing Ack bit not reported")
1814
1815    logger.debug("Unexpected Request bit in key info")
1816    dev[0].dump_monitor()
1817    msg = build_eapol_key_3_4(anonce, kck, b'12345678', replay_counter=counter,
1818                              key_info=0x1bca)
1819    counter += 1
1820    send_eapol(dev[0], bssid, build_eapol(msg))
1821    ev = dev[0].wait_event(["WPA: EAPOL-Key with Request bit"])
1822    if ev is None:
1823        raise Exception("Request bit not reported")
1824
1825    logger.debug("Unsupported key descriptor version 0")
1826    dev[0].dump_monitor()
1827    msg = build_eapol_key_3_4(anonce, kck, b'0123456789abcdef',
1828                              replay_counter=counter, key_info=0x13c8)
1829    counter += 1
1830    send_eapol(dev[0], bssid, build_eapol(msg))
1831    ev = dev[0].wait_event(["WPA: Unsupported EAPOL-Key descriptor version 0"])
1832    if ev is None:
1833        raise Exception("Unsupported EAPOL-Key descriptor version 0 not reported")
1834
1835    logger.debug("Key descriptor version 1 not allowed with CCMP")
1836    dev[0].dump_monitor()
1837    msg = build_eapol_key_3_4(anonce, kck, b'0123456789abcdef',
1838                              replay_counter=counter, key_info=0x13c9)
1839    counter += 1
1840    send_eapol(dev[0], bssid, build_eapol(msg))
1841    ev = dev[0].wait_event(["WPA: CCMP is used, but EAPOL-Key descriptor version (1) is not 2"])
1842    if ev is None:
1843        raise Exception("Not allowed EAPOL-Key descriptor version not reported")
1844
1845    logger.debug("Invalid AES wrap payload with key descriptor version 2")
1846    dev[0].dump_monitor()
1847    msg = build_eapol_key_3_4(anonce, kck, b'0123456789abcdef',
1848                              replay_counter=counter, key_info=0x13ca)
1849    counter += 1
1850    send_eapol(dev[0], bssid, build_eapol(msg))
1851    ev = dev[0].wait_event(["WPA: AES unwrap failed"])
1852    if ev is None:
1853        raise Exception("AES unwrap failure not reported")
1854
1855    logger.debug("Key descriptor version 3 workaround")
1856    dev[0].dump_monitor()
1857    msg = build_eapol_key_3_4(anonce, kck, b'0123456789abcdef',
1858                              replay_counter=counter, key_info=0x13cb)
1859    counter += 1
1860    send_eapol(dev[0], bssid, build_eapol(msg))
1861    ev = dev[0].wait_event(["WPA: CCMP is used, but EAPOL-Key descriptor version (3) is not 2"])
1862    if ev is None:
1863        raise Exception("CCMP key descriptor mismatch not reported")
1864    ev = dev[0].wait_event(["WPA: Interoperability workaround"])
1865    if ev is None:
1866        raise Exception("AES-128-CMAC workaround not reported")
1867    ev = dev[0].wait_event(["WPA: Invalid EAPOL-Key MIC - dropping packet"])
1868    if ev is None:
1869        raise Exception("MIC failure with AES-128-CMAC workaround not reported")
1870
1871    logger.debug("Unsupported key descriptor version 4")
1872    dev[0].dump_monitor()
1873    msg = build_eapol_key_3_4(anonce, kck, b'0123456789abcdef',
1874                              replay_counter=counter, key_info=0x13cc)
1875    counter += 1
1876    send_eapol(dev[0], bssid, build_eapol(msg))
1877    ev = dev[0].wait_event(["WPA: Unsupported EAPOL-Key descriptor version 4"])
1878    if ev is None:
1879        raise Exception("Unsupported EAPOL-Key descriptor version 4 not reported")
1880
1881    logger.debug("Unsupported key descriptor version 7")
1882    dev[0].dump_monitor()
1883    msg = build_eapol_key_3_4(anonce, kck, b'0123456789abcdef',
1884                              replay_counter=counter, key_info=0x13cf)
1885    counter += 1
1886    send_eapol(dev[0], bssid, build_eapol(msg))
1887    ev = dev[0].wait_event(["WPA: Unsupported EAPOL-Key descriptor version 7"])
1888    if ev is None:
1889        raise Exception("Unsupported EAPOL-Key descriptor version 7 not reported")
1890
1891    logger.debug("Too short EAPOL header length")
1892    dev[0].dump_monitor()
1893    msg = build_eapol_key_3_4(anonce, kck, b'12345678', replay_counter=counter,
1894                              extra_len=-1)
1895    counter += 1
1896    send_eapol(dev[0], bssid, build_eapol(msg))
1897    ev = dev[0].wait_event(["WPA: Invalid EAPOL-Key frame - key_data overflow (8 > 7)"])
1898    if ev is None:
1899        raise Exception("Key data overflow not reported")
1900
1901    logger.debug("Too long EAPOL header length")
1902    msg = build_eapol_key_3_4(anonce, kck, b'12345678', replay_counter=counter,
1903                              extra_len=1)
1904    counter += 1
1905    send_eapol(dev[0], bssid, build_eapol(msg))
1906
1907    logger.debug("Unsupported descriptor type 0")
1908    msg = build_eapol_key_3_4(anonce, kck, b'12345678', replay_counter=counter,
1909                              descr_type=0)
1910    counter += 1
1911    send_eapol(dev[0], bssid, build_eapol(msg))
1912
1913    logger.debug("WPA descriptor type 0")
1914    msg = build_eapol_key_3_4(anonce, kck, b'12345678', replay_counter=counter,
1915                              descr_type=254)
1916    counter += 1
1917    send_eapol(dev[0], bssid, build_eapol(msg))
1918
1919    logger.debug("Non-zero key index for pairwise key")
1920    dev[0].dump_monitor()
1921    wrapped = aes_wrap(kek, 16*b'z')
1922    msg = build_eapol_key_3_4(anonce, kck, wrapped, replay_counter=counter,
1923                              key_info=0x13ea)
1924    counter += 1
1925    send_eapol(dev[0], bssid, build_eapol(msg))
1926    ev = dev[0].wait_event(["WPA: Ignored EAPOL-Key (Pairwise) with non-zero key index"])
1927    if ev is None:
1928        raise Exception("Non-zero key index not reported")
1929
1930    logger.debug("Invalid Key Data plaintext payload --> disconnect")
1931    dev[0].dump_monitor()
1932    wrapped = aes_wrap(kek, 16*b'z')
1933    msg = build_eapol_key_3_4(anonce, kck, wrapped, replay_counter=counter)
1934    counter += 1
1935    send_eapol(dev[0], bssid, build_eapol(msg))
1936    dev[0].wait_disconnected(timeout=1)
1937
1938def test_ap_wpa2_psk_supp_proto_no_ie(dev, apdev):
1939    """WPA2-PSK supplicant protocol testing: IE not included"""
1940    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
1941
1942    # Wait for EAPOL-Key msg 1/4 from hostapd to determine when associated
1943    msg = recv_eapol(hapd)
1944    dev[0].dump_monitor()
1945
1946    # Build own EAPOL-Key msg 1/4
1947    anonce = binascii.unhexlify('2222222222222222222222222222222222222222222222222222222222222222')
1948    counter = 1
1949    msg = build_eapol_key_1_4(anonce, replay_counter=counter)
1950    counter += 1
1951    send_eapol(dev[0], bssid, build_eapol(msg))
1952    msg = recv_eapol(dev[0])
1953    snonce = msg['rsn_key_nonce']
1954
1955    (ptk, kck, kek) = pmk_to_ptk(pmk, addr, bssid, snonce, anonce)
1956
1957    logger.debug("No IEs in msg 3/4 --> disconnect")
1958    dev[0].dump_monitor()
1959    wrapped = aes_wrap(kek, 16*b'\x00')
1960    msg = build_eapol_key_3_4(anonce, kck, wrapped, replay_counter=counter)
1961    counter += 1
1962    send_eapol(dev[0], bssid, build_eapol(msg))
1963    dev[0].wait_disconnected(timeout=1)
1964
1965def test_ap_wpa2_psk_supp_proto_ie_mismatch(dev, apdev):
1966    """WPA2-PSK supplicant protocol testing: IE mismatch"""
1967    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
1968
1969    # Wait for EAPOL-Key msg 1/4 from hostapd to determine when associated
1970    msg = recv_eapol(hapd)
1971    dev[0].dump_monitor()
1972
1973    # Build own EAPOL-Key msg 1/4
1974    anonce = binascii.unhexlify('2222222222222222222222222222222222222222222222222222222222222222')
1975    counter = 1
1976    msg = build_eapol_key_1_4(anonce, replay_counter=counter)
1977    counter += 1
1978    send_eapol(dev[0], bssid, build_eapol(msg))
1979    msg = recv_eapol(dev[0])
1980    snonce = msg['rsn_key_nonce']
1981
1982    (ptk, kck, kek) = pmk_to_ptk(pmk, addr, bssid, snonce, anonce)
1983
1984    logger.debug("Msg 3/4 with mismatching IE")
1985    dev[0].dump_monitor()
1986    wrapped = aes_wrap(kek, pad_key_data(binascii.unhexlify('30060100000fac04dd16000fac010100dc11188831bf4aa4a8678d2b41498618')))
1987    msg = build_eapol_key_3_4(anonce, kck, wrapped, replay_counter=counter)
1988    counter += 1
1989    send_eapol(dev[0], bssid, build_eapol(msg))
1990    dev[0].wait_disconnected(timeout=1)
1991
1992def test_ap_wpa2_psk_supp_proto_ok(dev, apdev):
1993    """WPA2-PSK supplicant protocol testing: success"""
1994    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
1995
1996    # Wait for EAPOL-Key msg 1/4 from hostapd to determine when associated
1997    msg = recv_eapol(hapd)
1998    dev[0].dump_monitor()
1999
2000    # Build own EAPOL-Key msg 1/4
2001    anonce = binascii.unhexlify('2222222222222222222222222222222222222222222222222222222222222222')
2002    counter = 1
2003    msg = build_eapol_key_1_4(anonce, replay_counter=counter)
2004    counter += 1
2005    send_eapol(dev[0], bssid, build_eapol(msg))
2006    msg = recv_eapol(dev[0])
2007    snonce = msg['rsn_key_nonce']
2008
2009    (ptk, kck, kek) = pmk_to_ptk(pmk, addr, bssid, snonce, anonce)
2010
2011    logger.debug("Valid EAPOL-Key msg 3/4")
2012    dev[0].dump_monitor()
2013    plain = binascii.unhexlify('30140100000fac040100000fac040100000fac020c00dd16000fac010100dc11188831bf4aa4a8678d2b41498618')
2014    wrapped = aes_wrap(kek, pad_key_data(plain))
2015    msg = build_eapol_key_3_4(anonce, kck, wrapped, replay_counter=counter)
2016    counter += 1
2017    send_eapol(dev[0], bssid, build_eapol(msg))
2018    dev[0].wait_connected(timeout=1)
2019
2020def test_ap_wpa2_psk_supp_proto_no_gtk(dev, apdev):
2021    """WPA2-PSK supplicant protocol testing: no GTK"""
2022    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
2023
2024    # Wait for EAPOL-Key msg 1/4 from hostapd to determine when associated
2025    msg = recv_eapol(hapd)
2026    dev[0].dump_monitor()
2027
2028    # Build own EAPOL-Key msg 1/4
2029    anonce = binascii.unhexlify('2222222222222222222222222222222222222222222222222222222222222222')
2030    counter = 1
2031    msg = build_eapol_key_1_4(anonce, replay_counter=counter)
2032    counter += 1
2033    send_eapol(dev[0], bssid, build_eapol(msg))
2034    msg = recv_eapol(dev[0])
2035    snonce = msg['rsn_key_nonce']
2036
2037    (ptk, kck, kek) = pmk_to_ptk(pmk, addr, bssid, snonce, anonce)
2038
2039    logger.debug("EAPOL-Key msg 3/4 without GTK KDE")
2040    dev[0].dump_monitor()
2041    plain = binascii.unhexlify('30140100000fac040100000fac040100000fac020c00')
2042    wrapped = aes_wrap(kek, pad_key_data(plain))
2043    msg = build_eapol_key_3_4(anonce, kck, wrapped, replay_counter=counter)
2044    counter += 1
2045    send_eapol(dev[0], bssid, build_eapol(msg))
2046    ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=0.1)
2047    if ev is not None:
2048        raise Exception("Unexpected connection completion reported")
2049
2050def test_ap_wpa2_psk_supp_proto_anonce_change(dev, apdev):
2051    """WPA2-PSK supplicant protocol testing: ANonce change"""
2052    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
2053
2054    # Wait for EAPOL-Key msg 1/4 from hostapd to determine when associated
2055    msg = recv_eapol(hapd)
2056    dev[0].dump_monitor()
2057
2058    # Build own EAPOL-Key msg 1/4
2059    anonce = binascii.unhexlify('2222222222222222222222222222222222222222222222222222222222222222')
2060    counter = 1
2061    msg = build_eapol_key_1_4(anonce, replay_counter=counter)
2062    counter += 1
2063    send_eapol(dev[0], bssid, build_eapol(msg))
2064    msg = recv_eapol(dev[0])
2065    snonce = msg['rsn_key_nonce']
2066
2067    (ptk, kck, kek) = pmk_to_ptk(pmk, addr, bssid, snonce, anonce)
2068
2069    logger.debug("Valid EAPOL-Key msg 3/4")
2070    dev[0].dump_monitor()
2071    anonce2 = binascii.unhexlify('3333333333333333333333333333333333333333333333333333333333333333')
2072    plain = binascii.unhexlify('30140100000fac040100000fac040100000fac020c00dd16000fac010100dc11188831bf4aa4a8678d2b41498618')
2073    wrapped = aes_wrap(kek, pad_key_data(plain))
2074    msg = build_eapol_key_3_4(anonce2, kck, wrapped, replay_counter=counter)
2075    counter += 1
2076    send_eapol(dev[0], bssid, build_eapol(msg))
2077    ev = dev[0].wait_event(["WPA: ANonce from message 1 of 4-Way Handshake differs from 3 of 4-Way Handshake"])
2078    if ev is None:
2079        raise Exception("ANonce change not reported")
2080
2081def test_ap_wpa2_psk_supp_proto_unexpected_group_msg(dev, apdev):
2082    """WPA2-PSK supplicant protocol testing: unexpected group message"""
2083    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
2084
2085    # Wait for EAPOL-Key msg 1/4 from hostapd to determine when associated
2086    msg = recv_eapol(hapd)
2087    dev[0].dump_monitor()
2088
2089    # Build own EAPOL-Key msg 1/4
2090    anonce = binascii.unhexlify('2222222222222222222222222222222222222222222222222222222222222222')
2091    counter = 1
2092    msg = build_eapol_key_1_4(anonce, replay_counter=counter)
2093    counter += 1
2094    send_eapol(dev[0], bssid, build_eapol(msg))
2095    msg = recv_eapol(dev[0])
2096    snonce = msg['rsn_key_nonce']
2097
2098    (ptk, kck, kek) = pmk_to_ptk(pmk, addr, bssid, snonce, anonce)
2099
2100    logger.debug("Group key 1/2 instead of msg 3/4")
2101    dev[0].dump_monitor()
2102    wrapped = aes_wrap(kek, binascii.unhexlify('dd16000fac010100dc11188831bf4aa4a8678d2b41498618'))
2103    msg = build_eapol_key_3_4(anonce, kck, wrapped, replay_counter=counter,
2104                              key_info=0x13c2)
2105    counter += 1
2106    send_eapol(dev[0], bssid, build_eapol(msg))
2107    ev = dev[0].wait_event(["WPA: Group Key Handshake started prior to completion of 4-way handshake"])
2108    if ev is None:
2109        raise Exception("Unexpected group key message not reported")
2110    dev[0].wait_disconnected(timeout=1)
2111
2112@remote_compatible
2113def test_ap_wpa2_psk_supp_proto_msg_1_invalid_kde(dev, apdev):
2114    """WPA2-PSK supplicant protocol testing: invalid KDE in msg 1/4"""
2115    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
2116
2117    # Wait for EAPOL-Key msg 1/4 from hostapd to determine when associated
2118    msg = recv_eapol(hapd)
2119    dev[0].dump_monitor()
2120
2121    # Build own EAPOL-Key msg 1/4 with invalid KDE
2122    anonce = binascii.unhexlify('2222222222222222222222222222222222222222222222222222222222222222')
2123    counter = 1
2124    msg = build_eapol_key_1_4(anonce, replay_counter=counter,
2125                              key_data=binascii.unhexlify('5555'))
2126    counter += 1
2127    send_eapol(dev[0], bssid, build_eapol(msg))
2128    dev[0].wait_disconnected(timeout=1)
2129
2130def test_ap_wpa2_psk_supp_proto_wrong_pairwise_key_len(dev, apdev):
2131    """WPA2-PSK supplicant protocol testing: wrong pairwise key length"""
2132    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
2133
2134    # Wait for EAPOL-Key msg 1/4 from hostapd to determine when associated
2135    msg = recv_eapol(hapd)
2136    dev[0].dump_monitor()
2137
2138    # Build own EAPOL-Key msg 1/4
2139    anonce = binascii.unhexlify('2222222222222222222222222222222222222222222222222222222222222222')
2140    counter = 1
2141    msg = build_eapol_key_1_4(anonce, replay_counter=counter)
2142    counter += 1
2143    send_eapol(dev[0], bssid, build_eapol(msg))
2144    msg = recv_eapol(dev[0])
2145    snonce = msg['rsn_key_nonce']
2146
2147    (ptk, kck, kek) = pmk_to_ptk(pmk, addr, bssid, snonce, anonce)
2148
2149    logger.debug("Valid EAPOL-Key msg 3/4")
2150    dev[0].dump_monitor()
2151    plain = binascii.unhexlify('30140100000fac040100000fac040100000fac020c00dd16000fac010100dc11188831bf4aa4a8678d2b41498618')
2152    wrapped = aes_wrap(kek, pad_key_data(plain))
2153    msg = build_eapol_key_3_4(anonce, kck, wrapped, replay_counter=counter,
2154                              key_len=15)
2155    counter += 1
2156    send_eapol(dev[0], bssid, build_eapol(msg))
2157    ev = dev[0].wait_event(["WPA: Invalid CCMP key length 15"])
2158    if ev is None:
2159        raise Exception("Invalid CCMP key length not reported")
2160    dev[0].wait_disconnected(timeout=1)
2161
2162def test_ap_wpa2_psk_supp_proto_wrong_group_key_len(dev, apdev):
2163    """WPA2-PSK supplicant protocol testing: wrong group key length"""
2164    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
2165
2166    # Wait for EAPOL-Key msg 1/4 from hostapd to determine when associated
2167    msg = recv_eapol(hapd)
2168    dev[0].dump_monitor()
2169
2170    # Build own EAPOL-Key msg 1/4
2171    anonce = binascii.unhexlify('2222222222222222222222222222222222222222222222222222222222222222')
2172    counter = 1
2173    msg = build_eapol_key_1_4(anonce, replay_counter=counter)
2174    counter += 1
2175    send_eapol(dev[0], bssid, build_eapol(msg))
2176    msg = recv_eapol(dev[0])
2177    snonce = msg['rsn_key_nonce']
2178
2179    (ptk, kck, kek) = pmk_to_ptk(pmk, addr, bssid, snonce, anonce)
2180
2181    logger.debug("Valid EAPOL-Key msg 3/4")
2182    dev[0].dump_monitor()
2183    plain = binascii.unhexlify('30140100000fac040100000fac040100000fac020c00dd15000fac010100dc11188831bf4aa4a8678d2b414986')
2184    wrapped = aes_wrap(kek, pad_key_data(plain))
2185    msg = build_eapol_key_3_4(anonce, kck, wrapped, replay_counter=counter)
2186    counter += 1
2187    send_eapol(dev[0], bssid, build_eapol(msg))
2188    ev = dev[0].wait_event(["WPA: Unsupported CCMP Group Cipher key length 15"])
2189    if ev is None:
2190        raise Exception("Invalid CCMP key length not reported")
2191    dev[0].wait_disconnected(timeout=1)
2192
2193def test_ap_wpa2_psk_supp_proto_gtk_tx_bit_workaround(dev, apdev):
2194    """WPA2-PSK supplicant protocol testing: GTK TX bit workaround"""
2195    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
2196
2197    # Wait for EAPOL-Key msg 1/4 from hostapd to determine when associated
2198    msg = recv_eapol(hapd)
2199    dev[0].dump_monitor()
2200
2201    # Build own EAPOL-Key msg 1/4
2202    anonce = binascii.unhexlify('2222222222222222222222222222222222222222222222222222222222222222')
2203    counter = 1
2204    msg = build_eapol_key_1_4(anonce, replay_counter=counter)
2205    counter += 1
2206    send_eapol(dev[0], bssid, build_eapol(msg))
2207    msg = recv_eapol(dev[0])
2208    snonce = msg['rsn_key_nonce']
2209
2210    (ptk, kck, kek) = pmk_to_ptk(pmk, addr, bssid, snonce, anonce)
2211
2212    logger.debug("Valid EAPOL-Key msg 3/4")
2213    dev[0].dump_monitor()
2214    plain = binascii.unhexlify('30140100000fac040100000fac040100000fac020c00dd16000fac010500dc11188831bf4aa4a8678d2b41498618')
2215    wrapped = aes_wrap(kek, pad_key_data(plain))
2216    msg = build_eapol_key_3_4(anonce, kck, wrapped, replay_counter=counter)
2217    counter += 1
2218    send_eapol(dev[0], bssid, build_eapol(msg))
2219    ev = dev[0].wait_event(["WPA: Tx bit set for GTK, but pairwise keys are used - ignore Tx bit"])
2220    if ev is None:
2221        raise Exception("GTK Tx bit workaround not reported")
2222    dev[0].wait_connected(timeout=1)
2223
2224def test_ap_wpa2_psk_supp_proto_gtk_keyidx_0_and_3(dev, apdev):
2225    """WPA2-PSK supplicant protocol testing: GTK key index 0 and 3"""
2226    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
2227
2228    # Wait for EAPOL-Key msg 1/4 from hostapd to determine when associated
2229    msg = recv_eapol(hapd)
2230    dev[0].dump_monitor()
2231
2232    # Build own EAPOL-Key msg 1/4
2233    anonce = binascii.unhexlify('2222222222222222222222222222222222222222222222222222222222222222')
2234    counter = 1
2235    msg = build_eapol_key_1_4(anonce, replay_counter=counter)
2236    counter += 1
2237    send_eapol(dev[0], bssid, build_eapol(msg))
2238    msg = recv_eapol(dev[0])
2239    snonce = msg['rsn_key_nonce']
2240
2241    (ptk, kck, kek) = pmk_to_ptk(pmk, addr, bssid, snonce, anonce)
2242
2243    logger.debug("Valid EAPOL-Key msg 3/4 (GTK keyidx 0)")
2244    dev[0].dump_monitor()
2245    plain = binascii.unhexlify('30140100000fac040100000fac040100000fac020c00dd16000fac010000dc11188831bf4aa4a8678d2b41498618')
2246    wrapped = aes_wrap(kek, pad_key_data(plain))
2247    msg = build_eapol_key_3_4(anonce, kck, wrapped, replay_counter=counter)
2248    counter += 1
2249    send_eapol(dev[0], bssid, build_eapol(msg))
2250    dev[0].wait_connected(timeout=1)
2251
2252    logger.debug("Valid EAPOL-Key group msg 1/2 (GTK keyidx 3)")
2253    dev[0].dump_monitor()
2254    plain = binascii.unhexlify('dd16000fac010300dc11188831bf4aa4a8678d2b41498618')
2255    wrapped = aes_wrap(kek, pad_key_data(plain))
2256    msg = build_eapol_key_3_4(anonce, kck, wrapped, replay_counter=counter,
2257                              key_info=0x13c2)
2258    counter += 1
2259    send_eapol(dev[0], bssid, build_eapol(msg))
2260    msg = recv_eapol(dev[0])
2261    ev = dev[0].wait_event(["WPA: Group rekeying completed"])
2262    if ev is None:
2263        raise Exception("GTK rekeing not reported")
2264
2265    logger.debug("Unencrypted GTK KDE in group msg 1/2")
2266    dev[0].dump_monitor()
2267    plain = binascii.unhexlify('dd16000fac010300dc11188831bf4aa4a8678d2b41498618')
2268    msg = build_eapol_key_3_4(anonce, kck, plain, replay_counter=counter,
2269                              key_info=0x03c2)
2270    counter += 1
2271    send_eapol(dev[0], bssid, build_eapol(msg))
2272    ev = dev[0].wait_event(["WPA: GTK IE in unencrypted key data"])
2273    if ev is None:
2274        raise Exception("Unencrypted GTK KDE not reported")
2275    dev[0].wait_disconnected(timeout=1)
2276
2277def test_ap_wpa2_psk_supp_proto_no_gtk_in_group_msg(dev, apdev):
2278    """WPA2-PSK supplicant protocol testing: GTK KDE missing from group msg"""
2279    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
2280
2281    # Wait for EAPOL-Key msg 1/4 from hostapd to determine when associated
2282    msg = recv_eapol(hapd)
2283    dev[0].dump_monitor()
2284
2285    # Build own EAPOL-Key msg 1/4
2286    anonce = binascii.unhexlify('2222222222222222222222222222222222222222222222222222222222222222')
2287    counter = 1
2288    msg = build_eapol_key_1_4(anonce, replay_counter=counter)
2289    counter += 1
2290    send_eapol(dev[0], bssid, build_eapol(msg))
2291    msg = recv_eapol(dev[0])
2292    snonce = msg['rsn_key_nonce']
2293
2294    (ptk, kck, kek) = pmk_to_ptk(pmk, addr, bssid, snonce, anonce)
2295
2296    logger.debug("Valid EAPOL-Key msg 3/4 (GTK keyidx 0)")
2297    dev[0].dump_monitor()
2298    plain = binascii.unhexlify('30140100000fac040100000fac040100000fac020c00dd16000fac010000dc11188831bf4aa4a8678d2b41498618')
2299    wrapped = aes_wrap(kek, pad_key_data(plain))
2300    msg = build_eapol_key_3_4(anonce, kck, wrapped, replay_counter=counter)
2301    counter += 1
2302    send_eapol(dev[0], bssid, build_eapol(msg))
2303    dev[0].wait_connected(timeout=1)
2304
2305    logger.debug("No GTK KDE in EAPOL-Key group msg 1/2")
2306    dev[0].dump_monitor()
2307    plain = binascii.unhexlify('dd00dd00dd00dd00dd00dd00dd00dd00')
2308    wrapped = aes_wrap(kek, pad_key_data(plain))
2309    msg = build_eapol_key_3_4(anonce, kck, wrapped, replay_counter=counter,
2310                              key_info=0x13c2)
2311    counter += 1
2312    send_eapol(dev[0], bssid, build_eapol(msg))
2313    ev = dev[0].wait_event(["WPA: No GTK IE in Group Key msg 1/2"])
2314    if ev is None:
2315        raise Exception("Missing GTK KDE not reported")
2316    dev[0].wait_disconnected(timeout=1)
2317
2318def test_ap_wpa2_psk_supp_proto_too_long_gtk_in_group_msg(dev, apdev):
2319    """WPA2-PSK supplicant protocol testing: too long GTK KDE in group msg"""
2320    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
2321
2322    # Wait for EAPOL-Key msg 1/4 from hostapd to determine when associated
2323    msg = recv_eapol(hapd)
2324    dev[0].dump_monitor()
2325
2326    # Build own EAPOL-Key msg 1/4
2327    anonce = binascii.unhexlify('2222222222222222222222222222222222222222222222222222222222222222')
2328    counter = 1
2329    msg = build_eapol_key_1_4(anonce, replay_counter=counter)
2330    counter += 1
2331    send_eapol(dev[0], bssid, build_eapol(msg))
2332    msg = recv_eapol(dev[0])
2333    snonce = msg['rsn_key_nonce']
2334
2335    (ptk, kck, kek) = pmk_to_ptk(pmk, addr, bssid, snonce, anonce)
2336
2337    logger.debug("Valid EAPOL-Key msg 3/4 (GTK keyidx 0)")
2338    dev[0].dump_monitor()
2339    plain = binascii.unhexlify('30140100000fac040100000fac040100000fac020c00dd16000fac010000dc11188831bf4aa4a8678d2b41498618')
2340    wrapped = aes_wrap(kek, pad_key_data(plain))
2341    msg = build_eapol_key_3_4(anonce, kck, wrapped, replay_counter=counter)
2342    counter += 1
2343    send_eapol(dev[0], bssid, build_eapol(msg))
2344    dev[0].wait_connected(timeout=1)
2345
2346    logger.debug("EAPOL-Key group msg 1/2 with too long GTK KDE")
2347    dev[0].dump_monitor()
2348    plain = binascii.unhexlify('dd27000fac010100ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff')
2349    wrapped = aes_wrap(kek, pad_key_data(plain))
2350    msg = build_eapol_key_3_4(anonce, kck, wrapped, replay_counter=counter,
2351                              key_info=0x13c2)
2352    counter += 1
2353    send_eapol(dev[0], bssid, build_eapol(msg))
2354    ev = dev[0].wait_event(["WPA: Unsupported CCMP Group Cipher key length 33",
2355                            "RSN: Too long GTK in GTK KDE (len=33)"])
2356    if ev is None:
2357        raise Exception("Too long GTK KDE not reported")
2358    dev[0].wait_disconnected(timeout=1)
2359
2360def test_ap_wpa2_psk_supp_proto_too_long_gtk_kde(dev, apdev):
2361    """WPA2-PSK supplicant protocol testing: too long GTK KDE"""
2362    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
2363
2364    # Wait for EAPOL-Key msg 1/4 from hostapd to determine when associated
2365    msg = recv_eapol(hapd)
2366    dev[0].dump_monitor()
2367
2368    # Build own EAPOL-Key msg 1/4
2369    anonce = binascii.unhexlify('2222222222222222222222222222222222222222222222222222222222222222')
2370    counter = 1
2371    msg = build_eapol_key_1_4(anonce, replay_counter=counter)
2372    counter += 1
2373    send_eapol(dev[0], bssid, build_eapol(msg))
2374    msg = recv_eapol(dev[0])
2375    snonce = msg['rsn_key_nonce']
2376
2377    (ptk, kck, kek) = pmk_to_ptk(pmk, addr, bssid, snonce, anonce)
2378
2379    logger.debug("EAPOL-Key msg 3/4 with too short GTK KDE")
2380    dev[0].dump_monitor()
2381    plain = binascii.unhexlify('30140100000fac040100000fac040100000fac020c00dd27000fac010100ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff')
2382    wrapped = aes_wrap(kek, pad_key_data(plain))
2383    msg = build_eapol_key_3_4(anonce, kck, wrapped, replay_counter=counter)
2384    counter += 1
2385    send_eapol(dev[0], bssid, build_eapol(msg))
2386    dev[0].wait_disconnected(timeout=1)
2387
2388def test_ap_wpa2_psk_supp_proto_gtk_not_encrypted(dev, apdev):
2389    """WPA2-PSK supplicant protocol testing: GTK KDE not encrypted"""
2390    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
2391
2392    # Wait for EAPOL-Key msg 1/4 from hostapd to determine when associated
2393    msg = recv_eapol(hapd)
2394    dev[0].dump_monitor()
2395
2396    # Build own EAPOL-Key msg 1/4
2397    anonce = binascii.unhexlify('2222222222222222222222222222222222222222222222222222222222222222')
2398    counter = 1
2399    msg = build_eapol_key_1_4(anonce, replay_counter=counter)
2400    counter += 1
2401    send_eapol(dev[0], bssid, build_eapol(msg))
2402    msg = recv_eapol(dev[0])
2403    snonce = msg['rsn_key_nonce']
2404
2405    (ptk, kck, kek) = pmk_to_ptk(pmk, addr, bssid, snonce, anonce)
2406
2407    logger.debug("Valid EAPOL-Key msg 3/4")
2408    dev[0].dump_monitor()
2409    plain = binascii.unhexlify('30140100000fac040100000fac040100000fac020c00dd16000fac010100dc11188831bf4aa4a8678d2b41498618')
2410    msg = build_eapol_key_3_4(anonce, kck, plain, replay_counter=counter,
2411                              key_info=0x03ca)
2412    counter += 1
2413    send_eapol(dev[0], bssid, build_eapol(msg))
2414    ev = dev[0].wait_event(["WPA: GTK IE in unencrypted key data"])
2415    if ev is None:
2416        raise Exception("Unencrypted GTK KDE not reported")
2417    dev[0].wait_disconnected(timeout=1)
2418
2419def run_psk_supp_proto_pmf2(dev, apdev, igtk_kde=None, fail=False):
2420    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0],
2421                                                              ieee80211w=2)
2422
2423    # Wait for EAPOL-Key msg 1/4 from hostapd to determine when associated
2424    msg = recv_eapol(hapd)
2425    dev[0].dump_monitor()
2426
2427    # Build own EAPOL-Key msg 1/4
2428    anonce = binascii.unhexlify('2222222222222222222222222222222222222222222222222222222222222222')
2429    counter = 1
2430    msg = build_eapol_key_1_4(anonce, replay_counter=counter)
2431    counter += 1
2432    send_eapol(dev[0], bssid, build_eapol(msg))
2433    msg = recv_eapol(dev[0])
2434    snonce = msg['rsn_key_nonce']
2435
2436    (ptk, kck, kek) = pmk_to_ptk(pmk, addr, bssid, snonce, anonce)
2437
2438    logger.debug("EAPOL-Key msg 3/4")
2439    dev[0].dump_monitor()
2440    gtk_kde = binascii.unhexlify('dd16000fac010100dc11188831bf4aa4a8678d2b41498618')
2441    plain = rsne + gtk_kde
2442    if igtk_kde:
2443        plain += igtk_kde
2444    wrapped = aes_wrap(kek, pad_key_data(plain))
2445    msg = build_eapol_key_3_4(anonce, kck, wrapped, replay_counter=counter)
2446    counter += 1
2447    send_eapol(dev[0], bssid, build_eapol(msg))
2448    if fail:
2449        dev[0].wait_disconnected(timeout=1)
2450        return
2451
2452    dev[0].wait_connected(timeout=1)
2453
2454    # Verify that an unprotected broadcast Deauthentication frame is ignored
2455    bssid = binascii.unhexlify(hapd.own_addr().replace(':', ''))
2456    sock = start_monitor(apdev[1]["ifname"])
2457    radiotap = radiotap_build()
2458    frame = binascii.unhexlify("c0003a01")
2459    frame += 6*b'\xff' + bssid + bssid
2460    frame += binascii.unhexlify("1000" + "0300")
2461    sock.send(radiotap + frame)
2462    # And same with incorrect BIP protection
2463    for keyid in ["0400", "0500", "0600", "0004", "0005", "0006", "ffff"]:
2464        frame2 = frame + binascii.unhexlify("4c10" + keyid + "010000000000c0e5ca5f2b3b4de9")
2465        sock.send(radiotap + frame2)
2466    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=0.5)
2467    if ev is not None:
2468        raise Exception("Unexpected disconnection")
2469
2470def run_psk_supp_proto_pmf(dev, apdev, igtk_kde=None, fail=False):
2471    try:
2472        run_psk_supp_proto_pmf2(dev, apdev, igtk_kde=igtk_kde, fail=fail)
2473    finally:
2474        stop_monitor(apdev[1]["ifname"])
2475
2476def test_ap_wpa2_psk_supp_proto_no_igtk(dev, apdev):
2477    """WPA2-PSK supplicant protocol testing: no IGTK KDE"""
2478    run_psk_supp_proto_pmf(dev, apdev, igtk_kde=None)
2479
2480def test_ap_wpa2_psk_supp_proto_igtk_ok(dev, apdev):
2481    """WPA2-PSK supplicant protocol testing: valid IGTK KDE"""
2482    igtk_kde = binascii.unhexlify('dd1c' + '000fac09' + '0400' + 6*'00' + 16*'77')
2483    run_psk_supp_proto_pmf(dev, apdev, igtk_kde=igtk_kde)
2484
2485def test_ap_wpa2_psk_supp_proto_igtk_keyid_swap(dev, apdev):
2486    """WPA2-PSK supplicant protocol testing: swapped IGTK KeyID"""
2487    igtk_kde = binascii.unhexlify('dd1c' + '000fac09' + '0004' + 6*'00' + 16*'77')
2488    run_psk_supp_proto_pmf(dev, apdev, igtk_kde=igtk_kde)
2489
2490def test_ap_wpa2_psk_supp_proto_igtk_keyid_too_large(dev, apdev):
2491    """WPA2-PSK supplicant protocol testing: too large IGTK KeyID"""
2492    igtk_kde = binascii.unhexlify('dd1c' + '000fac09' + 'ffff' + 6*'00' + 16*'77')
2493    run_psk_supp_proto_pmf(dev, apdev, igtk_kde=igtk_kde, fail=True)
2494
2495def test_ap_wpa2_psk_supp_proto_igtk_keyid_unexpected(dev, apdev):
2496    """WPA2-PSK supplicant protocol testing: unexpected IGTK KeyID"""
2497    igtk_kde = binascii.unhexlify('dd1c' + '000fac09' + '0006' + 6*'00' + 16*'77')
2498    run_psk_supp_proto_pmf(dev, apdev, igtk_kde=igtk_kde, fail=True)
2499
2500def find_wpas_process(dev):
2501    ifname = dev.ifname
2502    err, data = dev.cmd_execute(['ps', 'ax'])
2503    for l in data.splitlines():
2504        if "wpa_supplicant" not in l:
2505            continue
2506        if "-i" + ifname not in l:
2507            continue
2508        return int(l.strip().split(' ')[0])
2509    raise Exception("Could not find wpa_supplicant process")
2510
2511def read_process_memory(pid, key=None):
2512    buf = bytes()
2513    logger.info("Reading process memory (pid=%d)" % pid)
2514    with open('/proc/%d/maps' % pid, 'r') as maps, \
2515         open('/proc/%d/mem' % pid, 'rb') as mem:
2516        for l in maps.readlines():
2517            m = re.match(r'([0-9a-f]+)-([0-9a-f]+) ([-r][-w][-x][-p])', l)
2518            if not m:
2519                continue
2520            start = int(m.group(1), 16)
2521            end = int(m.group(2), 16)
2522            perm = m.group(3)
2523            if start > 0xffffffffffff:
2524                continue
2525            if end < start:
2526                continue
2527            if not perm.startswith('rw'):
2528                continue
2529            for name in ["[heap]", "[stack]"]:
2530                if name in l:
2531                    logger.info("%s 0x%x-0x%x is at %d-%d" % (name, start, end, len(buf), len(buf) + (end - start)))
2532            mem.seek(start)
2533            data = mem.read(end - start)
2534            buf += data
2535            if key and key in data:
2536                logger.info("Key found in " + l)
2537    logger.info("Total process memory read: %d bytes" % len(buf))
2538    return buf
2539
2540def verify_not_present(buf, key, fname, keyname):
2541    pos = buf.find(key)
2542    if pos < 0:
2543        return
2544
2545    prefix = 2048 if pos > 2048 else pos
2546    with open(fname + keyname, 'wb') as f:
2547        f.write(buf[pos - prefix:pos + 2048])
2548    raise Exception(keyname + " found after disassociation")
2549
2550def get_key_locations(buf, key, keyname):
2551    count = 0
2552    pos = 0
2553    while True:
2554        pos = buf.find(key, pos)
2555        if pos < 0:
2556            break
2557        logger.info("Found %s at %d" % (keyname, pos))
2558        context = 128
2559        start = pos - context if pos > context else 0
2560        before = binascii.hexlify(buf[start:pos])
2561        context += len(key)
2562        end = pos + context if pos < len(buf) - context else len(buf) - context
2563        after = binascii.hexlify(buf[pos + len(key):end])
2564        logger.debug("Memory context %d-%d: %s|%s|%s" % (start, end, before, binascii.hexlify(key), after))
2565        count += 1
2566        pos += len(key)
2567    return count
2568
2569def test_wpa2_psk_key_lifetime_in_memory(dev, apdev, params):
2570    """WPA2-PSK and PSK/PTK lifetime in memory"""
2571    ssid = "test-wpa2-psk"
2572    passphrase = 'qwertyuiop'
2573    psk = '602e323e077bc63bd80307ef4745b754b0ae0a925c2638ecd13a794b9527b9e6'
2574    pmk = binascii.unhexlify(psk)
2575    p = hostapd.wpa2_params(ssid=ssid)
2576    p['wpa_psk'] = psk
2577    hapd = hostapd.add_ap(apdev[0], p)
2578
2579    pid = find_wpas_process(dev[0])
2580
2581    id = dev[0].connect(ssid, raw_psk=psk, scan_freq="2412",
2582                        only_add_network=True)
2583
2584    logger.info("Checking keys in memory after network profile configuration")
2585    buf = read_process_memory(pid, pmk)
2586    get_key_locations(buf, pmk, "PMK")
2587
2588    dev[0].request("REMOVE_NETWORK all")
2589    logger.info("Checking keys in memory after network profile removal")
2590    buf = read_process_memory(pid, pmk)
2591    get_key_locations(buf, pmk, "PMK")
2592
2593    id = dev[0].connect(ssid, psk=passphrase, scan_freq="2412",
2594                        only_add_network=True)
2595
2596    logger.info("Checking keys in memory before connection")
2597    buf = read_process_memory(pid, pmk)
2598    get_key_locations(buf, pmk, "PMK")
2599
2600    dev[0].connect_network(id, timeout=20)
2601    # The decrypted copy of GTK is freed only after the CTRL-EVENT-CONNECTED
2602    # event has been delivered, so verify that wpa_supplicant has returned to
2603    # eloop before reading process memory.
2604    time.sleep(1)
2605    dev[0].ping()
2606
2607    buf = read_process_memory(pid, pmk)
2608
2609    dev[0].request("DISCONNECT")
2610    dev[0].wait_disconnected()
2611
2612    dev[0].relog()
2613    ptk = None
2614    gtk = None
2615    with open(os.path.join(params['logdir'], 'log0'), 'r') as f:
2616        for l in f.readlines():
2617            if "WPA: PTK - hexdump" in l:
2618                val = l.strip().split(':')[3].replace(' ', '')
2619                ptk = binascii.unhexlify(val)
2620            if "WPA: Group Key - hexdump" in l:
2621                val = l.strip().split(':')[3].replace(' ', '')
2622                gtk = binascii.unhexlify(val)
2623    if not pmk or not ptk or not gtk:
2624        raise Exception("Could not find keys from debug log")
2625    if len(gtk) != 16:
2626        raise Exception("Unexpected GTK length")
2627
2628    kck = ptk[0:16]
2629    kek = ptk[16:32]
2630    tk = ptk[32:48]
2631
2632    logger.info("Checking keys in memory while associated")
2633    get_key_locations(buf, pmk, "PMK")
2634    if pmk not in buf:
2635        raise HwsimSkip("PMK not found while associated")
2636    if kck not in buf:
2637        raise Exception("KCK not found while associated")
2638    if kek not in buf:
2639        raise Exception("KEK not found while associated")
2640    #if tk in buf:
2641    #    raise Exception("TK found from memory")
2642
2643    logger.info("Checking keys in memory after disassociation")
2644    buf = read_process_memory(pid, pmk)
2645    get_key_locations(buf, pmk, "PMK")
2646
2647    # Note: PMK/PSK is still present in network configuration
2648
2649    fname = os.path.join(params['logdir'],
2650                         'wpa2_psk_key_lifetime_in_memory.memctx-')
2651    verify_not_present(buf, kck, fname, "KCK")
2652    verify_not_present(buf, kek, fname, "KEK")
2653    verify_not_present(buf, tk, fname, "TK")
2654    if gtk in buf:
2655        get_key_locations(buf, gtk, "GTK")
2656    verify_not_present(buf, gtk, fname, "GTK")
2657
2658    dev[0].request("REMOVE_NETWORK all")
2659
2660    logger.info("Checking keys in memory after network profile removal")
2661    buf = read_process_memory(pid, pmk)
2662    get_key_locations(buf, pmk, "PMK")
2663
2664    verify_not_present(buf, pmk, fname, "PMK")
2665    verify_not_present(buf, kck, fname, "KCK")
2666    verify_not_present(buf, kek, fname, "KEK")
2667    verify_not_present(buf, tk, fname, "TK")
2668    verify_not_present(buf, gtk, fname, "GTK")
2669
2670@remote_compatible
2671def test_ap_wpa2_psk_wep(dev, apdev):
2672    """WPA2-PSK AP and WEP enabled"""
2673    ssid = "test-wpa2-psk"
2674    passphrase = 'qwertyuiop'
2675    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
2676    hapd = hostapd.add_ap(apdev[0], params)
2677    try:
2678        hapd.set('wep_key0', '"hello"')
2679        raise Exception("WEP key accepted to WPA2 network")
2680    except Exception:
2681        pass
2682
2683def test_ap_wpa2_psk_wpas_in_bridge(dev, apdev):
2684    """WPA2-PSK AP and wpas interface in a bridge"""
2685    br_ifname = 'sta-br0'
2686    ifname = 'wlan5'
2687    try:
2688        _test_ap_wpa2_psk_wpas_in_bridge(dev, apdev)
2689    finally:
2690        subprocess.call(['ip', 'link', 'set', 'dev', br_ifname, 'down'])
2691        subprocess.call(['brctl', 'delif', br_ifname, ifname])
2692        subprocess.call(['brctl', 'delbr', br_ifname])
2693        subprocess.call(['iw', ifname, 'set', '4addr', 'off'])
2694
2695def _test_ap_wpa2_psk_wpas_in_bridge(dev, apdev):
2696    ssid = "test-wpa2-psk"
2697    passphrase = 'qwertyuiop'
2698    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
2699    hapd = hostapd.add_ap(apdev[0], params)
2700
2701    br_ifname = 'sta-br0'
2702    ifname = 'wlan5'
2703    wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
2704    subprocess.call(['brctl', 'addbr', br_ifname])
2705    subprocess.call(['brctl', 'setfd', br_ifname, '0'])
2706    subprocess.call(['ip', 'link', 'set', 'dev', br_ifname, 'up'])
2707    subprocess.call(['iw', ifname, 'set', '4addr', 'on'])
2708    subprocess.check_call(['brctl', 'addif', br_ifname, ifname])
2709    wpas.interface_add(ifname, br_ifname=br_ifname)
2710    wpas.dump_monitor()
2711
2712    wpas.connect(ssid, psk=passphrase, scan_freq="2412")
2713    wpas.dump_monitor()
2714
2715@remote_compatible
2716def test_ap_wpa2_psk_ifdown(dev, apdev):
2717    """AP with open mode and external ifconfig down"""
2718    ssid = "test-wpa2-psk"
2719    passphrase = 'qwertyuiop'
2720    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
2721    hapd = hostapd.add_ap(apdev[0], params)
2722    bssid = apdev[0]['bssid']
2723
2724    dev[0].connect(ssid, psk=passphrase, scan_freq="2412")
2725    hapd.cmd_execute(['ip', 'link', 'set', 'dev', apdev[0]['ifname'], 'down'])
2726    ev = hapd.wait_event(["INTERFACE-DISABLED"], timeout=10)
2727    if ev is None:
2728        raise Exception("No INTERFACE-DISABLED event")
2729    # this wait tests beacon loss detection in mac80211
2730    dev[0].wait_disconnected()
2731    hapd.cmd_execute(['ip', 'link', 'set', 'dev', apdev[0]['ifname'], 'up'])
2732    ev = hapd.wait_event(["INTERFACE-ENABLED"], timeout=10)
2733    if ev is None:
2734        raise Exception("No INTERFACE-ENABLED event")
2735    dev[0].wait_connected()
2736    hapd.wait_sta()
2737    hwsim_utils.test_connectivity(dev[0], hapd)
2738
2739def test_ap_wpa2_psk_drop_first_msg_4(dev, apdev):
2740    """WPA2-PSK and first EAPOL-Key msg 4/4 dropped"""
2741    hapd = setup_psk_ext(dev[0], apdev[0])
2742    bssid = apdev[0]['bssid']
2743    addr = dev[0].own_addr()
2744
2745    # EAPOL-Key msg 1/4
2746    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
2747    if ev is None:
2748        raise Exception("Timeout on EAPOL-TX from hostapd")
2749    res = dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
2750    if "OK" not in res:
2751        raise Exception("EAPOL_RX to wpa_supplicant failed")
2752
2753    # EAPOL-Key msg 2/4
2754    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
2755    if ev is None:
2756        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
2757    res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
2758    if "OK" not in res:
2759        raise Exception("EAPOL_RX to hostapd failed")
2760
2761    # EAPOL-Key msg 3/4
2762    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
2763    if ev is None:
2764        raise Exception("Timeout on EAPOL-TX from hostapd")
2765    res = dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
2766    if "OK" not in res:
2767        raise Exception("EAPOL_RX to wpa_supplicant failed")
2768
2769    # EAPOL-Key msg 4/4
2770    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
2771    if ev is None:
2772        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
2773    logger.info("Drop the first EAPOL-Key msg 4/4")
2774
2775    # wpa_supplicant believes now that 4-way handshake succeeded; hostapd
2776    # doesn't. Use normal EAPOL TX/RX to handle retries.
2777    hapd.request("SET ext_eapol_frame_io 0")
2778    dev[0].request("SET ext_eapol_frame_io 0")
2779    dev[0].wait_connected()
2780
2781    ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=15)
2782    if ev is None:
2783        raise Exception("Timeout on AP-STA-CONNECTED from hostapd")
2784
2785    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=0.1)
2786    if ev is not None:
2787        logger.info("Disconnection detected")
2788        # The EAPOL-Key retries are supposed to allow the connection to be
2789        # established without having to reassociate. However, this does not
2790        # currently work since mac80211 ends up encrypting EAPOL-Key msg 4/4
2791        # after the pairwise key has been configured and AP will drop those and
2792        # disconnect the station after reaching retransmission limit. Connection
2793        # is then established after reassociation. Once that behavior has been
2794        # optimized to prevent EAPOL-Key frame encryption for retransmission
2795        # case, this exception can be uncommented here.
2796        #raise Exception("Unexpected disconnection")
2797
2798@remote_compatible
2799def test_ap_wpa2_psk_disable_enable(dev, apdev):
2800    """WPA2-PSK AP getting disabled and re-enabled"""
2801    ssid = "test-wpa2-psk"
2802    passphrase = 'qwertyuiop'
2803    psk = '602e323e077bc63bd80307ef4745b754b0ae0a925c2638ecd13a794b9527b9e6'
2804    params = hostapd.wpa2_params(ssid=ssid)
2805    params['wpa_psk'] = psk
2806    hapd = hostapd.add_ap(apdev[0], params)
2807    dev[0].connect(ssid, raw_psk=psk, scan_freq="2412")
2808
2809    for i in range(2):
2810        hapd.request("DISABLE")
2811        dev[0].wait_disconnected()
2812        hapd.request("ENABLE")
2813        dev[0].wait_connected()
2814        hapd.wait_sta()
2815        hwsim_utils.test_connectivity(dev[0], hapd)
2816
2817@remote_compatible
2818def test_ap_wpa2_psk_incorrect_passphrase(dev, apdev):
2819    """WPA2-PSK AP and station using incorrect passphrase"""
2820    ssid = "test-wpa2-psk"
2821    passphrase = 'qwertyuiop'
2822    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
2823    hapd = hostapd.add_ap(apdev[0], params)
2824    dev[0].connect(ssid, psk="incorrect passphrase", scan_freq="2412",
2825                   wait_connect=False)
2826    ev = hapd.wait_event(["AP-STA-POSSIBLE-PSK-MISMATCH"], timeout=10)
2827    if ev is None:
2828        raise Exception("No AP-STA-POSSIBLE-PSK-MISMATCH reported")
2829    dev[0].dump_monitor()
2830
2831    hapd.disable()
2832    hapd.set("wpa_passphrase", "incorrect passphrase")
2833    hapd.enable()
2834
2835    dev[0].wait_connected(timeout=20)
2836
2837@remote_compatible
2838def test_ap_wpa_ie_parsing(dev, apdev):
2839    """WPA IE parsing"""
2840    skip_with_fips(dev[0])
2841    skip_without_tkip(dev[0])
2842    ssid = "test-wpa-psk"
2843    passphrase = 'qwertyuiop'
2844    params = hostapd.wpa_params(ssid=ssid, passphrase=passphrase)
2845    hapd = hostapd.add_ap(apdev[0], params)
2846    id = dev[0].connect(ssid, psk=passphrase, scan_freq="2412",
2847                        only_add_network=True)
2848
2849    tests = ["dd040050f201",
2850             "dd050050f20101",
2851             "dd060050f2010100",
2852             "dd060050f2010001",
2853             "dd070050f201010000",
2854             "dd080050f20101000050",
2855             "dd090050f20101000050f2",
2856             "dd0a0050f20101000050f202",
2857             "dd0b0050f20101000050f20201",
2858             "dd0c0050f20101000050f2020100",
2859             "dd0c0050f20101000050f2020000",
2860             "dd0c0050f20101000050f202ffff",
2861             "dd0d0050f20101000050f202010000",
2862             "dd0e0050f20101000050f20201000050",
2863             "dd0f0050f20101000050f20201000050f2",
2864             "dd100050f20101000050f20201000050f202",
2865             "dd110050f20101000050f20201000050f20201",
2866             "dd120050f20101000050f20201000050f2020100",
2867             "dd120050f20101000050f20201000050f2020000",
2868             "dd120050f20101000050f20201000050f202ffff",
2869             "dd130050f20101000050f20201000050f202010000",
2870             "dd140050f20101000050f20201000050f20201000050",
2871             "dd150050f20101000050f20201000050f20201000050f2"]
2872    for t in tests:
2873        try:
2874            if "OK" not in dev[0].request("VENDOR_ELEM_ADD 13 " + t):
2875                raise Exception("VENDOR_ELEM_ADD failed")
2876            dev[0].select_network(id)
2877            ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"], timeout=10)
2878            if ev is None:
2879                raise Exception("Association rejection not reported")
2880            dev[0].request("DISCONNECT")
2881            dev[0].dump_monitor()
2882        finally:
2883            dev[0].request("VENDOR_ELEM_REMOVE 13 *")
2884
2885    tests = ["dd170050f20101000050f20201000050f20201000050f202ff",
2886             "dd180050f20101000050f20201000050f20201000050f202ffff",
2887             "dd190050f20101000050f20201000050f20201000050f202ffffff"]
2888    for t in tests:
2889        try:
2890            if "OK" not in dev[0].request("VENDOR_ELEM_ADD 13 " + t):
2891                raise Exception("VENDOR_ELEM_ADD failed")
2892            dev[0].select_network(id)
2893            ev = dev[0].wait_event(['CTRL-EVENT-CONNECTED',
2894                                    'WPA: 4-Way Handshake failed'], timeout=10)
2895            if ev is None:
2896                raise Exception("Association failed unexpectedly")
2897            dev[0].request("DISCONNECT")
2898            dev[0].dump_monitor()
2899        finally:
2900            dev[0].request("VENDOR_ELEM_REMOVE 13 *")
2901
2902@remote_compatible
2903def test_ap_wpa2_psk_no_random(dev, apdev):
2904    """WPA2-PSK AP and no random numbers available"""
2905    ssid = "test-wpa2-psk"
2906    passphrase = 'qwertyuiop'
2907    psk = '602e323e077bc63bd80307ef4745b754b0ae0a925c2638ecd13a794b9527b9e6'
2908    params = hostapd.wpa2_params(ssid=ssid)
2909    params['wpa_psk'] = psk
2910    hapd = hostapd.add_ap(apdev[0], params)
2911    with fail_test(hapd, 1, "wpa_gmk_to_gtk"):
2912        id = dev[0].connect(ssid, raw_psk=psk, scan_freq="2412",
2913                            wait_connect=False)
2914        ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=15)
2915        if ev is None:
2916            raise Exception("Disconnection event not reported")
2917        dev[0].request("DISCONNECT")
2918        dev[0].select_network(id, freq=2412)
2919        dev[0].wait_connected()
2920
2921@remote_compatible
2922def test_rsn_ie_proto_psk_sta(dev, apdev):
2923    """RSN element protocol testing for PSK cases on STA side"""
2924    bssid = apdev[0]['bssid']
2925    ssid = "test-wpa2-psk"
2926    passphrase = 'qwertyuiop'
2927    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
2928    # This is the RSN element used normally by hostapd
2929    params['own_ie_override'] = '30140100000fac040100000fac040100000fac020c00'
2930    hapd = hostapd.add_ap(apdev[0], params)
2931    if "FAIL" not in hapd.request("SET own_ie_override qwerty"):
2932        raise Exception("Invalid own_ie_override value accepted")
2933    id = dev[0].connect(ssid, psk=passphrase, scan_freq="2412")
2934
2935    tests = [('No RSN Capabilities field',
2936              '30120100000fac040100000fac040100000fac02'),
2937             ('Reserved RSN Capabilities bits set',
2938              '30140100000fac040100000fac040100000fac023cff'),
2939             ('Truncated RSN Capabilities field',
2940              '30130100000fac040100000fac040100000fac023c'),
2941             ('Extra pairwise cipher suite (unsupported)',
2942              '30180100000fac040200ffffffff000fac040100000fac020c00'),
2943             ('Extra AKM suite (unsupported)',
2944              '30180100000fac040100000fac040200ffffffff000fac020c00'),
2945             ('PMKIDCount field included',
2946              '30160100000fac040100000fac040100000fac020c000000'),
2947             ('Truncated PMKIDCount field',
2948              '30150100000fac040100000fac040100000fac020c0000'),
2949             ('Unexpected Group Management Cipher Suite with PMF disabled',
2950              '301a0100000fac040100000fac040100000fac020c000000000fac06'),
2951             ('Extra octet after defined fields (future extensibility)',
2952              '301b0100000fac040100000fac040100000fac020c000000000fac0600')]
2953    for txt, ie in tests:
2954        dev[0].request("DISCONNECT")
2955        dev[0].wait_disconnected()
2956        dev[0].dump_monitor()
2957        dev[0].request("NOTE " + txt)
2958        logger.info(txt)
2959        hapd.disable()
2960        hapd.set('own_ie_override', ie)
2961        hapd.enable()
2962        dev[0].request("BSS_FLUSH 0")
2963        dev[0].scan_for_bss(bssid, 2412, force_scan=True, only_new=True)
2964        dev[0].select_network(id, freq=2412)
2965        dev[0].wait_connected()
2966
2967@remote_compatible
2968def test_ap_cli_order(dev, apdev):
2969    """hostapd configuration parameter SET ordering"""
2970    ssid = "test-rsn-setup"
2971    passphrase = 'zzzzzzzz'
2972
2973    hapd = hostapd.add_ap(apdev[0], {}, no_enable=True)
2974    hapd.set('ssid', ssid)
2975    hapd.set('wpa_passphrase', passphrase)
2976    hapd.set('rsn_pairwise', 'CCMP')
2977    hapd.set('wpa_key_mgmt', 'WPA-PSK')
2978    hapd.set('wpa', '2')
2979    hapd.enable()
2980    cfg = hapd.get_config()
2981    if cfg['group_cipher'] != 'CCMP':
2982        raise Exception("Unexpected group_cipher: " + cfg['group_cipher'])
2983    if cfg['rsn_pairwise_cipher'] != 'CCMP':
2984        raise Exception("Unexpected rsn_pairwise_cipher: " + cfg['rsn_pairwise_cipher'])
2985
2986    ev = hapd.wait_event(["AP-ENABLED", "AP-DISABLED"], timeout=30)
2987    if ev is None:
2988        raise Exception("AP startup timed out")
2989    if "AP-ENABLED" not in ev:
2990        raise Exception("AP startup failed")
2991
2992    dev[0].connect(ssid, psk=passphrase, scan_freq="2412")
2993
2994def set_test_assoc_ie(dev, ie):
2995    if "OK" not in dev.request("TEST_ASSOC_IE " + ie):
2996        raise Exception("Could not set TEST_ASSOC_IE")
2997
2998@remote_compatible
2999def test_ap_wpa2_psk_assoc_rsn(dev, apdev):
3000    """WPA2-PSK AP and association request RSN IE differences"""
3001    ssid = "test-wpa2-psk"
3002    passphrase = 'qwertyuiop'
3003    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
3004    hapd = hostapd.add_ap(apdev[0], params)
3005
3006    tests = [("Normal wpa_supplicant assoc req RSN IE",
3007              "30140100000fac040100000fac040100000fac020000"),
3008             ("RSN IE without RSN Capabilities",
3009              "30120100000fac040100000fac040100000fac02")]
3010    for title, ie in tests:
3011        logger.info(title)
3012        set_test_assoc_ie(dev[0], ie)
3013        dev[0].connect(ssid, psk=passphrase, scan_freq="2412")
3014        dev[0].request("REMOVE_NETWORK all")
3015        dev[0].wait_disconnected()
3016
3017    tests = [("WPA IE instead of RSN IE and only RSN enabled on AP",
3018              "dd160050f20101000050f20201000050f20201000050f202", 40),
3019             ("Empty RSN IE", "3000", 40),
3020             ("RSN IE with truncated Version", "300101", 40),
3021             ("RSN IE with only Version", "30020100", 43)]
3022    for title, ie, status in tests:
3023        logger.info(title)
3024        set_test_assoc_ie(dev[0], ie)
3025        dev[0].connect(ssid, psk=passphrase, scan_freq="2412",
3026                       wait_connect=False)
3027        ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"])
3028        if ev is None:
3029            raise Exception("Association rejection not reported")
3030        if "status_code=" + str(status) not in ev:
3031            raise Exception("Unexpected status code: " + ev)
3032        dev[0].request("REMOVE_NETWORK all")
3033        dev[0].dump_monitor()
3034
3035def test_ap_wpa2_psk_ft_workaround(dev, apdev):
3036    """WPA2-PSK+FT AP and workaround for incorrect STA behavior"""
3037    ssid = "test-wpa2-psk-ft"
3038    passphrase = 'qwertyuiop'
3039
3040    params = {"wpa": "2",
3041              "wpa_key_mgmt": "FT-PSK WPA-PSK",
3042              "rsn_pairwise": "CCMP",
3043              "ssid": ssid,
3044              "wpa_passphrase": passphrase}
3045    params["mobility_domain"] = "a1b2"
3046    params["r0_key_lifetime"] = "10000"
3047    params["pmk_r1_push"] = "1"
3048    params["reassociation_deadline"] = "1000"
3049    params['nas_identifier'] = "nas1.w1.fi"
3050    params['r1_key_holder'] = "000102030405"
3051    hapd = hostapd.add_ap(apdev[0], params)
3052
3053    # Include both WPA-PSK and FT-PSK AKMs in Association Request frame
3054    set_test_assoc_ie(dev[0],
3055                      "30180100000fac040100000fac040200000fac02000fac040000")
3056    dev[0].connect(ssid, psk=passphrase, scan_freq="2412")
3057    dev[0].request("REMOVE_NETWORK all")
3058    dev[0].wait_disconnected()
3059
3060def test_ap_wpa2_psk_assoc_rsn_pmkid(dev, apdev):
3061    """WPA2-PSK AP and association request RSN IE with PMKID"""
3062    ssid = "test-wpa2-psk"
3063    passphrase = 'qwertyuiop'
3064    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
3065    hapd = hostapd.add_ap(apdev[0], params)
3066
3067    set_test_assoc_ie(dev[0], "30260100000fac040100000fac040100000fac0200000100" + 16*'00')
3068    dev[0].connect(ssid, psk=passphrase, scan_freq="2412")
3069    dev[0].request("REMOVE_NETWORK all")
3070    dev[0].wait_disconnected()
3071
3072def test_ap_wpa_psk_rsn_pairwise(dev, apdev):
3073    """WPA-PSK AP and only rsn_pairwise set"""
3074    skip_without_tkip(dev[0])
3075    params = {"ssid": "wpapsk", "wpa": "1", "wpa_key_mgmt": "WPA-PSK",
3076              "rsn_pairwise": "TKIP", "wpa_passphrase": "1234567890"}
3077    hapd = hostapd.add_ap(apdev[0], params)
3078    dev[0].connect("wpapsk", psk="1234567890", proto="WPA", pairwise="TKIP",
3079                   scan_freq="2412")
3080
3081def test_ap_wpa2_eapol_retry_limit(dev, apdev):
3082    """WPA2-PSK EAPOL-Key retry limit configuration"""
3083    ssid = "test-wpa2-psk"
3084    passphrase = 'qwertyuiop'
3085    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
3086    params['wpa_ptk_rekey'] = '2'
3087    params['wpa_group_update_count'] = '1'
3088    params['wpa_pairwise_update_count'] = '1'
3089    hapd = hostapd.add_ap(apdev[0], params)
3090    dev[0].connect(ssid, psk=passphrase, scan_freq="2412")
3091    ev = dev[0].wait_event(["WPA: Key negotiation completed"])
3092    if ev is None:
3093        raise Exception("PTK rekey timed out")
3094
3095    if "FAIL" not in hapd.request("SET wpa_group_update_count 0"):
3096        raise Exception("Invalid wpa_group_update_count value accepted")
3097    if "FAIL" not in hapd.request("SET wpa_pairwise_update_count 0"):
3098        raise Exception("Invalid wpa_pairwise_update_count value accepted")
3099
3100def test_ap_wpa2_disable_eapol_retry(dev, apdev):
3101    """WPA2-PSK disable EAPOL-Key retry"""
3102    ssid = "test-wpa2-psk"
3103    passphrase = 'qwertyuiop'
3104    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
3105    params['wpa_disable_eapol_key_retries'] = '1'
3106    hapd = hostapd.add_ap(apdev[0], params)
3107    bssid = apdev[0]['bssid']
3108
3109    logger.info("Verify working 4-way handshake without retries")
3110    dev[0].connect(ssid, psk=passphrase, scan_freq="2412")
3111    dev[0].request("REMOVE_NETWORK all")
3112    dev[0].wait_disconnected()
3113    dev[0].dump_monitor()
3114    addr = dev[0].own_addr()
3115
3116    logger.info("Verify no retransmission of message 3/4")
3117    hapd.request("SET ext_eapol_frame_io 1")
3118    dev[0].request("SET ext_eapol_frame_io 1")
3119    dev[0].connect(ssid, psk=passphrase, scan_freq="2412", wait_connect=False)
3120
3121    ev = hapd.wait_event(["EAPOL-TX"], timeout=5)
3122    if ev is None:
3123        raise Exception("Timeout on EAPOL-TX (M1) from hostapd")
3124    ev = hapd.wait_event(["EAPOL-TX"], timeout=5)
3125    if ev is None:
3126        raise Exception("Timeout on EAPOL-TX (M1 retry) from hostapd")
3127    res = dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
3128    if "OK" not in res:
3129        raise Exception("EAPOL_RX (M1) to wpa_supplicant failed")
3130    ev = dev[0].wait_event(["EAPOL-TX"], timeout=5)
3131    if ev is None:
3132        raise Exception("Timeout on EAPOL-TX (M2) from wpa_supplicant")
3133    dev[0].dump_monitor()
3134    res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
3135    if "OK" not in res:
3136        raise Exception("EAPOL_RX (M2) to hostapd failed")
3137
3138    ev = hapd.wait_event(["EAPOL-TX"], timeout=5)
3139    if ev is None:
3140        raise Exception("Timeout on EAPOL-TX (M3) from hostapd")
3141    ev = hapd.wait_event(["EAPOL-TX"], timeout=2)
3142    if ev is not None:
3143        raise Exception("Unexpected EAPOL-TX M3 retry from hostapd")
3144    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=3)
3145    if ev is None:
3146        raise Exception("Disconnection not reported")
3147    dev[0].request("REMOVE_NETWORK all")
3148    dev[0].dump_monitor()
3149
3150def test_ap_wpa2_disable_eapol_retry_group(dev, apdev):
3151    """WPA2-PSK disable EAPOL-Key retry for group handshake"""
3152    ssid = "test-wpa2-psk"
3153    passphrase = 'qwertyuiop'
3154    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
3155    params['wpa_disable_eapol_key_retries'] = '1'
3156    params['wpa_strict_rekey'] = '1'
3157    hapd = hostapd.add_ap(apdev[0], params)
3158    bssid = apdev[0]['bssid']
3159
3160    id = dev[1].connect(ssid, psk=passphrase, scan_freq="2412")
3161    hapd.wait_sta()
3162    dev[0].connect(ssid, psk=passphrase, scan_freq="2412")
3163    hapd.wait_sta()
3164    dev[0].dump_monitor()
3165    addr = dev[0].own_addr()
3166
3167    dev[1].request("DISCONNECT")
3168    dev[1].wait_disconnected()
3169    ev = dev[0].wait_event(["WPA: Group rekeying completed"], timeout=2)
3170    if ev is None:
3171        raise Exception("GTK rekey timed out")
3172    dev[1].request("RECONNECT")
3173    dev[1].wait_connected()
3174    hapd.wait_sta()
3175    dev[0].dump_monitor()
3176
3177    hapd.request("SET ext_eapol_frame_io 1")
3178    dev[0].request("SET ext_eapol_frame_io 1")
3179    dev[1].request("DISCONNECT")
3180
3181    ev = hapd.wait_event(["EAPOL-TX"], timeout=5)
3182    if ev is None:
3183        raise Exception("Timeout on EAPOL-TX (group M1) from hostapd")
3184    ev = hapd.wait_event(["EAPOL-TX"], timeout=2)
3185    if ev is not None:
3186        raise Exception("Unexpected EAPOL-TX group M1 retry from hostapd")
3187    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=3)
3188    if ev is None:
3189        raise Exception("Disconnection not reported")
3190    dev[0].request("REMOVE_NETWORK all")
3191    dev[0].dump_monitor()
3192
3193def test_ap_wpa2_psk_mic_0(dev, apdev):
3194    """WPA2-PSK/TKIP and MIC=0 in EAPOL-Key msg 3/4"""
3195    skip_without_tkip(dev[0])
3196    bssid = apdev[0]['bssid']
3197    ssid = "test-wpa2-psk"
3198    passphrase = 'qwertyuiop'
3199    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
3200    params['rsn_pairwise'] = "TKIP"
3201    hapd = hostapd.add_ap(apdev[0], params)
3202    hapd.request("SET ext_eapol_frame_io 1")
3203    dev[0].request("SET ext_eapol_frame_io 1")
3204    dev[0].connect(ssid, psk=passphrase, scan_freq="2412", wait_connect=False)
3205    addr = dev[0].own_addr()
3206
3207    # EAPOL-Key msg 1/4
3208    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3209    if ev is None:
3210        raise Exception("Timeout on EAPOL-TX from hostapd")
3211    res = dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
3212    if "OK" not in res:
3213        raise Exception("EAPOL_RX to wpa_supplicant failed")
3214
3215    # EAPOL-Key msg 2/4
3216    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
3217    if ev is None:
3218        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
3219    res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
3220    if "OK" not in res:
3221        raise Exception("EAPOL_RX to hostapd failed")
3222    dev[0].dump_monitor()
3223
3224    # EAPOL-Key msg 3/4
3225    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3226    if ev is None:
3227        raise Exception("Timeout on EAPOL-TX from hostapd")
3228    msg3 = ev.split(' ')[2]
3229    res = dev[0].request("EAPOL_RX " + bssid + " " + msg3)
3230    if "OK" not in res:
3231        raise Exception("EAPOL_RX to wpa_supplicant failed")
3232
3233    # EAPOL-Key msg 4/4
3234    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
3235    if ev is None:
3236        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
3237    # Do not send to the AP
3238
3239    # EAPOL-Key msg 3/4 with MIC=0 and modifications
3240    eapol_hdr = msg3[0:8]
3241    key_type = msg3[8:10]
3242    key_info = msg3[10:14]
3243    key_length = msg3[14:18]
3244    replay_counter = msg3[18:34]
3245    key_nonce = msg3[34:98]
3246    key_iv = msg3[98:130]
3247    key_rsc = msg3[130:146]
3248    key_id = msg3[146:162]
3249    key_mic = msg3[162:194]
3250    key_data_len = msg3[194:198]
3251    key_data = msg3[198:]
3252
3253    msg3b = eapol_hdr + key_type
3254    msg3b += "12c9" # Clear MIC bit from key_info (originally 13c9)
3255    msg3b += key_length
3256    msg3b += '0000000000000003'
3257    msg3b += key_nonce + key_iv + key_rsc + key_id
3258    msg3b += 32*'0' # Clear MIC value
3259    msg3b += key_data_len + key_data
3260    dev[0].dump_monitor()
3261    res = dev[0].request("EAPOL_RX " + bssid + " " + msg3b)
3262    if "OK" not in res:
3263        raise Exception("EAPOL_RX to wpa_supplicant failed")
3264    ev = dev[0].wait_event(["EAPOL-TX", "WPA: Ignore EAPOL-Key"], timeout=2)
3265    if ev is None:
3266        raise Exception("No event from wpa_supplicant")
3267    if "EAPOL-TX" in ev:
3268        raise Exception("Unexpected EAPOL-Key message from wpa_supplicant")
3269    dev[0].request("DISCONNECT")
3270
3271def test_ap_wpa2_psk_local_error(dev, apdev):
3272    """WPA2-PSK and local error cases on supplicant"""
3273    ssid = "test-wpa2-psk"
3274    passphrase = 'qwertyuiop'
3275    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
3276    params["wpa_key_mgmt"] = "WPA-PSK WPA-PSK-SHA256"
3277    hapd = hostapd.add_ap(apdev[0], params)
3278
3279    with fail_test(dev[0], 1, "sha1_prf;wpa_pmk_to_ptk"):
3280        id = dev[0].connect(ssid, key_mgmt="WPA-PSK", psk=passphrase,
3281                            scan_freq="2412", wait_connect=False)
3282        ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=5)
3283        if ev is None:
3284            raise Exception("Disconnection event not reported")
3285        dev[0].request("REMOVE_NETWORK all")
3286        dev[0].dump_monitor()
3287
3288    with fail_test(dev[0], 1, "sha256_prf;wpa_pmk_to_ptk"):
3289        id = dev[0].connect(ssid, key_mgmt="WPA-PSK-SHA256", psk=passphrase,
3290                            scan_freq="2412", wait_connect=False)
3291        ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=5)
3292        if ev is None:
3293            raise Exception("Disconnection event not reported")
3294        dev[0].request("REMOVE_NETWORK all")
3295        dev[0].dump_monitor()
3296
3297def test_ap_wpa2_psk_inject_assoc(dev, apdev, params):
3298    """WPA2-PSK AP and Authentication and Association Request frame injection"""
3299    prefix = "ap_wpa2_psk_inject_assoc"
3300    ifname = apdev[0]["ifname"]
3301    cap = os.path.join(params['logdir'], prefix + "." + ifname + ".pcap")
3302
3303    ssid = "test"
3304    params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
3305    params["wpa_key_mgmt"] = "WPA-PSK"
3306    hapd = hostapd.add_ap(apdev[0], params)
3307    wt = WlantestCapture(ifname, cap)
3308    time.sleep(1)
3309
3310    bssid = hapd.own_addr().replace(':', '')
3311
3312    hapd.request("SET ext_mgmt_frame_handling 1")
3313    addr = "021122334455"
3314    auth = "b0003a01" + bssid + addr + bssid + '1000000001000000'
3315    res = hapd.request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % auth)
3316    if "OK" not in res:
3317        raise Exception("MGMT_RX_PROCESS failed")
3318    ev = hapd.wait_event(["MGMT-TX-STATUS"], timeout=5)
3319    if ev is None:
3320        raise Exception("No TX status seen")
3321    ev = ev.replace("ok=0", "ok=1")
3322    cmd = "MGMT_TX_STATUS_PROCESS %s" % (" ".join(ev.split(' ')[1:4]))
3323    if "OK" not in hapd.request(cmd):
3324        raise Exception("MGMT_TX_STATUS_PROCESS failed")
3325
3326    assoc = "00003a01" + bssid + addr + bssid + '2000' + '31040500' + '000474657374' + '010802040b160c121824' + '30140100000fac040100000fac040100000fac020000'
3327    res = hapd.request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % assoc)
3328    if "OK" not in res:
3329        raise Exception("MGMT_RX_PROCESS failed")
3330    ev = hapd.wait_event(["MGMT-TX-STATUS"], timeout=5)
3331    if ev is None:
3332        raise Exception("No TX status seen")
3333    ev = ev.replace("ok=0", "ok=1")
3334    cmd = "MGMT_TX_STATUS_PROCESS %s" % (" ".join(ev.split(' ')[1:4]))
3335    if "OK" not in hapd.request(cmd):
3336        raise Exception("MGMT_TX_STATUS_PROCESS failed")
3337    hapd.request("SET ext_mgmt_frame_handling 0")
3338
3339    dev[0].connect(ssid, psk="12345678", scan_freq="2412")
3340    hapd.wait_sta()
3341    hwsim_utils.test_connectivity(dev[0], hapd)
3342    time.sleep(1)
3343    hwsim_utils.test_connectivity(dev[0], hapd)
3344    time.sleep(0.5)
3345    wt.close()
3346    time.sleep(0.5)
3347
3348    # Check for Layer 2 Update frame and unexpected frames from the station
3349    # that did not fully complete authentication.
3350    res = run_tshark(cap, "basicxid.llc.xid.format == 0x81",
3351                     ["eth.src"], wait=False)
3352    real_sta_seen = False
3353    unexpected_sta_seen = False
3354    real_addr = dev[0].own_addr()
3355    for l in res.splitlines():
3356        if l == real_addr:
3357            real_sta_seen = True
3358        else:
3359            unexpected_sta_seen = True
3360    if unexpected_sta_seen:
3361        raise Exception("Layer 2 Update frame from unexpected STA seen")
3362    if not real_sta_seen:
3363        raise Exception("Layer 2 Update frame from real STA not seen")
3364
3365    res = run_tshark(cap, "eth.src == 02:11:22:33:44:55", ["eth.src"],
3366                     wait=False)
3367    if len(res) > 0:
3368        raise Exception("Unexpected frame from unauthorized STA seen")
3369
3370def test_ap_wpa2_psk_no_control_port(dev, apdev):
3371    """WPA2-PSK AP without nl80211 control port"""
3372    ssid = "test-wpa2-psk"
3373    passphrase = 'qwertyuiop'
3374    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
3375    params['driver_params'] = "control_port=0"
3376    hapd = hostapd.add_ap(apdev[0], params)
3377
3378    wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
3379    wpas.interface_add("wlan5", drv_params="control_port=0")
3380    wpas.connect(ssid, psk=passphrase, scan_freq="2412")
3381    hapd.wait_sta()
3382    hwsim_utils.test_connectivity(wpas, hapd)
3383    if "OK" not in wpas.request("KEY_REQUEST 0 1"):
3384        raise Exception("KEY_REQUEST failed")
3385    ev = wpas.wait_event(["WPA: Key negotiation completed"])
3386    if ev is None:
3387        raise Exception("PTK rekey timed out")
3388    hapd.wait_ptkinitdone(wpas.own_addr())
3389    hwsim_utils.test_connectivity(wpas, hapd)
3390    wpas.request("DISCONNECT")
3391    wpas.wait_disconnected()
3392    wpas.dump_monitor()
3393
3394def test_ap_wpa2_psk_ap_control_port(dev, apdev):
3395    """WPA2-PSK AP with nl80211 control port in AP mode"""
3396    run_ap_wpa2_psk_ap_control_port(dev, apdev, ctrl_val=1)
3397
3398def test_ap_wpa2_psk_ap_control_port_disabled(dev, apdev):
3399    """WPA2-PSK AP with nl80211 control port in AP mode disabled"""
3400    run_ap_wpa2_psk_ap_control_port(dev, apdev, ctrl_val=0)
3401
3402def run_ap_wpa2_psk_ap_control_port(dev, apdev, ctrl_val):
3403    ssid = "test-wpa2-psk"
3404    passphrase = 'qwertyuiop'
3405    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
3406    params['driver_params'] = "control_port_ap=%d" % ctrl_val
3407    hapd = hostapd.add_ap(apdev[0], params)
3408
3409    flags = hapd.request("DRIVER_FLAGS").splitlines()[1:]
3410    flags2 = hapd.request("DRIVER_FLAGS2").splitlines()[1:]
3411    logger.info("AP driver flags: " + str(flags))
3412    logger.info("AP driver flags2: " + str(flags2))
3413    if 'CONTROL_PORT' not in flags or 'CONTROL_PORT_RX' not in flags2:
3414        raise HwsimSkip("No AP driver support for CONTROL_PORT")
3415
3416    flags = dev[0].request("DRIVER_FLAGS").splitlines()[1:]
3417    flags2 = dev[0].request("DRIVER_FLAGS2").splitlines()[1:]
3418    logger.info("STA driver flags: " + str(flags))
3419    logger.info("STA driver flags2: " + str(flags2))
3420    if 'CONTROL_PORT' not in flags or 'CONTROL_PORT_RX' not in flags2:
3421        raise HwsimSkip("No STA driver support for CONTROL_PORT")
3422
3423    dev[0].connect(ssid, psk=passphrase, scan_freq="2412")
3424    hapd.wait_sta()
3425    hwsim_utils.test_connectivity(dev[0], hapd)
3426    if "OK" not in dev[0].request("KEY_REQUEST 0 1"):
3427        raise Exception("KEY_REQUEST failed")
3428    ev = dev[0].wait_event(["WPA: Key negotiation completed"])
3429    if ev is None:
3430        raise Exception("PTK rekey timed out")
3431    hapd.wait_ptkinitdone(dev[0].own_addr())
3432    hwsim_utils.test_connectivity(dev[0], hapd)
3433
3434def test_ap_wpa2_psk_rsne_mismatch_ap(dev, apdev):
3435    """RSNE mismatch in EAPOL-Key msg 3/4"""
3436    ie = "30140100000fac040100000fac040100000fac020c80"
3437    run_ap_wpa2_psk_rsne_mismatch_ap(dev, apdev, ie)
3438
3439def test_ap_wpa2_psk_rsne_mismatch_ap2(dev, apdev):
3440    """RSNE mismatch in EAPOL-Key msg 3/4"""
3441    ie = "30150100000fac040100000fac040100000fac020c0000"
3442    run_ap_wpa2_psk_rsne_mismatch_ap(dev, apdev, ie)
3443
3444def test_ap_wpa2_psk_rsne_mismatch_ap3(dev, apdev):
3445    """RSNE mismatch in EAPOL-Key msg 3/4"""
3446    run_ap_wpa2_psk_rsne_mismatch_ap(dev, apdev, "")
3447
3448def run_ap_wpa2_psk_rsne_mismatch_ap(dev, apdev, rsne):
3449    params = hostapd.wpa2_params(ssid="psk", passphrase="12345678")
3450    params['rsne_override_eapol'] = rsne
3451    hapd = hostapd.add_ap(apdev[0], params)
3452
3453    dev[0].connect("psk", psk="12345678", scan_freq="2412", wait_connect=False)
3454    ev = dev[0].wait_event(["Associated with"], timeout=10)
3455    if ev is None:
3456        raise Exception("No indication of association seen")
3457    ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
3458                            "CTRL-EVENT-DISCONNECTED"], timeout=5)
3459    dev[0].request("REMOVE_NETWORK all")
3460    if ev is None:
3461        raise Exception("No disconnection seen")
3462    if "CTRL-EVENT-DISCONNECTED" not in ev:
3463        raise Exception("Unexpected connection")
3464    if "reason=17 locally_generated=1" not in ev:
3465        raise Exception("Unexpected disconnection reason: " + ev)
3466
3467def test_ap_wpa2_psk_rsnxe_mismatch_ap(dev, apdev):
3468    """RSNXE mismatch in EAPOL-Key msg 3/4"""
3469    params = hostapd.wpa2_params(ssid="psk", passphrase="12345678")
3470    params['rsnxe_override_eapol'] = "F40100"
3471    hapd = hostapd.add_ap(apdev[0], params)
3472
3473    dev[0].connect("psk", psk="12345678", scan_freq="2412", wait_connect=False)
3474    ev = dev[0].wait_event(["Associated with"], timeout=10)
3475    if ev is None:
3476        raise Exception("No indication of association seen")
3477    ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
3478                            "CTRL-EVENT-DISCONNECTED"], timeout=5)
3479    dev[0].request("REMOVE_NETWORK all")
3480    if ev is None:
3481        raise Exception("No disconnection seen")
3482    if "CTRL-EVENT-DISCONNECTED" not in ev:
3483        raise Exception("Unexpected connection")
3484    if "reason=17 locally_generated=1" not in ev:
3485        raise Exception("Unexpected disconnection reason: " + ev)
3486
3487def test_ap_wpa2_psk_ext_key_id_ptk_rekey_ap0(dev, apdev):
3488    """WPA2-PSK AP and PTK rekey by AP (disabled on STA)"""
3489    run_ap_wpa2_psk_ext_key_id_ptk_rekey_ap(dev, apdev, 1, 0)
3490
3491def test_ap_wpa2_psk_ext_key_id_ptk_rekey_ap1(dev, apdev):
3492    """WPA2-PSK AP and PTK rekey by AP (start with Key ID 0)"""
3493    run_ap_wpa2_psk_ext_key_id_ptk_rekey_ap(dev, apdev, 1, 1)
3494
3495def test_ap_wpa2_psk_ext_key_id_ptk_rekey_ap2(dev, apdev):
3496    """WPA2-PSK AP and PTK rekey by AP (start with Key ID 1)"""
3497    run_ap_wpa2_psk_ext_key_id_ptk_rekey_ap(dev, apdev, 2, 1)
3498
3499def run_ap_wpa2_psk_ext_key_id_ptk_rekey_ap(dev, apdev, ap_ext_key_id,
3500                                            sta_ext_key_id):
3501    check_ext_key_id_capa(dev[0])
3502    ssid = "test-wpa2-psk"
3503    passphrase = 'qwertyuiop'
3504    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
3505    params['wpa_ptk_rekey'] = '2'
3506    params['extended_key_id'] = str(ap_ext_key_id)
3507    hapd = hostapd.add_ap(apdev[0], params)
3508    check_ext_key_id_capa(hapd)
3509    try:
3510        dev[0].set("extended_key_id", str(sta_ext_key_id))
3511        dev[0].connect(ssid, psk=passphrase, scan_freq="2412")
3512        idx = int(dev[0].request("GET last_tk_key_idx"))
3513        expect_idx = 1 if ap_ext_key_id == 2 and sta_ext_key_id else 0
3514        if idx != expect_idx:
3515            raise Exception("Unexpected Key ID for the first TK: %d (expected %d)" % (idx, expect_idx))
3516        ev = dev[0].wait_event(["WPA: Key negotiation completed"])
3517        if ev is None:
3518            raise Exception("PTK rekey timed out")
3519        idx = int(dev[0].request("GET last_tk_key_idx"))
3520        expect_idx = 1 if ap_ext_key_id == 1 and sta_ext_key_id else 0
3521        if idx != expect_idx:
3522            raise Exception("Unexpected Key ID for the second TK: %d (expected %d)" % (idx, expect_idx))
3523        hwsim_utils.test_connectivity(dev[0], hapd)
3524    finally:
3525        dev[0].set("extended_key_id", "0")
3526
3527def test_ap_wpa2_psk_ext_key_id_ptk_rekey_sta0(dev, apdev):
3528    """Extended Key ID and PTK rekey by station (Ext Key ID disabled on AP)"""
3529    run_ap_wpa2_psk_ext_key_id_ptk_rekey_sta(dev, apdev, 0)
3530
3531def test_ap_wpa2_psk_ext_key_id_ptk_rekey_sta1(dev, apdev):
3532    """Extended Key ID and PTK rekey by station (start with Key ID 0)"""
3533    run_ap_wpa2_psk_ext_key_id_ptk_rekey_sta(dev, apdev, 1)
3534
3535def test_ap_wpa2_psk_ext_key_id_ptk_rekey_sta2(dev, apdev):
3536    """Extended Key ID and PTK rekey by station (start with Key ID 1)"""
3537    run_ap_wpa2_psk_ext_key_id_ptk_rekey_sta(dev, apdev, 2)
3538
3539def run_ap_wpa2_psk_ext_key_id_ptk_rekey_sta(dev, apdev, ext_key_id):
3540    check_ext_key_id_capa(dev[0])
3541    ssid = "test-wpa2-psk"
3542    passphrase = 'qwertyuiop'
3543    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
3544    params['extended_key_id'] = str(ext_key_id)
3545    hapd = hostapd.add_ap(apdev[0], params)
3546    check_ext_key_id_capa(hapd)
3547
3548    Wlantest.setup(hapd)
3549    wt = Wlantest()
3550    wt.flush()
3551    wt.add_passphrase(passphrase)
3552
3553    try:
3554        dev[0].set("extended_key_id", "1")
3555        dev[0].connect(ssid, psk=passphrase, wpa_ptk_rekey="1",
3556                       scan_freq="2412")
3557        idx = int(dev[0].request("GET last_tk_key_idx"))
3558        expect_idx = 1 if ext_key_id == 2 else 0
3559        if idx != expect_idx:
3560            raise Exception("Unexpected Key ID for the first TK: %d (expected %d)" % (idx, expect_idx))
3561        ev = dev[0].wait_event(["WPA: Key negotiation completed",
3562                                "CTRL-EVENT-DISCONNECTED"])
3563        if ev is None:
3564            raise Exception("PTK rekey timed out")
3565        if "CTRL-EVENT-DISCONNECTED" in ev:
3566            raise Exception("Disconnect instead of rekey")
3567        idx = int(dev[0].request("GET last_tk_key_idx"))
3568        expect_idx = 1 if ext_key_id == 1 else 0
3569        if idx != expect_idx:
3570            raise Exception("Unexpected Key ID for the second TK: %d (expected %d)" % (idx, expect_idx))
3571        hwsim_utils.test_connectivity(dev[0], hapd)
3572    finally:
3573        dev[0].set("extended_key_id", "0")
3574