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