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