1 # -*- coding: utf-8 -*-
2 # WPA2-Enterprise tests
3 # Copyright (c) 2013-2019, 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 signal
16 import socket
17 try:
18     import SocketServer
19 except ImportError:
20     import socketserver as SocketServer
21 import struct
22 import tempfile
23 
24 import hwsim_utils
25 from hwsim import HWSimRadio
26 import hostapd
27 from utils import *
28 from wpasupplicant import WpaSupplicant
29 from test_ap_psk import check_mib, find_wpas_process, read_process_memory, verify_not_present, get_key_locations, set_test_assoc_ie
30 
31 try:
32     import OpenSSL
33     openssl_imported = True
34 except ImportError:
35     openssl_imported = False
36 
37 def check_hlr_auc_gw_support():
38     if not os.path.exists("/tmp/hlr_auc_gw.sock"):
39         raise HwsimSkip("No hlr_auc_gw available")
40 
41 def check_eap_capa(dev, method):
42     res = dev.get_capability("eap")
43     if method not in res:
44         raise HwsimSkip("EAP method %s not supported in the build" % method)
45 
46 def check_subject_match_support(dev):
47     tls = dev.request("GET tls_library")
48     if not tls.startswith("OpenSSL") and not tls.startswith("wolfSSL"):
49         raise HwsimSkip("subject_match not supported with this TLS library: " + tls)
50 
51 def check_check_cert_subject_support(dev):
52     tls = dev.request("GET tls_library")
53     if not tls.startswith("OpenSSL") and not tls.startswith("wolfSSL"):
54         raise HwsimSkip("check_cert_subject not supported with this TLS library: " + tls)
55 
56 def check_altsubject_match_support(dev):
57     tls = dev.request("GET tls_library")
58     if not tls.startswith("OpenSSL") and not tls.startswith("wolfSSL"):
59         raise HwsimSkip("altsubject_match not supported with this TLS library: " + tls)
60 
61 def check_domain_match(dev):
62     tls = dev.request("GET tls_library")
63     if tls.startswith("internal"):
64         raise HwsimSkip("domain_match not supported with this TLS library: " + tls)
65 
66 def check_domain_suffix_match(dev):
67     tls = dev.request("GET tls_library")
68     if tls.startswith("internal"):
69         raise HwsimSkip("domain_suffix_match not supported with this TLS library: " + tls)
70 
71 def check_domain_match_full(dev):
72     tls = dev.request("GET tls_library")
73     if not tls.startswith("OpenSSL") and not tls.startswith("wolfSSL"):
74         raise HwsimSkip("domain_suffix_match requires full match with this TLS library: " + tls)
75 
76 def check_cert_probe_support(dev):
77     tls = dev.request("GET tls_library")
78     if not tls.startswith("OpenSSL") and not tls.startswith("internal"):
79         raise HwsimSkip("Certificate probing not supported with this TLS library: " + tls)
80 
81 def check_ext_cert_check_support(dev):
82     tls = dev.request("GET tls_library")
83     if not tls.startswith("OpenSSL"):
84         raise HwsimSkip("ext_cert_check not supported with this TLS library: " + tls)
85 
86 def check_ocsp_support(dev):
87     tls = dev.request("GET tls_library")
88     #if tls.startswith("internal"):
89     #    raise HwsimSkip("OCSP not supported with this TLS library: " + tls)
90     #if "BoringSSL" in tls:
91     #    raise HwsimSkip("OCSP not supported with this TLS library: " + tls)
92     #if tls.startswith("wolfSSL"):
93     #    raise HwsimSkip("OCSP not supported with this TLS library: " + tls)
94 
95 def check_pkcs5_v15_support(dev):
96     tls = dev.request("GET tls_library")
97     if "BoringSSL" in tls or "GnuTLS" in tls:
98         raise HwsimSkip("PKCS#5 v1.5 not supported with this TLS library: " + tls)
99 
100 def check_tls13_support(dev):
101     tls = dev.request("GET tls_library")
102     ok = ['run=OpenSSL 1.1.1', 'run=OpenSSL 3.', 'wolfSSL']
103     for s in ok:
104         if s in tls:
105             return
106     raise HwsimSkip("TLS v1.3 not supported")
107 
108 def check_ocsp_multi_support(dev):
109     tls = dev.request("GET tls_library")
110     if not tls.startswith("internal"):
111         raise HwsimSkip("OCSP-multi not supported with this TLS library: " + tls)
112     as_hapd = hostapd.Hostapd("as")
113     res = as_hapd.request("GET tls_library")
114     del as_hapd
115     if not res.startswith("internal"):
116         raise HwsimSkip("Authentication server does not support ocsp_multi")
117 
118 def check_pkcs12_support(dev):
119     tls = dev.request("GET tls_library")
120     #if tls.startswith("internal"):
121     #    raise HwsimSkip("PKCS#12 not supported with this TLS library: " + tls)
122     if tls.startswith("wolfSSL"):
123         raise HwsimSkip("PKCS#12 not supported with this TLS library: " + tls)
124 
125 def check_dh_dsa_support(dev):
126     tls = dev.request("GET tls_library")
127     if tls.startswith("internal"):
128         raise HwsimSkip("DH DSA not supported with this TLS library: " + tls)
129 
130 def check_ec_support(dev):
131     tls = dev.request("GET tls_library")
132     if tls.startswith("internal"):
133         raise HwsimSkip("EC not supported with this TLS library: " + tls)
134 
135 def read_pem(fname, decode=True):
136     with open(fname, "r") as f:
137         lines = f.readlines()
138         copy = False
139         cert = ""
140         for l in lines:
141             if "-----END" in l:
142                 if not decode:
143                     cert = cert + l
144                 break
145             if copy:
146                 cert = cert + l
147             if "-----BEGIN" in l:
148                 copy = True
149                 if not decode:
150                     cert = cert + l
151     if decode:
152         return base64.b64decode(cert)
153     return cert.encode()
154 
155 def eap_connect(dev, hapd, method, identity, raw_identity=None,
156                 sha256=False, expect_failure=False, local_error_report=False,
157                 maybe_local_error=False, report_failure=False,
158                 expect_cert_error=None, sha384=False, **kwargs):
159     id = dev.connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256 WPA-EAP-SHA384",
160                      eap=method, identity=identity, raw_identity=raw_identity,
161                      wait_connect=False, scan_freq="2412", ieee80211w="1",
162                      **kwargs)
163     eap_check_auth(dev, method, True, sha256=sha256,
164                    expect_failure=expect_failure,
165                    local_error_report=local_error_report,
166                    maybe_local_error=maybe_local_error,
167                    report_failure=report_failure,
168                    expect_cert_error=expect_cert_error,
169                    sha384=sha384)
170     if expect_failure:
171         return id
172     if hapd:
173         ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=5)
174         if ev is None:
175             raise Exception("No connection event received from hostapd")
176     return id
177 
178 def eap_check_auth(dev, method, initial, rsn=True, sha256=False,
179                    expect_failure=False, local_error_report=False,
180                    maybe_local_error=False, report_failure=False,
181                    expect_cert_error=None, sha384=False):
182     ev = dev.wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
183     if ev is None:
184         raise Exception("Association and EAP start timed out")
185     ev = dev.wait_event(["CTRL-EVENT-EAP-METHOD",
186                          "CTRL-EVENT-EAP-FAILURE"], timeout=10)
187     if ev is None:
188         raise Exception("EAP method selection timed out")
189     if "CTRL-EVENT-EAP-FAILURE" in ev:
190         if maybe_local_error:
191             return
192         raise Exception("Could not select EAP method")
193     if method not in ev:
194         raise Exception("Unexpected EAP method")
195     if expect_cert_error is not None:
196         ev = dev.wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR",
197                              "CTRL-EVENT-EAP-FAILURE",
198                              "CTRL-EVENT-EAP-SUCCESS"], timeout=5)
199         if ev is None or "reason=%d " % expect_cert_error not in ev:
200             raise Exception("Expected certificate error not reported")
201     if expect_failure:
202         ev = dev.wait_event(["CTRL-EVENT-EAP-FAILURE",
203                              "CTRL-EVENT-EAP-SUCCESS"], timeout=5)
204         if ev is None:
205             raise Exception("EAP failure timed out")
206         if "CTRL-EVENT-EAP-SUCCESS" in ev:
207             raise Exception("Unexpected EAP success")
208         ev = dev.wait_disconnected(timeout=10)
209         if maybe_local_error and "locally_generated=1" in ev:
210             return
211         if not local_error_report:
212             if "reason=23" not in ev:
213                 raise Exception("Proper reason code for disconnection not reported: " + ev)
214         return
215     if report_failure:
216         ev = dev.wait_event(["CTRL-EVENT-EAP-SUCCESS",
217                              "CTRL-EVENT-EAP-FAILURE"], timeout=10)
218         if ev is None:
219             raise Exception("EAP success timed out")
220         if "CTRL-EVENT-EAP-SUCCESS" not in ev:
221             raise Exception("EAP failed")
222     else:
223         ev = dev.wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
224         if ev is None:
225             raise Exception("EAP success timed out")
226 
227     if initial:
228         ev = dev.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
229     else:
230         ev = dev.wait_event(["WPA: Key negotiation completed"], timeout=10)
231     if ev is None:
232         raise Exception("Association with the AP timed out")
233     status = dev.get_status()
234     if status["wpa_state"] != "COMPLETED":
235         raise Exception("Connection not completed")
236 
237     if status["suppPortStatus"] != "Authorized":
238         raise Exception("Port not authorized")
239     if "selectedMethod" not in status:
240         logger.info("Status: " + str(status))
241         raise Exception("No selectedMethod in status")
242     if method not in status["selectedMethod"]:
243         raise Exception("Incorrect EAP method status")
244     if sha256:
245         e = "WPA2-EAP-SHA256"
246     elif sha384:
247         e = "WPA2-EAP-SHA384"
248     elif rsn:
249         e = "WPA2/IEEE 802.1X/EAP"
250     else:
251         e = "WPA/IEEE 802.1X/EAP"
252     if status["key_mgmt"] != e:
253         raise Exception("Unexpected key_mgmt status: " + status["key_mgmt"])
254     return status
255 
256 def eap_reauth(dev, method, rsn=True, sha256=False, expect_failure=False, sha384=False):
257     dev.request("REAUTHENTICATE")
258     return eap_check_auth(dev, method, False, rsn=rsn, sha256=sha256,
259                           expect_failure=expect_failure, sha384=sha384)
260 
261 def test_ap_wpa2_eap_sim(dev, apdev):
262     """WPA2-Enterprise connection using EAP-SIM"""
263     check_hlr_auc_gw_support()
264     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
265     hapd = hostapd.add_ap(apdev[0], params)
266     eap_connect(dev[0], hapd, "SIM", "1232010000000000",
267                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581")
268     hwsim_utils.test_connectivity(dev[0], hapd)
269     eap_reauth(dev[0], "SIM")
270 
271     eap_connect(dev[1], hapd, "SIM", "1232010000000001",
272                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581")
273     eap_connect(dev[2], hapd, "SIM", "1232010000000002",
274                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
275                 expect_failure=True)
276 
277     logger.info("Negative test with incorrect key")
278     dev[0].request("REMOVE_NETWORK all")
279     eap_connect(dev[0], hapd, "SIM", "1232010000000000",
280                 password="ffdca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
281                 expect_failure=True)
282 
283     logger.info("Invalid GSM-Milenage key")
284     dev[0].request("REMOVE_NETWORK all")
285     eap_connect(dev[0], hapd, "SIM", "1232010000000000",
286                 password="ffdca4eda45b53cf0f12d7c9c3bc6a",
287                 expect_failure=True)
288 
289     logger.info("Invalid GSM-Milenage key(2)")
290     dev[0].request("REMOVE_NETWORK all")
291     eap_connect(dev[0], hapd, "SIM", "1232010000000000",
292                 password="ffdca4eda45b53cf0f12d7c9c3bc6a8q:cb9cccc4b9258e6dca4760379fb82581",
293                 expect_failure=True)
294 
295     logger.info("Invalid GSM-Milenage key(3)")
296     dev[0].request("REMOVE_NETWORK all")
297     eap_connect(dev[0], hapd, "SIM", "1232010000000000",
298                 password="ffdca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb8258q",
299                 expect_failure=True)
300 
301     logger.info("Invalid GSM-Milenage key(4)")
302     dev[0].request("REMOVE_NETWORK all")
303     eap_connect(dev[0], hapd, "SIM", "1232010000000000",
304                 password="ffdca4eda45b53cf0f12d7c9c3bc6a89qcb9cccc4b9258e6dca4760379fb82581",
305                 expect_failure=True)
306 
307     logger.info("Missing key configuration")
308     dev[0].request("REMOVE_NETWORK all")
309     eap_connect(dev[0], hapd, "SIM", "1232010000000000",
310                 expect_failure=True)
311 
312 def test_ap_wpa2_eap_sim_imsi_identity(dev, apdev, params):
313     """WPA2-Enterprise connection using EAP-SIM and imsi_identity"""
314     check_hlr_auc_gw_support()
315     prefix = params['prefix']
316     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
317     hapd = hostapd.add_ap(apdev[0], params)
318     check_imsi_privacy_support(hapd)
319 
320     imsi = "232010000000000"
321     realm = "wlan.mnc232.mcc02.3gppnetwork.org"
322     method_id = '1'
323     permanent_id = method_id + imsi + '@' + realm
324     # RSA-OAEP(permanent_id)
325     perm_id = prefix + '.permanent-id'
326     enc_id = prefix + '.enc-permanent-id'
327     with open(perm_id, 'w') as f:
328         f.write(permanent_id)
329     pubkey = prefix + ".cert-pub.pem"
330     subprocess.check_call(["openssl", "x509",
331                            "-in", "auth_serv/imsi-privacy-cert.pem",
332                            "-pubkey", "-noout",
333                            "-out", pubkey])
334     subprocess.check_call(["openssl", "pkeyutl",
335                            "-inkey", pubkey, "-pubin", "-in", perm_id,
336                            "-pkeyopt", "rsa_padding_mode:oaep",
337                            "-pkeyopt", "rsa_oaep_md:sha256",
338                            "-encrypt",
339                            "-out", enc_id])
340     with open(enc_id, 'rb') as f:
341         data = f.read()
342         encrypted_id = base64.b64encode(data).decode()
343         if len(encrypted_id) != 344:
344             raise Exception("Unexpected length of the base64 encoded identity: " + b64)
345     eap_connect(dev[0], hapd, "SIM", identity=None,
346                 raw_identity='P"\\0' + encrypted_id + '"',
347                 anonymous_identity=method_id + "anonymous@" + realm,
348                 imsi_identity=permanent_id,
349                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581")
350     eap_reauth(dev[0], "SIM")
351 
352 def test_ap_wpa2_eap_sim_imsi_privacy_key(dev, apdev):
353     """WPA2-Enterprise connection using EAP-SIM and imsi_privacy_cert"""
354     check_imsi_privacy_support(dev[0])
355     check_hlr_auc_gw_support()
356     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
357     hapd = hostapd.add_ap(apdev[0], params)
358     check_imsi_privacy_support(hapd)
359 
360     eap_connect(dev[0], hapd, "SIM",
361                 "1232010000000000@wlan.mnc232.mcc02.3gppnetwork.org",
362                 imsi_privacy_cert="auth_serv/imsi-privacy-cert.pem",
363                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581")
364     eap_reauth(dev[0], "SIM")
365 
366 def test_ap_wpa2_eap_sim_imsi_privacy_attr(dev, apdev):
367     """WPA2-Enterprise connection using EAP-SIM and imsi_privacy_cert/attr"""
368     check_imsi_privacy_support(dev[0])
369     check_hlr_auc_gw_support()
370     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
371     hapd = hostapd.add_ap(apdev[0], params)
372     check_imsi_privacy_support(hapd)
373 
374     eap_connect(dev[0], hapd, "SIM",
375                 "1232010000000000@wlan.mnc232.mcc02.3gppnetwork.org",
376                 imsi_privacy_cert="auth_serv/imsi-privacy-cert.pem",
377                 imsi_privacy_attr="name=value",
378                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581")
379 
380 def test_ap_wpa2_eap_sim_sql(dev, apdev, params):
381     """WPA2-Enterprise connection using EAP-SIM (SQL)"""
382     check_hlr_auc_gw_support()
383     try:
384         import sqlite3
385     except ImportError:
386         raise HwsimSkip("No sqlite3 module available")
387     con = sqlite3.connect(os.path.join(params['logdir'], "hostapd.db"))
388     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
389     params['auth_server_port'] = "1814"
390     hapd = hostapd.add_ap(apdev[0], params)
391     eap_connect(dev[0], hapd, "SIM", "1232010000000000",
392                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581")
393 
394     logger.info("SIM fast re-authentication")
395     eap_reauth(dev[0], "SIM")
396     hapd.wait_4way_hs()
397 
398     logger.info("SIM full auth with pseudonym")
399     with con:
400         cur = con.cursor()
401         cur.execute("DELETE FROM reauth WHERE permanent='1232010000000000'")
402     eap_reauth(dev[0], "SIM")
403     hapd.wait_4way_hs()
404 
405     logger.info("SIM full auth with permanent identity")
406     with con:
407         cur = con.cursor()
408         cur.execute("DELETE FROM reauth WHERE permanent='1232010000000000'")
409         cur.execute("DELETE FROM pseudonyms WHERE permanent='1232010000000000'")
410     eap_reauth(dev[0], "SIM")
411     hapd.wait_4way_hs()
412 
413     logger.info("SIM reauth with mismatching MK")
414     with con:
415         cur = con.cursor()
416         cur.execute("UPDATE reauth SET mk='0000000000000000000000000000000000000000' WHERE permanent='1232010000000000'")
417     eap_reauth(dev[0], "SIM", expect_failure=True)
418     dev[0].request("REMOVE_NETWORK all")
419 
420     eap_connect(dev[0], hapd, "SIM", "1232010000000000",
421                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581")
422     with con:
423         cur = con.cursor()
424         cur.execute("UPDATE reauth SET counter='10' WHERE permanent='1232010000000000'")
425     eap_reauth(dev[0], "SIM")
426     hapd.wait_4way_hs()
427     with con:
428         cur = con.cursor()
429         cur.execute("UPDATE reauth SET counter='10' WHERE permanent='1232010000000000'")
430     logger.info("SIM reauth with mismatching counter")
431     eap_reauth(dev[0], "SIM")
432     dev[0].request("REMOVE_NETWORK all")
433     dev[0].wait_disconnected()
434     hapd.wait_sta_disconnect()
435 
436     eap_connect(dev[0], hapd, "SIM", "1232010000000000",
437                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581")
438     with con:
439         cur = con.cursor()
440         cur.execute("UPDATE reauth SET counter='1001' WHERE permanent='1232010000000000'")
441     logger.info("SIM reauth with max reauth count reached")
442     eap_reauth(dev[0], "SIM")
443     hapd.wait_4way_hs()
444 
445 def test_ap_wpa2_eap_sim_sql_fallback_to_pseudonym(dev, apdev, params):
446     """WPA2-Enterprise connection using EAP-SIM (SQL) and fallback to pseudonym without SIM-Identity"""
447     run_ap_wpa2_eap_sim_sql_fallback_to_pseudonym(dev, apdev, params, 7)
448 
449 def run_ap_wpa2_eap_sim_sql_fallback_to_pseudonym(dev, apdev, params,
450                                                   eap_sim_id):
451     check_hlr_auc_gw_support()
452     db = os.path.join(params['logdir'], "hostapd.db")
453     params = int_eap_server_params()
454     params['eap_sim_db'] = 'unix:/tmp/hlr_auc_gw.sock db=' + db
455     params['eap_sim_aka_fast_reauth_limit'] = '0'
456     params['eap_sim_id'] = str(eap_sim_id)
457     hapd = hostapd.add_ap(apdev[0], params)
458     eap_connect(dev[0], hapd, "SIM", "1232010000000000",
459                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581")
460 
461     logger.info("SIM fallback from fast re-auth to full auth with pseudonym")
462     eap_reauth(dev[0], "SIM")
463 
464 def test_ap_wpa2_eap_sim_config(dev, apdev):
465     """EAP-SIM configuration options"""
466     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
467     hapd = hostapd.add_ap(apdev[0], params)
468     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="SIM",
469                    identity="1232010000000000",
470                    password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
471                    phase1="sim_min_num_chal=1",
472                    wait_connect=False, scan_freq="2412")
473     ev = dev[0].wait_event(["EAP: Failed to initialize EAP method: vendor 0 method 18 (SIM)"], timeout=10)
474     if ev is None:
475         raise Exception("No EAP error message seen")
476     dev[0].request("REMOVE_NETWORK all")
477 
478     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="SIM",
479                    identity="1232010000000000",
480                    password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
481                    phase1="sim_min_num_chal=4",
482                    wait_connect=False, scan_freq="2412")
483     ev = dev[0].wait_event(["EAP: Failed to initialize EAP method: vendor 0 method 18 (SIM)"], timeout=10)
484     if ev is None:
485         raise Exception("No EAP error message seen (2)")
486     dev[0].request("REMOVE_NETWORK all")
487 
488     eap_connect(dev[0], hapd, "SIM", "1232010000000000",
489                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
490                 phase1="sim_min_num_chal=2")
491     eap_connect(dev[1], hapd, "SIM", "1232010000000000",
492                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
493                 anonymous_identity="345678")
494 
495 def test_ap_wpa2_eap_sim_id_0(dev, apdev):
496     """WPA2-Enterprise connection using EAP-SIM (no pseudonym or reauth)"""
497     run_ap_wpa2_eap_sim_id(dev, apdev, 0)
498 
499 def test_ap_wpa2_eap_sim_id_1(dev, apdev):
500     """WPA2-Enterprise connection using EAP-SIM (pseudonym, no reauth)"""
501     run_ap_wpa2_eap_sim_id(dev, apdev, 1)
502 
503 def test_ap_wpa2_eap_sim_id_2(dev, apdev):
504     """WPA2-Enterprise connection using EAP-SIM (no pseudonym, reauth)"""
505     run_ap_wpa2_eap_sim_id(dev, apdev, 2)
506 
507 def test_ap_wpa2_eap_sim_id_3(dev, apdev):
508     """WPA2-Enterprise connection using EAP-SIM (pseudonym and reauth)"""
509     run_ap_wpa2_eap_sim_id(dev, apdev, 3)
510 
511 def test_ap_wpa2_eap_sim_id_4(dev, apdev):
512     """WPA2-Enterprise connection using EAP-SIM (no pseudonym or reauth)"""
513     run_ap_wpa2_eap_sim_id(dev, apdev, 4)
514 
515 def test_ap_wpa2_eap_sim_id_5(dev, apdev):
516     """WPA2-Enterprise connection using EAP-SIM (pseudonym, no reauth)"""
517     run_ap_wpa2_eap_sim_id(dev, apdev, 5)
518 
519 def test_ap_wpa2_eap_sim_id_6(dev, apdev):
520     """WPA2-Enterprise connection using EAP-SIM (no pseudonym, reauth)"""
521     run_ap_wpa2_eap_sim_id(dev, apdev, 6)
522 
523 def test_ap_wpa2_eap_sim_id_7(dev, apdev):
524     """WPA2-Enterprise connection using EAP-SIM (pseudonym and reauth)"""
525     run_ap_wpa2_eap_sim_id(dev, apdev, 7)
526 
527 def run_ap_wpa2_eap_sim_id(dev, apdev, eap_sim_id):
528     check_hlr_auc_gw_support()
529     params = int_eap_server_params()
530     params['eap_sim_id'] = str(eap_sim_id)
531     params['eap_sim_db'] = 'unix:/tmp/hlr_auc_gw.sock'
532     hapd = hostapd.add_ap(apdev[0], params)
533     eap_connect(dev[0], hapd, "SIM", "1232010000000000",
534                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581")
535     eap_reauth(dev[0], "SIM")
536 
537 def test_ap_wpa2_eap_sim_ext(dev, apdev):
538     """WPA2-Enterprise connection using EAP-SIM and external GSM auth"""
539     try:
540         _test_ap_wpa2_eap_sim_ext(dev, apdev)
541     finally:
542         dev[0].request("SET external_sim 0")
543 
544 def _test_ap_wpa2_eap_sim_ext(dev, apdev):
545     check_hlr_auc_gw_support()
546     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
547     hostapd.add_ap(apdev[0], params)
548     dev[0].request("SET external_sim 1")
549     id = dev[0].connect("test-wpa2-eap", eap="SIM", key_mgmt="WPA-EAP",
550                         identity="1232010000000000",
551                         wait_connect=False, scan_freq="2412")
552     ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=15)
553     if ev is None:
554         raise Exception("Network connected timed out")
555 
556     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
557     if ev is None:
558         raise Exception("Wait for external SIM processing request timed out")
559     p = ev.split(':', 2)
560     if p[1] != "GSM-AUTH":
561         raise Exception("Unexpected CTRL-REQ-SIM type")
562     rid = p[0].split('-')[3]
563 
564     # IK:CK:RES
565     resp = "00112233445566778899aabbccddeeff:00112233445566778899aabbccddeeff:0011223344"
566     # This will fail during processing, but the ctrl_iface command succeeds
567     dev[0].request("CTRL-RSP-SIM-" + rid + ":UMTS-AUTH:" + resp)
568     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
569     if ev is None:
570         raise Exception("EAP failure not reported")
571     dev[0].request("DISCONNECT")
572     dev[0].wait_disconnected()
573     time.sleep(0.1)
574 
575     dev[0].select_network(id, freq="2412")
576     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
577     if ev is None:
578         raise Exception("Wait for external SIM processing request timed out")
579     p = ev.split(':', 2)
580     if p[1] != "GSM-AUTH":
581         raise Exception("Unexpected CTRL-REQ-SIM type")
582     rid = p[0].split('-')[3]
583     # This will fail during GSM auth validation
584     if "OK" not in dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:q"):
585         raise Exception("CTRL-RSP-SIM failed")
586     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
587     if ev is None:
588         raise Exception("EAP failure not reported")
589     dev[0].request("DISCONNECT")
590     dev[0].wait_disconnected()
591     time.sleep(0.1)
592 
593     dev[0].select_network(id, freq="2412")
594     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
595     if ev is None:
596         raise Exception("Wait for external SIM processing request timed out")
597     p = ev.split(':', 2)
598     if p[1] != "GSM-AUTH":
599         raise Exception("Unexpected CTRL-REQ-SIM type")
600     rid = p[0].split('-')[3]
601     # This will fail during GSM auth validation
602     if "OK" not in dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:34"):
603         raise Exception("CTRL-RSP-SIM failed")
604     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
605     if ev is None:
606         raise Exception("EAP failure not reported")
607     dev[0].request("DISCONNECT")
608     dev[0].wait_disconnected()
609     time.sleep(0.1)
610 
611     dev[0].select_network(id, freq="2412")
612     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
613     if ev is None:
614         raise Exception("Wait for external SIM processing request timed out")
615     p = ev.split(':', 2)
616     if p[1] != "GSM-AUTH":
617         raise Exception("Unexpected CTRL-REQ-SIM type")
618     rid = p[0].split('-')[3]
619     # This will fail during GSM auth validation
620     if "OK" not in dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:0011223344556677"):
621         raise Exception("CTRL-RSP-SIM failed")
622     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
623     if ev is None:
624         raise Exception("EAP failure not reported")
625     dev[0].request("DISCONNECT")
626     dev[0].wait_disconnected()
627     time.sleep(0.1)
628 
629     dev[0].select_network(id, freq="2412")
630     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
631     if ev is None:
632         raise Exception("Wait for external SIM processing request timed out")
633     p = ev.split(':', 2)
634     if p[1] != "GSM-AUTH":
635         raise Exception("Unexpected CTRL-REQ-SIM type")
636     rid = p[0].split('-')[3]
637     # This will fail during GSM auth validation
638     if "OK" not in dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:0011223344556677:q"):
639         raise Exception("CTRL-RSP-SIM failed")
640     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
641     if ev is None:
642         raise Exception("EAP failure not reported")
643     dev[0].request("DISCONNECT")
644     dev[0].wait_disconnected()
645     time.sleep(0.1)
646 
647     dev[0].select_network(id, freq="2412")
648     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
649     if ev is None:
650         raise Exception("Wait for external SIM processing request timed out")
651     p = ev.split(':', 2)
652     if p[1] != "GSM-AUTH":
653         raise Exception("Unexpected CTRL-REQ-SIM type")
654     rid = p[0].split('-')[3]
655     # This will fail during GSM auth validation
656     if "OK" not in dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:0011223344556677:00112233"):
657         raise Exception("CTRL-RSP-SIM failed")
658     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
659     if ev is None:
660         raise Exception("EAP failure not reported")
661     dev[0].request("DISCONNECT")
662     dev[0].wait_disconnected()
663     time.sleep(0.1)
664 
665     dev[0].select_network(id, freq="2412")
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     # This will fail during GSM auth validation
674     if "OK" not in dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:0011223344556677:00112233:q"):
675         raise Exception("CTRL-RSP-SIM failed")
676     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
677     if ev is None:
678         raise Exception("EAP failure not reported")
679 
680 def test_ap_wpa2_eap_sim_ext_replace_sim(dev, apdev):
681     """EAP-SIM with external GSM auth and replacing SIM without clearing pseudonym id"""
682     try:
683         _test_ap_wpa2_eap_sim_ext_replace_sim(dev, apdev)
684     finally:
685         dev[0].request("SET external_sim 0")
686 
687 def _test_ap_wpa2_eap_sim_ext_replace_sim(dev, apdev):
688     check_hlr_auc_gw_support()
689     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
690     hostapd.add_ap(apdev[0], params)
691     dev[0].request("SET external_sim 1")
692     id = dev[0].connect("test-wpa2-eap", eap="SIM", key_mgmt="WPA-EAP",
693                         identity="1232010000000000",
694                         wait_connect=False, scan_freq="2412")
695 
696     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
697     if ev is None:
698         raise Exception("Wait for external SIM processing request timed out")
699     p = ev.split(':', 2)
700     if p[1] != "GSM-AUTH":
701         raise Exception("Unexpected CTRL-REQ-SIM type")
702     rid = p[0].split('-')[3]
703     rand = p[2].split(' ')[0]
704 
705     res = subprocess.check_output(["../../hostapd/hlr_auc_gw",
706                                    "-m",
707                                    "auth_serv/hlr_auc_gw.milenage_db",
708                                    "GSM-AUTH-REQ 232010000000000 " + rand]).decode()
709     if "GSM-AUTH-RESP" not in res:
710         raise Exception("Unexpected hlr_auc_gw response")
711     resp = res.split(' ')[2].rstrip()
712 
713     dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:" + resp)
714     dev[0].wait_connected(timeout=15)
715     dev[0].request("DISCONNECT")
716     dev[0].wait_disconnected()
717 
718     # Replace SIM, but forget to drop the previous pseudonym identity
719     dev[0].set_network_quoted(id, "identity", "1232010000000009")
720     dev[0].select_network(id, freq="2412")
721 
722     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
723     if ev is None:
724         raise Exception("Wait for external SIM processing request timed out")
725     p = ev.split(':', 2)
726     if p[1] != "GSM-AUTH":
727         raise Exception("Unexpected CTRL-REQ-SIM type")
728     rid = p[0].split('-')[3]
729     rand = p[2].split(' ')[0]
730 
731     res = subprocess.check_output(["../../hostapd/hlr_auc_gw",
732                                    "-m",
733                                    "auth_serv/hlr_auc_gw.milenage_db",
734                                    "GSM-AUTH-REQ 232010000000009 " + rand]).decode()
735     if "GSM-AUTH-RESP" not in res:
736         raise Exception("Unexpected hlr_auc_gw response")
737     resp = res.split(' ')[2].rstrip()
738 
739     dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:" + resp)
740     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
741     if ev is None:
742         raise Exception("EAP-Failure not reported")
743     dev[0].request("DISCONNECT")
744     dev[0].wait_disconnected()
745 
746 def test_ap_wpa2_eap_sim_ext_replace_sim2(dev, apdev):
747     """EAP-SIM with external GSM auth and replacing SIM and clearing pseudonym identity"""
748     try:
749         _test_ap_wpa2_eap_sim_ext_replace_sim2(dev, apdev)
750     finally:
751         dev[0].request("SET external_sim 0")
752 
753 def _test_ap_wpa2_eap_sim_ext_replace_sim2(dev, apdev):
754     check_hlr_auc_gw_support()
755     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
756     hostapd.add_ap(apdev[0], params)
757     dev[0].request("SET external_sim 1")
758     id = dev[0].connect("test-wpa2-eap", eap="SIM", key_mgmt="WPA-EAP",
759                         identity="1232010000000000",
760                         wait_connect=False, scan_freq="2412")
761 
762     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
763     if ev is None:
764         raise Exception("Wait for external SIM processing request timed out")
765     p = ev.split(':', 2)
766     if p[1] != "GSM-AUTH":
767         raise Exception("Unexpected CTRL-REQ-SIM type")
768     rid = p[0].split('-')[3]
769     rand = p[2].split(' ')[0]
770 
771     res = subprocess.check_output(["../../hostapd/hlr_auc_gw",
772                                    "-m",
773                                    "auth_serv/hlr_auc_gw.milenage_db",
774                                    "GSM-AUTH-REQ 232010000000000 " + rand]).decode()
775     if "GSM-AUTH-RESP" not in res:
776         raise Exception("Unexpected hlr_auc_gw response")
777     resp = res.split(' ')[2].rstrip()
778 
779     dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:" + resp)
780     dev[0].wait_connected(timeout=15)
781     dev[0].request("DISCONNECT")
782     dev[0].wait_disconnected()
783 
784     # Replace SIM and drop the previous pseudonym identity
785     dev[0].set_network_quoted(id, "identity", "1232010000000009")
786     dev[0].set_network(id, "anonymous_identity", "NULL")
787     dev[0].select_network(id, freq="2412")
788 
789     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
790     if ev is None:
791         raise Exception("Wait for external SIM processing request timed out")
792     p = ev.split(':', 2)
793     if p[1] != "GSM-AUTH":
794         raise Exception("Unexpected CTRL-REQ-SIM type")
795     rid = p[0].split('-')[3]
796     rand = p[2].split(' ')[0]
797 
798     res = subprocess.check_output(["../../hostapd/hlr_auc_gw",
799                                    "-m",
800                                    "auth_serv/hlr_auc_gw.milenage_db",
801                                    "GSM-AUTH-REQ 232010000000009 " + rand]).decode()
802     if "GSM-AUTH-RESP" not in res:
803         raise Exception("Unexpected hlr_auc_gw response")
804     resp = res.split(' ')[2].rstrip()
805 
806     dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:" + resp)
807     dev[0].wait_connected()
808     dev[0].request("DISCONNECT")
809     dev[0].wait_disconnected()
810 
811 def test_ap_wpa2_eap_sim_ext_replace_sim3(dev, apdev):
812     """EAP-SIM with external GSM auth, replacing SIM, and no identity in config"""
813     try:
814         _test_ap_wpa2_eap_sim_ext_replace_sim3(dev, apdev)
815     finally:
816         dev[0].request("SET external_sim 0")
817 
818 def _test_ap_wpa2_eap_sim_ext_replace_sim3(dev, apdev):
819     check_hlr_auc_gw_support()
820     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
821     hostapd.add_ap(apdev[0], params)
822     dev[0].request("SET external_sim 1")
823     id = dev[0].connect("test-wpa2-eap", eap="SIM", key_mgmt="WPA-EAP",
824                         wait_connect=False, scan_freq="2412")
825 
826     ev = dev[0].wait_event(["CTRL-REQ-IDENTITY"])
827     if ev is None:
828         raise Exception("Request for identity timed out")
829     rid = ev.split(':')[0].split('-')[-1]
830     dev[0].request("CTRL-RSP-IDENTITY-" + rid + ":1232010000000000")
831 
832     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
833     if ev is None:
834         raise Exception("Wait for external SIM processing request timed out")
835     p = ev.split(':', 2)
836     if p[1] != "GSM-AUTH":
837         raise Exception("Unexpected CTRL-REQ-SIM type")
838     rid = p[0].split('-')[3]
839     rand = p[2].split(' ')[0]
840 
841     res = subprocess.check_output(["../../hostapd/hlr_auc_gw",
842                                    "-m",
843                                    "auth_serv/hlr_auc_gw.milenage_db",
844                                    "GSM-AUTH-REQ 232010000000000 " + rand]).decode()
845     if "GSM-AUTH-RESP" not in res:
846         raise Exception("Unexpected hlr_auc_gw response")
847     resp = res.split(' ')[2].rstrip()
848 
849     dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:" + resp)
850     dev[0].wait_connected(timeout=15)
851     dev[0].request("DISCONNECT")
852     dev[0].wait_disconnected()
853 
854     # Replace SIM and drop the previous permanent and pseudonym identities
855     dev[0].set_network(id, "identity", "NULL")
856     dev[0].set_network(id, "anonymous_identity", "NULL")
857     dev[0].select_network(id, freq="2412")
858 
859     ev = dev[0].wait_event(["CTRL-REQ-IDENTITY"])
860     if ev is None:
861         raise Exception("Request for identity timed out")
862     rid = ev.split(':')[0].split('-')[-1]
863     dev[0].request("CTRL-RSP-IDENTITY-" + rid + ":1232010000000009")
864 
865     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
866     if ev is None:
867         raise Exception("Wait for external SIM processing request timed out")
868     p = ev.split(':', 2)
869     if p[1] != "GSM-AUTH":
870         raise Exception("Unexpected CTRL-REQ-SIM type")
871     rid = p[0].split('-')[3]
872     rand = p[2].split(' ')[0]
873 
874     res = subprocess.check_output(["../../hostapd/hlr_auc_gw",
875                                    "-m",
876                                    "auth_serv/hlr_auc_gw.milenage_db",
877                                    "GSM-AUTH-REQ 232010000000009 " + rand]).decode()
878     if "GSM-AUTH-RESP" not in res:
879         raise Exception("Unexpected hlr_auc_gw response")
880     resp = res.split(' ')[2].rstrip()
881 
882     dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:" + resp)
883     dev[0].wait_connected()
884     dev[0].request("DISCONNECT")
885     dev[0].wait_disconnected()
886 
887 def test_ap_wpa2_eap_sim_ext_auth_fail(dev, apdev):
888     """EAP-SIM with external GSM auth and auth failing"""
889     try:
890         _test_ap_wpa2_eap_sim_ext_auth_fail(dev, apdev)
891     finally:
892         dev[0].request("SET external_sim 0")
893 
894 def _test_ap_wpa2_eap_sim_ext_auth_fail(dev, apdev):
895     check_hlr_auc_gw_support()
896     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
897     hostapd.add_ap(apdev[0], params)
898     dev[0].request("SET external_sim 1")
899     id = dev[0].connect("test-wpa2-eap", eap="SIM", key_mgmt="WPA-EAP",
900                         identity="1232010000000000",
901                         wait_connect=False, scan_freq="2412")
902 
903     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
904     if ev is None:
905         raise Exception("Wait for external SIM processing request timed out")
906     p = ev.split(':', 2)
907     rid = p[0].split('-')[3]
908     dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-FAIL")
909     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
910     if ev is None:
911         raise Exception("EAP failure not reported")
912     dev[0].request("REMOVE_NETWORK all")
913     dev[0].wait_disconnected()
914 
915 def test_ap_wpa2_eap_sim_change_bssid(dev, apdev):
916     """EAP-SIM and external GSM auth to check fast reauth with bssid change"""
917     try:
918         _test_ap_wpa2_eap_sim_change_bssid(dev, apdev)
919     finally:
920         dev[0].request("SET external_sim 0")
921 
922 def _test_ap_wpa2_eap_sim_change_bssid(dev, apdev):
923     check_hlr_auc_gw_support()
924     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
925     hapd = hostapd.add_ap(apdev[0], params)
926     dev[0].request("SET external_sim 1")
927     id = dev[0].connect("test-wpa2-eap", eap="SIM", key_mgmt="WPA-EAP",
928                         identity="1232010000000000",
929                         wait_connect=False, scan_freq="2412")
930 
931     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
932     if ev is None:
933         raise Exception("Wait for external SIM processing request timed out")
934     p = ev.split(':', 2)
935     if p[1] != "GSM-AUTH":
936         raise Exception("Unexpected CTRL-REQ-SIM type")
937     rid = p[0].split('-')[3]
938     rand = p[2].split(' ')[0]
939 
940     res = subprocess.check_output(["../../hostapd/hlr_auc_gw",
941                                    "-m",
942                                    "auth_serv/hlr_auc_gw.milenage_db",
943                                    "GSM-AUTH-REQ 232010000000000 " + rand]).decode()
944     if "GSM-AUTH-RESP" not in res:
945         raise Exception("Unexpected hlr_auc_gw response")
946     resp = res.split(' ')[2].rstrip()
947 
948     dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:" + resp)
949     dev[0].wait_connected(timeout=15)
950     hapd.wait_sta()
951 
952     # Verify that EAP-SIM Reauthentication can be used after a profile change
953     # that does not affect EAP parameters.
954     dev[0].set_network(id, "bssid", "any")
955     eap_reauth(dev[0], "SIM")
956 
957 def test_ap_wpa2_eap_sim_no_change_set(dev, apdev):
958     """EAP-SIM and external GSM auth to check fast reauth with no-change SET_NETWORK"""
959     try:
960         _test_ap_wpa2_eap_sim_no_change_set(dev, apdev)
961     finally:
962         dev[0].request("SET external_sim 0")
963 
964 def _test_ap_wpa2_eap_sim_no_change_set(dev, apdev):
965     check_hlr_auc_gw_support()
966     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
967     hapd = hostapd.add_ap(apdev[0], params)
968     dev[0].request("SET external_sim 1")
969     id = dev[0].connect("test-wpa2-eap", eap="SIM", key_mgmt="WPA-EAP",
970                         identity="1232010000000000",
971                         wait_connect=False, scan_freq="2412")
972 
973     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
974     if ev is None:
975         raise Exception("Wait for external SIM processing request timed out")
976     p = ev.split(':', 2)
977     if p[1] != "GSM-AUTH":
978         raise Exception("Unexpected CTRL-REQ-SIM type")
979     rid = p[0].split('-')[3]
980     rand = p[2].split(' ')[0]
981 
982     res = subprocess.check_output(["../../hostapd/hlr_auc_gw",
983                                    "-m",
984                                    "auth_serv/hlr_auc_gw.milenage_db",
985                                    "GSM-AUTH-REQ 232010000000000 " + rand]).decode()
986     if "GSM-AUTH-RESP" not in res:
987         raise Exception("Unexpected hlr_auc_gw response")
988     resp = res.split(' ')[2].rstrip()
989 
990     dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:" + resp)
991     dev[0].wait_connected(timeout=15)
992     hapd.wait_sta()
993 
994     # Verify that EAP-SIM Reauthentication can be used after network profile
995     # SET_NETWORK commands that do not actually change previously set
996     # parameter values.
997     dev[0].set_network(id, "key_mgmt", "WPA-EAP")
998     dev[0].set_network(id, "eap", "SIM")
999     dev[0].set_network_quoted(id, "identity", "1232010000000000")
1000     dev[0].set_network_quoted(id, "ssid", "test-wpa2-eap")
1001     eap_reauth(dev[0], "SIM")
1002 
1003 def test_ap_wpa2_eap_sim_ext_anonymous(dev, apdev):
1004     """EAP-SIM with external GSM auth and anonymous identity"""
1005     check_hlr_auc_gw_support()
1006     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1007     hostapd.add_ap(apdev[0], params)
1008     try:
1009         run_ap_wpa2_eap_sim_ext_anonymous(dev, "anonymous@example.org")
1010         run_ap_wpa2_eap_sim_ext_anonymous(dev, "@example.org")
1011         run_ap_wpa2_eap_sim_ext_anonymous(dev, "example.org!anonymous@otherexample.org")
1012     finally:
1013         dev[0].request("SET external_sim 0")
1014 
1015 def test_ap_wpa2_eap_sim_ext_anonymous_no_pseudonym(dev, apdev):
1016     """EAP-SIM with external GSM auth and anonymous identity without pseudonym update"""
1017     check_hlr_auc_gw_support()
1018     params = int_eap_server_params()
1019     params['eap_sim_id'] = '0'
1020     params['eap_sim_db'] = 'unix:/tmp/hlr_auc_gw.sock'
1021     hostapd.add_ap(apdev[0], params)
1022     try:
1023         run_ap_wpa2_eap_sim_ext_anonymous(dev, "anonymous@example.org",
1024                                           anon_id_change=False)
1025         run_ap_wpa2_eap_sim_ext_anonymous(dev, "@example.org",
1026                                           anon_id_change=False)
1027     finally:
1028         dev[0].request("SET external_sim 0")
1029 
1030 def run_ap_wpa2_eap_sim_ext_anonymous(dev, anon, anon_id_change=True):
1031     dev[0].request("SET external_sim 1")
1032     id = dev[0].connect("test-wpa2-eap", eap="SIM", key_mgmt="WPA-EAP",
1033                         identity="1232010000000000",
1034                         anonymous_identity=anon,
1035                         wait_connect=False, scan_freq="2412")
1036 
1037     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
1038     if ev is None:
1039         raise Exception("Wait for external SIM processing request timed out")
1040     p = ev.split(':', 2)
1041     if p[1] != "GSM-AUTH":
1042         raise Exception("Unexpected CTRL-REQ-SIM type")
1043     rid = p[0].split('-')[3]
1044     rand = p[2].split(' ')[0]
1045 
1046     res = subprocess.check_output(["../../hostapd/hlr_auc_gw",
1047                                    "-m",
1048                                    "auth_serv/hlr_auc_gw.milenage_db",
1049                                    "GSM-AUTH-REQ 232010000000000 " + rand]).decode()
1050     if "GSM-AUTH-RESP" not in res:
1051         raise Exception("Unexpected hlr_auc_gw response")
1052     resp = res.split(' ')[2].rstrip()
1053 
1054     dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:" + resp)
1055     dev[0].wait_connected(timeout=5)
1056     anon_id = dev[0].get_network(id, "anonymous_identity").strip('"')
1057     if anon_id_change and anon == anon_id:
1058         raise Exception("anonymous_identity did not change")
1059     if not anon_id_change and anon != anon_id:
1060         raise Exception("anonymous_identity changed")
1061     dev[0].request("REMOVE_NETWORK all")
1062     dev[0].wait_disconnected()
1063     dev[0].dump_monitor()
1064 
1065 def test_ap_wpa2_eap_sim_oom(dev, apdev):
1066     """EAP-SIM and OOM"""
1067     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1068     hostapd.add_ap(apdev[0], params)
1069     tests = [(1, "milenage_f2345"),
1070              (2, "milenage_f2345"),
1071              (3, "milenage_f2345"),
1072              (4, "milenage_f2345"),
1073              (5, "milenage_f2345"),
1074              (6, "milenage_f2345"),
1075              (7, "milenage_f2345"),
1076              (8, "milenage_f2345"),
1077              (9, "milenage_f2345"),
1078              (10, "milenage_f2345"),
1079              (11, "milenage_f2345"),
1080              (12, "milenage_f2345")]
1081     for count, func in tests:
1082         with fail_test(dev[0], count, func):
1083             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="SIM",
1084                            identity="1232010000000000",
1085                            password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
1086                            wait_connect=False, scan_freq="2412")
1087             ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=5)
1088             if ev is None:
1089                 raise Exception("EAP method not selected")
1090             dev[0].wait_disconnected()
1091             dev[0].request("REMOVE_NETWORK all")
1092 
1093 def test_ap_wpa2_eap_aka(dev, apdev):
1094     """WPA2-Enterprise connection using EAP-AKA"""
1095     check_hlr_auc_gw_support()
1096     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1097     hapd = hostapd.add_ap(apdev[0], params)
1098     eap_connect(dev[0], hapd, "AKA", "0232010000000000",
1099                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123")
1100     hwsim_utils.test_connectivity(dev[0], hapd)
1101     eap_reauth(dev[0], "AKA")
1102 
1103     logger.info("Negative test with incorrect key")
1104     dev[0].request("REMOVE_NETWORK all")
1105     eap_connect(dev[0], hapd, "AKA", "0232010000000000",
1106                 password="ffdca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123",
1107                 expect_failure=True)
1108 
1109     logger.info("Invalid Milenage key")
1110     dev[0].request("REMOVE_NETWORK all")
1111     eap_connect(dev[0], hapd, "AKA", "0232010000000000",
1112                 password="ffdca4eda45b53cf0f12d7c9c3bc6a",
1113                 expect_failure=True)
1114 
1115     logger.info("Invalid Milenage key(2)")
1116     eap_connect(dev[0], hapd, "AKA", "0232010000000000",
1117                 password="ffdca4eda45b53cf0f12d7c9c3bc6a8q:cb9cccc4b9258e6dca4760379fb82581:000000000123",
1118                 expect_failure=True)
1119 
1120     logger.info("Invalid Milenage key(3)")
1121     eap_connect(dev[0], hapd, "AKA", "0232010000000000",
1122                 password="ffdca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb8258q:000000000123",
1123                 expect_failure=True)
1124 
1125     logger.info("Invalid Milenage key(4)")
1126     eap_connect(dev[0], hapd, "AKA", "0232010000000000",
1127                 password="ffdca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:00000000012q",
1128                 expect_failure=True)
1129 
1130     logger.info("Invalid Milenage key(5)")
1131     dev[0].request("REMOVE_NETWORK all")
1132     eap_connect(dev[0], hapd, "AKA", "0232010000000000",
1133                 password="ffdca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581q000000000123",
1134                 expect_failure=True)
1135 
1136     logger.info("Invalid Milenage key(6)")
1137     dev[0].request("REMOVE_NETWORK all")
1138     eap_connect(dev[0], hapd, "AKA", "0232010000000000",
1139                 password="ffdca4eda45b53cf0f12d7c9c3bc6a89qcb9cccc4b9258e6dca4760379fb82581q000000000123",
1140                 expect_failure=True)
1141 
1142     logger.info("Missing key configuration")
1143     dev[0].request("REMOVE_NETWORK all")
1144     eap_connect(dev[0], hapd, "AKA", "0232010000000000",
1145                 expect_failure=True)
1146 
1147 def test_ap_wpa2_eap_aka_imsi_identity(dev, apdev, params):
1148     """WPA2-Enterprise connection using EAP-AKA and imsi_identity"""
1149     run_ap_wpa2_eap_aka_imsi_identity(dev, apdev, params, False)
1150 
1151 def test_ap_wpa2_eap_aka_imsi_identity_fallback(dev, apdev, params):
1152     """WPA2-Enterprise connection using EAP-AKA and imsi_identity"""
1153     run_ap_wpa2_eap_aka_imsi_identity(dev, apdev, params, True)
1154 
1155 def run_ap_wpa2_eap_aka_imsi_identity(dev, apdev, params, fallback):
1156     check_hlr_auc_gw_support()
1157     prefix = params['prefix']
1158     if fallback:
1159         db = os.path.join(params['logdir'], "hostapd.db")
1160         params = int_eap_server_params()
1161         params['imsi_privacy_key'] = "auth_serv/imsi-privacy-key.pem"
1162         params['eap_sim_db'] = 'unix:/tmp/hlr_auc_gw.sock db=' + db
1163         params['eap_sim_aka_fast_reauth_limit'] = '0'
1164         params['eap_sim_id'] = "7"
1165     else:
1166         params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1167 
1168     hapd = hostapd.add_ap(apdev[0], params)
1169     check_imsi_privacy_support(hapd)
1170 
1171     imsi = "232010000000000"
1172     realm = "wlan.mnc232.mcc02.3gppnetwork.org"
1173     method_id = '0'
1174     permanent_id = method_id + imsi + '@' + realm
1175     # RSA-OAEP(permanent_id)
1176     perm_id = prefix + '.permanent-id'
1177     enc_id = prefix + '.enc-permanent-id'
1178     with open(perm_id, 'w') as f:
1179         f.write(permanent_id)
1180     pubkey = prefix + ".cert-pub.pem"
1181     subprocess.check_call(["openssl", "x509",
1182                            "-in", "auth_serv/imsi-privacy-cert.pem",
1183                            "-pubkey", "-noout",
1184                            "-out", pubkey])
1185     subprocess.check_call(["openssl", "pkeyutl",
1186                            "-inkey", pubkey, "-pubin", "-in", perm_id,
1187                            "-pkeyopt", "rsa_padding_mode:oaep",
1188                            "-pkeyopt", "rsa_oaep_md:sha256",
1189                            "-encrypt",
1190                            "-out", enc_id])
1191     with open(enc_id, 'rb') as f:
1192         data = f.read()
1193         encrypted_id = base64.b64encode(data).decode()
1194         if len(encrypted_id) != 344:
1195             raise Exception("Unexpected length of the base64 encoded identity: " + b64)
1196     eap_connect(dev[0], hapd, "AKA", identity=None,
1197                 raw_identity='P"\\0' + encrypted_id + '"',
1198                 anonymous_identity=method_id + "anonymous@" + realm,
1199                 imsi_identity=permanent_id,
1200                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123")
1201     eap_reauth(dev[0], "AKA")
1202 
1203 def test_ap_wpa2_eap_aka_imsi_privacy_key(dev, apdev):
1204     """WPA2-Enterprise connection using EAP-AKA and imsi_privacy_cert"""
1205     check_imsi_privacy_support(dev[0])
1206     check_hlr_auc_gw_support()
1207     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1208     hapd = hostapd.add_ap(apdev[0], params)
1209     check_imsi_privacy_support(hapd)
1210 
1211     eap_connect(dev[0], hapd, "AKA",
1212                 "0232010000000000@wlan.mnc232.mcc02.3gppnetwork.org",
1213                 imsi_privacy_cert="auth_serv/imsi-privacy-cert.pem",
1214                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123")
1215     eap_reauth(dev[0], "AKA")
1216 
1217 def test_ap_wpa2_eap_aka_imsi_privacy_attr(dev, apdev):
1218     """WPA2-Enterprise connection using EAP-AKA and imsi_privacy_cert/attr"""
1219     check_imsi_privacy_support(dev[0])
1220     check_hlr_auc_gw_support()
1221     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1222     hapd = hostapd.add_ap(apdev[0], params)
1223     check_imsi_privacy_support(hapd)
1224 
1225     eap_connect(dev[0], hapd, "AKA",
1226                 "0232010000000000@wlan.mnc232.mcc02.3gppnetwork.org",
1227                 imsi_privacy_cert="auth_serv/imsi-privacy-cert.pem",
1228                 imsi_privacy_attr="Name=Value",
1229                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123")
1230 
1231 def test_ap_wpa2_eap_aka_imsi_privacy_key_expired(dev, apdev):
1232     """WPA2-Enterprise connection using EAP-AKA and expired imsi_privacy_cert"""
1233     check_imsi_privacy_support(dev[0])
1234     check_hlr_auc_gw_support()
1235     params = int_eap_server_params()
1236     params['eap_sim_db'] = 'unix:/tmp/hlr_auc_gw.sock'
1237     params['imsi_privacy_key'] = 'auth_serv/imsi-privacy-key-2.pem'
1238     hapd = hostapd.add_ap(apdev[0], params)
1239     check_imsi_privacy_support(hapd)
1240 
1241     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
1242                    eap="AKA",
1243                    identity="0232010000000000@wlan.mnc232.mcc02.3gppnetwork.org",
1244                    wait_connect=False, scan_freq="2412", ieee80211w="1",
1245                    imsi_privacy_cert="auth_serv/imsi-privacy-cert-2.pem",
1246                    password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123")
1247     ev = dev[0].wait_event(["Trying to associate with"], timeout=10)
1248     if ev is not None:
1249         raise Exception("Unexpected association attempt")
1250 
1251 def test_ap_wpa2_eap_aka_sql(dev, apdev, params):
1252     """WPA2-Enterprise connection using EAP-AKA (SQL)"""
1253     check_hlr_auc_gw_support()
1254     try:
1255         import sqlite3
1256     except ImportError:
1257         raise HwsimSkip("No sqlite3 module available")
1258     con = sqlite3.connect(os.path.join(params['logdir'], "hostapd.db"))
1259     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1260     params['auth_server_port'] = "1814"
1261     hapd = hostapd.add_ap(apdev[0], params)
1262     eap_connect(dev[0], hapd, "AKA", "0232010000000000",
1263                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123")
1264 
1265     logger.info("AKA fast re-authentication")
1266     eap_reauth(dev[0], "AKA")
1267     hapd.wait_4way_hs()
1268 
1269     logger.info("AKA full auth with pseudonym")
1270     with con:
1271         cur = con.cursor()
1272         cur.execute("DELETE FROM reauth WHERE permanent='0232010000000000'")
1273     eap_reauth(dev[0], "AKA")
1274     hapd.wait_4way_hs()
1275 
1276     logger.info("AKA full auth with permanent identity")
1277     with con:
1278         cur = con.cursor()
1279         cur.execute("DELETE FROM reauth WHERE permanent='0232010000000000'")
1280         cur.execute("DELETE FROM pseudonyms WHERE permanent='0232010000000000'")
1281     eap_reauth(dev[0], "AKA")
1282     hapd.wait_4way_hs()
1283 
1284     logger.info("AKA reauth with mismatching MK")
1285     with con:
1286         cur = con.cursor()
1287         cur.execute("UPDATE reauth SET mk='0000000000000000000000000000000000000000' WHERE permanent='0232010000000000'")
1288     eap_reauth(dev[0], "AKA", expect_failure=True)
1289     dev[0].request("REMOVE_NETWORK all")
1290 
1291     eap_connect(dev[0], hapd, "AKA", "0232010000000000",
1292                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123")
1293     with con:
1294         cur = con.cursor()
1295         cur.execute("UPDATE reauth SET counter='10' WHERE permanent='0232010000000000'")
1296     eap_reauth(dev[0], "AKA")
1297     hapd.wait_4way_hs()
1298     with con:
1299         cur = con.cursor()
1300         cur.execute("UPDATE reauth SET counter='10' WHERE permanent='0232010000000000'")
1301     logger.info("AKA reauth with mismatching counter")
1302     eap_reauth(dev[0], "AKA")
1303     hapd.wait_4way_hs()
1304     dev[0].request("REMOVE_NETWORK all")
1305     dev[0].wait_disconnected()
1306     hapd.wait_sta_disconnect()
1307 
1308     eap_connect(dev[0], hapd, "AKA", "0232010000000000",
1309                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123")
1310     with con:
1311         cur = con.cursor()
1312         cur.execute("UPDATE reauth SET counter='1001' WHERE permanent='0232010000000000'")
1313     logger.info("AKA reauth with max reauth count reached")
1314     eap_reauth(dev[0], "AKA")
1315     hapd.wait_4way_hs()
1316 
1317 def test_ap_wpa2_eap_aka_sql_fallback_to_pseudonym_id(dev, apdev, params):
1318     """WPA2-Enterprise connection using EAP-AKA (SQL) and fallback to pseudonym using AKA-Identity"""
1319     run_ap_wpa2_eap_aka_sql_fallback_to_pseudonym(dev, apdev, params, 3)
1320 
1321 def test_ap_wpa2_eap_aka_sql_fallback_to_pseudonym(dev, apdev, params):
1322     """WPA2-Enterprise connection using EAP-AKA (SQL) and fallback to pseudonym without AKA-Identity"""
1323     run_ap_wpa2_eap_aka_sql_fallback_to_pseudonym(dev, apdev, params, 7)
1324 
1325 def run_ap_wpa2_eap_aka_sql_fallback_to_pseudonym(dev, apdev, params,
1326                                                   eap_sim_id):
1327     check_hlr_auc_gw_support()
1328     db = os.path.join(params['logdir'], "hostapd.db")
1329     params = int_eap_server_params()
1330     params['eap_sim_db'] = 'unix:/tmp/hlr_auc_gw.sock db=' + db
1331     params['eap_sim_aka_fast_reauth_limit'] = '0'
1332     params['eap_sim_id'] = str(eap_sim_id)
1333     hapd = hostapd.add_ap(apdev[0], params)
1334     eap_connect(dev[0], hapd, "AKA", "0232010000000000",
1335                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000000")
1336 
1337     logger.info("AKA fallback from fast re-auth to full auth with pseudonym")
1338     eap_reauth(dev[0], "AKA")
1339 
1340 def test_ap_wpa2_eap_aka_id_0(dev, apdev):
1341     """WPA2-Enterprise connection using EAP-AKA (no pseudonym or reauth)"""
1342     run_ap_wpa2_eap_aka_id(dev, apdev, 0)
1343 
1344 def test_ap_wpa2_eap_aka_id_1(dev, apdev):
1345     """WPA2-Enterprise connection using EAP-AKA (pseudonym, no reauth)"""
1346     run_ap_wpa2_eap_aka_id(dev, apdev, 1)
1347 
1348 def test_ap_wpa2_eap_aka_id_2(dev, apdev):
1349     """WPA2-Enterprise connection using EAP-AKA (no pseudonym, reauth)"""
1350     run_ap_wpa2_eap_aka_id(dev, apdev, 2)
1351 
1352 def test_ap_wpa2_eap_aka_id_3(dev, apdev):
1353     """WPA2-Enterprise connection using EAP-AKA (pseudonym and reauth)"""
1354     run_ap_wpa2_eap_aka_id(dev, apdev, 3)
1355 
1356 def test_ap_wpa2_eap_aka_id_4(dev, apdev):
1357     """WPA2-Enterprise connection using EAP-AKA (no pseudonym or reauth)"""
1358     run_ap_wpa2_eap_aka_id(dev, apdev, 4)
1359 
1360 def test_ap_wpa2_eap_aka_id_5(dev, apdev):
1361     """WPA2-Enterprise connection using EAP-AKA (pseudonym, no reauth)"""
1362     run_ap_wpa2_eap_aka_id(dev, apdev, 5)
1363 
1364 def test_ap_wpa2_eap_aka_id_6(dev, apdev):
1365     """WPA2-Enterprise connection using EAP-AKA (no pseudonym, reauth)"""
1366     run_ap_wpa2_eap_aka_id(dev, apdev, 6)
1367 
1368 def test_ap_wpa2_eap_aka_id_7(dev, apdev):
1369     """WPA2-Enterprise connection using EAP-AKA (pseudonym and reauth)"""
1370     run_ap_wpa2_eap_aka_id(dev, apdev, 7)
1371 
1372 def run_ap_wpa2_eap_aka_id(dev, apdev, eap_sim_id):
1373     check_hlr_auc_gw_support()
1374     params = int_eap_server_params()
1375     params['eap_sim_id'] = str(eap_sim_id)
1376     params['eap_sim_db'] = 'unix:/tmp/hlr_auc_gw.sock'
1377     hapd = hostapd.add_ap(apdev[0], params)
1378     eap_connect(dev[0], hapd, "AKA", "0232010000000000",
1379                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000000")
1380     eap_reauth(dev[0], "AKA")
1381 
1382 def test_ap_wpa2_eap_aka_config(dev, apdev):
1383     """EAP-AKA configuration options"""
1384     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1385     hapd = hostapd.add_ap(apdev[0], params)
1386     eap_connect(dev[0], hapd, "AKA", "0232010000000000",
1387                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123",
1388                 anonymous_identity="2345678")
1389 
1390 def test_ap_wpa2_eap_aka_ext(dev, apdev):
1391     """WPA2-Enterprise connection using EAP-AKA and external UMTS auth"""
1392     try:
1393         _test_ap_wpa2_eap_aka_ext(dev, apdev)
1394     finally:
1395         dev[0].request("SET external_sim 0")
1396 
1397 def _test_ap_wpa2_eap_aka_ext(dev, apdev):
1398     check_hlr_auc_gw_support()
1399     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1400     hostapd.add_ap(apdev[0], params)
1401     dev[0].request("SET external_sim 1")
1402     id = dev[0].connect("test-wpa2-eap", eap="AKA", key_mgmt="WPA-EAP",
1403                         identity="0232010000000000",
1404                         password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123",
1405                         wait_connect=False, scan_freq="2412")
1406     ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=15)
1407     if ev is None:
1408         raise Exception("Network connected timed out")
1409 
1410     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
1411     if ev is None:
1412         raise Exception("Wait for external SIM processing request timed out")
1413     p = ev.split(':', 2)
1414     if p[1] != "UMTS-AUTH":
1415         raise Exception("Unexpected CTRL-REQ-SIM type")
1416     rid = p[0].split('-')[3]
1417 
1418     # IK:CK:RES
1419     resp = "00112233445566778899aabbccddeeff:00112233445566778899aabbccddeeff:0011223344"
1420     # This will fail during processing, but the ctrl_iface command succeeds
1421     dev[0].request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:" + resp)
1422     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
1423     if ev is None:
1424         raise Exception("EAP failure not reported")
1425     dev[0].request("DISCONNECT")
1426     dev[0].wait_disconnected()
1427     time.sleep(0.1)
1428     dev[0].dump_monitor()
1429 
1430     dev[0].select_network(id, freq="2412")
1431     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
1432     if ev is None:
1433         raise Exception("Wait for external SIM processing request timed out")
1434     p = ev.split(':', 2)
1435     if p[1] != "UMTS-AUTH":
1436         raise Exception("Unexpected CTRL-REQ-SIM type")
1437     rid = p[0].split('-')[3]
1438     # This will fail during UMTS auth validation
1439     if "OK" not in dev[0].request("CTRL-RSP-SIM-" + rid + ":UMTS-AUTS:112233445566778899aabbccddee"):
1440         raise Exception("CTRL-RSP-SIM failed")
1441     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
1442     if ev is None:
1443         raise Exception("Wait for external SIM processing request timed out")
1444     p = ev.split(':', 2)
1445     if p[1] != "UMTS-AUTH":
1446         raise Exception("Unexpected CTRL-REQ-SIM type")
1447     rid = p[0].split('-')[3]
1448     # This will fail during UMTS auth validation
1449     if "OK" not in dev[0].request("CTRL-RSP-SIM-" + rid + ":UMTS-AUTS:12"):
1450         raise Exception("CTRL-RSP-SIM failed")
1451     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
1452     if ev is None:
1453         raise Exception("EAP failure not reported")
1454     dev[0].request("DISCONNECT")
1455     dev[0].wait_disconnected()
1456     time.sleep(0.1)
1457     dev[0].dump_monitor()
1458 
1459     tests = [":UMTS-AUTH:00112233445566778899aabbccddeeff:00112233445566778899aabbccddeeff:0011223344",
1460              ":UMTS-AUTH:34",
1461              ":UMTS-AUTH:00112233445566778899aabbccddeeff.00112233445566778899aabbccddeeff:0011223344",
1462              ":UMTS-AUTH:00112233445566778899aabbccddeeff:00112233445566778899aabbccddee:0011223344",
1463              ":UMTS-AUTH:00112233445566778899aabbccddeeff:00112233445566778899aabbccddeeff.0011223344",
1464              ":UMTS-AUTH:00112233445566778899aabbccddeeff:00112233445566778899aabbccddeeff:00112233445566778899aabbccddeeff0011223344",
1465              ":UMTS-AUTH:00112233445566778899aabbccddeeff:00112233445566778899aabbccddeeff:001122334q"]
1466     for t in tests:
1467         dev[0].select_network(id, freq="2412")
1468         ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
1469         if ev is None:
1470             raise Exception("Wait for external SIM processing request timed out")
1471         p = ev.split(':', 2)
1472         if p[1] != "UMTS-AUTH":
1473             raise Exception("Unexpected CTRL-REQ-SIM type")
1474         rid = p[0].split('-')[3]
1475         # This will fail during UMTS auth validation
1476         if "OK" not in dev[0].request("CTRL-RSP-SIM-" + rid + t):
1477             raise Exception("CTRL-RSP-SIM failed")
1478         ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
1479         if ev is None:
1480             raise Exception("EAP failure not reported")
1481         dev[0].request("DISCONNECT")
1482         dev[0].wait_disconnected()
1483         time.sleep(0.1)
1484         dev[0].dump_monitor()
1485 
1486 def test_ap_wpa2_eap_aka_ext_auth_fail(dev, apdev):
1487     """EAP-AKA with external UMTS auth and auth failing"""
1488     try:
1489         _test_ap_wpa2_eap_aka_ext_auth_fail(dev, apdev)
1490     finally:
1491         dev[0].request("SET external_sim 0")
1492 
1493 def _test_ap_wpa2_eap_aka_ext_auth_fail(dev, apdev):
1494     check_hlr_auc_gw_support()
1495     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1496     hostapd.add_ap(apdev[0], params)
1497     dev[0].request("SET external_sim 1")
1498     id = dev[0].connect("test-wpa2-eap", eap="AKA", key_mgmt="WPA-EAP",
1499                         identity="0232010000000000",
1500                         wait_connect=False, scan_freq="2412")
1501 
1502     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
1503     if ev is None:
1504         raise Exception("Wait for external SIM processing request timed out")
1505     p = ev.split(':', 2)
1506     rid = p[0].split('-')[3]
1507     dev[0].request("CTRL-RSP-SIM-" + rid + ":UMTS-FAIL")
1508     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
1509     if ev is None:
1510         raise Exception("EAP failure not reported")
1511     dev[0].request("REMOVE_NETWORK all")
1512     dev[0].wait_disconnected()
1513 
1514 def test_ap_wpa2_eap_aka_prime(dev, apdev):
1515     """WPA2-Enterprise connection using EAP-AKA'"""
1516     check_hlr_auc_gw_support()
1517     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1518     hapd = hostapd.add_ap(apdev[0], params)
1519     eap_connect(dev[0], hapd, "AKA'", "6555444333222111",
1520                 password="5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123")
1521     hwsim_utils.test_connectivity(dev[0], hapd)
1522     eap_reauth(dev[0], "AKA'")
1523 
1524     logger.info("EAP-AKA' bidding protection when EAP-AKA enabled as well")
1525     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="AKA' AKA",
1526                    identity="6555444333222111@both",
1527                    password="5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123",
1528                    wait_connect=False, scan_freq="2412")
1529     dev[1].wait_connected(timeout=15)
1530 
1531     logger.info("Negative test with incorrect key")
1532     dev[0].request("REMOVE_NETWORK all")
1533     eap_connect(dev[0], hapd, "AKA'", "6555444333222111",
1534                 password="ff22250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123",
1535                 expect_failure=True)
1536 
1537 def test_ap_wpa2_eap_aka_prime_imsi_identity(dev, apdev, params):
1538     """WPA2-Enterprise connection using EAP-AKA' and imsi_identity"""
1539     check_hlr_auc_gw_support()
1540     prefix = params['prefix']
1541     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1542     hapd = hostapd.add_ap(apdev[0], params)
1543     check_imsi_privacy_support(hapd)
1544 
1545     imsi = "555444333222111"
1546     realm = "wlan.mnc555.mcc44.3gppnetwork.org"
1547     method_id = '6'
1548     permanent_id = method_id + imsi + '@' + realm
1549     # RSA-OAEP(permanent_id)
1550     perm_id = prefix + '.permanent-id'
1551     enc_id = prefix + '.enc-permanent-id'
1552     with open(perm_id, 'w') as f:
1553         f.write(permanent_id)
1554     pubkey = prefix + ".cert-pub.pem"
1555     subprocess.check_call(["openssl", "x509",
1556                            "-in", "auth_serv/imsi-privacy-cert.pem",
1557                            "-pubkey", "-noout",
1558                            "-out", pubkey])
1559     subprocess.check_call(["openssl", "pkeyutl",
1560                            "-inkey", pubkey, "-pubin", "-in", perm_id,
1561                            "-pkeyopt", "rsa_padding_mode:oaep",
1562                            "-pkeyopt", "rsa_oaep_md:sha256",
1563                            "-encrypt",
1564                            "-out", enc_id])
1565     with open(enc_id, 'rb') as f:
1566         data = f.read()
1567         encrypted_id = base64.b64encode(data).decode()
1568         if len(encrypted_id) != 344:
1569             raise Exception("Unexpected length of the base64 encoded identity: " + b64)
1570     eap_connect(dev[0], hapd, "AKA'", identity=None,
1571                 raw_identity='P"\\0' + encrypted_id + '"',
1572                 anonymous_identity=method_id + "anonymous@" + realm,
1573                 imsi_identity=permanent_id,
1574                 password="5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123")
1575     eap_reauth(dev[0], "AKA'")
1576 
1577 def test_ap_wpa2_eap_aka_prime_imsi_privacy_key(dev, apdev):
1578     """WPA2-Enterprise connection using EAP-AKA' and imsi_privacy_cert"""
1579     check_imsi_privacy_support(dev[0])
1580     check_hlr_auc_gw_support()
1581     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1582     hapd = hostapd.add_ap(apdev[0], params)
1583     check_imsi_privacy_support(hapd)
1584 
1585     eap_connect(dev[0], hapd, "AKA'",
1586                 "6555444333222111@wlan.mnc555.mcc44.3gppnetwork.org",
1587                 imsi_privacy_cert="auth_serv/imsi-privacy-cert.pem",
1588                 password="5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123")
1589     eap_reauth(dev[0], "AKA'")
1590 
1591 def test_ap_wpa2_eap_aka_prime_sql(dev, apdev, params):
1592     """WPA2-Enterprise connection using EAP-AKA' (SQL)"""
1593     check_hlr_auc_gw_support()
1594     try:
1595         import sqlite3
1596     except ImportError:
1597         raise HwsimSkip("No sqlite3 module available")
1598     con = sqlite3.connect(os.path.join(params['logdir'], "hostapd.db"))
1599     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1600     params['auth_server_port'] = "1814"
1601     hapd = hostapd.add_ap(apdev[0], params)
1602     eap_connect(dev[0], hapd, "AKA'", "6555444333222111",
1603                 password="5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123")
1604 
1605     logger.info("AKA' fast re-authentication")
1606     eap_reauth(dev[0], "AKA'")
1607     hapd.wait_4way_hs()
1608 
1609     logger.info("AKA' full auth with pseudonym")
1610     with con:
1611         cur = con.cursor()
1612         cur.execute("DELETE FROM reauth WHERE permanent='6555444333222111'")
1613     eap_reauth(dev[0], "AKA'")
1614     hapd.wait_4way_hs()
1615 
1616     logger.info("AKA' full auth with permanent identity")
1617     with con:
1618         cur = con.cursor()
1619         cur.execute("DELETE FROM reauth WHERE permanent='6555444333222111'")
1620         cur.execute("DELETE FROM pseudonyms WHERE permanent='6555444333222111'")
1621     eap_reauth(dev[0], "AKA'")
1622     hapd.wait_4way_hs()
1623 
1624     logger.info("AKA' reauth with mismatching k_aut")
1625     with con:
1626         cur = con.cursor()
1627         cur.execute("UPDATE reauth SET k_aut='0000000000000000000000000000000000000000000000000000000000000000' WHERE permanent='6555444333222111'")
1628     eap_reauth(dev[0], "AKA'", expect_failure=True)
1629     dev[0].request("REMOVE_NETWORK all")
1630 
1631     eap_connect(dev[0], hapd, "AKA'", "6555444333222111",
1632                 password="5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123")
1633     with con:
1634         cur = con.cursor()
1635         cur.execute("UPDATE reauth SET counter='10' WHERE permanent='6555444333222111'")
1636     eap_reauth(dev[0], "AKA'")
1637     hapd.wait_4way_hs()
1638     with con:
1639         cur = con.cursor()
1640         cur.execute("UPDATE reauth SET counter='10' WHERE permanent='6555444333222111'")
1641     logger.info("AKA' reauth with mismatching counter")
1642     eap_reauth(dev[0], "AKA'")
1643     hapd.wait_4way_hs()
1644     dev[0].request("REMOVE_NETWORK all")
1645     dev[0].wait_disconnected()
1646     hapd.wait_sta_disconnect()
1647 
1648     eap_connect(dev[0], hapd, "AKA'", "6555444333222111",
1649                 password="5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123")
1650     with con:
1651         cur = con.cursor()
1652         cur.execute("UPDATE reauth SET counter='1001' WHERE permanent='6555444333222111'")
1653     logger.info("AKA' reauth with max reauth count reached")
1654     eap_reauth(dev[0], "AKA'")
1655     hapd.wait_4way_hs()
1656 
1657 def test_ap_wpa2_eap_aka_prime_ext_auth_fail(dev, apdev):
1658     """EAP-AKA' with external UMTS auth and auth failing"""
1659     try:
1660         _test_ap_wpa2_eap_aka_prime_ext_auth_fail(dev, apdev)
1661     finally:
1662         dev[0].request("SET external_sim 0")
1663 
1664 def _test_ap_wpa2_eap_aka_prime_ext_auth_fail(dev, apdev):
1665     check_hlr_auc_gw_support()
1666     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1667     hostapd.add_ap(apdev[0], params)
1668     dev[0].request("SET external_sim 1")
1669     id = dev[0].connect("test-wpa2-eap", eap="AKA'", key_mgmt="WPA-EAP",
1670                         identity="6555444333222111",
1671                         wait_connect=False, scan_freq="2412")
1672 
1673     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
1674     if ev is None:
1675         raise Exception("Wait for external SIM processing request timed out")
1676     p = ev.split(':', 2)
1677     rid = p[0].split('-')[3]
1678     dev[0].request("CTRL-RSP-SIM-" + rid + ":UMTS-FAIL")
1679     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
1680     if ev is None:
1681         raise Exception("EAP failure not reported")
1682     dev[0].request("REMOVE_NETWORK all")
1683     dev[0].wait_disconnected()
1684 
1685 def test_ap_wpa2_eap_aka_prime_ext(dev, apdev):
1686     """EAP-AKA' with external UMTS auth to hit Synchronization-Failure"""
1687     try:
1688         _test_ap_wpa2_eap_aka_prime_ext(dev, apdev)
1689     finally:
1690         dev[0].request("SET external_sim 0")
1691 
1692 def _test_ap_wpa2_eap_aka_prime_ext(dev, apdev):
1693     check_hlr_auc_gw_support()
1694     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1695     hostapd.add_ap(apdev[0], params)
1696     dev[0].request("SET external_sim 1")
1697     id = dev[0].connect("test-wpa2-eap", eap="AKA'", key_mgmt="WPA-EAP",
1698                         identity="6555444333222111",
1699                         password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123",
1700                         wait_connect=False, scan_freq="2412")
1701     ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=15)
1702     if ev is None:
1703         raise Exception("Network connected timed out")
1704 
1705     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
1706     if ev is None:
1707         raise Exception("Wait for external SIM processing request timed out")
1708     p = ev.split(':', 2)
1709     if p[1] != "UMTS-AUTH":
1710         raise Exception("Unexpected CTRL-REQ-SIM type")
1711     rid = p[0].split('-')[3]
1712     # This will fail during UMTS auth validation
1713     if "OK" not in dev[0].request("CTRL-RSP-SIM-" + rid + ":UMTS-AUTS:112233445566778899aabbccddee"):
1714         raise Exception("CTRL-RSP-SIM failed")
1715     ev = dev[0].wait_event(["CTRL-REQ-SIM"], timeout=15)
1716     if ev is None:
1717         raise Exception("Wait for external SIM processing request timed out")
1718 
1719 def test_ap_wpa2_eap_ttls_pap(dev, apdev):
1720     """WPA2-Enterprise connection using EAP-TTLS/PAP"""
1721     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1722     hapd = hostapd.add_ap(apdev[0], params)
1723     key_mgmt = hapd.get_config()['key_mgmt']
1724     if key_mgmt.split(' ')[0] != "WPA-EAP":
1725         raise Exception("Unexpected GET_CONFIG(key_mgmt): " + key_mgmt)
1726     eap_connect(dev[0], hapd, "TTLS", "pap user",
1727                 anonymous_identity="ttls", password="password",
1728                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP")
1729     hwsim_utils.test_connectivity(dev[0], hapd)
1730     eap_reauth(dev[0], "TTLS")
1731     check_mib(dev[0], [("dot11RSNAAuthenticationSuiteRequested", "00-0f-ac-1"),
1732                        ("dot11RSNAAuthenticationSuiteSelected", "00-0f-ac-1")])
1733 
1734 def test_ap_wpa2_eap_ttls_pap_subject_match(dev, apdev):
1735     """WPA2-Enterprise connection using EAP-TTLS/PAP and (alt)subject_match"""
1736     check_subject_match_support(dev[0])
1737     check_altsubject_match_support(dev[0])
1738     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1739     hapd = hostapd.add_ap(apdev[0], params)
1740     eap_connect(dev[0], hapd, "TTLS", "pap user",
1741                 anonymous_identity="ttls", password="password",
1742                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP",
1743                 subject_match="/C=FI/O=w1.fi/CN=server.w1.fi",
1744                 altsubject_match="EMAIL:noone@example.com;DNS:server.w1.fi;URI:http://example.com/")
1745     eap_reauth(dev[0], "TTLS")
1746 
1747 def test_ap_wpa2_eap_ttls_pap_check_cert_subject(dev, apdev):
1748     """EAP-TTLS/PAP and check_cert_subject"""
1749     check_check_cert_subject_support(dev[0])
1750     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1751     hapd = hostapd.add_ap(apdev[0], params)
1752     tests = ["C=FI/O=w1.fi/CN=server.w1.fi",
1753              "C=FI/O=w1.fi",
1754              "C=FI/CN=server.w1.fi",
1755              "O=w1.fi/CN=server.w1.fi",
1756              "C=FI",
1757              "O=w1.fi",
1758              "O=w1.*",
1759              "CN=server.w1.fi",
1760              "*"]
1761     for test in tests:
1762         eap_connect(dev[0], hapd, "TTLS", "pap user",
1763                     anonymous_identity="ttls", password="password",
1764                     ca_cert="auth_serv/ca.pem", phase2="auth=PAP",
1765                     check_cert_subject=test)
1766         dev[0].request("REMOVE_NETWORK all")
1767         dev[0].wait_disconnected()
1768         dev[0].dump_monitor()
1769 
1770 def test_ap_wpa2_eap_ttls_pap_check_cert_subject_neg(dev, apdev):
1771     """EAP-TTLS/PAP and check_cert_subject (negative)"""
1772     check_check_cert_subject_support(dev[0])
1773     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1774     hapd = hostapd.add_ap(apdev[0], params)
1775     tests = ["C=US",
1776              "C",
1777              "C=FI1*",
1778              "O=w1.f",
1779              "O=w1.fi1",
1780              "O=w1.fi/O=foo",
1781              "O=foo/O=w1.fi",
1782              "O=w1.fi/O=w1.fi"]
1783     for test in tests:
1784         eap_connect(dev[0], hapd, "TTLS", "pap user",
1785                     anonymous_identity="ttls", password="password",
1786                     ca_cert="auth_serv/ca.pem", phase2="auth=PAP",
1787                     expect_failure=True, expect_cert_error=12,
1788                     check_cert_subject=test)
1789         dev[0].request("REMOVE_NETWORK all")
1790         dev[0].dump_monitor()
1791 
1792 def test_ap_wpa2_eap_ttls_pap_incorrect_password(dev, apdev):
1793     """WPA2-Enterprise connection using EAP-TTLS/PAP - incorrect password"""
1794     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1795     hapd = hostapd.add_ap(apdev[0], params)
1796     eap_connect(dev[0], hapd, "TTLS", "pap user",
1797                 anonymous_identity="ttls", password="wrong",
1798                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP",
1799                 expect_failure=True)
1800     eap_connect(dev[1], hapd, "TTLS", "user",
1801                 anonymous_identity="ttls", password="password",
1802                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP",
1803                 expect_failure=True)
1804 
1805 def test_ap_wpa2_eap_ttls_chap(dev, apdev):
1806     """WPA2-Enterprise connection using EAP-TTLS/CHAP"""
1807     skip_with_fips(dev[0])
1808     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1809     hapd = hostapd.add_ap(apdev[0], params)
1810     eap_connect(dev[0], hapd, "TTLS", "chap user",
1811                 anonymous_identity="ttls", password="password",
1812                 ca_cert="auth_serv/ca.der", phase2="auth=CHAP")
1813     hwsim_utils.test_connectivity(dev[0], hapd)
1814     eap_reauth(dev[0], "TTLS")
1815 
1816 def test_ap_wpa2_eap_ttls_chap_altsubject_match(dev, apdev):
1817     """WPA2-Enterprise connection using EAP-TTLS/CHAP"""
1818     skip_with_fips(dev[0])
1819     check_altsubject_match_support(dev[0])
1820     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1821     hapd = hostapd.add_ap(apdev[0], params)
1822     eap_connect(dev[0], hapd, "TTLS", "chap user",
1823                 anonymous_identity="ttls", password="password",
1824                 ca_cert="auth_serv/ca.der", phase2="auth=CHAP",
1825                 altsubject_match="EMAIL:noone@example.com;URI:http://example.com/;DNS:server.w1.fi")
1826     eap_reauth(dev[0], "TTLS")
1827 
1828 def test_ap_wpa2_eap_ttls_chap_incorrect_password(dev, apdev):
1829     """WPA2-Enterprise connection using EAP-TTLS/CHAP - incorrect password"""
1830     skip_with_fips(dev[0])
1831     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1832     hapd = hostapd.add_ap(apdev[0], params)
1833     eap_connect(dev[0], hapd, "TTLS", "chap user",
1834                 anonymous_identity="ttls", password="wrong",
1835                 ca_cert="auth_serv/ca.pem", phase2="auth=CHAP",
1836                 expect_failure=True)
1837     eap_connect(dev[1], hapd, "TTLS", "user",
1838                 anonymous_identity="ttls", password="password",
1839                 ca_cert="auth_serv/ca.pem", phase2="auth=CHAP",
1840                 expect_failure=True)
1841 
1842 def test_ap_wpa2_eap_ttls_mschap(dev, apdev):
1843     """WPA2-Enterprise connection using EAP-TTLS/MSCHAP"""
1844     skip_with_fips(dev[0])
1845     check_domain_suffix_match(dev[0])
1846     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1847     hapd = hostapd.add_ap(apdev[0], params)
1848     eap_connect(dev[0], hapd, "TTLS", "mschap user",
1849                 anonymous_identity="ttls", password="password",
1850                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
1851                 domain_suffix_match="server.w1.fi")
1852     hwsim_utils.test_connectivity(dev[0], hapd)
1853     eap_reauth(dev[0], "TTLS")
1854     dev[0].request("REMOVE_NETWORK all")
1855     eap_connect(dev[0], hapd, "TTLS", "mschap user",
1856                 anonymous_identity="ttls", password="password",
1857                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
1858                 fragment_size="200")
1859     dev[0].request("REMOVE_NETWORK all")
1860     dev[0].wait_disconnected()
1861     eap_connect(dev[0], hapd, "TTLS", "mschap user",
1862                 anonymous_identity="ttls",
1863                 password_hex="hash:8846f7eaee8fb117ad06bdd830b7586c",
1864                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP")
1865 
1866 def test_ap_wpa2_eap_ttls_mschap_incorrect_password(dev, apdev):
1867     """WPA2-Enterprise connection using EAP-TTLS/MSCHAP - incorrect password"""
1868     skip_with_fips(dev[0])
1869     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1870     hapd = hostapd.add_ap(apdev[0], params)
1871     eap_connect(dev[0], hapd, "TTLS", "mschap user",
1872                 anonymous_identity="ttls", password="wrong",
1873                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
1874                 expect_failure=True)
1875     eap_connect(dev[1], hapd, "TTLS", "user",
1876                 anonymous_identity="ttls", password="password",
1877                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
1878                 expect_failure=True)
1879     eap_connect(dev[2], hapd, "TTLS", "no such user",
1880                 anonymous_identity="ttls", password="password",
1881                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
1882                 expect_failure=True)
1883 
1884 def test_ap_wpa2_eap_ttls_mschapv2(dev, apdev):
1885     """WPA2-Enterprise connection using EAP-TTLS/MSCHAPv2"""
1886     check_domain_suffix_match(dev[0])
1887     check_eap_capa(dev[0], "MSCHAPV2")
1888     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1889     hapd = hostapd.add_ap(apdev[0], params)
1890     eap_connect(dev[0], hapd, "TTLS", "DOMAIN\\mschapv2 user",
1891                 anonymous_identity="ttls", password="password",
1892                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1893                 domain_suffix_match="server.w1.fi")
1894     hwsim_utils.test_connectivity(dev[0], hapd)
1895     sta1 = hapd.get_sta(dev[0].p2p_interface_addr())
1896     eapol1 = hapd.get_sta(dev[0].p2p_interface_addr(), info="eapol")
1897     eap_reauth(dev[0], "TTLS")
1898     sta2 = hapd.get_sta(dev[0].p2p_interface_addr())
1899     eapol2 = hapd.get_sta(dev[0].p2p_interface_addr(), info="eapol")
1900     if int(sta2['dot1xAuthEapolFramesRx']) <= int(sta1['dot1xAuthEapolFramesRx']):
1901         raise Exception("dot1xAuthEapolFramesRx did not increase")
1902     if int(eapol2['authAuthEapStartsWhileAuthenticated']) < 1:
1903         raise Exception("authAuthEapStartsWhileAuthenticated did not increase")
1904     if int(eapol2['backendAuthSuccesses']) <= int(eapol1['backendAuthSuccesses']):
1905         raise Exception("backendAuthSuccesses did not increase")
1906 
1907     logger.info("Password as hash value")
1908     dev[0].request("REMOVE_NETWORK all")
1909     eap_connect(dev[0], hapd, "TTLS", "DOMAIN\\mschapv2 user",
1910                 anonymous_identity="ttls",
1911                 password_hex="hash:8846f7eaee8fb117ad06bdd830b7586c",
1912                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
1913 
1914 def test_ap_wpa2_eap_ttls_invalid_phase2(dev, apdev):
1915     """EAP-TTLS with invalid phase2 parameter values"""
1916     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1917     hostapd.add_ap(apdev[0], params)
1918     tests = ["auth=MSCHAPv2", "auth=MSCHAPV2 autheap=MD5",
1919              "autheap=MD5 auth=MSCHAPV2", "auth=PAP auth=CHAP",
1920              "autheap=MD5 autheap=FOO autheap=MSCHAPV2"]
1921     for t in tests:
1922         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
1923                        identity="DOMAIN\\mschapv2 user",
1924                        anonymous_identity="ttls", password="password",
1925                        ca_cert="auth_serv/ca.pem", phase2=t,
1926                        wait_connect=False, scan_freq="2412")
1927         ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=10)
1928         if ev is None or "method=21" not in ev:
1929             raise Exception("EAP-TTLS not started")
1930         ev = dev[0].wait_event(["EAP: Failed to initialize EAP method",
1931                                 "CTRL-EVENT-CONNECTED"], timeout=5)
1932         if ev is None or "CTRL-EVENT-CONNECTED" in ev:
1933             raise Exception("No EAP-TTLS failure reported for phase2=" + t)
1934         dev[0].request("REMOVE_NETWORK all")
1935         dev[0].wait_disconnected()
1936         dev[0].dump_monitor()
1937 
1938 def test_ap_wpa2_eap_ttls_mschapv2_suffix_match(dev, apdev):
1939     """WPA2-Enterprise connection using EAP-TTLS/MSCHAPv2"""
1940     check_domain_match_full(dev[0])
1941     skip_with_fips(dev[0])
1942     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1943     hapd = hostapd.add_ap(apdev[0], params)
1944     eap_connect(dev[0], hapd, "TTLS", "DOMAIN\\mschapv2 user",
1945                 anonymous_identity="ttls", password="password",
1946                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1947                 domain_suffix_match="w1.fi")
1948     hwsim_utils.test_connectivity(dev[0], hapd)
1949     eap_reauth(dev[0], "TTLS")
1950 
1951 def test_ap_wpa2_eap_ttls_mschapv2_domain_match(dev, apdev):
1952     """WPA2-Enterprise connection using EAP-TTLS/MSCHAPv2 (domain_match)"""
1953     check_domain_match(dev[0])
1954     skip_with_fips(dev[0])
1955     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1956     hapd = hostapd.add_ap(apdev[0], params)
1957     eap_connect(dev[0], hapd, "TTLS", "DOMAIN\\mschapv2 user",
1958                 anonymous_identity="ttls", password="password",
1959                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1960                 domain_match="Server.w1.fi")
1961     hwsim_utils.test_connectivity(dev[0], hapd)
1962     eap_reauth(dev[0], "TTLS")
1963 
1964 def test_ap_wpa2_eap_ttls_mschapv2_incorrect_password(dev, apdev):
1965     """WPA2-Enterprise connection using EAP-TTLS/MSCHAPv2 - incorrect password"""
1966     skip_with_fips(dev[0])
1967     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1968     hapd = hostapd.add_ap(apdev[0], params)
1969     eap_connect(dev[0], hapd, "TTLS", "DOMAIN\\mschapv2 user",
1970                 anonymous_identity="ttls", password="password1",
1971                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1972                 expect_failure=True)
1973     eap_connect(dev[1], hapd, "TTLS", "user",
1974                 anonymous_identity="ttls", password="password",
1975                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1976                 expect_failure=True)
1977 
1978 def test_ap_wpa2_eap_ttls_mschapv2_utf8(dev, apdev):
1979     """WPA2-Enterprise connection using EAP-TTLS/MSCHAPv2 and UTF-8 password"""
1980     skip_with_fips(dev[0])
1981     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
1982     hapd = hostapd.add_ap(apdev[0], params)
1983     eap_connect(dev[0], hapd, "TTLS", "utf8-user-hash",
1984                 anonymous_identity="ttls", password="secret-åäö-€-password",
1985                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
1986     eap_connect(dev[1], hapd, "TTLS", "utf8-user",
1987                 anonymous_identity="ttls",
1988                 password_hex="hash:bd5844fad2489992da7fe8c5a01559cf",
1989                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
1990     for p in ["80", "41c041e04141e041", 257*"41"]:
1991         dev[2].connect("test-wpa2-eap", key_mgmt="WPA-EAP",
1992                        eap="TTLS", identity="utf8-user-hash",
1993                        anonymous_identity="ttls", password_hex=p,
1994                        ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
1995                        wait_connect=False, scan_freq="2412")
1996         ev = dev[2].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=1)
1997         if ev is None:
1998             raise Exception("No failure reported")
1999         dev[2].request("REMOVE_NETWORK all")
2000         dev[2].wait_disconnected()
2001 
2002 def test_ap_wpa2_eap_ttls_eap_gtc(dev, apdev):
2003     """WPA2-Enterprise connection using EAP-TTLS/EAP-GTC"""
2004     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2005     hapd = hostapd.add_ap(apdev[0], params)
2006     eap_connect(dev[0], hapd, "TTLS", "user",
2007                 anonymous_identity="ttls", password="password",
2008                 ca_cert="auth_serv/ca.pem", phase2="autheap=GTC")
2009     hwsim_utils.test_connectivity(dev[0], hapd)
2010     eap_reauth(dev[0], "TTLS")
2011 
2012 def test_ap_wpa2_eap_ttls_eap_gtc_incorrect_password(dev, apdev):
2013     """WPA2-Enterprise connection using EAP-TTLS/EAP-GTC - incorrect password"""
2014     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2015     hapd = hostapd.add_ap(apdev[0], params)
2016     eap_connect(dev[0], hapd, "TTLS", "user",
2017                 anonymous_identity="ttls", password="wrong",
2018                 ca_cert="auth_serv/ca.pem", phase2="autheap=GTC",
2019                 expect_failure=True)
2020 
2021 def test_ap_wpa2_eap_ttls_eap_gtc_no_password(dev, apdev):
2022     """WPA2-Enterprise connection using EAP-TTLS/EAP-GTC - no password"""
2023     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2024     hapd = hostapd.add_ap(apdev[0], params)
2025     eap_connect(dev[0], hapd, "TTLS", "user-no-passwd",
2026                 anonymous_identity="ttls", password="password",
2027                 ca_cert="auth_serv/ca.pem", phase2="autheap=GTC",
2028                 expect_failure=True)
2029 
2030 def test_ap_wpa2_eap_ttls_eap_gtc_server_oom(dev, apdev):
2031     """WPA2-Enterprise connection using EAP-TTLS/EAP-GTC - server OOM"""
2032     params = int_eap_server_params()
2033     hapd = hostapd.add_ap(apdev[0], params)
2034     with alloc_fail(hapd, 1, "eap_gtc_init"):
2035         eap_connect(dev[0], hapd, "TTLS", "user",
2036                     anonymous_identity="ttls", password="password",
2037                     ca_cert="auth_serv/ca.pem", phase2="autheap=GTC",
2038                     expect_failure=True)
2039         dev[0].request("REMOVE_NETWORK all")
2040 
2041     with alloc_fail(hapd, 1, "eap_gtc_buildReq"):
2042         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
2043                        eap="TTLS", identity="user",
2044                        anonymous_identity="ttls", password="password",
2045                        ca_cert="auth_serv/ca.pem", phase2="autheap=GTC",
2046                        wait_connect=False, scan_freq="2412")
2047         # This would eventually time out, but we can stop after having reached
2048         # the allocation failure.
2049         for i in range(20):
2050             time.sleep(0.1)
2051             if hapd.request("GET_ALLOC_FAIL").startswith('0'):
2052                 break
2053 
2054 def test_ap_wpa2_eap_ttls_eap_gtc_oom(dev, apdev):
2055     """WPA2-Enterprise connection using EAP-TTLS/EAP-GTC (OOM)"""
2056     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2057     hapd = hostapd.add_ap(apdev[0], params)
2058 
2059     tests = ["eap_gtc_init",
2060              "eap_msg_alloc;eap_gtc_process"]
2061     for func in tests:
2062         with alloc_fail(dev[0], 1, func):
2063             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP",
2064                            scan_freq="2412",
2065                            eap="TTLS", identity="user",
2066                            anonymous_identity="ttls", password="password",
2067                            ca_cert="auth_serv/ca.pem", phase2="autheap=GTC",
2068                            wait_connect=False)
2069             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
2070             dev[0].request("REMOVE_NETWORK all")
2071             dev[0].wait_disconnected()
2072 
2073 def test_ap_wpa2_eap_ttls_eap_md5(dev, apdev):
2074     """WPA2-Enterprise connection using EAP-TTLS/EAP-MD5"""
2075     check_eap_capa(dev[0], "MD5")
2076     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2077     hapd = hostapd.add_ap(apdev[0], params)
2078     eap_connect(dev[0], hapd, "TTLS", "user",
2079                 anonymous_identity="ttls", password="password",
2080                 ca_cert="auth_serv/ca.pem", phase2="autheap=MD5")
2081     hwsim_utils.test_connectivity(dev[0], hapd)
2082     eap_reauth(dev[0], "TTLS")
2083 
2084 def test_ap_wpa2_eap_ttls_eap_md5_incorrect_password(dev, apdev):
2085     """WPA2-Enterprise connection using EAP-TTLS/EAP-MD5 - incorrect password"""
2086     check_eap_capa(dev[0], "MD5")
2087     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2088     hapd = hostapd.add_ap(apdev[0], params)
2089     eap_connect(dev[0], hapd, "TTLS", "user",
2090                 anonymous_identity="ttls", password="wrong",
2091                 ca_cert="auth_serv/ca.pem", phase2="autheap=MD5",
2092                 expect_failure=True)
2093 
2094 def test_ap_wpa2_eap_ttls_eap_md5_no_password(dev, apdev):
2095     """WPA2-Enterprise connection using EAP-TTLS/EAP-MD5 - no password"""
2096     check_eap_capa(dev[0], "MD5")
2097     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2098     hapd = hostapd.add_ap(apdev[0], params)
2099     eap_connect(dev[0], hapd, "TTLS", "user-no-passwd",
2100                 anonymous_identity="ttls", password="password",
2101                 ca_cert="auth_serv/ca.pem", phase2="autheap=MD5",
2102                 expect_failure=True)
2103 
2104 def test_ap_wpa2_eap_ttls_eap_md5_server_oom(dev, apdev):
2105     """WPA2-Enterprise connection using EAP-TTLS/EAP-MD5 - server OOM"""
2106     check_eap_capa(dev[0], "MD5")
2107     params = int_eap_server_params()
2108     hapd = hostapd.add_ap(apdev[0], params)
2109     with alloc_fail(hapd, 1, "eap_md5_init"):
2110         eap_connect(dev[0], hapd, "TTLS", "user",
2111                     anonymous_identity="ttls", password="password",
2112                     ca_cert="auth_serv/ca.pem", phase2="autheap=MD5",
2113                     expect_failure=True)
2114         dev[0].request("REMOVE_NETWORK all")
2115 
2116     with alloc_fail(hapd, 1, "eap_md5_buildReq"):
2117         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
2118                        eap="TTLS", identity="user",
2119                        anonymous_identity="ttls", password="password",
2120                        ca_cert="auth_serv/ca.pem", phase2="autheap=MD5",
2121                        wait_connect=False, scan_freq="2412")
2122         # This would eventually time out, but we can stop after having reached
2123         # the allocation failure.
2124         for i in range(20):
2125             time.sleep(0.1)
2126             if hapd.request("GET_ALLOC_FAIL").startswith('0'):
2127                 break
2128 
2129 def test_ap_wpa2_eap_ttls_eap_mschapv2(dev, apdev):
2130     """WPA2-Enterprise connection using EAP-TTLS/EAP-MSCHAPv2"""
2131     check_eap_capa(dev[0], "MSCHAPV2")
2132     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2133     hapd = hostapd.add_ap(apdev[0], params)
2134     eap_connect(dev[0], hapd, "TTLS", "user",
2135                 anonymous_identity="ttls", password="password",
2136                 ca_cert="auth_serv/ca.pem", phase2="autheap=MSCHAPV2")
2137     hwsim_utils.test_connectivity(dev[0], hapd)
2138     eap_reauth(dev[0], "TTLS")
2139 
2140     logger.info("Negative test with incorrect password")
2141     dev[0].request("REMOVE_NETWORK all")
2142     eap_connect(dev[0], hapd, "TTLS", "user",
2143                 anonymous_identity="ttls", password="password1",
2144                 ca_cert="auth_serv/ca.pem", phase2="autheap=MSCHAPV2",
2145                 expect_failure=True)
2146 
2147 def test_ap_wpa2_eap_ttls_eap_mschapv2_no_password(dev, apdev):
2148     """WPA2-Enterprise connection using EAP-TTLS/EAP-MSCHAPv2 - no password"""
2149     check_eap_capa(dev[0], "MSCHAPV2")
2150     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2151     hapd = hostapd.add_ap(apdev[0], params)
2152     eap_connect(dev[0], hapd, "TTLS", "user-no-passwd",
2153                 anonymous_identity="ttls", password="password",
2154                 ca_cert="auth_serv/ca.pem", phase2="autheap=MSCHAPV2",
2155                 expect_failure=True)
2156 
2157 def test_ap_wpa2_eap_ttls_eap_mschapv2_server_oom(dev, apdev):
2158     """WPA2-Enterprise connection using EAP-TTLS/EAP-MSCHAPv2 - server OOM"""
2159     check_eap_capa(dev[0], "MSCHAPV2")
2160     params = int_eap_server_params()
2161     hapd = hostapd.add_ap(apdev[0], params)
2162     with alloc_fail(hapd, 1, "eap_mschapv2_init"):
2163         eap_connect(dev[0], hapd, "TTLS", "user",
2164                     anonymous_identity="ttls", password="password",
2165                     ca_cert="auth_serv/ca.pem", phase2="autheap=MSCHAPV2",
2166                     expect_failure=True)
2167         dev[0].request("REMOVE_NETWORK all")
2168 
2169     with alloc_fail(hapd, 1, "eap_mschapv2_build_challenge"):
2170         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
2171                        eap="TTLS", identity="user",
2172                        anonymous_identity="ttls", password="password",
2173                        ca_cert="auth_serv/ca.pem", phase2="autheap=MSCHAPV2",
2174                        wait_connect=False, scan_freq="2412")
2175         # This would eventually time out, but we can stop after having reached
2176         # the allocation failure.
2177         for i in range(20):
2178             time.sleep(0.1)
2179             if hapd.request("GET_ALLOC_FAIL").startswith('0'):
2180                 break
2181         dev[0].request("REMOVE_NETWORK all")
2182 
2183     with alloc_fail(hapd, 1, "eap_mschapv2_build_success_req"):
2184         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
2185                        eap="TTLS", identity="user",
2186                        anonymous_identity="ttls", password="password",
2187                        ca_cert="auth_serv/ca.pem", phase2="autheap=MSCHAPV2",
2188                        wait_connect=False, scan_freq="2412")
2189         # This would eventually time out, but we can stop after having reached
2190         # the allocation failure.
2191         for i in range(20):
2192             time.sleep(0.1)
2193             if hapd.request("GET_ALLOC_FAIL").startswith('0'):
2194                 break
2195         dev[0].request("REMOVE_NETWORK all")
2196 
2197     with alloc_fail(hapd, 1, "eap_mschapv2_build_failure_req"):
2198         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
2199                        eap="TTLS", identity="user",
2200                        anonymous_identity="ttls", password="wrong",
2201                        ca_cert="auth_serv/ca.pem", phase2="autheap=MSCHAPV2",
2202                        wait_connect=False, scan_freq="2412")
2203         # This would eventually time out, but we can stop after having reached
2204         # the allocation failure.
2205         for i in range(20):
2206             time.sleep(0.1)
2207             if hapd.request("GET_ALLOC_FAIL").startswith('0'):
2208                 break
2209         dev[0].request("REMOVE_NETWORK all")
2210 
2211 def test_ap_wpa2_eap_ttls_eap_sim(dev, apdev):
2212     """WPA2-Enterprise connection using EAP-TTLS/EAP-SIM"""
2213     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2214     hapd = hostapd.add_ap(apdev[0], params)
2215     eap_connect(dev[0], hapd, "TTLS", "1232010000000000",
2216                 anonymous_identity="1232010000000000@ttls",
2217                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
2218                 ca_cert="auth_serv/ca.pem", phase2="autheap=SIM")
2219     eap_reauth(dev[0], "TTLS")
2220 
2221 def run_ext_sim_auth(hapd, dev):
2222     ev = dev.wait_event(["CTRL-REQ-SIM"], timeout=15)
2223     if ev is None:
2224         raise Exception("Wait for external SIM processing request timed out")
2225     p = ev.split(':', 2)
2226     if p[1] != "GSM-AUTH":
2227         raise Exception("Unexpected CTRL-REQ-SIM type")
2228     rid = p[0].split('-')[3]
2229     rand = p[2].split(' ')[0]
2230 
2231     res = subprocess.check_output(["../../hostapd/hlr_auc_gw",
2232                                    "-m",
2233                                    "auth_serv/hlr_auc_gw.milenage_db",
2234                                    "GSM-AUTH-REQ 232010000000000 " + rand]).decode()
2235     if "GSM-AUTH-RESP" not in res:
2236         raise Exception("Unexpected hlr_auc_gw response")
2237     resp = res.split(' ')[2].rstrip()
2238 
2239     dev.request("CTRL-RSP-SIM-" + rid + ":GSM-AUTH:" + resp)
2240     dev.wait_connected(timeout=15)
2241     hapd.wait_sta()
2242 
2243     dev.dump_monitor()
2244     dev.request("REAUTHENTICATE")
2245     ev = dev.wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=5)
2246     if ev is None:
2247         raise Exception("EAP reauthentication did not succeed")
2248     ev = dev.wait_event(["WPA: Key negotiation completed"], timeout=5)
2249     if ev is None:
2250         raise Exception("Key negotiation did not complete")
2251     dev.dump_monitor()
2252 
2253 def test_ap_wpa2_eap_ttls_eap_sim_ext(dev, apdev):
2254     """WPA2-Enterprise connection using EAP-TTLS/EAP-SIM and external GSM auth"""
2255     check_hlr_auc_gw_support()
2256     try:
2257         run_ap_wpa2_eap_ttls_eap_sim_ext(dev, apdev)
2258     finally:
2259         dev[0].request("SET external_sim 0")
2260 
2261 def run_ap_wpa2_eap_ttls_eap_sim_ext(dev, apdev):
2262     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2263     hapd = hostapd.add_ap(apdev[0], params)
2264     dev[0].request("SET external_sim 1")
2265     dev[0].connect("test-wpa2-eap", eap="TTLS", key_mgmt="WPA-EAP",
2266                    identity="1232010000000000",
2267                    anonymous_identity="1232010000000000@ttls",
2268                    password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
2269                    ca_cert="auth_serv/ca.pem", phase2="autheap=SIM",
2270                    wait_connect=False, scan_freq="2412")
2271     run_ext_sim_auth(hapd, dev[0])
2272 
2273 def test_ap_wpa2_eap_ttls_eap_vendor(dev, apdev):
2274     """WPA2-Enterprise connection using EAP-TTLS/EAP-vendor"""
2275     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2276     hapd = hostapd.add_ap(apdev[0], params)
2277     eap_connect(dev[0], hapd, "TTLS", "vendor-test-2",
2278                 anonymous_identity="ttls",
2279                 ca_cert="auth_serv/ca.pem", phase2="autheap=VENDOR-TEST")
2280 
2281 def test_ap_wpa2_eap_peap_eap_sim(dev, apdev):
2282     """WPA2-Enterprise connection using EAP-PEAP/EAP-SIM"""
2283     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2284     hapd = hostapd.add_ap(apdev[0], params)
2285     eap_connect(dev[0], hapd, "PEAP", "1232010000000000",
2286                 anonymous_identity="1232010000000000@peap",
2287                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
2288                 ca_cert="auth_serv/ca.pem", phase2="auth=SIM")
2289     eap_reauth(dev[0], "PEAP")
2290 
2291 def test_ap_wpa2_eap_peap_eap_sim_ext(dev, apdev):
2292     """WPA2-Enterprise connection using EAP-PEAP/EAP-SIM and external GSM auth"""
2293     check_hlr_auc_gw_support()
2294     try:
2295         run_ap_wpa2_eap_peap_eap_sim_ext(dev, apdev)
2296     finally:
2297         dev[0].request("SET external_sim 0")
2298 
2299 def run_ap_wpa2_eap_peap_eap_sim_ext(dev, apdev):
2300     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2301     hapd = hostapd.add_ap(apdev[0], params)
2302     dev[0].request("SET external_sim 1")
2303     dev[0].connect("test-wpa2-eap", eap="PEAP", key_mgmt="WPA-EAP",
2304                    identity="1232010000000000",
2305                    anonymous_identity="1232010000000000@peap",
2306                    password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
2307                    ca_cert="auth_serv/ca.pem", phase2="auth=SIM",
2308                    wait_connect=False, scan_freq="2412")
2309     run_ext_sim_auth(hapd, dev[0])
2310 
2311 def test_ap_wpa2_eap_fast_eap_sim(dev, apdev):
2312     """WPA2-Enterprise connection using EAP-FAST/EAP-SIM"""
2313     check_eap_capa(dev[0], "FAST")
2314     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2315     hapd = hostapd.add_ap(apdev[0], params)
2316     eap_connect(dev[0], hapd, "FAST", "1232010000000000",
2317                 anonymous_identity="1232010000000000@fast",
2318                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
2319                 phase1="fast_provisioning=2",
2320                 pac_file="blob://fast_pac_auth_sim",
2321                 ca_cert="auth_serv/ca.pem", phase2="auth=SIM")
2322     eap_reauth(dev[0], "FAST")
2323 
2324 def test_ap_wpa2_eap_fast_eap_sim_ext(dev, apdev):
2325     """WPA2-Enterprise connection using EAP-FAST/EAP-SIM and external GSM auth"""
2326     check_hlr_auc_gw_support()
2327     try:
2328         run_ap_wpa2_eap_fast_eap_sim_ext(dev, apdev)
2329     finally:
2330         dev[0].request("SET external_sim 0")
2331 
2332 def run_ap_wpa2_eap_fast_eap_sim_ext(dev, apdev):
2333     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2334     hapd = hostapd.add_ap(apdev[0], params)
2335     dev[0].request("SET external_sim 1")
2336     dev[0].connect("test-wpa2-eap", eap="PEAP", key_mgmt="WPA-EAP",
2337                    identity="1232010000000000",
2338                    anonymous_identity="1232010000000000@peap",
2339                    password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
2340                    phase1="fast_provisioning=2",
2341                    pac_file="blob://fast_pac_auth_sim",
2342                    ca_cert="auth_serv/ca.pem", phase2="auth=SIM",
2343                    wait_connect=False, scan_freq="2412")
2344     run_ext_sim_auth(hapd, dev[0])
2345 
2346 def test_ap_wpa2_eap_ttls_eap_aka(dev, apdev):
2347     """WPA2-Enterprise connection using EAP-TTLS/EAP-AKA"""
2348     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2349     hapd = hostapd.add_ap(apdev[0], params)
2350     eap_connect(dev[0], hapd, "TTLS", "0232010000000000",
2351                 anonymous_identity="0232010000000000@ttls",
2352                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123",
2353                 ca_cert="auth_serv/ca.pem", phase2="autheap=AKA")
2354     eap_reauth(dev[0], "TTLS")
2355 
2356 def test_ap_wpa2_eap_peap_eap_aka(dev, apdev):
2357     """WPA2-Enterprise connection using EAP-PEAP/EAP-AKA"""
2358     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2359     hapd = hostapd.add_ap(apdev[0], params)
2360     eap_connect(dev[0], hapd, "PEAP", "0232010000000000",
2361                 anonymous_identity="0232010000000000@peap",
2362                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123",
2363                 ca_cert="auth_serv/ca.pem", phase2="auth=AKA")
2364     eap_reauth(dev[0], "PEAP")
2365 
2366 def test_ap_wpa2_eap_fast_eap_aka(dev, apdev):
2367     """WPA2-Enterprise connection using EAP-FAST/EAP-AKA"""
2368     check_eap_capa(dev[0], "FAST")
2369     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2370     hapd = hostapd.add_ap(apdev[0], params)
2371     eap_connect(dev[0], hapd, "FAST", "0232010000000000",
2372                 anonymous_identity="0232010000000000@fast",
2373                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123",
2374                 phase1="fast_provisioning=2",
2375                 pac_file="blob://fast_pac_auth_aka",
2376                 ca_cert="auth_serv/ca.pem", phase2="auth=AKA")
2377     eap_reauth(dev[0], "FAST")
2378 
2379 def test_ap_wpa2_eap_peap_eap_mschapv2(dev, apdev):
2380     """WPA2-Enterprise connection using EAP-PEAP/EAP-MSCHAPv2"""
2381     check_eap_capa(dev[0], "MSCHAPV2")
2382     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2383     hapd = hostapd.add_ap(apdev[0], params)
2384     eap_connect(dev[0], hapd, "PEAP", "user",
2385                 anonymous_identity="peap", password="password",
2386                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
2387     hwsim_utils.test_connectivity(dev[0], hapd)
2388     eap_reauth(dev[0], "PEAP")
2389     dev[0].request("REMOVE_NETWORK all")
2390     eap_connect(dev[0], hapd, "PEAP", "user",
2391                 anonymous_identity="peap", password="password",
2392                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2393                 fragment_size="200")
2394 
2395     logger.info("Password as hash value")
2396     dev[0].request("REMOVE_NETWORK all")
2397     eap_connect(dev[0], hapd, "PEAP", "user",
2398                 anonymous_identity="peap",
2399                 password_hex="hash:8846f7eaee8fb117ad06bdd830b7586c",
2400                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
2401 
2402     logger.info("Negative test with incorrect password")
2403     dev[0].request("REMOVE_NETWORK all")
2404     eap_connect(dev[0], hapd, "PEAP", "user",
2405                 anonymous_identity="peap", password="password1",
2406                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2407                 expect_failure=True)
2408 
2409 def test_ap_wpa2_eap_peap_eap_mschapv2_domain(dev, apdev):
2410     """WPA2-Enterprise connection using EAP-PEAP/EAP-MSCHAPv2 with domain"""
2411     check_eap_capa(dev[0], "MSCHAPV2")
2412     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2413     hapd = hostapd.add_ap(apdev[0], params)
2414     eap_connect(dev[0], hapd, "PEAP", r"DOMAIN\user3",
2415                 anonymous_identity="peap", password="password",
2416                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
2417     hwsim_utils.test_connectivity(dev[0], hapd)
2418     eap_reauth(dev[0], "PEAP")
2419 
2420 def test_ap_wpa2_eap_peap_eap_mschapv2_incorrect_password(dev, apdev):
2421     """WPA2-Enterprise connection using EAP-PEAP/EAP-MSCHAPv2 - incorrect password"""
2422     check_eap_capa(dev[0], "MSCHAPV2")
2423     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2424     hapd = hostapd.add_ap(apdev[0], params)
2425     eap_connect(dev[0], hapd, "PEAP", "user",
2426                 anonymous_identity="peap", password="wrong",
2427                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2428                 expect_failure=True)
2429 
2430 def test_ap_wpa2_eap_peap_crypto_binding(dev, apdev):
2431     """WPA2-Enterprise connection using EAP-PEAPv0/EAP-MSCHAPv2 and crypto binding"""
2432     check_eap_capa(dev[0], "MSCHAPV2")
2433     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2434     hapd = hostapd.add_ap(apdev[0], params)
2435     eap_connect(dev[0], hapd, "PEAP", "user", password="password",
2436                 ca_cert="auth_serv/ca.pem",
2437                 phase1="peapver=0 crypto_binding=2",
2438                 phase2="auth=MSCHAPV2")
2439     hwsim_utils.test_connectivity(dev[0], hapd)
2440     eap_reauth(dev[0], "PEAP")
2441 
2442     eap_connect(dev[1], hapd, "PEAP", "user", password="password",
2443                 ca_cert="auth_serv/ca.pem",
2444                 phase1="peapver=0 crypto_binding=1",
2445                 phase2="auth=MSCHAPV2")
2446     eap_connect(dev[2], hapd, "PEAP", "user", password="password",
2447                 ca_cert="auth_serv/ca.pem",
2448                 phase1="peapver=0 crypto_binding=0",
2449                 phase2="auth=MSCHAPV2")
2450 
2451 def test_ap_wpa2_eap_peap_crypto_binding_server_oom(dev, apdev):
2452     """WPA2-Enterprise connection using EAP-PEAPv0/EAP-MSCHAPv2 and crypto binding with server OOM"""
2453     check_eap_capa(dev[0], "MSCHAPV2")
2454     params = int_eap_server_params()
2455     hapd = hostapd.add_ap(apdev[0], params)
2456     with alloc_fail(hapd, 1, "eap_mschapv2_getKey"):
2457         eap_connect(dev[0], hapd, "PEAP", "user", password="password",
2458                     ca_cert="auth_serv/ca.pem",
2459                     phase1="peapver=0 crypto_binding=2",
2460                     phase2="auth=MSCHAPV2",
2461                     expect_failure=True, local_error_report=True)
2462 
2463 def test_ap_wpa2_eap_peap_params(dev, apdev):
2464     """WPA2-Enterprise connection using EAP-PEAPv0/EAP-MSCHAPv2 and various parameters"""
2465     check_eap_capa(dev[0], "MSCHAPV2")
2466     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2467     hapd = hostapd.add_ap(apdev[0], params)
2468     eap_connect(dev[0], hapd, "PEAP", "user",
2469                 anonymous_identity="peap", password="password",
2470                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2471                 phase1="peapver=0 peaplabel=1",
2472                 expect_failure=True)
2473     dev[0].request("REMOVE_NETWORK all")
2474     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PEAP",
2475                    identity="user",
2476                    anonymous_identity="peap", password="password",
2477                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2478                    phase1="peap_outer_success=0",
2479                    wait_connect=False, scan_freq="2412")
2480     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=15)
2481     if ev is None:
2482         raise Exception("No EAP success seen")
2483     # This won't succeed to connect with peap_outer_success=0, so stop here.
2484     dev[0].request("REMOVE_NETWORK all")
2485     dev[0].wait_disconnected()
2486     eap_connect(dev[1], hapd, "PEAP", "user", password="password",
2487                 ca_cert="auth_serv/ca.pem",
2488                 phase1="peap_outer_success=1",
2489                 phase2="auth=MSCHAPV2")
2490     eap_connect(dev[2], hapd, "PEAP", "user", password="password",
2491                 ca_cert="auth_serv/ca.pem",
2492                 phase1="peap_outer_success=2",
2493                 phase2="auth=MSCHAPV2")
2494     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PEAP",
2495                    identity="user",
2496                    anonymous_identity="peap", password="password",
2497                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2498                    phase1="peapver=1 peaplabel=1",
2499                    wait_connect=False, scan_freq="2412")
2500     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=15)
2501     if ev is None:
2502         raise Exception("No EAP success seen")
2503     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
2504                             "CTRL-EVENT-DISCONNECTED"], timeout=1)
2505     if ev and "CTRL-EVENT-CONNECTED" in ev:
2506         raise Exception("Unexpected connection")
2507     dev[0].request("REMOVE_NETWORK all")
2508     dev[0].disconnect_and_stop_scan()
2509 
2510     tests = [("peap-ver0", ""),
2511              ("peap-ver1", ""),
2512              ("peap-ver0", "peapver=0"),
2513              ("peap-ver1", "peapver=1")]
2514     for anon, phase1 in tests:
2515         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PEAP",
2516                        identity="user", anonymous_identity=anon,
2517                        password="password", phase1=phase1,
2518                        ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2519                        scan_freq="2412")
2520         dev[0].request("REMOVE_NETWORK all")
2521         dev[0].wait_disconnected()
2522 
2523     tests = [("peap-ver0", "peapver=1"),
2524              ("peap-ver1", "peapver=0")]
2525     for anon, phase1 in tests:
2526         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PEAP",
2527                        identity="user", anonymous_identity=anon,
2528                        password="password", phase1=phase1,
2529                        ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
2530                        wait_connect=False, scan_freq="2412")
2531         ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
2532         if ev is None:
2533             raise Exception("No EAP-Failure seen")
2534         dev[0].request("REMOVE_NETWORK all")
2535         dev[0].wait_disconnected()
2536 
2537     eap_connect(dev[0], hapd, "PEAP", "user", password="password",
2538                 ca_cert="auth_serv/ca.pem",
2539                 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",
2540                 phase2="auth=MSCHAPV2")
2541 
2542 def test_ap_wpa2_eap_peap_eap_gtc(dev, apdev, params):
2543     """WPA2-Enterprise connection using EAP-PEAP/EAP-GTC"""
2544     p = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2545     hapd = hostapd.add_ap(apdev[0], p)
2546     eap_connect(dev[0], hapd, "PEAP", "user", phase1="peapver=1",
2547                 anonymous_identity="peap", password="password",
2548                 ca_cert="auth_serv/ca.pem", phase2="auth=GTC")
2549 
2550 def test_ap_wpa2_eap_peap_eap_tls(dev, apdev):
2551     """WPA2-Enterprise connection using EAP-PEAP/EAP-TLS"""
2552     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2553     hapd = hostapd.add_ap(apdev[0], params)
2554     eap_connect(dev[0], hapd, "PEAP", "cert user",
2555                 ca_cert="auth_serv/ca.pem", phase2="auth=TLS",
2556                 ca_cert2="auth_serv/ca.pem",
2557                 client_cert2="auth_serv/user.pem",
2558                 private_key2="auth_serv/user.key")
2559     eap_reauth(dev[0], "PEAP")
2560 
2561 def test_ap_wpa2_eap_peap_eap_vendor(dev, apdev):
2562     """WPA2-Enterprise connection using EAP-PEAP/EAP-vendor"""
2563     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2564     hapd = hostapd.add_ap(apdev[0], params)
2565     eap_connect(dev[0], hapd, "PEAP", "vendor-test-2",
2566                 ca_cert="auth_serv/ca.pem", phase2="auth=VENDOR-TEST")
2567 
2568 def test_ap_wpa2_eap_tls(dev, apdev):
2569     """WPA2-Enterprise connection using EAP-TLS"""
2570     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2571     hapd = hostapd.add_ap(apdev[0], params)
2572     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
2573                 client_cert="auth_serv/user.pem",
2574                 private_key="auth_serv/user.key")
2575     eap_reauth(dev[0], "TLS")
2576 
2577 def test_eap_tls_pkcs8_pkcs5_v2_des3(dev, apdev):
2578     """WPA2-Enterprise connection using EAP-TLS and PKCS #8, PKCS #5 v2 DES3 key"""
2579     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2580     hapd = hostapd.add_ap(apdev[0], params)
2581     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
2582                 client_cert="auth_serv/user.pem",
2583                 private_key="auth_serv/user.key.pkcs8",
2584                 private_key_passwd="whatever")
2585 
2586 def test_eap_tls_pkcs8_pkcs5_v15(dev, apdev):
2587     """WPA2-Enterprise connection using EAP-TLS and PKCS #8, PKCS #5 v1.5 key"""
2588     check_pkcs5_v15_support(dev[0])
2589     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2590     hapd = hostapd.add_ap(apdev[0], params)
2591     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
2592                 client_cert="auth_serv/user.pem",
2593                 private_key="auth_serv/user.key.pkcs8.pkcs5v15",
2594                 private_key_passwd="whatever")
2595 
2596 def test_ap_wpa2_eap_tls_blob(dev, apdev):
2597     """WPA2-Enterprise connection using EAP-TLS and config blobs"""
2598     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2599     hapd = hostapd.add_ap(apdev[0], params)
2600     cert = read_pem("auth_serv/ca.pem")
2601     if "OK" not in dev[0].request("SET blob cacert " +  binascii.hexlify(cert).decode()):
2602         raise Exception("Could not set cacert blob")
2603     cert = read_pem("auth_serv/user.pem")
2604     if "OK" not in dev[0].request("SET blob usercert " + binascii.hexlify(cert).decode()):
2605         raise Exception("Could not set usercert blob")
2606     key = read_pem("auth_serv/user.rsa-key")
2607     if "OK" not in dev[0].request("SET blob userkey " + binascii.hexlify(key).decode()):
2608         raise Exception("Could not set cacert blob")
2609     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="blob://cacert",
2610                 client_cert="blob://usercert",
2611                 private_key="blob://userkey")
2612 
2613 def test_ap_wpa2_eap_tls_blob_pem(dev, apdev):
2614     """WPA2-Enterprise connection using EAP-TLS and config blobs (PEM)"""
2615     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2616     hapd = hostapd.add_ap(apdev[0], params)
2617     cert = read_pem("auth_serv/ca.pem", decode=False)
2618     if "OK" not in dev[0].request("SET blob cacert " +  binascii.hexlify(cert).decode()):
2619         raise Exception("Could not set cacert blob")
2620     cert = read_pem("auth_serv/user.pem", decode=False)
2621     if "OK" not in dev[0].request("SET blob usercert " + binascii.hexlify(cert).decode()):
2622         raise Exception("Could not set usercert blob")
2623     key = read_pem("auth_serv/user.key.pkcs8", decode=False)
2624     if "OK" not in dev[0].request("SET blob userkey " + binascii.hexlify(key).decode()):
2625         raise Exception("Could not set cacert blob")
2626     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="blob://cacert",
2627                 client_cert="blob://usercert",
2628                 private_key="blob://userkey",
2629                 private_key_passwd="whatever")
2630 
2631 def test_ap_wpa2_eap_tls_blob_missing(dev, apdev):
2632     """EAP-TLS and config blob missing"""
2633     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2634     hostapd.add_ap(apdev[0], params)
2635     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
2636                    identity="tls user",
2637                    ca_cert="blob://testing-blob-does-not-exist",
2638                    client_cert="blob://testing-blob-does-not-exist",
2639                    private_key="blob://testing-blob-does-not-exist",
2640                    wait_connect=False, scan_freq="2412")
2641     ev = dev[0].wait_event(["EAP: Failed to initialize EAP method"], timeout=10)
2642     if ev is None:
2643         raise Exception("EAP failure not reported")
2644     dev[0].request("REMOVE_NETWORK all")
2645     dev[0].wait_disconnected()
2646 
2647 def test_ap_wpa2_eap_tls_with_tls_len(dev, apdev):
2648     """EAP-TLS and TLS Message Length in unfragmented packets"""
2649     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2650     hapd = hostapd.add_ap(apdev[0], params)
2651     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
2652                 phase1="include_tls_length=1",
2653                 client_cert="auth_serv/user.pem",
2654                 private_key="auth_serv/user.key")
2655 
2656 def test_ap_wpa2_eap_tls_pkcs12(dev, apdev):
2657     """WPA2-Enterprise connection using EAP-TLS and PKCS#12"""
2658     check_pkcs12_support(dev[0])
2659     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2660     hapd = hostapd.add_ap(apdev[0], params)
2661     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
2662                 private_key="auth_serv/user.pkcs12",
2663                 private_key_passwd="whatever")
2664     dev[0].request("REMOVE_NETWORK all")
2665     dev[0].wait_disconnected()
2666 
2667     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
2668                    identity="tls user",
2669                    ca_cert="auth_serv/ca.pem",
2670                    private_key="auth_serv/user.pkcs12",
2671                    wait_connect=False, scan_freq="2412")
2672     ev = dev[0].wait_event(["CTRL-REQ-PASSPHRASE"])
2673     if ev is None:
2674         raise Exception("Request for private key passphrase timed out")
2675     id = ev.split(':')[0].split('-')[-1]
2676     dev[0].request("CTRL-RSP-PASSPHRASE-" + id + ":whatever")
2677     dev[0].wait_connected(timeout=10)
2678     dev[0].request("REMOVE_NETWORK all")
2679     dev[0].wait_disconnected()
2680 
2681     # Run this twice to verify certificate chain handling with OpenSSL. Use two
2682     # different files to cover both cases of the extra certificate being the
2683     # one that signed the client certificate and it being unrelated to the
2684     # client certificate.
2685     for pkcs12 in "auth_serv/user2.pkcs12", "auth_serv/user3.pkcs12":
2686         for i in range(2):
2687             eap_connect(dev[0], hapd, "TLS", "tls user",
2688                         ca_cert="auth_serv/ca.pem",
2689                         private_key=pkcs12,
2690                         private_key_passwd="whatever")
2691             dev[0].request("REMOVE_NETWORK all")
2692             dev[0].wait_disconnected()
2693 
2694 def test_ap_wpa2_eap_tls_pkcs12_blob(dev, apdev):
2695     """WPA2-Enterprise connection using EAP-TLS and PKCS#12 from configuration blob"""
2696     cert = read_pem("auth_serv/ca.pem")
2697     cacert = binascii.hexlify(cert).decode()
2698     run_ap_wpa2_eap_tls_pkcs12_blob(dev, apdev, cacert)
2699 
2700 def test_ap_wpa2_eap_tls_pkcs12_blob_pem(dev, apdev):
2701     """WPA2-Enterprise connection using EAP-TLS and PKCS#12 from configuration blob and PEM ca_cert blob"""
2702     with open("auth_serv/ca.pem", "r") as f:
2703         lines = f.readlines()
2704         copy = False
2705         cert = ""
2706         for l in lines:
2707             if "-----BEGIN" in l:
2708                 copy = True
2709             if copy:
2710                 cert += l
2711             if "-----END" in l:
2712                 copy = False
2713                 break
2714     cacert = binascii.hexlify(cert.encode()).decode()
2715     run_ap_wpa2_eap_tls_pkcs12_blob(dev, apdev, cacert)
2716 
2717 def run_ap_wpa2_eap_tls_pkcs12_blob(dev, apdev, cacert):
2718     check_pkcs12_support(dev[0])
2719     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2720     hapd = hostapd.add_ap(apdev[0], params)
2721     if "OK" not in dev[0].request("SET blob cacert " + cacert):
2722         raise Exception("Could not set cacert blob")
2723     with open("auth_serv/user.pkcs12", "rb") as f:
2724         if "OK" not in dev[0].request("SET blob pkcs12 " + binascii.hexlify(f.read()).decode()):
2725             raise Exception("Could not set pkcs12 blob")
2726     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="blob://cacert",
2727                 private_key="blob://pkcs12",
2728                 private_key_passwd="whatever")
2729 
2730 def test_ap_wpa2_eap_tls_neg_incorrect_trust_root(dev, apdev):
2731     """WPA2-Enterprise negative test - incorrect trust root"""
2732     check_eap_capa(dev[0], "MSCHAPV2")
2733     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2734     hostapd.add_ap(apdev[0], params)
2735     cert = read_pem("auth_serv/ca-incorrect.pem")
2736     if "OK" not in dev[0].request("SET blob cacert " + binascii.hexlify(cert).decode()):
2737         raise Exception("Could not set cacert blob")
2738     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
2739                    identity="DOMAIN\\mschapv2 user", anonymous_identity="ttls",
2740                    password="password", phase2="auth=MSCHAPV2",
2741                    ca_cert="blob://cacert",
2742                    wait_connect=False, scan_freq="2412")
2743     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
2744                    identity="DOMAIN\\mschapv2 user", anonymous_identity="ttls",
2745                    password="password", phase2="auth=MSCHAPV2",
2746                    ca_cert="auth_serv/ca-incorrect.pem",
2747                    wait_connect=False, scan_freq="2412")
2748 
2749     for dev in (dev[0], dev[1]):
2750         ev = dev.wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
2751         if ev is None:
2752             raise Exception("Association and EAP start timed out")
2753 
2754         ev = dev.wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=10)
2755         if ev is None:
2756             raise Exception("EAP method selection timed out")
2757         if "TTLS" not in ev:
2758             raise Exception("Unexpected EAP method")
2759 
2760         ev = dev.wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR",
2761                              "CTRL-EVENT-EAP-SUCCESS",
2762                              "CTRL-EVENT-EAP-FAILURE",
2763                              "CTRL-EVENT-CONNECTED",
2764                              "CTRL-EVENT-DISCONNECTED"], timeout=10)
2765         if ev is None:
2766             raise Exception("EAP result timed out")
2767         if "CTRL-EVENT-EAP-TLS-CERT-ERROR" not in ev:
2768             raise Exception("TLS certificate error not reported")
2769 
2770         ev = dev.wait_event(["CTRL-EVENT-EAP-SUCCESS",
2771                              "CTRL-EVENT-EAP-FAILURE",
2772                              "CTRL-EVENT-CONNECTED",
2773                              "CTRL-EVENT-DISCONNECTED"], timeout=10)
2774         if ev is None:
2775             raise Exception("EAP result(2) timed out")
2776         if "CTRL-EVENT-EAP-FAILURE" not in ev:
2777             raise Exception("EAP failure not reported")
2778 
2779         ev = dev.wait_event(["CTRL-EVENT-CONNECTED",
2780                              "CTRL-EVENT-DISCONNECTED"], timeout=10)
2781         if ev is None:
2782             raise Exception("EAP result(3) timed out")
2783         if "CTRL-EVENT-DISCONNECTED" not in ev:
2784             raise Exception("Disconnection not reported")
2785 
2786         ev = dev.wait_event(["CTRL-EVENT-SSID-TEMP-DISABLED"], timeout=10)
2787         if ev is None:
2788             raise Exception("Network block disabling not reported")
2789 
2790 def test_ap_wpa2_eap_tls_diff_ca_trust(dev, apdev):
2791     """WPA2-Enterprise connection using EAP-TTLS/PAP and different CA trust"""
2792     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2793     hapd = hostapd.add_ap(apdev[0], params)
2794     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
2795                    identity="pap user", anonymous_identity="ttls",
2796                    password="password", phase2="auth=PAP",
2797                    ca_cert="auth_serv/ca.pem",
2798                    wait_connect=True, scan_freq="2412")
2799     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
2800                         identity="pap user", anonymous_identity="ttls",
2801                         password="password", phase2="auth=PAP",
2802                         ca_cert="auth_serv/ca-incorrect.pem",
2803                         only_add_network=True, scan_freq="2412")
2804 
2805     dev[0].request("DISCONNECT")
2806     dev[0].wait_disconnected()
2807     dev[0].dump_monitor()
2808     dev[0].select_network(id, freq="2412")
2809 
2810     ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD vendor=0 method=21"], timeout=15)
2811     if ev is None:
2812         raise Exception("EAP-TTLS not re-started")
2813 
2814     ev = dev[0].wait_disconnected(timeout=15)
2815     if "reason=23" not in ev:
2816         raise Exception("Proper reason code for disconnection not reported")
2817 
2818 def test_ap_wpa2_eap_tls_diff_ca_trust2(dev, apdev):
2819     """WPA2-Enterprise connection using EAP-TTLS/PAP and different CA trust"""
2820     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2821     hapd = hostapd.add_ap(apdev[0], params)
2822     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
2823                    identity="pap user", anonymous_identity="ttls",
2824                    password="password", phase2="auth=PAP",
2825                    wait_connect=True, scan_freq="2412")
2826     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
2827                         identity="pap user", anonymous_identity="ttls",
2828                         password="password", phase2="auth=PAP",
2829                         ca_cert="auth_serv/ca-incorrect.pem",
2830                         only_add_network=True, scan_freq="2412")
2831 
2832     dev[0].request("DISCONNECT")
2833     dev[0].wait_disconnected()
2834     dev[0].dump_monitor()
2835     dev[0].select_network(id, freq="2412")
2836 
2837     ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD vendor=0 method=21"], timeout=15)
2838     if ev is None:
2839         raise Exception("EAP-TTLS not re-started")
2840 
2841     ev = dev[0].wait_disconnected(timeout=15)
2842     if "reason=23" not in ev:
2843         raise Exception("Proper reason code for disconnection not reported")
2844 
2845 def test_ap_wpa2_eap_tls_diff_ca_trust3(dev, apdev):
2846     """WPA2-Enterprise connection using EAP-TTLS/PAP and different CA trust"""
2847     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2848     hapd = hostapd.add_ap(apdev[0], params)
2849     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
2850                         identity="pap user", anonymous_identity="ttls",
2851                         password="password", phase2="auth=PAP",
2852                         ca_cert="auth_serv/ca.pem",
2853                         wait_connect=True, scan_freq="2412")
2854     dev[0].request("DISCONNECT")
2855     dev[0].wait_disconnected()
2856     dev[0].dump_monitor()
2857     dev[0].set_network_quoted(id, "ca_cert", "auth_serv/ca-incorrect.pem")
2858     dev[0].select_network(id, freq="2412")
2859 
2860     ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD vendor=0 method=21"], timeout=15)
2861     if ev is None:
2862         raise Exception("EAP-TTLS not re-started")
2863 
2864     ev = dev[0].wait_disconnected(timeout=15)
2865     if "reason=23" not in ev:
2866         raise Exception("Proper reason code for disconnection not reported")
2867 
2868 def test_ap_wpa2_eap_tls_neg_suffix_match(dev, apdev):
2869     """WPA2-Enterprise negative test - domain suffix mismatch"""
2870     check_domain_suffix_match(dev[0])
2871     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2872     hostapd.add_ap(apdev[0], params)
2873     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
2874                    identity="DOMAIN\\mschapv2 user", anonymous_identity="ttls",
2875                    password="password", phase2="auth=MSCHAPV2",
2876                    ca_cert="auth_serv/ca.pem",
2877                    domain_suffix_match="incorrect.example.com",
2878                    wait_connect=False, scan_freq="2412")
2879 
2880     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
2881     if ev is None:
2882         raise Exception("Association and EAP start timed out")
2883 
2884     ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=10)
2885     if ev is None:
2886         raise Exception("EAP method selection timed out")
2887     if "TTLS" not in ev:
2888         raise Exception("Unexpected EAP method")
2889 
2890     ev = dev[0].wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR",
2891                             "CTRL-EVENT-EAP-SUCCESS",
2892                             "CTRL-EVENT-EAP-FAILURE",
2893                             "CTRL-EVENT-CONNECTED",
2894                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
2895     if ev is None:
2896         raise Exception("EAP result timed out")
2897     if "CTRL-EVENT-EAP-TLS-CERT-ERROR" not in ev:
2898         raise Exception("TLS certificate error not reported")
2899     if "Domain suffix mismatch" not in ev:
2900         raise Exception("Domain suffix mismatch not reported")
2901 
2902     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS",
2903                             "CTRL-EVENT-EAP-FAILURE",
2904                             "CTRL-EVENT-CONNECTED",
2905                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
2906     if ev is None:
2907         raise Exception("EAP result(2) timed out")
2908     if "CTRL-EVENT-EAP-FAILURE" not in ev:
2909         raise Exception("EAP failure not reported")
2910 
2911     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
2912                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
2913     if ev is None:
2914         raise Exception("EAP result(3) timed out")
2915     if "CTRL-EVENT-DISCONNECTED" not in ev:
2916         raise Exception("Disconnection not reported")
2917 
2918     ev = dev[0].wait_event(["CTRL-EVENT-SSID-TEMP-DISABLED"], timeout=10)
2919     if ev is None:
2920         raise Exception("Network block disabling not reported")
2921 
2922 def test_ap_wpa2_eap_tls_neg_domain_match(dev, apdev):
2923     """WPA2-Enterprise negative test - domain mismatch"""
2924     check_domain_match(dev[0])
2925     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2926     hostapd.add_ap(apdev[0], params)
2927     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
2928                    identity="DOMAIN\\mschapv2 user", anonymous_identity="ttls",
2929                    password="password", phase2="auth=MSCHAPV2",
2930                    ca_cert="auth_serv/ca.pem",
2931                    domain_match="w1.fi",
2932                    wait_connect=False, scan_freq="2412")
2933 
2934     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
2935     if ev is None:
2936         raise Exception("Association and EAP start timed out")
2937 
2938     ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=10)
2939     if ev is None:
2940         raise Exception("EAP method selection timed out")
2941     if "TTLS" not in ev:
2942         raise Exception("Unexpected EAP method")
2943 
2944     ev = dev[0].wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR",
2945                             "CTRL-EVENT-EAP-SUCCESS",
2946                             "CTRL-EVENT-EAP-FAILURE",
2947                             "CTRL-EVENT-CONNECTED",
2948                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
2949     if ev is None:
2950         raise Exception("EAP result timed out")
2951     if "CTRL-EVENT-EAP-TLS-CERT-ERROR" not in ev:
2952         raise Exception("TLS certificate error not reported")
2953     if "Domain mismatch" not in ev:
2954         raise Exception("Domain mismatch not reported")
2955 
2956     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS",
2957                             "CTRL-EVENT-EAP-FAILURE",
2958                             "CTRL-EVENT-CONNECTED",
2959                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
2960     if ev is None:
2961         raise Exception("EAP result(2) timed out")
2962     if "CTRL-EVENT-EAP-FAILURE" not in ev:
2963         raise Exception("EAP failure not reported")
2964 
2965     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
2966                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
2967     if ev is None:
2968         raise Exception("EAP result(3) timed out")
2969     if "CTRL-EVENT-DISCONNECTED" not in ev:
2970         raise Exception("Disconnection not reported")
2971 
2972     ev = dev[0].wait_event(["CTRL-EVENT-SSID-TEMP-DISABLED"], timeout=10)
2973     if ev is None:
2974         raise Exception("Network block disabling not reported")
2975 
2976 def test_ap_wpa2_eap_tls_neg_subject_match(dev, apdev):
2977     """WPA2-Enterprise negative test - subject mismatch"""
2978     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
2979     hostapd.add_ap(apdev[0], params)
2980     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
2981                    identity="DOMAIN\\mschapv2 user", anonymous_identity="ttls",
2982                    password="password", phase2="auth=MSCHAPV2",
2983                    ca_cert="auth_serv/ca.pem",
2984                    subject_match="/C=FI/O=w1.fi/CN=example.com",
2985                    wait_connect=False, scan_freq="2412")
2986 
2987     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
2988     if ev is None:
2989         raise Exception("Association and EAP start timed out")
2990 
2991     ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD",
2992                             "EAP: Failed to initialize EAP method"], timeout=10)
2993     if ev is None:
2994         raise Exception("EAP method selection timed out")
2995     if "EAP: Failed to initialize EAP method" in ev:
2996         tls = dev[0].request("GET tls_library")
2997         if tls.startswith("OpenSSL"):
2998             raise Exception("Failed to select EAP method")
2999         logger.info("subject_match not supported - connection failed, so test succeeded")
3000         return
3001     if "TTLS" not in ev:
3002         raise Exception("Unexpected EAP method")
3003 
3004     ev = dev[0].wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR",
3005                             "CTRL-EVENT-EAP-SUCCESS",
3006                             "CTRL-EVENT-EAP-FAILURE",
3007                             "CTRL-EVENT-CONNECTED",
3008                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
3009     if ev is None:
3010         raise Exception("EAP result timed out")
3011     if "CTRL-EVENT-EAP-TLS-CERT-ERROR" not in ev:
3012         raise Exception("TLS certificate error not reported")
3013     if "Subject mismatch" not in ev:
3014         raise Exception("Subject mismatch not reported")
3015 
3016     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS",
3017                             "CTRL-EVENT-EAP-FAILURE",
3018                             "CTRL-EVENT-CONNECTED",
3019                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
3020     if ev is None:
3021         raise Exception("EAP result(2) timed out")
3022     if "CTRL-EVENT-EAP-FAILURE" not in ev:
3023         raise Exception("EAP failure not reported")
3024 
3025     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
3026                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
3027     if ev is None:
3028         raise Exception("EAP result(3) timed out")
3029     if "CTRL-EVENT-DISCONNECTED" not in ev:
3030         raise Exception("Disconnection not reported")
3031 
3032     ev = dev[0].wait_event(["CTRL-EVENT-SSID-TEMP-DISABLED"], timeout=10)
3033     if ev is None:
3034         raise Exception("Network block disabling not reported")
3035 
3036 def test_ap_wpa2_eap_tls_neg_altsubject_match(dev, apdev):
3037     """WPA2-Enterprise negative test - altsubject mismatch"""
3038     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3039     hostapd.add_ap(apdev[0], params)
3040 
3041     tests = ["incorrect.example.com",
3042              "DNS:incorrect.example.com",
3043              "DNS:w1.fi",
3044              "DNS:erver.w1.fi"]
3045     for match in tests:
3046         _test_ap_wpa2_eap_tls_neg_altsubject_match(dev, apdev, match)
3047 
3048 def _test_ap_wpa2_eap_tls_neg_altsubject_match(dev, apdev, match):
3049     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3050                    identity="DOMAIN\\mschapv2 user", anonymous_identity="ttls",
3051                    password="password", phase2="auth=MSCHAPV2",
3052                    ca_cert="auth_serv/ca.pem",
3053                    altsubject_match=match,
3054                    wait_connect=False, scan_freq="2412")
3055 
3056     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
3057     if ev is None:
3058         raise Exception("Association and EAP start timed out")
3059 
3060     ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD",
3061                             "EAP: Failed to initialize EAP method"], timeout=10)
3062     if ev is None:
3063         raise Exception("EAP method selection timed out")
3064     if "EAP: Failed to initialize EAP method" in ev:
3065         tls = dev[0].request("GET tls_library")
3066         if tls.startswith("OpenSSL"):
3067             raise Exception("Failed to select EAP method")
3068         logger.info("altsubject_match not supported - connection failed, so test succeeded")
3069         return
3070     if "TTLS" not in ev:
3071         raise Exception("Unexpected EAP method")
3072 
3073     ev = dev[0].wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR",
3074                             "CTRL-EVENT-EAP-SUCCESS",
3075                             "CTRL-EVENT-EAP-FAILURE",
3076                             "CTRL-EVENT-CONNECTED",
3077                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
3078     if ev is None:
3079         raise Exception("EAP result timed out")
3080     if "CTRL-EVENT-EAP-TLS-CERT-ERROR" not in ev:
3081         raise Exception("TLS certificate error not reported")
3082     if "AltSubject mismatch" not in ev:
3083         raise Exception("altsubject mismatch not reported")
3084 
3085     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS",
3086                             "CTRL-EVENT-EAP-FAILURE",
3087                             "CTRL-EVENT-CONNECTED",
3088                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
3089     if ev is None:
3090         raise Exception("EAP result(2) timed out")
3091     if "CTRL-EVENT-EAP-FAILURE" not in ev:
3092         raise Exception("EAP failure not reported")
3093 
3094     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
3095                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
3096     if ev is None:
3097         raise Exception("EAP result(3) timed out")
3098     if "CTRL-EVENT-DISCONNECTED" not in ev:
3099         raise Exception("Disconnection not reported")
3100 
3101     ev = dev[0].wait_event(["CTRL-EVENT-SSID-TEMP-DISABLED"], timeout=10)
3102     if ev is None:
3103         raise Exception("Network block disabling not reported")
3104 
3105     dev[0].request("REMOVE_NETWORK all")
3106 
3107 def test_ap_wpa2_eap_unauth_tls(dev, apdev):
3108     """WPA2-Enterprise connection using UNAUTH-TLS"""
3109     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3110     hapd = hostapd.add_ap(apdev[0], params)
3111     eap_connect(dev[0], hapd, "UNAUTH-TLS", "unauth-tls",
3112                 ca_cert="auth_serv/ca.pem")
3113     eap_reauth(dev[0], "UNAUTH-TLS")
3114 
3115 def test_ap_wpa2_eap_ttls_server_cert_hash(dev, apdev):
3116     """WPA2-Enterprise connection using EAP-TTLS and server certificate hash"""
3117     check_cert_probe_support(dev[0])
3118     skip_with_fips(dev[0])
3119     srv_cert_hash = "afe085c36fd9533180aebfa286068e7cf093036e7178138f353a1dfeada129f8"
3120     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3121     hapd = hostapd.add_ap(apdev[0], params)
3122     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3123                    identity="probe", ca_cert="probe://",
3124                    wait_connect=False, scan_freq="2412")
3125     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
3126     if ev is None:
3127         raise Exception("Association and EAP start timed out")
3128     ev = dev[0].wait_event(["CTRL-EVENT-EAP-PEER-CERT depth=0"], timeout=10)
3129     if ev is None:
3130         raise Exception("No peer server certificate event seen")
3131     if "hash=" + srv_cert_hash not in ev:
3132         raise Exception("Expected server certificate hash not reported")
3133     ev = dev[0].wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR"], timeout=10)
3134     if ev is None:
3135         raise Exception("EAP result timed out")
3136     if "Server certificate chain probe" not in ev:
3137         raise Exception("Server certificate probe not reported")
3138     dev[0].wait_disconnected(timeout=10)
3139     dev[0].request("REMOVE_NETWORK all")
3140 
3141     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3142                    identity="DOMAIN\\mschapv2 user", anonymous_identity="ttls",
3143                    password="password", phase2="auth=MSCHAPV2",
3144                    ca_cert="hash://server/sha256/5a1bc1296205e6fdbe3979728efe3920798885c1c4590b5f90f43222d239ca6a",
3145                    wait_connect=False, scan_freq="2412")
3146     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
3147     if ev is None:
3148         raise Exception("Association and EAP start timed out")
3149     ev = dev[0].wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR"], timeout=10)
3150     if ev is None:
3151         raise Exception("EAP result timed out")
3152     if "Server certificate mismatch" not in ev:
3153         raise Exception("Server certificate mismatch not reported")
3154     dev[0].wait_disconnected(timeout=10)
3155     dev[0].request("REMOVE_NETWORK all")
3156 
3157     eap_connect(dev[0], hapd, "TTLS", "DOMAIN\\mschapv2 user",
3158                 anonymous_identity="ttls", password="password",
3159                 ca_cert="hash://server/sha256/" + srv_cert_hash,
3160                 phase2="auth=MSCHAPV2")
3161 
3162 def test_ap_wpa2_eap_ttls_server_cert_hash_invalid(dev, apdev):
3163     """WPA2-Enterprise connection using EAP-TTLS and server certificate hash (invalid config)"""
3164     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3165     hostapd.add_ap(apdev[0], params)
3166     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3167                    identity="DOMAIN\\mschapv2 user", anonymous_identity="ttls",
3168                    password="password", phase2="auth=MSCHAPV2",
3169                    ca_cert="hash://server/md5/5a1bc1296205e6fdbe3979728efe3920798885c1c4590b5f90f43222d239ca6a",
3170                    wait_connect=False, scan_freq="2412")
3171     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3172                    identity="DOMAIN\\mschapv2 user", anonymous_identity="ttls",
3173                    password="password", phase2="auth=MSCHAPV2",
3174                    ca_cert="hash://server/sha256/5a1bc1296205e6fdbe3979728efe3920798885c1c4590b5f90f43222d239ca",
3175                    wait_connect=False, scan_freq="2412")
3176     dev[2].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3177                    identity="DOMAIN\\mschapv2 user", anonymous_identity="ttls",
3178                    password="password", phase2="auth=MSCHAPV2",
3179                    ca_cert="hash://server/sha256/5a1bc1296205e6fdbe3979728efe3920798885c1c4590b5f90f43222d239ca6Q",
3180                    wait_connect=False, scan_freq="2412")
3181     for i in range(0, 3):
3182         ev = dev[i].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
3183         if ev is None:
3184             raise Exception("Association and EAP start timed out")
3185         ev = dev[i].wait_event(["EAP: Failed to initialize EAP method: vendor 0 method 21 (TTLS)"], timeout=5)
3186         if ev is None:
3187             raise Exception("Did not report EAP method initialization failure")
3188 
3189 def test_ap_wpa2_eap_pwd(dev, apdev):
3190     """WPA2-Enterprise connection using EAP-pwd"""
3191     check_eap_capa(dev[0], "PWD")
3192     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3193     hapd = hostapd.add_ap(apdev[0], params)
3194     eap_connect(dev[0], hapd, "PWD", "pwd user", password="secret password")
3195     eap_reauth(dev[0], "PWD")
3196     dev[0].request("REMOVE_NETWORK all")
3197 
3198     eap_connect(dev[1], hapd, "PWD",
3199                 "pwd.user@test123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890.example.com",
3200                 password="secret password",
3201                 fragment_size="90")
3202 
3203     logger.info("Negative test with incorrect password")
3204     eap_connect(dev[2], hapd, "PWD", "pwd user", password="secret-password",
3205                 expect_failure=True, local_error_report=True)
3206 
3207     eap_connect(dev[0], hapd, "PWD",
3208                 "pwd.user@test123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890.example.com",
3209                 password="secret password",
3210                 fragment_size="31")
3211 
3212 def test_ap_wpa2_eap_pwd_nthash(dev, apdev):
3213     """WPA2-Enterprise connection using EAP-pwd and NTHash"""
3214     check_eap_capa(dev[0], "PWD")
3215     skip_with_fips(dev[0])
3216     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3217     hapd = hostapd.add_ap(apdev[0], params)
3218     eap_connect(dev[0], hapd, "PWD", "pwd-hash", password="secret password")
3219     eap_connect(dev[1], hapd, "PWD", "pwd-hash",
3220                 password_hex="hash:e3718ece8ab74792cbbfffd316d2d19a")
3221     eap_connect(dev[2], hapd, "PWD", "pwd user",
3222                 password_hex="hash:e3718ece8ab74792cbbfffd316d2d19a",
3223                 expect_failure=True, local_error_report=True)
3224 
3225 def test_ap_wpa2_eap_pwd_salt_sha1(dev, apdev):
3226     """WPA2-Enterprise connection using EAP-pwd and salted password SHA-1"""
3227     check_eap_capa(dev[0], "PWD")
3228     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3229     hapd = hostapd.add_ap(apdev[0], params)
3230     eap_connect(dev[0], hapd, "PWD", "pwd-hash-sha1",
3231                 password="secret password")
3232 
3233 def test_ap_wpa2_eap_pwd_salt_sha256(dev, apdev):
3234     """WPA2-Enterprise connection using EAP-pwd and salted password SHA256"""
3235     check_eap_capa(dev[0], "PWD")
3236     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3237     hapd = hostapd.add_ap(apdev[0], params)
3238     eap_connect(dev[0], hapd, "PWD", "pwd-hash-sha256",
3239                 password="secret password")
3240 
3241 def test_ap_wpa2_eap_pwd_salt_sha512(dev, apdev):
3242     """WPA2-Enterprise connection using EAP-pwd and salted password SHA512"""
3243     check_eap_capa(dev[0], "PWD")
3244     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3245     hapd = hostapd.add_ap(apdev[0], params)
3246     eap_connect(dev[0], hapd, "PWD", "pwd-hash-sha512",
3247                 password="secret password")
3248 
3249 def test_ap_wpa2_eap_pwd_groups(dev, apdev):
3250     """WPA2-Enterprise connection using various EAP-pwd groups"""
3251     check_eap_capa(dev[0], "PWD")
3252     tls = dev[0].request("GET tls_library")
3253     params = {"ssid": "test-wpa2-eap", "wpa": "2", "wpa_key_mgmt": "WPA-EAP",
3254               "rsn_pairwise": "CCMP", "ieee8021x": "1",
3255               "eap_server": "1", "eap_user_file": "auth_serv/eap_user.conf"}
3256     groups = [19, 20, 21]
3257     for i in groups:
3258         logger.info("Group %d" % i)
3259         params['pwd_group'] = str(i)
3260         hapd = hostapd.add_ap(apdev[0], params)
3261         eap_connect(dev[0], hapd, "PWD", "pwd user",
3262                     password="secret password",
3263                     phase1="eap_pwd_groups=0-65535")
3264         dev[0].request("REMOVE_NETWORK all")
3265         dev[0].wait_disconnected()
3266         dev[0].dump_monitor()
3267         hapd.disable()
3268 
3269 def test_ap_wpa2_eap_pwd_invalid_group(dev, apdev):
3270     """WPA2-Enterprise connection using invalid EAP-pwd group"""
3271     check_eap_capa(dev[0], "PWD")
3272     params = {"ssid": "test-wpa2-eap", "wpa": "2", "wpa_key_mgmt": "WPA-EAP",
3273               "rsn_pairwise": "CCMP", "ieee8021x": "1",
3274               "eap_server": "1", "eap_user_file": "auth_serv/eap_user.conf"}
3275     for i in [0, 25, 26, 27]:
3276         logger.info("Group %d" % i)
3277         params['pwd_group'] = str(i)
3278         hapd = hostapd.add_ap(apdev[0], params)
3279         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PWD",
3280                        identity="pwd user", password="secret password",
3281                        phase1="eap_pwd_groups=0-65535",
3282                        scan_freq="2412", wait_connect=False)
3283         ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3284         if ev is None:
3285             raise Exception("Timeout on EAP failure report (group %d)" % i)
3286         dev[0].request("REMOVE_NETWORK all")
3287         dev[0].wait_disconnected()
3288         dev[0].dump_monitor()
3289         hapd.disable()
3290 
3291 def test_ap_wpa2_eap_pwd_disabled_group(dev, apdev):
3292     """WPA2-Enterprise connection using disabled EAP-pwd group"""
3293     check_eap_capa(dev[0], "PWD")
3294     params = {"ssid": "test-wpa2-eap", "wpa": "2", "wpa_key_mgmt": "WPA-EAP",
3295               "rsn_pairwise": "CCMP", "ieee8021x": "1",
3296               "eap_server": "1", "eap_user_file": "auth_serv/eap_user.conf"}
3297     for i in [19, 21]:
3298         logger.info("Group %d" % i)
3299         params['pwd_group'] = str(i)
3300         hapd = hostapd.add_ap(apdev[0], params)
3301         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PWD",
3302                        identity="pwd user", password="secret password",
3303                        phase1="eap_pwd_groups=20",
3304                        scan_freq="2412", wait_connect=False)
3305         ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3306         if ev is None:
3307             raise Exception("Timeout on EAP failure report (group %d)" % i)
3308         dev[0].request("REMOVE_NETWORK all")
3309         dev[0].wait_disconnected()
3310         dev[0].dump_monitor()
3311         hapd.disable()
3312 
3313     params['pwd_group'] = "20"
3314     hapd = hostapd.add_ap(apdev[0], params)
3315     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PWD",
3316                    identity="pwd user", password="secret password",
3317                    phase1="eap_pwd_groups=20",
3318                    scan_freq="2412")
3319 
3320 def test_ap_wpa2_eap_pwd_as_frag(dev, apdev):
3321     """WPA2-Enterprise connection using EAP-pwd with server fragmentation"""
3322     check_eap_capa(dev[0], "PWD")
3323     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3324     params = {"ssid": "test-wpa2-eap", "wpa": "2", "wpa_key_mgmt": "WPA-EAP",
3325               "rsn_pairwise": "CCMP", "ieee8021x": "1",
3326               "eap_server": "1", "eap_user_file": "auth_serv/eap_user.conf",
3327               "pwd_group": "19", "fragment_size": "40"}
3328     hapd = hostapd.add_ap(apdev[0], params)
3329     eap_connect(dev[0], hapd, "PWD", "pwd user", password="secret password")
3330 
3331 def test_ap_wpa2_eap_gpsk(dev, apdev):
3332     """WPA2-Enterprise connection using EAP-GPSK"""
3333     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3334     hapd = hostapd.add_ap(apdev[0], params)
3335     id = eap_connect(dev[0], hapd, "GPSK", "gpsk user",
3336                      password="abcdefghijklmnop0123456789abcdef")
3337     eap_reauth(dev[0], "GPSK")
3338 
3339     logger.info("Test forced algorithm selection")
3340     for phase1 in ["cipher=1", "cipher=2"]:
3341         dev[0].set_network_quoted(id, "phase1", phase1)
3342         ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
3343         if ev is None:
3344             raise Exception("EAP success timed out")
3345         dev[0].wait_connected(timeout=10)
3346 
3347     logger.info("Test failed algorithm negotiation")
3348     dev[0].set_network_quoted(id, "phase1", "cipher=9")
3349     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
3350     if ev is None:
3351         raise Exception("EAP failure timed out")
3352 
3353     logger.info("Negative test with incorrect password")
3354     dev[0].request("REMOVE_NETWORK all")
3355     eap_connect(dev[0], hapd, "GPSK", "gpsk user",
3356                 password="ffcdefghijklmnop0123456789abcdef",
3357                 expect_failure=True)
3358 
3359 def test_ap_wpa2_eap_sake(dev, apdev):
3360     """WPA2-Enterprise connection using EAP-SAKE"""
3361     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3362     hapd = hostapd.add_ap(apdev[0], params)
3363     eap_connect(dev[0], hapd, "SAKE", "sake user",
3364                 password_hex="0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef")
3365     eap_reauth(dev[0], "SAKE")
3366 
3367     logger.info("Negative test with incorrect password")
3368     dev[0].request("REMOVE_NETWORK all")
3369     eap_connect(dev[0], hapd, "SAKE", "sake user",
3370                 password_hex="ff23456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
3371                 expect_failure=True)
3372 
3373 def test_ap_wpa2_eap_eke(dev, apdev):
3374     """WPA2-Enterprise connection using EAP-EKE"""
3375     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3376     hapd = hostapd.add_ap(apdev[0], params)
3377     id = eap_connect(dev[0], hapd, "EKE", "eke user", password="hello")
3378     eap_reauth(dev[0], "EKE")
3379 
3380     logger.info("Test forced algorithm selection")
3381     for phase1 in ["dhgroup=5 encr=1 prf=2 mac=2",
3382                    "dhgroup=4 encr=1 prf=2 mac=2",
3383                    "dhgroup=3 encr=1 prf=2 mac=2",
3384                    "dhgroup=3 encr=1 prf=1 mac=1"]:
3385         dev[0].set_network_quoted(id, "phase1", phase1)
3386         ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
3387         if ev is None:
3388             raise Exception("EAP success timed out")
3389         dev[0].wait_connected(timeout=10)
3390     dev[0].dump_monitor()
3391 
3392     logger.info("Test failed algorithm negotiation")
3393     dev[0].set_network_quoted(id, "phase1", "dhgroup=9 encr=9 prf=9 mac=9")
3394     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
3395     if ev is None:
3396         raise Exception("EAP failure timed out")
3397     dev[0].dump_monitor()
3398 
3399     logger.info("Test unsupported algorithm proposals")
3400     dev[0].request("REMOVE_NETWORK all")
3401     dev[0].dump_monitor()
3402     eap_connect(dev[0], hapd, "EKE", "eke user", password="hello",
3403                 phase1="dhgroup=2 encr=1 prf=1 mac=1", expect_failure=True)
3404     dev[0].request("REMOVE_NETWORK all")
3405     dev[0].dump_monitor()
3406     eap_connect(dev[0], hapd, "EKE", "eke user", password="hello",
3407                 phase1="dhgroup=1 encr=1 prf=1 mac=1", expect_failure=True)
3408 
3409     logger.info("Negative test with incorrect password")
3410     dev[0].request("REMOVE_NETWORK all")
3411     eap_connect(dev[0], hapd, "EKE", "eke user", password="hello1",
3412                 expect_failure=True)
3413 
3414 @long_duration_test
3415 def test_ap_wpa2_eap_eke_many(dev, apdev):
3416     """WPA2-Enterprise connection using EAP-EKE (many connections)"""
3417     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3418     hostapd.add_ap(apdev[0], params)
3419     success = 0
3420     fail = 0
3421     for i in range(100):
3422         for j in range(3):
3423             dev[j].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="EKE",
3424                            identity="eke user", password="hello",
3425                            phase1="dhgroup=3 encr=1 prf=1 mac=1",
3426                            scan_freq="2412", wait_connect=False)
3427         for j in range(3):
3428             ev = dev[j].wait_event(["CTRL-EVENT-CONNECTED",
3429                                     "CTRL-EVENT-DISCONNECTED"], timeout=15)
3430             if ev is None:
3431                 raise Exception("No connected/disconnected event")
3432             if "CTRL-EVENT-DISCONNECTED" in ev:
3433                 fail += 1
3434                 # The RADIUS server limits on active sessions can be hit when
3435                 # going through this test case, so try to give some more time
3436                 # for the server to remove sessions.
3437                 logger.info("Failed to connect i=%d j=%d" % (i, j))
3438                 dev[j].request("REMOVE_NETWORK all")
3439                 time.sleep(1)
3440             else:
3441                 success += 1
3442                 dev[j].request("REMOVE_NETWORK all")
3443                 dev[j].wait_disconnected()
3444             dev[j].dump_monitor()
3445     logger.info("Total success=%d failure=%d" % (success, fail))
3446 
3447 def test_ap_wpa2_eap_eke_serverid_nai(dev, apdev):
3448     """WPA2-Enterprise connection using EAP-EKE with serverid NAI"""
3449     params = int_eap_server_params()
3450     params['server_id'] = 'example.server@w1.fi'
3451     hapd = hostapd.add_ap(apdev[0], params)
3452     eap_connect(dev[0], hapd, "EKE", "eke user", password="hello")
3453 
3454 def test_ap_wpa2_eap_eke_server_oom(dev, apdev):
3455     """WPA2-Enterprise connection using EAP-EKE with server OOM"""
3456     params = int_eap_server_params()
3457     hapd = hostapd.add_ap(apdev[0], params)
3458     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
3459 
3460     for count, func in [(1, "eap_eke_build_commit"),
3461                         (2, "eap_eke_build_commit"),
3462                         (3, "eap_eke_build_commit"),
3463                         (1, "eap_eke_build_confirm"),
3464                         (2, "eap_eke_build_confirm"),
3465                         (1, "eap_eke_process_commit"),
3466                         (2, "eap_eke_process_commit"),
3467                         (1, "eap_eke_process_confirm"),
3468                         (1, "eap_eke_process_identity"),
3469                         (2, "eap_eke_process_identity"),
3470                         (3, "eap_eke_process_identity"),
3471                         (4, "eap_eke_process_identity")]:
3472         with alloc_fail(hapd, count, func):
3473             eap_connect(dev[0], hapd, "EKE", "eke user", password="hello",
3474                         expect_failure=True)
3475             dev[0].request("REMOVE_NETWORK all")
3476 
3477     for count, func, pw in [(1, "eap_eke_init", "hello"),
3478                             (1, "eap_eke_get_session_id", "hello"),
3479                             (1, "eap_eke_getKey", "hello"),
3480                             (1, "eap_eke_build_msg", "hello"),
3481                             (1, "eap_eke_build_failure", "wrong"),
3482                             (1, "eap_eke_build_identity", "hello"),
3483                             (2, "eap_eke_build_identity", "hello")]:
3484         with alloc_fail(hapd, count, func):
3485             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
3486                            eap="EKE", identity="eke user", password=pw,
3487                            wait_connect=False, scan_freq="2412")
3488             # This would eventually time out, but we can stop after having
3489             # reached the allocation failure.
3490             for i in range(20):
3491                 time.sleep(0.1)
3492                 if hapd.request("GET_ALLOC_FAIL").startswith('0'):
3493                     break
3494             dev[0].request("REMOVE_NETWORK all")
3495 
3496     for count in range(1, 1000):
3497         # Fail on allocation number "count"
3498         hapd.request("TEST_ALLOC_FAIL %d:eap_server_sm_step" % count)
3499 
3500         dev[0].connect("test-wpa2-eap",
3501                        key_mgmt="WPA-EAP WPA-EAP-SHA256",
3502                        eap="EKE", identity="eke user", password=pw,
3503                        wait_connect=False, scan_freq="2412")
3504         # This would eventually time out, but we can stop after having
3505         # reached the allocation failure.
3506         for i in range(10):
3507             time.sleep(0.1)
3508             if hapd.request("GET_ALLOC_FAIL").startswith('0'):
3509                 break
3510         else:
3511             # Last iteration had no failure
3512             # i.e. we exceeded the number of allocations
3513             dev[0].request("REMOVE_NETWORK all")
3514             logger.info("%d allocation failures tested" % (count - 1))
3515             break
3516     else:
3517         # All iterations had an allocation failure
3518         hapd.request("TEST_ALLOC_FAIL 0:")
3519         raise Exception("More than %d allocations, test aborted" % (count - 1))
3520 
3521     if count < 30:
3522         raise Exception("Too few allocation failures")
3523 
3524 def test_ap_wpa2_eap_ikev2(dev, apdev):
3525     """WPA2-Enterprise connection using EAP-IKEv2"""
3526     check_eap_capa(dev[0], "IKEV2")
3527     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3528     hapd = hostapd.add_ap(apdev[0], params)
3529     eap_connect(dev[0], hapd, "IKEV2", "ikev2 user",
3530                 password="ike password")
3531     eap_reauth(dev[0], "IKEV2")
3532     dev[0].request("REMOVE_NETWORK all")
3533     eap_connect(dev[0], hapd, "IKEV2", "ikev2 user",
3534                 password="ike password", fragment_size="50")
3535 
3536     logger.info("Negative test with incorrect password")
3537     dev[0].request("REMOVE_NETWORK all")
3538     eap_connect(dev[0], hapd, "IKEV2", "ikev2 user",
3539                 password="ike-password", expect_failure=True)
3540     dev[0].request("REMOVE_NETWORK all")
3541 
3542     eap_connect(dev[0], hapd, "IKEV2", "ikev2 user",
3543                 password="ike password", fragment_size="0")
3544     dev[0].request("REMOVE_NETWORK all")
3545     dev[0].wait_disconnected()
3546 
3547 def test_ap_wpa2_eap_ikev2_as_frag(dev, apdev):
3548     """WPA2-Enterprise connection using EAP-IKEv2 with server fragmentation"""
3549     check_eap_capa(dev[0], "IKEV2")
3550     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3551     params = {"ssid": "test-wpa2-eap", "wpa": "2", "wpa_key_mgmt": "WPA-EAP",
3552               "rsn_pairwise": "CCMP", "ieee8021x": "1",
3553               "eap_server": "1", "eap_user_file": "auth_serv/eap_user.conf",
3554               "fragment_size": "50"}
3555     hapd = hostapd.add_ap(apdev[0], params)
3556     eap_connect(dev[0], hapd, "IKEV2", "ikev2 user",
3557                 password="ike password")
3558     eap_reauth(dev[0], "IKEV2")
3559 
3560 def test_ap_wpa2_eap_ikev2_oom(dev, apdev):
3561     """WPA2-Enterprise connection using EAP-IKEv2 and OOM"""
3562     check_eap_capa(dev[0], "IKEV2")
3563     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3564     hostapd.add_ap(apdev[0], params)
3565 
3566     tests = [(1, "dh_init"),
3567              (2, "dh_init"),
3568              (1, "dh_derive_shared")]
3569     for count, func in tests:
3570         with alloc_fail(dev[0], count, func):
3571             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="IKEV2",
3572                            identity="ikev2 user", password="ike password",
3573                            wait_connect=False, scan_freq="2412")
3574             ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=5)
3575             if ev is None:
3576                 raise Exception("EAP method not selected")
3577             for i in range(10):
3578                 if "0:" in dev[0].request("GET_ALLOC_FAIL"):
3579                     break
3580                 time.sleep(0.02)
3581             dev[0].request("REMOVE_NETWORK all")
3582 
3583     tls = dev[0].request("GET tls_library")
3584     if not tls.startswith("wolfSSL"):
3585         tests = [(1, "os_get_random;dh_init")]
3586     else:
3587         tests = [(1, "crypto_dh_init;dh_init")]
3588     for count, func in tests:
3589         with fail_test(dev[0], count, func):
3590             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="IKEV2",
3591                            identity="ikev2 user", password="ike password",
3592                            wait_connect=False, scan_freq="2412")
3593             ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=5)
3594             if ev is None:
3595                 raise Exception("EAP method not selected")
3596             for i in range(10):
3597                 if "0:" in dev[0].request("GET_FAIL"):
3598                     break
3599                 time.sleep(0.02)
3600             dev[0].request("REMOVE_NETWORK all")
3601 
3602 def test_ap_wpa2_eap_pax(dev, apdev):
3603     """WPA2-Enterprise connection using EAP-PAX"""
3604     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3605     hapd = hostapd.add_ap(apdev[0], params)
3606     eap_connect(dev[0], hapd, "PAX", "pax.user@example.com",
3607                 password_hex="0123456789abcdef0123456789abcdef")
3608     eap_reauth(dev[0], "PAX")
3609 
3610     logger.info("Negative test with incorrect password")
3611     dev[0].request("REMOVE_NETWORK all")
3612     eap_connect(dev[0], hapd, "PAX", "pax.user@example.com",
3613                 password_hex="ff23456789abcdef0123456789abcdef",
3614                 expect_failure=True)
3615 
3616 def test_ap_wpa2_eap_psk(dev, apdev):
3617     """WPA2-Enterprise connection using EAP-PSK"""
3618     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3619     params["wpa_key_mgmt"] = "WPA-EAP-SHA256"
3620     params["ieee80211w"] = "2"
3621     hapd = hostapd.add_ap(apdev[0], params)
3622     eap_connect(dev[0], hapd, "PSK", "psk.user@example.com",
3623                 password_hex="0123456789abcdef0123456789abcdef", sha256=True)
3624     eap_reauth(dev[0], "PSK", sha256=True)
3625     check_mib(dev[0], [("dot11RSNAAuthenticationSuiteRequested", "00-0f-ac-5"),
3626                        ("dot11RSNAAuthenticationSuiteSelected", "00-0f-ac-5")])
3627 
3628     bss = dev[0].get_bss(apdev[0]['bssid'])
3629     if 'flags' not in bss:
3630         raise Exception("Could not get BSS flags from BSS table")
3631     if "[WPA2-EAP-SHA256-CCMP]" not in bss['flags']:
3632         raise Exception("Unexpected BSS flags: " + bss['flags'])
3633 
3634     logger.info("Negative test with incorrect password")
3635     dev[0].request("REMOVE_NETWORK all")
3636     eap_connect(dev[0], hapd, "PSK", "psk.user@example.com",
3637                 password_hex="ff23456789abcdef0123456789abcdef", sha256=True,
3638                 expect_failure=True)
3639 
3640 def test_ap_wpa2_eap_psk_oom(dev, apdev):
3641     """WPA2-Enterprise connection using EAP-PSK and OOM"""
3642     skip_with_fips(dev[0])
3643     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3644     hostapd.add_ap(apdev[0], params)
3645     tests = [(1, "=aes_128_eax_encrypt"),
3646              (1, "=aes_128_eax_decrypt")]
3647     for count, func in tests:
3648         with alloc_fail(dev[0], count, func):
3649             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PSK",
3650                            identity="psk.user@example.com",
3651                            password_hex="0123456789abcdef0123456789abcdef",
3652                            wait_connect=False, scan_freq="2412")
3653             ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=5)
3654             if ev is None:
3655                 raise Exception("EAP method not selected")
3656             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL",
3657                               note="Failure not triggered: %d:%s" % (count, func))
3658             dev[0].request("REMOVE_NETWORK all")
3659             dev[0].wait_disconnected()
3660 
3661     tests = [(1, "aes_ctr_encrypt;aes_128_eax_encrypt"),
3662              (1, "omac1_aes_128;aes_128_eax_encrypt"),
3663              (2, "omac1_aes_128;aes_128_eax_encrypt"),
3664              (3, "omac1_aes_128;aes_128_eax_encrypt"),
3665              (1, "omac1_aes_vector"),
3666              (1, "omac1_aes_128;aes_128_eax_decrypt"),
3667              (2, "omac1_aes_128;aes_128_eax_decrypt"),
3668              (3, "omac1_aes_128;aes_128_eax_decrypt"),
3669              (1, "aes_ctr_encrypt;aes_128_eax_decrypt")]
3670     for count, func in tests:
3671         with fail_test(dev[0], count, func):
3672             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PSK",
3673                            identity="psk.user@example.com",
3674                            password_hex="0123456789abcdef0123456789abcdef",
3675                            wait_connect=False, scan_freq="2412")
3676             ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=5)
3677             if ev is None:
3678                 raise Exception("EAP method not selected")
3679             wait_fail_trigger(dev[0], "GET_FAIL",
3680                               note="Failure not triggered: %d:%s" % (count, func))
3681             dev[0].request("REMOVE_NETWORK all")
3682             dev[0].wait_disconnected()
3683 
3684     with fail_test(dev[0], 1, "aes_128_encrypt_block"):
3685             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PSK",
3686                            identity="psk.user@example.com",
3687                            password_hex="0123456789abcdef0123456789abcdef",
3688                            wait_connect=False, scan_freq="2412")
3689             ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
3690             if ev is None:
3691                 raise Exception("EAP method failure not reported")
3692             dev[0].request("REMOVE_NETWORK all")
3693             dev[0].wait_disconnected()
3694 
3695 def test_ap_wpa_eap_peap_eap_mschapv2(dev, apdev):
3696     """WPA-Enterprise connection using EAP-PEAP/EAP-MSCHAPv2"""
3697     skip_without_tkip(dev[0])
3698     check_eap_capa(dev[0], "MSCHAPV2")
3699     params = hostapd.wpa_eap_params(ssid="test-wpa-eap")
3700     hapd = hostapd.add_ap(apdev[0], params)
3701     dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="PEAP",
3702                    identity="user", password="password", phase2="auth=MSCHAPV2",
3703                    ca_cert="auth_serv/ca.pem", wait_connect=False,
3704                    scan_freq="2412")
3705     eap_check_auth(dev[0], "PEAP", True, rsn=False)
3706     hapd.wait_sta()
3707     hwsim_utils.test_connectivity(dev[0], hapd)
3708     eap_reauth(dev[0], "PEAP", rsn=False)
3709     check_mib(dev[0], [("dot11RSNAAuthenticationSuiteRequested", "00-50-f2-1"),
3710                        ("dot11RSNAAuthenticationSuiteSelected", "00-50-f2-1")])
3711     status = dev[0].get_status(extra="VERBOSE")
3712     if 'portControl' not in status:
3713         raise Exception("portControl missing from STATUS-VERBOSE")
3714     if status['portControl'] != 'Auto':
3715         raise Exception("Unexpected portControl value: " + status['portControl'])
3716     if 'eap_session_id' not in status:
3717         raise Exception("eap_session_id missing from STATUS-VERBOSE")
3718     if not status['eap_session_id'].startswith("19"):
3719         raise Exception("Unexpected eap_session_id value: " + status['eap_session_id'])
3720 
3721 def test_ap_wpa2_eap_interactive(dev, apdev):
3722     """WPA2-Enterprise connection using interactive identity/password entry"""
3723     check_eap_capa(dev[0], "MSCHAPV2")
3724     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3725     hapd = hostapd.add_ap(apdev[0], params)
3726 
3727     tests = [("Connection with dynamic TTLS/MSCHAPv2 password entry",
3728               "TTLS", "ttls", "DOMAIN\\mschapv2 user", "auth=MSCHAPV2",
3729               None, "password"),
3730              ("Connection with dynamic TTLS/MSCHAPv2 identity and password entry",
3731               "TTLS", "ttls", None, "auth=MSCHAPV2",
3732               "DOMAIN\\mschapv2 user", "password"),
3733              ("Connection with dynamic TTLS/EAP-MSCHAPv2 password entry",
3734               "TTLS", "ttls", "user", "autheap=MSCHAPV2", None, "password"),
3735              ("Connection with dynamic TTLS/EAP-MD5 password entry",
3736               "TTLS", "ttls", "user", "autheap=MD5", None, "password"),
3737              ("Connection with dynamic PEAP/EAP-MSCHAPv2 password entry",
3738               "PEAP", None, "user", "auth=MSCHAPV2", None, "password"),
3739              ("Connection with dynamic PEAP/EAP-GTC password entry",
3740               "PEAP", None, "user", "auth=GTC", None, "password")]
3741     for [desc, eap, anon, identity, phase2, req_id, req_pw] in tests:
3742         logger.info(desc)
3743         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap=eap,
3744                        anonymous_identity=anon, identity=identity,
3745                        ca_cert="auth_serv/ca.pem", phase2=phase2,
3746                        wait_connect=False, scan_freq="2412")
3747         if req_id:
3748             ev = dev[0].wait_event(["CTRL-REQ-IDENTITY"])
3749             if ev is None:
3750                 raise Exception("Request for identity timed out")
3751             id = ev.split(':')[0].split('-')[-1]
3752             dev[0].request("CTRL-RSP-IDENTITY-" + id + ":" + req_id)
3753         ev = dev[0].wait_event(["CTRL-REQ-PASSWORD", "CTRL-REQ-OTP"])
3754         if ev is None:
3755             raise Exception("Request for password timed out")
3756         id = ev.split(':')[0].split('-')[-1]
3757         type = "OTP" if "CTRL-REQ-OTP" in ev else "PASSWORD"
3758         dev[0].request("CTRL-RSP-" + type + "-" + id + ":" + req_pw)
3759         dev[0].wait_connected(timeout=10)
3760         dev[0].request("REMOVE_NETWORK all")
3761 
3762 def test_ap_wpa2_eap_ext_enable_network_while_connected(dev, apdev):
3763     """WPA2-Enterprise interactive identity entry and ENABLE_NETWORK"""
3764     check_eap_capa(dev[0], "MSCHAPV2")
3765     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3766     hapd = hostapd.add_ap(apdev[0], params)
3767 
3768     id_other = dev[0].connect("other", key_mgmt="NONE", scan_freq="2412",
3769                               only_add_network=True)
3770 
3771     req_id = "DOMAIN\\mschapv2 user"
3772     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
3773                    anonymous_identity="ttls", identity=None,
3774                    password="password",
3775                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3776                    wait_connect=False, scan_freq="2412")
3777     ev = dev[0].wait_event(["CTRL-REQ-IDENTITY"])
3778     if ev is None:
3779         raise Exception("Request for identity timed out")
3780     id = ev.split(':')[0].split('-')[-1]
3781     dev[0].request("CTRL-RSP-IDENTITY-" + id + ":" + req_id)
3782     dev[0].wait_connected(timeout=10)
3783 
3784     if "OK" not in dev[0].request("ENABLE_NETWORK " + str(id_other)):
3785         raise Exception("Failed to enable network")
3786     ev = dev[0].wait_event(["SME: Trying to authenticate"], timeout=1)
3787     if ev is not None:
3788         raise Exception("Unexpected reconnection attempt on ENABLE_NETWORK")
3789     dev[0].request("REMOVE_NETWORK all")
3790 
3791 def test_ap_wpa2_eap_vendor_test(dev, apdev):
3792     """WPA2-Enterprise connection using EAP vendor test"""
3793     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3794     hapd = hostapd.add_ap(apdev[0], params)
3795     eap_connect(dev[0], hapd, "VENDOR-TEST", "vendor-test")
3796     eap_reauth(dev[0], "VENDOR-TEST")
3797     eap_connect(dev[1], hapd, "VENDOR-TEST", "vendor-test",
3798                 password="pending")
3799 
3800 def test_ap_wpa2_eap_vendor_test_oom(dev, apdev):
3801     """WPA2-Enterprise connection using EAP vendor test (OOM)"""
3802     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3803     hostapd.add_ap(apdev[0], params)
3804 
3805     tests = ["eap_vendor_test_init",
3806              "eap_msg_alloc;eap_vendor_test_process",
3807              "eap_vendor_test_getKey"]
3808     for func in tests:
3809         with alloc_fail(dev[0], 1, func):
3810             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP",
3811                            scan_freq="2412",
3812                            eap="VENDOR-TEST", identity="vendor-test",
3813                            wait_connect=False)
3814             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
3815             dev[0].request("REMOVE_NETWORK all")
3816             dev[0].wait_disconnected()
3817 
3818 def test_ap_wpa2_eap_fast_mschapv2_unauth_prov(dev, apdev):
3819     """WPA2-Enterprise connection using EAP-FAST/MSCHAPv2 and unauthenticated provisioning"""
3820     check_eap_capa(dev[0], "FAST")
3821     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3822     hapd = hostapd.add_ap(apdev[0], params)
3823     eap_connect(dev[0], hapd, "FAST", "user",
3824                 anonymous_identity="FAST", password="password",
3825                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3826                 phase1="fast_provisioning=1", pac_file="blob://fast_pac")
3827     hwsim_utils.test_connectivity(dev[0], hapd)
3828     res = eap_reauth(dev[0], "FAST")
3829     if res['tls_session_reused'] != '1':
3830         raise Exception("EAP-FAST could not use PAC session ticket")
3831 
3832 def test_ap_wpa2_eap_fast_pac_file(dev, apdev, params):
3833     """WPA2-Enterprise connection using EAP-FAST/MSCHAPv2 and PAC file"""
3834     check_eap_capa(dev[0], "FAST")
3835     pac_file = os.path.join(params['logdir'], "fast.pac")
3836     pac_file2 = os.path.join(params['logdir'], "fast-bin.pac")
3837     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3838     hapd = hostapd.add_ap(apdev[0], params)
3839 
3840     try:
3841         eap_connect(dev[0], hapd, "FAST", "user",
3842                     anonymous_identity="FAST", password="password",
3843                     ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3844                     phase1="fast_provisioning=1", pac_file=pac_file)
3845         with open(pac_file, "r") as f:
3846             data = f.read()
3847             if "wpa_supplicant EAP-FAST PAC file - version 1" not in data:
3848                 raise Exception("PAC file header missing")
3849             if "PAC-Key=" not in data:
3850                 raise Exception("PAC-Key missing from PAC file")
3851         dev[0].request("REMOVE_NETWORK all")
3852         eap_connect(dev[0], hapd, "FAST", "user",
3853                     anonymous_identity="FAST", password="password",
3854                     ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3855                     pac_file=pac_file)
3856 
3857         eap_connect(dev[1], hapd, "FAST", "user",
3858                     anonymous_identity="FAST", password="password",
3859                     ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3860                     phase1="fast_provisioning=1 fast_pac_format=binary",
3861                     pac_file=pac_file2)
3862         dev[1].request("REMOVE_NETWORK all")
3863         eap_connect(dev[1], hapd, "FAST", "user",
3864                     anonymous_identity="FAST", password="password",
3865                     ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3866                     phase1="fast_pac_format=binary",
3867                     pac_file=pac_file2)
3868     finally:
3869         try:
3870             os.remove(pac_file)
3871         except:
3872             pass
3873         try:
3874             os.remove(pac_file2)
3875         except:
3876             pass
3877 
3878 def test_ap_wpa2_eap_fast_binary_pac(dev, apdev):
3879     """WPA2-Enterprise connection using EAP-FAST and binary PAC format"""
3880     check_eap_capa(dev[0], "FAST")
3881     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3882     hapd = hostapd.add_ap(apdev[0], params)
3883     eap_connect(dev[0], hapd, "FAST", "user",
3884                 anonymous_identity="FAST", password="password",
3885                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3886                 phase1="fast_provisioning=1 fast_max_pac_list_len=1 fast_pac_format=binary",
3887                 pac_file="blob://fast_pac_bin")
3888     res = eap_reauth(dev[0], "FAST")
3889     if res['tls_session_reused'] != '1':
3890         raise Exception("EAP-FAST could not use PAC session ticket")
3891 
3892     # Verify fast_max_pac_list_len=0 special case
3893     dev[0].request("REMOVE_NETWORK all")
3894     dev[0].wait_disconnected()
3895     eap_connect(dev[0], hapd, "FAST", "user",
3896                 anonymous_identity="FAST", password="password",
3897                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3898                 phase1="fast_provisioning=1 fast_max_pac_list_len=0 fast_pac_format=binary",
3899                 pac_file="blob://fast_pac_bin")
3900 
3901 def test_ap_wpa2_eap_fast_missing_pac_config(dev, apdev):
3902     """WPA2-Enterprise connection using EAP-FAST and missing PAC config"""
3903     check_eap_capa(dev[0], "FAST")
3904     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3905     hostapd.add_ap(apdev[0], params)
3906 
3907     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
3908                    identity="user", anonymous_identity="FAST",
3909                    password="password",
3910                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3911                    pac_file="blob://fast_pac_not_in_use",
3912                    wait_connect=False, scan_freq="2412")
3913     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3914     if ev is None:
3915         raise Exception("Timeout on EAP failure report")
3916     dev[0].request("REMOVE_NETWORK all")
3917 
3918     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
3919                    identity="user", anonymous_identity="FAST",
3920                    password="password",
3921                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3922                    wait_connect=False, scan_freq="2412")
3923     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
3924     if ev is None:
3925         raise Exception("Timeout on EAP failure report")
3926 
3927 def test_ap_wpa2_eap_fast_binary_pac_errors(dev, apdev):
3928     """EAP-FAST and binary PAC errors"""
3929     check_eap_capa(dev[0], "FAST")
3930     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
3931     hapd = hostapd.add_ap(apdev[0], params)
3932 
3933     tests = [(1, "=eap_fast_save_pac_bin"),
3934              (1, "eap_fast_write_pac"),
3935              (2, "eap_fast_write_pac"),]
3936     for count, func in tests:
3937         if "OK" not in dev[0].request("SET blob fast_pac_bin_errors "):
3938             raise Exception("Could not set blob")
3939 
3940         with alloc_fail(dev[0], count, func):
3941             eap_connect(dev[0], hapd, "FAST", "user",
3942                         anonymous_identity="FAST", password="password",
3943                         ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3944                         phase1="fast_provisioning=1 fast_pac_format=binary",
3945                         pac_file="blob://fast_pac_bin_errors")
3946             dev[0].request("REMOVE_NETWORK all")
3947             dev[0].wait_disconnected()
3948 
3949     tests = ["00", "000000000000", "6ae4920c0001",
3950              "6ae4920c000000",
3951              "6ae4920c0000" + "0000" + 32*"00" + "ffff" + "0000",
3952              "6ae4920c0000" + "0000" + 32*"00" + "0001" + "0000",
3953              "6ae4920c0000" + "0000" + 32*"00" + "0000" + "0001",
3954              "6ae4920c0000" + "0000" + 32*"00" + "0000" + "0008" + "00040000" + "0007000100"]
3955     for t in tests:
3956         if "OK" not in dev[0].request("SET blob fast_pac_bin_errors " + t):
3957             raise Exception("Could not set blob")
3958 
3959         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
3960                        identity="user", anonymous_identity="FAST",
3961                        password="password",
3962                        ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3963                        phase1="fast_provisioning=1 fast_pac_format=binary",
3964                        pac_file="blob://fast_pac_bin_errors",
3965                        scan_freq="2412", wait_connect=False)
3966         ev = dev[0].wait_event(["EAP: Failed to initialize EAP method"],
3967                                timeout=5)
3968         if ev is None:
3969             raise Exception("Failure not reported")
3970         dev[0].request("REMOVE_NETWORK all")
3971         dev[0].wait_disconnected()
3972 
3973     pac = "6ae4920c0000" + "0000" + 32*"00" + "0000" + "0000"
3974     tests = [(1, "eap_fast_load_pac_bin"),
3975              (2, "eap_fast_load_pac_bin"),
3976              (3, "eap_fast_load_pac_bin")]
3977     for count, func in tests:
3978         if "OK" not in dev[0].request("SET blob fast_pac_bin_errors " + pac):
3979             raise Exception("Could not set blob")
3980 
3981         with alloc_fail(dev[0], count, func):
3982             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
3983                            identity="user", anonymous_identity="FAST",
3984                            password="password",
3985                            ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
3986                            phase1="fast_provisioning=1 fast_pac_format=binary",
3987                            pac_file="blob://fast_pac_bin_errors",
3988                            scan_freq="2412", wait_connect=False)
3989             ev = dev[0].wait_event(["EAP: Failed to initialize EAP method"],
3990                                    timeout=5)
3991             if ev is None:
3992                 raise Exception("Failure not reported")
3993             dev[0].request("REMOVE_NETWORK all")
3994             dev[0].wait_disconnected()
3995 
3996     pac = "6ae4920c0000" + "0000" + 32*"00" + "0000" + "0005" + "0011223344"
3997     if "OK" not in dev[0].request("SET blob fast_pac_bin_errors " + pac):
3998         raise Exception("Could not set blob")
3999 
4000     eap_connect(dev[0], hapd, "FAST", "user",
4001                 anonymous_identity="FAST", password="password",
4002                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
4003                 phase1="fast_provisioning=1 fast_pac_format=binary",
4004                 pac_file="blob://fast_pac_bin_errors")
4005     dev[0].request("REMOVE_NETWORK all")
4006     dev[0].wait_disconnected()
4007 
4008     pac = "6ae4920c0000" + "0000" + 32*"00" + "0000" + "0009" + "00040000" + "0007000100"
4009     tests = [(1, "eap_fast_pac_get_a_id"),
4010              (2, "eap_fast_pac_get_a_id")]
4011     for count, func in tests:
4012         if "OK" not in dev[0].request("SET blob fast_pac_bin_errors " + pac):
4013             raise Exception("Could not set blob")
4014         with alloc_fail(dev[0], count, func):
4015             eap_connect(dev[0], hapd, "FAST", "user",
4016                         anonymous_identity="FAST", password="password",
4017                         ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
4018                         phase1="fast_provisioning=1 fast_pac_format=binary",
4019                         pac_file="blob://fast_pac_bin_errors")
4020             dev[0].request("REMOVE_NETWORK all")
4021             dev[0].wait_disconnected()
4022 
4023 def test_ap_wpa2_eap_fast_text_pac_errors(dev, apdev):
4024     """EAP-FAST and text PAC errors"""
4025     check_eap_capa(dev[0], "FAST")
4026     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4027     hostapd.add_ap(apdev[0], params)
4028 
4029     tests = [(1, "eap_fast_parse_hex;eap_fast_parse_pac_key"),
4030              (1, "eap_fast_parse_hex;eap_fast_parse_pac_opaque"),
4031              (1, "eap_fast_parse_hex;eap_fast_parse_a_id"),
4032              (1, "eap_fast_parse_start"),
4033              (1, "eap_fast_save_pac")]
4034     for count, func in tests:
4035         dev[0].request("FLUSH")
4036         if "OK" not in dev[0].request("SET blob fast_pac_text_errors "):
4037             raise Exception("Could not set blob")
4038 
4039         with alloc_fail(dev[0], count, func):
4040             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
4041                            identity="user", anonymous_identity="FAST",
4042                            password="password",
4043                            ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
4044                            phase1="fast_provisioning=1",
4045                            pac_file="blob://fast_pac_text_errors",
4046                            scan_freq="2412", wait_connect=False)
4047             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4048             dev[0].request("REMOVE_NETWORK all")
4049             dev[0].wait_disconnected()
4050 
4051     pac = "wpa_supplicant EAP-FAST PAC file - version 1\n"
4052     pac += "START\n"
4053     pac += "PAC-Type\n"
4054     pac += "END\n"
4055     if "OK" not in dev[0].request("SET blob fast_pac_text_errors " + binascii.hexlify(pac.encode()).decode()):
4056         raise Exception("Could not set blob")
4057 
4058     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
4059                    identity="user", anonymous_identity="FAST",
4060                    password="password",
4061                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
4062                    phase1="fast_provisioning=1",
4063                    pac_file="blob://fast_pac_text_errors",
4064                    scan_freq="2412", wait_connect=False)
4065     ev = dev[0].wait_event(["EAP: Failed to initialize EAP method"], timeout=5)
4066     if ev is None:
4067         raise Exception("Failure not reported")
4068     dev[0].request("REMOVE_NETWORK all")
4069     dev[0].wait_disconnected()
4070 
4071     dev[0].request("FLUSH")
4072     if "OK" not in dev[0].request("SET blob fast_pac_text_errors "):
4073         raise Exception("Could not set blob")
4074 
4075     with alloc_fail(dev[0], 1, "eap_fast_add_pac_data"):
4076         for i in range(3):
4077             params = int_eap_server_params()
4078             params['ssid'] = "test-wpa2-eap-2"
4079             params['pac_opaque_encr_key'] = "000102030405060708090a0b0c0dff%02x" % i
4080             params['eap_fast_a_id'] = "101112131415161718191a1b1c1dff%02x" % i
4081             params['eap_fast_a_id_info'] = "test server %d" % i
4082 
4083             hapd2 = hostapd.add_ap(apdev[1], params)
4084 
4085             dev[0].connect("test-wpa2-eap-2", key_mgmt="WPA-EAP", eap="FAST",
4086                            identity="user", anonymous_identity="FAST",
4087                            password="password",
4088                            ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
4089                            phase1="fast_provisioning=1",
4090                            pac_file="blob://fast_pac_text_errors",
4091                            scan_freq="2412", wait_connect=False)
4092             dev[0].wait_connected()
4093             dev[0].request("REMOVE_NETWORK all")
4094             dev[0].wait_disconnected()
4095 
4096             hapd2.disable()
4097 
4098 def test_ap_wpa2_eap_fast_pac_truncate(dev, apdev):
4099     """EAP-FAST and PAC list truncation"""
4100     check_eap_capa(dev[0], "FAST")
4101     if "OK" not in dev[0].request("SET blob fast_pac_truncate "):
4102         raise Exception("Could not set blob")
4103     for i in range(5):
4104         params = int_eap_server_params()
4105         params['pac_opaque_encr_key'] = "000102030405060708090a0b0c0dff%02x" % i
4106         params['eap_fast_a_id'] = "101112131415161718191a1b1c1dff%02x" % i
4107         params['eap_fast_a_id_info'] = "test server %d" % i
4108         hapd = hostapd.add_ap(apdev[0], params)
4109 
4110         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
4111                        identity="user", anonymous_identity="FAST",
4112                        password="password",
4113                        ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
4114                        phase1="fast_provisioning=1 fast_max_pac_list_len=2",
4115                        pac_file="blob://fast_pac_truncate",
4116                        scan_freq="2412", wait_connect=False)
4117         dev[0].wait_connected()
4118         dev[0].request("REMOVE_NETWORK all")
4119         dev[0].wait_disconnected()
4120 
4121         hapd.disable()
4122 
4123 def test_ap_wpa2_eap_fast_pac_refresh(dev, apdev):
4124     """EAP-FAST and PAC refresh"""
4125     check_eap_capa(dev[0], "FAST")
4126     if "OK" not in dev[0].request("SET blob fast_pac_refresh "):
4127         raise Exception("Could not set blob")
4128     for i in range(2):
4129         params = int_eap_server_params()
4130         params['pac_opaque_encr_key'] = "000102030405060708090a0b0c0dff%02x" % i
4131         params['eap_fast_a_id'] = "101112131415161718191a1b1c1dff%02x" % i
4132         params['eap_fast_a_id_info'] = "test server %d" % i
4133         params['pac_key_refresh_time'] = "1"
4134         params['pac_key_lifetime'] = "10"
4135         hapd = hostapd.add_ap(apdev[0], params)
4136 
4137         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
4138                        identity="user", anonymous_identity="FAST",
4139                        password="password",
4140                        ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
4141                        phase1="fast_provisioning=1",
4142                        pac_file="blob://fast_pac_refresh",
4143                        scan_freq="2412", wait_connect=False)
4144         dev[0].wait_connected()
4145         dev[0].request("REMOVE_NETWORK all")
4146         dev[0].wait_disconnected()
4147 
4148         hapd.disable()
4149 
4150     for i in range(2):
4151         params = int_eap_server_params()
4152         params['pac_opaque_encr_key'] = "000102030405060708090a0b0c0dff%02x" % i
4153         params['eap_fast_a_id'] = "101112131415161718191a1b1c1dff%02x" % i
4154         params['eap_fast_a_id_info'] = "test server %d" % i
4155         params['pac_key_refresh_time'] = "10"
4156         params['pac_key_lifetime'] = "10"
4157         hapd = hostapd.add_ap(apdev[0], params)
4158 
4159         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
4160                        identity="user", anonymous_identity="FAST",
4161                        password="password",
4162                        ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
4163                        phase1="fast_provisioning=1",
4164                        pac_file="blob://fast_pac_refresh",
4165                        scan_freq="2412", wait_connect=False)
4166         dev[0].wait_connected()
4167         dev[0].request("REMOVE_NETWORK all")
4168         dev[0].wait_disconnected()
4169 
4170         hapd.disable()
4171 
4172 def test_ap_wpa2_eap_fast_pac_lifetime(dev, apdev):
4173     """EAP-FAST and PAC lifetime"""
4174     check_eap_capa(dev[0], "FAST")
4175     if "OK" not in dev[0].request("SET blob fast_pac_refresh "):
4176         raise Exception("Could not set blob")
4177 
4178     i = 0
4179     params = int_eap_server_params()
4180     params['pac_opaque_encr_key'] = "000102030405060708090a0b0c0dff%02x" % i
4181     params['eap_fast_a_id'] = "101112131415161718191a1b1c1dff%02x" % i
4182     params['eap_fast_a_id_info'] = "test server %d" % i
4183     params['pac_key_refresh_time'] = "0"
4184     params['pac_key_lifetime'] = "2"
4185     hapd = hostapd.add_ap(apdev[0], params)
4186 
4187     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
4188                         identity="user", anonymous_identity="FAST",
4189                         password="password",
4190                         ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
4191                         phase1="fast_provisioning=2",
4192                         pac_file="blob://fast_pac_refresh",
4193                         scan_freq="2412", wait_connect=False)
4194     dev[0].wait_connected()
4195     dev[0].request("DISCONNECT")
4196     dev[0].wait_disconnected()
4197 
4198     time.sleep(3)
4199     dev[0].request("PMKSA_FLUSH")
4200     dev[0].request("RECONNECT")
4201     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4202     if ev is None:
4203         raise Exception("No EAP-Failure seen after expired PAC")
4204     dev[0].request("DISCONNECT")
4205     dev[0].wait_disconnected()
4206 
4207     dev[0].select_network(id)
4208     dev[0].wait_connected()
4209     dev[0].request("REMOVE_NETWORK all")
4210     dev[0].wait_disconnected()
4211 
4212 def test_ap_wpa2_eap_fast_gtc_auth_prov(dev, apdev):
4213     """WPA2-Enterprise connection using EAP-FAST/GTC and authenticated provisioning"""
4214     check_eap_capa(dev[0], "FAST")
4215     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4216     hapd = hostapd.add_ap(apdev[0], params)
4217     eap_connect(dev[0], hapd, "FAST", "user",
4218                 anonymous_identity="FAST", password="password",
4219                 ca_cert="auth_serv/ca.pem", phase2="auth=GTC",
4220                 phase1="fast_provisioning=2", pac_file="blob://fast_pac_auth")
4221     hwsim_utils.test_connectivity(dev[0], hapd)
4222     res = eap_reauth(dev[0], "FAST")
4223     if res['tls_session_reused'] != '1':
4224         raise Exception("EAP-FAST could not use PAC session ticket")
4225 
4226 def test_ap_wpa2_eap_fast_gtc_identity_change(dev, apdev):
4227     """WPA2-Enterprise connection using EAP-FAST/GTC and identity changing"""
4228     check_eap_capa(dev[0], "FAST")
4229     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4230     hapd = hostapd.add_ap(apdev[0], params)
4231     id = eap_connect(dev[0], hapd, "FAST", "user",
4232                      anonymous_identity="FAST", password="password",
4233                      ca_cert="auth_serv/ca.pem", phase2="auth=GTC",
4234                      phase1="fast_provisioning=2",
4235                      pac_file="blob://fast_pac_auth")
4236     dev[0].set_network_quoted(id, "identity", "user2")
4237     dev[0].wait_disconnected()
4238     ev = dev[0].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=15)
4239     if ev is None:
4240         raise Exception("EAP-FAST not started")
4241     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
4242     if ev is None:
4243         raise Exception("EAP failure not reported")
4244     dev[0].wait_disconnected()
4245 
4246 def test_ap_wpa2_eap_fast_prf_oom(dev, apdev):
4247     """WPA2-Enterprise connection using EAP-FAST and OOM in PRF"""
4248     check_eap_capa(dev[0], "FAST")
4249     tls = dev[0].request("GET tls_library")
4250     if tls.startswith("OpenSSL"):
4251         func = "tls_connection_get_eap_fast_key"
4252         count = 2
4253     elif tls.startswith("wolfSSL"):
4254         func = "tls_connection_get_eap_fast_key"
4255         count = 1
4256     elif tls.startswith("internal"):
4257         func = "tls_connection_prf"
4258         count = 1
4259     else:
4260         raise HwsimSkip("Unsupported TLS library")
4261     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4262     hapd = hostapd.add_ap(apdev[0], params)
4263     with alloc_fail(dev[0], count, func):
4264         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
4265                        identity="user", anonymous_identity="FAST",
4266                        password="password", ca_cert="auth_serv/ca.pem",
4267                        phase2="auth=GTC",
4268                        phase1="fast_provisioning=2",
4269                        pac_file="blob://fast_pac_auth",
4270                        wait_connect=False, scan_freq="2412")
4271         ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=15)
4272         if ev is None:
4273             raise Exception("EAP failure not reported")
4274     dev[0].request("DISCONNECT")
4275 
4276 def test_ap_wpa2_eap_fast_server_oom(dev, apdev):
4277     """EAP-FAST/MSCHAPv2 and server OOM"""
4278     check_eap_capa(dev[0], "FAST")
4279     tls = dev[0].request("GET tls_library")
4280     if not tls.startswith("OpenSSL"):
4281         raise HwsimSkip("TLS library is not OpenSSL: " + tls)
4282 
4283     params = int_eap_server_params()
4284     params['dh_file'] = 'auth_serv/dh.conf'
4285     params['pac_opaque_encr_key'] = '000102030405060708090a0b0c0d0e0f'
4286     params['eap_fast_a_id'] = '1011'
4287     params['eap_fast_a_id_info'] = 'another test server'
4288     hapd = hostapd.add_ap(apdev[0], params)
4289 
4290     with alloc_fail(hapd, 1, "tls_session_ticket_ext_cb"):
4291         id = eap_connect(dev[0], hapd, "FAST", "user",
4292                          anonymous_identity="FAST", password="password",
4293                          ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
4294                          phase1="fast_provisioning=1",
4295                          pac_file="blob://fast_pac",
4296                          expect_failure=True)
4297         ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4298         if ev is None:
4299             raise Exception("No EAP failure reported")
4300         dev[0].wait_disconnected()
4301         dev[0].request("DISCONNECT")
4302 
4303     dev[0].select_network(id, freq="2412")
4304 
4305 def test_ap_wpa2_eap_fast_cipher_suites(dev, apdev):
4306     """EAP-FAST and different TLS cipher suites"""
4307     check_eap_capa(dev[0], "FAST")
4308     tls = dev[0].request("GET tls_library")
4309     if not tls.startswith("OpenSSL") and not tls.startswith("wolfSSL"):
4310         raise HwsimSkip("TLS library is not OpenSSL or wolfSSL: " + tls)
4311 
4312     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4313     hapd = hostapd.add_ap(apdev[0], params)
4314 
4315     dev[0].request("SET blob fast_pac_ciphers ")
4316     eap_connect(dev[0], hapd, "FAST", "user",
4317                 anonymous_identity="FAST", password="password",
4318                 ca_cert="auth_serv/ca.pem", phase2="auth=GTC",
4319                 phase1="fast_provisioning=2",
4320                 pac_file="blob://fast_pac_ciphers")
4321     res = dev[0].get_status_field('EAP TLS cipher')
4322     dev[0].request("REMOVE_NETWORK all")
4323     dev[0].wait_disconnected()
4324     if res != "DHE-RSA-AES256-SHA":
4325         raise Exception("Unexpected cipher suite for provisioning: " + res)
4326 
4327     tests = ["DHE-RSA-AES128-SHA",
4328              "RC4-SHA",
4329              "AES128-SHA",
4330              "AES256-SHA",
4331              "DHE-RSA-AES256-SHA"]
4332     for cipher in tests:
4333         dev[0].dump_monitor()
4334         logger.info("Testing " + cipher)
4335         try:
4336             eap_connect(dev[0], hapd, "FAST", "user",
4337                         openssl_ciphers=cipher,
4338                         anonymous_identity="FAST", password="password",
4339                         ca_cert="auth_serv/ca.pem", phase2="auth=GTC",
4340                         pac_file="blob://fast_pac_ciphers",
4341                         report_failure=True)
4342         except Exception as e:
4343             if cipher == "RC4-SHA" and \
4344                ("Could not select EAP method" in str(e) or \
4345                 "EAP failed" in str(e)):
4346                 if "run=OpenSSL" in tls or "wolfSSL" in tls:
4347                     logger.info("Allow failure due to missing TLS library support")
4348                     dev[0].request("REMOVE_NETWORK all")
4349                     dev[0].wait_disconnected()
4350                     continue
4351             raise
4352         res = dev[0].get_status_field('EAP TLS cipher')
4353         dev[0].request("REMOVE_NETWORK all")
4354         dev[0].wait_disconnected()
4355         if res != cipher:
4356             raise Exception("Unexpected TLS cipher info (configured %s): %s" % (cipher, res))
4357 
4358 def test_ap_wpa2_eap_fast_prov(dev, apdev):
4359     """EAP-FAST and provisioning options"""
4360     check_eap_capa(dev[0], "FAST")
4361     if "OK" not in dev[0].request("SET blob fast_pac_prov "):
4362         raise Exception("Could not set blob")
4363 
4364     i = 100
4365     params = int_eap_server_params()
4366     params['disable_pmksa_caching'] = '1'
4367     params['pac_opaque_encr_key'] = "000102030405060708090a0b0c0dff%02x" % i
4368     params['eap_fast_a_id'] = "101112131415161718191a1b1c1dff%02x" % i
4369     params['eap_fast_a_id_info'] = "test server %d" % i
4370     params['eap_fast_prov'] = "0"
4371     hapd = hostapd.add_ap(apdev[0], params)
4372 
4373     logger.info("Provisioning attempt while server has provisioning disabled")
4374     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
4375                         identity="user", anonymous_identity="FAST",
4376                         password="password",
4377                         ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
4378                         phase1="fast_provisioning=2",
4379                         pac_file="blob://fast_pac_prov",
4380                         scan_freq="2412", wait_connect=False)
4381     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS status='completion'"],
4382                            timeout=15)
4383     if ev is None:
4384         raise Exception("EAP result not reported")
4385     if "parameter='failure'" not in ev:
4386         raise Exception("Unexpected EAP result: " + ev)
4387     dev[0].wait_disconnected()
4388     dev[0].request("DISCONNECT")
4389     dev[0].dump_monitor()
4390 
4391     hapd.disable()
4392     logger.info("Authenticated provisioning")
4393     hapd.set("eap_fast_prov", "2")
4394     hapd.enable()
4395 
4396     dev[0].select_network(id, freq="2412")
4397     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS status='completion'"],
4398                            timeout=15)
4399     if ev is None:
4400         raise Exception("EAP result not reported")
4401     if "parameter='success'" not in ev:
4402         raise Exception("Unexpected EAP result: " + ev)
4403     dev[0].wait_connected()
4404     dev[0].request("DISCONNECT")
4405     dev[0].wait_disconnected()
4406     dev[0].dump_monitor()
4407 
4408     hapd.disable()
4409     logger.info("Provisioning disabled - using previously provisioned PAC")
4410     hapd.set("eap_fast_prov", "0")
4411     hapd.enable()
4412 
4413     dev[0].select_network(id, freq="2412")
4414     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS status='completion'"],
4415                            timeout=15)
4416     if ev is None:
4417         raise Exception("EAP result not reported")
4418     if "parameter='success'" not in ev:
4419         raise Exception("Unexpected EAP result: " + ev)
4420     dev[0].wait_connected()
4421     dev[0].request("DISCONNECT")
4422     dev[0].wait_disconnected()
4423     dev[0].dump_monitor()
4424 
4425     logger.info("Drop PAC and verify connection failure")
4426     if "OK" not in dev[0].request("SET blob fast_pac_prov "):
4427         raise Exception("Could not set blob")
4428 
4429     dev[0].select_network(id, freq="2412")
4430     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS status='completion'"],
4431                            timeout=15)
4432     if ev is None:
4433         raise Exception("EAP result not reported")
4434     if "parameter='failure'" not in ev:
4435         raise Exception("Unexpected EAP result: " + ev)
4436     dev[0].wait_disconnected()
4437     dev[0].request("DISCONNECT")
4438     dev[0].dump_monitor()
4439 
4440     hapd.disable()
4441     logger.info("Anonymous provisioning")
4442     hapd.set("eap_fast_prov", "1")
4443     hapd.enable()
4444     dev[0].set_network_quoted(id, "phase1", "fast_provisioning=1")
4445     dev[0].select_network(id, freq="2412")
4446     # Anonymous provisioning results in EAP-Failure first
4447     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS status='completion'"],
4448                            timeout=15)
4449     if ev is None:
4450         raise Exception("EAP result not reported")
4451     if "parameter='failure'" not in ev:
4452         raise Exception("Unexpected EAP result: " + ev)
4453     dev[0].wait_disconnected()
4454     # And then the actual data connection
4455     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS status='completion'"],
4456                            timeout=15)
4457     if ev is None:
4458         raise Exception("EAP result not reported")
4459     if "parameter='success'" not in ev:
4460         raise Exception("Unexpected EAP result: " + ev)
4461     dev[0].wait_connected()
4462     dev[0].request("DISCONNECT")
4463     dev[0].wait_disconnected()
4464     dev[0].dump_monitor()
4465 
4466     hapd.disable()
4467     logger.info("Provisioning disabled - using previously provisioned PAC")
4468     hapd.set("eap_fast_prov", "0")
4469     hapd.enable()
4470 
4471     dev[0].select_network(id, freq="2412")
4472     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS status='completion'"],
4473                            timeout=15)
4474     if ev is None:
4475         raise Exception("EAP result not reported")
4476     if "parameter='success'" not in ev:
4477         raise Exception("Unexpected EAP result: " + ev)
4478     dev[0].wait_connected()
4479     dev[0].request("DISCONNECT")
4480     dev[0].wait_disconnected()
4481     dev[0].dump_monitor()
4482 
4483 def test_ap_wpa2_eap_fast_eap_vendor(dev, apdev):
4484     """WPA2-Enterprise connection using EAP-FAST/EAP-vendor"""
4485     check_eap_capa(dev[0], "FAST")
4486     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4487     hapd = hostapd.add_ap(apdev[0], params)
4488     eap_connect(dev[0], hapd, "FAST", "vendor-test-2",
4489                 anonymous_identity="FAST",
4490                 phase1="fast_provisioning=2", pac_file="blob://fast_pac",
4491                 ca_cert="auth_serv/ca.pem", phase2="auth=VENDOR-TEST")
4492 
4493 def test_ap_wpa2_eap_tls_ocsp(dev, apdev):
4494     """WPA2-Enterprise connection using EAP-TLS and verifying OCSP"""
4495     check_ocsp_support(dev[0])
4496     check_pkcs12_support(dev[0])
4497     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4498     hapd = hostapd.add_ap(apdev[0], params)
4499     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4500                 private_key="auth_serv/user.pkcs12",
4501                 private_key_passwd="whatever", ocsp=2)
4502 
4503 def test_ap_wpa2_eap_tls_ocsp_multi(dev, apdev):
4504     """WPA2-Enterprise connection using EAP-TLS and verifying OCSP-multi"""
4505     check_ocsp_multi_support(dev[0])
4506     check_pkcs12_support(dev[0])
4507 
4508     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
4509     hapd = hostapd.add_ap(apdev[0], params)
4510     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
4511                 private_key="auth_serv/user.pkcs12",
4512                 private_key_passwd="whatever", ocsp=2)
4513 
4514 def int_eap_server_params():
4515     params = {"ssid": "test-wpa2-eap", "wpa": "2", "wpa_key_mgmt": "WPA-EAP",
4516               "rsn_pairwise": "CCMP", "ieee8021x": "1",
4517               "eap_server": "1", "eap_user_file": "auth_serv/eap_user.conf",
4518               "ca_cert": "auth_serv/ca.pem",
4519               "server_cert": "auth_serv/server.pem",
4520               "private_key": "auth_serv/server.key",
4521               "dh_file": "auth_serv/dh.conf"}
4522     return params
4523 
4524 def run_openssl(arg):
4525     logger.info(' '.join(arg))
4526     cmd = subprocess.Popen(arg, stdout=subprocess.PIPE,
4527                            stderr=subprocess.PIPE)
4528     res = cmd.stdout.read().decode() + "\n" + cmd.stderr.read().decode()
4529     cmd.stdout.close()
4530     cmd.stderr.close()
4531     cmd.wait()
4532     if cmd.returncode != 0:
4533         raise Exception("bad return code from openssl\n\n" + res)
4534     logger.info("openssl result:\n" + res)
4535 
4536 def ocsp_cache_key_id(outfile):
4537     if os.path.exists(outfile):
4538         return
4539     arg = ["openssl", "ocsp", "-index", "auth_serv/index.txt",
4540            '-rsigner', 'auth_serv/ocsp-responder.pem',
4541            '-rkey', 'auth_serv/ocsp-responder.key',
4542            '-resp_key_id',
4543            '-CA', 'auth_serv/ca.pem',
4544            '-issuer', 'auth_serv/ca.pem',
4545            '-verify_other', 'auth_serv/ca.pem',
4546            '-trust_other',
4547            '-ndays', '7',
4548            '-reqin', 'auth_serv/ocsp-req.der',
4549            '-respout', outfile]
4550     run_openssl(arg)
4551 
4552 def test_ap_wpa2_eap_tls_ocsp_key_id(dev, apdev, params):
4553     """EAP-TLS and OCSP certificate signed OCSP response using key ID"""
4554     check_ocsp_support(dev[0])
4555     check_pkcs12_support(dev[0])
4556     ocsp = os.path.join(params['logdir'], "ocsp-server-cache-key-id.der")
4557     ocsp_cache_key_id(ocsp)
4558     if not os.path.exists(ocsp):
4559         raise HwsimSkip("No OCSP response available")
4560     params = int_eap_server_params()
4561     params["ocsp_stapling_response"] = ocsp
4562     hostapd.add_ap(apdev[0], params)
4563     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4564                    identity="tls user", ca_cert="auth_serv/ca.pem",
4565                    private_key="auth_serv/user.pkcs12",
4566                    private_key_passwd="whatever", ocsp=2,
4567                    scan_freq="2412")
4568 
4569 def ocsp_req(outfile):
4570     if os.path.exists(outfile):
4571         return
4572     arg = ["openssl", "ocsp",
4573            "-reqout", outfile,
4574            '-issuer', 'auth_serv/ca.pem',
4575            '-sha256',
4576            '-serial', '0xD8D3E3A6CBE3CD87',
4577            '-no_nonce']
4578     run_openssl(arg)
4579     if not os.path.exists(outfile):
4580         raise HwsimSkip("Failed to generate OCSP request")
4581 
4582 def ocsp_resp_ca_signed(reqfile, outfile, status):
4583     ocsp_req(reqfile)
4584     if os.path.exists(outfile):
4585         return
4586     arg = ["openssl", "ocsp",
4587            "-index", "auth_serv/index%s.txt" % status,
4588            "-rsigner", "auth_serv/ca.pem",
4589            "-rkey", "auth_serv/ca-key.pem",
4590            "-CA", "auth_serv/ca.pem",
4591            "-ndays", "7",
4592            "-reqin", reqfile,
4593            "-resp_no_certs",
4594            "-respout", outfile]
4595     run_openssl(arg)
4596     if not os.path.exists(outfile):
4597         raise HwsimSkip("No OCSP response available")
4598 
4599 def ocsp_resp_server_signed(reqfile, outfile):
4600     ocsp_req(reqfile)
4601     if os.path.exists(outfile):
4602         return
4603     arg = ["openssl", "ocsp",
4604            "-index", "auth_serv/index.txt",
4605            "-rsigner", "auth_serv/server.pem",
4606            "-rkey", "auth_serv/server.key",
4607            "-CA", "auth_serv/ca.pem",
4608            "-ndays", "7",
4609            "-reqin", reqfile,
4610            "-respout", outfile]
4611     run_openssl(arg)
4612     if not os.path.exists(outfile):
4613         raise HwsimSkip("No OCSP response available")
4614 
4615 def test_ap_wpa2_eap_tls_ocsp_ca_signed_good(dev, apdev, params):
4616     """EAP-TLS and CA signed OCSP response (good)"""
4617     check_ocsp_support(dev[0])
4618     check_pkcs12_support(dev[0])
4619     req = os.path.join(params['logdir'], "ocsp-req.der")
4620     ocsp = os.path.join(params['logdir'], "ocsp-resp-ca-signed.der")
4621     ocsp_resp_ca_signed(req, ocsp, "")
4622     params = int_eap_server_params()
4623     params["ocsp_stapling_response"] = ocsp
4624     hostapd.add_ap(apdev[0], params)
4625     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4626                    identity="tls user", ca_cert="auth_serv/ca.pem",
4627                    private_key="auth_serv/user.pkcs12",
4628                    private_key_passwd="whatever", ocsp=2,
4629                    scan_freq="2412")
4630 
4631 def test_ap_wpa2_eap_tls_ocsp_ca_signed_revoked(dev, apdev, params):
4632     """EAP-TLS and CA signed OCSP response (revoked)"""
4633     check_ocsp_support(dev[0])
4634     check_pkcs12_support(dev[0])
4635     req = os.path.join(params['logdir'], "ocsp-req.der")
4636     ocsp = os.path.join(params['logdir'], "ocsp-resp-ca-signed-revoked.der")
4637     ocsp_resp_ca_signed(req, ocsp, "-revoked")
4638     params = int_eap_server_params()
4639     params["ocsp_stapling_response"] = ocsp
4640     hostapd.add_ap(apdev[0], params)
4641     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4642                    identity="tls user", ca_cert="auth_serv/ca.pem",
4643                    private_key="auth_serv/user.pkcs12",
4644                    private_key_passwd="whatever", ocsp=2,
4645                    wait_connect=False, scan_freq="2412")
4646     count = 0
4647     while True:
4648         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
4649         if ev is None:
4650             raise Exception("Timeout on EAP status")
4651         if 'bad certificate status response' in ev:
4652             break
4653         if 'certificate revoked' in ev:
4654             break
4655         count = count + 1
4656         if count > 10:
4657             raise Exception("Unexpected number of EAP status messages")
4658 
4659     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
4660     if ev is None:
4661         raise Exception("Timeout on EAP failure report")
4662 
4663 def test_ap_wpa2_eap_tls_ocsp_ca_signed_unknown(dev, apdev, params):
4664     """EAP-TLS and CA signed OCSP response (unknown)"""
4665     check_ocsp_support(dev[0])
4666     check_pkcs12_support(dev[0])
4667     req = os.path.join(params['logdir'], "ocsp-req.der")
4668     ocsp = os.path.join(params['logdir'], "ocsp-resp-ca-signed-unknown.der")
4669     ocsp_resp_ca_signed(req, ocsp, "-unknown")
4670     params = int_eap_server_params()
4671     params["ocsp_stapling_response"] = ocsp
4672     hostapd.add_ap(apdev[0], params)
4673     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4674                    identity="tls user", ca_cert="auth_serv/ca.pem",
4675                    private_key="auth_serv/user.pkcs12",
4676                    private_key_passwd="whatever", ocsp=2,
4677                    wait_connect=False, scan_freq="2412")
4678     count = 0
4679     while True:
4680         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
4681         if ev is None:
4682             raise Exception("Timeout on EAP status")
4683         if 'bad certificate status response' in ev:
4684             break
4685         count = count + 1
4686         if count > 10:
4687             raise Exception("Unexpected number of EAP status messages")
4688 
4689     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
4690     if ev is None:
4691         raise Exception("Timeout on EAP failure report")
4692 
4693 def test_ap_wpa2_eap_tls_ocsp_server_signed(dev, apdev, params):
4694     """EAP-TLS and server signed OCSP response"""
4695     check_ocsp_support(dev[0])
4696     check_pkcs12_support(dev[0])
4697     req = os.path.join(params['logdir'], "ocsp-req.der")
4698     ocsp = os.path.join(params['logdir'], "ocsp-resp-server-signed.der")
4699     ocsp_resp_server_signed(req, ocsp)
4700     params = int_eap_server_params()
4701     params["ocsp_stapling_response"] = ocsp
4702     hostapd.add_ap(apdev[0], params)
4703     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4704                    identity="tls user", ca_cert="auth_serv/ca.pem",
4705                    private_key="auth_serv/user.pkcs12",
4706                    private_key_passwd="whatever", ocsp=2,
4707                    wait_connect=False, scan_freq="2412")
4708     count = 0
4709     while True:
4710         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
4711         if ev is None:
4712             raise Exception("Timeout on EAP status")
4713         if 'bad certificate status response' in ev:
4714             break
4715         count = count + 1
4716         if count > 10:
4717             raise Exception("Unexpected number of EAP status messages")
4718 
4719     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
4720     if ev is None:
4721         raise Exception("Timeout on EAP failure report")
4722 
4723 def test_ap_wpa2_eap_tls_ocsp_invalid_data(dev, apdev):
4724     """WPA2-Enterprise connection using EAP-TLS and invalid OCSP data"""
4725     check_ocsp_support(dev[0])
4726     check_pkcs12_support(dev[0])
4727     params = int_eap_server_params()
4728     params["ocsp_stapling_response"] = "auth_serv/ocsp-req.der"
4729     hostapd.add_ap(apdev[0], params)
4730     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4731                    identity="tls user", ca_cert="auth_serv/ca.pem",
4732                    private_key="auth_serv/user.pkcs12",
4733                    private_key_passwd="whatever", ocsp=2,
4734                    wait_connect=False, scan_freq="2412")
4735     count = 0
4736     while True:
4737         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
4738         if ev is None:
4739             raise Exception("Timeout on EAP status")
4740         if 'bad certificate status response' in ev:
4741             break
4742         count = count + 1
4743         if count > 10:
4744             raise Exception("Unexpected number of EAP status messages")
4745 
4746     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
4747     if ev is None:
4748         raise Exception("Timeout on EAP failure report")
4749 
4750 def test_ap_wpa2_eap_tls_ocsp_invalid(dev, apdev):
4751     """WPA2-Enterprise connection using EAP-TLS and invalid OCSP response"""
4752     check_ocsp_support(dev[0])
4753     check_pkcs12_support(dev[0])
4754     params = int_eap_server_params()
4755     params["ocsp_stapling_response"] = "auth_serv/ocsp-server-cache.der-invalid"
4756     hostapd.add_ap(apdev[0], params)
4757     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4758                    identity="tls user", ca_cert="auth_serv/ca.pem",
4759                    private_key="auth_serv/user.pkcs12",
4760                    private_key_passwd="whatever", ocsp=2,
4761                    wait_connect=False, scan_freq="2412")
4762     count = 0
4763     while True:
4764         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
4765         if ev is None:
4766             raise Exception("Timeout on EAP status")
4767         if 'bad certificate status response' in ev:
4768             break
4769         count = count + 1
4770         if count > 10:
4771             raise Exception("Unexpected number of EAP status messages")
4772 
4773     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
4774     if ev is None:
4775         raise Exception("Timeout on EAP failure report")
4776 
4777 def test_ap_wpa2_eap_tls_ocsp_unknown_sign(dev, apdev):
4778     """WPA2-Enterprise connection using EAP-TLS and unknown OCSP signer"""
4779     check_ocsp_support(dev[0])
4780     check_pkcs12_support(dev[0])
4781     params = int_eap_server_params()
4782     params["ocsp_stapling_response"] = "auth_serv/ocsp-server-cache.der-unknown-sign"
4783     hostapd.add_ap(apdev[0], params)
4784     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4785                    identity="tls user", ca_cert="auth_serv/ca.pem",
4786                    private_key="auth_serv/user.pkcs12",
4787                    private_key_passwd="whatever", ocsp=2,
4788                    wait_connect=False, scan_freq="2412")
4789     count = 0
4790     while True:
4791         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
4792         if ev is None:
4793             raise Exception("Timeout on EAP status")
4794         if 'bad certificate status response' in ev:
4795             break
4796         count = count + 1
4797         if count > 10:
4798             raise Exception("Unexpected number of EAP status messages")
4799 
4800     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
4801     if ev is None:
4802         raise Exception("Timeout on EAP failure report")
4803 
4804 def ocsp_resp_status(outfile, status):
4805     if os.path.exists(outfile):
4806         return
4807     arg = ["openssl", "ocsp", "-index", "auth_serv/index-%s.txt" % status,
4808            '-rsigner', 'auth_serv/ocsp-responder.pem',
4809            '-rkey', 'auth_serv/ocsp-responder.key',
4810            '-CA', 'auth_serv/ca.pem',
4811            '-issuer', 'auth_serv/ca.pem',
4812            '-verify_other', 'auth_serv/ca.pem',
4813            '-trust_other',
4814            '-ndays', '7',
4815            '-reqin', 'auth_serv/ocsp-req.der',
4816            '-respout', outfile]
4817     run_openssl(arg)
4818 
4819 def test_ap_wpa2_eap_ttls_ocsp_revoked(dev, apdev, params):
4820     """WPA2-Enterprise connection using EAP-TTLS and OCSP status revoked"""
4821     check_ocsp_support(dev[0])
4822     ocsp = os.path.join(params['logdir'], "ocsp-server-cache-revoked.der")
4823     ocsp_resp_status(ocsp, "revoked")
4824     if not os.path.exists(ocsp):
4825         raise HwsimSkip("No OCSP response available")
4826     params = int_eap_server_params()
4827     params["ocsp_stapling_response"] = ocsp
4828     hostapd.add_ap(apdev[0], params)
4829     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
4830                    identity="pap user", ca_cert="auth_serv/ca.pem",
4831                    anonymous_identity="ttls", password="password",
4832                    phase2="auth=PAP", ocsp=2,
4833                    wait_connect=False, scan_freq="2412")
4834     count = 0
4835     while True:
4836         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
4837         if ev is None:
4838             raise Exception("Timeout on EAP status")
4839         if 'bad certificate status response' in ev:
4840             break
4841         if 'certificate revoked' in ev:
4842             break
4843         count = count + 1
4844         if count > 10:
4845             raise Exception("Unexpected number of EAP status messages")
4846 
4847     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
4848     if ev is None:
4849         raise Exception("Timeout on EAP failure report")
4850 
4851 def test_ap_wpa2_eap_ttls_ocsp_unknown(dev, apdev, params):
4852     """WPA2-Enterprise connection using EAP-TTLS and OCSP status unknown"""
4853     check_ocsp_support(dev[0])
4854     ocsp = os.path.join(params['logdir'], "ocsp-server-cache-unknown.der")
4855     ocsp_resp_status(ocsp, "unknown")
4856     if not os.path.exists(ocsp):
4857         raise HwsimSkip("No OCSP response available")
4858     params = int_eap_server_params()
4859     params["ocsp_stapling_response"] = ocsp
4860     hostapd.add_ap(apdev[0], params)
4861     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
4862                    identity="pap user", ca_cert="auth_serv/ca.pem",
4863                    anonymous_identity="ttls", password="password",
4864                    phase2="auth=PAP", ocsp=2,
4865                    wait_connect=False, scan_freq="2412")
4866     count = 0
4867     while True:
4868         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"])
4869         if ev is None:
4870             raise Exception("Timeout on EAP status")
4871         if 'bad certificate status response' in ev:
4872             break
4873         count = count + 1
4874         if count > 10:
4875             raise Exception("Unexpected number of EAP status messages")
4876 
4877     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
4878     if ev is None:
4879         raise Exception("Timeout on EAP failure report")
4880 
4881 def test_ap_wpa2_eap_ttls_optional_ocsp_unknown(dev, apdev, params):
4882     """WPA2-Enterprise connection using EAP-TTLS and OCSP status unknown"""
4883     check_ocsp_support(dev[0])
4884     ocsp = os.path.join(params['logdir'], "ocsp-server-cache-unknown.der")
4885     ocsp_resp_status(ocsp, "unknown")
4886     if not os.path.exists(ocsp):
4887         raise HwsimSkip("No OCSP response available")
4888     params = int_eap_server_params()
4889     params["ocsp_stapling_response"] = ocsp
4890     hostapd.add_ap(apdev[0], params)
4891     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
4892                    identity="pap user", ca_cert="auth_serv/ca.pem",
4893                    anonymous_identity="ttls", password="password",
4894                    phase2="auth=PAP", ocsp=1, scan_freq="2412")
4895 
4896 def test_ap_wpa2_eap_tls_intermediate_ca(dev, apdev, params):
4897     """EAP-TLS with intermediate server/user CA"""
4898     params = int_eap_server_params()
4899     params["ca_cert"] = "auth_serv/iCA-server/ca-and-root.pem"
4900     params["server_cert"] = "auth_serv/iCA-server/server.pem"
4901     params["private_key"] = "auth_serv/iCA-server/server.key"
4902     hostapd.add_ap(apdev[0], params)
4903     tls = dev[0].request("GET tls_library")
4904     if "GnuTLS" in tls or "wolfSSL" in tls:
4905         ca_cert = "auth_serv/iCA-user/ca-and-root.pem"
4906         client_cert = "auth_serv/iCA-user/user_and_ica.pem"
4907     else:
4908         ca_cert = "auth_serv/iCA-user/ca-and-root.pem"
4909         client_cert = "auth_serv/iCA-user/user.pem"
4910     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4911                    identity="tls user",
4912                    ca_cert=ca_cert,
4913                    client_cert=client_cert,
4914                    private_key="auth_serv/iCA-user/user.key",
4915                    scan_freq="2412")
4916 
4917 def root_ocsp(cert):
4918     ca = "auth_serv/ca.pem"
4919 
4920     fd2, fn2 = tempfile.mkstemp()
4921     os.close(fd2)
4922 
4923     arg = ["openssl", "ocsp", "-reqout", fn2, "-issuer", ca, "-sha256",
4924            "-cert", cert, "-no_nonce", "-text"]
4925     run_openssl(arg)
4926 
4927     fd, fn = tempfile.mkstemp()
4928     os.close(fd)
4929     arg = ["openssl", "ocsp", "-index", "auth_serv/rootCA/index.txt",
4930            "-rsigner", ca, "-rkey", "auth_serv/ca-key.pem",
4931            "-CA", ca, "-issuer", ca, "-verify_other", ca, "-trust_other",
4932            "-ndays", "7", "-reqin", fn2, "-resp_no_certs", "-respout", fn,
4933            "-text"]
4934     run_openssl(arg)
4935     os.unlink(fn2)
4936     return fn
4937 
4938 def ica_ocsp(cert, md="-sha256"):
4939     prefix = "auth_serv/iCA-server/"
4940     ca = prefix + "cacert.pem"
4941     cert = prefix + cert
4942 
4943     fd2, fn2 = tempfile.mkstemp()
4944     os.close(fd2)
4945 
4946     arg = ["openssl", "ocsp", "-reqout", fn2, "-issuer", ca, md,
4947            "-cert", cert, "-no_nonce", "-text"]
4948     run_openssl(arg)
4949 
4950     fd, fn = tempfile.mkstemp()
4951     os.close(fd)
4952     arg = ["openssl", "ocsp", "-index", prefix + "index.txt",
4953            "-rsigner", ca, "-rkey", prefix + "private/cakey.pem",
4954            "-CA", ca, "-issuer", ca, "-verify_other", ca, "-trust_other",
4955            "-ndays", "7", "-reqin", fn2, "-resp_no_certs", "-respout", fn,
4956            "-text"]
4957     run_openssl(arg)
4958     os.unlink(fn2)
4959     return fn
4960 
4961 def test_ap_wpa2_eap_tls_intermediate_ca_ocsp(dev, apdev, params):
4962     """EAP-TLS with intermediate server/user CA and OCSP on server certificate"""
4963     run_ap_wpa2_eap_tls_intermediate_ca_ocsp(dev, apdev, params, "-sha256")
4964 
4965 def test_ap_wpa2_eap_tls_intermediate_ca_ocsp_sha1(dev, apdev, params):
4966     """EAP-TLS with intermediate server/user CA and OCSP on server certificate )SHA1)"""
4967     run_ap_wpa2_eap_tls_intermediate_ca_ocsp(dev, apdev, params, "-sha1")
4968 
4969 def run_ap_wpa2_eap_tls_intermediate_ca_ocsp(dev, apdev, params, md):
4970     params = int_eap_server_params()
4971     params["ca_cert"] = "auth_serv/iCA-server/ca-and-root.pem"
4972     params["server_cert"] = "auth_serv/iCA-server/server.pem"
4973     params["private_key"] = "auth_serv/iCA-server/server.key"
4974     fn = ica_ocsp("server.pem", md)
4975     params["ocsp_stapling_response"] = fn
4976     try:
4977         hostapd.add_ap(apdev[0], params)
4978         tls = dev[0].request("GET tls_library")
4979         if "GnuTLS" in tls or "wolfSSL" in tls:
4980             ca_cert = "auth_serv/iCA-user/ca-and-root.pem"
4981             client_cert = "auth_serv/iCA-user/user_and_ica.pem"
4982         else:
4983             ca_cert = "auth_serv/iCA-user/ca-and-root.pem"
4984             client_cert = "auth_serv/iCA-user/user.pem"
4985         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
4986                        identity="tls user",
4987                        ca_cert=ca_cert,
4988                        client_cert=client_cert,
4989                        private_key="auth_serv/iCA-user/user.key",
4990                        scan_freq="2412", ocsp=2)
4991     finally:
4992         os.unlink(fn)
4993 
4994 def test_ap_wpa2_eap_tls_intermediate_ca_ocsp_revoked(dev, apdev, params):
4995     """EAP-TLS with intermediate server/user CA and OCSP on revoked server certificate"""
4996     run_ap_wpa2_eap_tls_intermediate_ca_ocsp_revoked(dev, apdev, params,
4997                                                      "-sha256")
4998 
4999 def test_ap_wpa2_eap_tls_intermediate_ca_ocsp_revoked_sha1(dev, apdev, params):
5000     """EAP-TLS with intermediate server/user CA and OCSP on revoked server certificate (SHA1)"""
5001     run_ap_wpa2_eap_tls_intermediate_ca_ocsp_revoked(dev, apdev, params,
5002                                                      "-sha1")
5003 
5004 def run_ap_wpa2_eap_tls_intermediate_ca_ocsp_revoked(dev, apdev, params, md):
5005     check_ocsp_support(dev[0])
5006     params = int_eap_server_params()
5007     params["ca_cert"] = "auth_serv/iCA-server/ca-and-root.pem"
5008     params["server_cert"] = "auth_serv/iCA-server/server-revoked.pem"
5009     params["private_key"] = "auth_serv/iCA-server/server-revoked.key"
5010     fn = ica_ocsp("server-revoked.pem", md)
5011     params["ocsp_stapling_response"] = fn
5012     try:
5013         hostapd.add_ap(apdev[0], params)
5014         tls = dev[0].request("GET tls_library")
5015         if "GnuTLS" in tls or "wolfSSL" in tls:
5016             ca_cert = "auth_serv/iCA-user/ca-and-root.pem"
5017             client_cert = "auth_serv/iCA-user/user_and_ica.pem"
5018         else:
5019             ca_cert = "auth_serv/iCA-user/ca-and-root.pem"
5020             client_cert = "auth_serv/iCA-user/user.pem"
5021         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
5022                        identity="tls user",
5023                        ca_cert=ca_cert,
5024                        client_cert=client_cert,
5025                        private_key="auth_serv/iCA-user/user.key",
5026                        scan_freq="2412", ocsp=1, wait_connect=False)
5027         count = 0
5028         while True:
5029             ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS",
5030                                     "CTRL-EVENT-EAP-SUCCESS"])
5031             if ev is None:
5032                 raise Exception("Timeout on EAP status")
5033             if "CTRL-EVENT-EAP-SUCCESS" in ev:
5034                 raise Exception("Unexpected EAP-Success")
5035             if 'bad certificate status response' in ev:
5036                 break
5037             if 'certificate revoked' in ev:
5038                 break
5039             count = count + 1
5040             if count > 10:
5041                 raise Exception("Unexpected number of EAP status messages")
5042 
5043         ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
5044         if ev is None:
5045             raise Exception("Timeout on EAP failure report")
5046         dev[0].request("REMOVE_NETWORK all")
5047         dev[0].wait_disconnected()
5048     finally:
5049         os.unlink(fn)
5050 
5051 def test_ap_wpa2_eap_tls_intermediate_ca_ocsp_multi_missing_resp(dev, apdev, params):
5052     """EAP-TLS with intermediate server/user CA and OCSP multi missing response"""
5053     check_ocsp_support(dev[0])
5054     check_ocsp_multi_support(dev[0])
5055 
5056     params = int_eap_server_params()
5057     params["ca_cert"] = "auth_serv/iCA-server/ca-and-root.pem"
5058     params["server_cert"] = "auth_serv/iCA-server/server.pem"
5059     params["private_key"] = "auth_serv/iCA-server/server.key"
5060     fn = ica_ocsp("server.pem")
5061     params["ocsp_stapling_response"] = fn
5062     try:
5063         hostapd.add_ap(apdev[0], params)
5064         tls = dev[0].request("GET tls_library")
5065         if "GnuTLS" in tls or "wolfSSL" in tls:
5066             ca_cert = "auth_serv/iCA-user/ca-and-root.pem"
5067             client_cert = "auth_serv/iCA-user/user_and_ica.pem"
5068         else:
5069             ca_cert = "auth_serv/iCA-user/ca-and-root.pem"
5070             client_cert = "auth_serv/iCA-user/user.pem"
5071         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
5072                        identity="tls user",
5073                        ca_cert=ca_cert,
5074                        client_cert=client_cert,
5075                        private_key="auth_serv/iCA-user/user.key",
5076                        scan_freq="2412", ocsp=3, wait_connect=False)
5077         count = 0
5078         while True:
5079             ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS",
5080                                     "CTRL-EVENT-EAP-SUCCESS"])
5081             if ev is None:
5082                 raise Exception("Timeout on EAP status")
5083             if "CTRL-EVENT-EAP-SUCCESS" in ev:
5084                 raise Exception("Unexpected EAP-Success")
5085             if 'bad certificate status response' in ev:
5086                 break
5087             if 'certificate revoked' in ev:
5088                 break
5089             count = count + 1
5090             if count > 10:
5091                 raise Exception("Unexpected number of EAP status messages")
5092 
5093         ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
5094         if ev is None:
5095             raise Exception("Timeout on EAP failure report")
5096         dev[0].request("REMOVE_NETWORK all")
5097         dev[0].wait_disconnected()
5098     finally:
5099         os.unlink(fn)
5100 
5101 def test_ap_wpa2_eap_tls_intermediate_ca_ocsp_multi(dev, apdev, params):
5102     """EAP-TLS with intermediate server/user CA and OCSP multi OK"""
5103     check_ocsp_support(dev[0])
5104     check_ocsp_multi_support(dev[0])
5105 
5106     params = int_eap_server_params()
5107     params["ca_cert"] = "auth_serv/iCA-server/ca-and-root.pem"
5108     params["server_cert"] = "auth_serv/iCA-server/server.pem"
5109     params["private_key"] = "auth_serv/iCA-server/server.key"
5110     fn = ica_ocsp("server.pem")
5111     fn2 = root_ocsp("auth_serv/iCA-server/cacert.pem")
5112     params["ocsp_stapling_response"] = fn
5113 
5114     with open(fn, "rb") as f:
5115         resp_server = f.read()
5116     with open(fn2, "rb") as f:
5117         resp_ica = f.read()
5118 
5119     fd3, fn3 = tempfile.mkstemp()
5120     try:
5121         f = os.fdopen(fd3, 'wb')
5122         f.write(struct.pack(">L", len(resp_server))[1:4])
5123         f.write(resp_server)
5124         f.write(struct.pack(">L", len(resp_ica))[1:4])
5125         f.write(resp_ica)
5126         f.close()
5127 
5128         params["ocsp_stapling_response_multi"] = fn3
5129 
5130         hostapd.add_ap(apdev[0], params)
5131         tls = dev[0].request("GET tls_library")
5132         if "GnuTLS" in tls or "wolfSSL" in tls:
5133             ca_cert = "auth_serv/iCA-user/ca-and-root.pem"
5134             client_cert = "auth_serv/iCA-user/user_and_ica.pem"
5135         else:
5136             ca_cert = "auth_serv/iCA-user/ca-and-root.pem"
5137             client_cert = "auth_serv/iCA-user/user.pem"
5138         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
5139                        identity="tls user",
5140                        ca_cert=ca_cert,
5141                        client_cert=client_cert,
5142                        private_key="auth_serv/iCA-user/user.key",
5143                        scan_freq="2412", ocsp=3)
5144         dev[0].request("REMOVE_NETWORK all")
5145         dev[0].wait_disconnected()
5146     finally:
5147         os.unlink(fn)
5148         os.unlink(fn2)
5149         os.unlink(fn3)
5150 
5151 def test_ap_wpa2_eap_tls_ocsp_multi_revoked(dev, apdev, params):
5152     """EAP-TLS and CA signed OCSP multi response (revoked)"""
5153     check_ocsp_support(dev[0])
5154     check_ocsp_multi_support(dev[0])
5155     check_pkcs12_support(dev[0])
5156 
5157     req = os.path.join(params['logdir'], "ocsp-req.der")
5158     ocsp_revoked = os.path.join(params['logdir'],
5159                                 "ocsp-resp-ca-signed-revoked.der")
5160     ocsp_unknown = os.path.join(params['logdir'],
5161                                 "ocsp-resp-ca-signed-unknown.der")
5162     ocsp_resp_ca_signed(req, ocsp_revoked, "-revoked")
5163     ocsp_resp_ca_signed(req, ocsp_unknown, "-unknown")
5164 
5165     with open(ocsp_revoked, "rb") as f:
5166         resp_revoked = f.read()
5167     with open(ocsp_unknown, "rb") as f:
5168         resp_unknown = f.read()
5169 
5170     fd, fn = tempfile.mkstemp()
5171     try:
5172         # This is not really a valid order of the OCSPResponse items in the
5173         # list, but this works for now to verify parsing and processing of
5174         # multiple responses.
5175         f = os.fdopen(fd, 'wb')
5176         f.write(struct.pack(">L", len(resp_unknown))[1:4])
5177         f.write(resp_unknown)
5178         f.write(struct.pack(">L", len(resp_revoked))[1:4])
5179         f.write(resp_revoked)
5180         f.write(struct.pack(">L", 0)[1:4])
5181         f.write(struct.pack(">L", len(resp_unknown))[1:4])
5182         f.write(resp_unknown)
5183         f.close()
5184 
5185         params = int_eap_server_params()
5186         params["ocsp_stapling_response_multi"] = fn
5187         hostapd.add_ap(apdev[0], params)
5188         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
5189                        identity="tls user", ca_cert="auth_serv/ca.pem",
5190                        private_key="auth_serv/user.pkcs12",
5191                        private_key_passwd="whatever", ocsp=1,
5192                        wait_connect=False, scan_freq="2412")
5193         count = 0
5194         while True:
5195             ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS",
5196                                     "CTRL-EVENT-EAP-SUCCESS"])
5197             if ev is None:
5198                 raise Exception("Timeout on EAP status")
5199             if "CTRL-EVENT-EAP-SUCCESS" in ev:
5200                 raise Exception("Unexpected EAP-Success")
5201             if 'bad certificate status response' in ev:
5202                 break
5203             if 'certificate revoked' in ev:
5204                 break
5205             count = count + 1
5206             if count > 10:
5207                 raise Exception("Unexpected number of EAP status messages")
5208     finally:
5209         os.unlink(fn)
5210 
5211 def test_ap_wpa2_eap_tls_domain_suffix_match_cn_full(dev, apdev):
5212     """WPA2-Enterprise using EAP-TLS and domain suffix match (CN)"""
5213     check_domain_match_full(dev[0])
5214     check_pkcs12_support(dev[0])
5215     params = int_eap_server_params()
5216     params["server_cert"] = "auth_serv/server-no-dnsname.pem"
5217     params["private_key"] = "auth_serv/server-no-dnsname.key"
5218     hostapd.add_ap(apdev[0], params)
5219     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
5220                    identity="tls user", ca_cert="auth_serv/ca.pem",
5221                    private_key="auth_serv/user.pkcs12",
5222                    private_key_passwd="whatever",
5223                    domain_suffix_match="server3.w1.fi",
5224                    scan_freq="2412")
5225 
5226 def test_ap_wpa2_eap_tls_domain_match_cn(dev, apdev):
5227     """WPA2-Enterprise using EAP-TLS and domainmatch (CN)"""
5228     check_domain_match(dev[0])
5229     check_pkcs12_support(dev[0])
5230     params = int_eap_server_params()
5231     params["server_cert"] = "auth_serv/server-no-dnsname.pem"
5232     params["private_key"] = "auth_serv/server-no-dnsname.key"
5233     hostapd.add_ap(apdev[0], params)
5234     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
5235                    identity="tls user", ca_cert="auth_serv/ca.pem",
5236                    private_key="auth_serv/user.pkcs12",
5237                    private_key_passwd="whatever",
5238                    domain_match="server3.w1.fi",
5239                    scan_freq="2412")
5240 
5241 def test_ap_wpa2_eap_tls_domain_suffix_match_cn(dev, apdev):
5242     """WPA2-Enterprise using EAP-TLS and domain suffix match (CN)"""
5243     check_domain_match_full(dev[0])
5244     check_pkcs12_support(dev[0])
5245     params = int_eap_server_params()
5246     params["server_cert"] = "auth_serv/server-no-dnsname.pem"
5247     params["private_key"] = "auth_serv/server-no-dnsname.key"
5248     hostapd.add_ap(apdev[0], params)
5249     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
5250                    identity="tls user", ca_cert="auth_serv/ca.pem",
5251                    private_key="auth_serv/user.pkcs12",
5252                    private_key_passwd="whatever",
5253                    domain_suffix_match="w1.fi",
5254                    scan_freq="2412")
5255 
5256 def test_ap_wpa2_eap_tls_domain_suffix_mismatch_cn(dev, apdev):
5257     """WPA2-Enterprise using EAP-TLS and domain suffix mismatch (CN)"""
5258     check_domain_suffix_match(dev[0])
5259     check_pkcs12_support(dev[0])
5260     params = int_eap_server_params()
5261     params["server_cert"] = "auth_serv/server-no-dnsname.pem"
5262     params["private_key"] = "auth_serv/server-no-dnsname.key"
5263     hostapd.add_ap(apdev[0], params)
5264     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
5265                    identity="tls user", ca_cert="auth_serv/ca.pem",
5266                    private_key="auth_serv/user.pkcs12",
5267                    private_key_passwd="whatever",
5268                    domain_suffix_match="example.com",
5269                    wait_connect=False,
5270                    scan_freq="2412")
5271     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
5272                    identity="tls user", ca_cert="auth_serv/ca.pem",
5273                    private_key="auth_serv/user.pkcs12",
5274                    private_key_passwd="whatever",
5275                    domain_suffix_match="erver3.w1.fi",
5276                    wait_connect=False,
5277                    scan_freq="2412")
5278     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
5279     if ev is None:
5280         raise Exception("Timeout on EAP failure report")
5281     ev = dev[1].wait_event(["CTRL-EVENT-EAP-FAILURE"])
5282     if ev is None:
5283         raise Exception("Timeout on EAP failure report (2)")
5284 
5285 def test_ap_wpa2_eap_tls_domain_mismatch_cn(dev, apdev):
5286     """WPA2-Enterprise using EAP-TLS and domain mismatch (CN)"""
5287     check_domain_match(dev[0])
5288     check_pkcs12_support(dev[0])
5289     params = int_eap_server_params()
5290     params["server_cert"] = "auth_serv/server-no-dnsname.pem"
5291     params["private_key"] = "auth_serv/server-no-dnsname.key"
5292     hostapd.add_ap(apdev[0], params)
5293     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
5294                    identity="tls user", ca_cert="auth_serv/ca.pem",
5295                    private_key="auth_serv/user.pkcs12",
5296                    private_key_passwd="whatever",
5297                    domain_match="example.com",
5298                    wait_connect=False,
5299                    scan_freq="2412")
5300     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
5301                    identity="tls user", ca_cert="auth_serv/ca.pem",
5302                    private_key="auth_serv/user.pkcs12",
5303                    private_key_passwd="whatever",
5304                    domain_match="w1.fi",
5305                    wait_connect=False,
5306                    scan_freq="2412")
5307     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
5308     if ev is None:
5309         raise Exception("Timeout on EAP failure report")
5310     ev = dev[1].wait_event(["CTRL-EVENT-EAP-FAILURE"])
5311     if ev is None:
5312         raise Exception("Timeout on EAP failure report (2)")
5313 
5314 def test_ap_wpa2_eap_ttls_expired_cert(dev, apdev):
5315     """WPA2-Enterprise using EAP-TTLS and expired certificate"""
5316     skip_with_fips(dev[0])
5317     params = int_eap_server_params()
5318     params["server_cert"] = "auth_serv/server-expired.pem"
5319     params["private_key"] = "auth_serv/server-expired.key"
5320     hostapd.add_ap(apdev[0], params)
5321     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
5322                    identity="mschap user", password="password",
5323                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
5324                    wait_connect=False,
5325                    scan_freq="2412")
5326     ev = dev[0].wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR"])
5327     if ev is None:
5328         raise Exception("Timeout on EAP certificate error report")
5329     if "reason=4" not in ev or "certificate has expired" not in ev:
5330         raise Exception("Unexpected failure reason: " + ev)
5331     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
5332     if ev is None:
5333         raise Exception("Timeout on EAP failure report")
5334 
5335 def test_ap_wpa2_eap_ttls_ignore_expired_cert(dev, apdev):
5336     """WPA2-Enterprise using EAP-TTLS and ignore certificate expiration"""
5337     skip_with_fips(dev[0])
5338     params = int_eap_server_params()
5339     params["server_cert"] = "auth_serv/server-expired.pem"
5340     params["private_key"] = "auth_serv/server-expired.key"
5341     hostapd.add_ap(apdev[0], params)
5342     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
5343                    identity="mschap user", password="password",
5344                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
5345                    phase1="tls_disable_time_checks=1",
5346                    scan_freq="2412")
5347 
5348 def test_ap_wpa2_eap_ttls_long_duration(dev, apdev):
5349     """WPA2-Enterprise using EAP-TTLS and long certificate duration"""
5350     skip_with_fips(dev[0])
5351     params = int_eap_server_params()
5352     params["server_cert"] = "auth_serv/server-long-duration.pem"
5353     params["private_key"] = "auth_serv/server-long-duration.key"
5354     hostapd.add_ap(apdev[0], params)
5355     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
5356                    identity="mschap user", password="password",
5357                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
5358                    scan_freq="2412")
5359 
5360 def test_ap_wpa2_eap_ttls_server_cert_eku_client(dev, apdev):
5361     """WPA2-Enterprise using EAP-TTLS and server cert with client EKU"""
5362     skip_with_fips(dev[0])
5363     params = int_eap_server_params()
5364     params["server_cert"] = "auth_serv/server-eku-client.pem"
5365     params["private_key"] = "auth_serv/server-eku-client.key"
5366     hostapd.add_ap(apdev[0], params)
5367     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
5368                    identity="mschap user", password="password",
5369                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
5370                    wait_connect=False,
5371                    scan_freq="2412")
5372     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
5373     if ev is None:
5374         raise Exception("Timeout on EAP failure report")
5375 
5376 def test_ap_wpa2_eap_ttls_server_cert_eku_client_server(dev, apdev):
5377     """WPA2-Enterprise using EAP-TTLS and server cert with client and server EKU"""
5378     skip_with_fips(dev[0])
5379     params = int_eap_server_params()
5380     params["server_cert"] = "auth_serv/server-eku-client-server.pem"
5381     params["private_key"] = "auth_serv/server-eku-client-server.key"
5382     hostapd.add_ap(apdev[0], params)
5383     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
5384                    identity="mschap user", password="password",
5385                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
5386                    scan_freq="2412")
5387 
5388 def test_ap_wpa2_eap_ttls_server_pkcs12(dev, apdev):
5389     """WPA2-Enterprise using EAP-TTLS and server PKCS#12 file"""
5390     skip_with_fips(dev[0])
5391     params = int_eap_server_params()
5392     del params["server_cert"]
5393     params["private_key"] = "auth_serv/server.pkcs12"
5394     hostapd.add_ap(apdev[0], params)
5395     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
5396                    identity="mschap user", password="password",
5397                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
5398                    scan_freq="2412")
5399 
5400 def test_ap_wpa2_eap_ttls_server_pkcs12_extra(dev, apdev):
5401     """EAP-TTLS and server PKCS#12 file with extra certs"""
5402     skip_with_fips(dev[0])
5403     params = int_eap_server_params()
5404     del params["server_cert"]
5405     params["private_key"] = "auth_serv/server-extra.pkcs12"
5406     params["private_key_passwd"] = "whatever"
5407     hostapd.add_ap(apdev[0], params)
5408     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
5409                    identity="mschap user", password="password",
5410                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
5411                    scan_freq="2412")
5412 
5413 def test_ap_wpa2_eap_ttls_dh_params_server(dev, apdev):
5414     """WPA2-Enterprise using EAP-TTLS and alternative server dhparams"""
5415     params = int_eap_server_params()
5416     params["dh_file"] = "auth_serv/dh2.conf"
5417     hapd = hostapd.add_ap(apdev[0], params)
5418     eap_connect(dev[0], hapd, "TTLS", "pap user",
5419                 anonymous_identity="ttls", password="password",
5420                 ca_cert="auth_serv/ca.der", phase2="auth=PAP")
5421 
5422 def test_ap_wpa2_eap_ttls_dh_params_dsa_server(dev, apdev):
5423     """WPA2-Enterprise using EAP-TTLS and alternative server dhparams (DSA)"""
5424     params = int_eap_server_params()
5425     params["dh_file"] = "auth_serv/dsaparam.pem"
5426     hapd = hostapd.add_ap(apdev[0], params)
5427     eap_connect(dev[0], hapd, "TTLS", "pap user",
5428                 anonymous_identity="ttls", password="password",
5429                 ca_cert="auth_serv/ca.der", phase2="auth=PAP")
5430 
5431 def test_ap_wpa2_eap_ttls_dh_params_not_found(dev, apdev):
5432     """EAP-TLS server and dhparams file not found"""
5433     params = int_eap_server_params()
5434     params["dh_file"] = "auth_serv/dh-no-such-file.conf"
5435     hapd = hostapd.add_ap(apdev[0], params, no_enable=True)
5436     if "FAIL" not in hapd.request("ENABLE"):
5437         raise Exception("Invalid configuration accepted")
5438 
5439 def test_ap_wpa2_eap_ttls_dh_params_invalid(dev, apdev):
5440     """EAP-TLS server and invalid dhparams file"""
5441     params = int_eap_server_params()
5442     params["dh_file"] = "auth_serv/ca.pem"
5443     hapd = hostapd.add_ap(apdev[0], params, no_enable=True)
5444     if "FAIL" not in hapd.request("ENABLE"):
5445         raise Exception("Invalid configuration accepted")
5446 
5447 def test_ap_wpa2_eap_reauth(dev, apdev):
5448     """WPA2-Enterprise and Authenticator forcing reauthentication"""
5449     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
5450     params['eap_reauth_period'] = '2'
5451     hapd = hostapd.add_ap(apdev[0], params)
5452     eap_connect(dev[0], hapd, "PAX", "pax.user@example.com",
5453                 password_hex="0123456789abcdef0123456789abcdef")
5454     logger.info("Wait for reauthentication")
5455     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=10)
5456     if ev is None:
5457         raise Exception("Timeout on reauthentication")
5458     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
5459     if ev is None:
5460         raise Exception("Timeout on reauthentication")
5461     for i in range(0, 20):
5462         state = dev[0].get_status_field("wpa_state")
5463         if state == "COMPLETED":
5464             break
5465         time.sleep(0.1)
5466     if state != "COMPLETED":
5467         raise Exception("Reauthentication did not complete")
5468 
5469 def test_ap_wpa2_eap_reauth_ptk_rekey_blocked_ap(dev, apdev):
5470     """WPA2-Enterprise and Authenticator forcing reauthentication with PTK rekey blocked on AP"""
5471     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
5472     params['eap_reauth_period'] = '2'
5473     params['wpa_deny_ptk0_rekey'] = '2'
5474     hapd = hostapd.add_ap(apdev[0], params)
5475     eap_connect(dev[0], hapd, "PAX", "pax.user@example.com",
5476                 password_hex="0123456789abcdef0123456789abcdef")
5477     logger.info("Wait for disconnect due to reauth")
5478     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED",
5479                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
5480     if ev is None:
5481         raise Exception("Timeout on reauthentication")
5482     if "CTRL-EVENT-EAP-STARTED" in ev:
5483         raise Exception("Reauthentication without disconnect")
5484 
5485     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=1)
5486     if ev is None:
5487         raise Exception("Timeout on reconnect")
5488 
5489 def test_ap_wpa2_eap_reauth_ptk_rekey_blocked_sta(dev, apdev):
5490     """WPA2-Enterprise and Authenticator forcing reauthentication with PTK rekey blocked on station"""
5491     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
5492     params['eap_reauth_period'] = '2'
5493     hapd = hostapd.add_ap(apdev[0], params)
5494     eap_connect(dev[0], hapd, "PAX", "pax.user@example.com",
5495                 password_hex="0123456789abcdef0123456789abcdef",
5496                 wpa_deny_ptk0_rekey="2")
5497     logger.info("Wait for disconnect due to reauth")
5498     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED",
5499                             "CTRL-EVENT-DISCONNECTED"], timeout=10)
5500     if ev is None:
5501         raise Exception("Timeout on reauthentication")
5502     if "CTRL-EVENT-EAP-STARTED" in ev:
5503         raise Exception("Reauthentication without disconnect")
5504 
5505     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=1)
5506     if ev is None:
5507         raise Exception("Timeout on reconnect")
5508 
5509 def test_ap_wpa2_eap_request_identity_message(dev, apdev):
5510     """Optional displayable message in EAP Request-Identity"""
5511     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
5512     params['eap_message'] = 'hello\\0networkid=netw,nasid=foo,portid=0,NAIRealms=example.com'
5513     hapd = hostapd.add_ap(apdev[0], params)
5514     eap_connect(dev[0], hapd, "PAX", "pax.user@example.com",
5515                 password_hex="0123456789abcdef0123456789abcdef")
5516 
5517 def test_ap_wpa2_eap_sim_aka_result_ind(dev, apdev):
5518     """WPA2-Enterprise using EAP-SIM/AKA and protected result indication"""
5519     check_hlr_auc_gw_support()
5520     params = int_eap_server_params()
5521     params['eap_sim_db'] = "unix:/tmp/hlr_auc_gw.sock"
5522     params['eap_sim_aka_result_ind'] = "1"
5523     hapd = hostapd.add_ap(apdev[0], params)
5524 
5525     eap_connect(dev[0], hapd, "SIM", "1232010000000000",
5526                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
5527                 phase1="result_ind=1")
5528     eap_reauth(dev[0], "SIM")
5529     eap_connect(dev[1], hapd, "SIM", "1232010000000000",
5530                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581")
5531 
5532     dev[0].request("REMOVE_NETWORK all")
5533     dev[1].request("REMOVE_NETWORK all")
5534 
5535     eap_connect(dev[0], hapd, "AKA", "0232010000000000",
5536                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123",
5537                 phase1="result_ind=1")
5538     eap_reauth(dev[0], "AKA")
5539     eap_connect(dev[1], hapd, "AKA", "0232010000000000",
5540                 password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123")
5541 
5542     dev[0].request("REMOVE_NETWORK all")
5543     dev[1].request("REMOVE_NETWORK all")
5544 
5545     eap_connect(dev[0], hapd, "AKA'", "6555444333222111",
5546                 password="5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123",
5547                 phase1="result_ind=1")
5548     eap_reauth(dev[0], "AKA'")
5549     eap_connect(dev[1], hapd, "AKA'", "6555444333222111",
5550                 password="5122250214c33e723a5dd523fc145fc0:981d464c7c52eb6e5036234984ad0bcf:000000000123")
5551 
5552 def test_ap_wpa2_eap_sim_zero_db_timeout(dev, apdev):
5553     """WPA2-Enterprise using EAP-SIM with zero database timeout"""
5554     check_hlr_auc_gw_support()
5555     params = int_eap_server_params()
5556     params['eap_sim_db'] = "unix:/tmp/hlr_auc_gw.sock"
5557     params['eap_sim_db_timeout'] = "0"
5558     params['disable_pmksa_caching'] = '1'
5559     hapd = hostapd.add_ap(apdev[0], params)
5560 
5561     # Run multiple iterations to make it more likely to hit the case where the
5562     # DB request times out and response is lost.
5563     for i in range(20):
5564         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="SIM",
5565                        identity="1232010000000000",
5566                        password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
5567                        wait_connect=False, scan_freq="2412")
5568         ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
5569                                 "CTRL-EVENT-DISCONNECTED"],
5570                                timeout=15)
5571         if ev is None:
5572             raise Exception("No connection result")
5573         dev[0].request("REMOVE_NETWORK all")
5574         if "CTRL-EVENT-DISCONNECTED" in ev:
5575             break
5576         dev[0].wait_disconnected()
5577         hapd.ping()
5578 
5579 def test_ap_wpa2_eap_too_many_roundtrips(dev, apdev):
5580     """WPA2-Enterprise connection resulting in too many EAP roundtrips"""
5581     skip_with_fips(dev[0])
5582     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
5583     hostapd.add_ap(apdev[0], params)
5584     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
5585                    eap="TTLS", identity="mschap user",
5586                    wait_connect=False, scan_freq="2412", ieee80211w="1",
5587                    anonymous_identity="ttls", password="password",
5588                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
5589                    fragment_size="4")
5590     ev = dev[0].wait_event(["EAP: more than",
5591                             "CTRL-EVENT-EAP-SUCCESS"], timeout=20)
5592     if ev is None or "EAP: more than" not in ev:
5593         raise Exception("EAP roundtrip limit not reached")
5594 
5595 def test_ap_wpa2_eap_too_many_roundtrips_server(dev, apdev):
5596     """WPA2-Enterprise connection resulting in too many EAP roundtrips (server)"""
5597     run_ap_wpa2_eap_too_many_roundtrips_server(dev, apdev, 10, 10)
5598 
5599 def test_ap_wpa2_eap_too_many_roundtrips_server2(dev, apdev):
5600     """WPA2-Enterprise connection resulting in too many EAP roundtrips (server)"""
5601     run_ap_wpa2_eap_too_many_roundtrips_server(dev, apdev, 10, 1)
5602 
5603 def run_ap_wpa2_eap_too_many_roundtrips_server(dev, apdev, max_rounds,
5604                                                max_rounds_short):
5605     skip_with_fips(dev[0])
5606     params = int_eap_server_params()
5607     params["max_auth_rounds"] = str(max_rounds)
5608     params["max_auth_rounds_short"] = str(max_rounds_short)
5609     hostapd.add_ap(apdev[0], params)
5610     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
5611                    eap="TTLS", identity="mschap user",
5612                    wait_connect=False, scan_freq="2412", ieee80211w="1",
5613                    anonymous_identity="ttls", password="password",
5614                    ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
5615                    fragment_size="4")
5616     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE",
5617                             "CTRL-EVENT-EAP-SUCCESS"], timeout=10)
5618     dev[0].request("DISCONNECT")
5619     if ev is None or "SUCCESS" in ev:
5620         raise Exception("EAP roundtrip limit not reported")
5621 
5622 def test_ap_wpa2_eap_expanded_nak(dev, apdev):
5623     """WPA2-Enterprise connection with EAP resulting in expanded NAK"""
5624     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
5625     hostapd.add_ap(apdev[0], params)
5626     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
5627                    eap="PSK", identity="vendor-test",
5628                    password_hex="ff23456789abcdef0123456789abcdef",
5629                    wait_connect=False)
5630 
5631     found = False
5632     for i in range(0, 5):
5633         ev = dev[0].wait_event(["CTRL-EVENT-EAP-STATUS"], timeout=16)
5634         if ev is None:
5635             raise Exception("Association and EAP start timed out")
5636         if "refuse proposed method" in ev:
5637             found = True
5638             break
5639     if not found:
5640         raise Exception("Unexpected EAP status: " + ev)
5641 
5642     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"])
5643     if ev is None:
5644         raise Exception("EAP failure timed out")
5645 
5646 def test_ap_wpa2_eap_sql(dev, apdev, params):
5647     """WPA2-Enterprise connection using SQLite for user DB"""
5648     skip_with_fips(dev[0])
5649     try:
5650         import sqlite3
5651     except ImportError:
5652         raise HwsimSkip("No sqlite3 module available")
5653     dbfile = os.path.join(params['logdir'], "eap-user.db")
5654     try:
5655         os.remove(dbfile)
5656     except:
5657         pass
5658     con = sqlite3.connect(dbfile)
5659     with con:
5660         cur = con.cursor()
5661         cur.execute("CREATE TABLE users(identity TEXT PRIMARY KEY, methods TEXT, password TEXT, remediation TEXT, phase2 INTEGER)")
5662         cur.execute("CREATE TABLE wildcards(identity TEXT PRIMARY KEY, methods TEXT)")
5663         cur.execute("INSERT INTO users(identity,methods,password,phase2) VALUES ('user-pap','TTLS-PAP','password',1)")
5664         cur.execute("INSERT INTO users(identity,methods,password,phase2) VALUES ('user-chap','TTLS-CHAP','password',1)")
5665         cur.execute("INSERT INTO users(identity,methods,password,phase2) VALUES ('user-mschap','TTLS-MSCHAP','password',1)")
5666         cur.execute("INSERT INTO users(identity,methods,password,phase2) VALUES ('user-mschapv2','TTLS-MSCHAPV2','password',1)")
5667         cur.execute("INSERT INTO wildcards(identity,methods) VALUES ('','TTLS,TLS')")
5668         cur.execute("CREATE TABLE authlog(timestamp TEXT, session TEXT, nas_ip TEXT, username TEXT, note TEXT)")
5669 
5670     try:
5671         params = int_eap_server_params()
5672         params["eap_user_file"] = "sqlite:" + dbfile
5673         hapd = hostapd.add_ap(apdev[0], params)
5674         eap_connect(dev[0], hapd, "TTLS", "user-mschapv2",
5675                     anonymous_identity="ttls", password="password",
5676                     ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
5677         dev[0].request("REMOVE_NETWORK all")
5678         eap_connect(dev[1], hapd, "TTLS", "user-mschap",
5679                     anonymous_identity="ttls", password="password",
5680                     ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP")
5681         dev[1].request("REMOVE_NETWORK all")
5682         eap_connect(dev[0], hapd, "TTLS", "user-chap",
5683                     anonymous_identity="ttls", password="password",
5684                     ca_cert="auth_serv/ca.pem", phase2="auth=CHAP")
5685         eap_connect(dev[1], hapd, "TTLS", "user-pap",
5686                     anonymous_identity="ttls", password="password",
5687                     ca_cert="auth_serv/ca.pem", phase2="auth=PAP")
5688         dev[0].request("REMOVE_NETWORK all")
5689         dev[1].request("REMOVE_NETWORK all")
5690         dev[0].wait_disconnected()
5691         dev[1].wait_disconnected()
5692         hapd.disable()
5693         hapd.enable()
5694         eap_connect(dev[0], hapd, "TTLS", "user-mschapv2",
5695                     anonymous_identity="ttls", password="password",
5696                     ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
5697     finally:
5698         os.remove(dbfile)
5699 
5700 def test_ap_wpa2_eap_non_ascii_identity(dev, apdev):
5701     """WPA2-Enterprise connection attempt using non-ASCII identity"""
5702     params = int_eap_server_params()
5703     hostapd.add_ap(apdev[0], params)
5704     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
5705                    identity="\x80", password="password", wait_connect=False)
5706     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
5707                    identity="a\x80", password="password", wait_connect=False)
5708     for i in range(0, 2):
5709         ev = dev[i].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
5710         if ev is None:
5711             raise Exception("Association and EAP start timed out")
5712         ev = dev[i].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=10)
5713         if ev is None:
5714             raise Exception("EAP method selection timed out")
5715 
5716 def test_ap_wpa2_eap_non_ascii_identity2(dev, apdev):
5717     """WPA2-Enterprise connection attempt using non-ASCII identity"""
5718     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
5719     hostapd.add_ap(apdev[0], params)
5720     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
5721                    identity="\x80", password="password", wait_connect=False)
5722     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
5723                    identity="a\x80", password="password", wait_connect=False)
5724     for i in range(0, 2):
5725         ev = dev[i].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=16)
5726         if ev is None:
5727             raise Exception("Association and EAP start timed out")
5728         ev = dev[i].wait_event(["CTRL-EVENT-EAP-METHOD"], timeout=10)
5729         if ev is None:
5730             raise Exception("EAP method selection timed out")
5731 
5732 def test_openssl_cipher_suite_config_wpas(dev, apdev):
5733     """OpenSSL cipher suite configuration on wpa_supplicant"""
5734     tls = dev[0].request("GET tls_library")
5735     if not tls.startswith("OpenSSL"):
5736         raise HwsimSkip("TLS library is not OpenSSL: " + tls)
5737     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
5738     hapd = hostapd.add_ap(apdev[0], params)
5739     eap_connect(dev[0], hapd, "TTLS", "pap user",
5740                 anonymous_identity="ttls", password="password",
5741                 openssl_ciphers="AES128",
5742                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP")
5743     eap_connect(dev[1], hapd, "TTLS", "pap user",
5744                 anonymous_identity="ttls", password="password",
5745                 openssl_ciphers="EXPORT",
5746                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP",
5747                 expect_failure=True, maybe_local_error=True)
5748     dev[2].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
5749                    identity="pap user", anonymous_identity="ttls",
5750                    password="password",
5751                    openssl_ciphers="FOO",
5752                    ca_cert="auth_serv/ca.pem", phase2="auth=PAP",
5753                    wait_connect=False)
5754     ev = dev[2].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5755     if ev is None:
5756         raise Exception("EAP failure after invalid openssl_ciphers not reported")
5757     dev[2].request("DISCONNECT")
5758 
5759 def test_openssl_cipher_suite_config_hapd(dev, apdev):
5760     """OpenSSL cipher suite configuration on hostapd"""
5761     tls = dev[0].request("GET tls_library")
5762     if not tls.startswith("OpenSSL"):
5763         raise HwsimSkip("wpa_supplicant TLS library is not OpenSSL: " + tls)
5764     params = int_eap_server_params()
5765     params['openssl_ciphers'] = "AES256"
5766     hapd = hostapd.add_ap(apdev[0], params)
5767     tls = hapd.request("GET tls_library")
5768     if not tls.startswith("OpenSSL"):
5769         raise HwsimSkip("hostapd TLS library is not OpenSSL: " + tls)
5770     eap_connect(dev[0], hapd, "TTLS", "pap user",
5771                 anonymous_identity="ttls", password="password",
5772                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP")
5773     eap_connect(dev[1], hapd, "TTLS", "pap user",
5774                 anonymous_identity="ttls", password="password",
5775                 openssl_ciphers="AES128",
5776                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP",
5777                 expect_failure=True)
5778     eap_connect(dev[2], hapd, "TTLS", "pap user",
5779                 anonymous_identity="ttls", password="password",
5780                 openssl_ciphers="HIGH:!ADH",
5781                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP")
5782 
5783     params['openssl_ciphers'] = "FOO"
5784     hapd2 = hostapd.add_ap(apdev[1], params, no_enable=True)
5785     if "FAIL" not in hapd2.request("ENABLE"):
5786         if "run=OpenSSL 1.1.1" in tls:
5787             logger.info("Ignore acceptance of an invalid openssl_ciphers value with OpenSSL 1.1.1")
5788         else:
5789             raise Exception("Invalid openssl_ciphers value accepted")
5790 
5791 def test_wpa2_eap_ttls_pap_key_lifetime_in_memory(dev, apdev, params):
5792     """Key lifetime in memory with WPA2-Enterprise using EAP-TTLS/PAP"""
5793     p = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
5794     hapd = hostapd.add_ap(apdev[0], p)
5795     password = "63d2d21ac3c09ed567ee004a34490f1d16e7fa5835edf17ddba70a63f1a90a25"
5796     id = eap_connect(dev[0], hapd, "TTLS", "pap-secret",
5797                      anonymous_identity="ttls", password=password,
5798                      ca_cert="auth_serv/ca.pem", phase2="auth=PAP")
5799     run_eap_key_lifetime_in_memory(dev, params, id, password)
5800 
5801 def test_wpa2_eap_peap_gtc_key_lifetime_in_memory(dev, apdev, params):
5802     """Key lifetime in memory with WPA2-Enterprise using PEAP/GTC"""
5803     p = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
5804     hapd = hostapd.add_ap(apdev[0], p)
5805     password = "63d2d21ac3c09ed567ee004a34490f1d16e7fa5835edf17ddba70a63f1a90a25"
5806     id = eap_connect(dev[0], hapd, "PEAP", "user-secret",
5807                      anonymous_identity="peap", password=password,
5808                      ca_cert="auth_serv/ca.pem", phase2="auth=GTC")
5809     run_eap_key_lifetime_in_memory(dev, params, id, password)
5810 
5811 def run_eap_key_lifetime_in_memory(dev, params, id, password):
5812     pid = find_wpas_process(dev[0])
5813 
5814     # The decrypted copy of GTK is freed only after the CTRL-EVENT-CONNECTED
5815     # event has been delivered, so verify that wpa_supplicant has returned to
5816     # eloop before reading process memory.
5817     time.sleep(1)
5818     dev[0].ping()
5819     password = password.encode()
5820     buf = read_process_memory(pid, password)
5821 
5822     dev[0].request("DISCONNECT")
5823     dev[0].wait_disconnected()
5824 
5825     dev[0].relog()
5826     msk = None
5827     emsk = None
5828     pmk = None
5829     ptk = None
5830     gtk = None
5831     with open(os.path.join(params['logdir'], 'log0'), 'r') as f:
5832         for l in f.readlines():
5833             if "EAP-TTLS: Derived key - hexdump" in l or \
5834                "EAP-PEAP: Derived key - hexdump" in l:
5835                 val = l.strip().split(':')[3].replace(' ', '')
5836                 msk = binascii.unhexlify(val)
5837             if "EAP-TTLS: Derived EMSK - hexdump" in l or \
5838                "EAP-PEAP: Derived EMSK - hexdump" in l:
5839                 val = l.strip().split(':')[3].replace(' ', '')
5840                 emsk = binascii.unhexlify(val)
5841             if "WPA: PMK - hexdump" in l:
5842                 val = l.strip().split(':')[3].replace(' ', '')
5843                 pmk = binascii.unhexlify(val)
5844             if "WPA: PTK - hexdump" in l:
5845                 val = l.strip().split(':')[3].replace(' ', '')
5846                 ptk = binascii.unhexlify(val)
5847             if "WPA: Group Key - hexdump" in l:
5848                 val = l.strip().split(':')[3].replace(' ', '')
5849                 gtk = binascii.unhexlify(val)
5850     if not msk or not emsk or not pmk or not ptk or not gtk:
5851         raise Exception("Could not find keys from debug log")
5852     if len(gtk) != 16:
5853         raise Exception("Unexpected GTK length")
5854 
5855     kck = ptk[0:16]
5856     kek = ptk[16:32]
5857     tk = ptk[32:48]
5858 
5859     fname = os.path.join(params['logdir'],
5860                          'wpa2_eap_ttls_pap_key_lifetime_in_memory.memctx-')
5861 
5862     logger.info("Checking keys in memory while associated")
5863     get_key_locations(buf, password, "Password")
5864     get_key_locations(buf, pmk, "PMK")
5865     get_key_locations(buf, msk, "MSK")
5866     get_key_locations(buf, emsk, "EMSK")
5867     if password not in buf:
5868         raise HwsimSkip("Password not found while associated")
5869     if pmk not in buf:
5870         raise HwsimSkip("PMK not found while associated")
5871     if kck not in buf:
5872         raise Exception("KCK not found while associated")
5873     if kek not in buf:
5874         raise Exception("KEK not found while associated")
5875     #if tk in buf:
5876     #    raise Exception("TK found from memory")
5877 
5878     logger.info("Checking keys in memory after disassociation")
5879     buf = read_process_memory(pid, password)
5880 
5881     # Note: Password is still present in network configuration
5882     # Note: PMK is in PMKSA cache and EAP fast re-auth data
5883 
5884     get_key_locations(buf, password, "Password")
5885     get_key_locations(buf, pmk, "PMK")
5886     get_key_locations(buf, msk, "MSK")
5887     get_key_locations(buf, emsk, "EMSK")
5888     verify_not_present(buf, kck, fname, "KCK")
5889     verify_not_present(buf, kek, fname, "KEK")
5890     verify_not_present(buf, tk, fname, "TK")
5891     if gtk in buf:
5892         get_key_locations(buf, gtk, "GTK")
5893     verify_not_present(buf, gtk, fname, "GTK")
5894 
5895     dev[0].request("PMKSA_FLUSH")
5896     dev[0].set_network_quoted(id, "identity", "foo")
5897     logger.info("Checking keys in memory after PMKSA cache and EAP fast reauth flush")
5898     buf = read_process_memory(pid, password)
5899     get_key_locations(buf, password, "Password")
5900     get_key_locations(buf, pmk, "PMK")
5901     get_key_locations(buf, msk, "MSK")
5902     get_key_locations(buf, emsk, "EMSK")
5903     verify_not_present(buf, pmk, fname, "PMK")
5904 
5905     dev[0].request("REMOVE_NETWORK all")
5906 
5907     logger.info("Checking keys in memory after network profile removal")
5908     buf = read_process_memory(pid, password)
5909 
5910     get_key_locations(buf, password, "Password")
5911     get_key_locations(buf, pmk, "PMK")
5912     get_key_locations(buf, msk, "MSK")
5913     get_key_locations(buf, emsk, "EMSK")
5914     verify_not_present(buf, password, fname, "password")
5915     verify_not_present(buf, pmk, fname, "PMK")
5916     verify_not_present(buf, kck, fname, "KCK")
5917     verify_not_present(buf, kek, fname, "KEK")
5918     verify_not_present(buf, tk, fname, "TK")
5919     verify_not_present(buf, gtk, fname, "GTK")
5920     verify_not_present(buf, msk, fname, "MSK")
5921     verify_not_present(buf, emsk, fname, "EMSK")
5922 
5923 def test_ap_wpa2_eap_unexpected_wep_eapol_key(dev, apdev):
5924     """WPA2-Enterprise connection and unexpected WEP EAPOL-Key"""
5925     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
5926     hapd = hostapd.add_ap(apdev[0], params)
5927     bssid = apdev[0]['bssid']
5928     eap_connect(dev[0], hapd, "TTLS", "pap user",
5929                 anonymous_identity="ttls", password="password",
5930                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP")
5931 
5932     # Send unexpected WEP EAPOL-Key; this gets dropped
5933     res = dev[0].request("EAPOL_RX " + bssid + " 0203002c0100000000000000000000000000000000000000000000000000000000000000000000000000000000000000")
5934     if "OK" not in res:
5935         raise Exception("EAPOL_RX to wpa_supplicant failed")
5936 
5937 def test_ap_wpa2_eap_in_bridge(dev, apdev):
5938     """WPA2-EAP and wpas interface in a bridge"""
5939     br_ifname = 'sta-br0'
5940     ifname = 'wlan5'
5941     try:
5942         _test_ap_wpa2_eap_in_bridge(dev, apdev)
5943     finally:
5944         subprocess.call(['ip', 'link', 'set', 'dev', br_ifname, 'down'])
5945         subprocess.call(['brctl', 'delif', br_ifname, ifname])
5946         subprocess.call(['brctl', 'delbr', br_ifname])
5947         subprocess.call(['iw', ifname, 'set', '4addr', 'off'])
5948 
5949 def _test_ap_wpa2_eap_in_bridge(dev, apdev):
5950     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
5951     hapd = hostapd.add_ap(apdev[0], params)
5952 
5953     br_ifname = 'sta-br0'
5954     ifname = 'wlan5'
5955     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
5956     subprocess.call(['brctl', 'addbr', br_ifname])
5957     subprocess.call(['brctl', 'setfd', br_ifname, '0'])
5958     subprocess.call(['ip', 'link', 'set', 'dev', br_ifname, 'up'])
5959     subprocess.call(['iw', ifname, 'set', '4addr', 'on'])
5960     subprocess.check_call(['brctl', 'addif', br_ifname, ifname])
5961     wpas.interface_add(ifname, br_ifname=br_ifname)
5962     wpas.dump_monitor()
5963 
5964     id = eap_connect(wpas, hapd, "PAX", "pax.user@example.com",
5965                      password_hex="0123456789abcdef0123456789abcdef")
5966     wpas.dump_monitor()
5967     eap_reauth(wpas, "PAX")
5968     hapd.wait_4way_hs()
5969     wpas.dump_monitor()
5970     # Try again as a regression test for packet socket workaround
5971     eap_reauth(wpas, "PAX")
5972     hapd.wait_4way_hs()
5973     wpas.dump_monitor()
5974     wpas.request("DISCONNECT")
5975     wpas.wait_disconnected()
5976     hapd.wait_sta_disconnect()
5977     wpas.dump_monitor()
5978     wpas.request("RECONNECT")
5979     wpas.wait_connected()
5980     hapd.wait_sta()
5981     wpas.dump_monitor()
5982 
5983 def test_ap_wpa2_eap_session_ticket(dev, apdev):
5984     """WPA2-Enterprise connection using EAP-TTLS and TLS session ticket enabled"""
5985     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
5986     hapd = hostapd.add_ap(apdev[0], params)
5987     key_mgmt = hapd.get_config()['key_mgmt']
5988     if key_mgmt.split(' ')[0] != "WPA-EAP":
5989         raise Exception("Unexpected GET_CONFIG(key_mgmt): " + key_mgmt)
5990     eap_connect(dev[0], hapd, "TTLS", "pap user",
5991                 anonymous_identity="ttls", password="password",
5992                 ca_cert="auth_serv/ca.pem",
5993                 phase1="tls_disable_session_ticket=0", phase2="auth=PAP")
5994     eap_reauth(dev[0], "TTLS")
5995 
5996 def test_ap_wpa2_eap_no_workaround(dev, apdev):
5997     """WPA2-Enterprise connection using EAP-TTLS and eap_workaround=0"""
5998     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
5999     hapd = hostapd.add_ap(apdev[0], params)
6000     key_mgmt = hapd.get_config()['key_mgmt']
6001     if key_mgmt.split(' ')[0] != "WPA-EAP":
6002         raise Exception("Unexpected GET_CONFIG(key_mgmt): " + key_mgmt)
6003     eap_connect(dev[0], hapd, "TTLS", "pap user",
6004                 anonymous_identity="ttls", password="password",
6005                 ca_cert="auth_serv/ca.pem", eap_workaround='0',
6006                 phase2="auth=PAP")
6007     eap_reauth(dev[0], "TTLS")
6008 
6009 def test_ap_wpa2_eap_tls_check_crl(dev, apdev):
6010     """EAP-TLS and server checking CRL"""
6011     params = int_eap_server_params()
6012     params['check_crl'] = '1'
6013     hapd = hostapd.add_ap(apdev[0], params)
6014 
6015     # check_crl=1 and no CRL available --> reject connection
6016     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
6017                 client_cert="auth_serv/user.pem",
6018                 private_key="auth_serv/user.key", expect_failure=True)
6019     dev[0].request("REMOVE_NETWORK all")
6020 
6021     hapd.disable()
6022     hapd.set("ca_cert", "auth_serv/ca-and-crl.pem")
6023     hapd.enable()
6024 
6025     # check_crl=1 and valid CRL --> accept
6026     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
6027                 client_cert="auth_serv/user.pem",
6028                 private_key="auth_serv/user.key")
6029     dev[0].request("REMOVE_NETWORK all")
6030 
6031     hapd.disable()
6032     hapd.set("check_crl", "2")
6033     hapd.enable()
6034 
6035     # check_crl=2 and valid CRL --> accept
6036     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
6037                 client_cert="auth_serv/user.pem",
6038                 private_key="auth_serv/user.key")
6039     dev[0].request("REMOVE_NETWORK all")
6040 
6041 def test_ap_wpa2_eap_tls_check_crl_not_strict(dev, apdev):
6042     """EAP-TLS and server checking CRL with check_crl_strict=0"""
6043     params = int_eap_server_params()
6044     params['check_crl'] = '1'
6045     params['ca_cert'] = "auth_serv/ca-and-crl-expired.pem"
6046     hapd = hostapd.add_ap(apdev[0], params)
6047 
6048     # check_crl_strict=1 and expired CRL --> reject connection
6049     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
6050                 client_cert="auth_serv/user.pem",
6051                 private_key="auth_serv/user.key", expect_failure=True)
6052     dev[0].request("REMOVE_NETWORK all")
6053 
6054     hapd.disable()
6055     hapd.set("check_crl_strict", "0")
6056     hapd.enable()
6057 
6058     # check_crl_strict=0 --> accept
6059     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
6060                 client_cert="auth_serv/user.pem",
6061                 private_key="auth_serv/user.key")
6062     dev[0].request("REMOVE_NETWORK all")
6063 
6064 def test_ap_wpa2_eap_tls_crl_reload(dev, apdev, params):
6065     """EAP-TLS and server reloading CRL from ca_cert"""
6066     ca_cert = os.path.join(params['logdir'],
6067                            "ap_wpa2_eap_tls_crl_reload.ca_cert")
6068     with open('auth_serv/ca.pem', 'r') as f:
6069         only_cert = f.read()
6070     with open('auth_serv/ca-and-crl.pem', 'r') as f:
6071         cert_and_crl = f.read()
6072     with open(ca_cert, 'w') as f:
6073         f.write(only_cert)
6074     params = int_eap_server_params()
6075     params['ca_cert'] = ca_cert
6076     params['check_crl'] = '1'
6077     params['crl_reload_interval'] = '1'
6078     hapd = hostapd.add_ap(apdev[0], params)
6079 
6080     # check_crl=1 and no CRL available --> reject connection
6081     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
6082                 client_cert="auth_serv/user.pem",
6083                 private_key="auth_serv/user.key", expect_failure=True)
6084     dev[0].request("REMOVE_NETWORK all")
6085     dev[0].dump_monitor()
6086 
6087     with open(ca_cert, 'w') as f:
6088         f.write(cert_and_crl)
6089     time.sleep(1)
6090 
6091     # check_crl=1 and valid CRL --> accept
6092     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
6093                 client_cert="auth_serv/user.pem",
6094                 private_key="auth_serv/user.key")
6095     dev[0].request("REMOVE_NETWORK all")
6096     dev[0].wait_disconnected()
6097 
6098 def test_ap_wpa2_eap_tls_check_cert_subject(dev, apdev):
6099     """EAP-TLS and server checking client subject name"""
6100     params = int_eap_server_params()
6101     params['check_cert_subject'] = 'C=FI/O=w1.fi/CN=Test User'
6102     hapd = hostapd.add_ap(apdev[0], params)
6103     check_check_cert_subject_support(hapd)
6104 
6105     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
6106                 client_cert="auth_serv/user.pem",
6107                 private_key="auth_serv/user.key")
6108 
6109 def test_ap_wpa2_eap_tls_check_cert_subject_neg(dev, apdev):
6110     """EAP-TLS and server checking client subject name (negative)"""
6111     params = int_eap_server_params()
6112     params['check_cert_subject'] = 'C=FI/O=example'
6113     hapd = hostapd.add_ap(apdev[0], params)
6114     check_check_cert_subject_support(hapd)
6115 
6116     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
6117                 client_cert="auth_serv/user.pem",
6118                 private_key="auth_serv/user.key", expect_failure=True)
6119 
6120 def test_ap_wpa2_eap_tls_oom(dev, apdev):
6121     """EAP-TLS and OOM"""
6122     check_subject_match_support(dev[0])
6123     check_altsubject_match_support(dev[0])
6124     check_domain_match(dev[0])
6125     check_domain_match_full(dev[0])
6126 
6127     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
6128     hostapd.add_ap(apdev[0], params)
6129 
6130     tests = [(1, "tls_connection_set_subject_match"),
6131              (2, "tls_connection_set_subject_match"),
6132              (3, "tls_connection_set_subject_match"),
6133              (4, "tls_connection_set_subject_match")]
6134     for count, func in tests:
6135         with alloc_fail(dev[0], count, func):
6136             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
6137                            identity="tls user", ca_cert="auth_serv/ca.pem",
6138                            client_cert="auth_serv/user.pem",
6139                            private_key="auth_serv/user.key",
6140                            subject_match="/C=FI/O=w1.fi/CN=server.w1.fi",
6141                            altsubject_match="EMAIL:noone@example.com;DNS:server.w1.fi;URI:http://example.com/",
6142                            domain_suffix_match="server.w1.fi",
6143                            domain_match="server.w1.fi",
6144                            wait_connect=False, scan_freq="2412")
6145             # TLS parameter configuration error results in CTRL-REQ-PASSPHRASE
6146             ev = dev[0].wait_event(["CTRL-REQ-PASSPHRASE"], timeout=5)
6147             if ev is None:
6148                 raise Exception("No passphrase request")
6149             dev[0].request("REMOVE_NETWORK all")
6150             dev[0].wait_disconnected()
6151 
6152 def test_ap_wpa2_eap_tls_macacl(dev, apdev):
6153     """WPA2-Enterprise connection using MAC ACL"""
6154     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
6155     params["macaddr_acl"] = "2"
6156     hapd = hostapd.add_ap(apdev[0], params)
6157     eap_connect(dev[1], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
6158                 client_cert="auth_serv/user.pem",
6159                 private_key="auth_serv/user.key")
6160 
6161 def test_ap_wpa2_eap_oom(dev, apdev):
6162     """EAP server and OOM"""
6163     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
6164     hapd = hostapd.add_ap(apdev[0], params)
6165     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
6166 
6167     with alloc_fail(hapd, 1, "eapol_auth_alloc"):
6168         # The first attempt fails, but STA will send EAPOL-Start to retry and
6169         # that succeeds.
6170         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
6171                        identity="tls user", ca_cert="auth_serv/ca.pem",
6172                        client_cert="auth_serv/user.pem",
6173                        private_key="auth_serv/user.key",
6174                        scan_freq="2412")
6175 
6176 def check_tls_ver(dev, hapd, phase1, expected):
6177     eap_connect(dev, hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
6178                 client_cert="auth_serv/user.pem",
6179                 private_key="auth_serv/user.key",
6180                 phase1=phase1)
6181     ver = dev.get_status_field("eap_tls_version")
6182     if ver != expected:
6183         raise Exception("Unexpected TLS version (expected %s): %s" % (expected, ver))
6184     dev.request("REMOVE_NETWORK all")
6185     dev.wait_disconnected()
6186     dev.dump_monitor()
6187 
6188 def test_ap_wpa2_eap_tls_versions(dev, apdev):
6189     """EAP-TLS and TLS version configuration"""
6190     params = {"ssid": "test-wpa2-eap",
6191               "wpa": "2",
6192               "wpa_key_mgmt": "WPA-EAP",
6193               "rsn_pairwise": "CCMP",
6194               "ieee8021x": "1",
6195               "eap_server": "1",
6196               "tls_flags": "[ENABLE-TLSv1.0][ENABLE-TLSv1.1][ENABLE-TLSv1.2][ENABLE-TLSv1.3]",
6197               "eap_user_file": "auth_serv/eap_user.conf",
6198               "ca_cert": "auth_serv/ca.pem",
6199               "server_cert": "auth_serv/server.pem",
6200               "private_key": "auth_serv/server.key"}
6201     hapd = hostapd.add_ap(apdev[0], params)
6202 
6203     tls = dev[0].request("GET tls_library")
6204     if tls.startswith("OpenSSL"):
6205         if "build=OpenSSL 1.0.1" not in tls and "run=OpenSSL 1.0.1" not in tls:
6206             check_tls_ver(dev[0], hapd,
6207                           "tls_disable_tlsv1_0=1 tls_disable_tlsv1_1=1",
6208                           "TLSv1.2")
6209     if tls.startswith("wolfSSL"):
6210         check_tls_ver(dev[0], hapd,
6211                       "tls_disable_tlsv1_0=1 tls_disable_tlsv1_1=1", "TLSv1.2")
6212     elif tls.startswith("internal"):
6213         check_tls_ver(dev[0], hapd,
6214                       "tls_disable_tlsv1_0=1 tls_disable_tlsv1_1=1", "TLSv1.2")
6215     check_tls_ver(dev[1], hapd,
6216                   "tls_disable_tlsv1_0=1 tls_disable_tlsv1_1=0 tls_disable_tlsv1_2=1", "TLSv1.1")
6217     check_tls_ver(dev[2], hapd,
6218                   "tls_disable_tlsv1_0=0 tls_disable_tlsv1_1=1 tls_disable_tlsv1_2=1", "TLSv1")
6219     if "run=OpenSSL 1.1.1" in tls or "run=OpenSSL 3." in tls or \
6220        tls.startswith("wolfSSL"):
6221         check_tls_ver(dev[0], hapd,
6222                       "tls_disable_tlsv1_0=1 tls_disable_tlsv1_1=1 tls_disable_tlsv1_2=1 tls_disable_tlsv1_3=0", "TLSv1.3")
6223 
6224 def test_ap_wpa2_eap_tls_versions_server(dev, apdev):
6225     """EAP-TLS and TLS version configuration on server side"""
6226     params = {"ssid": "test-wpa2-eap",
6227               "wpa": "2",
6228               "wpa_key_mgmt": "WPA-EAP",
6229               "rsn_pairwise": "CCMP",
6230               "ieee8021x": "1",
6231               "eap_server": "1",
6232               "eap_user_file": "auth_serv/eap_user.conf",
6233               "ca_cert": "auth_serv/ca.pem",
6234               "server_cert": "auth_serv/server.pem",
6235               "private_key": "auth_serv/server.key"}
6236     hapd = hostapd.add_ap(apdev[0], params)
6237 
6238     tests = [("TLSv1", "[ENABLE-TLSv1.0][DISABLE-TLSv1.1][DISABLE-TLSv1.2][DISABLE-TLSv1.3]"),
6239              ("TLSv1.1", "[ENABLE-TLSv1.0][ENABLE-TLSv1.1][DISABLE-TLSv1.2][DISABLE-TLSv1.3]"),
6240              ("TLSv1.2", "[ENABLE-TLSv1.0][ENABLE-TLSv1.1][ENABLE-TLSv1.2][DISABLE-TLSv1.3]")]
6241     for exp, flags in tests:
6242         hapd.disable()
6243         hapd.set("tls_flags", flags)
6244         hapd.enable()
6245         check_tls_ver(dev[0], hapd, "tls_disable_tlsv1_0=0 tls_disable_tlsv1_1=0 tls_disable_tlsv1_2=0 tls_disable_tlsv1_3=0", exp)
6246 
6247 def test_ap_wpa2_eap_tls_13(dev, apdev):
6248     """EAP-TLS and TLS 1.3"""
6249     run_ap_wpa2_eap_tls_13(dev, apdev)
6250 
6251 def test_ap_wpa2_eap_tls_13_ocsp(dev, apdev):
6252     """EAP-TLS and TLS 1.3 with OCSP stapling"""
6253     run_ap_wpa2_eap_tls_13(dev, apdev, ocsp=True)
6254 
6255 def run_ap_wpa2_eap_tls_13(dev, apdev, ocsp=False):
6256     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
6257     hapd = hostapd.add_ap(apdev[0], params)
6258 
6259     check_tls13_support(dev[0])
6260     if ocsp:
6261         check_ocsp_support(dev[0])
6262     id = eap_connect(dev[0], hapd, "TLS", "tls user",
6263                      ca_cert="auth_serv/ca.pem",
6264                      client_cert="auth_serv/user.pem",
6265                      private_key="auth_serv/user.key",
6266                      phase1="tls_disable_tlsv1_0=1 tls_disable_tlsv1_1=1 tls_disable_tlsv1_2=1 tls_disable_tlsv1_3=0",
6267                      ocsp=2 if ocsp else 0)
6268     ver = dev[0].get_status_field("eap_tls_version")
6269     if ver != "TLSv1.3":
6270         raise Exception("Unexpected TLS version")
6271 
6272     eap_reauth(dev[0], "TLS")
6273     dev[0].request("DISCONNECT")
6274     dev[0].wait_disconnected()
6275     dev[0].request("PMKSA_FLUSH")
6276     dev[0].request("RECONNECT")
6277     dev[0].wait_connected()
6278 
6279 def test_ap_wpa2_eap_tls_13_missing_prot_success(dev, apdev):
6280     """EAP-TLSv1.3 and missing protected success indication"""
6281     params = int_eap_server_params()
6282     params['tls_flags'] = '[ENABLE-TLSv1.3]'
6283     params['eap_skip_prot_success'] = '1'
6284     hapd = hostapd.add_ap(apdev[0], params)
6285 
6286     check_tls13_support(dev[0])
6287     id = eap_connect(dev[0], hapd, "TLS", "tls user",
6288                      ca_cert="auth_serv/ca.pem",
6289                      client_cert="auth_serv/user.pem",
6290                      private_key="auth_serv/user.key",
6291                      phase1="tls_disable_tlsv1_0=1 tls_disable_tlsv1_1=1 tls_disable_tlsv1_2=1 tls_disable_tlsv1_3=0",
6292                      expect_failure=True, local_error_report=True)
6293 
6294 def test_ap_wpa2_eap_tls_13_fragmentation(dev, apdev):
6295     """EAP-TLSv1.3 and fragmentation"""
6296     params = int_eap_server_params()
6297     params['tls_flags'] = '[ENABLE-TLSv1.3]'
6298     params['fragment_size'] = '100'
6299     hapd = hostapd.add_ap(apdev[0], params)
6300 
6301     check_tls13_support(dev[0])
6302     id = eap_connect(dev[0], hapd, "TLS", "tls user",
6303                      ca_cert="auth_serv/ca.pem",
6304                      client_cert="auth_serv/user.pem",
6305                      private_key="auth_serv/user.key",
6306                      phase1="tls_disable_tlsv1_0=1 tls_disable_tlsv1_1=1 tls_disable_tlsv1_2=1 tls_disable_tlsv1_3=0",
6307                      fragment_size="100")
6308 
6309 def test_ap_wpa2_eap_ttls_13(dev, apdev):
6310     """EAP-TTLS and TLS 1.3"""
6311     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
6312     hapd = hostapd.add_ap(apdev[0], params)
6313 
6314     check_tls13_support(dev[0])
6315     id = eap_connect(dev[0], hapd, "TTLS", "pap user",
6316                      anonymous_identity="ttls", password="password",
6317                      ca_cert="auth_serv/ca.pem",
6318                      phase1="tls_disable_tlsv1_0=1 tls_disable_tlsv1_1=1 tls_disable_tlsv1_2=1 tls_disable_tlsv1_3=0",
6319                      phase2="auth=PAP")
6320     ver = dev[0].get_status_field("eap_tls_version")
6321     if ver != "TLSv1.3":
6322         raise Exception("Unexpected TLS version")
6323 
6324     eap_reauth(dev[0], "TTLS")
6325     dev[0].request("DISCONNECT")
6326     dev[0].wait_disconnected()
6327     dev[0].request("PMKSA_FLUSH")
6328     dev[0].request("RECONNECT")
6329     dev[0].wait_connected()
6330 
6331 def test_ap_wpa2_eap_peap_13(dev, apdev):
6332     """PEAP and TLS 1.3"""
6333     check_eap_capa(dev[0], "MSCHAPV2")
6334     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
6335     hapd = hostapd.add_ap(apdev[0], params)
6336 
6337     check_tls13_support(dev[0])
6338     id = eap_connect(dev[0], hapd, "PEAP", "user",
6339                      anonymous_identity="peap", password="password",
6340                      ca_cert="auth_serv/ca.pem",
6341                      phase1="tls_disable_tlsv1_0=1 tls_disable_tlsv1_1=1 tls_disable_tlsv1_2=1 tls_disable_tlsv1_3=0",
6342                      phase2="auth=MSCHAPV2")
6343     ver = dev[0].get_status_field("eap_tls_version")
6344     if ver != "TLSv1.3":
6345         raise Exception("Unexpected TLS version")
6346 
6347     eap_reauth(dev[0], "PEAP")
6348     dev[0].request("DISCONNECT")
6349     dev[0].wait_disconnected()
6350     dev[0].request("PMKSA_FLUSH")
6351     dev[0].request("RECONNECT")
6352     dev[0].wait_connected()
6353 
6354 def test_ap_wpa2_eap_tls_13_ec(dev, apdev):
6355     """EAP-TLS and TLS 1.3 (EC certificates)"""
6356     params = {"ssid": "test-wpa2-eap",
6357               "wpa": "2",
6358               "wpa_key_mgmt": "WPA-EAP",
6359               "rsn_pairwise": "CCMP",
6360               "ieee8021x": "1",
6361               "eap_server": "1",
6362               "eap_user_file": "auth_serv/eap_user.conf",
6363               "ca_cert": "auth_serv/ec-ca.pem",
6364               "server_cert": "auth_serv/ec-server.pem",
6365               "private_key": "auth_serv/ec-server.key",
6366               "tls_flags": "[ENABLE-TLSv1.3]"}
6367     hapd = hostapd.add_ap(apdev[0], params)
6368     check_tls13_support(hapd)
6369 
6370     check_tls13_support(dev[0])
6371     id = eap_connect(dev[0], hapd, "TLS", "tls user",
6372                      ca_cert="auth_serv/ec-ca.pem",
6373                      client_cert="auth_serv/ec-user.pem",
6374                      private_key="auth_serv/ec-user.key",
6375                      phase1="tls_disable_tlsv1_0=1 tls_disable_tlsv1_1=1 tls_disable_tlsv1_2=1 tls_disable_tlsv1_3=0")
6376     ver = dev[0].get_status_field("eap_tls_version")
6377     if ver != "TLSv1.3":
6378         raise Exception("Unexpected TLS version")
6379 
6380 def test_ap_wpa2_eap_tls_rsa_and_ec(dev, apdev, params):
6381     """EAP-TLS and both RSA and EC sertificates certificates"""
6382     check_ec_support(dev[0])
6383     ca = os.path.join(params['logdir'], "ap_wpa2_eap_tls_rsa_and_ec.ca.pem")
6384     with open(ca, "w") as f:
6385         with open("auth_serv/ca.pem", "r") as f2:
6386             f.write(f2.read())
6387         with open("auth_serv/ec-ca.pem", "r") as f2:
6388             f.write(f2.read())
6389     params = {"ssid": "test-wpa2-eap",
6390               "wpa": "2",
6391               "wpa_key_mgmt": "WPA-EAP",
6392               "rsn_pairwise": "CCMP",
6393               "ieee8021x": "1",
6394               "eap_server": "1",
6395               "eap_user_file": "auth_serv/eap_user.conf",
6396               "ca_cert": ca,
6397               "server_cert": "auth_serv/server.pem",
6398               "private_key": "auth_serv/server.key",
6399               "server_cert2": "auth_serv/ec-server.pem",
6400               "private_key2": "auth_serv/ec-server.key"}
6401     hapd = hostapd.add_ap(apdev[0], params)
6402 
6403     eap_connect(dev[0], hapd, "TLS", "tls user",
6404                 ca_cert="auth_serv/ec-ca.pem",
6405                 client_cert="auth_serv/ec-user.pem",
6406                 private_key="auth_serv/ec-user.key")
6407     dev[0].request("REMOVE_NETWORK all")
6408     dev[0].wait_disconnected()
6409 
6410     tls = dev[1].request("GET tls_library")
6411     if tls.startswith("wolfSSL"):
6412         ciphers = "RSA"
6413     else:
6414         ciphers = "DEFAULT:-aECDH:-aECDSA"
6415     # TODO: Make wpa_supplicant automatically filter out cipher suites that
6416     # would require ECDH/ECDSA keys when those are not configured in the
6417     # selected client certificate. And for no-client-cert case, deprioritize
6418     # those cipher suites based on configured ca_cert value so that the most
6419     # likely to work cipher suites are selected by the server. Only do these
6420     # when an explicit openssl_ciphers parameter is not set.
6421     eap_connect(dev[1], hapd, "TLS", "tls user",
6422                 openssl_ciphers=ciphers,
6423                 ca_cert="auth_serv/ca.pem",
6424                 client_cert="auth_serv/user.pem",
6425                 private_key="auth_serv/user.key")
6426     dev[1].request("REMOVE_NETWORK all")
6427     dev[1].wait_disconnected()
6428 
6429 def test_ap_wpa2_eap_tls_ec_and_rsa(dev, apdev, params):
6430     """EAP-TLS and both EC and RSA sertificates certificates"""
6431     check_ec_support(dev[0])
6432     ca = os.path.join(params['logdir'], "ap_wpa2_eap_tls_ec_and_rsa.ca.pem")
6433     with open(ca, "w") as f:
6434         with open("auth_serv/ca.pem", "r") as f2:
6435             f.write(f2.read())
6436         with open("auth_serv/ec-ca.pem", "r") as f2:
6437             f.write(f2.read())
6438     params = {"ssid": "test-wpa2-eap",
6439               "wpa": "2",
6440               "wpa_key_mgmt": "WPA-EAP",
6441               "rsn_pairwise": "CCMP",
6442               "ieee8021x": "1",
6443               "eap_server": "1",
6444               "eap_user_file": "auth_serv/eap_user.conf",
6445               "ca_cert": ca,
6446               "private_key2": "auth_serv/server-extra.pkcs12",
6447               "private_key_passwd2": "whatever",
6448               "server_cert": "auth_serv/ec-server.pem",
6449               "private_key": "auth_serv/ec-server.key"}
6450     hapd = hostapd.add_ap(apdev[0], params)
6451 
6452     eap_connect(dev[0], hapd, "TLS", "tls user",
6453                 ca_cert="auth_serv/ec-ca.pem",
6454                 client_cert="auth_serv/ec-user.pem",
6455                 private_key="auth_serv/ec-user.key")
6456     dev[0].request("REMOVE_NETWORK all")
6457     dev[0].wait_disconnected()
6458 
6459     tls = dev[1].request("GET tls_library")
6460     if tls.startswith("wolfSSL"):
6461         ciphers = "RSA"
6462     else:
6463         ciphers = "DEFAULT:-aECDH:-aECDSA"
6464     # TODO: Make wpa_supplicant automatically filter out cipher suites that
6465     # would require ECDH/ECDSA keys when those are not configured in the
6466     # selected client certificate. And for no-client-cert case, deprioritize
6467     # those cipher suites based on configured ca_cert value so that the most
6468     # likely to work cipher suites are selected by the server. Only do these
6469     # when an explicit openssl_ciphers parameter is not set.
6470     eap_connect(dev[1], hapd, "TLS", "tls user",
6471                 openssl_ciphers=ciphers,
6472                 ca_cert="auth_serv/ca.pem",
6473                 client_cert="auth_serv/user.pem",
6474                 private_key="auth_serv/user.key")
6475     dev[1].request("REMOVE_NETWORK all")
6476     dev[1].wait_disconnected()
6477 
6478 def test_rsn_ie_proto_eap_sta(dev, apdev):
6479     """RSN element protocol testing for EAP cases on STA side"""
6480     bssid = apdev[0]['bssid']
6481     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
6482     # This is the RSN element used normally by hostapd
6483     params['own_ie_override'] = '30140100000fac040100000fac040100000fac010c00'
6484     hapd = hostapd.add_ap(apdev[0], params)
6485     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="GPSK",
6486                         identity="gpsk user",
6487                         password="abcdefghijklmnop0123456789abcdef",
6488                         scan_freq="2412")
6489 
6490     tests = [('No RSN Capabilities field',
6491               '30120100000fac040100000fac040100000fac01'),
6492              ('No AKM Suite fields',
6493               '300c0100000fac040100000fac04'),
6494              ('No Pairwise Cipher Suite fields',
6495               '30060100000fac04'),
6496              ('No Group Data Cipher Suite field',
6497               '30020100')]
6498     for txt, ie in tests:
6499         dev[0].request("DISCONNECT")
6500         dev[0].wait_disconnected()
6501         logger.info(txt)
6502         hapd.disable()
6503         hapd.set('own_ie_override', ie)
6504         hapd.enable()
6505         dev[0].request("BSS_FLUSH 0")
6506         dev[0].scan_for_bss(bssid, 2412, force_scan=True, only_new=True)
6507         dev[0].select_network(id, freq=2412)
6508         dev[0].wait_connected()
6509 
6510     dev[0].request("DISCONNECT")
6511     dev[0].wait_disconnected()
6512     dev[0].flush_scan_cache()
6513 
6514 def check_tls_session_resumption_capa(dev, hapd):
6515     tls = hapd.request("GET tls_library")
6516     if not tls.startswith("OpenSSL") and not tls.startswith("wolfSSL"):
6517         raise HwsimSkip("hostapd TLS library is not OpenSSL or wolfSSL: " + tls)
6518 
6519     tls = dev.request("GET tls_library")
6520     if not tls.startswith("OpenSSL") and not tls.startswith("wolfSSL"):
6521         raise HwsimSkip("Session resumption not supported with this TLS library: " + tls)
6522 
6523 def test_eap_ttls_pap_session_resumption(dev, apdev):
6524     """EAP-TTLS/PAP session resumption"""
6525     run_eap_ttls_pap_session_resumption(dev, apdev, False)
6526 
6527 def test_eap_ttls_pap_session_resumption_force_phase2(dev, apdev):
6528     """EAP-TTLS/PAP session resumption while forcing Phase 2 authentication"""
6529     run_eap_ttls_pap_session_resumption(dev, apdev, True)
6530 
6531 def run_eap_ttls_pap_session_resumption(dev, apdev, phase2_auth):
6532     params = int_eap_server_params()
6533     params['tls_session_lifetime'] = '60'
6534     hapd = hostapd.add_ap(apdev[0], params)
6535     check_tls_session_resumption_capa(dev[0], hapd)
6536     phase1 = "phase2_auth=2" if phase2_auth else ""
6537     eap_connect(dev[0], hapd, "TTLS", "pap user",
6538                 anonymous_identity="ttls", password="password",
6539                 ca_cert="auth_serv/ca.pem", eap_workaround='0',
6540                 phase1=phase1, phase2="auth=PAP")
6541     if dev[0].get_status_field("tls_session_reused") != '0':
6542         raise Exception("Unexpected session resumption on the first connection")
6543 
6544     dev[0].request("REAUTHENTICATE")
6545     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
6546     if ev is None:
6547         raise Exception("EAP success timed out")
6548     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
6549     if ev is None:
6550         raise Exception("Key handshake with the AP timed out")
6551     reused = dev[0].get_status_field("tls_session_reused") == '1'
6552     if phase2_auth and reused:
6553         raise Exception("Session resumption used on the second connection")
6554     if not phase2_auth and not reused:
6555         raise Exception("Session resumption not used on the second connection")
6556     hwsim_utils.test_connectivity(dev[0], hapd)
6557 
6558 def test_eap_ttls_chap_session_resumption(dev, apdev):
6559     """EAP-TTLS/CHAP session resumption"""
6560     params = int_eap_server_params()
6561     params['tls_session_lifetime'] = '60'
6562     hapd = hostapd.add_ap(apdev[0], params)
6563     check_tls_session_resumption_capa(dev[0], hapd)
6564     eap_connect(dev[0], hapd, "TTLS", "chap user",
6565                 anonymous_identity="ttls", password="password",
6566                 ca_cert="auth_serv/ca.der", phase2="auth=CHAP")
6567     if dev[0].get_status_field("tls_session_reused") != '0':
6568         raise Exception("Unexpected session resumption on the first connection")
6569 
6570     dev[0].request("REAUTHENTICATE")
6571     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
6572     if ev is None:
6573         raise Exception("EAP success timed out")
6574     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
6575     if ev is None:
6576         raise Exception("Key handshake with the AP timed out")
6577     if dev[0].get_status_field("tls_session_reused") != '1':
6578         raise Exception("Session resumption not used on the second connection")
6579 
6580 def test_eap_ttls_mschap_session_resumption(dev, apdev):
6581     """EAP-TTLS/MSCHAP session resumption"""
6582     check_domain_suffix_match(dev[0])
6583     params = int_eap_server_params()
6584     params['tls_session_lifetime'] = '60'
6585     hapd = hostapd.add_ap(apdev[0], params)
6586     check_tls_session_resumption_capa(dev[0], hapd)
6587     eap_connect(dev[0], hapd, "TTLS", "mschap user",
6588                 anonymous_identity="ttls", password="password",
6589                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAP",
6590                 domain_suffix_match="server.w1.fi")
6591     if dev[0].get_status_field("tls_session_reused") != '0':
6592         raise Exception("Unexpected session resumption on the first connection")
6593 
6594     dev[0].request("REAUTHENTICATE")
6595     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
6596     if ev is None:
6597         raise Exception("EAP success timed out")
6598     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
6599     if ev is None:
6600         raise Exception("Key handshake with the AP timed out")
6601     if dev[0].get_status_field("tls_session_reused") != '1':
6602         raise Exception("Session resumption not used on the second connection")
6603 
6604 def test_eap_ttls_mschapv2_session_resumption(dev, apdev):
6605     """EAP-TTLS/MSCHAPv2 session resumption"""
6606     check_domain_suffix_match(dev[0])
6607     check_eap_capa(dev[0], "MSCHAPV2")
6608     params = int_eap_server_params()
6609     params['tls_session_lifetime'] = '60'
6610     hapd = hostapd.add_ap(apdev[0], params)
6611     check_tls_session_resumption_capa(dev[0], hapd)
6612     eap_connect(dev[0], hapd, "TTLS", "DOMAIN\\mschapv2 user",
6613                 anonymous_identity="ttls", password="password",
6614                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
6615                 domain_suffix_match="server.w1.fi")
6616     if dev[0].get_status_field("tls_session_reused") != '0':
6617         raise Exception("Unexpected session resumption on the first connection")
6618 
6619     dev[0].request("REAUTHENTICATE")
6620     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
6621     if ev is None:
6622         raise Exception("EAP success timed out")
6623     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
6624     if ev is None:
6625         raise Exception("Key handshake with the AP timed out")
6626     if dev[0].get_status_field("tls_session_reused") != '1':
6627         raise Exception("Session resumption not used on the second connection")
6628 
6629 def test_eap_ttls_eap_gtc_session_resumption(dev, apdev):
6630     """EAP-TTLS/EAP-GTC session resumption"""
6631     params = int_eap_server_params()
6632     params['tls_session_lifetime'] = '60'
6633     hapd = hostapd.add_ap(apdev[0], params)
6634     check_tls_session_resumption_capa(dev[0], hapd)
6635     eap_connect(dev[0], hapd, "TTLS", "user",
6636                 anonymous_identity="ttls", password="password",
6637                 ca_cert="auth_serv/ca.pem", phase2="autheap=GTC")
6638     if dev[0].get_status_field("tls_session_reused") != '0':
6639         raise Exception("Unexpected session resumption on the first connection")
6640 
6641     dev[0].request("REAUTHENTICATE")
6642     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
6643     if ev is None:
6644         raise Exception("EAP success timed out")
6645     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
6646     if ev is None:
6647         raise Exception("Key handshake with the AP timed out")
6648     if dev[0].get_status_field("tls_session_reused") != '1':
6649         raise Exception("Session resumption not used on the second connection")
6650 
6651 def test_eap_ttls_no_session_resumption(dev, apdev):
6652     """EAP-TTLS session resumption disabled on server"""
6653     params = int_eap_server_params()
6654     params['tls_session_lifetime'] = '0'
6655     hapd = hostapd.add_ap(apdev[0], params)
6656     eap_connect(dev[0], hapd, "TTLS", "pap user",
6657                 anonymous_identity="ttls", password="password",
6658                 ca_cert="auth_serv/ca.pem", eap_workaround='0',
6659                 phase2="auth=PAP")
6660     if dev[0].get_status_field("tls_session_reused") != '0':
6661         raise Exception("Unexpected session resumption on the first connection")
6662 
6663     dev[0].request("REAUTHENTICATE")
6664     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
6665     if ev is None:
6666         raise Exception("EAP success timed out")
6667     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
6668     if ev is None:
6669         raise Exception("Key handshake with the AP timed out")
6670     if dev[0].get_status_field("tls_session_reused") != '0':
6671         raise Exception("Unexpected session resumption on the second connection")
6672 
6673 def test_eap_peap_session_resumption(dev, apdev):
6674     """EAP-PEAP session resumption"""
6675     run_eap_peap_session_resumption(dev, apdev, False)
6676 
6677 def test_eap_peap_session_resumption_force_phase2(dev, apdev):
6678     """EAP-PEAP session resumption while forcing Phase 2 authentication"""
6679     run_eap_peap_session_resumption(dev, apdev, True)
6680 
6681 def run_eap_peap_session_resumption(dev, apdev, phase2_auth):
6682     check_eap_capa(dev[0], "MSCHAPV2")
6683     params = int_eap_server_params()
6684     params['tls_session_lifetime'] = '60'
6685     hapd = hostapd.add_ap(apdev[0], params)
6686     check_tls_session_resumption_capa(dev[0], hapd)
6687     phase1 = "phase2_auth=2" if phase2_auth else ""
6688     eap_connect(dev[0], hapd, "PEAP", "user",
6689                 anonymous_identity="peap", password="password",
6690                 ca_cert="auth_serv/ca.pem", phase1=phase1,
6691                 phase2="auth=MSCHAPV2")
6692     if dev[0].get_status_field("tls_session_reused") != '0':
6693         raise Exception("Unexpected session resumption on the first connection")
6694 
6695     dev[0].request("REAUTHENTICATE")
6696     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
6697     if ev is None:
6698         raise Exception("EAP success timed out")
6699     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
6700     if ev is None:
6701         raise Exception("Key handshake with the AP timed out")
6702     reused = dev[0].get_status_field("tls_session_reused") == '1'
6703     if phase2_auth and reused:
6704         raise Exception("Session resumption used on the second connection")
6705     if not phase2_auth and not reused:
6706         raise Exception("Session resumption not used on the second connection")
6707 
6708 def test_eap_peap_session_resumption_crypto_binding(dev, apdev):
6709     """EAP-PEAP session resumption with crypto binding"""
6710     params = int_eap_server_params()
6711     params['tls_session_lifetime'] = '60'
6712     hapd = hostapd.add_ap(apdev[0], params)
6713     check_tls_session_resumption_capa(dev[0], hapd)
6714     eap_connect(dev[0], hapd, "PEAP", "user",
6715                 anonymous_identity="peap", password="password",
6716                 phase1="peapver=0 crypto_binding=2",
6717                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
6718     if dev[0].get_status_field("tls_session_reused") != '0':
6719         raise Exception("Unexpected session resumption on the first connection")
6720 
6721     dev[0].request("REAUTHENTICATE")
6722     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
6723     if ev is None:
6724         raise Exception("EAP success timed out")
6725     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
6726     if ev is None:
6727         raise Exception("Key handshake with the AP timed out")
6728     if dev[0].get_status_field("tls_session_reused") != '1':
6729         raise Exception("Session resumption not used on the second connection")
6730 
6731 def test_eap_peap_no_session_resumption(dev, apdev):
6732     """EAP-PEAP session resumption disabled on server"""
6733     params = int_eap_server_params()
6734     hapd = hostapd.add_ap(apdev[0], params)
6735     eap_connect(dev[0], hapd, "PEAP", "user",
6736                 anonymous_identity="peap", password="password",
6737                 ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2")
6738     if dev[0].get_status_field("tls_session_reused") != '0':
6739         raise Exception("Unexpected session resumption on the first connection")
6740 
6741     dev[0].request("REAUTHENTICATE")
6742     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
6743     if ev is None:
6744         raise Exception("EAP success timed out")
6745     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
6746     if ev is None:
6747         raise Exception("Key handshake with the AP timed out")
6748     if dev[0].get_status_field("tls_session_reused") != '0':
6749         raise Exception("Unexpected session resumption on the second connection")
6750 
6751 def test_eap_tls_session_resumption(dev, apdev):
6752     """EAP-TLS session resumption"""
6753     params = int_eap_server_params()
6754     params['tls_session_lifetime'] = '60'
6755     hapd = hostapd.add_ap(apdev[0], params)
6756     check_tls_session_resumption_capa(dev[0], hapd)
6757     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
6758                 client_cert="auth_serv/user.pem",
6759                 private_key="auth_serv/user.key")
6760     if dev[0].get_status_field("tls_session_reused") != '0':
6761         raise Exception("Unexpected session resumption on the first connection")
6762     hapd.dump_monitor()
6763 
6764     dev[0].request("REAUTHENTICATE")
6765     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
6766     if ev is None:
6767         raise Exception("EAP success timed out")
6768     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
6769     if ev is None:
6770         raise Exception("Key handshake with the AP timed out")
6771     if dev[0].get_status_field("tls_session_reused") != '1':
6772         raise Exception("Session resumption not used on the second connection")
6773     ev = hapd.wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=1)
6774     if ev is None:
6775         raise Exception("EAP success timed out (AP)")
6776     hapd.wait_4way_hs()
6777     hapd.dump_monitor()
6778 
6779     dev[0].request("REAUTHENTICATE")
6780     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
6781     if ev is None:
6782         raise Exception("EAP success timed out")
6783     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
6784     if ev is None:
6785         raise Exception("Key handshake with the AP timed out")
6786     if dev[0].get_status_field("tls_session_reused") != '1':
6787         raise Exception("Session resumption not used on the third connection")
6788     ev = hapd.wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=1)
6789     if ev is None:
6790         raise Exception("EAP success timed out (AP)")
6791     hapd.wait_4way_hs()
6792     hapd.dump_monitor()
6793 
6794 def test_eap_tls_session_resumption_expiration(dev, apdev):
6795     """EAP-TLS session resumption"""
6796     params = int_eap_server_params()
6797     params['tls_session_lifetime'] = '1'
6798     hapd = hostapd.add_ap(apdev[0], params)
6799     check_tls_session_resumption_capa(dev[0], hapd)
6800     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
6801                 client_cert="auth_serv/user.pem",
6802                 private_key="auth_serv/user.key")
6803     if dev[0].get_status_field("tls_session_reused") != '0':
6804         raise Exception("Unexpected session resumption on the first connection")
6805 
6806     # Allow multiple attempts since OpenSSL may not expire the cached entry
6807     # immediately.
6808     for i in range(10):
6809         time.sleep(1.2)
6810 
6811         dev[0].request("REAUTHENTICATE")
6812         ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
6813         if ev is None:
6814             raise Exception("EAP success timed out")
6815         ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
6816         if ev is None:
6817             raise Exception("Key handshake with the AP timed out")
6818         if dev[0].get_status_field("tls_session_reused") == '0':
6819             break
6820     if dev[0].get_status_field("tls_session_reused") != '0':
6821         raise Exception("Session resumption used after lifetime expiration")
6822 
6823 def test_eap_tls_no_session_resumption(dev, apdev):
6824     """EAP-TLS session resumption disabled on server"""
6825     params = int_eap_server_params()
6826     hapd = hostapd.add_ap(apdev[0], params)
6827     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
6828                 client_cert="auth_serv/user.pem",
6829                 private_key="auth_serv/user.key")
6830     if dev[0].get_status_field("tls_session_reused") != '0':
6831         raise Exception("Unexpected session resumption on the first connection")
6832 
6833     dev[0].request("REAUTHENTICATE")
6834     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
6835     if ev is None:
6836         raise Exception("EAP success timed out")
6837     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
6838     if ev is None:
6839         raise Exception("Key handshake with the AP timed out")
6840     if dev[0].get_status_field("tls_session_reused") != '0':
6841         raise Exception("Unexpected session resumption on the second connection")
6842 
6843 def test_eap_tls_session_resumption_radius(dev, apdev):
6844     """EAP-TLS session resumption (RADIUS)"""
6845     params = {"ssid": "as", "beacon_int": "2000",
6846               "radius_server_clients": "auth_serv/radius_clients.conf",
6847               "radius_server_auth_port": '18128',
6848               "eap_server": "1",
6849               "eap_user_file": "auth_serv/eap_user.conf",
6850               "ca_cert": "auth_serv/ca.pem",
6851               "server_cert": "auth_serv/server.pem",
6852               "private_key": "auth_serv/server.key",
6853               "tls_session_lifetime": "60"}
6854     authsrv = hostapd.add_ap(apdev[1], params)
6855     check_tls_session_resumption_capa(dev[0], authsrv)
6856 
6857     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
6858     params['auth_server_port'] = "18128"
6859     hapd = hostapd.add_ap(apdev[0], params)
6860     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
6861                 client_cert="auth_serv/user.pem",
6862                 private_key="auth_serv/user.key")
6863     if dev[0].get_status_field("tls_session_reused") != '0':
6864         raise Exception("Unexpected session resumption on the first connection")
6865 
6866     dev[0].request("REAUTHENTICATE")
6867     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
6868     if ev is None:
6869         raise Exception("EAP success timed out")
6870     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
6871     if ev is None:
6872         raise Exception("Key handshake with the AP timed out")
6873     if dev[0].get_status_field("tls_session_reused") != '1':
6874         raise Exception("Session resumption not used on the second connection")
6875 
6876 def test_eap_tls_no_session_resumption_radius(dev, apdev):
6877     """EAP-TLS session resumption disabled (RADIUS)"""
6878     params = {"ssid": "as", "beacon_int": "2000",
6879               "radius_server_clients": "auth_serv/radius_clients.conf",
6880               "radius_server_auth_port": '18128',
6881               "eap_server": "1",
6882               "eap_user_file": "auth_serv/eap_user.conf",
6883               "ca_cert": "auth_serv/ca.pem",
6884               "server_cert": "auth_serv/server.pem",
6885               "private_key": "auth_serv/server.key",
6886               "tls_session_lifetime": "0"}
6887     hostapd.add_ap(apdev[1], params)
6888 
6889     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
6890     params['auth_server_port'] = "18128"
6891     hapd = hostapd.add_ap(apdev[0], params)
6892     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
6893                 client_cert="auth_serv/user.pem",
6894                 private_key="auth_serv/user.key")
6895     if dev[0].get_status_field("tls_session_reused") != '0':
6896         raise Exception("Unexpected session resumption on the first connection")
6897 
6898     dev[0].request("REAUTHENTICATE")
6899     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10)
6900     if ev is None:
6901         raise Exception("EAP success timed out")
6902     ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=10)
6903     if ev is None:
6904         raise Exception("Key handshake with the AP timed out")
6905     if dev[0].get_status_field("tls_session_reused") != '0':
6906         raise Exception("Unexpected session resumption on the second connection")
6907 
6908 def test_eap_mschapv2_errors(dev, apdev):
6909     """EAP-MSCHAPv2 error cases"""
6910     check_eap_capa(dev[0], "MSCHAPV2")
6911     check_eap_capa(dev[0], "FAST")
6912 
6913     params = hostapd.wpa2_eap_params(ssid="test-wpa-eap")
6914     hapd = hostapd.add_ap(apdev[0], params)
6915     dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="MSCHAPV2",
6916                    identity="phase1-user", password="password",
6917                    scan_freq="2412")
6918     dev[0].request("REMOVE_NETWORK all")
6919     dev[0].wait_disconnected()
6920 
6921     tests = [(1, "hash_nt_password_hash;mschapv2_derive_response"),
6922              (1, "nt_password_hash;mschapv2_derive_response"),
6923              (1, "nt_password_hash;=mschapv2_derive_response"),
6924              (1, "generate_nt_response;mschapv2_derive_response"),
6925              (1, "generate_authenticator_response;mschapv2_derive_response"),
6926              (1, "nt_password_hash;=mschapv2_derive_response"),
6927              (1, "get_master_key;mschapv2_derive_response"),
6928              (1, "os_get_random;eap_mschapv2_challenge_reply")]
6929     for count, func in tests:
6930         with fail_test(dev[0], count, func):
6931             dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="MSCHAPV2",
6932                            identity="phase1-user", password="password",
6933                            wait_connect=False, scan_freq="2412")
6934             wait_fail_trigger(dev[0], "GET_FAIL")
6935             dev[0].request("REMOVE_NETWORK all")
6936             dev[0].wait_disconnected()
6937 
6938     tests = [(1, "hash_nt_password_hash;mschapv2_derive_response"),
6939              (1, "hash_nt_password_hash;=mschapv2_derive_response"),
6940              (1, "generate_nt_response_pwhash;mschapv2_derive_response"),
6941              (1, "generate_authenticator_response_pwhash;mschapv2_derive_response")]
6942     for count, func in tests:
6943         with fail_test(dev[0], count, func):
6944             dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="MSCHAPV2",
6945                            identity="phase1-user",
6946                            password_hex="hash:8846f7eaee8fb117ad06bdd830b7586c",
6947                            wait_connect=False, scan_freq="2412")
6948             wait_fail_trigger(dev[0], "GET_FAIL")
6949             dev[0].request("REMOVE_NETWORK all")
6950             dev[0].wait_disconnected()
6951 
6952     tests = [(1, "eap_mschapv2_init"),
6953              (1, "eap_msg_alloc;eap_mschapv2_challenge_reply"),
6954              (1, "eap_msg_alloc;eap_mschapv2_success"),
6955              (1, "eap_mschapv2_getKey")]
6956     for count, func in tests:
6957         with alloc_fail(dev[0], count, func):
6958             dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="MSCHAPV2",
6959                            identity="phase1-user", password="password",
6960                            wait_connect=False, scan_freq="2412")
6961             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
6962             dev[0].request("REMOVE_NETWORK all")
6963             dev[0].wait_disconnected()
6964 
6965     tests = [(1, "eap_msg_alloc;eap_mschapv2_failure")]
6966     for count, func in tests:
6967         with alloc_fail(dev[0], count, func):
6968             dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="MSCHAPV2",
6969                            identity="phase1-user", password="wrong password",
6970                            wait_connect=False, scan_freq="2412")
6971             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
6972             dev[0].request("REMOVE_NETWORK all")
6973             dev[0].wait_disconnected()
6974 
6975     tests = [(2, "eap_mschapv2_init"),
6976              (3, "eap_mschapv2_init")]
6977     for count, func in tests:
6978         with alloc_fail(dev[0], count, func):
6979             dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="FAST",
6980                            anonymous_identity="FAST", identity="user",
6981                            password="password",
6982                            ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
6983                            phase1="fast_provisioning=1",
6984                            pac_file="blob://fast_pac",
6985                            wait_connect=False, scan_freq="2412")
6986             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
6987             dev[0].request("REMOVE_NETWORK all")
6988             dev[0].wait_disconnected()
6989 
6990 def test_eap_gpsk_errors(dev, apdev):
6991     """EAP-GPSK error cases"""
6992     params = hostapd.wpa2_eap_params(ssid="test-wpa-eap")
6993     hapd = hostapd.add_ap(apdev[0], params)
6994     dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="GPSK",
6995                    identity="gpsk user",
6996                    password="abcdefghijklmnop0123456789abcdef",
6997                    scan_freq="2412")
6998     dev[0].request("REMOVE_NETWORK all")
6999     dev[0].wait_disconnected()
7000 
7001     tests = [(1, "os_get_random;eap_gpsk_send_gpsk_2", None),
7002              (1, "eap_gpsk_derive_session_id;eap_gpsk_send_gpsk_2",
7003               "cipher=1"),
7004              (1, "eap_gpsk_derive_session_id;eap_gpsk_send_gpsk_2",
7005               "cipher=2"),
7006              (1, "eap_gpsk_derive_keys_helper", None),
7007              (2, "eap_gpsk_derive_keys_helper", None),
7008              (3, "eap_gpsk_derive_keys_helper", None),
7009              (1, "eap_gpsk_compute_mic_aes;eap_gpsk_compute_mic;eap_gpsk_send_gpsk_2",
7010               "cipher=1"),
7011              (1, "hmac_sha256;eap_gpsk_compute_mic;eap_gpsk_send_gpsk_2",
7012               "cipher=2"),
7013              (1, "eap_gpsk_compute_mic;eap_gpsk_validate_gpsk_3_mic", None),
7014              (1, "eap_gpsk_compute_mic;eap_gpsk_send_gpsk_4", None),
7015              (1, "eap_gpsk_derive_mid_helper", None)]
7016     for count, func, phase1 in tests:
7017         with fail_test(dev[0], count, func):
7018             dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="GPSK",
7019                            identity="gpsk user",
7020                            password="abcdefghijklmnop0123456789abcdef",
7021                            phase1=phase1,
7022                            wait_connect=False, scan_freq="2412")
7023             wait_fail_trigger(dev[0], "GET_FAIL")
7024             dev[0].request("REMOVE_NETWORK all")
7025             dev[0].wait_disconnected()
7026 
7027     tests = [(1, "eap_gpsk_init"),
7028              (2, "eap_gpsk_init"),
7029              (3, "eap_gpsk_init"),
7030              (1, "eap_gpsk_process_id_server"),
7031              (1, "eap_msg_alloc;eap_gpsk_send_gpsk_2"),
7032              (1, "eap_gpsk_derive_session_id;eap_gpsk_send_gpsk_2"),
7033              (1, "eap_gpsk_derive_mid_helper;eap_gpsk_derive_session_id;eap_gpsk_send_gpsk_2"),
7034              (1, "eap_gpsk_derive_keys"),
7035              (1, "eap_gpsk_derive_keys_helper"),
7036              (1, "eap_msg_alloc;eap_gpsk_send_gpsk_4"),
7037              (1, "eap_gpsk_getKey"),
7038              (1, "eap_gpsk_get_emsk"),
7039              (1, "eap_gpsk_get_session_id")]
7040     for count, func in tests:
7041         with alloc_fail(dev[0], count, func):
7042             dev[0].request("ERP_FLUSH")
7043             dev[0].connect("test-wpa-eap", key_mgmt="WPA-EAP", eap="GPSK",
7044                            identity="gpsk user@domain", erp="1",
7045                            password="abcdefghijklmnop0123456789abcdef",
7046                            wait_connect=False, scan_freq="2412")
7047             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
7048             dev[0].request("REMOVE_NETWORK all")
7049             dev[0].wait_disconnected()
7050 
7051 def test_ap_wpa2_eap_sim_db(dev, apdev, params):
7052     """EAP-SIM DB error cases"""
7053     sockpath = '/tmp/hlr_auc_gw.sock-test'
7054     try:
7055         os.remove(sockpath)
7056     except:
7057         pass
7058     hparams = int_eap_server_params()
7059     hparams['eap_sim_db'] = 'unix:' + sockpath
7060     hapd = hostapd.add_ap(apdev[0], hparams)
7061 
7062     # Initial test with hlr_auc_gw socket not available
7063     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
7064                         eap="SIM", identity="1232010000000000",
7065                         password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
7066                         scan_freq="2412", wait_connect=False)
7067     ev = dev[0].wait_event(["EAP-ERROR-CODE"], timeout=10)
7068     if ev is None:
7069         raise Exception("EAP method specific error code not reported")
7070     if int(ev.split()[1]) != 16384:
7071         raise Exception("Unexpected EAP method specific error code: " + ev)
7072     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
7073     if ev is None:
7074         raise Exception("EAP-Failure not reported")
7075     dev[0].wait_disconnected()
7076     dev[0].request("DISCONNECT")
7077 
7078     # Test with invalid responses and response timeout
7079 
7080     class test_handler(SocketServer.DatagramRequestHandler):
7081         def handle(self):
7082             data = self.request[0].decode().strip()
7083             socket = self.request[1]
7084             logger.debug("Received hlr_auc_gw request: " + data)
7085             # EAP-SIM DB: Failed to parse response string
7086             socket.sendto(b"FOO", self.client_address)
7087             # EAP-SIM DB: Failed to parse response string
7088             socket.sendto(b"FOO 1", self.client_address)
7089             # EAP-SIM DB: Unknown external response
7090             socket.sendto(b"FOO 1 2", self.client_address)
7091             logger.info("No proper response - wait for pending eap_sim_db request timeout")
7092 
7093     server = SocketServer.UnixDatagramServer(sockpath, test_handler)
7094     server.timeout = 1
7095 
7096     dev[0].select_network(id)
7097     server.handle_request()
7098     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
7099     if ev is None:
7100         raise Exception("EAP-Failure not reported")
7101     dev[0].wait_disconnected()
7102     dev[0].request("DISCONNECT")
7103 
7104     # Test with a valid response
7105 
7106     class test_handler2(SocketServer.DatagramRequestHandler):
7107         def handle(self):
7108             data = self.request[0].decode().strip()
7109             socket = self.request[1]
7110             logger.debug("Received hlr_auc_gw request: " + data)
7111             fname = os.path.join(params['logdir'],
7112                                  'hlr_auc_gw.milenage_db')
7113             cmd = subprocess.Popen(['../../hostapd/hlr_auc_gw',
7114                                     '-m', fname, data],
7115                                    stdout=subprocess.PIPE)
7116             out, err = cmd.communicate()
7117             res = out.decode().strip()
7118             logger.debug("hlr_auc_gw response: " + res)
7119             socket.sendto(res.encode(), self.client_address)
7120 
7121     server.RequestHandlerClass = test_handler2
7122 
7123     dev[0].select_network(id)
7124     server.handle_request()
7125     dev[0].wait_connected()
7126     dev[0].request("DISCONNECT")
7127     dev[0].wait_disconnected()
7128 
7129 def test_ap_wpa2_eap_sim_db_sqlite(dev, apdev, params):
7130     """EAP-SIM DB error cases (SQLite)"""
7131     sockpath = '/tmp/hlr_auc_gw.sock-test'
7132     try:
7133         os.remove(sockpath)
7134     except:
7135         pass
7136     hparams = int_eap_server_params()
7137     hparams['eap_sim_db'] = 'unix:' + sockpath
7138     hapd = hostapd.add_ap(apdev[0], hparams)
7139 
7140     fname = params['prefix'] + ".milenage_db.sqlite"
7141     cmd = subprocess.Popen(['../../hostapd/hlr_auc_gw',
7142                             '-D', fname, "FOO"],
7143                            stdout=subprocess.PIPE)
7144     out, err = cmd.communicate()
7145     res = out.decode().strip()
7146     logger.debug("hlr_auc_gw response: " + res)
7147 
7148     try:
7149         import sqlite3
7150     except ImportError:
7151         raise HwsimSkip("No sqlite3 module available")
7152     con = sqlite3.connect(fname)
7153     with con:
7154         cur = con.cursor()
7155         try:
7156             cur.execute("INSERT INTO milenage(imsi,ki,opc,amf,sqn) VALUES ('232010000000000', '90dca4eda45b53cf0f12d7c9c3bc6a89', 'cb9cccc4b9258e6dca4760379fb82581', '61df', '000000000000')")
7157         except sqlite3.IntegrityError as e:
7158             pass
7159 
7160     class test_handler3(SocketServer.DatagramRequestHandler):
7161         def handle(self):
7162             data = self.request[0].decode().strip()
7163             socket = self.request[1]
7164             logger.debug("Received hlr_auc_gw request: " + data)
7165             cmd = subprocess.Popen(['../../hostapd/hlr_auc_gw',
7166                                     '-D', fname, data],
7167                                    stdout=subprocess.PIPE)
7168             out, err = cmd.communicate()
7169             res = out.decode().strip()
7170             logger.debug("hlr_auc_gw response: " + res)
7171             socket.sendto(res.encode(), self.client_address)
7172 
7173     server = SocketServer.UnixDatagramServer(sockpath, test_handler3)
7174     server.timeout = 1
7175 
7176     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
7177                         eap="SIM", identity="1232010000000000",
7178                         password="90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581",
7179                         scan_freq="2412", wait_connect=False)
7180     server.handle_request()
7181     dev[0].wait_connected()
7182     dev[0].request("DISCONNECT")
7183     dev[0].wait_disconnected()
7184 
7185 def test_eap_tls_sha512(dev, apdev, params):
7186     """EAP-TLS with SHA512 signature"""
7187     params = int_eap_server_params()
7188     params["ca_cert"] = "auth_serv/sha512-ca.pem"
7189     params["server_cert"] = "auth_serv/sha512-server.pem"
7190     params["private_key"] = "auth_serv/sha512-server.key"
7191     hostapd.add_ap(apdev[0], params)
7192 
7193     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
7194                    identity="tls user sha512",
7195                    ca_cert="auth_serv/sha512-ca.pem",
7196                    client_cert="auth_serv/sha512-user.pem",
7197                    private_key="auth_serv/sha512-user.key",
7198                    scan_freq="2412")
7199     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
7200                    identity="tls user sha512",
7201                    ca_cert="auth_serv/sha512-ca.pem",
7202                    client_cert="auth_serv/sha384-user.pem",
7203                    private_key="auth_serv/sha384-user.key",
7204                    scan_freq="2412")
7205 
7206 def test_eap_tls_sha384(dev, apdev, params):
7207     """EAP-TLS with SHA384 signature"""
7208     params = int_eap_server_params()
7209     params["ca_cert"] = "auth_serv/sha512-ca.pem"
7210     params["server_cert"] = "auth_serv/sha384-server.pem"
7211     params["private_key"] = "auth_serv/sha384-server.key"
7212     hostapd.add_ap(apdev[0], params)
7213 
7214     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
7215                    identity="tls user sha512",
7216                    ca_cert="auth_serv/sha512-ca.pem",
7217                    client_cert="auth_serv/sha512-user.pem",
7218                    private_key="auth_serv/sha512-user.key",
7219                    scan_freq="2412")
7220     dev[1].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
7221                    identity="tls user sha512",
7222                    ca_cert="auth_serv/sha512-ca.pem",
7223                    client_cert="auth_serv/sha384-user.pem",
7224                    private_key="auth_serv/sha384-user.key",
7225                    scan_freq="2412")
7226 
7227 def test_ap_wpa2_eap_assoc_rsn(dev, apdev):
7228     """WPA2-Enterprise AP and association request RSN IE differences"""
7229     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
7230     hostapd.add_ap(apdev[0], params)
7231 
7232     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap-11w")
7233     params["ieee80211w"] = "2"
7234     hostapd.add_ap(apdev[1], params)
7235 
7236     # Success cases with optional RSN IE fields removed one by one
7237     tests = [("Normal wpa_supplicant assoc req RSN IE",
7238               "30140100000fac040100000fac040100000fac010000"),
7239              ("Extra PMKIDCount field in RSN IE",
7240               "30160100000fac040100000fac040100000fac0100000000"),
7241              ("Extra Group Management Cipher Suite in RSN IE",
7242               "301a0100000fac040100000fac040100000fac0100000000000fac06"),
7243              ("Extra undefined extension field in RSN IE",
7244               "301c0100000fac040100000fac040100000fac0100000000000fac061122"),
7245              ("RSN IE without RSN Capabilities",
7246               "30120100000fac040100000fac040100000fac01"),
7247              ("RSN IE without AKM", "300c0100000fac040100000fac04"),
7248              ("RSN IE without pairwise", "30060100000fac04"),
7249              ("RSN IE without group", "30020100")]
7250     for title, ie in tests:
7251         logger.info(title)
7252         set_test_assoc_ie(dev[0], ie)
7253         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="GPSK",
7254                        identity="gpsk user",
7255                        password="abcdefghijklmnop0123456789abcdef",
7256                        scan_freq="2412")
7257         dev[0].request("REMOVE_NETWORK all")
7258         dev[0].wait_disconnected()
7259 
7260     tests = [("Normal wpa_supplicant assoc req RSN IE",
7261               "30140100000fac040100000fac040100000fac01cc00"),
7262              ("Group management cipher included in assoc req RSN IE",
7263               "301a0100000fac040100000fac040100000fac01cc000000000fac06")]
7264     for title, ie in tests:
7265         logger.info(title)
7266         set_test_assoc_ie(dev[0], ie)
7267         dev[0].connect("test-wpa2-eap-11w", key_mgmt="WPA-EAP", ieee80211w="1",
7268                        eap="GPSK", identity="gpsk user",
7269                        password="abcdefghijklmnop0123456789abcdef",
7270                        scan_freq="2412")
7271         dev[0].request("REMOVE_NETWORK all")
7272         dev[0].wait_disconnected()
7273 
7274     tests = [("Invalid group cipher", "30060100000fac02", [40, 41]),
7275              ("Invalid pairwise cipher", "300c0100000fac040100000fac02", 42)]
7276     for title, ie, status in tests:
7277         logger.info(title)
7278         set_test_assoc_ie(dev[0], ie)
7279         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="GPSK",
7280                        identity="gpsk user",
7281                        password="abcdefghijklmnop0123456789abcdef",
7282                        scan_freq="2412", wait_connect=False)
7283         ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"])
7284         if ev is None:
7285             raise Exception("Association rejection not reported")
7286         ok = False
7287         if isinstance(status, list):
7288             for i in status:
7289                 ok = "status_code=" + str(i) in ev
7290                 if ok:
7291                     break
7292         else:
7293             ok = "status_code=" + str(status) in ev
7294         if not ok:
7295             raise Exception("Unexpected status code: " + ev)
7296         dev[0].request("REMOVE_NETWORK all")
7297         dev[0].dump_monitor()
7298 
7299     tests = [("Management frame protection not enabled",
7300               "30140100000fac040100000fac040100000fac010000", 31),
7301              ("Unsupported management group cipher",
7302               "301a0100000fac040100000fac040100000fac01cc000000000fac0b", 46)]
7303     for title, ie, status in tests:
7304         logger.info(title)
7305         set_test_assoc_ie(dev[0], ie)
7306         dev[0].connect("test-wpa2-eap-11w", key_mgmt="WPA-EAP", ieee80211w="1",
7307                        eap="GPSK", identity="gpsk user",
7308                        password="abcdefghijklmnop0123456789abcdef",
7309                        scan_freq="2412", wait_connect=False)
7310         ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"])
7311         if ev is None:
7312             raise Exception("Association rejection not reported")
7313         if "status_code=" + str(status) not in ev:
7314             raise Exception("Unexpected status code: " + ev)
7315         dev[0].request("REMOVE_NETWORK all")
7316         dev[0].dump_monitor()
7317 
7318 def test_eap_tls_ext_cert_check(dev, apdev):
7319     """EAP-TLS and external server certification validation"""
7320     # With internal server certificate chain validation
7321     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
7322                         identity="tls user",
7323                         ca_cert="auth_serv/ca.pem",
7324                         client_cert="auth_serv/user.pem",
7325                         private_key="auth_serv/user.key",
7326                         phase1="tls_ext_cert_check=1", scan_freq="2412",
7327                         only_add_network=True)
7328     run_ext_cert_check(dev, apdev, id)
7329 
7330 def test_eap_ttls_ext_cert_check(dev, apdev):
7331     """EAP-TTLS and external server certification validation"""
7332     # Without internal server certificate chain validation
7333     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
7334                         identity="pap user", anonymous_identity="ttls",
7335                         password="password", phase2="auth=PAP",
7336                         phase1="tls_ext_cert_check=1", scan_freq="2412",
7337                         only_add_network=True)
7338     run_ext_cert_check(dev, apdev, id)
7339 
7340 def test_eap_peap_ext_cert_check(dev, apdev):
7341     """EAP-PEAP and external server certification validation"""
7342     # With internal server certificate chain validation
7343     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PEAP",
7344                         identity="user", anonymous_identity="peap",
7345                         ca_cert="auth_serv/ca.pem",
7346                         password="password", phase2="auth=MSCHAPV2",
7347                         phase1="tls_ext_cert_check=1", scan_freq="2412",
7348                         only_add_network=True)
7349     run_ext_cert_check(dev, apdev, id)
7350 
7351 def test_eap_fast_ext_cert_check(dev, apdev):
7352     """EAP-FAST and external server certification validation"""
7353     check_eap_capa(dev[0], "FAST")
7354     # With internal server certificate chain validation
7355     dev[0].request("SET blob fast_pac_auth_ext ")
7356     id = dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="FAST",
7357                         identity="user", anonymous_identity="FAST",
7358                         ca_cert="auth_serv/ca.pem",
7359                         password="password", phase2="auth=GTC",
7360                         phase1="tls_ext_cert_check=1 fast_provisioning=2",
7361                         pac_file="blob://fast_pac_auth_ext",
7362                         scan_freq="2412",
7363                         only_add_network=True)
7364     run_ext_cert_check(dev, apdev, id)
7365 
7366 def run_ext_cert_check(dev, apdev, net_id):
7367     check_ext_cert_check_support(dev[0])
7368     if not openssl_imported:
7369         raise HwsimSkip("OpenSSL python method not available")
7370 
7371     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
7372     hapd = hostapd.add_ap(apdev[0], params)
7373 
7374     dev[0].select_network(net_id)
7375     certs = {}
7376     while True:
7377         ev = dev[0].wait_event(["CTRL-EVENT-EAP-PEER-CERT",
7378                                 "CTRL-REQ-EXT_CERT_CHECK",
7379                                 "CTRL-EVENT-EAP-SUCCESS"], timeout=10)
7380         if ev is None:
7381             raise Exception("No peer server certificate event seen")
7382         if "CTRL-EVENT-EAP-PEER-CERT" in ev:
7383             depth = None
7384             cert = None
7385             vals = ev.split(' ')
7386             for v in vals:
7387                 if v.startswith("depth="):
7388                     depth = int(v.split('=')[1])
7389                 elif v.startswith("cert="):
7390                     cert = v.split('=')[1]
7391             if depth is not None and cert:
7392                 certs[depth] = binascii.unhexlify(cert)
7393         elif "CTRL-EVENT-EAP-SUCCESS" in ev:
7394             raise Exception("Unexpected EAP-Success")
7395         elif "CTRL-REQ-EXT_CERT_CHECK" in ev:
7396             id = ev.split(':')[0].split('-')[-1]
7397             break
7398     if 0 not in certs:
7399         raise Exception("Server certificate not received")
7400     if 1 not in certs:
7401         raise Exception("Server certificate issuer not received")
7402 
7403     cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1,
7404                                            certs[0])
7405     cn = cert.get_subject().commonName
7406     logger.info("Server certificate CN=" + cn)
7407 
7408     issuer = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1,
7409                                              certs[1])
7410     icn = issuer.get_subject().commonName
7411     logger.info("Issuer certificate CN=" + icn)
7412 
7413     if cn != "server.w1.fi":
7414         raise Exception("Unexpected server certificate CN: " + cn)
7415     if icn != "Root CA":
7416         raise Exception("Unexpected server certificate issuer CN: " + icn)
7417 
7418     ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=0.1)
7419     if ev:
7420         raise Exception("Unexpected EAP-Success before external check result indication")
7421 
7422     dev[0].request("CTRL-RSP-EXT_CERT_CHECK-" + id + ":good")
7423     dev[0].wait_connected()
7424 
7425     dev[0].request("DISCONNECT")
7426     dev[0].wait_disconnected()
7427     if "FAIL" in dev[0].request("PMKSA_FLUSH"):
7428         raise Exception("PMKSA_FLUSH failed")
7429     dev[0].request("SET blob fast_pac_auth_ext ")
7430     dev[0].request("RECONNECT")
7431 
7432     ev = dev[0].wait_event(["CTRL-REQ-EXT_CERT_CHECK"], timeout=10)
7433     if ev is None:
7434         raise Exception("No peer server certificate event seen (2)")
7435     id = ev.split(':')[0].split('-')[-1]
7436     dev[0].request("CTRL-RSP-EXT_CERT_CHECK-" + id + ":bad")
7437     ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
7438     if ev is None:
7439         raise Exception("EAP-Failure not reported")
7440     dev[0].request("REMOVE_NETWORK all")
7441     dev[0].wait_disconnected()
7442 
7443 def test_eap_tls_errors(dev, apdev):
7444     """EAP-TLS error cases"""
7445     params = int_eap_server_params()
7446     params['fragment_size'] = '100'
7447     hostapd.add_ap(apdev[0], params)
7448     with alloc_fail(dev[0], 1,
7449                     "eap_peer_tls_reassemble_fragment"):
7450         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
7451                        identity="tls user", ca_cert="auth_serv/ca.pem",
7452                        client_cert="auth_serv/user.pem",
7453                        private_key="auth_serv/user.key",
7454                        wait_connect=False, scan_freq="2412")
7455         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
7456         dev[0].request("REMOVE_NETWORK all")
7457         dev[0].wait_disconnected()
7458 
7459     with alloc_fail(dev[0], 1, "eap_tls_init"):
7460         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
7461                        identity="tls user", ca_cert="auth_serv/ca.pem",
7462                        client_cert="auth_serv/user.pem",
7463                        private_key="auth_serv/user.key",
7464                        wait_connect=False, scan_freq="2412")
7465         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
7466         dev[0].request("REMOVE_NETWORK all")
7467         dev[0].wait_disconnected()
7468 
7469     with alloc_fail(dev[0], 1, "eap_peer_tls_ssl_init"):
7470         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
7471                        identity="tls user", ca_cert="auth_serv/ca.pem",
7472                        client_cert="auth_serv/user.pem",
7473                        private_key="auth_serv/user.key",
7474                        engine="1",
7475                        wait_connect=False, scan_freq="2412")
7476         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
7477         ev = dev[0].wait_event(["CTRL-REQ-PIN"], timeout=5)
7478         if ev is None:
7479             raise Exception("No CTRL-REQ-PIN seen")
7480         dev[0].request("REMOVE_NETWORK all")
7481         dev[0].wait_disconnected()
7482 
7483     tests = ["eap_peer_tls_derive_key;eap_tls_success",
7484              "eap_peer_tls_derive_session_id;eap_tls_success",
7485              "eap_tls_getKey",
7486              "eap_tls_get_emsk",
7487              "eap_tls_get_session_id"]
7488     for func in tests:
7489         with alloc_fail(dev[0], 1, func):
7490             dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TLS",
7491                            identity="tls user@domain",
7492                            ca_cert="auth_serv/ca.pem",
7493                            client_cert="auth_serv/user.pem",
7494                            private_key="auth_serv/user.key",
7495                            erp="1",
7496                            wait_connect=False, scan_freq="2412")
7497             wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
7498             dev[0].request("REMOVE_NETWORK all")
7499             dev[0].wait_disconnected()
7500 
7501     with alloc_fail(dev[0], 1, "eap_unauth_tls_init"):
7502         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="UNAUTH-TLS",
7503                        identity="unauth-tls", ca_cert="auth_serv/ca.pem",
7504                        wait_connect=False, scan_freq="2412")
7505         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
7506         dev[0].request("REMOVE_NETWORK all")
7507         dev[0].wait_disconnected()
7508 
7509     with alloc_fail(dev[0], 1, "eap_peer_tls_ssl_init;eap_unauth_tls_init"):
7510         dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="UNAUTH-TLS",
7511                        identity="unauth-tls", ca_cert="auth_serv/ca.pem",
7512                        wait_connect=False, scan_freq="2412")
7513         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
7514         dev[0].request("REMOVE_NETWORK all")
7515         dev[0].wait_disconnected()
7516 
7517 def test_ap_wpa2_eap_status(dev, apdev):
7518     """EAP state machine status information"""
7519     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
7520     hostapd.add_ap(apdev[0], params)
7521     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="PEAP",
7522                    identity="cert user",
7523                    ca_cert="auth_serv/ca.pem", phase2="auth=TLS",
7524                    ca_cert2="auth_serv/ca.pem",
7525                    client_cert2="auth_serv/user.pem",
7526                    private_key2="auth_serv/user.key",
7527                    scan_freq="2412", wait_connect=False)
7528     success = False
7529     states = []
7530     method_states = []
7531     decisions = []
7532     req_methods = []
7533     selected_methods = []
7534     connected = False
7535     for i in range(100000):
7536         if not connected and i % 10 == 9:
7537             ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=0.0001)
7538             if ev:
7539                 connected = True
7540         s = dev[0].get_status(extra="VERBOSE")
7541         if 'EAP state' in s:
7542             state = s['EAP state']
7543             if state:
7544                 if state not in states:
7545                     states.append(state)
7546                 if state == "SUCCESS":
7547                     success = True
7548                     break
7549         if 'methodState' in s:
7550             val = s['methodState']
7551             if val not in method_states:
7552                 method_states.append(val)
7553         if 'decision' in s:
7554             val = s['decision']
7555             if val not in decisions:
7556                 decisions.append(val)
7557         if 'reqMethod' in s:
7558             val = s['reqMethod']
7559             if val not in req_methods:
7560                 req_methods.append(val)
7561         if 'selectedMethod' in s:
7562             val = s['selectedMethod']
7563             if val not in selected_methods:
7564                 selected_methods.append(val)
7565     logger.info("Iterations: %d" % i)
7566     logger.info("EAP states: " + str(states))
7567     logger.info("methodStates: " + str(method_states))
7568     logger.info("decisions: " + str(decisions))
7569     logger.info("reqMethods: " + str(req_methods))
7570     logger.info("selectedMethods: " + str(selected_methods))
7571     if not success:
7572         raise Exception("EAP did not succeed")
7573     if not connected:
7574         dev[0].wait_connected()
7575     dev[0].request("REMOVE_NETWORK all")
7576     dev[0].wait_disconnected()
7577 
7578 def test_ap_wpa2_eap_gpsk_ptk_rekey_ap(dev, apdev):
7579     """WPA2-Enterprise with EAP-GPSK and PTK rekey enforced by AP"""
7580     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
7581     params['wpa_ptk_rekey'] = '2'
7582     hapd = hostapd.add_ap(apdev[0], params)
7583     id = eap_connect(dev[0], hapd, "GPSK", "gpsk user",
7584                      password="abcdefghijklmnop0123456789abcdef")
7585     ev = dev[0].wait_event(["WPA: Key negotiation completed"])
7586     if ev is None:
7587         raise Exception("PTK rekey timed out")
7588     time.sleep(0.1)
7589     hwsim_utils.test_connectivity(dev[0], hapd)
7590 
7591 def test_ap_wpa2_eap_wildcard_ssid(dev, apdev):
7592     """WPA2-Enterprise connection using EAP-GPSK and wildcard SSID"""
7593     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
7594     hapd = hostapd.add_ap(apdev[0], params)
7595     dev[0].connect(bssid=apdev[0]['bssid'], key_mgmt="WPA-EAP", eap="GPSK",
7596                    identity="gpsk user",
7597                    password="abcdefghijklmnop0123456789abcdef",
7598                    scan_freq="2412")
7599 
7600 def test_ap_wpa2_eap_psk_mac_addr_change(dev, apdev):
7601     """WPA2-Enterprise connection using EAP-PSK after MAC address change"""
7602     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
7603     hapd = hostapd.add_ap(apdev[0], params)
7604 
7605     cmd = subprocess.Popen(['pgrep', '-nf', 'wpa_supplicant.*' + dev[0].ifname],
7606                            stdout=subprocess.PIPE)
7607     out, err = cmd.communicate()
7608     res = out.decode().strip()
7609     if res:
7610         pid = int(res)
7611         logger.info("wpa_supplicant PID %d" % pid)
7612     else:
7613         raise Exception("Could not find wpa_supplicant PID")
7614 
7615     addr = dev[0].get_status_field("address")
7616     subprocess.call(['ip', 'link', 'set', 'dev', dev[0].ifname, 'down'])
7617     subprocess.call(['ip', 'link', 'set', 'dev', dev[0].ifname, 'address',
7618                      '02:11:22:33:44:55'])
7619     subprocess.call(['ip', 'link', 'set', 'dev', dev[0].ifname, 'up'])
7620     addr1 = dev[0].get_status_field("address")
7621     if addr1 != '02:11:22:33:44:55':
7622         raise Exception("Failed to change MAC address")
7623 
7624     # Scan using the externally set MAC address, stop the wpa_supplicant
7625     # process to avoid it from processing the ifdown event before the interface
7626     # is already UP, change the MAC address back, allow the wpa_supplicant
7627     # process to continue. This will result in the ifdown + ifup sequence of
7628     # RTM_NEWLINK events to be processed while the interface is already UP.
7629     try:
7630         dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
7631         os.kill(pid, signal.SIGSTOP)
7632         time.sleep(0.1)
7633     finally:
7634         subprocess.call(['ip', 'link', 'set', 'dev', dev[0].ifname, 'down'])
7635         subprocess.call(['ip', 'link', 'set', 'dev', dev[0].ifname, 'address',
7636                          addr])
7637         subprocess.call(['ip', 'link', 'set', 'dev', dev[0].ifname, 'up'])
7638         time.sleep(0.1)
7639         os.kill(pid, signal.SIGCONT)
7640 
7641     eap_connect(dev[0], hapd, "PSK", "psk.user@example.com",
7642                 password_hex="0123456789abcdef0123456789abcdef")
7643 
7644     addr2 = dev[0].get_status_field("address")
7645     if addr != addr2:
7646         raise Exception("Failed to restore MAC address")
7647 
7648 def test_ap_wpa2_eap_server_get_id(dev, apdev):
7649     """Internal EAP server and dot1xAuthSessionUserName"""
7650     params = int_eap_server_params()
7651     hapd = hostapd.add_ap(apdev[0], params)
7652     eap_connect(dev[0], hapd, "TLS", "tls user", ca_cert="auth_serv/ca.pem",
7653                 client_cert="auth_serv/user.pem",
7654                 private_key="auth_serv/user.key")
7655     sta = hapd.get_sta(dev[0].own_addr())
7656     if 'dot1xAuthSessionUserName' not in sta:
7657         raise Exception("No dot1xAuthSessionUserName included")
7658     user = sta['dot1xAuthSessionUserName']
7659     if user != "tls user":
7660         raise Exception("Unexpected dot1xAuthSessionUserName value: " + user)
7661 
7662 def test_ap_wpa2_radius_server_get_id(dev, apdev):
7663     """External RADIUS server and dot1xAuthSessionUserName"""
7664     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
7665     hapd = hostapd.add_ap(apdev[0], params)
7666     eap_connect(dev[0], hapd, "TTLS", "test-user",
7667                 anonymous_identity="ttls", password="password",
7668                 ca_cert="auth_serv/ca.pem", phase2="auth=PAP")
7669     sta = hapd.get_sta(dev[0].own_addr())
7670     if 'dot1xAuthSessionUserName' not in sta:
7671         raise Exception("No dot1xAuthSessionUserName included")
7672     user = sta['dot1xAuthSessionUserName']
7673     if user != "real-user":
7674         raise Exception("Unexpected dot1xAuthSessionUserName value: " + user)
7675 
7676 def test_openssl_systemwide_policy(dev, apdev, test_params):
7677     """OpenSSL systemwide policy and overrides"""
7678     prefix = "openssl_systemwide_policy"
7679     pidfile = os.path.join(test_params['logdir'], prefix + '.pid-wpas')
7680     try:
7681         with HWSimRadio() as (radio, iface):
7682             run_openssl_systemwide_policy(iface, apdev, test_params)
7683     finally:
7684         if os.path.exists(pidfile):
7685             with open(pidfile, 'r') as f:
7686                 pid = int(f.read().strip())
7687                 os.kill(pid, signal.SIGTERM)
7688 
7689 def write_openssl_cnf(cnf, MinProtocol=None, CipherString=None):
7690     with open(cnf, "w") as f:
7691         f.write("""openssl_conf = default_conf
7692 [default_conf]
7693 ssl_conf = ssl_sect
7694 [ssl_sect]
7695 system_default = system_default_sect
7696 [system_default_sect]
7697 """)
7698         if MinProtocol:
7699             f.write("MinProtocol = %s\n" % MinProtocol)
7700         if CipherString:
7701             f.write("CipherString = %s\n" % CipherString)
7702 
7703 def run_openssl_systemwide_policy(iface, apdev, test_params):
7704     prefix = "openssl_systemwide_policy"
7705     logfile = os.path.join(test_params['logdir'], prefix + '.log-wpas')
7706     pidfile = os.path.join(test_params['logdir'], prefix + '.pid-wpas')
7707     conffile = os.path.join(test_params['logdir'], prefix + '.conf')
7708     openssl_cnf = os.path.join(test_params['logdir'], prefix + '.openssl.cnf')
7709 
7710     write_openssl_cnf(openssl_cnf, "TLSv1.2", "DEFAULT@SECLEVEL=2")
7711 
7712     with open(conffile, 'w') as f:
7713         f.write("ctrl_interface=DIR=/var/run/wpa_supplicant\n")
7714 
7715     params = int_eap_server_params()
7716     params['tls_flags'] = "[DISABLE-TLSv1.1][DISABLE-TLSv1.2][DISABLE-TLSv1.3]"
7717 
7718     hapd = hostapd.add_ap(apdev[0], params)
7719 
7720     prg = os.path.join(test_params['logdir'],
7721                        'alt-wpa_supplicant/wpa_supplicant/wpa_supplicant')
7722     if not os.path.exists(prg):
7723         prg = '../../wpa_supplicant/wpa_supplicant'
7724     arg = [prg, '-BddtK', '-P', pidfile, '-f', logfile,
7725            '-Dnl80211', '-c', conffile, '-i', iface]
7726     logger.info("Start wpa_supplicant: " + str(arg))
7727     subprocess.call(arg, env={'OPENSSL_CONF': openssl_cnf})
7728     wpas = WpaSupplicant(ifname=iface)
7729     try:
7730         finish_openssl_systemwide_policy(wpas)
7731     finally:
7732         wpas.close_monitor()
7733         wpas.request("TERMINATE")
7734 
7735 def finish_openssl_systemwide_policy(wpas):
7736     if "PONG" not in wpas.request("PING"):
7737         raise Exception("Could not PING wpa_supplicant")
7738     tls = wpas.request("GET tls_library")
7739     if not tls.startswith("OpenSSL"):
7740         raise HwsimSkip("Not using OpenSSL")
7741 
7742     # Use default configuration without any TLS version overrides. This should
7743     # end up using OpenSSL systemwide policy and result in failure to find a
7744     # compatible protocol version.
7745     ca_file = os.path.join(os.getcwd(), "auth_serv/ca.pem")
7746     id = wpas.connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
7747                       identity="pap user", anonymous_identity="ttls",
7748                       password="password", phase2="auth=PAP",
7749                       ca_cert=ca_file,
7750                       scan_freq="2412", wait_connect=False)
7751     ev = wpas.wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=10)
7752     if ev is None:
7753         raise Exception("EAP not started")
7754     ev = wpas.wait_event(["CTRL-EVENT-EAP-STATUS status='local TLS alert'"],
7755                          timeout=1)
7756     if ev is None:
7757         raise HwsimSkip("OpenSSL systemwide policy not supported")
7758     wpas.request("DISCONNECT")
7759     wpas.wait_disconnected()
7760     wpas.dump_monitor()
7761 
7762     # Explicitly allow TLSv1.0 to be used to override OpenSSL systemwide policy
7763     wpas.set_network_quoted(id, "openssl_ciphers", "DEFAULT@SECLEVEL=1")
7764     wpas.set_network_quoted(id, "phase1", "tls_disable_tlsv1_0=0")
7765     wpas.select_network(id, freq="2412")
7766     wpas.wait_connected()
7767 
7768 def test_ap_wpa2_eap_tls_tod(dev, apdev):
7769     """EAP-TLS server certificate validation and TOD-STRICT"""
7770     check_tls_tod(dev[0])
7771     params = int_eap_server_params()
7772     params["server_cert"] = "auth_serv/server-certpol.pem"
7773     params["private_key"] = "auth_serv/server-certpol.key"
7774     hapd = hostapd.add_ap(apdev[0], params)
7775 
7776     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP",
7777                    eap="TLS", identity="tls user",
7778                    wait_connect=False, scan_freq="2412",
7779                    ca_cert="auth_serv/ca.pem",
7780                    client_cert="auth_serv/user.pem",
7781                    private_key="auth_serv/user.key")
7782     tod0 = None
7783     tod1 = None
7784     while tod0 is None or tod1 is None:
7785         ev = dev[0].wait_event(["CTRL-EVENT-EAP-PEER-CERT"], timeout=10)
7786         if ev is None:
7787             raise Exception("Peer certificate not reported")
7788         if "depth=1 " in ev and "hash=" in ev:
7789             tod1 = " tod=1" in ev
7790         if "depth=0 " in ev and "hash=" in ev:
7791             tod0 = " tod=1" in ev
7792     dev[0].wait_connected()
7793     if not tod0:
7794         raise Exception("TOD-STRICT policy not reported for server certificate")
7795     if tod1:
7796         raise Exception("TOD-STRICT policy unexpectedly reported for CA certificate")
7797 
7798 def test_ap_wpa2_eap_tls_tod_tofu(dev, apdev):
7799     """EAP-TLS server certificate validation and TOD-TOFU"""
7800     check_tls_tod(dev[0])
7801     params = int_eap_server_params()
7802     params["server_cert"] = "auth_serv/server-certpol2.pem"
7803     params["private_key"] = "auth_serv/server-certpol2.key"
7804     hapd = hostapd.add_ap(apdev[0], params)
7805 
7806     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP",
7807                    eap="TLS", identity="tls user",
7808                    wait_connect=False, scan_freq="2412",
7809                    ca_cert="auth_serv/ca.pem",
7810                    client_cert="auth_serv/user.pem",
7811                    private_key="auth_serv/user.key")
7812     tod0 = None
7813     tod1 = None
7814     while tod0 is None or tod1 is None:
7815         ev = dev[0].wait_event(["CTRL-EVENT-EAP-PEER-CERT"], timeout=10)
7816         if ev is None:
7817             raise Exception("Peer certificate not reported")
7818         if "depth=1 " in ev and "hash=" in ev:
7819             tod1 = " tod=2" in ev
7820         if "depth=0 " in ev and "hash=" in ev:
7821             tod0 = " tod=2" in ev
7822     dev[0].wait_connected()
7823     if not tod0:
7824         raise Exception("TOD-TOFU policy not reported for server certificate")
7825     if tod1:
7826         raise Exception("TOD-TOFU policy unexpectedly reported for CA certificate")
7827 
7828 def test_ap_wpa2_eap_sake_no_control_port(dev, apdev):
7829     """WPA2-Enterprise connection using EAP-SAKE without nl80211 control port"""
7830     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
7831     params['driver_params'] = "control_port=0"
7832     hapd = hostapd.add_ap(apdev[0], params)
7833     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
7834     wpas.interface_add("wlan5", drv_params="control_port=0")
7835     eap_connect(wpas, hapd, "SAKE", "sake user",
7836                 password_hex="0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef")
7837     eap_reauth(wpas, "SAKE")
7838 
7839     logger.info("Negative test with incorrect password")
7840     wpas.request("REMOVE_NETWORK all")
7841     eap_connect(wpas, hapd, "SAKE", "sake user",
7842                 password_hex="ff23456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
7843                 expect_failure=True)
7844 
7845 def test_ap_wpa3_eap_transition_disable(dev, apdev):
7846     """WPA3-Enterprise transition disable indication"""
7847     skip_without_tkip(dev[0])
7848     params = hostapd.wpa2_eap_params(ssid="test-wpa3-eap")
7849     params["ieee80211w"] = "1"
7850     params['transition_disable'] = '0x04'
7851     hapd = hostapd.add_ap(apdev[0], params)
7852     id = dev[0].connect("test-wpa3-eap", key_mgmt="WPA-EAP", ieee80211w="1",
7853                         proto="WPA WPA2", pairwise="CCMP", group="TKIP CCMP",
7854                         eap="GPSK", identity="gpsk user",
7855                         password="abcdefghijklmnop0123456789abcdef",
7856                         scan_freq="2412", wait_connect=False)
7857     ev = dev[0].wait_event(["TRANSITION-DISABLE"], timeout=20)
7858     if ev is None:
7859         raise Exception("Transition disable not indicated")
7860     if ev.split(' ')[1] != "04":
7861         raise Exception("Unexpected transition disable bitmap: " + ev)
7862 
7863     val = dev[0].get_network(id, "ieee80211w")
7864     if val != "2":
7865         raise Exception("Unexpected ieee80211w value: " + val)
7866     val = dev[0].get_network(id, "key_mgmt")
7867     if val != "WPA-EAP":
7868         raise Exception("Unexpected key_mgmt value: " + val)
7869     val = dev[0].get_network(id, "group")
7870     if val != "CCMP":
7871         raise Exception("Unexpected group value: " + val)
7872     val = dev[0].get_network(id, "proto")
7873     if val != "RSN":
7874         raise Exception("Unexpected proto value: " + val)
7875 
7876     dev[0].request("DISCONNECT")
7877     dev[0].wait_disconnected()
7878     dev[0].request("RECONNECT")
7879     dev[0].wait_connected()
7880 
7881 def test_ap_wpa2_eap_sha384_psk(dev, apdev):
7882     """WPA2-Enterprise connection using 802.1X-SHA384 and EAP-PSK"""
7883     params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
7884     params["wpa_key_mgmt"] = "WPA-EAP-SHA384"
7885     params["ieee80211w"] = "2"
7886     hapd = hostapd.add_ap(apdev[0], params)
7887 
7888     eap_connect(dev[0], hapd, "PSK", "psk.user@example.com",
7889                 password_hex="0123456789abcdef0123456789abcdef", sha384=True)
7890 
7891     eap_reauth(dev[0], "PSK", sha384=True)
7892     check_mib(dev[0], [("dot11RSNAAuthenticationSuiteRequested", "00-0f-ac-23"),
7893                        ("dot11RSNAAuthenticationSuiteSelected", "00-0f-ac-23")])
7894 
7895     bss = dev[0].get_bss(apdev[0]['bssid'])
7896     if 'flags' not in bss:
7897         raise Exception("Could not get BSS flags from BSS table")
7898     if "[WPA2-EAP-SHA384-CCMP]" not in bss['flags']:
7899         raise Exception("Unexpected BSS flags: " + bss['flags'])
7900 
7901 @long_duration_test
7902 def test_ap_wpa2_eap_timeout(dev, apdev):
7903     """hostapd internal EAP server and timeout triggering disconnection"""
7904     params = int_eap_server_params()
7905     params['disable_pmksa_caching'] = '1'
7906     hapd = hostapd.add_ap(apdev[0], params)
7907     dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP WPA-EAP-SHA256",
7908                    eap="TTLS", identity="user",
7909                    anonymous_identity="ttls", password="password",
7910                    ca_cert="auth_serv/ca.pem", phase2="autheap=GTC",
7911                    scan_freq="2412")
7912 
7913     # Start a new connection and EAP authentication, but force a timeout during
7914     # EAP exchange so that hostapd will go through the special case of EAP
7915     # state machine triggering disconnection of the STA.
7916     hapd.set("ext_eapol_frame_io", "1")
7917     dev[0].set("ext_eapol_frame_io", "1")
7918     dev[0].request("REASSOCIATE")
7919     from test_eap_proto import proxy_msg
7920     proxy_msg(hapd, dev[0]) # EAP-Identity/Request
7921     proxy_msg(dev[0], hapd) # EAP-Identity/Response
7922     time.sleep(1)
7923     dev[0].set("radio_disabled", "1")
7924     time.sleep(1)
7925     dev[0].request("DISCONNECT")
7926     ev = hapd.wait_event(["CTRL-EVENT-EAP-TIMEOUT-FAILURE"], timeout=120)
7927     hapd.set("ext_eapol_frame_io", "0")
7928     dev[0].set("ext_eapol_frame_io", "0")
7929     if ev is None:
7930         raise Exception("EAP timeout not reported")
7931     time.sleep(1)
7932 
7933     # Verify that connection can still be established
7934     dev[0].request("RECONNECT")
7935     dev[0].wait_connected()
7936