tests: Clear BSS table at the end of rsn_ie_proto_eap_sta
[mech_eap.git] / tests / hwsim / test_ap_eap.py
1 # -*- coding: utf-8 -*-
2 # WPA2-Enterprise tests
3 # Copyright (c) 2013-2015, Jouni Malinen <j@w1.fi>
4 #
5 # This software may be distributed under the terms of the BSD license.
6 # See README for more details.
7
8 import base64
9 import binascii
10 import time
11 import subprocess
12 import logging
13 logger = logging.getLogger()
14 import os
15 import socket
16 import SocketServer
17 import struct
18 import tempfile
19
20 import hwsim_utils
21 import hostapd
22 from utils import HwsimSkip, alloc_fail, fail_test, skip_with_fips, wait_fail_trigger
23 from wpasupplicant import WpaSupplicant
24 from test_ap_psk import check_mib, find_wpas_process, read_process_memory, verify_not_present, get_key_locations, set_test_assoc_ie
25
26 try:
27     import OpenSSL
28     openssl_imported = True
29 except ImportError:
30     openssl_imported = False
31
32 def check_hlr_auc_gw_support():
33     if not os.path.exists("/tmp/hlr_auc_gw.sock"):
34         raise HwsimSkip("No hlr_auc_gw available")
35
36 def check_eap_capa(dev, method):
37     res = dev.get_capability("eap")
38     if method not in res:
39         raise HwsimSkip("EAP method %s not supported in the build" % method)
40
41 def check_subject_match_support(dev):
42     tls = dev.request("GET tls_library")
43     if not tls.startswith("OpenSSL"):
44         raise HwsimSkip("subject_match not supported with this TLS library: " + tls)
45
46 def check_altsubject_match_support(dev):
47     tls = dev.request("GET tls_library")
48     if not tls.startswith("OpenSSL"):
49         raise HwsimSkip("altsubject_match not supported with this TLS library: " + tls)
50
51 def check_domain_match(dev):
52     tls = dev.request("GET tls_library")
53     if tls.startswith("internal"):
54         raise HwsimSkip("domain_match not supported with this TLS library: " + tls)
55
56 def check_domain_suffix_match(dev):
57     tls = dev.request("GET tls_library")
58     if tls.startswith("internal"):
59         raise HwsimSkip("domain_suffix_match not supported with this TLS library: " + tls)
60
61 def check_domain_match_full(dev):
62     tls = dev.request("GET tls_library")
63     if not tls.startswith("OpenSSL"):
64         raise HwsimSkip("domain_suffix_match requires full match with this TLS library: " + tls)
65
66 def check_cert_probe_support(dev):
67     tls = dev.request("GET tls_library")
68     if not tls.startswith("OpenSSL") and not tls.startswith("internal"):
69         raise HwsimSkip("Certificate probing not supported with this TLS library: " + tls)
70
71 def check_ext_cert_check_support(dev):
72     tls = dev.request("GET tls_library")
73     if not tls.startswith("OpenSSL"):
74         raise HwsimSkip("ext_cert_check not supported with this TLS library: " + tls)
75
76 def check_ocsp_support(dev):
77     tls = dev.request("GET tls_library")
78     #if tls.startswith("internal"):
79     #    raise HwsimSkip("OCSP not supported with this TLS library: " + tls)
80     #if "BoringSSL" in tls:
81     #    raise HwsimSkip("OCSP not supported with this TLS library: " + tls)
82
83 def check_ocsp_multi_support(dev):
84     tls = dev.request("GET tls_library")
85     if not tls.startswith("internal"):
86         raise HwsimSkip("OCSP-multi not supported with this TLS library: " + tls)
87     as_hapd = hostapd.Hostapd("as")
88     res = as_hapd.request("GET tls_library")
89     del as_hapd
90     if not res.startswith("internal"):
91         raise HwsimSkip("Authentication server does not support ocsp_multi")
92
93 def check_pkcs12_support(dev):
94     tls = dev.request("GET tls_library")
95     #if tls.startswith("internal"):
96     #    raise HwsimSkip("PKCS#12 not supported with this TLS library: " + tls)
97
98 def check_dh_dsa_support(dev):
99     tls = dev.request("GET tls_library")
100     if tls.startswith("internal"):
101         raise HwsimSkip("DH DSA not supported with this TLS library: " + tls)
102
103 def read_pem(fname):
104     with open(fname, "r") as f:
105         lines = f.readlines()
106         copy = False
107         cert = ""
108         for l in lines:
109             if "-----END" in l:
110                 break
111             if copy:
112                 cert = cert + l
113             if "-----BEGIN" in l:
114                 copy = True
115     return base64.b64decode(cert)
116
117 def eap_connect(dev, ap, method, identity,
118                 sha256=False, expect_failure=False, local_error_report=False,
119                 maybe_local_error=False, **kwargs):
120     hapd = hostapd.Hostapd(ap['ifname'])
121     id = dev.connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
122                      eap=method, identity=identity,
123                      wait_connect=False, scan_freq="2412", ieee80211w="1",
124                      **kwargs)
125     eap_check_auth(dev, method, True, sha256=sha256,
126                    expect_failure=expect_failure,
127                    local_error_report=local_error_report,
128                    maybe_local_error=maybe_local_error)
129     if expect_failure:
130         return id
131     ev = hapd.wait_event([ "AP-STA-CONNECTED" ], timeout=5)
132     if ev is None:
133         raise Exception("No connection event received from hostapd")
134     return id
135
136 def eap_check_auth(dev, method, initial, rsn=True, sha256=False,
137                    expect_failure=False, local_error_report=False,
138                    maybe_local_error=False):
139     ev = dev.wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
140     if ev is None:
141         raise Exception("Association and EAP start timed out")
142     ev = dev.wait_event(["CTRL-EVENT-EAP-METHOD",
143                          "CTRL-EVENT-EAP-FAILURE"], timeout=10)
144     if ev is None:
145         raise Exception("EAP method selection timed out")
146     if "CTRL-EVENT-EAP-FAILURE" in ev:
147         if maybe_local_error:
148             return
149         raise Exception("Could not select EAP method")
150     if method not in ev:
151         raise Exception("Unexpected EAP method")
152     if expect_failure:
153         ev = dev.wait_event(["CTRL-EVENT-EAP-FAILURE"])
154         if ev is None:
155             raise Exception("EAP failure timed out")
156         ev = dev.wait_disconnected(timeout=10)
157         if maybe_local_error and "locally_generated=1" in ev:
158             return
159         if not local_error_report:
160             if "reason=23" not in ev:
161                 raise Exception("Proper reason code for disconnection not reported")
162         return
163     ev = dev.wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
164     if ev is None:
165         raise Exception("EAP success timed out")
166
167     if initial:
168         ev = dev.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
169     else:
170         ev = dev.wait_event(["WPA: Key negotiation completed"], timeout=10)
171     if ev is None:
172         raise Exception("Association with the AP timed out")
173     status = dev.get_status()
174     if status["wpa_state"] != "COMPLETED":
175         raise Exception("Connection not completed")
176
177     if status["suppPortStatus"] != "Authorized":
178         raise Exception("Port not authorized")
179     if method not in status["selectedMethod"]:
180         raise Exception("Incorrect EAP method status")
181     if sha256:
182         e = "WPA2-EAP-SHA256"
183     elif rsn:
184         e = "WPA2/IEEE 802.1X/EAP"
185     else:
186         e = "WPA/IEEE 802.1X/EAP"
187     if status["key_mgmt"] != e:
188         raise Exception("Unexpected key_mgmt status: " + status["key_mgmt"])
189     return status
190
191 def eap_reauth(dev, method, rsn=True, sha256=False, expect_failure=False):
192     dev.request("REAUTHENTICATE")
193     return eap_check_auth(dev, method, False, rsn=rsn, sha256=sha256,
194                           expect_failure=expect_failure)
195
196 def test_ap_wpa2_eap_sim(dev, apdev):
197     """WPA2-Enterprise connection using EAP-SIM"""
198     check_hlr_auc_gw_support()
199     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
200     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
201     eap_connect(dev[0], apdev[0], "SIM", "1232010000000000",
202                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581")
203     hwsim_utils.test_connectivity(dev[0], hapd)
204     eap_reauth(dev[0], "SIM")
205
206     eap_connect(dev[1], apdev[0], "SIM", "1232010000000001",
207                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581")
208     eap_connect(dev[2], apdev[0], "SIM", "1232010000000002",
209                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
210                 expect_failure=True)
211
212     logger.info("Negative test with incorrect key")
213     dev[0].request("REMOVE_NETWORK all")
214     eap_connect(dev[0], apdev[0], "SIM", "1232010000000000",
215                 password="ffdca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
216                 expect_failure=True)
217
218     logger.info("Invalid GSM-Milenage key")
219     dev[0].request("REMOVE_NETWORK all")
220     eap_connect(dev[0], apdev[0], "SIM", "1232010000000000",
221                 password="ffdca4eda45b53cf0f12d7c9c3bc6a",
222                 expect_failure=True)
223
224     logger.info("Invalid GSM-Milenage key(2)")
225     dev[0].request("REMOVE_NETWORK all")
226     eap_connect(dev[0], apdev[0], "SIM", "1232010000000000",
227                 password="ffdca4eda45b53cf0f12d7c9c3bc6a8q:cb9cccc4b9258e6dca4760379fb82581",
228                 expect_failure=True)
229
230     logger.info("Invalid GSM-Milenage key(3)")
231     dev[0].request("REMOVE_NETWORK all")
232     eap_connect(dev[0], apdev[0], "SIM", "1232010000000000",
233                 password="ffdca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb8258q",
234                 expect_failure=True)
235
236     logger.info("Invalid GSM-Milenage key(4)")
237     dev[0].request("REMOVE_NETWORK all")
238     eap_connect(dev[0], apdev[0], "SIM", "1232010000000000",
239                 password="ffdca4eda45b53cf0f12d7c9c3bc6a89qcb9cccc4b9258e6dca4760379fb82581",
240                 expect_failure=True)
241
242     logger.info("Missing key configuration")
243     dev[0].request("REMOVE_NETWORK all")
244     eap_connect(dev[0], apdev[0], "SIM", "1232010000000000",
245                 expect_failure=True)
246
247 def test_ap_wpa2_eap_sim_sql(dev, apdev, params):
248     """WPA2-Enterprise connection using EAP-SIM (SQL)"""
249     check_hlr_auc_gw_support()
250     try:
251         import sqlite3
252     except ImportError:
253         raise HwsimSkip("No sqlite3 module available")
254     con = sqlite3.connect(os.path.join(params['logdir'], "hostapd.db"))
255     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
256     params['auth_server_port'] = "1814"
257     hostapd.add_ap(apdev[0]['ifname'], params)
258     eap_connect(dev[0], apdev[0], "SIM", "1232010000000000",
259                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581")
260
261     logger.info("SIM fast re-authentication")
262     eap_reauth(dev[0], "SIM")
263
264     logger.info("SIM full auth with pseudonym")
265     with con:
266         cur = con.cursor()
267         cur.execute("DELETE FROM reauth WHERE permanent='1232010000000000'")
268     eap_reauth(dev[0], "SIM")
269
270     logger.info("SIM full auth with permanent identity")
271     with con:
272         cur = con.cursor()
273         cur.execute("DELETE FROM reauth WHERE permanent='1232010000000000'")
274         cur.execute("DELETE FROM pseudonyms WHERE permanent='1232010000000000'")
275     eap_reauth(dev[0], "SIM")
276
277     logger.info("SIM reauth with mismatching MK")
278     with con:
279         cur = con.cursor()
280         cur.execute("UPDATE reauth SET mk='0000000000000000000000000000000000000000' WHERE permanent='1232010000000000'")
281     eap_reauth(dev[0], "SIM", expect_failure=True)
282     dev[0].request("REMOVE_NETWORK all")
283
284     eap_connect(dev[0], apdev[0], "SIM", "1232010000000000",
285                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581")
286     with con:
287         cur = con.cursor()
288         cur.execute("UPDATE reauth SET counter='10' WHERE permanent='1232010000000000'")
289     eap_reauth(dev[0], "SIM")
290     with con:
291         cur = con.cursor()
292         cur.execute("UPDATE reauth SET counter='10' WHERE permanent='1232010000000000'")
293     logger.info("SIM reauth with mismatching counter")
294     eap_reauth(dev[0], "SIM")
295     dev[0].request("REMOVE_NETWORK all")
296
297     eap_connect(dev[0], apdev[0], "SIM", "1232010000000000",
298                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581")
299     with con:
300         cur = con.cursor()
301         cur.execute("UPDATE reauth SET counter='1001' WHERE permanent='1232010000000000'")
302     logger.info("SIM reauth with max reauth count reached")
303     eap_reauth(dev[0], "SIM")
304
305 def test_ap_wpa2_eap_sim_config(dev, apdev):
306     """EAP-SIM configuration options"""
307     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
308     hostapd.add_ap(apdev[0]['ifname'], params)
309     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="SIM",
310                    identity="1232010000000000",
311                    password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
312                    phase1="sim_min_num_chal=1",
313                    wait_connect=False, scan_freq="2412")
314     ev = dev[0].wait_event(["EAP: Failed to initialize EAP method: vendor 0 method 18 (SIM)"], timeout=10)
315     if ev is None:
316         raise Exception("No EAP error message seen")
317     dev[0].request("REMOVE_NETWORK all")
318
319     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="SIM",
320                    identity="1232010000000000",
321                    password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
322                    phase1="sim_min_num_chal=4",
323                    wait_connect=False, scan_freq="2412")
324     ev = dev[0].wait_event(["EAP: Failed to initialize EAP method: vendor 0 method 18 (SIM)"], timeout=10)
325     if ev is None:
326         raise Exception("No EAP error message seen (2)")
327     dev[0].request("REMOVE_NETWORK all")
328
329     eap_connect(dev[0], apdev[0], "SIM", "1232010000000000",
330                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
331                 phase1="sim_min_num_chal=2")
332     eap_connect(dev[1], apdev[0], "SIM", "1232010000000000",
333                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
334                 anonymous_identity="345678")
335
336 def test_ap_wpa2_eap_sim_ext(dev, apdev):
337     """WPA2-Enterprise connection using EAP-SIM and external GSM auth"""
338     try:
339         _test_ap_wpa2_eap_sim_ext(dev, apdev)
340     finally:
341         dev[0].request("SET external_sim 0")
342
343 def _test_ap_wpa2_eap_sim_ext(dev, apdev):
344     check_hlr_auc_gw_support()
345     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
346     hostapd.add_ap(apdev[0]['ifname'], params)
347     dev[0].request("SET external_sim 1")
348     id = dev[0].connect("test-wpa2-eap", eap="SIM", key_mgmt="WPA-EAP",
349                         identity="1232010000000000",
350                         wait_connect=False, scan_freq="2412")
351     ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=15)
352     if ev is None:
353         raise Exception("Network connected timed out")
354
355     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
356     if ev is None:
357         raise Exception("Wait for external SIM processing request timed out")
358     p = ev.split(':', 2)
359     if p[1] != "GSM-AUTH":
360         raise Exception("Unexpected CTRL-REQ-SIM type")
361     rid = p[0].split('-')[3]
362
363     # IK:CK:RES
364     resp = "00112233445566778899aabbccddeeff:00112233445566778899aabbccddeeff:0011223344"
365     # This will fail during processing, but the ctrl_iface command succeeds
366     dev[0].request("CTRL-RSP-SIM-" + rid + ":UMTS-AUTH:" + resp)
367     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
368     if ev is None:
369         raise Exception("EAP failure not reported")
370     dev[0].request("DISCONNECT")
371     dev[0].wait_disconnected()
372     time.sleep(0.1)
373
374     dev[0].select_network(id, freq="2412")
375     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
376     if ev is None:
377         raise Exception("Wait for external SIM processing request timed out")
378     p = ev.split(':', 2)
379     if p[1] != "GSM-AUTH":
380         raise Exception("Unexpected CTRL-REQ-SIM type")
381     rid = p[0].split('-')[3]
382     # This will fail during GSM auth validation
383     if "OK" not in dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:q"):
384         raise Exception("CTRL-RSP-SIM failed")
385     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
386     if ev is None:
387         raise Exception("EAP failure not reported")
388     dev[0].request("DISCONNECT")
389     dev[0].wait_disconnected()
390     time.sleep(0.1)
391
392     dev[0].select_network(id, freq="2412")
393     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
394     if ev is None:
395         raise Exception("Wait for external SIM processing request timed out")
396     p = ev.split(':', 2)
397     if p[1] != "GSM-AUTH":
398         raise Exception("Unexpected CTRL-REQ-SIM type")
399     rid = p[0].split('-')[3]
400     # This will fail during GSM auth validation
401     if "OK" not in dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:34"):
402         raise Exception("CTRL-RSP-SIM failed")
403     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
404     if ev is None:
405         raise Exception("EAP failure not reported")
406     dev[0].request("DISCONNECT")
407     dev[0].wait_disconnected()
408     time.sleep(0.1)
409
410     dev[0].select_network(id, freq="2412")
411     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
412     if ev is None:
413         raise Exception("Wait for external SIM processing request timed out")
414     p = ev.split(':', 2)
415     if p[1] != "GSM-AUTH":
416         raise Exception("Unexpected CTRL-REQ-SIM type")
417     rid = p[0].split('-')[3]
418     # This will fail during GSM auth validation
419     if "OK" not in dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:0011223344556677"):
420         raise Exception("CTRL-RSP-SIM failed")
421     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
422     if ev is None:
423         raise Exception("EAP failure not reported")
424     dev[0].request("DISCONNECT")
425     dev[0].wait_disconnected()
426     time.sleep(0.1)
427
428     dev[0].select_network(id, freq="2412")
429     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
430     if ev is None:
431         raise Exception("Wait for external SIM processing request timed out")
432     p = ev.split(':', 2)
433     if p[1] != "GSM-AUTH":
434         raise Exception("Unexpected CTRL-REQ-SIM type")
435     rid = p[0].split('-')[3]
436     # This will fail during GSM auth validation
437     if "OK" not in dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:0011223344556677:q"):
438         raise Exception("CTRL-RSP-SIM failed")
439     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
440     if ev is None:
441         raise Exception("EAP failure not reported")
442     dev[0].request("DISCONNECT")
443     dev[0].wait_disconnected()
444     time.sleep(0.1)
445
446     dev[0].select_network(id, freq="2412")
447     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
448     if ev is None:
449         raise Exception("Wait for external SIM processing request timed out")
450     p = ev.split(':', 2)
451     if p[1] != "GSM-AUTH":
452         raise Exception("Unexpected CTRL-REQ-SIM type")
453     rid = p[0].split('-')[3]
454     # This will fail during GSM auth validation
455     if "OK" not in dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:0011223344556677:00112233"):
456         raise Exception("CTRL-RSP-SIM failed")
457     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
458     if ev is None:
459         raise Exception("EAP failure not reported")
460     dev[0].request("DISCONNECT")
461     dev[0].wait_disconnected()
462     time.sleep(0.1)
463
464     dev[0].select_network(id, freq="2412")
465     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
466     if ev is None:
467         raise Exception("Wait for external SIM processing request timed out")
468     p = ev.split(':', 2)
469     if p[1] != "GSM-AUTH":
470         raise Exception("Unexpected CTRL-REQ-SIM type")
471     rid = p[0].split('-')[3]
472     # This will fail during GSM auth validation
473     if "OK" not in dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:0011223344556677:00112233:q"):
474         raise Exception("CTRL-RSP-SIM failed")
475     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
476     if ev is None:
477         raise Exception("EAP failure not reported")
478
479 def test_ap_wpa2_eap_sim_oom(dev, apdev):
480     """EAP-SIM and OOM"""
481     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
482     hostapd.add_ap(apdev[0]['ifname'], params)
483     tests = [ (1, "milenage_f2345"),
484               (2, "milenage_f2345"),
485               (3, "milenage_f2345"),
486               (4, "milenage_f2345"),
487               (5, "milenage_f2345"),
488               (6, "milenage_f2345"),
489               (7, "milenage_f2345"),
490               (8, "milenage_f2345"),
491               (9, "milenage_f2345"),
492               (10, "milenage_f2345"),
493               (11, "milenage_f2345"),
494               (12, "milenage_f2345") ]
495     for count, func in tests:
496         with alloc_fail(dev[0], count, func):
497             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="SIM",
498                            identity="1232010000000000",
499                            password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
500                            wait_connect=False, scan_freq="2412")
501             ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=5)
502             if ev is None:
503                 raise Exception("EAP method not selected")
504             dev[0].wait_disconnected()
505             dev[0].request("REMOVE_NETWORK all")
506
507 def test_ap_wpa2_eap_aka(dev, apdev):
508     """WPA2-Enterprise connection using EAP-AKA"""
509     check_hlr_auc_gw_support()
510     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
511     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
512     eap_connect(dev[0], apdev[0], "AKA", "0232010000000000",
513                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123")
514     hwsim_utils.test_connectivity(dev[0], hapd)
515     eap_reauth(dev[0], "AKA")
516
517     logger.info("Negative test with incorrect key")
518     dev[0].request("REMOVE_NETWORK all")
519     eap_connect(dev[0], apdev[0], "AKA", "0232010000000000",
520                 password="ffdca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123",
521                 expect_failure=True)
522
523     logger.info("Invalid Milenage key")
524     dev[0].request("REMOVE_NETWORK all")
525     eap_connect(dev[0], apdev[0], "AKA", "0232010000000000",
526                 password="ffdca4eda45b53cf0f12d7c9c3bc6a",
527                 expect_failure=True)
528
529     logger.info("Invalid Milenage key(2)")
530     eap_connect(dev[0], apdev[0], "AKA", "0232010000000000",
531                 password="ffdca4eda45b53cf0f12d7c9c3bc6a8q:cb9cccc4b9258e6dca4760379fb82581:000000000123",
532                 expect_failure=True)
533
534     logger.info("Invalid Milenage key(3)")
535     eap_connect(dev[0], apdev[0], "AKA", "0232010000000000",
536                 password="ffdca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb8258q:000000000123",
537                 expect_failure=True)
538
539     logger.info("Invalid Milenage key(4)")
540     eap_connect(dev[0], apdev[0], "AKA", "0232010000000000",
541                 password="ffdca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:00000000012q",
542                 expect_failure=True)
543
544     logger.info("Invalid Milenage key(5)")
545     dev[0].request("REMOVE_NETWORK all")
546     eap_connect(dev[0], apdev[0], "AKA", "0232010000000000",
547                 password="ffdca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581q000000000123",
548                 expect_failure=True)
549
550     logger.info("Invalid Milenage key(6)")
551     dev[0].request("REMOVE_NETWORK all")
552     eap_connect(dev[0], apdev[0], "AKA", "0232010000000000",
553                 password="ffdca4eda45b53cf0f12d7c9c3bc6a89qcb9cccc4b9258e6dca4760379fb82581q000000000123",
554                 expect_failure=True)
555
556     logger.info("Missing key configuration")
557     dev[0].request("REMOVE_NETWORK all")
558     eap_connect(dev[0], apdev[0], "AKA", "0232010000000000",
559                 expect_failure=True)
560
561 def test_ap_wpa2_eap_aka_sql(dev, apdev, params):
562     """WPA2-Enterprise connection using EAP-AKA (SQL)"""
563     check_hlr_auc_gw_support()
564     try:
565         import sqlite3
566     except ImportError:
567         raise HwsimSkip("No sqlite3 module available")
568     con = sqlite3.connect(os.path.join(params['logdir'], "hostapd.db"))
569     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
570     params['auth_server_port'] = "1814"
571     hostapd.add_ap(apdev[0]['ifname'], params)
572     eap_connect(dev[0], apdev[0], "AKA", "0232010000000000",
573                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123")
574
575     logger.info("AKA fast re-authentication")
576     eap_reauth(dev[0], "AKA")
577
578     logger.info("AKA full auth with pseudonym")
579     with con:
580         cur = con.cursor()
581         cur.execute("DELETE FROM reauth WHERE permanent='0232010000000000'")
582     eap_reauth(dev[0], "AKA")
583
584     logger.info("AKA full auth with permanent identity")
585     with con:
586         cur = con.cursor()
587         cur.execute("DELETE FROM reauth WHERE permanent='0232010000000000'")
588         cur.execute("DELETE FROM pseudonyms WHERE permanent='0232010000000000'")
589     eap_reauth(dev[0], "AKA")
590
591     logger.info("AKA reauth with mismatching MK")
592     with con:
593         cur = con.cursor()
594         cur.execute("UPDATE reauth SET mk='0000000000000000000000000000000000000000' WHERE permanent='0232010000000000'")
595     eap_reauth(dev[0], "AKA", expect_failure=True)
596     dev[0].request("REMOVE_NETWORK all")
597
598     eap_connect(dev[0], apdev[0], "AKA", "0232010000000000",
599                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123")
600     with con:
601         cur = con.cursor()
602         cur.execute("UPDATE reauth SET counter='10' WHERE permanent='0232010000000000'")
603     eap_reauth(dev[0], "AKA")
604     with con:
605         cur = con.cursor()
606         cur.execute("UPDATE reauth SET counter='10' WHERE permanent='0232010000000000'")
607     logger.info("AKA reauth with mismatching counter")
608     eap_reauth(dev[0], "AKA")
609     dev[0].request("REMOVE_NETWORK all")
610
611     eap_connect(dev[0], apdev[0], "AKA", "0232010000000000",
612                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123")
613     with con:
614         cur = con.cursor()
615         cur.execute("UPDATE reauth SET counter='1001' WHERE permanent='0232010000000000'")
616     logger.info("AKA reauth with max reauth count reached")
617     eap_reauth(dev[0], "AKA")
618
619 def test_ap_wpa2_eap_aka_config(dev, apdev):
620     """EAP-AKA configuration options"""
621     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
622     hostapd.add_ap(apdev[0]['ifname'], params)
623     eap_connect(dev[0], apdev[0], "AKA", "0232010000000000",
624                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123",
625                 anonymous_identity="2345678")
626
627 def test_ap_wpa2_eap_aka_ext(dev, apdev):
628     """WPA2-Enterprise connection using EAP-AKA and external UMTS auth"""
629     try:
630         _test_ap_wpa2_eap_aka_ext(dev, apdev)
631     finally:
632         dev[0].request("SET external_sim 0")
633
634 def _test_ap_wpa2_eap_aka_ext(dev, apdev):
635     check_hlr_auc_gw_support()
636     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
637     hostapd.add_ap(apdev[0]['ifname'], params)
638     dev[0].request("SET external_sim 1")
639     id = dev[0].connect("test-wpa2-eap", eap="AKA", key_mgmt="WPA-EAP",
640                         identity="0232010000000000",
641                         password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123",
642                         wait_connect=False, scan_freq="2412")
643     ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=15)
644     if ev is None:
645         raise Exception("Network connected timed out")
646
647     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
648     if ev is None:
649         raise Exception("Wait for external SIM processing request timed out")
650     p = ev.split(':', 2)
651     if p[1] != "UMTS-AUTH":
652         raise Exception("Unexpected CTRL-REQ-SIM type")
653     rid = p[0].split('-')[3]
654
655     # IK:CK:RES
656     resp = "00112233445566778899aabbccddeeff:00112233445566778899aabbccddeeff:0011223344"
657     # This will fail during processing, but the ctrl_iface command succeeds
658     dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:" + resp)
659     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
660     if ev is None:
661         raise Exception("EAP failure not reported")
662     dev[0].request("DISCONNECT")
663     dev[0].wait_disconnected()
664     time.sleep(0.1)
665     dev[0].dump_monitor()
666
667     dev[0].select_network(id, freq="2412")
668     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
669     if ev is None:
670         raise Exception("Wait for external SIM processing request timed out")
671     p = ev.split(':', 2)
672     if p[1] != "UMTS-AUTH":
673         raise Exception("Unexpected CTRL-REQ-SIM type")
674     rid = p[0].split('-')[3]
675     # This will fail during UMTS auth validation
676     if "OK" not in dev[0].request("CTRL-RSP-SIM-" + rid + ":UMTS-AUTS:112233445566778899aabbccddee"):
677         raise Exception("CTRL-RSP-SIM failed")
678     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
679     if ev is None:
680         raise Exception("Wait for external SIM processing request timed out")
681     p = ev.split(':', 2)
682     if p[1] != "UMTS-AUTH":
683         raise Exception("Unexpected CTRL-REQ-SIM type")
684     rid = p[0].split('-')[3]
685     # This will fail during UMTS auth validation
686     if "OK" not in dev[0].request("CTRL-RSP-SIM-" + rid + ":UMTS-AUTS:12"):
687         raise Exception("CTRL-RSP-SIM failed")
688     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
689     if ev is None:
690         raise Exception("EAP failure not reported")
691     dev[0].request("DISCONNECT")
692     dev[0].wait_disconnected()
693     time.sleep(0.1)
694     dev[0].dump_monitor()
695
696     tests = [ ":UMTS-AUTH:00112233445566778899aabbccddeeff:00112233445566778899aabbccddeeff:0011223344",
697               ":UMTS-AUTH:34",
698               ":UMTS-AUTH:00112233445566778899aabbccddeeff.00112233445566778899aabbccddeeff:0011223344",
699               ":UMTS-AUTH:00112233445566778899aabbccddeeff:00112233445566778899aabbccddee:0011223344",
700               ":UMTS-AUTH:00112233445566778899aabbccddeeff:00112233445566778899aabbccddeeff.0011223344",
701               ":UMTS-AUTH:00112233445566778899aabbccddeeff:00112233445566778899aabbccddeeff:00112233445566778899aabbccddeeff0011223344",
702               ":UMTS-AUTH:00112233445566778899aabbccddeeff:00112233445566778899aabbccddeeff:001122334q" ]
703     for t in tests:
704         dev[0].select_network(id, freq="2412")
705         ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
706         if ev is None:
707             raise Exception("Wait for external SIM processing request timed out")
708         p = ev.split(':', 2)
709         if p[1] != "UMTS-AUTH":
710             raise Exception("Unexpected CTRL-REQ-SIM type")
711         rid = p[0].split('-')[3]
712         # This will fail during UMTS auth validation
713         if "OK" not in dev[0].request("CTRL-RSP-SIM-" + rid + t):
714             raise Exception("CTRL-RSP-SIM failed")
715         ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
716         if ev is None:
717             raise Exception("EAP failure not reported")
718         dev[0].request("DISCONNECT")
719         dev[0].wait_disconnected()
720         time.sleep(0.1)
721         dev[0].dump_monitor()
722
723 def test_ap_wpa2_eap_aka_prime(dev, apdev):
724     """WPA2-Enterprise connection using EAP-AKA'"""
725     check_hlr_auc_gw_support()
726     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
727     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
728     eap_connect(dev[0], apdev[0], "AKA'", "6555444333222111",
729                 password="5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123")
730     hwsim_utils.test_connectivity(dev[0], hapd)
731     eap_reauth(dev[0], "AKA'")
732
733     logger.info("EAP-AKA' bidding protection when EAP-AKA enabled as well")
734     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="AKA' AKA",
735                    identity="6555444333222111@both",
736                    password="5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123",
737                    wait_connect=False, scan_freq="2412")
738     dev[1].wait_connected(timeout=15)
739
740     logger.info("Negative test with incorrect key")
741     dev[0].request("REMOVE_NETWORK all")
742     eap_connect(dev[0], apdev[0], "AKA'", "6555444333222111",
743                 password="ff22250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123",
744                 expect_failure=True)
745
746 def test_ap_wpa2_eap_aka_prime_sql(dev, apdev, params):
747     """WPA2-Enterprise connection using EAP-AKA' (SQL)"""
748     check_hlr_auc_gw_support()
749     try:
750         import sqlite3
751     except ImportError:
752         raise HwsimSkip("No sqlite3 module available")
753     con = sqlite3.connect(os.path.join(params['logdir'], "hostapd.db"))
754     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
755     params['auth_server_port'] = "1814"
756     hostapd.add_ap(apdev[0]['ifname'], params)
757     eap_connect(dev[0], apdev[0], "AKA'", "6555444333222111",
758                 password="5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123")
759
760     logger.info("AKA' fast re-authentication")
761     eap_reauth(dev[0], "AKA'")
762
763     logger.info("AKA' full auth with pseudonym")
764     with con:
765         cur = con.cursor()
766         cur.execute("DELETE FROM reauth WHERE permanent='6555444333222111'")
767     eap_reauth(dev[0], "AKA'")
768
769     logger.info("AKA' full auth with permanent identity")
770     with con:
771         cur = con.cursor()
772         cur.execute("DELETE FROM reauth WHERE permanent='6555444333222111'")
773         cur.execute("DELETE FROM pseudonyms WHERE permanent='6555444333222111'")
774     eap_reauth(dev[0], "AKA'")
775
776     logger.info("AKA' reauth with mismatching k_aut")
777     with con:
778         cur = con.cursor()
779         cur.execute("UPDATE reauth SET k_aut='0000000000000000000000000000000000000000000000000000000000000000' WHERE permanent='6555444333222111'")
780     eap_reauth(dev[0], "AKA'", expect_failure=True)
781     dev[0].request("REMOVE_NETWORK all")
782
783     eap_connect(dev[0], apdev[0], "AKA'", "6555444333222111",
784                 password="5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123")
785     with con:
786         cur = con.cursor()
787         cur.execute("UPDATE reauth SET counter='10' WHERE permanent='6555444333222111'")
788     eap_reauth(dev[0], "AKA'")
789     with con:
790         cur = con.cursor()
791         cur.execute("UPDATE reauth SET counter='10' WHERE permanent='6555444333222111'")
792     logger.info("AKA' reauth with mismatching counter")
793     eap_reauth(dev[0], "AKA'")
794     dev[0].request("REMOVE_NETWORK all")
795
796     eap_connect(dev[0], apdev[0], "AKA'", "6555444333222111",
797                 password="5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123")
798     with con:
799         cur = con.cursor()
800         cur.execute("UPDATE reauth SET counter='1001' WHERE permanent='6555444333222111'")
801     logger.info("AKA' reauth with max reauth count reached")
802     eap_reauth(dev[0], "AKA'")
803
804 def test_ap_wpa2_eap_ttls_pap(dev, apdev):
805     """WPA2-Enterprise connection using EAP-TTLS/PAP"""
806     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
807     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
808     key_mgmt = hapd.get_config()['key_mgmt']
809     if key_mgmt.split(' ')[0] != "WPA-EAP":
810         raise Exception("Unexpected GET_CONFIG(key_mgmt): " + key_mgmt)
811     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
812                 anonymous_identity="ttls", password="password",
813                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP")
814     hwsim_utils.test_connectivity(dev[0], hapd)
815     eap_reauth(dev[0], "TTLS")
816     check_mib(dev[0], [ ("dot11RSNAAuthenticationSuiteRequested", "00-0f-ac-1"),
817                         ("dot11RSNAAuthenticationSuiteSelected", "00-0f-ac-1") ])
818
819 def test_ap_wpa2_eap_ttls_pap_subject_match(dev, apdev):
820     """WPA2-Enterprise connection using EAP-TTLS/PAP and (alt)subject_match"""
821     check_subject_match_support(dev[0])
822     check_altsubject_match_support(dev[0])
823     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
824     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
825     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
826                 anonymous_identity="ttls", password="password",
827                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP",
828                 subject_match="/C=FI/O=w1.fi/CN=server.w1.fi",
829                 altsubject_match="EMAIL:noone@example.com;DNS:server.w1.fi;URI:http://example.com/")
830     eap_reauth(dev[0], "TTLS")
831
832 def test_ap_wpa2_eap_ttls_pap_incorrect_password(dev, apdev):
833     """WPA2-Enterprise connection using EAP-TTLS/PAP - incorrect password"""
834     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
835     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
836     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
837                 anonymous_identity="ttls", password="wrong",
838                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP",
839                 expect_failure=True)
840     eap_connect(dev[1], apdev[0], "TTLS", "user",
841                 anonymous_identity="ttls", password="password",
842                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP",
843                 expect_failure=True)
844
845 def test_ap_wpa2_eap_ttls_chap(dev, apdev):
846     """WPA2-Enterprise connection using EAP-TTLS/CHAP"""
847     skip_with_fips(dev[0])
848     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
849     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
850     eap_connect(dev[0], apdev[0], "TTLS", "chap user",
851                 anonymous_identity="ttls", password="password",
852                 ca_cert="auth_serv/ca.der", phase2="auth=CHAP")
853     hwsim_utils.test_connectivity(dev[0], hapd)
854     eap_reauth(dev[0], "TTLS")
855
856 def test_ap_wpa2_eap_ttls_chap_altsubject_match(dev, apdev):
857     """WPA2-Enterprise connection using EAP-TTLS/CHAP"""
858     skip_with_fips(dev[0])
859     check_altsubject_match_support(dev[0])
860     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
861     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
862     eap_connect(dev[0], apdev[0], "TTLS", "chap user",
863                 anonymous_identity="ttls", password="password",
864                 ca_cert="auth_serv/ca.der", phase2="auth=CHAP",
865                 altsubject_match="EMAIL:noone@example.com;URI:http://example.com/;DNS:server.w1.fi")
866     eap_reauth(dev[0], "TTLS")
867
868 def test_ap_wpa2_eap_ttls_chap_incorrect_password(dev, apdev):
869     """WPA2-Enterprise connection using EAP-TTLS/CHAP - incorrect password"""
870     skip_with_fips(dev[0])
871     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
872     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
873     eap_connect(dev[0], apdev[0], "TTLS", "chap user",
874                 anonymous_identity="ttls", password="wrong",
875                 ca_cert="auth_serv/ca.pem", phase2="auth=CHAP",
876                 expect_failure=True)
877     eap_connect(dev[1], apdev[0], "TTLS", "user",
878                 anonymous_identity="ttls", password="password",
879                 ca_cert="auth_serv/ca.pem", phase2="auth=CHAP",
880                 expect_failure=True)
881
882 def test_ap_wpa2_eap_ttls_mschap(dev, apdev):
883     """WPA2-Enterprise connection using EAP-TTLS/MSCHAP"""
884     skip_with_fips(dev[0])
885     check_domain_suffix_match(dev[0])
886     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
887     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
888     eap_connect(dev[0], apdev[0], "TTLS", "mschap user",
889                 anonymous_identity="ttls", password="password",
890                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
891                 domain_suffix_match="server.w1.fi")
892     hwsim_utils.test_connectivity(dev[0], hapd)
893     eap_reauth(dev[0], "TTLS")
894     dev[0].request("REMOVE_NETWORK all")
895     eap_connect(dev[0], apdev[0], "TTLS", "mschap user",
896                 anonymous_identity="ttls", password="password",
897                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
898                 fragment_size="200")
899     dev[0].request("REMOVE_NETWORK all")
900     dev[0].wait_disconnected()
901     eap_connect(dev[0], apdev[0], "TTLS", "mschap user",
902                 anonymous_identity="ttls",
903                 password_hex="hash:8846f7eaee8fb117ad06bdd830b7586c",
904                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP")
905
906 def test_ap_wpa2_eap_ttls_mschap_incorrect_password(dev, apdev):
907     """WPA2-Enterprise connection using EAP-TTLS/MSCHAP - incorrect password"""
908     skip_with_fips(dev[0])
909     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
910     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
911     eap_connect(dev[0], apdev[0], "TTLS", "mschap user",
912                 anonymous_identity="ttls", password="wrong",
913                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
914                 expect_failure=True)
915     eap_connect(dev[1], apdev[0], "TTLS", "user",
916                 anonymous_identity="ttls", password="password",
917                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
918                 expect_failure=True)
919     eap_connect(dev[2], apdev[0], "TTLS", "no such user",
920                 anonymous_identity="ttls", password="password",
921                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
922                 expect_failure=True)
923
924 def test_ap_wpa2_eap_ttls_mschapv2(dev, apdev):
925     """WPA2-Enterprise connection using EAP-TTLS/MSCHAPv2"""
926     check_domain_suffix_match(dev[0])
927     check_eap_capa(dev[0], "MSCHAPV2")
928     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
929     hostapd.add_ap(apdev[0]['ifname'], params)
930     hapd = hostapd.Hostapd(apdev[0]['ifname'])
931     eap_connect(dev[0], apdev[0], "TTLS", "DOMAIN\mschapv2 user",
932                 anonymous_identity="ttls", password="password",
933                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
934                 domain_suffix_match="server.w1.fi")
935     hwsim_utils.test_connectivity(dev[0], hapd)
936     sta1 = hapd.get_sta(dev[0].p2p_interface_addr())
937     eapol1 = hapd.get_sta(dev[0].p2p_interface_addr(), info="eapol")
938     eap_reauth(dev[0], "TTLS")
939     sta2 = hapd.get_sta(dev[0].p2p_interface_addr())
940     eapol2 = hapd.get_sta(dev[0].p2p_interface_addr(), info="eapol")
941     if int(sta2['dot1xAuthEapolFramesRx']) <= int(sta1['dot1xAuthEapolFramesRx']):
942         raise Exception("dot1xAuthEapolFramesRx did not increase")
943     if int(eapol2['authAuthEapStartsWhileAuthenticated']) < 1:
944         raise Exception("authAuthEapStartsWhileAuthenticated did not increase")
945     if int(eapol2['backendAuthSuccesses']) <= int(eapol1['backendAuthSuccesses']):
946         raise Exception("backendAuthSuccesses did not increase")
947
948     logger.info("Password as hash value")
949     dev[0].request("REMOVE_NETWORK all")
950     eap_connect(dev[0], apdev[0], "TTLS", "DOMAIN\mschapv2 user",
951                 anonymous_identity="ttls",
952                 password_hex="hash:8846f7eaee8fb117ad06bdd830b7586c",
953                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
954
955 def test_ap_wpa2_eap_ttls_invalid_phase2(dev, apdev):
956     """EAP-TTLS with invalid phase2 parameter values"""
957     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
958     hostapd.add_ap(apdev[0]['ifname'], params)
959     tests = [ "auth=MSCHAPv2", "auth=MSCHAPV2 autheap=MD5",
960               "autheap=MD5 auth=MSCHAPV2", "auth=PAP auth=CHAP",
961               "autheap=MD5 autheap=FOO autheap=MSCHAPV2" ]
962     for t in tests:
963         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
964                        identity="DOMAIN\mschapv2 user",
965                        anonymous_identity="ttls", password="password",
966                        ca_cert="auth_serv/ca.pem", phase2=t,
967                        wait_connect=False, scan_freq="2412")
968         ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=10)
969         if ev is None or "method=21" not in ev:
970             raise Exception("EAP-TTLS not started")
971         ev = dev[0].wait_event(["EAP: Failed to initialize EAP method",
972                                 "CTRL-EVENT-CONNECTED"], timeout=5)
973         if ev is None or "CTRL-EVENT-CONNECTED" in ev:
974             raise Exception("No EAP-TTLS failure reported for phase2=" + t)
975         dev[0].request("REMOVE_NETWORK all")
976         dev[0].wait_disconnected()
977         dev[0].dump_monitor()
978
979 def test_ap_wpa2_eap_ttls_mschapv2_suffix_match(dev, apdev):
980     """WPA2-Enterprise connection using EAP-TTLS/MSCHAPv2"""
981     check_domain_match_full(dev[0])
982     skip_with_fips(dev[0])
983     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
984     hostapd.add_ap(apdev[0]['ifname'], params)
985     hapd = hostapd.Hostapd(apdev[0]['ifname'])
986     eap_connect(dev[0], apdev[0], "TTLS", "DOMAIN\mschapv2 user",
987                 anonymous_identity="ttls", password="password",
988                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
989                 domain_suffix_match="w1.fi")
990     hwsim_utils.test_connectivity(dev[0], hapd)
991     eap_reauth(dev[0], "TTLS")
992
993 def test_ap_wpa2_eap_ttls_mschapv2_domain_match(dev, apdev):
994     """WPA2-Enterprise connection using EAP-TTLS/MSCHAPv2 (domain_match)"""
995     check_domain_match(dev[0])
996     skip_with_fips(dev[0])
997     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
998     hostapd.add_ap(apdev[0]['ifname'], params)
999     hapd = hostapd.Hostapd(apdev[0]['ifname'])
1000     eap_connect(dev[0], apdev[0], "TTLS", "DOMAIN\mschapv2 user",
1001                 anonymous_identity="ttls", password="password",
1002                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1003                 domain_match="Server.w1.fi")
1004     hwsim_utils.test_connectivity(dev[0], hapd)
1005     eap_reauth(dev[0], "TTLS")
1006
1007 def test_ap_wpa2_eap_ttls_mschapv2_incorrect_password(dev, apdev):
1008     """WPA2-Enterprise connection using EAP-TTLS/MSCHAPv2 - incorrect password"""
1009     skip_with_fips(dev[0])
1010     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1011     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1012     eap_connect(dev[0], apdev[0], "TTLS", "DOMAIN\mschapv2 user",
1013                 anonymous_identity="ttls", password="password1",
1014                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1015                 expect_failure=True)
1016     eap_connect(dev[1], apdev[0], "TTLS", "user",
1017                 anonymous_identity="ttls", password="password",
1018                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1019                 expect_failure=True)
1020
1021 def test_ap_wpa2_eap_ttls_mschapv2_utf8(dev, apdev):
1022     """WPA2-Enterprise connection using EAP-TTLS/MSCHAPv2 and UTF-8 password"""
1023     skip_with_fips(dev[0])
1024     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1025     hostapd.add_ap(apdev[0]['ifname'], params)
1026     hapd = hostapd.Hostapd(apdev[0]['ifname'])
1027     eap_connect(dev[0], apdev[0], "TTLS", "utf8-user-hash",
1028                 anonymous_identity="ttls", password="secret-åäö-€-password",
1029                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
1030     eap_connect(dev[1], apdev[0], "TTLS", "utf8-user",
1031                 anonymous_identity="ttls",
1032                 password_hex="hash:bd5844fad2489992da7fe8c5a01559cf",
1033                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
1034     for p in [ "80", "41c041e04141e041", 257*"41" ]:
1035         dev[2].connect("test-wpa2-eap", key_mgmt="WPA-EAP",
1036                        eap="TTLS", identity="utf8-user-hash",
1037                        anonymous_identity="ttls", password_hex=p,
1038                        ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1039                        wait_connect=False, scan_freq="2412")
1040         ev = dev[2].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=1)
1041         if ev is None:
1042             raise Exception("No failure reported")
1043         dev[2].request("REMOVE_NETWORK all")
1044         dev[2].wait_disconnected()
1045
1046 def test_ap_wpa2_eap_ttls_eap_gtc(dev, apdev):
1047     """WPA2-Enterprise connection using EAP-TTLS/EAP-GTC"""
1048     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1049     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1050     eap_connect(dev[0], apdev[0], "TTLS", "user",
1051                 anonymous_identity="ttls", password="password",
1052                 ca_cert="auth_serv/ca.pem", phase2="autheap=GTC")
1053     hwsim_utils.test_connectivity(dev[0], hapd)
1054     eap_reauth(dev[0], "TTLS")
1055
1056 def test_ap_wpa2_eap_ttls_eap_gtc_incorrect_password(dev, apdev):
1057     """WPA2-Enterprise connection using EAP-TTLS/EAP-GTC - incorrect password"""
1058     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1059     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1060     eap_connect(dev[0], apdev[0], "TTLS", "user",
1061                 anonymous_identity="ttls", password="wrong",
1062                 ca_cert="auth_serv/ca.pem", phase2="autheap=GTC",
1063                 expect_failure=True)
1064
1065 def test_ap_wpa2_eap_ttls_eap_gtc_no_password(dev, apdev):
1066     """WPA2-Enterprise connection using EAP-TTLS/EAP-GTC - no password"""
1067     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1068     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1069     eap_connect(dev[0], apdev[0], "TTLS", "user-no-passwd",
1070                 anonymous_identity="ttls", password="password",
1071                 ca_cert="auth_serv/ca.pem", phase2="autheap=GTC",
1072                 expect_failure=True)
1073
1074 def test_ap_wpa2_eap_ttls_eap_gtc_server_oom(dev, apdev):
1075     """WPA2-Enterprise connection using EAP-TTLS/EAP-GTC - server OOM"""
1076     params = int_eap_server_params()
1077     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1078     with alloc_fail(hapd, 1, "eap_gtc_init"):
1079         eap_connect(dev[0], apdev[0], "TTLS", "user",
1080                     anonymous_identity="ttls", password="password",
1081                     ca_cert="auth_serv/ca.pem", phase2="autheap=GTC",
1082                     expect_failure=True)
1083         dev[0].request("REMOVE_NETWORK all")
1084
1085     with alloc_fail(hapd, 1, "eap_gtc_buildReq"):
1086         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
1087                        eap="TTLS", identity="user",
1088                        anonymous_identity="ttls", password="password",
1089                        ca_cert="auth_serv/ca.pem", phase2="autheap=GTC",
1090                        wait_connect=False, scan_freq="2412")
1091         # This would eventually time out, but we can stop after having reached
1092         # the allocation failure.
1093         for i in range(20):
1094             time.sleep(0.1)
1095             if hapd.request("GET_ALLOC_FAIL").startswith('0'):
1096                 break
1097
1098 def test_ap_wpa2_eap_ttls_eap_md5(dev, apdev):
1099     """WPA2-Enterprise connection using EAP-TTLS/EAP-MD5"""
1100     check_eap_capa(dev[0], "MD5")
1101     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1102     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1103     eap_connect(dev[0], apdev[0], "TTLS", "user",
1104                 anonymous_identity="ttls", password="password",
1105                 ca_cert="auth_serv/ca.pem", phase2="autheap=MD5")
1106     hwsim_utils.test_connectivity(dev[0], hapd)
1107     eap_reauth(dev[0], "TTLS")
1108
1109 def test_ap_wpa2_eap_ttls_eap_md5_incorrect_password(dev, apdev):
1110     """WPA2-Enterprise connection using EAP-TTLS/EAP-MD5 - incorrect password"""
1111     check_eap_capa(dev[0], "MD5")
1112     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1113     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1114     eap_connect(dev[0], apdev[0], "TTLS", "user",
1115                 anonymous_identity="ttls", password="wrong",
1116                 ca_cert="auth_serv/ca.pem", phase2="autheap=MD5",
1117                 expect_failure=True)
1118
1119 def test_ap_wpa2_eap_ttls_eap_md5_no_password(dev, apdev):
1120     """WPA2-Enterprise connection using EAP-TTLS/EAP-MD5 - no password"""
1121     check_eap_capa(dev[0], "MD5")
1122     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1123     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1124     eap_connect(dev[0], apdev[0], "TTLS", "user-no-passwd",
1125                 anonymous_identity="ttls", password="password",
1126                 ca_cert="auth_serv/ca.pem", phase2="autheap=MD5",
1127                 expect_failure=True)
1128
1129 def test_ap_wpa2_eap_ttls_eap_md5_server_oom(dev, apdev):
1130     """WPA2-Enterprise connection using EAP-TTLS/EAP-MD5 - server OOM"""
1131     check_eap_capa(dev[0], "MD5")
1132     params = int_eap_server_params()
1133     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1134     with alloc_fail(hapd, 1, "eap_md5_init"):
1135         eap_connect(dev[0], apdev[0], "TTLS", "user",
1136                     anonymous_identity="ttls", password="password",
1137                     ca_cert="auth_serv/ca.pem", phase2="autheap=MD5",
1138                     expect_failure=True)
1139         dev[0].request("REMOVE_NETWORK all")
1140
1141     with alloc_fail(hapd, 1, "eap_md5_buildReq"):
1142         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
1143                        eap="TTLS", identity="user",
1144                        anonymous_identity="ttls", password="password",
1145                        ca_cert="auth_serv/ca.pem", phase2="autheap=MD5",
1146                        wait_connect=False, scan_freq="2412")
1147         # This would eventually time out, but we can stop after having reached
1148         # the allocation failure.
1149         for i in range(20):
1150             time.sleep(0.1)
1151             if hapd.request("GET_ALLOC_FAIL").startswith('0'):
1152                 break
1153
1154 def test_ap_wpa2_eap_ttls_eap_mschapv2(dev, apdev):
1155     """WPA2-Enterprise connection using EAP-TTLS/EAP-MSCHAPv2"""
1156     check_eap_capa(dev[0], "MSCHAPV2")
1157     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1158     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1159     eap_connect(dev[0], apdev[0], "TTLS", "user",
1160                 anonymous_identity="ttls", password="password",
1161                 ca_cert="auth_serv/ca.pem", phase2="autheap=MSCHAPV2")
1162     hwsim_utils.test_connectivity(dev[0], hapd)
1163     eap_reauth(dev[0], "TTLS")
1164
1165     logger.info("Negative test with incorrect password")
1166     dev[0].request("REMOVE_NETWORK all")
1167     eap_connect(dev[0], apdev[0], "TTLS", "user",
1168                 anonymous_identity="ttls", password="password1",
1169                 ca_cert="auth_serv/ca.pem", phase2="autheap=MSCHAPV2",
1170                 expect_failure=True)
1171
1172 def test_ap_wpa2_eap_ttls_eap_mschapv2_no_password(dev, apdev):
1173     """WPA2-Enterprise connection using EAP-TTLS/EAP-MSCHAPv2 - no password"""
1174     check_eap_capa(dev[0], "MSCHAPV2")
1175     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1176     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1177     eap_connect(dev[0], apdev[0], "TTLS", "user-no-passwd",
1178                 anonymous_identity="ttls", password="password",
1179                 ca_cert="auth_serv/ca.pem", phase2="autheap=MSCHAPV2",
1180                 expect_failure=True)
1181
1182 def test_ap_wpa2_eap_ttls_eap_mschapv2_server_oom(dev, apdev):
1183     """WPA2-Enterprise connection using EAP-TTLS/EAP-MSCHAPv2 - server OOM"""
1184     check_eap_capa(dev[0], "MSCHAPV2")
1185     params = int_eap_server_params()
1186     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1187     with alloc_fail(hapd, 1, "eap_mschapv2_init"):
1188         eap_connect(dev[0], apdev[0], "TTLS", "user",
1189                     anonymous_identity="ttls", password="password",
1190                     ca_cert="auth_serv/ca.pem", phase2="autheap=MSCHAPV2",
1191                     expect_failure=True)
1192         dev[0].request("REMOVE_NETWORK all")
1193
1194     with alloc_fail(hapd, 1, "eap_mschapv2_build_challenge"):
1195         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
1196                        eap="TTLS", identity="user",
1197                        anonymous_identity="ttls", password="password",
1198                        ca_cert="auth_serv/ca.pem", phase2="autheap=MSCHAPV2",
1199                        wait_connect=False, scan_freq="2412")
1200         # This would eventually time out, but we can stop after having reached
1201         # the allocation failure.
1202         for i in range(20):
1203             time.sleep(0.1)
1204             if hapd.request("GET_ALLOC_FAIL").startswith('0'):
1205                 break
1206         dev[0].request("REMOVE_NETWORK all")
1207
1208     with alloc_fail(hapd, 1, "eap_mschapv2_build_success_req"):
1209         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
1210                        eap="TTLS", identity="user",
1211                        anonymous_identity="ttls", password="password",
1212                        ca_cert="auth_serv/ca.pem", phase2="autheap=MSCHAPV2",
1213                        wait_connect=False, scan_freq="2412")
1214         # This would eventually time out, but we can stop after having reached
1215         # the allocation failure.
1216         for i in range(20):
1217             time.sleep(0.1)
1218             if hapd.request("GET_ALLOC_FAIL").startswith('0'):
1219                 break
1220         dev[0].request("REMOVE_NETWORK all")
1221
1222     with alloc_fail(hapd, 1, "eap_mschapv2_build_failure_req"):
1223         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
1224                        eap="TTLS", identity="user",
1225                        anonymous_identity="ttls", password="wrong",
1226                        ca_cert="auth_serv/ca.pem", phase2="autheap=MSCHAPV2",
1227                        wait_connect=False, scan_freq="2412")
1228         # This would eventually time out, but we can stop after having reached
1229         # the allocation failure.
1230         for i in range(20):
1231             time.sleep(0.1)
1232             if hapd.request("GET_ALLOC_FAIL").startswith('0'):
1233                 break
1234         dev[0].request("REMOVE_NETWORK all")
1235
1236 def test_ap_wpa2_eap_ttls_eap_aka(dev, apdev):
1237     """WPA2-Enterprise connection using EAP-TTLS/EAP-AKA"""
1238     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1239     hostapd.add_ap(apdev[0]['ifname'], params)
1240     eap_connect(dev[0], apdev[0], "TTLS", "0232010000000000",
1241                 anonymous_identity="0232010000000000@ttls",
1242                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123",
1243                 ca_cert="auth_serv/ca.pem", phase2="autheap=AKA")
1244
1245 def test_ap_wpa2_eap_peap_eap_aka(dev, apdev):
1246     """WPA2-Enterprise connection using EAP-PEAP/EAP-AKA"""
1247     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1248     hostapd.add_ap(apdev[0]['ifname'], params)
1249     eap_connect(dev[0], apdev[0], "PEAP", "0232010000000000",
1250                 anonymous_identity="0232010000000000@peap",
1251                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123",
1252                 ca_cert="auth_serv/ca.pem", phase2="auth=AKA")
1253
1254 def test_ap_wpa2_eap_fast_eap_aka(dev, apdev):
1255     """WPA2-Enterprise connection using EAP-FAST/EAP-AKA"""
1256     check_eap_capa(dev[0], "FAST")
1257     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1258     hostapd.add_ap(apdev[0]['ifname'], params)
1259     eap_connect(dev[0], apdev[0], "FAST", "0232010000000000",
1260                 anonymous_identity="0232010000000000@fast",
1261                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123",
1262                 phase1="fast_provisioning=2",
1263                 pac_file="blob://fast_pac_auth_aka",
1264                 ca_cert="auth_serv/ca.pem", phase2="auth=AKA")
1265
1266 def test_ap_wpa2_eap_peap_eap_mschapv2(dev, apdev):
1267     """WPA2-Enterprise connection using EAP-PEAP/EAP-MSCHAPv2"""
1268     check_eap_capa(dev[0], "MSCHAPV2")
1269     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1270     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1271     eap_connect(dev[0], apdev[0], "PEAP", "user",
1272                 anonymous_identity="peap", password="password",
1273                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
1274     hwsim_utils.test_connectivity(dev[0], hapd)
1275     eap_reauth(dev[0], "PEAP")
1276     dev[0].request("REMOVE_NETWORK all")
1277     eap_connect(dev[0], apdev[0], "PEAP", "user",
1278                 anonymous_identity="peap", password="password",
1279                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1280                 fragment_size="200")
1281
1282     logger.info("Password as hash value")
1283     dev[0].request("REMOVE_NETWORK all")
1284     eap_connect(dev[0], apdev[0], "PEAP", "user",
1285                 anonymous_identity="peap",
1286                 password_hex="hash:8846f7eaee8fb117ad06bdd830b7586c",
1287                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
1288
1289     logger.info("Negative test with incorrect password")
1290     dev[0].request("REMOVE_NETWORK all")
1291     eap_connect(dev[0], apdev[0], "PEAP", "user",
1292                 anonymous_identity="peap", password="password1",
1293                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1294                 expect_failure=True)
1295
1296 def test_ap_wpa2_eap_peap_eap_mschapv2_domain(dev, apdev):
1297     """WPA2-Enterprise connection using EAP-PEAP/EAP-MSCHAPv2 with domain"""
1298     check_eap_capa(dev[0], "MSCHAPV2")
1299     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1300     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1301     eap_connect(dev[0], apdev[0], "PEAP", "DOMAIN\user3",
1302                 anonymous_identity="peap", password="password",
1303                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
1304     hwsim_utils.test_connectivity(dev[0], hapd)
1305     eap_reauth(dev[0], "PEAP")
1306
1307 def test_ap_wpa2_eap_peap_eap_mschapv2_incorrect_password(dev, apdev):
1308     """WPA2-Enterprise connection using EAP-PEAP/EAP-MSCHAPv2 - incorrect password"""
1309     check_eap_capa(dev[0], "MSCHAPV2")
1310     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1311     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1312     eap_connect(dev[0], apdev[0], "PEAP", "user",
1313                 anonymous_identity="peap", password="wrong",
1314                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1315                 expect_failure=True)
1316
1317 def test_ap_wpa2_eap_peap_crypto_binding(dev, apdev):
1318     """WPA2-Enterprise connection using EAP-PEAPv0/EAP-MSCHAPv2 and crypto binding"""
1319     check_eap_capa(dev[0], "MSCHAPV2")
1320     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1321     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1322     eap_connect(dev[0], apdev[0], "PEAP", "user", password="password",
1323                 ca_cert="auth_serv/ca.pem",
1324                 phase1="peapver=0 crypto_binding=2",
1325                 phase2="auth=MSCHAPV2")
1326     hwsim_utils.test_connectivity(dev[0], hapd)
1327     eap_reauth(dev[0], "PEAP")
1328
1329     eap_connect(dev[1], apdev[0], "PEAP", "user", password="password",
1330                 ca_cert="auth_serv/ca.pem",
1331                 phase1="peapver=0 crypto_binding=1",
1332                 phase2="auth=MSCHAPV2")
1333     eap_connect(dev[2], apdev[0], "PEAP", "user", password="password",
1334                 ca_cert="auth_serv/ca.pem",
1335                 phase1="peapver=0 crypto_binding=0",
1336                 phase2="auth=MSCHAPV2")
1337
1338 def test_ap_wpa2_eap_peap_crypto_binding_server_oom(dev, apdev):
1339     """WPA2-Enterprise connection using EAP-PEAPv0/EAP-MSCHAPv2 and crypto binding with server OOM"""
1340     check_eap_capa(dev[0], "MSCHAPV2")
1341     params = int_eap_server_params()
1342     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1343     with alloc_fail(hapd, 1, "eap_mschapv2_getKey"):
1344         eap_connect(dev[0], apdev[0], "PEAP", "user", password="password",
1345                     ca_cert="auth_serv/ca.pem",
1346                     phase1="peapver=0 crypto_binding=2",
1347                     phase2="auth=MSCHAPV2",
1348                     expect_failure=True, local_error_report=True)
1349
1350 def test_ap_wpa2_eap_peap_params(dev, apdev):
1351     """WPA2-Enterprise connection using EAP-PEAPv0/EAP-MSCHAPv2 and various parameters"""
1352     check_eap_capa(dev[0], "MSCHAPV2")
1353     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1354     hostapd.add_ap(apdev[0]['ifname'], params)
1355     eap_connect(dev[0], apdev[0], "PEAP", "user",
1356                 anonymous_identity="peap", password="password",
1357                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1358                 phase1="peapver=0 peaplabel=1",
1359                 expect_failure=True)
1360     dev[0].request("REMOVE_NETWORK all")
1361     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PEAP",
1362                    identity="user",
1363                    anonymous_identity="peap", password="password",
1364                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1365                    phase1="peap_outer_success=0",
1366                    wait_connect=False, scan_freq="2412")
1367     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=15)
1368     if ev is None:
1369         raise Exception("No EAP success seen")
1370     # This won't succeed to connect with peap_outer_success=0, so stop here.
1371     dev[0].request("REMOVE_NETWORK all")
1372     dev[0].wait_disconnected()
1373     eap_connect(dev[1], apdev[0], "PEAP", "user", password="password",
1374                 ca_cert="auth_serv/ca.pem",
1375                 phase1="peap_outer_success=1",
1376                 phase2="auth=MSCHAPV2")
1377     eap_connect(dev[2], apdev[0], "PEAP", "user", password="password",
1378                 ca_cert="auth_serv/ca.pem",
1379                 phase1="peap_outer_success=2",
1380                 phase2="auth=MSCHAPV2")
1381     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PEAP",
1382                    identity="user",
1383                    anonymous_identity="peap", password="password",
1384                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1385                    phase1="peapver=1 peaplabel=1",
1386                    wait_connect=False, scan_freq="2412")
1387     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=15)
1388     if ev is None:
1389         raise Exception("No EAP success seen")
1390     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
1391     if ev is not None:
1392         raise Exception("Unexpected connection")
1393
1394     tests = [ ("peap-ver0", ""),
1395               ("peap-ver1", ""),
1396               ("peap-ver0", "peapver=0"),
1397               ("peap-ver1", "peapver=1") ]
1398     for anon,phase1 in tests:
1399         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PEAP",
1400                        identity="user", anonymous_identity=anon,
1401                        password="password", phase1=phase1,
1402                        ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1403                        scan_freq="2412")
1404         dev[0].request("REMOVE_NETWORK all")
1405         dev[0].wait_disconnected()
1406
1407     tests = [ ("peap-ver0", "peapver=1"),
1408               ("peap-ver1", "peapver=0") ]
1409     for anon,phase1 in tests:
1410         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PEAP",
1411                        identity="user", anonymous_identity=anon,
1412                        password="password", phase1=phase1,
1413                        ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1414                        wait_connect=False, scan_freq="2412")
1415         ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
1416         if ev is None:
1417             raise Exception("No EAP-Failure seen")
1418         dev[0].request("REMOVE_NETWORK all")
1419         dev[0].wait_disconnected()
1420
1421     eap_connect(dev[0], apdev[0], "PEAP", "user", password="password",
1422                 ca_cert="auth_serv/ca.pem",
1423                 phase1="tls_allow_md5=1 tls_disable_session_ticket=1 tls_disable_tlsv1_0=0 tls_disable_tlsv1_1=0 tls_disable_tlsv1_2=0 tls_ext_cert_check=0",
1424                 phase2="auth=MSCHAPV2")
1425
1426 def test_ap_wpa2_eap_peap_eap_tls(dev, apdev):
1427     """WPA2-Enterprise connection using EAP-PEAP/EAP-TLS"""
1428     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1429     hostapd.add_ap(apdev[0]['ifname'], params)
1430     eap_connect(dev[0], apdev[0], "PEAP", "cert user",
1431                 ca_cert="auth_serv/ca.pem", phase2="auth=TLS",
1432                 ca_cert2="auth_serv/ca.pem",
1433                 client_cert2="auth_serv/user.pem",
1434                 private_key2="auth_serv/user.key")
1435     eap_reauth(dev[0], "PEAP")
1436
1437 def test_ap_wpa2_eap_tls(dev, apdev):
1438     """WPA2-Enterprise connection using EAP-TLS"""
1439     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1440     hostapd.add_ap(apdev[0]['ifname'], params)
1441     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
1442                 client_cert="auth_serv/user.pem",
1443                 private_key="auth_serv/user.key")
1444     eap_reauth(dev[0], "TLS")
1445
1446 def test_eap_tls_pkcs8_pkcs5_v2_des3(dev, apdev):
1447     """WPA2-Enterprise connection using EAP-TLS and PKCS #8, PKCS #5 v2 DES3 key"""
1448     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1449     hostapd.add_ap(apdev[0]['ifname'], params)
1450     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
1451                 client_cert="auth_serv/user.pem",
1452                 private_key="auth_serv/user.key.pkcs8",
1453                 private_key_passwd="whatever")
1454
1455 def test_eap_tls_pkcs8_pkcs5_v15(dev, apdev):
1456     """WPA2-Enterprise connection using EAP-TLS and PKCS #8, PKCS #5 v1.5 key"""
1457     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1458     hostapd.add_ap(apdev[0]['ifname'], params)
1459     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
1460                 client_cert="auth_serv/user.pem",
1461                 private_key="auth_serv/user.key.pkcs8.pkcs5v15",
1462                 private_key_passwd="whatever")
1463
1464 def test_ap_wpa2_eap_tls_blob(dev, apdev):
1465     """WPA2-Enterprise connection using EAP-TLS and config blobs"""
1466     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1467     hostapd.add_ap(apdev[0]['ifname'], params)
1468     cert = read_pem("auth_serv/ca.pem")
1469     if "OK" not in dev[0].request("SET blob cacert " + cert.encode("hex")):
1470         raise Exception("Could not set cacert blob")
1471     cert = read_pem("auth_serv/user.pem")
1472     if "OK" not in dev[0].request("SET blob usercert " + cert.encode("hex")):
1473         raise Exception("Could not set usercert blob")
1474     key = read_pem("auth_serv/user.rsa-key")
1475     if "OK" not in dev[0].request("SET blob userkey " + key.encode("hex")):
1476         raise Exception("Could not set cacert blob")
1477     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="blob://cacert",
1478                 client_cert="blob://usercert",
1479                 private_key="blob://userkey")
1480
1481 def test_ap_wpa2_eap_tls_blob_missing(dev, apdev):
1482     """EAP-TLS and config blob missing"""
1483     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1484     hostapd.add_ap(apdev[0]['ifname'], params)
1485     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
1486                    identity="tls user",
1487                    ca_cert="blob://testing-blob-does-not-exist",
1488                    client_cert="blob://testing-blob-does-not-exist",
1489                    private_key="blob://testing-blob-does-not-exist",
1490                    wait_connect=False, scan_freq="2412")
1491     ev = dev[0].wait_event(["EAP: Failed to initialize EAP method"], timeout=10)
1492     if ev is None:
1493         raise Exception("EAP failure not reported")
1494     dev[0].request("REMOVE_NETWORK all")
1495     dev[0].wait_disconnected()
1496
1497 def test_ap_wpa2_eap_tls_with_tls_len(dev, apdev):
1498     """EAP-TLS and TLS Message Length in unfragmented packets"""
1499     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1500     hostapd.add_ap(apdev[0]['ifname'], params)
1501     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
1502                 phase1="include_tls_length=1",
1503                 client_cert="auth_serv/user.pem",
1504                 private_key="auth_serv/user.key")
1505
1506 def test_ap_wpa2_eap_tls_pkcs12(dev, apdev):
1507     """WPA2-Enterprise connection using EAP-TLS and PKCS#12"""
1508     check_pkcs12_support(dev[0])
1509     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1510     hostapd.add_ap(apdev[0]['ifname'], params)
1511     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
1512                 private_key="auth_serv/user.pkcs12",
1513                 private_key_passwd="whatever")
1514     dev[0].request("REMOVE_NETWORK all")
1515     dev[0].wait_disconnected()
1516
1517     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
1518                    identity="tls user",
1519                    ca_cert="auth_serv/ca.pem",
1520                    private_key="auth_serv/user.pkcs12",
1521                    wait_connect=False, scan_freq="2412")
1522     ev = dev[0].wait_event(["CTRL-REQ-PASSPHRASE"])
1523     if ev is None:
1524         raise Exception("Request for private key passphrase timed out")
1525     id = ev.split(':')[0].split('-')[-1]
1526     dev[0].request("CTRL-RSP-PASSPHRASE-" + id + ":whatever")
1527     dev[0].wait_connected(timeout=10)
1528     dev[0].request("REMOVE_NETWORK all")
1529     dev[0].wait_disconnected()
1530
1531     # Run this twice to verify certificate chain handling with OpenSSL. Use two
1532     # different files to cover both cases of the extra certificate being the
1533     # one that signed the client certificate and it being unrelated to the
1534     # client certificate.
1535     for pkcs12 in "auth_serv/user2.pkcs12", "auth_serv/user3.pkcs12":
1536         for i in range(2):
1537             eap_connect(dev[0], apdev[0], "TLS", "tls user",
1538                         ca_cert="auth_serv/ca.pem",
1539                         private_key=pkcs12,
1540                         private_key_passwd="whatever")
1541             dev[0].request("REMOVE_NETWORK all")
1542             dev[0].wait_disconnected()
1543
1544 def test_ap_wpa2_eap_tls_pkcs12_blob(dev, apdev):
1545     """WPA2-Enterprise connection using EAP-TLS and PKCS#12 from configuration blob"""
1546     check_pkcs12_support(dev[0])
1547     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1548     hostapd.add_ap(apdev[0]['ifname'], params)
1549     cert = read_pem("auth_serv/ca.pem")
1550     if "OK" not in dev[0].request("SET blob cacert " + cert.encode("hex")):
1551         raise Exception("Could not set cacert blob")
1552     with open("auth_serv/user.pkcs12", "rb") as f:
1553         if "OK" not in dev[0].request("SET blob pkcs12 " + f.read().encode("hex")):
1554             raise Exception("Could not set pkcs12 blob")
1555     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="blob://cacert",
1556                 private_key="blob://pkcs12",
1557                 private_key_passwd="whatever")
1558
1559 def test_ap_wpa2_eap_tls_neg_incorrect_trust_root(dev, apdev):
1560     """WPA2-Enterprise negative test - incorrect trust root"""
1561     check_eap_capa(dev[0], "MSCHAPV2")
1562     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1563     hostapd.add_ap(apdev[0]['ifname'], params)
1564     cert = read_pem("auth_serv/ca-incorrect.pem")
1565     if "OK" not in dev[0].request("SET blob cacert " + cert.encode("hex")):
1566         raise Exception("Could not set cacert blob")
1567     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
1568                    identity="DOMAIN\mschapv2 user", anonymous_identity="ttls",
1569                    password="password", phase2="auth=MSCHAPV2",
1570                    ca_cert="blob://cacert",
1571                    wait_connect=False, scan_freq="2412")
1572     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
1573                    identity="DOMAIN\mschapv2 user", anonymous_identity="ttls",
1574                    password="password", phase2="auth=MSCHAPV2",
1575                    ca_cert="auth_serv/ca-incorrect.pem",
1576                    wait_connect=False, scan_freq="2412")
1577
1578     for dev in (dev[0], dev[1]):
1579         ev = dev.wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
1580         if ev is None:
1581             raise Exception("Association and EAP start timed out")
1582
1583         ev = dev.wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=10)
1584         if ev is None:
1585             raise Exception("EAP method selection timed out")
1586         if "TTLS" not in ev:
1587             raise Exception("Unexpected EAP method")
1588
1589         ev = dev.wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR",
1590                              "CTRL-EVENT-EAP-SUCCESS",
1591                              "CTRL-EVENT-EAP-FAILURE",
1592                              "CTRL-EVENT-CONNECTED",
1593                              "CTRL-EVENT-DISCONNECTED"], timeout=10)
1594         if ev is None:
1595             raise Exception("EAP result timed out")
1596         if "CTRL-EVENT-EAP-TLS-CERT-ERROR" not in ev:
1597             raise Exception("TLS certificate error not reported")
1598
1599         ev = dev.wait_event(["CTRL-EVENT-EAP-SUCCESS",
1600                              "CTRL-EVENT-EAP-FAILURE",
1601                              "CTRL-EVENT-CONNECTED",
1602                              "CTRL-EVENT-DISCONNECTED"], timeout=10)
1603         if ev is None:
1604             raise Exception("EAP result(2) timed out")
1605         if "CTRL-EVENT-EAP-FAILURE" not in ev:
1606             raise Exception("EAP failure not reported")
1607
1608         ev = dev.wait_event(["CTRL-EVENT-CONNECTED",
1609                              "CTRL-EVENT-DISCONNECTED"], timeout=10)
1610         if ev is None:
1611             raise Exception("EAP result(3) timed out")
1612         if "CTRL-EVENT-DISCONNECTED" not in ev:
1613             raise Exception("Disconnection not reported")
1614
1615         ev = dev.wait_event(["CTRL-EVENT-SSID-TEMP-DISABLED"], timeout=10)
1616         if ev is None:
1617             raise Exception("Network block disabling not reported")
1618
1619 def test_ap_wpa2_eap_tls_diff_ca_trust(dev, apdev):
1620     """WPA2-Enterprise connection using EAP-TTLS/PAP and different CA trust"""
1621     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1622     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1623     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
1624                    identity="pap user", anonymous_identity="ttls",
1625                    password="password", phase2="auth=PAP",
1626                    ca_cert="auth_serv/ca.pem",
1627                    wait_connect=True, scan_freq="2412")
1628     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
1629                         identity="pap user", anonymous_identity="ttls",
1630                         password="password", phase2="auth=PAP",
1631                         ca_cert="auth_serv/ca-incorrect.pem",
1632                         only_add_network=True, scan_freq="2412")
1633
1634     dev[0].request("DISCONNECT")
1635     dev[0].wait_disconnected()
1636     dev[0].dump_monitor()
1637     dev[0].select_network(id, freq="2412")
1638
1639     ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD vendor=0 method=21"], timeout=15)
1640     if ev is None:
1641         raise Exception("EAP-TTLS not re-started")
1642     
1643     ev = dev[0].wait_disconnected(timeout=15)
1644     if "reason=23" not in ev:
1645         raise Exception("Proper reason code for disconnection not reported")
1646
1647 def test_ap_wpa2_eap_tls_diff_ca_trust2(dev, apdev):
1648     """WPA2-Enterprise connection using EAP-TTLS/PAP and different CA trust"""
1649     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1650     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1651     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
1652                    identity="pap user", anonymous_identity="ttls",
1653                    password="password", phase2="auth=PAP",
1654                    wait_connect=True, scan_freq="2412")
1655     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
1656                         identity="pap user", anonymous_identity="ttls",
1657                         password="password", phase2="auth=PAP",
1658                         ca_cert="auth_serv/ca-incorrect.pem",
1659                         only_add_network=True, scan_freq="2412")
1660
1661     dev[0].request("DISCONNECT")
1662     dev[0].wait_disconnected()
1663     dev[0].dump_monitor()
1664     dev[0].select_network(id, freq="2412")
1665
1666     ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD vendor=0 method=21"], timeout=15)
1667     if ev is None:
1668         raise Exception("EAP-TTLS not re-started")
1669     
1670     ev = dev[0].wait_disconnected(timeout=15)
1671     if "reason=23" not in ev:
1672         raise Exception("Proper reason code for disconnection not reported")
1673
1674 def test_ap_wpa2_eap_tls_diff_ca_trust3(dev, apdev):
1675     """WPA2-Enterprise connection using EAP-TTLS/PAP and different CA trust"""
1676     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1677     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1678     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
1679                         identity="pap user", anonymous_identity="ttls",
1680                         password="password", phase2="auth=PAP",
1681                         ca_cert="auth_serv/ca.pem",
1682                         wait_connect=True, scan_freq="2412")
1683     dev[0].request("DISCONNECT")
1684     dev[0].wait_disconnected()
1685     dev[0].dump_monitor()
1686     dev[0].set_network_quoted(id, "ca_cert", "auth_serv/ca-incorrect.pem")
1687     dev[0].select_network(id, freq="2412")
1688
1689     ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD vendor=0 method=21"], timeout=15)
1690     if ev is None:
1691         raise Exception("EAP-TTLS not re-started")
1692     
1693     ev = dev[0].wait_disconnected(timeout=15)
1694     if "reason=23" not in ev:
1695         raise Exception("Proper reason code for disconnection not reported")
1696
1697 def test_ap_wpa2_eap_tls_neg_suffix_match(dev, apdev):
1698     """WPA2-Enterprise negative test - domain suffix mismatch"""
1699     check_domain_suffix_match(dev[0])
1700     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1701     hostapd.add_ap(apdev[0]['ifname'], params)
1702     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
1703                    identity="DOMAIN\mschapv2 user", anonymous_identity="ttls",
1704                    password="password", phase2="auth=MSCHAPV2",
1705                    ca_cert="auth_serv/ca.pem",
1706                    domain_suffix_match="incorrect.example.com",
1707                    wait_connect=False, scan_freq="2412")
1708
1709     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
1710     if ev is None:
1711         raise Exception("Association and EAP start timed out")
1712
1713     ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=10)
1714     if ev is None:
1715         raise Exception("EAP method selection timed out")
1716     if "TTLS" not in ev:
1717         raise Exception("Unexpected EAP method")
1718
1719     ev = dev[0].wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR",
1720                             "CTRL-EVENT-EAP-SUCCESS",
1721                             "CTRL-EVENT-EAP-FAILURE",
1722                             "CTRL-EVENT-CONNECTED",
1723                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
1724     if ev is None:
1725         raise Exception("EAP result timed out")
1726     if "CTRL-EVENT-EAP-TLS-CERT-ERROR" not in ev:
1727         raise Exception("TLS certificate error not reported")
1728     if "Domain suffix mismatch" not in ev:
1729         raise Exception("Domain suffix mismatch not reported")
1730
1731     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS",
1732                             "CTRL-EVENT-EAP-FAILURE",
1733                             "CTRL-EVENT-CONNECTED",
1734                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
1735     if ev is None:
1736         raise Exception("EAP result(2) timed out")
1737     if "CTRL-EVENT-EAP-FAILURE" not in ev:
1738         raise Exception("EAP failure not reported")
1739
1740     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
1741                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
1742     if ev is None:
1743         raise Exception("EAP result(3) timed out")
1744     if "CTRL-EVENT-DISCONNECTED" not in ev:
1745         raise Exception("Disconnection not reported")
1746
1747     ev = dev[0].wait_event(["CTRL-EVENT-SSID-TEMP-DISABLED"], timeout=10)
1748     if ev is None:
1749         raise Exception("Network block disabling not reported")
1750
1751 def test_ap_wpa2_eap_tls_neg_domain_match(dev, apdev):
1752     """WPA2-Enterprise negative test - domain mismatch"""
1753     check_domain_match(dev[0])
1754     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1755     hostapd.add_ap(apdev[0]['ifname'], params)
1756     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
1757                    identity="DOMAIN\mschapv2 user", anonymous_identity="ttls",
1758                    password="password", phase2="auth=MSCHAPV2",
1759                    ca_cert="auth_serv/ca.pem",
1760                    domain_match="w1.fi",
1761                    wait_connect=False, scan_freq="2412")
1762
1763     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
1764     if ev is None:
1765         raise Exception("Association and EAP start timed out")
1766
1767     ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=10)
1768     if ev is None:
1769         raise Exception("EAP method selection timed out")
1770     if "TTLS" not in ev:
1771         raise Exception("Unexpected EAP method")
1772
1773     ev = dev[0].wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR",
1774                             "CTRL-EVENT-EAP-SUCCESS",
1775                             "CTRL-EVENT-EAP-FAILURE",
1776                             "CTRL-EVENT-CONNECTED",
1777                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
1778     if ev is None:
1779         raise Exception("EAP result timed out")
1780     if "CTRL-EVENT-EAP-TLS-CERT-ERROR" not in ev:
1781         raise Exception("TLS certificate error not reported")
1782     if "Domain mismatch" not in ev:
1783         raise Exception("Domain mismatch not reported")
1784
1785     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS",
1786                             "CTRL-EVENT-EAP-FAILURE",
1787                             "CTRL-EVENT-CONNECTED",
1788                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
1789     if ev is None:
1790         raise Exception("EAP result(2) timed out")
1791     if "CTRL-EVENT-EAP-FAILURE" not in ev:
1792         raise Exception("EAP failure not reported")
1793
1794     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
1795                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
1796     if ev is None:
1797         raise Exception("EAP result(3) timed out")
1798     if "CTRL-EVENT-DISCONNECTED" not in ev:
1799         raise Exception("Disconnection not reported")
1800
1801     ev = dev[0].wait_event(["CTRL-EVENT-SSID-TEMP-DISABLED"], timeout=10)
1802     if ev is None:
1803         raise Exception("Network block disabling not reported")
1804
1805 def test_ap_wpa2_eap_tls_neg_subject_match(dev, apdev):
1806     """WPA2-Enterprise negative test - subject mismatch"""
1807     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1808     hostapd.add_ap(apdev[0]['ifname'], params)
1809     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
1810                    identity="DOMAIN\mschapv2 user", anonymous_identity="ttls",
1811                    password="password", phase2="auth=MSCHAPV2",
1812                    ca_cert="auth_serv/ca.pem",
1813                    subject_match="/C=FI/O=w1.fi/CN=example.com",
1814                    wait_connect=False, scan_freq="2412")
1815
1816     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
1817     if ev is None:
1818         raise Exception("Association and EAP start timed out")
1819
1820     ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD",
1821                             "EAP: Failed to initialize EAP method"], timeout=10)
1822     if ev is None:
1823         raise Exception("EAP method selection timed out")
1824     if "EAP: Failed to initialize EAP method" in ev:
1825         tls = dev[0].request("GET tls_library")
1826         if tls.startswith("OpenSSL"):
1827             raise Exception("Failed to select EAP method")
1828         logger.info("subject_match not supported - connection failed, so test succeeded")
1829         return
1830     if "TTLS" not in ev:
1831         raise Exception("Unexpected EAP method")
1832
1833     ev = dev[0].wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR",
1834                             "CTRL-EVENT-EAP-SUCCESS",
1835                             "CTRL-EVENT-EAP-FAILURE",
1836                             "CTRL-EVENT-CONNECTED",
1837                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
1838     if ev is None:
1839         raise Exception("EAP result timed out")
1840     if "CTRL-EVENT-EAP-TLS-CERT-ERROR" not in ev:
1841         raise Exception("TLS certificate error not reported")
1842     if "Subject mismatch" not in ev:
1843         raise Exception("Subject mismatch not reported")
1844
1845     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS",
1846                             "CTRL-EVENT-EAP-FAILURE",
1847                             "CTRL-EVENT-CONNECTED",
1848                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
1849     if ev is None:
1850         raise Exception("EAP result(2) timed out")
1851     if "CTRL-EVENT-EAP-FAILURE" not in ev:
1852         raise Exception("EAP failure not reported")
1853
1854     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
1855                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
1856     if ev is None:
1857         raise Exception("EAP result(3) timed out")
1858     if "CTRL-EVENT-DISCONNECTED" not in ev:
1859         raise Exception("Disconnection not reported")
1860
1861     ev = dev[0].wait_event(["CTRL-EVENT-SSID-TEMP-DISABLED"], timeout=10)
1862     if ev is None:
1863         raise Exception("Network block disabling not reported")
1864
1865 def test_ap_wpa2_eap_tls_neg_altsubject_match(dev, apdev):
1866     """WPA2-Enterprise negative test - altsubject mismatch"""
1867     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1868     hostapd.add_ap(apdev[0]['ifname'], params)
1869
1870     tests = [ "incorrect.example.com",
1871               "DNS:incorrect.example.com",
1872               "DNS:w1.fi",
1873               "DNS:erver.w1.fi" ]
1874     for match in tests:
1875         _test_ap_wpa2_eap_tls_neg_altsubject_match(dev, apdev, match)
1876
1877 def _test_ap_wpa2_eap_tls_neg_altsubject_match(dev, apdev, match):
1878     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
1879                    identity="DOMAIN\mschapv2 user", anonymous_identity="ttls",
1880                    password="password", phase2="auth=MSCHAPV2",
1881                    ca_cert="auth_serv/ca.pem",
1882                    altsubject_match=match,
1883                    wait_connect=False, scan_freq="2412")
1884
1885     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
1886     if ev is None:
1887         raise Exception("Association and EAP start timed out")
1888
1889     ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD",
1890                             "EAP: Failed to initialize EAP method"], timeout=10)
1891     if ev is None:
1892         raise Exception("EAP method selection timed out")
1893     if "EAP: Failed to initialize EAP method" in ev:
1894         tls = dev[0].request("GET tls_library")
1895         if tls.startswith("OpenSSL"):
1896             raise Exception("Failed to select EAP method")
1897         logger.info("altsubject_match not supported - connection failed, so test succeeded")
1898         return
1899     if "TTLS" not in ev:
1900         raise Exception("Unexpected EAP method")
1901
1902     ev = dev[0].wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR",
1903                             "CTRL-EVENT-EAP-SUCCESS",
1904                             "CTRL-EVENT-EAP-FAILURE",
1905                             "CTRL-EVENT-CONNECTED",
1906                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
1907     if ev is None:
1908         raise Exception("EAP result timed out")
1909     if "CTRL-EVENT-EAP-TLS-CERT-ERROR" not in ev:
1910         raise Exception("TLS certificate error not reported")
1911     if "AltSubject mismatch" not in ev:
1912         raise Exception("altsubject mismatch not reported")
1913
1914     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS",
1915                             "CTRL-EVENT-EAP-FAILURE",
1916                             "CTRL-EVENT-CONNECTED",
1917                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
1918     if ev is None:
1919         raise Exception("EAP result(2) timed out")
1920     if "CTRL-EVENT-EAP-FAILURE" not in ev:
1921         raise Exception("EAP failure not reported")
1922
1923     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
1924                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
1925     if ev is None:
1926         raise Exception("EAP result(3) timed out")
1927     if "CTRL-EVENT-DISCONNECTED" not in ev:
1928         raise Exception("Disconnection not reported")
1929
1930     ev = dev[0].wait_event(["CTRL-EVENT-SSID-TEMP-DISABLED"], timeout=10)
1931     if ev is None:
1932         raise Exception("Network block disabling not reported")
1933
1934     dev[0].request("REMOVE_NETWORK all")
1935
1936 def test_ap_wpa2_eap_unauth_tls(dev, apdev):
1937     """WPA2-Enterprise connection using UNAUTH-TLS"""
1938     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1939     hostapd.add_ap(apdev[0]['ifname'], params)
1940     eap_connect(dev[0], apdev[0], "UNAUTH-TLS", "unauth-tls",
1941                 ca_cert="auth_serv/ca.pem")
1942     eap_reauth(dev[0], "UNAUTH-TLS")
1943
1944 def test_ap_wpa2_eap_ttls_server_cert_hash(dev, apdev):
1945     """WPA2-Enterprise connection using EAP-TTLS and server certificate hash"""
1946     check_cert_probe_support(dev[0])
1947     skip_with_fips(dev[0])
1948     srv_cert_hash = "e75bd454c7b02d312e5006d75067c28ffa5baea422effeb2bbd572179cd000ca"
1949     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1950     hostapd.add_ap(apdev[0]['ifname'], params)
1951     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
1952                    identity="probe", ca_cert="probe://",
1953                    wait_connect=False, scan_freq="2412")
1954     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
1955     if ev is None:
1956         raise Exception("Association and EAP start timed out")
1957     ev = dev[0].wait_event(["CTRL-EVENT-EAP-PEER-CERT depth=0"], timeout=10)
1958     if ev is None:
1959         raise Exception("No peer server certificate event seen")
1960     if "hash=" + srv_cert_hash not in ev:
1961         raise Exception("Expected server certificate hash not reported")
1962     ev = dev[0].wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR"], timeout=10)
1963     if ev is None:
1964         raise Exception("EAP result timed out")
1965     if "Server certificate chain probe" not in ev:
1966         raise Exception("Server certificate probe not reported")
1967     dev[0].wait_disconnected(timeout=10)
1968     dev[0].request("REMOVE_NETWORK all")
1969
1970     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
1971                    identity="DOMAIN\mschapv2 user", anonymous_identity="ttls",
1972                    password="password", phase2="auth=MSCHAPV2",
1973                    ca_cert="hash://server/sha256/5a1bc1296205e6fdbe3979728efe3920798885c1c4590b5f90f43222d239ca6a",
1974                    wait_connect=False, scan_freq="2412")
1975     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
1976     if ev is None:
1977         raise Exception("Association and EAP start timed out")
1978     ev = dev[0].wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR"], timeout=10)
1979     if ev is None:
1980         raise Exception("EAP result timed out")
1981     if "Server certificate mismatch" not in ev:
1982         raise Exception("Server certificate mismatch not reported")
1983     dev[0].wait_disconnected(timeout=10)
1984     dev[0].request("REMOVE_NETWORK all")
1985
1986     eap_connect(dev[0], apdev[0], "TTLS", "DOMAIN\mschapv2 user",
1987                 anonymous_identity="ttls", password="password",
1988                 ca_cert="hash://server/sha256/" + srv_cert_hash,
1989                 phase2="auth=MSCHAPV2")
1990
1991 def test_ap_wpa2_eap_ttls_server_cert_hash_invalid(dev, apdev):
1992     """WPA2-Enterprise connection using EAP-TTLS and server certificate hash (invalid config)"""
1993     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1994     hostapd.add_ap(apdev[0]['ifname'], params)
1995     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
1996                    identity="DOMAIN\mschapv2 user", anonymous_identity="ttls",
1997                    password="password", phase2="auth=MSCHAPV2",
1998                    ca_cert="hash://server/md5/5a1bc1296205e6fdbe3979728efe3920798885c1c4590b5f90f43222d239ca6a",
1999                    wait_connect=False, scan_freq="2412")
2000     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
2001                    identity="DOMAIN\mschapv2 user", anonymous_identity="ttls",
2002                    password="password", phase2="auth=MSCHAPV2",
2003                    ca_cert="hash://server/sha256/5a1bc1296205e6fdbe3979728efe3920798885c1c4590b5f90f43222d239ca",
2004                    wait_connect=False, scan_freq="2412")
2005     dev[2].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
2006                    identity="DOMAIN\mschapv2 user", anonymous_identity="ttls",
2007                    password="password", phase2="auth=MSCHAPV2",
2008                    ca_cert="hash://server/sha256/5a1bc1296205e6fdbe3979728efe3920798885c1c4590b5f90f43222d239ca6Q",
2009                    wait_connect=False, scan_freq="2412")
2010     for i in range(0, 3):
2011         ev = dev[i].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
2012         if ev is None:
2013             raise Exception("Association and EAP start timed out")
2014         ev = dev[i].wait_event(["EAP: Failed to initialize EAP method: vendor 0 method 21 (TTLS)"], timeout=5)
2015         if ev is None:
2016             raise Exception("Did not report EAP method initialization failure")
2017
2018 def test_ap_wpa2_eap_pwd(dev, apdev):
2019     """WPA2-Enterprise connection using EAP-pwd"""
2020     check_eap_capa(dev[0], "PWD")
2021     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2022     hostapd.add_ap(apdev[0]['ifname'], params)
2023     eap_connect(dev[0], apdev[0], "PWD", "pwd user", password="secret password")
2024     eap_reauth(dev[0], "PWD")
2025     dev[0].request("REMOVE_NETWORK all")
2026
2027     eap_connect(dev[1], apdev[0], "PWD",
2028                 "pwd.user@test123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890.example.com",
2029                 password="secret password",
2030                 fragment_size="90")
2031
2032     logger.info("Negative test with incorrect password")
2033     eap_connect(dev[2], apdev[0], "PWD", "pwd user", password="secret-password",
2034                 expect_failure=True, local_error_report=True)
2035
2036     eap_connect(dev[0], apdev[0], "PWD",
2037                 "pwd.user@test123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890.example.com",
2038                 password="secret password",
2039                 fragment_size="31")
2040
2041 def test_ap_wpa2_eap_pwd_nthash(dev, apdev):
2042     """WPA2-Enterprise connection using EAP-pwd and NTHash"""
2043     check_eap_capa(dev[0], "PWD")
2044     skip_with_fips(dev[0])
2045     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2046     hostapd.add_ap(apdev[0]['ifname'], params)
2047     eap_connect(dev[0], apdev[0], "PWD", "pwd-hash", password="secret password")
2048     eap_connect(dev[1], apdev[0], "PWD", "pwd-hash",
2049                 password_hex="hash:e3718ece8ab74792cbbfffd316d2d19a")
2050     eap_connect(dev[2], apdev[0], "PWD", "pwd user",
2051                 password_hex="hash:e3718ece8ab74792cbbfffd316d2d19a",
2052                 expect_failure=True, local_error_report=True)
2053
2054 def test_ap_wpa2_eap_pwd_groups(dev, apdev):
2055     """WPA2-Enterprise connection using various EAP-pwd groups"""
2056     check_eap_capa(dev[0], "PWD")
2057     tls = dev[0].request("GET tls_library")
2058     params = { "ssid": "test-wpa2-eap", "wpa": "2", "wpa_key_mgmt": "WPA-EAP",
2059                "rsn_pairwise": "CCMP", "ieee8021x": "1",
2060                "eap_server": "1", "eap_user_file": "auth_serv/eap_user.conf" }
2061     groups = [ 19, 20, 21, 25, 26 ]
2062     if tls.startswith("OpenSSL") and "build=OpenSSL 1.0.2" in tls and "run=OpenSSL 1.0.2" in tls:
2063         logger.info("Add Brainpool EC groups since OpenSSL is new enough")
2064         groups += [ 27, 28, 29, 30 ]
2065     for i in groups:
2066         logger.info("Group %d" % i)
2067         params['pwd_group'] = str(i)
2068         hostapd.add_ap(apdev[0]['ifname'], params)
2069         try:
2070             eap_connect(dev[0], apdev[0], "PWD", "pwd user",
2071                         password="secret password")
2072             dev[0].request("REMOVE_NETWORK all")
2073             dev[0].wait_disconnected()
2074             dev[0].dump_monitor()
2075         except:
2076             if "BoringSSL" in tls and i in [ 25 ]:
2077                 logger.info("Ignore connection failure with group %d with BoringSSL" % i)
2078                 dev[0].request("DISCONNECT")
2079                 time.sleep(0.1)
2080                 dev[0].request("REMOVE_NETWORK all")
2081                 dev[0].dump_monitor()
2082                 continue
2083             raise
2084
2085 def test_ap_wpa2_eap_pwd_invalid_group(dev, apdev):
2086     """WPA2-Enterprise connection using invalid EAP-pwd group"""
2087     check_eap_capa(dev[0], "PWD")
2088     params = { "ssid": "test-wpa2-eap", "wpa": "2", "wpa_key_mgmt": "WPA-EAP",
2089                "rsn_pairwise": "CCMP", "ieee8021x": "1",
2090                "eap_server": "1", "eap_user_file": "auth_serv/eap_user.conf" }
2091     params['pwd_group'] = "0"
2092     hostapd.add_ap(apdev[0]['ifname'], params)
2093     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PWD",
2094                    identity="pwd user", password="secret password",
2095                    scan_freq="2412", wait_connect=False)
2096     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
2097     if ev is None:
2098         raise Exception("Timeout on EAP failure report")
2099
2100 def test_ap_wpa2_eap_pwd_as_frag(dev, apdev):
2101     """WPA2-Enterprise connection using EAP-pwd with server fragmentation"""
2102     check_eap_capa(dev[0], "PWD")
2103     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2104     params = { "ssid": "test-wpa2-eap", "wpa": "2", "wpa_key_mgmt": "WPA-EAP",
2105                "rsn_pairwise": "CCMP", "ieee8021x": "1",
2106                "eap_server": "1", "eap_user_file": "auth_serv/eap_user.conf",
2107                "pwd_group": "19", "fragment_size": "40" }
2108     hostapd.add_ap(apdev[0]['ifname'], params)
2109     eap_connect(dev[0], apdev[0], "PWD", "pwd user", password="secret password")
2110
2111 def test_ap_wpa2_eap_gpsk(dev, apdev):
2112     """WPA2-Enterprise connection using EAP-GPSK"""
2113     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2114     hostapd.add_ap(apdev[0]['ifname'], params)
2115     id = eap_connect(dev[0], apdev[0], "GPSK", "gpsk user",
2116                      password="abcdefghijklmnop0123456789abcdef")
2117     eap_reauth(dev[0], "GPSK")
2118
2119     logger.info("Test forced algorithm selection")
2120     for phase1 in [ "cipher=1", "cipher=2" ]:
2121         dev[0].set_network_quoted(id, "phase1", phase1)
2122         ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
2123         if ev is None:
2124             raise Exception("EAP success timed out")
2125         dev[0].wait_connected(timeout=10)
2126
2127     logger.info("Test failed algorithm negotiation")
2128     dev[0].set_network_quoted(id, "phase1", "cipher=9")
2129     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
2130     if ev is None:
2131         raise Exception("EAP failure timed out")
2132
2133     logger.info("Negative test with incorrect password")
2134     dev[0].request("REMOVE_NETWORK all")
2135     eap_connect(dev[0], apdev[0], "GPSK", "gpsk user",
2136                 password="ffcdefghijklmnop0123456789abcdef",
2137                 expect_failure=True)
2138
2139 def test_ap_wpa2_eap_sake(dev, apdev):
2140     """WPA2-Enterprise connection using EAP-SAKE"""
2141     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2142     hostapd.add_ap(apdev[0]['ifname'], params)
2143     eap_connect(dev[0], apdev[0], "SAKE", "sake user",
2144                 password_hex="0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef")
2145     eap_reauth(dev[0], "SAKE")
2146
2147     logger.info("Negative test with incorrect password")
2148     dev[0].request("REMOVE_NETWORK all")
2149     eap_connect(dev[0], apdev[0], "SAKE", "sake user",
2150                 password_hex="ff23456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
2151                 expect_failure=True)
2152
2153 def test_ap_wpa2_eap_eke(dev, apdev):
2154     """WPA2-Enterprise connection using EAP-EKE"""
2155     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2156     hostapd.add_ap(apdev[0]['ifname'], params)
2157     id = eap_connect(dev[0], apdev[0], "EKE", "eke user", password="hello")
2158     eap_reauth(dev[0], "EKE")
2159
2160     logger.info("Test forced algorithm selection")
2161     for phase1 in [ "dhgroup=5 encr=1 prf=2 mac=2",
2162                     "dhgroup=4 encr=1 prf=2 mac=2",
2163                     "dhgroup=3 encr=1 prf=2 mac=2",
2164                     "dhgroup=3 encr=1 prf=1 mac=1" ]:
2165         dev[0].set_network_quoted(id, "phase1", phase1)
2166         ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
2167         if ev is None:
2168             raise Exception("EAP success timed out")
2169         dev[0].wait_connected(timeout=10)
2170
2171     logger.info("Test failed algorithm negotiation")
2172     dev[0].set_network_quoted(id, "phase1", "dhgroup=9 encr=9 prf=9 mac=9")
2173     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
2174     if ev is None:
2175         raise Exception("EAP failure timed out")
2176
2177     logger.info("Negative test with incorrect password")
2178     dev[0].request("REMOVE_NETWORK all")
2179     eap_connect(dev[0], apdev[0], "EKE", "eke user", password="hello1",
2180                 expect_failure=True)
2181
2182 def test_ap_wpa2_eap_eke_many(dev, apdev, params):
2183     """WPA2-Enterprise connection using EAP-EKE (many connections) [long]"""
2184     if not params['long']:
2185         raise HwsimSkip("Skip test case with long duration due to --long not specified")
2186     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2187     hostapd.add_ap(apdev[0]['ifname'], params)
2188     success = 0
2189     fail = 0
2190     for i in range(100):
2191         for j in range(3):
2192             dev[j].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="EKE",
2193                            identity="eke user", password="hello",
2194                            phase1="dhgroup=3 encr=1 prf=1 mac=1",
2195                            scan_freq="2412", wait_connect=False)
2196         for j in range(3):
2197             ev = dev[j].wait_event(["CTRL-EVENT-CONNECTED",
2198                                     "CTRL-EVENT-DISCONNECTED"], timeout=15)
2199             if ev is None:
2200                 raise Exception("No connected/disconnected event")
2201             if "CTRL-EVENT-DISCONNECTED" in ev:
2202                 fail += 1
2203                 # The RADIUS server limits on active sessions can be hit when
2204                 # going through this test case, so try to give some more time
2205                 # for the server to remove sessions.
2206                 logger.info("Failed to connect i=%d j=%d" % (i, j))
2207                 dev[j].request("REMOVE_NETWORK all")
2208                 time.sleep(1)
2209             else:
2210                 success += 1
2211                 dev[j].request("REMOVE_NETWORK all")
2212                 dev[j].wait_disconnected()
2213             dev[j].dump_monitor()
2214     logger.info("Total success=%d failure=%d" % (success, fail))
2215
2216 def test_ap_wpa2_eap_eke_serverid_nai(dev, apdev):
2217     """WPA2-Enterprise connection using EAP-EKE with serverid NAI"""
2218     params = int_eap_server_params()
2219     params['server_id'] = 'example.server@w1.fi'
2220     hostapd.add_ap(apdev[0]['ifname'], params)
2221     eap_connect(dev[0], apdev[0], "EKE", "eke user", password="hello")
2222
2223 def test_ap_wpa2_eap_eke_server_oom(dev, apdev):
2224     """WPA2-Enterprise connection using EAP-EKE with server OOM"""
2225     params = int_eap_server_params()
2226     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
2227     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2228
2229     for count,func in [ (1, "eap_eke_build_commit"),
2230                         (2, "eap_eke_build_commit"),
2231                         (3, "eap_eke_build_commit"),
2232                         (1, "eap_eke_build_confirm"),
2233                         (2, "eap_eke_build_confirm"),
2234                         (1, "eap_eke_process_commit"),
2235                         (2, "eap_eke_process_commit"),
2236                         (1, "eap_eke_process_confirm"),
2237                         (1, "eap_eke_process_identity"),
2238                         (2, "eap_eke_process_identity"),
2239                         (3, "eap_eke_process_identity"),
2240                         (4, "eap_eke_process_identity") ]:
2241         with alloc_fail(hapd, count, func):
2242             eap_connect(dev[0], apdev[0], "EKE", "eke user", password="hello",
2243                         expect_failure=True)
2244             dev[0].request("REMOVE_NETWORK all")
2245
2246     for count,func,pw in [ (1, "eap_eke_init", "hello"),
2247                            (1, "eap_eke_get_session_id", "hello"),
2248                            (1, "eap_eke_getKey", "hello"),
2249                            (1, "eap_eke_build_msg", "hello"),
2250                            (1, "eap_eke_build_failure", "wrong"),
2251                            (1, "eap_eke_build_identity", "hello"),
2252                            (2, "eap_eke_build_identity", "hello") ]:
2253         with alloc_fail(hapd, count, func):
2254             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
2255                            eap="EKE", identity="eke user", password=pw,
2256                            wait_connect=False, scan_freq="2412")
2257             # This would eventually time out, but we can stop after having
2258             # reached the allocation failure.
2259             for i in range(20):
2260                 time.sleep(0.1)
2261                 if hapd.request("GET_ALLOC_FAIL").startswith('0'):
2262                     break
2263             dev[0].request("REMOVE_NETWORK all")
2264
2265     for count in range(1, 1000):
2266         try:
2267             with alloc_fail(hapd, count, "eap_server_sm_step"):
2268                 dev[0].connect("test-wpa2-eap",
2269                                key_mgmt="WPA-EAP WPA-EAP-SHA256",
2270                                eap="EKE", identity="eke user", password=pw,
2271                                wait_connect=False, scan_freq="2412")
2272                 # This would eventually time out, but we can stop after having
2273                 # reached the allocation failure.
2274                 for i in range(10):
2275                     time.sleep(0.1)
2276                     if hapd.request("GET_ALLOC_FAIL").startswith('0'):
2277                         break
2278                 dev[0].request("REMOVE_NETWORK all")
2279         except Exception, e:
2280             if str(e) == "Allocation failure did not trigger":
2281                 if count < 30:
2282                     raise Exception("Too few allocation failures")
2283                 logger.info("%d allocation failures tested" % (count - 1))
2284                 break
2285             raise e
2286
2287 def test_ap_wpa2_eap_ikev2(dev, apdev):
2288     """WPA2-Enterprise connection using EAP-IKEv2"""
2289     check_eap_capa(dev[0], "IKEV2")
2290     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2291     hostapd.add_ap(apdev[0]['ifname'], params)
2292     eap_connect(dev[0], apdev[0], "IKEV2", "ikev2 user",
2293                 password="ike password")
2294     eap_reauth(dev[0], "IKEV2")
2295     dev[0].request("REMOVE_NETWORK all")
2296     eap_connect(dev[0], apdev[0], "IKEV2", "ikev2 user",
2297                 password="ike password", fragment_size="50")
2298
2299     logger.info("Negative test with incorrect password")
2300     dev[0].request("REMOVE_NETWORK all")
2301     eap_connect(dev[0], apdev[0], "IKEV2", "ikev2 user",
2302                 password="ike-password", expect_failure=True)
2303
2304 def test_ap_wpa2_eap_ikev2_as_frag(dev, apdev):
2305     """WPA2-Enterprise connection using EAP-IKEv2 with server fragmentation"""
2306     check_eap_capa(dev[0], "IKEV2")
2307     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2308     params = { "ssid": "test-wpa2-eap", "wpa": "2", "wpa_key_mgmt": "WPA-EAP",
2309                "rsn_pairwise": "CCMP", "ieee8021x": "1",
2310                "eap_server": "1", "eap_user_file": "auth_serv/eap_user.conf",
2311                "fragment_size": "50" }
2312     hostapd.add_ap(apdev[0]['ifname'], params)
2313     eap_connect(dev[0], apdev[0], "IKEV2", "ikev2 user",
2314                 password="ike password")
2315     eap_reauth(dev[0], "IKEV2")
2316
2317 def test_ap_wpa2_eap_ikev2_oom(dev, apdev):
2318     """WPA2-Enterprise connection using EAP-IKEv2 and OOM"""
2319     check_eap_capa(dev[0], "IKEV2")
2320     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2321     hostapd.add_ap(apdev[0]['ifname'], params)
2322
2323     tests = [ (1, "dh_init"),
2324               (2, "dh_init"),
2325               (1, "dh_derive_shared") ]
2326     for count, func in tests:
2327         with alloc_fail(dev[0], count, func):
2328             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="IKEV2",
2329                            identity="ikev2 user", password="ike password",
2330                            wait_connect=False, scan_freq="2412")
2331             ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=5)
2332             if ev is None:
2333                 raise Exception("EAP method not selected")
2334             for i in range(10):
2335                 if "0:" in dev[0].request("GET_ALLOC_FAIL"):
2336                     break
2337                 time.sleep(0.02)
2338             dev[0].request("REMOVE_NETWORK all")
2339
2340     tests = [ (1, "os_get_random;dh_init") ]
2341     for count, func in tests:
2342         with fail_test(dev[0], count, func):
2343             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="IKEV2",
2344                            identity="ikev2 user", password="ike password",
2345                            wait_connect=False, scan_freq="2412")
2346             ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=5)
2347             if ev is None:
2348                 raise Exception("EAP method not selected")
2349             for i in range(10):
2350                 if "0:" in dev[0].request("GET_FAIL"):
2351                     break
2352                 time.sleep(0.02)
2353             dev[0].request("REMOVE_NETWORK all")
2354
2355 def test_ap_wpa2_eap_pax(dev, apdev):
2356     """WPA2-Enterprise connection using EAP-PAX"""
2357     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2358     hostapd.add_ap(apdev[0]['ifname'], params)
2359     eap_connect(dev[0], apdev[0], "PAX", "pax.user@example.com",
2360                 password_hex="0123456789abcdef0123456789abcdef")
2361     eap_reauth(dev[0], "PAX")
2362
2363     logger.info("Negative test with incorrect password")
2364     dev[0].request("REMOVE_NETWORK all")
2365     eap_connect(dev[0], apdev[0], "PAX", "pax.user@example.com",
2366                 password_hex="ff23456789abcdef0123456789abcdef",
2367                 expect_failure=True)
2368
2369 def test_ap_wpa2_eap_psk(dev, apdev):
2370     """WPA2-Enterprise connection using EAP-PSK"""
2371     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2372     params["wpa_key_mgmt"] = "WPA-EAP-SHA256"
2373     params["ieee80211w"] = "2"
2374     hostapd.add_ap(apdev[0]['ifname'], params)
2375     eap_connect(dev[0], apdev[0], "PSK", "psk.user@example.com",
2376                 password_hex="0123456789abcdef0123456789abcdef", sha256=True)
2377     eap_reauth(dev[0], "PSK", sha256=True)
2378     check_mib(dev[0], [ ("dot11RSNAAuthenticationSuiteRequested", "00-0f-ac-5"),
2379                         ("dot11RSNAAuthenticationSuiteSelected", "00-0f-ac-5") ])
2380
2381     bss = dev[0].get_bss(apdev[0]['bssid'])
2382     if 'flags' not in bss:
2383         raise Exception("Could not get BSS flags from BSS table")
2384     if "[WPA2-EAP-SHA256-CCMP]" not in bss['flags']:
2385         raise Exception("Unexpected BSS flags: " + bss['flags'])
2386
2387     logger.info("Negative test with incorrect password")
2388     dev[0].request("REMOVE_NETWORK all")
2389     eap_connect(dev[0], apdev[0], "PSK", "psk.user@example.com",
2390                 password_hex="ff23456789abcdef0123456789abcdef", sha256=True,
2391                 expect_failure=True)
2392
2393 def test_ap_wpa2_eap_psk_oom(dev, apdev):
2394     """WPA2-Enterprise connection using EAP-PSK and OOM"""
2395     skip_with_fips(dev[0])
2396     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2397     hostapd.add_ap(apdev[0]['ifname'], params)
2398     tests = [ (1, "aes_128_ctr_encrypt;aes_128_eax_encrypt"),
2399               (1, "omac1_aes_128;aes_128_eax_encrypt"),
2400               (2, "omac1_aes_128;aes_128_eax_encrypt"),
2401               (3, "omac1_aes_128;aes_128_eax_encrypt"),
2402               (1, "=aes_128_eax_encrypt"),
2403               (1, "omac1_aes_vector"),
2404               (1, "aes_128_ctr_encrypt;aes_128_eax_decrypt"),
2405               (1, "omac1_aes_128;aes_128_eax_decrypt"),
2406               (2, "omac1_aes_128;aes_128_eax_decrypt"),
2407               (3, "omac1_aes_128;aes_128_eax_decrypt"),
2408               (1, "=aes_128_eax_decrypt") ]
2409     for count, func in tests:
2410         with alloc_fail(dev[0], count, func):
2411             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PSK",
2412                            identity="psk.user@example.com",
2413                            password_hex="0123456789abcdef0123456789abcdef",
2414                            wait_connect=False, scan_freq="2412")
2415             ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=5)
2416             if ev is None:
2417                 raise Exception("EAP method not selected")
2418             for i in range(10):
2419                 if "0:" in dev[0].request("GET_ALLOC_FAIL"):
2420                     break
2421                 time.sleep(0.02)
2422             dev[0].request("REMOVE_NETWORK all")
2423
2424     with alloc_fail(dev[0], 1, "aes_128_encrypt_block"):
2425             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PSK",
2426                            identity="psk.user@example.com",
2427                            password_hex="0123456789abcdef0123456789abcdef",
2428                            wait_connect=False, scan_freq="2412")
2429             ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
2430             if ev is None:
2431                 raise Exception("EAP method failure not reported")
2432             dev[0].request("REMOVE_NETWORK all")
2433
2434 def test_ap_wpa_eap_peap_eap_mschapv2(dev, apdev):
2435     """WPA-Enterprise connection using EAP-PEAP/EAP-MSCHAPv2"""
2436     check_eap_capa(dev[0], "MSCHAPV2")
2437     params = hostapd.wpa_eap_params(ssid="test-wpa-eap")
2438     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
2439     dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="PEAP",
2440                    identity="user", password="password", phase2="auth=MSCHAPV2",
2441                    ca_cert="auth_serv/ca.pem", wait_connect=False,
2442                    scan_freq="2412")
2443     eap_check_auth(dev[0], "PEAP", True, rsn=False)
2444     hwsim_utils.test_connectivity(dev[0], hapd)
2445     eap_reauth(dev[0], "PEAP", rsn=False)
2446     check_mib(dev[0], [ ("dot11RSNAAuthenticationSuiteRequested", "00-50-f2-1"),
2447                         ("dot11RSNAAuthenticationSuiteSelected", "00-50-f2-1") ])
2448     status = dev[0].get_status(extra="VERBOSE")
2449     if 'portControl' not in status:
2450         raise Exception("portControl missing from STATUS-VERBOSE")
2451     if status['portControl'] != 'Auto':
2452         raise Exception("Unexpected portControl value: " + status['portControl'])
2453     if 'eap_session_id' not in status:
2454         raise Exception("eap_session_id missing from STATUS-VERBOSE")
2455     if not status['eap_session_id'].startswith("19"):
2456         raise Exception("Unexpected eap_session_id value: " + status['eap_session_id'])
2457
2458 def test_ap_wpa2_eap_interactive(dev, apdev):
2459     """WPA2-Enterprise connection using interactive identity/password entry"""
2460     check_eap_capa(dev[0], "MSCHAPV2")
2461     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2462     hostapd.add_ap(apdev[0]['ifname'], params)
2463     hapd = hostapd.Hostapd(apdev[0]['ifname'])
2464
2465     tests = [ ("Connection with dynamic TTLS/MSCHAPv2 password entry",
2466                "TTLS", "ttls", "DOMAIN\mschapv2 user", "auth=MSCHAPV2",
2467                None, "password"),
2468               ("Connection with dynamic TTLS/MSCHAPv2 identity and password entry",
2469                "TTLS", "ttls", None, "auth=MSCHAPV2",
2470                "DOMAIN\mschapv2 user", "password"),
2471               ("Connection with dynamic TTLS/EAP-MSCHAPv2 password entry",
2472                "TTLS", "ttls", "user", "autheap=MSCHAPV2", None, "password"),
2473               ("Connection with dynamic TTLS/EAP-MD5 password entry",
2474                "TTLS", "ttls", "user", "autheap=MD5", None, "password"),
2475               ("Connection with dynamic PEAP/EAP-MSCHAPv2 password entry",
2476                "PEAP", None, "user", "auth=MSCHAPV2", None, "password"),
2477               ("Connection with dynamic PEAP/EAP-GTC password entry",
2478                "PEAP", None, "user", "auth=GTC", None, "password") ]
2479     for [desc,eap,anon,identity,phase2,req_id,req_pw] in tests:
2480         logger.info(desc)
2481         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap=eap,
2482                        anonymous_identity=anon, identity=identity,
2483                        ca_cert="auth_serv/ca.pem", phase2=phase2,
2484                        wait_connect=False, scan_freq="2412")
2485         if req_id:
2486             ev = dev[0].wait_event(["CTRL-REQ-IDENTITY"])
2487             if ev is None:
2488                 raise Exception("Request for identity timed out")
2489             id = ev.split(':')[0].split('-')[-1]
2490             dev[0].request("CTRL-RSP-IDENTITY-" + id + ":" + req_id)
2491         ev = dev[0].wait_event(["CTRL-REQ-PASSWORD","CTRL-REQ-OTP"])
2492         if ev is None:
2493             raise Exception("Request for password timed out")
2494         id = ev.split(':')[0].split('-')[-1]
2495         type = "OTP" if "CTRL-REQ-OTP" in ev else "PASSWORD"
2496         dev[0].request("CTRL-RSP-" + type + "-" + id + ":" + req_pw)
2497         dev[0].wait_connected(timeout=10)
2498         dev[0].request("REMOVE_NETWORK all")
2499
2500 def test_ap_wpa2_eap_ext_enable_network_while_connected(dev, apdev):
2501     """WPA2-Enterprise interactive identity entry and ENABLE_NETWORK"""
2502     check_eap_capa(dev[0], "MSCHAPV2")
2503     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2504     hostapd.add_ap(apdev[0]['ifname'], params)
2505     hapd = hostapd.Hostapd(apdev[0]['ifname'])
2506
2507     id_other = dev[0].connect("other", key_mgmt="NONE", scan_freq="2412",
2508                               only_add_network=True)
2509
2510     req_id = "DOMAIN\mschapv2 user"
2511     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
2512                    anonymous_identity="ttls", identity=None,
2513                    password="password",
2514                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2515                    wait_connect=False, scan_freq="2412")
2516     ev = dev[0].wait_event(["CTRL-REQ-IDENTITY"])
2517     if ev is None:
2518         raise Exception("Request for identity timed out")
2519     id = ev.split(':')[0].split('-')[-1]
2520     dev[0].request("CTRL-RSP-IDENTITY-" + id + ":" + req_id)
2521     dev[0].wait_connected(timeout=10)
2522
2523     if "OK" not in dev[0].request("ENABLE_NETWORK " + str(id_other)):
2524         raise Exception("Failed to enable network")
2525     ev = dev[0].wait_event(["SME: Trying to authenticate"], timeout=1)
2526     if ev is not None:
2527         raise Exception("Unexpected reconnection attempt on ENABLE_NETWORK")
2528     dev[0].request("REMOVE_NETWORK all")
2529
2530 def test_ap_wpa2_eap_vendor_test(dev, apdev):
2531     """WPA2-Enterprise connection using EAP vendor test"""
2532     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2533     hostapd.add_ap(apdev[0]['ifname'], params)
2534     eap_connect(dev[0], apdev[0], "VENDOR-TEST", "vendor-test")
2535     eap_reauth(dev[0], "VENDOR-TEST")
2536     eap_connect(dev[1], apdev[0], "VENDOR-TEST", "vendor-test",
2537                 password="pending")
2538
2539 def test_ap_wpa2_eap_fast_mschapv2_unauth_prov(dev, apdev):
2540     """WPA2-Enterprise connection using EAP-FAST/MSCHAPv2 and unauthenticated provisioning"""
2541     check_eap_capa(dev[0], "FAST")
2542     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2543     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
2544     eap_connect(dev[0], apdev[0], "FAST", "user",
2545                 anonymous_identity="FAST", password="password",
2546                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2547                 phase1="fast_provisioning=1", pac_file="blob://fast_pac")
2548     hwsim_utils.test_connectivity(dev[0], hapd)
2549     res = eap_reauth(dev[0], "FAST")
2550     if res['tls_session_reused'] != '1':
2551         raise Exception("EAP-FAST could not use PAC session ticket")
2552
2553 def test_ap_wpa2_eap_fast_pac_file(dev, apdev, params):
2554     """WPA2-Enterprise connection using EAP-FAST/MSCHAPv2 and PAC file"""
2555     check_eap_capa(dev[0], "FAST")
2556     pac_file = os.path.join(params['logdir'], "fast.pac")
2557     pac_file2 = os.path.join(params['logdir'], "fast-bin.pac")
2558     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2559     hostapd.add_ap(apdev[0]['ifname'], params)
2560
2561     try:
2562         eap_connect(dev[0], apdev[0], "FAST", "user",
2563                     anonymous_identity="FAST", password="password",
2564                     ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2565                     phase1="fast_provisioning=1", pac_file=pac_file)
2566         with open(pac_file, "r") as f:
2567             data = f.read()
2568             if "wpa_supplicant EAP-FAST PAC file - version 1" not in data:
2569                 raise Exception("PAC file header missing")
2570             if "PAC-Key=" not in data:
2571                 raise Exception("PAC-Key missing from PAC file")
2572         dev[0].request("REMOVE_NETWORK all")
2573         eap_connect(dev[0], apdev[0], "FAST", "user",
2574                     anonymous_identity="FAST", password="password",
2575                     ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2576                     pac_file=pac_file)
2577
2578         eap_connect(dev[1], apdev[0], "FAST", "user",
2579                     anonymous_identity="FAST", password="password",
2580                     ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2581                     phase1="fast_provisioning=1 fast_pac_format=binary",
2582                     pac_file=pac_file2)
2583         dev[1].request("REMOVE_NETWORK all")
2584         eap_connect(dev[1], apdev[0], "FAST", "user",
2585                     anonymous_identity="FAST", password="password",
2586                     ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2587                     phase1="fast_pac_format=binary",
2588                     pac_file=pac_file2)
2589     finally:
2590         try:
2591             os.remove(pac_file)
2592         except:
2593             pass
2594         try:
2595             os.remove(pac_file2)
2596         except:
2597             pass
2598
2599 def test_ap_wpa2_eap_fast_binary_pac(dev, apdev):
2600     """WPA2-Enterprise connection using EAP-FAST and binary PAC format"""
2601     check_eap_capa(dev[0], "FAST")
2602     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2603     hostapd.add_ap(apdev[0]['ifname'], params)
2604     eap_connect(dev[0], apdev[0], "FAST", "user",
2605                 anonymous_identity="FAST", password="password",
2606                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2607                 phase1="fast_provisioning=1 fast_max_pac_list_len=1 fast_pac_format=binary",
2608                 pac_file="blob://fast_pac_bin")
2609     res = eap_reauth(dev[0], "FAST")
2610     if res['tls_session_reused'] != '1':
2611         raise Exception("EAP-FAST could not use PAC session ticket")
2612
2613 def test_ap_wpa2_eap_fast_missing_pac_config(dev, apdev):
2614     """WPA2-Enterprise connection using EAP-FAST and missing PAC config"""
2615     check_eap_capa(dev[0], "FAST")
2616     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2617     hostapd.add_ap(apdev[0]['ifname'], params)
2618
2619     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
2620                    identity="user", anonymous_identity="FAST",
2621                    password="password",
2622                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2623                    pac_file="blob://fast_pac_not_in_use",
2624                    wait_connect=False, scan_freq="2412")
2625     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
2626     if ev is None:
2627         raise Exception("Timeout on EAP failure report")
2628     dev[0].request("REMOVE_NETWORK all")
2629
2630     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
2631                    identity="user", anonymous_identity="FAST",
2632                    password="password",
2633                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2634                    wait_connect=False, scan_freq="2412")
2635     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
2636     if ev is None:
2637         raise Exception("Timeout on EAP failure report")
2638
2639 def test_ap_wpa2_eap_fast_gtc_auth_prov(dev, apdev):
2640     """WPA2-Enterprise connection using EAP-FAST/GTC and authenticated provisioning"""
2641     check_eap_capa(dev[0], "FAST")
2642     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2643     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
2644     eap_connect(dev[0], apdev[0], "FAST", "user",
2645                 anonymous_identity="FAST", password="password",
2646                 ca_cert="auth_serv/ca.pem", phase2="auth=GTC",
2647                 phase1="fast_provisioning=2", pac_file="blob://fast_pac_auth")
2648     hwsim_utils.test_connectivity(dev[0], hapd)
2649     res = eap_reauth(dev[0], "FAST")
2650     if res['tls_session_reused'] != '1':
2651         raise Exception("EAP-FAST could not use PAC session ticket")
2652
2653 def test_ap_wpa2_eap_fast_gtc_identity_change(dev, apdev):
2654     """WPA2-Enterprise connection using EAP-FAST/GTC and identity changing"""
2655     check_eap_capa(dev[0], "FAST")
2656     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2657     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
2658     id = eap_connect(dev[0], apdev[0], "FAST", "user",
2659                      anonymous_identity="FAST", password="password",
2660                      ca_cert="auth_serv/ca.pem", phase2="auth=GTC",
2661                      phase1="fast_provisioning=2",
2662                      pac_file="blob://fast_pac_auth")
2663     dev[0].set_network_quoted(id, "identity", "user2")
2664     dev[0].wait_disconnected()
2665     ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=15)
2666     if ev is None:
2667         raise Exception("EAP-FAST not started")
2668     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
2669     if ev is None:
2670         raise Exception("EAP failure not reported")
2671     dev[0].wait_disconnected()
2672
2673 def test_ap_wpa2_eap_fast_prf_oom(dev, apdev):
2674     """WPA2-Enterprise connection using EAP-FAST and OOM in PRF"""
2675     check_eap_capa(dev[0], "FAST")
2676     tls = dev[0].request("GET tls_library")
2677     if tls.startswith("OpenSSL"):
2678         func = "openssl_tls_prf"
2679         count = 2
2680     elif tls.startswith("internal"):
2681         func = "tls_connection_prf"
2682         count = 1
2683     else:
2684         raise HwsimSkip("Unsupported TLS library")
2685     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2686     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
2687     with alloc_fail(dev[0], count, func):
2688         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
2689                        identity="user", anonymous_identity="FAST",
2690                        password="password", ca_cert="auth_serv/ca.pem",
2691                        phase2="auth=GTC",
2692                        phase1="fast_provisioning=2",
2693                        pac_file="blob://fast_pac_auth",
2694                        wait_connect=False, scan_freq="2412")
2695         ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
2696         if ev is None:
2697             raise Exception("EAP failure not reported")
2698     dev[0].request("DISCONNECT")
2699
2700 def test_ap_wpa2_eap_fast_server_oom(dev, apdev):
2701     """EAP-FAST/MSCHAPv2 and server OOM"""
2702     check_eap_capa(dev[0], "FAST")
2703
2704     params = int_eap_server_params()
2705     params['dh_file'] = 'auth_serv/dh.conf'
2706     params['pac_opaque_encr_key'] = '000102030405060708090a0b0c0d0e0f'
2707     params['eap_fast_a_id'] = '1011'
2708     params['eap_fast_a_id_info'] = 'another test server'
2709     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
2710
2711     with alloc_fail(hapd, 1, "tls_session_ticket_ext_cb"):
2712         id = eap_connect(dev[0], apdev[0], "FAST", "user",
2713                          anonymous_identity="FAST", password="password",
2714                          ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2715                          phase1="fast_provisioning=1",
2716                          pac_file="blob://fast_pac",
2717                          expect_failure=True)
2718         ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
2719         if ev is None:
2720             raise Exception("No EAP failure reported")
2721         dev[0].wait_disconnected()
2722         dev[0].request("DISCONNECT")
2723
2724     dev[0].select_network(id, freq="2412")
2725
2726 def test_ap_wpa2_eap_tls_ocsp(dev, apdev):
2727     """WPA2-Enterprise connection using EAP-TLS and verifying OCSP"""
2728     check_ocsp_support(dev[0])
2729     check_pkcs12_support(dev[0])
2730     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2731     hostapd.add_ap(apdev[0]['ifname'], params)
2732     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
2733                 private_key="auth_serv/user.pkcs12",
2734                 private_key_passwd="whatever", ocsp=2)
2735
2736 def test_ap_wpa2_eap_tls_ocsp_multi(dev, apdev):
2737     """WPA2-Enterprise connection using EAP-TLS and verifying OCSP-multi"""
2738     check_ocsp_multi_support(dev[0])
2739     check_pkcs12_support(dev[0])
2740
2741     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2742     hostapd.add_ap(apdev[0]['ifname'], params)
2743     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
2744                 private_key="auth_serv/user.pkcs12",
2745                 private_key_passwd="whatever", ocsp=2)
2746
2747 def int_eap_server_params():
2748     params = { "ssid": "test-wpa2-eap", "wpa": "2", "wpa_key_mgmt": "WPA-EAP",
2749                "rsn_pairwise": "CCMP", "ieee8021x": "1",
2750                "eap_server": "1", "eap_user_file": "auth_serv/eap_user.conf",
2751                "ca_cert": "auth_serv/ca.pem",
2752                "server_cert": "auth_serv/server.pem",
2753                "private_key": "auth_serv/server.key",
2754                "dh_file": "auth_serv/dh.conf" }
2755     return params
2756
2757 def test_ap_wpa2_eap_tls_ocsp_key_id(dev, apdev, params):
2758     """EAP-TLS and OCSP certificate signed OCSP response using key ID"""
2759     check_ocsp_support(dev[0])
2760     ocsp = os.path.join(params['logdir'], "ocsp-server-cache-key-id.der")
2761     if not os.path.exists(ocsp):
2762         raise HwsimSkip("No OCSP response available")
2763     params = int_eap_server_params()
2764     params["ocsp_stapling_response"] = ocsp
2765     hostapd.add_ap(apdev[0]['ifname'], params)
2766     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
2767                    identity="tls user", ca_cert="auth_serv/ca.pem",
2768                    private_key="auth_serv/user.pkcs12",
2769                    private_key_passwd="whatever", ocsp=2,
2770                    scan_freq="2412")
2771
2772 def test_ap_wpa2_eap_tls_ocsp_ca_signed_good(dev, apdev, params):
2773     """EAP-TLS and CA signed OCSP response (good)"""
2774     check_ocsp_support(dev[0])
2775     ocsp = os.path.join(params['logdir'], "ocsp-resp-ca-signed.der")
2776     if not os.path.exists(ocsp):
2777         raise HwsimSkip("No OCSP response available")
2778     params = int_eap_server_params()
2779     params["ocsp_stapling_response"] = ocsp
2780     hostapd.add_ap(apdev[0]['ifname'], params)
2781     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
2782                    identity="tls user", ca_cert="auth_serv/ca.pem",
2783                    private_key="auth_serv/user.pkcs12",
2784                    private_key_passwd="whatever", ocsp=2,
2785                    scan_freq="2412")
2786
2787 def test_ap_wpa2_eap_tls_ocsp_ca_signed_revoked(dev, apdev, params):
2788     """EAP-TLS and CA signed OCSP response (revoked)"""
2789     check_ocsp_support(dev[0])
2790     ocsp = os.path.join(params['logdir'], "ocsp-resp-ca-signed-revoked.der")
2791     if not os.path.exists(ocsp):
2792         raise HwsimSkip("No OCSP response available")
2793     params = int_eap_server_params()
2794     params["ocsp_stapling_response"] = ocsp
2795     hostapd.add_ap(apdev[0]['ifname'], params)
2796     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
2797                    identity="tls user", ca_cert="auth_serv/ca.pem",
2798                    private_key="auth_serv/user.pkcs12",
2799                    private_key_passwd="whatever", ocsp=2,
2800                    wait_connect=False, scan_freq="2412")
2801     count = 0
2802     while True:
2803         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
2804         if ev is None:
2805             raise Exception("Timeout on EAP status")
2806         if 'bad certificate status response' in ev:
2807             break
2808         if 'certificate revoked' in ev:
2809             break
2810         count = count + 1
2811         if count > 10:
2812             raise Exception("Unexpected number of EAP status messages")
2813
2814     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
2815     if ev is None:
2816         raise Exception("Timeout on EAP failure report")
2817
2818 def test_ap_wpa2_eap_tls_ocsp_ca_signed_unknown(dev, apdev, params):
2819     """EAP-TLS and CA signed OCSP response (unknown)"""
2820     check_ocsp_support(dev[0])
2821     ocsp = os.path.join(params['logdir'], "ocsp-resp-ca-signed-unknown.der")
2822     if not os.path.exists(ocsp):
2823         raise HwsimSkip("No OCSP response available")
2824     params = int_eap_server_params()
2825     params["ocsp_stapling_response"] = ocsp
2826     hostapd.add_ap(apdev[0]['ifname'], params)
2827     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
2828                    identity="tls user", ca_cert="auth_serv/ca.pem",
2829                    private_key="auth_serv/user.pkcs12",
2830                    private_key_passwd="whatever", ocsp=2,
2831                    wait_connect=False, scan_freq="2412")
2832     count = 0
2833     while True:
2834         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
2835         if ev is None:
2836             raise Exception("Timeout on EAP status")
2837         if 'bad certificate status response' in ev:
2838             break
2839         count = count + 1
2840         if count > 10:
2841             raise Exception("Unexpected number of EAP status messages")
2842
2843     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
2844     if ev is None:
2845         raise Exception("Timeout on EAP failure report")
2846
2847 def test_ap_wpa2_eap_tls_ocsp_server_signed(dev, apdev, params):
2848     """EAP-TLS and server signed OCSP response"""
2849     check_ocsp_support(dev[0])
2850     ocsp = os.path.join(params['logdir'], "ocsp-resp-server-signed.der")
2851     if not os.path.exists(ocsp):
2852         raise HwsimSkip("No OCSP response available")
2853     params = int_eap_server_params()
2854     params["ocsp_stapling_response"] = ocsp
2855     hostapd.add_ap(apdev[0]['ifname'], params)
2856     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
2857                    identity="tls user", ca_cert="auth_serv/ca.pem",
2858                    private_key="auth_serv/user.pkcs12",
2859                    private_key_passwd="whatever", ocsp=2,
2860                    wait_connect=False, scan_freq="2412")
2861     count = 0
2862     while True:
2863         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
2864         if ev is None:
2865             raise Exception("Timeout on EAP status")
2866         if 'bad certificate status response' in ev:
2867             break
2868         count = count + 1
2869         if count > 10:
2870             raise Exception("Unexpected number of EAP status messages")
2871
2872     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
2873     if ev is None:
2874         raise Exception("Timeout on EAP failure report")
2875
2876 def test_ap_wpa2_eap_tls_ocsp_invalid_data(dev, apdev):
2877     """WPA2-Enterprise connection using EAP-TLS and invalid OCSP data"""
2878     check_ocsp_support(dev[0])
2879     params = int_eap_server_params()
2880     params["ocsp_stapling_response"] = "auth_serv/ocsp-req.der"
2881     hostapd.add_ap(apdev[0]['ifname'], params)
2882     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
2883                    identity="tls user", ca_cert="auth_serv/ca.pem",
2884                    private_key="auth_serv/user.pkcs12",
2885                    private_key_passwd="whatever", ocsp=2,
2886                    wait_connect=False, scan_freq="2412")
2887     count = 0
2888     while True:
2889         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
2890         if ev is None:
2891             raise Exception("Timeout on EAP status")
2892         if 'bad certificate status response' in ev:
2893             break
2894         count = count + 1
2895         if count > 10:
2896             raise Exception("Unexpected number of EAP status messages")
2897
2898     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
2899     if ev is None:
2900         raise Exception("Timeout on EAP failure report")
2901
2902 def test_ap_wpa2_eap_tls_ocsp_invalid(dev, apdev):
2903     """WPA2-Enterprise connection using EAP-TLS and invalid OCSP response"""
2904     check_ocsp_support(dev[0])
2905     params = int_eap_server_params()
2906     params["ocsp_stapling_response"] = "auth_serv/ocsp-server-cache.der-invalid"
2907     hostapd.add_ap(apdev[0]['ifname'], params)
2908     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
2909                    identity="tls user", ca_cert="auth_serv/ca.pem",
2910                    private_key="auth_serv/user.pkcs12",
2911                    private_key_passwd="whatever", ocsp=2,
2912                    wait_connect=False, scan_freq="2412")
2913     count = 0
2914     while True:
2915         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
2916         if ev is None:
2917             raise Exception("Timeout on EAP status")
2918         if 'bad certificate status response' in ev:
2919             break
2920         count = count + 1
2921         if count > 10:
2922             raise Exception("Unexpected number of EAP status messages")
2923
2924     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
2925     if ev is None:
2926         raise Exception("Timeout on EAP failure report")
2927
2928 def test_ap_wpa2_eap_tls_ocsp_unknown_sign(dev, apdev):
2929     """WPA2-Enterprise connection using EAP-TLS and unknown OCSP signer"""
2930     check_ocsp_support(dev[0])
2931     params = int_eap_server_params()
2932     params["ocsp_stapling_response"] = "auth_serv/ocsp-server-cache.der-unknown-sign"
2933     hostapd.add_ap(apdev[0]['ifname'], params)
2934     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
2935                    identity="tls user", ca_cert="auth_serv/ca.pem",
2936                    private_key="auth_serv/user.pkcs12",
2937                    private_key_passwd="whatever", ocsp=2,
2938                    wait_connect=False, scan_freq="2412")
2939     count = 0
2940     while True:
2941         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
2942         if ev is None:
2943             raise Exception("Timeout on EAP status")
2944         if 'bad certificate status response' in ev:
2945             break
2946         count = count + 1
2947         if count > 10:
2948             raise Exception("Unexpected number of EAP status messages")
2949
2950     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
2951     if ev is None:
2952         raise Exception("Timeout on EAP failure report")
2953
2954 def test_ap_wpa2_eap_ttls_ocsp_revoked(dev, apdev, params):
2955     """WPA2-Enterprise connection using EAP-TTLS and OCSP status revoked"""
2956     check_ocsp_support(dev[0])
2957     ocsp = os.path.join(params['logdir'], "ocsp-server-cache-revoked.der")
2958     if not os.path.exists(ocsp):
2959         raise HwsimSkip("No OCSP response available")
2960     params = int_eap_server_params()
2961     params["ocsp_stapling_response"] = ocsp
2962     hostapd.add_ap(apdev[0]['ifname'], params)
2963     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
2964                    identity="pap user", ca_cert="auth_serv/ca.pem",
2965                    anonymous_identity="ttls", password="password",
2966                    phase2="auth=PAP", ocsp=2,
2967                    wait_connect=False, scan_freq="2412")
2968     count = 0
2969     while True:
2970         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
2971         if ev is None:
2972             raise Exception("Timeout on EAP status")
2973         if 'bad certificate status response' in ev:
2974             break
2975         if 'certificate revoked' in ev:
2976             break
2977         count = count + 1
2978         if count > 10:
2979             raise Exception("Unexpected number of EAP status messages")
2980
2981     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
2982     if ev is None:
2983         raise Exception("Timeout on EAP failure report")
2984
2985 def test_ap_wpa2_eap_ttls_ocsp_unknown(dev, apdev, params):
2986     """WPA2-Enterprise connection using EAP-TTLS and OCSP status revoked"""
2987     check_ocsp_support(dev[0])
2988     ocsp = os.path.join(params['logdir'], "ocsp-server-cache-unknown.der")
2989     if not os.path.exists(ocsp):
2990         raise HwsimSkip("No OCSP response available")
2991     params = int_eap_server_params()
2992     params["ocsp_stapling_response"] = ocsp
2993     hostapd.add_ap(apdev[0]['ifname'], params)
2994     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
2995                    identity="pap user", ca_cert="auth_serv/ca.pem",
2996                    anonymous_identity="ttls", password="password",
2997                    phase2="auth=PAP", ocsp=2,
2998                    wait_connect=False, scan_freq="2412")
2999     count = 0
3000     while True:
3001         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
3002         if ev is None:
3003             raise Exception("Timeout on EAP status")
3004         if 'bad certificate status response' in ev:
3005             break
3006         count = count + 1
3007         if count > 10:
3008             raise Exception("Unexpected number of EAP status messages")
3009
3010     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3011     if ev is None:
3012         raise Exception("Timeout on EAP failure report")
3013
3014 def test_ap_wpa2_eap_ttls_optional_ocsp_unknown(dev, apdev, params):
3015     """WPA2-Enterprise connection using EAP-TTLS and OCSP status revoked"""
3016     ocsp = os.path.join(params['logdir'], "ocsp-server-cache-unknown.der")
3017     if not os.path.exists(ocsp):
3018         raise HwsimSkip("No OCSP response available")
3019     params = int_eap_server_params()
3020     params["ocsp_stapling_response"] = ocsp
3021     hostapd.add_ap(apdev[0]['ifname'], params)
3022     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3023                    identity="pap user", ca_cert="auth_serv/ca.pem",
3024                    anonymous_identity="ttls", password="password",
3025                    phase2="auth=PAP", ocsp=1, scan_freq="2412")
3026
3027 def test_ap_wpa2_eap_tls_intermediate_ca(dev, apdev, params):
3028     """EAP-TLS with intermediate server/user CA"""
3029     params = int_eap_server_params()
3030     params["ca_cert"] = "auth_serv/iCA-server/ca-and-root.pem"
3031     params["server_cert"] = "auth_serv/iCA-server/server.pem"
3032     params["private_key"] = "auth_serv/iCA-server/server.key"
3033     hostapd.add_ap(apdev[0]['ifname'], params)
3034     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3035                    identity="tls user",
3036                    ca_cert="auth_serv/iCA-user/ca-and-root.pem",
3037                    client_cert="auth_serv/iCA-user/user.pem",
3038                    private_key="auth_serv/iCA-user/user.key",
3039                    scan_freq="2412")
3040
3041 def root_ocsp(cert):
3042     ca = "auth_serv/ca.pem"
3043
3044     fd2, fn2 = tempfile.mkstemp()
3045     os.close(fd2)
3046
3047     arg = [ "openssl", "ocsp", "-reqout", fn2, "-issuer", ca, "-cert", cert,
3048             "-no_nonce", "-sha256", "-text" ]
3049     cmd = subprocess.Popen(arg, stdout=subprocess.PIPE,
3050                            stderr=subprocess.PIPE)
3051     res = cmd.stdout.read() + "\n" + cmd.stderr.read()
3052     cmd.stdout.close()
3053     cmd.stderr.close()
3054     logger.info("OCSP request:\n" + res)
3055
3056     fd, fn = tempfile.mkstemp()
3057     os.close(fd)
3058     arg = [ "openssl", "ocsp", "-index", "rootCA/index.txt",
3059             "-rsigner", ca, "-rkey", "auth_serv/caa-key.pem",
3060             "-CA", ca, "-issuer", ca, "-verify_other", ca, "-trust_other",
3061             "-ndays", "7", "-reqin", fn2, "-resp_no_certs", "-respout", fn,
3062             "-text" ]
3063     cmd = subprocess.Popen(arg, stdout=subprocess.PIPE,
3064                            stderr=subprocess.PIPE)
3065     res = cmd.stdout.read() + "\n" + cmd.stderr.read()
3066     cmd.stdout.close()
3067     cmd.stderr.close()
3068     logger.info("OCSP response:\n" + res)
3069     os.unlink(fn2)
3070     return fn
3071
3072 def ica_ocsp(cert):
3073     prefix = "auth_serv/iCA-server/"
3074     ca = prefix + "cacert.pem"
3075     cert = prefix + cert
3076
3077     fd2, fn2 = tempfile.mkstemp()
3078     os.close(fd2)
3079
3080     arg = [ "openssl", "ocsp", "-reqout", fn2, "-issuer", ca, "-cert", cert,
3081             "-no_nonce", "-sha256", "-text" ]
3082     cmd = subprocess.Popen(arg, stdout=subprocess.PIPE,
3083                            stderr=subprocess.PIPE)
3084     res = cmd.stdout.read() + "\n" + cmd.stderr.read()
3085     cmd.stdout.close()
3086     cmd.stderr.close()
3087     logger.info("OCSP request:\n" + res)
3088
3089     fd, fn = tempfile.mkstemp()
3090     os.close(fd)
3091     arg = [ "openssl", "ocsp", "-index", prefix + "index.txt",
3092             "-rsigner", ca, "-rkey", prefix + "private/cakey.pem",
3093             "-CA", ca, "-issuer", ca, "-verify_other", ca, "-trust_other",
3094             "-ndays", "7", "-reqin", fn2, "-resp_no_certs", "-respout", fn,
3095             "-text" ]
3096     cmd = subprocess.Popen(arg, stdout=subprocess.PIPE,
3097                            stderr=subprocess.PIPE)
3098     res = cmd.stdout.read() + "\n" + cmd.stderr.read()
3099     cmd.stdout.close()
3100     cmd.stderr.close()
3101     logger.info("OCSP response:\n" + res)
3102     os.unlink(fn2)
3103     return fn
3104
3105 def test_ap_wpa2_eap_tls_intermediate_ca_ocsp(dev, apdev, params):
3106     """EAP-TLS with intermediate server/user CA and OCSP on server certificate"""
3107     params = int_eap_server_params()
3108     params["ca_cert"] = "auth_serv/iCA-server/ca-and-root.pem"
3109     params["server_cert"] = "auth_serv/iCA-server/server.pem"
3110     params["private_key"] = "auth_serv/iCA-server/server.key"
3111     fn = ica_ocsp("server.pem")
3112     params["ocsp_stapling_response"] = fn
3113     try:
3114         hostapd.add_ap(apdev[0]['ifname'], params)
3115         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3116                        identity="tls user",
3117                        ca_cert="auth_serv/iCA-user/ca-and-root.pem",
3118                        client_cert="auth_serv/iCA-user/user.pem",
3119                        private_key="auth_serv/iCA-user/user.key",
3120                        scan_freq="2412", ocsp=2)
3121     finally:
3122         os.unlink(fn)
3123
3124 def test_ap_wpa2_eap_tls_intermediate_ca_ocsp_revoked(dev, apdev, params):
3125     """EAP-TLS with intermediate server/user CA and OCSP on revoked server certificate"""
3126     params = int_eap_server_params()
3127     params["ca_cert"] = "auth_serv/iCA-server/ca-and-root.pem"
3128     params["server_cert"] = "auth_serv/iCA-server/server-revoked.pem"
3129     params["private_key"] = "auth_serv/iCA-server/server-revoked.key"
3130     fn = ica_ocsp("server-revoked.pem")
3131     params["ocsp_stapling_response"] = fn
3132     try:
3133         hostapd.add_ap(apdev[0]['ifname'], params)
3134         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3135                        identity="tls user",
3136                        ca_cert="auth_serv/iCA-user/ca-and-root.pem",
3137                        client_cert="auth_serv/iCA-user/user.pem",
3138                        private_key="auth_serv/iCA-user/user.key",
3139                        scan_freq="2412", ocsp=1, wait_connect=False)
3140         count = 0
3141         while True:
3142             ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS",
3143                                     "CTRL-EVENT-EAP-SUCCESS"])
3144             if ev is None:
3145                 raise Exception("Timeout on EAP status")
3146             if "CTRL-EVENT-EAP-SUCCESS" in ev:
3147                 raise Exception("Unexpected EAP-Success")
3148             if 'bad certificate status response' in ev:
3149                 break
3150             if 'certificate revoked' in ev:
3151                 break
3152             count = count + 1
3153             if count > 10:
3154                 raise Exception("Unexpected number of EAP status messages")
3155
3156         ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3157         if ev is None:
3158             raise Exception("Timeout on EAP failure report")
3159         dev[0].request("REMOVE_NETWORK all")
3160         dev[0].wait_disconnected()
3161     finally:
3162         os.unlink(fn)
3163
3164 def test_ap_wpa2_eap_tls_intermediate_ca_ocsp_multi_missing_resp(dev, apdev, params):
3165     """EAP-TLS with intermediate server/user CA and OCSP multi missing response"""
3166     check_ocsp_support(dev[0])
3167     check_ocsp_multi_support(dev[0])
3168
3169     params = int_eap_server_params()
3170     params["ca_cert"] = "auth_serv/iCA-server/ca-and-root.pem"
3171     params["server_cert"] = "auth_serv/iCA-server/server.pem"
3172     params["private_key"] = "auth_serv/iCA-server/server.key"
3173     fn = ica_ocsp("server.pem")
3174     params["ocsp_stapling_response"] = fn
3175     try:
3176         hostapd.add_ap(apdev[0]['ifname'], params)
3177         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3178                        identity="tls user",
3179                        ca_cert="auth_serv/iCA-user/ca-and-root.pem",
3180                        client_cert="auth_serv/iCA-user/user.pem",
3181                        private_key="auth_serv/iCA-user/user.key",
3182                        scan_freq="2412", ocsp=3, wait_connect=False)
3183         count = 0
3184         while True:
3185             ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS",
3186                                     "CTRL-EVENT-EAP-SUCCESS"])
3187             if ev is None:
3188                 raise Exception("Timeout on EAP status")
3189             if "CTRL-EVENT-EAP-SUCCESS" in ev:
3190                 raise Exception("Unexpected EAP-Success")
3191             if 'bad certificate status response' in ev:
3192                 break
3193             if 'certificate revoked' in ev:
3194                 break
3195             count = count + 1
3196             if count > 10:
3197                 raise Exception("Unexpected number of EAP status messages")
3198
3199         ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3200         if ev is None:
3201             raise Exception("Timeout on EAP failure report")
3202         dev[0].request("REMOVE_NETWORK all")
3203         dev[0].wait_disconnected()
3204     finally:
3205         os.unlink(fn)
3206
3207 def test_ap_wpa2_eap_tls_intermediate_ca_ocsp_multi(dev, apdev, params):
3208     """EAP-TLS with intermediate server/user CA and OCSP multi OK"""
3209     check_ocsp_support(dev[0])
3210     check_ocsp_multi_support(dev[0])
3211
3212     params = int_eap_server_params()
3213     params["ca_cert"] = "auth_serv/iCA-server/ca-and-root.pem"
3214     params["server_cert"] = "auth_serv/iCA-server/server.pem"
3215     params["private_key"] = "auth_serv/iCA-server/server.key"
3216     fn = ica_ocsp("server.pem")
3217     fn2 = root_ocsp("auth_serv/iCA-server/cacert.pem")
3218     params["ocsp_stapling_response"] = fn
3219
3220     with open(fn, "r") as f:
3221         resp_server = f.read()
3222     with open(fn2, "r") as f:
3223         resp_ica = f.read()
3224
3225     fd3, fn3 = tempfile.mkstemp()
3226     try:
3227         f = os.fdopen(fd3, 'w')
3228         f.write(struct.pack(">L", len(resp_server))[1:4])
3229         f.write(resp_server)
3230         f.write(struct.pack(">L", len(resp_ica))[1:4])
3231         f.write(resp_ica)
3232         f.close()
3233
3234         params["ocsp_stapling_response_multi"] = fn3
3235
3236         hostapd.add_ap(apdev[0]['ifname'], params)
3237         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3238                        identity="tls user",
3239                        ca_cert="auth_serv/iCA-user/ca-and-root.pem",
3240                        client_cert="auth_serv/iCA-user/user.pem",
3241                        private_key="auth_serv/iCA-user/user.key",
3242                        scan_freq="2412", ocsp=3, wait_connect=False)
3243         count = 0
3244         while True:
3245             ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS",
3246                                     "CTRL-EVENT-EAP-SUCCESS"])
3247             if ev is None:
3248                 raise Exception("Timeout on EAP status")
3249             if "CTRL-EVENT-EAP-SUCCESS" in ev:
3250                 raise Exception("Unexpected EAP-Success")
3251             if 'bad certificate status response' in ev:
3252                 break
3253             if 'certificate revoked' in ev:
3254                 break
3255             count = count + 1
3256             if count > 10:
3257                 raise Exception("Unexpected number of EAP status messages")
3258
3259         ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3260         if ev is None:
3261             raise Exception("Timeout on EAP failure report")
3262         dev[0].request("REMOVE_NETWORK all")
3263         dev[0].wait_disconnected()
3264     finally:
3265         os.unlink(fn)
3266         os.unlink(fn2)
3267         os.unlink(fn3)
3268
3269 def test_ap_wpa2_eap_tls_ocsp_multi_revoked(dev, apdev, params):
3270     """EAP-TLS and CA signed OCSP multi response (revoked)"""
3271     check_ocsp_support(dev[0])
3272     check_ocsp_multi_support(dev[0])
3273
3274     ocsp_revoked = os.path.join(params['logdir'],
3275                                 "ocsp-resp-ca-signed-revoked.der")
3276     if not os.path.exists(ocsp_revoked):
3277         raise HwsimSkip("No OCSP response (revoked) available")
3278     ocsp_unknown = os.path.join(params['logdir'],
3279                                 "ocsp-resp-ca-signed-unknown.der")
3280     if not os.path.exists(ocsp_unknown):
3281         raise HwsimSkip("No OCSP response(unknown) available")
3282
3283     with open(ocsp_revoked, "r") as f:
3284         resp_revoked = f.read()
3285     with open(ocsp_unknown, "r") as f:
3286         resp_unknown = f.read()
3287
3288     fd, fn = tempfile.mkstemp()
3289     try:
3290         # This is not really a valid order of the OCSPResponse items in the
3291         # list, but this works for now to verify parsing and processing of
3292         # multiple responses.
3293         f = os.fdopen(fd, 'w')
3294         f.write(struct.pack(">L", len(resp_unknown))[1:4])
3295         f.write(resp_unknown)
3296         f.write(struct.pack(">L", len(resp_revoked))[1:4])
3297         f.write(resp_revoked)
3298         f.write(struct.pack(">L", 0)[1:4])
3299         f.write(struct.pack(">L", len(resp_unknown))[1:4])
3300         f.write(resp_unknown)
3301         f.close()
3302
3303         params = int_eap_server_params()
3304         params["ocsp_stapling_response_multi"] = fn
3305         hostapd.add_ap(apdev[0]['ifname'], params)
3306         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3307                        identity="tls user", ca_cert="auth_serv/ca.pem",
3308                        private_key="auth_serv/user.pkcs12",
3309                        private_key_passwd="whatever", ocsp=1,
3310                        wait_connect=False, scan_freq="2412")
3311         count = 0
3312         while True:
3313             ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS",
3314                                     "CTRL-EVENT-EAP-SUCCESS"])
3315             if ev is None:
3316                 raise Exception("Timeout on EAP status")
3317             if "CTRL-EVENT-EAP-SUCCESS" in ev:
3318                 raise Exception("Unexpected EAP-Success")
3319             if 'bad certificate status response' in ev:
3320                 break
3321             if 'certificate revoked' in ev:
3322                 break
3323             count = count + 1
3324             if count > 10:
3325                 raise Exception("Unexpected number of EAP status messages")
3326     finally:
3327         os.unlink(fn)
3328
3329 def test_ap_wpa2_eap_tls_domain_suffix_match_cn_full(dev, apdev):
3330     """WPA2-Enterprise using EAP-TLS and domain suffix match (CN)"""
3331     check_domain_match_full(dev[0])
3332     params = int_eap_server_params()
3333     params["server_cert"] = "auth_serv/server-no-dnsname.pem"
3334     params["private_key"] = "auth_serv/server-no-dnsname.key"
3335     hostapd.add_ap(apdev[0]['ifname'], params)
3336     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3337                    identity="tls user", ca_cert="auth_serv/ca.pem",
3338                    private_key="auth_serv/user.pkcs12",
3339                    private_key_passwd="whatever",
3340                    domain_suffix_match="server3.w1.fi",
3341                    scan_freq="2412")
3342
3343 def test_ap_wpa2_eap_tls_domain_match_cn(dev, apdev):
3344     """WPA2-Enterprise using EAP-TLS and domainmatch (CN)"""
3345     check_domain_match(dev[0])
3346     params = int_eap_server_params()
3347     params["server_cert"] = "auth_serv/server-no-dnsname.pem"
3348     params["private_key"] = "auth_serv/server-no-dnsname.key"
3349     hostapd.add_ap(apdev[0]['ifname'], params)
3350     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3351                    identity="tls user", ca_cert="auth_serv/ca.pem",
3352                    private_key="auth_serv/user.pkcs12",
3353                    private_key_passwd="whatever",
3354                    domain_match="server3.w1.fi",
3355                    scan_freq="2412")
3356
3357 def test_ap_wpa2_eap_tls_domain_suffix_match_cn(dev, apdev):
3358     """WPA2-Enterprise using EAP-TLS and domain suffix match (CN)"""
3359     check_domain_match_full(dev[0])
3360     params = int_eap_server_params()
3361     params["server_cert"] = "auth_serv/server-no-dnsname.pem"
3362     params["private_key"] = "auth_serv/server-no-dnsname.key"
3363     hostapd.add_ap(apdev[0]['ifname'], params)
3364     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3365                    identity="tls user", ca_cert="auth_serv/ca.pem",
3366                    private_key="auth_serv/user.pkcs12",
3367                    private_key_passwd="whatever",
3368                    domain_suffix_match="w1.fi",
3369                    scan_freq="2412")
3370
3371 def test_ap_wpa2_eap_tls_domain_suffix_mismatch_cn(dev, apdev):
3372     """WPA2-Enterprise using EAP-TLS and domain suffix mismatch (CN)"""
3373     check_domain_suffix_match(dev[0])
3374     params = int_eap_server_params()
3375     params["server_cert"] = "auth_serv/server-no-dnsname.pem"
3376     params["private_key"] = "auth_serv/server-no-dnsname.key"
3377     hostapd.add_ap(apdev[0]['ifname'], params)
3378     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3379                    identity="tls user", ca_cert="auth_serv/ca.pem",
3380                    private_key="auth_serv/user.pkcs12",
3381                    private_key_passwd="whatever",
3382                    domain_suffix_match="example.com",
3383                    wait_connect=False,
3384                    scan_freq="2412")
3385     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3386                    identity="tls user", ca_cert="auth_serv/ca.pem",
3387                    private_key="auth_serv/user.pkcs12",
3388                    private_key_passwd="whatever",
3389                    domain_suffix_match="erver3.w1.fi",
3390                    wait_connect=False,
3391                    scan_freq="2412")
3392     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3393     if ev is None:
3394         raise Exception("Timeout on EAP failure report")
3395     ev = dev[1].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3396     if ev is None:
3397         raise Exception("Timeout on EAP failure report (2)")
3398
3399 def test_ap_wpa2_eap_tls_domain_mismatch_cn(dev, apdev):
3400     """WPA2-Enterprise using EAP-TLS and domain mismatch (CN)"""
3401     check_domain_match(dev[0])
3402     params = int_eap_server_params()
3403     params["server_cert"] = "auth_serv/server-no-dnsname.pem"
3404     params["private_key"] = "auth_serv/server-no-dnsname.key"
3405     hostapd.add_ap(apdev[0]['ifname'], params)
3406     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3407                    identity="tls user", ca_cert="auth_serv/ca.pem",
3408                    private_key="auth_serv/user.pkcs12",
3409                    private_key_passwd="whatever",
3410                    domain_match="example.com",
3411                    wait_connect=False,
3412                    scan_freq="2412")
3413     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3414                    identity="tls user", ca_cert="auth_serv/ca.pem",
3415                    private_key="auth_serv/user.pkcs12",
3416                    private_key_passwd="whatever",
3417                    domain_match="w1.fi",
3418                    wait_connect=False,
3419                    scan_freq="2412")
3420     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3421     if ev is None:
3422         raise Exception("Timeout on EAP failure report")
3423     ev = dev[1].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3424     if ev is None:
3425         raise Exception("Timeout on EAP failure report (2)")
3426
3427 def test_ap_wpa2_eap_ttls_expired_cert(dev, apdev):
3428     """WPA2-Enterprise using EAP-TTLS and expired certificate"""
3429     skip_with_fips(dev[0])
3430     params = int_eap_server_params()
3431     params["server_cert"] = "auth_serv/server-expired.pem"
3432     params["private_key"] = "auth_serv/server-expired.key"
3433     hostapd.add_ap(apdev[0]['ifname'], params)
3434     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3435                    identity="mschap user", password="password",
3436                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
3437                    wait_connect=False,
3438                    scan_freq="2412")
3439     ev = dev[0].wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR"])
3440     if ev is None:
3441         raise Exception("Timeout on EAP certificate error report")
3442     if "reason=4" not in ev or "certificate has expired" not in ev:
3443         raise Exception("Unexpected failure reason: " + ev)
3444     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3445     if ev is None:
3446         raise Exception("Timeout on EAP failure report")
3447
3448 def test_ap_wpa2_eap_ttls_ignore_expired_cert(dev, apdev):
3449     """WPA2-Enterprise using EAP-TTLS and ignore certificate expiration"""
3450     skip_with_fips(dev[0])
3451     params = int_eap_server_params()
3452     params["server_cert"] = "auth_serv/server-expired.pem"
3453     params["private_key"] = "auth_serv/server-expired.key"
3454     hostapd.add_ap(apdev[0]['ifname'], params)
3455     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3456                    identity="mschap user", password="password",
3457                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
3458                    phase1="tls_disable_time_checks=1",
3459                    scan_freq="2412")
3460
3461 def test_ap_wpa2_eap_ttls_long_duration(dev, apdev):
3462     """WPA2-Enterprise using EAP-TTLS and long certificate duration"""
3463     skip_with_fips(dev[0])
3464     params = int_eap_server_params()
3465     params["server_cert"] = "auth_serv/server-long-duration.pem"
3466     params["private_key"] = "auth_serv/server-long-duration.key"
3467     hostapd.add_ap(apdev[0]['ifname'], params)
3468     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3469                    identity="mschap user", password="password",
3470                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
3471                    scan_freq="2412")
3472
3473 def test_ap_wpa2_eap_ttls_server_cert_eku_client(dev, apdev):
3474     """WPA2-Enterprise using EAP-TTLS and server cert with client EKU"""
3475     skip_with_fips(dev[0])
3476     params = int_eap_server_params()
3477     params["server_cert"] = "auth_serv/server-eku-client.pem"
3478     params["private_key"] = "auth_serv/server-eku-client.key"
3479     hostapd.add_ap(apdev[0]['ifname'], params)
3480     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3481                    identity="mschap user", password="password",
3482                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
3483                    wait_connect=False,
3484                    scan_freq="2412")
3485     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3486     if ev is None:
3487         raise Exception("Timeout on EAP failure report")
3488
3489 def test_ap_wpa2_eap_ttls_server_cert_eku_client_server(dev, apdev):
3490     """WPA2-Enterprise using EAP-TTLS and server cert with client and server EKU"""
3491     skip_with_fips(dev[0])
3492     params = int_eap_server_params()
3493     params["server_cert"] = "auth_serv/server-eku-client-server.pem"
3494     params["private_key"] = "auth_serv/server-eku-client-server.key"
3495     hostapd.add_ap(apdev[0]['ifname'], params)
3496     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3497                    identity="mschap user", password="password",
3498                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
3499                    scan_freq="2412")
3500
3501 def test_ap_wpa2_eap_ttls_server_pkcs12(dev, apdev):
3502     """WPA2-Enterprise using EAP-TTLS and server PKCS#12 file"""
3503     skip_with_fips(dev[0])
3504     params = int_eap_server_params()
3505     del params["server_cert"]
3506     params["private_key"] = "auth_serv/server.pkcs12"
3507     hostapd.add_ap(apdev[0]['ifname'], params)
3508     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3509                    identity="mschap user", password="password",
3510                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
3511                    scan_freq="2412")
3512
3513 def test_ap_wpa2_eap_ttls_dh_params(dev, apdev):
3514     """WPA2-Enterprise connection using EAP-TTLS/CHAP and setting DH params"""
3515     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3516     hostapd.add_ap(apdev[0]['ifname'], params)
3517     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
3518                 anonymous_identity="ttls", password="password",
3519                 ca_cert="auth_serv/ca.der", phase2="auth=PAP",
3520                 dh_file="auth_serv/dh.conf")
3521
3522 def test_ap_wpa2_eap_ttls_dh_params_dsa(dev, apdev):
3523     """WPA2-Enterprise connection using EAP-TTLS and setting DH params (DSA)"""
3524     check_dh_dsa_support(dev[0])
3525     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3526     hostapd.add_ap(apdev[0]['ifname'], params)
3527     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
3528                 anonymous_identity="ttls", password="password",
3529                 ca_cert="auth_serv/ca.der", phase2="auth=PAP",
3530                 dh_file="auth_serv/dsaparam.pem")
3531
3532 def test_ap_wpa2_eap_ttls_dh_params_not_found(dev, apdev):
3533     """EAP-TTLS and DH params file not found"""
3534     skip_with_fips(dev[0])
3535     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3536     hostapd.add_ap(apdev[0]['ifname'], params)
3537     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3538                    identity="mschap user", password="password",
3539                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
3540                    dh_file="auth_serv/dh-no-such-file.conf",
3541                    scan_freq="2412", wait_connect=False)
3542     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3543     if ev is None:
3544         raise Exception("EAP failure timed out")
3545     dev[0].request("REMOVE_NETWORK all")
3546     dev[0].wait_disconnected()
3547
3548 def test_ap_wpa2_eap_ttls_dh_params_invalid(dev, apdev):
3549     """EAP-TTLS and invalid DH params file"""
3550     skip_with_fips(dev[0])
3551     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3552     hostapd.add_ap(apdev[0]['ifname'], params)
3553     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3554                    identity="mschap user", password="password",
3555                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
3556                    dh_file="auth_serv/ca.pem",
3557                    scan_freq="2412", wait_connect=False)
3558     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3559     if ev is None:
3560         raise Exception("EAP failure timed out")
3561     dev[0].request("REMOVE_NETWORK all")
3562     dev[0].wait_disconnected()
3563
3564 def test_ap_wpa2_eap_ttls_dh_params_blob(dev, apdev):
3565     """WPA2-Enterprise connection using EAP-TTLS/CHAP and setting DH params from blob"""
3566     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3567     hostapd.add_ap(apdev[0]['ifname'], params)
3568     dh = read_pem("auth_serv/dh2.conf")
3569     if "OK" not in dev[0].request("SET blob dhparams " + dh.encode("hex")):
3570         raise Exception("Could not set dhparams blob")
3571     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
3572                 anonymous_identity="ttls", password="password",
3573                 ca_cert="auth_serv/ca.der", phase2="auth=PAP",
3574                 dh_file="blob://dhparams")
3575
3576 def test_ap_wpa2_eap_ttls_dh_params_server(dev, apdev):
3577     """WPA2-Enterprise using EAP-TTLS and alternative server dhparams"""
3578     params = int_eap_server_params()
3579     params["dh_file"] = "auth_serv/dh2.conf"
3580     hostapd.add_ap(apdev[0]['ifname'], params)
3581     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
3582                 anonymous_identity="ttls", password="password",
3583                 ca_cert="auth_serv/ca.der", phase2="auth=PAP")
3584
3585 def test_ap_wpa2_eap_ttls_dh_params_dsa_server(dev, apdev):
3586     """WPA2-Enterprise using EAP-TTLS and alternative server dhparams (DSA)"""
3587     params = int_eap_server_params()
3588     params["dh_file"] = "auth_serv/dsaparam.pem"
3589     hostapd.add_ap(apdev[0]['ifname'], params)
3590     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
3591                 anonymous_identity="ttls", password="password",
3592                 ca_cert="auth_serv/ca.der", phase2="auth=PAP")
3593
3594 def test_ap_wpa2_eap_ttls_dh_params_not_found(dev, apdev):
3595     """EAP-TLS server and dhparams file not found"""
3596     params = int_eap_server_params()
3597     params["dh_file"] = "auth_serv/dh-no-such-file.conf"
3598     hapd = hostapd.add_ap(apdev[0]['ifname'], params, no_enable=True)
3599     if "FAIL" not in hapd.request("ENABLE"):
3600         raise Exception("Invalid configuration accepted")
3601
3602 def test_ap_wpa2_eap_ttls_dh_params_invalid(dev, apdev):
3603     """EAP-TLS server and invalid dhparams file"""
3604     params = int_eap_server_params()
3605     params["dh_file"] = "auth_serv/ca.pem"
3606     hapd = hostapd.add_ap(apdev[0]['ifname'], params, no_enable=True)
3607     if "FAIL" not in hapd.request("ENABLE"):
3608         raise Exception("Invalid configuration accepted")
3609
3610 def test_ap_wpa2_eap_reauth(dev, apdev):
3611     """WPA2-Enterprise and Authenticator forcing reauthentication"""
3612     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3613     params['eap_reauth_period'] = '2'
3614     hostapd.add_ap(apdev[0]['ifname'], params)
3615     eap_connect(dev[0], apdev[0], "PAX", "pax.user@example.com",
3616                 password_hex="0123456789abcdef0123456789abcdef")
3617     logger.info("Wait for reauthentication")
3618     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=10)
3619     if ev is None:
3620         raise Exception("Timeout on reauthentication")
3621     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
3622     if ev is None:
3623         raise Exception("Timeout on reauthentication")
3624     for i in range(0, 20):
3625         state = dev[0].get_status_field("wpa_state")
3626         if state == "COMPLETED":
3627             break
3628         time.sleep(0.1)
3629     if state != "COMPLETED":
3630         raise Exception("Reauthentication did not complete")
3631
3632 def test_ap_wpa2_eap_request_identity_message(dev, apdev):
3633     """Optional displayable message in EAP Request-Identity"""
3634     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3635     params['eap_message'] = 'hello\\0networkid=netw,nasid=foo,portid=0,NAIRealms=example.com'
3636     hostapd.add_ap(apdev[0]['ifname'], params)
3637     eap_connect(dev[0], apdev[0], "PAX", "pax.user@example.com",
3638                 password_hex="0123456789abcdef0123456789abcdef")
3639
3640 def test_ap_wpa2_eap_sim_aka_result_ind(dev, apdev):
3641     """WPA2-Enterprise using EAP-SIM/AKA and protected result indication"""
3642     check_hlr_auc_gw_support()
3643     params = int_eap_server_params()
3644     params['eap_sim_db'] = "unix:/tmp/hlr_auc_gw.sock"
3645     params['eap_sim_aka_result_ind'] = "1"
3646     hostapd.add_ap(apdev[0]['ifname'], params)
3647
3648     eap_connect(dev[0], apdev[0], "SIM", "1232010000000000",
3649                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
3650                 phase1="result_ind=1")
3651     eap_reauth(dev[0], "SIM")
3652     eap_connect(dev[1], apdev[0], "SIM", "1232010000000000",
3653                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581")
3654
3655     dev[0].request("REMOVE_NETWORK all")
3656     dev[1].request("REMOVE_NETWORK all")
3657
3658     eap_connect(dev[0], apdev[0], "AKA", "0232010000000000",
3659                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123",
3660                 phase1="result_ind=1")
3661     eap_reauth(dev[0], "AKA")
3662     eap_connect(dev[1], apdev[0], "AKA", "0232010000000000",
3663                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123")
3664
3665     dev[0].request("REMOVE_NETWORK all")
3666     dev[1].request("REMOVE_NETWORK all")
3667
3668     eap_connect(dev[0], apdev[0], "AKA'", "6555444333222111",
3669                 password="5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123",
3670                 phase1="result_ind=1")
3671     eap_reauth(dev[0], "AKA'")
3672     eap_connect(dev[1], apdev[0], "AKA'", "6555444333222111",
3673                 password="5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123")
3674
3675 def test_ap_wpa2_eap_too_many_roundtrips(dev, apdev):
3676     """WPA2-Enterprise connection resulting in too many EAP roundtrips"""
3677     skip_with_fips(dev[0])
3678     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3679     hostapd.add_ap(apdev[0]['ifname'], params)
3680     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
3681                    eap="TTLS", identity="mschap user",
3682                    wait_connect=False, scan_freq="2412", ieee80211w="1",
3683                    anonymous_identity="ttls", password="password",
3684                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
3685                    fragment_size="10")
3686     ev = dev[0].wait_event(["EAP: more than"], timeout=20)
3687     if ev is None:
3688         raise Exception("EAP roundtrip limit not reached")
3689
3690 def test_ap_wpa2_eap_expanded_nak(dev, apdev):
3691     """WPA2-Enterprise connection with EAP resulting in expanded NAK"""
3692     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3693     hostapd.add_ap(apdev[0]['ifname'], params)
3694     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
3695                    eap="PSK", identity="vendor-test",
3696                    password_hex="ff23456789abcdef0123456789abcdef",
3697                    wait_connect=False)
3698
3699     found = False
3700     for i in range(0, 5):
3701         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"], timeout=16)
3702         if ev is None:
3703             raise Exception("Association and EAP start timed out")
3704         if "refuse proposed method" in ev:
3705             found = True
3706             break
3707     if not found:
3708         raise Exception("Unexpected EAP status: " + ev)
3709
3710     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3711     if ev is None:
3712         raise Exception("EAP failure timed out")
3713
3714 def test_ap_wpa2_eap_sql(dev, apdev, params):
3715     """WPA2-Enterprise connection using SQLite for user DB"""
3716     skip_with_fips(dev[0])
3717     try:
3718         import sqlite3
3719     except ImportError:
3720         raise HwsimSkip("No sqlite3 module available")
3721     dbfile = os.path.join(params['logdir'], "eap-user.db")
3722     try:
3723         os.remove(dbfile)
3724     except:
3725         pass
3726     con = sqlite3.connect(dbfile)
3727     with con:
3728         cur = con.cursor()
3729         cur.execute("CREATE TABLE users(identity TEXT PRIMARY KEY, methods TEXT, password TEXT, remediation TEXT, phase2 INTEGER)")
3730         cur.execute("CREATE TABLE wildcards(identity TEXT PRIMARY KEY, methods TEXT)")
3731         cur.execute("INSERT INTO users(identity,methods,password,phase2) VALUES ('user-pap','TTLS-PAP','password',1)")
3732         cur.execute("INSERT INTO users(identity,methods,password,phase2) VALUES ('user-chap','TTLS-CHAP','password',1)")
3733         cur.execute("INSERT INTO users(identity,methods,password,phase2) VALUES ('user-mschap','TTLS-MSCHAP','password',1)")
3734         cur.execute("INSERT INTO users(identity,methods,password,phase2) VALUES ('user-mschapv2','TTLS-MSCHAPV2','password',1)")
3735         cur.execute("INSERT INTO wildcards(identity,methods) VALUES ('','TTLS,TLS')")
3736         cur.execute("CREATE TABLE authlog(timestamp TEXT, session TEXT, nas_ip TEXT, username TEXT, note TEXT)")
3737
3738     try:
3739         params = int_eap_server_params()
3740         params["eap_user_file"] = "sqlite:" + dbfile
3741         hostapd.add_ap(apdev[0]['ifname'], params)
3742         eap_connect(dev[0], apdev[0], "TTLS", "user-mschapv2",
3743                     anonymous_identity="ttls", password="password",
3744                     ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
3745         dev[0].request("REMOVE_NETWORK all")
3746         eap_connect(dev[1], apdev[0], "TTLS", "user-mschap",
3747                     anonymous_identity="ttls", password="password",
3748                     ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP")
3749         dev[1].request("REMOVE_NETWORK all")
3750         eap_connect(dev[0], apdev[0], "TTLS", "user-chap",
3751                     anonymous_identity="ttls", password="password",
3752                     ca_cert="auth_serv/ca.pem", phase2="auth=CHAP")
3753         eap_connect(dev[1], apdev[0], "TTLS", "user-pap",
3754                     anonymous_identity="ttls", password="password",
3755                     ca_cert="auth_serv/ca.pem", phase2="auth=PAP")
3756     finally:
3757         os.remove(dbfile)
3758
3759 def test_ap_wpa2_eap_non_ascii_identity(dev, apdev):
3760     """WPA2-Enterprise connection attempt using non-ASCII identity"""
3761     params = int_eap_server_params()
3762     hostapd.add_ap(apdev[0]['ifname'], params)
3763     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3764                    identity="\x80", password="password", wait_connect=False)
3765     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3766                    identity="a\x80", password="password", wait_connect=False)
3767     for i in range(0, 2):
3768         ev = dev[i].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
3769         if ev is None:
3770             raise Exception("Association and EAP start timed out")
3771         ev = dev[i].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=10)
3772         if ev is None:
3773             raise Exception("EAP method selection timed out")
3774
3775 def test_ap_wpa2_eap_non_ascii_identity2(dev, apdev):
3776     """WPA2-Enterprise connection attempt using non-ASCII identity"""
3777     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3778     hostapd.add_ap(apdev[0]['ifname'], params)
3779     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3780                    identity="\x80", password="password", wait_connect=False)
3781     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3782                    identity="a\x80", password="password", wait_connect=False)
3783     for i in range(0, 2):
3784         ev = dev[i].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
3785         if ev is None:
3786             raise Exception("Association and EAP start timed out")
3787         ev = dev[i].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=10)
3788         if ev is None:
3789             raise Exception("EAP method selection timed out")
3790
3791 def test_openssl_cipher_suite_config_wpas(dev, apdev):
3792     """OpenSSL cipher suite configuration on wpa_supplicant"""
3793     tls = dev[0].request("GET tls_library")
3794     if not tls.startswith("OpenSSL"):
3795         raise HwsimSkip("TLS library is not OpenSSL: " + tls)
3796     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3797     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
3798     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
3799                 anonymous_identity="ttls", password="password",
3800                 openssl_ciphers="AES128",
3801                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP")
3802     eap_connect(dev[1], apdev[0], "TTLS", "pap user",
3803                 anonymous_identity="ttls", password="password",
3804                 openssl_ciphers="EXPORT",
3805                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP",
3806                 expect_failure=True, maybe_local_error=True)
3807     dev[2].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3808                    identity="pap user", anonymous_identity="ttls",
3809                    password="password",
3810                    openssl_ciphers="FOO",
3811                    ca_cert="auth_serv/ca.pem", phase2="auth=PAP",
3812                    wait_connect=False)
3813     ev = dev[2].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
3814     if ev is None:
3815         raise Exception("EAP failure after invalid openssl_ciphers not reported")
3816     dev[2].request("DISCONNECT")
3817
3818 def test_openssl_cipher_suite_config_hapd(dev, apdev):
3819     """OpenSSL cipher suite configuration on hostapd"""
3820     tls = dev[0].request("GET tls_library")
3821     if not tls.startswith("OpenSSL"):
3822         raise HwsimSkip("wpa_supplicant TLS library is not OpenSSL: " + tls)
3823     params = int_eap_server_params()
3824     params['openssl_ciphers'] = "AES256"
3825     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
3826     tls = hapd.request("GET tls_library")
3827     if not tls.startswith("OpenSSL"):
3828         raise HwsimSkip("hostapd TLS library is not OpenSSL: " + tls)
3829     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
3830                 anonymous_identity="ttls", password="password",
3831                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP")
3832     eap_connect(dev[1], apdev[0], "TTLS", "pap user",
3833                 anonymous_identity="ttls", password="password",
3834                 openssl_ciphers="AES128",
3835                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP",
3836                 expect_failure=True)
3837     eap_connect(dev[2], apdev[0], "TTLS", "pap user",
3838                 anonymous_identity="ttls", password="password",
3839                 openssl_ciphers="HIGH:!ADH",
3840                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP")
3841
3842     params['openssl_ciphers'] = "FOO"
3843     hapd2 = hostapd.add_ap(apdev[1]['ifname'], params, no_enable=True)
3844     if "FAIL" not in hapd2.request("ENABLE"):
3845         raise Exception("Invalid openssl_ciphers value accepted")
3846
3847 def test_wpa2_eap_ttls_pap_key_lifetime_in_memory(dev, apdev, params):
3848     """Key lifetime in memory with WPA2-Enterprise using EAP-TTLS/PAP"""
3849     p = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3850     hapd = hostapd.add_ap(apdev[0]['ifname'], p)
3851     password = "63d2d21ac3c09ed567ee004a34490f1d16e7fa5835edf17ddba70a63f1a90a25"
3852     pid = find_wpas_process(dev[0])
3853     id = eap_connect(dev[0], apdev[0], "TTLS", "pap-secret",
3854                      anonymous_identity="ttls", password=password,
3855                      ca_cert="auth_serv/ca.pem", phase2="auth=PAP")
3856     # The decrypted copy of GTK is freed only after the CTRL-EVENT-CONNECTED
3857     # event has been delivered, so verify that wpa_supplicant has returned to
3858     # eloop before reading process memory.
3859     time.sleep(1)
3860     dev[0].ping()
3861     buf = read_process_memory(pid, password)
3862
3863     dev[0].request("DISCONNECT")
3864     dev[0].wait_disconnected()
3865
3866     dev[0].relog()
3867     msk = None
3868     emsk = None
3869     pmk = None
3870     ptk = None
3871     gtk = None
3872     with open(os.path.join(params['logdir'], 'log0'), 'r') as f:
3873         for l in f.readlines():
3874             if "EAP-TTLS: Derived key - hexdump" in l:
3875                 val = l.strip().split(':')[3].replace(' ', '')
3876                 msk = binascii.unhexlify(val)
3877             if "EAP-TTLS: Derived EMSK - hexdump" in l:
3878                 val = l.strip().split(':')[3].replace(' ', '')
3879                 emsk = binascii.unhexlify(val)
3880             if "WPA: PMK - hexdump" in l:
3881                 val = l.strip().split(':')[3].replace(' ', '')
3882                 pmk = binascii.unhexlify(val)
3883             if "WPA: PTK - hexdump" in l:
3884                 val = l.strip().split(':')[3].replace(' ', '')
3885                 ptk = binascii.unhexlify(val)
3886             if "WPA: Group Key - hexdump" in l:
3887                 val = l.strip().split(':')[3].replace(' ', '')
3888                 gtk = binascii.unhexlify(val)
3889     if not msk or not emsk or not pmk or not ptk or not gtk:
3890         raise Exception("Could not find keys from debug log")
3891     if len(gtk) != 16:
3892         raise Exception("Unexpected GTK length")
3893
3894     kck = ptk[0:16]
3895     kek = ptk[16:32]
3896     tk = ptk[32:48]
3897
3898     fname = os.path.join(params['logdir'],
3899                          'wpa2_eap_ttls_pap_key_lifetime_in_memory.memctx-')
3900
3901     logger.info("Checking keys in memory while associated")
3902     get_key_locations(buf, password, "Password")
3903     get_key_locations(buf, pmk, "PMK")
3904     get_key_locations(buf, msk, "MSK")
3905     get_key_locations(buf, emsk, "EMSK")
3906     if password not in buf:
3907         raise HwsimSkip("Password not found while associated")
3908     if pmk not in buf:
3909         raise HwsimSkip("PMK not found while associated")
3910     if kck not in buf:
3911         raise Exception("KCK not found while associated")
3912     if kek not in buf:
3913         raise Exception("KEK not found while associated")
3914     if tk in buf:
3915         raise Exception("TK found from memory")
3916     if gtk in buf:
3917         get_key_locations(buf, gtk, "GTK")
3918         raise Exception("GTK found from memory")
3919
3920     logger.info("Checking keys in memory after disassociation")
3921     buf = read_process_memory(pid, password)
3922
3923     # Note: Password is still present in network configuration
3924     # Note: PMK is in PMKSA cache and EAP fast re-auth data
3925
3926     get_key_locations(buf, password, "Password")
3927     get_key_locations(buf, pmk, "PMK")
3928     get_key_locations(buf, msk, "MSK")
3929     get_key_locations(buf, emsk, "EMSK")
3930     verify_not_present(buf, kck, fname, "KCK")
3931     verify_not_present(buf, kek, fname, "KEK")
3932     verify_not_present(buf, tk, fname, "TK")
3933     verify_not_present(buf, gtk, fname, "GTK")
3934
3935     dev[0].request("PMKSA_FLUSH")
3936     dev[0].set_network_quoted(id, "identity", "foo")
3937     logger.info("Checking keys in memory after PMKSA cache and EAP fast reauth flush")
3938     buf = read_process_memory(pid, password)
3939     get_key_locations(buf, password, "Password")
3940     get_key_locations(buf, pmk, "PMK")
3941     get_key_locations(buf, msk, "MSK")
3942     get_key_locations(buf, emsk, "EMSK")
3943     verify_not_present(buf, pmk, fname, "PMK")
3944
3945     dev[0].request("REMOVE_NETWORK all")
3946
3947     logger.info("Checking keys in memory after network profile removal")
3948     buf = read_process_memory(pid, password)
3949
3950     get_key_locations(buf, password, "Password")
3951     get_key_locations(buf, pmk, "PMK")
3952     get_key_locations(buf, msk, "MSK")
3953     get_key_locations(buf, emsk, "EMSK")
3954     verify_not_present(buf, password, fname, "password")
3955     verify_not_present(buf, pmk, fname, "PMK")
3956     verify_not_present(buf, kck, fname, "KCK")
3957     verify_not_present(buf, kek, fname, "KEK")
3958     verify_not_present(buf, tk, fname, "TK")
3959     verify_not_present(buf, gtk, fname, "GTK")
3960     verify_not_present(buf, msk, fname, "MSK")
3961     verify_not_present(buf, emsk, fname, "EMSK")
3962
3963 def test_ap_wpa2_eap_unexpected_wep_eapol_key(dev, apdev):
3964     """WPA2-Enterprise connection and unexpected WEP EAPOL-Key"""
3965     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3966     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
3967     bssid = apdev[0]['bssid']
3968     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
3969                 anonymous_identity="ttls", password="password",
3970                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP")
3971
3972     # Send unexpected WEP EAPOL-Key; this gets dropped
3973     res = dev[0].request("EAPOL_RX " + bssid + " 0203002c0100000000000000000000000000000000000000000000000000000000000000000000000000000000000000")
3974     if "OK" not in res:
3975         raise Exception("EAPOL_RX to wpa_supplicant failed")
3976
3977 def test_ap_wpa2_eap_in_bridge(dev, apdev):
3978     """WPA2-EAP and wpas interface in a bridge"""
3979     br_ifname='sta-br0'
3980     ifname='wlan5'
3981     try:
3982         _test_ap_wpa2_eap_in_bridge(dev, apdev)
3983     finally:
3984         subprocess.call(['ip', 'link', 'set', 'dev', br_ifname, 'down'])
3985         subprocess.call(['brctl', 'delif', br_ifname, ifname])
3986         subprocess.call(['brctl', 'delbr', br_ifname])
3987         subprocess.call(['iw', ifname, 'set', '4addr', 'off'])
3988
3989 def _test_ap_wpa2_eap_in_bridge(dev, apdev):
3990     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3991     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
3992
3993     br_ifname='sta-br0'
3994     ifname='wlan5'
3995     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
3996     subprocess.call(['brctl', 'addbr', br_ifname])
3997     subprocess.call(['brctl', 'setfd', br_ifname, '0'])
3998     subprocess.call(['ip', 'link', 'set', 'dev', br_ifname, 'up'])
3999     subprocess.call(['iw', ifname, 'set', '4addr', 'on'])
4000     subprocess.check_call(['brctl', 'addif', br_ifname, ifname])
4001     wpas.interface_add(ifname, br_ifname=br_ifname)
4002     wpas.dump_monitor()
4003
4004     id = eap_connect(wpas, apdev[0], "PAX", "pax.user@example.com",
4005                      password_hex="0123456789abcdef0123456789abcdef")
4006     wpas.dump_monitor()
4007     eap_reauth(wpas, "PAX")
4008     wpas.dump_monitor()
4009     # Try again as a regression test for packet socket workaround
4010     eap_reauth(wpas, "PAX")
4011     wpas.dump_monitor()
4012     wpas.request("DISCONNECT")
4013     wpas.wait_disconnected()
4014     wpas.dump_monitor()
4015     wpas.request("RECONNECT")
4016     wpas.wait_connected()
4017     wpas.dump_monitor()
4018
4019 def test_ap_wpa2_eap_session_ticket(dev, apdev):
4020     """WPA2-Enterprise connection using EAP-TTLS and TLS session ticket enabled"""
4021     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4022     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4023     key_mgmt = hapd.get_config()['key_mgmt']
4024     if key_mgmt.split(' ')[0] != "WPA-EAP":
4025         raise Exception("Unexpected GET_CONFIG(key_mgmt): " + key_mgmt)
4026     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
4027                 anonymous_identity="ttls", password="password",
4028                 ca_cert="auth_serv/ca.pem",
4029                 phase1="tls_disable_session_ticket=0", phase2="auth=PAP")
4030     eap_reauth(dev[0], "TTLS")
4031
4032 def test_ap_wpa2_eap_no_workaround(dev, apdev):
4033     """WPA2-Enterprise connection using EAP-TTLS and eap_workaround=0"""
4034     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4035     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4036     key_mgmt = hapd.get_config()['key_mgmt']
4037     if key_mgmt.split(' ')[0] != "WPA-EAP":
4038         raise Exception("Unexpected GET_CONFIG(key_mgmt): " + key_mgmt)
4039     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
4040                 anonymous_identity="ttls", password="password",
4041                 ca_cert="auth_serv/ca.pem", eap_workaround='0',
4042                 phase2="auth=PAP")
4043     eap_reauth(dev[0], "TTLS")
4044
4045 def test_ap_wpa2_eap_tls_check_crl(dev, apdev):
4046     """EAP-TLS and server checking CRL"""
4047     params = int_eap_server_params()
4048     params['check_crl'] = '1'
4049     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4050
4051     # check_crl=1 and no CRL available --> reject connection
4052     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4053                 client_cert="auth_serv/user.pem",
4054                 private_key="auth_serv/user.key", expect_failure=True)
4055     dev[0].request("REMOVE_NETWORK all")
4056
4057     hapd.disable()
4058     hapd.set("ca_cert", "auth_serv/ca-and-crl.pem")
4059     hapd.enable()
4060
4061     # check_crl=1 and valid CRL --> accept
4062     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4063                 client_cert="auth_serv/user.pem",
4064                 private_key="auth_serv/user.key")
4065     dev[0].request("REMOVE_NETWORK all")
4066
4067     hapd.disable()
4068     hapd.set("check_crl", "2")
4069     hapd.enable()
4070
4071     # check_crl=2 and valid CRL --> accept
4072     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4073                 client_cert="auth_serv/user.pem",
4074                 private_key="auth_serv/user.key")
4075     dev[0].request("REMOVE_NETWORK all")
4076
4077 def test_ap_wpa2_eap_tls_oom(dev, apdev):
4078     """EAP-TLS and OOM"""
4079     check_subject_match_support(dev[0])
4080     check_altsubject_match_support(dev[0])
4081     check_domain_match(dev[0])
4082     check_domain_match_full(dev[0])
4083
4084     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4085     hostapd.add_ap(apdev[0]['ifname'], params)
4086
4087     tests = [ (1, "tls_connection_set_subject_match"),
4088               (2, "tls_connection_set_subject_match"),
4089               (3, "tls_connection_set_subject_match"),
4090               (4, "tls_connection_set_subject_match") ]
4091     for count, func in tests:
4092         with alloc_fail(dev[0], count, func):
4093             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4094                            identity="tls user", ca_cert="auth_serv/ca.pem",
4095                            client_cert="auth_serv/user.pem",
4096                            private_key="auth_serv/user.key",
4097                            subject_match="/C=FI/O=w1.fi/CN=server.w1.fi",
4098                            altsubject_match="EMAIL:noone@example.com;DNS:server.w1.fi;URI:http://example.com/",
4099                            domain_suffix_match="server.w1.fi",
4100                            domain_match="server.w1.fi",
4101                            wait_connect=False, scan_freq="2412")
4102             # TLS parameter configuration error results in CTRL-REQ-PASSPHRASE
4103             ev = dev[0].wait_event(["CTRL-REQ-PASSPHRASE"], timeout=5)
4104             if ev is None:
4105                 raise Exception("No passphrase request")
4106             dev[0].request("REMOVE_NETWORK all")
4107             dev[0].wait_disconnected()
4108
4109 def test_ap_wpa2_eap_tls_macacl(dev, apdev):
4110     """WPA2-Enterprise connection using MAC ACL"""
4111     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4112     params["macaddr_acl"] = "2"
4113     hostapd.add_ap(apdev[0]['ifname'], params)
4114     eap_connect(dev[1], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4115                 client_cert="auth_serv/user.pem",
4116                 private_key="auth_serv/user.key")
4117
4118 def test_ap_wpa2_eap_oom(dev, apdev):
4119     """EAP server and OOM"""
4120     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4121     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4122     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
4123
4124     with alloc_fail(hapd, 1, "eapol_auth_alloc"):
4125         # The first attempt fails, but STA will send EAPOL-Start to retry and
4126         # that succeeds.
4127         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4128                        identity="tls user", ca_cert="auth_serv/ca.pem",
4129                        client_cert="auth_serv/user.pem",
4130                        private_key="auth_serv/user.key",
4131                        scan_freq="2412")
4132
4133 def check_tls_ver(dev, ap, phase1, expected):
4134     eap_connect(dev, ap, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4135                 client_cert="auth_serv/user.pem",
4136                 private_key="auth_serv/user.key",
4137                 phase1=phase1)
4138     ver = dev.get_status_field("eap_tls_version")
4139     if ver != expected:
4140         raise Exception("Unexpected TLS version (expected %s): %s" % (expected, ver))
4141
4142 def test_ap_wpa2_eap_tls_versions(dev, apdev):
4143     """EAP-TLS and TLS version configuration"""
4144     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4145     hostapd.add_ap(apdev[0]['ifname'], params)
4146
4147     tls = dev[0].request("GET tls_library")
4148     if tls.startswith("OpenSSL"):
4149         if "build=OpenSSL 1.0.2" in tls and "run=OpenSSL 1.0.2" in tls:
4150             check_tls_ver(dev[0], apdev[0],
4151                           "tls_disable_tlsv1_0=1 tls_disable_tlsv1_1=1",
4152                           "TLSv1.2")
4153     elif tls.startswith("internal"):
4154         check_tls_ver(dev[0], apdev[0],
4155                       "tls_disable_tlsv1_0=1 tls_disable_tlsv1_1=1", "TLSv1.2")
4156     check_tls_ver(dev[1], apdev[0],
4157                   "tls_disable_tlsv1_0=1 tls_disable_tlsv1_2=1", "TLSv1.1")
4158     check_tls_ver(dev[2], apdev[0],
4159                   "tls_disable_tlsv1_1=1 tls_disable_tlsv1_2=1", "TLSv1")
4160
4161 def test_rsn_ie_proto_eap_sta(dev, apdev):
4162     """RSN element protocol testing for EAP cases on STA side"""
4163     bssid = apdev[0]['bssid']
4164     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4165     # This is the RSN element used normally by hostapd
4166     params['own_ie_override'] = '30140100000fac040100000fac040100000fac010c00'
4167     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4168     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="GPSK",
4169                         identity="gpsk user",
4170                         password="abcdefghijklmnop0123456789abcdef",
4171                         scan_freq="2412")
4172
4173     tests = [ ('No RSN Capabilities field',
4174                '30120100000fac040100000fac040100000fac01'),
4175               ('No AKM Suite fields',
4176                '300c0100000fac040100000fac04'),
4177               ('No Pairwise Cipher Suite fields',
4178                '30060100000fac04'),
4179               ('No Group Data Cipher Suite field',
4180                '30020100') ]
4181     for txt,ie in tests:
4182         dev[0].request("DISCONNECT")
4183         dev[0].wait_disconnected()
4184         logger.info(txt)
4185         hapd.disable()
4186         hapd.set('own_ie_override', ie)
4187         hapd.enable()
4188         dev[0].request("BSS_FLUSH 0")
4189         dev[0].scan_for_bss(bssid, 2412, force_scan=True, only_new=True)
4190         dev[0].select_network(id, freq=2412)
4191         dev[0].wait_connected()
4192
4193     dev[0].request("DISCONNECT")
4194     dev[0].wait_disconnected()
4195     dev[0].flush_scan_cache()
4196
4197 def check_tls_session_resumption_capa(dev, hapd):
4198     tls = hapd.request("GET tls_library")
4199     if not tls.startswith("OpenSSL"):
4200         raise HwsimSkip("hostapd TLS library is not OpenSSL: " + tls)
4201
4202     tls = dev.request("GET tls_library")
4203     if not tls.startswith("OpenSSL"):
4204         raise HwsimSkip("Session resumption not supported with this TLS library: " + tls)
4205
4206 def test_eap_ttls_pap_session_resumption(dev, apdev):
4207     """EAP-TTLS/PAP session resumption"""
4208     params = int_eap_server_params()
4209     params['tls_session_lifetime'] = '60'
4210     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4211     check_tls_session_resumption_capa(dev[0], hapd)
4212     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
4213                 anonymous_identity="ttls", password="password",
4214                 ca_cert="auth_serv/ca.pem", eap_workaround='0',
4215                 phase2="auth=PAP")
4216     if dev[0].get_status_field("tls_session_reused") != '0':
4217         raise Exception("Unexpected session resumption on the first connection")
4218
4219     dev[0].request("REAUTHENTICATE")
4220     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4221     if ev is None:
4222         raise Exception("EAP success timed out")
4223     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4224     if ev is None:
4225         raise Exception("Key handshake with the AP timed out")
4226     if dev[0].get_status_field("tls_session_reused") != '1':
4227         raise Exception("Session resumption not used on the second connection")
4228
4229 def test_eap_ttls_chap_session_resumption(dev, apdev):
4230     """EAP-TTLS/CHAP session resumption"""
4231     params = int_eap_server_params()
4232     params['tls_session_lifetime'] = '60'
4233     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4234     check_tls_session_resumption_capa(dev[0], hapd)
4235     eap_connect(dev[0], apdev[0], "TTLS", "chap user",
4236                 anonymous_identity="ttls", password="password",
4237                 ca_cert="auth_serv/ca.der", phase2="auth=CHAP")
4238     if dev[0].get_status_field("tls_session_reused") != '0':
4239         raise Exception("Unexpected session resumption on the first connection")
4240
4241     dev[0].request("REAUTHENTICATE")
4242     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4243     if ev is None:
4244         raise Exception("EAP success timed out")
4245     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4246     if ev is None:
4247         raise Exception("Key handshake with the AP timed out")
4248     if dev[0].get_status_field("tls_session_reused") != '1':
4249         raise Exception("Session resumption not used on the second connection")
4250
4251 def test_eap_ttls_mschap_session_resumption(dev, apdev):
4252     """EAP-TTLS/MSCHAP session resumption"""
4253     check_domain_suffix_match(dev[0])
4254     params = int_eap_server_params()
4255     params['tls_session_lifetime'] = '60'
4256     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4257     check_tls_session_resumption_capa(dev[0], hapd)
4258     eap_connect(dev[0], apdev[0], "TTLS", "mschap user",
4259                 anonymous_identity="ttls", password="password",
4260                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
4261                 domain_suffix_match="server.w1.fi")
4262     if dev[0].get_status_field("tls_session_reused") != '0':
4263         raise Exception("Unexpected session resumption on the first connection")
4264
4265     dev[0].request("REAUTHENTICATE")
4266     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4267     if ev is None:
4268         raise Exception("EAP success timed out")
4269     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4270     if ev is None:
4271         raise Exception("Key handshake with the AP timed out")
4272     if dev[0].get_status_field("tls_session_reused") != '1':
4273         raise Exception("Session resumption not used on the second connection")
4274
4275 def test_eap_ttls_mschapv2_session_resumption(dev, apdev):
4276     """EAP-TTLS/MSCHAPv2 session resumption"""
4277     check_domain_suffix_match(dev[0])
4278     check_eap_capa(dev[0], "MSCHAPV2")
4279     params = int_eap_server_params()
4280     params['tls_session_lifetime'] = '60'
4281     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4282     check_tls_session_resumption_capa(dev[0], hapd)
4283     eap_connect(dev[0], apdev[0], "TTLS", "DOMAIN\mschapv2 user",
4284                 anonymous_identity="ttls", password="password",
4285                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
4286                 domain_suffix_match="server.w1.fi")
4287     if dev[0].get_status_field("tls_session_reused") != '0':
4288         raise Exception("Unexpected session resumption on the first connection")
4289
4290     dev[0].request("REAUTHENTICATE")
4291     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4292     if ev is None:
4293         raise Exception("EAP success timed out")
4294     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4295     if ev is None:
4296         raise Exception("Key handshake with the AP timed out")
4297     if dev[0].get_status_field("tls_session_reused") != '1':
4298         raise Exception("Session resumption not used on the second connection")
4299
4300 def test_eap_ttls_eap_gtc_session_resumption(dev, apdev):
4301     """EAP-TTLS/EAP-GTC session resumption"""
4302     params = int_eap_server_params()
4303     params['tls_session_lifetime'] = '60'
4304     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4305     check_tls_session_resumption_capa(dev[0], hapd)
4306     eap_connect(dev[0], apdev[0], "TTLS", "user",
4307                 anonymous_identity="ttls", password="password",
4308                 ca_cert="auth_serv/ca.pem", phase2="autheap=GTC")
4309     if dev[0].get_status_field("tls_session_reused") != '0':
4310         raise Exception("Unexpected session resumption on the first connection")
4311
4312     dev[0].request("REAUTHENTICATE")
4313     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4314     if ev is None:
4315         raise Exception("EAP success timed out")
4316     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4317     if ev is None:
4318         raise Exception("Key handshake with the AP timed out")
4319     if dev[0].get_status_field("tls_session_reused") != '1':
4320         raise Exception("Session resumption not used on the second connection")
4321
4322 def test_eap_ttls_no_session_resumption(dev, apdev):
4323     """EAP-TTLS session resumption disabled on server"""
4324     params = int_eap_server_params()
4325     params['tls_session_lifetime'] = '0'
4326     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4327     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
4328                 anonymous_identity="ttls", password="password",
4329                 ca_cert="auth_serv/ca.pem", eap_workaround='0',
4330                 phase2="auth=PAP")
4331     if dev[0].get_status_field("tls_session_reused") != '0':
4332         raise Exception("Unexpected session resumption on the first connection")
4333
4334     dev[0].request("REAUTHENTICATE")
4335     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4336     if ev is None:
4337         raise Exception("EAP success timed out")
4338     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4339     if ev is None:
4340         raise Exception("Key handshake with the AP timed out")
4341     if dev[0].get_status_field("tls_session_reused") != '0':
4342         raise Exception("Unexpected session resumption on the second connection")
4343
4344 def test_eap_peap_session_resumption(dev, apdev):
4345     """EAP-PEAP session resumption"""
4346     params = int_eap_server_params()
4347     params['tls_session_lifetime'] = '60'
4348     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4349     check_tls_session_resumption_capa(dev[0], hapd)
4350     eap_connect(dev[0], apdev[0], "PEAP", "user",
4351                 anonymous_identity="peap", password="password",
4352                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
4353     if dev[0].get_status_field("tls_session_reused") != '0':
4354         raise Exception("Unexpected session resumption on the first connection")
4355
4356     dev[0].request("REAUTHENTICATE")
4357     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4358     if ev is None:
4359         raise Exception("EAP success timed out")
4360     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4361     if ev is None:
4362         raise Exception("Key handshake with the AP timed out")
4363     if dev[0].get_status_field("tls_session_reused") != '1':
4364         raise Exception("Session resumption not used on the second connection")
4365
4366 def test_eap_peap_session_resumption_crypto_binding(dev, apdev):
4367     """EAP-PEAP session resumption with crypto binding"""
4368     params = int_eap_server_params()
4369     params['tls_session_lifetime'] = '60'
4370     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4371     check_tls_session_resumption_capa(dev[0], hapd)
4372     eap_connect(dev[0], apdev[0], "PEAP", "user",
4373                 anonymous_identity="peap", password="password",
4374                 phase1="peapver=0 crypto_binding=2",
4375                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
4376     if dev[0].get_status_field("tls_session_reused") != '0':
4377         raise Exception("Unexpected session resumption on the first connection")
4378
4379     dev[0].request("REAUTHENTICATE")
4380     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4381     if ev is None:
4382         raise Exception("EAP success timed out")
4383     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4384     if ev is None:
4385         raise Exception("Key handshake with the AP timed out")
4386     if dev[0].get_status_field("tls_session_reused") != '1':
4387         raise Exception("Session resumption not used on the second connection")
4388
4389 def test_eap_peap_no_session_resumption(dev, apdev):
4390     """EAP-PEAP session resumption disabled on server"""
4391     params = int_eap_server_params()
4392     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4393     eap_connect(dev[0], apdev[0], "PEAP", "user",
4394                 anonymous_identity="peap", password="password",
4395                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
4396     if dev[0].get_status_field("tls_session_reused") != '0':
4397         raise Exception("Unexpected session resumption on the first connection")
4398
4399     dev[0].request("REAUTHENTICATE")
4400     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4401     if ev is None:
4402         raise Exception("EAP success timed out")
4403     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4404     if ev is None:
4405         raise Exception("Key handshake with the AP timed out")
4406     if dev[0].get_status_field("tls_session_reused") != '0':
4407         raise Exception("Unexpected session resumption on the second connection")
4408
4409 def test_eap_tls_session_resumption(dev, apdev):
4410     """EAP-TLS session resumption"""
4411     params = int_eap_server_params()
4412     params['tls_session_lifetime'] = '60'
4413     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4414     check_tls_session_resumption_capa(dev[0], hapd)
4415     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4416                 client_cert="auth_serv/user.pem",
4417                 private_key="auth_serv/user.key")
4418     if dev[0].get_status_field("tls_session_reused") != '0':
4419         raise Exception("Unexpected session resumption on the first connection")
4420
4421     dev[0].request("REAUTHENTICATE")
4422     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4423     if ev is None:
4424         raise Exception("EAP success timed out")
4425     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4426     if ev is None:
4427         raise Exception("Key handshake with the AP timed out")
4428     if dev[0].get_status_field("tls_session_reused") != '1':
4429         raise Exception("Session resumption not used on the second connection")
4430
4431     dev[0].request("REAUTHENTICATE")
4432     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4433     if ev is None:
4434         raise Exception("EAP success timed out")
4435     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4436     if ev is None:
4437         raise Exception("Key handshake with the AP timed out")
4438     if dev[0].get_status_field("tls_session_reused") != '1':
4439         raise Exception("Session resumption not used on the third connection")
4440
4441 def test_eap_tls_session_resumption_expiration(dev, apdev):
4442     """EAP-TLS session resumption"""
4443     params = int_eap_server_params()
4444     params['tls_session_lifetime'] = '1'
4445     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4446     check_tls_session_resumption_capa(dev[0], hapd)
4447     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4448                 client_cert="auth_serv/user.pem",
4449                 private_key="auth_serv/user.key")
4450     if dev[0].get_status_field("tls_session_reused") != '0':
4451         raise Exception("Unexpected session resumption on the first connection")
4452
4453     # Allow multiple attempts since OpenSSL may not expire the cached entry
4454     # immediately.
4455     for i in range(10):
4456         time.sleep(1.2)
4457
4458         dev[0].request("REAUTHENTICATE")
4459         ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4460         if ev is None:
4461             raise Exception("EAP success timed out")
4462         ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4463         if ev is None:
4464             raise Exception("Key handshake with the AP timed out")
4465         if dev[0].get_status_field("tls_session_reused") == '0':
4466             break
4467     if dev[0].get_status_field("tls_session_reused") != '0':
4468         raise Exception("Session resumption used after lifetime expiration")
4469
4470 def test_eap_tls_no_session_resumption(dev, apdev):
4471     """EAP-TLS session resumption disabled on server"""
4472     params = int_eap_server_params()
4473     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4474     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4475                 client_cert="auth_serv/user.pem",
4476                 private_key="auth_serv/user.key")
4477     if dev[0].get_status_field("tls_session_reused") != '0':
4478         raise Exception("Unexpected session resumption on the first connection")
4479
4480     dev[0].request("REAUTHENTICATE")
4481     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4482     if ev is None:
4483         raise Exception("EAP success timed out")
4484     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4485     if ev is None:
4486         raise Exception("Key handshake with the AP timed out")
4487     if dev[0].get_status_field("tls_session_reused") != '0':
4488         raise Exception("Unexpected session resumption on the second connection")
4489
4490 def test_eap_tls_session_resumption_radius(dev, apdev):
4491     """EAP-TLS session resumption (RADIUS)"""
4492     params = { "ssid": "as", "beacon_int": "2000",
4493                "radius_server_clients": "auth_serv/radius_clients.conf",
4494                "radius_server_auth_port": '18128',
4495                "eap_server": "1",
4496                "eap_user_file": "auth_serv/eap_user.conf",
4497                "ca_cert": "auth_serv/ca.pem",
4498                "server_cert": "auth_serv/server.pem",
4499                "private_key": "auth_serv/server.key",
4500                "tls_session_lifetime": "60" }
4501     authsrv = hostapd.add_ap(apdev[1]['ifname'], params)
4502     check_tls_session_resumption_capa(dev[0], authsrv)
4503
4504     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4505     params['auth_server_port'] = "18128"
4506     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4507     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4508                 client_cert="auth_serv/user.pem",
4509                 private_key="auth_serv/user.key")
4510     if dev[0].get_status_field("tls_session_reused") != '0':
4511         raise Exception("Unexpected session resumption on the first connection")
4512
4513     dev[0].request("REAUTHENTICATE")
4514     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4515     if ev is None:
4516         raise Exception("EAP success timed out")
4517     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4518     if ev is None:
4519         raise Exception("Key handshake with the AP timed out")
4520     if dev[0].get_status_field("tls_session_reused") != '1':
4521         raise Exception("Session resumption not used on the second connection")
4522
4523 def test_eap_tls_no_session_resumption_radius(dev, apdev):
4524     """EAP-TLS session resumption disabled (RADIUS)"""
4525     params = { "ssid": "as", "beacon_int": "2000",
4526                "radius_server_clients": "auth_serv/radius_clients.conf",
4527                "radius_server_auth_port": '18128',
4528                "eap_server": "1",
4529                "eap_user_file": "auth_serv/eap_user.conf",
4530                "ca_cert": "auth_serv/ca.pem",
4531                "server_cert": "auth_serv/server.pem",
4532                "private_key": "auth_serv/server.key",
4533                "tls_session_lifetime": "0" }
4534     hostapd.add_ap(apdev[1]['ifname'], params)
4535
4536     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4537     params['auth_server_port'] = "18128"
4538     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4539     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4540                 client_cert="auth_serv/user.pem",
4541                 private_key="auth_serv/user.key")
4542     if dev[0].get_status_field("tls_session_reused") != '0':
4543         raise Exception("Unexpected session resumption on the first connection")
4544
4545     dev[0].request("REAUTHENTICATE")
4546     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4547     if ev is None:
4548         raise Exception("EAP success timed out")
4549     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4550     if ev is None:
4551         raise Exception("Key handshake with the AP timed out")
4552     if dev[0].get_status_field("tls_session_reused") != '0':
4553         raise Exception("Unexpected session resumption on the second connection")
4554
4555 def test_eap_mschapv2_errors(dev, apdev):
4556     """EAP-MSCHAPv2 error cases"""
4557     check_eap_capa(dev[0], "MSCHAPV2")
4558     check_eap_capa(dev[0], "FAST")
4559
4560     params = hostapd.wpa2_eap_params(ssid="test-wpa-eap")
4561     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4562     dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="MSCHAPV2",
4563                    identity="phase1-user", password="password",
4564                    scan_freq="2412")
4565     dev[0].request("REMOVE_NETWORK all")
4566     dev[0].wait_disconnected()
4567
4568     tests = [ (1, "hash_nt_password_hash;mschapv2_derive_response"),
4569               (1, "nt_password_hash;mschapv2_derive_response"),
4570               (1, "nt_password_hash;=mschapv2_derive_response"),
4571               (1, "generate_nt_response;mschapv2_derive_response"),
4572               (1, "generate_authenticator_response;mschapv2_derive_response"),
4573               (1, "nt_password_hash;=mschapv2_derive_response"),
4574               (1, "get_master_key;mschapv2_derive_response"),
4575               (1, "os_get_random;eap_mschapv2_challenge_reply") ]
4576     for count, func in tests:
4577         with fail_test(dev[0], count, func):
4578             dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="MSCHAPV2",
4579                            identity="phase1-user", password="password",
4580                            wait_connect=False, scan_freq="2412")
4581             wait_fail_trigger(dev[0], "GET_FAIL")
4582             dev[0].request("REMOVE_NETWORK all")
4583             dev[0].wait_disconnected()
4584
4585     tests = [ (1, "hash_nt_password_hash;mschapv2_derive_response"),
4586               (1, "hash_nt_password_hash;=mschapv2_derive_response"),
4587               (1, "generate_nt_response_pwhash;mschapv2_derive_response"),
4588               (1, "generate_authenticator_response_pwhash;mschapv2_derive_response") ]
4589     for count, func in tests:
4590         with fail_test(dev[0], count, func):
4591             dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="MSCHAPV2",
4592                            identity="phase1-user",
4593                            password_hex="hash:8846f7eaee8fb117ad06bdd830b7586c",
4594                            wait_connect=False, scan_freq="2412")
4595             wait_fail_trigger(dev[0], "GET_FAIL")
4596             dev[0].request("REMOVE_NETWORK all")
4597             dev[0].wait_disconnected()
4598
4599     tests = [ (1, "eap_mschapv2_init"),
4600               (1, "eap_msg_alloc;eap_mschapv2_challenge_reply"),
4601               (1, "eap_msg_alloc;eap_mschapv2_success"),
4602               (1, "eap_mschapv2_getKey") ]
4603     for count, func in tests:
4604         with alloc_fail(dev[0], count, func):
4605             dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="MSCHAPV2",
4606                            identity="phase1-user", password="password",
4607                            wait_connect=False, scan_freq="2412")
4608             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4609             dev[0].request("REMOVE_NETWORK all")
4610             dev[0].wait_disconnected()
4611
4612     tests = [ (1, "eap_msg_alloc;eap_mschapv2_failure") ]
4613     for count, func in tests:
4614         with alloc_fail(dev[0], count, func):
4615             dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="MSCHAPV2",
4616                            identity="phase1-user", password="wrong password",
4617                            wait_connect=False, scan_freq="2412")
4618             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4619             dev[0].request("REMOVE_NETWORK all")
4620             dev[0].wait_disconnected()
4621
4622     tests = [ (2, "eap_mschapv2_init"),
4623               (3, "eap_mschapv2_init") ]
4624     for count, func in tests:
4625         with alloc_fail(dev[0], count, func):
4626             dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="FAST",
4627                            anonymous_identity="FAST", identity="user",
4628                            password="password",
4629                            ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
4630                            phase1="fast_provisioning=1",
4631                            pac_file="blob://fast_pac",
4632                            wait_connect=False, scan_freq="2412")
4633             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4634             dev[0].request("REMOVE_NETWORK all")
4635             dev[0].wait_disconnected()
4636
4637 def test_eap_gpsk_errors(dev, apdev):
4638     """EAP-GPSK error cases"""
4639     params = hostapd.wpa2_eap_params(ssid="test-wpa-eap")
4640     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4641     dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="GPSK",
4642                    identity="gpsk user",
4643                    password="abcdefghijklmnop0123456789abcdef",
4644                    scan_freq="2412")
4645     dev[0].request("REMOVE_NETWORK all")
4646     dev[0].wait_disconnected()
4647
4648     tests = [ (1, "os_get_random;eap_gpsk_send_gpsk_2", None),
4649               (1, "eap_gpsk_derive_session_id;eap_gpsk_send_gpsk_2",
4650                "cipher=1"),
4651               (1, "eap_gpsk_derive_session_id;eap_gpsk_send_gpsk_2",
4652                "cipher=2"),
4653               (1, "eap_gpsk_derive_keys_helper", None),
4654               (2, "eap_gpsk_derive_keys_helper", None),
4655               (1, "eap_gpsk_compute_mic_aes;eap_gpsk_compute_mic;eap_gpsk_send_gpsk_2",
4656                "cipher=1"),
4657               (1, "hmac_sha256;eap_gpsk_compute_mic;eap_gpsk_send_gpsk_2",
4658                "cipher=2"),
4659               (1, "eap_gpsk_compute_mic;eap_gpsk_validate_gpsk_3_mic", None),
4660               (1, "eap_gpsk_compute_mic;eap_gpsk_send_gpsk_4", None),
4661               (1, "eap_gpsk_derive_mid_helper", None) ]
4662     for count, func, phase1 in tests:
4663         with fail_test(dev[0], count, func):
4664             dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="GPSK",
4665                            identity="gpsk user",
4666                            password="abcdefghijklmnop0123456789abcdef",
4667                            phase1=phase1,
4668                            wait_connect=False, scan_freq="2412")
4669             wait_fail_trigger(dev[0], "GET_FAIL")
4670             dev[0].request("REMOVE_NETWORK all")
4671             dev[0].wait_disconnected()
4672
4673     tests = [ (1, "eap_gpsk_init"),
4674               (2, "eap_gpsk_init"),
4675               (3, "eap_gpsk_init"),
4676               (1, "eap_gpsk_process_id_server"),
4677               (1, "eap_msg_alloc;eap_gpsk_send_gpsk_2"),
4678               (1, "eap_gpsk_derive_session_id;eap_gpsk_send_gpsk_2"),
4679               (1, "eap_gpsk_derive_mid_helper;eap_gpsk_derive_session_id;eap_gpsk_send_gpsk_2"),
4680               (1, "eap_gpsk_derive_keys"),
4681               (1, "eap_gpsk_derive_keys_helper"),
4682               (1, "eap_msg_alloc;eap_gpsk_send_gpsk_4"),
4683               (1, "eap_gpsk_getKey"),
4684               (1, "eap_gpsk_get_emsk"),
4685               (1, "eap_gpsk_get_session_id") ]
4686     for count, func in tests:
4687         with alloc_fail(dev[0], count, func):
4688             dev[0].request("ERP_FLUSH")
4689             dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="GPSK",
4690                            identity="gpsk user", erp="1",
4691                            password="abcdefghijklmnop0123456789abcdef",
4692                            wait_connect=False, scan_freq="2412")
4693             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4694             dev[0].request("REMOVE_NETWORK all")
4695             dev[0].wait_disconnected()
4696
4697 def test_ap_wpa2_eap_sim_db(dev, apdev, params):
4698     """EAP-SIM DB error cases"""
4699     sockpath = '/tmp/hlr_auc_gw.sock-test'
4700     try:
4701         os.remove(sockpath)
4702     except:
4703         pass
4704     hparams = int_eap_server_params()
4705     hparams['eap_sim_db'] = 'unix:' + sockpath
4706     hapd = hostapd.add_ap(apdev[0]['ifname'], hparams)
4707
4708     # Initial test with hlr_auc_gw socket not available
4709     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
4710                         eap="SIM", identity="1232010000000000",
4711                         password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
4712                         scan_freq="2412", wait_connect=False)
4713     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4714     if ev is None:
4715         raise Exception("EAP-Failure not reported")
4716     dev[0].wait_disconnected()
4717     dev[0].request("DISCONNECT")
4718
4719     # Test with invalid responses and response timeout
4720
4721     class test_handler(SocketServer.DatagramRequestHandler):
4722         def handle(self):
4723             data = self.request[0].strip()
4724             socket = self.request[1]
4725             logger.debug("Received hlr_auc_gw request: " + data)
4726             # EAP-SIM DB: Failed to parse response string
4727             socket.sendto("FOO", self.client_address)
4728             # EAP-SIM DB: Failed to parse response string
4729             socket.sendto("FOO 1", self.client_address)
4730             # EAP-SIM DB: Unknown external response
4731             socket.sendto("FOO 1 2", self.client_address)
4732             logger.info("No proper response - wait for pending eap_sim_db request timeout")
4733
4734     server = SocketServer.UnixDatagramServer(sockpath, test_handler)
4735     server.timeout = 1
4736
4737     dev[0].select_network(id)
4738     server.handle_request()
4739     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4740     if ev is None:
4741         raise Exception("EAP-Failure not reported")
4742     dev[0].wait_disconnected()
4743     dev[0].request("DISCONNECT")
4744
4745     # Test with a valid response
4746
4747     class test_handler2(SocketServer.DatagramRequestHandler):
4748         def handle(self):
4749             data = self.request[0].strip()
4750             socket = self.request[1]
4751             logger.debug("Received hlr_auc_gw request: " + data)
4752             fname = os.path.join(params['logdir'],
4753                                  'hlr_auc_gw.milenage_db')
4754             cmd = subprocess.Popen(['../../hostapd/hlr_auc_gw',
4755                                     '-m', fname, data],
4756                                    stdout=subprocess.PIPE)
4757             res = cmd.stdout.read().strip()
4758             cmd.stdout.close()
4759             logger.debug("hlr_auc_gw response: " + res)
4760             socket.sendto(res, self.client_address)
4761
4762     server.RequestHandlerClass = test_handler2
4763
4764     dev[0].select_network(id)
4765     server.handle_request()
4766     dev[0].wait_connected()
4767     dev[0].request("DISCONNECT")
4768     dev[0].wait_disconnected()
4769
4770 def test_eap_tls_sha512(dev, apdev, params):
4771     """EAP-TLS with SHA512 signature"""
4772     params = int_eap_server_params()
4773     params["ca_cert"] = "auth_serv/sha512-ca.pem"
4774     params["server_cert"] = "auth_serv/sha512-server.pem"
4775     params["private_key"] = "auth_serv/sha512-server.key"
4776     hostapd.add_ap(apdev[0]['ifname'], params)
4777
4778     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4779                    identity="tls user sha512",
4780                    ca_cert="auth_serv/sha512-ca.pem",
4781                    client_cert="auth_serv/sha512-user.pem",
4782                    private_key="auth_serv/sha512-user.key",
4783                    scan_freq="2412")
4784     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4785                    identity="tls user sha512",
4786                    ca_cert="auth_serv/sha512-ca.pem",
4787                    client_cert="auth_serv/sha384-user.pem",
4788                    private_key="auth_serv/sha384-user.key",
4789                    scan_freq="2412")
4790
4791 def test_eap_tls_sha384(dev, apdev, params):
4792     """EAP-TLS with SHA384 signature"""
4793     params = int_eap_server_params()
4794     params["ca_cert"] = "auth_serv/sha512-ca.pem"
4795     params["server_cert"] = "auth_serv/sha384-server.pem"
4796     params["private_key"] = "auth_serv/sha384-server.key"
4797     hostapd.add_ap(apdev[0]['ifname'], params)
4798
4799     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4800                    identity="tls user sha512",
4801                    ca_cert="auth_serv/sha512-ca.pem",
4802                    client_cert="auth_serv/sha512-user.pem",
4803                    private_key="auth_serv/sha512-user.key",
4804                    scan_freq="2412")
4805     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4806                    identity="tls user sha512",
4807                    ca_cert="auth_serv/sha512-ca.pem",
4808                    client_cert="auth_serv/sha384-user.pem",
4809                    private_key="auth_serv/sha384-user.key",
4810                    scan_freq="2412")
4811
4812 def test_ap_wpa2_eap_assoc_rsn(dev, apdev):
4813     """WPA2-Enterprise AP and association request RSN IE differences"""
4814     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4815     hostapd.add_ap(apdev[0]['ifname'], params)
4816
4817     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap-11w")
4818     params["ieee80211w"] = "2"
4819     hostapd.add_ap(apdev[1]['ifname'], params)
4820
4821     # Success cases with optional RSN IE fields removed one by one
4822     tests = [ ("Normal wpa_supplicant assoc req RSN IE",
4823                "30140100000fac040100000fac040100000fac010000"),
4824               ("Extra PMKIDCount field in RSN IE",
4825                "30160100000fac040100000fac040100000fac0100000000"),
4826               ("Extra Group Management Cipher Suite in RSN IE",
4827                "301a0100000fac040100000fac040100000fac0100000000000fac06"),
4828               ("Extra undefined extension field in RSN IE",
4829                "301c0100000fac040100000fac040100000fac0100000000000fac061122"),
4830               ("RSN IE without RSN Capabilities",
4831                "30120100000fac040100000fac040100000fac01"),
4832               ("RSN IE without AKM", "300c0100000fac040100000fac04"),
4833               ("RSN IE without pairwise", "30060100000fac04"),
4834               ("RSN IE without group", "30020100") ]
4835     for title, ie in tests:
4836         logger.info(title)
4837         set_test_assoc_ie(dev[0], ie)
4838         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="GPSK",
4839                        identity="gpsk user",
4840                        password="abcdefghijklmnop0123456789abcdef",
4841                        scan_freq="2412")
4842         dev[0].request("REMOVE_NETWORK all")
4843         dev[0].wait_disconnected()
4844
4845     tests = [ ("Normal wpa_supplicant assoc req RSN IE",
4846                "30140100000fac040100000fac040100000fac01cc00"),
4847               ("Group management cipher included in assoc req RSN IE",
4848                "301a0100000fac040100000fac040100000fac01cc000000000fac06") ]
4849     for title, ie in tests:
4850         logger.info(title)
4851         set_test_assoc_ie(dev[0], ie)
4852         dev[0].connect("test-wpa2-eap-11w", key_mgmt="WPA-EAP", ieee80211w="1",
4853                        eap="GPSK", identity="gpsk user",
4854                        password="abcdefghijklmnop0123456789abcdef",
4855                        scan_freq="2412")
4856         dev[0].request("REMOVE_NETWORK all")
4857         dev[0].wait_disconnected()
4858
4859     tests = [ ("Invalid group cipher", "30060100000fac02", 41),
4860               ("Invalid pairwise cipher", "300c0100000fac040100000fac02", 42) ]
4861     for title, ie, status in tests:
4862         logger.info(title)
4863         set_test_assoc_ie(dev[0], ie)
4864         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="GPSK",
4865                        identity="gpsk user",
4866                        password="abcdefghijklmnop0123456789abcdef",
4867                        scan_freq="2412", wait_connect=False)
4868         ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"])
4869         if ev is None:
4870             raise Exception("Association rejection not reported")
4871         if "status_code=" + str(status) not in ev:
4872             raise Exception("Unexpected status code: " + ev)
4873         dev[0].request("REMOVE_NETWORK all")
4874         dev[0].dump_monitor()
4875
4876     tests = [ ("Management frame protection not enabled",
4877                "30140100000fac040100000fac040100000fac010000", 31),
4878               ("Unsupported management group cipher",
4879                "301a0100000fac040100000fac040100000fac01cc000000000fac0b", 31) ]
4880     for title, ie, status in tests:
4881         logger.info(title)
4882         set_test_assoc_ie(dev[0], ie)
4883         dev[0].connect("test-wpa2-eap-11w", key_mgmt="WPA-EAP", ieee80211w="1",
4884                        eap="GPSK", identity="gpsk user",
4885                        password="abcdefghijklmnop0123456789abcdef",
4886                        scan_freq="2412", wait_connect=False)
4887         ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"])
4888         if ev is None:
4889             raise Exception("Association rejection not reported")
4890         if "status_code=" + str(status) not in ev:
4891             raise Exception("Unexpected status code: " + ev)
4892         dev[0].request("REMOVE_NETWORK all")
4893         dev[0].dump_monitor()
4894
4895 def test_eap_tls_ext_cert_check(dev, apdev):
4896     """EAP-TLS and external server certification validation"""
4897     # With internal server certificate chain validation
4898     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4899                         identity="tls user",
4900                         ca_cert="auth_serv/ca.pem",
4901                         client_cert="auth_serv/user.pem",
4902                         private_key="auth_serv/user.key",
4903                         phase1="tls_ext_cert_check=1", scan_freq="2412",
4904                         only_add_network=True)
4905     run_ext_cert_check(dev, apdev, id)
4906
4907 def test_eap_ttls_ext_cert_check(dev, apdev):
4908     """EAP-TTLS and external server certification validation"""
4909     # Without internal server certificate chain validation
4910     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
4911                         identity="pap user", anonymous_identity="ttls",
4912                         password="password", phase2="auth=PAP",
4913                         phase1="tls_ext_cert_check=1", scan_freq="2412",
4914                         only_add_network=True)
4915     run_ext_cert_check(dev, apdev, id)
4916
4917 def test_eap_peap_ext_cert_check(dev, apdev):
4918     """EAP-PEAP and external server certification validation"""
4919     # With internal server certificate chain validation
4920     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PEAP",
4921                         identity="user", anonymous_identity="peap",
4922                         ca_cert="auth_serv/ca.pem",
4923                         password="password", phase2="auth=MSCHAPV2",
4924                         phase1="tls_ext_cert_check=1", scan_freq="2412",
4925                         only_add_network=True)
4926     run_ext_cert_check(dev, apdev, id)
4927
4928 def test_eap_fast_ext_cert_check(dev, apdev):
4929     """EAP-FAST and external server certification validation"""
4930     check_eap_capa(dev[0], "FAST")
4931     # With internal server certificate chain validation
4932     dev[0].request("SET blob fast_pac_auth_ext ")
4933     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
4934                         identity="user", anonymous_identity="FAST",
4935                         ca_cert="auth_serv/ca.pem",
4936                         password="password", phase2="auth=GTC",
4937                         phase1="tls_ext_cert_check=1 fast_provisioning=2",
4938                         pac_file="blob://fast_pac_auth_ext",
4939                         scan_freq="2412",
4940                         only_add_network=True)
4941     run_ext_cert_check(dev, apdev, id)
4942
4943 def run_ext_cert_check(dev, apdev, net_id):
4944     check_ext_cert_check_support(dev[0])
4945     if not openssl_imported:
4946         raise HwsimSkip("OpenSSL python method not available")
4947
4948     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4949     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4950
4951     dev[0].select_network(net_id)
4952     certs = {}
4953     while True:
4954         ev = dev[0].wait_event(["CTRL-EVENT-EAP-PEER-CERT",
4955                                 "CTRL-REQ-EXT_CERT_CHECK",
4956                                 "CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4957         if ev is None:
4958             raise Exception("No peer server certificate event seen")
4959         if "CTRL-EVENT-EAP-PEER-CERT" in ev:
4960             depth = None
4961             cert = None
4962             vals = ev.split(' ')
4963             for v in vals:
4964                 if v.startswith("depth="):
4965                     depth = int(v.split('=')[1])
4966                 elif v.startswith("cert="):
4967                     cert = v.split('=')[1]
4968             if depth is not None and cert:
4969                 certs[depth] = binascii.unhexlify(cert)
4970         elif "CTRL-EVENT-EAP-SUCCESS" in ev:
4971             raise Exception("Unexpected EAP-Success")
4972         elif "CTRL-REQ-EXT_CERT_CHECK" in ev:
4973             id = ev.split(':')[0].split('-')[-1]
4974             break
4975     if 0 not in certs:
4976         raise Exception("Server certificate not received")
4977     if 1 not in certs:
4978         raise Exception("Server certificate issuer not received")
4979
4980     cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1,
4981                                            certs[0])
4982     cn = cert.get_subject().commonName
4983     logger.info("Server certificate CN=" + cn)
4984
4985     issuer = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1,
4986                                              certs[1])
4987     icn = issuer.get_subject().commonName
4988     logger.info("Issuer certificate CN=" + icn)
4989
4990     if cn != "server.w1.fi":
4991         raise Exception("Unexpected server certificate CN: " + cn)
4992     if icn != "Root CA":
4993         raise Exception("Unexpected server certificate issuer CN: " + icn)
4994
4995     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=0.1)
4996     if ev:
4997         raise Exception("Unexpected EAP-Success before external check result indication")
4998
4999     dev[0].request("CTRL-RSP-EXT_CERT_CHECK-" + id + ":good")
5000     dev[0].wait_connected()
5001
5002     dev[0].request("DISCONNECT")
5003     dev[0].wait_disconnected()
5004     if "FAIL" in dev[0].request("PMKSA_FLUSH"):
5005         raise Exception("PMKSA_FLUSH failed")
5006     dev[0].request("SET blob fast_pac_auth_ext ")
5007     dev[0].request("RECONNECT")
5008
5009     ev = dev[0].wait_event(["CTRL-REQ-EXT_CERT_CHECK"], timeout=10)
5010     if ev is None:
5011         raise Exception("No peer server certificate event seen (2)")
5012     id = ev.split(':')[0].split('-')[-1]
5013     dev[0].request("CTRL-RSP-EXT_CERT_CHECK-" + id + ":bad")
5014     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
5015     if ev is None:
5016         raise Exception("EAP-Failure not reported")
5017     dev[0].request("REMOVE_NETWORK all")
5018     dev[0].wait_disconnected()