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