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