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