tests: WPA2-Enterprise connection using EAP vendor test (OOM)
[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_vendor_test_oom(dev, apdev):
2540     """WPA2-Enterprise connection using EAP vendor test (OOM)"""
2541     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2542     hostapd.add_ap(apdev[0]['ifname'], params)
2543
2544     tests = [ "eap_vendor_test_init",
2545               "eap_msg_alloc;eap_vendor_test_process",
2546               "eap_vendor_test_getKey" ]
2547     for func in tests:
2548         with alloc_fail(dev[0], 1, func):
2549             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP",
2550                            scan_freq="2412",
2551                            eap="VENDOR-TEST", identity="vendor-test",
2552                            wait_connect=False)
2553             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
2554             dev[0].request("REMOVE_NETWORK all")
2555             dev[0].wait_disconnected()
2556
2557 def test_ap_wpa2_eap_fast_mschapv2_unauth_prov(dev, apdev):
2558     """WPA2-Enterprise connection using EAP-FAST/MSCHAPv2 and unauthenticated provisioning"""
2559     check_eap_capa(dev[0], "FAST")
2560     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2561     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
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="blob://fast_pac")
2566     hwsim_utils.test_connectivity(dev[0], hapd)
2567     res = eap_reauth(dev[0], "FAST")
2568     if res['tls_session_reused'] != '1':
2569         raise Exception("EAP-FAST could not use PAC session ticket")
2570
2571 def test_ap_wpa2_eap_fast_pac_file(dev, apdev, params):
2572     """WPA2-Enterprise connection using EAP-FAST/MSCHAPv2 and PAC file"""
2573     check_eap_capa(dev[0], "FAST")
2574     pac_file = os.path.join(params['logdir'], "fast.pac")
2575     pac_file2 = os.path.join(params['logdir'], "fast-bin.pac")
2576     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2577     hostapd.add_ap(apdev[0]['ifname'], params)
2578
2579     try:
2580         eap_connect(dev[0], apdev[0], "FAST", "user",
2581                     anonymous_identity="FAST", password="password",
2582                     ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2583                     phase1="fast_provisioning=1", pac_file=pac_file)
2584         with open(pac_file, "r") as f:
2585             data = f.read()
2586             if "wpa_supplicant EAP-FAST PAC file - version 1" not in data:
2587                 raise Exception("PAC file header missing")
2588             if "PAC-Key=" not in data:
2589                 raise Exception("PAC-Key missing from PAC file")
2590         dev[0].request("REMOVE_NETWORK all")
2591         eap_connect(dev[0], apdev[0], "FAST", "user",
2592                     anonymous_identity="FAST", password="password",
2593                     ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2594                     pac_file=pac_file)
2595
2596         eap_connect(dev[1], apdev[0], "FAST", "user",
2597                     anonymous_identity="FAST", password="password",
2598                     ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2599                     phase1="fast_provisioning=1 fast_pac_format=binary",
2600                     pac_file=pac_file2)
2601         dev[1].request("REMOVE_NETWORK all")
2602         eap_connect(dev[1], apdev[0], "FAST", "user",
2603                     anonymous_identity="FAST", password="password",
2604                     ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2605                     phase1="fast_pac_format=binary",
2606                     pac_file=pac_file2)
2607     finally:
2608         try:
2609             os.remove(pac_file)
2610         except:
2611             pass
2612         try:
2613             os.remove(pac_file2)
2614         except:
2615             pass
2616
2617 def test_ap_wpa2_eap_fast_binary_pac(dev, apdev):
2618     """WPA2-Enterprise connection using EAP-FAST and binary PAC format"""
2619     check_eap_capa(dev[0], "FAST")
2620     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2621     hostapd.add_ap(apdev[0]['ifname'], params)
2622     eap_connect(dev[0], apdev[0], "FAST", "user",
2623                 anonymous_identity="FAST", password="password",
2624                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2625                 phase1="fast_provisioning=1 fast_max_pac_list_len=1 fast_pac_format=binary",
2626                 pac_file="blob://fast_pac_bin")
2627     res = eap_reauth(dev[0], "FAST")
2628     if res['tls_session_reused'] != '1':
2629         raise Exception("EAP-FAST could not use PAC session ticket")
2630
2631 def test_ap_wpa2_eap_fast_missing_pac_config(dev, apdev):
2632     """WPA2-Enterprise connection using EAP-FAST and missing PAC config"""
2633     check_eap_capa(dev[0], "FAST")
2634     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2635     hostapd.add_ap(apdev[0]['ifname'], params)
2636
2637     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
2638                    identity="user", anonymous_identity="FAST",
2639                    password="password",
2640                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2641                    pac_file="blob://fast_pac_not_in_use",
2642                    wait_connect=False, scan_freq="2412")
2643     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
2644     if ev is None:
2645         raise Exception("Timeout on EAP failure report")
2646     dev[0].request("REMOVE_NETWORK all")
2647
2648     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
2649                    identity="user", anonymous_identity="FAST",
2650                    password="password",
2651                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2652                    wait_connect=False, scan_freq="2412")
2653     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
2654     if ev is None:
2655         raise Exception("Timeout on EAP failure report")
2656
2657 def test_ap_wpa2_eap_fast_gtc_auth_prov(dev, apdev):
2658     """WPA2-Enterprise connection using EAP-FAST/GTC and authenticated provisioning"""
2659     check_eap_capa(dev[0], "FAST")
2660     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2661     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
2662     eap_connect(dev[0], apdev[0], "FAST", "user",
2663                 anonymous_identity="FAST", password="password",
2664                 ca_cert="auth_serv/ca.pem", phase2="auth=GTC",
2665                 phase1="fast_provisioning=2", pac_file="blob://fast_pac_auth")
2666     hwsim_utils.test_connectivity(dev[0], hapd)
2667     res = eap_reauth(dev[0], "FAST")
2668     if res['tls_session_reused'] != '1':
2669         raise Exception("EAP-FAST could not use PAC session ticket")
2670
2671 def test_ap_wpa2_eap_fast_gtc_identity_change(dev, apdev):
2672     """WPA2-Enterprise connection using EAP-FAST/GTC and identity changing"""
2673     check_eap_capa(dev[0], "FAST")
2674     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2675     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
2676     id = eap_connect(dev[0], apdev[0], "FAST", "user",
2677                      anonymous_identity="FAST", password="password",
2678                      ca_cert="auth_serv/ca.pem", phase2="auth=GTC",
2679                      phase1="fast_provisioning=2",
2680                      pac_file="blob://fast_pac_auth")
2681     dev[0].set_network_quoted(id, "identity", "user2")
2682     dev[0].wait_disconnected()
2683     ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=15)
2684     if ev is None:
2685         raise Exception("EAP-FAST not started")
2686     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
2687     if ev is None:
2688         raise Exception("EAP failure not reported")
2689     dev[0].wait_disconnected()
2690
2691 def test_ap_wpa2_eap_fast_prf_oom(dev, apdev):
2692     """WPA2-Enterprise connection using EAP-FAST and OOM in PRF"""
2693     check_eap_capa(dev[0], "FAST")
2694     tls = dev[0].request("GET tls_library")
2695     if tls.startswith("OpenSSL"):
2696         func = "openssl_tls_prf"
2697         count = 2
2698     elif tls.startswith("internal"):
2699         func = "tls_connection_prf"
2700         count = 1
2701     else:
2702         raise HwsimSkip("Unsupported TLS library")
2703     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2704     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
2705     with alloc_fail(dev[0], count, func):
2706         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
2707                        identity="user", anonymous_identity="FAST",
2708                        password="password", ca_cert="auth_serv/ca.pem",
2709                        phase2="auth=GTC",
2710                        phase1="fast_provisioning=2",
2711                        pac_file="blob://fast_pac_auth",
2712                        wait_connect=False, scan_freq="2412")
2713         ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
2714         if ev is None:
2715             raise Exception("EAP failure not reported")
2716     dev[0].request("DISCONNECT")
2717
2718 def test_ap_wpa2_eap_fast_server_oom(dev, apdev):
2719     """EAP-FAST/MSCHAPv2 and server OOM"""
2720     check_eap_capa(dev[0], "FAST")
2721
2722     params = int_eap_server_params()
2723     params['dh_file'] = 'auth_serv/dh.conf'
2724     params['pac_opaque_encr_key'] = '000102030405060708090a0b0c0d0e0f'
2725     params['eap_fast_a_id'] = '1011'
2726     params['eap_fast_a_id_info'] = 'another test server'
2727     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
2728
2729     with alloc_fail(hapd, 1, "tls_session_ticket_ext_cb"):
2730         id = eap_connect(dev[0], apdev[0], "FAST", "user",
2731                          anonymous_identity="FAST", password="password",
2732                          ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2733                          phase1="fast_provisioning=1",
2734                          pac_file="blob://fast_pac",
2735                          expect_failure=True)
2736         ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
2737         if ev is None:
2738             raise Exception("No EAP failure reported")
2739         dev[0].wait_disconnected()
2740         dev[0].request("DISCONNECT")
2741
2742     dev[0].select_network(id, freq="2412")
2743
2744 def test_ap_wpa2_eap_fast_cipher_suites(dev, apdev):
2745     """EAP-FAST and different TLS cipher suites"""
2746     check_eap_capa(dev[0], "FAST")
2747     tls = dev[0].request("GET tls_library")
2748     if not tls.startswith("OpenSSL"):
2749         raise HwsimSkip("TLS library is not OpenSSL: " + tls)
2750
2751     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2752     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
2753
2754     dev[0].request("SET blob fast_pac_ciphers ")
2755     eap_connect(dev[0], apdev[0], "FAST", "user",
2756                 anonymous_identity="FAST", password="password",
2757                 ca_cert="auth_serv/ca.pem", phase2="auth=GTC",
2758                 phase1="fast_provisioning=2",
2759                 pac_file="blob://fast_pac_ciphers")
2760     res = dev[0].get_status_field('EAP TLS cipher')
2761     dev[0].request("REMOVE_NETWORK all")
2762     dev[0].wait_disconnected()
2763     if res != "DHE-RSA-AES256-SHA":
2764         raise Exception("Unexpected cipher suite for provisioning: " + res)
2765
2766     tests = [ "DHE-RSA-AES128-SHA",
2767               "RC4-SHA",
2768               "AES128-SHA",
2769               "AES256-SHA",
2770               "DHE-RSA-AES256-SHA" ]
2771     for cipher in tests:
2772         eap_connect(dev[0], apdev[0], "FAST", "user",
2773                     openssl_ciphers=cipher,
2774                     anonymous_identity="FAST", password="password",
2775                     ca_cert="auth_serv/ca.pem", phase2="auth=GTC",
2776                     pac_file="blob://fast_pac_ciphers")
2777         res = dev[0].get_status_field('EAP TLS cipher')
2778         dev[0].request("REMOVE_NETWORK all")
2779         dev[0].wait_disconnected()
2780         if res != cipher:
2781             raise Exception("Unexpected TLS cipher info (configured %s): %s" % (cipher, res))
2782
2783 def test_ap_wpa2_eap_tls_ocsp(dev, apdev):
2784     """WPA2-Enterprise connection using EAP-TLS and verifying OCSP"""
2785     check_ocsp_support(dev[0])
2786     check_pkcs12_support(dev[0])
2787     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2788     hostapd.add_ap(apdev[0]['ifname'], params)
2789     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
2790                 private_key="auth_serv/user.pkcs12",
2791                 private_key_passwd="whatever", ocsp=2)
2792
2793 def test_ap_wpa2_eap_tls_ocsp_multi(dev, apdev):
2794     """WPA2-Enterprise connection using EAP-TLS and verifying OCSP-multi"""
2795     check_ocsp_multi_support(dev[0])
2796     check_pkcs12_support(dev[0])
2797
2798     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2799     hostapd.add_ap(apdev[0]['ifname'], params)
2800     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
2801                 private_key="auth_serv/user.pkcs12",
2802                 private_key_passwd="whatever", ocsp=2)
2803
2804 def int_eap_server_params():
2805     params = { "ssid": "test-wpa2-eap", "wpa": "2", "wpa_key_mgmt": "WPA-EAP",
2806                "rsn_pairwise": "CCMP", "ieee8021x": "1",
2807                "eap_server": "1", "eap_user_file": "auth_serv/eap_user.conf",
2808                "ca_cert": "auth_serv/ca.pem",
2809                "server_cert": "auth_serv/server.pem",
2810                "private_key": "auth_serv/server.key",
2811                "dh_file": "auth_serv/dh.conf" }
2812     return params
2813
2814 def test_ap_wpa2_eap_tls_ocsp_key_id(dev, apdev, params):
2815     """EAP-TLS and OCSP certificate signed OCSP response using key ID"""
2816     check_ocsp_support(dev[0])
2817     ocsp = os.path.join(params['logdir'], "ocsp-server-cache-key-id.der")
2818     if not os.path.exists(ocsp):
2819         raise HwsimSkip("No OCSP response available")
2820     params = int_eap_server_params()
2821     params["ocsp_stapling_response"] = ocsp
2822     hostapd.add_ap(apdev[0]['ifname'], params)
2823     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
2824                    identity="tls user", ca_cert="auth_serv/ca.pem",
2825                    private_key="auth_serv/user.pkcs12",
2826                    private_key_passwd="whatever", ocsp=2,
2827                    scan_freq="2412")
2828
2829 def test_ap_wpa2_eap_tls_ocsp_ca_signed_good(dev, apdev, params):
2830     """EAP-TLS and CA signed OCSP response (good)"""
2831     check_ocsp_support(dev[0])
2832     ocsp = os.path.join(params['logdir'], "ocsp-resp-ca-signed.der")
2833     if not os.path.exists(ocsp):
2834         raise HwsimSkip("No OCSP response available")
2835     params = int_eap_server_params()
2836     params["ocsp_stapling_response"] = ocsp
2837     hostapd.add_ap(apdev[0]['ifname'], params)
2838     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
2839                    identity="tls user", ca_cert="auth_serv/ca.pem",
2840                    private_key="auth_serv/user.pkcs12",
2841                    private_key_passwd="whatever", ocsp=2,
2842                    scan_freq="2412")
2843
2844 def test_ap_wpa2_eap_tls_ocsp_ca_signed_revoked(dev, apdev, params):
2845     """EAP-TLS and CA signed OCSP response (revoked)"""
2846     check_ocsp_support(dev[0])
2847     ocsp = os.path.join(params['logdir'], "ocsp-resp-ca-signed-revoked.der")
2848     if not os.path.exists(ocsp):
2849         raise HwsimSkip("No OCSP response available")
2850     params = int_eap_server_params()
2851     params["ocsp_stapling_response"] = ocsp
2852     hostapd.add_ap(apdev[0]['ifname'], params)
2853     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
2854                    identity="tls user", ca_cert="auth_serv/ca.pem",
2855                    private_key="auth_serv/user.pkcs12",
2856                    private_key_passwd="whatever", ocsp=2,
2857                    wait_connect=False, scan_freq="2412")
2858     count = 0
2859     while True:
2860         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
2861         if ev is None:
2862             raise Exception("Timeout on EAP status")
2863         if 'bad certificate status response' in ev:
2864             break
2865         if 'certificate revoked' in ev:
2866             break
2867         count = count + 1
2868         if count > 10:
2869             raise Exception("Unexpected number of EAP status messages")
2870
2871     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
2872     if ev is None:
2873         raise Exception("Timeout on EAP failure report")
2874
2875 def test_ap_wpa2_eap_tls_ocsp_ca_signed_unknown(dev, apdev, params):
2876     """EAP-TLS and CA signed OCSP response (unknown)"""
2877     check_ocsp_support(dev[0])
2878     ocsp = os.path.join(params['logdir'], "ocsp-resp-ca-signed-unknown.der")
2879     if not os.path.exists(ocsp):
2880         raise HwsimSkip("No OCSP response available")
2881     params = int_eap_server_params()
2882     params["ocsp_stapling_response"] = ocsp
2883     hostapd.add_ap(apdev[0]['ifname'], params)
2884     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
2885                    identity="tls user", ca_cert="auth_serv/ca.pem",
2886                    private_key="auth_serv/user.pkcs12",
2887                    private_key_passwd="whatever", ocsp=2,
2888                    wait_connect=False, scan_freq="2412")
2889     count = 0
2890     while True:
2891         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
2892         if ev is None:
2893             raise Exception("Timeout on EAP status")
2894         if 'bad certificate status response' in ev:
2895             break
2896         count = count + 1
2897         if count > 10:
2898             raise Exception("Unexpected number of EAP status messages")
2899
2900     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
2901     if ev is None:
2902         raise Exception("Timeout on EAP failure report")
2903
2904 def test_ap_wpa2_eap_tls_ocsp_server_signed(dev, apdev, params):
2905     """EAP-TLS and server signed OCSP response"""
2906     check_ocsp_support(dev[0])
2907     ocsp = os.path.join(params['logdir'], "ocsp-resp-server-signed.der")
2908     if not os.path.exists(ocsp):
2909         raise HwsimSkip("No OCSP response available")
2910     params = int_eap_server_params()
2911     params["ocsp_stapling_response"] = ocsp
2912     hostapd.add_ap(apdev[0]['ifname'], params)
2913     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
2914                    identity="tls user", ca_cert="auth_serv/ca.pem",
2915                    private_key="auth_serv/user.pkcs12",
2916                    private_key_passwd="whatever", ocsp=2,
2917                    wait_connect=False, scan_freq="2412")
2918     count = 0
2919     while True:
2920         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
2921         if ev is None:
2922             raise Exception("Timeout on EAP status")
2923         if 'bad certificate status response' in ev:
2924             break
2925         count = count + 1
2926         if count > 10:
2927             raise Exception("Unexpected number of EAP status messages")
2928
2929     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
2930     if ev is None:
2931         raise Exception("Timeout on EAP failure report")
2932
2933 def test_ap_wpa2_eap_tls_ocsp_invalid_data(dev, apdev):
2934     """WPA2-Enterprise connection using EAP-TLS and invalid OCSP data"""
2935     check_ocsp_support(dev[0])
2936     params = int_eap_server_params()
2937     params["ocsp_stapling_response"] = "auth_serv/ocsp-req.der"
2938     hostapd.add_ap(apdev[0]['ifname'], params)
2939     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
2940                    identity="tls user", ca_cert="auth_serv/ca.pem",
2941                    private_key="auth_serv/user.pkcs12",
2942                    private_key_passwd="whatever", ocsp=2,
2943                    wait_connect=False, scan_freq="2412")
2944     count = 0
2945     while True:
2946         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
2947         if ev is None:
2948             raise Exception("Timeout on EAP status")
2949         if 'bad certificate status response' in ev:
2950             break
2951         count = count + 1
2952         if count > 10:
2953             raise Exception("Unexpected number of EAP status messages")
2954
2955     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
2956     if ev is None:
2957         raise Exception("Timeout on EAP failure report")
2958
2959 def test_ap_wpa2_eap_tls_ocsp_invalid(dev, apdev):
2960     """WPA2-Enterprise connection using EAP-TLS and invalid OCSP response"""
2961     check_ocsp_support(dev[0])
2962     params = int_eap_server_params()
2963     params["ocsp_stapling_response"] = "auth_serv/ocsp-server-cache.der-invalid"
2964     hostapd.add_ap(apdev[0]['ifname'], params)
2965     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
2966                    identity="tls user", ca_cert="auth_serv/ca.pem",
2967                    private_key="auth_serv/user.pkcs12",
2968                    private_key_passwd="whatever", ocsp=2,
2969                    wait_connect=False, scan_freq="2412")
2970     count = 0
2971     while True:
2972         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
2973         if ev is None:
2974             raise Exception("Timeout on EAP status")
2975         if 'bad certificate status response' 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_tls_ocsp_unknown_sign(dev, apdev):
2986     """WPA2-Enterprise connection using EAP-TLS and unknown OCSP signer"""
2987     check_ocsp_support(dev[0])
2988     params = int_eap_server_params()
2989     params["ocsp_stapling_response"] = "auth_serv/ocsp-server-cache.der-unknown-sign"
2990     hostapd.add_ap(apdev[0]['ifname'], params)
2991     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
2992                    identity="tls user", ca_cert="auth_serv/ca.pem",
2993                    private_key="auth_serv/user.pkcs12",
2994                    private_key_passwd="whatever", ocsp=2,
2995                    wait_connect=False, scan_freq="2412")
2996     count = 0
2997     while True:
2998         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
2999         if ev is None:
3000             raise Exception("Timeout on EAP status")
3001         if 'bad certificate status response' in ev:
3002             break
3003         count = count + 1
3004         if count > 10:
3005             raise Exception("Unexpected number of EAP status messages")
3006
3007     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3008     if ev is None:
3009         raise Exception("Timeout on EAP failure report")
3010
3011 def test_ap_wpa2_eap_ttls_ocsp_revoked(dev, apdev, params):
3012     """WPA2-Enterprise connection using EAP-TTLS and OCSP status revoked"""
3013     check_ocsp_support(dev[0])
3014     ocsp = os.path.join(params['logdir'], "ocsp-server-cache-revoked.der")
3015     if not os.path.exists(ocsp):
3016         raise HwsimSkip("No OCSP response available")
3017     params = int_eap_server_params()
3018     params["ocsp_stapling_response"] = ocsp
3019     hostapd.add_ap(apdev[0]['ifname'], params)
3020     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3021                    identity="pap user", ca_cert="auth_serv/ca.pem",
3022                    anonymous_identity="ttls", password="password",
3023                    phase2="auth=PAP", ocsp=2,
3024                    wait_connect=False, scan_freq="2412")
3025     count = 0
3026     while True:
3027         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
3028         if ev is None:
3029             raise Exception("Timeout on EAP status")
3030         if 'bad certificate status response' in ev:
3031             break
3032         if 'certificate revoked' in ev:
3033             break
3034         count = count + 1
3035         if count > 10:
3036             raise Exception("Unexpected number of EAP status messages")
3037
3038     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3039     if ev is None:
3040         raise Exception("Timeout on EAP failure report")
3041
3042 def test_ap_wpa2_eap_ttls_ocsp_unknown(dev, apdev, params):
3043     """WPA2-Enterprise connection using EAP-TTLS and OCSP status revoked"""
3044     check_ocsp_support(dev[0])
3045     ocsp = os.path.join(params['logdir'], "ocsp-server-cache-unknown.der")
3046     if not os.path.exists(ocsp):
3047         raise HwsimSkip("No OCSP response available")
3048     params = int_eap_server_params()
3049     params["ocsp_stapling_response"] = ocsp
3050     hostapd.add_ap(apdev[0]['ifname'], params)
3051     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3052                    identity="pap user", ca_cert="auth_serv/ca.pem",
3053                    anonymous_identity="ttls", password="password",
3054                    phase2="auth=PAP", ocsp=2,
3055                    wait_connect=False, scan_freq="2412")
3056     count = 0
3057     while True:
3058         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
3059         if ev is None:
3060             raise Exception("Timeout on EAP status")
3061         if 'bad certificate status response' in ev:
3062             break
3063         count = count + 1
3064         if count > 10:
3065             raise Exception("Unexpected number of EAP status messages")
3066
3067     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3068     if ev is None:
3069         raise Exception("Timeout on EAP failure report")
3070
3071 def test_ap_wpa2_eap_ttls_optional_ocsp_unknown(dev, apdev, params):
3072     """WPA2-Enterprise connection using EAP-TTLS and OCSP status revoked"""
3073     ocsp = os.path.join(params['logdir'], "ocsp-server-cache-unknown.der")
3074     if not os.path.exists(ocsp):
3075         raise HwsimSkip("No OCSP response available")
3076     params = int_eap_server_params()
3077     params["ocsp_stapling_response"] = ocsp
3078     hostapd.add_ap(apdev[0]['ifname'], params)
3079     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3080                    identity="pap user", ca_cert="auth_serv/ca.pem",
3081                    anonymous_identity="ttls", password="password",
3082                    phase2="auth=PAP", ocsp=1, scan_freq="2412")
3083
3084 def test_ap_wpa2_eap_tls_intermediate_ca(dev, apdev, params):
3085     """EAP-TLS with intermediate server/user CA"""
3086     params = int_eap_server_params()
3087     params["ca_cert"] = "auth_serv/iCA-server/ca-and-root.pem"
3088     params["server_cert"] = "auth_serv/iCA-server/server.pem"
3089     params["private_key"] = "auth_serv/iCA-server/server.key"
3090     hostapd.add_ap(apdev[0]['ifname'], params)
3091     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3092                    identity="tls user",
3093                    ca_cert="auth_serv/iCA-user/ca-and-root.pem",
3094                    client_cert="auth_serv/iCA-user/user.pem",
3095                    private_key="auth_serv/iCA-user/user.key",
3096                    scan_freq="2412")
3097
3098 def root_ocsp(cert):
3099     ca = "auth_serv/ca.pem"
3100
3101     fd2, fn2 = tempfile.mkstemp()
3102     os.close(fd2)
3103
3104     arg = [ "openssl", "ocsp", "-reqout", fn2, "-issuer", ca, "-cert", cert,
3105             "-no_nonce", "-sha256", "-text" ]
3106     cmd = subprocess.Popen(arg, stdout=subprocess.PIPE,
3107                            stderr=subprocess.PIPE)
3108     res = cmd.stdout.read() + "\n" + cmd.stderr.read()
3109     cmd.stdout.close()
3110     cmd.stderr.close()
3111     logger.info("OCSP request:\n" + res)
3112
3113     fd, fn = tempfile.mkstemp()
3114     os.close(fd)
3115     arg = [ "openssl", "ocsp", "-index", "rootCA/index.txt",
3116             "-rsigner", ca, "-rkey", "auth_serv/caa-key.pem",
3117             "-CA", ca, "-issuer", ca, "-verify_other", ca, "-trust_other",
3118             "-ndays", "7", "-reqin", fn2, "-resp_no_certs", "-respout", fn,
3119             "-text" ]
3120     cmd = subprocess.Popen(arg, stdout=subprocess.PIPE,
3121                            stderr=subprocess.PIPE)
3122     res = cmd.stdout.read() + "\n" + cmd.stderr.read()
3123     cmd.stdout.close()
3124     cmd.stderr.close()
3125     logger.info("OCSP response:\n" + res)
3126     os.unlink(fn2)
3127     return fn
3128
3129 def ica_ocsp(cert):
3130     prefix = "auth_serv/iCA-server/"
3131     ca = prefix + "cacert.pem"
3132     cert = prefix + cert
3133
3134     fd2, fn2 = tempfile.mkstemp()
3135     os.close(fd2)
3136
3137     arg = [ "openssl", "ocsp", "-reqout", fn2, "-issuer", ca, "-cert", cert,
3138             "-no_nonce", "-sha256", "-text" ]
3139     cmd = subprocess.Popen(arg, stdout=subprocess.PIPE,
3140                            stderr=subprocess.PIPE)
3141     res = cmd.stdout.read() + "\n" + cmd.stderr.read()
3142     cmd.stdout.close()
3143     cmd.stderr.close()
3144     logger.info("OCSP request:\n" + res)
3145
3146     fd, fn = tempfile.mkstemp()
3147     os.close(fd)
3148     arg = [ "openssl", "ocsp", "-index", prefix + "index.txt",
3149             "-rsigner", ca, "-rkey", prefix + "private/cakey.pem",
3150             "-CA", ca, "-issuer", ca, "-verify_other", ca, "-trust_other",
3151             "-ndays", "7", "-reqin", fn2, "-resp_no_certs", "-respout", fn,
3152             "-text" ]
3153     cmd = subprocess.Popen(arg, stdout=subprocess.PIPE,
3154                            stderr=subprocess.PIPE)
3155     res = cmd.stdout.read() + "\n" + cmd.stderr.read()
3156     cmd.stdout.close()
3157     cmd.stderr.close()
3158     logger.info("OCSP response:\n" + res)
3159     os.unlink(fn2)
3160     return fn
3161
3162 def test_ap_wpa2_eap_tls_intermediate_ca_ocsp(dev, apdev, params):
3163     """EAP-TLS with intermediate server/user CA and OCSP on server certificate"""
3164     params = int_eap_server_params()
3165     params["ca_cert"] = "auth_serv/iCA-server/ca-and-root.pem"
3166     params["server_cert"] = "auth_serv/iCA-server/server.pem"
3167     params["private_key"] = "auth_serv/iCA-server/server.key"
3168     fn = ica_ocsp("server.pem")
3169     params["ocsp_stapling_response"] = fn
3170     try:
3171         hostapd.add_ap(apdev[0]['ifname'], params)
3172         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3173                        identity="tls user",
3174                        ca_cert="auth_serv/iCA-user/ca-and-root.pem",
3175                        client_cert="auth_serv/iCA-user/user.pem",
3176                        private_key="auth_serv/iCA-user/user.key",
3177                        scan_freq="2412", ocsp=2)
3178     finally:
3179         os.unlink(fn)
3180
3181 def test_ap_wpa2_eap_tls_intermediate_ca_ocsp_revoked(dev, apdev, params):
3182     """EAP-TLS with intermediate server/user CA and OCSP on revoked server certificate"""
3183     params = int_eap_server_params()
3184     params["ca_cert"] = "auth_serv/iCA-server/ca-and-root.pem"
3185     params["server_cert"] = "auth_serv/iCA-server/server-revoked.pem"
3186     params["private_key"] = "auth_serv/iCA-server/server-revoked.key"
3187     fn = ica_ocsp("server-revoked.pem")
3188     params["ocsp_stapling_response"] = fn
3189     try:
3190         hostapd.add_ap(apdev[0]['ifname'], params)
3191         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3192                        identity="tls user",
3193                        ca_cert="auth_serv/iCA-user/ca-and-root.pem",
3194                        client_cert="auth_serv/iCA-user/user.pem",
3195                        private_key="auth_serv/iCA-user/user.key",
3196                        scan_freq="2412", ocsp=1, wait_connect=False)
3197         count = 0
3198         while True:
3199             ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS",
3200                                     "CTRL-EVENT-EAP-SUCCESS"])
3201             if ev is None:
3202                 raise Exception("Timeout on EAP status")
3203             if "CTRL-EVENT-EAP-SUCCESS" in ev:
3204                 raise Exception("Unexpected EAP-Success")
3205             if 'bad certificate status response' in ev:
3206                 break
3207             if 'certificate revoked' in ev:
3208                 break
3209             count = count + 1
3210             if count > 10:
3211                 raise Exception("Unexpected number of EAP status messages")
3212
3213         ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3214         if ev is None:
3215             raise Exception("Timeout on EAP failure report")
3216         dev[0].request("REMOVE_NETWORK all")
3217         dev[0].wait_disconnected()
3218     finally:
3219         os.unlink(fn)
3220
3221 def test_ap_wpa2_eap_tls_intermediate_ca_ocsp_multi_missing_resp(dev, apdev, params):
3222     """EAP-TLS with intermediate server/user CA and OCSP multi missing response"""
3223     check_ocsp_support(dev[0])
3224     check_ocsp_multi_support(dev[0])
3225
3226     params = int_eap_server_params()
3227     params["ca_cert"] = "auth_serv/iCA-server/ca-and-root.pem"
3228     params["server_cert"] = "auth_serv/iCA-server/server.pem"
3229     params["private_key"] = "auth_serv/iCA-server/server.key"
3230     fn = ica_ocsp("server.pem")
3231     params["ocsp_stapling_response"] = fn
3232     try:
3233         hostapd.add_ap(apdev[0]['ifname'], params)
3234         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3235                        identity="tls user",
3236                        ca_cert="auth_serv/iCA-user/ca-and-root.pem",
3237                        client_cert="auth_serv/iCA-user/user.pem",
3238                        private_key="auth_serv/iCA-user/user.key",
3239                        scan_freq="2412", ocsp=3, wait_connect=False)
3240         count = 0
3241         while True:
3242             ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS",
3243                                     "CTRL-EVENT-EAP-SUCCESS"])
3244             if ev is None:
3245                 raise Exception("Timeout on EAP status")
3246             if "CTRL-EVENT-EAP-SUCCESS" in ev:
3247                 raise Exception("Unexpected EAP-Success")
3248             if 'bad certificate status response' in ev:
3249                 break
3250             if 'certificate revoked' in ev:
3251                 break
3252             count = count + 1
3253             if count > 10:
3254                 raise Exception("Unexpected number of EAP status messages")
3255
3256         ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3257         if ev is None:
3258             raise Exception("Timeout on EAP failure report")
3259         dev[0].request("REMOVE_NETWORK all")
3260         dev[0].wait_disconnected()
3261     finally:
3262         os.unlink(fn)
3263
3264 def test_ap_wpa2_eap_tls_intermediate_ca_ocsp_multi(dev, apdev, params):
3265     """EAP-TLS with intermediate server/user CA and OCSP multi OK"""
3266     check_ocsp_support(dev[0])
3267     check_ocsp_multi_support(dev[0])
3268
3269     params = int_eap_server_params()
3270     params["ca_cert"] = "auth_serv/iCA-server/ca-and-root.pem"
3271     params["server_cert"] = "auth_serv/iCA-server/server.pem"
3272     params["private_key"] = "auth_serv/iCA-server/server.key"
3273     fn = ica_ocsp("server.pem")
3274     fn2 = root_ocsp("auth_serv/iCA-server/cacert.pem")
3275     params["ocsp_stapling_response"] = fn
3276
3277     with open(fn, "r") as f:
3278         resp_server = f.read()
3279     with open(fn2, "r") as f:
3280         resp_ica = f.read()
3281
3282     fd3, fn3 = tempfile.mkstemp()
3283     try:
3284         f = os.fdopen(fd3, 'w')
3285         f.write(struct.pack(">L", len(resp_server))[1:4])
3286         f.write(resp_server)
3287         f.write(struct.pack(">L", len(resp_ica))[1:4])
3288         f.write(resp_ica)
3289         f.close()
3290
3291         params["ocsp_stapling_response_multi"] = fn3
3292
3293         hostapd.add_ap(apdev[0]['ifname'], params)
3294         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3295                        identity="tls user",
3296                        ca_cert="auth_serv/iCA-user/ca-and-root.pem",
3297                        client_cert="auth_serv/iCA-user/user.pem",
3298                        private_key="auth_serv/iCA-user/user.key",
3299                        scan_freq="2412", ocsp=3, wait_connect=False)
3300         count = 0
3301         while True:
3302             ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS",
3303                                     "CTRL-EVENT-EAP-SUCCESS"])
3304             if ev is None:
3305                 raise Exception("Timeout on EAP status")
3306             if "CTRL-EVENT-EAP-SUCCESS" in ev:
3307                 raise Exception("Unexpected EAP-Success")
3308             if 'bad certificate status response' in ev:
3309                 break
3310             if 'certificate revoked' in ev:
3311                 break
3312             count = count + 1
3313             if count > 10:
3314                 raise Exception("Unexpected number of EAP status messages")
3315
3316         ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3317         if ev is None:
3318             raise Exception("Timeout on EAP failure report")
3319         dev[0].request("REMOVE_NETWORK all")
3320         dev[0].wait_disconnected()
3321     finally:
3322         os.unlink(fn)
3323         os.unlink(fn2)
3324         os.unlink(fn3)
3325
3326 def test_ap_wpa2_eap_tls_ocsp_multi_revoked(dev, apdev, params):
3327     """EAP-TLS and CA signed OCSP multi response (revoked)"""
3328     check_ocsp_support(dev[0])
3329     check_ocsp_multi_support(dev[0])
3330
3331     ocsp_revoked = os.path.join(params['logdir'],
3332                                 "ocsp-resp-ca-signed-revoked.der")
3333     if not os.path.exists(ocsp_revoked):
3334         raise HwsimSkip("No OCSP response (revoked) available")
3335     ocsp_unknown = os.path.join(params['logdir'],
3336                                 "ocsp-resp-ca-signed-unknown.der")
3337     if not os.path.exists(ocsp_unknown):
3338         raise HwsimSkip("No OCSP response(unknown) available")
3339
3340     with open(ocsp_revoked, "r") as f:
3341         resp_revoked = f.read()
3342     with open(ocsp_unknown, "r") as f:
3343         resp_unknown = f.read()
3344
3345     fd, fn = tempfile.mkstemp()
3346     try:
3347         # This is not really a valid order of the OCSPResponse items in the
3348         # list, but this works for now to verify parsing and processing of
3349         # multiple responses.
3350         f = os.fdopen(fd, 'w')
3351         f.write(struct.pack(">L", len(resp_unknown))[1:4])
3352         f.write(resp_unknown)
3353         f.write(struct.pack(">L", len(resp_revoked))[1:4])
3354         f.write(resp_revoked)
3355         f.write(struct.pack(">L", 0)[1:4])
3356         f.write(struct.pack(">L", len(resp_unknown))[1:4])
3357         f.write(resp_unknown)
3358         f.close()
3359
3360         params = int_eap_server_params()
3361         params["ocsp_stapling_response_multi"] = fn
3362         hostapd.add_ap(apdev[0]['ifname'], params)
3363         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3364                        identity="tls user", ca_cert="auth_serv/ca.pem",
3365                        private_key="auth_serv/user.pkcs12",
3366                        private_key_passwd="whatever", ocsp=1,
3367                        wait_connect=False, scan_freq="2412")
3368         count = 0
3369         while True:
3370             ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS",
3371                                     "CTRL-EVENT-EAP-SUCCESS"])
3372             if ev is None:
3373                 raise Exception("Timeout on EAP status")
3374             if "CTRL-EVENT-EAP-SUCCESS" in ev:
3375                 raise Exception("Unexpected EAP-Success")
3376             if 'bad certificate status response' in ev:
3377                 break
3378             if 'certificate revoked' in ev:
3379                 break
3380             count = count + 1
3381             if count > 10:
3382                 raise Exception("Unexpected number of EAP status messages")
3383     finally:
3384         os.unlink(fn)
3385
3386 def test_ap_wpa2_eap_tls_domain_suffix_match_cn_full(dev, apdev):
3387     """WPA2-Enterprise using EAP-TLS and domain suffix match (CN)"""
3388     check_domain_match_full(dev[0])
3389     params = int_eap_server_params()
3390     params["server_cert"] = "auth_serv/server-no-dnsname.pem"
3391     params["private_key"] = "auth_serv/server-no-dnsname.key"
3392     hostapd.add_ap(apdev[0]['ifname'], params)
3393     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3394                    identity="tls user", ca_cert="auth_serv/ca.pem",
3395                    private_key="auth_serv/user.pkcs12",
3396                    private_key_passwd="whatever",
3397                    domain_suffix_match="server3.w1.fi",
3398                    scan_freq="2412")
3399
3400 def test_ap_wpa2_eap_tls_domain_match_cn(dev, apdev):
3401     """WPA2-Enterprise using EAP-TLS and domainmatch (CN)"""
3402     check_domain_match(dev[0])
3403     params = int_eap_server_params()
3404     params["server_cert"] = "auth_serv/server-no-dnsname.pem"
3405     params["private_key"] = "auth_serv/server-no-dnsname.key"
3406     hostapd.add_ap(apdev[0]['ifname'], params)
3407     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3408                    identity="tls user", ca_cert="auth_serv/ca.pem",
3409                    private_key="auth_serv/user.pkcs12",
3410                    private_key_passwd="whatever",
3411                    domain_match="server3.w1.fi",
3412                    scan_freq="2412")
3413
3414 def test_ap_wpa2_eap_tls_domain_suffix_match_cn(dev, apdev):
3415     """WPA2-Enterprise using EAP-TLS and domain suffix match (CN)"""
3416     check_domain_match_full(dev[0])
3417     params = int_eap_server_params()
3418     params["server_cert"] = "auth_serv/server-no-dnsname.pem"
3419     params["private_key"] = "auth_serv/server-no-dnsname.key"
3420     hostapd.add_ap(apdev[0]['ifname'], params)
3421     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3422                    identity="tls user", ca_cert="auth_serv/ca.pem",
3423                    private_key="auth_serv/user.pkcs12",
3424                    private_key_passwd="whatever",
3425                    domain_suffix_match="w1.fi",
3426                    scan_freq="2412")
3427
3428 def test_ap_wpa2_eap_tls_domain_suffix_mismatch_cn(dev, apdev):
3429     """WPA2-Enterprise using EAP-TLS and domain suffix mismatch (CN)"""
3430     check_domain_suffix_match(dev[0])
3431     params = int_eap_server_params()
3432     params["server_cert"] = "auth_serv/server-no-dnsname.pem"
3433     params["private_key"] = "auth_serv/server-no-dnsname.key"
3434     hostapd.add_ap(apdev[0]['ifname'], params)
3435     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3436                    identity="tls user", ca_cert="auth_serv/ca.pem",
3437                    private_key="auth_serv/user.pkcs12",
3438                    private_key_passwd="whatever",
3439                    domain_suffix_match="example.com",
3440                    wait_connect=False,
3441                    scan_freq="2412")
3442     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3443                    identity="tls user", ca_cert="auth_serv/ca.pem",
3444                    private_key="auth_serv/user.pkcs12",
3445                    private_key_passwd="whatever",
3446                    domain_suffix_match="erver3.w1.fi",
3447                    wait_connect=False,
3448                    scan_freq="2412")
3449     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3450     if ev is None:
3451         raise Exception("Timeout on EAP failure report")
3452     ev = dev[1].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3453     if ev is None:
3454         raise Exception("Timeout on EAP failure report (2)")
3455
3456 def test_ap_wpa2_eap_tls_domain_mismatch_cn(dev, apdev):
3457     """WPA2-Enterprise using EAP-TLS and domain mismatch (CN)"""
3458     check_domain_match(dev[0])
3459     params = int_eap_server_params()
3460     params["server_cert"] = "auth_serv/server-no-dnsname.pem"
3461     params["private_key"] = "auth_serv/server-no-dnsname.key"
3462     hostapd.add_ap(apdev[0]['ifname'], params)
3463     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3464                    identity="tls user", ca_cert="auth_serv/ca.pem",
3465                    private_key="auth_serv/user.pkcs12",
3466                    private_key_passwd="whatever",
3467                    domain_match="example.com",
3468                    wait_connect=False,
3469                    scan_freq="2412")
3470     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3471                    identity="tls user", ca_cert="auth_serv/ca.pem",
3472                    private_key="auth_serv/user.pkcs12",
3473                    private_key_passwd="whatever",
3474                    domain_match="w1.fi",
3475                    wait_connect=False,
3476                    scan_freq="2412")
3477     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3478     if ev is None:
3479         raise Exception("Timeout on EAP failure report")
3480     ev = dev[1].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3481     if ev is None:
3482         raise Exception("Timeout on EAP failure report (2)")
3483
3484 def test_ap_wpa2_eap_ttls_expired_cert(dev, apdev):
3485     """WPA2-Enterprise using EAP-TTLS and expired certificate"""
3486     skip_with_fips(dev[0])
3487     params = int_eap_server_params()
3488     params["server_cert"] = "auth_serv/server-expired.pem"
3489     params["private_key"] = "auth_serv/server-expired.key"
3490     hostapd.add_ap(apdev[0]['ifname'], params)
3491     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3492                    identity="mschap user", password="password",
3493                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
3494                    wait_connect=False,
3495                    scan_freq="2412")
3496     ev = dev[0].wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR"])
3497     if ev is None:
3498         raise Exception("Timeout on EAP certificate error report")
3499     if "reason=4" not in ev or "certificate has expired" not in ev:
3500         raise Exception("Unexpected failure reason: " + ev)
3501     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3502     if ev is None:
3503         raise Exception("Timeout on EAP failure report")
3504
3505 def test_ap_wpa2_eap_ttls_ignore_expired_cert(dev, apdev):
3506     """WPA2-Enterprise using EAP-TTLS and ignore certificate expiration"""
3507     skip_with_fips(dev[0])
3508     params = int_eap_server_params()
3509     params["server_cert"] = "auth_serv/server-expired.pem"
3510     params["private_key"] = "auth_serv/server-expired.key"
3511     hostapd.add_ap(apdev[0]['ifname'], params)
3512     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3513                    identity="mschap user", password="password",
3514                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
3515                    phase1="tls_disable_time_checks=1",
3516                    scan_freq="2412")
3517
3518 def test_ap_wpa2_eap_ttls_long_duration(dev, apdev):
3519     """WPA2-Enterprise using EAP-TTLS and long certificate duration"""
3520     skip_with_fips(dev[0])
3521     params = int_eap_server_params()
3522     params["server_cert"] = "auth_serv/server-long-duration.pem"
3523     params["private_key"] = "auth_serv/server-long-duration.key"
3524     hostapd.add_ap(apdev[0]['ifname'], params)
3525     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3526                    identity="mschap user", password="password",
3527                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
3528                    scan_freq="2412")
3529
3530 def test_ap_wpa2_eap_ttls_server_cert_eku_client(dev, apdev):
3531     """WPA2-Enterprise using EAP-TTLS and server cert with client EKU"""
3532     skip_with_fips(dev[0])
3533     params = int_eap_server_params()
3534     params["server_cert"] = "auth_serv/server-eku-client.pem"
3535     params["private_key"] = "auth_serv/server-eku-client.key"
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                    wait_connect=False,
3541                    scan_freq="2412")
3542     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3543     if ev is None:
3544         raise Exception("Timeout on EAP failure report")
3545
3546 def test_ap_wpa2_eap_ttls_server_cert_eku_client_server(dev, apdev):
3547     """WPA2-Enterprise using EAP-TTLS and server cert with client and server EKU"""
3548     skip_with_fips(dev[0])
3549     params = int_eap_server_params()
3550     params["server_cert"] = "auth_serv/server-eku-client-server.pem"
3551     params["private_key"] = "auth_serv/server-eku-client-server.key"
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                    scan_freq="2412")
3557
3558 def test_ap_wpa2_eap_ttls_server_pkcs12(dev, apdev):
3559     """WPA2-Enterprise using EAP-TTLS and server PKCS#12 file"""
3560     skip_with_fips(dev[0])
3561     params = int_eap_server_params()
3562     del params["server_cert"]
3563     params["private_key"] = "auth_serv/server.pkcs12"
3564     hostapd.add_ap(apdev[0]['ifname'], params)
3565     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3566                    identity="mschap user", password="password",
3567                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
3568                    scan_freq="2412")
3569
3570 def test_ap_wpa2_eap_ttls_dh_params(dev, apdev):
3571     """WPA2-Enterprise connection using EAP-TTLS/CHAP and setting DH params"""
3572     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3573     hostapd.add_ap(apdev[0]['ifname'], params)
3574     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
3575                 anonymous_identity="ttls", password="password",
3576                 ca_cert="auth_serv/ca.der", phase2="auth=PAP",
3577                 dh_file="auth_serv/dh.conf")
3578
3579 def test_ap_wpa2_eap_ttls_dh_params_dsa(dev, apdev):
3580     """WPA2-Enterprise connection using EAP-TTLS and setting DH params (DSA)"""
3581     check_dh_dsa_support(dev[0])
3582     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3583     hostapd.add_ap(apdev[0]['ifname'], params)
3584     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
3585                 anonymous_identity="ttls", password="password",
3586                 ca_cert="auth_serv/ca.der", phase2="auth=PAP",
3587                 dh_file="auth_serv/dsaparam.pem")
3588
3589 def test_ap_wpa2_eap_ttls_dh_params_not_found(dev, apdev):
3590     """EAP-TTLS and DH params file not found"""
3591     skip_with_fips(dev[0])
3592     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3593     hostapd.add_ap(apdev[0]['ifname'], params)
3594     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3595                    identity="mschap user", password="password",
3596                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
3597                    dh_file="auth_serv/dh-no-such-file.conf",
3598                    scan_freq="2412", wait_connect=False)
3599     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3600     if ev is None:
3601         raise Exception("EAP failure timed out")
3602     dev[0].request("REMOVE_NETWORK all")
3603     dev[0].wait_disconnected()
3604
3605 def test_ap_wpa2_eap_ttls_dh_params_invalid(dev, apdev):
3606     """EAP-TTLS and invalid DH params file"""
3607     skip_with_fips(dev[0])
3608     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3609     hostapd.add_ap(apdev[0]['ifname'], params)
3610     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3611                    identity="mschap user", password="password",
3612                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
3613                    dh_file="auth_serv/ca.pem",
3614                    scan_freq="2412", wait_connect=False)
3615     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3616     if ev is None:
3617         raise Exception("EAP failure timed out")
3618     dev[0].request("REMOVE_NETWORK all")
3619     dev[0].wait_disconnected()
3620
3621 def test_ap_wpa2_eap_ttls_dh_params_blob(dev, apdev):
3622     """WPA2-Enterprise connection using EAP-TTLS/CHAP and setting DH params from blob"""
3623     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3624     hostapd.add_ap(apdev[0]['ifname'], params)
3625     dh = read_pem("auth_serv/dh2.conf")
3626     if "OK" not in dev[0].request("SET blob dhparams " + dh.encode("hex")):
3627         raise Exception("Could not set dhparams blob")
3628     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
3629                 anonymous_identity="ttls", password="password",
3630                 ca_cert="auth_serv/ca.der", phase2="auth=PAP",
3631                 dh_file="blob://dhparams")
3632
3633 def test_ap_wpa2_eap_ttls_dh_params_server(dev, apdev):
3634     """WPA2-Enterprise using EAP-TTLS and alternative server dhparams"""
3635     params = int_eap_server_params()
3636     params["dh_file"] = "auth_serv/dh2.conf"
3637     hostapd.add_ap(apdev[0]['ifname'], params)
3638     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
3639                 anonymous_identity="ttls", password="password",
3640                 ca_cert="auth_serv/ca.der", phase2="auth=PAP")
3641
3642 def test_ap_wpa2_eap_ttls_dh_params_dsa_server(dev, apdev):
3643     """WPA2-Enterprise using EAP-TTLS and alternative server dhparams (DSA)"""
3644     params = int_eap_server_params()
3645     params["dh_file"] = "auth_serv/dsaparam.pem"
3646     hostapd.add_ap(apdev[0]['ifname'], params)
3647     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
3648                 anonymous_identity="ttls", password="password",
3649                 ca_cert="auth_serv/ca.der", phase2="auth=PAP")
3650
3651 def test_ap_wpa2_eap_ttls_dh_params_not_found(dev, apdev):
3652     """EAP-TLS server and dhparams file not found"""
3653     params = int_eap_server_params()
3654     params["dh_file"] = "auth_serv/dh-no-such-file.conf"
3655     hapd = hostapd.add_ap(apdev[0]['ifname'], params, no_enable=True)
3656     if "FAIL" not in hapd.request("ENABLE"):
3657         raise Exception("Invalid configuration accepted")
3658
3659 def test_ap_wpa2_eap_ttls_dh_params_invalid(dev, apdev):
3660     """EAP-TLS server and invalid dhparams file"""
3661     params = int_eap_server_params()
3662     params["dh_file"] = "auth_serv/ca.pem"
3663     hapd = hostapd.add_ap(apdev[0]['ifname'], params, no_enable=True)
3664     if "FAIL" not in hapd.request("ENABLE"):
3665         raise Exception("Invalid configuration accepted")
3666
3667 def test_ap_wpa2_eap_reauth(dev, apdev):
3668     """WPA2-Enterprise and Authenticator forcing reauthentication"""
3669     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3670     params['eap_reauth_period'] = '2'
3671     hostapd.add_ap(apdev[0]['ifname'], params)
3672     eap_connect(dev[0], apdev[0], "PAX", "pax.user@example.com",
3673                 password_hex="0123456789abcdef0123456789abcdef")
3674     logger.info("Wait for reauthentication")
3675     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=10)
3676     if ev is None:
3677         raise Exception("Timeout on reauthentication")
3678     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
3679     if ev is None:
3680         raise Exception("Timeout on reauthentication")
3681     for i in range(0, 20):
3682         state = dev[0].get_status_field("wpa_state")
3683         if state == "COMPLETED":
3684             break
3685         time.sleep(0.1)
3686     if state != "COMPLETED":
3687         raise Exception("Reauthentication did not complete")
3688
3689 def test_ap_wpa2_eap_request_identity_message(dev, apdev):
3690     """Optional displayable message in EAP Request-Identity"""
3691     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3692     params['eap_message'] = 'hello\\0networkid=netw,nasid=foo,portid=0,NAIRealms=example.com'
3693     hostapd.add_ap(apdev[0]['ifname'], params)
3694     eap_connect(dev[0], apdev[0], "PAX", "pax.user@example.com",
3695                 password_hex="0123456789abcdef0123456789abcdef")
3696
3697 def test_ap_wpa2_eap_sim_aka_result_ind(dev, apdev):
3698     """WPA2-Enterprise using EAP-SIM/AKA and protected result indication"""
3699     check_hlr_auc_gw_support()
3700     params = int_eap_server_params()
3701     params['eap_sim_db'] = "unix:/tmp/hlr_auc_gw.sock"
3702     params['eap_sim_aka_result_ind'] = "1"
3703     hostapd.add_ap(apdev[0]['ifname'], params)
3704
3705     eap_connect(dev[0], apdev[0], "SIM", "1232010000000000",
3706                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
3707                 phase1="result_ind=1")
3708     eap_reauth(dev[0], "SIM")
3709     eap_connect(dev[1], apdev[0], "SIM", "1232010000000000",
3710                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581")
3711
3712     dev[0].request("REMOVE_NETWORK all")
3713     dev[1].request("REMOVE_NETWORK all")
3714
3715     eap_connect(dev[0], apdev[0], "AKA", "0232010000000000",
3716                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123",
3717                 phase1="result_ind=1")
3718     eap_reauth(dev[0], "AKA")
3719     eap_connect(dev[1], apdev[0], "AKA", "0232010000000000",
3720                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123")
3721
3722     dev[0].request("REMOVE_NETWORK all")
3723     dev[1].request("REMOVE_NETWORK all")
3724
3725     eap_connect(dev[0], apdev[0], "AKA'", "6555444333222111",
3726                 password="5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123",
3727                 phase1="result_ind=1")
3728     eap_reauth(dev[0], "AKA'")
3729     eap_connect(dev[1], apdev[0], "AKA'", "6555444333222111",
3730                 password="5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123")
3731
3732 def test_ap_wpa2_eap_too_many_roundtrips(dev, apdev):
3733     """WPA2-Enterprise connection resulting in too many EAP roundtrips"""
3734     skip_with_fips(dev[0])
3735     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3736     hostapd.add_ap(apdev[0]['ifname'], params)
3737     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
3738                    eap="TTLS", identity="mschap user",
3739                    wait_connect=False, scan_freq="2412", ieee80211w="1",
3740                    anonymous_identity="ttls", password="password",
3741                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
3742                    fragment_size="10")
3743     ev = dev[0].wait_event(["EAP: more than"], timeout=20)
3744     if ev is None:
3745         raise Exception("EAP roundtrip limit not reached")
3746
3747 def test_ap_wpa2_eap_expanded_nak(dev, apdev):
3748     """WPA2-Enterprise connection with EAP resulting in expanded NAK"""
3749     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3750     hostapd.add_ap(apdev[0]['ifname'], params)
3751     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
3752                    eap="PSK", identity="vendor-test",
3753                    password_hex="ff23456789abcdef0123456789abcdef",
3754                    wait_connect=False)
3755
3756     found = False
3757     for i in range(0, 5):
3758         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"], timeout=16)
3759         if ev is None:
3760             raise Exception("Association and EAP start timed out")
3761         if "refuse proposed method" in ev:
3762             found = True
3763             break
3764     if not found:
3765         raise Exception("Unexpected EAP status: " + ev)
3766
3767     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3768     if ev is None:
3769         raise Exception("EAP failure timed out")
3770
3771 def test_ap_wpa2_eap_sql(dev, apdev, params):
3772     """WPA2-Enterprise connection using SQLite for user DB"""
3773     skip_with_fips(dev[0])
3774     try:
3775         import sqlite3
3776     except ImportError:
3777         raise HwsimSkip("No sqlite3 module available")
3778     dbfile = os.path.join(params['logdir'], "eap-user.db")
3779     try:
3780         os.remove(dbfile)
3781     except:
3782         pass
3783     con = sqlite3.connect(dbfile)
3784     with con:
3785         cur = con.cursor()
3786         cur.execute("CREATE TABLE users(identity TEXT PRIMARY KEY, methods TEXT, password TEXT, remediation TEXT, phase2 INTEGER)")
3787         cur.execute("CREATE TABLE wildcards(identity TEXT PRIMARY KEY, methods TEXT)")
3788         cur.execute("INSERT INTO users(identity,methods,password,phase2) VALUES ('user-pap','TTLS-PAP','password',1)")
3789         cur.execute("INSERT INTO users(identity,methods,password,phase2) VALUES ('user-chap','TTLS-CHAP','password',1)")
3790         cur.execute("INSERT INTO users(identity,methods,password,phase2) VALUES ('user-mschap','TTLS-MSCHAP','password',1)")
3791         cur.execute("INSERT INTO users(identity,methods,password,phase2) VALUES ('user-mschapv2','TTLS-MSCHAPV2','password',1)")
3792         cur.execute("INSERT INTO wildcards(identity,methods) VALUES ('','TTLS,TLS')")
3793         cur.execute("CREATE TABLE authlog(timestamp TEXT, session TEXT, nas_ip TEXT, username TEXT, note TEXT)")
3794
3795     try:
3796         params = int_eap_server_params()
3797         params["eap_user_file"] = "sqlite:" + dbfile
3798         hostapd.add_ap(apdev[0]['ifname'], params)
3799         eap_connect(dev[0], apdev[0], "TTLS", "user-mschapv2",
3800                     anonymous_identity="ttls", password="password",
3801                     ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
3802         dev[0].request("REMOVE_NETWORK all")
3803         eap_connect(dev[1], apdev[0], "TTLS", "user-mschap",
3804                     anonymous_identity="ttls", password="password",
3805                     ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP")
3806         dev[1].request("REMOVE_NETWORK all")
3807         eap_connect(dev[0], apdev[0], "TTLS", "user-chap",
3808                     anonymous_identity="ttls", password="password",
3809                     ca_cert="auth_serv/ca.pem", phase2="auth=CHAP")
3810         eap_connect(dev[1], apdev[0], "TTLS", "user-pap",
3811                     anonymous_identity="ttls", password="password",
3812                     ca_cert="auth_serv/ca.pem", phase2="auth=PAP")
3813     finally:
3814         os.remove(dbfile)
3815
3816 def test_ap_wpa2_eap_non_ascii_identity(dev, apdev):
3817     """WPA2-Enterprise connection attempt using non-ASCII identity"""
3818     params = int_eap_server_params()
3819     hostapd.add_ap(apdev[0]['ifname'], params)
3820     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3821                    identity="\x80", password="password", wait_connect=False)
3822     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3823                    identity="a\x80", password="password", wait_connect=False)
3824     for i in range(0, 2):
3825         ev = dev[i].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
3826         if ev is None:
3827             raise Exception("Association and EAP start timed out")
3828         ev = dev[i].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=10)
3829         if ev is None:
3830             raise Exception("EAP method selection timed out")
3831
3832 def test_ap_wpa2_eap_non_ascii_identity2(dev, apdev):
3833     """WPA2-Enterprise connection attempt using non-ASCII identity"""
3834     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3835     hostapd.add_ap(apdev[0]['ifname'], params)
3836     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3837                    identity="\x80", password="password", wait_connect=False)
3838     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3839                    identity="a\x80", password="password", wait_connect=False)
3840     for i in range(0, 2):
3841         ev = dev[i].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
3842         if ev is None:
3843             raise Exception("Association and EAP start timed out")
3844         ev = dev[i].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=10)
3845         if ev is None:
3846             raise Exception("EAP method selection timed out")
3847
3848 def test_openssl_cipher_suite_config_wpas(dev, apdev):
3849     """OpenSSL cipher suite configuration on wpa_supplicant"""
3850     tls = dev[0].request("GET tls_library")
3851     if not tls.startswith("OpenSSL"):
3852         raise HwsimSkip("TLS library is not OpenSSL: " + tls)
3853     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3854     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
3855     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
3856                 anonymous_identity="ttls", password="password",
3857                 openssl_ciphers="AES128",
3858                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP")
3859     eap_connect(dev[1], apdev[0], "TTLS", "pap user",
3860                 anonymous_identity="ttls", password="password",
3861                 openssl_ciphers="EXPORT",
3862                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP",
3863                 expect_failure=True, maybe_local_error=True)
3864     dev[2].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3865                    identity="pap user", anonymous_identity="ttls",
3866                    password="password",
3867                    openssl_ciphers="FOO",
3868                    ca_cert="auth_serv/ca.pem", phase2="auth=PAP",
3869                    wait_connect=False)
3870     ev = dev[2].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
3871     if ev is None:
3872         raise Exception("EAP failure after invalid openssl_ciphers not reported")
3873     dev[2].request("DISCONNECT")
3874
3875 def test_openssl_cipher_suite_config_hapd(dev, apdev):
3876     """OpenSSL cipher suite configuration on hostapd"""
3877     tls = dev[0].request("GET tls_library")
3878     if not tls.startswith("OpenSSL"):
3879         raise HwsimSkip("wpa_supplicant TLS library is not OpenSSL: " + tls)
3880     params = int_eap_server_params()
3881     params['openssl_ciphers'] = "AES256"
3882     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
3883     tls = hapd.request("GET tls_library")
3884     if not tls.startswith("OpenSSL"):
3885         raise HwsimSkip("hostapd TLS library is not OpenSSL: " + tls)
3886     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
3887                 anonymous_identity="ttls", password="password",
3888                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP")
3889     eap_connect(dev[1], apdev[0], "TTLS", "pap user",
3890                 anonymous_identity="ttls", password="password",
3891                 openssl_ciphers="AES128",
3892                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP",
3893                 expect_failure=True)
3894     eap_connect(dev[2], apdev[0], "TTLS", "pap user",
3895                 anonymous_identity="ttls", password="password",
3896                 openssl_ciphers="HIGH:!ADH",
3897                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP")
3898
3899     params['openssl_ciphers'] = "FOO"
3900     hapd2 = hostapd.add_ap(apdev[1]['ifname'], params, no_enable=True)
3901     if "FAIL" not in hapd2.request("ENABLE"):
3902         raise Exception("Invalid openssl_ciphers value accepted")
3903
3904 def test_wpa2_eap_ttls_pap_key_lifetime_in_memory(dev, apdev, params):
3905     """Key lifetime in memory with WPA2-Enterprise using EAP-TTLS/PAP"""
3906     p = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3907     hapd = hostapd.add_ap(apdev[0]['ifname'], p)
3908     password = "63d2d21ac3c09ed567ee004a34490f1d16e7fa5835edf17ddba70a63f1a90a25"
3909     pid = find_wpas_process(dev[0])
3910     id = eap_connect(dev[0], apdev[0], "TTLS", "pap-secret",
3911                      anonymous_identity="ttls", password=password,
3912                      ca_cert="auth_serv/ca.pem", phase2="auth=PAP")
3913     # The decrypted copy of GTK is freed only after the CTRL-EVENT-CONNECTED
3914     # event has been delivered, so verify that wpa_supplicant has returned to
3915     # eloop before reading process memory.
3916     time.sleep(1)
3917     dev[0].ping()
3918     buf = read_process_memory(pid, password)
3919
3920     dev[0].request("DISCONNECT")
3921     dev[0].wait_disconnected()
3922
3923     dev[0].relog()
3924     msk = None
3925     emsk = None
3926     pmk = None
3927     ptk = None
3928     gtk = None
3929     with open(os.path.join(params['logdir'], 'log0'), 'r') as f:
3930         for l in f.readlines():
3931             if "EAP-TTLS: Derived key - hexdump" in l:
3932                 val = l.strip().split(':')[3].replace(' ', '')
3933                 msk = binascii.unhexlify(val)
3934             if "EAP-TTLS: Derived EMSK - hexdump" in l:
3935                 val = l.strip().split(':')[3].replace(' ', '')
3936                 emsk = binascii.unhexlify(val)
3937             if "WPA: PMK - hexdump" in l:
3938                 val = l.strip().split(':')[3].replace(' ', '')
3939                 pmk = binascii.unhexlify(val)
3940             if "WPA: PTK - hexdump" in l:
3941                 val = l.strip().split(':')[3].replace(' ', '')
3942                 ptk = binascii.unhexlify(val)
3943             if "WPA: Group Key - hexdump" in l:
3944                 val = l.strip().split(':')[3].replace(' ', '')
3945                 gtk = binascii.unhexlify(val)
3946     if not msk or not emsk or not pmk or not ptk or not gtk:
3947         raise Exception("Could not find keys from debug log")
3948     if len(gtk) != 16:
3949         raise Exception("Unexpected GTK length")
3950
3951     kck = ptk[0:16]
3952     kek = ptk[16:32]
3953     tk = ptk[32:48]
3954
3955     fname = os.path.join(params['logdir'],
3956                          'wpa2_eap_ttls_pap_key_lifetime_in_memory.memctx-')
3957
3958     logger.info("Checking keys in memory while associated")
3959     get_key_locations(buf, password, "Password")
3960     get_key_locations(buf, pmk, "PMK")
3961     get_key_locations(buf, msk, "MSK")
3962     get_key_locations(buf, emsk, "EMSK")
3963     if password not in buf:
3964         raise HwsimSkip("Password not found while associated")
3965     if pmk not in buf:
3966         raise HwsimSkip("PMK not found while associated")
3967     if kck not in buf:
3968         raise Exception("KCK not found while associated")
3969     if kek not in buf:
3970         raise Exception("KEK not found while associated")
3971     if tk in buf:
3972         raise Exception("TK found from memory")
3973     if gtk in buf:
3974         get_key_locations(buf, gtk, "GTK")
3975         raise Exception("GTK found from memory")
3976
3977     logger.info("Checking keys in memory after disassociation")
3978     buf = read_process_memory(pid, password)
3979
3980     # Note: Password is still present in network configuration
3981     # Note: PMK is in PMKSA cache and EAP fast re-auth data
3982
3983     get_key_locations(buf, password, "Password")
3984     get_key_locations(buf, pmk, "PMK")
3985     get_key_locations(buf, msk, "MSK")
3986     get_key_locations(buf, emsk, "EMSK")
3987     verify_not_present(buf, kck, fname, "KCK")
3988     verify_not_present(buf, kek, fname, "KEK")
3989     verify_not_present(buf, tk, fname, "TK")
3990     verify_not_present(buf, gtk, fname, "GTK")
3991
3992     dev[0].request("PMKSA_FLUSH")
3993     dev[0].set_network_quoted(id, "identity", "foo")
3994     logger.info("Checking keys in memory after PMKSA cache and EAP fast reauth flush")
3995     buf = read_process_memory(pid, password)
3996     get_key_locations(buf, password, "Password")
3997     get_key_locations(buf, pmk, "PMK")
3998     get_key_locations(buf, msk, "MSK")
3999     get_key_locations(buf, emsk, "EMSK")
4000     verify_not_present(buf, pmk, fname, "PMK")
4001
4002     dev[0].request("REMOVE_NETWORK all")
4003
4004     logger.info("Checking keys in memory after network profile removal")
4005     buf = read_process_memory(pid, password)
4006
4007     get_key_locations(buf, password, "Password")
4008     get_key_locations(buf, pmk, "PMK")
4009     get_key_locations(buf, msk, "MSK")
4010     get_key_locations(buf, emsk, "EMSK")
4011     verify_not_present(buf, password, fname, "password")
4012     verify_not_present(buf, pmk, fname, "PMK")
4013     verify_not_present(buf, kck, fname, "KCK")
4014     verify_not_present(buf, kek, fname, "KEK")
4015     verify_not_present(buf, tk, fname, "TK")
4016     verify_not_present(buf, gtk, fname, "GTK")
4017     verify_not_present(buf, msk, fname, "MSK")
4018     verify_not_present(buf, emsk, fname, "EMSK")
4019
4020 def test_ap_wpa2_eap_unexpected_wep_eapol_key(dev, apdev):
4021     """WPA2-Enterprise connection and unexpected WEP EAPOL-Key"""
4022     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4023     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4024     bssid = apdev[0]['bssid']
4025     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
4026                 anonymous_identity="ttls", password="password",
4027                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP")
4028
4029     # Send unexpected WEP EAPOL-Key; this gets dropped
4030     res = dev[0].request("EAPOL_RX " + bssid + " 0203002c0100000000000000000000000000000000000000000000000000000000000000000000000000000000000000")
4031     if "OK" not in res:
4032         raise Exception("EAPOL_RX to wpa_supplicant failed")
4033
4034 def test_ap_wpa2_eap_in_bridge(dev, apdev):
4035     """WPA2-EAP and wpas interface in a bridge"""
4036     br_ifname='sta-br0'
4037     ifname='wlan5'
4038     try:
4039         _test_ap_wpa2_eap_in_bridge(dev, apdev)
4040     finally:
4041         subprocess.call(['ip', 'link', 'set', 'dev', br_ifname, 'down'])
4042         subprocess.call(['brctl', 'delif', br_ifname, ifname])
4043         subprocess.call(['brctl', 'delbr', br_ifname])
4044         subprocess.call(['iw', ifname, 'set', '4addr', 'off'])
4045
4046 def _test_ap_wpa2_eap_in_bridge(dev, apdev):
4047     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4048     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4049
4050     br_ifname='sta-br0'
4051     ifname='wlan5'
4052     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
4053     subprocess.call(['brctl', 'addbr', br_ifname])
4054     subprocess.call(['brctl', 'setfd', br_ifname, '0'])
4055     subprocess.call(['ip', 'link', 'set', 'dev', br_ifname, 'up'])
4056     subprocess.call(['iw', ifname, 'set', '4addr', 'on'])
4057     subprocess.check_call(['brctl', 'addif', br_ifname, ifname])
4058     wpas.interface_add(ifname, br_ifname=br_ifname)
4059     wpas.dump_monitor()
4060
4061     id = eap_connect(wpas, apdev[0], "PAX", "pax.user@example.com",
4062                      password_hex="0123456789abcdef0123456789abcdef")
4063     wpas.dump_monitor()
4064     eap_reauth(wpas, "PAX")
4065     wpas.dump_monitor()
4066     # Try again as a regression test for packet socket workaround
4067     eap_reauth(wpas, "PAX")
4068     wpas.dump_monitor()
4069     wpas.request("DISCONNECT")
4070     wpas.wait_disconnected()
4071     wpas.dump_monitor()
4072     wpas.request("RECONNECT")
4073     wpas.wait_connected()
4074     wpas.dump_monitor()
4075
4076 def test_ap_wpa2_eap_session_ticket(dev, apdev):
4077     """WPA2-Enterprise connection using EAP-TTLS and TLS session ticket enabled"""
4078     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4079     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4080     key_mgmt = hapd.get_config()['key_mgmt']
4081     if key_mgmt.split(' ')[0] != "WPA-EAP":
4082         raise Exception("Unexpected GET_CONFIG(key_mgmt): " + key_mgmt)
4083     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
4084                 anonymous_identity="ttls", password="password",
4085                 ca_cert="auth_serv/ca.pem",
4086                 phase1="tls_disable_session_ticket=0", phase2="auth=PAP")
4087     eap_reauth(dev[0], "TTLS")
4088
4089 def test_ap_wpa2_eap_no_workaround(dev, apdev):
4090     """WPA2-Enterprise connection using EAP-TTLS and eap_workaround=0"""
4091     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4092     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4093     key_mgmt = hapd.get_config()['key_mgmt']
4094     if key_mgmt.split(' ')[0] != "WPA-EAP":
4095         raise Exception("Unexpected GET_CONFIG(key_mgmt): " + key_mgmt)
4096     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
4097                 anonymous_identity="ttls", password="password",
4098                 ca_cert="auth_serv/ca.pem", eap_workaround='0',
4099                 phase2="auth=PAP")
4100     eap_reauth(dev[0], "TTLS")
4101
4102 def test_ap_wpa2_eap_tls_check_crl(dev, apdev):
4103     """EAP-TLS and server checking CRL"""
4104     params = int_eap_server_params()
4105     params['check_crl'] = '1'
4106     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4107
4108     # check_crl=1 and no CRL available --> reject connection
4109     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4110                 client_cert="auth_serv/user.pem",
4111                 private_key="auth_serv/user.key", expect_failure=True)
4112     dev[0].request("REMOVE_NETWORK all")
4113
4114     hapd.disable()
4115     hapd.set("ca_cert", "auth_serv/ca-and-crl.pem")
4116     hapd.enable()
4117
4118     # check_crl=1 and valid CRL --> accept
4119     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4120                 client_cert="auth_serv/user.pem",
4121                 private_key="auth_serv/user.key")
4122     dev[0].request("REMOVE_NETWORK all")
4123
4124     hapd.disable()
4125     hapd.set("check_crl", "2")
4126     hapd.enable()
4127
4128     # check_crl=2 and valid CRL --> accept
4129     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4130                 client_cert="auth_serv/user.pem",
4131                 private_key="auth_serv/user.key")
4132     dev[0].request("REMOVE_NETWORK all")
4133
4134 def test_ap_wpa2_eap_tls_oom(dev, apdev):
4135     """EAP-TLS and OOM"""
4136     check_subject_match_support(dev[0])
4137     check_altsubject_match_support(dev[0])
4138     check_domain_match(dev[0])
4139     check_domain_match_full(dev[0])
4140
4141     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4142     hostapd.add_ap(apdev[0]['ifname'], params)
4143
4144     tests = [ (1, "tls_connection_set_subject_match"),
4145               (2, "tls_connection_set_subject_match"),
4146               (3, "tls_connection_set_subject_match"),
4147               (4, "tls_connection_set_subject_match") ]
4148     for count, func in tests:
4149         with alloc_fail(dev[0], count, func):
4150             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4151                            identity="tls user", ca_cert="auth_serv/ca.pem",
4152                            client_cert="auth_serv/user.pem",
4153                            private_key="auth_serv/user.key",
4154                            subject_match="/C=FI/O=w1.fi/CN=server.w1.fi",
4155                            altsubject_match="EMAIL:noone@example.com;DNS:server.w1.fi;URI:http://example.com/",
4156                            domain_suffix_match="server.w1.fi",
4157                            domain_match="server.w1.fi",
4158                            wait_connect=False, scan_freq="2412")
4159             # TLS parameter configuration error results in CTRL-REQ-PASSPHRASE
4160             ev = dev[0].wait_event(["CTRL-REQ-PASSPHRASE"], timeout=5)
4161             if ev is None:
4162                 raise Exception("No passphrase request")
4163             dev[0].request("REMOVE_NETWORK all")
4164             dev[0].wait_disconnected()
4165
4166 def test_ap_wpa2_eap_tls_macacl(dev, apdev):
4167     """WPA2-Enterprise connection using MAC ACL"""
4168     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4169     params["macaddr_acl"] = "2"
4170     hostapd.add_ap(apdev[0]['ifname'], params)
4171     eap_connect(dev[1], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4172                 client_cert="auth_serv/user.pem",
4173                 private_key="auth_serv/user.key")
4174
4175 def test_ap_wpa2_eap_oom(dev, apdev):
4176     """EAP server and OOM"""
4177     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4178     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4179     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
4180
4181     with alloc_fail(hapd, 1, "eapol_auth_alloc"):
4182         # The first attempt fails, but STA will send EAPOL-Start to retry and
4183         # that succeeds.
4184         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4185                        identity="tls user", ca_cert="auth_serv/ca.pem",
4186                        client_cert="auth_serv/user.pem",
4187                        private_key="auth_serv/user.key",
4188                        scan_freq="2412")
4189
4190 def check_tls_ver(dev, ap, phase1, expected):
4191     eap_connect(dev, ap, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4192                 client_cert="auth_serv/user.pem",
4193                 private_key="auth_serv/user.key",
4194                 phase1=phase1)
4195     ver = dev.get_status_field("eap_tls_version")
4196     if ver != expected:
4197         raise Exception("Unexpected TLS version (expected %s): %s" % (expected, ver))
4198
4199 def test_ap_wpa2_eap_tls_versions(dev, apdev):
4200     """EAP-TLS and TLS version configuration"""
4201     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4202     hostapd.add_ap(apdev[0]['ifname'], params)
4203
4204     tls = dev[0].request("GET tls_library")
4205     if tls.startswith("OpenSSL"):
4206         if "build=OpenSSL 1.0.2" in tls and "run=OpenSSL 1.0.2" in tls:
4207             check_tls_ver(dev[0], apdev[0],
4208                           "tls_disable_tlsv1_0=1 tls_disable_tlsv1_1=1",
4209                           "TLSv1.2")
4210     elif tls.startswith("internal"):
4211         check_tls_ver(dev[0], apdev[0],
4212                       "tls_disable_tlsv1_0=1 tls_disable_tlsv1_1=1", "TLSv1.2")
4213     check_tls_ver(dev[1], apdev[0],
4214                   "tls_disable_tlsv1_0=1 tls_disable_tlsv1_2=1", "TLSv1.1")
4215     check_tls_ver(dev[2], apdev[0],
4216                   "tls_disable_tlsv1_1=1 tls_disable_tlsv1_2=1", "TLSv1")
4217
4218 def test_rsn_ie_proto_eap_sta(dev, apdev):
4219     """RSN element protocol testing for EAP cases on STA side"""
4220     bssid = apdev[0]['bssid']
4221     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4222     # This is the RSN element used normally by hostapd
4223     params['own_ie_override'] = '30140100000fac040100000fac040100000fac010c00'
4224     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4225     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="GPSK",
4226                         identity="gpsk user",
4227                         password="abcdefghijklmnop0123456789abcdef",
4228                         scan_freq="2412")
4229
4230     tests = [ ('No RSN Capabilities field',
4231                '30120100000fac040100000fac040100000fac01'),
4232               ('No AKM Suite fields',
4233                '300c0100000fac040100000fac04'),
4234               ('No Pairwise Cipher Suite fields',
4235                '30060100000fac04'),
4236               ('No Group Data Cipher Suite field',
4237                '30020100') ]
4238     for txt,ie in tests:
4239         dev[0].request("DISCONNECT")
4240         dev[0].wait_disconnected()
4241         logger.info(txt)
4242         hapd.disable()
4243         hapd.set('own_ie_override', ie)
4244         hapd.enable()
4245         dev[0].request("BSS_FLUSH 0")
4246         dev[0].scan_for_bss(bssid, 2412, force_scan=True, only_new=True)
4247         dev[0].select_network(id, freq=2412)
4248         dev[0].wait_connected()
4249
4250     dev[0].request("DISCONNECT")
4251     dev[0].wait_disconnected()
4252     dev[0].flush_scan_cache()
4253
4254 def check_tls_session_resumption_capa(dev, hapd):
4255     tls = hapd.request("GET tls_library")
4256     if not tls.startswith("OpenSSL"):
4257         raise HwsimSkip("hostapd TLS library is not OpenSSL: " + tls)
4258
4259     tls = dev.request("GET tls_library")
4260     if not tls.startswith("OpenSSL"):
4261         raise HwsimSkip("Session resumption not supported with this TLS library: " + tls)
4262
4263 def test_eap_ttls_pap_session_resumption(dev, apdev):
4264     """EAP-TTLS/PAP session resumption"""
4265     params = int_eap_server_params()
4266     params['tls_session_lifetime'] = '60'
4267     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4268     check_tls_session_resumption_capa(dev[0], hapd)
4269     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
4270                 anonymous_identity="ttls", password="password",
4271                 ca_cert="auth_serv/ca.pem", eap_workaround='0',
4272                 phase2="auth=PAP")
4273     if dev[0].get_status_field("tls_session_reused") != '0':
4274         raise Exception("Unexpected session resumption on the first connection")
4275
4276     dev[0].request("REAUTHENTICATE")
4277     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4278     if ev is None:
4279         raise Exception("EAP success timed out")
4280     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4281     if ev is None:
4282         raise Exception("Key handshake with the AP timed out")
4283     if dev[0].get_status_field("tls_session_reused") != '1':
4284         raise Exception("Session resumption not used on the second connection")
4285
4286 def test_eap_ttls_chap_session_resumption(dev, apdev):
4287     """EAP-TTLS/CHAP session resumption"""
4288     params = int_eap_server_params()
4289     params['tls_session_lifetime'] = '60'
4290     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4291     check_tls_session_resumption_capa(dev[0], hapd)
4292     eap_connect(dev[0], apdev[0], "TTLS", "chap user",
4293                 anonymous_identity="ttls", password="password",
4294                 ca_cert="auth_serv/ca.der", phase2="auth=CHAP")
4295     if dev[0].get_status_field("tls_session_reused") != '0':
4296         raise Exception("Unexpected session resumption on the first connection")
4297
4298     dev[0].request("REAUTHENTICATE")
4299     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4300     if ev is None:
4301         raise Exception("EAP success timed out")
4302     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4303     if ev is None:
4304         raise Exception("Key handshake with the AP timed out")
4305     if dev[0].get_status_field("tls_session_reused") != '1':
4306         raise Exception("Session resumption not used on the second connection")
4307
4308 def test_eap_ttls_mschap_session_resumption(dev, apdev):
4309     """EAP-TTLS/MSCHAP session resumption"""
4310     check_domain_suffix_match(dev[0])
4311     params = int_eap_server_params()
4312     params['tls_session_lifetime'] = '60'
4313     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4314     check_tls_session_resumption_capa(dev[0], hapd)
4315     eap_connect(dev[0], apdev[0], "TTLS", "mschap user",
4316                 anonymous_identity="ttls", password="password",
4317                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
4318                 domain_suffix_match="server.w1.fi")
4319     if dev[0].get_status_field("tls_session_reused") != '0':
4320         raise Exception("Unexpected session resumption on the first connection")
4321
4322     dev[0].request("REAUTHENTICATE")
4323     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4324     if ev is None:
4325         raise Exception("EAP success timed out")
4326     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4327     if ev is None:
4328         raise Exception("Key handshake with the AP timed out")
4329     if dev[0].get_status_field("tls_session_reused") != '1':
4330         raise Exception("Session resumption not used on the second connection")
4331
4332 def test_eap_ttls_mschapv2_session_resumption(dev, apdev):
4333     """EAP-TTLS/MSCHAPv2 session resumption"""
4334     check_domain_suffix_match(dev[0])
4335     check_eap_capa(dev[0], "MSCHAPV2")
4336     params = int_eap_server_params()
4337     params['tls_session_lifetime'] = '60'
4338     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4339     check_tls_session_resumption_capa(dev[0], hapd)
4340     eap_connect(dev[0], apdev[0], "TTLS", "DOMAIN\mschapv2 user",
4341                 anonymous_identity="ttls", password="password",
4342                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
4343                 domain_suffix_match="server.w1.fi")
4344     if dev[0].get_status_field("tls_session_reused") != '0':
4345         raise Exception("Unexpected session resumption on the first connection")
4346
4347     dev[0].request("REAUTHENTICATE")
4348     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4349     if ev is None:
4350         raise Exception("EAP success timed out")
4351     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4352     if ev is None:
4353         raise Exception("Key handshake with the AP timed out")
4354     if dev[0].get_status_field("tls_session_reused") != '1':
4355         raise Exception("Session resumption not used on the second connection")
4356
4357 def test_eap_ttls_eap_gtc_session_resumption(dev, apdev):
4358     """EAP-TTLS/EAP-GTC session resumption"""
4359     params = int_eap_server_params()
4360     params['tls_session_lifetime'] = '60'
4361     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4362     check_tls_session_resumption_capa(dev[0], hapd)
4363     eap_connect(dev[0], apdev[0], "TTLS", "user",
4364                 anonymous_identity="ttls", password="password",
4365                 ca_cert="auth_serv/ca.pem", phase2="autheap=GTC")
4366     if dev[0].get_status_field("tls_session_reused") != '0':
4367         raise Exception("Unexpected session resumption on the first connection")
4368
4369     dev[0].request("REAUTHENTICATE")
4370     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4371     if ev is None:
4372         raise Exception("EAP success timed out")
4373     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4374     if ev is None:
4375         raise Exception("Key handshake with the AP timed out")
4376     if dev[0].get_status_field("tls_session_reused") != '1':
4377         raise Exception("Session resumption not used on the second connection")
4378
4379 def test_eap_ttls_no_session_resumption(dev, apdev):
4380     """EAP-TTLS session resumption disabled on server"""
4381     params = int_eap_server_params()
4382     params['tls_session_lifetime'] = '0'
4383     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4384     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
4385                 anonymous_identity="ttls", password="password",
4386                 ca_cert="auth_serv/ca.pem", eap_workaround='0',
4387                 phase2="auth=PAP")
4388     if dev[0].get_status_field("tls_session_reused") != '0':
4389         raise Exception("Unexpected session resumption on the first connection")
4390
4391     dev[0].request("REAUTHENTICATE")
4392     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4393     if ev is None:
4394         raise Exception("EAP success timed out")
4395     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4396     if ev is None:
4397         raise Exception("Key handshake with the AP timed out")
4398     if dev[0].get_status_field("tls_session_reused") != '0':
4399         raise Exception("Unexpected session resumption on the second connection")
4400
4401 def test_eap_peap_session_resumption(dev, apdev):
4402     """EAP-PEAP session resumption"""
4403     params = int_eap_server_params()
4404     params['tls_session_lifetime'] = '60'
4405     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4406     check_tls_session_resumption_capa(dev[0], hapd)
4407     eap_connect(dev[0], apdev[0], "PEAP", "user",
4408                 anonymous_identity="peap", password="password",
4409                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
4410     if dev[0].get_status_field("tls_session_reused") != '0':
4411         raise Exception("Unexpected session resumption on the first connection")
4412
4413     dev[0].request("REAUTHENTICATE")
4414     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4415     if ev is None:
4416         raise Exception("EAP success timed out")
4417     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4418     if ev is None:
4419         raise Exception("Key handshake with the AP timed out")
4420     if dev[0].get_status_field("tls_session_reused") != '1':
4421         raise Exception("Session resumption not used on the second connection")
4422
4423 def test_eap_peap_session_resumption_crypto_binding(dev, apdev):
4424     """EAP-PEAP session resumption with crypto binding"""
4425     params = int_eap_server_params()
4426     params['tls_session_lifetime'] = '60'
4427     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4428     check_tls_session_resumption_capa(dev[0], hapd)
4429     eap_connect(dev[0], apdev[0], "PEAP", "user",
4430                 anonymous_identity="peap", password="password",
4431                 phase1="peapver=0 crypto_binding=2",
4432                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
4433     if dev[0].get_status_field("tls_session_reused") != '0':
4434         raise Exception("Unexpected session resumption on the first connection")
4435
4436     dev[0].request("REAUTHENTICATE")
4437     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4438     if ev is None:
4439         raise Exception("EAP success timed out")
4440     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4441     if ev is None:
4442         raise Exception("Key handshake with the AP timed out")
4443     if dev[0].get_status_field("tls_session_reused") != '1':
4444         raise Exception("Session resumption not used on the second connection")
4445
4446 def test_eap_peap_no_session_resumption(dev, apdev):
4447     """EAP-PEAP session resumption disabled on server"""
4448     params = int_eap_server_params()
4449     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4450     eap_connect(dev[0], apdev[0], "PEAP", "user",
4451                 anonymous_identity="peap", password="password",
4452                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
4453     if dev[0].get_status_field("tls_session_reused") != '0':
4454         raise Exception("Unexpected session resumption on the first connection")
4455
4456     dev[0].request("REAUTHENTICATE")
4457     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4458     if ev is None:
4459         raise Exception("EAP success timed out")
4460     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4461     if ev is None:
4462         raise Exception("Key handshake with the AP timed out")
4463     if dev[0].get_status_field("tls_session_reused") != '0':
4464         raise Exception("Unexpected session resumption on the second connection")
4465
4466 def test_eap_tls_session_resumption(dev, apdev):
4467     """EAP-TLS session resumption"""
4468     params = int_eap_server_params()
4469     params['tls_session_lifetime'] = '60'
4470     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4471     check_tls_session_resumption_capa(dev[0], hapd)
4472     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4473                 client_cert="auth_serv/user.pem",
4474                 private_key="auth_serv/user.key")
4475     if dev[0].get_status_field("tls_session_reused") != '0':
4476         raise Exception("Unexpected session resumption on the first connection")
4477
4478     dev[0].request("REAUTHENTICATE")
4479     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4480     if ev is None:
4481         raise Exception("EAP success timed out")
4482     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4483     if ev is None:
4484         raise Exception("Key handshake with the AP timed out")
4485     if dev[0].get_status_field("tls_session_reused") != '1':
4486         raise Exception("Session resumption not used on the second connection")
4487
4488     dev[0].request("REAUTHENTICATE")
4489     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4490     if ev is None:
4491         raise Exception("EAP success timed out")
4492     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4493     if ev is None:
4494         raise Exception("Key handshake with the AP timed out")
4495     if dev[0].get_status_field("tls_session_reused") != '1':
4496         raise Exception("Session resumption not used on the third connection")
4497
4498 def test_eap_tls_session_resumption_expiration(dev, apdev):
4499     """EAP-TLS session resumption"""
4500     params = int_eap_server_params()
4501     params['tls_session_lifetime'] = '1'
4502     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4503     check_tls_session_resumption_capa(dev[0], hapd)
4504     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4505                 client_cert="auth_serv/user.pem",
4506                 private_key="auth_serv/user.key")
4507     if dev[0].get_status_field("tls_session_reused") != '0':
4508         raise Exception("Unexpected session resumption on the first connection")
4509
4510     # Allow multiple attempts since OpenSSL may not expire the cached entry
4511     # immediately.
4512     for i in range(10):
4513         time.sleep(1.2)
4514
4515         dev[0].request("REAUTHENTICATE")
4516         ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4517         if ev is None:
4518             raise Exception("EAP success timed out")
4519         ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4520         if ev is None:
4521             raise Exception("Key handshake with the AP timed out")
4522         if dev[0].get_status_field("tls_session_reused") == '0':
4523             break
4524     if dev[0].get_status_field("tls_session_reused") != '0':
4525         raise Exception("Session resumption used after lifetime expiration")
4526
4527 def test_eap_tls_no_session_resumption(dev, apdev):
4528     """EAP-TLS session resumption disabled on server"""
4529     params = int_eap_server_params()
4530     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4531     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4532                 client_cert="auth_serv/user.pem",
4533                 private_key="auth_serv/user.key")
4534     if dev[0].get_status_field("tls_session_reused") != '0':
4535         raise Exception("Unexpected session resumption on the first connection")
4536
4537     dev[0].request("REAUTHENTICATE")
4538     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4539     if ev is None:
4540         raise Exception("EAP success timed out")
4541     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4542     if ev is None:
4543         raise Exception("Key handshake with the AP timed out")
4544     if dev[0].get_status_field("tls_session_reused") != '0':
4545         raise Exception("Unexpected session resumption on the second connection")
4546
4547 def test_eap_tls_session_resumption_radius(dev, apdev):
4548     """EAP-TLS session resumption (RADIUS)"""
4549     params = { "ssid": "as", "beacon_int": "2000",
4550                "radius_server_clients": "auth_serv/radius_clients.conf",
4551                "radius_server_auth_port": '18128',
4552                "eap_server": "1",
4553                "eap_user_file": "auth_serv/eap_user.conf",
4554                "ca_cert": "auth_serv/ca.pem",
4555                "server_cert": "auth_serv/server.pem",
4556                "private_key": "auth_serv/server.key",
4557                "tls_session_lifetime": "60" }
4558     authsrv = hostapd.add_ap(apdev[1]['ifname'], params)
4559     check_tls_session_resumption_capa(dev[0], authsrv)
4560
4561     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4562     params['auth_server_port'] = "18128"
4563     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4564     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4565                 client_cert="auth_serv/user.pem",
4566                 private_key="auth_serv/user.key")
4567     if dev[0].get_status_field("tls_session_reused") != '0':
4568         raise Exception("Unexpected session resumption on the first connection")
4569
4570     dev[0].request("REAUTHENTICATE")
4571     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4572     if ev is None:
4573         raise Exception("EAP success timed out")
4574     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4575     if ev is None:
4576         raise Exception("Key handshake with the AP timed out")
4577     if dev[0].get_status_field("tls_session_reused") != '1':
4578         raise Exception("Session resumption not used on the second connection")
4579
4580 def test_eap_tls_no_session_resumption_radius(dev, apdev):
4581     """EAP-TLS session resumption disabled (RADIUS)"""
4582     params = { "ssid": "as", "beacon_int": "2000",
4583                "radius_server_clients": "auth_serv/radius_clients.conf",
4584                "radius_server_auth_port": '18128',
4585                "eap_server": "1",
4586                "eap_user_file": "auth_serv/eap_user.conf",
4587                "ca_cert": "auth_serv/ca.pem",
4588                "server_cert": "auth_serv/server.pem",
4589                "private_key": "auth_serv/server.key",
4590                "tls_session_lifetime": "0" }
4591     hostapd.add_ap(apdev[1]['ifname'], params)
4592
4593     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4594     params['auth_server_port'] = "18128"
4595     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4596     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4597                 client_cert="auth_serv/user.pem",
4598                 private_key="auth_serv/user.key")
4599     if dev[0].get_status_field("tls_session_reused") != '0':
4600         raise Exception("Unexpected session resumption on the first connection")
4601
4602     dev[0].request("REAUTHENTICATE")
4603     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4604     if ev is None:
4605         raise Exception("EAP success timed out")
4606     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4607     if ev is None:
4608         raise Exception("Key handshake with the AP timed out")
4609     if dev[0].get_status_field("tls_session_reused") != '0':
4610         raise Exception("Unexpected session resumption on the second connection")
4611
4612 def test_eap_mschapv2_errors(dev, apdev):
4613     """EAP-MSCHAPv2 error cases"""
4614     check_eap_capa(dev[0], "MSCHAPV2")
4615     check_eap_capa(dev[0], "FAST")
4616
4617     params = hostapd.wpa2_eap_params(ssid="test-wpa-eap")
4618     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4619     dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="MSCHAPV2",
4620                    identity="phase1-user", password="password",
4621                    scan_freq="2412")
4622     dev[0].request("REMOVE_NETWORK all")
4623     dev[0].wait_disconnected()
4624
4625     tests = [ (1, "hash_nt_password_hash;mschapv2_derive_response"),
4626               (1, "nt_password_hash;mschapv2_derive_response"),
4627               (1, "nt_password_hash;=mschapv2_derive_response"),
4628               (1, "generate_nt_response;mschapv2_derive_response"),
4629               (1, "generate_authenticator_response;mschapv2_derive_response"),
4630               (1, "nt_password_hash;=mschapv2_derive_response"),
4631               (1, "get_master_key;mschapv2_derive_response"),
4632               (1, "os_get_random;eap_mschapv2_challenge_reply") ]
4633     for count, func in tests:
4634         with fail_test(dev[0], count, func):
4635             dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="MSCHAPV2",
4636                            identity="phase1-user", password="password",
4637                            wait_connect=False, scan_freq="2412")
4638             wait_fail_trigger(dev[0], "GET_FAIL")
4639             dev[0].request("REMOVE_NETWORK all")
4640             dev[0].wait_disconnected()
4641
4642     tests = [ (1, "hash_nt_password_hash;mschapv2_derive_response"),
4643               (1, "hash_nt_password_hash;=mschapv2_derive_response"),
4644               (1, "generate_nt_response_pwhash;mschapv2_derive_response"),
4645               (1, "generate_authenticator_response_pwhash;mschapv2_derive_response") ]
4646     for count, func in tests:
4647         with fail_test(dev[0], count, func):
4648             dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="MSCHAPV2",
4649                            identity="phase1-user",
4650                            password_hex="hash:8846f7eaee8fb117ad06bdd830b7586c",
4651                            wait_connect=False, scan_freq="2412")
4652             wait_fail_trigger(dev[0], "GET_FAIL")
4653             dev[0].request("REMOVE_NETWORK all")
4654             dev[0].wait_disconnected()
4655
4656     tests = [ (1, "eap_mschapv2_init"),
4657               (1, "eap_msg_alloc;eap_mschapv2_challenge_reply"),
4658               (1, "eap_msg_alloc;eap_mschapv2_success"),
4659               (1, "eap_mschapv2_getKey") ]
4660     for count, func in tests:
4661         with alloc_fail(dev[0], count, func):
4662             dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="MSCHAPV2",
4663                            identity="phase1-user", password="password",
4664                            wait_connect=False, scan_freq="2412")
4665             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4666             dev[0].request("REMOVE_NETWORK all")
4667             dev[0].wait_disconnected()
4668
4669     tests = [ (1, "eap_msg_alloc;eap_mschapv2_failure") ]
4670     for count, func in tests:
4671         with alloc_fail(dev[0], count, func):
4672             dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="MSCHAPV2",
4673                            identity="phase1-user", password="wrong password",
4674                            wait_connect=False, scan_freq="2412")
4675             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4676             dev[0].request("REMOVE_NETWORK all")
4677             dev[0].wait_disconnected()
4678
4679     tests = [ (2, "eap_mschapv2_init"),
4680               (3, "eap_mschapv2_init") ]
4681     for count, func in tests:
4682         with alloc_fail(dev[0], count, func):
4683             dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="FAST",
4684                            anonymous_identity="FAST", identity="user",
4685                            password="password",
4686                            ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
4687                            phase1="fast_provisioning=1",
4688                            pac_file="blob://fast_pac",
4689                            wait_connect=False, scan_freq="2412")
4690             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4691             dev[0].request("REMOVE_NETWORK all")
4692             dev[0].wait_disconnected()
4693
4694 def test_eap_gpsk_errors(dev, apdev):
4695     """EAP-GPSK error cases"""
4696     params = hostapd.wpa2_eap_params(ssid="test-wpa-eap")
4697     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4698     dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="GPSK",
4699                    identity="gpsk user",
4700                    password="abcdefghijklmnop0123456789abcdef",
4701                    scan_freq="2412")
4702     dev[0].request("REMOVE_NETWORK all")
4703     dev[0].wait_disconnected()
4704
4705     tests = [ (1, "os_get_random;eap_gpsk_send_gpsk_2", None),
4706               (1, "eap_gpsk_derive_session_id;eap_gpsk_send_gpsk_2",
4707                "cipher=1"),
4708               (1, "eap_gpsk_derive_session_id;eap_gpsk_send_gpsk_2",
4709                "cipher=2"),
4710               (1, "eap_gpsk_derive_keys_helper", None),
4711               (2, "eap_gpsk_derive_keys_helper", None),
4712               (1, "eap_gpsk_compute_mic_aes;eap_gpsk_compute_mic;eap_gpsk_send_gpsk_2",
4713                "cipher=1"),
4714               (1, "hmac_sha256;eap_gpsk_compute_mic;eap_gpsk_send_gpsk_2",
4715                "cipher=2"),
4716               (1, "eap_gpsk_compute_mic;eap_gpsk_validate_gpsk_3_mic", None),
4717               (1, "eap_gpsk_compute_mic;eap_gpsk_send_gpsk_4", None),
4718               (1, "eap_gpsk_derive_mid_helper", None) ]
4719     for count, func, phase1 in tests:
4720         with fail_test(dev[0], count, func):
4721             dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="GPSK",
4722                            identity="gpsk user",
4723                            password="abcdefghijklmnop0123456789abcdef",
4724                            phase1=phase1,
4725                            wait_connect=False, scan_freq="2412")
4726             wait_fail_trigger(dev[0], "GET_FAIL")
4727             dev[0].request("REMOVE_NETWORK all")
4728             dev[0].wait_disconnected()
4729
4730     tests = [ (1, "eap_gpsk_init"),
4731               (2, "eap_gpsk_init"),
4732               (3, "eap_gpsk_init"),
4733               (1, "eap_gpsk_process_id_server"),
4734               (1, "eap_msg_alloc;eap_gpsk_send_gpsk_2"),
4735               (1, "eap_gpsk_derive_session_id;eap_gpsk_send_gpsk_2"),
4736               (1, "eap_gpsk_derive_mid_helper;eap_gpsk_derive_session_id;eap_gpsk_send_gpsk_2"),
4737               (1, "eap_gpsk_derive_keys"),
4738               (1, "eap_gpsk_derive_keys_helper"),
4739               (1, "eap_msg_alloc;eap_gpsk_send_gpsk_4"),
4740               (1, "eap_gpsk_getKey"),
4741               (1, "eap_gpsk_get_emsk"),
4742               (1, "eap_gpsk_get_session_id") ]
4743     for count, func in tests:
4744         with alloc_fail(dev[0], count, func):
4745             dev[0].request("ERP_FLUSH")
4746             dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="GPSK",
4747                            identity="gpsk user", erp="1",
4748                            password="abcdefghijklmnop0123456789abcdef",
4749                            wait_connect=False, scan_freq="2412")
4750             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4751             dev[0].request("REMOVE_NETWORK all")
4752             dev[0].wait_disconnected()
4753
4754 def test_ap_wpa2_eap_sim_db(dev, apdev, params):
4755     """EAP-SIM DB error cases"""
4756     sockpath = '/tmp/hlr_auc_gw.sock-test'
4757     try:
4758         os.remove(sockpath)
4759     except:
4760         pass
4761     hparams = int_eap_server_params()
4762     hparams['eap_sim_db'] = 'unix:' + sockpath
4763     hapd = hostapd.add_ap(apdev[0]['ifname'], hparams)
4764
4765     # Initial test with hlr_auc_gw socket not available
4766     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
4767                         eap="SIM", identity="1232010000000000",
4768                         password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
4769                         scan_freq="2412", wait_connect=False)
4770     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4771     if ev is None:
4772         raise Exception("EAP-Failure not reported")
4773     dev[0].wait_disconnected()
4774     dev[0].request("DISCONNECT")
4775
4776     # Test with invalid responses and response timeout
4777
4778     class test_handler(SocketServer.DatagramRequestHandler):
4779         def handle(self):
4780             data = self.request[0].strip()
4781             socket = self.request[1]
4782             logger.debug("Received hlr_auc_gw request: " + data)
4783             # EAP-SIM DB: Failed to parse response string
4784             socket.sendto("FOO", self.client_address)
4785             # EAP-SIM DB: Failed to parse response string
4786             socket.sendto("FOO 1", self.client_address)
4787             # EAP-SIM DB: Unknown external response
4788             socket.sendto("FOO 1 2", self.client_address)
4789             logger.info("No proper response - wait for pending eap_sim_db request timeout")
4790
4791     server = SocketServer.UnixDatagramServer(sockpath, test_handler)
4792     server.timeout = 1
4793
4794     dev[0].select_network(id)
4795     server.handle_request()
4796     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4797     if ev is None:
4798         raise Exception("EAP-Failure not reported")
4799     dev[0].wait_disconnected()
4800     dev[0].request("DISCONNECT")
4801
4802     # Test with a valid response
4803
4804     class test_handler2(SocketServer.DatagramRequestHandler):
4805         def handle(self):
4806             data = self.request[0].strip()
4807             socket = self.request[1]
4808             logger.debug("Received hlr_auc_gw request: " + data)
4809             fname = os.path.join(params['logdir'],
4810                                  'hlr_auc_gw.milenage_db')
4811             cmd = subprocess.Popen(['../../hostapd/hlr_auc_gw',
4812                                     '-m', fname, data],
4813                                    stdout=subprocess.PIPE)
4814             res = cmd.stdout.read().strip()
4815             cmd.stdout.close()
4816             logger.debug("hlr_auc_gw response: " + res)
4817             socket.sendto(res, self.client_address)
4818
4819     server.RequestHandlerClass = test_handler2
4820
4821     dev[0].select_network(id)
4822     server.handle_request()
4823     dev[0].wait_connected()
4824     dev[0].request("DISCONNECT")
4825     dev[0].wait_disconnected()
4826
4827 def test_eap_tls_sha512(dev, apdev, params):
4828     """EAP-TLS with SHA512 signature"""
4829     params = int_eap_server_params()
4830     params["ca_cert"] = "auth_serv/sha512-ca.pem"
4831     params["server_cert"] = "auth_serv/sha512-server.pem"
4832     params["private_key"] = "auth_serv/sha512-server.key"
4833     hostapd.add_ap(apdev[0]['ifname'], params)
4834
4835     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4836                    identity="tls user sha512",
4837                    ca_cert="auth_serv/sha512-ca.pem",
4838                    client_cert="auth_serv/sha512-user.pem",
4839                    private_key="auth_serv/sha512-user.key",
4840                    scan_freq="2412")
4841     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4842                    identity="tls user sha512",
4843                    ca_cert="auth_serv/sha512-ca.pem",
4844                    client_cert="auth_serv/sha384-user.pem",
4845                    private_key="auth_serv/sha384-user.key",
4846                    scan_freq="2412")
4847
4848 def test_eap_tls_sha384(dev, apdev, params):
4849     """EAP-TLS with SHA384 signature"""
4850     params = int_eap_server_params()
4851     params["ca_cert"] = "auth_serv/sha512-ca.pem"
4852     params["server_cert"] = "auth_serv/sha384-server.pem"
4853     params["private_key"] = "auth_serv/sha384-server.key"
4854     hostapd.add_ap(apdev[0]['ifname'], params)
4855
4856     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4857                    identity="tls user sha512",
4858                    ca_cert="auth_serv/sha512-ca.pem",
4859                    client_cert="auth_serv/sha512-user.pem",
4860                    private_key="auth_serv/sha512-user.key",
4861                    scan_freq="2412")
4862     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4863                    identity="tls user sha512",
4864                    ca_cert="auth_serv/sha512-ca.pem",
4865                    client_cert="auth_serv/sha384-user.pem",
4866                    private_key="auth_serv/sha384-user.key",
4867                    scan_freq="2412")
4868
4869 def test_ap_wpa2_eap_assoc_rsn(dev, apdev):
4870     """WPA2-Enterprise AP and association request RSN IE differences"""
4871     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4872     hostapd.add_ap(apdev[0]['ifname'], params)
4873
4874     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap-11w")
4875     params["ieee80211w"] = "2"
4876     hostapd.add_ap(apdev[1]['ifname'], params)
4877
4878     # Success cases with optional RSN IE fields removed one by one
4879     tests = [ ("Normal wpa_supplicant assoc req RSN IE",
4880                "30140100000fac040100000fac040100000fac010000"),
4881               ("Extra PMKIDCount field in RSN IE",
4882                "30160100000fac040100000fac040100000fac0100000000"),
4883               ("Extra Group Management Cipher Suite in RSN IE",
4884                "301a0100000fac040100000fac040100000fac0100000000000fac06"),
4885               ("Extra undefined extension field in RSN IE",
4886                "301c0100000fac040100000fac040100000fac0100000000000fac061122"),
4887               ("RSN IE without RSN Capabilities",
4888                "30120100000fac040100000fac040100000fac01"),
4889               ("RSN IE without AKM", "300c0100000fac040100000fac04"),
4890               ("RSN IE without pairwise", "30060100000fac04"),
4891               ("RSN IE without group", "30020100") ]
4892     for title, ie in tests:
4893         logger.info(title)
4894         set_test_assoc_ie(dev[0], ie)
4895         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="GPSK",
4896                        identity="gpsk user",
4897                        password="abcdefghijklmnop0123456789abcdef",
4898                        scan_freq="2412")
4899         dev[0].request("REMOVE_NETWORK all")
4900         dev[0].wait_disconnected()
4901
4902     tests = [ ("Normal wpa_supplicant assoc req RSN IE",
4903                "30140100000fac040100000fac040100000fac01cc00"),
4904               ("Group management cipher included in assoc req RSN IE",
4905                "301a0100000fac040100000fac040100000fac01cc000000000fac06") ]
4906     for title, ie in tests:
4907         logger.info(title)
4908         set_test_assoc_ie(dev[0], ie)
4909         dev[0].connect("test-wpa2-eap-11w", key_mgmt="WPA-EAP", ieee80211w="1",
4910                        eap="GPSK", identity="gpsk user",
4911                        password="abcdefghijklmnop0123456789abcdef",
4912                        scan_freq="2412")
4913         dev[0].request("REMOVE_NETWORK all")
4914         dev[0].wait_disconnected()
4915
4916     tests = [ ("Invalid group cipher", "30060100000fac02", 41),
4917               ("Invalid pairwise cipher", "300c0100000fac040100000fac02", 42) ]
4918     for title, ie, status in tests:
4919         logger.info(title)
4920         set_test_assoc_ie(dev[0], ie)
4921         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="GPSK",
4922                        identity="gpsk user",
4923                        password="abcdefghijklmnop0123456789abcdef",
4924                        scan_freq="2412", wait_connect=False)
4925         ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"])
4926         if ev is None:
4927             raise Exception("Association rejection not reported")
4928         if "status_code=" + str(status) not in ev:
4929             raise Exception("Unexpected status code: " + ev)
4930         dev[0].request("REMOVE_NETWORK all")
4931         dev[0].dump_monitor()
4932
4933     tests = [ ("Management frame protection not enabled",
4934                "30140100000fac040100000fac040100000fac010000", 31),
4935               ("Unsupported management group cipher",
4936                "301a0100000fac040100000fac040100000fac01cc000000000fac0b", 31) ]
4937     for title, ie, status in tests:
4938         logger.info(title)
4939         set_test_assoc_ie(dev[0], ie)
4940         dev[0].connect("test-wpa2-eap-11w", key_mgmt="WPA-EAP", ieee80211w="1",
4941                        eap="GPSK", identity="gpsk user",
4942                        password="abcdefghijklmnop0123456789abcdef",
4943                        scan_freq="2412", wait_connect=False)
4944         ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"])
4945         if ev is None:
4946             raise Exception("Association rejection not reported")
4947         if "status_code=" + str(status) not in ev:
4948             raise Exception("Unexpected status code: " + ev)
4949         dev[0].request("REMOVE_NETWORK all")
4950         dev[0].dump_monitor()
4951
4952 def test_eap_tls_ext_cert_check(dev, apdev):
4953     """EAP-TLS and external server certification validation"""
4954     # With internal server certificate chain validation
4955     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4956                         identity="tls user",
4957                         ca_cert="auth_serv/ca.pem",
4958                         client_cert="auth_serv/user.pem",
4959                         private_key="auth_serv/user.key",
4960                         phase1="tls_ext_cert_check=1", scan_freq="2412",
4961                         only_add_network=True)
4962     run_ext_cert_check(dev, apdev, id)
4963
4964 def test_eap_ttls_ext_cert_check(dev, apdev):
4965     """EAP-TTLS and external server certification validation"""
4966     # Without internal server certificate chain validation
4967     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
4968                         identity="pap user", anonymous_identity="ttls",
4969                         password="password", phase2="auth=PAP",
4970                         phase1="tls_ext_cert_check=1", scan_freq="2412",
4971                         only_add_network=True)
4972     run_ext_cert_check(dev, apdev, id)
4973
4974 def test_eap_peap_ext_cert_check(dev, apdev):
4975     """EAP-PEAP and external server certification validation"""
4976     # With internal server certificate chain validation
4977     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PEAP",
4978                         identity="user", anonymous_identity="peap",
4979                         ca_cert="auth_serv/ca.pem",
4980                         password="password", phase2="auth=MSCHAPV2",
4981                         phase1="tls_ext_cert_check=1", scan_freq="2412",
4982                         only_add_network=True)
4983     run_ext_cert_check(dev, apdev, id)
4984
4985 def test_eap_fast_ext_cert_check(dev, apdev):
4986     """EAP-FAST and external server certification validation"""
4987     check_eap_capa(dev[0], "FAST")
4988     # With internal server certificate chain validation
4989     dev[0].request("SET blob fast_pac_auth_ext ")
4990     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
4991                         identity="user", anonymous_identity="FAST",
4992                         ca_cert="auth_serv/ca.pem",
4993                         password="password", phase2="auth=GTC",
4994                         phase1="tls_ext_cert_check=1 fast_provisioning=2",
4995                         pac_file="blob://fast_pac_auth_ext",
4996                         scan_freq="2412",
4997                         only_add_network=True)
4998     run_ext_cert_check(dev, apdev, id)
4999
5000 def run_ext_cert_check(dev, apdev, net_id):
5001     check_ext_cert_check_support(dev[0])
5002     if not openssl_imported:
5003         raise HwsimSkip("OpenSSL python method not available")
5004
5005     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
5006     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
5007
5008     dev[0].select_network(net_id)
5009     certs = {}
5010     while True:
5011         ev = dev[0].wait_event(["CTRL-EVENT-EAP-PEER-CERT",
5012                                 "CTRL-REQ-EXT_CERT_CHECK",
5013                                 "CTRL-EVENT-EAP-SUCCESS"], timeout=10)
5014         if ev is None:
5015             raise Exception("No peer server certificate event seen")
5016         if "CTRL-EVENT-EAP-PEER-CERT" in ev:
5017             depth = None
5018             cert = None
5019             vals = ev.split(' ')
5020             for v in vals:
5021                 if v.startswith("depth="):
5022                     depth = int(v.split('=')[1])
5023                 elif v.startswith("cert="):
5024                     cert = v.split('=')[1]
5025             if depth is not None and cert:
5026                 certs[depth] = binascii.unhexlify(cert)
5027         elif "CTRL-EVENT-EAP-SUCCESS" in ev:
5028             raise Exception("Unexpected EAP-Success")
5029         elif "CTRL-REQ-EXT_CERT_CHECK" in ev:
5030             id = ev.split(':')[0].split('-')[-1]
5031             break
5032     if 0 not in certs:
5033         raise Exception("Server certificate not received")
5034     if 1 not in certs:
5035         raise Exception("Server certificate issuer not received")
5036
5037     cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1,
5038                                            certs[0])
5039     cn = cert.get_subject().commonName
5040     logger.info("Server certificate CN=" + cn)
5041
5042     issuer = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1,
5043                                              certs[1])
5044     icn = issuer.get_subject().commonName
5045     logger.info("Issuer certificate CN=" + icn)
5046
5047     if cn != "server.w1.fi":
5048         raise Exception("Unexpected server certificate CN: " + cn)
5049     if icn != "Root CA":
5050         raise Exception("Unexpected server certificate issuer CN: " + icn)
5051
5052     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=0.1)
5053     if ev:
5054         raise Exception("Unexpected EAP-Success before external check result indication")
5055
5056     dev[0].request("CTRL-RSP-EXT_CERT_CHECK-" + id + ":good")
5057     dev[0].wait_connected()
5058
5059     dev[0].request("DISCONNECT")
5060     dev[0].wait_disconnected()
5061     if "FAIL" in dev[0].request("PMKSA_FLUSH"):
5062         raise Exception("PMKSA_FLUSH failed")
5063     dev[0].request("SET blob fast_pac_auth_ext ")
5064     dev[0].request("RECONNECT")
5065
5066     ev = dev[0].wait_event(["CTRL-REQ-EXT_CERT_CHECK"], timeout=10)
5067     if ev is None:
5068         raise Exception("No peer server certificate event seen (2)")
5069     id = ev.split(':')[0].split('-')[-1]
5070     dev[0].request("CTRL-RSP-EXT_CERT_CHECK-" + id + ":bad")
5071     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
5072     if ev is None:
5073         raise Exception("EAP-Failure not reported")
5074     dev[0].request("REMOVE_NETWORK all")
5075     dev[0].wait_disconnected()