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