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