tests: Update server and user certificates (2015)
[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 import struct
18 import tempfile
19
20 import hwsim_utils
21 import hostapd
22 from utils import HwsimSkip, alloc_fail, fail_test, skip_with_fips, wait_fail_trigger
23 from wpasupplicant import WpaSupplicant
24 from test_ap_psk import check_mib, find_wpas_process, read_process_memory, verify_not_present, get_key_locations, set_test_assoc_ie
25
26 try:
27     import OpenSSL
28     openssl_imported = True
29 except ImportError:
30     openssl_imported = False
31
32 def check_hlr_auc_gw_support():
33     if not os.path.exists("/tmp/hlr_auc_gw.sock"):
34         raise HwsimSkip("No hlr_auc_gw available")
35
36 def check_eap_capa(dev, method):
37     res = dev.get_capability("eap")
38     if method not in res:
39         raise HwsimSkip("EAP method %s not supported in the build" % method)
40
41 def check_subject_match_support(dev):
42     tls = dev.request("GET tls_library")
43     if not tls.startswith("OpenSSL"):
44         raise HwsimSkip("subject_match not supported with this TLS library: " + tls)
45
46 def check_altsubject_match_support(dev):
47     tls = dev.request("GET tls_library")
48     if not tls.startswith("OpenSSL"):
49         raise HwsimSkip("altsubject_match not supported with this TLS library: " + tls)
50
51 def check_domain_match(dev):
52     tls = dev.request("GET tls_library")
53     if tls.startswith("internal"):
54         raise HwsimSkip("domain_match not supported with this TLS library: " + tls)
55
56 def check_domain_suffix_match(dev):
57     tls = dev.request("GET tls_library")
58     if tls.startswith("internal"):
59         raise HwsimSkip("domain_suffix_match not supported with this TLS library: " + tls)
60
61 def check_domain_match_full(dev):
62     tls = dev.request("GET tls_library")
63     if not tls.startswith("OpenSSL"):
64         raise HwsimSkip("domain_suffix_match requires full match with this TLS library: " + tls)
65
66 def check_cert_probe_support(dev):
67     tls = dev.request("GET tls_library")
68     if not tls.startswith("OpenSSL") and not tls.startswith("internal"):
69         raise HwsimSkip("Certificate probing not supported with this TLS library: " + tls)
70
71 def check_ext_cert_check_support(dev):
72     tls = dev.request("GET tls_library")
73     if not tls.startswith("OpenSSL"):
74         raise HwsimSkip("ext_cert_check not supported with this TLS library: " + tls)
75
76 def check_ocsp_support(dev):
77     tls = dev.request("GET tls_library")
78     #if tls.startswith("internal"):
79     #    raise HwsimSkip("OCSP not supported with this TLS library: " + tls)
80     #if "BoringSSL" in tls:
81     #    raise HwsimSkip("OCSP not supported with this TLS library: " + tls)
82
83 def check_ocsp_multi_support(dev):
84     tls = dev.request("GET tls_library")
85     if not tls.startswith("internal"):
86         raise HwsimSkip("OCSP-multi not supported with this TLS library: " + tls)
87     as_hapd = hostapd.Hostapd("as")
88     res = as_hapd.request("GET tls_library")
89     del as_hapd
90     if not res.startswith("internal"):
91         raise HwsimSkip("Authentication server does not support ocsp_multi")
92
93 def check_pkcs12_support(dev):
94     tls = dev.request("GET tls_library")
95     #if tls.startswith("internal"):
96     #    raise HwsimSkip("PKCS#12 not supported with this TLS library: " + tls)
97
98 def check_dh_dsa_support(dev):
99     tls = dev.request("GET tls_library")
100     if tls.startswith("internal"):
101         raise HwsimSkip("DH DSA not supported with this TLS library: " + tls)
102
103 def read_pem(fname):
104     with open(fname, "r") as f:
105         lines = f.readlines()
106         copy = False
107         cert = ""
108         for l in lines:
109             if "-----END" in l:
110                 break
111             if copy:
112                 cert = cert + l
113             if "-----BEGIN" in l:
114                 copy = True
115     return base64.b64decode(cert)
116
117 def eap_connect(dev, hapd, method, identity,
118                 sha256=False, expect_failure=False, local_error_report=False,
119                 maybe_local_error=False, **kwargs):
120     id = dev.connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
121                      eap=method, identity=identity,
122                      wait_connect=False, scan_freq="2412", ieee80211w="1",
123                      **kwargs)
124     eap_check_auth(dev, method, True, sha256=sha256,
125                    expect_failure=expect_failure,
126                    local_error_report=local_error_report,
127                    maybe_local_error=maybe_local_error)
128     if expect_failure:
129         return id
130     ev = hapd.wait_event([ "AP-STA-CONNECTED" ], timeout=5)
131     if ev is None:
132         raise Exception("No connection event received from hostapd")
133     return id
134
135 def eap_check_auth(dev, method, initial, rsn=True, sha256=False,
136                    expect_failure=False, local_error_report=False,
137                    maybe_local_error=False):
138     ev = dev.wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
139     if ev is None:
140         raise Exception("Association and EAP start timed out")
141     ev = dev.wait_event(["CTRL-EVENT-EAP-METHOD",
142                          "CTRL-EVENT-EAP-FAILURE"], timeout=10)
143     if ev is None:
144         raise Exception("EAP method selection timed out")
145     if "CTRL-EVENT-EAP-FAILURE" in ev:
146         if maybe_local_error:
147             return
148         raise Exception("Could not select EAP method")
149     if method not in ev:
150         raise Exception("Unexpected EAP method")
151     if expect_failure:
152         ev = dev.wait_event(["CTRL-EVENT-EAP-FAILURE"])
153         if ev is None:
154             raise Exception("EAP failure timed out")
155         ev = dev.wait_disconnected(timeout=10)
156         if maybe_local_error and "locally_generated=1" in ev:
157             return
158         if not local_error_report:
159             if "reason=23" not in ev:
160                 raise Exception("Proper reason code for disconnection not reported")
161         return
162     ev = dev.wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
163     if ev is None:
164         raise Exception("EAP success timed out")
165
166     if initial:
167         ev = dev.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
168     else:
169         ev = dev.wait_event(["WPA: Key negotiation completed"], timeout=10)
170     if ev is None:
171         raise Exception("Association with the AP timed out")
172     status = dev.get_status()
173     if status["wpa_state"] != "COMPLETED":
174         raise Exception("Connection not completed")
175
176     if status["suppPortStatus"] != "Authorized":
177         raise Exception("Port not authorized")
178     if "selectedMethod" not in status:
179         logger.info("Status: " + str(status))
180         raise Exception("No selectedMethod in status")
181     if method not in status["selectedMethod"]:
182         raise Exception("Incorrect EAP method status")
183     if sha256:
184         e = "WPA2-EAP-SHA256"
185     elif rsn:
186         e = "WPA2/IEEE 802.1X/EAP"
187     else:
188         e = "WPA/IEEE 802.1X/EAP"
189     if status["key_mgmt"] != e:
190         raise Exception("Unexpected key_mgmt status: " + status["key_mgmt"])
191     return status
192
193 def eap_reauth(dev, method, rsn=True, sha256=False, expect_failure=False):
194     dev.request("REAUTHENTICATE")
195     return eap_check_auth(dev, method, False, rsn=rsn, sha256=sha256,
196                           expect_failure=expect_failure)
197
198 def test_ap_wpa2_eap_sim(dev, apdev):
199     """WPA2-Enterprise connection using EAP-SIM"""
200     check_hlr_auc_gw_support()
201     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
202     hapd = hostapd.add_ap(apdev[0], params)
203     eap_connect(dev[0], hapd, "SIM", "1232010000000000",
204                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581")
205     hwsim_utils.test_connectivity(dev[0], hapd)
206     eap_reauth(dev[0], "SIM")
207
208     eap_connect(dev[1], hapd, "SIM", "1232010000000001",
209                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581")
210     eap_connect(dev[2], hapd, "SIM", "1232010000000002",
211                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
212                 expect_failure=True)
213
214     logger.info("Negative test with incorrect key")
215     dev[0].request("REMOVE_NETWORK all")
216     eap_connect(dev[0], hapd, "SIM", "1232010000000000",
217                 password="ffdca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
218                 expect_failure=True)
219
220     logger.info("Invalid GSM-Milenage key")
221     dev[0].request("REMOVE_NETWORK all")
222     eap_connect(dev[0], hapd, "SIM", "1232010000000000",
223                 password="ffdca4eda45b53cf0f12d7c9c3bc6a",
224                 expect_failure=True)
225
226     logger.info("Invalid GSM-Milenage key(2)")
227     dev[0].request("REMOVE_NETWORK all")
228     eap_connect(dev[0], hapd, "SIM", "1232010000000000",
229                 password="ffdca4eda45b53cf0f12d7c9c3bc6a8q:cb9cccc4b9258e6dca4760379fb82581",
230                 expect_failure=True)
231
232     logger.info("Invalid GSM-Milenage key(3)")
233     dev[0].request("REMOVE_NETWORK all")
234     eap_connect(dev[0], hapd, "SIM", "1232010000000000",
235                 password="ffdca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb8258q",
236                 expect_failure=True)
237
238     logger.info("Invalid GSM-Milenage key(4)")
239     dev[0].request("REMOVE_NETWORK all")
240     eap_connect(dev[0], hapd, "SIM", "1232010000000000",
241                 password="ffdca4eda45b53cf0f12d7c9c3bc6a89qcb9cccc4b9258e6dca4760379fb82581",
242                 expect_failure=True)
243
244     logger.info("Missing key configuration")
245     dev[0].request("REMOVE_NETWORK all")
246     eap_connect(dev[0], hapd, "SIM", "1232010000000000",
247                 expect_failure=True)
248
249 def test_ap_wpa2_eap_sim_sql(dev, apdev, params):
250     """WPA2-Enterprise connection using EAP-SIM (SQL)"""
251     check_hlr_auc_gw_support()
252     try:
253         import sqlite3
254     except ImportError:
255         raise HwsimSkip("No sqlite3 module available")
256     con = sqlite3.connect(os.path.join(params['logdir'], "hostapd.db"))
257     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
258     params['auth_server_port'] = "1814"
259     hapd = hostapd.add_ap(apdev[0], params)
260     eap_connect(dev[0], hapd, "SIM", "1232010000000000",
261                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581")
262
263     logger.info("SIM fast re-authentication")
264     eap_reauth(dev[0], "SIM")
265
266     logger.info("SIM full auth with pseudonym")
267     with con:
268         cur = con.cursor()
269         cur.execute("DELETE FROM reauth WHERE permanent='1232010000000000'")
270     eap_reauth(dev[0], "SIM")
271
272     logger.info("SIM full auth with permanent identity")
273     with con:
274         cur = con.cursor()
275         cur.execute("DELETE FROM reauth WHERE permanent='1232010000000000'")
276         cur.execute("DELETE FROM pseudonyms WHERE permanent='1232010000000000'")
277     eap_reauth(dev[0], "SIM")
278
279     logger.info("SIM reauth with mismatching MK")
280     with con:
281         cur = con.cursor()
282         cur.execute("UPDATE reauth SET mk='0000000000000000000000000000000000000000' WHERE permanent='1232010000000000'")
283     eap_reauth(dev[0], "SIM", expect_failure=True)
284     dev[0].request("REMOVE_NETWORK all")
285
286     eap_connect(dev[0], hapd, "SIM", "1232010000000000",
287                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581")
288     with con:
289         cur = con.cursor()
290         cur.execute("UPDATE reauth SET counter='10' WHERE permanent='1232010000000000'")
291     eap_reauth(dev[0], "SIM")
292     with con:
293         cur = con.cursor()
294         cur.execute("UPDATE reauth SET counter='10' WHERE permanent='1232010000000000'")
295     logger.info("SIM reauth with mismatching counter")
296     eap_reauth(dev[0], "SIM")
297     dev[0].request("REMOVE_NETWORK all")
298
299     eap_connect(dev[0], hapd, "SIM", "1232010000000000",
300                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581")
301     with con:
302         cur = con.cursor()
303         cur.execute("UPDATE reauth SET counter='1001' WHERE permanent='1232010000000000'")
304     logger.info("SIM reauth with max reauth count reached")
305     eap_reauth(dev[0], "SIM")
306
307 def test_ap_wpa2_eap_sim_config(dev, apdev):
308     """EAP-SIM configuration options"""
309     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
310     hapd = hostapd.add_ap(apdev[0], params)
311     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="SIM",
312                    identity="1232010000000000",
313                    password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
314                    phase1="sim_min_num_chal=1",
315                    wait_connect=False, scan_freq="2412")
316     ev = dev[0].wait_event(["EAP: Failed to initialize EAP method: vendor 0 method 18 (SIM)"], timeout=10)
317     if ev is None:
318         raise Exception("No EAP error message seen")
319     dev[0].request("REMOVE_NETWORK all")
320
321     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="SIM",
322                    identity="1232010000000000",
323                    password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
324                    phase1="sim_min_num_chal=4",
325                    wait_connect=False, scan_freq="2412")
326     ev = dev[0].wait_event(["EAP: Failed to initialize EAP method: vendor 0 method 18 (SIM)"], timeout=10)
327     if ev is None:
328         raise Exception("No EAP error message seen (2)")
329     dev[0].request("REMOVE_NETWORK all")
330
331     eap_connect(dev[0], hapd, "SIM", "1232010000000000",
332                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
333                 phase1="sim_min_num_chal=2")
334     eap_connect(dev[1], hapd, "SIM", "1232010000000000",
335                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
336                 anonymous_identity="345678")
337
338 def test_ap_wpa2_eap_sim_ext(dev, apdev):
339     """WPA2-Enterprise connection using EAP-SIM and external GSM auth"""
340     try:
341         _test_ap_wpa2_eap_sim_ext(dev, apdev)
342     finally:
343         dev[0].request("SET external_sim 0")
344
345 def _test_ap_wpa2_eap_sim_ext(dev, apdev):
346     check_hlr_auc_gw_support()
347     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
348     hostapd.add_ap(apdev[0], params)
349     dev[0].request("SET external_sim 1")
350     id = dev[0].connect("test-wpa2-eap", eap="SIM", key_mgmt="WPA-EAP",
351                         identity="1232010000000000",
352                         wait_connect=False, scan_freq="2412")
353     ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=15)
354     if ev is None:
355         raise Exception("Network connected timed out")
356
357     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
358     if ev is None:
359         raise Exception("Wait for external SIM processing request timed out")
360     p = ev.split(':', 2)
361     if p[1] != "GSM-AUTH":
362         raise Exception("Unexpected CTRL-REQ-SIM type")
363     rid = p[0].split('-')[3]
364
365     # IK:CK:RES
366     resp = "00112233445566778899aabbccddeeff:00112233445566778899aabbccddeeff:0011223344"
367     # This will fail during processing, but the ctrl_iface command succeeds
368     dev[0].request("CTRL-RSP-SIM-" + rid + ":UMTS-AUTH:" + resp)
369     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
370     if ev is None:
371         raise Exception("EAP failure not reported")
372     dev[0].request("DISCONNECT")
373     dev[0].wait_disconnected()
374     time.sleep(0.1)
375
376     dev[0].select_network(id, freq="2412")
377     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
378     if ev is None:
379         raise Exception("Wait for external SIM processing request timed out")
380     p = ev.split(':', 2)
381     if p[1] != "GSM-AUTH":
382         raise Exception("Unexpected CTRL-REQ-SIM type")
383     rid = p[0].split('-')[3]
384     # This will fail during GSM auth validation
385     if "OK" not in dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:q"):
386         raise Exception("CTRL-RSP-SIM failed")
387     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
388     if ev is None:
389         raise Exception("EAP failure not reported")
390     dev[0].request("DISCONNECT")
391     dev[0].wait_disconnected()
392     time.sleep(0.1)
393
394     dev[0].select_network(id, freq="2412")
395     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
396     if ev is None:
397         raise Exception("Wait for external SIM processing request timed out")
398     p = ev.split(':', 2)
399     if p[1] != "GSM-AUTH":
400         raise Exception("Unexpected CTRL-REQ-SIM type")
401     rid = p[0].split('-')[3]
402     # This will fail during GSM auth validation
403     if "OK" not in dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:34"):
404         raise Exception("CTRL-RSP-SIM failed")
405     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
406     if ev is None:
407         raise Exception("EAP failure not reported")
408     dev[0].request("DISCONNECT")
409     dev[0].wait_disconnected()
410     time.sleep(0.1)
411
412     dev[0].select_network(id, freq="2412")
413     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
414     if ev is None:
415         raise Exception("Wait for external SIM processing request timed out")
416     p = ev.split(':', 2)
417     if p[1] != "GSM-AUTH":
418         raise Exception("Unexpected CTRL-REQ-SIM type")
419     rid = p[0].split('-')[3]
420     # This will fail during GSM auth validation
421     if "OK" not in dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:0011223344556677"):
422         raise Exception("CTRL-RSP-SIM failed")
423     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
424     if ev is None:
425         raise Exception("EAP failure not reported")
426     dev[0].request("DISCONNECT")
427     dev[0].wait_disconnected()
428     time.sleep(0.1)
429
430     dev[0].select_network(id, freq="2412")
431     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
432     if ev is None:
433         raise Exception("Wait for external SIM processing request timed out")
434     p = ev.split(':', 2)
435     if p[1] != "GSM-AUTH":
436         raise Exception("Unexpected CTRL-REQ-SIM type")
437     rid = p[0].split('-')[3]
438     # This will fail during GSM auth validation
439     if "OK" not in dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:0011223344556677:q"):
440         raise Exception("CTRL-RSP-SIM failed")
441     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
442     if ev is None:
443         raise Exception("EAP failure not reported")
444     dev[0].request("DISCONNECT")
445     dev[0].wait_disconnected()
446     time.sleep(0.1)
447
448     dev[0].select_network(id, freq="2412")
449     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
450     if ev is None:
451         raise Exception("Wait for external SIM processing request timed out")
452     p = ev.split(':', 2)
453     if p[1] != "GSM-AUTH":
454         raise Exception("Unexpected CTRL-REQ-SIM type")
455     rid = p[0].split('-')[3]
456     # This will fail during GSM auth validation
457     if "OK" not in dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:0011223344556677:00112233"):
458         raise Exception("CTRL-RSP-SIM failed")
459     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
460     if ev is None:
461         raise Exception("EAP failure not reported")
462     dev[0].request("DISCONNECT")
463     dev[0].wait_disconnected()
464     time.sleep(0.1)
465
466     dev[0].select_network(id, freq="2412")
467     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
468     if ev is None:
469         raise Exception("Wait for external SIM processing request timed out")
470     p = ev.split(':', 2)
471     if p[1] != "GSM-AUTH":
472         raise Exception("Unexpected CTRL-REQ-SIM type")
473     rid = p[0].split('-')[3]
474     # This will fail during GSM auth validation
475     if "OK" not in dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:0011223344556677:00112233:q"):
476         raise Exception("CTRL-RSP-SIM failed")
477     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
478     if ev is None:
479         raise Exception("EAP failure not reported")
480
481 def test_ap_wpa2_eap_sim_ext_replace_sim(dev, apdev):
482     """EAP-SIM with external GSM auth and replacing SIM without clearing pseudonym id"""
483     try:
484         _test_ap_wpa2_eap_sim_ext_replace_sim(dev, apdev)
485     finally:
486         dev[0].request("SET external_sim 0")
487
488 def _test_ap_wpa2_eap_sim_ext_replace_sim(dev, apdev):
489     check_hlr_auc_gw_support()
490     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
491     hostapd.add_ap(apdev[0], params)
492     dev[0].request("SET external_sim 1")
493     id = dev[0].connect("test-wpa2-eap", eap="SIM", key_mgmt="WPA-EAP",
494                         identity="1232010000000000",
495                         wait_connect=False, scan_freq="2412")
496
497     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
498     if ev is None:
499         raise Exception("Wait for external SIM processing request timed out")
500     p = ev.split(':', 2)
501     if p[1] != "GSM-AUTH":
502         raise Exception("Unexpected CTRL-REQ-SIM type")
503     rid = p[0].split('-')[3]
504     rand = p[2].split(' ')[0]
505
506     res = subprocess.check_output(["../../hostapd/hlr_auc_gw",
507                                    "-m",
508                                    "auth_serv/hlr_auc_gw.milenage_db",
509                                    "GSM-AUTH-REQ 232010000000000 " + rand])
510     if "GSM-AUTH-RESP" not in res:
511         raise Exception("Unexpected hlr_auc_gw response")
512     resp = res.split(' ')[2].rstrip()
513
514     dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:" + resp)
515     dev[0].wait_connected(timeout=15)
516     dev[0].request("DISCONNECT")
517     dev[0].wait_disconnected()
518
519     # Replace SIM, but forget to drop the previous pseudonym identity
520     dev[0].set_network_quoted(id, "identity", "1232010000000009")
521     dev[0].select_network(id, freq="2412")
522
523     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
524     if ev is None:
525         raise Exception("Wait for external SIM processing request timed out")
526     p = ev.split(':', 2)
527     if p[1] != "GSM-AUTH":
528         raise Exception("Unexpected CTRL-REQ-SIM type")
529     rid = p[0].split('-')[3]
530     rand = p[2].split(' ')[0]
531
532     res = subprocess.check_output(["../../hostapd/hlr_auc_gw",
533                                    "-m",
534                                    "auth_serv/hlr_auc_gw.milenage_db",
535                                    "GSM-AUTH-REQ 232010000000009 " + rand])
536     if "GSM-AUTH-RESP" not in res:
537         raise Exception("Unexpected hlr_auc_gw response")
538     resp = res.split(' ')[2].rstrip()
539
540     dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:" + resp)
541     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
542     if ev is None:
543         raise Exception("EAP-Failure not reported")
544     dev[0].request("DISCONNECT")
545     dev[0].wait_disconnected()
546
547 def test_ap_wpa2_eap_sim_ext_replace_sim2(dev, apdev):
548     """EAP-SIM with external GSM auth and replacing SIM and clearing pseudonym identity"""
549     try:
550         _test_ap_wpa2_eap_sim_ext_replace_sim2(dev, apdev)
551     finally:
552         dev[0].request("SET external_sim 0")
553
554 def _test_ap_wpa2_eap_sim_ext_replace_sim2(dev, apdev):
555     check_hlr_auc_gw_support()
556     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
557     hostapd.add_ap(apdev[0], params)
558     dev[0].request("SET external_sim 1")
559     id = dev[0].connect("test-wpa2-eap", eap="SIM", key_mgmt="WPA-EAP",
560                         identity="1232010000000000",
561                         wait_connect=False, scan_freq="2412")
562
563     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
564     if ev is None:
565         raise Exception("Wait for external SIM processing request timed out")
566     p = ev.split(':', 2)
567     if p[1] != "GSM-AUTH":
568         raise Exception("Unexpected CTRL-REQ-SIM type")
569     rid = p[0].split('-')[3]
570     rand = p[2].split(' ')[0]
571
572     res = subprocess.check_output(["../../hostapd/hlr_auc_gw",
573                                    "-m",
574                                    "auth_serv/hlr_auc_gw.milenage_db",
575                                    "GSM-AUTH-REQ 232010000000000 " + rand])
576     if "GSM-AUTH-RESP" not in res:
577         raise Exception("Unexpected hlr_auc_gw response")
578     resp = res.split(' ')[2].rstrip()
579
580     dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:" + resp)
581     dev[0].wait_connected(timeout=15)
582     dev[0].request("DISCONNECT")
583     dev[0].wait_disconnected()
584
585     # Replace SIM and drop the previous pseudonym identity
586     dev[0].set_network_quoted(id, "identity", "1232010000000009")
587     dev[0].set_network(id, "anonymous_identity", "NULL")
588     dev[0].select_network(id, freq="2412")
589
590     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
591     if ev is None:
592         raise Exception("Wait for external SIM processing request timed out")
593     p = ev.split(':', 2)
594     if p[1] != "GSM-AUTH":
595         raise Exception("Unexpected CTRL-REQ-SIM type")
596     rid = p[0].split('-')[3]
597     rand = p[2].split(' ')[0]
598
599     res = subprocess.check_output(["../../hostapd/hlr_auc_gw",
600                                    "-m",
601                                    "auth_serv/hlr_auc_gw.milenage_db",
602                                    "GSM-AUTH-REQ 232010000000009 " + rand])
603     if "GSM-AUTH-RESP" not in res:
604         raise Exception("Unexpected hlr_auc_gw response")
605     resp = res.split(' ')[2].rstrip()
606
607     dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:" + resp)
608     dev[0].wait_connected()
609     dev[0].request("DISCONNECT")
610     dev[0].wait_disconnected()
611
612 def test_ap_wpa2_eap_sim_ext_replace_sim3(dev, apdev):
613     """EAP-SIM with external GSM auth, replacing SIM, and no identity in config"""
614     try:
615         _test_ap_wpa2_eap_sim_ext_replace_sim3(dev, apdev)
616     finally:
617         dev[0].request("SET external_sim 0")
618
619 def _test_ap_wpa2_eap_sim_ext_replace_sim3(dev, apdev):
620     check_hlr_auc_gw_support()
621     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
622     hostapd.add_ap(apdev[0], params)
623     dev[0].request("SET external_sim 1")
624     id = dev[0].connect("test-wpa2-eap", eap="SIM", key_mgmt="WPA-EAP",
625                         wait_connect=False, scan_freq="2412")
626
627     ev = dev[0].wait_event(["CTRL-REQ-IDENTITY"])
628     if ev is None:
629         raise Exception("Request for identity timed out")
630     rid = ev.split(':')[0].split('-')[-1]
631     dev[0].request("CTRL-RSP-IDENTITY-" + rid + ":1232010000000000")
632
633     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
634     if ev is None:
635         raise Exception("Wait for external SIM processing request timed out")
636     p = ev.split(':', 2)
637     if p[1] != "GSM-AUTH":
638         raise Exception("Unexpected CTRL-REQ-SIM type")
639     rid = p[0].split('-')[3]
640     rand = p[2].split(' ')[0]
641
642     res = subprocess.check_output(["../../hostapd/hlr_auc_gw",
643                                    "-m",
644                                    "auth_serv/hlr_auc_gw.milenage_db",
645                                    "GSM-AUTH-REQ 232010000000000 " + rand])
646     if "GSM-AUTH-RESP" not in res:
647         raise Exception("Unexpected hlr_auc_gw response")
648     resp = res.split(' ')[2].rstrip()
649
650     dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:" + resp)
651     dev[0].wait_connected(timeout=15)
652     dev[0].request("DISCONNECT")
653     dev[0].wait_disconnected()
654
655     # Replace SIM and drop the previous permanent and pseudonym identities
656     dev[0].set_network(id, "identity", "NULL")
657     dev[0].set_network(id, "anonymous_identity", "NULL")
658     dev[0].select_network(id, freq="2412")
659
660     ev = dev[0].wait_event(["CTRL-REQ-IDENTITY"])
661     if ev is None:
662         raise Exception("Request for identity timed out")
663     rid = ev.split(':')[0].split('-')[-1]
664     dev[0].request("CTRL-RSP-IDENTITY-" + rid + ":1232010000000009")
665
666     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
667     if ev is None:
668         raise Exception("Wait for external SIM processing request timed out")
669     p = ev.split(':', 2)
670     if p[1] != "GSM-AUTH":
671         raise Exception("Unexpected CTRL-REQ-SIM type")
672     rid = p[0].split('-')[3]
673     rand = p[2].split(' ')[0]
674
675     res = subprocess.check_output(["../../hostapd/hlr_auc_gw",
676                                    "-m",
677                                    "auth_serv/hlr_auc_gw.milenage_db",
678                                    "GSM-AUTH-REQ 232010000000009 " + rand])
679     if "GSM-AUTH-RESP" not in res:
680         raise Exception("Unexpected hlr_auc_gw response")
681     resp = res.split(' ')[2].rstrip()
682
683     dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:" + resp)
684     dev[0].wait_connected()
685     dev[0].request("DISCONNECT")
686     dev[0].wait_disconnected()
687
688 def test_ap_wpa2_eap_sim_ext_auth_fail(dev, apdev):
689     """EAP-SIM with external GSM auth and auth failing"""
690     try:
691         _test_ap_wpa2_eap_sim_ext_auth_fail(dev, apdev)
692     finally:
693         dev[0].request("SET external_sim 0")
694
695 def _test_ap_wpa2_eap_sim_ext_auth_fail(dev, apdev):
696     check_hlr_auc_gw_support()
697     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
698     hostapd.add_ap(apdev[0], params)
699     dev[0].request("SET external_sim 1")
700     id = dev[0].connect("test-wpa2-eap", eap="SIM", key_mgmt="WPA-EAP",
701                         identity="1232010000000000",
702                         wait_connect=False, scan_freq="2412")
703
704     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
705     if ev is None:
706         raise Exception("Wait for external SIM processing request timed out")
707     p = ev.split(':', 2)
708     rid = p[0].split('-')[3]
709     dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-FAIL")
710     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
711     if ev is None:
712         raise Exception("EAP failure not reported")
713     dev[0].request("REMOVE_NETWORK all")
714     dev[0].wait_disconnected()
715
716 def test_ap_wpa2_eap_sim_change_bssid(dev, apdev):
717     """EAP-SIM and external GSM auth to check fast reauth with bssid change"""
718     try:
719         _test_ap_wpa2_eap_sim_change_bssid(dev, apdev)
720     finally:
721         dev[0].request("SET external_sim 0")
722
723 def _test_ap_wpa2_eap_sim_change_bssid(dev, apdev):
724     check_hlr_auc_gw_support()
725     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
726     hostapd.add_ap(apdev[0], params)
727     dev[0].request("SET external_sim 1")
728     id = dev[0].connect("test-wpa2-eap", eap="SIM", key_mgmt="WPA-EAP",
729                         identity="1232010000000000",
730                         wait_connect=False, scan_freq="2412")
731
732     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
733     if ev is None:
734         raise Exception("Wait for external SIM processing request timed out")
735     p = ev.split(':', 2)
736     if p[1] != "GSM-AUTH":
737         raise Exception("Unexpected CTRL-REQ-SIM type")
738     rid = p[0].split('-')[3]
739     rand = p[2].split(' ')[0]
740
741     res = subprocess.check_output(["../../hostapd/hlr_auc_gw",
742                                    "-m",
743                                    "auth_serv/hlr_auc_gw.milenage_db",
744                                    "GSM-AUTH-REQ 232010000000000 " + rand])
745     if "GSM-AUTH-RESP" not in res:
746         raise Exception("Unexpected hlr_auc_gw response")
747     resp = res.split(' ')[2].rstrip()
748
749     dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:" + resp)
750     dev[0].wait_connected(timeout=15)
751
752     # Verify that EAP-SIM Reauthentication can be used after a profile change
753     # that does not affect EAP parameters.
754     dev[0].set_network(id, "bssid", "any")
755     eap_reauth(dev[0], "SIM")
756
757 def test_ap_wpa2_eap_sim_no_change_set(dev, apdev):
758     """EAP-SIM and external GSM auth to check fast reauth with no-change SET_NETWORK"""
759     try:
760         _test_ap_wpa2_eap_sim_no_change_set(dev, apdev)
761     finally:
762         dev[0].request("SET external_sim 0")
763
764 def _test_ap_wpa2_eap_sim_no_change_set(dev, apdev):
765     check_hlr_auc_gw_support()
766     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
767     hostapd.add_ap(apdev[0], params)
768     dev[0].request("SET external_sim 1")
769     id = dev[0].connect("test-wpa2-eap", eap="SIM", key_mgmt="WPA-EAP",
770                         identity="1232010000000000",
771                         wait_connect=False, scan_freq="2412")
772
773     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
774     if ev is None:
775         raise Exception("Wait for external SIM processing request timed out")
776     p = ev.split(':', 2)
777     if p[1] != "GSM-AUTH":
778         raise Exception("Unexpected CTRL-REQ-SIM type")
779     rid = p[0].split('-')[3]
780     rand = p[2].split(' ')[0]
781
782     res = subprocess.check_output(["../../hostapd/hlr_auc_gw",
783                                    "-m",
784                                    "auth_serv/hlr_auc_gw.milenage_db",
785                                    "GSM-AUTH-REQ 232010000000000 " + rand])
786     if "GSM-AUTH-RESP" not in res:
787         raise Exception("Unexpected hlr_auc_gw response")
788     resp = res.split(' ')[2].rstrip()
789
790     dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:" + resp)
791     dev[0].wait_connected(timeout=15)
792
793     # Verify that EAP-SIM Reauthentication can be used after network profile
794     # SET_NETWORK commands that do not actually change previously set
795     # parameter values.
796     dev[0].set_network(id, "key_mgmt", "WPA-EAP")
797     dev[0].set_network(id, "eap", "SIM")
798     dev[0].set_network_quoted(id, "identity", "1232010000000000")
799     dev[0].set_network_quoted(id, "ssid", "test-wpa2-eap")
800     eap_reauth(dev[0], "SIM")
801
802 def test_ap_wpa2_eap_sim_oom(dev, apdev):
803     """EAP-SIM and OOM"""
804     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
805     hostapd.add_ap(apdev[0], params)
806     tests = [ (1, "milenage_f2345"),
807               (2, "milenage_f2345"),
808               (3, "milenage_f2345"),
809               (4, "milenage_f2345"),
810               (5, "milenage_f2345"),
811               (6, "milenage_f2345"),
812               (7, "milenage_f2345"),
813               (8, "milenage_f2345"),
814               (9, "milenage_f2345"),
815               (10, "milenage_f2345"),
816               (11, "milenage_f2345"),
817               (12, "milenage_f2345") ]
818     for count, func in tests:
819         with fail_test(dev[0], count, func):
820             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="SIM",
821                            identity="1232010000000000",
822                            password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
823                            wait_connect=False, scan_freq="2412")
824             ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=5)
825             if ev is None:
826                 raise Exception("EAP method not selected")
827             dev[0].wait_disconnected()
828             dev[0].request("REMOVE_NETWORK all")
829
830 def test_ap_wpa2_eap_aka(dev, apdev):
831     """WPA2-Enterprise connection using EAP-AKA"""
832     check_hlr_auc_gw_support()
833     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
834     hapd = hostapd.add_ap(apdev[0], params)
835     eap_connect(dev[0], hapd, "AKA", "0232010000000000",
836                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123")
837     hwsim_utils.test_connectivity(dev[0], hapd)
838     eap_reauth(dev[0], "AKA")
839
840     logger.info("Negative test with incorrect key")
841     dev[0].request("REMOVE_NETWORK all")
842     eap_connect(dev[0], hapd, "AKA", "0232010000000000",
843                 password="ffdca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123",
844                 expect_failure=True)
845
846     logger.info("Invalid Milenage key")
847     dev[0].request("REMOVE_NETWORK all")
848     eap_connect(dev[0], hapd, "AKA", "0232010000000000",
849                 password="ffdca4eda45b53cf0f12d7c9c3bc6a",
850                 expect_failure=True)
851
852     logger.info("Invalid Milenage key(2)")
853     eap_connect(dev[0], hapd, "AKA", "0232010000000000",
854                 password="ffdca4eda45b53cf0f12d7c9c3bc6a8q:cb9cccc4b9258e6dca4760379fb82581:000000000123",
855                 expect_failure=True)
856
857     logger.info("Invalid Milenage key(3)")
858     eap_connect(dev[0], hapd, "AKA", "0232010000000000",
859                 password="ffdca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb8258q:000000000123",
860                 expect_failure=True)
861
862     logger.info("Invalid Milenage key(4)")
863     eap_connect(dev[0], hapd, "AKA", "0232010000000000",
864                 password="ffdca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:00000000012q",
865                 expect_failure=True)
866
867     logger.info("Invalid Milenage key(5)")
868     dev[0].request("REMOVE_NETWORK all")
869     eap_connect(dev[0], hapd, "AKA", "0232010000000000",
870                 password="ffdca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581q000000000123",
871                 expect_failure=True)
872
873     logger.info("Invalid Milenage key(6)")
874     dev[0].request("REMOVE_NETWORK all")
875     eap_connect(dev[0], hapd, "AKA", "0232010000000000",
876                 password="ffdca4eda45b53cf0f12d7c9c3bc6a89qcb9cccc4b9258e6dca4760379fb82581q000000000123",
877                 expect_failure=True)
878
879     logger.info("Missing key configuration")
880     dev[0].request("REMOVE_NETWORK all")
881     eap_connect(dev[0], hapd, "AKA", "0232010000000000",
882                 expect_failure=True)
883
884 def test_ap_wpa2_eap_aka_sql(dev, apdev, params):
885     """WPA2-Enterprise connection using EAP-AKA (SQL)"""
886     check_hlr_auc_gw_support()
887     try:
888         import sqlite3
889     except ImportError:
890         raise HwsimSkip("No sqlite3 module available")
891     con = sqlite3.connect(os.path.join(params['logdir'], "hostapd.db"))
892     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
893     params['auth_server_port'] = "1814"
894     hapd = hostapd.add_ap(apdev[0], params)
895     eap_connect(dev[0], hapd, "AKA", "0232010000000000",
896                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123")
897
898     logger.info("AKA fast re-authentication")
899     eap_reauth(dev[0], "AKA")
900
901     logger.info("AKA full auth with pseudonym")
902     with con:
903         cur = con.cursor()
904         cur.execute("DELETE FROM reauth WHERE permanent='0232010000000000'")
905     eap_reauth(dev[0], "AKA")
906
907     logger.info("AKA full auth with permanent identity")
908     with con:
909         cur = con.cursor()
910         cur.execute("DELETE FROM reauth WHERE permanent='0232010000000000'")
911         cur.execute("DELETE FROM pseudonyms WHERE permanent='0232010000000000'")
912     eap_reauth(dev[0], "AKA")
913
914     logger.info("AKA reauth with mismatching MK")
915     with con:
916         cur = con.cursor()
917         cur.execute("UPDATE reauth SET mk='0000000000000000000000000000000000000000' WHERE permanent='0232010000000000'")
918     eap_reauth(dev[0], "AKA", expect_failure=True)
919     dev[0].request("REMOVE_NETWORK all")
920
921     eap_connect(dev[0], hapd, "AKA", "0232010000000000",
922                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123")
923     with con:
924         cur = con.cursor()
925         cur.execute("UPDATE reauth SET counter='10' WHERE permanent='0232010000000000'")
926     eap_reauth(dev[0], "AKA")
927     with con:
928         cur = con.cursor()
929         cur.execute("UPDATE reauth SET counter='10' WHERE permanent='0232010000000000'")
930     logger.info("AKA reauth with mismatching counter")
931     eap_reauth(dev[0], "AKA")
932     dev[0].request("REMOVE_NETWORK all")
933
934     eap_connect(dev[0], hapd, "AKA", "0232010000000000",
935                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123")
936     with con:
937         cur = con.cursor()
938         cur.execute("UPDATE reauth SET counter='1001' WHERE permanent='0232010000000000'")
939     logger.info("AKA reauth with max reauth count reached")
940     eap_reauth(dev[0], "AKA")
941
942 def test_ap_wpa2_eap_aka_config(dev, apdev):
943     """EAP-AKA configuration options"""
944     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
945     hapd = hostapd.add_ap(apdev[0], params)
946     eap_connect(dev[0], hapd, "AKA", "0232010000000000",
947                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123",
948                 anonymous_identity="2345678")
949
950 def test_ap_wpa2_eap_aka_ext(dev, apdev):
951     """WPA2-Enterprise connection using EAP-AKA and external UMTS auth"""
952     try:
953         _test_ap_wpa2_eap_aka_ext(dev, apdev)
954     finally:
955         dev[0].request("SET external_sim 0")
956
957 def _test_ap_wpa2_eap_aka_ext(dev, apdev):
958     check_hlr_auc_gw_support()
959     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
960     hostapd.add_ap(apdev[0], params)
961     dev[0].request("SET external_sim 1")
962     id = dev[0].connect("test-wpa2-eap", eap="AKA", key_mgmt="WPA-EAP",
963                         identity="0232010000000000",
964                         password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123",
965                         wait_connect=False, scan_freq="2412")
966     ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=15)
967     if ev is None:
968         raise Exception("Network connected timed out")
969
970     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
971     if ev is None:
972         raise Exception("Wait for external SIM processing request timed out")
973     p = ev.split(':', 2)
974     if p[1] != "UMTS-AUTH":
975         raise Exception("Unexpected CTRL-REQ-SIM type")
976     rid = p[0].split('-')[3]
977
978     # IK:CK:RES
979     resp = "00112233445566778899aabbccddeeff:00112233445566778899aabbccddeeff:0011223344"
980     # This will fail during processing, but the ctrl_iface command succeeds
981     dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:" + resp)
982     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
983     if ev is None:
984         raise Exception("EAP failure not reported")
985     dev[0].request("DISCONNECT")
986     dev[0].wait_disconnected()
987     time.sleep(0.1)
988     dev[0].dump_monitor()
989
990     dev[0].select_network(id, freq="2412")
991     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
992     if ev is None:
993         raise Exception("Wait for external SIM processing request timed out")
994     p = ev.split(':', 2)
995     if p[1] != "UMTS-AUTH":
996         raise Exception("Unexpected CTRL-REQ-SIM type")
997     rid = p[0].split('-')[3]
998     # This will fail during UMTS auth validation
999     if "OK" not in dev[0].request("CTRL-RSP-SIM-" + rid + ":UMTS-AUTS:112233445566778899aabbccddee"):
1000         raise Exception("CTRL-RSP-SIM failed")
1001     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
1002     if ev is None:
1003         raise Exception("Wait for external SIM processing request timed out")
1004     p = ev.split(':', 2)
1005     if p[1] != "UMTS-AUTH":
1006         raise Exception("Unexpected CTRL-REQ-SIM type")
1007     rid = p[0].split('-')[3]
1008     # This will fail during UMTS auth validation
1009     if "OK" not in dev[0].request("CTRL-RSP-SIM-" + rid + ":UMTS-AUTS:12"):
1010         raise Exception("CTRL-RSP-SIM failed")
1011     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
1012     if ev is None:
1013         raise Exception("EAP failure not reported")
1014     dev[0].request("DISCONNECT")
1015     dev[0].wait_disconnected()
1016     time.sleep(0.1)
1017     dev[0].dump_monitor()
1018
1019     tests = [ ":UMTS-AUTH:00112233445566778899aabbccddeeff:00112233445566778899aabbccddeeff:0011223344",
1020               ":UMTS-AUTH:34",
1021               ":UMTS-AUTH:00112233445566778899aabbccddeeff.00112233445566778899aabbccddeeff:0011223344",
1022               ":UMTS-AUTH:00112233445566778899aabbccddeeff:00112233445566778899aabbccddee:0011223344",
1023               ":UMTS-AUTH:00112233445566778899aabbccddeeff:00112233445566778899aabbccddeeff.0011223344",
1024               ":UMTS-AUTH:00112233445566778899aabbccddeeff:00112233445566778899aabbccddeeff:00112233445566778899aabbccddeeff0011223344",
1025               ":UMTS-AUTH:00112233445566778899aabbccddeeff:00112233445566778899aabbccddeeff:001122334q" ]
1026     for t in tests:
1027         dev[0].select_network(id, freq="2412")
1028         ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
1029         if ev is None:
1030             raise Exception("Wait for external SIM processing request timed out")
1031         p = ev.split(':', 2)
1032         if p[1] != "UMTS-AUTH":
1033             raise Exception("Unexpected CTRL-REQ-SIM type")
1034         rid = p[0].split('-')[3]
1035         # This will fail during UMTS auth validation
1036         if "OK" not in dev[0].request("CTRL-RSP-SIM-" + rid + t):
1037             raise Exception("CTRL-RSP-SIM failed")
1038         ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
1039         if ev is None:
1040             raise Exception("EAP failure not reported")
1041         dev[0].request("DISCONNECT")
1042         dev[0].wait_disconnected()
1043         time.sleep(0.1)
1044         dev[0].dump_monitor()
1045
1046 def test_ap_wpa2_eap_aka_ext_auth_fail(dev, apdev):
1047     """EAP-AKA with external UMTS auth and auth failing"""
1048     try:
1049         _test_ap_wpa2_eap_aka_ext_auth_fail(dev, apdev)
1050     finally:
1051         dev[0].request("SET external_sim 0")
1052
1053 def _test_ap_wpa2_eap_aka_ext_auth_fail(dev, apdev):
1054     check_hlr_auc_gw_support()
1055     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1056     hostapd.add_ap(apdev[0], params)
1057     dev[0].request("SET external_sim 1")
1058     id = dev[0].connect("test-wpa2-eap", eap="AKA", key_mgmt="WPA-EAP",
1059                         identity="0232010000000000",
1060                         wait_connect=False, scan_freq="2412")
1061
1062     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
1063     if ev is None:
1064         raise Exception("Wait for external SIM processing request timed out")
1065     p = ev.split(':', 2)
1066     rid = p[0].split('-')[3]
1067     dev[0].request("CTRL-RSP-SIM-" + rid + ":UMTS-FAIL")
1068     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
1069     if ev is None:
1070         raise Exception("EAP failure not reported")
1071     dev[0].request("REMOVE_NETWORK all")
1072     dev[0].wait_disconnected()
1073
1074 def test_ap_wpa2_eap_aka_prime(dev, apdev):
1075     """WPA2-Enterprise connection using EAP-AKA'"""
1076     check_hlr_auc_gw_support()
1077     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1078     hapd = hostapd.add_ap(apdev[0], params)
1079     eap_connect(dev[0], hapd, "AKA'", "6555444333222111",
1080                 password="5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123")
1081     hwsim_utils.test_connectivity(dev[0], hapd)
1082     eap_reauth(dev[0], "AKA'")
1083
1084     logger.info("EAP-AKA' bidding protection when EAP-AKA enabled as well")
1085     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="AKA' AKA",
1086                    identity="6555444333222111@both",
1087                    password="5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123",
1088                    wait_connect=False, scan_freq="2412")
1089     dev[1].wait_connected(timeout=15)
1090
1091     logger.info("Negative test with incorrect key")
1092     dev[0].request("REMOVE_NETWORK all")
1093     eap_connect(dev[0], hapd, "AKA'", "6555444333222111",
1094                 password="ff22250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123",
1095                 expect_failure=True)
1096
1097 def test_ap_wpa2_eap_aka_prime_sql(dev, apdev, params):
1098     """WPA2-Enterprise connection using EAP-AKA' (SQL)"""
1099     check_hlr_auc_gw_support()
1100     try:
1101         import sqlite3
1102     except ImportError:
1103         raise HwsimSkip("No sqlite3 module available")
1104     con = sqlite3.connect(os.path.join(params['logdir'], "hostapd.db"))
1105     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1106     params['auth_server_port'] = "1814"
1107     hapd = hostapd.add_ap(apdev[0], params)
1108     eap_connect(dev[0], hapd, "AKA'", "6555444333222111",
1109                 password="5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123")
1110
1111     logger.info("AKA' fast re-authentication")
1112     eap_reauth(dev[0], "AKA'")
1113
1114     logger.info("AKA' full auth with pseudonym")
1115     with con:
1116         cur = con.cursor()
1117         cur.execute("DELETE FROM reauth WHERE permanent='6555444333222111'")
1118     eap_reauth(dev[0], "AKA'")
1119
1120     logger.info("AKA' full auth with permanent identity")
1121     with con:
1122         cur = con.cursor()
1123         cur.execute("DELETE FROM reauth WHERE permanent='6555444333222111'")
1124         cur.execute("DELETE FROM pseudonyms WHERE permanent='6555444333222111'")
1125     eap_reauth(dev[0], "AKA'")
1126
1127     logger.info("AKA' reauth with mismatching k_aut")
1128     with con:
1129         cur = con.cursor()
1130         cur.execute("UPDATE reauth SET k_aut='0000000000000000000000000000000000000000000000000000000000000000' WHERE permanent='6555444333222111'")
1131     eap_reauth(dev[0], "AKA'", expect_failure=True)
1132     dev[0].request("REMOVE_NETWORK all")
1133
1134     eap_connect(dev[0], hapd, "AKA'", "6555444333222111",
1135                 password="5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123")
1136     with con:
1137         cur = con.cursor()
1138         cur.execute("UPDATE reauth SET counter='10' WHERE permanent='6555444333222111'")
1139     eap_reauth(dev[0], "AKA'")
1140     with con:
1141         cur = con.cursor()
1142         cur.execute("UPDATE reauth SET counter='10' WHERE permanent='6555444333222111'")
1143     logger.info("AKA' reauth with mismatching counter")
1144     eap_reauth(dev[0], "AKA'")
1145     dev[0].request("REMOVE_NETWORK all")
1146
1147     eap_connect(dev[0], hapd, "AKA'", "6555444333222111",
1148                 password="5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123")
1149     with con:
1150         cur = con.cursor()
1151         cur.execute("UPDATE reauth SET counter='1001' WHERE permanent='6555444333222111'")
1152     logger.info("AKA' reauth with max reauth count reached")
1153     eap_reauth(dev[0], "AKA'")
1154
1155 def test_ap_wpa2_eap_aka_prime_ext_auth_fail(dev, apdev):
1156     """EAP-AKA' with external UMTS auth and auth failing"""
1157     try:
1158         _test_ap_wpa2_eap_aka_prime_ext_auth_fail(dev, apdev)
1159     finally:
1160         dev[0].request("SET external_sim 0")
1161
1162 def _test_ap_wpa2_eap_aka_prime_ext_auth_fail(dev, apdev):
1163     check_hlr_auc_gw_support()
1164     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1165     hostapd.add_ap(apdev[0], params)
1166     dev[0].request("SET external_sim 1")
1167     id = dev[0].connect("test-wpa2-eap", eap="AKA'", key_mgmt="WPA-EAP",
1168                         identity="6555444333222111",
1169                         wait_connect=False, scan_freq="2412")
1170
1171     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
1172     if ev is None:
1173         raise Exception("Wait for external SIM processing request timed out")
1174     p = ev.split(':', 2)
1175     rid = p[0].split('-')[3]
1176     dev[0].request("CTRL-RSP-SIM-" + rid + ":UMTS-FAIL")
1177     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
1178     if ev is None:
1179         raise Exception("EAP failure not reported")
1180     dev[0].request("REMOVE_NETWORK all")
1181     dev[0].wait_disconnected()
1182
1183 def test_ap_wpa2_eap_ttls_pap(dev, apdev):
1184     """WPA2-Enterprise connection using EAP-TTLS/PAP"""
1185     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1186     hapd = hostapd.add_ap(apdev[0], params)
1187     key_mgmt = hapd.get_config()['key_mgmt']
1188     if key_mgmt.split(' ')[0] != "WPA-EAP":
1189         raise Exception("Unexpected GET_CONFIG(key_mgmt): " + key_mgmt)
1190     eap_connect(dev[0], hapd, "TTLS", "pap user",
1191                 anonymous_identity="ttls", password="password",
1192                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP")
1193     hwsim_utils.test_connectivity(dev[0], hapd)
1194     eap_reauth(dev[0], "TTLS")
1195     check_mib(dev[0], [ ("dot11RSNAAuthenticationSuiteRequested", "00-0f-ac-1"),
1196                         ("dot11RSNAAuthenticationSuiteSelected", "00-0f-ac-1") ])
1197
1198 def test_ap_wpa2_eap_ttls_pap_subject_match(dev, apdev):
1199     """WPA2-Enterprise connection using EAP-TTLS/PAP and (alt)subject_match"""
1200     check_subject_match_support(dev[0])
1201     check_altsubject_match_support(dev[0])
1202     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1203     hapd = hostapd.add_ap(apdev[0], params)
1204     eap_connect(dev[0], hapd, "TTLS", "pap user",
1205                 anonymous_identity="ttls", password="password",
1206                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP",
1207                 subject_match="/C=FI/O=w1.fi/CN=server.w1.fi",
1208                 altsubject_match="EMAIL:noone@example.com;DNS:server.w1.fi;URI:http://example.com/")
1209     eap_reauth(dev[0], "TTLS")
1210
1211 def test_ap_wpa2_eap_ttls_pap_incorrect_password(dev, apdev):
1212     """WPA2-Enterprise connection using EAP-TTLS/PAP - incorrect password"""
1213     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1214     hapd = hostapd.add_ap(apdev[0], params)
1215     eap_connect(dev[0], hapd, "TTLS", "pap user",
1216                 anonymous_identity="ttls", password="wrong",
1217                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP",
1218                 expect_failure=True)
1219     eap_connect(dev[1], hapd, "TTLS", "user",
1220                 anonymous_identity="ttls", password="password",
1221                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP",
1222                 expect_failure=True)
1223
1224 def test_ap_wpa2_eap_ttls_chap(dev, apdev):
1225     """WPA2-Enterprise connection using EAP-TTLS/CHAP"""
1226     skip_with_fips(dev[0])
1227     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1228     hapd = hostapd.add_ap(apdev[0], params)
1229     eap_connect(dev[0], hapd, "TTLS", "chap user",
1230                 anonymous_identity="ttls", password="password",
1231                 ca_cert="auth_serv/ca.der", phase2="auth=CHAP")
1232     hwsim_utils.test_connectivity(dev[0], hapd)
1233     eap_reauth(dev[0], "TTLS")
1234
1235 def test_ap_wpa2_eap_ttls_chap_altsubject_match(dev, apdev):
1236     """WPA2-Enterprise connection using EAP-TTLS/CHAP"""
1237     skip_with_fips(dev[0])
1238     check_altsubject_match_support(dev[0])
1239     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1240     hapd = hostapd.add_ap(apdev[0], params)
1241     eap_connect(dev[0], hapd, "TTLS", "chap user",
1242                 anonymous_identity="ttls", password="password",
1243                 ca_cert="auth_serv/ca.der", phase2="auth=CHAP",
1244                 altsubject_match="EMAIL:noone@example.com;URI:http://example.com/;DNS:server.w1.fi")
1245     eap_reauth(dev[0], "TTLS")
1246
1247 def test_ap_wpa2_eap_ttls_chap_incorrect_password(dev, apdev):
1248     """WPA2-Enterprise connection using EAP-TTLS/CHAP - incorrect password"""
1249     skip_with_fips(dev[0])
1250     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1251     hapd = hostapd.add_ap(apdev[0], params)
1252     eap_connect(dev[0], hapd, "TTLS", "chap user",
1253                 anonymous_identity="ttls", password="wrong",
1254                 ca_cert="auth_serv/ca.pem", phase2="auth=CHAP",
1255                 expect_failure=True)
1256     eap_connect(dev[1], hapd, "TTLS", "user",
1257                 anonymous_identity="ttls", password="password",
1258                 ca_cert="auth_serv/ca.pem", phase2="auth=CHAP",
1259                 expect_failure=True)
1260
1261 def test_ap_wpa2_eap_ttls_mschap(dev, apdev):
1262     """WPA2-Enterprise connection using EAP-TTLS/MSCHAP"""
1263     skip_with_fips(dev[0])
1264     check_domain_suffix_match(dev[0])
1265     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1266     hapd = hostapd.add_ap(apdev[0], params)
1267     eap_connect(dev[0], hapd, "TTLS", "mschap user",
1268                 anonymous_identity="ttls", password="password",
1269                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
1270                 domain_suffix_match="server.w1.fi")
1271     hwsim_utils.test_connectivity(dev[0], hapd)
1272     eap_reauth(dev[0], "TTLS")
1273     dev[0].request("REMOVE_NETWORK all")
1274     eap_connect(dev[0], hapd, "TTLS", "mschap user",
1275                 anonymous_identity="ttls", password="password",
1276                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
1277                 fragment_size="200")
1278     dev[0].request("REMOVE_NETWORK all")
1279     dev[0].wait_disconnected()
1280     eap_connect(dev[0], hapd, "TTLS", "mschap user",
1281                 anonymous_identity="ttls",
1282                 password_hex="hash:8846f7eaee8fb117ad06bdd830b7586c",
1283                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP")
1284
1285 def test_ap_wpa2_eap_ttls_mschap_incorrect_password(dev, apdev):
1286     """WPA2-Enterprise connection using EAP-TTLS/MSCHAP - incorrect password"""
1287     skip_with_fips(dev[0])
1288     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1289     hapd = hostapd.add_ap(apdev[0], params)
1290     eap_connect(dev[0], hapd, "TTLS", "mschap user",
1291                 anonymous_identity="ttls", password="wrong",
1292                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
1293                 expect_failure=True)
1294     eap_connect(dev[1], hapd, "TTLS", "user",
1295                 anonymous_identity="ttls", password="password",
1296                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
1297                 expect_failure=True)
1298     eap_connect(dev[2], hapd, "TTLS", "no such user",
1299                 anonymous_identity="ttls", password="password",
1300                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
1301                 expect_failure=True)
1302
1303 def test_ap_wpa2_eap_ttls_mschapv2(dev, apdev):
1304     """WPA2-Enterprise connection using EAP-TTLS/MSCHAPv2"""
1305     check_domain_suffix_match(dev[0])
1306     check_eap_capa(dev[0], "MSCHAPV2")
1307     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1308     hapd = hostapd.add_ap(apdev[0], params)
1309     eap_connect(dev[0], hapd, "TTLS", "DOMAIN\mschapv2 user",
1310                 anonymous_identity="ttls", password="password",
1311                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1312                 domain_suffix_match="server.w1.fi")
1313     hwsim_utils.test_connectivity(dev[0], hapd)
1314     sta1 = hapd.get_sta(dev[0].p2p_interface_addr())
1315     eapol1 = hapd.get_sta(dev[0].p2p_interface_addr(), info="eapol")
1316     eap_reauth(dev[0], "TTLS")
1317     sta2 = hapd.get_sta(dev[0].p2p_interface_addr())
1318     eapol2 = hapd.get_sta(dev[0].p2p_interface_addr(), info="eapol")
1319     if int(sta2['dot1xAuthEapolFramesRx']) <= int(sta1['dot1xAuthEapolFramesRx']):
1320         raise Exception("dot1xAuthEapolFramesRx did not increase")
1321     if int(eapol2['authAuthEapStartsWhileAuthenticated']) < 1:
1322         raise Exception("authAuthEapStartsWhileAuthenticated did not increase")
1323     if int(eapol2['backendAuthSuccesses']) <= int(eapol1['backendAuthSuccesses']):
1324         raise Exception("backendAuthSuccesses did not increase")
1325
1326     logger.info("Password as hash value")
1327     dev[0].request("REMOVE_NETWORK all")
1328     eap_connect(dev[0], hapd, "TTLS", "DOMAIN\mschapv2 user",
1329                 anonymous_identity="ttls",
1330                 password_hex="hash:8846f7eaee8fb117ad06bdd830b7586c",
1331                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
1332
1333 def test_ap_wpa2_eap_ttls_invalid_phase2(dev, apdev):
1334     """EAP-TTLS with invalid phase2 parameter values"""
1335     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1336     hostapd.add_ap(apdev[0], params)
1337     tests = [ "auth=MSCHAPv2", "auth=MSCHAPV2 autheap=MD5",
1338               "autheap=MD5 auth=MSCHAPV2", "auth=PAP auth=CHAP",
1339               "autheap=MD5 autheap=FOO autheap=MSCHAPV2" ]
1340     for t in tests:
1341         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
1342                        identity="DOMAIN\mschapv2 user",
1343                        anonymous_identity="ttls", password="password",
1344                        ca_cert="auth_serv/ca.pem", phase2=t,
1345                        wait_connect=False, scan_freq="2412")
1346         ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=10)
1347         if ev is None or "method=21" not in ev:
1348             raise Exception("EAP-TTLS not started")
1349         ev = dev[0].wait_event(["EAP: Failed to initialize EAP method",
1350                                 "CTRL-EVENT-CONNECTED"], timeout=5)
1351         if ev is None or "CTRL-EVENT-CONNECTED" in ev:
1352             raise Exception("No EAP-TTLS failure reported for phase2=" + t)
1353         dev[0].request("REMOVE_NETWORK all")
1354         dev[0].wait_disconnected()
1355         dev[0].dump_monitor()
1356
1357 def test_ap_wpa2_eap_ttls_mschapv2_suffix_match(dev, apdev):
1358     """WPA2-Enterprise connection using EAP-TTLS/MSCHAPv2"""
1359     check_domain_match_full(dev[0])
1360     skip_with_fips(dev[0])
1361     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1362     hapd = hostapd.add_ap(apdev[0], params)
1363     eap_connect(dev[0], hapd, "TTLS", "DOMAIN\mschapv2 user",
1364                 anonymous_identity="ttls", password="password",
1365                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1366                 domain_suffix_match="w1.fi")
1367     hwsim_utils.test_connectivity(dev[0], hapd)
1368     eap_reauth(dev[0], "TTLS")
1369
1370 def test_ap_wpa2_eap_ttls_mschapv2_domain_match(dev, apdev):
1371     """WPA2-Enterprise connection using EAP-TTLS/MSCHAPv2 (domain_match)"""
1372     check_domain_match(dev[0])
1373     skip_with_fips(dev[0])
1374     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1375     hapd = hostapd.add_ap(apdev[0], params)
1376     eap_connect(dev[0], hapd, "TTLS", "DOMAIN\mschapv2 user",
1377                 anonymous_identity="ttls", password="password",
1378                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1379                 domain_match="Server.w1.fi")
1380     hwsim_utils.test_connectivity(dev[0], hapd)
1381     eap_reauth(dev[0], "TTLS")
1382
1383 def test_ap_wpa2_eap_ttls_mschapv2_incorrect_password(dev, apdev):
1384     """WPA2-Enterprise connection using EAP-TTLS/MSCHAPv2 - incorrect password"""
1385     skip_with_fips(dev[0])
1386     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1387     hapd = hostapd.add_ap(apdev[0], params)
1388     eap_connect(dev[0], hapd, "TTLS", "DOMAIN\mschapv2 user",
1389                 anonymous_identity="ttls", password="password1",
1390                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1391                 expect_failure=True)
1392     eap_connect(dev[1], hapd, "TTLS", "user",
1393                 anonymous_identity="ttls", password="password",
1394                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1395                 expect_failure=True)
1396
1397 def test_ap_wpa2_eap_ttls_mschapv2_utf8(dev, apdev):
1398     """WPA2-Enterprise connection using EAP-TTLS/MSCHAPv2 and UTF-8 password"""
1399     skip_with_fips(dev[0])
1400     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1401     hapd = hostapd.add_ap(apdev[0], params)
1402     eap_connect(dev[0], hapd, "TTLS", "utf8-user-hash",
1403                 anonymous_identity="ttls", password="secret-åäö-€-password",
1404                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
1405     eap_connect(dev[1], hapd, "TTLS", "utf8-user",
1406                 anonymous_identity="ttls",
1407                 password_hex="hash:bd5844fad2489992da7fe8c5a01559cf",
1408                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
1409     for p in [ "80", "41c041e04141e041", 257*"41" ]:
1410         dev[2].connect("test-wpa2-eap", key_mgmt="WPA-EAP",
1411                        eap="TTLS", identity="utf8-user-hash",
1412                        anonymous_identity="ttls", password_hex=p,
1413                        ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1414                        wait_connect=False, scan_freq="2412")
1415         ev = dev[2].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=1)
1416         if ev is None:
1417             raise Exception("No failure reported")
1418         dev[2].request("REMOVE_NETWORK all")
1419         dev[2].wait_disconnected()
1420
1421 def test_ap_wpa2_eap_ttls_eap_gtc(dev, apdev):
1422     """WPA2-Enterprise connection using EAP-TTLS/EAP-GTC"""
1423     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1424     hapd = hostapd.add_ap(apdev[0], params)
1425     eap_connect(dev[0], hapd, "TTLS", "user",
1426                 anonymous_identity="ttls", password="password",
1427                 ca_cert="auth_serv/ca.pem", phase2="autheap=GTC")
1428     hwsim_utils.test_connectivity(dev[0], hapd)
1429     eap_reauth(dev[0], "TTLS")
1430
1431 def test_ap_wpa2_eap_ttls_eap_gtc_incorrect_password(dev, apdev):
1432     """WPA2-Enterprise connection using EAP-TTLS/EAP-GTC - incorrect password"""
1433     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1434     hapd = hostapd.add_ap(apdev[0], params)
1435     eap_connect(dev[0], hapd, "TTLS", "user",
1436                 anonymous_identity="ttls", password="wrong",
1437                 ca_cert="auth_serv/ca.pem", phase2="autheap=GTC",
1438                 expect_failure=True)
1439
1440 def test_ap_wpa2_eap_ttls_eap_gtc_no_password(dev, apdev):
1441     """WPA2-Enterprise connection using EAP-TTLS/EAP-GTC - no password"""
1442     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1443     hapd = hostapd.add_ap(apdev[0], params)
1444     eap_connect(dev[0], hapd, "TTLS", "user-no-passwd",
1445                 anonymous_identity="ttls", password="password",
1446                 ca_cert="auth_serv/ca.pem", phase2="autheap=GTC",
1447                 expect_failure=True)
1448
1449 def test_ap_wpa2_eap_ttls_eap_gtc_server_oom(dev, apdev):
1450     """WPA2-Enterprise connection using EAP-TTLS/EAP-GTC - server OOM"""
1451     params = int_eap_server_params()
1452     hapd = hostapd.add_ap(apdev[0], params)
1453     with alloc_fail(hapd, 1, "eap_gtc_init"):
1454         eap_connect(dev[0], hapd, "TTLS", "user",
1455                     anonymous_identity="ttls", password="password",
1456                     ca_cert="auth_serv/ca.pem", phase2="autheap=GTC",
1457                     expect_failure=True)
1458         dev[0].request("REMOVE_NETWORK all")
1459
1460     with alloc_fail(hapd, 1, "eap_gtc_buildReq"):
1461         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
1462                        eap="TTLS", identity="user",
1463                        anonymous_identity="ttls", password="password",
1464                        ca_cert="auth_serv/ca.pem", phase2="autheap=GTC",
1465                        wait_connect=False, scan_freq="2412")
1466         # This would eventually time out, but we can stop after having reached
1467         # the allocation failure.
1468         for i in range(20):
1469             time.sleep(0.1)
1470             if hapd.request("GET_ALLOC_FAIL").startswith('0'):
1471                 break
1472
1473 def test_ap_wpa2_eap_ttls_eap_gtc_oom(dev, apdev):
1474     """WPA2-Enterprise connection using EAP-TTLS/EAP-GTC (OOM)"""
1475     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1476     hapd = hostapd.add_ap(apdev[0], params)
1477
1478     tests = [ "eap_gtc_init",
1479               "eap_msg_alloc;eap_gtc_process" ]
1480     for func in tests:
1481         with alloc_fail(dev[0], 1, func):
1482             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP",
1483                            scan_freq="2412",
1484                            eap="TTLS", identity="user",
1485                            anonymous_identity="ttls", password="password",
1486                            ca_cert="auth_serv/ca.pem", phase2="autheap=GTC",
1487                            wait_connect=False)
1488             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
1489             dev[0].request("REMOVE_NETWORK all")
1490             dev[0].wait_disconnected()
1491
1492 def test_ap_wpa2_eap_ttls_eap_md5(dev, apdev):
1493     """WPA2-Enterprise connection using EAP-TTLS/EAP-MD5"""
1494     check_eap_capa(dev[0], "MD5")
1495     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1496     hapd = hostapd.add_ap(apdev[0], params)
1497     eap_connect(dev[0], hapd, "TTLS", "user",
1498                 anonymous_identity="ttls", password="password",
1499                 ca_cert="auth_serv/ca.pem", phase2="autheap=MD5")
1500     hwsim_utils.test_connectivity(dev[0], hapd)
1501     eap_reauth(dev[0], "TTLS")
1502
1503 def test_ap_wpa2_eap_ttls_eap_md5_incorrect_password(dev, apdev):
1504     """WPA2-Enterprise connection using EAP-TTLS/EAP-MD5 - incorrect password"""
1505     check_eap_capa(dev[0], "MD5")
1506     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1507     hapd = hostapd.add_ap(apdev[0], params)
1508     eap_connect(dev[0], hapd, "TTLS", "user",
1509                 anonymous_identity="ttls", password="wrong",
1510                 ca_cert="auth_serv/ca.pem", phase2="autheap=MD5",
1511                 expect_failure=True)
1512
1513 def test_ap_wpa2_eap_ttls_eap_md5_no_password(dev, apdev):
1514     """WPA2-Enterprise connection using EAP-TTLS/EAP-MD5 - no password"""
1515     check_eap_capa(dev[0], "MD5")
1516     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1517     hapd = hostapd.add_ap(apdev[0], params)
1518     eap_connect(dev[0], hapd, "TTLS", "user-no-passwd",
1519                 anonymous_identity="ttls", password="password",
1520                 ca_cert="auth_serv/ca.pem", phase2="autheap=MD5",
1521                 expect_failure=True)
1522
1523 def test_ap_wpa2_eap_ttls_eap_md5_server_oom(dev, apdev):
1524     """WPA2-Enterprise connection using EAP-TTLS/EAP-MD5 - server OOM"""
1525     check_eap_capa(dev[0], "MD5")
1526     params = int_eap_server_params()
1527     hapd = hostapd.add_ap(apdev[0], params)
1528     with alloc_fail(hapd, 1, "eap_md5_init"):
1529         eap_connect(dev[0], hapd, "TTLS", "user",
1530                     anonymous_identity="ttls", password="password",
1531                     ca_cert="auth_serv/ca.pem", phase2="autheap=MD5",
1532                     expect_failure=True)
1533         dev[0].request("REMOVE_NETWORK all")
1534
1535     with alloc_fail(hapd, 1, "eap_md5_buildReq"):
1536         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
1537                        eap="TTLS", identity="user",
1538                        anonymous_identity="ttls", password="password",
1539                        ca_cert="auth_serv/ca.pem", phase2="autheap=MD5",
1540                        wait_connect=False, scan_freq="2412")
1541         # This would eventually time out, but we can stop after having reached
1542         # the allocation failure.
1543         for i in range(20):
1544             time.sleep(0.1)
1545             if hapd.request("GET_ALLOC_FAIL").startswith('0'):
1546                 break
1547
1548 def test_ap_wpa2_eap_ttls_eap_mschapv2(dev, apdev):
1549     """WPA2-Enterprise connection using EAP-TTLS/EAP-MSCHAPv2"""
1550     check_eap_capa(dev[0], "MSCHAPV2")
1551     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1552     hapd = hostapd.add_ap(apdev[0], params)
1553     eap_connect(dev[0], hapd, "TTLS", "user",
1554                 anonymous_identity="ttls", password="password",
1555                 ca_cert="auth_serv/ca.pem", phase2="autheap=MSCHAPV2")
1556     hwsim_utils.test_connectivity(dev[0], hapd)
1557     eap_reauth(dev[0], "TTLS")
1558
1559     logger.info("Negative test with incorrect password")
1560     dev[0].request("REMOVE_NETWORK all")
1561     eap_connect(dev[0], hapd, "TTLS", "user",
1562                 anonymous_identity="ttls", password="password1",
1563                 ca_cert="auth_serv/ca.pem", phase2="autheap=MSCHAPV2",
1564                 expect_failure=True)
1565
1566 def test_ap_wpa2_eap_ttls_eap_mschapv2_no_password(dev, apdev):
1567     """WPA2-Enterprise connection using EAP-TTLS/EAP-MSCHAPv2 - no password"""
1568     check_eap_capa(dev[0], "MSCHAPV2")
1569     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1570     hapd = hostapd.add_ap(apdev[0], params)
1571     eap_connect(dev[0], hapd, "TTLS", "user-no-passwd",
1572                 anonymous_identity="ttls", password="password",
1573                 ca_cert="auth_serv/ca.pem", phase2="autheap=MSCHAPV2",
1574                 expect_failure=True)
1575
1576 def test_ap_wpa2_eap_ttls_eap_mschapv2_server_oom(dev, apdev):
1577     """WPA2-Enterprise connection using EAP-TTLS/EAP-MSCHAPv2 - server OOM"""
1578     check_eap_capa(dev[0], "MSCHAPV2")
1579     params = int_eap_server_params()
1580     hapd = hostapd.add_ap(apdev[0], params)
1581     with alloc_fail(hapd, 1, "eap_mschapv2_init"):
1582         eap_connect(dev[0], hapd, "TTLS", "user",
1583                     anonymous_identity="ttls", password="password",
1584                     ca_cert="auth_serv/ca.pem", phase2="autheap=MSCHAPV2",
1585                     expect_failure=True)
1586         dev[0].request("REMOVE_NETWORK all")
1587
1588     with alloc_fail(hapd, 1, "eap_mschapv2_build_challenge"):
1589         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
1590                        eap="TTLS", identity="user",
1591                        anonymous_identity="ttls", password="password",
1592                        ca_cert="auth_serv/ca.pem", phase2="autheap=MSCHAPV2",
1593                        wait_connect=False, scan_freq="2412")
1594         # This would eventually time out, but we can stop after having reached
1595         # the allocation failure.
1596         for i in range(20):
1597             time.sleep(0.1)
1598             if hapd.request("GET_ALLOC_FAIL").startswith('0'):
1599                 break
1600         dev[0].request("REMOVE_NETWORK all")
1601
1602     with alloc_fail(hapd, 1, "eap_mschapv2_build_success_req"):
1603         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
1604                        eap="TTLS", identity="user",
1605                        anonymous_identity="ttls", password="password",
1606                        ca_cert="auth_serv/ca.pem", phase2="autheap=MSCHAPV2",
1607                        wait_connect=False, scan_freq="2412")
1608         # This would eventually time out, but we can stop after having reached
1609         # the allocation failure.
1610         for i in range(20):
1611             time.sleep(0.1)
1612             if hapd.request("GET_ALLOC_FAIL").startswith('0'):
1613                 break
1614         dev[0].request("REMOVE_NETWORK all")
1615
1616     with alloc_fail(hapd, 1, "eap_mschapv2_build_failure_req"):
1617         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
1618                        eap="TTLS", identity="user",
1619                        anonymous_identity="ttls", password="wrong",
1620                        ca_cert="auth_serv/ca.pem", phase2="autheap=MSCHAPV2",
1621                        wait_connect=False, scan_freq="2412")
1622         # This would eventually time out, but we can stop after having reached
1623         # the allocation failure.
1624         for i in range(20):
1625             time.sleep(0.1)
1626             if hapd.request("GET_ALLOC_FAIL").startswith('0'):
1627                 break
1628         dev[0].request("REMOVE_NETWORK all")
1629
1630 def test_ap_wpa2_eap_ttls_eap_aka(dev, apdev):
1631     """WPA2-Enterprise connection using EAP-TTLS/EAP-AKA"""
1632     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1633     hapd = hostapd.add_ap(apdev[0], params)
1634     eap_connect(dev[0], hapd, "TTLS", "0232010000000000",
1635                 anonymous_identity="0232010000000000@ttls",
1636                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123",
1637                 ca_cert="auth_serv/ca.pem", phase2="autheap=AKA")
1638
1639 def test_ap_wpa2_eap_peap_eap_aka(dev, apdev):
1640     """WPA2-Enterprise connection using EAP-PEAP/EAP-AKA"""
1641     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1642     hapd = hostapd.add_ap(apdev[0], params)
1643     eap_connect(dev[0], hapd, "PEAP", "0232010000000000",
1644                 anonymous_identity="0232010000000000@peap",
1645                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123",
1646                 ca_cert="auth_serv/ca.pem", phase2="auth=AKA")
1647
1648 def test_ap_wpa2_eap_fast_eap_aka(dev, apdev):
1649     """WPA2-Enterprise connection using EAP-FAST/EAP-AKA"""
1650     check_eap_capa(dev[0], "FAST")
1651     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1652     hapd = hostapd.add_ap(apdev[0], params)
1653     eap_connect(dev[0], hapd, "FAST", "0232010000000000",
1654                 anonymous_identity="0232010000000000@fast",
1655                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123",
1656                 phase1="fast_provisioning=2",
1657                 pac_file="blob://fast_pac_auth_aka",
1658                 ca_cert="auth_serv/ca.pem", phase2="auth=AKA")
1659
1660 def test_ap_wpa2_eap_peap_eap_mschapv2(dev, apdev):
1661     """WPA2-Enterprise connection using EAP-PEAP/EAP-MSCHAPv2"""
1662     check_eap_capa(dev[0], "MSCHAPV2")
1663     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1664     hapd = hostapd.add_ap(apdev[0], params)
1665     eap_connect(dev[0], hapd, "PEAP", "user",
1666                 anonymous_identity="peap", password="password",
1667                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
1668     hwsim_utils.test_connectivity(dev[0], hapd)
1669     eap_reauth(dev[0], "PEAP")
1670     dev[0].request("REMOVE_NETWORK all")
1671     eap_connect(dev[0], hapd, "PEAP", "user",
1672                 anonymous_identity="peap", password="password",
1673                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1674                 fragment_size="200")
1675
1676     logger.info("Password as hash value")
1677     dev[0].request("REMOVE_NETWORK all")
1678     eap_connect(dev[0], hapd, "PEAP", "user",
1679                 anonymous_identity="peap",
1680                 password_hex="hash:8846f7eaee8fb117ad06bdd830b7586c",
1681                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
1682
1683     logger.info("Negative test with incorrect password")
1684     dev[0].request("REMOVE_NETWORK all")
1685     eap_connect(dev[0], hapd, "PEAP", "user",
1686                 anonymous_identity="peap", password="password1",
1687                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1688                 expect_failure=True)
1689
1690 def test_ap_wpa2_eap_peap_eap_mschapv2_domain(dev, apdev):
1691     """WPA2-Enterprise connection using EAP-PEAP/EAP-MSCHAPv2 with domain"""
1692     check_eap_capa(dev[0], "MSCHAPV2")
1693     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1694     hapd = hostapd.add_ap(apdev[0], params)
1695     eap_connect(dev[0], hapd, "PEAP", "DOMAIN\user3",
1696                 anonymous_identity="peap", password="password",
1697                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
1698     hwsim_utils.test_connectivity(dev[0], hapd)
1699     eap_reauth(dev[0], "PEAP")
1700
1701 def test_ap_wpa2_eap_peap_eap_mschapv2_incorrect_password(dev, apdev):
1702     """WPA2-Enterprise connection using EAP-PEAP/EAP-MSCHAPv2 - incorrect password"""
1703     check_eap_capa(dev[0], "MSCHAPV2")
1704     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1705     hapd = hostapd.add_ap(apdev[0], params)
1706     eap_connect(dev[0], hapd, "PEAP", "user",
1707                 anonymous_identity="peap", password="wrong",
1708                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1709                 expect_failure=True)
1710
1711 def test_ap_wpa2_eap_peap_crypto_binding(dev, apdev):
1712     """WPA2-Enterprise connection using EAP-PEAPv0/EAP-MSCHAPv2 and crypto binding"""
1713     check_eap_capa(dev[0], "MSCHAPV2")
1714     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1715     hapd = hostapd.add_ap(apdev[0], params)
1716     eap_connect(dev[0], hapd, "PEAP", "user", password="password",
1717                 ca_cert="auth_serv/ca.pem",
1718                 phase1="peapver=0 crypto_binding=2",
1719                 phase2="auth=MSCHAPV2")
1720     hwsim_utils.test_connectivity(dev[0], hapd)
1721     eap_reauth(dev[0], "PEAP")
1722
1723     eap_connect(dev[1], hapd, "PEAP", "user", password="password",
1724                 ca_cert="auth_serv/ca.pem",
1725                 phase1="peapver=0 crypto_binding=1",
1726                 phase2="auth=MSCHAPV2")
1727     eap_connect(dev[2], hapd, "PEAP", "user", password="password",
1728                 ca_cert="auth_serv/ca.pem",
1729                 phase1="peapver=0 crypto_binding=0",
1730                 phase2="auth=MSCHAPV2")
1731
1732 def test_ap_wpa2_eap_peap_crypto_binding_server_oom(dev, apdev):
1733     """WPA2-Enterprise connection using EAP-PEAPv0/EAP-MSCHAPv2 and crypto binding with server OOM"""
1734     check_eap_capa(dev[0], "MSCHAPV2")
1735     params = int_eap_server_params()
1736     hapd = hostapd.add_ap(apdev[0], params)
1737     with alloc_fail(hapd, 1, "eap_mschapv2_getKey"):
1738         eap_connect(dev[0], hapd, "PEAP", "user", password="password",
1739                     ca_cert="auth_serv/ca.pem",
1740                     phase1="peapver=0 crypto_binding=2",
1741                     phase2="auth=MSCHAPV2",
1742                     expect_failure=True, local_error_report=True)
1743
1744 def test_ap_wpa2_eap_peap_params(dev, apdev):
1745     """WPA2-Enterprise connection using EAP-PEAPv0/EAP-MSCHAPv2 and various parameters"""
1746     check_eap_capa(dev[0], "MSCHAPV2")
1747     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1748     hapd = hostapd.add_ap(apdev[0], params)
1749     eap_connect(dev[0], hapd, "PEAP", "user",
1750                 anonymous_identity="peap", password="password",
1751                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1752                 phase1="peapver=0 peaplabel=1",
1753                 expect_failure=True)
1754     dev[0].request("REMOVE_NETWORK all")
1755     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PEAP",
1756                    identity="user",
1757                    anonymous_identity="peap", password="password",
1758                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1759                    phase1="peap_outer_success=0",
1760                    wait_connect=False, scan_freq="2412")
1761     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=15)
1762     if ev is None:
1763         raise Exception("No EAP success seen")
1764     # This won't succeed to connect with peap_outer_success=0, so stop here.
1765     dev[0].request("REMOVE_NETWORK all")
1766     dev[0].wait_disconnected()
1767     eap_connect(dev[1], hapd, "PEAP", "user", password="password",
1768                 ca_cert="auth_serv/ca.pem",
1769                 phase1="peap_outer_success=1",
1770                 phase2="auth=MSCHAPV2")
1771     eap_connect(dev[2], hapd, "PEAP", "user", password="password",
1772                 ca_cert="auth_serv/ca.pem",
1773                 phase1="peap_outer_success=2",
1774                 phase2="auth=MSCHAPV2")
1775     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PEAP",
1776                    identity="user",
1777                    anonymous_identity="peap", password="password",
1778                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1779                    phase1="peapver=1 peaplabel=1",
1780                    wait_connect=False, scan_freq="2412")
1781     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=15)
1782     if ev is None:
1783         raise Exception("No EAP success seen")
1784     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
1785     if ev is not None:
1786         raise Exception("Unexpected connection")
1787
1788     tests = [ ("peap-ver0", ""),
1789               ("peap-ver1", ""),
1790               ("peap-ver0", "peapver=0"),
1791               ("peap-ver1", "peapver=1") ]
1792     for anon,phase1 in tests:
1793         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PEAP",
1794                        identity="user", anonymous_identity=anon,
1795                        password="password", phase1=phase1,
1796                        ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1797                        scan_freq="2412")
1798         dev[0].request("REMOVE_NETWORK all")
1799         dev[0].wait_disconnected()
1800
1801     tests = [ ("peap-ver0", "peapver=1"),
1802               ("peap-ver1", "peapver=0") ]
1803     for anon,phase1 in tests:
1804         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PEAP",
1805                        identity="user", anonymous_identity=anon,
1806                        password="password", phase1=phase1,
1807                        ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1808                        wait_connect=False, scan_freq="2412")
1809         ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
1810         if ev is None:
1811             raise Exception("No EAP-Failure seen")
1812         dev[0].request("REMOVE_NETWORK all")
1813         dev[0].wait_disconnected()
1814
1815     eap_connect(dev[0], hapd, "PEAP", "user", password="password",
1816                 ca_cert="auth_serv/ca.pem",
1817                 phase1="tls_allow_md5=1 tls_disable_session_ticket=1 tls_disable_tlsv1_0=0 tls_disable_tlsv1_1=0 tls_disable_tlsv1_2=0 tls_ext_cert_check=0",
1818                 phase2="auth=MSCHAPV2")
1819
1820 def test_ap_wpa2_eap_peap_eap_tls(dev, apdev):
1821     """WPA2-Enterprise connection using EAP-PEAP/EAP-TLS"""
1822     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1823     hapd = hostapd.add_ap(apdev[0], params)
1824     eap_connect(dev[0], hapd, "PEAP", "cert user",
1825                 ca_cert="auth_serv/ca.pem", phase2="auth=TLS",
1826                 ca_cert2="auth_serv/ca.pem",
1827                 client_cert2="auth_serv/user.pem",
1828                 private_key2="auth_serv/user.key")
1829     eap_reauth(dev[0], "PEAP")
1830
1831 def test_ap_wpa2_eap_tls(dev, apdev):
1832     """WPA2-Enterprise connection using EAP-TLS"""
1833     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1834     hapd = hostapd.add_ap(apdev[0], params)
1835     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
1836                 client_cert="auth_serv/user.pem",
1837                 private_key="auth_serv/user.key")
1838     eap_reauth(dev[0], "TLS")
1839
1840 def test_eap_tls_pkcs8_pkcs5_v2_des3(dev, apdev):
1841     """WPA2-Enterprise connection using EAP-TLS and PKCS #8, PKCS #5 v2 DES3 key"""
1842     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1843     hapd = hostapd.add_ap(apdev[0], params)
1844     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
1845                 client_cert="auth_serv/user.pem",
1846                 private_key="auth_serv/user.key.pkcs8",
1847                 private_key_passwd="whatever")
1848
1849 def test_eap_tls_pkcs8_pkcs5_v15(dev, apdev):
1850     """WPA2-Enterprise connection using EAP-TLS and PKCS #8, PKCS #5 v1.5 key"""
1851     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1852     hapd = hostapd.add_ap(apdev[0], params)
1853     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
1854                 client_cert="auth_serv/user.pem",
1855                 private_key="auth_serv/user.key.pkcs8.pkcs5v15",
1856                 private_key_passwd="whatever")
1857
1858 def test_ap_wpa2_eap_tls_blob(dev, apdev):
1859     """WPA2-Enterprise connection using EAP-TLS and config blobs"""
1860     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1861     hapd = hostapd.add_ap(apdev[0], params)
1862     cert = read_pem("auth_serv/ca.pem")
1863     if "OK" not in dev[0].request("SET blob cacert " + cert.encode("hex")):
1864         raise Exception("Could not set cacert blob")
1865     cert = read_pem("auth_serv/user.pem")
1866     if "OK" not in dev[0].request("SET blob usercert " + cert.encode("hex")):
1867         raise Exception("Could not set usercert blob")
1868     key = read_pem("auth_serv/user.rsa-key")
1869     if "OK" not in dev[0].request("SET blob userkey " + key.encode("hex")):
1870         raise Exception("Could not set cacert blob")
1871     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="blob://cacert",
1872                 client_cert="blob://usercert",
1873                 private_key="blob://userkey")
1874
1875 def test_ap_wpa2_eap_tls_blob_missing(dev, apdev):
1876     """EAP-TLS and config blob missing"""
1877     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1878     hostapd.add_ap(apdev[0], params)
1879     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
1880                    identity="tls user",
1881                    ca_cert="blob://testing-blob-does-not-exist",
1882                    client_cert="blob://testing-blob-does-not-exist",
1883                    private_key="blob://testing-blob-does-not-exist",
1884                    wait_connect=False, scan_freq="2412")
1885     ev = dev[0].wait_event(["EAP: Failed to initialize EAP method"], timeout=10)
1886     if ev is None:
1887         raise Exception("EAP failure not reported")
1888     dev[0].request("REMOVE_NETWORK all")
1889     dev[0].wait_disconnected()
1890
1891 def test_ap_wpa2_eap_tls_with_tls_len(dev, apdev):
1892     """EAP-TLS and TLS Message Length in unfragmented packets"""
1893     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1894     hapd = hostapd.add_ap(apdev[0], params)
1895     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
1896                 phase1="include_tls_length=1",
1897                 client_cert="auth_serv/user.pem",
1898                 private_key="auth_serv/user.key")
1899
1900 def test_ap_wpa2_eap_tls_pkcs12(dev, apdev):
1901     """WPA2-Enterprise connection using EAP-TLS and PKCS#12"""
1902     check_pkcs12_support(dev[0])
1903     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1904     hapd = hostapd.add_ap(apdev[0], params)
1905     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
1906                 private_key="auth_serv/user.pkcs12",
1907                 private_key_passwd="whatever")
1908     dev[0].request("REMOVE_NETWORK all")
1909     dev[0].wait_disconnected()
1910
1911     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
1912                    identity="tls user",
1913                    ca_cert="auth_serv/ca.pem",
1914                    private_key="auth_serv/user.pkcs12",
1915                    wait_connect=False, scan_freq="2412")
1916     ev = dev[0].wait_event(["CTRL-REQ-PASSPHRASE"])
1917     if ev is None:
1918         raise Exception("Request for private key passphrase timed out")
1919     id = ev.split(':')[0].split('-')[-1]
1920     dev[0].request("CTRL-RSP-PASSPHRASE-" + id + ":whatever")
1921     dev[0].wait_connected(timeout=10)
1922     dev[0].request("REMOVE_NETWORK all")
1923     dev[0].wait_disconnected()
1924
1925     # Run this twice to verify certificate chain handling with OpenSSL. Use two
1926     # different files to cover both cases of the extra certificate being the
1927     # one that signed the client certificate and it being unrelated to the
1928     # client certificate.
1929     for pkcs12 in "auth_serv/user2.pkcs12", "auth_serv/user3.pkcs12":
1930         for i in range(2):
1931             eap_connect(dev[0], hapd, "TLS", "tls user",
1932                         ca_cert="auth_serv/ca.pem",
1933                         private_key=pkcs12,
1934                         private_key_passwd="whatever")
1935             dev[0].request("REMOVE_NETWORK all")
1936             dev[0].wait_disconnected()
1937
1938 def test_ap_wpa2_eap_tls_pkcs12_blob(dev, apdev):
1939     """WPA2-Enterprise connection using EAP-TLS and PKCS#12 from configuration blob"""
1940     check_pkcs12_support(dev[0])
1941     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1942     hapd = hostapd.add_ap(apdev[0], params)
1943     cert = read_pem("auth_serv/ca.pem")
1944     if "OK" not in dev[0].request("SET blob cacert " + cert.encode("hex")):
1945         raise Exception("Could not set cacert blob")
1946     with open("auth_serv/user.pkcs12", "rb") as f:
1947         if "OK" not in dev[0].request("SET blob pkcs12 " + f.read().encode("hex")):
1948             raise Exception("Could not set pkcs12 blob")
1949     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="blob://cacert",
1950                 private_key="blob://pkcs12",
1951                 private_key_passwd="whatever")
1952
1953 def test_ap_wpa2_eap_tls_neg_incorrect_trust_root(dev, apdev):
1954     """WPA2-Enterprise negative test - incorrect trust root"""
1955     check_eap_capa(dev[0], "MSCHAPV2")
1956     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1957     hostapd.add_ap(apdev[0], params)
1958     cert = read_pem("auth_serv/ca-incorrect.pem")
1959     if "OK" not in dev[0].request("SET blob cacert " + cert.encode("hex")):
1960         raise Exception("Could not set cacert blob")
1961     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
1962                    identity="DOMAIN\mschapv2 user", anonymous_identity="ttls",
1963                    password="password", phase2="auth=MSCHAPV2",
1964                    ca_cert="blob://cacert",
1965                    wait_connect=False, scan_freq="2412")
1966     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
1967                    identity="DOMAIN\mschapv2 user", anonymous_identity="ttls",
1968                    password="password", phase2="auth=MSCHAPV2",
1969                    ca_cert="auth_serv/ca-incorrect.pem",
1970                    wait_connect=False, scan_freq="2412")
1971
1972     for dev in (dev[0], dev[1]):
1973         ev = dev.wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
1974         if ev is None:
1975             raise Exception("Association and EAP start timed out")
1976
1977         ev = dev.wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=10)
1978         if ev is None:
1979             raise Exception("EAP method selection timed out")
1980         if "TTLS" not in ev:
1981             raise Exception("Unexpected EAP method")
1982
1983         ev = dev.wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR",
1984                              "CTRL-EVENT-EAP-SUCCESS",
1985                              "CTRL-EVENT-EAP-FAILURE",
1986                              "CTRL-EVENT-CONNECTED",
1987                              "CTRL-EVENT-DISCONNECTED"], timeout=10)
1988         if ev is None:
1989             raise Exception("EAP result timed out")
1990         if "CTRL-EVENT-EAP-TLS-CERT-ERROR" not in ev:
1991             raise Exception("TLS certificate error not reported")
1992
1993         ev = dev.wait_event(["CTRL-EVENT-EAP-SUCCESS",
1994                              "CTRL-EVENT-EAP-FAILURE",
1995                              "CTRL-EVENT-CONNECTED",
1996                              "CTRL-EVENT-DISCONNECTED"], timeout=10)
1997         if ev is None:
1998             raise Exception("EAP result(2) timed out")
1999         if "CTRL-EVENT-EAP-FAILURE" not in ev:
2000             raise Exception("EAP failure not reported")
2001
2002         ev = dev.wait_event(["CTRL-EVENT-CONNECTED",
2003                              "CTRL-EVENT-DISCONNECTED"], timeout=10)
2004         if ev is None:
2005             raise Exception("EAP result(3) timed out")
2006         if "CTRL-EVENT-DISCONNECTED" not in ev:
2007             raise Exception("Disconnection not reported")
2008
2009         ev = dev.wait_event(["CTRL-EVENT-SSID-TEMP-DISABLED"], timeout=10)
2010         if ev is None:
2011             raise Exception("Network block disabling not reported")
2012
2013 def test_ap_wpa2_eap_tls_diff_ca_trust(dev, apdev):
2014     """WPA2-Enterprise connection using EAP-TTLS/PAP and different CA trust"""
2015     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2016     hapd = hostapd.add_ap(apdev[0], params)
2017     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
2018                    identity="pap user", anonymous_identity="ttls",
2019                    password="password", phase2="auth=PAP",
2020                    ca_cert="auth_serv/ca.pem",
2021                    wait_connect=True, scan_freq="2412")
2022     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
2023                         identity="pap user", anonymous_identity="ttls",
2024                         password="password", phase2="auth=PAP",
2025                         ca_cert="auth_serv/ca-incorrect.pem",
2026                         only_add_network=True, scan_freq="2412")
2027
2028     dev[0].request("DISCONNECT")
2029     dev[0].wait_disconnected()
2030     dev[0].dump_monitor()
2031     dev[0].select_network(id, freq="2412")
2032
2033     ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD vendor=0 method=21"], timeout=15)
2034     if ev is None:
2035         raise Exception("EAP-TTLS not re-started")
2036     
2037     ev = dev[0].wait_disconnected(timeout=15)
2038     if "reason=23" not in ev:
2039         raise Exception("Proper reason code for disconnection not reported")
2040
2041 def test_ap_wpa2_eap_tls_diff_ca_trust2(dev, apdev):
2042     """WPA2-Enterprise connection using EAP-TTLS/PAP and different CA trust"""
2043     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2044     hapd = hostapd.add_ap(apdev[0], params)
2045     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
2046                    identity="pap user", anonymous_identity="ttls",
2047                    password="password", phase2="auth=PAP",
2048                    wait_connect=True, scan_freq="2412")
2049     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
2050                         identity="pap user", anonymous_identity="ttls",
2051                         password="password", phase2="auth=PAP",
2052                         ca_cert="auth_serv/ca-incorrect.pem",
2053                         only_add_network=True, scan_freq="2412")
2054
2055     dev[0].request("DISCONNECT")
2056     dev[0].wait_disconnected()
2057     dev[0].dump_monitor()
2058     dev[0].select_network(id, freq="2412")
2059
2060     ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD vendor=0 method=21"], timeout=15)
2061     if ev is None:
2062         raise Exception("EAP-TTLS not re-started")
2063     
2064     ev = dev[0].wait_disconnected(timeout=15)
2065     if "reason=23" not in ev:
2066         raise Exception("Proper reason code for disconnection not reported")
2067
2068 def test_ap_wpa2_eap_tls_diff_ca_trust3(dev, apdev):
2069     """WPA2-Enterprise connection using EAP-TTLS/PAP and different CA trust"""
2070     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2071     hapd = hostapd.add_ap(apdev[0], params)
2072     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
2073                         identity="pap user", anonymous_identity="ttls",
2074                         password="password", phase2="auth=PAP",
2075                         ca_cert="auth_serv/ca.pem",
2076                         wait_connect=True, scan_freq="2412")
2077     dev[0].request("DISCONNECT")
2078     dev[0].wait_disconnected()
2079     dev[0].dump_monitor()
2080     dev[0].set_network_quoted(id, "ca_cert", "auth_serv/ca-incorrect.pem")
2081     dev[0].select_network(id, freq="2412")
2082
2083     ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD vendor=0 method=21"], timeout=15)
2084     if ev is None:
2085         raise Exception("EAP-TTLS not re-started")
2086     
2087     ev = dev[0].wait_disconnected(timeout=15)
2088     if "reason=23" not in ev:
2089         raise Exception("Proper reason code for disconnection not reported")
2090
2091 def test_ap_wpa2_eap_tls_neg_suffix_match(dev, apdev):
2092     """WPA2-Enterprise negative test - domain suffix mismatch"""
2093     check_domain_suffix_match(dev[0])
2094     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2095     hostapd.add_ap(apdev[0], params)
2096     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
2097                    identity="DOMAIN\mschapv2 user", anonymous_identity="ttls",
2098                    password="password", phase2="auth=MSCHAPV2",
2099                    ca_cert="auth_serv/ca.pem",
2100                    domain_suffix_match="incorrect.example.com",
2101                    wait_connect=False, scan_freq="2412")
2102
2103     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
2104     if ev is None:
2105         raise Exception("Association and EAP start timed out")
2106
2107     ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=10)
2108     if ev is None:
2109         raise Exception("EAP method selection timed out")
2110     if "TTLS" not in ev:
2111         raise Exception("Unexpected EAP method")
2112
2113     ev = dev[0].wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR",
2114                             "CTRL-EVENT-EAP-SUCCESS",
2115                             "CTRL-EVENT-EAP-FAILURE",
2116                             "CTRL-EVENT-CONNECTED",
2117                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
2118     if ev is None:
2119         raise Exception("EAP result timed out")
2120     if "CTRL-EVENT-EAP-TLS-CERT-ERROR" not in ev:
2121         raise Exception("TLS certificate error not reported")
2122     if "Domain suffix mismatch" not in ev:
2123         raise Exception("Domain suffix mismatch not reported")
2124
2125     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS",
2126                             "CTRL-EVENT-EAP-FAILURE",
2127                             "CTRL-EVENT-CONNECTED",
2128                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
2129     if ev is None:
2130         raise Exception("EAP result(2) timed out")
2131     if "CTRL-EVENT-EAP-FAILURE" not in ev:
2132         raise Exception("EAP failure not reported")
2133
2134     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
2135                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
2136     if ev is None:
2137         raise Exception("EAP result(3) timed out")
2138     if "CTRL-EVENT-DISCONNECTED" not in ev:
2139         raise Exception("Disconnection not reported")
2140
2141     ev = dev[0].wait_event(["CTRL-EVENT-SSID-TEMP-DISABLED"], timeout=10)
2142     if ev is None:
2143         raise Exception("Network block disabling not reported")
2144
2145 def test_ap_wpa2_eap_tls_neg_domain_match(dev, apdev):
2146     """WPA2-Enterprise negative test - domain mismatch"""
2147     check_domain_match(dev[0])
2148     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2149     hostapd.add_ap(apdev[0], params)
2150     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
2151                    identity="DOMAIN\mschapv2 user", anonymous_identity="ttls",
2152                    password="password", phase2="auth=MSCHAPV2",
2153                    ca_cert="auth_serv/ca.pem",
2154                    domain_match="w1.fi",
2155                    wait_connect=False, scan_freq="2412")
2156
2157     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
2158     if ev is None:
2159         raise Exception("Association and EAP start timed out")
2160
2161     ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=10)
2162     if ev is None:
2163         raise Exception("EAP method selection timed out")
2164     if "TTLS" not in ev:
2165         raise Exception("Unexpected EAP method")
2166
2167     ev = dev[0].wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR",
2168                             "CTRL-EVENT-EAP-SUCCESS",
2169                             "CTRL-EVENT-EAP-FAILURE",
2170                             "CTRL-EVENT-CONNECTED",
2171                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
2172     if ev is None:
2173         raise Exception("EAP result timed out")
2174     if "CTRL-EVENT-EAP-TLS-CERT-ERROR" not in ev:
2175         raise Exception("TLS certificate error not reported")
2176     if "Domain mismatch" not in ev:
2177         raise Exception("Domain mismatch not reported")
2178
2179     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS",
2180                             "CTRL-EVENT-EAP-FAILURE",
2181                             "CTRL-EVENT-CONNECTED",
2182                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
2183     if ev is None:
2184         raise Exception("EAP result(2) timed out")
2185     if "CTRL-EVENT-EAP-FAILURE" not in ev:
2186         raise Exception("EAP failure not reported")
2187
2188     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
2189                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
2190     if ev is None:
2191         raise Exception("EAP result(3) timed out")
2192     if "CTRL-EVENT-DISCONNECTED" not in ev:
2193         raise Exception("Disconnection not reported")
2194
2195     ev = dev[0].wait_event(["CTRL-EVENT-SSID-TEMP-DISABLED"], timeout=10)
2196     if ev is None:
2197         raise Exception("Network block disabling not reported")
2198
2199 def test_ap_wpa2_eap_tls_neg_subject_match(dev, apdev):
2200     """WPA2-Enterprise negative test - subject mismatch"""
2201     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2202     hostapd.add_ap(apdev[0], params)
2203     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
2204                    identity="DOMAIN\mschapv2 user", anonymous_identity="ttls",
2205                    password="password", phase2="auth=MSCHAPV2",
2206                    ca_cert="auth_serv/ca.pem",
2207                    subject_match="/C=FI/O=w1.fi/CN=example.com",
2208                    wait_connect=False, scan_freq="2412")
2209
2210     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
2211     if ev is None:
2212         raise Exception("Association and EAP start timed out")
2213
2214     ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD",
2215                             "EAP: Failed to initialize EAP method"], timeout=10)
2216     if ev is None:
2217         raise Exception("EAP method selection timed out")
2218     if "EAP: Failed to initialize EAP method" in ev:
2219         tls = dev[0].request("GET tls_library")
2220         if tls.startswith("OpenSSL"):
2221             raise Exception("Failed to select EAP method")
2222         logger.info("subject_match not supported - connection failed, so test succeeded")
2223         return
2224     if "TTLS" not in ev:
2225         raise Exception("Unexpected EAP method")
2226
2227     ev = dev[0].wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR",
2228                             "CTRL-EVENT-EAP-SUCCESS",
2229                             "CTRL-EVENT-EAP-FAILURE",
2230                             "CTRL-EVENT-CONNECTED",
2231                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
2232     if ev is None:
2233         raise Exception("EAP result timed out")
2234     if "CTRL-EVENT-EAP-TLS-CERT-ERROR" not in ev:
2235         raise Exception("TLS certificate error not reported")
2236     if "Subject mismatch" not in ev:
2237         raise Exception("Subject mismatch not reported")
2238
2239     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS",
2240                             "CTRL-EVENT-EAP-FAILURE",
2241                             "CTRL-EVENT-CONNECTED",
2242                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
2243     if ev is None:
2244         raise Exception("EAP result(2) timed out")
2245     if "CTRL-EVENT-EAP-FAILURE" not in ev:
2246         raise Exception("EAP failure not reported")
2247
2248     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
2249                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
2250     if ev is None:
2251         raise Exception("EAP result(3) timed out")
2252     if "CTRL-EVENT-DISCONNECTED" not in ev:
2253         raise Exception("Disconnection not reported")
2254
2255     ev = dev[0].wait_event(["CTRL-EVENT-SSID-TEMP-DISABLED"], timeout=10)
2256     if ev is None:
2257         raise Exception("Network block disabling not reported")
2258
2259 def test_ap_wpa2_eap_tls_neg_altsubject_match(dev, apdev):
2260     """WPA2-Enterprise negative test - altsubject mismatch"""
2261     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2262     hostapd.add_ap(apdev[0], params)
2263
2264     tests = [ "incorrect.example.com",
2265               "DNS:incorrect.example.com",
2266               "DNS:w1.fi",
2267               "DNS:erver.w1.fi" ]
2268     for match in tests:
2269         _test_ap_wpa2_eap_tls_neg_altsubject_match(dev, apdev, match)
2270
2271 def _test_ap_wpa2_eap_tls_neg_altsubject_match(dev, apdev, match):
2272     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
2273                    identity="DOMAIN\mschapv2 user", anonymous_identity="ttls",
2274                    password="password", phase2="auth=MSCHAPV2",
2275                    ca_cert="auth_serv/ca.pem",
2276                    altsubject_match=match,
2277                    wait_connect=False, scan_freq="2412")
2278
2279     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
2280     if ev is None:
2281         raise Exception("Association and EAP start timed out")
2282
2283     ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD",
2284                             "EAP: Failed to initialize EAP method"], timeout=10)
2285     if ev is None:
2286         raise Exception("EAP method selection timed out")
2287     if "EAP: Failed to initialize EAP method" in ev:
2288         tls = dev[0].request("GET tls_library")
2289         if tls.startswith("OpenSSL"):
2290             raise Exception("Failed to select EAP method")
2291         logger.info("altsubject_match not supported - connection failed, so test succeeded")
2292         return
2293     if "TTLS" not in ev:
2294         raise Exception("Unexpected EAP method")
2295
2296     ev = dev[0].wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR",
2297                             "CTRL-EVENT-EAP-SUCCESS",
2298                             "CTRL-EVENT-EAP-FAILURE",
2299                             "CTRL-EVENT-CONNECTED",
2300                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
2301     if ev is None:
2302         raise Exception("EAP result timed out")
2303     if "CTRL-EVENT-EAP-TLS-CERT-ERROR" not in ev:
2304         raise Exception("TLS certificate error not reported")
2305     if "AltSubject mismatch" not in ev:
2306         raise Exception("altsubject mismatch not reported")
2307
2308     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS",
2309                             "CTRL-EVENT-EAP-FAILURE",
2310                             "CTRL-EVENT-CONNECTED",
2311                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
2312     if ev is None:
2313         raise Exception("EAP result(2) timed out")
2314     if "CTRL-EVENT-EAP-FAILURE" not in ev:
2315         raise Exception("EAP failure not reported")
2316
2317     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
2318                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
2319     if ev is None:
2320         raise Exception("EAP result(3) timed out")
2321     if "CTRL-EVENT-DISCONNECTED" not in ev:
2322         raise Exception("Disconnection not reported")
2323
2324     ev = dev[0].wait_event(["CTRL-EVENT-SSID-TEMP-DISABLED"], timeout=10)
2325     if ev is None:
2326         raise Exception("Network block disabling not reported")
2327
2328     dev[0].request("REMOVE_NETWORK all")
2329
2330 def test_ap_wpa2_eap_unauth_tls(dev, apdev):
2331     """WPA2-Enterprise connection using UNAUTH-TLS"""
2332     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2333     hapd = hostapd.add_ap(apdev[0], params)
2334     eap_connect(dev[0], hapd, "UNAUTH-TLS", "unauth-tls",
2335                 ca_cert="auth_serv/ca.pem")
2336     eap_reauth(dev[0], "UNAUTH-TLS")
2337
2338 def test_ap_wpa2_eap_ttls_server_cert_hash(dev, apdev):
2339     """WPA2-Enterprise connection using EAP-TTLS and server certificate hash"""
2340     check_cert_probe_support(dev[0])
2341     skip_with_fips(dev[0])
2342     srv_cert_hash = "bdb9cb55d3df278e52a071abf58e7f0238fbec3ad8fb2c254742f63562628272"
2343     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2344     hapd = hostapd.add_ap(apdev[0], params)
2345     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
2346                    identity="probe", ca_cert="probe://",
2347                    wait_connect=False, scan_freq="2412")
2348     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
2349     if ev is None:
2350         raise Exception("Association and EAP start timed out")
2351     ev = dev[0].wait_event(["CTRL-EVENT-EAP-PEER-CERT depth=0"], timeout=10)
2352     if ev is None:
2353         raise Exception("No peer server certificate event seen")
2354     if "hash=" + srv_cert_hash not in ev:
2355         raise Exception("Expected server certificate hash not reported")
2356     ev = dev[0].wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR"], timeout=10)
2357     if ev is None:
2358         raise Exception("EAP result timed out")
2359     if "Server certificate chain probe" not in ev:
2360         raise Exception("Server certificate probe not reported")
2361     dev[0].wait_disconnected(timeout=10)
2362     dev[0].request("REMOVE_NETWORK all")
2363
2364     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
2365                    identity="DOMAIN\mschapv2 user", anonymous_identity="ttls",
2366                    password="password", phase2="auth=MSCHAPV2",
2367                    ca_cert="hash://server/sha256/5a1bc1296205e6fdbe3979728efe3920798885c1c4590b5f90f43222d239ca6a",
2368                    wait_connect=False, scan_freq="2412")
2369     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
2370     if ev is None:
2371         raise Exception("Association and EAP start timed out")
2372     ev = dev[0].wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR"], timeout=10)
2373     if ev is None:
2374         raise Exception("EAP result timed out")
2375     if "Server certificate mismatch" not in ev:
2376         raise Exception("Server certificate mismatch not reported")
2377     dev[0].wait_disconnected(timeout=10)
2378     dev[0].request("REMOVE_NETWORK all")
2379
2380     eap_connect(dev[0], hapd, "TTLS", "DOMAIN\mschapv2 user",
2381                 anonymous_identity="ttls", password="password",
2382                 ca_cert="hash://server/sha256/" + srv_cert_hash,
2383                 phase2="auth=MSCHAPV2")
2384
2385 def test_ap_wpa2_eap_ttls_server_cert_hash_invalid(dev, apdev):
2386     """WPA2-Enterprise connection using EAP-TTLS and server certificate hash (invalid config)"""
2387     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2388     hostapd.add_ap(apdev[0], params)
2389     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
2390                    identity="DOMAIN\mschapv2 user", anonymous_identity="ttls",
2391                    password="password", phase2="auth=MSCHAPV2",
2392                    ca_cert="hash://server/md5/5a1bc1296205e6fdbe3979728efe3920798885c1c4590b5f90f43222d239ca6a",
2393                    wait_connect=False, scan_freq="2412")
2394     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
2395                    identity="DOMAIN\mschapv2 user", anonymous_identity="ttls",
2396                    password="password", phase2="auth=MSCHAPV2",
2397                    ca_cert="hash://server/sha256/5a1bc1296205e6fdbe3979728efe3920798885c1c4590b5f90f43222d239ca",
2398                    wait_connect=False, scan_freq="2412")
2399     dev[2].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
2400                    identity="DOMAIN\mschapv2 user", anonymous_identity="ttls",
2401                    password="password", phase2="auth=MSCHAPV2",
2402                    ca_cert="hash://server/sha256/5a1bc1296205e6fdbe3979728efe3920798885c1c4590b5f90f43222d239ca6Q",
2403                    wait_connect=False, scan_freq="2412")
2404     for i in range(0, 3):
2405         ev = dev[i].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
2406         if ev is None:
2407             raise Exception("Association and EAP start timed out")
2408         ev = dev[i].wait_event(["EAP: Failed to initialize EAP method: vendor 0 method 21 (TTLS)"], timeout=5)
2409         if ev is None:
2410             raise Exception("Did not report EAP method initialization failure")
2411
2412 def test_ap_wpa2_eap_pwd(dev, apdev):
2413     """WPA2-Enterprise connection using EAP-pwd"""
2414     check_eap_capa(dev[0], "PWD")
2415     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2416     hapd = hostapd.add_ap(apdev[0], params)
2417     eap_connect(dev[0], hapd, "PWD", "pwd user", password="secret password")
2418     eap_reauth(dev[0], "PWD")
2419     dev[0].request("REMOVE_NETWORK all")
2420
2421     eap_connect(dev[1], hapd, "PWD",
2422                 "pwd.user@test123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890.example.com",
2423                 password="secret password",
2424                 fragment_size="90")
2425
2426     logger.info("Negative test with incorrect password")
2427     eap_connect(dev[2], hapd, "PWD", "pwd user", password="secret-password",
2428                 expect_failure=True, local_error_report=True)
2429
2430     eap_connect(dev[0], hapd, "PWD",
2431                 "pwd.user@test123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890.example.com",
2432                 password="secret password",
2433                 fragment_size="31")
2434
2435 def test_ap_wpa2_eap_pwd_nthash(dev, apdev):
2436     """WPA2-Enterprise connection using EAP-pwd and NTHash"""
2437     check_eap_capa(dev[0], "PWD")
2438     skip_with_fips(dev[0])
2439     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2440     hapd = hostapd.add_ap(apdev[0], params)
2441     eap_connect(dev[0], hapd, "PWD", "pwd-hash", password="secret password")
2442     eap_connect(dev[1], hapd, "PWD", "pwd-hash",
2443                 password_hex="hash:e3718ece8ab74792cbbfffd316d2d19a")
2444     eap_connect(dev[2], hapd, "PWD", "pwd user",
2445                 password_hex="hash:e3718ece8ab74792cbbfffd316d2d19a",
2446                 expect_failure=True, local_error_report=True)
2447
2448 def test_ap_wpa2_eap_pwd_groups(dev, apdev):
2449     """WPA2-Enterprise connection using various EAP-pwd groups"""
2450     check_eap_capa(dev[0], "PWD")
2451     tls = dev[0].request("GET tls_library")
2452     params = { "ssid": "test-wpa2-eap", "wpa": "2", "wpa_key_mgmt": "WPA-EAP",
2453                "rsn_pairwise": "CCMP", "ieee8021x": "1",
2454                "eap_server": "1", "eap_user_file": "auth_serv/eap_user.conf" }
2455     groups = [ 19, 20, 21, 25, 26 ]
2456     if tls.startswith("OpenSSL") and "build=OpenSSL 1.0.2" in tls and "run=OpenSSL 1.0.2" in tls:
2457         logger.info("Add Brainpool EC groups since OpenSSL is new enough")
2458         groups += [ 27, 28, 29, 30 ]
2459     for i in groups:
2460         logger.info("Group %d" % i)
2461         params['pwd_group'] = str(i)
2462         hapd = hostapd.add_ap(apdev[0], params)
2463         try:
2464             eap_connect(dev[0], hapd, "PWD", "pwd user",
2465                         password="secret password")
2466             dev[0].request("REMOVE_NETWORK all")
2467             dev[0].wait_disconnected()
2468             dev[0].dump_monitor()
2469         except:
2470             if "BoringSSL" in tls and i in [ 25 ]:
2471                 logger.info("Ignore connection failure with group %d with BoringSSL" % i)
2472                 dev[0].request("DISCONNECT")
2473                 time.sleep(0.1)
2474                 dev[0].request("REMOVE_NETWORK all")
2475                 dev[0].dump_monitor()
2476                 continue
2477             raise
2478
2479 def test_ap_wpa2_eap_pwd_invalid_group(dev, apdev):
2480     """WPA2-Enterprise connection using invalid EAP-pwd group"""
2481     check_eap_capa(dev[0], "PWD")
2482     params = { "ssid": "test-wpa2-eap", "wpa": "2", "wpa_key_mgmt": "WPA-EAP",
2483                "rsn_pairwise": "CCMP", "ieee8021x": "1",
2484                "eap_server": "1", "eap_user_file": "auth_serv/eap_user.conf" }
2485     params['pwd_group'] = "0"
2486     hostapd.add_ap(apdev[0], params)
2487     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PWD",
2488                    identity="pwd user", password="secret password",
2489                    scan_freq="2412", wait_connect=False)
2490     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
2491     if ev is None:
2492         raise Exception("Timeout on EAP failure report")
2493
2494 def test_ap_wpa2_eap_pwd_as_frag(dev, apdev):
2495     """WPA2-Enterprise connection using EAP-pwd with server fragmentation"""
2496     check_eap_capa(dev[0], "PWD")
2497     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2498     params = { "ssid": "test-wpa2-eap", "wpa": "2", "wpa_key_mgmt": "WPA-EAP",
2499                "rsn_pairwise": "CCMP", "ieee8021x": "1",
2500                "eap_server": "1", "eap_user_file": "auth_serv/eap_user.conf",
2501                "pwd_group": "19", "fragment_size": "40" }
2502     hapd = hostapd.add_ap(apdev[0], params)
2503     eap_connect(dev[0], hapd, "PWD", "pwd user", password="secret password")
2504
2505 def test_ap_wpa2_eap_gpsk(dev, apdev):
2506     """WPA2-Enterprise connection using EAP-GPSK"""
2507     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2508     hapd = hostapd.add_ap(apdev[0], params)
2509     id = eap_connect(dev[0], hapd, "GPSK", "gpsk user",
2510                      password="abcdefghijklmnop0123456789abcdef")
2511     eap_reauth(dev[0], "GPSK")
2512
2513     logger.info("Test forced algorithm selection")
2514     for phase1 in [ "cipher=1", "cipher=2" ]:
2515         dev[0].set_network_quoted(id, "phase1", phase1)
2516         ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
2517         if ev is None:
2518             raise Exception("EAP success timed out")
2519         dev[0].wait_connected(timeout=10)
2520
2521     logger.info("Test failed algorithm negotiation")
2522     dev[0].set_network_quoted(id, "phase1", "cipher=9")
2523     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
2524     if ev is None:
2525         raise Exception("EAP failure timed out")
2526
2527     logger.info("Negative test with incorrect password")
2528     dev[0].request("REMOVE_NETWORK all")
2529     eap_connect(dev[0], hapd, "GPSK", "gpsk user",
2530                 password="ffcdefghijklmnop0123456789abcdef",
2531                 expect_failure=True)
2532
2533 def test_ap_wpa2_eap_sake(dev, apdev):
2534     """WPA2-Enterprise connection using EAP-SAKE"""
2535     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2536     hapd = hostapd.add_ap(apdev[0], params)
2537     eap_connect(dev[0], hapd, "SAKE", "sake user",
2538                 password_hex="0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef")
2539     eap_reauth(dev[0], "SAKE")
2540
2541     logger.info("Negative test with incorrect password")
2542     dev[0].request("REMOVE_NETWORK all")
2543     eap_connect(dev[0], hapd, "SAKE", "sake user",
2544                 password_hex="ff23456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
2545                 expect_failure=True)
2546
2547 def test_ap_wpa2_eap_eke(dev, apdev):
2548     """WPA2-Enterprise connection using EAP-EKE"""
2549     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2550     hapd = hostapd.add_ap(apdev[0], params)
2551     id = eap_connect(dev[0], hapd, "EKE", "eke user", password="hello")
2552     eap_reauth(dev[0], "EKE")
2553
2554     logger.info("Test forced algorithm selection")
2555     for phase1 in [ "dhgroup=5 encr=1 prf=2 mac=2",
2556                     "dhgroup=4 encr=1 prf=2 mac=2",
2557                     "dhgroup=3 encr=1 prf=2 mac=2",
2558                     "dhgroup=3 encr=1 prf=1 mac=1" ]:
2559         dev[0].set_network_quoted(id, "phase1", phase1)
2560         ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
2561         if ev is None:
2562             raise Exception("EAP success timed out")
2563         dev[0].wait_connected(timeout=10)
2564
2565     logger.info("Test failed algorithm negotiation")
2566     dev[0].set_network_quoted(id, "phase1", "dhgroup=9 encr=9 prf=9 mac=9")
2567     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
2568     if ev is None:
2569         raise Exception("EAP failure timed out")
2570
2571     logger.info("Negative test with incorrect password")
2572     dev[0].request("REMOVE_NETWORK all")
2573     eap_connect(dev[0], hapd, "EKE", "eke user", password="hello1",
2574                 expect_failure=True)
2575
2576 def test_ap_wpa2_eap_eke_many(dev, apdev, params):
2577     """WPA2-Enterprise connection using EAP-EKE (many connections) [long]"""
2578     if not params['long']:
2579         raise HwsimSkip("Skip test case with long duration due to --long not specified")
2580     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2581     hostapd.add_ap(apdev[0], params)
2582     success = 0
2583     fail = 0
2584     for i in range(100):
2585         for j in range(3):
2586             dev[j].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="EKE",
2587                            identity="eke user", password="hello",
2588                            phase1="dhgroup=3 encr=1 prf=1 mac=1",
2589                            scan_freq="2412", wait_connect=False)
2590         for j in range(3):
2591             ev = dev[j].wait_event(["CTRL-EVENT-CONNECTED",
2592                                     "CTRL-EVENT-DISCONNECTED"], timeout=15)
2593             if ev is None:
2594                 raise Exception("No connected/disconnected event")
2595             if "CTRL-EVENT-DISCONNECTED" in ev:
2596                 fail += 1
2597                 # The RADIUS server limits on active sessions can be hit when
2598                 # going through this test case, so try to give some more time
2599                 # for the server to remove sessions.
2600                 logger.info("Failed to connect i=%d j=%d" % (i, j))
2601                 dev[j].request("REMOVE_NETWORK all")
2602                 time.sleep(1)
2603             else:
2604                 success += 1
2605                 dev[j].request("REMOVE_NETWORK all")
2606                 dev[j].wait_disconnected()
2607             dev[j].dump_monitor()
2608     logger.info("Total success=%d failure=%d" % (success, fail))
2609
2610 def test_ap_wpa2_eap_eke_serverid_nai(dev, apdev):
2611     """WPA2-Enterprise connection using EAP-EKE with serverid NAI"""
2612     params = int_eap_server_params()
2613     params['server_id'] = 'example.server@w1.fi'
2614     hapd = hostapd.add_ap(apdev[0], params)
2615     eap_connect(dev[0], hapd, "EKE", "eke user", password="hello")
2616
2617 def test_ap_wpa2_eap_eke_server_oom(dev, apdev):
2618     """WPA2-Enterprise connection using EAP-EKE with server OOM"""
2619     params = int_eap_server_params()
2620     hapd = hostapd.add_ap(apdev[0], params)
2621     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2622
2623     for count,func in [ (1, "eap_eke_build_commit"),
2624                         (2, "eap_eke_build_commit"),
2625                         (3, "eap_eke_build_commit"),
2626                         (1, "eap_eke_build_confirm"),
2627                         (2, "eap_eke_build_confirm"),
2628                         (1, "eap_eke_process_commit"),
2629                         (2, "eap_eke_process_commit"),
2630                         (1, "eap_eke_process_confirm"),
2631                         (1, "eap_eke_process_identity"),
2632                         (2, "eap_eke_process_identity"),
2633                         (3, "eap_eke_process_identity"),
2634                         (4, "eap_eke_process_identity") ]:
2635         with alloc_fail(hapd, count, func):
2636             eap_connect(dev[0], hapd, "EKE", "eke user", password="hello",
2637                         expect_failure=True)
2638             dev[0].request("REMOVE_NETWORK all")
2639
2640     for count,func,pw in [ (1, "eap_eke_init", "hello"),
2641                            (1, "eap_eke_get_session_id", "hello"),
2642                            (1, "eap_eke_getKey", "hello"),
2643                            (1, "eap_eke_build_msg", "hello"),
2644                            (1, "eap_eke_build_failure", "wrong"),
2645                            (1, "eap_eke_build_identity", "hello"),
2646                            (2, "eap_eke_build_identity", "hello") ]:
2647         with alloc_fail(hapd, count, func):
2648             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
2649                            eap="EKE", identity="eke user", password=pw,
2650                            wait_connect=False, scan_freq="2412")
2651             # This would eventually time out, but we can stop after having
2652             # reached the allocation failure.
2653             for i in range(20):
2654                 time.sleep(0.1)
2655                 if hapd.request("GET_ALLOC_FAIL").startswith('0'):
2656                     break
2657             dev[0].request("REMOVE_NETWORK all")
2658
2659     for count in range(1, 1000):
2660         try:
2661             with alloc_fail(hapd, count, "eap_server_sm_step"):
2662                 dev[0].connect("test-wpa2-eap",
2663                                key_mgmt="WPA-EAP WPA-EAP-SHA256",
2664                                eap="EKE", identity="eke user", password=pw,
2665                                wait_connect=False, scan_freq="2412")
2666                 # This would eventually time out, but we can stop after having
2667                 # reached the allocation failure.
2668                 for i in range(10):
2669                     time.sleep(0.1)
2670                     if hapd.request("GET_ALLOC_FAIL").startswith('0'):
2671                         break
2672                 dev[0].request("REMOVE_NETWORK all")
2673         except Exception, e:
2674             if str(e) == "Allocation failure did not trigger":
2675                 if count < 30:
2676                     raise Exception("Too few allocation failures")
2677                 logger.info("%d allocation failures tested" % (count - 1))
2678                 break
2679             raise e
2680
2681 def test_ap_wpa2_eap_ikev2(dev, apdev):
2682     """WPA2-Enterprise connection using EAP-IKEv2"""
2683     check_eap_capa(dev[0], "IKEV2")
2684     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2685     hapd = hostapd.add_ap(apdev[0], params)
2686     eap_connect(dev[0], hapd, "IKEV2", "ikev2 user",
2687                 password="ike password")
2688     eap_reauth(dev[0], "IKEV2")
2689     dev[0].request("REMOVE_NETWORK all")
2690     eap_connect(dev[0], hapd, "IKEV2", "ikev2 user",
2691                 password="ike password", fragment_size="50")
2692
2693     logger.info("Negative test with incorrect password")
2694     dev[0].request("REMOVE_NETWORK all")
2695     eap_connect(dev[0], hapd, "IKEV2", "ikev2 user",
2696                 password="ike-password", expect_failure=True)
2697     dev[0].request("REMOVE_NETWORK all")
2698
2699     eap_connect(dev[0], hapd, "IKEV2", "ikev2 user",
2700                 password="ike password", fragment_size="0")
2701     dev[0].request("REMOVE_NETWORK all")
2702     dev[0].wait_disconnected()
2703
2704 def test_ap_wpa2_eap_ikev2_as_frag(dev, apdev):
2705     """WPA2-Enterprise connection using EAP-IKEv2 with server fragmentation"""
2706     check_eap_capa(dev[0], "IKEV2")
2707     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2708     params = { "ssid": "test-wpa2-eap", "wpa": "2", "wpa_key_mgmt": "WPA-EAP",
2709                "rsn_pairwise": "CCMP", "ieee8021x": "1",
2710                "eap_server": "1", "eap_user_file": "auth_serv/eap_user.conf",
2711                "fragment_size": "50" }
2712     hapd = hostapd.add_ap(apdev[0], params)
2713     eap_connect(dev[0], hapd, "IKEV2", "ikev2 user",
2714                 password="ike password")
2715     eap_reauth(dev[0], "IKEV2")
2716
2717 def test_ap_wpa2_eap_ikev2_oom(dev, apdev):
2718     """WPA2-Enterprise connection using EAP-IKEv2 and OOM"""
2719     check_eap_capa(dev[0], "IKEV2")
2720     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2721     hostapd.add_ap(apdev[0], params)
2722
2723     tests = [ (1, "dh_init"),
2724               (2, "dh_init"),
2725               (1, "dh_derive_shared") ]
2726     for count, func in tests:
2727         with alloc_fail(dev[0], count, func):
2728             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="IKEV2",
2729                            identity="ikev2 user", password="ike password",
2730                            wait_connect=False, scan_freq="2412")
2731             ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=5)
2732             if ev is None:
2733                 raise Exception("EAP method not selected")
2734             for i in range(10):
2735                 if "0:" in dev[0].request("GET_ALLOC_FAIL"):
2736                     break
2737                 time.sleep(0.02)
2738             dev[0].request("REMOVE_NETWORK all")
2739
2740     tests = [ (1, "os_get_random;dh_init") ]
2741     for count, func in tests:
2742         with fail_test(dev[0], count, func):
2743             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="IKEV2",
2744                            identity="ikev2 user", password="ike password",
2745                            wait_connect=False, scan_freq="2412")
2746             ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=5)
2747             if ev is None:
2748                 raise Exception("EAP method not selected")
2749             for i in range(10):
2750                 if "0:" in dev[0].request("GET_FAIL"):
2751                     break
2752                 time.sleep(0.02)
2753             dev[0].request("REMOVE_NETWORK all")
2754
2755 def test_ap_wpa2_eap_pax(dev, apdev):
2756     """WPA2-Enterprise connection using EAP-PAX"""
2757     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2758     hapd = hostapd.add_ap(apdev[0], params)
2759     eap_connect(dev[0], hapd, "PAX", "pax.user@example.com",
2760                 password_hex="0123456789abcdef0123456789abcdef")
2761     eap_reauth(dev[0], "PAX")
2762
2763     logger.info("Negative test with incorrect password")
2764     dev[0].request("REMOVE_NETWORK all")
2765     eap_connect(dev[0], hapd, "PAX", "pax.user@example.com",
2766                 password_hex="ff23456789abcdef0123456789abcdef",
2767                 expect_failure=True)
2768
2769 def test_ap_wpa2_eap_psk(dev, apdev):
2770     """WPA2-Enterprise connection using EAP-PSK"""
2771     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2772     params["wpa_key_mgmt"] = "WPA-EAP-SHA256"
2773     params["ieee80211w"] = "2"
2774     hapd = hostapd.add_ap(apdev[0], params)
2775     eap_connect(dev[0], hapd, "PSK", "psk.user@example.com",
2776                 password_hex="0123456789abcdef0123456789abcdef", sha256=True)
2777     eap_reauth(dev[0], "PSK", sha256=True)
2778     check_mib(dev[0], [ ("dot11RSNAAuthenticationSuiteRequested", "00-0f-ac-5"),
2779                         ("dot11RSNAAuthenticationSuiteSelected", "00-0f-ac-5") ])
2780
2781     bss = dev[0].get_bss(apdev[0]['bssid'])
2782     if 'flags' not in bss:
2783         raise Exception("Could not get BSS flags from BSS table")
2784     if "[WPA2-EAP-SHA256-CCMP]" not in bss['flags']:
2785         raise Exception("Unexpected BSS flags: " + bss['flags'])
2786
2787     logger.info("Negative test with incorrect password")
2788     dev[0].request("REMOVE_NETWORK all")
2789     eap_connect(dev[0], hapd, "PSK", "psk.user@example.com",
2790                 password_hex="ff23456789abcdef0123456789abcdef", sha256=True,
2791                 expect_failure=True)
2792
2793 def test_ap_wpa2_eap_psk_oom(dev, apdev):
2794     """WPA2-Enterprise connection using EAP-PSK and OOM"""
2795     skip_with_fips(dev[0])
2796     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2797     hostapd.add_ap(apdev[0], params)
2798     tests = [ (1, "=aes_128_eax_encrypt"),
2799               (1, "=aes_128_eax_decrypt") ]
2800     for count, func in tests:
2801         with alloc_fail(dev[0], count, func):
2802             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PSK",
2803                            identity="psk.user@example.com",
2804                            password_hex="0123456789abcdef0123456789abcdef",
2805                            wait_connect=False, scan_freq="2412")
2806             ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=5)
2807             if ev is None:
2808                 raise Exception("EAP method not selected")
2809             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL",
2810                               note="Failure not triggered: %d:%s" % (count, func))
2811             dev[0].request("REMOVE_NETWORK all")
2812             dev[0].wait_disconnected()
2813
2814     tests = [ (1, "aes_128_ctr_encrypt;aes_128_eax_encrypt"),
2815               (1, "omac1_aes_128;aes_128_eax_encrypt"),
2816               (2, "omac1_aes_128;aes_128_eax_encrypt"),
2817               (3, "omac1_aes_128;aes_128_eax_encrypt"),
2818               (1, "omac1_aes_vector"),
2819               (1, "omac1_aes_128;aes_128_eax_decrypt"),
2820               (2, "omac1_aes_128;aes_128_eax_decrypt"),
2821               (3, "omac1_aes_128;aes_128_eax_decrypt"),
2822               (1, "aes_128_ctr_encrypt;aes_128_eax_decrypt") ]
2823     for count, func in tests:
2824         with fail_test(dev[0], count, func):
2825             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PSK",
2826                            identity="psk.user@example.com",
2827                            password_hex="0123456789abcdef0123456789abcdef",
2828                            wait_connect=False, scan_freq="2412")
2829             ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=5)
2830             if ev is None:
2831                 raise Exception("EAP method not selected")
2832             wait_fail_trigger(dev[0], "GET_FAIL",
2833                               note="Failure not triggered: %d:%s" % (count, func))
2834             dev[0].request("REMOVE_NETWORK all")
2835             dev[0].wait_disconnected()
2836
2837     with fail_test(dev[0], 1, "aes_128_encrypt_block"):
2838             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PSK",
2839                            identity="psk.user@example.com",
2840                            password_hex="0123456789abcdef0123456789abcdef",
2841                            wait_connect=False, scan_freq="2412")
2842             ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
2843             if ev is None:
2844                 raise Exception("EAP method failure not reported")
2845             dev[0].request("REMOVE_NETWORK all")
2846             dev[0].wait_disconnected()
2847
2848 def test_ap_wpa_eap_peap_eap_mschapv2(dev, apdev):
2849     """WPA-Enterprise connection using EAP-PEAP/EAP-MSCHAPv2"""
2850     check_eap_capa(dev[0], "MSCHAPV2")
2851     params = hostapd.wpa_eap_params(ssid="test-wpa-eap")
2852     hapd = hostapd.add_ap(apdev[0], params)
2853     dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="PEAP",
2854                    identity="user", password="password", phase2="auth=MSCHAPV2",
2855                    ca_cert="auth_serv/ca.pem", wait_connect=False,
2856                    scan_freq="2412")
2857     eap_check_auth(dev[0], "PEAP", True, rsn=False)
2858     hwsim_utils.test_connectivity(dev[0], hapd)
2859     eap_reauth(dev[0], "PEAP", rsn=False)
2860     check_mib(dev[0], [ ("dot11RSNAAuthenticationSuiteRequested", "00-50-f2-1"),
2861                         ("dot11RSNAAuthenticationSuiteSelected", "00-50-f2-1") ])
2862     status = dev[0].get_status(extra="VERBOSE")
2863     if 'portControl' not in status:
2864         raise Exception("portControl missing from STATUS-VERBOSE")
2865     if status['portControl'] != 'Auto':
2866         raise Exception("Unexpected portControl value: " + status['portControl'])
2867     if 'eap_session_id' not in status:
2868         raise Exception("eap_session_id missing from STATUS-VERBOSE")
2869     if not status['eap_session_id'].startswith("19"):
2870         raise Exception("Unexpected eap_session_id value: " + status['eap_session_id'])
2871
2872 def test_ap_wpa2_eap_interactive(dev, apdev):
2873     """WPA2-Enterprise connection using interactive identity/password entry"""
2874     check_eap_capa(dev[0], "MSCHAPV2")
2875     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2876     hapd = hostapd.add_ap(apdev[0], params)
2877
2878     tests = [ ("Connection with dynamic TTLS/MSCHAPv2 password entry",
2879                "TTLS", "ttls", "DOMAIN\mschapv2 user", "auth=MSCHAPV2",
2880                None, "password"),
2881               ("Connection with dynamic TTLS/MSCHAPv2 identity and password entry",
2882                "TTLS", "ttls", None, "auth=MSCHAPV2",
2883                "DOMAIN\mschapv2 user", "password"),
2884               ("Connection with dynamic TTLS/EAP-MSCHAPv2 password entry",
2885                "TTLS", "ttls", "user", "autheap=MSCHAPV2", None, "password"),
2886               ("Connection with dynamic TTLS/EAP-MD5 password entry",
2887                "TTLS", "ttls", "user", "autheap=MD5", None, "password"),
2888               ("Connection with dynamic PEAP/EAP-MSCHAPv2 password entry",
2889                "PEAP", None, "user", "auth=MSCHAPV2", None, "password"),
2890               ("Connection with dynamic PEAP/EAP-GTC password entry",
2891                "PEAP", None, "user", "auth=GTC", None, "password") ]
2892     for [desc,eap,anon,identity,phase2,req_id,req_pw] in tests:
2893         logger.info(desc)
2894         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap=eap,
2895                        anonymous_identity=anon, identity=identity,
2896                        ca_cert="auth_serv/ca.pem", phase2=phase2,
2897                        wait_connect=False, scan_freq="2412")
2898         if req_id:
2899             ev = dev[0].wait_event(["CTRL-REQ-IDENTITY"])
2900             if ev is None:
2901                 raise Exception("Request for identity timed out")
2902             id = ev.split(':')[0].split('-')[-1]
2903             dev[0].request("CTRL-RSP-IDENTITY-" + id + ":" + req_id)
2904         ev = dev[0].wait_event(["CTRL-REQ-PASSWORD","CTRL-REQ-OTP"])
2905         if ev is None:
2906             raise Exception("Request for password timed out")
2907         id = ev.split(':')[0].split('-')[-1]
2908         type = "OTP" if "CTRL-REQ-OTP" in ev else "PASSWORD"
2909         dev[0].request("CTRL-RSP-" + type + "-" + id + ":" + req_pw)
2910         dev[0].wait_connected(timeout=10)
2911         dev[0].request("REMOVE_NETWORK all")
2912
2913 def test_ap_wpa2_eap_ext_enable_network_while_connected(dev, apdev):
2914     """WPA2-Enterprise interactive identity entry and ENABLE_NETWORK"""
2915     check_eap_capa(dev[0], "MSCHAPV2")
2916     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2917     hapd = hostapd.add_ap(apdev[0], params)
2918
2919     id_other = dev[0].connect("other", key_mgmt="NONE", scan_freq="2412",
2920                               only_add_network=True)
2921
2922     req_id = "DOMAIN\mschapv2 user"
2923     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
2924                    anonymous_identity="ttls", identity=None,
2925                    password="password",
2926                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2927                    wait_connect=False, scan_freq="2412")
2928     ev = dev[0].wait_event(["CTRL-REQ-IDENTITY"])
2929     if ev is None:
2930         raise Exception("Request for identity timed out")
2931     id = ev.split(':')[0].split('-')[-1]
2932     dev[0].request("CTRL-RSP-IDENTITY-" + id + ":" + req_id)
2933     dev[0].wait_connected(timeout=10)
2934
2935     if "OK" not in dev[0].request("ENABLE_NETWORK " + str(id_other)):
2936         raise Exception("Failed to enable network")
2937     ev = dev[0].wait_event(["SME: Trying to authenticate"], timeout=1)
2938     if ev is not None:
2939         raise Exception("Unexpected reconnection attempt on ENABLE_NETWORK")
2940     dev[0].request("REMOVE_NETWORK all")
2941
2942 def test_ap_wpa2_eap_vendor_test(dev, apdev):
2943     """WPA2-Enterprise connection using EAP vendor test"""
2944     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2945     hapd = hostapd.add_ap(apdev[0], params)
2946     eap_connect(dev[0], hapd, "VENDOR-TEST", "vendor-test")
2947     eap_reauth(dev[0], "VENDOR-TEST")
2948     eap_connect(dev[1], hapd, "VENDOR-TEST", "vendor-test",
2949                 password="pending")
2950
2951 def test_ap_wpa2_eap_vendor_test_oom(dev, apdev):
2952     """WPA2-Enterprise connection using EAP vendor test (OOM)"""
2953     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2954     hostapd.add_ap(apdev[0], params)
2955
2956     tests = [ "eap_vendor_test_init",
2957               "eap_msg_alloc;eap_vendor_test_process",
2958               "eap_vendor_test_getKey" ]
2959     for func in tests:
2960         with alloc_fail(dev[0], 1, func):
2961             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP",
2962                            scan_freq="2412",
2963                            eap="VENDOR-TEST", identity="vendor-test",
2964                            wait_connect=False)
2965             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
2966             dev[0].request("REMOVE_NETWORK all")
2967             dev[0].wait_disconnected()
2968
2969 def test_ap_wpa2_eap_fast_mschapv2_unauth_prov(dev, apdev):
2970     """WPA2-Enterprise connection using EAP-FAST/MSCHAPv2 and unauthenticated provisioning"""
2971     check_eap_capa(dev[0], "FAST")
2972     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2973     hapd = hostapd.add_ap(apdev[0], params)
2974     eap_connect(dev[0], hapd, "FAST", "user",
2975                 anonymous_identity="FAST", password="password",
2976                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2977                 phase1="fast_provisioning=1", pac_file="blob://fast_pac")
2978     hwsim_utils.test_connectivity(dev[0], hapd)
2979     res = eap_reauth(dev[0], "FAST")
2980     if res['tls_session_reused'] != '1':
2981         raise Exception("EAP-FAST could not use PAC session ticket")
2982
2983 def test_ap_wpa2_eap_fast_pac_file(dev, apdev, params):
2984     """WPA2-Enterprise connection using EAP-FAST/MSCHAPv2 and PAC file"""
2985     check_eap_capa(dev[0], "FAST")
2986     pac_file = os.path.join(params['logdir'], "fast.pac")
2987     pac_file2 = os.path.join(params['logdir'], "fast-bin.pac")
2988     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2989     hapd = hostapd.add_ap(apdev[0], params)
2990
2991     try:
2992         eap_connect(dev[0], hapd, "FAST", "user",
2993                     anonymous_identity="FAST", password="password",
2994                     ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2995                     phase1="fast_provisioning=1", pac_file=pac_file)
2996         with open(pac_file, "r") as f:
2997             data = f.read()
2998             if "wpa_supplicant EAP-FAST PAC file - version 1" not in data:
2999                 raise Exception("PAC file header missing")
3000             if "PAC-Key=" not in data:
3001                 raise Exception("PAC-Key missing from PAC file")
3002         dev[0].request("REMOVE_NETWORK all")
3003         eap_connect(dev[0], hapd, "FAST", "user",
3004                     anonymous_identity="FAST", password="password",
3005                     ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3006                     pac_file=pac_file)
3007
3008         eap_connect(dev[1], hapd, "FAST", "user",
3009                     anonymous_identity="FAST", password="password",
3010                     ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3011                     phase1="fast_provisioning=1 fast_pac_format=binary",
3012                     pac_file=pac_file2)
3013         dev[1].request("REMOVE_NETWORK all")
3014         eap_connect(dev[1], hapd, "FAST", "user",
3015                     anonymous_identity="FAST", password="password",
3016                     ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3017                     phase1="fast_pac_format=binary",
3018                     pac_file=pac_file2)
3019     finally:
3020         try:
3021             os.remove(pac_file)
3022         except:
3023             pass
3024         try:
3025             os.remove(pac_file2)
3026         except:
3027             pass
3028
3029 def test_ap_wpa2_eap_fast_binary_pac(dev, apdev):
3030     """WPA2-Enterprise connection using EAP-FAST and binary PAC format"""
3031     check_eap_capa(dev[0], "FAST")
3032     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3033     hapd = hostapd.add_ap(apdev[0], params)
3034     eap_connect(dev[0], hapd, "FAST", "user",
3035                 anonymous_identity="FAST", password="password",
3036                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3037                 phase1="fast_provisioning=1 fast_max_pac_list_len=1 fast_pac_format=binary",
3038                 pac_file="blob://fast_pac_bin")
3039     res = eap_reauth(dev[0], "FAST")
3040     if res['tls_session_reused'] != '1':
3041         raise Exception("EAP-FAST could not use PAC session ticket")
3042
3043     # Verify fast_max_pac_list_len=0 special case
3044     dev[0].request("REMOVE_NETWORK all")
3045     dev[0].wait_disconnected()
3046     eap_connect(dev[0], hapd, "FAST", "user",
3047                 anonymous_identity="FAST", password="password",
3048                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3049                 phase1="fast_provisioning=1 fast_max_pac_list_len=0 fast_pac_format=binary",
3050                 pac_file="blob://fast_pac_bin")
3051
3052 def test_ap_wpa2_eap_fast_missing_pac_config(dev, apdev):
3053     """WPA2-Enterprise connection using EAP-FAST and missing PAC config"""
3054     check_eap_capa(dev[0], "FAST")
3055     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3056     hostapd.add_ap(apdev[0], params)
3057
3058     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
3059                    identity="user", anonymous_identity="FAST",
3060                    password="password",
3061                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3062                    pac_file="blob://fast_pac_not_in_use",
3063                    wait_connect=False, scan_freq="2412")
3064     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3065     if ev is None:
3066         raise Exception("Timeout on EAP failure report")
3067     dev[0].request("REMOVE_NETWORK all")
3068
3069     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
3070                    identity="user", anonymous_identity="FAST",
3071                    password="password",
3072                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3073                    wait_connect=False, scan_freq="2412")
3074     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3075     if ev is None:
3076         raise Exception("Timeout on EAP failure report")
3077
3078 def test_ap_wpa2_eap_fast_binary_pac_errors(dev, apdev):
3079     """EAP-FAST and binary PAC errors"""
3080     check_eap_capa(dev[0], "FAST")
3081     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3082     hapd = hostapd.add_ap(apdev[0], params)
3083
3084     tests = [ (1, "=eap_fast_save_pac_bin"),
3085               (1, "eap_fast_write_pac"),
3086               (2, "eap_fast_write_pac"), ]
3087     for count, func in tests:
3088         if "OK" not in dev[0].request("SET blob fast_pac_bin_errors "):
3089             raise Exception("Could not set blob")
3090
3091         with alloc_fail(dev[0], count, func):
3092             eap_connect(dev[0], hapd, "FAST", "user",
3093                         anonymous_identity="FAST", password="password",
3094                         ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3095                         phase1="fast_provisioning=1 fast_pac_format=binary",
3096                         pac_file="blob://fast_pac_bin_errors")
3097             dev[0].request("REMOVE_NETWORK all")
3098             dev[0].wait_disconnected()
3099
3100     tests = [ "00", "000000000000", "6ae4920c0001",
3101               "6ae4920c000000",
3102               "6ae4920c0000" + "0000" + 32*"00" + "ffff" + "0000",
3103               "6ae4920c0000" + "0000" + 32*"00" + "0001" + "0000",
3104               "6ae4920c0000" + "0000" + 32*"00" + "0000" + "0001",
3105               "6ae4920c0000" + "0000" + 32*"00" + "0000" + "0008" + "00040000" + "0007000100"]
3106     for t in tests:
3107         if "OK" not in dev[0].request("SET blob fast_pac_bin_errors " + t):
3108             raise Exception("Could not set blob")
3109
3110         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
3111                        identity="user", anonymous_identity="FAST",
3112                        password="password",
3113                        ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3114                        phase1="fast_provisioning=1 fast_pac_format=binary",
3115                        pac_file="blob://fast_pac_bin_errors",
3116                        scan_freq="2412", wait_connect=False)
3117         ev = dev[0].wait_event(["EAP: Failed to initialize EAP method"],
3118                                timeout=5)
3119         if ev is None:
3120             raise Exception("Failure not reported")
3121         dev[0].request("REMOVE_NETWORK all")
3122         dev[0].wait_disconnected()
3123
3124     pac = "6ae4920c0000" + "0000" + 32*"00" + "0000" + "0000"
3125     tests = [ (1, "eap_fast_load_pac_bin"),
3126               (2, "eap_fast_load_pac_bin"),
3127               (3, "eap_fast_load_pac_bin") ]
3128     for count, func in tests:
3129         if "OK" not in dev[0].request("SET blob fast_pac_bin_errors " + pac):
3130             raise Exception("Could not set blob")
3131
3132         with alloc_fail(dev[0], count, func):
3133             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
3134                            identity="user", anonymous_identity="FAST",
3135                            password="password",
3136                            ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3137                            phase1="fast_provisioning=1 fast_pac_format=binary",
3138                            pac_file="blob://fast_pac_bin_errors",
3139                            scan_freq="2412", wait_connect=False)
3140             ev = dev[0].wait_event(["EAP: Failed to initialize EAP method"],
3141                                    timeout=5)
3142             if ev is None:
3143                 raise Exception("Failure not reported")
3144             dev[0].request("REMOVE_NETWORK all")
3145             dev[0].wait_disconnected()
3146
3147     pac = "6ae4920c0000" + "0000" + 32*"00" + "0000" + "0005" + "0011223344"
3148     if "OK" not in dev[0].request("SET blob fast_pac_bin_errors " + pac):
3149         raise Exception("Could not set blob")
3150
3151     eap_connect(dev[0], hapd, "FAST", "user",
3152                 anonymous_identity="FAST", password="password",
3153                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3154                 phase1="fast_provisioning=1 fast_pac_format=binary",
3155                 pac_file="blob://fast_pac_bin_errors")
3156     dev[0].request("REMOVE_NETWORK all")
3157     dev[0].wait_disconnected()
3158
3159     pac = "6ae4920c0000" + "0000" + 32*"00" + "0000" + "0009" + "00040000" + "0007000100"
3160     tests = [ (1, "eap_fast_pac_get_a_id"),
3161               (2, "eap_fast_pac_get_a_id") ]
3162     for count, func in tests:
3163         if "OK" not in dev[0].request("SET blob fast_pac_bin_errors " + pac):
3164             raise Exception("Could not set blob")
3165         with alloc_fail(dev[0], count, func):
3166             eap_connect(dev[0], hapd, "FAST", "user",
3167                         anonymous_identity="FAST", password="password",
3168                         ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3169                         phase1="fast_provisioning=1 fast_pac_format=binary",
3170                         pac_file="blob://fast_pac_bin_errors")
3171             dev[0].request("REMOVE_NETWORK all")
3172             dev[0].wait_disconnected()
3173
3174 def test_ap_wpa2_eap_fast_text_pac_errors(dev, apdev):
3175     """EAP-FAST and text PAC errors"""
3176     check_eap_capa(dev[0], "FAST")
3177     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3178     hostapd.add_ap(apdev[0], params)
3179
3180     tests = [ (1, "eap_fast_parse_hex;eap_fast_parse_pac_key"),
3181               (1, "eap_fast_parse_hex;eap_fast_parse_pac_opaque"),
3182               (1, "eap_fast_parse_hex;eap_fast_parse_a_id"),
3183               (1, "eap_fast_parse_start"),
3184               (1, "eap_fast_save_pac") ]
3185     for count, func in tests:
3186         dev[0].request("FLUSH")
3187         if "OK" not in dev[0].request("SET blob fast_pac_text_errors "):
3188             raise Exception("Could not set blob")
3189
3190         with alloc_fail(dev[0], count, func):
3191             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
3192                            identity="user", anonymous_identity="FAST",
3193                            password="password",
3194                            ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3195                            phase1="fast_provisioning=1",
3196                            pac_file="blob://fast_pac_text_errors",
3197                            scan_freq="2412", wait_connect=False)
3198             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
3199             dev[0].request("REMOVE_NETWORK all")
3200             dev[0].wait_disconnected()
3201
3202     pac = "wpa_supplicant EAP-FAST PAC file - version 1\n"
3203     pac += "START\n"
3204     pac += "PAC-Type\n"
3205     pac += "END\n"
3206     if "OK" not in dev[0].request("SET blob fast_pac_text_errors " + pac.encode("hex")):
3207         raise Exception("Could not set blob")
3208
3209     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
3210                    identity="user", anonymous_identity="FAST",
3211                    password="password",
3212                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3213                    phase1="fast_provisioning=1",
3214                    pac_file="blob://fast_pac_text_errors",
3215                    scan_freq="2412", wait_connect=False)
3216     ev = dev[0].wait_event(["EAP: Failed to initialize EAP method"], timeout=5)
3217     if ev is None:
3218         raise Exception("Failure not reported")
3219     dev[0].request("REMOVE_NETWORK all")
3220     dev[0].wait_disconnected()
3221
3222     dev[0].request("FLUSH")
3223     if "OK" not in dev[0].request("SET blob fast_pac_text_errors "):
3224         raise Exception("Could not set blob")
3225
3226     with alloc_fail(dev[0], 1, "eap_fast_add_pac_data"):
3227         for i in range(3):
3228             params = int_eap_server_params()
3229             params['ssid'] = "test-wpa2-eap-2"
3230             params['pac_opaque_encr_key'] = "000102030405060708090a0b0c0dff%02x" % i
3231             params['eap_fast_a_id'] = "101112131415161718191a1b1c1dff%02x" % i
3232             params['eap_fast_a_id_info'] = "test server %d" % i
3233
3234             hapd2 = hostapd.add_ap(apdev[1], params)
3235
3236             dev[0].connect("test-wpa2-eap-2", key_mgmt="WPA-EAP", eap="FAST",
3237                            identity="user", anonymous_identity="FAST",
3238                            password="password",
3239                            ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3240                            phase1="fast_provisioning=1",
3241                            pac_file="blob://fast_pac_text_errors",
3242                            scan_freq="2412", wait_connect=False)
3243             dev[0].wait_connected()
3244             dev[0].request("REMOVE_NETWORK all")
3245             dev[0].wait_disconnected()
3246
3247             hapd2.disable()
3248
3249 def test_ap_wpa2_eap_fast_pac_truncate(dev, apdev):
3250     """EAP-FAST and PAC list truncation"""
3251     check_eap_capa(dev[0], "FAST")
3252     if "OK" not in dev[0].request("SET blob fast_pac_truncate "):
3253         raise Exception("Could not set blob")
3254     for i in range(5):
3255         params = int_eap_server_params()
3256         params['pac_opaque_encr_key'] = "000102030405060708090a0b0c0dff%02x" % i
3257         params['eap_fast_a_id'] = "101112131415161718191a1b1c1dff%02x" % i
3258         params['eap_fast_a_id_info'] = "test server %d" % i
3259         hapd = hostapd.add_ap(apdev[0], params)
3260
3261         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
3262                        identity="user", anonymous_identity="FAST",
3263                        password="password",
3264                        ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3265                        phase1="fast_provisioning=1 fast_max_pac_list_len=2",
3266                        pac_file="blob://fast_pac_truncate",
3267                        scan_freq="2412", wait_connect=False)
3268         dev[0].wait_connected()
3269         dev[0].request("REMOVE_NETWORK all")
3270         dev[0].wait_disconnected()
3271
3272         hapd.disable()
3273
3274 def test_ap_wpa2_eap_fast_pac_refresh(dev, apdev):
3275     """EAP-FAST and PAC refresh"""
3276     check_eap_capa(dev[0], "FAST")
3277     if "OK" not in dev[0].request("SET blob fast_pac_refresh "):
3278         raise Exception("Could not set blob")
3279     for i in range(2):
3280         params = int_eap_server_params()
3281         params['pac_opaque_encr_key'] = "000102030405060708090a0b0c0dff%02x" % i
3282         params['eap_fast_a_id'] = "101112131415161718191a1b1c1dff%02x" % i
3283         params['eap_fast_a_id_info'] = "test server %d" % i
3284         params['pac_key_refresh_time'] = "1"
3285         params['pac_key_lifetime'] = "10"
3286         hapd = hostapd.add_ap(apdev[0], params)
3287
3288         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
3289                        identity="user", anonymous_identity="FAST",
3290                        password="password",
3291                        ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3292                        phase1="fast_provisioning=1",
3293                        pac_file="blob://fast_pac_refresh",
3294                        scan_freq="2412", wait_connect=False)
3295         dev[0].wait_connected()
3296         dev[0].request("REMOVE_NETWORK all")
3297         dev[0].wait_disconnected()
3298
3299         hapd.disable()
3300
3301     for i in range(2):
3302         params = int_eap_server_params()
3303         params['pac_opaque_encr_key'] = "000102030405060708090a0b0c0dff%02x" % i
3304         params['eap_fast_a_id'] = "101112131415161718191a1b1c1dff%02x" % i
3305         params['eap_fast_a_id_info'] = "test server %d" % i
3306         params['pac_key_refresh_time'] = "10"
3307         params['pac_key_lifetime'] = "10"
3308         hapd = hostapd.add_ap(apdev[0], params)
3309
3310         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
3311                        identity="user", anonymous_identity="FAST",
3312                        password="password",
3313                        ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3314                        phase1="fast_provisioning=1",
3315                        pac_file="blob://fast_pac_refresh",
3316                        scan_freq="2412", wait_connect=False)
3317         dev[0].wait_connected()
3318         dev[0].request("REMOVE_NETWORK all")
3319         dev[0].wait_disconnected()
3320
3321         hapd.disable()
3322
3323 def test_ap_wpa2_eap_fast_pac_lifetime(dev, apdev):
3324     """EAP-FAST and PAC lifetime"""
3325     check_eap_capa(dev[0], "FAST")
3326     if "OK" not in dev[0].request("SET blob fast_pac_refresh "):
3327         raise Exception("Could not set blob")
3328
3329     i = 0
3330     params = int_eap_server_params()
3331     params['pac_opaque_encr_key'] = "000102030405060708090a0b0c0dff%02x" % i
3332     params['eap_fast_a_id'] = "101112131415161718191a1b1c1dff%02x" % i
3333     params['eap_fast_a_id_info'] = "test server %d" % i
3334     params['pac_key_refresh_time'] = "0"
3335     params['pac_key_lifetime'] = "2"
3336     hapd = hostapd.add_ap(apdev[0], params)
3337
3338     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
3339                         identity="user", anonymous_identity="FAST",
3340                         password="password",
3341                         ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3342                         phase1="fast_provisioning=2",
3343                         pac_file="blob://fast_pac_refresh",
3344                         scan_freq="2412", wait_connect=False)
3345     dev[0].wait_connected()
3346     dev[0].request("DISCONNECT")
3347     dev[0].wait_disconnected()
3348
3349     time.sleep(3)
3350     dev[0].request("PMKSA_FLUSH")
3351     dev[0].request("RECONNECT")
3352     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
3353     if ev is None:
3354         raise Exception("No EAP-Failure seen after expired PAC")
3355     dev[0].request("DISCONNECT")
3356     dev[0].wait_disconnected()
3357
3358     dev[0].select_network(id)
3359     dev[0].wait_connected()
3360     dev[0].request("REMOVE_NETWORK all")
3361     dev[0].wait_disconnected()
3362
3363 def test_ap_wpa2_eap_fast_gtc_auth_prov(dev, apdev):
3364     """WPA2-Enterprise connection using EAP-FAST/GTC and authenticated provisioning"""
3365     check_eap_capa(dev[0], "FAST")
3366     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3367     hapd = hostapd.add_ap(apdev[0], params)
3368     eap_connect(dev[0], hapd, "FAST", "user",
3369                 anonymous_identity="FAST", password="password",
3370                 ca_cert="auth_serv/ca.pem", phase2="auth=GTC",
3371                 phase1="fast_provisioning=2", pac_file="blob://fast_pac_auth")
3372     hwsim_utils.test_connectivity(dev[0], hapd)
3373     res = eap_reauth(dev[0], "FAST")
3374     if res['tls_session_reused'] != '1':
3375         raise Exception("EAP-FAST could not use PAC session ticket")
3376
3377 def test_ap_wpa2_eap_fast_gtc_identity_change(dev, apdev):
3378     """WPA2-Enterprise connection using EAP-FAST/GTC and identity changing"""
3379     check_eap_capa(dev[0], "FAST")
3380     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3381     hapd = hostapd.add_ap(apdev[0], params)
3382     id = eap_connect(dev[0], hapd, "FAST", "user",
3383                      anonymous_identity="FAST", password="password",
3384                      ca_cert="auth_serv/ca.pem", phase2="auth=GTC",
3385                      phase1="fast_provisioning=2",
3386                      pac_file="blob://fast_pac_auth")
3387     dev[0].set_network_quoted(id, "identity", "user2")
3388     dev[0].wait_disconnected()
3389     ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=15)
3390     if ev is None:
3391         raise Exception("EAP-FAST not started")
3392     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
3393     if ev is None:
3394         raise Exception("EAP failure not reported")
3395     dev[0].wait_disconnected()
3396
3397 def test_ap_wpa2_eap_fast_prf_oom(dev, apdev):
3398     """WPA2-Enterprise connection using EAP-FAST and OOM in PRF"""
3399     check_eap_capa(dev[0], "FAST")
3400     tls = dev[0].request("GET tls_library")
3401     if tls.startswith("OpenSSL"):
3402         func = "tls_connection_get_eap_fast_key"
3403         count = 2
3404     elif tls.startswith("internal"):
3405         func = "tls_connection_prf"
3406         count = 1
3407     else:
3408         raise HwsimSkip("Unsupported TLS library")
3409     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3410     hapd = hostapd.add_ap(apdev[0], params)
3411     with alloc_fail(dev[0], count, func):
3412         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
3413                        identity="user", anonymous_identity="FAST",
3414                        password="password", ca_cert="auth_serv/ca.pem",
3415                        phase2="auth=GTC",
3416                        phase1="fast_provisioning=2",
3417                        pac_file="blob://fast_pac_auth",
3418                        wait_connect=False, scan_freq="2412")
3419         ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
3420         if ev is None:
3421             raise Exception("EAP failure not reported")
3422     dev[0].request("DISCONNECT")
3423
3424 def test_ap_wpa2_eap_fast_server_oom(dev, apdev):
3425     """EAP-FAST/MSCHAPv2 and server OOM"""
3426     check_eap_capa(dev[0], "FAST")
3427
3428     params = int_eap_server_params()
3429     params['dh_file'] = 'auth_serv/dh.conf'
3430     params['pac_opaque_encr_key'] = '000102030405060708090a0b0c0d0e0f'
3431     params['eap_fast_a_id'] = '1011'
3432     params['eap_fast_a_id_info'] = 'another test server'
3433     hapd = hostapd.add_ap(apdev[0], params)
3434
3435     with alloc_fail(hapd, 1, "tls_session_ticket_ext_cb"):
3436         id = eap_connect(dev[0], hapd, "FAST", "user",
3437                          anonymous_identity="FAST", password="password",
3438                          ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3439                          phase1="fast_provisioning=1",
3440                          pac_file="blob://fast_pac",
3441                          expect_failure=True)
3442         ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
3443         if ev is None:
3444             raise Exception("No EAP failure reported")
3445         dev[0].wait_disconnected()
3446         dev[0].request("DISCONNECT")
3447
3448     dev[0].select_network(id, freq="2412")
3449
3450 def test_ap_wpa2_eap_fast_cipher_suites(dev, apdev):
3451     """EAP-FAST and different TLS cipher suites"""
3452     check_eap_capa(dev[0], "FAST")
3453     tls = dev[0].request("GET tls_library")
3454     if not tls.startswith("OpenSSL"):
3455         raise HwsimSkip("TLS library is not OpenSSL: " + tls)
3456
3457     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3458     hapd = hostapd.add_ap(apdev[0], params)
3459
3460     dev[0].request("SET blob fast_pac_ciphers ")
3461     eap_connect(dev[0], hapd, "FAST", "user",
3462                 anonymous_identity="FAST", password="password",
3463                 ca_cert="auth_serv/ca.pem", phase2="auth=GTC",
3464                 phase1="fast_provisioning=2",
3465                 pac_file="blob://fast_pac_ciphers")
3466     res = dev[0].get_status_field('EAP TLS cipher')
3467     dev[0].request("REMOVE_NETWORK all")
3468     dev[0].wait_disconnected()
3469     if res != "DHE-RSA-AES256-SHA":
3470         raise Exception("Unexpected cipher suite for provisioning: " + res)
3471
3472     tests = [ "DHE-RSA-AES128-SHA",
3473               "RC4-SHA",
3474               "AES128-SHA",
3475               "AES256-SHA",
3476               "DHE-RSA-AES256-SHA" ]
3477     for cipher in tests:
3478         dev[0].dump_monitor()
3479         logger.info("Testing " + cipher)
3480         try:
3481             eap_connect(dev[0], hapd, "FAST", "user",
3482                         openssl_ciphers=cipher,
3483                         anonymous_identity="FAST", password="password",
3484                         ca_cert="auth_serv/ca.pem", phase2="auth=GTC",
3485                         pac_file="blob://fast_pac_ciphers")
3486         except Exception, e:
3487             if "Could not select EAP method" in str(e) and cipher == "RC4-SHA":
3488                 tls = dev[0].request("GET tls_library")
3489                 if "run=OpenSSL 1.1" in tls:
3490                     logger.info("Allow failure due to missing TLS library support")
3491                     dev[0].request("REMOVE_NETWORK all")
3492                     dev[0].wait_disconnected()
3493                     continue
3494             raise
3495         res = dev[0].get_status_field('EAP TLS cipher')
3496         dev[0].request("REMOVE_NETWORK all")
3497         dev[0].wait_disconnected()
3498         if res != cipher:
3499             raise Exception("Unexpected TLS cipher info (configured %s): %s" % (cipher, res))
3500
3501 def test_ap_wpa2_eap_tls_ocsp(dev, apdev):
3502     """WPA2-Enterprise connection using EAP-TLS and verifying OCSP"""
3503     check_ocsp_support(dev[0])
3504     check_pkcs12_support(dev[0])
3505     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3506     hapd = hostapd.add_ap(apdev[0], params)
3507     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
3508                 private_key="auth_serv/user.pkcs12",
3509                 private_key_passwd="whatever", ocsp=2)
3510
3511 def test_ap_wpa2_eap_tls_ocsp_multi(dev, apdev):
3512     """WPA2-Enterprise connection using EAP-TLS and verifying OCSP-multi"""
3513     check_ocsp_multi_support(dev[0])
3514     check_pkcs12_support(dev[0])
3515
3516     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3517     hapd = hostapd.add_ap(apdev[0], params)
3518     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
3519                 private_key="auth_serv/user.pkcs12",
3520                 private_key_passwd="whatever", ocsp=2)
3521
3522 def int_eap_server_params():
3523     params = { "ssid": "test-wpa2-eap", "wpa": "2", "wpa_key_mgmt": "WPA-EAP",
3524                "rsn_pairwise": "CCMP", "ieee8021x": "1",
3525                "eap_server": "1", "eap_user_file": "auth_serv/eap_user.conf",
3526                "ca_cert": "auth_serv/ca.pem",
3527                "server_cert": "auth_serv/server.pem",
3528                "private_key": "auth_serv/server.key",
3529                "dh_file": "auth_serv/dh.conf" }
3530     return params
3531
3532 def test_ap_wpa2_eap_tls_ocsp_key_id(dev, apdev, params):
3533     """EAP-TLS and OCSP certificate signed OCSP response using key ID"""
3534     check_ocsp_support(dev[0])
3535     ocsp = os.path.join(params['logdir'], "ocsp-server-cache-key-id.der")
3536     if not os.path.exists(ocsp):
3537         raise HwsimSkip("No OCSP response available")
3538     params = int_eap_server_params()
3539     params["ocsp_stapling_response"] = ocsp
3540     hostapd.add_ap(apdev[0], params)
3541     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3542                    identity="tls user", ca_cert="auth_serv/ca.pem",
3543                    private_key="auth_serv/user.pkcs12",
3544                    private_key_passwd="whatever", ocsp=2,
3545                    scan_freq="2412")
3546
3547 def test_ap_wpa2_eap_tls_ocsp_ca_signed_good(dev, apdev, params):
3548     """EAP-TLS and CA signed OCSP response (good)"""
3549     check_ocsp_support(dev[0])
3550     ocsp = os.path.join(params['logdir'], "ocsp-resp-ca-signed.der")
3551     if not os.path.exists(ocsp):
3552         raise HwsimSkip("No OCSP response available")
3553     params = int_eap_server_params()
3554     params["ocsp_stapling_response"] = ocsp
3555     hostapd.add_ap(apdev[0], params)
3556     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3557                    identity="tls user", ca_cert="auth_serv/ca.pem",
3558                    private_key="auth_serv/user.pkcs12",
3559                    private_key_passwd="whatever", ocsp=2,
3560                    scan_freq="2412")
3561
3562 def test_ap_wpa2_eap_tls_ocsp_ca_signed_revoked(dev, apdev, params):
3563     """EAP-TLS and CA signed OCSP response (revoked)"""
3564     check_ocsp_support(dev[0])
3565     ocsp = os.path.join(params['logdir'], "ocsp-resp-ca-signed-revoked.der")
3566     if not os.path.exists(ocsp):
3567         raise HwsimSkip("No OCSP response available")
3568     params = int_eap_server_params()
3569     params["ocsp_stapling_response"] = ocsp
3570     hostapd.add_ap(apdev[0], params)
3571     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3572                    identity="tls user", ca_cert="auth_serv/ca.pem",
3573                    private_key="auth_serv/user.pkcs12",
3574                    private_key_passwd="whatever", ocsp=2,
3575                    wait_connect=False, scan_freq="2412")
3576     count = 0
3577     while True:
3578         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
3579         if ev is None:
3580             raise Exception("Timeout on EAP status")
3581         if 'bad certificate status response' in ev:
3582             break
3583         if 'certificate revoked' in ev:
3584             break
3585         count = count + 1
3586         if count > 10:
3587             raise Exception("Unexpected number of EAP status messages")
3588
3589     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3590     if ev is None:
3591         raise Exception("Timeout on EAP failure report")
3592
3593 def test_ap_wpa2_eap_tls_ocsp_ca_signed_unknown(dev, apdev, params):
3594     """EAP-TLS and CA signed OCSP response (unknown)"""
3595     check_ocsp_support(dev[0])
3596     ocsp = os.path.join(params['logdir'], "ocsp-resp-ca-signed-unknown.der")
3597     if not os.path.exists(ocsp):
3598         raise HwsimSkip("No OCSP response available")
3599     params = int_eap_server_params()
3600     params["ocsp_stapling_response"] = ocsp
3601     hostapd.add_ap(apdev[0], params)
3602     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3603                    identity="tls user", ca_cert="auth_serv/ca.pem",
3604                    private_key="auth_serv/user.pkcs12",
3605                    private_key_passwd="whatever", ocsp=2,
3606                    wait_connect=False, scan_freq="2412")
3607     count = 0
3608     while True:
3609         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
3610         if ev is None:
3611             raise Exception("Timeout on EAP status")
3612         if 'bad certificate status response' in ev:
3613             break
3614         count = count + 1
3615         if count > 10:
3616             raise Exception("Unexpected number of EAP status messages")
3617
3618     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3619     if ev is None:
3620         raise Exception("Timeout on EAP failure report")
3621
3622 def test_ap_wpa2_eap_tls_ocsp_server_signed(dev, apdev, params):
3623     """EAP-TLS and server signed OCSP response"""
3624     check_ocsp_support(dev[0])
3625     ocsp = os.path.join(params['logdir'], "ocsp-resp-server-signed.der")
3626     if not os.path.exists(ocsp):
3627         raise HwsimSkip("No OCSP response available")
3628     params = int_eap_server_params()
3629     params["ocsp_stapling_response"] = ocsp
3630     hostapd.add_ap(apdev[0], params)
3631     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3632                    identity="tls user", ca_cert="auth_serv/ca.pem",
3633                    private_key="auth_serv/user.pkcs12",
3634                    private_key_passwd="whatever", ocsp=2,
3635                    wait_connect=False, scan_freq="2412")
3636     count = 0
3637     while True:
3638         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
3639         if ev is None:
3640             raise Exception("Timeout on EAP status")
3641         if 'bad certificate status response' in ev:
3642             break
3643         count = count + 1
3644         if count > 10:
3645             raise Exception("Unexpected number of EAP status messages")
3646
3647     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3648     if ev is None:
3649         raise Exception("Timeout on EAP failure report")
3650
3651 def test_ap_wpa2_eap_tls_ocsp_invalid_data(dev, apdev):
3652     """WPA2-Enterprise connection using EAP-TLS and invalid OCSP data"""
3653     check_ocsp_support(dev[0])
3654     params = int_eap_server_params()
3655     params["ocsp_stapling_response"] = "auth_serv/ocsp-req.der"
3656     hostapd.add_ap(apdev[0], params)
3657     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3658                    identity="tls user", ca_cert="auth_serv/ca.pem",
3659                    private_key="auth_serv/user.pkcs12",
3660                    private_key_passwd="whatever", ocsp=2,
3661                    wait_connect=False, scan_freq="2412")
3662     count = 0
3663     while True:
3664         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
3665         if ev is None:
3666             raise Exception("Timeout on EAP status")
3667         if 'bad certificate status response' in ev:
3668             break
3669         count = count + 1
3670         if count > 10:
3671             raise Exception("Unexpected number of EAP status messages")
3672
3673     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3674     if ev is None:
3675         raise Exception("Timeout on EAP failure report")
3676
3677 def test_ap_wpa2_eap_tls_ocsp_invalid(dev, apdev):
3678     """WPA2-Enterprise connection using EAP-TLS and invalid OCSP response"""
3679     check_ocsp_support(dev[0])
3680     params = int_eap_server_params()
3681     params["ocsp_stapling_response"] = "auth_serv/ocsp-server-cache.der-invalid"
3682     hostapd.add_ap(apdev[0], params)
3683     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3684                    identity="tls user", ca_cert="auth_serv/ca.pem",
3685                    private_key="auth_serv/user.pkcs12",
3686                    private_key_passwd="whatever", ocsp=2,
3687                    wait_connect=False, scan_freq="2412")
3688     count = 0
3689     while True:
3690         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
3691         if ev is None:
3692             raise Exception("Timeout on EAP status")
3693         if 'bad certificate status response' in ev:
3694             break
3695         count = count + 1
3696         if count > 10:
3697             raise Exception("Unexpected number of EAP status messages")
3698
3699     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3700     if ev is None:
3701         raise Exception("Timeout on EAP failure report")
3702
3703 def test_ap_wpa2_eap_tls_ocsp_unknown_sign(dev, apdev):
3704     """WPA2-Enterprise connection using EAP-TLS and unknown OCSP signer"""
3705     check_ocsp_support(dev[0])
3706     params = int_eap_server_params()
3707     params["ocsp_stapling_response"] = "auth_serv/ocsp-server-cache.der-unknown-sign"
3708     hostapd.add_ap(apdev[0], params)
3709     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3710                    identity="tls user", ca_cert="auth_serv/ca.pem",
3711                    private_key="auth_serv/user.pkcs12",
3712                    private_key_passwd="whatever", ocsp=2,
3713                    wait_connect=False, scan_freq="2412")
3714     count = 0
3715     while True:
3716         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
3717         if ev is None:
3718             raise Exception("Timeout on EAP status")
3719         if 'bad certificate status response' in ev:
3720             break
3721         count = count + 1
3722         if count > 10:
3723             raise Exception("Unexpected number of EAP status messages")
3724
3725     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3726     if ev is None:
3727         raise Exception("Timeout on EAP failure report")
3728
3729 def test_ap_wpa2_eap_ttls_ocsp_revoked(dev, apdev, params):
3730     """WPA2-Enterprise connection using EAP-TTLS and OCSP status revoked"""
3731     check_ocsp_support(dev[0])
3732     ocsp = os.path.join(params['logdir'], "ocsp-server-cache-revoked.der")
3733     if not os.path.exists(ocsp):
3734         raise HwsimSkip("No OCSP response available")
3735     params = int_eap_server_params()
3736     params["ocsp_stapling_response"] = ocsp
3737     hostapd.add_ap(apdev[0], params)
3738     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3739                    identity="pap user", ca_cert="auth_serv/ca.pem",
3740                    anonymous_identity="ttls", password="password",
3741                    phase2="auth=PAP", ocsp=2,
3742                    wait_connect=False, scan_freq="2412")
3743     count = 0
3744     while True:
3745         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
3746         if ev is None:
3747             raise Exception("Timeout on EAP status")
3748         if 'bad certificate status response' in ev:
3749             break
3750         if 'certificate revoked' in ev:
3751             break
3752         count = count + 1
3753         if count > 10:
3754             raise Exception("Unexpected number of EAP status messages")
3755
3756     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3757     if ev is None:
3758         raise Exception("Timeout on EAP failure report")
3759
3760 def test_ap_wpa2_eap_ttls_ocsp_unknown(dev, apdev, params):
3761     """WPA2-Enterprise connection using EAP-TTLS and OCSP status revoked"""
3762     check_ocsp_support(dev[0])
3763     ocsp = os.path.join(params['logdir'], "ocsp-server-cache-unknown.der")
3764     if not os.path.exists(ocsp):
3765         raise HwsimSkip("No OCSP response available")
3766     params = int_eap_server_params()
3767     params["ocsp_stapling_response"] = ocsp
3768     hostapd.add_ap(apdev[0], params)
3769     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3770                    identity="pap user", ca_cert="auth_serv/ca.pem",
3771                    anonymous_identity="ttls", password="password",
3772                    phase2="auth=PAP", ocsp=2,
3773                    wait_connect=False, scan_freq="2412")
3774     count = 0
3775     while True:
3776         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
3777         if ev is None:
3778             raise Exception("Timeout on EAP status")
3779         if 'bad certificate status response' in ev:
3780             break
3781         count = count + 1
3782         if count > 10:
3783             raise Exception("Unexpected number of EAP status messages")
3784
3785     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3786     if ev is None:
3787         raise Exception("Timeout on EAP failure report")
3788
3789 def test_ap_wpa2_eap_ttls_optional_ocsp_unknown(dev, apdev, params):
3790     """WPA2-Enterprise connection using EAP-TTLS and OCSP status revoked"""
3791     ocsp = os.path.join(params['logdir'], "ocsp-server-cache-unknown.der")
3792     if not os.path.exists(ocsp):
3793         raise HwsimSkip("No OCSP response available")
3794     params = int_eap_server_params()
3795     params["ocsp_stapling_response"] = ocsp
3796     hostapd.add_ap(apdev[0], params)
3797     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3798                    identity="pap user", ca_cert="auth_serv/ca.pem",
3799                    anonymous_identity="ttls", password="password",
3800                    phase2="auth=PAP", ocsp=1, scan_freq="2412")
3801
3802 def test_ap_wpa2_eap_tls_intermediate_ca(dev, apdev, params):
3803     """EAP-TLS with intermediate server/user CA"""
3804     params = int_eap_server_params()
3805     params["ca_cert"] = "auth_serv/iCA-server/ca-and-root.pem"
3806     params["server_cert"] = "auth_serv/iCA-server/server.pem"
3807     params["private_key"] = "auth_serv/iCA-server/server.key"
3808     hostapd.add_ap(apdev[0], params)
3809     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3810                    identity="tls user",
3811                    ca_cert="auth_serv/iCA-user/ca-and-root.pem",
3812                    client_cert="auth_serv/iCA-user/user.pem",
3813                    private_key="auth_serv/iCA-user/user.key",
3814                    scan_freq="2412")
3815
3816 def root_ocsp(cert):
3817     ca = "auth_serv/ca.pem"
3818
3819     fd2, fn2 = tempfile.mkstemp()
3820     os.close(fd2)
3821
3822     arg = [ "openssl", "ocsp", "-reqout", fn2, "-issuer", ca, "-cert", cert,
3823             "-no_nonce", "-sha256", "-text" ]
3824     cmd = subprocess.Popen(arg, stdout=subprocess.PIPE,
3825                            stderr=subprocess.PIPE)
3826     res = cmd.stdout.read() + "\n" + cmd.stderr.read()
3827     cmd.stdout.close()
3828     cmd.stderr.close()
3829     logger.info("OCSP request:\n" + res)
3830
3831     fd, fn = tempfile.mkstemp()
3832     os.close(fd)
3833     arg = [ "openssl", "ocsp", "-index", "auth_serv/rootCA/index.txt",
3834             "-rsigner", ca, "-rkey", "auth_serv/ca-key.pem",
3835             "-CA", ca, "-issuer", ca, "-verify_other", ca, "-trust_other",
3836             "-ndays", "7", "-reqin", fn2, "-resp_no_certs", "-respout", fn,
3837             "-text" ]
3838     cmd = subprocess.Popen(arg, stdout=subprocess.PIPE,
3839                            stderr=subprocess.PIPE)
3840     res = cmd.stdout.read() + "\n" + cmd.stderr.read()
3841     cmd.stdout.close()
3842     cmd.stderr.close()
3843     logger.info("OCSP response:\n" + res)
3844     os.unlink(fn2)
3845     return fn
3846
3847 def ica_ocsp(cert):
3848     prefix = "auth_serv/iCA-server/"
3849     ca = prefix + "cacert.pem"
3850     cert = prefix + cert
3851
3852     fd2, fn2 = tempfile.mkstemp()
3853     os.close(fd2)
3854
3855     arg = [ "openssl", "ocsp", "-reqout", fn2, "-issuer", ca, "-cert", cert,
3856             "-no_nonce", "-sha256", "-text" ]
3857     cmd = subprocess.Popen(arg, stdout=subprocess.PIPE,
3858                            stderr=subprocess.PIPE)
3859     res = cmd.stdout.read() + "\n" + cmd.stderr.read()
3860     cmd.stdout.close()
3861     cmd.stderr.close()
3862     logger.info("OCSP request:\n" + res)
3863
3864     fd, fn = tempfile.mkstemp()
3865     os.close(fd)
3866     arg = [ "openssl", "ocsp", "-index", prefix + "index.txt",
3867             "-rsigner", ca, "-rkey", prefix + "private/cakey.pem",
3868             "-CA", ca, "-issuer", ca, "-verify_other", ca, "-trust_other",
3869             "-ndays", "7", "-reqin", fn2, "-resp_no_certs", "-respout", fn,
3870             "-text" ]
3871     cmd = subprocess.Popen(arg, stdout=subprocess.PIPE,
3872                            stderr=subprocess.PIPE)
3873     res = cmd.stdout.read() + "\n" + cmd.stderr.read()
3874     cmd.stdout.close()
3875     cmd.stderr.close()
3876     logger.info("OCSP response:\n" + res)
3877     os.unlink(fn2)
3878     return fn
3879
3880 def test_ap_wpa2_eap_tls_intermediate_ca_ocsp(dev, apdev, params):
3881     """EAP-TLS with intermediate server/user CA and OCSP on server certificate"""
3882     params = int_eap_server_params()
3883     params["ca_cert"] = "auth_serv/iCA-server/ca-and-root.pem"
3884     params["server_cert"] = "auth_serv/iCA-server/server.pem"
3885     params["private_key"] = "auth_serv/iCA-server/server.key"
3886     fn = ica_ocsp("server.pem")
3887     params["ocsp_stapling_response"] = fn
3888     try:
3889         hostapd.add_ap(apdev[0], params)
3890         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3891                        identity="tls user",
3892                        ca_cert="auth_serv/iCA-user/ca-and-root.pem",
3893                        client_cert="auth_serv/iCA-user/user.pem",
3894                        private_key="auth_serv/iCA-user/user.key",
3895                        scan_freq="2412", ocsp=2)
3896     finally:
3897         os.unlink(fn)
3898
3899 def test_ap_wpa2_eap_tls_intermediate_ca_ocsp_revoked(dev, apdev, params):
3900     """EAP-TLS with intermediate server/user CA and OCSP on revoked server certificate"""
3901     params = int_eap_server_params()
3902     params["ca_cert"] = "auth_serv/iCA-server/ca-and-root.pem"
3903     params["server_cert"] = "auth_serv/iCA-server/server-revoked.pem"
3904     params["private_key"] = "auth_serv/iCA-server/server-revoked.key"
3905     fn = ica_ocsp("server-revoked.pem")
3906     params["ocsp_stapling_response"] = fn
3907     try:
3908         hostapd.add_ap(apdev[0], params)
3909         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3910                        identity="tls user",
3911                        ca_cert="auth_serv/iCA-user/ca-and-root.pem",
3912                        client_cert="auth_serv/iCA-user/user.pem",
3913                        private_key="auth_serv/iCA-user/user.key",
3914                        scan_freq="2412", ocsp=1, wait_connect=False)
3915         count = 0
3916         while True:
3917             ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS",
3918                                     "CTRL-EVENT-EAP-SUCCESS"])
3919             if ev is None:
3920                 raise Exception("Timeout on EAP status")
3921             if "CTRL-EVENT-EAP-SUCCESS" in ev:
3922                 raise Exception("Unexpected EAP-Success")
3923             if 'bad certificate status response' in ev:
3924                 break
3925             if 'certificate revoked' in ev:
3926                 break
3927             count = count + 1
3928             if count > 10:
3929                 raise Exception("Unexpected number of EAP status messages")
3930
3931         ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3932         if ev is None:
3933             raise Exception("Timeout on EAP failure report")
3934         dev[0].request("REMOVE_NETWORK all")
3935         dev[0].wait_disconnected()
3936     finally:
3937         os.unlink(fn)
3938
3939 def test_ap_wpa2_eap_tls_intermediate_ca_ocsp_multi_missing_resp(dev, apdev, params):
3940     """EAP-TLS with intermediate server/user CA and OCSP multi missing response"""
3941     check_ocsp_support(dev[0])
3942     check_ocsp_multi_support(dev[0])
3943
3944     params = int_eap_server_params()
3945     params["ca_cert"] = "auth_serv/iCA-server/ca-and-root.pem"
3946     params["server_cert"] = "auth_serv/iCA-server/server.pem"
3947     params["private_key"] = "auth_serv/iCA-server/server.key"
3948     fn = ica_ocsp("server.pem")
3949     params["ocsp_stapling_response"] = fn
3950     try:
3951         hostapd.add_ap(apdev[0], params)
3952         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
3953                        identity="tls user",
3954                        ca_cert="auth_serv/iCA-user/ca-and-root.pem",
3955                        client_cert="auth_serv/iCA-user/user.pem",
3956                        private_key="auth_serv/iCA-user/user.key",
3957                        scan_freq="2412", ocsp=3, wait_connect=False)
3958         count = 0
3959         while True:
3960             ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS",
3961                                     "CTRL-EVENT-EAP-SUCCESS"])
3962             if ev is None:
3963                 raise Exception("Timeout on EAP status")
3964             if "CTRL-EVENT-EAP-SUCCESS" in ev:
3965                 raise Exception("Unexpected EAP-Success")
3966             if 'bad certificate status response' in ev:
3967                 break
3968             if 'certificate revoked' in ev:
3969                 break
3970             count = count + 1
3971             if count > 10:
3972                 raise Exception("Unexpected number of EAP status messages")
3973
3974         ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3975         if ev is None:
3976             raise Exception("Timeout on EAP failure report")
3977         dev[0].request("REMOVE_NETWORK all")
3978         dev[0].wait_disconnected()
3979     finally:
3980         os.unlink(fn)
3981
3982 def test_ap_wpa2_eap_tls_intermediate_ca_ocsp_multi(dev, apdev, params):
3983     """EAP-TLS with intermediate server/user CA and OCSP multi OK"""
3984     check_ocsp_support(dev[0])
3985     check_ocsp_multi_support(dev[0])
3986
3987     params = int_eap_server_params()
3988     params["ca_cert"] = "auth_serv/iCA-server/ca-and-root.pem"
3989     params["server_cert"] = "auth_serv/iCA-server/server.pem"
3990     params["private_key"] = "auth_serv/iCA-server/server.key"
3991     fn = ica_ocsp("server.pem")
3992     fn2 = root_ocsp("auth_serv/iCA-server/cacert.pem")
3993     params["ocsp_stapling_response"] = fn
3994
3995     with open(fn, "r") as f:
3996         resp_server = f.read()
3997     with open(fn2, "r") as f:
3998         resp_ica = f.read()
3999
4000     fd3, fn3 = tempfile.mkstemp()
4001     try:
4002         f = os.fdopen(fd3, 'w')
4003         f.write(struct.pack(">L", len(resp_server))[1:4])
4004         f.write(resp_server)
4005         f.write(struct.pack(">L", len(resp_ica))[1:4])
4006         f.write(resp_ica)
4007         f.close()
4008
4009         params["ocsp_stapling_response_multi"] = fn3
4010
4011         hostapd.add_ap(apdev[0], params)
4012         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4013                        identity="tls user",
4014                        ca_cert="auth_serv/iCA-user/ca-and-root.pem",
4015                        client_cert="auth_serv/iCA-user/user.pem",
4016                        private_key="auth_serv/iCA-user/user.key",
4017                        scan_freq="2412", ocsp=3)
4018         dev[0].request("REMOVE_NETWORK all")
4019         dev[0].wait_disconnected()
4020     finally:
4021         os.unlink(fn)
4022         os.unlink(fn2)
4023         os.unlink(fn3)
4024
4025 def test_ap_wpa2_eap_tls_ocsp_multi_revoked(dev, apdev, params):
4026     """EAP-TLS and CA signed OCSP multi response (revoked)"""
4027     check_ocsp_support(dev[0])
4028     check_ocsp_multi_support(dev[0])
4029
4030     ocsp_revoked = os.path.join(params['logdir'],
4031                                 "ocsp-resp-ca-signed-revoked.der")
4032     if not os.path.exists(ocsp_revoked):
4033         raise HwsimSkip("No OCSP response (revoked) available")
4034     ocsp_unknown = os.path.join(params['logdir'],
4035                                 "ocsp-resp-ca-signed-unknown.der")
4036     if not os.path.exists(ocsp_unknown):
4037         raise HwsimSkip("No OCSP response(unknown) available")
4038
4039     with open(ocsp_revoked, "r") as f:
4040         resp_revoked = f.read()
4041     with open(ocsp_unknown, "r") as f:
4042         resp_unknown = f.read()
4043
4044     fd, fn = tempfile.mkstemp()
4045     try:
4046         # This is not really a valid order of the OCSPResponse items in the
4047         # list, but this works for now to verify parsing and processing of
4048         # multiple responses.
4049         f = os.fdopen(fd, 'w')
4050         f.write(struct.pack(">L", len(resp_unknown))[1:4])
4051         f.write(resp_unknown)
4052         f.write(struct.pack(">L", len(resp_revoked))[1:4])
4053         f.write(resp_revoked)
4054         f.write(struct.pack(">L", 0)[1:4])
4055         f.write(struct.pack(">L", len(resp_unknown))[1:4])
4056         f.write(resp_unknown)
4057         f.close()
4058
4059         params = int_eap_server_params()
4060         params["ocsp_stapling_response_multi"] = fn
4061         hostapd.add_ap(apdev[0], params)
4062         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4063                        identity="tls user", ca_cert="auth_serv/ca.pem",
4064                        private_key="auth_serv/user.pkcs12",
4065                        private_key_passwd="whatever", ocsp=1,
4066                        wait_connect=False, scan_freq="2412")
4067         count = 0
4068         while True:
4069             ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS",
4070                                     "CTRL-EVENT-EAP-SUCCESS"])
4071             if ev is None:
4072                 raise Exception("Timeout on EAP status")
4073             if "CTRL-EVENT-EAP-SUCCESS" in ev:
4074                 raise Exception("Unexpected EAP-Success")
4075             if 'bad certificate status response' in ev:
4076                 break
4077             if 'certificate revoked' in ev:
4078                 break
4079             count = count + 1
4080             if count > 10:
4081                 raise Exception("Unexpected number of EAP status messages")
4082     finally:
4083         os.unlink(fn)
4084
4085 def test_ap_wpa2_eap_tls_domain_suffix_match_cn_full(dev, apdev):
4086     """WPA2-Enterprise using EAP-TLS and domain suffix match (CN)"""
4087     check_domain_match_full(dev[0])
4088     params = int_eap_server_params()
4089     params["server_cert"] = "auth_serv/server-no-dnsname.pem"
4090     params["private_key"] = "auth_serv/server-no-dnsname.key"
4091     hostapd.add_ap(apdev[0], params)
4092     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4093                    identity="tls user", ca_cert="auth_serv/ca.pem",
4094                    private_key="auth_serv/user.pkcs12",
4095                    private_key_passwd="whatever",
4096                    domain_suffix_match="server3.w1.fi",
4097                    scan_freq="2412")
4098
4099 def test_ap_wpa2_eap_tls_domain_match_cn(dev, apdev):
4100     """WPA2-Enterprise using EAP-TLS and domainmatch (CN)"""
4101     check_domain_match(dev[0])
4102     params = int_eap_server_params()
4103     params["server_cert"] = "auth_serv/server-no-dnsname.pem"
4104     params["private_key"] = "auth_serv/server-no-dnsname.key"
4105     hostapd.add_ap(apdev[0], params)
4106     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4107                    identity="tls user", ca_cert="auth_serv/ca.pem",
4108                    private_key="auth_serv/user.pkcs12",
4109                    private_key_passwd="whatever",
4110                    domain_match="server3.w1.fi",
4111                    scan_freq="2412")
4112
4113 def test_ap_wpa2_eap_tls_domain_suffix_match_cn(dev, apdev):
4114     """WPA2-Enterprise using EAP-TLS and domain suffix match (CN)"""
4115     check_domain_match_full(dev[0])
4116     params = int_eap_server_params()
4117     params["server_cert"] = "auth_serv/server-no-dnsname.pem"
4118     params["private_key"] = "auth_serv/server-no-dnsname.key"
4119     hostapd.add_ap(apdev[0], params)
4120     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4121                    identity="tls user", ca_cert="auth_serv/ca.pem",
4122                    private_key="auth_serv/user.pkcs12",
4123                    private_key_passwd="whatever",
4124                    domain_suffix_match="w1.fi",
4125                    scan_freq="2412")
4126
4127 def test_ap_wpa2_eap_tls_domain_suffix_mismatch_cn(dev, apdev):
4128     """WPA2-Enterprise using EAP-TLS and domain suffix mismatch (CN)"""
4129     check_domain_suffix_match(dev[0])
4130     params = int_eap_server_params()
4131     params["server_cert"] = "auth_serv/server-no-dnsname.pem"
4132     params["private_key"] = "auth_serv/server-no-dnsname.key"
4133     hostapd.add_ap(apdev[0], params)
4134     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4135                    identity="tls user", ca_cert="auth_serv/ca.pem",
4136                    private_key="auth_serv/user.pkcs12",
4137                    private_key_passwd="whatever",
4138                    domain_suffix_match="example.com",
4139                    wait_connect=False,
4140                    scan_freq="2412")
4141     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4142                    identity="tls user", ca_cert="auth_serv/ca.pem",
4143                    private_key="auth_serv/user.pkcs12",
4144                    private_key_passwd="whatever",
4145                    domain_suffix_match="erver3.w1.fi",
4146                    wait_connect=False,
4147                    scan_freq="2412")
4148     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
4149     if ev is None:
4150         raise Exception("Timeout on EAP failure report")
4151     ev = dev[1].wait_event(["CTRL-EVENT-EAP-FAILURE"])
4152     if ev is None:
4153         raise Exception("Timeout on EAP failure report (2)")
4154
4155 def test_ap_wpa2_eap_tls_domain_mismatch_cn(dev, apdev):
4156     """WPA2-Enterprise using EAP-TLS and domain mismatch (CN)"""
4157     check_domain_match(dev[0])
4158     params = int_eap_server_params()
4159     params["server_cert"] = "auth_serv/server-no-dnsname.pem"
4160     params["private_key"] = "auth_serv/server-no-dnsname.key"
4161     hostapd.add_ap(apdev[0], params)
4162     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4163                    identity="tls user", ca_cert="auth_serv/ca.pem",
4164                    private_key="auth_serv/user.pkcs12",
4165                    private_key_passwd="whatever",
4166                    domain_match="example.com",
4167                    wait_connect=False,
4168                    scan_freq="2412")
4169     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4170                    identity="tls user", ca_cert="auth_serv/ca.pem",
4171                    private_key="auth_serv/user.pkcs12",
4172                    private_key_passwd="whatever",
4173                    domain_match="w1.fi",
4174                    wait_connect=False,
4175                    scan_freq="2412")
4176     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
4177     if ev is None:
4178         raise Exception("Timeout on EAP failure report")
4179     ev = dev[1].wait_event(["CTRL-EVENT-EAP-FAILURE"])
4180     if ev is None:
4181         raise Exception("Timeout on EAP failure report (2)")
4182
4183 def test_ap_wpa2_eap_ttls_expired_cert(dev, apdev):
4184     """WPA2-Enterprise using EAP-TTLS and expired certificate"""
4185     skip_with_fips(dev[0])
4186     params = int_eap_server_params()
4187     params["server_cert"] = "auth_serv/server-expired.pem"
4188     params["private_key"] = "auth_serv/server-expired.key"
4189     hostapd.add_ap(apdev[0], params)
4190     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
4191                    identity="mschap user", password="password",
4192                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
4193                    wait_connect=False,
4194                    scan_freq="2412")
4195     ev = dev[0].wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR"])
4196     if ev is None:
4197         raise Exception("Timeout on EAP certificate error report")
4198     if "reason=4" not in ev or "certificate has expired" not in ev:
4199         raise Exception("Unexpected failure reason: " + ev)
4200     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
4201     if ev is None:
4202         raise Exception("Timeout on EAP failure report")
4203
4204 def test_ap_wpa2_eap_ttls_ignore_expired_cert(dev, apdev):
4205     """WPA2-Enterprise using EAP-TTLS and ignore certificate expiration"""
4206     skip_with_fips(dev[0])
4207     params = int_eap_server_params()
4208     params["server_cert"] = "auth_serv/server-expired.pem"
4209     params["private_key"] = "auth_serv/server-expired.key"
4210     hostapd.add_ap(apdev[0], params)
4211     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
4212                    identity="mschap user", password="password",
4213                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
4214                    phase1="tls_disable_time_checks=1",
4215                    scan_freq="2412")
4216
4217 def test_ap_wpa2_eap_ttls_long_duration(dev, apdev):
4218     """WPA2-Enterprise using EAP-TTLS and long certificate duration"""
4219     skip_with_fips(dev[0])
4220     params = int_eap_server_params()
4221     params["server_cert"] = "auth_serv/server-long-duration.pem"
4222     params["private_key"] = "auth_serv/server-long-duration.key"
4223     hostapd.add_ap(apdev[0], params)
4224     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
4225                    identity="mschap user", password="password",
4226                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
4227                    scan_freq="2412")
4228
4229 def test_ap_wpa2_eap_ttls_server_cert_eku_client(dev, apdev):
4230     """WPA2-Enterprise using EAP-TTLS and server cert with client EKU"""
4231     skip_with_fips(dev[0])
4232     params = int_eap_server_params()
4233     params["server_cert"] = "auth_serv/server-eku-client.pem"
4234     params["private_key"] = "auth_serv/server-eku-client.key"
4235     hostapd.add_ap(apdev[0], params)
4236     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
4237                    identity="mschap user", password="password",
4238                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
4239                    wait_connect=False,
4240                    scan_freq="2412")
4241     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
4242     if ev is None:
4243         raise Exception("Timeout on EAP failure report")
4244
4245 def test_ap_wpa2_eap_ttls_server_cert_eku_client_server(dev, apdev):
4246     """WPA2-Enterprise using EAP-TTLS and server cert with client and server EKU"""
4247     skip_with_fips(dev[0])
4248     params = int_eap_server_params()
4249     params["server_cert"] = "auth_serv/server-eku-client-server.pem"
4250     params["private_key"] = "auth_serv/server-eku-client-server.key"
4251     hostapd.add_ap(apdev[0], params)
4252     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
4253                    identity="mschap user", password="password",
4254                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
4255                    scan_freq="2412")
4256
4257 def test_ap_wpa2_eap_ttls_server_pkcs12(dev, apdev):
4258     """WPA2-Enterprise using EAP-TTLS and server PKCS#12 file"""
4259     skip_with_fips(dev[0])
4260     params = int_eap_server_params()
4261     del params["server_cert"]
4262     params["private_key"] = "auth_serv/server.pkcs12"
4263     hostapd.add_ap(apdev[0], params)
4264     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
4265                    identity="mschap user", password="password",
4266                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
4267                    scan_freq="2412")
4268
4269 def test_ap_wpa2_eap_ttls_server_pkcs12_extra(dev, apdev):
4270     """EAP-TTLS and server PKCS#12 file with extra certs"""
4271     skip_with_fips(dev[0])
4272     params = int_eap_server_params()
4273     del params["server_cert"]
4274     params["private_key"] = "auth_serv/server-extra.pkcs12"
4275     params["private_key_passwd"] = "whatever"
4276     hostapd.add_ap(apdev[0], params)
4277     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
4278                    identity="mschap user", password="password",
4279                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
4280                    scan_freq="2412")
4281
4282 def test_ap_wpa2_eap_ttls_dh_params(dev, apdev):
4283     """WPA2-Enterprise connection using EAP-TTLS/CHAP and setting DH params"""
4284     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4285     hapd = hostapd.add_ap(apdev[0], params)
4286     eap_connect(dev[0], hapd, "TTLS", "pap user",
4287                 anonymous_identity="ttls", password="password",
4288                 ca_cert="auth_serv/ca.der", phase2="auth=PAP",
4289                 dh_file="auth_serv/dh.conf")
4290
4291 def test_ap_wpa2_eap_ttls_dh_params_dsa(dev, apdev):
4292     """WPA2-Enterprise connection using EAP-TTLS and setting DH params (DSA)"""
4293     check_dh_dsa_support(dev[0])
4294     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4295     hapd = hostapd.add_ap(apdev[0], params)
4296     eap_connect(dev[0], hapd, "TTLS", "pap user",
4297                 anonymous_identity="ttls", password="password",
4298                 ca_cert="auth_serv/ca.der", phase2="auth=PAP",
4299                 dh_file="auth_serv/dsaparam.pem")
4300
4301 def test_ap_wpa2_eap_ttls_dh_params_not_found(dev, apdev):
4302     """EAP-TTLS and DH params file not found"""
4303     skip_with_fips(dev[0])
4304     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4305     hostapd.add_ap(apdev[0], params)
4306     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
4307                    identity="mschap user", password="password",
4308                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
4309                    dh_file="auth_serv/dh-no-such-file.conf",
4310                    scan_freq="2412", wait_connect=False)
4311     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
4312     if ev is None:
4313         raise Exception("EAP failure timed out")
4314     dev[0].request("REMOVE_NETWORK all")
4315     dev[0].wait_disconnected()
4316
4317 def test_ap_wpa2_eap_ttls_dh_params_invalid(dev, apdev):
4318     """EAP-TTLS and invalid DH params file"""
4319     skip_with_fips(dev[0])
4320     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4321     hostapd.add_ap(apdev[0], params)
4322     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
4323                    identity="mschap user", password="password",
4324                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
4325                    dh_file="auth_serv/ca.pem",
4326                    scan_freq="2412", wait_connect=False)
4327     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
4328     if ev is None:
4329         raise Exception("EAP failure timed out")
4330     dev[0].request("REMOVE_NETWORK all")
4331     dev[0].wait_disconnected()
4332
4333 def test_ap_wpa2_eap_ttls_dh_params_blob(dev, apdev):
4334     """WPA2-Enterprise connection using EAP-TTLS/CHAP and setting DH params from blob"""
4335     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4336     hapd = hostapd.add_ap(apdev[0], params)
4337     dh = read_pem("auth_serv/dh2.conf")
4338     if "OK" not in dev[0].request("SET blob dhparams " + dh.encode("hex")):
4339         raise Exception("Could not set dhparams blob")
4340     eap_connect(dev[0], hapd, "TTLS", "pap user",
4341                 anonymous_identity="ttls", password="password",
4342                 ca_cert="auth_serv/ca.der", phase2="auth=PAP",
4343                 dh_file="blob://dhparams")
4344
4345 def test_ap_wpa2_eap_ttls_dh_params_server(dev, apdev):
4346     """WPA2-Enterprise using EAP-TTLS and alternative server dhparams"""
4347     params = int_eap_server_params()
4348     params["dh_file"] = "auth_serv/dh2.conf"
4349     hapd = hostapd.add_ap(apdev[0], params)
4350     eap_connect(dev[0], hapd, "TTLS", "pap user",
4351                 anonymous_identity="ttls", password="password",
4352                 ca_cert="auth_serv/ca.der", phase2="auth=PAP")
4353
4354 def test_ap_wpa2_eap_ttls_dh_params_dsa_server(dev, apdev):
4355     """WPA2-Enterprise using EAP-TTLS and alternative server dhparams (DSA)"""
4356     params = int_eap_server_params()
4357     params["dh_file"] = "auth_serv/dsaparam.pem"
4358     hapd = hostapd.add_ap(apdev[0], params)
4359     eap_connect(dev[0], hapd, "TTLS", "pap user",
4360                 anonymous_identity="ttls", password="password",
4361                 ca_cert="auth_serv/ca.der", phase2="auth=PAP")
4362
4363 def test_ap_wpa2_eap_ttls_dh_params_not_found(dev, apdev):
4364     """EAP-TLS server and dhparams file not found"""
4365     params = int_eap_server_params()
4366     params["dh_file"] = "auth_serv/dh-no-such-file.conf"
4367     hapd = hostapd.add_ap(apdev[0], params, no_enable=True)
4368     if "FAIL" not in hapd.request("ENABLE"):
4369         raise Exception("Invalid configuration accepted")
4370
4371 def test_ap_wpa2_eap_ttls_dh_params_invalid(dev, apdev):
4372     """EAP-TLS server and invalid dhparams file"""
4373     params = int_eap_server_params()
4374     params["dh_file"] = "auth_serv/ca.pem"
4375     hapd = hostapd.add_ap(apdev[0], params, no_enable=True)
4376     if "FAIL" not in hapd.request("ENABLE"):
4377         raise Exception("Invalid configuration accepted")
4378
4379 def test_ap_wpa2_eap_reauth(dev, apdev):
4380     """WPA2-Enterprise and Authenticator forcing reauthentication"""
4381     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4382     params['eap_reauth_period'] = '2'
4383     hapd = hostapd.add_ap(apdev[0], params)
4384     eap_connect(dev[0], hapd, "PAX", "pax.user@example.com",
4385                 password_hex="0123456789abcdef0123456789abcdef")
4386     logger.info("Wait for reauthentication")
4387     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=10)
4388     if ev is None:
4389         raise Exception("Timeout on reauthentication")
4390     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4391     if ev is None:
4392         raise Exception("Timeout on reauthentication")
4393     for i in range(0, 20):
4394         state = dev[0].get_status_field("wpa_state")
4395         if state == "COMPLETED":
4396             break
4397         time.sleep(0.1)
4398     if state != "COMPLETED":
4399         raise Exception("Reauthentication did not complete")
4400
4401 def test_ap_wpa2_eap_request_identity_message(dev, apdev):
4402     """Optional displayable message in EAP Request-Identity"""
4403     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4404     params['eap_message'] = 'hello\\0networkid=netw,nasid=foo,portid=0,NAIRealms=example.com'
4405     hapd = hostapd.add_ap(apdev[0], params)
4406     eap_connect(dev[0], hapd, "PAX", "pax.user@example.com",
4407                 password_hex="0123456789abcdef0123456789abcdef")
4408
4409 def test_ap_wpa2_eap_sim_aka_result_ind(dev, apdev):
4410     """WPA2-Enterprise using EAP-SIM/AKA and protected result indication"""
4411     check_hlr_auc_gw_support()
4412     params = int_eap_server_params()
4413     params['eap_sim_db'] = "unix:/tmp/hlr_auc_gw.sock"
4414     params['eap_sim_aka_result_ind'] = "1"
4415     hapd = hostapd.add_ap(apdev[0], params)
4416
4417     eap_connect(dev[0], hapd, "SIM", "1232010000000000",
4418                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
4419                 phase1="result_ind=1")
4420     eap_reauth(dev[0], "SIM")
4421     eap_connect(dev[1], hapd, "SIM", "1232010000000000",
4422                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581")
4423
4424     dev[0].request("REMOVE_NETWORK all")
4425     dev[1].request("REMOVE_NETWORK all")
4426
4427     eap_connect(dev[0], hapd, "AKA", "0232010000000000",
4428                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123",
4429                 phase1="result_ind=1")
4430     eap_reauth(dev[0], "AKA")
4431     eap_connect(dev[1], hapd, "AKA", "0232010000000000",
4432                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123")
4433
4434     dev[0].request("REMOVE_NETWORK all")
4435     dev[1].request("REMOVE_NETWORK all")
4436
4437     eap_connect(dev[0], hapd, "AKA'", "6555444333222111",
4438                 password="5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123",
4439                 phase1="result_ind=1")
4440     eap_reauth(dev[0], "AKA'")
4441     eap_connect(dev[1], hapd, "AKA'", "6555444333222111",
4442                 password="5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123")
4443
4444 def test_ap_wpa2_eap_too_many_roundtrips(dev, apdev):
4445     """WPA2-Enterprise connection resulting in too many EAP roundtrips"""
4446     skip_with_fips(dev[0])
4447     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4448     hostapd.add_ap(apdev[0], params)
4449     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
4450                    eap="TTLS", identity="mschap user",
4451                    wait_connect=False, scan_freq="2412", ieee80211w="1",
4452                    anonymous_identity="ttls", password="password",
4453                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
4454                    fragment_size="8")
4455     ev = dev[0].wait_event(["EAP: more than",
4456                             "CTRL-EVENT-EAP-SUCCESS"], timeout=20)
4457     if ev is None or "EAP: more than" not in ev:
4458         raise Exception("EAP roundtrip limit not reached")
4459
4460 def test_ap_wpa2_eap_expanded_nak(dev, apdev):
4461     """WPA2-Enterprise connection with EAP resulting in expanded NAK"""
4462     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4463     hostapd.add_ap(apdev[0], params)
4464     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
4465                    eap="PSK", identity="vendor-test",
4466                    password_hex="ff23456789abcdef0123456789abcdef",
4467                    wait_connect=False)
4468
4469     found = False
4470     for i in range(0, 5):
4471         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"], timeout=16)
4472         if ev is None:
4473             raise Exception("Association and EAP start timed out")
4474         if "refuse proposed method" in ev:
4475             found = True
4476             break
4477     if not found:
4478         raise Exception("Unexpected EAP status: " + ev)
4479
4480     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
4481     if ev is None:
4482         raise Exception("EAP failure timed out")
4483
4484 def test_ap_wpa2_eap_sql(dev, apdev, params):
4485     """WPA2-Enterprise connection using SQLite for user DB"""
4486     skip_with_fips(dev[0])
4487     try:
4488         import sqlite3
4489     except ImportError:
4490         raise HwsimSkip("No sqlite3 module available")
4491     dbfile = os.path.join(params['logdir'], "eap-user.db")
4492     try:
4493         os.remove(dbfile)
4494     except:
4495         pass
4496     con = sqlite3.connect(dbfile)
4497     with con:
4498         cur = con.cursor()
4499         cur.execute("CREATE TABLE users(identity TEXT PRIMARY KEY, methods TEXT, password TEXT, remediation TEXT, phase2 INTEGER)")
4500         cur.execute("CREATE TABLE wildcards(identity TEXT PRIMARY KEY, methods TEXT)")
4501         cur.execute("INSERT INTO users(identity,methods,password,phase2) VALUES ('user-pap','TTLS-PAP','password',1)")
4502         cur.execute("INSERT INTO users(identity,methods,password,phase2) VALUES ('user-chap','TTLS-CHAP','password',1)")
4503         cur.execute("INSERT INTO users(identity,methods,password,phase2) VALUES ('user-mschap','TTLS-MSCHAP','password',1)")
4504         cur.execute("INSERT INTO users(identity,methods,password,phase2) VALUES ('user-mschapv2','TTLS-MSCHAPV2','password',1)")
4505         cur.execute("INSERT INTO wildcards(identity,methods) VALUES ('','TTLS,TLS')")
4506         cur.execute("CREATE TABLE authlog(timestamp TEXT, session TEXT, nas_ip TEXT, username TEXT, note TEXT)")
4507
4508     try:
4509         params = int_eap_server_params()
4510         params["eap_user_file"] = "sqlite:" + dbfile
4511         hapd = hostapd.add_ap(apdev[0], params)
4512         eap_connect(dev[0], hapd, "TTLS", "user-mschapv2",
4513                     anonymous_identity="ttls", password="password",
4514                     ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
4515         dev[0].request("REMOVE_NETWORK all")
4516         eap_connect(dev[1], hapd, "TTLS", "user-mschap",
4517                     anonymous_identity="ttls", password="password",
4518                     ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP")
4519         dev[1].request("REMOVE_NETWORK all")
4520         eap_connect(dev[0], hapd, "TTLS", "user-chap",
4521                     anonymous_identity="ttls", password="password",
4522                     ca_cert="auth_serv/ca.pem", phase2="auth=CHAP")
4523         eap_connect(dev[1], hapd, "TTLS", "user-pap",
4524                     anonymous_identity="ttls", password="password",
4525                     ca_cert="auth_serv/ca.pem", phase2="auth=PAP")
4526     finally:
4527         os.remove(dbfile)
4528
4529 def test_ap_wpa2_eap_non_ascii_identity(dev, apdev):
4530     """WPA2-Enterprise connection attempt using non-ASCII identity"""
4531     params = int_eap_server_params()
4532     hostapd.add_ap(apdev[0], params)
4533     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
4534                    identity="\x80", password="password", wait_connect=False)
4535     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
4536                    identity="a\x80", password="password", wait_connect=False)
4537     for i in range(0, 2):
4538         ev = dev[i].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
4539         if ev is None:
4540             raise Exception("Association and EAP start timed out")
4541         ev = dev[i].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=10)
4542         if ev is None:
4543             raise Exception("EAP method selection timed out")
4544
4545 def test_ap_wpa2_eap_non_ascii_identity2(dev, apdev):
4546     """WPA2-Enterprise connection attempt using non-ASCII identity"""
4547     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4548     hostapd.add_ap(apdev[0], params)
4549     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
4550                    identity="\x80", password="password", wait_connect=False)
4551     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
4552                    identity="a\x80", password="password", wait_connect=False)
4553     for i in range(0, 2):
4554         ev = dev[i].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
4555         if ev is None:
4556             raise Exception("Association and EAP start timed out")
4557         ev = dev[i].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=10)
4558         if ev is None:
4559             raise Exception("EAP method selection timed out")
4560
4561 def test_openssl_cipher_suite_config_wpas(dev, apdev):
4562     """OpenSSL cipher suite configuration on wpa_supplicant"""
4563     tls = dev[0].request("GET tls_library")
4564     if not tls.startswith("OpenSSL"):
4565         raise HwsimSkip("TLS library is not OpenSSL: " + tls)
4566     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4567     hapd = hostapd.add_ap(apdev[0], params)
4568     eap_connect(dev[0], hapd, "TTLS", "pap user",
4569                 anonymous_identity="ttls", password="password",
4570                 openssl_ciphers="AES128",
4571                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP")
4572     eap_connect(dev[1], hapd, "TTLS", "pap user",
4573                 anonymous_identity="ttls", password="password",
4574                 openssl_ciphers="EXPORT",
4575                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP",
4576                 expect_failure=True, maybe_local_error=True)
4577     dev[2].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
4578                    identity="pap user", anonymous_identity="ttls",
4579                    password="password",
4580                    openssl_ciphers="FOO",
4581                    ca_cert="auth_serv/ca.pem", phase2="auth=PAP",
4582                    wait_connect=False)
4583     ev = dev[2].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4584     if ev is None:
4585         raise Exception("EAP failure after invalid openssl_ciphers not reported")
4586     dev[2].request("DISCONNECT")
4587
4588 def test_openssl_cipher_suite_config_hapd(dev, apdev):
4589     """OpenSSL cipher suite configuration on hostapd"""
4590     tls = dev[0].request("GET tls_library")
4591     if not tls.startswith("OpenSSL"):
4592         raise HwsimSkip("wpa_supplicant TLS library is not OpenSSL: " + tls)
4593     params = int_eap_server_params()
4594     params['openssl_ciphers'] = "AES256"
4595     hapd = hostapd.add_ap(apdev[0], params)
4596     tls = hapd.request("GET tls_library")
4597     if not tls.startswith("OpenSSL"):
4598         raise HwsimSkip("hostapd TLS library is not OpenSSL: " + tls)
4599     eap_connect(dev[0], hapd, "TTLS", "pap user",
4600                 anonymous_identity="ttls", password="password",
4601                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP")
4602     eap_connect(dev[1], hapd, "TTLS", "pap user",
4603                 anonymous_identity="ttls", password="password",
4604                 openssl_ciphers="AES128",
4605                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP",
4606                 expect_failure=True)
4607     eap_connect(dev[2], hapd, "TTLS", "pap user",
4608                 anonymous_identity="ttls", password="password",
4609                 openssl_ciphers="HIGH:!ADH",
4610                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP")
4611
4612     params['openssl_ciphers'] = "FOO"
4613     hapd2 = hostapd.add_ap(apdev[1], params, no_enable=True)
4614     if "FAIL" not in hapd2.request("ENABLE"):
4615         raise Exception("Invalid openssl_ciphers value accepted")
4616
4617 def test_wpa2_eap_ttls_pap_key_lifetime_in_memory(dev, apdev, params):
4618     """Key lifetime in memory with WPA2-Enterprise using EAP-TTLS/PAP"""
4619     p = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4620     hapd = hostapd.add_ap(apdev[0], p)
4621     password = "63d2d21ac3c09ed567ee004a34490f1d16e7fa5835edf17ddba70a63f1a90a25"
4622     pid = find_wpas_process(dev[0])
4623     id = eap_connect(dev[0], hapd, "TTLS", "pap-secret",
4624                      anonymous_identity="ttls", password=password,
4625                      ca_cert="auth_serv/ca.pem", phase2="auth=PAP")
4626     # The decrypted copy of GTK is freed only after the CTRL-EVENT-CONNECTED
4627     # event has been delivered, so verify that wpa_supplicant has returned to
4628     # eloop before reading process memory.
4629     time.sleep(1)
4630     dev[0].ping()
4631     buf = read_process_memory(pid, password)
4632
4633     dev[0].request("DISCONNECT")
4634     dev[0].wait_disconnected()
4635
4636     dev[0].relog()
4637     msk = None
4638     emsk = None
4639     pmk = None
4640     ptk = None
4641     gtk = None
4642     with open(os.path.join(params['logdir'], 'log0'), 'r') as f:
4643         for l in f.readlines():
4644             if "EAP-TTLS: Derived key - hexdump" in l:
4645                 val = l.strip().split(':')[3].replace(' ', '')
4646                 msk = binascii.unhexlify(val)
4647             if "EAP-TTLS: Derived EMSK - hexdump" in l:
4648                 val = l.strip().split(':')[3].replace(' ', '')
4649                 emsk = binascii.unhexlify(val)
4650             if "WPA: PMK - hexdump" in l:
4651                 val = l.strip().split(':')[3].replace(' ', '')
4652                 pmk = binascii.unhexlify(val)
4653             if "WPA: PTK - hexdump" in l:
4654                 val = l.strip().split(':')[3].replace(' ', '')
4655                 ptk = binascii.unhexlify(val)
4656             if "WPA: Group Key - hexdump" in l:
4657                 val = l.strip().split(':')[3].replace(' ', '')
4658                 gtk = binascii.unhexlify(val)
4659     if not msk or not emsk or not pmk or not ptk or not gtk:
4660         raise Exception("Could not find keys from debug log")
4661     if len(gtk) != 16:
4662         raise Exception("Unexpected GTK length")
4663
4664     kck = ptk[0:16]
4665     kek = ptk[16:32]
4666     tk = ptk[32:48]
4667
4668     fname = os.path.join(params['logdir'],
4669                          'wpa2_eap_ttls_pap_key_lifetime_in_memory.memctx-')
4670
4671     logger.info("Checking keys in memory while associated")
4672     get_key_locations(buf, password, "Password")
4673     get_key_locations(buf, pmk, "PMK")
4674     get_key_locations(buf, msk, "MSK")
4675     get_key_locations(buf, emsk, "EMSK")
4676     if password not in buf:
4677         raise HwsimSkip("Password not found while associated")
4678     if pmk not in buf:
4679         raise HwsimSkip("PMK not found while associated")
4680     if kck not in buf:
4681         raise Exception("KCK not found while associated")
4682     if kek not in buf:
4683         raise Exception("KEK not found while associated")
4684     if tk in buf:
4685         raise Exception("TK found from memory")
4686     if gtk in buf:
4687         get_key_locations(buf, gtk, "GTK")
4688         raise Exception("GTK found from memory")
4689
4690     logger.info("Checking keys in memory after disassociation")
4691     buf = read_process_memory(pid, password)
4692
4693     # Note: Password is still present in network configuration
4694     # Note: PMK is in PMKSA cache and EAP fast re-auth data
4695
4696     get_key_locations(buf, password, "Password")
4697     get_key_locations(buf, pmk, "PMK")
4698     get_key_locations(buf, msk, "MSK")
4699     get_key_locations(buf, emsk, "EMSK")
4700     verify_not_present(buf, kck, fname, "KCK")
4701     verify_not_present(buf, kek, fname, "KEK")
4702     verify_not_present(buf, tk, fname, "TK")
4703     verify_not_present(buf, gtk, fname, "GTK")
4704
4705     dev[0].request("PMKSA_FLUSH")
4706     dev[0].set_network_quoted(id, "identity", "foo")
4707     logger.info("Checking keys in memory after PMKSA cache and EAP fast reauth flush")
4708     buf = read_process_memory(pid, password)
4709     get_key_locations(buf, password, "Password")
4710     get_key_locations(buf, pmk, "PMK")
4711     get_key_locations(buf, msk, "MSK")
4712     get_key_locations(buf, emsk, "EMSK")
4713     verify_not_present(buf, pmk, fname, "PMK")
4714
4715     dev[0].request("REMOVE_NETWORK all")
4716
4717     logger.info("Checking keys in memory after network profile removal")
4718     buf = read_process_memory(pid, password)
4719
4720     get_key_locations(buf, password, "Password")
4721     get_key_locations(buf, pmk, "PMK")
4722     get_key_locations(buf, msk, "MSK")
4723     get_key_locations(buf, emsk, "EMSK")
4724     verify_not_present(buf, password, fname, "password")
4725     verify_not_present(buf, pmk, fname, "PMK")
4726     verify_not_present(buf, kck, fname, "KCK")
4727     verify_not_present(buf, kek, fname, "KEK")
4728     verify_not_present(buf, tk, fname, "TK")
4729     verify_not_present(buf, gtk, fname, "GTK")
4730     verify_not_present(buf, msk, fname, "MSK")
4731     verify_not_present(buf, emsk, fname, "EMSK")
4732
4733 def test_ap_wpa2_eap_unexpected_wep_eapol_key(dev, apdev):
4734     """WPA2-Enterprise connection and unexpected WEP EAPOL-Key"""
4735     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4736     hapd = hostapd.add_ap(apdev[0], params)
4737     bssid = apdev[0]['bssid']
4738     eap_connect(dev[0], hapd, "TTLS", "pap user",
4739                 anonymous_identity="ttls", password="password",
4740                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP")
4741
4742     # Send unexpected WEP EAPOL-Key; this gets dropped
4743     res = dev[0].request("EAPOL_RX " + bssid + " 0203002c0100000000000000000000000000000000000000000000000000000000000000000000000000000000000000")
4744     if "OK" not in res:
4745         raise Exception("EAPOL_RX to wpa_supplicant failed")
4746
4747 def test_ap_wpa2_eap_in_bridge(dev, apdev):
4748     """WPA2-EAP and wpas interface in a bridge"""
4749     br_ifname='sta-br0'
4750     ifname='wlan5'
4751     try:
4752         _test_ap_wpa2_eap_in_bridge(dev, apdev)
4753     finally:
4754         subprocess.call(['ip', 'link', 'set', 'dev', br_ifname, 'down'])
4755         subprocess.call(['brctl', 'delif', br_ifname, ifname])
4756         subprocess.call(['brctl', 'delbr', br_ifname])
4757         subprocess.call(['iw', ifname, 'set', '4addr', 'off'])
4758
4759 def _test_ap_wpa2_eap_in_bridge(dev, apdev):
4760     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4761     hapd = hostapd.add_ap(apdev[0], params)
4762
4763     br_ifname='sta-br0'
4764     ifname='wlan5'
4765     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
4766     subprocess.call(['brctl', 'addbr', br_ifname])
4767     subprocess.call(['brctl', 'setfd', br_ifname, '0'])
4768     subprocess.call(['ip', 'link', 'set', 'dev', br_ifname, 'up'])
4769     subprocess.call(['iw', ifname, 'set', '4addr', 'on'])
4770     subprocess.check_call(['brctl', 'addif', br_ifname, ifname])
4771     wpas.interface_add(ifname, br_ifname=br_ifname)
4772     wpas.dump_monitor()
4773
4774     id = eap_connect(wpas, hapd, "PAX", "pax.user@example.com",
4775                      password_hex="0123456789abcdef0123456789abcdef")
4776     wpas.dump_monitor()
4777     eap_reauth(wpas, "PAX")
4778     wpas.dump_monitor()
4779     # Try again as a regression test for packet socket workaround
4780     eap_reauth(wpas, "PAX")
4781     wpas.dump_monitor()
4782     wpas.request("DISCONNECT")
4783     wpas.wait_disconnected()
4784     wpas.dump_monitor()
4785     wpas.request("RECONNECT")
4786     wpas.wait_connected()
4787     wpas.dump_monitor()
4788
4789 def test_ap_wpa2_eap_session_ticket(dev, apdev):
4790     """WPA2-Enterprise connection using EAP-TTLS and TLS session ticket enabled"""
4791     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4792     hapd = hostapd.add_ap(apdev[0], params)
4793     key_mgmt = hapd.get_config()['key_mgmt']
4794     if key_mgmt.split(' ')[0] != "WPA-EAP":
4795         raise Exception("Unexpected GET_CONFIG(key_mgmt): " + key_mgmt)
4796     eap_connect(dev[0], hapd, "TTLS", "pap user",
4797                 anonymous_identity="ttls", password="password",
4798                 ca_cert="auth_serv/ca.pem",
4799                 phase1="tls_disable_session_ticket=0", phase2="auth=PAP")
4800     eap_reauth(dev[0], "TTLS")
4801
4802 def test_ap_wpa2_eap_no_workaround(dev, apdev):
4803     """WPA2-Enterprise connection using EAP-TTLS and eap_workaround=0"""
4804     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4805     hapd = hostapd.add_ap(apdev[0], params)
4806     key_mgmt = hapd.get_config()['key_mgmt']
4807     if key_mgmt.split(' ')[0] != "WPA-EAP":
4808         raise Exception("Unexpected GET_CONFIG(key_mgmt): " + key_mgmt)
4809     eap_connect(dev[0], hapd, "TTLS", "pap user",
4810                 anonymous_identity="ttls", password="password",
4811                 ca_cert="auth_serv/ca.pem", eap_workaround='0',
4812                 phase2="auth=PAP")
4813     eap_reauth(dev[0], "TTLS")
4814
4815 def test_ap_wpa2_eap_tls_check_crl(dev, apdev):
4816     """EAP-TLS and server checking CRL"""
4817     params = int_eap_server_params()
4818     params['check_crl'] = '1'
4819     hapd = hostapd.add_ap(apdev[0], params)
4820
4821     # check_crl=1 and no CRL available --> reject connection
4822     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4823                 client_cert="auth_serv/user.pem",
4824                 private_key="auth_serv/user.key", expect_failure=True)
4825     dev[0].request("REMOVE_NETWORK all")
4826
4827     hapd.disable()
4828     hapd.set("ca_cert", "auth_serv/ca-and-crl.pem")
4829     hapd.enable()
4830
4831     # check_crl=1 and valid CRL --> accept
4832     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4833                 client_cert="auth_serv/user.pem",
4834                 private_key="auth_serv/user.key")
4835     dev[0].request("REMOVE_NETWORK all")
4836
4837     hapd.disable()
4838     hapd.set("check_crl", "2")
4839     hapd.enable()
4840
4841     # check_crl=2 and valid CRL --> accept
4842     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4843                 client_cert="auth_serv/user.pem",
4844                 private_key="auth_serv/user.key")
4845     dev[0].request("REMOVE_NETWORK all")
4846
4847 def test_ap_wpa2_eap_tls_oom(dev, apdev):
4848     """EAP-TLS and OOM"""
4849     check_subject_match_support(dev[0])
4850     check_altsubject_match_support(dev[0])
4851     check_domain_match(dev[0])
4852     check_domain_match_full(dev[0])
4853
4854     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4855     hostapd.add_ap(apdev[0], params)
4856
4857     tests = [ (1, "tls_connection_set_subject_match"),
4858               (2, "tls_connection_set_subject_match"),
4859               (3, "tls_connection_set_subject_match"),
4860               (4, "tls_connection_set_subject_match") ]
4861     for count, func in tests:
4862         with alloc_fail(dev[0], count, func):
4863             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4864                            identity="tls user", ca_cert="auth_serv/ca.pem",
4865                            client_cert="auth_serv/user.pem",
4866                            private_key="auth_serv/user.key",
4867                            subject_match="/C=FI/O=w1.fi/CN=server.w1.fi",
4868                            altsubject_match="EMAIL:noone@example.com;DNS:server.w1.fi;URI:http://example.com/",
4869                            domain_suffix_match="server.w1.fi",
4870                            domain_match="server.w1.fi",
4871                            wait_connect=False, scan_freq="2412")
4872             # TLS parameter configuration error results in CTRL-REQ-PASSPHRASE
4873             ev = dev[0].wait_event(["CTRL-REQ-PASSPHRASE"], timeout=5)
4874             if ev is None:
4875                 raise Exception("No passphrase request")
4876             dev[0].request("REMOVE_NETWORK all")
4877             dev[0].wait_disconnected()
4878
4879 def test_ap_wpa2_eap_tls_macacl(dev, apdev):
4880     """WPA2-Enterprise connection using MAC ACL"""
4881     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4882     params["macaddr_acl"] = "2"
4883     hapd = hostapd.add_ap(apdev[0], params)
4884     eap_connect(dev[1], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4885                 client_cert="auth_serv/user.pem",
4886                 private_key="auth_serv/user.key")
4887
4888 def test_ap_wpa2_eap_oom(dev, apdev):
4889     """EAP server and OOM"""
4890     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4891     hapd = hostapd.add_ap(apdev[0], params)
4892     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
4893
4894     with alloc_fail(hapd, 1, "eapol_auth_alloc"):
4895         # The first attempt fails, but STA will send EAPOL-Start to retry and
4896         # that succeeds.
4897         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4898                        identity="tls user", ca_cert="auth_serv/ca.pem",
4899                        client_cert="auth_serv/user.pem",
4900                        private_key="auth_serv/user.key",
4901                        scan_freq="2412")
4902
4903 def check_tls_ver(dev, hapd, phase1, expected):
4904     eap_connect(dev, hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4905                 client_cert="auth_serv/user.pem",
4906                 private_key="auth_serv/user.key",
4907                 phase1=phase1)
4908     ver = dev.get_status_field("eap_tls_version")
4909     if ver != expected:
4910         raise Exception("Unexpected TLS version (expected %s): %s" % (expected, ver))
4911
4912 def test_ap_wpa2_eap_tls_versions(dev, apdev):
4913     """EAP-TLS and TLS version configuration"""
4914     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4915     hapd = hostapd.add_ap(apdev[0], params)
4916
4917     tls = dev[0].request("GET tls_library")
4918     if tls.startswith("OpenSSL"):
4919         if "build=OpenSSL 1.0.2" in tls and "run=OpenSSL 1.0.2" in tls:
4920             check_tls_ver(dev[0], hapd,
4921                           "tls_disable_tlsv1_0=1 tls_disable_tlsv1_1=1",
4922                           "TLSv1.2")
4923     elif tls.startswith("internal"):
4924         check_tls_ver(dev[0], hapd,
4925                       "tls_disable_tlsv1_0=1 tls_disable_tlsv1_1=1", "TLSv1.2")
4926     check_tls_ver(dev[1], hapd,
4927                   "tls_disable_tlsv1_0=1 tls_disable_tlsv1_2=1", "TLSv1.1")
4928     check_tls_ver(dev[2], hapd,
4929                   "tls_disable_tlsv1_1=1 tls_disable_tlsv1_2=1", "TLSv1")
4930
4931 def test_rsn_ie_proto_eap_sta(dev, apdev):
4932     """RSN element protocol testing for EAP cases on STA side"""
4933     bssid = apdev[0]['bssid']
4934     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4935     # This is the RSN element used normally by hostapd
4936     params['own_ie_override'] = '30140100000fac040100000fac040100000fac010c00'
4937     hapd = hostapd.add_ap(apdev[0], params)
4938     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="GPSK",
4939                         identity="gpsk user",
4940                         password="abcdefghijklmnop0123456789abcdef",
4941                         scan_freq="2412")
4942
4943     tests = [ ('No RSN Capabilities field',
4944                '30120100000fac040100000fac040100000fac01'),
4945               ('No AKM Suite fields',
4946                '300c0100000fac040100000fac04'),
4947               ('No Pairwise Cipher Suite fields',
4948                '30060100000fac04'),
4949               ('No Group Data Cipher Suite field',
4950                '30020100') ]
4951     for txt,ie in tests:
4952         dev[0].request("DISCONNECT")
4953         dev[0].wait_disconnected()
4954         logger.info(txt)
4955         hapd.disable()
4956         hapd.set('own_ie_override', ie)
4957         hapd.enable()
4958         dev[0].request("BSS_FLUSH 0")
4959         dev[0].scan_for_bss(bssid, 2412, force_scan=True, only_new=True)
4960         dev[0].select_network(id, freq=2412)
4961         dev[0].wait_connected()
4962
4963     dev[0].request("DISCONNECT")
4964     dev[0].wait_disconnected()
4965     dev[0].flush_scan_cache()
4966
4967 def check_tls_session_resumption_capa(dev, hapd):
4968     tls = hapd.request("GET tls_library")
4969     if not tls.startswith("OpenSSL"):
4970         raise HwsimSkip("hostapd TLS library is not OpenSSL: " + tls)
4971
4972     tls = dev.request("GET tls_library")
4973     if not tls.startswith("OpenSSL"):
4974         raise HwsimSkip("Session resumption not supported with this TLS library: " + tls)
4975
4976 def test_eap_ttls_pap_session_resumption(dev, apdev):
4977     """EAP-TTLS/PAP session resumption"""
4978     params = int_eap_server_params()
4979     params['tls_session_lifetime'] = '60'
4980     hapd = hostapd.add_ap(apdev[0], params)
4981     check_tls_session_resumption_capa(dev[0], hapd)
4982     eap_connect(dev[0], hapd, "TTLS", "pap user",
4983                 anonymous_identity="ttls", password="password",
4984                 ca_cert="auth_serv/ca.pem", eap_workaround='0',
4985                 phase2="auth=PAP")
4986     if dev[0].get_status_field("tls_session_reused") != '0':
4987         raise Exception("Unexpected session resumption on the first connection")
4988
4989     dev[0].request("REAUTHENTICATE")
4990     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
4991     if ev is None:
4992         raise Exception("EAP success timed out")
4993     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
4994     if ev is None:
4995         raise Exception("Key handshake with the AP timed out")
4996     if dev[0].get_status_field("tls_session_reused") != '1':
4997         raise Exception("Session resumption not used on the second connection")
4998
4999 def test_eap_ttls_chap_session_resumption(dev, apdev):
5000     """EAP-TTLS/CHAP session resumption"""
5001     params = int_eap_server_params()
5002     params['tls_session_lifetime'] = '60'
5003     hapd = hostapd.add_ap(apdev[0], params)
5004     check_tls_session_resumption_capa(dev[0], hapd)
5005     eap_connect(dev[0], hapd, "TTLS", "chap user",
5006                 anonymous_identity="ttls", password="password",
5007                 ca_cert="auth_serv/ca.der", phase2="auth=CHAP")
5008     if dev[0].get_status_field("tls_session_reused") != '0':
5009         raise Exception("Unexpected session resumption on the first connection")
5010
5011     dev[0].request("REAUTHENTICATE")
5012     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
5013     if ev is None:
5014         raise Exception("EAP success timed out")
5015     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
5016     if ev is None:
5017         raise Exception("Key handshake with the AP timed out")
5018     if dev[0].get_status_field("tls_session_reused") != '1':
5019         raise Exception("Session resumption not used on the second connection")
5020
5021 def test_eap_ttls_mschap_session_resumption(dev, apdev):
5022     """EAP-TTLS/MSCHAP session resumption"""
5023     check_domain_suffix_match(dev[0])
5024     params = int_eap_server_params()
5025     params['tls_session_lifetime'] = '60'
5026     hapd = hostapd.add_ap(apdev[0], params)
5027     check_tls_session_resumption_capa(dev[0], hapd)
5028     eap_connect(dev[0], hapd, "TTLS", "mschap user",
5029                 anonymous_identity="ttls", password="password",
5030                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
5031                 domain_suffix_match="server.w1.fi")
5032     if dev[0].get_status_field("tls_session_reused") != '0':
5033         raise Exception("Unexpected session resumption on the first connection")
5034
5035     dev[0].request("REAUTHENTICATE")
5036     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
5037     if ev is None:
5038         raise Exception("EAP success timed out")
5039     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
5040     if ev is None:
5041         raise Exception("Key handshake with the AP timed out")
5042     if dev[0].get_status_field("tls_session_reused") != '1':
5043         raise Exception("Session resumption not used on the second connection")
5044
5045 def test_eap_ttls_mschapv2_session_resumption(dev, apdev):
5046     """EAP-TTLS/MSCHAPv2 session resumption"""
5047     check_domain_suffix_match(dev[0])
5048     check_eap_capa(dev[0], "MSCHAPV2")
5049     params = int_eap_server_params()
5050     params['tls_session_lifetime'] = '60'
5051     hapd = hostapd.add_ap(apdev[0], params)
5052     check_tls_session_resumption_capa(dev[0], hapd)
5053     eap_connect(dev[0], hapd, "TTLS", "DOMAIN\mschapv2 user",
5054                 anonymous_identity="ttls", password="password",
5055                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
5056                 domain_suffix_match="server.w1.fi")
5057     if dev[0].get_status_field("tls_session_reused") != '0':
5058         raise Exception("Unexpected session resumption on the first connection")
5059
5060     dev[0].request("REAUTHENTICATE")
5061     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
5062     if ev is None:
5063         raise Exception("EAP success timed out")
5064     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
5065     if ev is None:
5066         raise Exception("Key handshake with the AP timed out")
5067     if dev[0].get_status_field("tls_session_reused") != '1':
5068         raise Exception("Session resumption not used on the second connection")
5069
5070 def test_eap_ttls_eap_gtc_session_resumption(dev, apdev):
5071     """EAP-TTLS/EAP-GTC session resumption"""
5072     params = int_eap_server_params()
5073     params['tls_session_lifetime'] = '60'
5074     hapd = hostapd.add_ap(apdev[0], params)
5075     check_tls_session_resumption_capa(dev[0], hapd)
5076     eap_connect(dev[0], hapd, "TTLS", "user",
5077                 anonymous_identity="ttls", password="password",
5078                 ca_cert="auth_serv/ca.pem", phase2="autheap=GTC")
5079     if dev[0].get_status_field("tls_session_reused") != '0':
5080         raise Exception("Unexpected session resumption on the first connection")
5081
5082     dev[0].request("REAUTHENTICATE")
5083     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
5084     if ev is None:
5085         raise Exception("EAP success timed out")
5086     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
5087     if ev is None:
5088         raise Exception("Key handshake with the AP timed out")
5089     if dev[0].get_status_field("tls_session_reused") != '1':
5090         raise Exception("Session resumption not used on the second connection")
5091
5092 def test_eap_ttls_no_session_resumption(dev, apdev):
5093     """EAP-TTLS session resumption disabled on server"""
5094     params = int_eap_server_params()
5095     params['tls_session_lifetime'] = '0'
5096     hapd = hostapd.add_ap(apdev[0], params)
5097     eap_connect(dev[0], hapd, "TTLS", "pap user",
5098                 anonymous_identity="ttls", password="password",
5099                 ca_cert="auth_serv/ca.pem", eap_workaround='0',
5100                 phase2="auth=PAP")
5101     if dev[0].get_status_field("tls_session_reused") != '0':
5102         raise Exception("Unexpected session resumption on the first connection")
5103
5104     dev[0].request("REAUTHENTICATE")
5105     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
5106     if ev is None:
5107         raise Exception("EAP success timed out")
5108     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
5109     if ev is None:
5110         raise Exception("Key handshake with the AP timed out")
5111     if dev[0].get_status_field("tls_session_reused") != '0':
5112         raise Exception("Unexpected session resumption on the second connection")
5113
5114 def test_eap_peap_session_resumption(dev, apdev):
5115     """EAP-PEAP session resumption"""
5116     params = int_eap_server_params()
5117     params['tls_session_lifetime'] = '60'
5118     hapd = hostapd.add_ap(apdev[0], params)
5119     check_tls_session_resumption_capa(dev[0], hapd)
5120     eap_connect(dev[0], hapd, "PEAP", "user",
5121                 anonymous_identity="peap", password="password",
5122                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
5123     if dev[0].get_status_field("tls_session_reused") != '0':
5124         raise Exception("Unexpected session resumption on the first connection")
5125
5126     dev[0].request("REAUTHENTICATE")
5127     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
5128     if ev is None:
5129         raise Exception("EAP success timed out")
5130     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
5131     if ev is None:
5132         raise Exception("Key handshake with the AP timed out")
5133     if dev[0].get_status_field("tls_session_reused") != '1':
5134         raise Exception("Session resumption not used on the second connection")
5135
5136 def test_eap_peap_session_resumption_crypto_binding(dev, apdev):
5137     """EAP-PEAP session resumption with crypto binding"""
5138     params = int_eap_server_params()
5139     params['tls_session_lifetime'] = '60'
5140     hapd = hostapd.add_ap(apdev[0], params)
5141     check_tls_session_resumption_capa(dev[0], hapd)
5142     eap_connect(dev[0], hapd, "PEAP", "user",
5143                 anonymous_identity="peap", password="password",
5144                 phase1="peapver=0 crypto_binding=2",
5145                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
5146     if dev[0].get_status_field("tls_session_reused") != '0':
5147         raise Exception("Unexpected session resumption on the first connection")
5148
5149     dev[0].request("REAUTHENTICATE")
5150     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
5151     if ev is None:
5152         raise Exception("EAP success timed out")
5153     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
5154     if ev is None:
5155         raise Exception("Key handshake with the AP timed out")
5156     if dev[0].get_status_field("tls_session_reused") != '1':
5157         raise Exception("Session resumption not used on the second connection")
5158
5159 def test_eap_peap_no_session_resumption(dev, apdev):
5160     """EAP-PEAP session resumption disabled on server"""
5161     params = int_eap_server_params()
5162     hapd = hostapd.add_ap(apdev[0], params)
5163     eap_connect(dev[0], hapd, "PEAP", "user",
5164                 anonymous_identity="peap", password="password",
5165                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
5166     if dev[0].get_status_field("tls_session_reused") != '0':
5167         raise Exception("Unexpected session resumption on the first connection")
5168
5169     dev[0].request("REAUTHENTICATE")
5170     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
5171     if ev is None:
5172         raise Exception("EAP success timed out")
5173     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
5174     if ev is None:
5175         raise Exception("Key handshake with the AP timed out")
5176     if dev[0].get_status_field("tls_session_reused") != '0':
5177         raise Exception("Unexpected session resumption on the second connection")
5178
5179 def test_eap_tls_session_resumption(dev, apdev):
5180     """EAP-TLS session resumption"""
5181     params = int_eap_server_params()
5182     params['tls_session_lifetime'] = '60'
5183     hapd = hostapd.add_ap(apdev[0], params)
5184     check_tls_session_resumption_capa(dev[0], hapd)
5185     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
5186                 client_cert="auth_serv/user.pem",
5187                 private_key="auth_serv/user.key")
5188     if dev[0].get_status_field("tls_session_reused") != '0':
5189         raise Exception("Unexpected session resumption on the first connection")
5190
5191     dev[0].request("REAUTHENTICATE")
5192     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
5193     if ev is None:
5194         raise Exception("EAP success timed out")
5195     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
5196     if ev is None:
5197         raise Exception("Key handshake with the AP timed out")
5198     if dev[0].get_status_field("tls_session_reused") != '1':
5199         raise Exception("Session resumption not used on the second connection")
5200
5201     dev[0].request("REAUTHENTICATE")
5202     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
5203     if ev is None:
5204         raise Exception("EAP success timed out")
5205     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
5206     if ev is None:
5207         raise Exception("Key handshake with the AP timed out")
5208     if dev[0].get_status_field("tls_session_reused") != '1':
5209         raise Exception("Session resumption not used on the third connection")
5210
5211 def test_eap_tls_session_resumption_expiration(dev, apdev):
5212     """EAP-TLS session resumption"""
5213     params = int_eap_server_params()
5214     params['tls_session_lifetime'] = '1'
5215     hapd = hostapd.add_ap(apdev[0], params)
5216     check_tls_session_resumption_capa(dev[0], hapd)
5217     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
5218                 client_cert="auth_serv/user.pem",
5219                 private_key="auth_serv/user.key")
5220     if dev[0].get_status_field("tls_session_reused") != '0':
5221         raise Exception("Unexpected session resumption on the first connection")
5222
5223     # Allow multiple attempts since OpenSSL may not expire the cached entry
5224     # immediately.
5225     for i in range(10):
5226         time.sleep(1.2)
5227
5228         dev[0].request("REAUTHENTICATE")
5229         ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
5230         if ev is None:
5231             raise Exception("EAP success timed out")
5232         ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
5233         if ev is None:
5234             raise Exception("Key handshake with the AP timed out")
5235         if dev[0].get_status_field("tls_session_reused") == '0':
5236             break
5237     if dev[0].get_status_field("tls_session_reused") != '0':
5238         raise Exception("Session resumption used after lifetime expiration")
5239
5240 def test_eap_tls_no_session_resumption(dev, apdev):
5241     """EAP-TLS session resumption disabled on server"""
5242     params = int_eap_server_params()
5243     hapd = hostapd.add_ap(apdev[0], params)
5244     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
5245                 client_cert="auth_serv/user.pem",
5246                 private_key="auth_serv/user.key")
5247     if dev[0].get_status_field("tls_session_reused") != '0':
5248         raise Exception("Unexpected session resumption on the first connection")
5249
5250     dev[0].request("REAUTHENTICATE")
5251     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
5252     if ev is None:
5253         raise Exception("EAP success timed out")
5254     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
5255     if ev is None:
5256         raise Exception("Key handshake with the AP timed out")
5257     if dev[0].get_status_field("tls_session_reused") != '0':
5258         raise Exception("Unexpected session resumption on the second connection")
5259
5260 def test_eap_tls_session_resumption_radius(dev, apdev):
5261     """EAP-TLS session resumption (RADIUS)"""
5262     params = { "ssid": "as", "beacon_int": "2000",
5263                "radius_server_clients": "auth_serv/radius_clients.conf",
5264                "radius_server_auth_port": '18128',
5265                "eap_server": "1",
5266                "eap_user_file": "auth_serv/eap_user.conf",
5267                "ca_cert": "auth_serv/ca.pem",
5268                "server_cert": "auth_serv/server.pem",
5269                "private_key": "auth_serv/server.key",
5270                "tls_session_lifetime": "60" }
5271     authsrv = hostapd.add_ap(apdev[1], params)
5272     check_tls_session_resumption_capa(dev[0], authsrv)
5273
5274     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
5275     params['auth_server_port'] = "18128"
5276     hapd = hostapd.add_ap(apdev[0], params)
5277     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
5278                 client_cert="auth_serv/user.pem",
5279                 private_key="auth_serv/user.key")
5280     if dev[0].get_status_field("tls_session_reused") != '0':
5281         raise Exception("Unexpected session resumption on the first connection")
5282
5283     dev[0].request("REAUTHENTICATE")
5284     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
5285     if ev is None:
5286         raise Exception("EAP success timed out")
5287     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
5288     if ev is None:
5289         raise Exception("Key handshake with the AP timed out")
5290     if dev[0].get_status_field("tls_session_reused") != '1':
5291         raise Exception("Session resumption not used on the second connection")
5292
5293 def test_eap_tls_no_session_resumption_radius(dev, apdev):
5294     """EAP-TLS session resumption disabled (RADIUS)"""
5295     params = { "ssid": "as", "beacon_int": "2000",
5296                "radius_server_clients": "auth_serv/radius_clients.conf",
5297                "radius_server_auth_port": '18128',
5298                "eap_server": "1",
5299                "eap_user_file": "auth_serv/eap_user.conf",
5300                "ca_cert": "auth_serv/ca.pem",
5301                "server_cert": "auth_serv/server.pem",
5302                "private_key": "auth_serv/server.key",
5303                "tls_session_lifetime": "0" }
5304     hostapd.add_ap(apdev[1], params)
5305
5306     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
5307     params['auth_server_port'] = "18128"
5308     hapd = hostapd.add_ap(apdev[0], params)
5309     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
5310                 client_cert="auth_serv/user.pem",
5311                 private_key="auth_serv/user.key")
5312     if dev[0].get_status_field("tls_session_reused") != '0':
5313         raise Exception("Unexpected session resumption on the first connection")
5314
5315     dev[0].request("REAUTHENTICATE")
5316     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
5317     if ev is None:
5318         raise Exception("EAP success timed out")
5319     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
5320     if ev is None:
5321         raise Exception("Key handshake with the AP timed out")
5322     if dev[0].get_status_field("tls_session_reused") != '0':
5323         raise Exception("Unexpected session resumption on the second connection")
5324
5325 def test_eap_mschapv2_errors(dev, apdev):
5326     """EAP-MSCHAPv2 error cases"""
5327     check_eap_capa(dev[0], "MSCHAPV2")
5328     check_eap_capa(dev[0], "FAST")
5329
5330     params = hostapd.wpa2_eap_params(ssid="test-wpa-eap")
5331     hapd = hostapd.add_ap(apdev[0], params)
5332     dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="MSCHAPV2",
5333                    identity="phase1-user", password="password",
5334                    scan_freq="2412")
5335     dev[0].request("REMOVE_NETWORK all")
5336     dev[0].wait_disconnected()
5337
5338     tests = [ (1, "hash_nt_password_hash;mschapv2_derive_response"),
5339               (1, "nt_password_hash;mschapv2_derive_response"),
5340               (1, "nt_password_hash;=mschapv2_derive_response"),
5341               (1, "generate_nt_response;mschapv2_derive_response"),
5342               (1, "generate_authenticator_response;mschapv2_derive_response"),
5343               (1, "nt_password_hash;=mschapv2_derive_response"),
5344               (1, "get_master_key;mschapv2_derive_response"),
5345               (1, "os_get_random;eap_mschapv2_challenge_reply") ]
5346     for count, func in tests:
5347         with fail_test(dev[0], count, func):
5348             dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="MSCHAPV2",
5349                            identity="phase1-user", password="password",
5350                            wait_connect=False, scan_freq="2412")
5351             wait_fail_trigger(dev[0], "GET_FAIL")
5352             dev[0].request("REMOVE_NETWORK all")
5353             dev[0].wait_disconnected()
5354
5355     tests = [ (1, "hash_nt_password_hash;mschapv2_derive_response"),
5356               (1, "hash_nt_password_hash;=mschapv2_derive_response"),
5357               (1, "generate_nt_response_pwhash;mschapv2_derive_response"),
5358               (1, "generate_authenticator_response_pwhash;mschapv2_derive_response") ]
5359     for count, func in tests:
5360         with fail_test(dev[0], count, func):
5361             dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="MSCHAPV2",
5362                            identity="phase1-user",
5363                            password_hex="hash:8846f7eaee8fb117ad06bdd830b7586c",
5364                            wait_connect=False, scan_freq="2412")
5365             wait_fail_trigger(dev[0], "GET_FAIL")
5366             dev[0].request("REMOVE_NETWORK all")
5367             dev[0].wait_disconnected()
5368
5369     tests = [ (1, "eap_mschapv2_init"),
5370               (1, "eap_msg_alloc;eap_mschapv2_challenge_reply"),
5371               (1, "eap_msg_alloc;eap_mschapv2_success"),
5372               (1, "eap_mschapv2_getKey") ]
5373     for count, func in tests:
5374         with alloc_fail(dev[0], count, func):
5375             dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="MSCHAPV2",
5376                            identity="phase1-user", password="password",
5377                            wait_connect=False, scan_freq="2412")
5378             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
5379             dev[0].request("REMOVE_NETWORK all")
5380             dev[0].wait_disconnected()
5381
5382     tests = [ (1, "eap_msg_alloc;eap_mschapv2_failure") ]
5383     for count, func in tests:
5384         with alloc_fail(dev[0], count, func):
5385             dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="MSCHAPV2",
5386                            identity="phase1-user", password="wrong password",
5387                            wait_connect=False, scan_freq="2412")
5388             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
5389             dev[0].request("REMOVE_NETWORK all")
5390             dev[0].wait_disconnected()
5391
5392     tests = [ (2, "eap_mschapv2_init"),
5393               (3, "eap_mschapv2_init") ]
5394     for count, func in tests:
5395         with alloc_fail(dev[0], count, func):
5396             dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="FAST",
5397                            anonymous_identity="FAST", identity="user",
5398                            password="password",
5399                            ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
5400                            phase1="fast_provisioning=1",
5401                            pac_file="blob://fast_pac",
5402                            wait_connect=False, scan_freq="2412")
5403             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
5404             dev[0].request("REMOVE_NETWORK all")
5405             dev[0].wait_disconnected()
5406
5407 def test_eap_gpsk_errors(dev, apdev):
5408     """EAP-GPSK error cases"""
5409     params = hostapd.wpa2_eap_params(ssid="test-wpa-eap")
5410     hapd = hostapd.add_ap(apdev[0], params)
5411     dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="GPSK",
5412                    identity="gpsk user",
5413                    password="abcdefghijklmnop0123456789abcdef",
5414                    scan_freq="2412")
5415     dev[0].request("REMOVE_NETWORK all")
5416     dev[0].wait_disconnected()
5417
5418     tests = [ (1, "os_get_random;eap_gpsk_send_gpsk_2", None),
5419               (1, "eap_gpsk_derive_session_id;eap_gpsk_send_gpsk_2",
5420                "cipher=1"),
5421               (1, "eap_gpsk_derive_session_id;eap_gpsk_send_gpsk_2",
5422                "cipher=2"),
5423               (1, "eap_gpsk_derive_keys_helper", None),
5424               (2, "eap_gpsk_derive_keys_helper", None),
5425               (1, "eap_gpsk_compute_mic_aes;eap_gpsk_compute_mic;eap_gpsk_send_gpsk_2",
5426                "cipher=1"),
5427               (1, "hmac_sha256;eap_gpsk_compute_mic;eap_gpsk_send_gpsk_2",
5428                "cipher=2"),
5429               (1, "eap_gpsk_compute_mic;eap_gpsk_validate_gpsk_3_mic", None),
5430               (1, "eap_gpsk_compute_mic;eap_gpsk_send_gpsk_4", None),
5431               (1, "eap_gpsk_derive_mid_helper", None) ]
5432     for count, func, phase1 in tests:
5433         with fail_test(dev[0], count, func):
5434             dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="GPSK",
5435                            identity="gpsk user",
5436                            password="abcdefghijklmnop0123456789abcdef",
5437                            phase1=phase1,
5438                            wait_connect=False, scan_freq="2412")
5439             wait_fail_trigger(dev[0], "GET_FAIL")
5440             dev[0].request("REMOVE_NETWORK all")
5441             dev[0].wait_disconnected()
5442
5443     tests = [ (1, "eap_gpsk_init"),
5444               (2, "eap_gpsk_init"),
5445               (3, "eap_gpsk_init"),
5446               (1, "eap_gpsk_process_id_server"),
5447               (1, "eap_msg_alloc;eap_gpsk_send_gpsk_2"),
5448               (1, "eap_gpsk_derive_session_id;eap_gpsk_send_gpsk_2"),
5449               (1, "eap_gpsk_derive_mid_helper;eap_gpsk_derive_session_id;eap_gpsk_send_gpsk_2"),
5450               (1, "eap_gpsk_derive_keys"),
5451               (1, "eap_gpsk_derive_keys_helper"),
5452               (1, "eap_msg_alloc;eap_gpsk_send_gpsk_4"),
5453               (1, "eap_gpsk_getKey"),
5454               (1, "eap_gpsk_get_emsk"),
5455               (1, "eap_gpsk_get_session_id") ]
5456     for count, func in tests:
5457         with alloc_fail(dev[0], count, func):
5458             dev[0].request("ERP_FLUSH")
5459             dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="GPSK",
5460                            identity="gpsk user", erp="1",
5461                            password="abcdefghijklmnop0123456789abcdef",
5462                            wait_connect=False, scan_freq="2412")
5463             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
5464             dev[0].request("REMOVE_NETWORK all")
5465             dev[0].wait_disconnected()
5466
5467 def test_ap_wpa2_eap_sim_db(dev, apdev, params):
5468     """EAP-SIM DB error cases"""
5469     sockpath = '/tmp/hlr_auc_gw.sock-test'
5470     try:
5471         os.remove(sockpath)
5472     except:
5473         pass
5474     hparams = int_eap_server_params()
5475     hparams['eap_sim_db'] = 'unix:' + sockpath
5476     hapd = hostapd.add_ap(apdev[0], hparams)
5477
5478     # Initial test with hlr_auc_gw socket not available
5479     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
5480                         eap="SIM", identity="1232010000000000",
5481                         password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
5482                         scan_freq="2412", wait_connect=False)
5483     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5484     if ev is None:
5485         raise Exception("EAP-Failure not reported")
5486     dev[0].wait_disconnected()
5487     dev[0].request("DISCONNECT")
5488
5489     # Test with invalid responses and response timeout
5490
5491     class test_handler(SocketServer.DatagramRequestHandler):
5492         def handle(self):
5493             data = self.request[0].strip()
5494             socket = self.request[1]
5495             logger.debug("Received hlr_auc_gw request: " + data)
5496             # EAP-SIM DB: Failed to parse response string
5497             socket.sendto("FOO", self.client_address)
5498             # EAP-SIM DB: Failed to parse response string
5499             socket.sendto("FOO 1", self.client_address)
5500             # EAP-SIM DB: Unknown external response
5501             socket.sendto("FOO 1 2", self.client_address)
5502             logger.info("No proper response - wait for pending eap_sim_db request timeout")
5503
5504     server = SocketServer.UnixDatagramServer(sockpath, test_handler)
5505     server.timeout = 1
5506
5507     dev[0].select_network(id)
5508     server.handle_request()
5509     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5510     if ev is None:
5511         raise Exception("EAP-Failure not reported")
5512     dev[0].wait_disconnected()
5513     dev[0].request("DISCONNECT")
5514
5515     # Test with a valid response
5516
5517     class test_handler2(SocketServer.DatagramRequestHandler):
5518         def handle(self):
5519             data = self.request[0].strip()
5520             socket = self.request[1]
5521             logger.debug("Received hlr_auc_gw request: " + data)
5522             fname = os.path.join(params['logdir'],
5523                                  'hlr_auc_gw.milenage_db')
5524             cmd = subprocess.Popen(['../../hostapd/hlr_auc_gw',
5525                                     '-m', fname, data],
5526                                    stdout=subprocess.PIPE)
5527             res = cmd.stdout.read().strip()
5528             cmd.stdout.close()
5529             logger.debug("hlr_auc_gw response: " + res)
5530             socket.sendto(res, self.client_address)
5531
5532     server.RequestHandlerClass = test_handler2
5533
5534     dev[0].select_network(id)
5535     server.handle_request()
5536     dev[0].wait_connected()
5537     dev[0].request("DISCONNECT")
5538     dev[0].wait_disconnected()
5539
5540 def test_eap_tls_sha512(dev, apdev, params):
5541     """EAP-TLS with SHA512 signature"""
5542     params = int_eap_server_params()
5543     params["ca_cert"] = "auth_serv/sha512-ca.pem"
5544     params["server_cert"] = "auth_serv/sha512-server.pem"
5545     params["private_key"] = "auth_serv/sha512-server.key"
5546     hostapd.add_ap(apdev[0], params)
5547
5548     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
5549                    identity="tls user sha512",
5550                    ca_cert="auth_serv/sha512-ca.pem",
5551                    client_cert="auth_serv/sha512-user.pem",
5552                    private_key="auth_serv/sha512-user.key",
5553                    scan_freq="2412")
5554     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
5555                    identity="tls user sha512",
5556                    ca_cert="auth_serv/sha512-ca.pem",
5557                    client_cert="auth_serv/sha384-user.pem",
5558                    private_key="auth_serv/sha384-user.key",
5559                    scan_freq="2412")
5560
5561 def test_eap_tls_sha384(dev, apdev, params):
5562     """EAP-TLS with SHA384 signature"""
5563     params = int_eap_server_params()
5564     params["ca_cert"] = "auth_serv/sha512-ca.pem"
5565     params["server_cert"] = "auth_serv/sha384-server.pem"
5566     params["private_key"] = "auth_serv/sha384-server.key"
5567     hostapd.add_ap(apdev[0], params)
5568
5569     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
5570                    identity="tls user sha512",
5571                    ca_cert="auth_serv/sha512-ca.pem",
5572                    client_cert="auth_serv/sha512-user.pem",
5573                    private_key="auth_serv/sha512-user.key",
5574                    scan_freq="2412")
5575     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
5576                    identity="tls user sha512",
5577                    ca_cert="auth_serv/sha512-ca.pem",
5578                    client_cert="auth_serv/sha384-user.pem",
5579                    private_key="auth_serv/sha384-user.key",
5580                    scan_freq="2412")
5581
5582 def test_ap_wpa2_eap_assoc_rsn(dev, apdev):
5583     """WPA2-Enterprise AP and association request RSN IE differences"""
5584     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
5585     hostapd.add_ap(apdev[0], params)
5586
5587     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap-11w")
5588     params["ieee80211w"] = "2"
5589     hostapd.add_ap(apdev[1], params)
5590
5591     # Success cases with optional RSN IE fields removed one by one
5592     tests = [ ("Normal wpa_supplicant assoc req RSN IE",
5593                "30140100000fac040100000fac040100000fac010000"),
5594               ("Extra PMKIDCount field in RSN IE",
5595                "30160100000fac040100000fac040100000fac0100000000"),
5596               ("Extra Group Management Cipher Suite in RSN IE",
5597                "301a0100000fac040100000fac040100000fac0100000000000fac06"),
5598               ("Extra undefined extension field in RSN IE",
5599                "301c0100000fac040100000fac040100000fac0100000000000fac061122"),
5600               ("RSN IE without RSN Capabilities",
5601                "30120100000fac040100000fac040100000fac01"),
5602               ("RSN IE without AKM", "300c0100000fac040100000fac04"),
5603               ("RSN IE without pairwise", "30060100000fac04"),
5604               ("RSN IE without group", "30020100") ]
5605     for title, ie in tests:
5606         logger.info(title)
5607         set_test_assoc_ie(dev[0], ie)
5608         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="GPSK",
5609                        identity="gpsk user",
5610                        password="abcdefghijklmnop0123456789abcdef",
5611                        scan_freq="2412")
5612         dev[0].request("REMOVE_NETWORK all")
5613         dev[0].wait_disconnected()
5614
5615     tests = [ ("Normal wpa_supplicant assoc req RSN IE",
5616                "30140100000fac040100000fac040100000fac01cc00"),
5617               ("Group management cipher included in assoc req RSN IE",
5618                "301a0100000fac040100000fac040100000fac01cc000000000fac06") ]
5619     for title, ie in tests:
5620         logger.info(title)
5621         set_test_assoc_ie(dev[0], ie)
5622         dev[0].connect("test-wpa2-eap-11w", key_mgmt="WPA-EAP", ieee80211w="1",
5623                        eap="GPSK", identity="gpsk user",
5624                        password="abcdefghijklmnop0123456789abcdef",
5625                        scan_freq="2412")
5626         dev[0].request("REMOVE_NETWORK all")
5627         dev[0].wait_disconnected()
5628
5629     tests = [ ("Invalid group cipher", "30060100000fac02", 41),
5630               ("Invalid pairwise cipher", "300c0100000fac040100000fac02", 42) ]
5631     for title, ie, status in tests:
5632         logger.info(title)
5633         set_test_assoc_ie(dev[0], ie)
5634         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="GPSK",
5635                        identity="gpsk user",
5636                        password="abcdefghijklmnop0123456789abcdef",
5637                        scan_freq="2412", wait_connect=False)
5638         ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"])
5639         if ev is None:
5640             raise Exception("Association rejection not reported")
5641         if "status_code=" + str(status) not in ev:
5642             raise Exception("Unexpected status code: " + ev)
5643         dev[0].request("REMOVE_NETWORK all")
5644         dev[0].dump_monitor()
5645
5646     tests = [ ("Management frame protection not enabled",
5647                "30140100000fac040100000fac040100000fac010000", 31),
5648               ("Unsupported management group cipher",
5649                "301a0100000fac040100000fac040100000fac01cc000000000fac0b", 31) ]
5650     for title, ie, status in tests:
5651         logger.info(title)
5652         set_test_assoc_ie(dev[0], ie)
5653         dev[0].connect("test-wpa2-eap-11w", key_mgmt="WPA-EAP", ieee80211w="1",
5654                        eap="GPSK", identity="gpsk user",
5655                        password="abcdefghijklmnop0123456789abcdef",
5656                        scan_freq="2412", wait_connect=False)
5657         ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"])
5658         if ev is None:
5659             raise Exception("Association rejection not reported")
5660         if "status_code=" + str(status) not in ev:
5661             raise Exception("Unexpected status code: " + ev)
5662         dev[0].request("REMOVE_NETWORK all")
5663         dev[0].dump_monitor()
5664
5665 def test_eap_tls_ext_cert_check(dev, apdev):
5666     """EAP-TLS and external server certification validation"""
5667     # With internal server certificate chain validation
5668     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
5669                         identity="tls user",
5670                         ca_cert="auth_serv/ca.pem",
5671                         client_cert="auth_serv/user.pem",
5672                         private_key="auth_serv/user.key",
5673                         phase1="tls_ext_cert_check=1", scan_freq="2412",
5674                         only_add_network=True)
5675     run_ext_cert_check(dev, apdev, id)
5676
5677 def test_eap_ttls_ext_cert_check(dev, apdev):
5678     """EAP-TTLS and external server certification validation"""
5679     # Without internal server certificate chain validation
5680     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
5681                         identity="pap user", anonymous_identity="ttls",
5682                         password="password", phase2="auth=PAP",
5683                         phase1="tls_ext_cert_check=1", scan_freq="2412",
5684                         only_add_network=True)
5685     run_ext_cert_check(dev, apdev, id)
5686
5687 def test_eap_peap_ext_cert_check(dev, apdev):
5688     """EAP-PEAP and external server certification validation"""
5689     # With internal server certificate chain validation
5690     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PEAP",
5691                         identity="user", anonymous_identity="peap",
5692                         ca_cert="auth_serv/ca.pem",
5693                         password="password", phase2="auth=MSCHAPV2",
5694                         phase1="tls_ext_cert_check=1", scan_freq="2412",
5695                         only_add_network=True)
5696     run_ext_cert_check(dev, apdev, id)
5697
5698 def test_eap_fast_ext_cert_check(dev, apdev):
5699     """EAP-FAST and external server certification validation"""
5700     check_eap_capa(dev[0], "FAST")
5701     # With internal server certificate chain validation
5702     dev[0].request("SET blob fast_pac_auth_ext ")
5703     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
5704                         identity="user", anonymous_identity="FAST",
5705                         ca_cert="auth_serv/ca.pem",
5706                         password="password", phase2="auth=GTC",
5707                         phase1="tls_ext_cert_check=1 fast_provisioning=2",
5708                         pac_file="blob://fast_pac_auth_ext",
5709                         scan_freq="2412",
5710                         only_add_network=True)
5711     run_ext_cert_check(dev, apdev, id)
5712
5713 def run_ext_cert_check(dev, apdev, net_id):
5714     check_ext_cert_check_support(dev[0])
5715     if not openssl_imported:
5716         raise HwsimSkip("OpenSSL python method not available")
5717
5718     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
5719     hapd = hostapd.add_ap(apdev[0], params)
5720
5721     dev[0].select_network(net_id)
5722     certs = {}
5723     while True:
5724         ev = dev[0].wait_event(["CTRL-EVENT-EAP-PEER-CERT",
5725                                 "CTRL-REQ-EXT_CERT_CHECK",
5726                                 "CTRL-EVENT-EAP-SUCCESS"], timeout=10)
5727         if ev is None:
5728             raise Exception("No peer server certificate event seen")
5729         if "CTRL-EVENT-EAP-PEER-CERT" in ev:
5730             depth = None
5731             cert = None
5732             vals = ev.split(' ')
5733             for v in vals:
5734                 if v.startswith("depth="):
5735                     depth = int(v.split('=')[1])
5736                 elif v.startswith("cert="):
5737                     cert = v.split('=')[1]
5738             if depth is not None and cert:
5739                 certs[depth] = binascii.unhexlify(cert)
5740         elif "CTRL-EVENT-EAP-SUCCESS" in ev:
5741             raise Exception("Unexpected EAP-Success")
5742         elif "CTRL-REQ-EXT_CERT_CHECK" in ev:
5743             id = ev.split(':')[0].split('-')[-1]
5744             break
5745     if 0 not in certs:
5746         raise Exception("Server certificate not received")
5747     if 1 not in certs:
5748         raise Exception("Server certificate issuer not received")
5749
5750     cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1,
5751                                            certs[0])
5752     cn = cert.get_subject().commonName
5753     logger.info("Server certificate CN=" + cn)
5754
5755     issuer = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1,
5756                                              certs[1])
5757     icn = issuer.get_subject().commonName
5758     logger.info("Issuer certificate CN=" + icn)
5759
5760     if cn != "server.w1.fi":
5761         raise Exception("Unexpected server certificate CN: " + cn)
5762     if icn != "Root CA":
5763         raise Exception("Unexpected server certificate issuer CN: " + icn)
5764
5765     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=0.1)
5766     if ev:
5767         raise Exception("Unexpected EAP-Success before external check result indication")
5768
5769     dev[0].request("CTRL-RSP-EXT_CERT_CHECK-" + id + ":good")
5770     dev[0].wait_connected()
5771
5772     dev[0].request("DISCONNECT")
5773     dev[0].wait_disconnected()
5774     if "FAIL" in dev[0].request("PMKSA_FLUSH"):
5775         raise Exception("PMKSA_FLUSH failed")
5776     dev[0].request("SET blob fast_pac_auth_ext ")
5777     dev[0].request("RECONNECT")
5778
5779     ev = dev[0].wait_event(["CTRL-REQ-EXT_CERT_CHECK"], timeout=10)
5780     if ev is None:
5781         raise Exception("No peer server certificate event seen (2)")
5782     id = ev.split(':')[0].split('-')[-1]
5783     dev[0].request("CTRL-RSP-EXT_CERT_CHECK-" + id + ":bad")
5784     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
5785     if ev is None:
5786         raise Exception("EAP-Failure not reported")
5787     dev[0].request("REMOVE_NETWORK all")
5788     dev[0].wait_disconnected()
5789
5790 def test_eap_tls_errors(dev, apdev):
5791     """EAP-TLS error cases"""
5792     params = int_eap_server_params()
5793     params['fragment_size'] = '100'
5794     hostapd.add_ap(apdev[0], params)
5795     with alloc_fail(dev[0], 1,
5796                     "eap_peer_tls_reassemble_fragment"):
5797         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
5798                        identity="tls user", ca_cert="auth_serv/ca.pem",
5799                        client_cert="auth_serv/user.pem",
5800                        private_key="auth_serv/user.key",
5801                        wait_connect=False, scan_freq="2412")
5802         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
5803         dev[0].request("REMOVE_NETWORK all")
5804         dev[0].wait_disconnected()
5805
5806     with alloc_fail(dev[0], 1, "eap_tls_init"):
5807         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
5808                        identity="tls user", ca_cert="auth_serv/ca.pem",
5809                        client_cert="auth_serv/user.pem",
5810                        private_key="auth_serv/user.key",
5811                        wait_connect=False, scan_freq="2412")
5812         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
5813         dev[0].request("REMOVE_NETWORK all")
5814         dev[0].wait_disconnected()
5815
5816     with alloc_fail(dev[0], 1, "eap_peer_tls_ssl_init"):
5817         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
5818                        identity="tls user", ca_cert="auth_serv/ca.pem",
5819                        client_cert="auth_serv/user.pem",
5820                        private_key="auth_serv/user.key",
5821                        engine="1",
5822                        wait_connect=False, scan_freq="2412")
5823         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
5824         ev = dev[0].wait_event(["CTRL-REQ-PIN"], timeout=5)
5825         if ev is None:
5826             raise Exception("No CTRL-REQ-PIN seen")
5827         dev[0].request("REMOVE_NETWORK all")
5828         dev[0].wait_disconnected()
5829
5830     tests = [ "eap_peer_tls_derive_key;eap_tls_success",
5831               "eap_peer_tls_derive_session_id;eap_tls_success",
5832               "eap_tls_getKey",
5833               "eap_tls_get_emsk",
5834               "eap_tls_get_session_id" ]
5835     for func in tests:
5836         with alloc_fail(dev[0], 1, func):
5837             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
5838                            identity="tls user", ca_cert="auth_serv/ca.pem",
5839                            client_cert="auth_serv/user.pem",
5840                            private_key="auth_serv/user.key",
5841                            erp="1",
5842                            wait_connect=False, scan_freq="2412")
5843             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
5844             dev[0].request("REMOVE_NETWORK all")
5845             dev[0].wait_disconnected()
5846
5847     with alloc_fail(dev[0], 1, "eap_unauth_tls_init"):
5848         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="UNAUTH-TLS",
5849                        identity="unauth-tls", ca_cert="auth_serv/ca.pem",
5850                        wait_connect=False, scan_freq="2412")
5851         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
5852         dev[0].request("REMOVE_NETWORK all")
5853         dev[0].wait_disconnected()
5854
5855     with alloc_fail(dev[0], 1, "eap_peer_tls_ssl_init;eap_unauth_tls_init"):
5856         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="UNAUTH-TLS",
5857                        identity="unauth-tls", ca_cert="auth_serv/ca.pem",
5858                        wait_connect=False, scan_freq="2412")
5859         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
5860         dev[0].request("REMOVE_NETWORK all")
5861         dev[0].wait_disconnected()
5862
5863     with alloc_fail(dev[0], 1, "eap_wfa_unauth_tls_init"):
5864         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP",
5865                        eap="WFA-UNAUTH-TLS",
5866                        identity="osen@example.com", ca_cert="auth_serv/ca.pem",
5867                        wait_connect=False, scan_freq="2412")
5868         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
5869         dev[0].request("REMOVE_NETWORK all")
5870         dev[0].wait_disconnected()
5871
5872     with alloc_fail(dev[0], 1, "eap_peer_tls_ssl_init;eap_wfa_unauth_tls_init"):
5873         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP",
5874                        eap="WFA-UNAUTH-TLS",
5875                        identity="osen@example.com", ca_cert="auth_serv/ca.pem",
5876                        wait_connect=False, scan_freq="2412")
5877         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
5878         dev[0].request("REMOVE_NETWORK all")
5879         dev[0].wait_disconnected()
5880
5881 def test_ap_wpa2_eap_status(dev, apdev):
5882     """EAP state machine status information"""
5883     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
5884     hostapd.add_ap(apdev[0], params)
5885     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PEAP",
5886                    identity="cert user",
5887                    ca_cert="auth_serv/ca.pem", phase2="auth=TLS",
5888                    ca_cert2="auth_serv/ca.pem",
5889                    client_cert2="auth_serv/user.pem",
5890                    private_key2="auth_serv/user.key",
5891                    scan_freq="2412", wait_connect=False)
5892     success = False
5893     states = []
5894     method_states = []
5895     decisions = []
5896     req_methods = []
5897     selected_methods = []
5898     for i in range(100000):
5899         s = dev[0].get_status(extra="VERBOSE")
5900         if 'EAP state' in s:
5901             state = s['EAP state']
5902             if state:
5903                 if state not in states:
5904                     states.append(state)
5905                 if state == "SUCCESS":
5906                     success = True
5907                     break
5908         if 'methodState' in s:
5909             val = s['methodState']
5910             if val not in method_states:
5911                 method_states.append(val)
5912         if 'decision' in s:
5913             val = s['decision']
5914             if val not in decisions:
5915                 decisions.append(val)
5916         if 'reqMethod' in s:
5917             val = s['reqMethod']
5918             if val not in req_methods:
5919                 req_methods.append(val)
5920         if 'selectedMethod' in s:
5921             val = s['selectedMethod']
5922             if val not in selected_methods:
5923                 selected_methods.append(val)
5924     logger.info("Iterations: %d" % i)
5925     logger.info("EAP states: " + str(states))
5926     logger.info("methodStates: " + str(method_states))
5927     logger.info("decisions: " + str(decisions))
5928     logger.info("reqMethods: " + str(req_methods))
5929     logger.info("selectedMethods: " + str(selected_methods))
5930     if not success:
5931         raise Exception("EAP did not succeed")
5932     dev[0].wait_connected()
5933     dev[0].request("REMOVE_NETWORK all")
5934     dev[0].wait_disconnected()
5935
5936 def test_ap_wpa2_eap_gpsk_ptk_rekey_ap(dev, apdev):
5937     """WPA2-Enterprise with EAP-GPSK and PTK rekey enforced by AP"""
5938     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
5939     params['wpa_ptk_rekey'] = '2'
5940     hapd = hostapd.add_ap(apdev[0], params)
5941     id = eap_connect(dev[0], hapd, "GPSK", "gpsk user",
5942                      password="abcdefghijklmnop0123456789abcdef")
5943     ev = dev[0].wait_event(["WPA: Key negotiation completed"])
5944     if ev is None:
5945         raise Exception("PTK rekey timed out")
5946     hwsim_utils.test_connectivity(dev[0], hapd)
5947
5948 def test_ap_wpa2_eap_wildcard_ssid(dev, apdev):
5949     """WPA2-Enterprise connection using EAP-GPSK and wildcard SSID"""
5950     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
5951     hapd = hostapd.add_ap(apdev[0], params)
5952     dev[0].connect(bssid=apdev[0]['bssid'], key_mgmt="WPA-EAP", eap="GPSK",
5953                    identity="gpsk user",
5954                    password="abcdefghijklmnop0123456789abcdef",
5955                    scan_freq="2412")