tests: WPA2-Enterprise connection using EAP-TTLS/EAP-GTC (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_gtc_oom(dev, apdev):
1099     """WPA2-Enterprise connection using EAP-TTLS/EAP-GTC (OOM)"""
1100     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1101     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1102
1103     tests = [ "eap_gtc_init",
1104               "eap_msg_alloc;eap_gtc_process" ]
1105     for func in tests:
1106         with alloc_fail(dev[0], 1, func):
1107             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP",
1108                            scan_freq="2412",
1109                            eap="TTLS", identity="user",
1110                            anonymous_identity="ttls", password="password",
1111                            ca_cert="auth_serv/ca.pem", phase2="autheap=GTC",
1112                            wait_connect=False)
1113             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
1114             dev[0].request("REMOVE_NETWORK all")
1115             dev[0].wait_disconnected()
1116
1117 def test_ap_wpa2_eap_ttls_eap_md5(dev, apdev):
1118     """WPA2-Enterprise connection using EAP-TTLS/EAP-MD5"""
1119     check_eap_capa(dev[0], "MD5")
1120     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1121     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1122     eap_connect(dev[0], apdev[0], "TTLS", "user",
1123                 anonymous_identity="ttls", password="password",
1124                 ca_cert="auth_serv/ca.pem", phase2="autheap=MD5")
1125     hwsim_utils.test_connectivity(dev[0], hapd)
1126     eap_reauth(dev[0], "TTLS")
1127
1128 def test_ap_wpa2_eap_ttls_eap_md5_incorrect_password(dev, apdev):
1129     """WPA2-Enterprise connection using EAP-TTLS/EAP-MD5 - incorrect password"""
1130     check_eap_capa(dev[0], "MD5")
1131     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1132     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1133     eap_connect(dev[0], apdev[0], "TTLS", "user",
1134                 anonymous_identity="ttls", password="wrong",
1135                 ca_cert="auth_serv/ca.pem", phase2="autheap=MD5",
1136                 expect_failure=True)
1137
1138 def test_ap_wpa2_eap_ttls_eap_md5_no_password(dev, apdev):
1139     """WPA2-Enterprise connection using EAP-TTLS/EAP-MD5 - no password"""
1140     check_eap_capa(dev[0], "MD5")
1141     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1142     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1143     eap_connect(dev[0], apdev[0], "TTLS", "user-no-passwd",
1144                 anonymous_identity="ttls", password="password",
1145                 ca_cert="auth_serv/ca.pem", phase2="autheap=MD5",
1146                 expect_failure=True)
1147
1148 def test_ap_wpa2_eap_ttls_eap_md5_server_oom(dev, apdev):
1149     """WPA2-Enterprise connection using EAP-TTLS/EAP-MD5 - server OOM"""
1150     check_eap_capa(dev[0], "MD5")
1151     params = int_eap_server_params()
1152     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1153     with alloc_fail(hapd, 1, "eap_md5_init"):
1154         eap_connect(dev[0], apdev[0], "TTLS", "user",
1155                     anonymous_identity="ttls", password="password",
1156                     ca_cert="auth_serv/ca.pem", phase2="autheap=MD5",
1157                     expect_failure=True)
1158         dev[0].request("REMOVE_NETWORK all")
1159
1160     with alloc_fail(hapd, 1, "eap_md5_buildReq"):
1161         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
1162                        eap="TTLS", identity="user",
1163                        anonymous_identity="ttls", password="password",
1164                        ca_cert="auth_serv/ca.pem", phase2="autheap=MD5",
1165                        wait_connect=False, scan_freq="2412")
1166         # This would eventually time out, but we can stop after having reached
1167         # the allocation failure.
1168         for i in range(20):
1169             time.sleep(0.1)
1170             if hapd.request("GET_ALLOC_FAIL").startswith('0'):
1171                 break
1172
1173 def test_ap_wpa2_eap_ttls_eap_mschapv2(dev, apdev):
1174     """WPA2-Enterprise connection using EAP-TTLS/EAP-MSCHAPv2"""
1175     check_eap_capa(dev[0], "MSCHAPV2")
1176     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1177     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1178     eap_connect(dev[0], apdev[0], "TTLS", "user",
1179                 anonymous_identity="ttls", password="password",
1180                 ca_cert="auth_serv/ca.pem", phase2="autheap=MSCHAPV2")
1181     hwsim_utils.test_connectivity(dev[0], hapd)
1182     eap_reauth(dev[0], "TTLS")
1183
1184     logger.info("Negative test with incorrect password")
1185     dev[0].request("REMOVE_NETWORK all")
1186     eap_connect(dev[0], apdev[0], "TTLS", "user",
1187                 anonymous_identity="ttls", password="password1",
1188                 ca_cert="auth_serv/ca.pem", phase2="autheap=MSCHAPV2",
1189                 expect_failure=True)
1190
1191 def test_ap_wpa2_eap_ttls_eap_mschapv2_no_password(dev, apdev):
1192     """WPA2-Enterprise connection using EAP-TTLS/EAP-MSCHAPv2 - no password"""
1193     check_eap_capa(dev[0], "MSCHAPV2")
1194     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1195     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1196     eap_connect(dev[0], apdev[0], "TTLS", "user-no-passwd",
1197                 anonymous_identity="ttls", password="password",
1198                 ca_cert="auth_serv/ca.pem", phase2="autheap=MSCHAPV2",
1199                 expect_failure=True)
1200
1201 def test_ap_wpa2_eap_ttls_eap_mschapv2_server_oom(dev, apdev):
1202     """WPA2-Enterprise connection using EAP-TTLS/EAP-MSCHAPv2 - server OOM"""
1203     check_eap_capa(dev[0], "MSCHAPV2")
1204     params = int_eap_server_params()
1205     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1206     with alloc_fail(hapd, 1, "eap_mschapv2_init"):
1207         eap_connect(dev[0], apdev[0], "TTLS", "user",
1208                     anonymous_identity="ttls", password="password",
1209                     ca_cert="auth_serv/ca.pem", phase2="autheap=MSCHAPV2",
1210                     expect_failure=True)
1211         dev[0].request("REMOVE_NETWORK all")
1212
1213     with alloc_fail(hapd, 1, "eap_mschapv2_build_challenge"):
1214         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
1215                        eap="TTLS", identity="user",
1216                        anonymous_identity="ttls", password="password",
1217                        ca_cert="auth_serv/ca.pem", phase2="autheap=MSCHAPV2",
1218                        wait_connect=False, scan_freq="2412")
1219         # This would eventually time out, but we can stop after having reached
1220         # the allocation failure.
1221         for i in range(20):
1222             time.sleep(0.1)
1223             if hapd.request("GET_ALLOC_FAIL").startswith('0'):
1224                 break
1225         dev[0].request("REMOVE_NETWORK all")
1226
1227     with alloc_fail(hapd, 1, "eap_mschapv2_build_success_req"):
1228         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
1229                        eap="TTLS", identity="user",
1230                        anonymous_identity="ttls", password="password",
1231                        ca_cert="auth_serv/ca.pem", phase2="autheap=MSCHAPV2",
1232                        wait_connect=False, scan_freq="2412")
1233         # This would eventually time out, but we can stop after having reached
1234         # the allocation failure.
1235         for i in range(20):
1236             time.sleep(0.1)
1237             if hapd.request("GET_ALLOC_FAIL").startswith('0'):
1238                 break
1239         dev[0].request("REMOVE_NETWORK all")
1240
1241     with alloc_fail(hapd, 1, "eap_mschapv2_build_failure_req"):
1242         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
1243                        eap="TTLS", identity="user",
1244                        anonymous_identity="ttls", password="wrong",
1245                        ca_cert="auth_serv/ca.pem", phase2="autheap=MSCHAPV2",
1246                        wait_connect=False, scan_freq="2412")
1247         # This would eventually time out, but we can stop after having reached
1248         # the allocation failure.
1249         for i in range(20):
1250             time.sleep(0.1)
1251             if hapd.request("GET_ALLOC_FAIL").startswith('0'):
1252                 break
1253         dev[0].request("REMOVE_NETWORK all")
1254
1255 def test_ap_wpa2_eap_ttls_eap_aka(dev, apdev):
1256     """WPA2-Enterprise connection using EAP-TTLS/EAP-AKA"""
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], "TTLS", "0232010000000000",
1260                 anonymous_identity="0232010000000000@ttls",
1261                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123",
1262                 ca_cert="auth_serv/ca.pem", phase2="autheap=AKA")
1263
1264 def test_ap_wpa2_eap_peap_eap_aka(dev, apdev):
1265     """WPA2-Enterprise connection using EAP-PEAP/EAP-AKA"""
1266     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1267     hostapd.add_ap(apdev[0]['ifname'], params)
1268     eap_connect(dev[0], apdev[0], "PEAP", "0232010000000000",
1269                 anonymous_identity="0232010000000000@peap",
1270                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123",
1271                 ca_cert="auth_serv/ca.pem", phase2="auth=AKA")
1272
1273 def test_ap_wpa2_eap_fast_eap_aka(dev, apdev):
1274     """WPA2-Enterprise connection using EAP-FAST/EAP-AKA"""
1275     check_eap_capa(dev[0], "FAST")
1276     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1277     hostapd.add_ap(apdev[0]['ifname'], params)
1278     eap_connect(dev[0], apdev[0], "FAST", "0232010000000000",
1279                 anonymous_identity="0232010000000000@fast",
1280                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123",
1281                 phase1="fast_provisioning=2",
1282                 pac_file="blob://fast_pac_auth_aka",
1283                 ca_cert="auth_serv/ca.pem", phase2="auth=AKA")
1284
1285 def test_ap_wpa2_eap_peap_eap_mschapv2(dev, apdev):
1286     """WPA2-Enterprise connection using EAP-PEAP/EAP-MSCHAPv2"""
1287     check_eap_capa(dev[0], "MSCHAPV2")
1288     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1289     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1290     eap_connect(dev[0], apdev[0], "PEAP", "user",
1291                 anonymous_identity="peap", password="password",
1292                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
1293     hwsim_utils.test_connectivity(dev[0], hapd)
1294     eap_reauth(dev[0], "PEAP")
1295     dev[0].request("REMOVE_NETWORK all")
1296     eap_connect(dev[0], apdev[0], "PEAP", "user",
1297                 anonymous_identity="peap", password="password",
1298                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1299                 fragment_size="200")
1300
1301     logger.info("Password as hash value")
1302     dev[0].request("REMOVE_NETWORK all")
1303     eap_connect(dev[0], apdev[0], "PEAP", "user",
1304                 anonymous_identity="peap",
1305                 password_hex="hash:8846f7eaee8fb117ad06bdd830b7586c",
1306                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
1307
1308     logger.info("Negative test with incorrect password")
1309     dev[0].request("REMOVE_NETWORK all")
1310     eap_connect(dev[0], apdev[0], "PEAP", "user",
1311                 anonymous_identity="peap", password="password1",
1312                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1313                 expect_failure=True)
1314
1315 def test_ap_wpa2_eap_peap_eap_mschapv2_domain(dev, apdev):
1316     """WPA2-Enterprise connection using EAP-PEAP/EAP-MSCHAPv2 with domain"""
1317     check_eap_capa(dev[0], "MSCHAPV2")
1318     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1319     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1320     eap_connect(dev[0], apdev[0], "PEAP", "DOMAIN\user3",
1321                 anonymous_identity="peap", password="password",
1322                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
1323     hwsim_utils.test_connectivity(dev[0], hapd)
1324     eap_reauth(dev[0], "PEAP")
1325
1326 def test_ap_wpa2_eap_peap_eap_mschapv2_incorrect_password(dev, apdev):
1327     """WPA2-Enterprise connection using EAP-PEAP/EAP-MSCHAPv2 - incorrect password"""
1328     check_eap_capa(dev[0], "MSCHAPV2")
1329     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1330     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1331     eap_connect(dev[0], apdev[0], "PEAP", "user",
1332                 anonymous_identity="peap", password="wrong",
1333                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1334                 expect_failure=True)
1335
1336 def test_ap_wpa2_eap_peap_crypto_binding(dev, apdev):
1337     """WPA2-Enterprise connection using EAP-PEAPv0/EAP-MSCHAPv2 and crypto binding"""
1338     check_eap_capa(dev[0], "MSCHAPV2")
1339     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1340     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1341     eap_connect(dev[0], apdev[0], "PEAP", "user", password="password",
1342                 ca_cert="auth_serv/ca.pem",
1343                 phase1="peapver=0 crypto_binding=2",
1344                 phase2="auth=MSCHAPV2")
1345     hwsim_utils.test_connectivity(dev[0], hapd)
1346     eap_reauth(dev[0], "PEAP")
1347
1348     eap_connect(dev[1], apdev[0], "PEAP", "user", password="password",
1349                 ca_cert="auth_serv/ca.pem",
1350                 phase1="peapver=0 crypto_binding=1",
1351                 phase2="auth=MSCHAPV2")
1352     eap_connect(dev[2], apdev[0], "PEAP", "user", password="password",
1353                 ca_cert="auth_serv/ca.pem",
1354                 phase1="peapver=0 crypto_binding=0",
1355                 phase2="auth=MSCHAPV2")
1356
1357 def test_ap_wpa2_eap_peap_crypto_binding_server_oom(dev, apdev):
1358     """WPA2-Enterprise connection using EAP-PEAPv0/EAP-MSCHAPv2 and crypto binding with server OOM"""
1359     check_eap_capa(dev[0], "MSCHAPV2")
1360     params = int_eap_server_params()
1361     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1362     with alloc_fail(hapd, 1, "eap_mschapv2_getKey"):
1363         eap_connect(dev[0], apdev[0], "PEAP", "user", password="password",
1364                     ca_cert="auth_serv/ca.pem",
1365                     phase1="peapver=0 crypto_binding=2",
1366                     phase2="auth=MSCHAPV2",
1367                     expect_failure=True, local_error_report=True)
1368
1369 def test_ap_wpa2_eap_peap_params(dev, apdev):
1370     """WPA2-Enterprise connection using EAP-PEAPv0/EAP-MSCHAPv2 and various parameters"""
1371     check_eap_capa(dev[0], "MSCHAPV2")
1372     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1373     hostapd.add_ap(apdev[0]['ifname'], params)
1374     eap_connect(dev[0], apdev[0], "PEAP", "user",
1375                 anonymous_identity="peap", password="password",
1376                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1377                 phase1="peapver=0 peaplabel=1",
1378                 expect_failure=True)
1379     dev[0].request("REMOVE_NETWORK all")
1380     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PEAP",
1381                    identity="user",
1382                    anonymous_identity="peap", password="password",
1383                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1384                    phase1="peap_outer_success=0",
1385                    wait_connect=False, scan_freq="2412")
1386     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=15)
1387     if ev is None:
1388         raise Exception("No EAP success seen")
1389     # This won't succeed to connect with peap_outer_success=0, so stop here.
1390     dev[0].request("REMOVE_NETWORK all")
1391     dev[0].wait_disconnected()
1392     eap_connect(dev[1], apdev[0], "PEAP", "user", password="password",
1393                 ca_cert="auth_serv/ca.pem",
1394                 phase1="peap_outer_success=1",
1395                 phase2="auth=MSCHAPV2")
1396     eap_connect(dev[2], apdev[0], "PEAP", "user", password="password",
1397                 ca_cert="auth_serv/ca.pem",
1398                 phase1="peap_outer_success=2",
1399                 phase2="auth=MSCHAPV2")
1400     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PEAP",
1401                    identity="user",
1402                    anonymous_identity="peap", password="password",
1403                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1404                    phase1="peapver=1 peaplabel=1",
1405                    wait_connect=False, scan_freq="2412")
1406     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=15)
1407     if ev is None:
1408         raise Exception("No EAP success seen")
1409     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
1410     if ev is not None:
1411         raise Exception("Unexpected connection")
1412
1413     tests = [ ("peap-ver0", ""),
1414               ("peap-ver1", ""),
1415               ("peap-ver0", "peapver=0"),
1416               ("peap-ver1", "peapver=1") ]
1417     for anon,phase1 in tests:
1418         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PEAP",
1419                        identity="user", anonymous_identity=anon,
1420                        password="password", phase1=phase1,
1421                        ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1422                        scan_freq="2412")
1423         dev[0].request("REMOVE_NETWORK all")
1424         dev[0].wait_disconnected()
1425
1426     tests = [ ("peap-ver0", "peapver=1"),
1427               ("peap-ver1", "peapver=0") ]
1428     for anon,phase1 in tests:
1429         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PEAP",
1430                        identity="user", anonymous_identity=anon,
1431                        password="password", phase1=phase1,
1432                        ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1433                        wait_connect=False, scan_freq="2412")
1434         ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
1435         if ev is None:
1436             raise Exception("No EAP-Failure seen")
1437         dev[0].request("REMOVE_NETWORK all")
1438         dev[0].wait_disconnected()
1439
1440     eap_connect(dev[0], apdev[0], "PEAP", "user", password="password",
1441                 ca_cert="auth_serv/ca.pem",
1442                 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",
1443                 phase2="auth=MSCHAPV2")
1444
1445 def test_ap_wpa2_eap_peap_eap_tls(dev, apdev):
1446     """WPA2-Enterprise connection using EAP-PEAP/EAP-TLS"""
1447     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1448     hostapd.add_ap(apdev[0]['ifname'], params)
1449     eap_connect(dev[0], apdev[0], "PEAP", "cert user",
1450                 ca_cert="auth_serv/ca.pem", phase2="auth=TLS",
1451                 ca_cert2="auth_serv/ca.pem",
1452                 client_cert2="auth_serv/user.pem",
1453                 private_key2="auth_serv/user.key")
1454     eap_reauth(dev[0], "PEAP")
1455
1456 def test_ap_wpa2_eap_tls(dev, apdev):
1457     """WPA2-Enterprise connection using EAP-TLS"""
1458     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1459     hostapd.add_ap(apdev[0]['ifname'], params)
1460     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
1461                 client_cert="auth_serv/user.pem",
1462                 private_key="auth_serv/user.key")
1463     eap_reauth(dev[0], "TLS")
1464
1465 def test_eap_tls_pkcs8_pkcs5_v2_des3(dev, apdev):
1466     """WPA2-Enterprise connection using EAP-TLS and PKCS #8, PKCS #5 v2 DES3 key"""
1467     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1468     hostapd.add_ap(apdev[0]['ifname'], params)
1469     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
1470                 client_cert="auth_serv/user.pem",
1471                 private_key="auth_serv/user.key.pkcs8",
1472                 private_key_passwd="whatever")
1473
1474 def test_eap_tls_pkcs8_pkcs5_v15(dev, apdev):
1475     """WPA2-Enterprise connection using EAP-TLS and PKCS #8, PKCS #5 v1.5 key"""
1476     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1477     hostapd.add_ap(apdev[0]['ifname'], params)
1478     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
1479                 client_cert="auth_serv/user.pem",
1480                 private_key="auth_serv/user.key.pkcs8.pkcs5v15",
1481                 private_key_passwd="whatever")
1482
1483 def test_ap_wpa2_eap_tls_blob(dev, apdev):
1484     """WPA2-Enterprise connection using EAP-TLS and config blobs"""
1485     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1486     hostapd.add_ap(apdev[0]['ifname'], params)
1487     cert = read_pem("auth_serv/ca.pem")
1488     if "OK" not in dev[0].request("SET blob cacert " + cert.encode("hex")):
1489         raise Exception("Could not set cacert blob")
1490     cert = read_pem("auth_serv/user.pem")
1491     if "OK" not in dev[0].request("SET blob usercert " + cert.encode("hex")):
1492         raise Exception("Could not set usercert blob")
1493     key = read_pem("auth_serv/user.rsa-key")
1494     if "OK" not in dev[0].request("SET blob userkey " + key.encode("hex")):
1495         raise Exception("Could not set cacert blob")
1496     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="blob://cacert",
1497                 client_cert="blob://usercert",
1498                 private_key="blob://userkey")
1499
1500 def test_ap_wpa2_eap_tls_blob_missing(dev, apdev):
1501     """EAP-TLS and config blob missing"""
1502     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1503     hostapd.add_ap(apdev[0]['ifname'], params)
1504     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
1505                    identity="tls user",
1506                    ca_cert="blob://testing-blob-does-not-exist",
1507                    client_cert="blob://testing-blob-does-not-exist",
1508                    private_key="blob://testing-blob-does-not-exist",
1509                    wait_connect=False, scan_freq="2412")
1510     ev = dev[0].wait_event(["EAP: Failed to initialize EAP method"], timeout=10)
1511     if ev is None:
1512         raise Exception("EAP failure not reported")
1513     dev[0].request("REMOVE_NETWORK all")
1514     dev[0].wait_disconnected()
1515
1516 def test_ap_wpa2_eap_tls_with_tls_len(dev, apdev):
1517     """EAP-TLS and TLS Message Length in unfragmented packets"""
1518     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1519     hostapd.add_ap(apdev[0]['ifname'], params)
1520     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
1521                 phase1="include_tls_length=1",
1522                 client_cert="auth_serv/user.pem",
1523                 private_key="auth_serv/user.key")
1524
1525 def test_ap_wpa2_eap_tls_pkcs12(dev, apdev):
1526     """WPA2-Enterprise connection using EAP-TLS and PKCS#12"""
1527     check_pkcs12_support(dev[0])
1528     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1529     hostapd.add_ap(apdev[0]['ifname'], params)
1530     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
1531                 private_key="auth_serv/user.pkcs12",
1532                 private_key_passwd="whatever")
1533     dev[0].request("REMOVE_NETWORK all")
1534     dev[0].wait_disconnected()
1535
1536     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
1537                    identity="tls user",
1538                    ca_cert="auth_serv/ca.pem",
1539                    private_key="auth_serv/user.pkcs12",
1540                    wait_connect=False, scan_freq="2412")
1541     ev = dev[0].wait_event(["CTRL-REQ-PASSPHRASE"])
1542     if ev is None:
1543         raise Exception("Request for private key passphrase timed out")
1544     id = ev.split(':')[0].split('-')[-1]
1545     dev[0].request("CTRL-RSP-PASSPHRASE-" + id + ":whatever")
1546     dev[0].wait_connected(timeout=10)
1547     dev[0].request("REMOVE_NETWORK all")
1548     dev[0].wait_disconnected()
1549
1550     # Run this twice to verify certificate chain handling with OpenSSL. Use two
1551     # different files to cover both cases of the extra certificate being the
1552     # one that signed the client certificate and it being unrelated to the
1553     # client certificate.
1554     for pkcs12 in "auth_serv/user2.pkcs12", "auth_serv/user3.pkcs12":
1555         for i in range(2):
1556             eap_connect(dev[0], apdev[0], "TLS", "tls user",
1557                         ca_cert="auth_serv/ca.pem",
1558                         private_key=pkcs12,
1559                         private_key_passwd="whatever")
1560             dev[0].request("REMOVE_NETWORK all")
1561             dev[0].wait_disconnected()
1562
1563 def test_ap_wpa2_eap_tls_pkcs12_blob(dev, apdev):
1564     """WPA2-Enterprise connection using EAP-TLS and PKCS#12 from configuration blob"""
1565     check_pkcs12_support(dev[0])
1566     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1567     hostapd.add_ap(apdev[0]['ifname'], params)
1568     cert = read_pem("auth_serv/ca.pem")
1569     if "OK" not in dev[0].request("SET blob cacert " + cert.encode("hex")):
1570         raise Exception("Could not set cacert blob")
1571     with open("auth_serv/user.pkcs12", "rb") as f:
1572         if "OK" not in dev[0].request("SET blob pkcs12 " + f.read().encode("hex")):
1573             raise Exception("Could not set pkcs12 blob")
1574     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="blob://cacert",
1575                 private_key="blob://pkcs12",
1576                 private_key_passwd="whatever")
1577
1578 def test_ap_wpa2_eap_tls_neg_incorrect_trust_root(dev, apdev):
1579     """WPA2-Enterprise negative test - incorrect trust root"""
1580     check_eap_capa(dev[0], "MSCHAPV2")
1581     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1582     hostapd.add_ap(apdev[0]['ifname'], params)
1583     cert = read_pem("auth_serv/ca-incorrect.pem")
1584     if "OK" not in dev[0].request("SET blob cacert " + cert.encode("hex")):
1585         raise Exception("Could not set cacert blob")
1586     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
1587                    identity="DOMAIN\mschapv2 user", anonymous_identity="ttls",
1588                    password="password", phase2="auth=MSCHAPV2",
1589                    ca_cert="blob://cacert",
1590                    wait_connect=False, scan_freq="2412")
1591     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
1592                    identity="DOMAIN\mschapv2 user", anonymous_identity="ttls",
1593                    password="password", phase2="auth=MSCHAPV2",
1594                    ca_cert="auth_serv/ca-incorrect.pem",
1595                    wait_connect=False, scan_freq="2412")
1596
1597     for dev in (dev[0], dev[1]):
1598         ev = dev.wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
1599         if ev is None:
1600             raise Exception("Association and EAP start timed out")
1601
1602         ev = dev.wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=10)
1603         if ev is None:
1604             raise Exception("EAP method selection timed out")
1605         if "TTLS" not in ev:
1606             raise Exception("Unexpected EAP method")
1607
1608         ev = dev.wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR",
1609                              "CTRL-EVENT-EAP-SUCCESS",
1610                              "CTRL-EVENT-EAP-FAILURE",
1611                              "CTRL-EVENT-CONNECTED",
1612                              "CTRL-EVENT-DISCONNECTED"], timeout=10)
1613         if ev is None:
1614             raise Exception("EAP result timed out")
1615         if "CTRL-EVENT-EAP-TLS-CERT-ERROR" not in ev:
1616             raise Exception("TLS certificate error not reported")
1617
1618         ev = dev.wait_event(["CTRL-EVENT-EAP-SUCCESS",
1619                              "CTRL-EVENT-EAP-FAILURE",
1620                              "CTRL-EVENT-CONNECTED",
1621                              "CTRL-EVENT-DISCONNECTED"], timeout=10)
1622         if ev is None:
1623             raise Exception("EAP result(2) timed out")
1624         if "CTRL-EVENT-EAP-FAILURE" not in ev:
1625             raise Exception("EAP failure not reported")
1626
1627         ev = dev.wait_event(["CTRL-EVENT-CONNECTED",
1628                              "CTRL-EVENT-DISCONNECTED"], timeout=10)
1629         if ev is None:
1630             raise Exception("EAP result(3) timed out")
1631         if "CTRL-EVENT-DISCONNECTED" not in ev:
1632             raise Exception("Disconnection not reported")
1633
1634         ev = dev.wait_event(["CTRL-EVENT-SSID-TEMP-DISABLED"], timeout=10)
1635         if ev is None:
1636             raise Exception("Network block disabling not reported")
1637
1638 def test_ap_wpa2_eap_tls_diff_ca_trust(dev, apdev):
1639     """WPA2-Enterprise connection using EAP-TTLS/PAP and different CA trust"""
1640     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1641     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1642     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
1643                    identity="pap user", anonymous_identity="ttls",
1644                    password="password", phase2="auth=PAP",
1645                    ca_cert="auth_serv/ca.pem",
1646                    wait_connect=True, scan_freq="2412")
1647     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
1648                         identity="pap user", anonymous_identity="ttls",
1649                         password="password", phase2="auth=PAP",
1650                         ca_cert="auth_serv/ca-incorrect.pem",
1651                         only_add_network=True, scan_freq="2412")
1652
1653     dev[0].request("DISCONNECT")
1654     dev[0].wait_disconnected()
1655     dev[0].dump_monitor()
1656     dev[0].select_network(id, freq="2412")
1657
1658     ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD vendor=0 method=21"], timeout=15)
1659     if ev is None:
1660         raise Exception("EAP-TTLS not re-started")
1661     
1662     ev = dev[0].wait_disconnected(timeout=15)
1663     if "reason=23" not in ev:
1664         raise Exception("Proper reason code for disconnection not reported")
1665
1666 def test_ap_wpa2_eap_tls_diff_ca_trust2(dev, apdev):
1667     """WPA2-Enterprise connection using EAP-TTLS/PAP and different CA trust"""
1668     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1669     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1670     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
1671                    identity="pap user", anonymous_identity="ttls",
1672                    password="password", phase2="auth=PAP",
1673                    wait_connect=True, scan_freq="2412")
1674     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
1675                         identity="pap user", anonymous_identity="ttls",
1676                         password="password", phase2="auth=PAP",
1677                         ca_cert="auth_serv/ca-incorrect.pem",
1678                         only_add_network=True, scan_freq="2412")
1679
1680     dev[0].request("DISCONNECT")
1681     dev[0].wait_disconnected()
1682     dev[0].dump_monitor()
1683     dev[0].select_network(id, freq="2412")
1684
1685     ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD vendor=0 method=21"], timeout=15)
1686     if ev is None:
1687         raise Exception("EAP-TTLS not re-started")
1688     
1689     ev = dev[0].wait_disconnected(timeout=15)
1690     if "reason=23" not in ev:
1691         raise Exception("Proper reason code for disconnection not reported")
1692
1693 def test_ap_wpa2_eap_tls_diff_ca_trust3(dev, apdev):
1694     """WPA2-Enterprise connection using EAP-TTLS/PAP and different CA trust"""
1695     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1696     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1697     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
1698                         identity="pap user", anonymous_identity="ttls",
1699                         password="password", phase2="auth=PAP",
1700                         ca_cert="auth_serv/ca.pem",
1701                         wait_connect=True, scan_freq="2412")
1702     dev[0].request("DISCONNECT")
1703     dev[0].wait_disconnected()
1704     dev[0].dump_monitor()
1705     dev[0].set_network_quoted(id, "ca_cert", "auth_serv/ca-incorrect.pem")
1706     dev[0].select_network(id, freq="2412")
1707
1708     ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD vendor=0 method=21"], timeout=15)
1709     if ev is None:
1710         raise Exception("EAP-TTLS not re-started")
1711     
1712     ev = dev[0].wait_disconnected(timeout=15)
1713     if "reason=23" not in ev:
1714         raise Exception("Proper reason code for disconnection not reported")
1715
1716 def test_ap_wpa2_eap_tls_neg_suffix_match(dev, apdev):
1717     """WPA2-Enterprise negative test - domain suffix mismatch"""
1718     check_domain_suffix_match(dev[0])
1719     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1720     hostapd.add_ap(apdev[0]['ifname'], params)
1721     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
1722                    identity="DOMAIN\mschapv2 user", anonymous_identity="ttls",
1723                    password="password", phase2="auth=MSCHAPV2",
1724                    ca_cert="auth_serv/ca.pem",
1725                    domain_suffix_match="incorrect.example.com",
1726                    wait_connect=False, scan_freq="2412")
1727
1728     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
1729     if ev is None:
1730         raise Exception("Association and EAP start timed out")
1731
1732     ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=10)
1733     if ev is None:
1734         raise Exception("EAP method selection timed out")
1735     if "TTLS" not in ev:
1736         raise Exception("Unexpected EAP method")
1737
1738     ev = dev[0].wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR",
1739                             "CTRL-EVENT-EAP-SUCCESS",
1740                             "CTRL-EVENT-EAP-FAILURE",
1741                             "CTRL-EVENT-CONNECTED",
1742                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
1743     if ev is None:
1744         raise Exception("EAP result timed out")
1745     if "CTRL-EVENT-EAP-TLS-CERT-ERROR" not in ev:
1746         raise Exception("TLS certificate error not reported")
1747     if "Domain suffix mismatch" not in ev:
1748         raise Exception("Domain suffix mismatch not reported")
1749
1750     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS",
1751                             "CTRL-EVENT-EAP-FAILURE",
1752                             "CTRL-EVENT-CONNECTED",
1753                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
1754     if ev is None:
1755         raise Exception("EAP result(2) timed out")
1756     if "CTRL-EVENT-EAP-FAILURE" not in ev:
1757         raise Exception("EAP failure not reported")
1758
1759     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
1760                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
1761     if ev is None:
1762         raise Exception("EAP result(3) timed out")
1763     if "CTRL-EVENT-DISCONNECTED" not in ev:
1764         raise Exception("Disconnection not reported")
1765
1766     ev = dev[0].wait_event(["CTRL-EVENT-SSID-TEMP-DISABLED"], timeout=10)
1767     if ev is None:
1768         raise Exception("Network block disabling not reported")
1769
1770 def test_ap_wpa2_eap_tls_neg_domain_match(dev, apdev):
1771     """WPA2-Enterprise negative test - domain mismatch"""
1772     check_domain_match(dev[0])
1773     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1774     hostapd.add_ap(apdev[0]['ifname'], params)
1775     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
1776                    identity="DOMAIN\mschapv2 user", anonymous_identity="ttls",
1777                    password="password", phase2="auth=MSCHAPV2",
1778                    ca_cert="auth_serv/ca.pem",
1779                    domain_match="w1.fi",
1780                    wait_connect=False, scan_freq="2412")
1781
1782     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
1783     if ev is None:
1784         raise Exception("Association and EAP start timed out")
1785
1786     ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=10)
1787     if ev is None:
1788         raise Exception("EAP method selection timed out")
1789     if "TTLS" not in ev:
1790         raise Exception("Unexpected EAP method")
1791
1792     ev = dev[0].wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR",
1793                             "CTRL-EVENT-EAP-SUCCESS",
1794                             "CTRL-EVENT-EAP-FAILURE",
1795                             "CTRL-EVENT-CONNECTED",
1796                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
1797     if ev is None:
1798         raise Exception("EAP result timed out")
1799     if "CTRL-EVENT-EAP-TLS-CERT-ERROR" not in ev:
1800         raise Exception("TLS certificate error not reported")
1801     if "Domain mismatch" not in ev:
1802         raise Exception("Domain mismatch not reported")
1803
1804     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS",
1805                             "CTRL-EVENT-EAP-FAILURE",
1806                             "CTRL-EVENT-CONNECTED",
1807                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
1808     if ev is None:
1809         raise Exception("EAP result(2) timed out")
1810     if "CTRL-EVENT-EAP-FAILURE" not in ev:
1811         raise Exception("EAP failure not reported")
1812
1813     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
1814                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
1815     if ev is None:
1816         raise Exception("EAP result(3) timed out")
1817     if "CTRL-EVENT-DISCONNECTED" not in ev:
1818         raise Exception("Disconnection not reported")
1819
1820     ev = dev[0].wait_event(["CTRL-EVENT-SSID-TEMP-DISABLED"], timeout=10)
1821     if ev is None:
1822         raise Exception("Network block disabling not reported")
1823
1824 def test_ap_wpa2_eap_tls_neg_subject_match(dev, apdev):
1825     """WPA2-Enterprise negative test - subject mismatch"""
1826     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1827     hostapd.add_ap(apdev[0]['ifname'], params)
1828     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
1829                    identity="DOMAIN\mschapv2 user", anonymous_identity="ttls",
1830                    password="password", phase2="auth=MSCHAPV2",
1831                    ca_cert="auth_serv/ca.pem",
1832                    subject_match="/C=FI/O=w1.fi/CN=example.com",
1833                    wait_connect=False, scan_freq="2412")
1834
1835     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
1836     if ev is None:
1837         raise Exception("Association and EAP start timed out")
1838
1839     ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD",
1840                             "EAP: Failed to initialize EAP method"], timeout=10)
1841     if ev is None:
1842         raise Exception("EAP method selection timed out")
1843     if "EAP: Failed to initialize EAP method" in ev:
1844         tls = dev[0].request("GET tls_library")
1845         if tls.startswith("OpenSSL"):
1846             raise Exception("Failed to select EAP method")
1847         logger.info("subject_match not supported - connection failed, so test succeeded")
1848         return
1849     if "TTLS" not in ev:
1850         raise Exception("Unexpected EAP method")
1851
1852     ev = dev[0].wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR",
1853                             "CTRL-EVENT-EAP-SUCCESS",
1854                             "CTRL-EVENT-EAP-FAILURE",
1855                             "CTRL-EVENT-CONNECTED",
1856                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
1857     if ev is None:
1858         raise Exception("EAP result timed out")
1859     if "CTRL-EVENT-EAP-TLS-CERT-ERROR" not in ev:
1860         raise Exception("TLS certificate error not reported")
1861     if "Subject mismatch" not in ev:
1862         raise Exception("Subject mismatch not reported")
1863
1864     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS",
1865                             "CTRL-EVENT-EAP-FAILURE",
1866                             "CTRL-EVENT-CONNECTED",
1867                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
1868     if ev is None:
1869         raise Exception("EAP result(2) timed out")
1870     if "CTRL-EVENT-EAP-FAILURE" not in ev:
1871         raise Exception("EAP failure not reported")
1872
1873     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
1874                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
1875     if ev is None:
1876         raise Exception("EAP result(3) timed out")
1877     if "CTRL-EVENT-DISCONNECTED" not in ev:
1878         raise Exception("Disconnection not reported")
1879
1880     ev = dev[0].wait_event(["CTRL-EVENT-SSID-TEMP-DISABLED"], timeout=10)
1881     if ev is None:
1882         raise Exception("Network block disabling not reported")
1883
1884 def test_ap_wpa2_eap_tls_neg_altsubject_match(dev, apdev):
1885     """WPA2-Enterprise negative test - altsubject mismatch"""
1886     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1887     hostapd.add_ap(apdev[0]['ifname'], params)
1888
1889     tests = [ "incorrect.example.com",
1890               "DNS:incorrect.example.com",
1891               "DNS:w1.fi",
1892               "DNS:erver.w1.fi" ]
1893     for match in tests:
1894         _test_ap_wpa2_eap_tls_neg_altsubject_match(dev, apdev, match)
1895
1896 def _test_ap_wpa2_eap_tls_neg_altsubject_match(dev, apdev, match):
1897     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
1898                    identity="DOMAIN\mschapv2 user", anonymous_identity="ttls",
1899                    password="password", phase2="auth=MSCHAPV2",
1900                    ca_cert="auth_serv/ca.pem",
1901                    altsubject_match=match,
1902                    wait_connect=False, scan_freq="2412")
1903
1904     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
1905     if ev is None:
1906         raise Exception("Association and EAP start timed out")
1907
1908     ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD",
1909                             "EAP: Failed to initialize EAP method"], timeout=10)
1910     if ev is None:
1911         raise Exception("EAP method selection timed out")
1912     if "EAP: Failed to initialize EAP method" in ev:
1913         tls = dev[0].request("GET tls_library")
1914         if tls.startswith("OpenSSL"):
1915             raise Exception("Failed to select EAP method")
1916         logger.info("altsubject_match not supported - connection failed, so test succeeded")
1917         return
1918     if "TTLS" not in ev:
1919         raise Exception("Unexpected EAP method")
1920
1921     ev = dev[0].wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR",
1922                             "CTRL-EVENT-EAP-SUCCESS",
1923                             "CTRL-EVENT-EAP-FAILURE",
1924                             "CTRL-EVENT-CONNECTED",
1925                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
1926     if ev is None:
1927         raise Exception("EAP result timed out")
1928     if "CTRL-EVENT-EAP-TLS-CERT-ERROR" not in ev:
1929         raise Exception("TLS certificate error not reported")
1930     if "AltSubject mismatch" not in ev:
1931         raise Exception("altsubject mismatch not reported")
1932
1933     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS",
1934                             "CTRL-EVENT-EAP-FAILURE",
1935                             "CTRL-EVENT-CONNECTED",
1936                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
1937     if ev is None:
1938         raise Exception("EAP result(2) timed out")
1939     if "CTRL-EVENT-EAP-FAILURE" not in ev:
1940         raise Exception("EAP failure not reported")
1941
1942     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
1943                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
1944     if ev is None:
1945         raise Exception("EAP result(3) timed out")
1946     if "CTRL-EVENT-DISCONNECTED" not in ev:
1947         raise Exception("Disconnection not reported")
1948
1949     ev = dev[0].wait_event(["CTRL-EVENT-SSID-TEMP-DISABLED"], timeout=10)
1950     if ev is None:
1951         raise Exception("Network block disabling not reported")
1952
1953     dev[0].request("REMOVE_NETWORK all")
1954
1955 def test_ap_wpa2_eap_unauth_tls(dev, apdev):
1956     """WPA2-Enterprise connection using UNAUTH-TLS"""
1957     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1958     hostapd.add_ap(apdev[0]['ifname'], params)
1959     eap_connect(dev[0], apdev[0], "UNAUTH-TLS", "unauth-tls",
1960                 ca_cert="auth_serv/ca.pem")
1961     eap_reauth(dev[0], "UNAUTH-TLS")
1962
1963 def test_ap_wpa2_eap_ttls_server_cert_hash(dev, apdev):
1964     """WPA2-Enterprise connection using EAP-TTLS and server certificate hash"""
1965     check_cert_probe_support(dev[0])
1966     skip_with_fips(dev[0])
1967     srv_cert_hash = "e75bd454c7b02d312e5006d75067c28ffa5baea422effeb2bbd572179cd000ca"
1968     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1969     hostapd.add_ap(apdev[0]['ifname'], params)
1970     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
1971                    identity="probe", ca_cert="probe://",
1972                    wait_connect=False, scan_freq="2412")
1973     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
1974     if ev is None:
1975         raise Exception("Association and EAP start timed out")
1976     ev = dev[0].wait_event(["CTRL-EVENT-EAP-PEER-CERT depth=0"], timeout=10)
1977     if ev is None:
1978         raise Exception("No peer server certificate event seen")
1979     if "hash=" + srv_cert_hash not in ev:
1980         raise Exception("Expected server certificate hash not reported")
1981     ev = dev[0].wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR"], timeout=10)
1982     if ev is None:
1983         raise Exception("EAP result timed out")
1984     if "Server certificate chain probe" not in ev:
1985         raise Exception("Server certificate probe not reported")
1986     dev[0].wait_disconnected(timeout=10)
1987     dev[0].request("REMOVE_NETWORK all")
1988
1989     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
1990                    identity="DOMAIN\mschapv2 user", anonymous_identity="ttls",
1991                    password="password", phase2="auth=MSCHAPV2",
1992                    ca_cert="hash://server/sha256/5a1bc1296205e6fdbe3979728efe3920798885c1c4590b5f90f43222d239ca6a",
1993                    wait_connect=False, scan_freq="2412")
1994     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
1995     if ev is None:
1996         raise Exception("Association and EAP start timed out")
1997     ev = dev[0].wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR"], timeout=10)
1998     if ev is None:
1999         raise Exception("EAP result timed out")
2000     if "Server certificate mismatch" not in ev:
2001         raise Exception("Server certificate mismatch not reported")
2002     dev[0].wait_disconnected(timeout=10)
2003     dev[0].request("REMOVE_NETWORK all")
2004
2005     eap_connect(dev[0], apdev[0], "TTLS", "DOMAIN\mschapv2 user",
2006                 anonymous_identity="ttls", password="password",
2007                 ca_cert="hash://server/sha256/" + srv_cert_hash,
2008                 phase2="auth=MSCHAPV2")
2009
2010 def test_ap_wpa2_eap_ttls_server_cert_hash_invalid(dev, apdev):
2011     """WPA2-Enterprise connection using EAP-TTLS and server certificate hash (invalid config)"""
2012     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2013     hostapd.add_ap(apdev[0]['ifname'], params)
2014     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
2015                    identity="DOMAIN\mschapv2 user", anonymous_identity="ttls",
2016                    password="password", phase2="auth=MSCHAPV2",
2017                    ca_cert="hash://server/md5/5a1bc1296205e6fdbe3979728efe3920798885c1c4590b5f90f43222d239ca6a",
2018                    wait_connect=False, scan_freq="2412")
2019     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
2020                    identity="DOMAIN\mschapv2 user", anonymous_identity="ttls",
2021                    password="password", phase2="auth=MSCHAPV2",
2022                    ca_cert="hash://server/sha256/5a1bc1296205e6fdbe3979728efe3920798885c1c4590b5f90f43222d239ca",
2023                    wait_connect=False, scan_freq="2412")
2024     dev[2].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
2025                    identity="DOMAIN\mschapv2 user", anonymous_identity="ttls",
2026                    password="password", phase2="auth=MSCHAPV2",
2027                    ca_cert="hash://server/sha256/5a1bc1296205e6fdbe3979728efe3920798885c1c4590b5f90f43222d239ca6Q",
2028                    wait_connect=False, scan_freq="2412")
2029     for i in range(0, 3):
2030         ev = dev[i].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
2031         if ev is None:
2032             raise Exception("Association and EAP start timed out")
2033         ev = dev[i].wait_event(["EAP: Failed to initialize EAP method: vendor 0 method 21 (TTLS)"], timeout=5)
2034         if ev is None:
2035             raise Exception("Did not report EAP method initialization failure")
2036
2037 def test_ap_wpa2_eap_pwd(dev, apdev):
2038     """WPA2-Enterprise connection using EAP-pwd"""
2039     check_eap_capa(dev[0], "PWD")
2040     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2041     hostapd.add_ap(apdev[0]['ifname'], params)
2042     eap_connect(dev[0], apdev[0], "PWD", "pwd user", password="secret password")
2043     eap_reauth(dev[0], "PWD")
2044     dev[0].request("REMOVE_NETWORK all")
2045
2046     eap_connect(dev[1], apdev[0], "PWD",
2047                 "pwd.user@test123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890.example.com",
2048                 password="secret password",
2049                 fragment_size="90")
2050
2051     logger.info("Negative test with incorrect password")
2052     eap_connect(dev[2], apdev[0], "PWD", "pwd user", password="secret-password",
2053                 expect_failure=True, local_error_report=True)
2054
2055     eap_connect(dev[0], apdev[0], "PWD",
2056                 "pwd.user@test123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890.example.com",
2057                 password="secret password",
2058                 fragment_size="31")
2059
2060 def test_ap_wpa2_eap_pwd_nthash(dev, apdev):
2061     """WPA2-Enterprise connection using EAP-pwd and NTHash"""
2062     check_eap_capa(dev[0], "PWD")
2063     skip_with_fips(dev[0])
2064     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2065     hostapd.add_ap(apdev[0]['ifname'], params)
2066     eap_connect(dev[0], apdev[0], "PWD", "pwd-hash", password="secret password")
2067     eap_connect(dev[1], apdev[0], "PWD", "pwd-hash",
2068                 password_hex="hash:e3718ece8ab74792cbbfffd316d2d19a")
2069     eap_connect(dev[2], apdev[0], "PWD", "pwd user",
2070                 password_hex="hash:e3718ece8ab74792cbbfffd316d2d19a",
2071                 expect_failure=True, local_error_report=True)
2072
2073 def test_ap_wpa2_eap_pwd_groups(dev, apdev):
2074     """WPA2-Enterprise connection using various EAP-pwd groups"""
2075     check_eap_capa(dev[0], "PWD")
2076     tls = dev[0].request("GET tls_library")
2077     params = { "ssid": "test-wpa2-eap", "wpa": "2", "wpa_key_mgmt": "WPA-EAP",
2078                "rsn_pairwise": "CCMP", "ieee8021x": "1",
2079                "eap_server": "1", "eap_user_file": "auth_serv/eap_user.conf" }
2080     groups = [ 19, 20, 21, 25, 26 ]
2081     if tls.startswith("OpenSSL") and "build=OpenSSL 1.0.2" in tls and "run=OpenSSL 1.0.2" in tls:
2082         logger.info("Add Brainpool EC groups since OpenSSL is new enough")
2083         groups += [ 27, 28, 29, 30 ]
2084     for i in groups:
2085         logger.info("Group %d" % i)
2086         params['pwd_group'] = str(i)
2087         hostapd.add_ap(apdev[0]['ifname'], params)
2088         try:
2089             eap_connect(dev[0], apdev[0], "PWD", "pwd user",
2090                         password="secret password")
2091             dev[0].request("REMOVE_NETWORK all")
2092             dev[0].wait_disconnected()
2093             dev[0].dump_monitor()
2094         except:
2095             if "BoringSSL" in tls and i in [ 25 ]:
2096                 logger.info("Ignore connection failure with group %d with BoringSSL" % i)
2097                 dev[0].request("DISCONNECT")
2098                 time.sleep(0.1)
2099                 dev[0].request("REMOVE_NETWORK all")
2100                 dev[0].dump_monitor()
2101                 continue
2102             raise
2103
2104 def test_ap_wpa2_eap_pwd_invalid_group(dev, apdev):
2105     """WPA2-Enterprise connection using invalid EAP-pwd group"""
2106     check_eap_capa(dev[0], "PWD")
2107     params = { "ssid": "test-wpa2-eap", "wpa": "2", "wpa_key_mgmt": "WPA-EAP",
2108                "rsn_pairwise": "CCMP", "ieee8021x": "1",
2109                "eap_server": "1", "eap_user_file": "auth_serv/eap_user.conf" }
2110     params['pwd_group'] = "0"
2111     hostapd.add_ap(apdev[0]['ifname'], params)
2112     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PWD",
2113                    identity="pwd user", password="secret password",
2114                    scan_freq="2412", wait_connect=False)
2115     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
2116     if ev is None:
2117         raise Exception("Timeout on EAP failure report")
2118
2119 def test_ap_wpa2_eap_pwd_as_frag(dev, apdev):
2120     """WPA2-Enterprise connection using EAP-pwd with server fragmentation"""
2121     check_eap_capa(dev[0], "PWD")
2122     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2123     params = { "ssid": "test-wpa2-eap", "wpa": "2", "wpa_key_mgmt": "WPA-EAP",
2124                "rsn_pairwise": "CCMP", "ieee8021x": "1",
2125                "eap_server": "1", "eap_user_file": "auth_serv/eap_user.conf",
2126                "pwd_group": "19", "fragment_size": "40" }
2127     hostapd.add_ap(apdev[0]['ifname'], params)
2128     eap_connect(dev[0], apdev[0], "PWD", "pwd user", password="secret password")
2129
2130 def test_ap_wpa2_eap_gpsk(dev, apdev):
2131     """WPA2-Enterprise connection using EAP-GPSK"""
2132     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2133     hostapd.add_ap(apdev[0]['ifname'], params)
2134     id = eap_connect(dev[0], apdev[0], "GPSK", "gpsk user",
2135                      password="abcdefghijklmnop0123456789abcdef")
2136     eap_reauth(dev[0], "GPSK")
2137
2138     logger.info("Test forced algorithm selection")
2139     for phase1 in [ "cipher=1", "cipher=2" ]:
2140         dev[0].set_network_quoted(id, "phase1", phase1)
2141         ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
2142         if ev is None:
2143             raise Exception("EAP success timed out")
2144         dev[0].wait_connected(timeout=10)
2145
2146     logger.info("Test failed algorithm negotiation")
2147     dev[0].set_network_quoted(id, "phase1", "cipher=9")
2148     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
2149     if ev is None:
2150         raise Exception("EAP failure timed out")
2151
2152     logger.info("Negative test with incorrect password")
2153     dev[0].request("REMOVE_NETWORK all")
2154     eap_connect(dev[0], apdev[0], "GPSK", "gpsk user",
2155                 password="ffcdefghijklmnop0123456789abcdef",
2156                 expect_failure=True)
2157
2158 def test_ap_wpa2_eap_sake(dev, apdev):
2159     """WPA2-Enterprise connection using EAP-SAKE"""
2160     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2161     hostapd.add_ap(apdev[0]['ifname'], params)
2162     eap_connect(dev[0], apdev[0], "SAKE", "sake user",
2163                 password_hex="0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef")
2164     eap_reauth(dev[0], "SAKE")
2165
2166     logger.info("Negative test with incorrect password")
2167     dev[0].request("REMOVE_NETWORK all")
2168     eap_connect(dev[0], apdev[0], "SAKE", "sake user",
2169                 password_hex="ff23456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
2170                 expect_failure=True)
2171
2172 def test_ap_wpa2_eap_eke(dev, apdev):
2173     """WPA2-Enterprise connection using EAP-EKE"""
2174     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2175     hostapd.add_ap(apdev[0]['ifname'], params)
2176     id = eap_connect(dev[0], apdev[0], "EKE", "eke user", password="hello")
2177     eap_reauth(dev[0], "EKE")
2178
2179     logger.info("Test forced algorithm selection")
2180     for phase1 in [ "dhgroup=5 encr=1 prf=2 mac=2",
2181                     "dhgroup=4 encr=1 prf=2 mac=2",
2182                     "dhgroup=3 encr=1 prf=2 mac=2",
2183                     "dhgroup=3 encr=1 prf=1 mac=1" ]:
2184         dev[0].set_network_quoted(id, "phase1", phase1)
2185         ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
2186         if ev is None:
2187             raise Exception("EAP success timed out")
2188         dev[0].wait_connected(timeout=10)
2189
2190     logger.info("Test failed algorithm negotiation")
2191     dev[0].set_network_quoted(id, "phase1", "dhgroup=9 encr=9 prf=9 mac=9")
2192     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
2193     if ev is None:
2194         raise Exception("EAP failure timed out")
2195
2196     logger.info("Negative test with incorrect password")
2197     dev[0].request("REMOVE_NETWORK all")
2198     eap_connect(dev[0], apdev[0], "EKE", "eke user", password="hello1",
2199                 expect_failure=True)
2200
2201 def test_ap_wpa2_eap_eke_many(dev, apdev, params):
2202     """WPA2-Enterprise connection using EAP-EKE (many connections) [long]"""
2203     if not params['long']:
2204         raise HwsimSkip("Skip test case with long duration due to --long not specified")
2205     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2206     hostapd.add_ap(apdev[0]['ifname'], params)
2207     success = 0
2208     fail = 0
2209     for i in range(100):
2210         for j in range(3):
2211             dev[j].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="EKE",
2212                            identity="eke user", password="hello",
2213                            phase1="dhgroup=3 encr=1 prf=1 mac=1",
2214                            scan_freq="2412", wait_connect=False)
2215         for j in range(3):
2216             ev = dev[j].wait_event(["CTRL-EVENT-CONNECTED",
2217                                     "CTRL-EVENT-DISCONNECTED"], timeout=15)
2218             if ev is None:
2219                 raise Exception("No connected/disconnected event")
2220             if "CTRL-EVENT-DISCONNECTED" in ev:
2221                 fail += 1
2222                 # The RADIUS server limits on active sessions can be hit when
2223                 # going through this test case, so try to give some more time
2224                 # for the server to remove sessions.
2225                 logger.info("Failed to connect i=%d j=%d" % (i, j))
2226                 dev[j].request("REMOVE_NETWORK all")
2227                 time.sleep(1)
2228             else:
2229                 success += 1
2230                 dev[j].request("REMOVE_NETWORK all")
2231                 dev[j].wait_disconnected()
2232             dev[j].dump_monitor()
2233     logger.info("Total success=%d failure=%d" % (success, fail))
2234
2235 def test_ap_wpa2_eap_eke_serverid_nai(dev, apdev):
2236     """WPA2-Enterprise connection using EAP-EKE with serverid NAI"""
2237     params = int_eap_server_params()
2238     params['server_id'] = 'example.server@w1.fi'
2239     hostapd.add_ap(apdev[0]['ifname'], params)
2240     eap_connect(dev[0], apdev[0], "EKE", "eke user", password="hello")
2241
2242 def test_ap_wpa2_eap_eke_server_oom(dev, apdev):
2243     """WPA2-Enterprise connection using EAP-EKE with server OOM"""
2244     params = int_eap_server_params()
2245     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
2246     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2247
2248     for count,func in [ (1, "eap_eke_build_commit"),
2249                         (2, "eap_eke_build_commit"),
2250                         (3, "eap_eke_build_commit"),
2251                         (1, "eap_eke_build_confirm"),
2252                         (2, "eap_eke_build_confirm"),
2253                         (1, "eap_eke_process_commit"),
2254                         (2, "eap_eke_process_commit"),
2255                         (1, "eap_eke_process_confirm"),
2256                         (1, "eap_eke_process_identity"),
2257                         (2, "eap_eke_process_identity"),
2258                         (3, "eap_eke_process_identity"),
2259                         (4, "eap_eke_process_identity") ]:
2260         with alloc_fail(hapd, count, func):
2261             eap_connect(dev[0], apdev[0], "EKE", "eke user", password="hello",
2262                         expect_failure=True)
2263             dev[0].request("REMOVE_NETWORK all")
2264
2265     for count,func,pw in [ (1, "eap_eke_init", "hello"),
2266                            (1, "eap_eke_get_session_id", "hello"),
2267                            (1, "eap_eke_getKey", "hello"),
2268                            (1, "eap_eke_build_msg", "hello"),
2269                            (1, "eap_eke_build_failure", "wrong"),
2270                            (1, "eap_eke_build_identity", "hello"),
2271                            (2, "eap_eke_build_identity", "hello") ]:
2272         with alloc_fail(hapd, count, func):
2273             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
2274                            eap="EKE", identity="eke user", password=pw,
2275                            wait_connect=False, scan_freq="2412")
2276             # This would eventually time out, but we can stop after having
2277             # reached the allocation failure.
2278             for i in range(20):
2279                 time.sleep(0.1)
2280                 if hapd.request("GET_ALLOC_FAIL").startswith('0'):
2281                     break
2282             dev[0].request("REMOVE_NETWORK all")
2283
2284     for count in range(1, 1000):
2285         try:
2286             with alloc_fail(hapd, count, "eap_server_sm_step"):
2287                 dev[0].connect("test-wpa2-eap",
2288                                key_mgmt="WPA-EAP WPA-EAP-SHA256",
2289                                eap="EKE", identity="eke user", password=pw,
2290                                wait_connect=False, scan_freq="2412")
2291                 # This would eventually time out, but we can stop after having
2292                 # reached the allocation failure.
2293                 for i in range(10):
2294                     time.sleep(0.1)
2295                     if hapd.request("GET_ALLOC_FAIL").startswith('0'):
2296                         break
2297                 dev[0].request("REMOVE_NETWORK all")
2298         except Exception, e:
2299             if str(e) == "Allocation failure did not trigger":
2300                 if count < 30:
2301                     raise Exception("Too few allocation failures")
2302                 logger.info("%d allocation failures tested" % (count - 1))
2303                 break
2304             raise e
2305
2306 def test_ap_wpa2_eap_ikev2(dev, apdev):
2307     """WPA2-Enterprise connection using EAP-IKEv2"""
2308     check_eap_capa(dev[0], "IKEV2")
2309     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2310     hostapd.add_ap(apdev[0]['ifname'], params)
2311     eap_connect(dev[0], apdev[0], "IKEV2", "ikev2 user",
2312                 password="ike password")
2313     eap_reauth(dev[0], "IKEV2")
2314     dev[0].request("REMOVE_NETWORK all")
2315     eap_connect(dev[0], apdev[0], "IKEV2", "ikev2 user",
2316                 password="ike password", fragment_size="50")
2317
2318     logger.info("Negative test with incorrect password")
2319     dev[0].request("REMOVE_NETWORK all")
2320     eap_connect(dev[0], apdev[0], "IKEV2", "ikev2 user",
2321                 password="ike-password", expect_failure=True)
2322
2323 def test_ap_wpa2_eap_ikev2_as_frag(dev, apdev):
2324     """WPA2-Enterprise connection using EAP-IKEv2 with server fragmentation"""
2325     check_eap_capa(dev[0], "IKEV2")
2326     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2327     params = { "ssid": "test-wpa2-eap", "wpa": "2", "wpa_key_mgmt": "WPA-EAP",
2328                "rsn_pairwise": "CCMP", "ieee8021x": "1",
2329                "eap_server": "1", "eap_user_file": "auth_serv/eap_user.conf",
2330                "fragment_size": "50" }
2331     hostapd.add_ap(apdev[0]['ifname'], params)
2332     eap_connect(dev[0], apdev[0], "IKEV2", "ikev2 user",
2333                 password="ike password")
2334     eap_reauth(dev[0], "IKEV2")
2335
2336 def test_ap_wpa2_eap_ikev2_oom(dev, apdev):
2337     """WPA2-Enterprise connection using EAP-IKEv2 and OOM"""
2338     check_eap_capa(dev[0], "IKEV2")
2339     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2340     hostapd.add_ap(apdev[0]['ifname'], params)
2341
2342     tests = [ (1, "dh_init"),
2343               (2, "dh_init"),
2344               (1, "dh_derive_shared") ]
2345     for count, func in tests:
2346         with alloc_fail(dev[0], count, func):
2347             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="IKEV2",
2348                            identity="ikev2 user", password="ike password",
2349                            wait_connect=False, scan_freq="2412")
2350             ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=5)
2351             if ev is None:
2352                 raise Exception("EAP method not selected")
2353             for i in range(10):
2354                 if "0:" in dev[0].request("GET_ALLOC_FAIL"):
2355                     break
2356                 time.sleep(0.02)
2357             dev[0].request("REMOVE_NETWORK all")
2358
2359     tests = [ (1, "os_get_random;dh_init") ]
2360     for count, func in tests:
2361         with fail_test(dev[0], count, func):
2362             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="IKEV2",
2363                            identity="ikev2 user", password="ike password",
2364                            wait_connect=False, scan_freq="2412")
2365             ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=5)
2366             if ev is None:
2367                 raise Exception("EAP method not selected")
2368             for i in range(10):
2369                 if "0:" in dev[0].request("GET_FAIL"):
2370                     break
2371                 time.sleep(0.02)
2372             dev[0].request("REMOVE_NETWORK all")
2373
2374 def test_ap_wpa2_eap_pax(dev, apdev):
2375     """WPA2-Enterprise connection using EAP-PAX"""
2376     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2377     hostapd.add_ap(apdev[0]['ifname'], params)
2378     eap_connect(dev[0], apdev[0], "PAX", "pax.user@example.com",
2379                 password_hex="0123456789abcdef0123456789abcdef")
2380     eap_reauth(dev[0], "PAX")
2381
2382     logger.info("Negative test with incorrect password")
2383     dev[0].request("REMOVE_NETWORK all")
2384     eap_connect(dev[0], apdev[0], "PAX", "pax.user@example.com",
2385                 password_hex="ff23456789abcdef0123456789abcdef",
2386                 expect_failure=True)
2387
2388 def test_ap_wpa2_eap_psk(dev, apdev):
2389     """WPA2-Enterprise connection using EAP-PSK"""
2390     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2391     params["wpa_key_mgmt"] = "WPA-EAP-SHA256"
2392     params["ieee80211w"] = "2"
2393     hostapd.add_ap(apdev[0]['ifname'], params)
2394     eap_connect(dev[0], apdev[0], "PSK", "psk.user@example.com",
2395                 password_hex="0123456789abcdef0123456789abcdef", sha256=True)
2396     eap_reauth(dev[0], "PSK", sha256=True)
2397     check_mib(dev[0], [ ("dot11RSNAAuthenticationSuiteRequested", "00-0f-ac-5"),
2398                         ("dot11RSNAAuthenticationSuiteSelected", "00-0f-ac-5") ])
2399
2400     bss = dev[0].get_bss(apdev[0]['bssid'])
2401     if 'flags' not in bss:
2402         raise Exception("Could not get BSS flags from BSS table")
2403     if "[WPA2-EAP-SHA256-CCMP]" not in bss['flags']:
2404         raise Exception("Unexpected BSS flags: " + bss['flags'])
2405
2406     logger.info("Negative test with incorrect password")
2407     dev[0].request("REMOVE_NETWORK all")
2408     eap_connect(dev[0], apdev[0], "PSK", "psk.user@example.com",
2409                 password_hex="ff23456789abcdef0123456789abcdef", sha256=True,
2410                 expect_failure=True)
2411
2412 def test_ap_wpa2_eap_psk_oom(dev, apdev):
2413     """WPA2-Enterprise connection using EAP-PSK and OOM"""
2414     skip_with_fips(dev[0])
2415     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2416     hostapd.add_ap(apdev[0]['ifname'], params)
2417     tests = [ (1, "aes_128_ctr_encrypt;aes_128_eax_encrypt"),
2418               (1, "omac1_aes_128;aes_128_eax_encrypt"),
2419               (2, "omac1_aes_128;aes_128_eax_encrypt"),
2420               (3, "omac1_aes_128;aes_128_eax_encrypt"),
2421               (1, "=aes_128_eax_encrypt"),
2422               (1, "omac1_aes_vector"),
2423               (1, "aes_128_ctr_encrypt;aes_128_eax_decrypt"),
2424               (1, "omac1_aes_128;aes_128_eax_decrypt"),
2425               (2, "omac1_aes_128;aes_128_eax_decrypt"),
2426               (3, "omac1_aes_128;aes_128_eax_decrypt"),
2427               (1, "=aes_128_eax_decrypt") ]
2428     for count, func in tests:
2429         with alloc_fail(dev[0], count, func):
2430             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PSK",
2431                            identity="psk.user@example.com",
2432                            password_hex="0123456789abcdef0123456789abcdef",
2433                            wait_connect=False, scan_freq="2412")
2434             ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=5)
2435             if ev is None:
2436                 raise Exception("EAP method not selected")
2437             for i in range(10):
2438                 if "0:" in dev[0].request("GET_ALLOC_FAIL"):
2439                     break
2440                 time.sleep(0.02)
2441             dev[0].request("REMOVE_NETWORK all")
2442
2443     with alloc_fail(dev[0], 1, "aes_128_encrypt_block"):
2444             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PSK",
2445                            identity="psk.user@example.com",
2446                            password_hex="0123456789abcdef0123456789abcdef",
2447                            wait_connect=False, scan_freq="2412")
2448             ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
2449             if ev is None:
2450                 raise Exception("EAP method failure not reported")
2451             dev[0].request("REMOVE_NETWORK all")
2452
2453 def test_ap_wpa_eap_peap_eap_mschapv2(dev, apdev):
2454     """WPA-Enterprise connection using EAP-PEAP/EAP-MSCHAPv2"""
2455     check_eap_capa(dev[0], "MSCHAPV2")
2456     params = hostapd.wpa_eap_params(ssid="test-wpa-eap")
2457     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
2458     dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="PEAP",
2459                    identity="user", password="password", phase2="auth=MSCHAPV2",
2460                    ca_cert="auth_serv/ca.pem", wait_connect=False,
2461                    scan_freq="2412")
2462     eap_check_auth(dev[0], "PEAP", True, rsn=False)
2463     hwsim_utils.test_connectivity(dev[0], hapd)
2464     eap_reauth(dev[0], "PEAP", rsn=False)
2465     check_mib(dev[0], [ ("dot11RSNAAuthenticationSuiteRequested", "00-50-f2-1"),
2466                         ("dot11RSNAAuthenticationSuiteSelected", "00-50-f2-1") ])
2467     status = dev[0].get_status(extra="VERBOSE")
2468     if 'portControl' not in status:
2469         raise Exception("portControl missing from STATUS-VERBOSE")
2470     if status['portControl'] != 'Auto':
2471         raise Exception("Unexpected portControl value: " + status['portControl'])
2472     if 'eap_session_id' not in status:
2473         raise Exception("eap_session_id missing from STATUS-VERBOSE")
2474     if not status['eap_session_id'].startswith("19"):
2475         raise Exception("Unexpected eap_session_id value: " + status['eap_session_id'])
2476
2477 def test_ap_wpa2_eap_interactive(dev, apdev):
2478     """WPA2-Enterprise connection using interactive identity/password entry"""
2479     check_eap_capa(dev[0], "MSCHAPV2")
2480     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2481     hostapd.add_ap(apdev[0]['ifname'], params)
2482     hapd = hostapd.Hostapd(apdev[0]['ifname'])
2483
2484     tests = [ ("Connection with dynamic TTLS/MSCHAPv2 password entry",
2485                "TTLS", "ttls", "DOMAIN\mschapv2 user", "auth=MSCHAPV2",
2486                None, "password"),
2487               ("Connection with dynamic TTLS/MSCHAPv2 identity and password entry",
2488                "TTLS", "ttls", None, "auth=MSCHAPV2",
2489                "DOMAIN\mschapv2 user", "password"),
2490               ("Connection with dynamic TTLS/EAP-MSCHAPv2 password entry",
2491                "TTLS", "ttls", "user", "autheap=MSCHAPV2", None, "password"),
2492               ("Connection with dynamic TTLS/EAP-MD5 password entry",
2493                "TTLS", "ttls", "user", "autheap=MD5", None, "password"),
2494               ("Connection with dynamic PEAP/EAP-MSCHAPv2 password entry",
2495                "PEAP", None, "user", "auth=MSCHAPV2", None, "password"),
2496               ("Connection with dynamic PEAP/EAP-GTC password entry",
2497                "PEAP", None, "user", "auth=GTC", None, "password") ]
2498     for [desc,eap,anon,identity,phase2,req_id,req_pw] in tests:
2499         logger.info(desc)
2500         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap=eap,
2501                        anonymous_identity=anon, identity=identity,
2502                        ca_cert="auth_serv/ca.pem", phase2=phase2,
2503                        wait_connect=False, scan_freq="2412")
2504         if req_id:
2505             ev = dev[0].wait_event(["CTRL-REQ-IDENTITY"])
2506             if ev is None:
2507                 raise Exception("Request for identity timed out")
2508             id = ev.split(':')[0].split('-')[-1]
2509             dev[0].request("CTRL-RSP-IDENTITY-" + id + ":" + req_id)
2510         ev = dev[0].wait_event(["CTRL-REQ-PASSWORD","CTRL-REQ-OTP"])
2511         if ev is None:
2512             raise Exception("Request for password timed out")
2513         id = ev.split(':')[0].split('-')[-1]
2514         type = "OTP" if "CTRL-REQ-OTP" in ev else "PASSWORD"
2515         dev[0].request("CTRL-RSP-" + type + "-" + id + ":" + req_pw)
2516         dev[0].wait_connected(timeout=10)
2517         dev[0].request("REMOVE_NETWORK all")
2518
2519 def test_ap_wpa2_eap_ext_enable_network_while_connected(dev, apdev):
2520     """WPA2-Enterprise interactive identity entry and ENABLE_NETWORK"""
2521     check_eap_capa(dev[0], "MSCHAPV2")
2522     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2523     hostapd.add_ap(apdev[0]['ifname'], params)
2524     hapd = hostapd.Hostapd(apdev[0]['ifname'])
2525
2526     id_other = dev[0].connect("other", key_mgmt="NONE", scan_freq="2412",
2527                               only_add_network=True)
2528
2529     req_id = "DOMAIN\mschapv2 user"
2530     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
2531                    anonymous_identity="ttls", identity=None,
2532                    password="password",
2533                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2534                    wait_connect=False, scan_freq="2412")
2535     ev = dev[0].wait_event(["CTRL-REQ-IDENTITY"])
2536     if ev is None:
2537         raise Exception("Request for identity timed out")
2538     id = ev.split(':')[0].split('-')[-1]
2539     dev[0].request("CTRL-RSP-IDENTITY-" + id + ":" + req_id)
2540     dev[0].wait_connected(timeout=10)
2541
2542     if "OK" not in dev[0].request("ENABLE_NETWORK " + str(id_other)):
2543         raise Exception("Failed to enable network")
2544     ev = dev[0].wait_event(["SME: Trying to authenticate"], timeout=1)
2545     if ev is not None:
2546         raise Exception("Unexpected reconnection attempt on ENABLE_NETWORK")
2547     dev[0].request("REMOVE_NETWORK all")
2548
2549 def test_ap_wpa2_eap_vendor_test(dev, apdev):
2550     """WPA2-Enterprise connection using EAP vendor test"""
2551     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2552     hostapd.add_ap(apdev[0]['ifname'], params)
2553     eap_connect(dev[0], apdev[0], "VENDOR-TEST", "vendor-test")
2554     eap_reauth(dev[0], "VENDOR-TEST")
2555     eap_connect(dev[1], apdev[0], "VENDOR-TEST", "vendor-test",
2556                 password="pending")
2557
2558 def test_ap_wpa2_eap_vendor_test_oom(dev, apdev):
2559     """WPA2-Enterprise connection using EAP vendor test (OOM)"""
2560     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2561     hostapd.add_ap(apdev[0]['ifname'], params)
2562
2563     tests = [ "eap_vendor_test_init",
2564               "eap_msg_alloc;eap_vendor_test_process",
2565               "eap_vendor_test_getKey" ]
2566     for func in tests:
2567         with alloc_fail(dev[0], 1, func):
2568             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP",
2569                            scan_freq="2412",
2570                            eap="VENDOR-TEST", identity="vendor-test",
2571                            wait_connect=False)
2572             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
2573             dev[0].request("REMOVE_NETWORK all")
2574             dev[0].wait_disconnected()
2575
2576 def test_ap_wpa2_eap_fast_mschapv2_unauth_prov(dev, apdev):
2577     """WPA2-Enterprise connection using EAP-FAST/MSCHAPv2 and unauthenticated provisioning"""
2578     check_eap_capa(dev[0], "FAST")
2579     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2580     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
2581     eap_connect(dev[0], apdev[0], "FAST", "user",
2582                 anonymous_identity="FAST", password="password",
2583                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2584                 phase1="fast_provisioning=1", pac_file="blob://fast_pac")
2585     hwsim_utils.test_connectivity(dev[0], hapd)
2586     res = eap_reauth(dev[0], "FAST")
2587     if res['tls_session_reused'] != '1':
2588         raise Exception("EAP-FAST could not use PAC session ticket")
2589
2590 def test_ap_wpa2_eap_fast_pac_file(dev, apdev, params):
2591     """WPA2-Enterprise connection using EAP-FAST/MSCHAPv2 and PAC file"""
2592     check_eap_capa(dev[0], "FAST")
2593     pac_file = os.path.join(params['logdir'], "fast.pac")
2594     pac_file2 = os.path.join(params['logdir'], "fast-bin.pac")
2595     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2596     hostapd.add_ap(apdev[0]['ifname'], params)
2597
2598     try:
2599         eap_connect(dev[0], apdev[0], "FAST", "user",
2600                     anonymous_identity="FAST", password="password",
2601                     ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2602                     phase1="fast_provisioning=1", pac_file=pac_file)
2603         with open(pac_file, "r") as f:
2604             data = f.read()
2605             if "wpa_supplicant EAP-FAST PAC file - version 1" not in data:
2606                 raise Exception("PAC file header missing")
2607             if "PAC-Key=" not in data:
2608                 raise Exception("PAC-Key missing from PAC file")
2609         dev[0].request("REMOVE_NETWORK all")
2610         eap_connect(dev[0], apdev[0], "FAST", "user",
2611                     anonymous_identity="FAST", password="password",
2612                     ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2613                     pac_file=pac_file)
2614
2615         eap_connect(dev[1], apdev[0], "FAST", "user",
2616                     anonymous_identity="FAST", password="password",
2617                     ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2618                     phase1="fast_provisioning=1 fast_pac_format=binary",
2619                     pac_file=pac_file2)
2620         dev[1].request("REMOVE_NETWORK all")
2621         eap_connect(dev[1], apdev[0], "FAST", "user",
2622                     anonymous_identity="FAST", password="password",
2623                     ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2624                     phase1="fast_pac_format=binary",
2625                     pac_file=pac_file2)
2626     finally:
2627         try:
2628             os.remove(pac_file)
2629         except:
2630             pass
2631         try:
2632             os.remove(pac_file2)
2633         except:
2634             pass
2635
2636 def test_ap_wpa2_eap_fast_binary_pac(dev, apdev):
2637     """WPA2-Enterprise connection using EAP-FAST and binary PAC format"""
2638     check_eap_capa(dev[0], "FAST")
2639     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2640     hostapd.add_ap(apdev[0]['ifname'], params)
2641     eap_connect(dev[0], apdev[0], "FAST", "user",
2642                 anonymous_identity="FAST", password="password",
2643                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2644                 phase1="fast_provisioning=1 fast_max_pac_list_len=1 fast_pac_format=binary",
2645                 pac_file="blob://fast_pac_bin")
2646     res = eap_reauth(dev[0], "FAST")
2647     if res['tls_session_reused'] != '1':
2648         raise Exception("EAP-FAST could not use PAC session ticket")
2649
2650 def test_ap_wpa2_eap_fast_missing_pac_config(dev, apdev):
2651     """WPA2-Enterprise connection using EAP-FAST and missing PAC config"""
2652     check_eap_capa(dev[0], "FAST")
2653     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2654     hostapd.add_ap(apdev[0]['ifname'], params)
2655
2656     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
2657                    identity="user", anonymous_identity="FAST",
2658                    password="password",
2659                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2660                    pac_file="blob://fast_pac_not_in_use",
2661                    wait_connect=False, scan_freq="2412")
2662     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
2663     if ev is None:
2664         raise Exception("Timeout on EAP failure report")
2665     dev[0].request("REMOVE_NETWORK all")
2666
2667     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
2668                    identity="user", anonymous_identity="FAST",
2669                    password="password",
2670                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2671                    wait_connect=False, scan_freq="2412")
2672     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
2673     if ev is None:
2674         raise Exception("Timeout on EAP failure report")
2675
2676 def test_ap_wpa2_eap_fast_gtc_auth_prov(dev, apdev):
2677     """WPA2-Enterprise connection using EAP-FAST/GTC and authenticated provisioning"""
2678     check_eap_capa(dev[0], "FAST")
2679     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2680     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
2681     eap_connect(dev[0], apdev[0], "FAST", "user",
2682                 anonymous_identity="FAST", password="password",
2683                 ca_cert="auth_serv/ca.pem", phase2="auth=GTC",
2684                 phase1="fast_provisioning=2", pac_file="blob://fast_pac_auth")
2685     hwsim_utils.test_connectivity(dev[0], hapd)
2686     res = eap_reauth(dev[0], "FAST")
2687     if res['tls_session_reused'] != '1':
2688         raise Exception("EAP-FAST could not use PAC session ticket")
2689
2690 def test_ap_wpa2_eap_fast_gtc_identity_change(dev, apdev):
2691     """WPA2-Enterprise connection using EAP-FAST/GTC and identity changing"""
2692     check_eap_capa(dev[0], "FAST")
2693     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2694     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
2695     id = eap_connect(dev[0], apdev[0], "FAST", "user",
2696                      anonymous_identity="FAST", password="password",
2697                      ca_cert="auth_serv/ca.pem", phase2="auth=GTC",
2698                      phase1="fast_provisioning=2",
2699                      pac_file="blob://fast_pac_auth")
2700     dev[0].set_network_quoted(id, "identity", "user2")
2701     dev[0].wait_disconnected()
2702     ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=15)
2703     if ev is None:
2704         raise Exception("EAP-FAST not started")
2705     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
2706     if ev is None:
2707         raise Exception("EAP failure not reported")
2708     dev[0].wait_disconnected()
2709
2710 def test_ap_wpa2_eap_fast_prf_oom(dev, apdev):
2711     """WPA2-Enterprise connection using EAP-FAST and OOM in PRF"""
2712     check_eap_capa(dev[0], "FAST")
2713     tls = dev[0].request("GET tls_library")
2714     if tls.startswith("OpenSSL"):
2715         func = "openssl_tls_prf"
2716         count = 2
2717     elif tls.startswith("internal"):
2718         func = "tls_connection_prf"
2719         count = 1
2720     else:
2721         raise HwsimSkip("Unsupported TLS library")
2722     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2723     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
2724     with alloc_fail(dev[0], count, func):
2725         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
2726                        identity="user", anonymous_identity="FAST",
2727                        password="password", ca_cert="auth_serv/ca.pem",
2728                        phase2="auth=GTC",
2729                        phase1="fast_provisioning=2",
2730                        pac_file="blob://fast_pac_auth",
2731                        wait_connect=False, scan_freq="2412")
2732         ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
2733         if ev is None:
2734             raise Exception("EAP failure not reported")
2735     dev[0].request("DISCONNECT")
2736
2737 def test_ap_wpa2_eap_fast_server_oom(dev, apdev):
2738     """EAP-FAST/MSCHAPv2 and server OOM"""
2739     check_eap_capa(dev[0], "FAST")
2740
2741     params = int_eap_server_params()
2742     params['dh_file'] = 'auth_serv/dh.conf'
2743     params['pac_opaque_encr_key'] = '000102030405060708090a0b0c0d0e0f'
2744     params['eap_fast_a_id'] = '1011'
2745     params['eap_fast_a_id_info'] = 'another test server'
2746     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
2747
2748     with alloc_fail(hapd, 1, "tls_session_ticket_ext_cb"):
2749         id = eap_connect(dev[0], apdev[0], "FAST", "user",
2750                          anonymous_identity="FAST", password="password",
2751                          ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2752                          phase1="fast_provisioning=1",
2753                          pac_file="blob://fast_pac",
2754                          expect_failure=True)
2755         ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
2756         if ev is None:
2757             raise Exception("No EAP failure reported")
2758         dev[0].wait_disconnected()
2759         dev[0].request("DISCONNECT")
2760
2761     dev[0].select_network(id, freq="2412")
2762
2763 def test_ap_wpa2_eap_fast_cipher_suites(dev, apdev):
2764     """EAP-FAST and different TLS cipher suites"""
2765     check_eap_capa(dev[0], "FAST")
2766     tls = dev[0].request("GET tls_library")
2767     if not tls.startswith("OpenSSL"):
2768         raise HwsimSkip("TLS library is not OpenSSL: " + tls)
2769
2770     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2771     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
2772
2773     dev[0].request("SET blob fast_pac_ciphers ")
2774     eap_connect(dev[0], apdev[0], "FAST", "user",
2775                 anonymous_identity="FAST", password="password",
2776                 ca_cert="auth_serv/ca.pem", phase2="auth=GTC",
2777                 phase1="fast_provisioning=2",
2778                 pac_file="blob://fast_pac_ciphers")
2779     res = dev[0].get_status_field('EAP TLS cipher')
2780     dev[0].request("REMOVE_NETWORK all")
2781     dev[0].wait_disconnected()
2782     if res != "DHE-RSA-AES256-SHA":
2783         raise Exception("Unexpected cipher suite for provisioning: " + res)
2784
2785     tests = [ "DHE-RSA-AES128-SHA",
2786               "RC4-SHA",
2787               "AES128-SHA",
2788               "AES256-SHA",
2789               "DHE-RSA-AES256-SHA" ]
2790     for cipher in tests:
2791         eap_connect(dev[0], apdev[0], "FAST", "user",
2792                     openssl_ciphers=cipher,
2793                     anonymous_identity="FAST", password="password",
2794                     ca_cert="auth_serv/ca.pem", phase2="auth=GTC",
2795                     pac_file="blob://fast_pac_ciphers")
2796         res = dev[0].get_status_field('EAP TLS cipher')
2797         dev[0].request("REMOVE_NETWORK all")
2798         dev[0].wait_disconnected()
2799         if res != cipher:
2800             raise Exception("Unexpected TLS cipher info (configured %s): %s" % (cipher, res))
2801
2802 def test_ap_wpa2_eap_tls_ocsp(dev, apdev):
2803     """WPA2-Enterprise connection using EAP-TLS and verifying OCSP"""
2804     check_ocsp_support(dev[0])
2805     check_pkcs12_support(dev[0])
2806     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2807     hostapd.add_ap(apdev[0]['ifname'], params)
2808     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
2809                 private_key="auth_serv/user.pkcs12",
2810                 private_key_passwd="whatever", ocsp=2)
2811
2812 def test_ap_wpa2_eap_tls_ocsp_multi(dev, apdev):
2813     """WPA2-Enterprise connection using EAP-TLS and verifying OCSP-multi"""
2814     check_ocsp_multi_support(dev[0])
2815     check_pkcs12_support(dev[0])
2816
2817     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2818     hostapd.add_ap(apdev[0]['ifname'], params)
2819     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
2820                 private_key="auth_serv/user.pkcs12",
2821                 private_key_passwd="whatever", ocsp=2)
2822
2823 def int_eap_server_params():
2824     params = { "ssid": "test-wpa2-eap", "wpa": "2", "wpa_key_mgmt": "WPA-EAP",
2825                "rsn_pairwise": "CCMP", "ieee8021x": "1",
2826                "eap_server": "1", "eap_user_file": "auth_serv/eap_user.conf",
2827                "ca_cert": "auth_serv/ca.pem",
2828                "server_cert": "auth_serv/server.pem",
2829                "private_key": "auth_serv/server.key",
2830                "dh_file": "auth_serv/dh.conf" }
2831     return params
2832
2833 def test_ap_wpa2_eap_tls_ocsp_key_id(dev, apdev, params):
2834     """EAP-TLS and OCSP certificate signed OCSP response using key ID"""
2835     check_ocsp_support(dev[0])
2836     ocsp = os.path.join(params['logdir'], "ocsp-server-cache-key-id.der")
2837     if not os.path.exists(ocsp):
2838         raise HwsimSkip("No OCSP response available")
2839     params = int_eap_server_params()
2840     params["ocsp_stapling_response"] = ocsp
2841     hostapd.add_ap(apdev[0]['ifname'], params)
2842     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
2843                    identity="tls user", ca_cert="auth_serv/ca.pem",
2844                    private_key="auth_serv/user.pkcs12",
2845                    private_key_passwd="whatever", ocsp=2,
2846                    scan_freq="2412")
2847
2848 def test_ap_wpa2_eap_tls_ocsp_ca_signed_good(dev, apdev, params):
2849     """EAP-TLS and CA signed OCSP response (good)"""
2850     check_ocsp_support(dev[0])
2851     ocsp = os.path.join(params['logdir'], "ocsp-resp-ca-signed.der")
2852     if not os.path.exists(ocsp):
2853         raise HwsimSkip("No OCSP response available")
2854     params = int_eap_server_params()
2855     params["ocsp_stapling_response"] = ocsp
2856     hostapd.add_ap(apdev[0]['ifname'], params)
2857     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
2858                    identity="tls user", ca_cert="auth_serv/ca.pem",
2859                    private_key="auth_serv/user.pkcs12",
2860                    private_key_passwd="whatever", ocsp=2,
2861                    scan_freq="2412")
2862
2863 def test_ap_wpa2_eap_tls_ocsp_ca_signed_revoked(dev, apdev, params):
2864     """EAP-TLS and CA signed OCSP response (revoked)"""
2865     check_ocsp_support(dev[0])
2866     ocsp = os.path.join(params['logdir'], "ocsp-resp-ca-signed-revoked.der")
2867     if not os.path.exists(ocsp):
2868         raise HwsimSkip("No OCSP response available")
2869     params = int_eap_server_params()
2870     params["ocsp_stapling_response"] = ocsp
2871     hostapd.add_ap(apdev[0]['ifname'], params)
2872     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
2873                    identity="tls user", ca_cert="auth_serv/ca.pem",
2874                    private_key="auth_serv/user.pkcs12",
2875                    private_key_passwd="whatever", ocsp=2,
2876                    wait_connect=False, scan_freq="2412")
2877     count = 0
2878     while True:
2879         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
2880         if ev is None:
2881             raise Exception("Timeout on EAP status")
2882         if 'bad certificate status response' in ev:
2883             break
2884         if 'certificate revoked' in ev:
2885             break
2886         count = count + 1
2887         if count > 10:
2888             raise Exception("Unexpected number of EAP status messages")
2889
2890     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
2891     if ev is None:
2892         raise Exception("Timeout on EAP failure report")
2893
2894 def test_ap_wpa2_eap_tls_ocsp_ca_signed_unknown(dev, apdev, params):
2895     """EAP-TLS and CA signed OCSP response (unknown)"""
2896     check_ocsp_support(dev[0])
2897     ocsp = os.path.join(params['logdir'], "ocsp-resp-ca-signed-unknown.der")
2898     if not os.path.exists(ocsp):
2899         raise HwsimSkip("No OCSP response available")
2900     params = int_eap_server_params()
2901     params["ocsp_stapling_response"] = ocsp
2902     hostapd.add_ap(apdev[0]['ifname'], params)
2903     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
2904                    identity="tls user", ca_cert="auth_serv/ca.pem",
2905                    private_key="auth_serv/user.pkcs12",
2906                    private_key_passwd="whatever", ocsp=2,
2907                    wait_connect=False, scan_freq="2412")
2908     count = 0
2909     while True:
2910         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
2911         if ev is None:
2912             raise Exception("Timeout on EAP status")
2913         if 'bad certificate status response' in ev:
2914             break
2915         count = count + 1
2916         if count > 10:
2917             raise Exception("Unexpected number of EAP status messages")
2918
2919     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
2920     if ev is None:
2921         raise Exception("Timeout on EAP failure report")
2922
2923 def test_ap_wpa2_eap_tls_ocsp_server_signed(dev, apdev, params):
2924     """EAP-TLS and server signed OCSP response"""
2925     check_ocsp_support(dev[0])
2926     ocsp = os.path.join(params['logdir'], "ocsp-resp-server-signed.der")
2927     if not os.path.exists(ocsp):
2928         raise HwsimSkip("No OCSP response available")
2929     params = int_eap_server_params()
2930     params["ocsp_stapling_response"] = ocsp
2931     hostapd.add_ap(apdev[0]['ifname'], params)
2932     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
2933                    identity="tls user", ca_cert="auth_serv/ca.pem",
2934                    private_key="auth_serv/user.pkcs12",
2935                    private_key_passwd="whatever", ocsp=2,
2936                    wait_connect=False, scan_freq="2412")
2937     count = 0
2938     while True:
2939         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
2940         if ev is None:
2941             raise Exception("Timeout on EAP status")
2942         if 'bad certificate status response' in ev:
2943             break
2944         count = count + 1
2945         if count > 10:
2946             raise Exception("Unexpected number of EAP status messages")
2947
2948     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
2949     if ev is None:
2950         raise Exception("Timeout on EAP failure report")
2951
2952 def test_ap_wpa2_eap_tls_ocsp_invalid_data(dev, apdev):
2953     """WPA2-Enterprise connection using EAP-TLS and invalid OCSP data"""
2954     check_ocsp_support(dev[0])
2955     params = int_eap_server_params()
2956     params["ocsp_stapling_response"] = "auth_serv/ocsp-req.der"
2957     hostapd.add_ap(apdev[0]['ifname'], params)
2958     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
2959                    identity="tls user", ca_cert="auth_serv/ca.pem",
2960                    private_key="auth_serv/user.pkcs12",
2961                    private_key_passwd="whatever", ocsp=2,
2962                    wait_connect=False, scan_freq="2412")
2963     count = 0
2964     while True:
2965         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
2966         if ev is None:
2967             raise Exception("Timeout on EAP status")
2968         if 'bad certificate status response' in ev:
2969             break
2970         count = count + 1
2971         if count > 10:
2972             raise Exception("Unexpected number of EAP status messages")
2973
2974     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
2975     if ev is None:
2976         raise Exception("Timeout on EAP failure report")
2977
2978 def test_ap_wpa2_eap_tls_ocsp_invalid(dev, apdev):
2979     """WPA2-Enterprise connection using EAP-TLS and invalid OCSP response"""
2980     check_ocsp_support(dev[0])
2981     params = int_eap_server_params()
2982     params["ocsp_stapling_response"] = "auth_serv/ocsp-server-cache.der-invalid"
2983     hostapd.add_ap(apdev[0]['ifname'], params)
2984     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
2985                    identity="tls user", ca_cert="auth_serv/ca.pem",
2986                    private_key="auth_serv/user.pkcs12",
2987                    private_key_passwd="whatever", ocsp=2,
2988                    wait_connect=False, scan_freq="2412")
2989     count = 0
2990     while True:
2991         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
2992         if ev is None:
2993             raise Exception("Timeout on EAP status")
2994         if 'bad certificate status response' in ev:
2995             break
2996         count = count + 1
2997         if count > 10:
2998             raise Exception("Unexpected number of EAP status messages")
2999
3000     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3001     if ev is None:
3002         raise Exception("Timeout on EAP failure report")
3003
3004 def test_ap_wpa2_eap_tls_ocsp_unknown_sign(dev, apdev):
3005     """WPA2-Enterprise connection using EAP-TLS and unknown OCSP signer"""
3006     check_ocsp_support(dev[0])
3007     params = int_eap_server_params()
3008     params["ocsp_stapling_response"] = "auth_serv/ocsp-server-cache.der-unknown-sign"
3009     hostapd.add_ap(apdev[0]['ifname'], params)
3010     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3011                    identity="tls user", ca_cert="auth_serv/ca.pem",
3012                    private_key="auth_serv/user.pkcs12",
3013                    private_key_passwd="whatever", ocsp=2,
3014                    wait_connect=False, scan_freq="2412")
3015     count = 0
3016     while True:
3017         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
3018         if ev is None:
3019             raise Exception("Timeout on EAP status")
3020         if 'bad certificate status response' in ev:
3021             break
3022         count = count + 1
3023         if count > 10:
3024             raise Exception("Unexpected number of EAP status messages")
3025
3026     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3027     if ev is None:
3028         raise Exception("Timeout on EAP failure report")
3029
3030 def test_ap_wpa2_eap_ttls_ocsp_revoked(dev, apdev, params):
3031     """WPA2-Enterprise connection using EAP-TTLS and OCSP status revoked"""
3032     check_ocsp_support(dev[0])
3033     ocsp = os.path.join(params['logdir'], "ocsp-server-cache-revoked.der")
3034     if not os.path.exists(ocsp):
3035         raise HwsimSkip("No OCSP response available")
3036     params = int_eap_server_params()
3037     params["ocsp_stapling_response"] = ocsp
3038     hostapd.add_ap(apdev[0]['ifname'], params)
3039     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3040                    identity="pap user", ca_cert="auth_serv/ca.pem",
3041                    anonymous_identity="ttls", password="password",
3042                    phase2="auth=PAP", ocsp=2,
3043                    wait_connect=False, scan_freq="2412")
3044     count = 0
3045     while True:
3046         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
3047         if ev is None:
3048             raise Exception("Timeout on EAP status")
3049         if 'bad certificate status response' in ev:
3050             break
3051         if 'certificate revoked' in ev:
3052             break
3053         count = count + 1
3054         if count > 10:
3055             raise Exception("Unexpected number of EAP status messages")
3056
3057     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3058     if ev is None:
3059         raise Exception("Timeout on EAP failure report")
3060
3061 def test_ap_wpa2_eap_ttls_ocsp_unknown(dev, apdev, params):
3062     """WPA2-Enterprise connection using EAP-TTLS and OCSP status revoked"""
3063     check_ocsp_support(dev[0])
3064     ocsp = os.path.join(params['logdir'], "ocsp-server-cache-unknown.der")
3065     if not os.path.exists(ocsp):
3066         raise HwsimSkip("No OCSP response available")
3067     params = int_eap_server_params()
3068     params["ocsp_stapling_response"] = ocsp
3069     hostapd.add_ap(apdev[0]['ifname'], params)
3070     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3071                    identity="pap user", ca_cert="auth_serv/ca.pem",
3072                    anonymous_identity="ttls", password="password",
3073                    phase2="auth=PAP", ocsp=2,
3074                    wait_connect=False, scan_freq="2412")
3075     count = 0
3076     while True:
3077         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
3078         if ev is None:
3079             raise Exception("Timeout on EAP status")
3080         if 'bad certificate status response' in ev:
3081             break
3082         count = count + 1
3083         if count > 10:
3084             raise Exception("Unexpected number of EAP status messages")
3085
3086     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3087     if ev is None:
3088         raise Exception("Timeout on EAP failure report")
3089
3090 def test_ap_wpa2_eap_ttls_optional_ocsp_unknown(dev, apdev, params):
3091     """WPA2-Enterprise connection using EAP-TTLS and OCSP status revoked"""
3092     ocsp = os.path.join(params['logdir'], "ocsp-server-cache-unknown.der")
3093     if not os.path.exists(ocsp):
3094         raise HwsimSkip("No OCSP response available")
3095     params = int_eap_server_params()
3096     params["ocsp_stapling_response"] = ocsp
3097     hostapd.add_ap(apdev[0]['ifname'], params)
3098     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3099                    identity="pap user", ca_cert="auth_serv/ca.pem",
3100                    anonymous_identity="ttls", password="password",
3101                    phase2="auth=PAP", ocsp=1, scan_freq="2412")
3102
3103 def test_ap_wpa2_eap_tls_intermediate_ca(dev, apdev, params):
3104     """EAP-TLS with intermediate server/user CA"""
3105     params = int_eap_server_params()
3106     params["ca_cert"] = "auth_serv/iCA-server/ca-and-root.pem"
3107     params["server_cert"] = "auth_serv/iCA-server/server.pem"
3108     params["private_key"] = "auth_serv/iCA-server/server.key"
3109     hostapd.add_ap(apdev[0]['ifname'], params)
3110     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3111                    identity="tls user",
3112                    ca_cert="auth_serv/iCA-user/ca-and-root.pem",
3113                    client_cert="auth_serv/iCA-user/user.pem",
3114                    private_key="auth_serv/iCA-user/user.key",
3115                    scan_freq="2412")
3116
3117 def root_ocsp(cert):
3118     ca = "auth_serv/ca.pem"
3119
3120     fd2, fn2 = tempfile.mkstemp()
3121     os.close(fd2)
3122
3123     arg = [ "openssl", "ocsp", "-reqout", fn2, "-issuer", ca, "-cert", cert,
3124             "-no_nonce", "-sha256", "-text" ]
3125     cmd = subprocess.Popen(arg, stdout=subprocess.PIPE,
3126                            stderr=subprocess.PIPE)
3127     res = cmd.stdout.read() + "\n" + cmd.stderr.read()
3128     cmd.stdout.close()
3129     cmd.stderr.close()
3130     logger.info("OCSP request:\n" + res)
3131
3132     fd, fn = tempfile.mkstemp()
3133     os.close(fd)
3134     arg = [ "openssl", "ocsp", "-index", "rootCA/index.txt",
3135             "-rsigner", ca, "-rkey", "auth_serv/caa-key.pem",
3136             "-CA", ca, "-issuer", ca, "-verify_other", ca, "-trust_other",
3137             "-ndays", "7", "-reqin", fn2, "-resp_no_certs", "-respout", fn,
3138             "-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 response:\n" + res)
3145     os.unlink(fn2)
3146     return fn
3147
3148 def ica_ocsp(cert):
3149     prefix = "auth_serv/iCA-server/"
3150     ca = prefix + "cacert.pem"
3151     cert = prefix + cert
3152
3153     fd2, fn2 = tempfile.mkstemp()
3154     os.close(fd2)
3155
3156     arg = [ "openssl", "ocsp", "-reqout", fn2, "-issuer", ca, "-cert", cert,
3157             "-no_nonce", "-sha256", "-text" ]
3158     cmd = subprocess.Popen(arg, stdout=subprocess.PIPE,
3159                            stderr=subprocess.PIPE)
3160     res = cmd.stdout.read() + "\n" + cmd.stderr.read()
3161     cmd.stdout.close()
3162     cmd.stderr.close()
3163     logger.info("OCSP request:\n" + res)
3164
3165     fd, fn = tempfile.mkstemp()
3166     os.close(fd)
3167     arg = [ "openssl", "ocsp", "-index", prefix + "index.txt",
3168             "-rsigner", ca, "-rkey", prefix + "private/cakey.pem",
3169             "-CA", ca, "-issuer", ca, "-verify_other", ca, "-trust_other",
3170             "-ndays", "7", "-reqin", fn2, "-resp_no_certs", "-respout", fn,
3171             "-text" ]
3172     cmd = subprocess.Popen(arg, stdout=subprocess.PIPE,
3173                            stderr=subprocess.PIPE)
3174     res = cmd.stdout.read() + "\n" + cmd.stderr.read()
3175     cmd.stdout.close()
3176     cmd.stderr.close()
3177     logger.info("OCSP response:\n" + res)
3178     os.unlink(fn2)
3179     return fn
3180
3181 def test_ap_wpa2_eap_tls_intermediate_ca_ocsp(dev, apdev, params):
3182     """EAP-TLS with intermediate server/user CA and OCSP on 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.pem"
3186     params["private_key"] = "auth_serv/iCA-server/server.key"
3187     fn = ica_ocsp("server.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=2)
3197     finally:
3198         os.unlink(fn)
3199
3200 def test_ap_wpa2_eap_tls_intermediate_ca_ocsp_revoked(dev, apdev, params):
3201     """EAP-TLS with intermediate server/user CA and OCSP on revoked server certificate"""
3202     params = int_eap_server_params()
3203     params["ca_cert"] = "auth_serv/iCA-server/ca-and-root.pem"
3204     params["server_cert"] = "auth_serv/iCA-server/server-revoked.pem"
3205     params["private_key"] = "auth_serv/iCA-server/server-revoked.key"
3206     fn = ica_ocsp("server-revoked.pem")
3207     params["ocsp_stapling_response"] = fn
3208     try:
3209         hostapd.add_ap(apdev[0]['ifname'], params)
3210         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3211                        identity="tls user",
3212                        ca_cert="auth_serv/iCA-user/ca-and-root.pem",
3213                        client_cert="auth_serv/iCA-user/user.pem",
3214                        private_key="auth_serv/iCA-user/user.key",
3215                        scan_freq="2412", ocsp=1, wait_connect=False)
3216         count = 0
3217         while True:
3218             ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS",
3219                                     "CTRL-EVENT-EAP-SUCCESS"])
3220             if ev is None:
3221                 raise Exception("Timeout on EAP status")
3222             if "CTRL-EVENT-EAP-SUCCESS" in ev:
3223                 raise Exception("Unexpected EAP-Success")
3224             if 'bad certificate status response' in ev:
3225                 break
3226             if 'certificate revoked' in ev:
3227                 break
3228             count = count + 1
3229             if count > 10:
3230                 raise Exception("Unexpected number of EAP status messages")
3231
3232         ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3233         if ev is None:
3234             raise Exception("Timeout on EAP failure report")
3235         dev[0].request("REMOVE_NETWORK all")
3236         dev[0].wait_disconnected()
3237     finally:
3238         os.unlink(fn)
3239
3240 def test_ap_wpa2_eap_tls_intermediate_ca_ocsp_multi_missing_resp(dev, apdev, params):
3241     """EAP-TLS with intermediate server/user CA and OCSP multi missing response"""
3242     check_ocsp_support(dev[0])
3243     check_ocsp_multi_support(dev[0])
3244
3245     params = int_eap_server_params()
3246     params["ca_cert"] = "auth_serv/iCA-server/ca-and-root.pem"
3247     params["server_cert"] = "auth_serv/iCA-server/server.pem"
3248     params["private_key"] = "auth_serv/iCA-server/server.key"
3249     fn = ica_ocsp("server.pem")
3250     params["ocsp_stapling_response"] = fn
3251     try:
3252         hostapd.add_ap(apdev[0]['ifname'], params)
3253         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3254                        identity="tls user",
3255                        ca_cert="auth_serv/iCA-user/ca-and-root.pem",
3256                        client_cert="auth_serv/iCA-user/user.pem",
3257                        private_key="auth_serv/iCA-user/user.key",
3258                        scan_freq="2412", ocsp=3, wait_connect=False)
3259         count = 0
3260         while True:
3261             ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS",
3262                                     "CTRL-EVENT-EAP-SUCCESS"])
3263             if ev is None:
3264                 raise Exception("Timeout on EAP status")
3265             if "CTRL-EVENT-EAP-SUCCESS" in ev:
3266                 raise Exception("Unexpected EAP-Success")
3267             if 'bad certificate status response' in ev:
3268                 break
3269             if 'certificate revoked' in ev:
3270                 break
3271             count = count + 1
3272             if count > 10:
3273                 raise Exception("Unexpected number of EAP status messages")
3274
3275         ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3276         if ev is None:
3277             raise Exception("Timeout on EAP failure report")
3278         dev[0].request("REMOVE_NETWORK all")
3279         dev[0].wait_disconnected()
3280     finally:
3281         os.unlink(fn)
3282
3283 def test_ap_wpa2_eap_tls_intermediate_ca_ocsp_multi(dev, apdev, params):
3284     """EAP-TLS with intermediate server/user CA and OCSP multi OK"""
3285     check_ocsp_support(dev[0])
3286     check_ocsp_multi_support(dev[0])
3287
3288     params = int_eap_server_params()
3289     params["ca_cert"] = "auth_serv/iCA-server/ca-and-root.pem"
3290     params["server_cert"] = "auth_serv/iCA-server/server.pem"
3291     params["private_key"] = "auth_serv/iCA-server/server.key"
3292     fn = ica_ocsp("server.pem")
3293     fn2 = root_ocsp("auth_serv/iCA-server/cacert.pem")
3294     params["ocsp_stapling_response"] = fn
3295
3296     with open(fn, "r") as f:
3297         resp_server = f.read()
3298     with open(fn2, "r") as f:
3299         resp_ica = f.read()
3300
3301     fd3, fn3 = tempfile.mkstemp()
3302     try:
3303         f = os.fdopen(fd3, 'w')
3304         f.write(struct.pack(">L", len(resp_server))[1:4])
3305         f.write(resp_server)
3306         f.write(struct.pack(">L", len(resp_ica))[1:4])
3307         f.write(resp_ica)
3308         f.close()
3309
3310         params["ocsp_stapling_response_multi"] = fn3
3311
3312         hostapd.add_ap(apdev[0]['ifname'], params)
3313         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3314                        identity="tls user",
3315                        ca_cert="auth_serv/iCA-user/ca-and-root.pem",
3316                        client_cert="auth_serv/iCA-user/user.pem",
3317                        private_key="auth_serv/iCA-user/user.key",
3318                        scan_freq="2412", ocsp=3, wait_connect=False)
3319         count = 0
3320         while True:
3321             ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS",
3322                                     "CTRL-EVENT-EAP-SUCCESS"])
3323             if ev is None:
3324                 raise Exception("Timeout on EAP status")
3325             if "CTRL-EVENT-EAP-SUCCESS" in ev:
3326                 raise Exception("Unexpected EAP-Success")
3327             if 'bad certificate status response' in ev:
3328                 break
3329             if 'certificate revoked' in ev:
3330                 break
3331             count = count + 1
3332             if count > 10:
3333                 raise Exception("Unexpected number of EAP status messages")
3334
3335         ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3336         if ev is None:
3337             raise Exception("Timeout on EAP failure report")
3338         dev[0].request("REMOVE_NETWORK all")
3339         dev[0].wait_disconnected()
3340     finally:
3341         os.unlink(fn)
3342         os.unlink(fn2)
3343         os.unlink(fn3)
3344
3345 def test_ap_wpa2_eap_tls_ocsp_multi_revoked(dev, apdev, params):
3346     """EAP-TLS and CA signed OCSP multi response (revoked)"""
3347     check_ocsp_support(dev[0])
3348     check_ocsp_multi_support(dev[0])
3349
3350     ocsp_revoked = os.path.join(params['logdir'],
3351                                 "ocsp-resp-ca-signed-revoked.der")
3352     if not os.path.exists(ocsp_revoked):
3353         raise HwsimSkip("No OCSP response (revoked) available")
3354     ocsp_unknown = os.path.join(params['logdir'],
3355                                 "ocsp-resp-ca-signed-unknown.der")
3356     if not os.path.exists(ocsp_unknown):
3357         raise HwsimSkip("No OCSP response(unknown) available")
3358
3359     with open(ocsp_revoked, "r") as f:
3360         resp_revoked = f.read()
3361     with open(ocsp_unknown, "r") as f:
3362         resp_unknown = f.read()
3363
3364     fd, fn = tempfile.mkstemp()
3365     try:
3366         # This is not really a valid order of the OCSPResponse items in the
3367         # list, but this works for now to verify parsing and processing of
3368         # multiple responses.
3369         f = os.fdopen(fd, 'w')
3370         f.write(struct.pack(">L", len(resp_unknown))[1:4])
3371         f.write(resp_unknown)
3372         f.write(struct.pack(">L", len(resp_revoked))[1:4])
3373         f.write(resp_revoked)
3374         f.write(struct.pack(">L", 0)[1:4])
3375         f.write(struct.pack(">L", len(resp_unknown))[1:4])
3376         f.write(resp_unknown)
3377         f.close()
3378
3379         params = int_eap_server_params()
3380         params["ocsp_stapling_response_multi"] = fn
3381         hostapd.add_ap(apdev[0]['ifname'], params)
3382         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3383                        identity="tls user", ca_cert="auth_serv/ca.pem",
3384                        private_key="auth_serv/user.pkcs12",
3385                        private_key_passwd="whatever", ocsp=1,
3386                        wait_connect=False, scan_freq="2412")
3387         count = 0
3388         while True:
3389             ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS",
3390                                     "CTRL-EVENT-EAP-SUCCESS"])
3391             if ev is None:
3392                 raise Exception("Timeout on EAP status")
3393             if "CTRL-EVENT-EAP-SUCCESS" in ev:
3394                 raise Exception("Unexpected EAP-Success")
3395             if 'bad certificate status response' in ev:
3396                 break
3397             if 'certificate revoked' in ev:
3398                 break
3399             count = count + 1
3400             if count > 10:
3401                 raise Exception("Unexpected number of EAP status messages")
3402     finally:
3403         os.unlink(fn)
3404
3405 def test_ap_wpa2_eap_tls_domain_suffix_match_cn_full(dev, apdev):
3406     """WPA2-Enterprise using EAP-TLS and domain suffix match (CN)"""
3407     check_domain_match_full(dev[0])
3408     params = int_eap_server_params()
3409     params["server_cert"] = "auth_serv/server-no-dnsname.pem"
3410     params["private_key"] = "auth_serv/server-no-dnsname.key"
3411     hostapd.add_ap(apdev[0]['ifname'], params)
3412     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3413                    identity="tls user", ca_cert="auth_serv/ca.pem",
3414                    private_key="auth_serv/user.pkcs12",
3415                    private_key_passwd="whatever",
3416                    domain_suffix_match="server3.w1.fi",
3417                    scan_freq="2412")
3418
3419 def test_ap_wpa2_eap_tls_domain_match_cn(dev, apdev):
3420     """WPA2-Enterprise using EAP-TLS and domainmatch (CN)"""
3421     check_domain_match(dev[0])
3422     params = int_eap_server_params()
3423     params["server_cert"] = "auth_serv/server-no-dnsname.pem"
3424     params["private_key"] = "auth_serv/server-no-dnsname.key"
3425     hostapd.add_ap(apdev[0]['ifname'], params)
3426     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3427                    identity="tls user", ca_cert="auth_serv/ca.pem",
3428                    private_key="auth_serv/user.pkcs12",
3429                    private_key_passwd="whatever",
3430                    domain_match="server3.w1.fi",
3431                    scan_freq="2412")
3432
3433 def test_ap_wpa2_eap_tls_domain_suffix_match_cn(dev, apdev):
3434     """WPA2-Enterprise using EAP-TLS and domain suffix match (CN)"""
3435     check_domain_match_full(dev[0])
3436     params = int_eap_server_params()
3437     params["server_cert"] = "auth_serv/server-no-dnsname.pem"
3438     params["private_key"] = "auth_serv/server-no-dnsname.key"
3439     hostapd.add_ap(apdev[0]['ifname'], params)
3440     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3441                    identity="tls user", ca_cert="auth_serv/ca.pem",
3442                    private_key="auth_serv/user.pkcs12",
3443                    private_key_passwd="whatever",
3444                    domain_suffix_match="w1.fi",
3445                    scan_freq="2412")
3446
3447 def test_ap_wpa2_eap_tls_domain_suffix_mismatch_cn(dev, apdev):
3448     """WPA2-Enterprise using EAP-TLS and domain suffix mismatch (CN)"""
3449     check_domain_suffix_match(dev[0])
3450     params = int_eap_server_params()
3451     params["server_cert"] = "auth_serv/server-no-dnsname.pem"
3452     params["private_key"] = "auth_serv/server-no-dnsname.key"
3453     hostapd.add_ap(apdev[0]['ifname'], params)
3454     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3455                    identity="tls user", ca_cert="auth_serv/ca.pem",
3456                    private_key="auth_serv/user.pkcs12",
3457                    private_key_passwd="whatever",
3458                    domain_suffix_match="example.com",
3459                    wait_connect=False,
3460                    scan_freq="2412")
3461     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3462                    identity="tls user", ca_cert="auth_serv/ca.pem",
3463                    private_key="auth_serv/user.pkcs12",
3464                    private_key_passwd="whatever",
3465                    domain_suffix_match="erver3.w1.fi",
3466                    wait_connect=False,
3467                    scan_freq="2412")
3468     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3469     if ev is None:
3470         raise Exception("Timeout on EAP failure report")
3471     ev = dev[1].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3472     if ev is None:
3473         raise Exception("Timeout on EAP failure report (2)")
3474
3475 def test_ap_wpa2_eap_tls_domain_mismatch_cn(dev, apdev):
3476     """WPA2-Enterprise using EAP-TLS and domain mismatch (CN)"""
3477     check_domain_match(dev[0])
3478     params = int_eap_server_params()
3479     params["server_cert"] = "auth_serv/server-no-dnsname.pem"
3480     params["private_key"] = "auth_serv/server-no-dnsname.key"
3481     hostapd.add_ap(apdev[0]['ifname'], params)
3482     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3483                    identity="tls user", ca_cert="auth_serv/ca.pem",
3484                    private_key="auth_serv/user.pkcs12",
3485                    private_key_passwd="whatever",
3486                    domain_match="example.com",
3487                    wait_connect=False,
3488                    scan_freq="2412")
3489     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3490                    identity="tls user", ca_cert="auth_serv/ca.pem",
3491                    private_key="auth_serv/user.pkcs12",
3492                    private_key_passwd="whatever",
3493                    domain_match="w1.fi",
3494                    wait_connect=False,
3495                    scan_freq="2412")
3496     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3497     if ev is None:
3498         raise Exception("Timeout on EAP failure report")
3499     ev = dev[1].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3500     if ev is None:
3501         raise Exception("Timeout on EAP failure report (2)")
3502
3503 def test_ap_wpa2_eap_ttls_expired_cert(dev, apdev):
3504     """WPA2-Enterprise using EAP-TTLS and expired certificate"""
3505     skip_with_fips(dev[0])
3506     params = int_eap_server_params()
3507     params["server_cert"] = "auth_serv/server-expired.pem"
3508     params["private_key"] = "auth_serv/server-expired.key"
3509     hostapd.add_ap(apdev[0]['ifname'], params)
3510     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3511                    identity="mschap user", password="password",
3512                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
3513                    wait_connect=False,
3514                    scan_freq="2412")
3515     ev = dev[0].wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR"])
3516     if ev is None:
3517         raise Exception("Timeout on EAP certificate error report")
3518     if "reason=4" not in ev or "certificate has expired" not in ev:
3519         raise Exception("Unexpected failure reason: " + ev)
3520     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3521     if ev is None:
3522         raise Exception("Timeout on EAP failure report")
3523
3524 def test_ap_wpa2_eap_ttls_ignore_expired_cert(dev, apdev):
3525     """WPA2-Enterprise using EAP-TTLS and ignore certificate expiration"""
3526     skip_with_fips(dev[0])
3527     params = int_eap_server_params()
3528     params["server_cert"] = "auth_serv/server-expired.pem"
3529     params["private_key"] = "auth_serv/server-expired.key"
3530     hostapd.add_ap(apdev[0]['ifname'], params)
3531     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3532                    identity="mschap user", password="password",
3533                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
3534                    phase1="tls_disable_time_checks=1",
3535                    scan_freq="2412")
3536
3537 def test_ap_wpa2_eap_ttls_long_duration(dev, apdev):
3538     """WPA2-Enterprise using EAP-TTLS and long certificate duration"""
3539     skip_with_fips(dev[0])
3540     params = int_eap_server_params()
3541     params["server_cert"] = "auth_serv/server-long-duration.pem"
3542     params["private_key"] = "auth_serv/server-long-duration.key"
3543     hostapd.add_ap(apdev[0]['ifname'], params)
3544     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3545                    identity="mschap user", password="password",
3546                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
3547                    scan_freq="2412")
3548
3549 def test_ap_wpa2_eap_ttls_server_cert_eku_client(dev, apdev):
3550     """WPA2-Enterprise using EAP-TTLS and server cert with client EKU"""
3551     skip_with_fips(dev[0])
3552     params = int_eap_server_params()
3553     params["server_cert"] = "auth_serv/server-eku-client.pem"
3554     params["private_key"] = "auth_serv/server-eku-client.key"
3555     hostapd.add_ap(apdev[0]['ifname'], params)
3556     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3557                    identity="mschap user", password="password",
3558                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
3559                    wait_connect=False,
3560                    scan_freq="2412")
3561     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3562     if ev is None:
3563         raise Exception("Timeout on EAP failure report")
3564
3565 def test_ap_wpa2_eap_ttls_server_cert_eku_client_server(dev, apdev):
3566     """WPA2-Enterprise using EAP-TTLS and server cert with client and server EKU"""
3567     skip_with_fips(dev[0])
3568     params = int_eap_server_params()
3569     params["server_cert"] = "auth_serv/server-eku-client-server.pem"
3570     params["private_key"] = "auth_serv/server-eku-client-server.key"
3571     hostapd.add_ap(apdev[0]['ifname'], params)
3572     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3573                    identity="mschap user", password="password",
3574                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
3575                    scan_freq="2412")
3576
3577 def test_ap_wpa2_eap_ttls_server_pkcs12(dev, apdev):
3578     """WPA2-Enterprise using EAP-TTLS and server PKCS#12 file"""
3579     skip_with_fips(dev[0])
3580     params = int_eap_server_params()
3581     del params["server_cert"]
3582     params["private_key"] = "auth_serv/server.pkcs12"
3583     hostapd.add_ap(apdev[0]['ifname'], params)
3584     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3585                    identity="mschap user", password="password",
3586                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
3587                    scan_freq="2412")
3588
3589 def test_ap_wpa2_eap_ttls_dh_params(dev, apdev):
3590     """WPA2-Enterprise connection using EAP-TTLS/CHAP and setting DH params"""
3591     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3592     hostapd.add_ap(apdev[0]['ifname'], params)
3593     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
3594                 anonymous_identity="ttls", password="password",
3595                 ca_cert="auth_serv/ca.der", phase2="auth=PAP",
3596                 dh_file="auth_serv/dh.conf")
3597
3598 def test_ap_wpa2_eap_ttls_dh_params_dsa(dev, apdev):
3599     """WPA2-Enterprise connection using EAP-TTLS and setting DH params (DSA)"""
3600     check_dh_dsa_support(dev[0])
3601     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3602     hostapd.add_ap(apdev[0]['ifname'], params)
3603     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
3604                 anonymous_identity="ttls", password="password",
3605                 ca_cert="auth_serv/ca.der", phase2="auth=PAP",
3606                 dh_file="auth_serv/dsaparam.pem")
3607
3608 def test_ap_wpa2_eap_ttls_dh_params_not_found(dev, apdev):
3609     """EAP-TTLS and DH params file not found"""
3610     skip_with_fips(dev[0])
3611     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3612     hostapd.add_ap(apdev[0]['ifname'], params)
3613     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3614                    identity="mschap user", password="password",
3615                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
3616                    dh_file="auth_serv/dh-no-such-file.conf",
3617                    scan_freq="2412", wait_connect=False)
3618     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3619     if ev is None:
3620         raise Exception("EAP failure timed out")
3621     dev[0].request("REMOVE_NETWORK all")
3622     dev[0].wait_disconnected()
3623
3624 def test_ap_wpa2_eap_ttls_dh_params_invalid(dev, apdev):
3625     """EAP-TTLS and invalid DH params file"""
3626     skip_with_fips(dev[0])
3627     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3628     hostapd.add_ap(apdev[0]['ifname'], params)
3629     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3630                    identity="mschap user", password="password",
3631                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
3632                    dh_file="auth_serv/ca.pem",
3633                    scan_freq="2412", wait_connect=False)
3634     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3635     if ev is None:
3636         raise Exception("EAP failure timed out")
3637     dev[0].request("REMOVE_NETWORK all")
3638     dev[0].wait_disconnected()
3639
3640 def test_ap_wpa2_eap_ttls_dh_params_blob(dev, apdev):
3641     """WPA2-Enterprise connection using EAP-TTLS/CHAP and setting DH params from blob"""
3642     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3643     hostapd.add_ap(apdev[0]['ifname'], params)
3644     dh = read_pem("auth_serv/dh2.conf")
3645     if "OK" not in dev[0].request("SET blob dhparams " + dh.encode("hex")):
3646         raise Exception("Could not set dhparams blob")
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                 dh_file="blob://dhparams")
3651
3652 def test_ap_wpa2_eap_ttls_dh_params_server(dev, apdev):
3653     """WPA2-Enterprise using EAP-TTLS and alternative server dhparams"""
3654     params = int_eap_server_params()
3655     params["dh_file"] = "auth_serv/dh2.conf"
3656     hostapd.add_ap(apdev[0]['ifname'], params)
3657     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
3658                 anonymous_identity="ttls", password="password",
3659                 ca_cert="auth_serv/ca.der", phase2="auth=PAP")
3660
3661 def test_ap_wpa2_eap_ttls_dh_params_dsa_server(dev, apdev):
3662     """WPA2-Enterprise using EAP-TTLS and alternative server dhparams (DSA)"""
3663     params = int_eap_server_params()
3664     params["dh_file"] = "auth_serv/dsaparam.pem"
3665     hostapd.add_ap(apdev[0]['ifname'], params)
3666     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
3667                 anonymous_identity="ttls", password="password",
3668                 ca_cert="auth_serv/ca.der", phase2="auth=PAP")
3669
3670 def test_ap_wpa2_eap_ttls_dh_params_not_found(dev, apdev):
3671     """EAP-TLS server and dhparams file not found"""
3672     params = int_eap_server_params()
3673     params["dh_file"] = "auth_serv/dh-no-such-file.conf"
3674     hapd = hostapd.add_ap(apdev[0]['ifname'], params, no_enable=True)
3675     if "FAIL" not in hapd.request("ENABLE"):
3676         raise Exception("Invalid configuration accepted")
3677
3678 def test_ap_wpa2_eap_ttls_dh_params_invalid(dev, apdev):
3679     """EAP-TLS server and invalid dhparams file"""
3680     params = int_eap_server_params()
3681     params["dh_file"] = "auth_serv/ca.pem"
3682     hapd = hostapd.add_ap(apdev[0]['ifname'], params, no_enable=True)
3683     if "FAIL" not in hapd.request("ENABLE"):
3684         raise Exception("Invalid configuration accepted")
3685
3686 def test_ap_wpa2_eap_reauth(dev, apdev):
3687     """WPA2-Enterprise and Authenticator forcing reauthentication"""
3688     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3689     params['eap_reauth_period'] = '2'
3690     hostapd.add_ap(apdev[0]['ifname'], params)
3691     eap_connect(dev[0], apdev[0], "PAX", "pax.user@example.com",
3692                 password_hex="0123456789abcdef0123456789abcdef")
3693     logger.info("Wait for reauthentication")
3694     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=10)
3695     if ev is None:
3696         raise Exception("Timeout on reauthentication")
3697     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
3698     if ev is None:
3699         raise Exception("Timeout on reauthentication")
3700     for i in range(0, 20):
3701         state = dev[0].get_status_field("wpa_state")
3702         if state == "COMPLETED":
3703             break
3704         time.sleep(0.1)
3705     if state != "COMPLETED":
3706         raise Exception("Reauthentication did not complete")
3707
3708 def test_ap_wpa2_eap_request_identity_message(dev, apdev):
3709     """Optional displayable message in EAP Request-Identity"""
3710     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3711     params['eap_message'] = 'hello\\0networkid=netw,nasid=foo,portid=0,NAIRealms=example.com'
3712     hostapd.add_ap(apdev[0]['ifname'], params)
3713     eap_connect(dev[0], apdev[0], "PAX", "pax.user@example.com",
3714                 password_hex="0123456789abcdef0123456789abcdef")
3715
3716 def test_ap_wpa2_eap_sim_aka_result_ind(dev, apdev):
3717     """WPA2-Enterprise using EAP-SIM/AKA and protected result indication"""
3718     check_hlr_auc_gw_support()
3719     params = int_eap_server_params()
3720     params['eap_sim_db'] = "unix:/tmp/hlr_auc_gw.sock"
3721     params['eap_sim_aka_result_ind'] = "1"
3722     hostapd.add_ap(apdev[0]['ifname'], params)
3723
3724     eap_connect(dev[0], apdev[0], "SIM", "1232010000000000",
3725                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
3726                 phase1="result_ind=1")
3727     eap_reauth(dev[0], "SIM")
3728     eap_connect(dev[1], apdev[0], "SIM", "1232010000000000",
3729                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581")
3730
3731     dev[0].request("REMOVE_NETWORK all")
3732     dev[1].request("REMOVE_NETWORK all")
3733
3734     eap_connect(dev[0], apdev[0], "AKA", "0232010000000000",
3735                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123",
3736                 phase1="result_ind=1")
3737     eap_reauth(dev[0], "AKA")
3738     eap_connect(dev[1], apdev[0], "AKA", "0232010000000000",
3739                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123")
3740
3741     dev[0].request("REMOVE_NETWORK all")
3742     dev[1].request("REMOVE_NETWORK all")
3743
3744     eap_connect(dev[0], apdev[0], "AKA'", "6555444333222111",
3745                 password="5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123",
3746                 phase1="result_ind=1")
3747     eap_reauth(dev[0], "AKA'")
3748     eap_connect(dev[1], apdev[0], "AKA'", "6555444333222111",
3749                 password="5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123")
3750
3751 def test_ap_wpa2_eap_too_many_roundtrips(dev, apdev):
3752     """WPA2-Enterprise connection resulting in too many EAP roundtrips"""
3753     skip_with_fips(dev[0])
3754     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3755     hostapd.add_ap(apdev[0]['ifname'], params)
3756     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
3757                    eap="TTLS", identity="mschap user",
3758                    wait_connect=False, scan_freq="2412", ieee80211w="1",
3759                    anonymous_identity="ttls", password="password",
3760                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
3761                    fragment_size="10")
3762     ev = dev[0].wait_event(["EAP: more than"], timeout=20)
3763     if ev is None:
3764         raise Exception("EAP roundtrip limit not reached")
3765
3766 def test_ap_wpa2_eap_expanded_nak(dev, apdev):
3767     """WPA2-Enterprise connection with EAP resulting in expanded NAK"""
3768     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3769     hostapd.add_ap(apdev[0]['ifname'], params)
3770     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
3771                    eap="PSK", identity="vendor-test",
3772                    password_hex="ff23456789abcdef0123456789abcdef",
3773                    wait_connect=False)
3774
3775     found = False
3776     for i in range(0, 5):
3777         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"], timeout=16)
3778         if ev is None:
3779             raise Exception("Association and EAP start timed out")
3780         if "refuse proposed method" in ev:
3781             found = True
3782             break
3783     if not found:
3784         raise Exception("Unexpected EAP status: " + ev)
3785
3786     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3787     if ev is None:
3788         raise Exception("EAP failure timed out")
3789
3790 def test_ap_wpa2_eap_sql(dev, apdev, params):
3791     """WPA2-Enterprise connection using SQLite for user DB"""
3792     skip_with_fips(dev[0])
3793     try:
3794         import sqlite3
3795     except ImportError:
3796         raise HwsimSkip("No sqlite3 module available")
3797     dbfile = os.path.join(params['logdir'], "eap-user.db")
3798     try:
3799         os.remove(dbfile)
3800     except:
3801         pass
3802     con = sqlite3.connect(dbfile)
3803     with con:
3804         cur = con.cursor()
3805         cur.execute("CREATE TABLE users(identity TEXT PRIMARY KEY, methods TEXT, password TEXT, remediation TEXT, phase2 INTEGER)")
3806         cur.execute("CREATE TABLE wildcards(identity TEXT PRIMARY KEY, methods TEXT)")
3807         cur.execute("INSERT INTO users(identity,methods,password,phase2) VALUES ('user-pap','TTLS-PAP','password',1)")
3808         cur.execute("INSERT INTO users(identity,methods,password,phase2) VALUES ('user-chap','TTLS-CHAP','password',1)")
3809         cur.execute("INSERT INTO users(identity,methods,password,phase2) VALUES ('user-mschap','TTLS-MSCHAP','password',1)")
3810         cur.execute("INSERT INTO users(identity,methods,password,phase2) VALUES ('user-mschapv2','TTLS-MSCHAPV2','password',1)")
3811         cur.execute("INSERT INTO wildcards(identity,methods) VALUES ('','TTLS,TLS')")
3812         cur.execute("CREATE TABLE authlog(timestamp TEXT, session TEXT, nas_ip TEXT, username TEXT, note TEXT)")
3813
3814     try:
3815         params = int_eap_server_params()
3816         params["eap_user_file"] = "sqlite:" + dbfile
3817         hostapd.add_ap(apdev[0]['ifname'], params)
3818         eap_connect(dev[0], apdev[0], "TTLS", "user-mschapv2",
3819                     anonymous_identity="ttls", password="password",
3820                     ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
3821         dev[0].request("REMOVE_NETWORK all")
3822         eap_connect(dev[1], apdev[0], "TTLS", "user-mschap",
3823                     anonymous_identity="ttls", password="password",
3824                     ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP")
3825         dev[1].request("REMOVE_NETWORK all")
3826         eap_connect(dev[0], apdev[0], "TTLS", "user-chap",
3827                     anonymous_identity="ttls", password="password",
3828                     ca_cert="auth_serv/ca.pem", phase2="auth=CHAP")
3829         eap_connect(dev[1], apdev[0], "TTLS", "user-pap",
3830                     anonymous_identity="ttls", password="password",
3831                     ca_cert="auth_serv/ca.pem", phase2="auth=PAP")
3832     finally:
3833         os.remove(dbfile)
3834
3835 def test_ap_wpa2_eap_non_ascii_identity(dev, apdev):
3836     """WPA2-Enterprise connection attempt using non-ASCII identity"""
3837     params = int_eap_server_params()
3838     hostapd.add_ap(apdev[0]['ifname'], params)
3839     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3840                    identity="\x80", password="password", wait_connect=False)
3841     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3842                    identity="a\x80", password="password", wait_connect=False)
3843     for i in range(0, 2):
3844         ev = dev[i].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
3845         if ev is None:
3846             raise Exception("Association and EAP start timed out")
3847         ev = dev[i].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=10)
3848         if ev is None:
3849             raise Exception("EAP method selection timed out")
3850
3851 def test_ap_wpa2_eap_non_ascii_identity2(dev, apdev):
3852     """WPA2-Enterprise connection attempt using non-ASCII identity"""
3853     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3854     hostapd.add_ap(apdev[0]['ifname'], params)
3855     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3856                    identity="\x80", password="password", wait_connect=False)
3857     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3858                    identity="a\x80", password="password", wait_connect=False)
3859     for i in range(0, 2):
3860         ev = dev[i].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
3861         if ev is None:
3862             raise Exception("Association and EAP start timed out")
3863         ev = dev[i].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=10)
3864         if ev is None:
3865             raise Exception("EAP method selection timed out")
3866
3867 def test_openssl_cipher_suite_config_wpas(dev, apdev):
3868     """OpenSSL cipher suite configuration on wpa_supplicant"""
3869     tls = dev[0].request("GET tls_library")
3870     if not tls.startswith("OpenSSL"):
3871         raise HwsimSkip("TLS library is not OpenSSL: " + tls)
3872     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3873     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
3874     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
3875                 anonymous_identity="ttls", password="password",
3876                 openssl_ciphers="AES128",
3877                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP")
3878     eap_connect(dev[1], apdev[0], "TTLS", "pap user",
3879                 anonymous_identity="ttls", password="password",
3880                 openssl_ciphers="EXPORT",
3881                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP",
3882                 expect_failure=True, maybe_local_error=True)
3883     dev[2].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3884                    identity="pap user", anonymous_identity="ttls",
3885                    password="password",
3886                    openssl_ciphers="FOO",
3887                    ca_cert="auth_serv/ca.pem", phase2="auth=PAP",
3888                    wait_connect=False)
3889     ev = dev[2].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
3890     if ev is None:
3891         raise Exception("EAP failure after invalid openssl_ciphers not reported")
3892     dev[2].request("DISCONNECT")
3893
3894 def test_openssl_cipher_suite_config_hapd(dev, apdev):
3895     """OpenSSL cipher suite configuration on hostapd"""
3896     tls = dev[0].request("GET tls_library")
3897     if not tls.startswith("OpenSSL"):
3898         raise HwsimSkip("wpa_supplicant TLS library is not OpenSSL: " + tls)
3899     params = int_eap_server_params()
3900     params['openssl_ciphers'] = "AES256"
3901     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
3902     tls = hapd.request("GET tls_library")
3903     if not tls.startswith("OpenSSL"):
3904         raise HwsimSkip("hostapd TLS library is not OpenSSL: " + tls)
3905     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
3906                 anonymous_identity="ttls", password="password",
3907                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP")
3908     eap_connect(dev[1], apdev[0], "TTLS", "pap user",
3909                 anonymous_identity="ttls", password="password",
3910                 openssl_ciphers="AES128",
3911                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP",
3912                 expect_failure=True)
3913     eap_connect(dev[2], apdev[0], "TTLS", "pap user",
3914                 anonymous_identity="ttls", password="password",
3915                 openssl_ciphers="HIGH:!ADH",
3916                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP")
3917
3918     params['openssl_ciphers'] = "FOO"
3919     hapd2 = hostapd.add_ap(apdev[1]['ifname'], params, no_enable=True)
3920     if "FAIL" not in hapd2.request("ENABLE"):
3921         raise Exception("Invalid openssl_ciphers value accepted")
3922
3923 def test_wpa2_eap_ttls_pap_key_lifetime_in_memory(dev, apdev, params):
3924     """Key lifetime in memory with WPA2-Enterprise using EAP-TTLS/PAP"""
3925     p = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3926     hapd = hostapd.add_ap(apdev[0]['ifname'], p)
3927     password = "63d2d21ac3c09ed567ee004a34490f1d16e7fa5835edf17ddba70a63f1a90a25"
3928     pid = find_wpas_process(dev[0])
3929     id = eap_connect(dev[0], apdev[0], "TTLS", "pap-secret",
3930                      anonymous_identity="ttls", password=password,
3931                      ca_cert="auth_serv/ca.pem", phase2="auth=PAP")
3932     # The decrypted copy of GTK is freed only after the CTRL-EVENT-CONNECTED
3933     # event has been delivered, so verify that wpa_supplicant has returned to
3934     # eloop before reading process memory.
3935     time.sleep(1)
3936     dev[0].ping()
3937     buf = read_process_memory(pid, password)
3938
3939     dev[0].request("DISCONNECT")
3940     dev[0].wait_disconnected()
3941
3942     dev[0].relog()
3943     msk = None
3944     emsk = None
3945     pmk = None
3946     ptk = None
3947     gtk = None
3948     with open(os.path.join(params['logdir'], 'log0'), 'r') as f:
3949         for l in f.readlines():
3950             if "EAP-TTLS: Derived key - hexdump" in l:
3951                 val = l.strip().split(':')[3].replace(' ', '')
3952                 msk = binascii.unhexlify(val)
3953             if "EAP-TTLS: Derived EMSK - hexdump" in l:
3954                 val = l.strip().split(':')[3].replace(' ', '')
3955                 emsk = binascii.unhexlify(val)
3956             if "WPA: PMK - hexdump" in l:
3957                 val = l.strip().split(':')[3].replace(' ', '')
3958                 pmk = binascii.unhexlify(val)
3959             if "WPA: PTK - hexdump" in l:
3960                 val = l.strip().split(':')[3].replace(' ', '')
3961                 ptk = binascii.unhexlify(val)
3962             if "WPA: Group Key - hexdump" in l:
3963                 val = l.strip().split(':')[3].replace(' ', '')
3964                 gtk = binascii.unhexlify(val)
3965     if not msk or not emsk or not pmk or not ptk or not gtk:
3966         raise Exception("Could not find keys from debug log")
3967     if len(gtk) != 16:
3968         raise Exception("Unexpected GTK length")
3969
3970     kck = ptk[0:16]
3971     kek = ptk[16:32]
3972     tk = ptk[32:48]
3973
3974     fname = os.path.join(params['logdir'],
3975                          'wpa2_eap_ttls_pap_key_lifetime_in_memory.memctx-')
3976
3977     logger.info("Checking keys in memory while associated")
3978     get_key_locations(buf, password, "Password")
3979     get_key_locations(buf, pmk, "PMK")
3980     get_key_locations(buf, msk, "MSK")
3981     get_key_locations(buf, emsk, "EMSK")
3982     if password not in buf:
3983         raise HwsimSkip("Password not found while associated")
3984     if pmk not in buf:
3985         raise HwsimSkip("PMK not found while associated")
3986     if kck not in buf:
3987         raise Exception("KCK not found while associated")
3988     if kek not in buf:
3989         raise Exception("KEK not found while associated")
3990     if tk in buf:
3991         raise Exception("TK found from memory")
3992     if gtk in buf:
3993         get_key_locations(buf, gtk, "GTK")
3994         raise Exception("GTK found from memory")
3995
3996     logger.info("Checking keys in memory after disassociation")
3997     buf = read_process_memory(pid, password)
3998
3999     # Note: Password is still present in network configuration
4000     # Note: PMK is in PMKSA cache and EAP fast re-auth data
4001
4002     get_key_locations(buf, password, "Password")
4003     get_key_locations(buf, pmk, "PMK")
4004     get_key_locations(buf, msk, "MSK")
4005     get_key_locations(buf, emsk, "EMSK")
4006     verify_not_present(buf, kck, fname, "KCK")
4007     verify_not_present(buf, kek, fname, "KEK")
4008     verify_not_present(buf, tk, fname, "TK")
4009     verify_not_present(buf, gtk, fname, "GTK")
4010
4011     dev[0].request("PMKSA_FLUSH")
4012     dev[0].set_network_quoted(id, "identity", "foo")
4013     logger.info("Checking keys in memory after PMKSA cache and EAP fast reauth flush")
4014     buf = read_process_memory(pid, password)
4015     get_key_locations(buf, password, "Password")
4016     get_key_locations(buf, pmk, "PMK")
4017     get_key_locations(buf, msk, "MSK")
4018     get_key_locations(buf, emsk, "EMSK")
4019     verify_not_present(buf, pmk, fname, "PMK")
4020
4021     dev[0].request("REMOVE_NETWORK all")
4022
4023     logger.info("Checking keys in memory after network profile removal")
4024     buf = read_process_memory(pid, password)
4025
4026     get_key_locations(buf, password, "Password")
4027     get_key_locations(buf, pmk, "PMK")
4028     get_key_locations(buf, msk, "MSK")
4029     get_key_locations(buf, emsk, "EMSK")
4030     verify_not_present(buf, password, fname, "password")
4031     verify_not_present(buf, pmk, fname, "PMK")
4032     verify_not_present(buf, kck, fname, "KCK")
4033     verify_not_present(buf, kek, fname, "KEK")
4034     verify_not_present(buf, tk, fname, "TK")
4035     verify_not_present(buf, gtk, fname, "GTK")
4036     verify_not_present(buf, msk, fname, "MSK")
4037     verify_not_present(buf, emsk, fname, "EMSK")
4038
4039 def test_ap_wpa2_eap_unexpected_wep_eapol_key(dev, apdev):
4040     """WPA2-Enterprise connection and unexpected WEP EAPOL-Key"""
4041     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4042     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4043     bssid = apdev[0]['bssid']
4044     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
4045                 anonymous_identity="ttls", password="password",
4046                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP")
4047
4048     # Send unexpected WEP EAPOL-Key; this gets dropped
4049     res = dev[0].request("EAPOL_RX " + bssid + " 0203002c0100000000000000000000000000000000000000000000000000000000000000000000000000000000000000")
4050     if "OK" not in res:
4051         raise Exception("EAPOL_RX to wpa_supplicant failed")
4052
4053 def test_ap_wpa2_eap_in_bridge(dev, apdev):
4054     """WPA2-EAP and wpas interface in a bridge"""
4055     br_ifname='sta-br0'
4056     ifname='wlan5'
4057     try:
4058         _test_ap_wpa2_eap_in_bridge(dev, apdev)
4059     finally:
4060         subprocess.call(['ip', 'link', 'set', 'dev', br_ifname, 'down'])
4061         subprocess.call(['brctl', 'delif', br_ifname, ifname])
4062         subprocess.call(['brctl', 'delbr', br_ifname])
4063         subprocess.call(['iw', ifname, 'set', '4addr', 'off'])
4064
4065 def _test_ap_wpa2_eap_in_bridge(dev, apdev):
4066     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4067     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4068
4069     br_ifname='sta-br0'
4070     ifname='wlan5'
4071     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
4072     subprocess.call(['brctl', 'addbr', br_ifname])
4073     subprocess.call(['brctl', 'setfd', br_ifname, '0'])
4074     subprocess.call(['ip', 'link', 'set', 'dev', br_ifname, 'up'])
4075     subprocess.call(['iw', ifname, 'set', '4addr', 'on'])
4076     subprocess.check_call(['brctl', 'addif', br_ifname, ifname])
4077     wpas.interface_add(ifname, br_ifname=br_ifname)
4078     wpas.dump_monitor()
4079
4080     id = eap_connect(wpas, apdev[0], "PAX", "pax.user@example.com",
4081                      password_hex="0123456789abcdef0123456789abcdef")
4082     wpas.dump_monitor()
4083     eap_reauth(wpas, "PAX")
4084     wpas.dump_monitor()
4085     # Try again as a regression test for packet socket workaround
4086     eap_reauth(wpas, "PAX")
4087     wpas.dump_monitor()
4088     wpas.request("DISCONNECT")
4089     wpas.wait_disconnected()
4090     wpas.dump_monitor()
4091     wpas.request("RECONNECT")
4092     wpas.wait_connected()
4093     wpas.dump_monitor()
4094
4095 def test_ap_wpa2_eap_session_ticket(dev, apdev):
4096     """WPA2-Enterprise connection using EAP-TTLS and TLS session ticket enabled"""
4097     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4098     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4099     key_mgmt = hapd.get_config()['key_mgmt']
4100     if key_mgmt.split(' ')[0] != "WPA-EAP":
4101         raise Exception("Unexpected GET_CONFIG(key_mgmt): " + key_mgmt)
4102     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
4103                 anonymous_identity="ttls", password="password",
4104                 ca_cert="auth_serv/ca.pem",
4105                 phase1="tls_disable_session_ticket=0", phase2="auth=PAP")
4106     eap_reauth(dev[0], "TTLS")
4107
4108 def test_ap_wpa2_eap_no_workaround(dev, apdev):
4109     """WPA2-Enterprise connection using EAP-TTLS and eap_workaround=0"""
4110     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4111     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4112     key_mgmt = hapd.get_config()['key_mgmt']
4113     if key_mgmt.split(' ')[0] != "WPA-EAP":
4114         raise Exception("Unexpected GET_CONFIG(key_mgmt): " + key_mgmt)
4115     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
4116                 anonymous_identity="ttls", password="password",
4117                 ca_cert="auth_serv/ca.pem", eap_workaround='0',
4118                 phase2="auth=PAP")
4119     eap_reauth(dev[0], "TTLS")
4120
4121 def test_ap_wpa2_eap_tls_check_crl(dev, apdev):
4122     """EAP-TLS and server checking CRL"""
4123     params = int_eap_server_params()
4124     params['check_crl'] = '1'
4125     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4126
4127     # check_crl=1 and no CRL available --> reject connection
4128     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4129                 client_cert="auth_serv/user.pem",
4130                 private_key="auth_serv/user.key", expect_failure=True)
4131     dev[0].request("REMOVE_NETWORK all")
4132
4133     hapd.disable()
4134     hapd.set("ca_cert", "auth_serv/ca-and-crl.pem")
4135     hapd.enable()
4136
4137     # check_crl=1 and valid CRL --> accept
4138     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4139                 client_cert="auth_serv/user.pem",
4140                 private_key="auth_serv/user.key")
4141     dev[0].request("REMOVE_NETWORK all")
4142
4143     hapd.disable()
4144     hapd.set("check_crl", "2")
4145     hapd.enable()
4146
4147     # check_crl=2 and valid CRL --> accept
4148     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4149                 client_cert="auth_serv/user.pem",
4150                 private_key="auth_serv/user.key")
4151     dev[0].request("REMOVE_NETWORK all")
4152
4153 def test_ap_wpa2_eap_tls_oom(dev, apdev):
4154     """EAP-TLS and OOM"""
4155     check_subject_match_support(dev[0])
4156     check_altsubject_match_support(dev[0])
4157     check_domain_match(dev[0])
4158     check_domain_match_full(dev[0])
4159
4160     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4161     hostapd.add_ap(apdev[0]['ifname'], params)
4162
4163     tests = [ (1, "tls_connection_set_subject_match"),
4164               (2, "tls_connection_set_subject_match"),
4165               (3, "tls_connection_set_subject_match"),
4166               (4, "tls_connection_set_subject_match") ]
4167     for count, func in tests:
4168         with alloc_fail(dev[0], count, func):
4169             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4170                            identity="tls user", ca_cert="auth_serv/ca.pem",
4171                            client_cert="auth_serv/user.pem",
4172                            private_key="auth_serv/user.key",
4173                            subject_match="/C=FI/O=w1.fi/CN=server.w1.fi",
4174                            altsubject_match="EMAIL:noone@example.com;DNS:server.w1.fi;URI:http://example.com/",
4175                            domain_suffix_match="server.w1.fi",
4176                            domain_match="server.w1.fi",
4177                            wait_connect=False, scan_freq="2412")
4178             # TLS parameter configuration error results in CTRL-REQ-PASSPHRASE
4179             ev = dev[0].wait_event(["CTRL-REQ-PASSPHRASE"], timeout=5)
4180             if ev is None:
4181                 raise Exception("No passphrase request")
4182             dev[0].request("REMOVE_NETWORK all")
4183             dev[0].wait_disconnected()
4184
4185 def test_ap_wpa2_eap_tls_macacl(dev, apdev):
4186     """WPA2-Enterprise connection using MAC ACL"""
4187     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4188     params["macaddr_acl"] = "2"
4189     hostapd.add_ap(apdev[0]['ifname'], params)
4190     eap_connect(dev[1], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4191                 client_cert="auth_serv/user.pem",
4192                 private_key="auth_serv/user.key")
4193
4194 def test_ap_wpa2_eap_oom(dev, apdev):
4195     """EAP server and OOM"""
4196     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4197     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4198     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
4199
4200     with alloc_fail(hapd, 1, "eapol_auth_alloc"):
4201         # The first attempt fails, but STA will send EAPOL-Start to retry and
4202         # that succeeds.
4203         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4204                        identity="tls user", ca_cert="auth_serv/ca.pem",
4205                        client_cert="auth_serv/user.pem",
4206                        private_key="auth_serv/user.key",
4207                        scan_freq="2412")
4208
4209 def check_tls_ver(dev, ap, phase1, expected):
4210     eap_connect(dev, ap, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4211                 client_cert="auth_serv/user.pem",
4212                 private_key="auth_serv/user.key",
4213                 phase1=phase1)
4214     ver = dev.get_status_field("eap_tls_version")
4215     if ver != expected:
4216         raise Exception("Unexpected TLS version (expected %s): %s" % (expected, ver))
4217
4218 def test_ap_wpa2_eap_tls_versions(dev, apdev):
4219     """EAP-TLS and TLS version configuration"""
4220     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4221     hostapd.add_ap(apdev[0]['ifname'], params)
4222
4223     tls = dev[0].request("GET tls_library")
4224     if tls.startswith("OpenSSL"):
4225         if "build=OpenSSL 1.0.2" in tls and "run=OpenSSL 1.0.2" in tls:
4226             check_tls_ver(dev[0], apdev[0],
4227                           "tls_disable_tlsv1_0=1 tls_disable_tlsv1_1=1",
4228                           "TLSv1.2")
4229     elif tls.startswith("internal"):
4230         check_tls_ver(dev[0], apdev[0],
4231                       "tls_disable_tlsv1_0=1 tls_disable_tlsv1_1=1", "TLSv1.2")
4232     check_tls_ver(dev[1], apdev[0],
4233                   "tls_disable_tlsv1_0=1 tls_disable_tlsv1_2=1", "TLSv1.1")
4234     check_tls_ver(dev[2], apdev[0],
4235                   "tls_disable_tlsv1_1=1 tls_disable_tlsv1_2=1", "TLSv1")
4236
4237 def test_rsn_ie_proto_eap_sta(dev, apdev):
4238     """RSN element protocol testing for EAP cases on STA side"""
4239     bssid = apdev[0]['bssid']
4240     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4241     # This is the RSN element used normally by hostapd
4242     params['own_ie_override'] = '30140100000fac040100000fac040100000fac010c00'
4243     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4244     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="GPSK",
4245                         identity="gpsk user",
4246                         password="abcdefghijklmnop0123456789abcdef",
4247                         scan_freq="2412")
4248
4249     tests = [ ('No RSN Capabilities field',
4250                '30120100000fac040100000fac040100000fac01'),
4251               ('No AKM Suite fields',
4252                '300c0100000fac040100000fac04'),
4253               ('No Pairwise Cipher Suite fields',
4254                '30060100000fac04'),
4255               ('No Group Data Cipher Suite field',
4256                '30020100') ]
4257     for txt,ie in tests:
4258         dev[0].request("DISCONNECT")
4259         dev[0].wait_disconnected()
4260         logger.info(txt)
4261         hapd.disable()
4262         hapd.set('own_ie_override', ie)
4263         hapd.enable()
4264         dev[0].request("BSS_FLUSH 0")
4265         dev[0].scan_for_bss(bssid, 2412, force_scan=True, only_new=True)
4266         dev[0].select_network(id, freq=2412)
4267         dev[0].wait_connected()
4268
4269     dev[0].request("DISCONNECT")
4270     dev[0].wait_disconnected()
4271     dev[0].flush_scan_cache()
4272
4273 def check_tls_session_resumption_capa(dev, hapd):
4274     tls = hapd.request("GET tls_library")
4275     if not tls.startswith("OpenSSL"):
4276         raise HwsimSkip("hostapd TLS library is not OpenSSL: " + tls)
4277
4278     tls = dev.request("GET tls_library")
4279     if not tls.startswith("OpenSSL"):
4280         raise HwsimSkip("Session resumption not supported with this TLS library: " + tls)
4281
4282 def test_eap_ttls_pap_session_resumption(dev, apdev):
4283     """EAP-TTLS/PAP session resumption"""
4284     params = int_eap_server_params()
4285     params['tls_session_lifetime'] = '60'
4286     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4287     check_tls_session_resumption_capa(dev[0], hapd)
4288     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
4289                 anonymous_identity="ttls", password="password",
4290                 ca_cert="auth_serv/ca.pem", eap_workaround='0',
4291                 phase2="auth=PAP")
4292     if dev[0].get_status_field("tls_session_reused") != '0':
4293         raise Exception("Unexpected session resumption on the first connection")
4294
4295     dev[0].request("REAUTHENTICATE")
4296     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4297     if ev is None:
4298         raise Exception("EAP success timed out")
4299     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4300     if ev is None:
4301         raise Exception("Key handshake with the AP timed out")
4302     if dev[0].get_status_field("tls_session_reused") != '1':
4303         raise Exception("Session resumption not used on the second connection")
4304
4305 def test_eap_ttls_chap_session_resumption(dev, apdev):
4306     """EAP-TTLS/CHAP session resumption"""
4307     params = int_eap_server_params()
4308     params['tls_session_lifetime'] = '60'
4309     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4310     check_tls_session_resumption_capa(dev[0], hapd)
4311     eap_connect(dev[0], apdev[0], "TTLS", "chap user",
4312                 anonymous_identity="ttls", password="password",
4313                 ca_cert="auth_serv/ca.der", phase2="auth=CHAP")
4314     if dev[0].get_status_field("tls_session_reused") != '0':
4315         raise Exception("Unexpected session resumption on the first connection")
4316
4317     dev[0].request("REAUTHENTICATE")
4318     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4319     if ev is None:
4320         raise Exception("EAP success timed out")
4321     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4322     if ev is None:
4323         raise Exception("Key handshake with the AP timed out")
4324     if dev[0].get_status_field("tls_session_reused") != '1':
4325         raise Exception("Session resumption not used on the second connection")
4326
4327 def test_eap_ttls_mschap_session_resumption(dev, apdev):
4328     """EAP-TTLS/MSCHAP session resumption"""
4329     check_domain_suffix_match(dev[0])
4330     params = int_eap_server_params()
4331     params['tls_session_lifetime'] = '60'
4332     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4333     check_tls_session_resumption_capa(dev[0], hapd)
4334     eap_connect(dev[0], apdev[0], "TTLS", "mschap user",
4335                 anonymous_identity="ttls", password="password",
4336                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
4337                 domain_suffix_match="server.w1.fi")
4338     if dev[0].get_status_field("tls_session_reused") != '0':
4339         raise Exception("Unexpected session resumption on the first connection")
4340
4341     dev[0].request("REAUTHENTICATE")
4342     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4343     if ev is None:
4344         raise Exception("EAP success timed out")
4345     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4346     if ev is None:
4347         raise Exception("Key handshake with the AP timed out")
4348     if dev[0].get_status_field("tls_session_reused") != '1':
4349         raise Exception("Session resumption not used on the second connection")
4350
4351 def test_eap_ttls_mschapv2_session_resumption(dev, apdev):
4352     """EAP-TTLS/MSCHAPv2 session resumption"""
4353     check_domain_suffix_match(dev[0])
4354     check_eap_capa(dev[0], "MSCHAPV2")
4355     params = int_eap_server_params()
4356     params['tls_session_lifetime'] = '60'
4357     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4358     check_tls_session_resumption_capa(dev[0], hapd)
4359     eap_connect(dev[0], apdev[0], "TTLS", "DOMAIN\mschapv2 user",
4360                 anonymous_identity="ttls", password="password",
4361                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
4362                 domain_suffix_match="server.w1.fi")
4363     if dev[0].get_status_field("tls_session_reused") != '0':
4364         raise Exception("Unexpected session resumption on the first connection")
4365
4366     dev[0].request("REAUTHENTICATE")
4367     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4368     if ev is None:
4369         raise Exception("EAP success timed out")
4370     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4371     if ev is None:
4372         raise Exception("Key handshake with the AP timed out")
4373     if dev[0].get_status_field("tls_session_reused") != '1':
4374         raise Exception("Session resumption not used on the second connection")
4375
4376 def test_eap_ttls_eap_gtc_session_resumption(dev, apdev):
4377     """EAP-TTLS/EAP-GTC session resumption"""
4378     params = int_eap_server_params()
4379     params['tls_session_lifetime'] = '60'
4380     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4381     check_tls_session_resumption_capa(dev[0], hapd)
4382     eap_connect(dev[0], apdev[0], "TTLS", "user",
4383                 anonymous_identity="ttls", password="password",
4384                 ca_cert="auth_serv/ca.pem", phase2="autheap=GTC")
4385     if dev[0].get_status_field("tls_session_reused") != '0':
4386         raise Exception("Unexpected session resumption on the first connection")
4387
4388     dev[0].request("REAUTHENTICATE")
4389     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4390     if ev is None:
4391         raise Exception("EAP success timed out")
4392     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4393     if ev is None:
4394         raise Exception("Key handshake with the AP timed out")
4395     if dev[0].get_status_field("tls_session_reused") != '1':
4396         raise Exception("Session resumption not used on the second connection")
4397
4398 def test_eap_ttls_no_session_resumption(dev, apdev):
4399     """EAP-TTLS session resumption disabled on server"""
4400     params = int_eap_server_params()
4401     params['tls_session_lifetime'] = '0'
4402     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4403     eap_connect(dev[0], apdev[0], "TTLS", "pap user",
4404                 anonymous_identity="ttls", password="password",
4405                 ca_cert="auth_serv/ca.pem", eap_workaround='0',
4406                 phase2="auth=PAP")
4407     if dev[0].get_status_field("tls_session_reused") != '0':
4408         raise Exception("Unexpected session resumption on the first connection")
4409
4410     dev[0].request("REAUTHENTICATE")
4411     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4412     if ev is None:
4413         raise Exception("EAP success timed out")
4414     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4415     if ev is None:
4416         raise Exception("Key handshake with the AP timed out")
4417     if dev[0].get_status_field("tls_session_reused") != '0':
4418         raise Exception("Unexpected session resumption on the second connection")
4419
4420 def test_eap_peap_session_resumption(dev, apdev):
4421     """EAP-PEAP session resumption"""
4422     params = int_eap_server_params()
4423     params['tls_session_lifetime'] = '60'
4424     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4425     check_tls_session_resumption_capa(dev[0], hapd)
4426     eap_connect(dev[0], apdev[0], "PEAP", "user",
4427                 anonymous_identity="peap", password="password",
4428                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
4429     if dev[0].get_status_field("tls_session_reused") != '0':
4430         raise Exception("Unexpected session resumption on the first connection")
4431
4432     dev[0].request("REAUTHENTICATE")
4433     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4434     if ev is None:
4435         raise Exception("EAP success timed out")
4436     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4437     if ev is None:
4438         raise Exception("Key handshake with the AP timed out")
4439     if dev[0].get_status_field("tls_session_reused") != '1':
4440         raise Exception("Session resumption not used on the second connection")
4441
4442 def test_eap_peap_session_resumption_crypto_binding(dev, apdev):
4443     """EAP-PEAP session resumption with crypto binding"""
4444     params = int_eap_server_params()
4445     params['tls_session_lifetime'] = '60'
4446     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4447     check_tls_session_resumption_capa(dev[0], hapd)
4448     eap_connect(dev[0], apdev[0], "PEAP", "user",
4449                 anonymous_identity="peap", password="password",
4450                 phase1="peapver=0 crypto_binding=2",
4451                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
4452     if dev[0].get_status_field("tls_session_reused") != '0':
4453         raise Exception("Unexpected session resumption on the first connection")
4454
4455     dev[0].request("REAUTHENTICATE")
4456     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4457     if ev is None:
4458         raise Exception("EAP success timed out")
4459     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4460     if ev is None:
4461         raise Exception("Key handshake with the AP timed out")
4462     if dev[0].get_status_field("tls_session_reused") != '1':
4463         raise Exception("Session resumption not used on the second connection")
4464
4465 def test_eap_peap_no_session_resumption(dev, apdev):
4466     """EAP-PEAP session resumption disabled on server"""
4467     params = int_eap_server_params()
4468     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4469     eap_connect(dev[0], apdev[0], "PEAP", "user",
4470                 anonymous_identity="peap", password="password",
4471                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
4472     if dev[0].get_status_field("tls_session_reused") != '0':
4473         raise Exception("Unexpected session resumption on the first connection")
4474
4475     dev[0].request("REAUTHENTICATE")
4476     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4477     if ev is None:
4478         raise Exception("EAP success timed out")
4479     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4480     if ev is None:
4481         raise Exception("Key handshake with the AP timed out")
4482     if dev[0].get_status_field("tls_session_reused") != '0':
4483         raise Exception("Unexpected session resumption on the second connection")
4484
4485 def test_eap_tls_session_resumption(dev, apdev):
4486     """EAP-TLS session resumption"""
4487     params = int_eap_server_params()
4488     params['tls_session_lifetime'] = '60'
4489     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4490     check_tls_session_resumption_capa(dev[0], hapd)
4491     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4492                 client_cert="auth_serv/user.pem",
4493                 private_key="auth_serv/user.key")
4494     if dev[0].get_status_field("tls_session_reused") != '0':
4495         raise Exception("Unexpected session resumption on the first connection")
4496
4497     dev[0].request("REAUTHENTICATE")
4498     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4499     if ev is None:
4500         raise Exception("EAP success timed out")
4501     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4502     if ev is None:
4503         raise Exception("Key handshake with the AP timed out")
4504     if dev[0].get_status_field("tls_session_reused") != '1':
4505         raise Exception("Session resumption not used on the second connection")
4506
4507     dev[0].request("REAUTHENTICATE")
4508     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4509     if ev is None:
4510         raise Exception("EAP success timed out")
4511     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4512     if ev is None:
4513         raise Exception("Key handshake with the AP timed out")
4514     if dev[0].get_status_field("tls_session_reused") != '1':
4515         raise Exception("Session resumption not used on the third connection")
4516
4517 def test_eap_tls_session_resumption_expiration(dev, apdev):
4518     """EAP-TLS session resumption"""
4519     params = int_eap_server_params()
4520     params['tls_session_lifetime'] = '1'
4521     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4522     check_tls_session_resumption_capa(dev[0], hapd)
4523     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4524                 client_cert="auth_serv/user.pem",
4525                 private_key="auth_serv/user.key")
4526     if dev[0].get_status_field("tls_session_reused") != '0':
4527         raise Exception("Unexpected session resumption on the first connection")
4528
4529     # Allow multiple attempts since OpenSSL may not expire the cached entry
4530     # immediately.
4531     for i in range(10):
4532         time.sleep(1.2)
4533
4534         dev[0].request("REAUTHENTICATE")
4535         ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4536         if ev is None:
4537             raise Exception("EAP success timed out")
4538         ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4539         if ev is None:
4540             raise Exception("Key handshake with the AP timed out")
4541         if dev[0].get_status_field("tls_session_reused") == '0':
4542             break
4543     if dev[0].get_status_field("tls_session_reused") != '0':
4544         raise Exception("Session resumption used after lifetime expiration")
4545
4546 def test_eap_tls_no_session_resumption(dev, apdev):
4547     """EAP-TLS session resumption disabled on server"""
4548     params = int_eap_server_params()
4549     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4550     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4551                 client_cert="auth_serv/user.pem",
4552                 private_key="auth_serv/user.key")
4553     if dev[0].get_status_field("tls_session_reused") != '0':
4554         raise Exception("Unexpected session resumption on the first connection")
4555
4556     dev[0].request("REAUTHENTICATE")
4557     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4558     if ev is None:
4559         raise Exception("EAP success timed out")
4560     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4561     if ev is None:
4562         raise Exception("Key handshake with the AP timed out")
4563     if dev[0].get_status_field("tls_session_reused") != '0':
4564         raise Exception("Unexpected session resumption on the second connection")
4565
4566 def test_eap_tls_session_resumption_radius(dev, apdev):
4567     """EAP-TLS session resumption (RADIUS)"""
4568     params = { "ssid": "as", "beacon_int": "2000",
4569                "radius_server_clients": "auth_serv/radius_clients.conf",
4570                "radius_server_auth_port": '18128',
4571                "eap_server": "1",
4572                "eap_user_file": "auth_serv/eap_user.conf",
4573                "ca_cert": "auth_serv/ca.pem",
4574                "server_cert": "auth_serv/server.pem",
4575                "private_key": "auth_serv/server.key",
4576                "tls_session_lifetime": "60" }
4577     authsrv = hostapd.add_ap(apdev[1]['ifname'], params)
4578     check_tls_session_resumption_capa(dev[0], authsrv)
4579
4580     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4581     params['auth_server_port'] = "18128"
4582     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4583     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4584                 client_cert="auth_serv/user.pem",
4585                 private_key="auth_serv/user.key")
4586     if dev[0].get_status_field("tls_session_reused") != '0':
4587         raise Exception("Unexpected session resumption on the first connection")
4588
4589     dev[0].request("REAUTHENTICATE")
4590     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4591     if ev is None:
4592         raise Exception("EAP success timed out")
4593     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4594     if ev is None:
4595         raise Exception("Key handshake with the AP timed out")
4596     if dev[0].get_status_field("tls_session_reused") != '1':
4597         raise Exception("Session resumption not used on the second connection")
4598
4599 def test_eap_tls_no_session_resumption_radius(dev, apdev):
4600     """EAP-TLS session resumption disabled (RADIUS)"""
4601     params = { "ssid": "as", "beacon_int": "2000",
4602                "radius_server_clients": "auth_serv/radius_clients.conf",
4603                "radius_server_auth_port": '18128',
4604                "eap_server": "1",
4605                "eap_user_file": "auth_serv/eap_user.conf",
4606                "ca_cert": "auth_serv/ca.pem",
4607                "server_cert": "auth_serv/server.pem",
4608                "private_key": "auth_serv/server.key",
4609                "tls_session_lifetime": "0" }
4610     hostapd.add_ap(apdev[1]['ifname'], params)
4611
4612     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4613     params['auth_server_port'] = "18128"
4614     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4615     eap_connect(dev[0], apdev[0], "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4616                 client_cert="auth_serv/user.pem",
4617                 private_key="auth_serv/user.key")
4618     if dev[0].get_status_field("tls_session_reused") != '0':
4619         raise Exception("Unexpected session resumption on the first connection")
4620
4621     dev[0].request("REAUTHENTICATE")
4622     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4623     if ev is None:
4624         raise Exception("EAP success timed out")
4625     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4626     if ev is None:
4627         raise Exception("Key handshake with the AP timed out")
4628     if dev[0].get_status_field("tls_session_reused") != '0':
4629         raise Exception("Unexpected session resumption on the second connection")
4630
4631 def test_eap_mschapv2_errors(dev, apdev):
4632     """EAP-MSCHAPv2 error cases"""
4633     check_eap_capa(dev[0], "MSCHAPV2")
4634     check_eap_capa(dev[0], "FAST")
4635
4636     params = hostapd.wpa2_eap_params(ssid="test-wpa-eap")
4637     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4638     dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="MSCHAPV2",
4639                    identity="phase1-user", password="password",
4640                    scan_freq="2412")
4641     dev[0].request("REMOVE_NETWORK all")
4642     dev[0].wait_disconnected()
4643
4644     tests = [ (1, "hash_nt_password_hash;mschapv2_derive_response"),
4645               (1, "nt_password_hash;mschapv2_derive_response"),
4646               (1, "nt_password_hash;=mschapv2_derive_response"),
4647               (1, "generate_nt_response;mschapv2_derive_response"),
4648               (1, "generate_authenticator_response;mschapv2_derive_response"),
4649               (1, "nt_password_hash;=mschapv2_derive_response"),
4650               (1, "get_master_key;mschapv2_derive_response"),
4651               (1, "os_get_random;eap_mschapv2_challenge_reply") ]
4652     for count, func in tests:
4653         with fail_test(dev[0], count, func):
4654             dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="MSCHAPV2",
4655                            identity="phase1-user", password="password",
4656                            wait_connect=False, scan_freq="2412")
4657             wait_fail_trigger(dev[0], "GET_FAIL")
4658             dev[0].request("REMOVE_NETWORK all")
4659             dev[0].wait_disconnected()
4660
4661     tests = [ (1, "hash_nt_password_hash;mschapv2_derive_response"),
4662               (1, "hash_nt_password_hash;=mschapv2_derive_response"),
4663               (1, "generate_nt_response_pwhash;mschapv2_derive_response"),
4664               (1, "generate_authenticator_response_pwhash;mschapv2_derive_response") ]
4665     for count, func in tests:
4666         with fail_test(dev[0], count, func):
4667             dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="MSCHAPV2",
4668                            identity="phase1-user",
4669                            password_hex="hash:8846f7eaee8fb117ad06bdd830b7586c",
4670                            wait_connect=False, scan_freq="2412")
4671             wait_fail_trigger(dev[0], "GET_FAIL")
4672             dev[0].request("REMOVE_NETWORK all")
4673             dev[0].wait_disconnected()
4674
4675     tests = [ (1, "eap_mschapv2_init"),
4676               (1, "eap_msg_alloc;eap_mschapv2_challenge_reply"),
4677               (1, "eap_msg_alloc;eap_mschapv2_success"),
4678               (1, "eap_mschapv2_getKey") ]
4679     for count, func in tests:
4680         with alloc_fail(dev[0], count, func):
4681             dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="MSCHAPV2",
4682                            identity="phase1-user", password="password",
4683                            wait_connect=False, scan_freq="2412")
4684             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4685             dev[0].request("REMOVE_NETWORK all")
4686             dev[0].wait_disconnected()
4687
4688     tests = [ (1, "eap_msg_alloc;eap_mschapv2_failure") ]
4689     for count, func in tests:
4690         with alloc_fail(dev[0], count, func):
4691             dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="MSCHAPV2",
4692                            identity="phase1-user", password="wrong password",
4693                            wait_connect=False, scan_freq="2412")
4694             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4695             dev[0].request("REMOVE_NETWORK all")
4696             dev[0].wait_disconnected()
4697
4698     tests = [ (2, "eap_mschapv2_init"),
4699               (3, "eap_mschapv2_init") ]
4700     for count, func in tests:
4701         with alloc_fail(dev[0], count, func):
4702             dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="FAST",
4703                            anonymous_identity="FAST", identity="user",
4704                            password="password",
4705                            ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
4706                            phase1="fast_provisioning=1",
4707                            pac_file="blob://fast_pac",
4708                            wait_connect=False, scan_freq="2412")
4709             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4710             dev[0].request("REMOVE_NETWORK all")
4711             dev[0].wait_disconnected()
4712
4713 def test_eap_gpsk_errors(dev, apdev):
4714     """EAP-GPSK error cases"""
4715     params = hostapd.wpa2_eap_params(ssid="test-wpa-eap")
4716     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4717     dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="GPSK",
4718                    identity="gpsk user",
4719                    password="abcdefghijklmnop0123456789abcdef",
4720                    scan_freq="2412")
4721     dev[0].request("REMOVE_NETWORK all")
4722     dev[0].wait_disconnected()
4723
4724     tests = [ (1, "os_get_random;eap_gpsk_send_gpsk_2", None),
4725               (1, "eap_gpsk_derive_session_id;eap_gpsk_send_gpsk_2",
4726                "cipher=1"),
4727               (1, "eap_gpsk_derive_session_id;eap_gpsk_send_gpsk_2",
4728                "cipher=2"),
4729               (1, "eap_gpsk_derive_keys_helper", None),
4730               (2, "eap_gpsk_derive_keys_helper", None),
4731               (1, "eap_gpsk_compute_mic_aes;eap_gpsk_compute_mic;eap_gpsk_send_gpsk_2",
4732                "cipher=1"),
4733               (1, "hmac_sha256;eap_gpsk_compute_mic;eap_gpsk_send_gpsk_2",
4734                "cipher=2"),
4735               (1, "eap_gpsk_compute_mic;eap_gpsk_validate_gpsk_3_mic", None),
4736               (1, "eap_gpsk_compute_mic;eap_gpsk_send_gpsk_4", None),
4737               (1, "eap_gpsk_derive_mid_helper", None) ]
4738     for count, func, phase1 in tests:
4739         with fail_test(dev[0], count, func):
4740             dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="GPSK",
4741                            identity="gpsk user",
4742                            password="abcdefghijklmnop0123456789abcdef",
4743                            phase1=phase1,
4744                            wait_connect=False, scan_freq="2412")
4745             wait_fail_trigger(dev[0], "GET_FAIL")
4746             dev[0].request("REMOVE_NETWORK all")
4747             dev[0].wait_disconnected()
4748
4749     tests = [ (1, "eap_gpsk_init"),
4750               (2, "eap_gpsk_init"),
4751               (3, "eap_gpsk_init"),
4752               (1, "eap_gpsk_process_id_server"),
4753               (1, "eap_msg_alloc;eap_gpsk_send_gpsk_2"),
4754               (1, "eap_gpsk_derive_session_id;eap_gpsk_send_gpsk_2"),
4755               (1, "eap_gpsk_derive_mid_helper;eap_gpsk_derive_session_id;eap_gpsk_send_gpsk_2"),
4756               (1, "eap_gpsk_derive_keys"),
4757               (1, "eap_gpsk_derive_keys_helper"),
4758               (1, "eap_msg_alloc;eap_gpsk_send_gpsk_4"),
4759               (1, "eap_gpsk_getKey"),
4760               (1, "eap_gpsk_get_emsk"),
4761               (1, "eap_gpsk_get_session_id") ]
4762     for count, func in tests:
4763         with alloc_fail(dev[0], count, func):
4764             dev[0].request("ERP_FLUSH")
4765             dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="GPSK",
4766                            identity="gpsk user", erp="1",
4767                            password="abcdefghijklmnop0123456789abcdef",
4768                            wait_connect=False, scan_freq="2412")
4769             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4770             dev[0].request("REMOVE_NETWORK all")
4771             dev[0].wait_disconnected()
4772
4773 def test_ap_wpa2_eap_sim_db(dev, apdev, params):
4774     """EAP-SIM DB error cases"""
4775     sockpath = '/tmp/hlr_auc_gw.sock-test'
4776     try:
4777         os.remove(sockpath)
4778     except:
4779         pass
4780     hparams = int_eap_server_params()
4781     hparams['eap_sim_db'] = 'unix:' + sockpath
4782     hapd = hostapd.add_ap(apdev[0]['ifname'], hparams)
4783
4784     # Initial test with hlr_auc_gw socket not available
4785     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
4786                         eap="SIM", identity="1232010000000000",
4787                         password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
4788                         scan_freq="2412", wait_connect=False)
4789     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4790     if ev is None:
4791         raise Exception("EAP-Failure not reported")
4792     dev[0].wait_disconnected()
4793     dev[0].request("DISCONNECT")
4794
4795     # Test with invalid responses and response timeout
4796
4797     class test_handler(SocketServer.DatagramRequestHandler):
4798         def handle(self):
4799             data = self.request[0].strip()
4800             socket = self.request[1]
4801             logger.debug("Received hlr_auc_gw request: " + data)
4802             # EAP-SIM DB: Failed to parse response string
4803             socket.sendto("FOO", self.client_address)
4804             # EAP-SIM DB: Failed to parse response string
4805             socket.sendto("FOO 1", self.client_address)
4806             # EAP-SIM DB: Unknown external response
4807             socket.sendto("FOO 1 2", self.client_address)
4808             logger.info("No proper response - wait for pending eap_sim_db request timeout")
4809
4810     server = SocketServer.UnixDatagramServer(sockpath, test_handler)
4811     server.timeout = 1
4812
4813     dev[0].select_network(id)
4814     server.handle_request()
4815     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4816     if ev is None:
4817         raise Exception("EAP-Failure not reported")
4818     dev[0].wait_disconnected()
4819     dev[0].request("DISCONNECT")
4820
4821     # Test with a valid response
4822
4823     class test_handler2(SocketServer.DatagramRequestHandler):
4824         def handle(self):
4825             data = self.request[0].strip()
4826             socket = self.request[1]
4827             logger.debug("Received hlr_auc_gw request: " + data)
4828             fname = os.path.join(params['logdir'],
4829                                  'hlr_auc_gw.milenage_db')
4830             cmd = subprocess.Popen(['../../hostapd/hlr_auc_gw',
4831                                     '-m', fname, data],
4832                                    stdout=subprocess.PIPE)
4833             res = cmd.stdout.read().strip()
4834             cmd.stdout.close()
4835             logger.debug("hlr_auc_gw response: " + res)
4836             socket.sendto(res, self.client_address)
4837
4838     server.RequestHandlerClass = test_handler2
4839
4840     dev[0].select_network(id)
4841     server.handle_request()
4842     dev[0].wait_connected()
4843     dev[0].request("DISCONNECT")
4844     dev[0].wait_disconnected()
4845
4846 def test_eap_tls_sha512(dev, apdev, params):
4847     """EAP-TLS with SHA512 signature"""
4848     params = int_eap_server_params()
4849     params["ca_cert"] = "auth_serv/sha512-ca.pem"
4850     params["server_cert"] = "auth_serv/sha512-server.pem"
4851     params["private_key"] = "auth_serv/sha512-server.key"
4852     hostapd.add_ap(apdev[0]['ifname'], params)
4853
4854     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4855                    identity="tls user sha512",
4856                    ca_cert="auth_serv/sha512-ca.pem",
4857                    client_cert="auth_serv/sha512-user.pem",
4858                    private_key="auth_serv/sha512-user.key",
4859                    scan_freq="2412")
4860     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4861                    identity="tls user sha512",
4862                    ca_cert="auth_serv/sha512-ca.pem",
4863                    client_cert="auth_serv/sha384-user.pem",
4864                    private_key="auth_serv/sha384-user.key",
4865                    scan_freq="2412")
4866
4867 def test_eap_tls_sha384(dev, apdev, params):
4868     """EAP-TLS with SHA384 signature"""
4869     params = int_eap_server_params()
4870     params["ca_cert"] = "auth_serv/sha512-ca.pem"
4871     params["server_cert"] = "auth_serv/sha384-server.pem"
4872     params["private_key"] = "auth_serv/sha384-server.key"
4873     hostapd.add_ap(apdev[0]['ifname'], params)
4874
4875     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4876                    identity="tls user sha512",
4877                    ca_cert="auth_serv/sha512-ca.pem",
4878                    client_cert="auth_serv/sha512-user.pem",
4879                    private_key="auth_serv/sha512-user.key",
4880                    scan_freq="2412")
4881     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4882                    identity="tls user sha512",
4883                    ca_cert="auth_serv/sha512-ca.pem",
4884                    client_cert="auth_serv/sha384-user.pem",
4885                    private_key="auth_serv/sha384-user.key",
4886                    scan_freq="2412")
4887
4888 def test_ap_wpa2_eap_assoc_rsn(dev, apdev):
4889     """WPA2-Enterprise AP and association request RSN IE differences"""
4890     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4891     hostapd.add_ap(apdev[0]['ifname'], params)
4892
4893     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap-11w")
4894     params["ieee80211w"] = "2"
4895     hostapd.add_ap(apdev[1]['ifname'], params)
4896
4897     # Success cases with optional RSN IE fields removed one by one
4898     tests = [ ("Normal wpa_supplicant assoc req RSN IE",
4899                "30140100000fac040100000fac040100000fac010000"),
4900               ("Extra PMKIDCount field in RSN IE",
4901                "30160100000fac040100000fac040100000fac0100000000"),
4902               ("Extra Group Management Cipher Suite in RSN IE",
4903                "301a0100000fac040100000fac040100000fac0100000000000fac06"),
4904               ("Extra undefined extension field in RSN IE",
4905                "301c0100000fac040100000fac040100000fac0100000000000fac061122"),
4906               ("RSN IE without RSN Capabilities",
4907                "30120100000fac040100000fac040100000fac01"),
4908               ("RSN IE without AKM", "300c0100000fac040100000fac04"),
4909               ("RSN IE without pairwise", "30060100000fac04"),
4910               ("RSN IE without group", "30020100") ]
4911     for title, ie in tests:
4912         logger.info(title)
4913         set_test_assoc_ie(dev[0], ie)
4914         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="GPSK",
4915                        identity="gpsk user",
4916                        password="abcdefghijklmnop0123456789abcdef",
4917                        scan_freq="2412")
4918         dev[0].request("REMOVE_NETWORK all")
4919         dev[0].wait_disconnected()
4920
4921     tests = [ ("Normal wpa_supplicant assoc req RSN IE",
4922                "30140100000fac040100000fac040100000fac01cc00"),
4923               ("Group management cipher included in assoc req RSN IE",
4924                "301a0100000fac040100000fac040100000fac01cc000000000fac06") ]
4925     for title, ie in tests:
4926         logger.info(title)
4927         set_test_assoc_ie(dev[0], ie)
4928         dev[0].connect("test-wpa2-eap-11w", key_mgmt="WPA-EAP", ieee80211w="1",
4929                        eap="GPSK", identity="gpsk user",
4930                        password="abcdefghijklmnop0123456789abcdef",
4931                        scan_freq="2412")
4932         dev[0].request("REMOVE_NETWORK all")
4933         dev[0].wait_disconnected()
4934
4935     tests = [ ("Invalid group cipher", "30060100000fac02", 41),
4936               ("Invalid pairwise cipher", "300c0100000fac040100000fac02", 42) ]
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", key_mgmt="WPA-EAP", eap="GPSK",
4941                        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     tests = [ ("Management frame protection not enabled",
4953                "30140100000fac040100000fac040100000fac010000", 31),
4954               ("Unsupported management group cipher",
4955                "301a0100000fac040100000fac040100000fac01cc000000000fac0b", 31) ]
4956     for title, ie, status in tests:
4957         logger.info(title)
4958         set_test_assoc_ie(dev[0], ie)
4959         dev[0].connect("test-wpa2-eap-11w", key_mgmt="WPA-EAP", ieee80211w="1",
4960                        eap="GPSK", identity="gpsk user",
4961                        password="abcdefghijklmnop0123456789abcdef",
4962                        scan_freq="2412", wait_connect=False)
4963         ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"])
4964         if ev is None:
4965             raise Exception("Association rejection not reported")
4966         if "status_code=" + str(status) not in ev:
4967             raise Exception("Unexpected status code: " + ev)
4968         dev[0].request("REMOVE_NETWORK all")
4969         dev[0].dump_monitor()
4970
4971 def test_eap_tls_ext_cert_check(dev, apdev):
4972     """EAP-TLS and external server certification validation"""
4973     # With internal server certificate chain validation
4974     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4975                         identity="tls user",
4976                         ca_cert="auth_serv/ca.pem",
4977                         client_cert="auth_serv/user.pem",
4978                         private_key="auth_serv/user.key",
4979                         phase1="tls_ext_cert_check=1", scan_freq="2412",
4980                         only_add_network=True)
4981     run_ext_cert_check(dev, apdev, id)
4982
4983 def test_eap_ttls_ext_cert_check(dev, apdev):
4984     """EAP-TTLS and external server certification validation"""
4985     # Without internal server certificate chain validation
4986     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
4987                         identity="pap user", anonymous_identity="ttls",
4988                         password="password", phase2="auth=PAP",
4989                         phase1="tls_ext_cert_check=1", scan_freq="2412",
4990                         only_add_network=True)
4991     run_ext_cert_check(dev, apdev, id)
4992
4993 def test_eap_peap_ext_cert_check(dev, apdev):
4994     """EAP-PEAP and external server certification validation"""
4995     # With internal server certificate chain validation
4996     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PEAP",
4997                         identity="user", anonymous_identity="peap",
4998                         ca_cert="auth_serv/ca.pem",
4999                         password="password", phase2="auth=MSCHAPV2",
5000                         phase1="tls_ext_cert_check=1", scan_freq="2412",
5001                         only_add_network=True)
5002     run_ext_cert_check(dev, apdev, id)
5003
5004 def test_eap_fast_ext_cert_check(dev, apdev):
5005     """EAP-FAST and external server certification validation"""
5006     check_eap_capa(dev[0], "FAST")
5007     # With internal server certificate chain validation
5008     dev[0].request("SET blob fast_pac_auth_ext ")
5009     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
5010                         identity="user", anonymous_identity="FAST",
5011                         ca_cert="auth_serv/ca.pem",
5012                         password="password", phase2="auth=GTC",
5013                         phase1="tls_ext_cert_check=1 fast_provisioning=2",
5014                         pac_file="blob://fast_pac_auth_ext",
5015                         scan_freq="2412",
5016                         only_add_network=True)
5017     run_ext_cert_check(dev, apdev, id)
5018
5019 def run_ext_cert_check(dev, apdev, net_id):
5020     check_ext_cert_check_support(dev[0])
5021     if not openssl_imported:
5022         raise HwsimSkip("OpenSSL python method not available")
5023
5024     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
5025     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
5026
5027     dev[0].select_network(net_id)
5028     certs = {}
5029     while True:
5030         ev = dev[0].wait_event(["CTRL-EVENT-EAP-PEER-CERT",
5031                                 "CTRL-REQ-EXT_CERT_CHECK",
5032                                 "CTRL-EVENT-EAP-SUCCESS"], timeout=10)
5033         if ev is None:
5034             raise Exception("No peer server certificate event seen")
5035         if "CTRL-EVENT-EAP-PEER-CERT" in ev:
5036             depth = None
5037             cert = None
5038             vals = ev.split(' ')
5039             for v in vals:
5040                 if v.startswith("depth="):
5041                     depth = int(v.split('=')[1])
5042                 elif v.startswith("cert="):
5043                     cert = v.split('=')[1]
5044             if depth is not None and cert:
5045                 certs[depth] = binascii.unhexlify(cert)
5046         elif "CTRL-EVENT-EAP-SUCCESS" in ev:
5047             raise Exception("Unexpected EAP-Success")
5048         elif "CTRL-REQ-EXT_CERT_CHECK" in ev:
5049             id = ev.split(':')[0].split('-')[-1]
5050             break
5051     if 0 not in certs:
5052         raise Exception("Server certificate not received")
5053     if 1 not in certs:
5054         raise Exception("Server certificate issuer not received")
5055
5056     cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1,
5057                                            certs[0])
5058     cn = cert.get_subject().commonName
5059     logger.info("Server certificate CN=" + cn)
5060
5061     issuer = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1,
5062                                              certs[1])
5063     icn = issuer.get_subject().commonName
5064     logger.info("Issuer certificate CN=" + icn)
5065
5066     if cn != "server.w1.fi":
5067         raise Exception("Unexpected server certificate CN: " + cn)
5068     if icn != "Root CA":
5069         raise Exception("Unexpected server certificate issuer CN: " + icn)
5070
5071     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=0.1)
5072     if ev:
5073         raise Exception("Unexpected EAP-Success before external check result indication")
5074
5075     dev[0].request("CTRL-RSP-EXT_CERT_CHECK-" + id + ":good")
5076     dev[0].wait_connected()
5077
5078     dev[0].request("DISCONNECT")
5079     dev[0].wait_disconnected()
5080     if "FAIL" in dev[0].request("PMKSA_FLUSH"):
5081         raise Exception("PMKSA_FLUSH failed")
5082     dev[0].request("SET blob fast_pac_auth_ext ")
5083     dev[0].request("RECONNECT")
5084
5085     ev = dev[0].wait_event(["CTRL-REQ-EXT_CERT_CHECK"], timeout=10)
5086     if ev is None:
5087         raise Exception("No peer server certificate event seen (2)")
5088     id = ev.split(':')[0].split('-')[-1]
5089     dev[0].request("CTRL-RSP-EXT_CERT_CHECK-" + id + ":bad")
5090     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
5091     if ev is None:
5092         raise Exception("EAP-Failure not reported")
5093     dev[0].request("REMOVE_NETWORK all")
5094     dev[0].wait_disconnected()