1# Test cases for Device Provisioning Protocol (DPP)
2# Copyright (c) 2017, Qualcomm Atheros, Inc.
3# Copyright (c) 2018-2019, The Linux Foundation
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 hashlib
11import logging
12logger = logging.getLogger()
13import os
14import socket
15import struct
16import subprocess
17import time
18try:
19    from socketserver import StreamRequestHandler, TCPServer
20except ImportError:
21    from SocketServer import StreamRequestHandler, TCPServer
22
23import hostapd
24import hwsim_utils
25from hwsim import HWSimRadio
26from utils import *
27from wpasupplicant import WpaSupplicant
28from wlantest import WlantestCapture
29
30try:
31    import OpenSSL
32    openssl_imported = True
33except ImportError:
34    openssl_imported = False
35
36def check_dpp_capab(dev, brainpool=False, min_ver=1):
37    if "UNKNOWN COMMAND" in dev.request("DPP_BOOTSTRAP_GET_URI 0"):
38        raise HwsimSkip("DPP not supported")
39    if brainpool:
40        tls = dev.request("GET tls_library")
41        if not tls.startswith("OpenSSL") or "run=BoringSSL" in tls:
42            raise HwsimSkip("Crypto library does not support Brainpool curves: " + tls)
43    capa = dev.request("GET_CAPABILITY dpp")
44    ver = 1
45    if capa.startswith("DPP="):
46        ver = int(capa[4:])
47    if ver < min_ver:
48        raise HwsimSkip("DPP version %d not supported" % min_ver)
49    return ver
50
51def wait_dpp_fail(dev, expected=None):
52    ev = dev.wait_event(["DPP-FAIL"], timeout=5)
53    if ev is None:
54        raise Exception("Failure not reported")
55    if expected and expected not in ev:
56        raise Exception("Unexpected result: " + ev)
57
58def test_dpp_qr_code_parsing(dev, apdev):
59    """DPP QR Code parsing"""
60    check_dpp_capab(dev[0])
61    id = []
62
63    tests = ["DPP:C:81/1,115/36;K:MDkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDIgADM2206avxHJaHXgLMkq/24e0rsrfMP9K1Tm8gx+ovP0I=;;",
64             "DPP:C:81/1,81/2,81/3,81/4,81/5,81/6,81/7,81/8,81/9,81/10,81/11,81/12,81/13,82/14,83/1,83/2,83/3,83/4,83/5,83/6,83/7,83/8,83/9,84/5,84/6,84/7,84/8,84/9,84/10,84/11,84/12,84/13,115/36;K:MDkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDIgADM2206avxHJaHXgLMkq/24e0rsrfMP9K1Tm8gx+ovP0I=;;",
65             "DPP:C:81/1,2,3,4,5,6,7,8,9,10,11,12,13,82/14,83/1,2,3,4,5,6,7,8,9,84/5,6,7,8,9,10,11,12,13,115/36;K:MDkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDIgADM2206avxHJaHXgLMkq/24e0rsrfMP9K1Tm8gx+ovP0I=;;",
66             "DPP:C:81/1,2,3;K:MDkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDIgADM2206avxHJaHXgLMkq/24e0rsrfMP9K1Tm8gx+ovP0I=;;",
67             "DPP:I:SN=4774LH2b4044;M:010203040506;K:MDkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDIgADURzxmttZoIRIPWGoQMV00XHWCAQIhXruVWOz0NjlkIA=;;",
68             "DPP:I:;M:010203040506;K:MDkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDIgADURzxmttZoIRIPWGoQMV00XHWCAQIhXruVWOz0NjlkIA=;;"]
69    for uri in tests:
70        id.append(dev[0].dpp_qr_code(uri))
71
72        uri2 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id[-1])
73        if uri != uri2:
74            raise Exception("Returned URI does not match")
75
76    tests = ["foo",
77             "DPP:",
78             "DPP:;;",
79             "DPP:C:1/2;M:;K;;",
80             "DPP:I:;M:01020304050;K:MDkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDIgADURzxmttZoIRIPWGoQMV00XHWCAQIhXruVWOz0NjlkIA=;;",
81             "DPP:K:" + base64.b64encode(b"hello").decode() + ";;",
82             "DPP:K:MEkwEwYHKoZIzj0CAQYIKoZIzj0DAQEDMgAEXiJuIWt1Q/CPCkuULechh37UsXPmbUANOeN5U9sOQROE4o/NEFeFEejROHYwwehF;;",
83             "DPP:K:MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANNZaZA4T/kRDjnmpI1ACOJhAuTIIEk2KFOpS6XPpGF+EVr/ao3XemkE0/nzXmGaLzLqTUCJknSdxTnVPeWfCVsCAwEAAQ==;;",
84             "DPP:K:MIIBCjCB0wYHKoZIzj0CATCBxwIBATAkBgcqhkjOPQEBAhkA/////////////////////v//////////MEsEGP////////////////////7//////////AQYZCEFGeWcgOcPp+mrciQwSf643uzBRrmxAxUAMEWub8hCL2TtV5Uo04Eg6uEhltUEMQQYjagOsDCQ9ny/IOtDoYgA9P8K/YL/EBIHGSuV/8jaeGMQEe1rJM3Vc/l3oR55SBECGQD///////////////+Z3vg2FGvJsbTSKDECAQEDMgAEXiJuIWt1Q/CPCkuULechh37UsXPmbUANOeN5U9sOQROE4o/NEFeFEejROHYwwehF;;",
85             "DPP:I:foo\tbar;M:010203040506;K:MDkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDIgADURzxmttZoIRIPWGoQMV00XHWCAQIhXruVWOz0NjlkIA=;;",
86             "DPP:C:1;K:MDkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDIgADM2206avxHJaHXgLMkqa24e0rsrfMP9K1Tm8gx+ovP0I=;;",
87             "DPP:C:81/1a;K:MDkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDIgADM2206avxHJaHXgLMkqa24e0rsrfMP9K1Tm8gx+ovP0I=;;",
88             "DPP:C:1/2000,81/-1;K:MDkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDIgADM2206avxHJaHXgLMkqa24e0rsrfMP9K1Tm8gx+ovP0I=;;",
89             "DPP:C:-1/1;K:MDkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDIgADM2206avxHJaHXgLMkqa24e0rsrfMP9K1Tm8gx+ovP0I=;;"]
90    for t in tests:
91        res = dev[0].request("DPP_QR_CODE " + t)
92        if "FAIL" not in res:
93            raise Exception("Accepted invalid QR Code: " + t)
94
95    logger.info("ID: " + str(id))
96    if id[0] == id[1] or id[0] == id[2] or id[1] == id[2]:
97        raise Exception("Duplicate ID returned")
98
99    if "FAIL" not in dev[0].request("DPP_BOOTSTRAP_REMOVE 12345678"):
100        raise Exception("DPP_BOOTSTRAP_REMOVE accepted unexpectedly")
101    if "OK" not in dev[0].request("DPP_BOOTSTRAP_REMOVE %d" % id[1]):
102        raise Exception("DPP_BOOTSTRAP_REMOVE failed")
103
104    id = dev[0].dpp_bootstrap_gen()
105    uri = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id)
106    logger.info("Generated URI: " + uri)
107
108    dev[0].dpp_qr_code(uri)
109
110    id = dev[0].dpp_bootstrap_gen(chan="81/1,115/36", mac="010203040506",
111                                  info="foo")
112    uri = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id)
113    logger.info("Generated URI: " + uri)
114
115    dev[0].dpp_qr_code(uri)
116
117def test_dpp_uri_version(dev, apdev):
118    """DPP URI version information"""
119    check_dpp_capab(dev[0], min_ver=2)
120
121    id0 = dev[0].dpp_bootstrap_gen()
122    uri = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
123    logger.info("Generated URI: " + uri)
124
125    id1 = dev[0].dpp_qr_code(uri)
126    uri = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id1)
127    info = dev[0].request("DPP_BOOTSTRAP_INFO %d" % id1)
128    logger.info("Parsed URI info:\n" + info)
129    if "version=2" not in info.splitlines():
130        raise Exception("Unexpected version information (v2)")
131
132    dev[0].set("dpp_version_override", "1")
133    id0 = dev[0].dpp_bootstrap_gen()
134    uri = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
135    logger.info("Generated URI: " + uri)
136
137    id1 = dev[0].dpp_qr_code(uri)
138    uri = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id1)
139    info = dev[0].request("DPP_BOOTSTRAP_INFO %d" % id1)
140    logger.info("Parsed URI info:\n" + info)
141    if "version=0" not in info.splitlines():
142        raise Exception("Unexpected version information (without indication)")
143
144def test_dpp_qr_code_parsing_fail(dev, apdev):
145    """DPP QR Code parsing local failure"""
146    check_dpp_capab(dev[0])
147    with alloc_fail(dev[0], 1, "dpp_parse_uri_info"):
148        if "FAIL" not in dev[0].request("DPP_QR_CODE DPP:I:SN=4774LH2b4044;M:010203040506;K:MDkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDIgADURzxmttZoIRIPWGoQMV00XHWCAQIhXruVWOz0NjlkIA=;;"):
149            raise Exception("DPP_QR_CODE failure not reported")
150
151    with alloc_fail(dev[0], 1, "dpp_parse_uri_pk"):
152        if "FAIL" not in dev[0].request("DPP_QR_CODE DPP:K:MDkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDIgADURzxmttZoIRIPWGoQMV00XHWCAQIhXruVWOz0NjlkIA=;;"):
153            raise Exception("DPP_QR_CODE failure not reported")
154
155    with fail_test(dev[0], 1, "dpp_parse_uri_pk"):
156        if "FAIL" not in dev[0].request("DPP_QR_CODE DPP:K:MDkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDIgADURzxmttZoIRIPWGoQMV00XHWCAQIhXruVWOz0NjlkIA=;;"):
157            raise Exception("DPP_QR_CODE failure not reported")
158
159    with alloc_fail(dev[0], 1, "dpp_parse_uri"):
160        if "FAIL" not in dev[0].request("DPP_QR_CODE DPP:I:SN=4774LH2b4044;M:010203040506;K:MDkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDIgADURzxmttZoIRIPWGoQMV00XHWCAQIhXruVWOz0NjlkIA=;;"):
161            raise Exception("DPP_QR_CODE failure not reported")
162
163dpp_key_p256 = "30570201010420777fc55dc51e967c10ec051b91d860b5f1e6c934e48d5daffef98d032c64b170a00a06082a8648ce3d030107a124032200020c804188c7f85beb6e91070d2b3e5e39b90ca77b4d3c5251bc1844d6ca29dcad"
164dpp_key_p384 = "307402010104302f56fdd83b5345cacb630eb7c22fa5ad5daba37307c95191e2a75756d137003bd8b32dbcb00eb5650c1eb499ecfcaec0a00706052b81040022a13403320003615ec2141b5b77aebb6523f8a012755f9a34405a8398d2ceeeebca7f5ce868bf55056cba4c4ec62fad3ed26dd29e0f23"
165dpp_key_p521 = "308198020101044200c8010d5357204c252551aaf4e210343111e503fd1dc615b257058997c49b6b643c975226e93be8181cca3d83a7072defd161dfbdf433c19abe1f2ad51867a05761a00706052b81040023a1460344000301cdf3608b1305fe34a1f976095dcf001182b9973354efe156291a66830292f9babd8f412ad462958663e7a75d1d0610abdfc3dd95d40669f7ab3bc001668cfb3b7c"
166dpp_key_bp256 = "3058020101042057133a676fb60bf2a3e6797e19833c7b0f89dc192ab99ab5fa377ae23a157765a00b06092b2403030208010107a12403220002945d9bf7ce30c9c1ac0ff21ca62b984d5bb80ff69d2be8c9716ab39a10d2caf0"
167dpp_key_bp384 = "307802010104304902df9f3033a9b7128554c0851dc7127c3573eed150671dae74c0013e9896a9b1c22b6f7d43d8a2ebb7cd474dc55039a00b06092b240303020801010ba13403320003623cb5e68787f351faababf3425161571560add2e6f9a306fcbffb507735bf955bb46dd20ba246b0d5cadce73e5bd6a6"
168dpp_key_bp512 = "30819802010104405803494226eb7e50bf0e90633f37e7e35d33f5fa502165eeba721d927f9f846caf12e925701d18e123abaaaf4a7edb4fc4de21ce18bc10c4d12e8b3439f74e40a00b06092b240303020801010da144034200033b086ccd47486522d35dc16fbb2229642c2e9e87897d45abbf21f9fb52acb5a6272b31d1b227c3e53720769cc16b4cb181b26cd0d35fe463218aaedf3b6ec00a"
169
170def test_dpp_qr_code_curves(dev, apdev):
171    """DPP QR Code and supported curves"""
172    check_dpp_capab(dev[0])
173    tests = [("prime256v1", dpp_key_p256),
174             ("secp384r1", dpp_key_p384),
175             ("secp521r1", dpp_key_p521)]
176    for curve, hex in tests:
177        id = dev[0].dpp_bootstrap_gen(key=hex)
178        info = dev[0].request("DPP_BOOTSTRAP_INFO %d" % id)
179        if "FAIL" in info:
180            raise Exception("Failed to get info for " + curve)
181        if "curve=" + curve not in info:
182            raise Exception("Curve mismatch for " + curve)
183
184def test_dpp_qr_code_curves_brainpool(dev, apdev):
185    """DPP QR Code and supported Brainpool curves"""
186    check_dpp_capab(dev[0], brainpool=True)
187    tests = [("brainpoolP256r1", dpp_key_bp256),
188             ("brainpoolP384r1", dpp_key_bp384),
189             ("brainpoolP512r1", dpp_key_bp512)]
190    for curve, hex in tests:
191        id = dev[0].dpp_bootstrap_gen(key=hex)
192        info = dev[0].request("DPP_BOOTSTRAP_INFO %d" % id)
193        if "FAIL" in info:
194            raise Exception("Failed to get info for " + curve)
195        if "curve=" + curve not in info:
196            raise Exception("Curve mismatch for " + curve)
197
198def test_dpp_qr_code_unsupported_curve(dev, apdev):
199    """DPP QR Code and unsupported curve"""
200    check_dpp_capab(dev[0])
201
202    id = dev[0].request("DPP_BOOTSTRAP_GEN type=qrcode curve=unsupported")
203    if "FAIL" not in id:
204        raise Exception("Unsupported curve accepted")
205
206    tests = ["30",
207             "305f02010104187f723ed9e1b41979ec5cd02eb82696efc76b40e277661049a00a06082a8648ce3d030101a134033200043f292614dea97c43f500f069e79ae9fb48f8b07369180de5eec8fa2bc9eea5af7a46dc335f52f10cb1c0e9464201d41b"]
208    for hex in tests:
209        id = dev[0].request("DPP_BOOTSTRAP_GEN type=qrcode key=" + hex)
210        if "FAIL" not in id:
211            raise Exception("Unsupported/invalid curve accepted")
212
213def test_dpp_qr_code_keygen_fail(dev, apdev):
214    """DPP QR Code and keygen failure"""
215    check_dpp_capab(dev[0])
216
217    with alloc_fail(dev[0], 1,
218                    "crypto_ec_key_get_subject_public_key;dpp_keygen"):
219        if "FAIL" not in dev[0].request("DPP_BOOTSTRAP_GEN type=qrcode"):
220            raise Exception("Failure not reported")
221
222    with alloc_fail(dev[0], 1, "base64_gen_encode;dpp_keygen"):
223        if "FAIL" not in dev[0].request("DPP_BOOTSTRAP_GEN type=qrcode"):
224            raise Exception("Failure not reported")
225
226def test_dpp_qr_code_curve_select(dev, apdev):
227    """DPP QR Code and curve selection"""
228    check_dpp_capab(dev[0], brainpool=True)
229    check_dpp_capab(dev[1], brainpool=True)
230
231    bi = []
232    for key in [dpp_key_p256, dpp_key_p384, dpp_key_p521,
233                dpp_key_bp256, dpp_key_bp384, dpp_key_bp512]:
234        id = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True, key=key)
235        info = dev[0].request("DPP_BOOTSTRAP_INFO %d" % id)
236        for i in info.splitlines():
237            if '=' in i:
238                name, val = i.split('=')
239                if name == "curve":
240                    curve = val
241                    break
242        uri = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id)
243        bi.append((curve, uri))
244
245    for curve, uri in bi:
246        logger.info("Curve: " + curve)
247        logger.info("URI: " + uri)
248
249        dev[0].dpp_listen(2412)
250        dev[1].dpp_auth_init(uri=uri)
251        wait_auth_success(dev[0], dev[1], configurator=dev[1], enrollee=dev[0],
252                          allow_enrollee_failure=True, stop_responder=True,
253                          stop_initiator=True)
254
255def test_dpp_qr_code_auth_broadcast(dev, apdev):
256    """DPP QR Code and authentication exchange (broadcast)"""
257    check_dpp_capab(dev[0])
258    check_dpp_capab(dev[1])
259    logger.info("dev0 displays QR Code")
260    id0 = dev[0].dpp_bootstrap_gen(chan="81/1")
261    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
262    logger.info("dev1 scans QR Code and initiates DPP Authentication")
263    dev[0].dpp_listen(2412)
264    dev[1].dpp_auth_init(uri=uri0)
265    wait_auth_success(dev[0], dev[1], stop_responder=True)
266
267def test_dpp_qr_code_auth_unicast(dev, apdev):
268    """DPP QR Code and authentication exchange (unicast)"""
269    run_dpp_qr_code_auth_unicast(dev, apdev, None)
270
271def test_dpp_qr_code_auth_unicast_ap_enrollee(dev, apdev):
272    """DPP QR Code and authentication exchange (AP enrollee)"""
273    run_dpp_qr_code_auth_unicast(dev, apdev, None, netrole="ap")
274
275def run_dpp_configurator_enrollee(dev, apdev, conf_curve=None):
276    run_dpp_qr_code_auth_unicast(dev, apdev, None, netrole="configurator",
277                                 configurator=True, conf_curve=conf_curve,
278                                 conf="configurator")
279    ev = dev[0].wait_event(["DPP-CONFIGURATOR-ID"], timeout=2)
280    if ev is None:
281        raise Exception("No Configurator instance added")
282
283def test_dpp_configurator_enrollee(dev, apdev):
284    """DPP Configurator enrolling"""
285    run_dpp_configurator_enrollee(dev, apdev)
286
287def test_dpp_configurator_enrollee_prime256v1(dev, apdev):
288    """DPP Configurator enrolling (prime256v1)"""
289    run_dpp_configurator_enrollee(dev, apdev, conf_curve="prime256v1")
290
291def test_dpp_configurator_enrollee_secp384r1(dev, apdev):
292    """DPP Configurator enrolling (secp384r1)"""
293    run_dpp_configurator_enrollee(dev, apdev, conf_curve="secp384r1")
294
295def test_dpp_configurator_enrollee_secp521r1(dev, apdev):
296    """DPP Configurator enrolling (secp521r1)"""
297    run_dpp_configurator_enrollee(dev, apdev, conf_curve="secp521r1")
298
299def test_dpp_configurator_enrollee_brainpoolP256r1(dev, apdev):
300    """DPP Configurator enrolling (brainpoolP256r1)"""
301    run_dpp_configurator_enrollee(dev, apdev, conf_curve="brainpoolP256r1")
302
303def test_dpp_configurator_enrollee_brainpoolP384r1(dev, apdev):
304    """DPP Configurator enrolling (brainpoolP384r1)"""
305    run_dpp_configurator_enrollee(dev, apdev, conf_curve="brainpoolP384r1")
306
307def test_dpp_configurator_enrollee_brainpoolP512r1(dev, apdev):
308    """DPP Configurator enrolling (brainpoolP512r1)"""
309    run_dpp_configurator_enrollee(dev, apdev, conf_curve="brainpoolP512r1")
310
311def test_dpp_configurator_enroll_conf(dev, apdev):
312    """DPP Configurator enrolling followed by use of the new Configurator"""
313    check_dpp_capab(dev[0], min_ver=2)
314    try:
315        dev[0].set("dpp_config_processing", "2")
316        run_dpp_configurator_enroll_conf(dev, apdev)
317    finally:
318        dev[0].set("dpp_config_processing", "0", allow_fail=True)
319
320def run_dpp_configurator_enroll_conf(dev, apdev):
321    run_dpp_qr_code_auth_unicast(dev, apdev, None, netrole="configurator",
322                                 configurator=True, conf="configurator",
323                                 qr="mutual", stop_responder=False)
324    ev = dev[0].wait_event(["DPP-CONFIGURATOR-ID"], timeout=2)
325    if ev is None:
326        raise Exception("No Configurator instance added")
327    dev[1].reset()
328    dev[0].dump_monitor()
329
330    ssid = "test-network"
331    passphrase = "test-passphrase"
332    dev[0].set("dpp_configurator_params",
333               "conf=sta-psk ssid=%s pass=%s" % (binascii.hexlify(ssid.encode()).decode(), binascii.hexlify(passphrase.encode()).decode()))
334    dev[0].dpp_listen(2412, role="configurator")
335    id0 = dev[0].dpp_bootstrap_gen(chan="81/1")
336    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
337    dev[1].dpp_auth_init(uri=uri0, role="enrollee")
338    wait_auth_success(dev[0], dev[1], configurator=dev[0], enrollee=dev[1])
339
340def test_dpp_qr_code_curve_prime256v1(dev, apdev):
341    """DPP QR Code and curve prime256v1"""
342    run_dpp_qr_code_auth_unicast(dev, apdev, "prime256v1")
343
344def test_dpp_qr_code_curve_secp384r1(dev, apdev):
345    """DPP QR Code and curve secp384r1"""
346    run_dpp_qr_code_auth_unicast(dev, apdev, "secp384r1")
347
348def test_dpp_qr_code_curve_secp521r1(dev, apdev):
349    """DPP QR Code and curve secp521r1"""
350    run_dpp_qr_code_auth_unicast(dev, apdev, "secp521r1")
351
352def test_dpp_qr_code_curve_brainpoolP256r1(dev, apdev):
353    """DPP QR Code and curve brainpoolP256r1"""
354    run_dpp_qr_code_auth_unicast(dev, apdev, "brainpoolP256r1")
355
356def test_dpp_qr_code_curve_brainpoolP384r1(dev, apdev):
357    """DPP QR Code and curve brainpoolP384r1"""
358    run_dpp_qr_code_auth_unicast(dev, apdev, "brainpoolP384r1")
359
360def test_dpp_qr_code_curve_brainpoolP512r1(dev, apdev):
361    """DPP QR Code and curve brainpoolP512r1"""
362    run_dpp_qr_code_auth_unicast(dev, apdev, "brainpoolP512r1")
363
364def test_dpp_qr_code_set_key(dev, apdev):
365    """DPP QR Code and fixed bootstrapping key"""
366    run_dpp_qr_code_auth_unicast(dev, apdev, None, key="30770201010420e5143ac74682cc6869a830e8f5301a5fa569130ac329b1d7dd6f2a7495dbcbe1a00a06082a8648ce3d030107a144034200045e13e167c33dbc7d85541e5509600aa8139bbb3e39e25898992c5d01be92039ee2850f17e71506ded0d6b25677441eae249f8e225c68dd15a6354dca54006383")
367
368def run_dpp_qr_code_auth_unicast(dev, apdev, curve, netrole=None, key=None,
369                                 require_conf_success=False, init_extra=None,
370                                 require_conf_failure=False,
371                                 configurator=False, conf_curve=None,
372                                 conf=None, qr=None, stop_responder=True):
373    brainpool = (curve and "brainpool" in curve) or \
374        (conf_curve and "brainpool" in conf_curve)
375    check_dpp_capab(dev[0], brainpool)
376    check_dpp_capab(dev[1], brainpool)
377    if configurator:
378        conf_id = dev[1].dpp_configurator_add(curve=conf_curve)
379    else:
380        conf_id = None
381
382    if qr == "mutual":
383        logger.info("dev1 displays QR Code and dev0 scans it")
384        id1 = dev[1].dpp_bootstrap_gen(chan="81/1", mac=True, curve=curve)
385        uri1 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id1)
386        id1c = dev[0].dpp_qr_code(uri1)
387    else:
388        id1 = None
389
390    logger.info("dev0 displays QR Code")
391    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True, curve=curve, key=key)
392    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
393
394    logger.info("dev1 scans QR Code and initiates DPP Authentication")
395    dev[0].dpp_listen(2412, netrole=netrole, qr=qr)
396    dev[1].dpp_auth_init(uri=uri0, extra=init_extra, configurator=conf_id,
397                         conf=conf, own=id1)
398    wait_auth_success(dev[0], dev[1], configurator=dev[1], enrollee=dev[0],
399                      allow_enrollee_failure=True,
400                      allow_configurator_failure=not require_conf_success,
401                      require_configurator_failure=require_conf_failure,
402                      stop_responder=stop_responder)
403
404def test_dpp_qr_code_auth_mutual(dev, apdev):
405    """DPP QR Code and authentication exchange (mutual)"""
406    check_dpp_capab(dev[0])
407    check_dpp_capab(dev[1])
408    logger.info("dev0 displays QR Code")
409    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
410    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
411
412    logger.info("dev1 displays QR Code")
413    id1b = dev[1].dpp_bootstrap_gen(chan="81/1", mac=True)
414    uri1b = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id1b)
415
416    logger.info("dev0 scans QR Code")
417    id0b = dev[0].dpp_qr_code(uri1b)
418
419    logger.info("dev1 scans QR Code and initiates DPP Authentication")
420    dev[0].dpp_listen(2412)
421    dev[1].dpp_auth_init(uri=uri0, own=id1b)
422
423    ev = dev[1].wait_event(["DPP-AUTH-DIRECTION"], timeout=5)
424    if ev is None:
425        raise Exception("DPP authentication direction not indicated (Initiator)")
426    if "mutual=1" not in ev:
427        raise Exception("Mutual authentication not used")
428
429    wait_auth_success(dev[0], dev[1], stop_responder=True)
430
431def test_dpp_qr_code_auth_mutual2(dev, apdev):
432    """DPP QR Code and authentication exchange (mutual2)"""
433    check_dpp_capab(dev[0])
434    check_dpp_capab(dev[1])
435    logger.info("dev0 displays QR Code")
436    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
437    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
438
439    logger.info("dev1 displays QR Code")
440    id1b = dev[1].dpp_bootstrap_gen(chan="81/1", mac=True)
441    uri1b = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id1b)
442
443    logger.info("dev1 scans QR Code and initiates DPP Authentication")
444    dev[0].dpp_listen(2412, qr="mutual")
445    dev[1].dpp_auth_init(uri=uri0, own=id1b)
446
447    ev = dev[1].wait_event(["DPP-RESPONSE-PENDING"], timeout=5)
448    if ev is None:
449        raise Exception("Pending response not reported")
450    ev = dev[0].wait_event(["DPP-SCAN-PEER-QR-CODE"], timeout=5)
451    if ev is None:
452        raise Exception("QR Code scan for mutual authentication not requested")
453
454    logger.info("dev0 scans QR Code")
455    id0b = dev[0].dpp_qr_code(uri1b)
456
457    ev = dev[1].wait_event(["DPP-AUTH-DIRECTION"], timeout=5)
458    if ev is None:
459        raise Exception("DPP authentication direction not indicated (Initiator)")
460    if "mutual=1" not in ev:
461        raise Exception("Mutual authentication not used")
462
463    wait_auth_success(dev[0], dev[1], stop_responder=True)
464
465def test_dpp_qr_code_auth_mutual_p_256(dev, apdev):
466    """DPP QR Code and authentication exchange (mutual, autogen P-256)"""
467    run_dpp_qr_code_auth_mutual(dev, apdev, "P-256")
468
469def test_dpp_qr_code_auth_mutual_p_384(dev, apdev):
470    """DPP QR Code and authentication exchange (mutual, autogen P-384)"""
471    run_dpp_qr_code_auth_mutual(dev, apdev, "P-384")
472
473def test_dpp_qr_code_auth_mutual_p_521(dev, apdev):
474    """DPP QR Code and authentication exchange (mutual, autogen P-521)"""
475    run_dpp_qr_code_auth_mutual(dev, apdev, "P-521")
476
477def test_dpp_qr_code_auth_mutual_bp_256(dev, apdev):
478    """DPP QR Code and authentication exchange (mutual, autogen BP-256)"""
479    run_dpp_qr_code_auth_mutual(dev, apdev, "BP-256")
480
481def test_dpp_qr_code_auth_mutual_bp_384(dev, apdev):
482    """DPP QR Code and authentication exchange (mutual, autogen BP-384)"""
483    run_dpp_qr_code_auth_mutual(dev, apdev, "BP-384")
484
485def test_dpp_qr_code_auth_mutual_bp_512(dev, apdev):
486    """DPP QR Code and authentication exchange (mutual, autogen BP-512)"""
487    run_dpp_qr_code_auth_mutual(dev, apdev, "BP-512")
488
489def run_dpp_qr_code_auth_mutual(dev, apdev, curve):
490    check_dpp_capab(dev[0], curve and "BP-" in curve)
491    check_dpp_capab(dev[1], curve and "BP-" in curve)
492    logger.info("dev0 displays QR Code")
493    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True, curve=curve)
494    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
495    logger.info("dev1 scans QR Code and initiates DPP Authentication")
496    dev[0].dpp_listen(2412, qr="mutual")
497    dev[1].dpp_auth_init(uri=uri0)
498
499    ev = dev[1].wait_event(["DPP-RESPONSE-PENDING"], timeout=5)
500    if ev is None:
501        raise Exception("Pending response not reported")
502    uri = ev.split(' ')[1]
503
504    ev = dev[0].wait_event(["DPP-SCAN-PEER-QR-CODE"], timeout=5)
505    if ev is None:
506        raise Exception("QR Code scan for mutual authentication not requested")
507
508    logger.info("dev0 scans QR Code")
509    dev[0].dpp_qr_code(uri)
510
511    ev = dev[1].wait_event(["DPP-AUTH-DIRECTION"], timeout=5)
512    if ev is None:
513        raise Exception("DPP authentication direction not indicated (Initiator)")
514    if "mutual=1" not in ev:
515        raise Exception("Mutual authentication not used")
516
517    wait_auth_success(dev[0], dev[1], stop_responder=True)
518
519def test_dpp_auth_resp_retries(dev, apdev):
520    """DPP Authentication Response retries"""
521    check_dpp_capab(dev[0])
522    check_dpp_capab(dev[1])
523    dev[0].set("dpp_resp_max_tries", "3")
524    dev[0].set("dpp_resp_retry_time", "100")
525
526    logger.info("dev0 displays QR Code")
527    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
528    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
529    logger.info("dev1 displays QR Code")
530    id1b = dev[1].dpp_bootstrap_gen(chan="81/1", mac=True)
531    uri1b = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id1b)
532    logger.info("dev1 scans QR Code and initiates DPP Authentication")
533    dev[0].dpp_listen(2412, qr="mutual")
534    dev[1].dpp_auth_init(uri=uri0, own=id1b)
535
536    ev = dev[1].wait_event(["DPP-RESPONSE-PENDING"], timeout=5)
537    if ev is None:
538        raise Exception("Pending response not reported")
539    ev = dev[0].wait_event(["DPP-SCAN-PEER-QR-CODE"], timeout=5)
540    if ev is None:
541        raise Exception("QR Code scan for mutual authentication not requested")
542
543    # Stop Initiator from listening to frames to force retransmission of the
544    # DPP Authentication Response frame with Status=0
545    dev[1].request("DPP_STOP_LISTEN")
546
547    dev[1].dump_monitor()
548    dev[0].dump_monitor()
549
550    logger.info("dev0 scans QR Code")
551    id0b = dev[0].dpp_qr_code(uri1b)
552
553    ev = dev[0].wait_event(["DPP-TX "], timeout=5)
554    if ev is None or "type=1" not in ev:
555        raise Exception("DPP Authentication Response not sent")
556    ev = dev[0].wait_event(["DPP-TX-STATUS"], timeout=5)
557    if ev is None:
558        raise Exception("TX status for DPP Authentication Response not reported")
559    if "result=no-ACK" not in ev:
560        raise Exception("Unexpected TX status for Authentication Response: " + ev)
561
562    ev = dev[0].wait_event(["DPP-TX "], timeout=15)
563    if ev is None or "type=1" not in ev:
564        raise Exception("DPP Authentication Response retransmission not sent")
565
566def test_dpp_qr_code_auth_mutual_not_used(dev, apdev):
567    """DPP QR Code and authentication exchange (mutual not used)"""
568    check_dpp_capab(dev[0])
569    check_dpp_capab(dev[1])
570    logger.info("dev0 displays QR Code")
571    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
572    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
573    logger.info("dev1 displays QR Code")
574    id1b = dev[1].dpp_bootstrap_gen(chan="81/1", mac=True)
575    uri1b = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id1b)
576    logger.info("dev0 does not scan QR Code")
577    logger.info("dev1 scans QR Code and initiates DPP Authentication")
578    dev[0].dpp_listen(2412)
579    dev[1].dpp_auth_init(uri=uri0, own=id1b)
580
581    ev = dev[1].wait_event(["DPP-AUTH-DIRECTION"], timeout=5)
582    if ev is None:
583        raise Exception("DPP authentication direction not indicated (Initiator)")
584    if "mutual=0" not in ev:
585        raise Exception("Mutual authentication not used")
586
587    wait_auth_success(dev[0], dev[1], stop_responder=True)
588
589def test_dpp_qr_code_auth_mutual_curve_mismatch(dev, apdev):
590    """DPP QR Code and authentication exchange (mutual/mismatch)"""
591    check_dpp_capab(dev[0])
592    check_dpp_capab(dev[1])
593    logger.info("dev0 displays QR Code")
594    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
595    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
596    logger.info("dev1 displays QR Code")
597    id1b = dev[1].dpp_bootstrap_gen(chan="81/1", mac=True, curve="secp384r1")
598    uri1b = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id1b)
599    logger.info("dev0 scans QR Code")
600    id0b = dev[0].dpp_qr_code(uri1b)
601    logger.info("dev1 scans QR Code")
602    dev[1].dpp_auth_init(uri=uri0, own=id1b, expect_fail=True)
603
604def test_dpp_qr_code_auth_hostapd_mutual2(dev, apdev):
605    """DPP QR Code and authentication exchange (hostapd mutual2)"""
606    check_dpp_capab(dev[0])
607    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured"})
608    check_dpp_capab(hapd)
609    logger.info("AP displays QR Code")
610    id_h = hapd.dpp_bootstrap_gen(chan="81/1", mac=True)
611    uri_h = hapd.request("DPP_BOOTSTRAP_GET_URI %d" % id_h)
612    logger.info("dev0 displays QR Code")
613    id0b = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
614    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0b)
615    logger.info("dev0 scans QR Code and initiates DPP Authentication")
616    hapd.dpp_listen(2412, qr="mutual")
617    dev[0].dpp_auth_init(uri=uri_h, own=id0b)
618
619    ev = dev[0].wait_event(["DPP-RESPONSE-PENDING"], timeout=5)
620    if ev is None:
621        raise Exception("Pending response not reported")
622    ev = hapd.wait_event(["DPP-SCAN-PEER-QR-CODE"], timeout=5)
623    if ev is None:
624        raise Exception("QR Code scan for mutual authentication not requested")
625
626    logger.info("AP scans QR Code")
627    hapd.dpp_qr_code(uri0)
628
629    wait_auth_success(hapd, dev[0], stop_responder=True)
630
631def test_dpp_qr_code_listen_continue(dev, apdev):
632    """DPP QR Code and listen operation needing continuation"""
633    check_dpp_capab(dev[0])
634    check_dpp_capab(dev[1])
635    logger.info("dev0 displays QR Code")
636    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
637    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
638    dev[0].dpp_listen(2412)
639    logger.info("Wait for listen to expire and get restarted")
640    time.sleep(5.5)
641    logger.info("dev1 scans QR Code and initiates DPP Authentication")
642    dev[1].dpp_auth_init(uri=uri0)
643    wait_auth_success(dev[0], dev[1], stop_responder=True)
644
645def test_dpp_qr_code_auth_initiator_enrollee(dev, apdev):
646    """DPP QR Code and authentication exchange (Initiator in Enrollee role)"""
647    try:
648        run_dpp_qr_code_auth_initiator_enrollee(dev, apdev)
649    finally:
650        dev[0].set("gas_address3", "0")
651        dev[1].set("gas_address3", "0")
652
653def run_dpp_qr_code_auth_initiator_enrollee(dev, apdev):
654    check_dpp_capab(dev[0])
655    check_dpp_capab(dev[1])
656    dev[0].request("SET gas_address3 1")
657    dev[1].request("SET gas_address3 1")
658    logger.info("dev0 displays QR Code")
659    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
660    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
661    logger.info("dev1 scans QR Code and initiates DPP Authentication")
662    dev[0].dpp_listen(2412)
663    dev[1].dpp_auth_init(uri=uri0, role="enrollee")
664    wait_auth_success(dev[0], dev[1], configurator=dev[0], enrollee=dev[1],
665                      allow_enrollee_failure=True, stop_responder=True)
666
667def test_dpp_qr_code_auth_initiator_either_1(dev, apdev):
668    """DPP QR Code and authentication exchange (Initiator in either role)"""
669    run_dpp_qr_code_auth_initiator_either(dev, apdev, None, dev[1], dev[0])
670
671def test_dpp_qr_code_auth_initiator_either_2(dev, apdev):
672    """DPP QR Code and authentication exchange (Initiator in either role)"""
673    run_dpp_qr_code_auth_initiator_either(dev, apdev, "enrollee",
674                                          dev[1], dev[0])
675
676def test_dpp_qr_code_auth_initiator_either_3(dev, apdev):
677    """DPP QR Code and authentication exchange (Initiator in either role)"""
678    run_dpp_qr_code_auth_initiator_either(dev, apdev, "configurator",
679                                          dev[0], dev[1])
680
681def run_dpp_qr_code_auth_initiator_either(dev, apdev, resp_role,
682                                          conf_dev, enrollee_dev):
683    check_dpp_capab(dev[0])
684    check_dpp_capab(dev[1])
685    logger.info("dev0 displays QR Code")
686    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
687    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
688    logger.info("dev1 scans QR Code and initiates DPP Authentication")
689    dev[0].dpp_listen(2412, role=resp_role)
690    dev[1].dpp_auth_init(uri=uri0, role="either")
691    wait_auth_success(dev[0], dev[1], configurator=conf_dev,
692                      enrollee=enrollee_dev, allow_enrollee_failure=True,
693                      stop_responder=True)
694
695def run_init_incompatible_roles(dev, role="enrollee"):
696    check_dpp_capab(dev[0])
697    check_dpp_capab(dev[1])
698    logger.info("dev0 displays QR Code")
699    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
700    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
701
702    logger.info("dev1 scans QR Code")
703    id1 = dev[1].dpp_qr_code(uri0)
704
705    logger.info("dev1 initiates DPP Authentication")
706    dev[0].dpp_listen(2412, role=role)
707    return id1
708
709def test_dpp_qr_code_auth_incompatible_roles(dev, apdev):
710    """DPP QR Code and authentication exchange (incompatible roles)"""
711    id1 = run_init_incompatible_roles(dev)
712    dev[1].dpp_auth_init(peer=id1, role="enrollee")
713    ev = dev[1].wait_event(["DPP-NOT-COMPATIBLE"], timeout=5)
714    if ev is None:
715        raise Exception("DPP-NOT-COMPATIBLE event on initiator timed out")
716    ev = dev[0].wait_event(["DPP-NOT-COMPATIBLE"], timeout=1)
717    if ev is None:
718        raise Exception("DPP-NOT-COMPATIBLE event on responder timed out")
719    dev[1].dpp_auth_init(peer=id1, role="configurator")
720    wait_auth_success(dev[0], dev[1], stop_responder=True)
721
722def test_dpp_qr_code_auth_incompatible_roles2(dev, apdev):
723    """DPP QR Code and authentication exchange (incompatible roles 2)"""
724    id1 = run_init_incompatible_roles(dev, role="configurator")
725    dev[1].dpp_auth_init(peer=id1, role="configurator")
726    ev = dev[1].wait_event(["DPP-NOT-COMPATIBLE"], timeout=5)
727    if ev is None:
728        raise Exception("DPP-NOT-COMPATIBLE event on initiator timed out")
729    ev = dev[0].wait_event(["DPP-NOT-COMPATIBLE"], timeout=1)
730    if ev is None:
731        raise Exception("DPP-NOT-COMPATIBLE event on responder timed out")
732
733def test_dpp_qr_code_auth_incompatible_roles_failure(dev, apdev):
734    """DPP QR Code and authentication exchange (incompatible roles failure)"""
735    id1 = run_init_incompatible_roles(dev, role="configurator")
736    with alloc_fail(dev[0], 1, "dpp_auth_build_resp_status"):
737        dev[1].dpp_auth_init(peer=id1, role="configurator")
738        ev = dev[0].wait_event(["DPP-NOT-COMPATIBLE"], timeout=1)
739        if ev is None:
740            raise Exception("DPP-NOT-COMPATIBLE event on responder timed out")
741
742def test_dpp_qr_code_auth_incompatible_roles_failure2(dev, apdev):
743    """DPP QR Code and authentication exchange (incompatible roles failure 2)"""
744    id1 = run_init_incompatible_roles(dev, role="configurator")
745    with alloc_fail(dev[1], 1, "dpp_auth_resp_rx_status"):
746        dev[1].dpp_auth_init(peer=id1, role="configurator")
747        wait_fail_trigger(dev[1], "GET_ALLOC_FAIL")
748
749def test_dpp_qr_code_auth_incompatible_roles_failure3(dev, apdev):
750    """DPP QR Code and authentication exchange (incompatible roles failure 3)"""
751    id1 = run_init_incompatible_roles(dev, role="configurator")
752    with fail_test(dev[1], 1, "dpp_auth_resp_rx_status"):
753        dev[1].dpp_auth_init(peer=id1, role="configurator")
754        wait_dpp_fail(dev[1], "AES-SIV decryption failed")
755
756def test_dpp_qr_code_auth_neg_chan(dev, apdev):
757    """DPP QR Code and authentication exchange with requested different channel"""
758    check_dpp_capab(dev[0])
759    check_dpp_capab(dev[1])
760    conf_id = dev[1].dpp_configurator_add()
761    logger.info("dev0 displays QR Code")
762    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
763    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
764    logger.info("dev1 scans QR Code and initiates DPP Authentication")
765    dev[0].dpp_listen(2412)
766    dev[1].dpp_auth_init(uri=uri0, conf="sta-dpp", neg_freq=2462,
767                         configurator=conf_id)
768
769    ev = dev[1].wait_event(["DPP-TX "], timeout=5)
770    if ev is None:
771        raise Exception("DPP Authentication Request not sent")
772    if "freq=2412 type=0" not in ev:
773        raise Exception("Unexpected TX data for Authentication Request: " + ev)
774
775    ev = dev[0].wait_event(["DPP-RX"], timeout=5)
776    if ev is None:
777        raise Exception("DPP Authentication Request not received")
778    if "freq=2412 type=0" not in ev:
779        raise Exception("Unexpected RX data for Authentication Request: " + ev)
780
781    ev = dev[1].wait_event(["DPP-TX-STATUS"], timeout=5)
782    if ev is None:
783        raise Exception("TX status for DPP Authentication Request not reported")
784    if "freq=2412 result=SUCCESS" not in ev:
785        raise Exception("Unexpected TX status for Authentication Request: " + ev)
786
787    ev = dev[0].wait_event(["DPP-TX "], timeout=5)
788    if ev is None:
789        raise Exception("DPP Authentication Response not sent")
790    if "freq=2462 type=1" not in ev:
791        raise Exception("Unexpected TX data for Authentication Response: " + ev)
792
793    ev = dev[1].wait_event(["DPP-RX"], timeout=5)
794    if ev is None:
795        raise Exception("DPP Authentication Response not received")
796    if "freq=2462 type=1" not in ev:
797        raise Exception("Unexpected RX data for Authentication Response: " + ev)
798
799    ev = dev[0].wait_event(["DPP-TX-STATUS"], timeout=5)
800    if ev is None:
801        raise Exception("TX status for DPP Authentication Response not reported")
802    if "freq=2462 result=SUCCESS" not in ev:
803        raise Exception("Unexpected TX status for Authentication Response: " + ev)
804
805    ev = dev[1].wait_event(["DPP-TX "], timeout=5)
806    if ev is None:
807        raise Exception("DPP Authentication Confirm not sent")
808    if "freq=2462 type=2" not in ev:
809        raise Exception("Unexpected TX data for Authentication Confirm: " + ev)
810
811    ev = dev[0].wait_event(["DPP-RX"], timeout=5)
812    if ev is None:
813        raise Exception("DPP Authentication Confirm not received")
814    if "freq=2462 type=2" not in ev:
815        raise Exception("Unexpected RX data for Authentication Confirm: " + ev)
816
817    ev = dev[1].wait_event(["DPP-TX-STATUS"], timeout=5)
818    if ev is None:
819        raise Exception("TX status for DPP Authentication Confirm not reported")
820    if "freq=2462 result=SUCCESS" not in ev:
821        raise Exception("Unexpected TX status for Authentication Confirm: " + ev)
822
823    wait_auth_success(dev[0], dev[1], configurator=dev[1], enrollee=dev[0],
824                      stop_responder=True)
825
826def test_dpp_config_legacy(dev, apdev):
827    """DPP Config Object for legacy network using passphrase"""
828    check_dpp_capab(dev[1])
829    conf = '{"wi-fi_tech":"infra", "discovery":{"ssid":"test"},"cred":{"akm":"psk","pass":"secret passphrase"}}'
830    dev[1].set("dpp_config_obj_override", conf)
831    run_dpp_qr_code_auth_unicast(dev, apdev, "prime256v1",
832                                 require_conf_success=True)
833
834def test_dpp_config_legacy_psk_hex(dev, apdev):
835    """DPP Config Object for legacy network using PSK"""
836    check_dpp_capab(dev[1])
837    conf = '{"wi-fi_tech":"infra", "discovery":{"ssid":"test"},"cred":{"akm":"psk","psk_hex":"' + 32*"12" + '"}}'
838    dev[1].set("dpp_config_obj_override", conf)
839    run_dpp_qr_code_auth_unicast(dev, apdev, "prime256v1",
840                                 require_conf_success=True)
841
842def test_dpp_config_fragmentation(dev, apdev):
843    """DPP Config Object for legacy network requiring fragmentation"""
844    check_dpp_capab(dev[1])
845    conf = '{"wi-fi_tech":"infra", "discovery":{"ssid":"test"},"cred":{"akm":"psk","pass":"secret passphrase"}}' + 3000*' '
846    dev[1].set("dpp_config_obj_override", conf)
847    run_dpp_qr_code_auth_unicast(dev, apdev, "prime256v1",
848                                 require_conf_success=True)
849
850def test_dpp_config_legacy_gen(dev, apdev):
851    """Generate DPP Config Object for legacy network"""
852    run_dpp_qr_code_auth_unicast(dev, apdev, "prime256v1",
853                                 init_extra="conf=sta-psk pass=%s" % binascii.hexlify(b"passphrase").decode(),
854                                 require_conf_success=True)
855
856def test_dpp_config_legacy_gen_psk(dev, apdev):
857    """Generate DPP Config Object for legacy network (PSK)"""
858    run_dpp_qr_code_auth_unicast(dev, apdev, "prime256v1",
859                                 init_extra="conf=sta-psk psk=0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
860                                 require_conf_success=True)
861
862def test_dpp_config_dpp_gen_prime256v1(dev, apdev):
863    """Generate DPP Config Object for DPP network (P-256)"""
864    run_dpp_qr_code_auth_unicast(dev, apdev, "prime256v1",
865                                 init_extra="conf=sta-dpp",
866                                 require_conf_success=True,
867                                 configurator=True)
868
869def test_dpp_config_dpp_gen_secp384r1(dev, apdev):
870    """Generate DPP Config Object for DPP network (P-384)"""
871    run_dpp_qr_code_auth_unicast(dev, apdev, "secp384r1",
872                                 init_extra="conf=sta-dpp",
873                                 require_conf_success=True,
874                                 configurator=True)
875
876def test_dpp_config_dpp_gen_secp521r1(dev, apdev):
877    """Generate DPP Config Object for DPP network (P-521)"""
878    run_dpp_qr_code_auth_unicast(dev, apdev, "secp521r1",
879                                 init_extra="conf=sta-dpp",
880                                 require_conf_success=True,
881                                 configurator=True)
882
883def test_dpp_config_dpp_gen_prime256v1_prime256v1(dev, apdev):
884    """Generate DPP Config Object for DPP network (P-256 + P-256)"""
885    run_dpp_qr_code_auth_unicast(dev, apdev, "prime256v1",
886                                 init_extra="conf=sta-dpp",
887                                 require_conf_success=True,
888                                 configurator=True,
889                                 conf_curve="prime256v1")
890
891def test_dpp_config_dpp_gen_prime256v1_secp384r1(dev, apdev):
892    """Generate DPP Config Object for DPP network (P-256 + P-384)"""
893    run_dpp_qr_code_auth_unicast(dev, apdev, "prime256v1",
894                                 init_extra="conf=sta-dpp",
895                                 require_conf_success=True,
896                                 configurator=True,
897                                 conf_curve="secp384r1")
898
899def test_dpp_config_dpp_gen_prime256v1_secp521r1(dev, apdev):
900    """Generate DPP Config Object for DPP network (P-256 + P-521)"""
901    run_dpp_qr_code_auth_unicast(dev, apdev, "prime256v1",
902                                 init_extra="conf=sta-dpp",
903                                 require_conf_success=True,
904                                 configurator=True,
905                                 conf_curve="secp521r1")
906
907def test_dpp_config_dpp_gen_secp384r1_prime256v1(dev, apdev):
908    """Generate DPP Config Object for DPP network (P-384 + P-256)"""
909    run_dpp_qr_code_auth_unicast(dev, apdev, "secp384r1",
910                                 init_extra="conf=sta-dpp",
911                                 require_conf_success=True,
912                                 configurator=True,
913                                 conf_curve="prime256v1")
914
915def test_dpp_config_dpp_gen_secp384r1_secp384r1(dev, apdev):
916    """Generate DPP Config Object for DPP network (P-384 + P-384)"""
917    run_dpp_qr_code_auth_unicast(dev, apdev, "secp384r1",
918                                 init_extra="conf=sta-dpp",
919                                 require_conf_success=True,
920                                 configurator=True,
921                                 conf_curve="secp384r1")
922
923def test_dpp_config_dpp_gen_secp384r1_secp521r1(dev, apdev):
924    """Generate DPP Config Object for DPP network (P-384 + P-521)"""
925    run_dpp_qr_code_auth_unicast(dev, apdev, "secp384r1",
926                                 init_extra="conf=sta-dpp",
927                                 require_conf_success=True,
928                                 configurator=True,
929                                 conf_curve="secp521r1")
930
931def test_dpp_config_dpp_gen_secp521r1_prime256v1(dev, apdev):
932    """Generate DPP Config Object for DPP network (P-521 + P-256)"""
933    run_dpp_qr_code_auth_unicast(dev, apdev, "secp521r1",
934                                 init_extra="conf=sta-dpp",
935                                 require_conf_success=True,
936                                 configurator=True,
937                                 conf_curve="prime256v1")
938
939def test_dpp_config_dpp_gen_secp521r1_secp384r1(dev, apdev):
940    """Generate DPP Config Object for DPP network (P-521 + P-384)"""
941    run_dpp_qr_code_auth_unicast(dev, apdev, "secp521r1",
942                                 init_extra="conf=sta-dpp",
943                                 require_conf_success=True,
944                                 configurator=True,
945                                 conf_curve="secp384r1")
946
947def test_dpp_config_dpp_gen_secp521r1_secp521r1(dev, apdev):
948    """Generate DPP Config Object for DPP network (P-521 + P-521)"""
949    run_dpp_qr_code_auth_unicast(dev, apdev, "secp521r1",
950                                 init_extra="conf=sta-dpp",
951                                 require_conf_success=True,
952                                 configurator=True,
953                                 conf_curve="secp521r1")
954
955def test_dpp_config_dpp_gen_expiry(dev, apdev):
956    """Generate DPP Config Object for DPP network with expiry value"""
957    run_dpp_qr_code_auth_unicast(dev, apdev, "prime256v1",
958                                 init_extra="conf=sta-dpp expiry=%d" % (time.time() + 1000),
959                                 require_conf_success=True,
960                                 configurator=True)
961
962def test_dpp_config_dpp_gen_expired_key(dev, apdev):
963    """Generate DPP Config Object for DPP network with expiry value"""
964    run_dpp_qr_code_auth_unicast(dev, apdev, "prime256v1",
965                                 init_extra="conf=sta-dpp expiry=%d" % (time.time() - 10),
966                                 require_conf_failure=True,
967                                 configurator=True)
968
969def test_dpp_config_dpp_override_prime256v1(dev, apdev):
970    """DPP Config Object override (P-256)"""
971    check_dpp_capab(dev[0])
972    check_dpp_capab(dev[1])
973    conf = '{"wi-fi_tech":"infra","discovery":{"ssid":"test"},"cred":{"akm":"dpp","signedConnector":"eyJ0eXAiOiJkcHBDb24iLCJraWQiOiJUbkdLaklsTlphYXRyRUFZcmJiamlCNjdyamtMX0FHVldYTzZxOWhESktVIiwiYWxnIjoiRVMyNTYifQ.eyJncm91cHMiOlt7Imdyb3VwSWQiOiIqIiwibmV0Um9sZSI6InN0YSJ9XSwibmV0QWNjZXNzS2V5Ijp7Imt0eSI6IkVDIiwiY3J2IjoiUC0yNTYiLCJ4IjoiYVRGNEpFR0lQS1NaMFh2OXpkQ01qbS10bjVYcE1zWUlWWjl3eVNBejFnSSIsInkiOiJRR2NIV0FfNnJiVTlYRFhBenRvWC1NNVEzc3VUbk1hcUVoVUx0bjdTU1h3In19._sm6YswxMf6hJLVTyYoU1uYUeY2VVkUNjrzjSiEhY42StD_RWowStEE-9CRsdCvLmsTptZ72_g40vTFwdId20A","csign":{"kty":"EC","crv":"P-256","x":"W4-Y5N1Pkos3UWb9A5qme0KUYRtY3CVUpekx_MapZ9s","y":"Et-M4NSF4NGjvh2VCh4B1sJ9eSCZ4RNzP2DBdP137VE","kid":"TnGKjIlNZaatrEAYrbbjiB67rjkL_AGVWXO6q9hDJKU"}}}'
974    dev[0].set("dpp_ignore_netaccesskey_mismatch", "1")
975    dev[1].set("dpp_config_obj_override", conf)
976    run_dpp_qr_code_auth_unicast(dev, apdev, "prime256v1",
977                                 require_conf_success=True)
978
979def test_dpp_config_dpp_override_secp384r1(dev, apdev):
980    """DPP Config Object override (P-384)"""
981    check_dpp_capab(dev[0])
982    check_dpp_capab(dev[1])
983    conf = '{"wi-fi_tech":"infra","discovery":{"ssid":"test"},"cred":{"akm":"dpp","signedConnector":"eyJ0eXAiOiJkcHBDb24iLCJraWQiOiJabi1iMndjbjRLM2pGQklkYmhGZkpVTHJTXzdESS0yMWxFQi02R3gxNjl3IiwiYWxnIjoiRVMzODQifQ.eyJncm91cHMiOlt7Imdyb3VwSWQiOiIqIiwibmV0Um9sZSI6InN0YSJ9XSwibmV0QWNjZXNzS2V5Ijp7Imt0eSI6IkVDIiwiY3J2IjoiUC0zODQiLCJ4IjoickdrSGg1UUZsOUtfWjdqYUZkVVhmbThoY1RTRjM1b25Xb1NIRXVsbVNzWW9oX1RXZGpoRjhiVGdiS0ZRN2tBViIsInkiOiJBbU1QVDA5VmFENWpGdzMwTUFKQlp2VkZXeGNlVVlKLXR5blQ0bVJ5N0xOZWxhZ0dEWHpfOExaRlpOU2FaNUdLIn19.Yn_F7m-bbOQ5PlaYQJ9-1qsuqYQ6V-rAv8nWw1COKiCYwwbt3WFBJ8DljY0dPrlg5CHJC4saXwkytpI-CpELW1yUdzYb4Lrun07d20Eo_g10ICyOl5sqQCAUElKMe_Xr","csign":{"kty":"EC","crv":"P-384","x":"dmTyXXiPV2Y8a01fujL-jo08gvzyby23XmzOtzjAiujKQZZgPJsbhfEKrZDlc6ey","y":"H5Z0av5c7bqInxYb2_OOJdNiMhVf3zlcULR0516ZZitOY4U31KhL4wl4KGV7g2XW","kid":"Zn-b2wcn4K3jFBIdbhFfJULrS_7DI-21lEB-6Gx169w"}}}'
984    dev[0].set("dpp_ignore_netaccesskey_mismatch", "1")
985    dev[1].set("dpp_config_obj_override", conf)
986    run_dpp_qr_code_auth_unicast(dev, apdev, "secp384r1",
987                                 require_conf_success=True)
988
989def test_dpp_config_dpp_override_secp521r1(dev, apdev):
990    """DPP Config Object override (P-521)"""
991    check_dpp_capab(dev[0])
992    check_dpp_capab(dev[1])
993    conf = '{"wi-fi_tech":"infra","discovery":{"ssid":"test"},"cred":{"akm":"dpp","signedConnector":"eyJ0eXAiOiJkcHBDb24iLCJraWQiOiJMZkhKY3hnV2ZKcG1uS2IwenZRT0F2VDB2b0ZKc0JjZnBmYzgxY3Y5ZXFnIiwiYWxnIjoiRVM1MTIifQ.eyJncm91cHMiOlt7Imdyb3VwSWQiOiIqIiwibmV0Um9sZSI6InN0YSJ9XSwibmV0QWNjZXNzS2V5Ijp7Imt0eSI6IkVDIiwiY3J2IjoiUC01MjEiLCJ4IjoiQVJlUFBrMFNISkRRR2NWbnlmM3lfbTlaQllHNjFJeElIbDN1NkdwRHVhMkU1WVd4TE1BSUtMMnZuUGtlSGFVRXljRmZaZlpYZ2JlNkViUUxMVkRVUm1VUSIsInkiOiJBWUtaYlNwUkFFNjJVYm9YZ2c1ZWRBVENzbEpzTlpwcm9RR1dUcW9Md04weXkzQkVoT3ZRZmZrOWhaR2lKZ295TzFobXFRRVRrS0pXb2tIYTBCQUpLSGZtIn19.ACEZLyPk13cM_OFScpLoCElQ2t1sxq5z2d_W_3_QslTQQe5SFiH_o8ycL4632YLAH4RV0gZcMKKRMtZdHgBYHjkzASDqgY-_aYN2SBmpfl8hw0YdDlUJWX3DJf-ofqNAlTbnGmhpSg69cEAhFn41Xgvx2MdwYcPVncxxESVOtWl5zNLK","csign":{"kty":"EC","crv":"P-521","x":"ADiOI_YJOAipEXHB-SpGl4KqokX8m8h3BVYCc8dgiwssZ061-nIIY3O1SIO6Re4Jjfy53RPgzDG6jitOgOGLtzZs","y":"AZKggKaQi0ExutSpJAU3-lqDV03sBQLA9C7KabfWoAn8qD6Vk4jU0WAJdt-wBBTF9o1nVuiqS2OxMVYrxN4lOz79","kid":"LfHJcxgWfJpmnKb0zvQOAvT0voFJsBcfpfc81cv9eqg"}}}'
994    dev[0].set("dpp_ignore_netaccesskey_mismatch", "1")
995    dev[1].set("dpp_config_obj_override", conf)
996    run_dpp_qr_code_auth_unicast(dev, apdev, "secp521r1",
997                                 require_conf_success=True)
998
999def test_dpp_config_override_objects(dev, apdev):
1000    """Generate DPP Config Object and override objects)"""
1001    check_dpp_capab(dev[1])
1002    discovery = '{\n"ssid":"mywifi"\n}'
1003    groups = '[\n  {"groupId":"home","netRole":"sta"},\n  {"groupId":"cottage","netRole":"sta"}\n]'
1004    dev[1].set("dpp_discovery_override", discovery)
1005    dev[1].set("dpp_groups_override", groups)
1006    run_dpp_qr_code_auth_unicast(dev, apdev, "prime256v1",
1007                                 init_extra="conf=sta-dpp",
1008                                 require_conf_success=True,
1009                                 configurator=True)
1010
1011def build_conf_obj(kty="EC", crv="P-256",
1012                   x="W4-Y5N1Pkos3UWb9A5qme0KUYRtY3CVUpekx_MapZ9s",
1013                   y="Et-M4NSF4NGjvh2VCh4B1sJ9eSCZ4RNzP2DBdP137VE",
1014                   kid="TnGKjIlNZaatrEAYrbbjiB67rjkL_AGVWXO6q9hDJKU",
1015                   prot_hdr='{"typ":"dppCon","kid":"TnGKjIlNZaatrEAYrbbjiB67rjkL_AGVWXO6q9hDJKU","alg":"ES256"}',
1016                   signed_connector=None,
1017                   no_signed_connector=False,
1018                   csign=True):
1019    conf = '{"wi-fi_tech":"infra","discovery":{"ssid":"test"},"cred":{'
1020    conf += '"akm":"dpp",'
1021
1022    if signed_connector:
1023        conn = signed_connector
1024        conf += '"signedConnector":"%s",' % conn
1025    elif not no_signed_connector:
1026        payload = '{"groups":[{"groupId":"*","netRole":"sta"}],"netAccessKey":{"kty":"EC","crv":"P-256","x":"aTF4JEGIPKSZ0Xv9zdCMjm-tn5XpMsYIVZ9wySAz1gI","y":"QGcHWA_6rbU9XDXAztoX-M5Q3suTnMaqEhULtn7SSXw"}}'
1027        sign = "_sm6YswxMf6hJLVTyYoU1uYUeY2VVkUNjrzjSiEhY42StD_RWowStEE-9CRsdCvLmsTptZ72_g40vTFwdId20A"
1028        conn = base64.urlsafe_b64encode(prot_hdr.encode()).decode().rstrip('=') + '.'
1029        conn += base64.urlsafe_b64encode(payload.encode()).decode().rstrip('=') + '.'
1030        conn += sign
1031        conf += '"signedConnector":"%s",' % conn
1032
1033    if csign:
1034        conf += '"csign":{'
1035        if kty:
1036            conf += '"kty":"%s",' % kty
1037        if crv:
1038            conf += '"crv":"%s",' % crv
1039        if x:
1040            conf += '"x":"%s",' % x
1041        if y:
1042            conf += '"y":"%s",' % y
1043        if kid:
1044            conf += '"kid":"%s"' % kid
1045        conf = conf.rstrip(',')
1046        conf += '}'
1047    else:
1048        conf = conf.rstrip(',')
1049
1050    conf += '}}'
1051
1052    return conf
1053
1054def run_dpp_config_error(dev, apdev, conf,
1055                         skip_net_access_key_mismatch=True,
1056                         conf_failure=True):
1057    check_dpp_capab(dev[0])
1058    check_dpp_capab(dev[1])
1059    if skip_net_access_key_mismatch:
1060        dev[0].set("dpp_ignore_netaccesskey_mismatch", "1")
1061    dev[1].set("dpp_config_obj_override", conf)
1062    run_dpp_qr_code_auth_unicast(dev, apdev, "prime256v1",
1063                                 require_conf_success=not conf_failure,
1064                                 require_conf_failure=conf_failure)
1065
1066def test_dpp_config_jwk_error_no_kty(dev, apdev):
1067    """DPP Config Object JWK error - no kty"""
1068    run_dpp_config_error(dev, apdev, build_conf_obj(kty=None))
1069
1070def test_dpp_config_jwk_error_unexpected_kty(dev, apdev):
1071    """DPP Config Object JWK error - unexpected kty"""
1072    run_dpp_config_error(dev, apdev, build_conf_obj(kty="unknown"))
1073
1074def test_dpp_config_jwk_error_no_crv(dev, apdev):
1075    """DPP Config Object JWK error - no crv"""
1076    run_dpp_config_error(dev, apdev, build_conf_obj(crv=None))
1077
1078def test_dpp_config_jwk_error_unsupported_crv(dev, apdev):
1079    """DPP Config Object JWK error - unsupported curve"""
1080    run_dpp_config_error(dev, apdev, build_conf_obj(crv="unsupported"))
1081
1082def test_dpp_config_jwk_error_no_x(dev, apdev):
1083    """DPP Config Object JWK error - no x"""
1084    run_dpp_config_error(dev, apdev, build_conf_obj(x=None))
1085
1086def test_dpp_config_jwk_error_invalid_x(dev, apdev):
1087    """DPP Config Object JWK error - invalid x"""
1088    run_dpp_config_error(dev, apdev, build_conf_obj(x="MTIz"))
1089
1090def test_dpp_config_jwk_error_no_y(dev, apdev):
1091    """DPP Config Object JWK error - no y"""
1092    run_dpp_config_error(dev, apdev, build_conf_obj(y=None))
1093
1094def test_dpp_config_jwk_error_invalid_y(dev, apdev):
1095    """DPP Config Object JWK error - invalid y"""
1096    run_dpp_config_error(dev, apdev, build_conf_obj(y="MTIz"))
1097
1098def test_dpp_config_jwk_error_invalid_xy(dev, apdev):
1099    """DPP Config Object JWK error - invalid x,y"""
1100    conf = build_conf_obj(x="MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY",
1101                          y="MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY")
1102    run_dpp_config_error(dev, apdev, conf)
1103
1104def test_dpp_config_jwk_error_no_kid(dev, apdev):
1105    """DPP Config Object JWK error - no kid"""
1106    # csign kid is optional field, so this results in success
1107    run_dpp_config_error(dev, apdev, build_conf_obj(kid=None),
1108                         conf_failure=False)
1109
1110def test_dpp_config_jws_error_prot_hdr_not_an_object(dev, apdev):
1111    """DPP Config Object JWS error - protected header not an object"""
1112    run_dpp_config_error(dev, apdev, build_conf_obj(prot_hdr="1"))
1113
1114def test_dpp_config_jws_error_prot_hdr_no_typ(dev, apdev):
1115    """DPP Config Object JWS error - protected header - no typ"""
1116    prot_hdr = '{"kid":"TnGKjIlNZaatrEAYrbbjiB67rjkL_AGVWXO6q9hDJKU","alg":"ES256"}'
1117    run_dpp_config_error(dev, apdev, build_conf_obj(prot_hdr=prot_hdr))
1118
1119def test_dpp_config_jws_error_prot_hdr_unsupported_typ(dev, apdev):
1120    """DPP Config Object JWS error - protected header - unsupported typ"""
1121    prot_hdr = '{"typ":"unsupported","kid":"TnGKjIlNZaatrEAYrbbjiB67rjkL_AGVWXO6q9hDJKU","alg":"ES256"}'
1122    run_dpp_config_error(dev, apdev, build_conf_obj(prot_hdr=prot_hdr))
1123
1124def test_dpp_config_jws_error_prot_hdr_no_alg(dev, apdev):
1125    """DPP Config Object JWS error - protected header - no alg"""
1126    prot_hdr = '{"typ":"dppCon","kid":"TnGKjIlNZaatrEAYrbbjiB67rjkL_AGVWXO6q9hDJKU"}'
1127    run_dpp_config_error(dev, apdev, build_conf_obj(prot_hdr=prot_hdr))
1128
1129def test_dpp_config_jws_error_prot_hdr_unexpected_alg(dev, apdev):
1130    """DPP Config Object JWS error - protected header - unexpected alg"""
1131    prot_hdr = '{"typ":"dppCon","kid":"TnGKjIlNZaatrEAYrbbjiB67rjkL_AGVWXO6q9hDJKU","alg":"unexpected"}'
1132    run_dpp_config_error(dev, apdev, build_conf_obj(prot_hdr=prot_hdr))
1133
1134def test_dpp_config_jws_error_prot_hdr_no_kid(dev, apdev):
1135    """DPP Config Object JWS error - protected header - no kid"""
1136    prot_hdr = '{"typ":"dppCon","alg":"ES256"}'
1137    run_dpp_config_error(dev, apdev, build_conf_obj(prot_hdr=prot_hdr))
1138
1139def test_dpp_config_jws_error_prot_hdr_unexpected_kid(dev, apdev):
1140    """DPP Config Object JWS error - protected header - unexpected kid"""
1141    prot_hdr = '{"typ":"dppCon","kid":"MTIz","alg":"ES256"}'
1142    run_dpp_config_error(dev, apdev, build_conf_obj(prot_hdr=prot_hdr))
1143
1144def test_dpp_config_signed_connector_error_no_dot_1(dev, apdev):
1145    """DPP Config Object signedConnector error - no dot(1)"""
1146    conn = "MTIz"
1147    run_dpp_config_error(dev, apdev, build_conf_obj(signed_connector=conn))
1148
1149def test_dpp_config_signed_connector_error_no_dot_2(dev, apdev):
1150    """DPP Config Object signedConnector error - no dot(2)"""
1151    conn = "eyJ0eXAiOiJkcHBDb24iLCJraWQiOiJUbkdLaklsTlphYXRyRUFZcmJiamlCNjdyamtMX0FHVldYTzZxOWhESktVIiwiYWxnIjoiRVMyNTYifQ.MTIz"
1152    run_dpp_config_error(dev, apdev, build_conf_obj(signed_connector=conn))
1153
1154def test_dpp_config_signed_connector_error_unexpected_signature_len(dev, apdev):
1155    """DPP Config Object signedConnector error - unexpected signature length"""
1156    conn = "eyJ0eXAiOiJkcHBDb24iLCJraWQiOiJUbkdLaklsTlphYXRyRUFZcmJiamlCNjdyamtMX0FHVldYTzZxOWhESktVIiwiYWxnIjoiRVMyNTYifQ.MTIz.MTIz"
1157    run_dpp_config_error(dev, apdev, build_conf_obj(signed_connector=conn))
1158
1159def test_dpp_config_signed_connector_error_invalid_signature_der(dev, apdev):
1160    """DPP Config Object signedConnector error - invalid signature DER"""
1161    conn = "eyJ0eXAiOiJkcHBDb24iLCJraWQiOiJUbkdLaklsTlphYXRyRUFZcmJiamlCNjdyamtMX0FHVldYTzZxOWhESktVIiwiYWxnIjoiRVMyNTYifQ.MTIz.MTI"
1162    run_dpp_config_error(dev, apdev, build_conf_obj(signed_connector=conn))
1163
1164def test_dpp_config_no_csign(dev, apdev):
1165    """DPP Config Object error - no csign"""
1166    run_dpp_config_error(dev, apdev, build_conf_obj(csign=False))
1167
1168def test_dpp_config_no_signed_connector(dev, apdev):
1169    """DPP Config Object error - no signedConnector"""
1170    run_dpp_config_error(dev, apdev, build_conf_obj(no_signed_connector=True))
1171
1172def test_dpp_config_unexpected_signed_connector_char(dev, apdev):
1173    """DPP Config Object error - unexpected signedConnector character"""
1174    run_dpp_config_error(dev, apdev, build_conf_obj(signed_connector='a\nb'))
1175
1176def test_dpp_config_root_not_an_object(dev, apdev):
1177    """DPP Config Object error - root not an object"""
1178    conf = "1"
1179    run_dpp_config_error(dev, apdev, conf)
1180
1181def test_dpp_config_no_wi_fi_tech(dev, apdev):
1182    """DPP Config Object error - no wi-fi_tech"""
1183    conf = "{}"
1184    run_dpp_config_error(dev, apdev, conf)
1185
1186def test_dpp_config_unsupported_wi_fi_tech(dev, apdev):
1187    """DPP Config Object error - unsupported wi-fi_tech"""
1188    conf = '{"wi-fi_tech":"unsupported"}'
1189    run_dpp_config_error(dev, apdev, conf)
1190
1191def test_dpp_config_no_discovery(dev, apdev):
1192    """DPP Config Object error - no discovery"""
1193    conf = '{"wi-fi_tech":"infra"}'
1194    run_dpp_config_error(dev, apdev, conf)
1195
1196def test_dpp_config_no_discovery_ssid(dev, apdev):
1197    """DPP Config Object error - no discovery::ssid"""
1198    conf = '{"wi-fi_tech":"infra","discovery":{}}'
1199    run_dpp_config_error(dev, apdev, conf)
1200
1201def test_dpp_config_too_long_discovery_ssid(dev, apdev):
1202    """DPP Config Object error - too long discovery::ssid"""
1203    conf = '{"wi-fi_tech":"infra","discovery":{"ssid":"%s"}}' % (33*'A')
1204    run_dpp_config_error(dev, apdev, conf)
1205
1206def test_dpp_config_no_cred(dev, apdev):
1207    """DPP Config Object error - no cred"""
1208    conf = '{"wi-fi_tech":"infra","discovery":{"ssid":"test"}}'
1209    run_dpp_config_error(dev, apdev, conf)
1210
1211def test_dpp_config_no_cred_akm(dev, apdev):
1212    """DPP Config Object error - no cred::akm"""
1213    conf = '{"wi-fi_tech":"infra","discovery":{"ssid":"test"},"cred":{}}'
1214    run_dpp_config_error(dev, apdev, conf)
1215
1216def test_dpp_config_unsupported_cred_akm(dev, apdev):
1217    """DPP Config Object error - unsupported cred::akm"""
1218    conf = '{"wi-fi_tech":"infra","discovery":{"ssid":"test"},"cred":{"akm":"unsupported"}}'
1219    run_dpp_config_error(dev, apdev, conf)
1220
1221def test_dpp_config_error_legacy_no_pass(dev, apdev):
1222    """DPP Config Object legacy error - no pass/psk"""
1223    conf = '{"wi-fi_tech":"infra","discovery":{"ssid":"test"},"cred":{"akm":"psk"}}'
1224    run_dpp_config_error(dev, apdev, conf)
1225
1226def test_dpp_config_error_legacy_too_short_pass(dev, apdev):
1227    """DPP Config Object legacy error - too short pass/psk"""
1228    conf = '{"wi-fi_tech":"infra","discovery":{"ssid":"test"},"cred":{"akm":"psk","pass":"1"}}'
1229    run_dpp_config_error(dev, apdev, conf)
1230
1231def test_dpp_config_error_legacy_too_long_pass(dev, apdev):
1232    """DPP Config Object legacy error - too long pass/psk"""
1233    conf = '{"wi-fi_tech":"infra","discovery":{"ssid":"test"},"cred":{"akm":"psk","pass":"%s"}}' % (64*'A')
1234    run_dpp_config_error(dev, apdev, conf)
1235
1236def test_dpp_config_error_legacy_psk_with_sae(dev, apdev):
1237    """DPP Config Object legacy error - psk_hex with SAE"""
1238    conf = '{"wi-fi_tech":"infra","discovery":{"ssid":"test"},"cred":{"akm":"sae","psk_hex":"%s"}}' % (32*"12")
1239    run_dpp_config_error(dev, apdev, conf)
1240
1241def test_dpp_config_error_legacy_no_pass_for_sae(dev, apdev):
1242    """DPP Config Object legacy error - no pass for SAE"""
1243    conf = '{"wi-fi_tech":"infra","discovery":{"ssid":"test"},"cred":{"akm":"psk+sae","psk_hex":"%s"}}' % (32*"12")
1244    run_dpp_config_error(dev, apdev, conf)
1245
1246def test_dpp_config_error_legacy_invalid_psk(dev, apdev):
1247    """DPP Config Object legacy error - invalid psk_hex"""
1248    conf = '{"wi-fi_tech":"infra","discovery":{"ssid":"test"},"cred":{"akm":"psk","psk_hex":"%s"}}' % (32*"qa")
1249    run_dpp_config_error(dev, apdev, conf)
1250
1251def test_dpp_config_error_legacy_too_short_psk(dev, apdev):
1252    """DPP Config Object legacy error - too short psk_hex"""
1253    conf = '{"wi-fi_tech":"infra","discovery":{"ssid":"test"},"cred":{"akm":"psk","psk_hex":"%s"}}' % (31*"12")
1254    run_dpp_config_error(dev, apdev, conf)
1255
1256def get_der_int_32(val):
1257    a, b = struct.unpack('BB', val[0:2])
1258    if a != 0x02:
1259        raise Exception("Invalid DER encoding of INTEGER")
1260    if b > len(val) - 2:
1261        raise Exception("Invalid length of INTEGER (truncated)")
1262    val = val[2:]
1263    if b == 32:
1264        r = val[0:32]
1265    elif b == 33:
1266        if val[0] != 0:
1267            raise Exception("Too large INTEGER (32)")
1268        r = val[1:33]
1269    elif b < 32:
1270        r = (32 - b) * b'\x00' + val[0:b]
1271    else:
1272        raise Exception("Invalid length of INTEGER (32): %d" % b)
1273    return r, val[b:]
1274
1275def ecdsa_sign(pkey, message, alg="sha256"):
1276    sign = OpenSSL.crypto.sign(pkey, message, alg)
1277    logger.debug("sign=" + binascii.hexlify(sign).decode())
1278    a, b = struct.unpack('BB', sign[0:2])
1279    if a != 0x30:
1280        raise Exception("Invalid DER encoding of ECDSA signature")
1281    if b != len(sign) - 2:
1282        raise Exception("Invalid length of ECDSA signature")
1283    sign = sign[2:]
1284
1285    r, sign = get_der_int_32(sign)
1286    s, sign = get_der_int_32(sign)
1287    if len(sign) != 0:
1288        raise Exception("Extra data at the end of ECDSA signature")
1289
1290    logger.info("r=" + binascii.hexlify(r).decode())
1291    logger.info("s=" + binascii.hexlify(s).decode())
1292    raw_sign = r + s
1293    return base64.urlsafe_b64encode(raw_sign).decode().rstrip('=')
1294
1295p256_priv_key = """-----BEGIN EC PRIVATE KEY-----
1296MHcCAQEEIBVQij9ah629f1pu3tarDQGQvrzHgAkgYd1jHGiLxNajoAoGCCqGSM49
1297AwEHoUQDQgAEAC9d2/JirKu72F2qLuv5jEFMD1Cqu9EiyGk7cOzn/2DJ51p2mEoW
1298n03N6XRvTC+G7WPol9Ng97NAM2sK57+F/Q==
1299-----END EC PRIVATE KEY-----"""
1300p256_pub_key_x = binascii.unhexlify("002f5ddbf262acabbbd85daa2eebf98c414c0f50aabbd122c8693b70ece7ff60")
1301p256_pub_key_y = binascii.unhexlify("c9e75a76984a169f4dcde9746f4c2f86ed63e897d360f7b340336b0ae7bf85fd")
1302
1303def run_dpp_config_connector(dev, apdev, expiry=None, payload=None,
1304                             skip_net_access_key_mismatch=True,
1305                             conf_failure=True):
1306    if not openssl_imported:
1307        raise HwsimSkip("OpenSSL python method not available")
1308    pkey = OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM,
1309                                          p256_priv_key)
1310    x = base64.urlsafe_b64encode(p256_pub_key_x).decode().rstrip('=')
1311    y = base64.urlsafe_b64encode(p256_pub_key_y).decode().rstrip('=')
1312
1313    pubkey = b'\x04' + p256_pub_key_x + p256_pub_key_y
1314    kid = base64.urlsafe_b64encode(hashlib.sha256(pubkey).digest()).decode().rstrip('=')
1315
1316    prot_hdr = '{"typ":"dppCon","kid":"%s","alg":"ES256"}' % kid
1317
1318    if not payload:
1319        payload = '{"groups":[{"groupId":"*","netRole":"sta"}],"netAccessKey":{"kty":"EC","crv":"P-256","x":"aTF4JEGIPKSZ0Xv9zdCMjm-tn5XpMsYIVZ9wySAz1gI","y":"QGcHWA_6rbU9XDXAztoX-M5Q3suTnMaqEhULtn7SSXw"}'
1320        if expiry:
1321            payload += ',"expiry":"%s"' % expiry
1322        payload += '}'
1323    conn = base64.urlsafe_b64encode(prot_hdr.encode()).decode().rstrip('=') + '.'
1324    conn += base64.urlsafe_b64encode(payload.encode()).decode().rstrip('=')
1325    sign = ecdsa_sign(pkey, conn)
1326    conn += '.' + sign
1327    run_dpp_config_error(dev, apdev,
1328                         build_conf_obj(x=x, y=y, signed_connector=conn),
1329                         skip_net_access_key_mismatch=skip_net_access_key_mismatch,
1330                         conf_failure=conf_failure)
1331
1332def test_dpp_config_connector_error_ext_sign(dev, apdev):
1333    """DPP Config Object connector error - external signature calculation"""
1334    run_dpp_config_connector(dev, apdev, conf_failure=False)
1335
1336def test_dpp_config_connector_error_too_short_timestamp(dev, apdev):
1337    """DPP Config Object connector error - too short timestamp"""
1338    run_dpp_config_connector(dev, apdev, expiry="1")
1339
1340def test_dpp_config_connector_error_invalid_timestamp(dev, apdev):
1341    """DPP Config Object connector error - invalid timestamp"""
1342    run_dpp_config_connector(dev, apdev, expiry=19*"1")
1343
1344def test_dpp_config_connector_error_invalid_timestamp_date(dev, apdev):
1345    """DPP Config Object connector error - invalid timestamp date"""
1346    run_dpp_config_connector(dev, apdev, expiry="9999-99-99T99:99:99Z")
1347
1348def test_dpp_config_connector_error_invalid_time_zone(dev, apdev):
1349    """DPP Config Object connector error - invalid time zone"""
1350    run_dpp_config_connector(dev, apdev, expiry="2018-01-01T00:00:00*")
1351
1352def test_dpp_config_connector_error_invalid_time_zone_2(dev, apdev):
1353    """DPP Config Object connector error - invalid time zone 2"""
1354    run_dpp_config_connector(dev, apdev, expiry="2018-01-01T00:00:00+")
1355
1356def test_dpp_config_connector_error_expired_1(dev, apdev):
1357    """DPP Config Object connector error - expired 1"""
1358    run_dpp_config_connector(dev, apdev, expiry="2018-01-01T00:00:00")
1359
1360def test_dpp_config_connector_error_expired_2(dev, apdev):
1361    """DPP Config Object connector error - expired 2"""
1362    run_dpp_config_connector(dev, apdev, expiry="2018-01-01T00:00:00Z")
1363
1364def test_dpp_config_connector_error_expired_3(dev, apdev):
1365    """DPP Config Object connector error - expired 3"""
1366    run_dpp_config_connector(dev, apdev, expiry="2018-01-01T00:00:00+01")
1367
1368def test_dpp_config_connector_error_expired_4(dev, apdev):
1369    """DPP Config Object connector error - expired 4"""
1370    run_dpp_config_connector(dev, apdev, expiry="2018-01-01T00:00:00+01:02")
1371
1372def test_dpp_config_connector_error_expired_5(dev, apdev):
1373    """DPP Config Object connector error - expired 5"""
1374    run_dpp_config_connector(dev, apdev, expiry="2018-01-01T00:00:00-01")
1375
1376def test_dpp_config_connector_error_expired_6(dev, apdev):
1377    """DPP Config Object connector error - expired 6"""
1378    run_dpp_config_connector(dev, apdev, expiry="2018-01-01T00:00:00-01:02")
1379
1380def test_dpp_config_connector_error_no_groups(dev, apdev):
1381    """DPP Config Object connector error - no groups"""
1382    payload = '{"netAccessKey":{"kty":"EC","crv":"P-256","x":"aTF4JEGIPKSZ0Xv9zdCMjm-tn5XpMsYIVZ9wySAz1gI","y":"QGcHWA_6rbU9XDXAztoX-M5Q3suTnMaqEhULtn7SSXw"}}'
1383    run_dpp_config_connector(dev, apdev, payload=payload)
1384
1385def test_dpp_config_connector_error_empty_groups(dev, apdev):
1386    """DPP Config Object connector error - empty groups"""
1387    payload = '{"groups":[],"netAccessKey":{"kty":"EC","crv":"P-256","x":"aTF4JEGIPKSZ0Xv9zdCMjm-tn5XpMsYIVZ9wySAz1gI","y":"QGcHWA_6rbU9XDXAztoX-M5Q3suTnMaqEhULtn7SSXw"}}'
1388    run_dpp_config_connector(dev, apdev, payload=payload)
1389
1390def test_dpp_config_connector_error_missing_group_id(dev, apdev):
1391    """DPP Config Object connector error - missing groupId"""
1392    payload = '{"groups":[{"netRole":"sta"}],"netAccessKey":{"kty":"EC","crv":"P-256","x":"aTF4JEGIPKSZ0Xv9zdCMjm-tn5XpMsYIVZ9wySAz1gI","y":"QGcHWA_6rbU9XDXAztoX-M5Q3suTnMaqEhULtn7SSXw"}}'
1393    run_dpp_config_connector(dev, apdev, payload=payload)
1394
1395def test_dpp_config_connector_error_missing_net_role(dev, apdev):
1396    """DPP Config Object connector error - missing netRole"""
1397    payload = '{"groups":[{"groupId":"*"}],"netAccessKey":{"kty":"EC","crv":"P-256","x":"aTF4JEGIPKSZ0Xv9zdCMjm-tn5XpMsYIVZ9wySAz1gI","y":"QGcHWA_6rbU9XDXAztoX-M5Q3suTnMaqEhULtn7SSXw"}}'
1398    run_dpp_config_connector(dev, apdev, payload=payload)
1399
1400def test_dpp_config_connector_error_missing_net_access_key(dev, apdev):
1401    """DPP Config Object connector error - missing netAccessKey"""
1402    payload = '{"groups":[{"groupId":"*","netRole":"sta"}]}'
1403    run_dpp_config_connector(dev, apdev, payload=payload)
1404
1405def test_dpp_config_connector_error_net_access_key_mismatch(dev, apdev):
1406    """DPP Config Object connector error - netAccessKey mismatch"""
1407    payload = '{"groups":[{"groupId":"*","netRole":"sta"}],"netAccessKey":{"kty":"EC","crv":"P-256","x":"aTF4JEGIPKSZ0Xv9zdCMjm-tn5XpMsYIVZ9wySAz1gI","y":"QGcHWA_6rbU9XDXAztoX-M5Q3suTnMaqEhULtn7SSXw"}}'
1408    run_dpp_config_connector(dev, apdev, payload=payload,
1409                             skip_net_access_key_mismatch=False)
1410
1411def test_dpp_gas_timeout(dev, apdev):
1412    """DPP and GAS server timeout for a query"""
1413    check_dpp_capab(dev[0])
1414    check_dpp_capab(dev[1])
1415    logger.info("dev0 displays QR Code")
1416    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
1417    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
1418
1419    logger.info("dev1 scans QR Code and initiates DPP Authentication")
1420    dev[0].set("ext_mgmt_frame_handling", "1")
1421    dev[0].dpp_listen(2412)
1422
1423    # Force GAS fragmentation
1424    conf = '{"wi-fi_tech":"infra", "discovery":{"ssid":"test"},"cred":{"akm":"psk","pass":"secret passphrase"}}' + 3000*' '
1425    dev[1].set("dpp_config_obj_override", conf)
1426
1427    dev[1].dpp_auth_init(uri=uri0)
1428
1429    # DPP Authentication Request
1430    msg = dev[0].mgmt_rx()
1431    if "OK" not in dev[0].request("MGMT_RX_PROCESS freq={} datarate={} ssi_signal={} frame={}".format(
1432        msg['freq'], msg['datarate'], msg['ssi_signal'], binascii.hexlify(msg['frame']).decode())):
1433        raise Exception("MGMT_RX_PROCESS failed")
1434
1435    # DPP Authentication Confirmation
1436    msg = dev[0].mgmt_rx()
1437    if "OK" not in dev[0].request("MGMT_RX_PROCESS freq={} datarate={} ssi_signal={} frame={}".format(
1438        msg['freq'], msg['datarate'], msg['ssi_signal'], binascii.hexlify(msg['frame']).decode())):
1439        raise Exception("MGMT_RX_PROCESS failed")
1440
1441    wait_auth_success(dev[0], dev[1])
1442
1443    # DPP Configuration Response (GAS Initial Response frame)
1444    msg = dev[0].mgmt_rx()
1445    if "OK" not in dev[0].request("MGMT_RX_PROCESS freq={} datarate={} ssi_signal={} frame={}".format(
1446        msg['freq'], msg['datarate'], msg['ssi_signal'], binascii.hexlify(msg['frame']).decode())):
1447        raise Exception("MGMT_RX_PROCESS failed")
1448
1449    # GAS Comeback Response frame
1450    msg = dev[0].mgmt_rx()
1451    # Do not continue to force timeout on GAS server
1452
1453    ev = dev[0].wait_event(["GAS-QUERY-DONE"], timeout=10)
1454    if ev is None:
1455        raise Exception("GAS result not reported (Enrollee)")
1456    if "result=TIMEOUT" not in ev:
1457        raise Exception("Unexpected GAS result (Enrollee): " + ev)
1458    dev[0].set("ext_mgmt_frame_handling", "0")
1459
1460    ev = dev[1].wait_event(["DPP-CONF-FAILED"], timeout=15)
1461    if ev is None:
1462        raise Exception("DPP configuration failure not reported (Configurator)")
1463
1464    ev = dev[0].wait_event(["DPP-CONF-FAILED"], timeout=1)
1465    if ev is None:
1466        raise Exception("DPP configuration failure not reported (Enrollee)")
1467
1468def test_dpp_akm_sha256(dev, apdev):
1469    """DPP AKM (SHA256)"""
1470    run_dpp_akm(dev, apdev, 32)
1471
1472def test_dpp_akm_sha384(dev, apdev):
1473    """DPP AKM (SHA384)"""
1474    run_dpp_akm(dev, apdev, 48)
1475
1476def test_dpp_akm_sha512(dev, apdev):
1477    """DPP AKM (SHA512)"""
1478    run_dpp_akm(dev, apdev, 64)
1479
1480def run_dpp_akm(dev, apdev, pmk_len):
1481    check_dpp_capab(dev[0])
1482    check_dpp_capab(dev[1])
1483    params = {"ssid": "dpp",
1484              "wpa": "2",
1485              "wpa_key_mgmt": "DPP",
1486              "rsn_pairwise": "CCMP",
1487              "ieee80211w": "2"}
1488    try:
1489        hapd = hostapd.add_ap(apdev[0], params)
1490    except:
1491        raise HwsimSkip("DPP not supported")
1492
1493    conf = hapd.request("GET_CONFIG")
1494    if "key_mgmt=DPP" not in conf.splitlines():
1495        logger.info("GET_CONFIG:\n" + conf)
1496        raise Exception("GET_CONFIG did not report correct key_mgmt")
1497
1498    id = dev[0].connect("dpp", key_mgmt="DPP", ieee80211w="2", scan_freq="2412",
1499                        dpp_pfs="2", wait_connect=False)
1500    ev = dev[0].wait_event(["CTRL-EVENT-NETWORK-NOT-FOUND"], timeout=2)
1501    if not ev:
1502        raise Exception("Network mismatch not reported")
1503    dev[0].request("DISCONNECT")
1504    dev[0].dump_monitor()
1505
1506    bssid = hapd.own_addr()
1507    pmkid = 16*'11'
1508    akmp = 2**23
1509    pmk = pmk_len*'22'
1510    cmd = "PMKSA_ADD %d %s %s %s 30240 43200 %d 0" % (id, bssid, pmkid, pmk, akmp)
1511    if "OK" not in dev[0].request(cmd):
1512        raise Exception("PMKSA_ADD failed (wpa_supplicant)")
1513    dev[0].select_network(id, freq="2412")
1514    ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"], timeout=2)
1515    dev[0].request("DISCONNECT")
1516    dev[0].dump_monitor()
1517    if not ev:
1518        raise Exception("Association attempt was not rejected")
1519    if "status_code=53" not in ev:
1520        raise Exception("Unexpected status code: " + ev)
1521
1522    addr = dev[0].own_addr()
1523    cmd = "PMKSA_ADD %s %s %s 0 %d" % (addr, pmkid, pmk, akmp)
1524    if "OK" not in hapd.request(cmd):
1525        raise Exception("PMKSA_ADD failed (hostapd)")
1526
1527    dev[0].select_network(id, freq="2412")
1528    dev[0].wait_connected()
1529    val = dev[0].get_status_field("key_mgmt")
1530    if val != "DPP":
1531        raise Exception("Unexpected key_mgmt: " + val)
1532
1533params1_csign = "3059301306072a8648ce3d020106082a8648ce3d03010703420004d02e5bd81a120762b5f0f2994777f5d40297238a6c294fd575cdf35fabec44c050a6421c401d98d659fd2ed13c961cc8287944dd3202f516977800d3ab2f39ee"
1534params1_ap_connector = "eyJ0eXAiOiJkcHBDb24iLCJraWQiOiJzOEFrYjg5bTV4UGhoYk5UbTVmVVo0eVBzNU5VMkdxYXNRY3hXUWhtQVFRIiwiYWxnIjoiRVMyNTYifQ.eyJncm91cHMiOlt7Imdyb3VwSWQiOiIqIiwibmV0Um9sZSI6ImFwIn1dLCJuZXRBY2Nlc3NLZXkiOnsia3R5IjoiRUMiLCJjcnYiOiJQLTI1NiIsIngiOiIwOHF4TlNYRzRWemdCV3BjVUdNSmc1czNvbElOVFJsRVQ1aERpNkRKY3ZjIiwieSI6IlVhaGFYQXpKRVpRQk1YaHRUQnlZZVlrOWtJYjk5UDA3UV9NcW9TVVZTVEkifX0.a5_nfMVr7Qe1SW0ZL3u6oQRm5NUCYUSfixDAJOUFN3XUfECBZ6E8fm8xjeSfdOytgRidTz0CTlIRjzPQo82dmQ"
1535params1_ap_netaccesskey = "30770201010420f6531d17f29dfab655b7c9e923478d5a345164c489aadd44a3519c3e9dcc792da00a06082a8648ce3d030107a14403420004d3cab13525c6e15ce0056a5c506309839b37a2520d4d19444f98438ba0c972f751a85a5c0cc911940131786d4c1c9879893d9086fdf4fd3b43f32aa125154932"
1536params1_sta_connector = "eyJ0eXAiOiJkcHBDb24iLCJraWQiOiJzOEFrYjg5bTV4UGhoYk5UbTVmVVo0eVBzNU5VMkdxYXNRY3hXUWhtQVFRIiwiYWxnIjoiRVMyNTYifQ.eyJncm91cHMiOlt7Imdyb3VwSWQiOiIqIiwibmV0Um9sZSI6InN0YSJ9XSwibmV0QWNjZXNzS2V5Ijp7Imt0eSI6IkVDIiwiY3J2IjoiUC0yNTYiLCJ4IjoiZWMzR3NqQ3lQMzVBUUZOQUJJdEltQnN4WXVyMGJZX1dES1lfSE9zUGdjNCIsInkiOiJTRS1HVllkdWVnTFhLMU1TQXZNMEx2QWdLREpTNWoyQVhCbE9PMTdUSTRBIn19.PDK9zsGlK-e1pEOmNxVeJfCS8pNeay6ckIS1TXCQsR64AR-9wFPCNVjqOxWvVKltehyMFqVAtOcv0IrjtMJFqQ"
1537params1_sta_netaccesskey = "30770201010420bc33380c26fd2168b69cd8242ed1df07ba89aa4813f8d4e8523de6ca3f8dd28ba00a06082a8648ce3d030107a1440342000479cdc6b230b23f7e40405340048b48981b3162eaf46d8fd60ca63f1ceb0f81ce484f8655876e7a02d72b531202f3342ef020283252e63d805c194e3b5ed32380"
1538
1539def test_dpp_network_introduction(dev, apdev):
1540    """DPP network introduction"""
1541    check_dpp_capab(dev[0])
1542    check_dpp_capab(dev[1])
1543
1544    params = {"ssid": "dpp",
1545              "wpa": "2",
1546              "wpa_key_mgmt": "DPP",
1547              "ieee80211w": "2",
1548              "rsn_pairwise": "CCMP",
1549              "dpp_connector": params1_ap_connector,
1550              "dpp_csign": params1_csign,
1551              "dpp_netaccesskey": params1_ap_netaccesskey}
1552    try:
1553        hapd = hostapd.add_ap(apdev[0], params)
1554    except:
1555        raise HwsimSkip("DPP not supported")
1556
1557    id = dev[0].connect("dpp", key_mgmt="DPP", scan_freq="2412",
1558                        ieee80211w="2",
1559                        dpp_csign=params1_csign,
1560                        dpp_connector=params1_sta_connector,
1561                        dpp_netaccesskey=params1_sta_netaccesskey)
1562    val = dev[0].get_status_field("key_mgmt")
1563    if val != "DPP":
1564        raise Exception("Unexpected key_mgmt: " + val)
1565
1566def test_dpp_network_introduction_expired(dev, apdev):
1567    """DPP network introduction with expired netaccesskey"""
1568    check_dpp_capab(dev[0])
1569    check_dpp_capab(dev[1])
1570
1571    params = {"ssid": "dpp",
1572              "wpa": "2",
1573              "wpa_key_mgmt": "DPP",
1574              "ieee80211w": "2",
1575              "rsn_pairwise": "CCMP",
1576              "dpp_connector": params1_ap_connector,
1577              "dpp_csign": params1_csign,
1578              "dpp_netaccesskey": params1_ap_netaccesskey,
1579              "dpp_netaccesskey_expiry": "1565530889"}
1580    try:
1581        hapd = hostapd.add_ap(apdev[0], params)
1582    except:
1583        raise HwsimSkip("DPP not supported")
1584
1585    dev[0].connect("dpp", key_mgmt="DPP", scan_freq="2412",
1586                   ieee80211w="2",
1587                   dpp_csign=params1_csign,
1588                   dpp_connector=params1_sta_connector,
1589                   dpp_netaccesskey=params1_sta_netaccesskey,
1590                   wait_connect=False)
1591    ev = hapd.wait_event(["DPP-RX"], timeout=10)
1592    if ev is None:
1593        raise Exception("No DPP Peer Discovery Request seen")
1594    if "type=5" not in ev:
1595        raise Exception("Unexpected DPP message received: " + ev)
1596    ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
1597    dev[0].request("DISCONNECT")
1598    if ev:
1599        raise Exception("Connection reported")
1600
1601    hapd.disable()
1602    hapd.set("dpp_netaccesskey_expiry", "2565530889")
1603    hapd.enable()
1604    dev[0].request("RECONNECT")
1605    dev[0].wait_connected()
1606
1607def test_dpp_and_sae_akm(dev, apdev):
1608    """DPP and SAE AKMs"""
1609    check_dpp_capab(dev[0])
1610    check_dpp_capab(dev[1])
1611    if "SAE" not in dev[1].get_capability("auth_alg"):
1612        raise HwsimSkip("SAE not supported")
1613
1614    params = {"ssid": "dpp+sae",
1615              "wpa": "2",
1616              "wpa_key_mgmt": "DPP SAE",
1617              "ieee80211w": "2",
1618              "rsn_pairwise": "CCMP",
1619              "sae_password": "sae-password",
1620              "dpp_connector": params1_ap_connector,
1621              "dpp_csign": params1_csign,
1622              "dpp_netaccesskey": params1_ap_netaccesskey}
1623    try:
1624        hapd = hostapd.add_ap(apdev[0], params)
1625    except:
1626        raise HwsimSkip("DPP not supported")
1627
1628    id = dev[0].connect("dpp+sae", key_mgmt="DPP", scan_freq="2412",
1629                        ieee80211w="2",
1630                        dpp_csign=params1_csign,
1631                        dpp_connector=params1_sta_connector,
1632                        dpp_netaccesskey=params1_sta_netaccesskey)
1633    val = dev[0].get_status_field("key_mgmt")
1634    if val != "DPP":
1635        raise Exception("Unexpected key_mgmt for DPP: " + val)
1636
1637    dev[1].request("SET sae_groups ")
1638    id = dev[1].connect("dpp+sae", key_mgmt="SAE", scan_freq="2412",
1639                        ieee80211w="2", psk="sae-password")
1640    val = dev[1].get_status_field("key_mgmt")
1641    if val != "SAE":
1642        raise Exception("Unexpected key_mgmt for SAE: " + val)
1643
1644def test_dpp_ap_config(dev, apdev):
1645    """DPP and AP configuration"""
1646    run_dpp_ap_config(dev, apdev)
1647
1648def test_dpp_ap_config_p256_p256(dev, apdev):
1649    """DPP and AP configuration (P-256 + P-256)"""
1650    run_dpp_ap_config(dev, apdev, curve="P-256", conf_curve="P-256")
1651
1652def test_dpp_ap_config_p256_p384(dev, apdev):
1653    """DPP and AP configuration (P-256 + P-384)"""
1654    run_dpp_ap_config(dev, apdev, curve="P-256", conf_curve="P-384")
1655
1656def test_dpp_ap_config_p256_p521(dev, apdev):
1657    """DPP and AP configuration (P-256 + P-521)"""
1658    run_dpp_ap_config(dev, apdev, curve="P-256", conf_curve="P-521")
1659
1660def test_dpp_ap_config_p384_p256(dev, apdev):
1661    """DPP and AP configuration (P-384 + P-256)"""
1662    run_dpp_ap_config(dev, apdev, curve="P-384", conf_curve="P-256")
1663
1664def test_dpp_ap_config_p384_p384(dev, apdev):
1665    """DPP and AP configuration (P-384 + P-384)"""
1666    run_dpp_ap_config(dev, apdev, curve="P-384", conf_curve="P-384")
1667
1668def test_dpp_ap_config_p384_p521(dev, apdev):
1669    """DPP and AP configuration (P-384 + P-521)"""
1670    run_dpp_ap_config(dev, apdev, curve="P-384", conf_curve="P-521")
1671
1672def test_dpp_ap_config_p521_p256(dev, apdev):
1673    """DPP and AP configuration (P-521 + P-256)"""
1674    run_dpp_ap_config(dev, apdev, curve="P-521", conf_curve="P-256")
1675
1676def test_dpp_ap_config_p521_p384(dev, apdev):
1677    """DPP and AP configuration (P-521 + P-384)"""
1678    run_dpp_ap_config(dev, apdev, curve="P-521", conf_curve="P-384")
1679
1680def test_dpp_ap_config_p521_p521(dev, apdev):
1681    """DPP and AP configuration (P-521 + P-521)"""
1682    run_dpp_ap_config(dev, apdev, curve="P-521", conf_curve="P-521")
1683
1684def test_dpp_ap_config_bp256_bp256(dev, apdev):
1685    """DPP and AP configuration (BP-256 + BP-256)"""
1686    run_dpp_ap_config(dev, apdev, curve="BP-256", conf_curve="BP-256")
1687
1688def test_dpp_ap_config_bp384_bp384(dev, apdev):
1689    """DPP and AP configuration (BP-384 + BP-384)"""
1690    run_dpp_ap_config(dev, apdev, curve="BP-384", conf_curve="BP-384")
1691
1692def test_dpp_ap_config_bp512_bp512(dev, apdev):
1693    """DPP and AP configuration (BP-512 + BP-512)"""
1694    run_dpp_ap_config(dev, apdev, curve="BP-512", conf_curve="BP-512")
1695
1696def test_dpp_ap_config_p256_bp256(dev, apdev):
1697    """DPP and AP configuration (P-256 + BP-256)"""
1698    run_dpp_ap_config(dev, apdev, curve="P-256", conf_curve="BP-256")
1699
1700def test_dpp_ap_config_bp256_p256(dev, apdev):
1701    """DPP and AP configuration (BP-256 + P-256)"""
1702    run_dpp_ap_config(dev, apdev, curve="BP-256", conf_curve="P-256")
1703
1704def test_dpp_ap_config_p521_bp512(dev, apdev):
1705    """DPP and AP configuration (P-521 + BP-512)"""
1706    run_dpp_ap_config(dev, apdev, curve="P-521", conf_curve="BP-512")
1707
1708def test_dpp_ap_config_bp512_p521(dev, apdev):
1709    """DPP and AP configuration (BP-512 + P-521)"""
1710    run_dpp_ap_config(dev, apdev, curve="BP-512", conf_curve="P-521")
1711
1712def test_dpp_ap_config_reconfig_configurator(dev, apdev):
1713    """DPP and AP configuration with Configurator reconfiguration"""
1714    run_dpp_ap_config(dev, apdev, reconf_configurator=True)
1715
1716def update_hapd_config(hapd):
1717    ev = hapd.wait_event(["DPP-CONFOBJ-SSID"], timeout=1)
1718    if ev is None:
1719        raise Exception("SSID not reported (AP)")
1720    ssid = ev.split(' ')[1]
1721
1722    ev = hapd.wait_event(["DPP-CONNECTOR"], timeout=1)
1723    if ev is None:
1724        raise Exception("Connector not reported (AP)")
1725    connector = ev.split(' ')[1]
1726
1727    ev = hapd.wait_event(["DPP-C-SIGN-KEY"], timeout=1)
1728    if ev is None:
1729        raise Exception("C-sign-key not reported (AP)")
1730    p = ev.split(' ')
1731    csign = p[1]
1732
1733    ev = hapd.wait_event(["DPP-NET-ACCESS-KEY"], timeout=1)
1734    if ev is None:
1735        raise Exception("netAccessKey not reported (AP)")
1736    p = ev.split(' ')
1737    net_access_key = p[1]
1738    net_access_key_expiry = p[2] if len(p) > 2 else None
1739
1740    logger.info("Update AP configuration to use key_mgmt=DPP")
1741    hapd.disable()
1742    hapd.set("ssid", ssid)
1743    hapd.set("utf8_ssid", "1")
1744    hapd.set("wpa", "2")
1745    hapd.set("wpa_key_mgmt", "DPP")
1746    hapd.set("ieee80211w", "2")
1747    hapd.set("rsn_pairwise", "CCMP")
1748    hapd.set("dpp_connector", connector)
1749    hapd.set("dpp_csign", csign)
1750    hapd.set("dpp_netaccesskey", net_access_key)
1751    if net_access_key_expiry:
1752        hapd.set("dpp_netaccesskey_expiry", net_access_key_expiry)
1753    hapd.enable()
1754
1755def run_dpp_ap_config(dev, apdev, curve=None, conf_curve=None,
1756                      reconf_configurator=False):
1757    brainpool = (curve and "BP-" in curve) or \
1758        (conf_curve and "BP-" in conf_curve)
1759    check_dpp_capab(dev[0], brainpool)
1760    check_dpp_capab(dev[1], brainpool)
1761    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured"})
1762    check_dpp_capab(hapd)
1763
1764    id_h = hapd.dpp_bootstrap_gen(chan="81/1", mac=True, curve=curve)
1765    uri = hapd.request("DPP_BOOTSTRAP_GET_URI %d" % id_h)
1766
1767    conf_id = dev[0].dpp_configurator_add(curve=conf_curve)
1768
1769    if reconf_configurator:
1770        csign = dev[0].request("DPP_CONFIGURATOR_GET_KEY %d" % conf_id)
1771        if "FAIL" in csign or len(csign) == 0:
1772            raise Exception("DPP_CONFIGURATOR_GET_KEY failed")
1773
1774    dev[0].dpp_auth_init(uri=uri, conf="ap-dpp", configurator=conf_id)
1775    wait_auth_success(hapd, dev[0], configurator=dev[0], enrollee=hapd)
1776    update_hapd_config(hapd)
1777
1778    id1 = dev[1].dpp_bootstrap_gen(chan="81/1", mac=True, curve=curve)
1779    uri1 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id1)
1780
1781    if reconf_configurator:
1782        dev[0].dpp_configurator_remove(conf_id)
1783        conf_id = dev[0].dpp_configurator_add(curve=conf_curve, key=csign)
1784
1785    dev[1].dpp_listen(2412)
1786    dev[0].dpp_auth_init(uri=uri1, conf="sta-dpp", configurator=conf_id)
1787    wait_auth_success(dev[1], dev[0], configurator=dev[0], enrollee=dev[1],
1788                      stop_responder=True)
1789
1790    ev = dev[1].wait_event(["DPP-CONFOBJ-SSID"], timeout=1)
1791    if ev is None:
1792        raise Exception("SSID not reported")
1793    ssid = ev.split(' ')[1]
1794
1795    ev = dev[1].wait_event(["DPP-CONNECTOR"], timeout=1)
1796    if ev is None:
1797        raise Exception("Connector not reported")
1798    connector = ev.split(' ')[1]
1799
1800    ev = dev[1].wait_event(["DPP-C-SIGN-KEY"], timeout=1)
1801    if ev is None:
1802        raise Exception("C-sign-key not reported")
1803    p = ev.split(' ')
1804    csign = p[1]
1805
1806    ev = dev[1].wait_event(["DPP-NET-ACCESS-KEY"], timeout=1)
1807    if ev is None:
1808        raise Exception("netAccessKey not reported")
1809    p = ev.split(' ')
1810    net_access_key = p[1]
1811    net_access_key_expiry = p[2] if len(p) > 2 else None
1812
1813    dev[1].dump_monitor()
1814
1815    id = dev[1].connect(ssid, key_mgmt="DPP", ieee80211w="2", scan_freq="2412",
1816                        only_add_network=True)
1817    dev[1].set_network_quoted(id, "dpp_connector", connector)
1818    dev[1].set_network(id, "dpp_csign", csign)
1819    dev[1].set_network(id, "dpp_netaccesskey", net_access_key)
1820    if net_access_key_expiry:
1821        dev[1].set_network(id, "dpp_netaccess_expiry", net_access_key_expiry)
1822
1823    logger.info("Check data connection")
1824    dev[1].select_network(id, freq="2412")
1825    dev[1].wait_connected()
1826
1827def test_dpp_auto_connect_1(dev, apdev):
1828    """DPP and auto connect (1)"""
1829    try:
1830        run_dpp_auto_connect(dev, apdev, 1)
1831    finally:
1832        dev[0].set("dpp_config_processing", "0", allow_fail=True)
1833
1834def test_dpp_auto_connect_2(dev, apdev):
1835    """DPP and auto connect (2)"""
1836    try:
1837        run_dpp_auto_connect(dev, apdev, 2)
1838    finally:
1839        dev[0].set("dpp_config_processing", "0", allow_fail=True)
1840
1841def test_dpp_auto_connect_2_connect_cmd(dev, apdev):
1842    """DPP and auto connect (2) using connect_cmd"""
1843    wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
1844    wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
1845    dev_new = [wpas, dev[1]]
1846    try:
1847        run_dpp_auto_connect(dev_new, apdev, 2)
1848    finally:
1849        wpas.set("dpp_config_processing", "0", allow_fail=True)
1850
1851def test_dpp_auto_connect_2_sta_ver1(dev, apdev):
1852    """DPP and auto connect (2; STA using ver 1)"""
1853    try:
1854        run_dpp_auto_connect(dev, apdev, 2, sta_version=1)
1855    finally:
1856        dev[0].set("dpp_config_processing", "0", allow_fail=True)
1857
1858def test_dpp_auto_connect_2_ap_ver1(dev, apdev):
1859    """DPP and auto connect (2; AP using ver 1)"""
1860    try:
1861        run_dpp_auto_connect(dev, apdev, 2, ap_version=1)
1862    finally:
1863        dev[0].set("dpp_config_processing", "0", allow_fail=True)
1864
1865def test_dpp_auto_connect_2_ver1(dev, apdev):
1866    """DPP and auto connect (2; AP and STA using ver 1)"""
1867    try:
1868        run_dpp_auto_connect(dev, apdev, 2, ap_version=1, sta_version=1)
1869    finally:
1870        dev[0].set("dpp_config_processing", "0", allow_fail=True)
1871
1872def test_dpp_auto_connect_2_conf_ver1(dev, apdev):
1873    """DPP and auto connect (2; Configurator using ver 1)"""
1874    try:
1875        run_dpp_auto_connect(dev, apdev, 2, sta1_version=1)
1876    finally:
1877        dev[0].set("dpp_config_processing", "0", allow_fail=True)
1878
1879def run_dpp_auto_connect(dev, apdev, processing, ap_version=0, sta_version=0,
1880                         sta1_version=0):
1881    check_dpp_capab(dev[0])
1882    check_dpp_capab(dev[1])
1883
1884    csign = "30770201010420768240a3fc89d6662d9782f120527fe7fb9edc6366ab0b9c7dde96125cfd250fa00a06082a8648ce3d030107a144034200042908e1baf7bf413cc66f9e878a03e8bb1835ba94b033dbe3d6969fc8575d5eb5dfda1cb81c95cee21d0cd7d92ba30541ffa05cb6296f5dd808b0c1c2a83c0708"
1885    csign_pub = "3059301306072a8648ce3d020106082a8648ce3d030107034200042908e1baf7bf413cc66f9e878a03e8bb1835ba94b033dbe3d6969fc8575d5eb5dfda1cb81c95cee21d0cd7d92ba30541ffa05cb6296f5dd808b0c1c2a83c0708"
1886    ap_connector = "eyJ0eXAiOiJkcHBDb24iLCJraWQiOiJwYWtZbXVzd1dCdWpSYTl5OEsweDViaTVrT3VNT3dzZHRlaml2UG55ZHZzIiwiYWxnIjoiRVMyNTYifQ.eyJncm91cHMiOlt7Imdyb3VwSWQiOiIqIiwibmV0Um9sZSI6ImFwIn1dLCJuZXRBY2Nlc3NLZXkiOnsia3R5IjoiRUMiLCJjcnYiOiJQLTI1NiIsIngiOiIybU5vNXZuRkI5bEw3d1VWb1hJbGVPYzBNSEE1QXZKbnpwZXZULVVTYzVNIiwieSI6IlhzS3dqVHJlLTg5WWdpU3pKaG9CN1haeUttTU05OTl3V2ZaSVl0bi01Q3MifX0.XhjFpZgcSa7G2lHy0OCYTvaZFRo5Hyx6b7g7oYyusLC7C_73AJ4_BxEZQVYJXAtDuGvb3dXSkHEKxREP9Q6Qeg"
1887    ap_netaccesskey = "30770201010420ceba752db2ad5200fa7bc565b9c05c69b7eb006751b0b329b0279de1c19ca67ca00a06082a8648ce3d030107a14403420004da6368e6f9c507d94bef0515a1722578e73430703902f267ce97af4fe51273935ec2b08d3adefbcf588224b3261a01ed76722a630cf7df7059f64862d9fee42b"
1888
1889    params = {"ssid": "test",
1890              "wpa": "2",
1891              "wpa_key_mgmt": "DPP",
1892              "ieee80211w": "2",
1893              "rsn_pairwise": "CCMP",
1894              "dpp_connector": ap_connector,
1895              "dpp_csign": csign_pub,
1896              "dpp_netaccesskey": ap_netaccesskey}
1897    try:
1898        hapd = hostapd.add_ap(apdev[0], params)
1899        if ap_version:
1900            hapd.set("dpp_version_override", str(ap_version))
1901    except:
1902        raise HwsimSkip("DPP not supported")
1903
1904    if sta_version:
1905        dev[0].set("dpp_version_override", str(sta_version))
1906    if sta1_version:
1907        dev[1].set("dpp_version_override", str(sta1_version))
1908    conf_id = dev[1].dpp_configurator_add(key=csign)
1909    dev[0].set("dpp_config_processing", str(processing))
1910    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
1911    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
1912    dev[0].dpp_listen(2412)
1913    dev[1].dpp_auth_init(uri=uri0, conf="sta-dpp", configurator=conf_id)
1914    wait_auth_success(dev[0], dev[1], configurator=dev[1], enrollee=dev[0])
1915    ev = dev[0].wait_event(["DPP-NETWORK-ID"], timeout=1)
1916    if ev is None:
1917        raise Exception("DPP network profile not generated")
1918    id = ev.split(' ')[1]
1919
1920    if processing == 1:
1921        dev[0].select_network(id, freq=2412)
1922
1923    dev[0].wait_connected()
1924    hwsim_utils.test_connectivity(dev[0], hapd)
1925
1926def test_dpp_auto_connect_legacy(dev, apdev):
1927    """DPP and auto connect (legacy)"""
1928    try:
1929        run_dpp_auto_connect_legacy(dev, apdev)
1930    finally:
1931        dev[0].set("dpp_config_processing", "0", allow_fail=True)
1932
1933def test_dpp_auto_connect_legacy_ssid_charset(dev, apdev):
1934    """DPP and auto connect (legacy, ssid_charset)"""
1935    try:
1936        run_dpp_auto_connect_legacy(dev, apdev, ssid_charset=12345)
1937    finally:
1938        dev[0].set("dpp_config_processing", "0", allow_fail=True)
1939
1940def test_dpp_auto_connect_legacy_sae_1(dev, apdev):
1941    """DPP and auto connect (legacy SAE)"""
1942    try:
1943        run_dpp_auto_connect_legacy(dev, apdev, conf='sta-sae', psk_sae=True)
1944    finally:
1945        dev[0].set("dpp_config_processing", "0", allow_fail=True)
1946
1947def test_dpp_auto_connect_legacy_sae_2(dev, apdev):
1948    """DPP and auto connect (legacy SAE)"""
1949    try:
1950        run_dpp_auto_connect_legacy(dev, apdev, conf='sta-sae', sae_only=True)
1951    finally:
1952        dev[0].set("dpp_config_processing", "0", allow_fail=True)
1953
1954def test_dpp_auto_connect_legacy_psk_sae_1(dev, apdev):
1955    """DPP and auto connect (legacy PSK+SAE)"""
1956    try:
1957        run_dpp_auto_connect_legacy(dev, apdev, conf='sta-psk-sae',
1958                                    psk_sae=True)
1959    finally:
1960        dev[0].set("dpp_config_processing", "0", allow_fail=True)
1961
1962def test_dpp_auto_connect_legacy_psk_sae_2(dev, apdev):
1963    """DPP and auto connect (legacy PSK+SAE)"""
1964    try:
1965        run_dpp_auto_connect_legacy(dev, apdev, conf='sta-psk-sae',
1966                                    sae_only=True)
1967    finally:
1968        dev[0].set("dpp_config_processing", "0", allow_fail=True)
1969
1970def test_dpp_auto_connect_legacy_psk_sae_3(dev, apdev):
1971    """DPP and auto connect (legacy PSK+SAE)"""
1972    try:
1973        run_dpp_auto_connect_legacy(dev, apdev, conf='sta-psk-sae')
1974    finally:
1975        dev[0].set("dpp_config_processing", "0", allow_fail=True)
1976
1977def run_dpp_auto_connect_legacy(dev, apdev, conf='sta-psk',
1978                                ssid_charset=None,
1979                                psk_sae=False, sae_only=False):
1980    check_dpp_capab(dev[0])
1981    check_dpp_capab(dev[1])
1982
1983    params = hostapd.wpa2_params(ssid="dpp-legacy",
1984                                 passphrase="secret passphrase")
1985    if sae_only:
1986            params['wpa_key_mgmt'] = 'SAE'
1987            params['ieee80211w'] = '2'
1988    elif psk_sae:
1989            params['wpa_key_mgmt'] = 'WPA-PSK SAE'
1990            params['ieee80211w'] = '1'
1991            params['sae_require_mfp'] = '1'
1992
1993    hapd = hostapd.add_ap(apdev[0], params)
1994
1995    dev[0].request("SET sae_groups ")
1996    dev[0].set("dpp_config_processing", "2")
1997    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
1998    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
1999
2000    dev[0].dpp_listen(2412)
2001    dev[1].dpp_auth_init(uri=uri0, conf=conf, ssid="dpp-legacy",
2002                         ssid_charset=ssid_charset,
2003                         passphrase="secret passphrase")
2004    wait_auth_success(dev[0], dev[1], configurator=dev[1], enrollee=dev[0])
2005    if ssid_charset:
2006        ev = dev[0].wait_event(["DPP-CONFOBJ-SSID-CHARSET"], timeout=1)
2007        if ev is None:
2008            raise Exception("ssid_charset not reported")
2009        charset = ev.split(' ')[1]
2010        if charset != str(ssid_charset):
2011            raise Exception("Incorrect ssid_charset reported: " + ev)
2012    ev = dev[0].wait_event(["DPP-NETWORK-ID"], timeout=1)
2013    if ev is None:
2014        raise Exception("DPP network profile not generated")
2015    id = ev.split(' ')[1]
2016
2017    dev[0].wait_connected()
2018
2019def test_dpp_auto_connect_legacy_pmf_required(dev, apdev):
2020    """DPP and auto connect (legacy, PMF required)"""
2021    try:
2022        run_dpp_auto_connect_legacy_pmf_required(dev, apdev)
2023    finally:
2024        dev[0].set("dpp_config_processing", "0", allow_fail=True)
2025
2026def run_dpp_auto_connect_legacy_pmf_required(dev, apdev):
2027    check_dpp_capab(dev[0])
2028    check_dpp_capab(dev[1])
2029
2030    params = hostapd.wpa2_params(ssid="dpp-legacy",
2031                                 passphrase="secret passphrase")
2032    params['wpa_key_mgmt'] = "WPA-PSK-SHA256"
2033    params['ieee80211w'] = "2"
2034    hapd = hostapd.add_ap(apdev[0], params)
2035
2036    dev[0].set("dpp_config_processing", "2")
2037    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
2038    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
2039    dev[0].dpp_listen(2412)
2040    dev[1].dpp_auth_init(uri=uri0, conf="sta-psk", ssid="dpp-legacy",
2041                         passphrase="secret passphrase")
2042    wait_auth_success(dev[0], dev[1], configurator=dev[1], enrollee=dev[0])
2043    ev = dev[0].wait_event(["DPP-NETWORK-ID"], timeout=1)
2044    if ev is None:
2045        raise Exception("DPP network profile not generated")
2046    dev[0].wait_connected()
2047
2048def test_dpp_qr_code_auth_responder_configurator(dev, apdev):
2049    """DPP QR Code and responder as the configurator"""
2050    run_dpp_qr_code_auth_responder_configurator(dev, apdev, "")
2051
2052def test_dpp_qr_code_auth_responder_configurator_group_id(dev, apdev):
2053    """DPP QR Code and responder as the configurator with group_id)"""
2054    run_dpp_qr_code_auth_responder_configurator(dev, apdev,
2055                                                " group_id=test-group")
2056
2057def run_dpp_qr_code_auth_responder_configurator(dev, apdev, extra):
2058    check_dpp_capab(dev[0])
2059    check_dpp_capab(dev[1])
2060    conf_id = dev[0].dpp_configurator_add()
2061    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
2062    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
2063    dev[0].set("dpp_configurator_params",
2064               " conf=sta-dpp configurator=%d%s" % (conf_id, extra))
2065    dev[0].dpp_listen(2412, role="configurator")
2066    dev[1].dpp_auth_init(uri=uri0, role="enrollee")
2067    wait_auth_success(dev[0], dev[1], configurator=dev[0], enrollee=dev[1],
2068                      stop_responder=True)
2069
2070def test_dpp_qr_code_auth_enrollee_init_netrole(dev, apdev):
2071    """DPP QR Code and enrollee initiating with netrole specified"""
2072    check_dpp_capab(dev[0])
2073    check_dpp_capab(dev[1])
2074    conf_id = dev[0].dpp_configurator_add()
2075    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
2076    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
2077    dev[0].set("dpp_configurator_params",
2078               " conf=configurator configurator=%d" % conf_id)
2079    dev[0].dpp_listen(2412, role="configurator")
2080    dev[1].dpp_auth_init(uri=uri0, role="enrollee", netrole="configurator")
2081    wait_auth_success(dev[0], dev[1], configurator=dev[0], enrollee=dev[1],
2082                      stop_responder=True)
2083    dev[0].dump_monitor()
2084    dev[1].dump_monitor()
2085
2086    # verify that netrole resets back to sta, if not explicitly stated
2087    dev[0].set("dpp_configurator_params",
2088               "conf=sta-dpp configurator=%d" % conf_id)
2089    dev[0].dpp_listen(2412, role="configurator")
2090    dev[1].dpp_auth_init(uri=uri0, role="enrollee")
2091    wait_auth_success(dev[0], dev[1], configurator=dev[0], enrollee=dev[1],
2092                      stop_responder=True)
2093
2094def test_dpp_qr_code_hostapd_init(dev, apdev):
2095    """DPP QR Code and hostapd as initiator"""
2096    check_dpp_capab(dev[0])
2097    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured",
2098                                     "channel": "6"})
2099    check_dpp_capab(hapd)
2100    conf_id = dev[0].dpp_configurator_add()
2101    id0 = dev[0].dpp_bootstrap_gen(chan="81/6", mac=True)
2102    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
2103    dev[0].set("dpp_configurator_params",
2104               " conf=ap-dpp configurator=%d" % conf_id)
2105    dev[0].dpp_listen(2437, role="configurator")
2106    hapd.dpp_auth_init(uri=uri0, role="enrollee")
2107    wait_auth_success(dev[0], hapd, configurator=dev[0], enrollee=hapd,
2108                      stop_responder=True)
2109
2110def test_dpp_qr_code_hostapd_init_offchannel(dev, apdev):
2111    """DPP QR Code and hostapd as initiator (offchannel)"""
2112    run_dpp_qr_code_hostapd_init_offchannel(dev, apdev, None)
2113
2114def test_dpp_qr_code_hostapd_init_offchannel_neg_freq(dev, apdev):
2115    """DPP QR Code and hostapd as initiator (offchannel, neg_freq)"""
2116    run_dpp_qr_code_hostapd_init_offchannel(dev, apdev, "neg_freq=2437")
2117
2118def run_dpp_qr_code_hostapd_init_offchannel(dev, apdev, extra):
2119    check_dpp_capab(dev[0])
2120    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured",
2121                                     "channel": "6"})
2122    check_dpp_capab(hapd)
2123    conf_id = dev[0].dpp_configurator_add()
2124    id0 = dev[0].dpp_bootstrap_gen(chan="81/1,81/11", mac=True)
2125    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
2126    dev[0].set("dpp_configurator_params",
2127               " conf=ap-dpp configurator=%d" % conf_id)
2128    dev[0].dpp_listen(2462, role="configurator")
2129    hapd.dpp_auth_init(uri=uri0, role="enrollee", extra=extra)
2130    wait_auth_success(dev[0], hapd, configurator=dev[0], enrollee=hapd,
2131                      stop_responder=True)
2132
2133def test_dpp_qr_code_hostapd_ignore_mismatch(dev, apdev):
2134    """DPP QR Code and hostapd ignoring netaccessKey mismatch"""
2135    check_dpp_capab(dev[0])
2136    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured",
2137                                     "channel": "6"})
2138    check_dpp_capab(hapd)
2139    conf_id = dev[0].dpp_configurator_add()
2140    id0 = dev[0].dpp_bootstrap_gen(chan="81/6", mac=True)
2141    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
2142    dev[0].set("dpp_configurator_params",
2143               "conf=ap-dpp configurator=%d" % conf_id)
2144    conf = '{"wi-fi_tech":"infra","discovery":{"ssid":"test"},"cred":{"akm":"dpp","signedConnector":"eyJ0eXAiOiJkcHBDb24iLCJraWQiOiJUbkdLaklsTlphYXRyRUFZcmJiamlCNjdyamtMX0FHVldYTzZxOWhESktVIiwiYWxnIjoiRVMyNTYifQ.eyJncm91cHMiOlt7Imdyb3VwSWQiOiIqIiwibmV0Um9sZSI6InN0YSJ9XSwibmV0QWNjZXNzS2V5Ijp7Imt0eSI6IkVDIiwiY3J2IjoiUC0yNTYiLCJ4IjoiYVRGNEpFR0lQS1NaMFh2OXpkQ01qbS10bjVYcE1zWUlWWjl3eVNBejFnSSIsInkiOiJRR2NIV0FfNnJiVTlYRFhBenRvWC1NNVEzc3VUbk1hcUVoVUx0bjdTU1h3In19._sm6YswxMf6hJLVTyYoU1uYUeY2VVkUNjrzjSiEhY42StD_RWowStEE-9CRsdCvLmsTptZ72_g40vTFwdId20A","csign":{"kty":"EC","crv":"P-256","x":"W4-Y5N1Pkos3UWb9A5qme0KUYRtY3CVUpekx_MapZ9s","y":"Et-M4NSF4NGjvh2VCh4B1sJ9eSCZ4RNzP2DBdP137VE","kid":"TnGKjIlNZaatrEAYrbbjiB67rjkL_AGVWXO6q9hDJKU"}}}'
2145    dev[0].set("dpp_config_obj_override", conf)
2146    dev[0].dpp_listen(2437, role="configurator")
2147    hapd.set("dpp_ignore_netaccesskey_mismatch", "1")
2148    hapd.dpp_auth_init(uri=uri0, role="enrollee")
2149    wait_auth_success(dev[0], hapd, configurator=dev[0], enrollee=hapd,
2150                      stop_responder=True)
2151
2152def test_dpp_test_vector_p_256(dev, apdev):
2153    """DPP P-256 test vector (mutual auth)"""
2154    check_dpp_capab(dev[0])
2155    check_dpp_capab(dev[1])
2156
2157    # Responder bootstrapping key
2158    priv = "54ce181a98525f217216f59b245f60e9df30ac7f6b26c939418cfc3c42d1afa0"
2159    id0 = dev[0].dpp_bootstrap_gen(chan="81/11", mac=True, key="30310201010420" + priv + "a00a06082a8648ce3d030107")
2160    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
2161
2162    # Responder protocol keypair override
2163    priv = "f798ed2e19286f6a6efe210b1863badb99af2a14b497634dbfd2a97394fb5aa5"
2164    dev[0].set("dpp_protocol_key_override",
2165               "30310201010420" + priv + "a00a06082a8648ce3d030107")
2166
2167    dev[0].set("dpp_nonce_override", "3d0cfb011ca916d796f7029ff0b43393")
2168
2169    # Initiator bootstrapping key
2170    priv = "15b2a83c5a0a38b61f2aa8200ee4994b8afdc01c58507d10d0a38f7eedf051bb"
2171    id1 = dev[1].dpp_bootstrap_gen(key="30310201010420" + priv + "a00a06082a8648ce3d030107")
2172    uri1 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id1)
2173
2174    # Initiator protocol keypair override
2175    priv = "a87de9afbb406c96e5f79a3df895ecac3ad406f95da66314c8cb3165e0c61783"
2176    dev[1].set("dpp_protocol_key_override",
2177               "30310201010420" + priv + "a00a06082a8648ce3d030107")
2178
2179    dev[1].set("dpp_nonce_override", "13f4602a16daeb69712263b9c46cba31")
2180
2181    dev[0].dpp_qr_code(uri1)
2182    dev[0].dpp_listen(2462, qr="mutual")
2183    dev[1].dpp_auth_init(uri=uri0, own=id1, neg_freq=2412)
2184    wait_auth_success(dev[0], dev[1])
2185
2186def test_dpp_test_vector_p_256_b(dev, apdev):
2187    """DPP P-256 test vector (Responder-only auth)"""
2188    check_dpp_capab(dev[0])
2189    check_dpp_capab(dev[1])
2190
2191    # Responder bootstrapping key
2192    priv = "54ce181a98525f217216f59b245f60e9df30ac7f6b26c939418cfc3c42d1afa0"
2193    id0 = dev[0].dpp_bootstrap_gen(chan="81/11", mac=True, key="30310201010420" + priv + "a00a06082a8648ce3d030107")
2194    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
2195
2196    # Responder protocol keypair override
2197    priv = "f798ed2e19286f6a6efe210b1863badb99af2a14b497634dbfd2a97394fb5aa5"
2198    dev[0].set("dpp_protocol_key_override",
2199               "30310201010420" + priv + "a00a06082a8648ce3d030107")
2200
2201    dev[0].set("dpp_nonce_override", "3d0cfb011ca916d796f7029ff0b43393")
2202
2203    # Initiator bootstrapping key
2204    priv = "15b2a83c5a0a38b61f2aa8200ee4994b8afdc01c58507d10d0a38f7eedf051bb"
2205    id1 = dev[1].dpp_bootstrap_gen(key="30310201010420" + priv + "a00a06082a8648ce3d030107")
2206    uri1 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id1)
2207
2208    # Initiator protocol keypair override
2209    priv = "a87de9afbb406c96e5f79a3df895ecac3ad406f95da66314c8cb3165e0c61783"
2210    dev[1].set("dpp_protocol_key_override",
2211               "30310201010420" + priv + "a00a06082a8648ce3d030107")
2212
2213    dev[1].set("dpp_nonce_override", "13f4602a16daeb69712263b9c46cba31")
2214
2215    dev[0].dpp_listen(2462)
2216    dev[1].dpp_auth_init(uri=uri0, own=id1, neg_freq=2412)
2217    wait_auth_success(dev[0], dev[1])
2218
2219def der_priv_key_p_521(priv):
2220    if len(priv) != 2 * 66:
2221        raise Exception("Unexpected der_priv_key_p_521 parameter: " + priv)
2222    der_prefix = "30500201010442"
2223    der_postfix = "a00706052b81040023"
2224    return der_prefix + priv + der_postfix
2225
2226def test_dpp_test_vector_p_521(dev, apdev):
2227    """DPP P-521 test vector (mutual auth)"""
2228    check_dpp_capab(dev[0])
2229    check_dpp_capab(dev[1])
2230
2231    # Responder bootstrapping key
2232    priv = "0061e54f518cdf859735da3dd64c6f72c2f086f41a6fd52915152ea2fe0f24ddaecd8883730c9c9fd82cf7c043a41021696388cf5190b731dd83638bcd56d8b6c743"
2233    id0 = dev[0].dpp_bootstrap_gen(chan="81/11", mac=True,
2234                                   key=der_priv_key_p_521(priv))
2235    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
2236
2237    # Responder protocol keypair override
2238    priv = "01d8b7b17cd1b0a33f7c66fb4220999329cdaf4f8b44b2ffadde8ab8ed8abffa9f5358c5b1caae26709ca4fb78e52a4d08f2e4f24111a36a6f440d20a0000ff51597"
2239    dev[0].set("dpp_protocol_key_override", der_priv_key_p_521(priv))
2240
2241    dev[0].set("dpp_nonce_override",
2242               "d749a782012eb0a8595af30b2dfc8d0880d004ebddb55ecc5afbdef18c400e01")
2243
2244    # Initiator bootstrapping key
2245    priv = "0060c10df14af5ef27f6e362d31bdd9eeb44be77a323ba64b08f3f03d58b92cbfe05c182a91660caa081ca344243c47b5aa088bcdf738840eb35f0218b9f26881e02"
2246    id1 = dev[1].dpp_bootstrap_gen(key=der_priv_key_p_521(priv))
2247    uri1 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id1)
2248
2249    # Initiator protocol keypair override
2250    priv = "019c1c08caaeec38fb931894699b095bc3ab8c1ec7ef0622d2e3eba821477c8c6fca41774f21166ad98aebda37c067d9aa08a8a2e1b5c44c61f2bae02a61f85d9661"
2251    dev[1].set("dpp_protocol_key_override", der_priv_key_p_521(priv))
2252
2253    dev[1].set("dpp_nonce_override",
2254               "de972af3847bec3ba2aedd9f5c21cfdec7bf0bc5fe8b276cbcd0267807fb15b0")
2255
2256    dev[0].dpp_qr_code(uri1)
2257    dev[0].dpp_listen(2462, qr="mutual")
2258    dev[1].dpp_auth_init(uri=uri0, own=id1, neg_freq=2412)
2259    wait_auth_success(dev[0], dev[1])
2260
2261def test_dpp_pkex(dev, apdev):
2262    """DPP and PKEX"""
2263    run_dpp_pkex(dev, apdev)
2264
2265def test_dpp_pkex_p256(dev, apdev):
2266    """DPP and PKEX (P-256)"""
2267    run_dpp_pkex(dev, apdev, "P-256")
2268
2269def test_dpp_pkex_p384(dev, apdev):
2270    """DPP and PKEX (P-384)"""
2271    run_dpp_pkex(dev, apdev, "P-384")
2272
2273def test_dpp_pkex_p521(dev, apdev):
2274    """DPP and PKEX (P-521)"""
2275    run_dpp_pkex(dev, apdev, "P-521")
2276
2277def test_dpp_pkex_bp256(dev, apdev):
2278    """DPP and PKEX (BP-256)"""
2279    run_dpp_pkex(dev, apdev, "brainpoolP256r1")
2280
2281def test_dpp_pkex_bp384(dev, apdev):
2282    """DPP and PKEX (BP-384)"""
2283    run_dpp_pkex(dev, apdev, "brainpoolP384r1")
2284
2285def test_dpp_pkex_bp512(dev, apdev):
2286    """DPP and PKEX (BP-512)"""
2287    run_dpp_pkex(dev, apdev, "brainpoolP512r1")
2288
2289def test_dpp_pkex_config(dev, apdev):
2290    """DPP and PKEX with initiator as the configurator"""
2291    check_dpp_capab(dev[1])
2292    conf_id = dev[1].dpp_configurator_add()
2293    run_dpp_pkex(dev, apdev,
2294                 init_extra="conf=sta-dpp configurator=%d" % (conf_id),
2295                 check_config=True)
2296
2297def test_dpp_pkex_no_identifier(dev, apdev):
2298    """DPP and PKEX without identifier"""
2299    run_dpp_pkex(dev, apdev, identifier_i=None, identifier_r=None)
2300
2301def test_dpp_pkex_identifier_mismatch(dev, apdev):
2302    """DPP and PKEX with different identifiers"""
2303    run_dpp_pkex(dev, apdev, identifier_i="foo", identifier_r="bar",
2304                 expect_no_resp=True)
2305
2306def test_dpp_pkex_identifier_mismatch2(dev, apdev):
2307    """DPP and PKEX with initiator using identifier and the responder not"""
2308    run_dpp_pkex(dev, apdev, identifier_i="foo", identifier_r=None,
2309                 expect_no_resp=True)
2310
2311def test_dpp_pkex_identifier_mismatch3(dev, apdev):
2312    """DPP and PKEX with responder using identifier and the initiator not"""
2313    run_dpp_pkex(dev, apdev, identifier_i=None, identifier_r="bar",
2314                 expect_no_resp=True)
2315
2316def run_dpp_pkex(dev, apdev, curve=None, init_extra=None, check_config=False,
2317                 identifier_i="test", identifier_r="test",
2318                 expect_no_resp=False):
2319    check_dpp_capab(dev[0], curve and "brainpool" in curve)
2320    check_dpp_capab(dev[1], curve and "brainpool" in curve)
2321    dev[0].dpp_pkex_resp(2437, identifier=identifier_r, code="secret",
2322                         curve=curve)
2323    dev[1].dpp_pkex_init(identifier=identifier_i, code="secret", curve=curve,
2324                         extra=init_extra)
2325
2326    if expect_no_resp:
2327        ev = dev[0].wait_event(["DPP-RX"], timeout=10)
2328        if ev is None:
2329            raise Exception("DPP PKEX frame not received")
2330        ev = dev[1].wait_event(["DPP-AUTH-SUCCESS"], timeout=1)
2331        if ev is not None:
2332            raise Exception("DPP authentication succeeded")
2333        ev = dev[0].wait_event(["DPP-AUTH-SUCCESS"], timeout=0.1)
2334        if ev is not None:
2335            raise Exception("DPP authentication succeeded")
2336        return
2337
2338    wait_auth_success(dev[0], dev[1],
2339                      configurator=dev[1] if check_config else None,
2340                      enrollee=dev[0] if check_config else None)
2341
2342def test_dpp_pkex_5ghz(dev, apdev):
2343    """DPP and PKEX on 5 GHz"""
2344    try:
2345        dev[0].request("SET country US")
2346        dev[1].request("SET country US")
2347        ev = dev[0].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=1)
2348        if ev is None:
2349            ev = dev[0].wait_global_event(["CTRL-EVENT-REGDOM-CHANGE"],
2350                                          timeout=1)
2351        run_dpp_pkex_5ghz(dev, apdev)
2352    finally:
2353        dev[0].request("SET country 00")
2354        dev[1].request("SET country 00")
2355        subprocess.call(['iw', 'reg', 'set', '00'])
2356        time.sleep(0.1)
2357
2358def run_dpp_pkex_5ghz(dev, apdev):
2359    check_dpp_capab(dev[0])
2360    check_dpp_capab(dev[1])
2361    dev[0].dpp_pkex_resp(5745, identifier="test", code="secret")
2362    dev[1].dpp_pkex_init(identifier="test", code="secret")
2363    wait_auth_success(dev[0], dev[1], timeout=20)
2364
2365def test_dpp_pkex_test_vector(dev, apdev):
2366    """DPP and PKEX (P-256) test vector"""
2367    check_dpp_capab(dev[0])
2368    check_dpp_capab(dev[1])
2369
2370    init_addr = "ac:64:91:f4:52:07"
2371    resp_addr = "6e:5e:ce:6e:f3:dd"
2372
2373    identifier = "joes_key"
2374    code = "thisisreallysecret"
2375
2376    # Initiator bootstrapping private key
2377    init_priv = "5941b51acfc702cdc1c347264beb2920db88eb1a0bf03a211868b1632233c269"
2378
2379    # Responder bootstrapping private key
2380    resp_priv = "2ae8956293f49986b6d0b8169a86805d9232babb5f6813fdfe96f19d59536c60"
2381
2382    # Initiator x/X keypair override
2383    init_x_priv = "8365c5ed93d751bef2d92b410dc6adfd95670889183fac1bd66759ad85c3187a"
2384
2385    # Responder y/Y keypair override
2386    resp_y_priv = "d98faa24d7dd3f592665d71a95c862bfd02c4c48acb0c515a41cbc6e929675ea"
2387
2388    p256_prefix = "30310201010420"
2389    p256_postfix = "a00a06082a8648ce3d030107"
2390
2391    dev[0].set("dpp_pkex_own_mac_override", resp_addr)
2392    dev[0].set("dpp_pkex_peer_mac_override", init_addr)
2393    dev[1].set("dpp_pkex_own_mac_override", init_addr)
2394    dev[1].set("dpp_pkex_peer_mac_override", resp_addr)
2395
2396    # Responder y/Y keypair override
2397    dev[0].set("dpp_pkex_ephemeral_key_override",
2398               p256_prefix + resp_y_priv + p256_postfix)
2399
2400    # Initiator x/X keypair override
2401    dev[1].set("dpp_pkex_ephemeral_key_override",
2402               p256_prefix + init_x_priv + p256_postfix)
2403
2404    dev[0].dpp_pkex_resp(2437, identifier=identifier, code=code,
2405                         key=p256_prefix + resp_priv + p256_postfix)
2406    dev[1].dpp_pkex_init(identifier=identifier, code=code,
2407                         key=p256_prefix + init_priv + p256_postfix)
2408    wait_auth_success(dev[0], dev[1])
2409
2410def test_dpp_pkex_code_mismatch(dev, apdev):
2411    """DPP and PKEX with mismatching code"""
2412    check_dpp_capab(dev[0])
2413    check_dpp_capab(dev[1])
2414    dev[0].dpp_pkex_resp(2437, identifier="test", code="secret")
2415    id1 = dev[1].dpp_pkex_init(identifier="test", code="unknown")
2416    wait_dpp_fail(dev[0], "possible PKEX code mismatch")
2417    dev[0].dump_monitor()
2418    dev[1].dump_monitor()
2419    dev[1].dpp_pkex_init(identifier="test", code="secret", use_id=id1)
2420    wait_auth_success(dev[0], dev[1])
2421
2422def test_dpp_pkex_code_mismatch_limit(dev, apdev):
2423    """DPP and PKEX with mismatching code limit"""
2424    check_dpp_capab(dev[0])
2425    check_dpp_capab(dev[1])
2426    dev[0].dpp_pkex_resp(2437, identifier="test", code="secret")
2427
2428    id1 = None
2429    for i in range(5):
2430        dev[0].dump_monitor()
2431        dev[1].dump_monitor()
2432        id1 = dev[1].dpp_pkex_init(identifier="test", code="unknown",
2433                                   use_id=id1)
2434        wait_dpp_fail(dev[0], "possible PKEX code mismatch")
2435
2436    ev = dev[0].wait_event(["DPP-PKEX-T-LIMIT"], timeout=1)
2437    if ev is None:
2438        raise Exception("PKEX t limit not reported")
2439
2440def test_dpp_pkex_curve_mismatch(dev, apdev):
2441    """DPP and PKEX with mismatching curve"""
2442    check_dpp_capab(dev[0])
2443    check_dpp_capab(dev[1])
2444    dev[0].dpp_pkex_resp(2437, identifier="test", code="secret", curve="P-256")
2445    dev[1].dpp_pkex_init(identifier="test", code="secret", curve="P-384")
2446    wait_dpp_fail(dev[0], "Mismatching PKEX curve: peer=20 own=19")
2447    wait_dpp_fail(dev[1], "Peer indicated mismatching PKEX group - proposed 19")
2448
2449def test_dpp_pkex_curve_mismatch_failure(dev, apdev):
2450    """DPP and PKEX with mismatching curve (local failure)"""
2451    run_dpp_pkex_curve_mismatch_failure(dev, apdev, "=dpp_pkex_rx_exchange_req")
2452
2453def test_dpp_pkex_curve_mismatch_failure2(dev, apdev):
2454    """DPP and PKEX with mismatching curve (local failure 2)"""
2455    run_dpp_pkex_curve_mismatch_failure(dev, apdev,
2456                                        "dpp_pkex_build_exchange_resp")
2457
2458def run_dpp_pkex_curve_mismatch_failure(dev, apdev, func):
2459    check_dpp_capab(dev[0])
2460    check_dpp_capab(dev[1])
2461    dev[0].dpp_pkex_resp(2437, identifier="test", code="secret", curve="P-256")
2462
2463    with alloc_fail(dev[0], 1, func):
2464        dev[1].dpp_pkex_init(identifier="test", code="secret", curve="P-384")
2465
2466        ev = dev[0].wait_event(["DPP-FAIL"], timeout=5)
2467        if ev is None:
2468            raise Exception("Failure not reported (dev 0)")
2469        if "Mismatching PKEX curve: peer=20 own=19" not in ev:
2470            raise Exception("Unexpected result: " + ev)
2471        wait_dpp_fail(dev[0], "Mismatching PKEX curve: peer=20 own=19")
2472
2473def test_dpp_pkex_exchange_resp_processing_failure(dev, apdev):
2474    """DPP and PKEX with local failure in processing Exchange Resp"""
2475    check_dpp_capab(dev[0])
2476    check_dpp_capab(dev[1])
2477    dev[0].dpp_pkex_resp(2437, identifier="test", code="secret")
2478
2479    with fail_test(dev[1], 1, "dpp_pkex_derive_Qr;dpp_pkex_rx_exchange_resp"):
2480        dev[1].dpp_pkex_init(identifier="test", code="secret")
2481        wait_fail_trigger(dev[1], "GET_FAIL")
2482
2483def test_dpp_pkex_commit_reveal_req_processing_failure(dev, apdev):
2484    """DPP and PKEX with local failure in processing Commit Reveal Req"""
2485    check_dpp_capab(dev[0])
2486    check_dpp_capab(dev[1])
2487    dev[0].dpp_pkex_resp(2437, identifier="test", code="secret")
2488
2489    with alloc_fail(dev[0], 1,
2490                    "crypto_ec_key_get_pubkey_point;dpp_pkex_rx_commit_reveal_req"):
2491        dev[1].dpp_pkex_init(identifier="test", code="secret")
2492        wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
2493
2494def test_dpp_pkex_config2(dev, apdev):
2495    """DPP and PKEX with responder as the configurator"""
2496    check_dpp_capab(dev[0])
2497    conf_id = dev[0].dpp_configurator_add()
2498    dev[0].set("dpp_configurator_params",
2499               " conf=sta-dpp configurator=%d" % conf_id)
2500    run_dpp_pkex2(dev, apdev)
2501
2502def run_dpp_pkex2(dev, apdev, curve=None, init_extra=""):
2503    check_dpp_capab(dev[0])
2504    check_dpp_capab(dev[1])
2505    dev[0].dpp_pkex_resp(2437, identifier="test", code="secret", curve=curve,
2506                         listen_role="configurator")
2507    dev[1].dpp_pkex_init(identifier="test", code="secret", role="enrollee",
2508                         curve=curve, extra=init_extra)
2509    wait_auth_success(dev[0], dev[1], configurator=dev[0], enrollee=dev[1])
2510
2511def test_dpp_pkex_no_responder(dev, apdev):
2512    """DPP and PKEX with no responder (retry behavior)"""
2513    check_dpp_capab(dev[0])
2514    dev[0].dpp_pkex_init(identifier="test", code="secret")
2515
2516    for i in range(15):
2517        ev = dev[0].wait_event(["DPP-TX ", "DPP-FAIL"], timeout=5)
2518        if ev is None:
2519            raise Exception("DPP PKEX failure not reported")
2520        if "DPP-FAIL" not in ev:
2521            continue
2522        if "No response from PKEX peer" not in ev:
2523            raise Exception("Unexpected failure reason: " + ev)
2524        break
2525
2526def test_dpp_pkex_after_retry(dev, apdev):
2527    """DPP and PKEX completing after retry"""
2528    check_dpp_capab(dev[0])
2529    dev[0].dpp_pkex_init(identifier="test", code="secret")
2530    time.sleep(0.1)
2531    dev[1].dpp_pkex_resp(2437, identifier="test", code="secret")
2532    wait_auth_success(dev[1], dev[0], configurator=dev[0], enrollee=dev[1],
2533                      allow_enrollee_failure=True)
2534
2535def test_dpp_pkex_hostapd_responder(dev, apdev):
2536    """DPP PKEX with hostapd as responder"""
2537    check_dpp_capab(dev[0])
2538    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured",
2539                                     "channel": "6"})
2540    check_dpp_capab(hapd)
2541    hapd.dpp_pkex_resp(2437, identifier="test", code="secret")
2542    conf_id = dev[0].dpp_configurator_add()
2543    dev[0].dpp_pkex_init(identifier="test", code="secret",
2544                         extra="conf=ap-dpp configurator=%d" % conf_id)
2545    wait_auth_success(hapd, dev[0], configurator=dev[0], enrollee=hapd,
2546                      stop_initiator=True)
2547
2548def test_dpp_pkex_hostapd_initiator(dev, apdev):
2549    """DPP PKEX with hostapd as initiator"""
2550    check_dpp_capab(dev[0])
2551    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured",
2552                                     "channel": "6"})
2553    check_dpp_capab(hapd)
2554    conf_id = dev[0].dpp_configurator_add()
2555    dev[0].set("dpp_configurator_params",
2556               " conf=ap-dpp configurator=%d" % conf_id)
2557    dev[0].dpp_pkex_resp(2437, identifier="test", code="secret",
2558                         listen_role="configurator")
2559    hapd.dpp_pkex_init(identifier="test", code="secret", role="enrollee")
2560    wait_auth_success(hapd, dev[0], configurator=dev[0], enrollee=hapd,
2561                      stop_initiator=True)
2562
2563def test_dpp_pkex_hostapd_errors(dev, apdev):
2564    """DPP PKEX errors with hostapd"""
2565    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured",
2566                                     "channel": "6"})
2567    check_dpp_capab(hapd)
2568    id0 = hapd.dpp_bootstrap_gen(type="pkex")
2569    tests = ["own=%d" % id0,
2570             "own=%d identifier=foo" % id0,
2571             ""]
2572    for t in tests:
2573        if "FAIL" not in hapd.request("DPP_PKEX_ADD " + t):
2574            raise Exception("Invalid DPP_PKEX_ADD accepted: " + t)
2575
2576    res = hapd.request("DPP_PKEX_ADD own=%d code=foo" % id0)
2577    if "FAIL" in res:
2578        raise Exception("Failed to add PKEX responder")
2579    if "OK" not in hapd.request("DPP_PKEX_REMOVE " + res):
2580        raise Exception("Failed to remove PKEX responder")
2581    if "FAIL" not in hapd.request("DPP_PKEX_REMOVE " + res):
2582        raise Exception("Unknown PKEX responder removal accepted")
2583
2584    res = hapd.request("DPP_PKEX_ADD own=%d code=foo" % id0)
2585    if "FAIL" in res:
2586        raise Exception("Failed to add PKEX responder")
2587    if "OK" not in hapd.request("DPP_PKEX_REMOVE *"):
2588        raise Exception("Failed to flush PKEX responders")
2589    hapd.request("DPP_PKEX_REMOVE *")
2590
2591def test_dpp_hostapd_configurator(dev, apdev):
2592    """DPP with hostapd as configurator/initiator"""
2593    run_dpp_hostapd_configurator(dev, apdev)
2594
2595def test_dpp_hostapd_configurator_enrollee_v1(dev, apdev):
2596    """DPP with hostapd as configurator/initiator with v1 enrollee"""
2597    dev[0].set("dpp_version_override", "1")
2598    run_dpp_hostapd_configurator(dev, apdev)
2599
2600def run_dpp_hostapd_configurator(dev, apdev):
2601    check_dpp_capab(dev[0])
2602    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured",
2603                                     "channel": "1"})
2604    check_dpp_capab(hapd)
2605    conf_id = hapd.dpp_configurator_add()
2606    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
2607    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
2608    id1 = hapd.dpp_qr_code(uri0)
2609    res = hapd.request("DPP_BOOTSTRAP_INFO %d" % id1)
2610    if "FAIL" in res:
2611        raise Exception("DPP_BOOTSTRAP_INFO failed")
2612    if "type=QRCODE" not in res:
2613        raise Exception("DPP_BOOTSTRAP_INFO did not report correct type")
2614    if "mac_addr=" + dev[0].own_addr() not in res:
2615        raise Exception("DPP_BOOTSTRAP_INFO did not report correct mac_addr")
2616    dev[0].dpp_listen(2412)
2617    hapd.dpp_auth_init(peer=id1, configurator=conf_id, conf="sta-dpp")
2618    wait_auth_success(dev[0], hapd, configurator=hapd, enrollee=dev[0],
2619                      stop_responder=True)
2620
2621def test_dpp_hostapd_configurator_responder(dev, apdev):
2622    """DPP with hostapd as configurator/responder"""
2623    check_dpp_capab(dev[0])
2624    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured",
2625                                     "channel": "1"})
2626    check_dpp_capab(hapd)
2627    conf_id = hapd.dpp_configurator_add()
2628    hapd.set("dpp_configurator_params",
2629             " conf=sta-dpp configurator=%d" % conf_id)
2630    id0 = hapd.dpp_bootstrap_gen(chan="81/1", mac=True)
2631    uri0 = hapd.request("DPP_BOOTSTRAP_GET_URI %d" % id0)
2632    dev[0].dpp_auth_init(uri=uri0, role="enrollee")
2633    wait_auth_success(hapd, dev[0], configurator=hapd, enrollee=dev[0],
2634                      stop_initiator=True)
2635
2636def test_dpp_hostapd_configurator_fragmentation(dev, apdev):
2637    """DPP with hostapd as configurator/initiator requiring fragmentation"""
2638    check_dpp_capab(dev[0])
2639    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured",
2640                                     "channel": "1"})
2641    check_dpp_capab(hapd)
2642    conf_id = hapd.dpp_configurator_add()
2643    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
2644    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
2645    id1 = hapd.dpp_qr_code(uri0)
2646    res = hapd.request("DPP_BOOTSTRAP_INFO %d" % id1)
2647    if "FAIL" in res:
2648        raise Exception("DPP_BOOTSTRAP_INFO failed")
2649    if "type=QRCODE" not in res:
2650        raise Exception("DPP_BOOTSTRAP_INFO did not report correct type")
2651    if "mac_addr=" + dev[0].own_addr() not in res:
2652        raise Exception("DPP_BOOTSTRAP_INFO did not report correct mac_addr")
2653    dev[0].dpp_listen(2412)
2654    conf = '{"wi-fi_tech":"infra", "discovery":{"ssid":"test"},"cred":{"akm":"psk","pass":"secret passphrase"}}' + 3000*' '
2655    hapd.set("dpp_config_obj_override", conf)
2656    hapd.dpp_auth_init(peer=id1, configurator=conf_id, conf="sta-dpp")
2657    wait_auth_success(dev[0], hapd, configurator=hapd, enrollee=dev[0],
2658                      stop_responder=True)
2659
2660def test_dpp_hostapd_enrollee_fragmentation(dev, apdev):
2661    """DPP and hostapd as Enrollee with GAS fragmentation"""
2662    check_dpp_capab(dev[0])
2663    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured",
2664                                     "channel": "6"})
2665    check_dpp_capab(hapd)
2666    conf_id = dev[0].dpp_configurator_add()
2667    id0 = dev[0].dpp_bootstrap_gen(chan="81/6", mac=True)
2668    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
2669    conf = '{"wi-fi_tech":"infra", "discovery":{"ssid":"test"},"cred":{"akm":"psk","pass":"secret passphrase"}}' + 3000*' '
2670    dev[0].set("dpp_config_obj_override", conf)
2671    dev[0].set("dpp_configurator_params",
2672               " conf=ap-dpp configurator=%d" % conf_id)
2673    dev[0].dpp_listen(2437, role="configurator")
2674    hapd.dpp_auth_init(uri=uri0, role="enrollee")
2675    wait_auth_success(dev[0], hapd, configurator=dev[0], enrollee=hapd,
2676                      stop_responder=True)
2677
2678def test_dpp_hostapd_enrollee_gas_timeout(dev, apdev):
2679    """DPP and hostapd as Enrollee with GAS timeout"""
2680    check_dpp_capab(dev[0])
2681    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured",
2682                                     "channel": "6"})
2683    check_dpp_capab(hapd)
2684    conf_id = dev[0].dpp_configurator_add()
2685    id0 = dev[0].dpp_bootstrap_gen(chan="81/6", mac=True)
2686    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
2687    conf = '{"wi-fi_tech":"infra", "discovery":{"ssid":"test"},"cred":{"akm":"psk","pass":"secret passphrase"}}' + 3000*' '
2688    dev[0].set("dpp_config_obj_override", conf)
2689    dev[0].set("dpp_configurator_params",
2690               "conf=ap-dpp configurator=%d" % conf_id)
2691    dev[0].set("ext_mgmt_frame_handling", "1")
2692    dev[0].dpp_listen(2437, role="configurator")
2693    hapd.dpp_auth_init(uri=uri0, role="enrollee")
2694    process_dpp_frames(dev[0])
2695    ev = hapd.wait_event(["GAS-QUERY-DONE"], timeout=10)
2696    if "result=TIMEOUT" not in ev:
2697        raise Exception("GAS timeout not reported")
2698
2699def test_dpp_hostapd_enrollee_gas_timeout_comeback(dev, apdev):
2700    """DPP and hostapd as Enrollee with GAS timeout during comeback"""
2701    check_dpp_capab(dev[0])
2702    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured",
2703                                     "channel": "6"})
2704    check_dpp_capab(hapd)
2705    conf_id = dev[0].dpp_configurator_add()
2706    id0 = dev[0].dpp_bootstrap_gen(chan="81/6", mac=True)
2707    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
2708    conf = '{"wi-fi_tech":"infra", "discovery":{"ssid":"test"},"cred":{"akm":"psk","pass":"secret passphrase"}}' + 3000*' '
2709    dev[0].set("dpp_config_obj_override", conf)
2710    dev[0].set("dpp_configurator_params",
2711               "conf=ap-dpp configurator=%d" % conf_id)
2712    dev[0].set("ext_mgmt_frame_handling", "1")
2713    dev[0].dpp_listen(2437, role="configurator")
2714    hapd.dpp_auth_init(uri=uri0, role="enrollee")
2715    process_dpp_frames(dev[0], count=4)
2716    ev = hapd.wait_event(["GAS-QUERY-DONE"], timeout=10)
2717    if "result=TIMEOUT" not in ev:
2718        raise Exception("GAS timeout not reported")
2719
2720def process_dpp_frames(dev, count=3):
2721    for i in range(count):
2722        msg = dev.mgmt_rx()
2723        cmd = "MGMT_RX_PROCESS freq={} datarate={} ssi_signal={} frame={}".format(msg['freq'], msg['datarate'], msg['ssi_signal'], binascii.hexlify(msg['frame']).decode())
2724        if "OK" not in dev.request(cmd):
2725            raise Exception("MGMT_RX_PROCESS failed")
2726
2727def test_dpp_hostapd_enrollee_gas_errors(dev, apdev):
2728    """DPP and hostapd as Enrollee with GAS query local errors"""
2729    check_dpp_capab(dev[0])
2730    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured",
2731                                     "channel": "6"})
2732    check_dpp_capab(hapd)
2733    conf_id = dev[0].dpp_configurator_add()
2734    id0 = dev[0].dpp_bootstrap_gen(chan="81/6", mac=True)
2735    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
2736    dev[0].set("dpp_configurator_params",
2737               "conf=ap-dpp configurator=%d" % conf_id)
2738    dev[0].set("ext_mgmt_frame_handling", "1")
2739
2740    # GAS without comeback
2741    tests = [(1, "gas_query_append;gas_query_rx_initial", 3, True),
2742             (1, "gas_query_rx_initial", 3, True),
2743             (1, "gas_query_tx_initial_req", 2, True),
2744             (1, "gas_query_ap_req", 2, False)]
2745    for count, func, frame_count, wait_ev in tests:
2746        dev[0].request("DPP_STOP_LISTEN")
2747        dev[0].dpp_listen(2437, role="configurator")
2748        dev[0].dump_monitor()
2749        hapd.dump_monitor()
2750        with alloc_fail(hapd, count, func):
2751            hapd.dpp_auth_init(uri=uri0, role="enrollee")
2752            process_dpp_frames(dev[0], count=frame_count)
2753            if wait_ev:
2754                ev = hapd.wait_event(["GAS-QUERY-DONE"], timeout=10)
2755                if not ev or "result=INTERNAL_ERROR" not in ev:
2756                    raise Exception("Unexpect GAS query result: " + str(ev))
2757
2758    # GAS with comeback
2759    conf = '{"wi-fi_tech":"infra", "discovery":{"ssid":"test"},"cred":{"akm":"psk","pass":"secret passphrase"}}' + 3000*' '
2760    dev[0].set("dpp_config_obj_override", conf)
2761
2762    tests = [(1, "gas_query_append;gas_query_rx_comeback", 4),
2763             (1, "wpabuf_alloc;gas_query_tx_comeback_req", 3),
2764             (1, "hostapd_drv_send_action;gas_query_tx_comeback_req", 3)]
2765    for count, func, frame_count in tests:
2766        dev[0].request("DPP_STOP_LISTEN")
2767        dev[0].dpp_listen(2437, role="configurator")
2768        dev[0].dump_monitor()
2769        hapd.dump_monitor()
2770        with alloc_fail(hapd, count, func):
2771            hapd.dpp_auth_init(uri=uri0, role="enrollee")
2772            process_dpp_frames(dev[0], count=frame_count)
2773            ev = hapd.wait_event(["GAS-QUERY-DONE"], timeout=10)
2774            if not ev or "result=INTERNAL_ERROR" not in ev:
2775                raise Exception("Unexpect GAS query result: " + str(ev))
2776
2777def test_dpp_hostapd_enrollee_gas_proto(dev, apdev):
2778    """DPP and hostapd as Enrollee with GAS query protocol testing"""
2779    check_dpp_capab(dev[0])
2780    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured",
2781                                     "channel": "6"})
2782    check_dpp_capab(hapd)
2783    bssid = hapd.own_addr()
2784    conf_id = dev[0].dpp_configurator_add()
2785    id0 = dev[0].dpp_bootstrap_gen(chan="81/6", mac=True)
2786    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
2787    dev[0].set("dpp_configurator_params",
2788               "conf=ap-dpp configurator=%d" % conf_id)
2789    conf = '{"wi-fi_tech":"infra", "discovery":{"ssid":"test"},"cred":{"akm":"psk","pass":"secret passphrase"}}' + 3000*' '
2790    dev[0].set("dpp_config_obj_override", conf)
2791    dev[0].set("ext_mgmt_frame_handling", "1")
2792    dev[0].dpp_listen(2437, role="configurator")
2793    hapd.dpp_auth_init(uri=uri0, role="enrollee")
2794    process_dpp_frames(dev[0], count=3)
2795    msg = dev[0].mgmt_rx()
2796    payload = msg['payload']
2797    dialog_token, = struct.unpack('B', payload[2:3])
2798    hdr = struct.pack('<BBBHBH', 4, 13, dialog_token, 0, 0x80, 0)
2799    # GAS: Advertisement Protocol changed between initial and comeback response from 02:00:00:00:00:00
2800    adv_proto = "6c087fdd05506f9a1a02"
2801    action = binascii.hexlify(hdr).decode() + adv_proto + "0300" + "001001"
2802    cmd = "MGMT_TX %s %s freq=2437 wait_time=100 action=%s" % (bssid, bssid, action)
2803    dev[0].request(cmd)
2804    ev = hapd.wait_event(["GAS-QUERY-DONE"], timeout=10)
2805    if not ev or "result=PEER_ERROR" not in ev:
2806        raise Exception("Unexpect GAS query result: " + str(ev))
2807    dev[0].request("DPP_STOP_LISTEN")
2808    hapd.dump_monitor()
2809    dev[0].dump_monitor()
2810
2811    dev[0].dpp_listen(2437, role="configurator")
2812    hapd.dpp_auth_init(uri=uri0, role="enrollee")
2813    process_dpp_frames(dev[0], count=3)
2814    msg = dev[0].mgmt_rx()
2815    payload = msg['payload']
2816    dialog_token, = struct.unpack('B', payload[2:3])
2817    # Another comeback delay
2818    hdr = struct.pack('<BBBHBH', 4, 13, dialog_token, 0, 0x80, 1)
2819    adv_proto = "6c087fdd05506f9a1a01"
2820    action = binascii.hexlify(hdr).decode() + adv_proto + "0300" + "001001"
2821    cmd = "MGMT_TX %s %s freq=2437 wait_time=100 action=%s" % (bssid, bssid, action)
2822    dev[0].request(cmd)
2823    msg = dev[0].mgmt_rx()
2824    hdr = struct.pack('<BBBHBH', 4, 13, dialog_token, 0, 0x81, 1)
2825    # GAS: Invalid comeback response with non-zero frag_id and comeback_delay from 02:00:00:00:00:00
2826    action = binascii.hexlify(hdr).decode() + adv_proto + "0300" + "001001"
2827    cmd = "MGMT_TX %s %s freq=2437 wait_time=100 action=%s" % (bssid, bssid, action)
2828    dev[0].request(cmd)
2829    ev = hapd.wait_event(["GAS-QUERY-DONE"], timeout=10)
2830    if not ev or "result=PEER_ERROR" not in ev:
2831        raise Exception("Unexpect GAS query result: " + str(ev))
2832    dev[0].request("DPP_STOP_LISTEN")
2833    hapd.dump_monitor()
2834    dev[0].dump_monitor()
2835
2836    dev[0].dpp_listen(2437, role="configurator")
2837    hapd.dpp_auth_init(uri=uri0, role="enrollee")
2838    process_dpp_frames(dev[0], count=3)
2839    msg = dev[0].mgmt_rx()
2840    payload = msg['payload']
2841    dialog_token, = struct.unpack('B', payload[2:3])
2842    # Valid comeback response
2843    hdr = struct.pack('<BBBHBH', 4, 13, dialog_token, 0, 0x80, 0)
2844    action = binascii.hexlify(hdr).decode() + adv_proto + "0300" + "001001"
2845    cmd = "MGMT_TX %s %s freq=2437 wait_time=100 action=%s" % (bssid, bssid, action)
2846    dev[0].request(cmd)
2847    msg = dev[0].mgmt_rx()
2848    # GAS: Drop frame as possible retry of previous fragment
2849    hdr = struct.pack('<BBBHBH', 4, 13, dialog_token, 0, 0x80, 0)
2850    action = binascii.hexlify(hdr).decode() + adv_proto + "0300" + "001001"
2851    cmd = "MGMT_TX %s %s freq=2437 wait_time=100 action=%s" % (bssid, bssid, action)
2852    dev[0].request(cmd)
2853    # GAS: Unexpected frag_id in response from 02:00:00:00:00:00
2854    hdr = struct.pack('<BBBHBH', 4, 13, dialog_token, 0, 0x82, 0)
2855    action = binascii.hexlify(hdr).decode() + adv_proto + "0300" + "001001"
2856    cmd = "MGMT_TX %s %s freq=2437 wait_time=100 action=%s" % (bssid, bssid, action)
2857    dev[0].request(cmd)
2858    ev = hapd.wait_event(["GAS-QUERY-DONE"], timeout=10)
2859    if not ev or "result=PEER_ERROR" not in ev:
2860        raise Exception("Unexpect GAS query result: " + str(ev))
2861    dev[0].request("DPP_STOP_LISTEN")
2862    hapd.dump_monitor()
2863    dev[0].dump_monitor()
2864
2865    dev[0].dpp_listen(2437, role="configurator")
2866    hapd.dpp_auth_init(uri=uri0, role="enrollee")
2867    process_dpp_frames(dev[0], count=3)
2868    msg = dev[0].mgmt_rx()
2869    payload = msg['payload']
2870    dialog_token, = struct.unpack('B', payload[2:3])
2871    # GAS: Unexpected initial response from 02:00:00:00:00:00 dialog token 3 when waiting for comeback response
2872    hdr = struct.pack('<BBBHBH', 4, 11, dialog_token, 0, 0x80, 0)
2873    action = binascii.hexlify(hdr).decode() + adv_proto + "0300" + "001001"
2874    cmd = "MGMT_TX %s %s freq=2437 wait_time=100 action=%s" % (bssid, bssid, action)
2875    dev[0].request(cmd)
2876    # GAS: Allow non-zero status for outstanding comeback response
2877    hdr = struct.pack('<BBBHBH', 4, 13, dialog_token, 95, 0x80, 0)
2878    # GAS: Ignore 1 octets of extra data after Query Response from 02:00:00:00:00:00
2879    action = binascii.hexlify(hdr).decode() + adv_proto + "0300" + "001001" + "ff"
2880    cmd = "MGMT_TX %s %s freq=2437 wait_time=100 action=%s" % (bssid, bssid, action)
2881    dev[0].request(cmd)
2882    # GAS: No pending query found for 02:00:00:00:00:00 dialog token 4
2883    hdr = struct.pack('<BBBHBH', 4, 13, (dialog_token + 1) % 256, 0, 0x80, 0)
2884    action = binascii.hexlify(hdr).decode() + adv_proto + "0300" + "001001"
2885    cmd = "MGMT_TX %s %s freq=2437 wait_time=100 action=%s" % (bssid, bssid, action)
2886    dev[0].request(cmd)
2887    # GAS: Truncated Query Response in response from 02:00:00:00:00:00
2888    hdr = struct.pack('<BBBHBH', 4, 13, dialog_token, 0, 0x81, 0)
2889    action = binascii.hexlify(hdr).decode() + adv_proto + "0300" + "0010"
2890    cmd = "MGMT_TX %s %s freq=2437 wait_time=100 action=%s" % (bssid, bssid, action)
2891    dev[0].request(cmd)
2892    # GAS: No room for GAS Response Length
2893    hdr = struct.pack('<BBBHBH', 4, 13, dialog_token, 0, 0x81, 0)
2894    action = binascii.hexlify(hdr).decode() + adv_proto + "03"
2895    cmd = "MGMT_TX %s %s freq=2437 wait_time=100 action=%s" % (bssid, bssid, action)
2896    dev[0].request(cmd)
2897    # GAS: Unexpected Advertisement Protocol element ID 0 in response from 02:00:00:00:00:00
2898    hdr = struct.pack('<BBBHBH', 4, 13, dialog_token, 0, 0x81, 0)
2899    adv_proto_broken = "0000"
2900    action = binascii.hexlify(hdr).decode() + adv_proto_broken + "0300" + "001001"
2901    cmd = "MGMT_TX %s %s freq=2437 wait_time=100 action=%s" % (bssid, bssid, action)
2902    dev[0].request(cmd)
2903    # GAS: No room for Advertisement Protocol element in the response from 02:00:00:00:00:00
2904    hdr = struct.pack('<BBBHBH', 4, 13, dialog_token, 0, 0x81, 0)
2905    adv_proto_broken = "00ff"
2906    action = binascii.hexlify(hdr).decode() + adv_proto_broken + "0300" + "001001"
2907    cmd = "MGMT_TX %s %s freq=2437 wait_time=100 action=%s" % (bssid, bssid, action)
2908    dev[0].request(cmd)
2909    # No room for Comeback Delay
2910    hdr = struct.pack('<BBBHBB', 4, 13, dialog_token, 0, 0x81, 0)
2911    action = binascii.hexlify(hdr).decode()
2912    cmd = "MGMT_TX %s %s freq=2437 wait_time=100 action=%s" % (bssid, bssid, action)
2913    dev[0].request(cmd)
2914    # No room for frag_id
2915    hdr = struct.pack('<BBBH', 4, 13, dialog_token, 0)
2916    action = binascii.hexlify(hdr).decode()
2917    cmd = "MGMT_TX %s %s freq=2437 wait_time=100 action=%s" % (bssid, bssid, action)
2918    dev[0].request(cmd)
2919    # GAS: Query to 02:00:00:00:00:00 dialog token 3 failed - status code 1
2920    hdr = struct.pack('<BBBHBH', 4, 13, dialog_token, 1, 0x81, 0)
2921    action = binascii.hexlify(hdr).decode() + adv_proto + "0300" + "001001"
2922    cmd = "MGMT_TX %s %s freq=2437 wait_time=100 action=%s" % (bssid, bssid, action)
2923    dev[0].request(cmd)
2924    ev = hapd.wait_event(["GAS-QUERY-DONE"], timeout=10)
2925    if not ev or "result=FAILURE" not in ev:
2926        raise Exception("Unexpect GAS query result: " + str(ev))
2927    dev[0].request("DPP_STOP_LISTEN")
2928    hapd.dump_monitor()
2929    dev[0].dump_monitor()
2930
2931    dev[0].dpp_listen(2437, role="configurator")
2932    hapd.dpp_auth_init(uri=uri0, role="enrollee")
2933    process_dpp_frames(dev[0], count=2)
2934    msg = dev[0].mgmt_rx()
2935    payload = msg['payload']
2936    dialog_token, = struct.unpack('B', payload[2:3])
2937    # Unexpected comeback delay
2938    hdr = struct.pack('<BBBHBH', 4, 13, dialog_token, 0, 0x80, 0)
2939    adv_proto = "6c087fdd05506f9a1a01"
2940    action = binascii.hexlify(hdr).decode() + adv_proto + "0300" + "001001"
2941    cmd = "MGMT_TX %s %s freq=2437 wait_time=100 action=%s" % (bssid, bssid, action)
2942    dev[0].request(cmd)
2943    # GAS: Query to 02:00:00:00:00:00 dialog token 3 failed - status code 1
2944    hdr = struct.pack('<BBBHBH', 4, 11, dialog_token, 1, 0x80, 0)
2945    action = binascii.hexlify(hdr).decode() + adv_proto + "0300" + "001001"
2946    cmd = "MGMT_TX %s %s freq=2437 wait_time=100 action=%s" % (bssid, bssid, action)
2947    dev[0].request(cmd)
2948    ev = hapd.wait_event(["GAS-QUERY-DONE"], timeout=10)
2949    if not ev or "result=FAILURE" not in ev:
2950        raise Exception("Unexpect GAS query result: " + str(ev))
2951    dev[0].request("DPP_STOP_LISTEN")
2952    hapd.dump_monitor()
2953    dev[0].dump_monitor()
2954
2955def test_dpp_hostapd_enrollee_gas_tx_status_errors(dev, apdev):
2956    """DPP and hostapd as Enrollee with GAS TX status errors"""
2957    check_dpp_capab(dev[0])
2958    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured",
2959                                     "channel": "6"})
2960    check_dpp_capab(hapd)
2961    conf_id = dev[0].dpp_configurator_add()
2962    id0 = dev[0].dpp_bootstrap_gen(chan="81/6", mac=True)
2963    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
2964    conf = '{"wi-fi_tech":"infra", "discovery":{"ssid":"test"},"cred":{"akm":"psk","pass":"secret passphrase"}}' + 3000*' '
2965    dev[0].set("dpp_config_obj_override", conf)
2966    dev[0].set("dpp_configurator_params",
2967               "conf=ap-dpp configurator=%d" % conf_id)
2968    dev[0].set("ext_mgmt_frame_handling", "1")
2969    dev[0].dpp_listen(2437, role="configurator")
2970    hapd.dpp_auth_init(uri=uri0, role="enrollee")
2971    process_dpp_frames(dev[0], count=3)
2972
2973    hapd.set("ext_mgmt_frame_handling", "1")
2974    # GAS: TX status for unexpected destination
2975    frame = "d0003a01" + "222222222222"
2976    frame += hapd.own_addr().replace(':', '') + "ffffffffffff"
2977    frame += "5000" + "040a"
2978    hapd.request("MGMT_TX_STATUS_PROCESS stype=13 ok=1 buf=" + frame)
2979
2980    # GAS: No ACK to GAS request
2981    frame = "d0003a01" + dev[0].own_addr().replace(':', '')
2982    frame += hapd.own_addr().replace(':', '') + "ffffffffffff"
2983    frame += "5000" + "040a"
2984    hapd.request("MGMT_TX_STATUS_PROCESS stype=13 ok=0 buf=" + frame)
2985
2986    ev = hapd.wait_event(["GAS-QUERY-DONE"], timeout=10)
2987    if "result=TIMEOUT" not in ev:
2988        raise Exception("GAS timeout not reported")
2989
2990    # GAS: Unexpected TX status: dst=02:00:00:00:00:00 ok=1 - no query in progress
2991    hapd.request("MGMT_TX_STATUS_PROCESS stype=13 ok=1 buf=" + frame)
2992    hapd.set("ext_mgmt_frame_handling", "0")
2993
2994def test_dpp_hostapd_configurator_override_objects(dev, apdev):
2995    """DPP with hostapd as configurator and override objects"""
2996    check_dpp_capab(dev[0])
2997    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured",
2998                                     "channel": "1"})
2999    check_dpp_capab(hapd)
3000    conf_id = hapd.dpp_configurator_add()
3001    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
3002    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
3003    id1 = hapd.dpp_qr_code(uri0)
3004    res = hapd.request("DPP_BOOTSTRAP_INFO %d" % id1)
3005    if "FAIL" in res:
3006        raise Exception("DPP_BOOTSTRAP_INFO failed")
3007    dev[0].dpp_listen(2412)
3008    discovery = '{\n"ssid":"mywifi"\n}'
3009    groups = '[\n  {"groupId":"home","netRole":"sta"},\n  {"groupId":"cottage","netRole":"sta"}\n]'
3010    hapd.set("dpp_discovery_override", discovery)
3011    hapd.set("dpp_groups_override", groups)
3012    hapd.dpp_auth_init(peer=id1, configurator=conf_id, conf="sta-dpp")
3013    wait_auth_success(dev[0], hapd, configurator=hapd, enrollee=dev[0],
3014                      stop_responder=True)
3015
3016def test_dpp_own_config(dev, apdev):
3017    """DPP configurator signing own connector"""
3018    try:
3019        run_dpp_own_config(dev, apdev)
3020    finally:
3021        dev[0].set("dpp_config_processing", "0", allow_fail=True)
3022
3023def test_dpp_own_config_group_id(dev, apdev):
3024    """DPP configurator signing own connector"""
3025    try:
3026        run_dpp_own_config(dev, apdev, extra=" group_id=test-group")
3027    finally:
3028        dev[0].set("dpp_config_processing", "0", allow_fail=True)
3029
3030def test_dpp_own_config_curve_mismatch(dev, apdev):
3031    """DPP configurator signing own connector using mismatching curve"""
3032    try:
3033        run_dpp_own_config(dev, apdev, own_curve="BP-384", expect_failure=True)
3034    finally:
3035        dev[0].set("dpp_config_processing", "0", allow_fail=True)
3036
3037def run_dpp_own_config(dev, apdev, own_curve=None, expect_failure=False,
3038                       extra=None):
3039    check_dpp_capab(dev[0], own_curve and "BP" in own_curve)
3040    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured"})
3041    check_dpp_capab(hapd)
3042    id_h = hapd.dpp_bootstrap_gen(chan="81/1", mac=True)
3043    uri = hapd.request("DPP_BOOTSTRAP_GET_URI %d" % id_h)
3044    conf_id = dev[0].dpp_configurator_add()
3045    dev[0].dpp_auth_init(uri=uri, conf="ap-dpp", configurator=conf_id,
3046                         extra=extra)
3047    wait_auth_success(hapd, dev[0], configurator=dev[0], enrollee=hapd)
3048    update_hapd_config(hapd)
3049
3050    dev[0].set("dpp_config_processing", "1")
3051    cmd = "DPP_CONFIGURATOR_SIGN conf=sta-dpp configurator=%d%s" % (conf_id, extra)
3052    if own_curve:
3053        cmd += " curve=" + own_curve
3054    res = dev[0].request(cmd)
3055    if "FAIL" in res:
3056        raise Exception("Failed to generate own configuration")
3057
3058    ev = dev[0].wait_event(["DPP-NETWORK-ID"], timeout=1)
3059    if ev is None:
3060        raise Exception("DPP network profile not generated")
3061    id = ev.split(' ')[1]
3062    dev[0].select_network(id, freq="2412")
3063    if expect_failure:
3064        ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
3065        if ev is not None:
3066            raise Exception("Unexpected connection")
3067        dev[0].request("DISCONNECT")
3068    else:
3069        dev[0].wait_connected()
3070
3071def test_dpp_own_config_ap(dev, apdev):
3072    """DPP configurator (AP) signing own connector"""
3073    try:
3074        run_dpp_own_config_ap(dev, apdev)
3075    finally:
3076        dev[0].set("dpp_config_processing", "0", allow_fail=True)
3077
3078def test_dpp_own_config_ap_group_id(dev, apdev):
3079    """DPP configurator (AP) signing own connector (group_id)"""
3080    try:
3081        run_dpp_own_config_ap(dev, apdev, extra=" group_id=test-group")
3082    finally:
3083        dev[0].set("dpp_config_processing", "0", allow_fail=True)
3084
3085def test_dpp_own_config_ap_reconf(dev, apdev):
3086    """DPP configurator (AP) signing own connector and configurator reconf"""
3087    try:
3088        run_dpp_own_config_ap(dev, apdev)
3089    finally:
3090        dev[0].set("dpp_config_processing", "0", allow_fail=True)
3091
3092def run_dpp_own_config_ap(dev, apdev, reconf_configurator=False, extra=None):
3093    check_dpp_capab(dev[0])
3094    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured"})
3095    check_dpp_capab(hapd)
3096    conf_id = hapd.dpp_configurator_add()
3097    if reconf_configurator:
3098        csign = hapd.request("DPP_CONFIGURATOR_GET_KEY %d" % conf_id)
3099        if "FAIL" in csign or len(csign) == 0:
3100            raise Exception("DPP_CONFIGURATOR_GET_KEY failed")
3101
3102    cmd = "DPP_CONFIGURATOR_SIGN conf=ap-dpp configurator=%d%s" % (conf_id, extra)
3103    res = hapd.request(cmd)
3104    if "FAIL" in res:
3105        raise Exception("Failed to generate own configuration")
3106    update_hapd_config(hapd)
3107
3108    if reconf_configurator:
3109        hapd.dpp_configurator_remove(conf_id)
3110        conf_id = hapd.dpp_configurator_add(key=csign)
3111
3112    id = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
3113    uri = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id)
3114    dev[0].set("dpp_config_processing", "2")
3115    dev[0].dpp_listen(2412)
3116    hapd.dpp_auth_init(uri=uri, conf="sta-dpp", configurator=conf_id,
3117                       extra=extra)
3118    wait_auth_success(dev[0], hapd, configurator=hapd, enrollee=dev[0])
3119    dev[0].wait_connected()
3120
3121def test_dpp_intro_mismatch(dev, apdev):
3122    """DPP network introduction mismatch cases"""
3123    try:
3124        wpas = None
3125        wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
3126        wpas.interface_add("wlan5")
3127        check_dpp_capab(wpas)
3128        run_dpp_intro_mismatch(dev, apdev, wpas)
3129    finally:
3130        dev[0].set("dpp_config_processing", "0", allow_fail=True)
3131        dev[2].set("dpp_config_processing", "0", allow_fail=True)
3132        if wpas:
3133            wpas.set("dpp_config_processing", "0", allow_fail=True)
3134
3135def run_dpp_intro_mismatch(dev, apdev, wpas):
3136    check_dpp_capab(dev[0])
3137    check_dpp_capab(dev[1])
3138    check_dpp_capab(dev[2])
3139    logger.info("Start AP in unconfigured state")
3140    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured"})
3141    check_dpp_capab(hapd)
3142    id_h = hapd.dpp_bootstrap_gen(chan="81/1", mac=True)
3143    uri = hapd.request("DPP_BOOTSTRAP_GET_URI %d" % id_h)
3144    logger.info("Provision AP with DPP configuration")
3145    conf_id = dev[1].dpp_configurator_add()
3146    dev[1].set("dpp_groups_override", '[{"groupId":"a","netRole":"ap"}]')
3147    dev[1].dpp_auth_init(uri=uri, conf="ap-dpp", configurator=conf_id)
3148    update_hapd_config(hapd)
3149
3150    logger.info("Provision STA0 with DPP Connector that has mismatching groupId")
3151    dev[0].set("dpp_config_processing", "2")
3152    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
3153    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
3154    dev[0].dpp_listen(2412)
3155    dev[1].set("dpp_groups_override", '[{"groupId":"b","netRole":"sta"}]')
3156    dev[1].dpp_auth_init(uri=uri0, conf="sta-dpp", configurator=conf_id)
3157    wait_auth_success(dev[0], dev[1], configurator=dev[1], enrollee=dev[0])
3158
3159    logger.info("Provision STA2 with DPP Connector that has mismatching C-sign-key")
3160    dev[2].set("dpp_config_processing", "2")
3161    id2 = dev[2].dpp_bootstrap_gen(chan="81/1", mac=True)
3162    uri2 = dev[2].request("DPP_BOOTSTRAP_GET_URI %d" % id2)
3163    dev[2].dpp_listen(2412)
3164    conf_id_2 = dev[1].dpp_configurator_add()
3165    dev[1].set("dpp_groups_override", '')
3166    dev[1].dpp_auth_init(uri=uri2, conf="sta-dpp", configurator=conf_id_2)
3167    wait_auth_success(dev[2], dev[1], configurator=dev[1], enrollee=dev[2])
3168
3169    logger.info("Provision STA5 with DPP Connector that has mismatching netAccessKey EC group")
3170    wpas.set("dpp_config_processing", "2")
3171    id5 = wpas.dpp_bootstrap_gen(chan="81/1", mac=True, curve="P-521")
3172    uri5 = wpas.request("DPP_BOOTSTRAP_GET_URI %d" % id5)
3173    wpas.dpp_listen(2412)
3174    dev[1].set("dpp_groups_override", '')
3175    dev[1].dpp_auth_init(uri=uri5, conf="sta-dpp", configurator=conf_id)
3176    wait_auth_success(wpas, dev[1], configurator=dev[1], enrollee=wpas)
3177
3178    logger.info("Verify network introduction results")
3179    ev = dev[0].wait_event(["DPP-INTRO"], timeout=10)
3180    if ev is None:
3181        raise Exception("DPP network introduction result not seen on STA0")
3182    if "status=8" not in ev:
3183        raise Exception("Unexpected network introduction result on STA0: " + ev)
3184
3185    ev = dev[2].wait_event(["DPP-INTRO"], timeout=5)
3186    if ev is None:
3187        raise Exception("DPP network introduction result not seen on STA2")
3188    if "status=8" not in ev:
3189        raise Exception("Unexpected network introduction result on STA2: " + ev)
3190
3191    ev = wpas.wait_event(["DPP-INTRO"], timeout=10)
3192    if ev is None:
3193        raise Exception("DPP network introduction result not seen on STA5")
3194    if "status=7" not in ev:
3195        raise Exception("Unexpected network introduction result on STA5: " + ev)
3196
3197def run_dpp_proto_init(dev, test_dev, test, mutual=False, unicast=True,
3198                       listen=True, chan="81/1", init_enrollee=False,
3199                       incompatible_roles=False):
3200    check_dpp_capab(dev[0])
3201    check_dpp_capab(dev[1])
3202    dev[test_dev].set("dpp_test", str(test))
3203    if init_enrollee:
3204        conf_id = dev[0].dpp_configurator_add()
3205    else:
3206        conf_id = dev[1].dpp_configurator_add()
3207    id0 = dev[0].dpp_bootstrap_gen(chan=chan, mac=unicast)
3208    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
3209
3210    if mutual:
3211        id1b = dev[1].dpp_bootstrap_gen(chan="81/1", mac=True)
3212        uri1b = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id1b)
3213
3214        id0b = dev[0].dpp_qr_code(uri1b)
3215        qr = "mutual"
3216    else:
3217        qr = None
3218
3219    if init_enrollee:
3220        if incompatible_roles:
3221            role = "enrollee"
3222        else:
3223            role = "configurator"
3224        dev[0].set("dpp_configurator_params",
3225                   " conf=sta-dpp configurator=%d" % conf_id)
3226    elif incompatible_roles:
3227        role = "enrollee"
3228    else:
3229        role = None
3230
3231    if listen:
3232        dev[0].dpp_listen(2412, qr=qr, role=role)
3233
3234    role = None
3235    configurator = None
3236    conf = None
3237    own = None
3238
3239    if init_enrollee:
3240        role="enrollee"
3241    else:
3242        configurator=conf_id
3243        conf="sta-dpp"
3244        if incompatible_roles:
3245            role="enrollee"
3246    if mutual:
3247        own = id1b
3248    dev[1].dpp_auth_init(uri=uri0, role=role, configurator=configurator,
3249                         conf=conf, own=own)
3250    return uri0, role, configurator, conf, own
3251
3252def test_dpp_proto_after_wrapped_data_auth_req(dev, apdev):
3253    """DPP protocol testing - attribute after Wrapped Data in Auth Req"""
3254    run_dpp_proto_init(dev, 1, 1)
3255    ev = dev[0].wait_event(["DPP-RX"], timeout=5)
3256    if ev is None:
3257        raise Exception("DPP Authentication Request not seen")
3258    if "type=0" not in ev or "ignore=invalid-attributes" not in ev:
3259        raise Exception("Unexpected RX info: " + ev)
3260    ev = dev[1].wait_event(["DPP-RX"], timeout=0.1)
3261    if ev is not None:
3262        raise Exception("Unexpected DPP message seen")
3263
3264def test_dpp_auth_req_stop_after_ack(dev, apdev):
3265    """DPP initiator stopping after ACK, but no response"""
3266    run_dpp_proto_init(dev, 1, 1, listen=True)
3267    ev = dev[1].wait_event(["DPP-AUTH-INIT-FAILED"], timeout=5)
3268    if ev is None:
3269        raise Exception("Authentication failure not reported")
3270
3271def test_dpp_auth_req_retries(dev, apdev):
3272    """DPP initiator retries with no ACK"""
3273    check_dpp_capab(dev[1])
3274    dev[1].set("dpp_init_max_tries", "3")
3275    dev[1].set("dpp_init_retry_time", "1000")
3276    dev[1].set("dpp_resp_wait_time", "100")
3277    run_dpp_proto_init(dev, 1, 1, unicast=False, listen=False)
3278
3279    for i in range(3):
3280        ev = dev[1].wait_event(["DPP-TX "], timeout=5)
3281        if ev is None:
3282            raise Exception("Auth Req not sent (%d)" % i)
3283
3284    ev = dev[1].wait_event(["DPP-AUTH-INIT-FAILED"], timeout=5)
3285    if ev is None:
3286        raise Exception("Authentication failure not reported")
3287
3288def test_dpp_auth_req_retries_multi_chan(dev, apdev):
3289    """DPP initiator retries with no ACK and multiple channels"""
3290    check_dpp_capab(dev[1])
3291    dev[1].set("dpp_init_max_tries", "3")
3292    dev[1].set("dpp_init_retry_time", "1000")
3293    dev[1].set("dpp_resp_wait_time", "100")
3294    run_dpp_proto_init(dev, 1, 1, unicast=False, listen=False,
3295                       chan="81/1,81/6,81/11")
3296
3297    for i in range(3 * 3):
3298        ev = dev[1].wait_event(["DPP-TX "], timeout=5)
3299        if ev is None:
3300            raise Exception("Auth Req not sent (%d)" % i)
3301
3302    ev = dev[1].wait_event(["DPP-AUTH-INIT-FAILED"], timeout=5)
3303    if ev is None:
3304        raise Exception("Authentication failure not reported")
3305
3306def test_dpp_proto_after_wrapped_data_auth_resp(dev, apdev):
3307    """DPP protocol testing - attribute after Wrapped Data in Auth Resp"""
3308    run_dpp_proto_init(dev, 0, 2)
3309    ev = dev[1].wait_event(["DPP-RX"], timeout=5)
3310    if ev is None:
3311        raise Exception("DPP Authentication Response not seen")
3312    if "type=1" not in ev or "ignore=invalid-attributes" not in ev:
3313        raise Exception("Unexpected RX info: " + ev)
3314    ev = dev[0].wait_event(["DPP-RX"], timeout=1)
3315    if ev is None or "type=0" not in ev:
3316        raise Exception("DPP Authentication Request not seen")
3317    ev = dev[0].wait_event(["DPP-RX"], timeout=0.1)
3318    if ev is not None:
3319        raise Exception("Unexpected DPP message seen")
3320
3321def test_dpp_proto_after_wrapped_data_auth_conf(dev, apdev):
3322    """DPP protocol testing - attribute after Wrapped Data in Auth Conf"""
3323    run_dpp_proto_init(dev, 1, 3)
3324    ev = dev[0].wait_event(["DPP-RX"], timeout=5)
3325    if ev is None or "type=0" not in ev:
3326        raise Exception("DPP Authentication Request not seen")
3327    ev = dev[0].wait_event(["DPP-RX"], timeout=5)
3328    if ev is None:
3329        raise Exception("DPP Authentication Confirm not seen")
3330    if "type=2" not in ev or "ignore=invalid-attributes" not in ev:
3331        raise Exception("Unexpected RX info: " + ev)
3332
3333def test_dpp_proto_after_wrapped_data_conf_req(dev, apdev):
3334    """DPP protocol testing - attribute after Wrapped Data in Conf Req"""
3335    run_dpp_proto_init(dev, 0, 6)
3336    ev = dev[1].wait_event(["DPP-CONF-FAILED"], timeout=10)
3337    if ev is None:
3338        raise Exception("DPP Configuration failure not seen")
3339
3340def test_dpp_proto_after_wrapped_data_conf_resp(dev, apdev):
3341    """DPP protocol testing - attribute after Wrapped Data in Conf Resp"""
3342    run_dpp_proto_init(dev, 1, 7)
3343    ev = dev[0].wait_event(["DPP-CONF-FAILED"], timeout=10)
3344    if ev is None:
3345        raise Exception("DPP Configuration failure not seen")
3346
3347def test_dpp_proto_zero_i_capab(dev, apdev):
3348    """DPP protocol testing - zero I-capability in Auth Req"""
3349    run_dpp_proto_init(dev, 1, 8)
3350    wait_dpp_fail(dev[0], "Invalid role in I-capabilities 0x00")
3351    ev = dev[1].wait_event(["DPP-RX"], timeout=0.1)
3352    if ev is not None:
3353        raise Exception("Unexpected DPP message seen")
3354
3355def test_dpp_proto_zero_r_capab(dev, apdev):
3356    """DPP protocol testing - zero R-capability in Auth Resp"""
3357    run_dpp_proto_init(dev, 0, 9)
3358    wait_dpp_fail(dev[1], "Unexpected role in R-capabilities 0x00")
3359    ev = dev[0].wait_event(["DPP-RX"], timeout=1)
3360    if ev is None or "type=0" not in ev:
3361        raise Exception("DPP Authentication Request not seen")
3362    ev = dev[0].wait_event(["DPP-RX"], timeout=0.1)
3363    if ev is not None:
3364        raise Exception("Unexpected DPP message seen")
3365
3366def run_dpp_proto_auth_req_missing(dev, test, reason, mutual=False):
3367    run_dpp_proto_init(dev, 1, test, mutual=mutual)
3368    wait_dpp_fail(dev[0], reason)
3369    ev = dev[1].wait_event(["DPP-RX"], timeout=0.1)
3370    if ev is not None:
3371        raise Exception("Unexpected DPP message seen")
3372
3373def test_dpp_proto_auth_req_no_r_bootstrap_key(dev, apdev):
3374    """DPP protocol testing - no R-bootstrap key in Auth Req"""
3375    run_dpp_proto_auth_req_missing(dev, 10, "Missing or invalid required Responder Bootstrapping Key Hash attribute")
3376
3377def test_dpp_proto_auth_req_invalid_r_bootstrap_key(dev, apdev):
3378    """DPP protocol testing - invalid R-bootstrap key in Auth Req"""
3379    run_dpp_proto_auth_req_missing(dev, 68, "No matching own bootstrapping key found - ignore message")
3380
3381def test_dpp_proto_auth_req_no_i_bootstrap_key(dev, apdev):
3382    """DPP protocol testing - no I-bootstrap key in Auth Req"""
3383    run_dpp_proto_auth_req_missing(dev, 11, "Missing or invalid required Initiator Bootstrapping Key Hash attribute")
3384
3385def test_dpp_proto_auth_req_invalid_i_bootstrap_key(dev, apdev):
3386    """DPP protocol testing - invalid I-bootstrap key in Auth Req"""
3387    run_dpp_proto_init(dev, 1, 69, mutual=True)
3388    ev = dev[0].wait_event(["DPP-SCAN-PEER-QR-CODE"], timeout=5)
3389    if ev is None:
3390        raise Exception("DPP scan request not seen")
3391    ev = dev[1].wait_event(["DPP-RESPONSE-PENDING"], timeout=5)
3392    if ev is None:
3393        raise Exception("DPP response pending indivation not seen")
3394
3395def test_dpp_proto_auth_req_no_i_proto_key(dev, apdev):
3396    """DPP protocol testing - no I-proto key in Auth Req"""
3397    run_dpp_proto_auth_req_missing(dev, 12, "Missing required Initiator Protocol Key attribute")
3398
3399def test_dpp_proto_auth_req_invalid_i_proto_key(dev, apdev):
3400    """DPP protocol testing - invalid I-proto key in Auth Req"""
3401    run_dpp_proto_auth_req_missing(dev, 66, "Invalid Initiator Protocol Key")
3402
3403def test_dpp_proto_auth_req_no_i_nonce(dev, apdev):
3404    """DPP protocol testing - no I-nonce in Auth Req"""
3405    run_dpp_proto_auth_req_missing(dev, 13, "Missing or invalid I-nonce")
3406
3407def test_dpp_proto_auth_req_invalid_i_nonce(dev, apdev):
3408    """DPP protocol testing - invalid I-nonce in Auth Req"""
3409    run_dpp_proto_auth_req_missing(dev, 81, "Missing or invalid I-nonce")
3410
3411def test_dpp_proto_auth_req_no_i_capab(dev, apdev):
3412    """DPP protocol testing - no I-capab in Auth Req"""
3413    run_dpp_proto_auth_req_missing(dev, 14, "Missing or invalid I-capab")
3414
3415def test_dpp_proto_auth_req_no_wrapped_data(dev, apdev):
3416    """DPP protocol testing - no Wrapped Data in Auth Req"""
3417    run_dpp_proto_auth_req_missing(dev, 15, "Missing or invalid required Wrapped Data attribute")
3418
3419def run_dpp_proto_auth_resp_missing(dev, test, reason,
3420                                    incompatible_roles=False):
3421    run_dpp_proto_init(dev, 0, test, mutual=True,
3422                       incompatible_roles=incompatible_roles)
3423    if reason is None:
3424        if incompatible_roles:
3425            ev = dev[0].wait_event(["DPP-NOT-COMPATIBLE"], timeout=5)
3426            if ev is None:
3427                raise Exception("DPP-NOT-COMPATIBLE not reported")
3428        time.sleep(0.1)
3429        return
3430    wait_dpp_fail(dev[1], reason)
3431    ev = dev[0].wait_event(["DPP-RX"], timeout=1)
3432    if ev is None or "type=0" not in ev:
3433        raise Exception("DPP Authentication Request not seen")
3434    ev = dev[0].wait_event(["DPP-RX"], timeout=0.1)
3435    if ev is not None:
3436        raise Exception("Unexpected DPP message seen")
3437
3438def test_dpp_proto_auth_resp_no_status(dev, apdev):
3439    """DPP protocol testing - no Status in Auth Resp"""
3440    run_dpp_proto_auth_resp_missing(dev, 16, "Missing or invalid required DPP Status attribute")
3441
3442def test_dpp_proto_auth_resp_status_no_status(dev, apdev):
3443    """DPP protocol testing - no Status in Auth Resp(status)"""
3444    run_dpp_proto_auth_resp_missing(dev, 16,
3445                                    "Missing or invalid required DPP Status attribute",
3446                                    incompatible_roles=True)
3447
3448def test_dpp_proto_auth_resp_invalid_status(dev, apdev):
3449    """DPP protocol testing - invalid Status in Auth Resp"""
3450    run_dpp_proto_auth_resp_missing(dev, 74, "Responder reported failure")
3451
3452def test_dpp_proto_auth_resp_no_r_bootstrap_key(dev, apdev):
3453    """DPP protocol testing - no R-bootstrap key in Auth Resp"""
3454    run_dpp_proto_auth_resp_missing(dev, 17, "Missing or invalid required Responder Bootstrapping Key Hash attribute")
3455
3456def test_dpp_proto_auth_resp_status_no_r_bootstrap_key(dev, apdev):
3457    """DPP protocol testing - no R-bootstrap key in Auth Resp(status)"""
3458    run_dpp_proto_auth_resp_missing(dev, 17,
3459                                    "Missing or invalid required Responder Bootstrapping Key Hash attribute",
3460                                    incompatible_roles=True)
3461
3462def test_dpp_proto_auth_resp_invalid_r_bootstrap_key(dev, apdev):
3463    """DPP protocol testing - invalid R-bootstrap key in Auth Resp"""
3464    run_dpp_proto_auth_resp_missing(dev, 70, "Unexpected Responder Bootstrapping Key Hash value")
3465
3466def test_dpp_proto_auth_resp_status_invalid_r_bootstrap_key(dev, apdev):
3467    """DPP protocol testing - invalid R-bootstrap key in Auth Resp(status)"""
3468    run_dpp_proto_auth_resp_missing(dev, 70,
3469                                    "Unexpected Responder Bootstrapping Key Hash value",
3470                                    incompatible_roles=True)
3471
3472def test_dpp_proto_auth_resp_no_i_bootstrap_key(dev, apdev):
3473    """DPP protocol testing - no I-bootstrap key in Auth Resp"""
3474    run_dpp_proto_auth_resp_missing(dev, 18, None)
3475
3476def test_dpp_proto_auth_resp_status_no_i_bootstrap_key(dev, apdev):
3477    """DPP protocol testing - no I-bootstrap key in Auth Resp(status)"""
3478    run_dpp_proto_auth_resp_missing(dev, 18, None, incompatible_roles=True)
3479
3480def test_dpp_proto_auth_resp_invalid_i_bootstrap_key(dev, apdev):
3481    """DPP protocol testing - invalid I-bootstrap key in Auth Resp"""
3482    run_dpp_proto_auth_resp_missing(dev, 71, "Initiator Bootstrapping Key Hash attribute did not match")
3483
3484def test_dpp_proto_auth_resp_status_invalid_i_bootstrap_key(dev, apdev):
3485    """DPP protocol testing - invalid I-bootstrap key in Auth Resp(status)"""
3486    run_dpp_proto_auth_resp_missing(dev, 71,
3487                                    "Initiator Bootstrapping Key Hash attribute did not match",
3488                                    incompatible_roles=True)
3489
3490def test_dpp_proto_auth_resp_no_r_proto_key(dev, apdev):
3491    """DPP protocol testing - no R-Proto Key in Auth Resp"""
3492    run_dpp_proto_auth_resp_missing(dev, 19, "Missing required Responder Protocol Key attribute")
3493
3494def test_dpp_proto_auth_resp_invalid_r_proto_key(dev, apdev):
3495    """DPP protocol testing - invalid R-Proto Key in Auth Resp"""
3496    run_dpp_proto_auth_resp_missing(dev, 67, "Invalid Responder Protocol Key")
3497
3498def test_dpp_proto_auth_resp_no_r_nonce(dev, apdev):
3499    """DPP protocol testing - no R-nonce in Auth Resp"""
3500    run_dpp_proto_auth_resp_missing(dev, 20, "Missing or invalid R-nonce")
3501
3502def test_dpp_proto_auth_resp_no_i_nonce(dev, apdev):
3503    """DPP protocol testing - no I-nonce in Auth Resp"""
3504    run_dpp_proto_auth_resp_missing(dev, 21, "Missing or invalid I-nonce")
3505
3506def test_dpp_proto_auth_resp_status_no_i_nonce(dev, apdev):
3507    """DPP protocol testing - no I-nonce in Auth Resp(status)"""
3508    run_dpp_proto_auth_resp_missing(dev, 21, "Missing or invalid I-nonce",
3509                                    incompatible_roles=True)
3510
3511def test_dpp_proto_auth_resp_no_r_capab(dev, apdev):
3512    """DPP protocol testing - no R-capab in Auth Resp"""
3513    run_dpp_proto_auth_resp_missing(dev, 22, "Missing or invalid R-capabilities")
3514
3515def test_dpp_proto_auth_resp_no_r_auth(dev, apdev):
3516    """DPP protocol testing - no R-auth in Auth Resp"""
3517    run_dpp_proto_auth_resp_missing(dev, 23, "Missing or invalid Secondary Wrapped Data")
3518
3519def test_dpp_proto_auth_resp_no_wrapped_data(dev, apdev):
3520    """DPP protocol testing - no Wrapped Data in Auth Resp"""
3521    run_dpp_proto_auth_resp_missing(dev, 24, "Missing or invalid required Wrapped Data attribute")
3522
3523def test_dpp_proto_auth_resp_i_nonce_mismatch(dev, apdev):
3524    """DPP protocol testing - I-nonce mismatch in Auth Resp"""
3525    run_dpp_proto_init(dev, 0, 30, mutual=True)
3526    wait_dpp_fail(dev[1], "I-nonce mismatch")
3527    ev = dev[0].wait_event(["DPP-RX"], timeout=1)
3528    if ev is None or "type=0" not in ev:
3529        raise Exception("DPP Authentication Request not seen")
3530    ev = dev[0].wait_event(["DPP-RX"], timeout=0.1)
3531    if ev is not None:
3532        raise Exception("Unexpected DPP message seen")
3533
3534def test_dpp_proto_auth_resp_incompatible_r_capab(dev, apdev):
3535    """DPP protocol testing - Incompatible R-capab in Auth Resp"""
3536    run_dpp_proto_init(dev, 0, 31, mutual=True)
3537    wait_dpp_fail(dev[1], "Unexpected role in R-capabilities 0x02")
3538    wait_dpp_fail(dev[0], "Peer reported incompatible R-capab role")
3539
3540def test_dpp_proto_auth_resp_r_auth_mismatch(dev, apdev):
3541    """DPP protocol testing - R-auth mismatch in Auth Resp"""
3542    run_dpp_proto_init(dev, 0, 32, mutual=True)
3543    wait_dpp_fail(dev[1], "Mismatching Responder Authenticating Tag")
3544    wait_dpp_fail(dev[0], "Peer reported authentication failure")
3545
3546def test_dpp_proto_auth_resp_r_auth_mismatch_failure(dev, apdev):
3547    """DPP protocol testing - Auth Conf RX processing failure"""
3548    with alloc_fail(dev[0], 1, "dpp_auth_conf_rx_failure"):
3549        run_dpp_proto_init(dev, 0, 32, mutual=True)
3550        wait_dpp_fail(dev[0], "Authentication failed")
3551
3552def test_dpp_proto_auth_resp_r_auth_mismatch_failure2(dev, apdev):
3553    """DPP protocol testing - Auth Conf RX processing failure 2"""
3554    with fail_test(dev[0], 1, "dpp_auth_conf_rx_failure"):
3555        run_dpp_proto_init(dev, 0, 32, mutual=True)
3556        wait_dpp_fail(dev[0], "AES-SIV decryption failed")
3557
3558def run_dpp_proto_auth_conf_missing(dev, test, reason):
3559    run_dpp_proto_init(dev, 1, test, mutual=True)
3560    if reason is None:
3561        time.sleep(0.1)
3562        return
3563    wait_dpp_fail(dev[0], reason)
3564
3565def test_dpp_proto_auth_conf_no_status(dev, apdev):
3566    """DPP protocol testing - no Status in Auth Conf"""
3567    run_dpp_proto_auth_conf_missing(dev, 25, "Missing or invalid required DPP Status attribute")
3568
3569def test_dpp_proto_auth_conf_invalid_status(dev, apdev):
3570    """DPP protocol testing - invalid Status in Auth Conf"""
3571    run_dpp_proto_auth_conf_missing(dev, 75, "Authentication failed")
3572
3573def test_dpp_proto_auth_conf_no_r_bootstrap_key(dev, apdev):
3574    """DPP protocol testing - no R-bootstrap key in Auth Conf"""
3575    run_dpp_proto_auth_conf_missing(dev, 26, "Missing or invalid required Responder Bootstrapping Key Hash attribute")
3576
3577def test_dpp_proto_auth_conf_invalid_r_bootstrap_key(dev, apdev):
3578    """DPP protocol testing - invalid R-bootstrap key in Auth Conf"""
3579    run_dpp_proto_auth_conf_missing(dev, 72, "Responder Bootstrapping Key Hash mismatch")
3580
3581def test_dpp_proto_auth_conf_no_i_bootstrap_key(dev, apdev):
3582    """DPP protocol testing - no I-bootstrap key in Auth Conf"""
3583    run_dpp_proto_auth_conf_missing(dev, 27, "Missing Initiator Bootstrapping Key Hash attribute")
3584
3585def test_dpp_proto_auth_conf_invalid_i_bootstrap_key(dev, apdev):
3586    """DPP protocol testing - invalid I-bootstrap key in Auth Conf"""
3587    run_dpp_proto_auth_conf_missing(dev, 73, "Initiator Bootstrapping Key Hash mismatch")
3588
3589def test_dpp_proto_auth_conf_no_i_auth(dev, apdev):
3590    """DPP protocol testing - no I-Auth in Auth Conf"""
3591    run_dpp_proto_auth_conf_missing(dev, 28, "Missing or invalid Initiator Authenticating Tag")
3592
3593def test_dpp_proto_auth_conf_no_wrapped_data(dev, apdev):
3594    """DPP protocol testing - no Wrapped Data in Auth Conf"""
3595    run_dpp_proto_auth_conf_missing(dev, 29, "Missing or invalid required Wrapped Data attribute")
3596
3597def test_dpp_proto_auth_conf_i_auth_mismatch(dev, apdev):
3598    """DPP protocol testing - I-auth mismatch in Auth Conf"""
3599    run_dpp_proto_init(dev, 1, 33, mutual=True)
3600    wait_dpp_fail(dev[0], "Mismatching Initiator Authenticating Tag")
3601
3602def test_dpp_proto_auth_conf_replaced_by_resp(dev, apdev):
3603    """DPP protocol testing - Auth Conf replaced by Resp"""
3604    run_dpp_proto_init(dev, 1, 65, mutual=True)
3605    wait_dpp_fail(dev[0], "Unexpected Authentication Response")
3606
3607def run_dpp_proto_conf_req_missing(dev, test, reason):
3608    run_dpp_proto_init(dev, 0, test)
3609    wait_dpp_fail(dev[1], reason)
3610
3611def test_dpp_proto_conf_req_no_e_nonce(dev, apdev):
3612    """DPP protocol testing - no E-nonce in Conf Req"""
3613    run_dpp_proto_conf_req_missing(dev, 51,
3614                                   "Missing or invalid Enrollee Nonce attribute")
3615
3616def test_dpp_proto_conf_req_invalid_e_nonce(dev, apdev):
3617    """DPP protocol testing - invalid E-nonce in Conf Req"""
3618    run_dpp_proto_conf_req_missing(dev, 83,
3619                                   "Missing or invalid Enrollee Nonce attribute")
3620
3621def test_dpp_proto_conf_req_no_config_attr_obj(dev, apdev):
3622    """DPP protocol testing - no Config Attr Obj in Conf Req"""
3623    run_dpp_proto_conf_req_missing(dev, 52,
3624                                   "Missing or invalid Config Attributes attribute")
3625
3626def test_dpp_proto_conf_req_invalid_config_attr_obj(dev, apdev):
3627    """DPP protocol testing - invalid Config Attr Obj in Conf Req"""
3628    run_dpp_proto_conf_req_missing(dev, 76,
3629                                   "Unsupported wi-fi_tech")
3630
3631def test_dpp_proto_conf_req_no_wrapped_data(dev, apdev):
3632    """DPP protocol testing - no Wrapped Data in Conf Req"""
3633    run_dpp_proto_conf_req_missing(dev, 53,
3634                                   "Missing or invalid required Wrapped Data attribute")
3635
3636def run_dpp_proto_conf_resp_missing(dev, test, reason):
3637    run_dpp_proto_init(dev, 1, test)
3638    wait_dpp_fail(dev[0], reason)
3639
3640def test_dpp_proto_conf_resp_no_e_nonce(dev, apdev):
3641    """DPP protocol testing - no E-nonce in Conf Resp"""
3642    run_dpp_proto_conf_resp_missing(dev, 54,
3643                                    "Missing or invalid Enrollee Nonce attribute")
3644
3645def test_dpp_proto_conf_resp_no_config_obj(dev, apdev):
3646    """DPP protocol testing - no Config Object in Conf Resp"""
3647    run_dpp_proto_conf_resp_missing(dev, 55,
3648                                    "Missing required Configuration Object attribute")
3649
3650def test_dpp_proto_conf_resp_no_status(dev, apdev):
3651    """DPP protocol testing - no Status in Conf Resp"""
3652    run_dpp_proto_conf_resp_missing(dev, 56,
3653                                    "Missing or invalid required DPP Status attribute")
3654
3655def test_dpp_proto_conf_resp_no_wrapped_data(dev, apdev):
3656    """DPP protocol testing - no Wrapped Data in Conf Resp"""
3657    run_dpp_proto_conf_resp_missing(dev, 57,
3658                                    "Missing or invalid required Wrapped Data attribute")
3659
3660def test_dpp_proto_conf_resp_invalid_status(dev, apdev):
3661    """DPP protocol testing - invalid Status in Conf Resp"""
3662    run_dpp_proto_conf_resp_missing(dev, 58,
3663                                    "Configurator rejected configuration")
3664
3665def test_dpp_proto_conf_resp_e_nonce_mismatch(dev, apdev):
3666    """DPP protocol testing - E-nonce mismatch in Conf Resp"""
3667    run_dpp_proto_conf_resp_missing(dev, 59,
3668                                    "Enrollee Nonce mismatch")
3669
3670def test_dpp_proto_stop_at_auth_req(dev, apdev):
3671    """DPP protocol testing - stop when receiving Auth Req"""
3672    run_dpp_proto_init(dev, 0, 87)
3673    ev = dev[1].wait_event(["DPP-AUTH-INIT-FAILED"], timeout=5)
3674    if ev is None:
3675        raise Exception("Authentication init failure not reported")
3676
3677def test_dpp_proto_stop_at_auth_resp(dev, apdev):
3678    """DPP protocol testing - stop when receiving Auth Resp"""
3679    uri0, role, configurator, conf, own = run_dpp_proto_init(dev, 1, 88)
3680
3681    ev = dev[1].wait_event(["DPP-TX "], timeout=5)
3682    if ev is None:
3683        raise Exception("Auth Req TX not seen")
3684
3685    ev = dev[0].wait_event(["DPP-TX "], timeout=5)
3686    if ev is None:
3687        raise Exception("Auth Resp TX not seen")
3688
3689    ev = dev[1].wait_event(["DPP-TX "], timeout=0.1)
3690    if ev is not None:
3691        raise Exception("Unexpected Auth Conf TX")
3692
3693    ev = dev[0].wait_event(["DPP-FAIL"], timeout=2)
3694    if ev is None or "No Auth Confirm received" not in ev:
3695        raise Exception("DPP-FAIL for missing Auth Confirm not reported")
3696    time.sleep(0.1)
3697
3698    # Try again without special testing behavior to confirm Responder is able
3699    # to accept a new provisioning attempt.
3700    dev[1].set("dpp_test", "0")
3701    dev[1].dpp_auth_init(uri=uri0, role=role, configurator=configurator,
3702                         conf=conf, own=own)
3703    wait_auth_success(dev[0], dev[1])
3704
3705def test_dpp_proto_stop_at_auth_conf(dev, apdev):
3706    """DPP protocol testing - stop when receiving Auth Conf"""
3707    run_dpp_proto_init(dev, 0, 89, init_enrollee=True)
3708    ev = dev[1].wait_event(["GAS-QUERY-START"], timeout=10)
3709    if ev is None:
3710        raise Exception("Enrollee did not start GAS")
3711    ev = dev[1].wait_event(["GAS-QUERY-DONE"], timeout=10)
3712    if ev is None:
3713        raise Exception("Enrollee did not time out GAS")
3714    if "result=TIMEOUT" not in ev:
3715        raise Exception("Unexpected GAS result: " + ev)
3716
3717def test_dpp_proto_stop_at_auth_conf_tx(dev, apdev):
3718    """DPP protocol testing - stop when transmitting Auth Conf (Registrar)"""
3719    run_dpp_proto_init(dev, 1, 89, init_enrollee=True)
3720    wait_auth_success(dev[0], dev[1], timeout=10)
3721    ev = dev[1].wait_event(["GAS-QUERY-START"], timeout=0.1)
3722    if ev is not None:
3723        raise Exception("Unexpected GAS query")
3724
3725    # There is currently no timeout on GAS server side, so no event to wait for
3726    # in this case.
3727
3728def test_dpp_proto_stop_at_auth_conf_tx2(dev, apdev):
3729    """DPP protocol testing - stop when transmitting Auth Conf (Enrollee)"""
3730    run_dpp_proto_init(dev, 1, 89)
3731    wait_auth_success(dev[0], dev[1], timeout=10)
3732
3733    ev = dev[0].wait_event(["GAS-QUERY-DONE"], timeout=5)
3734    if ev is None or "result=TIMEOUT" not in ev:
3735        raise Exception("GAS query did not time out")
3736
3737def test_dpp_proto_stop_at_conf_req(dev, apdev):
3738    """DPP protocol testing - stop when receiving Auth Req"""
3739    run_dpp_proto_init(dev, 1, 90)
3740    ev = dev[0].wait_event(["GAS-QUERY-START"], timeout=10)
3741    if ev is None:
3742        raise Exception("Enrollee did not start GAS")
3743    ev = dev[0].wait_event(["GAS-QUERY-DONE"], timeout=10)
3744    if ev is None:
3745        raise Exception("Enrollee did not time out GAS")
3746    if "result=TIMEOUT" not in ev:
3747        raise Exception("Unexpected GAS result: " + ev)
3748
3749def run_dpp_proto_init_pkex(dev, test_dev, test):
3750    check_dpp_capab(dev[0])
3751    check_dpp_capab(dev[1])
3752    dev[test_dev].set("dpp_test", str(test))
3753    dev[0].dpp_pkex_resp(2437, identifier="test", code="secret")
3754    dev[1].dpp_pkex_init(identifier="test", code="secret")
3755
3756def test_dpp_proto_after_wrapped_data_pkex_cr_req(dev, apdev):
3757    """DPP protocol testing - attribute after Wrapped Data in PKEX CR Req"""
3758    run_dpp_proto_init_pkex(dev, 1, 4)
3759    ev = dev[0].wait_event(["DPP-RX"], timeout=5)
3760    if ev is None or "type=7" not in ev:
3761        raise Exception("PKEX Exchange Request not seen")
3762    ev = dev[0].wait_event(["DPP-RX"], timeout=5)
3763    if ev is None or "type=9" not in ev:
3764        raise Exception("PKEX Commit-Reveal Request not seen")
3765    if "ignore=invalid-attributes" not in ev:
3766        raise Exception("Unexpected RX info: " + ev)
3767
3768def test_dpp_proto_after_wrapped_data_pkex_cr_resp(dev, apdev):
3769    """DPP protocol testing - attribute after Wrapped Data in PKEX CR Resp"""
3770    run_dpp_proto_init_pkex(dev, 0, 5)
3771    ev = dev[1].wait_event(["DPP-RX"], timeout=5)
3772    if ev is None or "type=8" not in ev:
3773        raise Exception("PKEX Exchange Response not seen")
3774    ev = dev[1].wait_event(["DPP-RX"], timeout=5)
3775    if ev is None or "type=10" not in ev:
3776        raise Exception("PKEX Commit-Reveal Response not seen")
3777    if "ignore=invalid-attributes" not in ev:
3778        raise Exception("Unexpected RX info: " + ev)
3779
3780def run_dpp_proto_pkex_req_missing(dev, test, reason):
3781    run_dpp_proto_init_pkex(dev, 1, test)
3782    wait_dpp_fail(dev[0], reason)
3783
3784def run_dpp_proto_pkex_resp_missing(dev, test, reason):
3785    run_dpp_proto_init_pkex(dev, 0, test)
3786    wait_dpp_fail(dev[1], reason)
3787
3788def test_dpp_proto_pkex_exchange_req_no_finite_cyclic_group(dev, apdev):
3789    """DPP protocol testing - no Finite Cyclic Group in PKEX Exchange Request"""
3790    run_dpp_proto_pkex_req_missing(dev, 34,
3791                                   "Missing or invalid Finite Cyclic Group attribute")
3792
3793def test_dpp_proto_pkex_exchange_req_no_encrypted_key(dev, apdev):
3794    """DPP protocol testing - no Encrypted Key in PKEX Exchange Request"""
3795    run_dpp_proto_pkex_req_missing(dev, 35,
3796                                   "Missing Encrypted Key attribute")
3797
3798def test_dpp_proto_pkex_exchange_resp_no_status(dev, apdev):
3799    """DPP protocol testing - no Status in PKEX Exchange Response"""
3800    run_dpp_proto_pkex_resp_missing(dev, 36, "No DPP Status attribute")
3801
3802def test_dpp_proto_pkex_exchange_resp_no_encrypted_key(dev, apdev):
3803    """DPP protocol testing - no Encrypted Key in PKEX Exchange Response"""
3804    run_dpp_proto_pkex_resp_missing(dev, 37, "Missing Encrypted Key attribute")
3805
3806def test_dpp_proto_pkex_cr_req_no_bootstrap_key(dev, apdev):
3807    """DPP protocol testing - no Bootstrap Key in PKEX Commit-Reveal Request"""
3808    run_dpp_proto_pkex_req_missing(dev, 38,
3809                                   "No valid peer bootstrapping key found")
3810
3811def test_dpp_proto_pkex_cr_req_no_i_auth_tag(dev, apdev):
3812    """DPP protocol testing - no I-Auth Tag in PKEX Commit-Reveal Request"""
3813    run_dpp_proto_pkex_req_missing(dev, 39, "No valid u (I-Auth tag) found")
3814
3815def test_dpp_proto_pkex_cr_req_no_wrapped_data(dev, apdev):
3816    """DPP protocol testing - no Wrapped Data in PKEX Commit-Reveal Request"""
3817    run_dpp_proto_pkex_req_missing(dev, 40, "Missing or invalid required Wrapped Data attribute")
3818
3819def test_dpp_proto_pkex_cr_resp_no_bootstrap_key(dev, apdev):
3820    """DPP protocol testing - no Bootstrap Key in PKEX Commit-Reveal Response"""
3821    run_dpp_proto_pkex_resp_missing(dev, 41,
3822                                   "No valid peer bootstrapping key found")
3823
3824def test_dpp_proto_pkex_cr_resp_no_r_auth_tag(dev, apdev):
3825    """DPP protocol testing - no R-Auth Tag in PKEX Commit-Reveal Response"""
3826    run_dpp_proto_pkex_resp_missing(dev, 42, "No valid v (R-Auth tag) found")
3827
3828def test_dpp_proto_pkex_cr_resp_no_wrapped_data(dev, apdev):
3829    """DPP protocol testing - no Wrapped Data in PKEX Commit-Reveal Response"""
3830    run_dpp_proto_pkex_resp_missing(dev, 43, "Missing or invalid required Wrapped Data attribute")
3831
3832def test_dpp_proto_pkex_exchange_req_invalid_encrypted_key(dev, apdev):
3833    """DPP protocol testing - invalid Encrypted Key in PKEX Exchange Request"""
3834    run_dpp_proto_pkex_req_missing(dev, 44,
3835                                   "Invalid Encrypted Key value")
3836
3837def test_dpp_proto_pkex_exchange_resp_invalid_encrypted_key(dev, apdev):
3838    """DPP protocol testing - invalid Encrypted Key in PKEX Exchange Response"""
3839    run_dpp_proto_pkex_resp_missing(dev, 45,
3840                                    "Invalid Encrypted Key value")
3841
3842def test_dpp_proto_pkex_exchange_resp_invalid_status(dev, apdev):
3843    """DPP protocol testing - invalid Status in PKEX Exchange Response"""
3844    run_dpp_proto_pkex_resp_missing(dev, 46,
3845                                    "PKEX failed (peer indicated failure)")
3846
3847def test_dpp_proto_pkex_cr_req_invalid_bootstrap_key(dev, apdev):
3848    """DPP protocol testing - invalid Bootstrap Key in PKEX Commit-Reveal Request"""
3849    run_dpp_proto_pkex_req_missing(dev, 47,
3850                                   "Peer bootstrapping key is invalid")
3851
3852def test_dpp_proto_pkex_cr_resp_invalid_bootstrap_key(dev, apdev):
3853    """DPP protocol testing - invalid Bootstrap Key in PKEX Commit-Reveal Response"""
3854    run_dpp_proto_pkex_resp_missing(dev, 48,
3855                                    "Peer bootstrapping key is invalid")
3856
3857def test_dpp_proto_pkex_cr_req_i_auth_tag_mismatch(dev, apdev):
3858    """DPP protocol testing - I-auth tag mismatch in PKEX Commit-Reveal Request"""
3859    run_dpp_proto_pkex_req_missing(dev, 49, "No valid u (I-Auth tag) found")
3860
3861def test_dpp_proto_pkex_cr_resp_r_auth_tag_mismatch(dev, apdev):
3862    """DPP protocol testing - R-auth tag mismatch in PKEX Commit-Reveal Response"""
3863    run_dpp_proto_pkex_resp_missing(dev, 50, "No valid v (R-Auth tag) found")
3864
3865def test_dpp_proto_stop_at_pkex_exchange_resp(dev, apdev):
3866    """DPP protocol testing - stop when receiving PKEX Exchange Response"""
3867    run_dpp_proto_init_pkex(dev, 1, 84)
3868
3869    ev = dev[1].wait_event(["DPP-TX "], timeout=5)
3870    if ev is None:
3871        raise Exception("PKEX Exchange Req TX not seen")
3872
3873    ev = dev[0].wait_event(["DPP-TX "], timeout=5)
3874    if ev is None:
3875        raise Exception("PKEX Exchange Resp not seen")
3876
3877    ev = dev[1].wait_event(["DPP-TX "], timeout=0.1)
3878    if ev is not None:
3879        raise Exception("Unexpected PKEX CR Req TX")
3880
3881def test_dpp_proto_stop_at_pkex_cr_req(dev, apdev):
3882    """DPP protocol testing - stop when receiving PKEX CR Request"""
3883    run_dpp_proto_init_pkex(dev, 0, 85)
3884
3885    ev = dev[1].wait_event(["DPP-TX "], timeout=5)
3886    if ev is None:
3887        raise Exception("PKEX Exchange Req TX not seen")
3888
3889    ev = dev[0].wait_event(["DPP-TX "], timeout=5)
3890    if ev is None:
3891        raise Exception("PKEX Exchange Resp not seen")
3892
3893    ev = dev[1].wait_event(["DPP-TX "], timeout=5)
3894    if ev is None:
3895        raise Exception("PKEX CR Req TX not seen")
3896
3897    ev = dev[0].wait_event(["DPP-TX "], timeout=0.1)
3898    if ev is not None:
3899        raise Exception("Unexpected PKEX CR Resp TX")
3900
3901def test_dpp_proto_stop_at_pkex_cr_resp(dev, apdev):
3902    """DPP protocol testing - stop when receiving PKEX CR Response"""
3903    run_dpp_proto_init_pkex(dev, 1, 86)
3904
3905    ev = dev[1].wait_event(["DPP-TX "], timeout=5)
3906    if ev is None:
3907        raise Exception("PKEX Exchange Req TX not seen")
3908
3909    ev = dev[0].wait_event(["DPP-TX "], timeout=5)
3910    if ev is None:
3911        raise Exception("PKEX Exchange Resp not seen")
3912
3913    ev = dev[1].wait_event(["DPP-TX "], timeout=5)
3914    if ev is None:
3915        raise Exception("PKEX CR Req TX not seen")
3916
3917    ev = dev[0].wait_event(["DPP-TX "], timeout=5)
3918    if ev is None:
3919        raise Exception("PKEX CR Resp TX not seen")
3920
3921    ev = dev[1].wait_event(["DPP-TX "], timeout=0.1)
3922    if ev is not None:
3923        raise Exception("Unexpected Auth Req TX")
3924
3925def test_dpp_proto_network_introduction(dev, apdev):
3926    """DPP protocol testing - network introduction"""
3927    check_dpp_capab(dev[0])
3928    check_dpp_capab(dev[1])
3929
3930    params = {"ssid": "dpp",
3931              "wpa": "2",
3932              "wpa_key_mgmt": "DPP",
3933              "ieee80211w": "2",
3934              "rsn_pairwise": "CCMP",
3935              "dpp_connector": params1_ap_connector,
3936              "dpp_csign": params1_csign,
3937              "dpp_netaccesskey": params1_ap_netaccesskey}
3938    try:
3939        hapd = hostapd.add_ap(apdev[0], params)
3940    except:
3941        raise HwsimSkip("DPP not supported")
3942
3943    for test in [60, 61, 80, 82]:
3944        dev[0].set("dpp_test", str(test))
3945        dev[0].connect("dpp", key_mgmt="DPP", scan_freq="2412", ieee80211w="2",
3946                       dpp_csign=params1_csign,
3947                       dpp_connector=params1_sta_connector,
3948                       dpp_netaccesskey=params1_sta_netaccesskey,
3949                       wait_connect=False)
3950
3951        ev = dev[0].wait_event(["DPP-TX "], timeout=10)
3952        if ev is None or "type=5" not in ev:
3953            raise Exception("Peer Discovery Request TX not reported")
3954        ev = dev[0].wait_event(["DPP-TX-STATUS"], timeout=2)
3955        if ev is None or "result=SUCCESS" not in ev:
3956            raise Exception("Peer Discovery Request TX status not reported")
3957
3958        ev = hapd.wait_event(["DPP-RX"], timeout=10)
3959        if ev is None or "type=5" not in ev:
3960            raise Exception("Peer Discovery Request RX not reported")
3961
3962        if test == 80:
3963            ev = dev[0].wait_event(["DPP-INTRO"], timeout=10)
3964            if ev is None:
3965                raise Exception("DPP-INTRO not reported for test 80")
3966            if "status=7" not in ev:
3967                raise Exception("Unexpected result in test 80: " + ev)
3968
3969        dev[0].request("REMOVE_NETWORK all")
3970        dev[0].dump_monitor()
3971        hapd.dump_monitor()
3972    dev[0].set("dpp_test", "0")
3973
3974    for test in [62, 63, 64, 77, 78, 79]:
3975        hapd.set("dpp_test", str(test))
3976        dev[0].connect("dpp", key_mgmt="DPP", scan_freq="2412", ieee80211w="2",
3977                       dpp_csign=params1_csign,
3978                       dpp_connector=params1_sta_connector,
3979                       dpp_netaccesskey=params1_sta_netaccesskey,
3980                       wait_connect=False)
3981
3982        ev = dev[0].wait_event(["DPP-INTRO"], timeout=10)
3983        if ev is None:
3984            raise Exception("Peer introduction result not reported (test %d)" % test)
3985        if test == 77:
3986            if "fail=transaction_id_mismatch" not in ev:
3987                raise Exception("Connector validation failure not reported")
3988        elif test == 78:
3989            if "status=254" not in ev:
3990                raise Exception("Invalid status value not reported")
3991        elif test == 79:
3992            if "fail=peer_connector_validation_failed" not in ev:
3993                raise Exception("Connector validation failure not reported")
3994        elif "status=" in ev:
3995            raise Exception("Unexpected peer introduction result (test %d): " % test + ev)
3996
3997        dev[0].request("REMOVE_NETWORK all")
3998        dev[0].dump_monitor()
3999        hapd.dump_monitor()
4000    hapd.set("dpp_test", "0")
4001
4002    dev[0].connect("dpp", key_mgmt="DPP", scan_freq="2412", ieee80211w="2",
4003                   dpp_csign=params1_csign, dpp_connector=params1_sta_connector,
4004                   dpp_netaccesskey=params1_sta_netaccesskey)
4005
4006def test_dpp_hostapd_auth_conf_timeout(dev, apdev):
4007    """DPP Authentication Confirm timeout in hostapd"""
4008    check_dpp_capab(dev[0])
4009    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured"})
4010    check_dpp_capab(hapd)
4011    id_h = hapd.dpp_bootstrap_gen(chan="81/1", mac=True)
4012    uri_h = hapd.request("DPP_BOOTSTRAP_GET_URI %d" % id_h)
4013    hapd.dpp_listen(2412)
4014    dev[0].set("dpp_test", "88")
4015    dev[0].dpp_auth_init(uri=uri_h)
4016    ev = hapd.wait_event(["DPP-FAIL"], timeout=10)
4017    if ev is None:
4018        raise Exception("DPP-FAIL not reported")
4019    if "No Auth Confirm received" not in ev:
4020        raise Exception("Unexpected failure reason: " + ev)
4021
4022def test_dpp_hostapd_auth_resp_retries(dev, apdev):
4023    """DPP Authentication Response retries in hostapd"""
4024    check_dpp_capab(dev[0])
4025    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured"})
4026    check_dpp_capab(hapd)
4027
4028    hapd.set("dpp_resp_max_tries", "3")
4029    hapd.set("dpp_resp_retry_time", "100")
4030
4031    id_h = hapd.dpp_bootstrap_gen(chan="81/1", mac=True)
4032    uri_h = hapd.request("DPP_BOOTSTRAP_GET_URI %d" % id_h)
4033    id0b = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
4034    uri0b = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0b)
4035    hapd.dpp_listen(2412, qr="mutual")
4036    dev[0].dpp_auth_init(uri=uri_h, own=id0b)
4037
4038    ev = dev[0].wait_event(["DPP-RESPONSE-PENDING"], timeout=5)
4039    if ev is None:
4040        raise Exception("Pending response not reported")
4041    ev = hapd.wait_event(["DPP-SCAN-PEER-QR-CODE"], timeout=5)
4042    if ev is None:
4043        raise Exception("QR Code scan for mutual authentication not requested")
4044
4045    # Stop Initiator from listening to frames to force retransmission of the
4046    # DPP Authentication Response frame with Status=0
4047    dev[0].request("DPP_STOP_LISTEN")
4048
4049    hapd.dump_monitor()
4050    dev[0].dump_monitor()
4051
4052    id0b = hapd.dpp_qr_code(uri0b)
4053
4054    ev = hapd.wait_event(["DPP-TX "], timeout=5)
4055    if ev is None or "type=1" not in ev:
4056        raise Exception("DPP Authentication Response not sent")
4057    ev = hapd.wait_event(["DPP-TX-STATUS"], timeout=5)
4058    if ev is None:
4059        raise Exception("TX status for DPP Authentication Response not reported")
4060    if "result=FAILED" not in ev:
4061        raise Exception("Unexpected TX status for Authentication Response: " + ev)
4062
4063    ev = hapd.wait_event(["DPP-TX "], timeout=15)
4064    if ev is None or "type=1" not in ev:
4065        raise Exception("DPP Authentication Response retransmission not sent")
4066
4067def test_dpp_qr_code_no_chan_list_unicast(dev, apdev):
4068    """DPP QR Code and no channel list (unicast)"""
4069    run_dpp_qr_code_chan_list(dev, apdev, True, 2417, None)
4070
4071def test_dpp_qr_code_chan_list_unicast(dev, apdev):
4072    """DPP QR Code and 2.4 GHz channels (unicast)"""
4073    run_dpp_qr_code_chan_list(dev, apdev, True, 2417,
4074                              "81/1,81/2,81/3,81/4,81/5,81/6,81/7,81/8,81/9,81/10,81/11,81/12,81/13")
4075
4076def test_dpp_qr_code_chan_list_unicast2(dev, apdev):
4077    """DPP QR Code and 2.4 GHz channels (unicast 2)"""
4078    run_dpp_qr_code_chan_list(dev, apdev, True, 2417,
4079                              "81/1,2,3,4,5,6,7,8,9,10,11,12,13")
4080
4081def test_dpp_qr_code_chan_list_no_peer_unicast(dev, apdev):
4082    """DPP QR Code and channel list and no peer (unicast)"""
4083    run_dpp_qr_code_chan_list(dev, apdev, True, 2417, "81/1,81/6,81/11",
4084                              no_wait=True)
4085    ev = dev[1].wait_event(["DPP-AUTH-INIT-FAILED"], timeout=5)
4086    if ev is None:
4087        raise Exception("Initiation failure not reported")
4088
4089def test_dpp_qr_code_no_chan_list_broadcast(dev, apdev):
4090    """DPP QR Code and no channel list (broadcast)"""
4091    run_dpp_qr_code_chan_list(dev, apdev, False, 2412, None)
4092
4093def test_dpp_qr_code_chan_list_broadcast(dev, apdev):
4094    """DPP QR Code and some 2.4 GHz channels (broadcast)"""
4095    run_dpp_qr_code_chan_list(dev, apdev, False, 2412, "81/1,81/6,81/11",
4096                              timeout=10)
4097
4098def run_dpp_qr_code_chan_list(dev, apdev, unicast, listen_freq, chanlist,
4099                              no_wait=False, timeout=5):
4100    check_dpp_capab(dev[0])
4101    check_dpp_capab(dev[1])
4102    dev[1].set("dpp_init_max_tries", "3")
4103    dev[1].set("dpp_init_retry_time", "100")
4104    dev[1].set("dpp_resp_wait_time", "1000")
4105
4106    logger.info("dev0 displays QR Code")
4107    id0 = dev[0].dpp_bootstrap_gen(chan=chanlist, mac=unicast)
4108    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
4109    logger.info("dev1 scans QR Code and initiates DPP Authentication")
4110    dev[0].dpp_listen(listen_freq)
4111    dev[1].dpp_auth_init(uri=uri0)
4112    if no_wait:
4113        return
4114    wait_auth_success(dev[0], dev[1], timeout=timeout, configurator=dev[1],
4115                      enrollee=dev[0], allow_enrollee_failure=True,
4116                      stop_responder=True)
4117
4118def test_dpp_qr_code_chan_list_no_match(dev, apdev):
4119    """DPP QR Code and no matching supported channel"""
4120    check_dpp_capab(dev[0])
4121    check_dpp_capab(dev[1])
4122    id0 = dev[0].dpp_bootstrap_gen(chan="123/123")
4123    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
4124    dev[1].dpp_auth_init(uri=uri0, expect_fail=True)
4125
4126def test_dpp_pkex_alloc_fail(dev, apdev):
4127    """DPP/PKEX and memory allocation failures"""
4128    check_dpp_capab(dev[0])
4129    check_dpp_capab(dev[1])
4130
4131    tests = [(1, "=dpp_keygen_configurator"),
4132             (1, "base64_gen_encode;dpp_keygen_configurator")]
4133    for count, func in tests:
4134        with alloc_fail(dev[1], count, func):
4135            cmd = "DPP_CONFIGURATOR_ADD"
4136            res = dev[1].request(cmd)
4137            if "FAIL" not in res:
4138                raise Exception("Unexpected DPP_CONFIGURATOR_ADD success")
4139
4140    conf_id = dev[1].dpp_configurator_add()
4141
4142    id0 = None
4143    id1 = None
4144
4145    # Local error cases on the Initiator
4146    tests = [(1, "crypto_ec_key_get_pubkey_point"),
4147             (1, "dpp_alloc_msg;dpp_pkex_build_exchange_req"),
4148             (1, "dpp_alloc_msg;dpp_pkex_build_commit_reveal_req"),
4149             (1, "dpp_alloc_msg;dpp_auth_build_req"),
4150             (1, "dpp_alloc_msg;dpp_auth_build_conf"),
4151             (1, "dpp_bootstrap_key_hash"),
4152             (1, "dpp_auth_init"),
4153             (1, "dpp_alloc_auth"),
4154             (1, "=dpp_auth_resp_rx"),
4155             (1, "dpp_build_conf_start"),
4156             (1, "dpp_build_conf_obj_dpp"),
4157             (2, "dpp_build_conf_obj_dpp"),
4158             (3, "dpp_build_conf_obj_dpp"),
4159             (4, "dpp_build_conf_obj_dpp"),
4160             (5, "dpp_build_conf_obj_dpp"),
4161             (6, "dpp_build_conf_obj_dpp"),
4162             (7, "dpp_build_conf_obj_dpp"),
4163             (8, "dpp_build_conf_obj_dpp"),
4164             (1, "dpp_conf_req_rx"),
4165             (2, "dpp_conf_req_rx"),
4166             (3, "dpp_conf_req_rx"),
4167             (4, "dpp_conf_req_rx"),
4168             (5, "dpp_conf_req_rx"),
4169             (6, "dpp_conf_req_rx"),
4170             (7, "dpp_conf_req_rx"),
4171             (1, "dpp_pkex_init"),
4172             (2, "dpp_pkex_init"),
4173             (3, "dpp_pkex_init"),
4174             (1, "dpp_pkex_derive_z"),
4175             (1, "=dpp_pkex_rx_commit_reveal_resp"),
4176             (1, "crypto_ec_key_get_pubkey_point;dpp_build_jwk"),
4177             (2, "crypto_ec_key_get_pubkey_point;dpp_build_jwk"),
4178             (1, "crypto_ec_key_get_pubkey_point;dpp_auth_init")]
4179    for count, func in tests:
4180        dev[0].request("DPP_STOP_LISTEN")
4181        dev[1].request("DPP_STOP_LISTEN")
4182        dev[0].dump_monitor()
4183        dev[1].dump_monitor()
4184        id0 = dev[0].dpp_pkex_resp(2437, identifier="test", code="secret",
4185                                   use_id=id0)
4186
4187        with alloc_fail(dev[1], count, func):
4188            id1 = dev[1].dpp_pkex_init(identifier="test", code="secret",
4189                                       use_id=id1,
4190                                       extra="conf=sta-dpp configurator=%d" % conf_id,
4191                                       allow_fail=True)
4192            wait_fail_trigger(dev[1], "GET_ALLOC_FAIL", max_iter=100)
4193            ev = dev[0].wait_event(["GAS-QUERY-START"], timeout=0.01)
4194            if ev:
4195                dev[0].request("DPP_STOP_LISTEN")
4196                dev[0].wait_event(["GAS-QUERY-DONE"], timeout=3)
4197
4198    # Local error cases on the Responder
4199    tests = [(1, "crypto_ec_key_get_pubkey_point"),
4200             (1, "dpp_alloc_msg;dpp_pkex_build_exchange_resp"),
4201             (1, "dpp_alloc_msg;dpp_pkex_build_commit_reveal_resp"),
4202             (1, "dpp_alloc_msg;dpp_auth_build_resp"),
4203             (1, "crypto_ec_key_get_pubkey_point;dpp_auth_build_resp_ok"),
4204             (1, "dpp_alloc_auth"),
4205             (1, "=dpp_auth_req_rx"),
4206             (1, "=dpp_auth_conf_rx"),
4207             (1, "json_parse;dpp_parse_jws_prot_hdr"),
4208             (1, "json_get_member_base64url;dpp_parse_jws_prot_hdr"),
4209             (1, "json_get_member_base64url;dpp_parse_jwk"),
4210             (2, "json_get_member_base64url;dpp_parse_jwk"),
4211             (1, "json_parse;dpp_parse_connector"),
4212             (1, "dpp_parse_jwk;dpp_parse_connector"),
4213             (1, "dpp_parse_jwk;dpp_parse_cred_dpp"),
4214             (1, "crypto_ec_key_get_pubkey_point;dpp_check_pubkey_match"),
4215             (1, "base64_gen_decode;dpp_process_signed_connector"),
4216             (1, "dpp_parse_jws_prot_hdr;dpp_process_signed_connector"),
4217             (2, "base64_gen_decode;dpp_process_signed_connector"),
4218             (3, "base64_gen_decode;dpp_process_signed_connector"),
4219             (4, "base64_gen_decode;dpp_process_signed_connector"),
4220             (1, "json_parse;dpp_parse_conf_obj"),
4221             (1, "dpp_conf_resp_rx"),
4222             (1, "=dpp_pkex_derive_z"),
4223             (1, "=dpp_pkex_rx_exchange_req"),
4224             (2, "=dpp_pkex_rx_exchange_req"),
4225             (3, "=dpp_pkex_rx_exchange_req"),
4226             (1, "=dpp_pkex_rx_commit_reveal_req"),
4227             (1, "crypto_ec_key_get_pubkey_point;dpp_pkex_rx_commit_reveal_req"),
4228             (1, "dpp_bootstrap_key_hash")]
4229    for count, func in tests:
4230        dev[0].request("DPP_STOP_LISTEN")
4231        dev[1].request("DPP_STOP_LISTEN")
4232        dev[0].dump_monitor()
4233        dev[1].dump_monitor()
4234        id0 = dev[0].dpp_pkex_resp(2437, identifier="test", code="secret",
4235                                   use_id=id0)
4236
4237        with alloc_fail(dev[0], count, func):
4238            id1 = dev[1].dpp_pkex_init(identifier="test", code="secret",
4239                                       use_id=id1,
4240                                       extra="conf=sta-dpp configurator=%d" % conf_id)
4241            wait_fail_trigger(dev[0], "GET_ALLOC_FAIL", max_iter=100)
4242            ev = dev[0].wait_event(["GAS-QUERY-START"], timeout=0.01)
4243            if ev:
4244                dev[0].request("DPP_STOP_LISTEN")
4245                dev[0].wait_event(["GAS-QUERY-DONE"], timeout=3)
4246
4247def test_dpp_pkex_test_fail(dev, apdev):
4248    """DPP/PKEX and local failures"""
4249    check_dpp_capab(dev[0])
4250    check_dpp_capab(dev[1])
4251
4252    tests = [(1, "dpp_keygen_configurator")]
4253    for count, func in tests:
4254        with fail_test(dev[1], count, func):
4255            cmd = "DPP_CONFIGURATOR_ADD"
4256            res = dev[1].request(cmd)
4257            if "FAIL" not in res:
4258                raise Exception("Unexpected DPP_CONFIGURATOR_ADD success")
4259
4260    tests = [(1, "dpp_keygen")]
4261    for count, func in tests:
4262        with fail_test(dev[1], count, func):
4263            cmd = "DPP_BOOTSTRAP_GEN type=pkex"
4264            res = dev[1].request(cmd)
4265            if "FAIL" not in res:
4266                raise Exception("Unexpected DPP_BOOTSTRAP_GEN success")
4267
4268    conf_id = dev[1].dpp_configurator_add()
4269
4270    id0 = None
4271    id1 = None
4272
4273    # Local error cases on the Initiator
4274    tests = [(1, "aes_siv_encrypt;dpp_auth_build_req"),
4275             (1, "os_get_random;dpp_auth_init"),
4276             (1, "dpp_derive_k1;dpp_auth_init"),
4277             (1, "dpp_hkdf_expand;dpp_derive_k1;dpp_auth_init"),
4278             (1, "dpp_gen_i_auth;dpp_auth_build_conf"),
4279             (1, "aes_siv_encrypt;dpp_auth_build_conf"),
4280             (1, "dpp_derive_k2;dpp_auth_resp_rx"),
4281             (1, "dpp_hkdf_expand;dpp_derive_k2;dpp_auth_resp_rx"),
4282             (1, "dpp_derive_bk_ke;dpp_auth_resp_rx"),
4283             (1, "dpp_hkdf_expand;dpp_derive_bk_ke;dpp_auth_resp_rx"),
4284             (1, "dpp_gen_r_auth;dpp_auth_resp_rx"),
4285             (1, "aes_siv_encrypt;dpp_build_conf_resp"),
4286             (1, "dpp_pkex_derive_Qi;dpp_pkex_build_exchange_req"),
4287             (1, "aes_siv_encrypt;dpp_pkex_build_commit_reveal_req"),
4288             (1, "hmac_sha256_vector;dpp_pkex_rx_exchange_resp"),
4289             (1, "aes_siv_decrypt;dpp_pkex_rx_commit_reveal_resp"),
4290             (1, "hmac_sha256_vector;dpp_pkex_rx_commit_reveal_resp"),
4291             (1, "dpp_bootstrap_key_hash")]
4292    for count, func in tests:
4293        dev[0].request("DPP_STOP_LISTEN")
4294        dev[1].request("DPP_STOP_LISTEN")
4295        dev[0].dump_monitor()
4296        dev[1].dump_monitor()
4297        id0 = dev[0].dpp_pkex_resp(2437, identifier="test", code="secret",
4298                                   use_id=id0)
4299
4300        with fail_test(dev[1], count, func):
4301            id1 = dev[1].dpp_pkex_init(identifier="test", code="secret",
4302                                       use_id=id1,
4303                                       extra="conf=sta-dpp configurator=%d" % conf_id,
4304                                       allow_fail=True)
4305            wait_fail_trigger(dev[1], "GET_FAIL", max_iter=100)
4306            ev = dev[0].wait_event(["GAS-QUERY-START"], timeout=0.01)
4307            if ev:
4308                dev[0].request("DPP_STOP_LISTEN")
4309                dev[0].wait_event(["GAS-QUERY-DONE"], timeout=3)
4310
4311    # Local error cases on the Responder
4312    tests = [(1, "aes_siv_encrypt;dpp_auth_build_resp"),
4313             (1, "aes_siv_encrypt;dpp_auth_build_resp;dpp_auth_build_resp_ok"),
4314             (1, "os_get_random;dpp_build_conf_req"),
4315             (1, "aes_siv_encrypt;dpp_build_conf_req"),
4316             (1, "os_get_random;dpp_auth_build_resp_ok"),
4317             (1, "dpp_derive_k2;dpp_auth_build_resp_ok"),
4318             (1, "dpp_derive_bk_ke;dpp_auth_build_resp_ok"),
4319             (1, "dpp_gen_r_auth;dpp_auth_build_resp_ok"),
4320             (1, "aes_siv_encrypt;dpp_auth_build_resp_ok"),
4321             (1, "dpp_derive_k1;dpp_auth_req_rx"),
4322             (1, "aes_siv_decrypt;dpp_auth_req_rx"),
4323             (1, "aes_siv_decrypt;dpp_auth_conf_rx"),
4324             (1, "dpp_gen_i_auth;dpp_auth_conf_rx"),
4325             (1, "dpp_check_pubkey_match"),
4326             (1, "aes_siv_decrypt;dpp_conf_resp_rx"),
4327             (1, "hmac_sha256_kdf;dpp_pkex_derive_z"),
4328             (1, "dpp_pkex_derive_Qi;dpp_pkex_rx_exchange_req"),
4329             (1, "dpp_pkex_derive_Qr;dpp_pkex_rx_exchange_req"),
4330             (1, "aes_siv_encrypt;dpp_pkex_build_commit_reveal_resp"),
4331             (1, "aes_siv_decrypt;dpp_pkex_rx_commit_reveal_req"),
4332             (1, "hmac_sha256_vector;dpp_pkex_rx_commit_reveal_req"),
4333             (2, "hmac_sha256_vector;dpp_pkex_rx_commit_reveal_req")]
4334    for count, func in tests:
4335        dev[0].request("DPP_STOP_LISTEN")
4336        dev[1].request("DPP_STOP_LISTEN")
4337        dev[0].dump_monitor()
4338        dev[1].dump_monitor()
4339        id0 = dev[0].dpp_pkex_resp(2437, identifier="test", code="secret",
4340                                   use_id=id0)
4341
4342        with fail_test(dev[0], count, func):
4343            id1 = dev[1].dpp_pkex_init(identifier="test", code="secret",
4344                                       use_id=id1,
4345                                       extra="conf=sta-dpp configurator=%d" % conf_id)
4346            wait_fail_trigger(dev[0], "GET_FAIL", max_iter=100)
4347            ev = dev[0].wait_event(["GAS-QUERY-START"], timeout=0.01)
4348            if ev:
4349                dev[0].request("DPP_STOP_LISTEN")
4350                dev[0].wait_event(["GAS-QUERY-DONE"], timeout=3)
4351
4352def test_dpp_keygen_configurator_error(dev, apdev):
4353    """DPP Configurator keygen error case"""
4354    check_dpp_capab(dev[0])
4355    if "FAIL" not in dev[0].request("DPP_CONFIGURATOR_ADD curve=unknown"):
4356        raise Exception("Unexpected success of invalid DPP_CONFIGURATOR_ADD")
4357
4358def rx_process_frame(dev):
4359    msg = dev.mgmt_rx()
4360    if msg is None:
4361        raise Exception("No management frame RX reported")
4362    if "OK" not in dev.request("MGMT_RX_PROCESS freq={} datarate={} ssi_signal={} frame={}".format(
4363        msg['freq'], msg['datarate'], msg['ssi_signal'], binascii.hexlify(msg['frame']).decode())):
4364        raise Exception("MGMT_RX_PROCESS failed")
4365    return msg
4366
4367def wait_auth_success(responder, initiator, configurator=None, enrollee=None,
4368                      allow_enrollee_failure=False,
4369                      allow_configurator_failure=False,
4370                      require_configurator_failure=False,
4371                      timeout=5, stop_responder=False, stop_initiator=False):
4372    res = {}
4373    ev = responder.wait_event(["DPP-AUTH-SUCCESS", "DPP-FAIL"], timeout=timeout)
4374    if ev is None or "DPP-AUTH-SUCCESS" not in ev:
4375        raise Exception("DPP authentication did not succeed (Responder)")
4376    ev = initiator.wait_event(["DPP-AUTH-SUCCESS", "DPP-FAIL"], timeout=5)
4377    if ev is None or "DPP-AUTH-SUCCESS" not in ev:
4378        raise Exception("DPP authentication did not succeed (Initiator)")
4379    if configurator:
4380        ev = configurator.wait_event(["DPP-CONF-SENT",
4381                                      "DPP-CONF-FAILED"], timeout=5)
4382        if ev is None:
4383            raise Exception("DPP configuration not completed (Configurator)")
4384        if "DPP-CONF-FAILED" in ev and not allow_configurator_failure:
4385            raise Exception("DPP configuration did not succeed (Configurator)")
4386        if "DPP-CONF-SENT" in ev and require_configurator_failure:
4387            raise Exception("DPP configuration succeeded (Configurator)")
4388        if "DPP-CONF-SENT" in ev and "wait_conn_status=1" in ev:
4389            res['wait_conn_status'] = True
4390    if enrollee:
4391        ev = enrollee.wait_event(["DPP-CONF-RECEIVED",
4392                                  "DPP-CONF-FAILED"], timeout=5)
4393        if ev is None:
4394            raise Exception("DPP configuration not completed (Enrollee)")
4395        if "DPP-CONF-FAILED" in ev and not allow_enrollee_failure:
4396            raise Exception("DPP configuration did not succeed (Enrollee)")
4397    if stop_responder:
4398        responder.request("DPP_STOP_LISTEN")
4399    if stop_initiator:
4400        initiator.request("DPP_STOP_LISTEN")
4401    return res
4402
4403def wait_conf_completion(configurator, enrollee):
4404    ev = configurator.wait_event(["DPP-CONF-SENT"], timeout=5)
4405    if ev is None:
4406        raise Exception("DPP configuration not completed (Configurator)")
4407    ev = enrollee.wait_event(["DPP-CONF-RECEIVED", "DPP-CONF-FAILED"],
4408                             timeout=5)
4409    if ev is None:
4410        raise Exception("DPP configuration not completed (Enrollee)")
4411
4412def start_dpp(dev):
4413    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
4414    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
4415
4416    conf = '{"wi-fi_tech":"infra", "discovery":{"ssid":"test"},"cred":{"akm":"psk","pass":"secret passphrase"}}' + 3000*' '
4417    dev[0].set("dpp_config_obj_override", conf)
4418
4419    dev[0].set("ext_mgmt_frame_handling", "1")
4420    dev[0].dpp_listen(2412)
4421    dev[1].dpp_auth_init(uri=uri0, role="enrollee")
4422
4423def test_dpp_gas_timeout_handling(dev, apdev):
4424    """DPP and GAS timeout handling"""
4425    check_dpp_capab(dev[0])
4426    check_dpp_capab(dev[1])
4427    start_dpp(dev)
4428
4429    # DPP Authentication Request
4430    rx_process_frame(dev[0])
4431
4432    # DPP Authentication Confirmation
4433    rx_process_frame(dev[0])
4434
4435    wait_auth_success(dev[0], dev[1])
4436
4437    # DPP Configuration Request (GAS Initial Request frame)
4438    rx_process_frame(dev[0])
4439
4440    # DPP Configuration Request (GAS Comeback Request frame)
4441    rx_process_frame(dev[0])
4442
4443    # Wait for GAS timeout
4444    ev = dev[1].wait_event(["DPP-CONF-FAILED"], timeout=5)
4445    if ev is None:
4446        raise Exception("DPP configuration not completed (Enrollee)")
4447
4448def test_dpp_gas_comeback_after_failure(dev, apdev):
4449    """DPP and GAS comeback after failure"""
4450    check_dpp_capab(dev[0])
4451    check_dpp_capab(dev[1])
4452    start_dpp(dev)
4453
4454    # DPP Authentication Request
4455    rx_process_frame(dev[0])
4456
4457    # DPP Authentication Confirmation
4458    rx_process_frame(dev[0])
4459
4460    wait_auth_success(dev[0], dev[1])
4461
4462    # DPP Configuration Request (GAS Initial Request frame)
4463    rx_process_frame(dev[0])
4464
4465    # DPP Configuration Request (GAS Comeback Request frame)
4466    msg = dev[0].mgmt_rx()
4467    frame = binascii.hexlify(msg['frame']).decode()
4468    with alloc_fail(dev[0], 1, "gas_build_comeback_resp;gas_server_handle_rx_comeback_req"):
4469        if "OK" not in dev[0].request("MGMT_RX_PROCESS freq={} datarate={} ssi_signal={} frame={}".format(msg['freq'], msg['datarate'], msg['ssi_signal'], frame)):
4470            raise Exception("MGMT_RX_PROCESS failed")
4471        wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4472    # Try the same frame again - this is expected to fail since the response has
4473    # already been freed.
4474    if "OK" not in dev[0].request("MGMT_RX_PROCESS freq={} datarate={} ssi_signal={} frame={}".format(msg['freq'], msg['datarate'], msg['ssi_signal'], frame)):
4475        raise Exception("MGMT_RX_PROCESS failed")
4476
4477    # DPP Configuration Request (GAS Comeback Request frame retry)
4478    msg = dev[0].mgmt_rx()
4479
4480def test_dpp_gas(dev, apdev):
4481    """DPP and GAS protocol testing"""
4482    ver0 = check_dpp_capab(dev[0])
4483    ver1 = check_dpp_capab(dev[1])
4484    start_dpp(dev)
4485
4486    # DPP Authentication Request
4487    rx_process_frame(dev[0])
4488
4489    # DPP Authentication Confirmation
4490    rx_process_frame(dev[0])
4491
4492    wait_auth_success(dev[0], dev[1])
4493
4494    # DPP Configuration Request (GAS Initial Request frame)
4495    msg = dev[0].mgmt_rx()
4496
4497    # Protected Dual of GAS Initial Request frame (dropped by GAS server)
4498    if msg == None:
4499        raise Exception("MGMT_RX_PROCESS failed. <Please retry>")
4500    frame = binascii.hexlify(msg['frame'])
4501    frame = frame[0:48] + b"09" + frame[50:]
4502    frame = frame.decode()
4503    if "OK" not in dev[0].request("MGMT_RX_PROCESS freq={} datarate={} ssi_signal={} frame={}".format(msg['freq'], msg['datarate'], msg['ssi_signal'], frame)):
4504        raise Exception("MGMT_RX_PROCESS failed")
4505
4506    with alloc_fail(dev[0], 1, "gas_server_send_resp"):
4507        frame = binascii.hexlify(msg['frame']).decode()
4508        if "OK" not in dev[0].request("MGMT_RX_PROCESS freq={} datarate={} ssi_signal={} frame={}".format(msg['freq'], msg['datarate'], msg['ssi_signal'], frame)):
4509            raise Exception("MGMT_RX_PROCESS failed")
4510        wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4511
4512    with alloc_fail(dev[0], 1, "gas_build_initial_resp;gas_server_send_resp"):
4513        frame = binascii.hexlify(msg['frame']).decode()
4514        if "OK" not in dev[0].request("MGMT_RX_PROCESS freq={} datarate={} ssi_signal={} frame={}".format(msg['freq'], msg['datarate'], msg['ssi_signal'], frame)):
4515            raise Exception("MGMT_RX_PROCESS failed")
4516        wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4517
4518    # Add extra data after Query Request field to trigger
4519    # "GAS: Ignored extra data after Query Request field"
4520    frame = binascii.hexlify(msg['frame']).decode() + "00"
4521    if "OK" not in dev[0].request("MGMT_RX_PROCESS freq={} datarate={} ssi_signal={} frame={}".format(msg['freq'], msg['datarate'], msg['ssi_signal'], frame)):
4522        raise Exception("MGMT_RX_PROCESS failed")
4523
4524    # DPP Configuration Request (GAS Comeback Request frame)
4525    rx_process_frame(dev[0])
4526
4527    # DPP Configuration Request (GAS Comeback Request frame)
4528    rx_process_frame(dev[0])
4529
4530    # DPP Configuration Request (GAS Comeback Request frame)
4531    rx_process_frame(dev[0])
4532
4533    if ver0 >= 2 and ver1 >= 2:
4534        # DPP Configuration Result
4535        rx_process_frame(dev[0])
4536
4537    wait_conf_completion(dev[0], dev[1])
4538
4539def test_dpp_truncated_attr(dev, apdev):
4540    """DPP and truncated attribute"""
4541    check_dpp_capab(dev[0])
4542    check_dpp_capab(dev[1])
4543    start_dpp(dev)
4544
4545    # DPP Authentication Request
4546    msg = dev[0].mgmt_rx()
4547    frame = msg['frame']
4548
4549    # DPP: Truncated message - not enough room for the attribute - dropped
4550    frame1 = binascii.hexlify(frame[0:36]).decode()
4551    if "OK" not in dev[0].request("MGMT_RX_PROCESS freq={} datarate={} ssi_signal={} frame={}".format(msg['freq'], msg['datarate'], msg['ssi_signal'], frame1)):
4552        raise Exception("MGMT_RX_PROCESS failed")
4553    ev = dev[0].wait_event(["DPP-RX"], timeout=5)
4554    if ev is None or "ignore=invalid-attributes" not in ev:
4555        raise Exception("Invalid attribute error not reported")
4556
4557    # DPP: Unexpected octets (3) after the last attribute
4558    frame2 = binascii.hexlify(frame).decode() + "000000"
4559    if "OK" not in dev[0].request("MGMT_RX_PROCESS freq={} datarate={} ssi_signal={} frame={}".format(msg['freq'], msg['datarate'], msg['ssi_signal'], frame2)):
4560        raise Exception("MGMT_RX_PROCESS failed")
4561    ev = dev[0].wait_event(["DPP-RX"], timeout=5)
4562    if ev is None or "ignore=invalid-attributes" not in ev:
4563        raise Exception("Invalid attribute error not reported")
4564
4565def test_dpp_bootstrap_key_autogen_issues(dev, apdev):
4566    """DPP bootstrap key autogen issues"""
4567    check_dpp_capab(dev[0])
4568    check_dpp_capab(dev[1])
4569
4570    logger.info("dev0 displays QR Code")
4571    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
4572    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
4573
4574    logger.info("dev1 scans QR Code")
4575    id1 = dev[1].dpp_qr_code(uri0)
4576
4577    logger.info("dev1 initiates DPP Authentication")
4578    dev[0].dpp_listen(2412)
4579    with alloc_fail(dev[1], 1, "dpp_autogen_bootstrap_key"):
4580        dev[1].dpp_auth_init(peer=id1, expect_fail=True)
4581    with alloc_fail(dev[1], 1, "dpp_gen_uri;dpp_autogen_bootstrap_key"):
4582        dev[1].dpp_auth_init(peer=id1, expect_fail=True)
4583    with fail_test(dev[1], 1, "dpp_keygen;dpp_autogen_bootstrap_key"):
4584        dev[1].dpp_auth_init(peer=id1, expect_fail=True)
4585    dev[0].request("DPP_STOP_LISTEN")
4586
4587def test_dpp_auth_resp_status_failure(dev, apdev):
4588    """DPP and Auth Resp(status) build failure"""
4589    with alloc_fail(dev[0], 1, "dpp_auth_build_resp"):
4590        run_dpp_proto_auth_resp_missing(dev, 99999, None,
4591                                        incompatible_roles=True)
4592
4593def test_dpp_auth_resp_aes_siv_issue(dev, apdev):
4594    """DPP Auth Resp AES-SIV issue"""
4595    check_dpp_capab(dev[0])
4596    check_dpp_capab(dev[1])
4597    logger.info("dev0 displays QR Code")
4598    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
4599    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
4600    logger.info("dev1 scans QR Code and initiates DPP Authentication")
4601    dev[0].dpp_listen(2412)
4602    with fail_test(dev[1], 1, "aes_siv_decrypt;dpp_auth_resp_rx"):
4603        dev[1].dpp_auth_init(uri=uri0)
4604        wait_dpp_fail(dev[1], "AES-SIV decryption failed")
4605    dev[0].request("DPP_STOP_LISTEN")
4606
4607def test_dpp_invalid_legacy_params(dev, apdev):
4608    """DPP invalid legacy parameters"""
4609    check_dpp_capab(dev[0])
4610    check_dpp_capab(dev[1])
4611    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
4612    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
4613    # No pass/psk
4614    dev[1].dpp_auth_init(uri=uri0, conf="sta-psk", ssid="dpp-legacy",
4615                         expect_fail=True)
4616
4617def test_dpp_invalid_legacy_params2(dev, apdev):
4618    """DPP invalid legacy parameters 2"""
4619    check_dpp_capab(dev[0])
4620    check_dpp_capab(dev[1])
4621    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
4622    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
4623    dev[0].set("dpp_configurator_params",
4624               " conf=sta-psk ssid=%s" % (binascii.hexlify(b"dpp-legacy").decode()))
4625    dev[0].dpp_listen(2412, role="configurator")
4626    dev[1].dpp_auth_init(uri=uri0, role="enrollee")
4627    # No pass/psk
4628    ev = dev[0].wait_event(["DPP: Failed to set configurator parameters"],
4629                           timeout=5)
4630    if ev is None:
4631        raise Exception("DPP configuration failure not reported")
4632
4633def test_dpp_legacy_params_failure(dev, apdev):
4634    """DPP legacy parameters local failure"""
4635    check_dpp_capab(dev[0])
4636    check_dpp_capab(dev[1])
4637    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
4638    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
4639    dev[0].dpp_listen(2412)
4640    with alloc_fail(dev[1], 1, "dpp_build_conf_obj_legacy"):
4641        dev[1].dpp_auth_init(uri=uri0, conf="sta-psk", passphrase="passphrase",
4642                             ssid="dpp-legacy")
4643        ev = dev[0].wait_event(["DPP-CONF-FAILED"], timeout=5)
4644        if ev is None:
4645            raise Exception("DPP configuration failure not reported")
4646
4647def test_dpp_invalid_configurator_key(dev, apdev):
4648    """DPP invalid configurator key"""
4649    check_dpp_capab(dev[0])
4650
4651    if "FAIL" not in dev[0].request("DPP_CONFIGURATOR_ADD key=aa"):
4652        raise Exception("Invalid key accepted")
4653
4654    with alloc_fail(dev[0], 1, "dpp_keygen_configurator"):
4655        if "FAIL" not in dev[0].request("DPP_CONFIGURATOR_ADD key=" + dpp_key_p256):
4656            raise Exception("Error not reported")
4657
4658    with alloc_fail(dev[0], 1,
4659                    "crypto_ec_key_get_pubkey_point;dpp_keygen_configurator"):
4660        if "FAIL" not in dev[0].request("DPP_CONFIGURATOR_ADD key=" + dpp_key_p256):
4661            raise Exception("Error not reported")
4662
4663    with alloc_fail(dev[0], 1, "base64_gen_encode;dpp_keygen_configurator"):
4664        if "FAIL" not in dev[0].request("DPP_CONFIGURATOR_ADD key=" + dpp_key_p256):
4665            raise Exception("Error not reported")
4666
4667    with fail_test(dev[0], 1, "dpp_keygen_configurator"):
4668        if "FAIL" not in dev[0].request("DPP_CONFIGURATOR_ADD key=" + dpp_key_p256):
4669            raise Exception("Error not reported")
4670
4671def test_dpp_own_config_sign_fail(dev, apdev):
4672    """DPP own config signing failure"""
4673    check_dpp_capab(dev[0])
4674    conf_id = dev[0].dpp_configurator_add()
4675    tests = ["",
4676             " ",
4677             " conf=sta-dpp",
4678             " configurator=%d" % conf_id,
4679             " conf=sta-dpp configurator=%d curve=unsupported" % conf_id]
4680    for t in tests:
4681        if "FAIL" not in dev[0].request("DPP_CONFIGURATOR_SIGN " + t):
4682            raise Exception("Invalid command accepted: " + t)
4683
4684def test_dpp_peer_intro_failures(dev, apdev):
4685    """DPP peer introduction failures"""
4686    try:
4687        run_dpp_peer_intro_failures(dev, apdev)
4688    finally:
4689        dev[0].set("dpp_config_processing", "0", allow_fail=True)
4690
4691def run_dpp_peer_intro_failures(dev, apdev):
4692    check_dpp_capab(dev[0])
4693    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured"})
4694    check_dpp_capab(hapd)
4695
4696    conf_id = hapd.dpp_configurator_add(key=dpp_key_p256)
4697    csign = hapd.request("DPP_CONFIGURATOR_GET_KEY %d" % conf_id)
4698    if "FAIL" in csign or len(csign) == 0:
4699        raise Exception("DPP_CONFIGURATOR_GET_KEY failed")
4700
4701    conf_id2 = dev[0].dpp_configurator_add(key=csign)
4702    csign2 = dev[0].request("DPP_CONFIGURATOR_GET_KEY %d" % conf_id2)
4703
4704    if csign != csign2:
4705        raise Exception("Unexpected difference in configurator key")
4706
4707    cmd = "DPP_CONFIGURATOR_SIGN  conf=ap-dpp configurator=%d" % conf_id
4708    res = hapd.request(cmd)
4709    if "FAIL" in res:
4710        raise Exception("Failed to generate own configuration")
4711    update_hapd_config(hapd)
4712
4713    dev[0].set("dpp_config_processing", "1")
4714    cmd = "DPP_CONFIGURATOR_SIGN  conf=sta-dpp configurator=%d" % conf_id
4715    res = dev[0].request(cmd)
4716    if "FAIL" in res:
4717        raise Exception("Failed to generate own configuration")
4718    ev = dev[0].wait_event(["DPP-NETWORK-ID"], timeout=1)
4719    if ev is None:
4720        raise Exception("DPP network profile not generated")
4721    id = ev.split(' ')[1]
4722    dev[0].select_network(id, freq=2412)
4723    dev[0].wait_connected()
4724    dev[0].request("DISCONNECT")
4725    dev[0].wait_disconnected()
4726    dev[0].dump_monitor()
4727
4728    tests = ["eyJ0eXAiOiJkcHBDb24iLCJraWQiOiIwTlNSNTlxRTc0alFfZTFLVGVPV1lYY1pTWnFUaDdNXzU0aHJPcFRpaFJnIiwiYWxnIjoiRVMyNTYifQ.eyJncm91cHMiOltdLCJuZXRBY2Nlc3NLZXkiOnsia3R5IjoiRUMiLCJjcnYiOiJQLTI1NiIsIngiOiJiVmFMRGlBT09OQmFjcVFVN1pYamFBVEtEMVhhbDVlUExqOUZFZUl3VkN3IiwieSI6Il95c25JR1hTYjBvNEsyMWg0anZmSkZxMHdVNnlPNWp1VUFPd3FuM0dHVHMifX0.WgzZBOJaisWBRxvtXPbVYPXU7OIZxs6sZD-cPOLmJVTIYZKdMkSOMvP5b6si_j61FIrjhm43tmGq1P6cpoxB_g",
4729             "eyJ0eXAiOiJkcHBDb24iLCJraWQiOiIwTlNSNTlxRTc0alFfZTFLVGVPV1lYY1pTWnFUaDdNXzU0aHJPcFRpaFJnIiwiYWxnIjoiRVMyNTYifQ.eyJncm91cHMiOlt7fV0sIm5ldEFjY2Vzc0tleSI6eyJrdHkiOiJFQyIsImNydiI6IlAtMjU2IiwieCI6IkJhY3BWSDNpNDBrZklNS0RHa1FFRzhCODBCaEk4cEFmTWpLbzM5NlFZT2ciLCJ5IjoiMjBDYjhDNjRsSjFzQzV2NXlKMnBFZXRRempxMjI4YVV2cHMxNmQ0M3EwQSJ9fQ.dG2y8VvZQJ5hfob8E5F2FAeR7Nd700qstYkxDgA2QfARaNMZ0_SfKfoG-yKXsIZNM-TvGBfACgfhagG9Oaw_Xw",
4730             "eyJ0eXAiOiJkcHBDb24iLCJraWQiOiIwTlNSNTlxRTc0alFfZTFLVGVPV1lYY1pTWnFUaDdNXzU0aHJPcFRpaFJnIiwiYWxnIjoiRVMyNTYifQ.eyJncm91cHMiOlt7Imdyb3VwSWQiOiIqIn1dLCJuZXRBY2Nlc3NLZXkiOnsia3R5IjoiRUMiLCJjcnYiOiJQLTI1NiIsIngiOiJkc2VmcmJWWlhad0RMWHRpLWlObDBBYkFIOXpqeFFKd0R1SUd5NzNuZGU0IiwieSI6IjZFQnExN3cwYW1fZlh1OUQ4UGxWYk9XZ2I3b19DcTUxWHlmSG8wcHJyeDQifX0.caBvdDUtXrhnS61-juVZ_2FQdprepv0yZjC04G4ERvLUpeX7cgu0Hp-A1aFDogP1PEFGpkaEdcAWRQnSSRiIKQ"]
4731    for t in tests:
4732        dev[0].set_network_quoted(id, "dpp_connector", t)
4733        dev[0].select_network(id, freq=2412)
4734        ev = dev[0].wait_event(["DPP-INTRO"], timeout=5)
4735        if ev is None or "status=8" not in ev:
4736            raise Exception("Introduction failure not reported")
4737        dev[0].request("DISCONNECT")
4738        dev[0].dump_monitor()
4739
4740def test_dpp_peer_intro_local_failures(dev, apdev):
4741    """DPP peer introduction local failures"""
4742    check_dpp_capab(dev[0])
4743    check_dpp_capab(dev[1])
4744
4745    params = {"ssid": "dpp",
4746              "wpa": "2",
4747              "wpa_key_mgmt": "DPP",
4748              "ieee80211w": "2",
4749              "rsn_pairwise": "CCMP",
4750              "dpp_connector": params1_ap_connector,
4751              "dpp_csign": params1_csign,
4752              "dpp_netaccesskey": params1_ap_netaccesskey}
4753    try:
4754        hapd = hostapd.add_ap(apdev[0], params)
4755    except:
4756        raise HwsimSkip("DPP not supported")
4757
4758    tests = ["dpp_derive_pmk",
4759             "dpp_hkdf_expand;dpp_derive_pmk",
4760             "dpp_derive_pmkid"]
4761    for func in tests:
4762        with fail_test(dev[0], 1, func):
4763            dev[0].connect("dpp", key_mgmt="DPP", scan_freq="2412",
4764                           ieee80211w="2",
4765                           dpp_csign=params1_csign,
4766                           dpp_connector=params1_sta_connector,
4767                           dpp_netaccesskey=params1_sta_netaccesskey,
4768                           wait_connect=False)
4769            ev = dev[0].wait_event(["DPP-INTRO"], timeout=10)
4770            if ev is None or "fail=peer_connector_validation_failed" not in ev:
4771                raise Exception("Introduction failure not reported")
4772            dev[0].request("REMOVE_NETWORK all")
4773            dev[0].dump_monitor()
4774
4775    tests = [(1, "base64_gen_decode;dpp_peer_intro"),
4776             (1, "json_parse;dpp_peer_intro"),
4777             (50, "json_parse;dpp_peer_intro"),
4778             (1, "=dpp_check_signed_connector;dpp_peer_intro"),
4779             (1, "dpp_parse_jwk")]
4780    for count, func in tests:
4781        with alloc_fail(dev[0], count, func):
4782            dev[0].connect("dpp", key_mgmt="DPP", scan_freq="2412",
4783                           ieee80211w="2",
4784                           dpp_csign=params1_csign,
4785                           dpp_connector=params1_sta_connector,
4786                           dpp_netaccesskey=params1_sta_netaccesskey,
4787                           wait_connect=False)
4788            ev = dev[0].wait_event(["DPP-INTRO"], timeout=10)
4789            if ev is None or "fail=peer_connector_validation_failed" not in ev:
4790                raise Exception("Introduction failure not reported")
4791            dev[0].request("REMOVE_NETWORK all")
4792            dev[0].dump_monitor()
4793
4794    parts = params1_ap_connector.split('.')
4795    for ap_connector in ['.'.join(parts[0:2]), '.'.join(parts[0:1])]:
4796        hapd.set("dpp_connector", ap_connector)
4797        dev[0].connect("dpp", key_mgmt="DPP", scan_freq="2412",
4798                       ieee80211w="2",
4799                       dpp_csign=params1_csign,
4800                       dpp_connector=params1_sta_connector,
4801                       dpp_netaccesskey=params1_sta_netaccesskey,
4802                       wait_connect=False)
4803        ev = dev[0].wait_event(["DPP-TX-STATUS"], timeout=10)
4804        if ev is None:
4805            raise Exception("No TX status reported")
4806        dev[0].request("REMOVE_NETWORK all")
4807        dev[0].dump_monitor()
4808
4809    hapd.set("dpp_netaccesskey", "00")
4810    dev[0].connect("dpp", key_mgmt="DPP", scan_freq="2412",
4811                   ieee80211w="2",
4812                   dpp_csign=params1_csign,
4813                   dpp_connector=params1_sta_connector,
4814                   dpp_netaccesskey=params1_sta_netaccesskey,
4815                   wait_connect=False)
4816    ev = dev[0].wait_event(["DPP-TX-STATUS"], timeout=10)
4817    if ev is None:
4818        raise Exception("No TX status reported")
4819    dev[0].request("REMOVE_NETWORK all")
4820    dev[0].dump_monitor()
4821
4822    hapd.set("dpp_csign", "00")
4823    dev[0].connect("dpp", key_mgmt="DPP", scan_freq="2412",
4824                   ieee80211w="2",
4825                   dpp_csign=params1_csign,
4826                   dpp_connector=params1_sta_connector,
4827                   dpp_netaccesskey=params1_sta_netaccesskey,
4828                   wait_connect=False)
4829    ev = dev[0].wait_event(["DPP-TX-STATUS"], timeout=10)
4830    if ev is None:
4831        raise Exception("No TX status reported")
4832    dev[0].request("REMOVE_NETWORK all")
4833
4834def run_dpp_configurator_id_unknown(dev):
4835    check_dpp_capab(dev)
4836    conf_id = dev.dpp_configurator_add()
4837    if "FAIL" not in dev.request("DPP_CONFIGURATOR_GET_KEY %d" % (conf_id + 1)):
4838        raise Exception("DPP_CONFIGURATOR_GET_KEY with incorrect id accepted")
4839
4840    cmd = "DPP_CONFIGURATOR_SIGN  conf=sta-dpp configurator=%d" % (conf_id + 1)
4841    if "FAIL" not in dev.request(cmd):
4842        raise Exception("DPP_CONFIGURATOR_SIGN with incorrect id accepted")
4843
4844def test_dpp_configurator_id_unknown(dev, apdev):
4845    """DPP and unknown configurator id"""
4846    run_dpp_configurator_id_unknown(dev[0])
4847    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured"})
4848    run_dpp_configurator_id_unknown(hapd)
4849
4850def run_dpp_bootstrap_gen_failures(dev):
4851    check_dpp_capab(dev)
4852
4853    tests = ["type=unsupported",
4854             "type=qrcode chan=-1",
4855             "type=qrcode mac=a",
4856             "type=qrcode key=qq",
4857             "type=qrcode key=",
4858             "type=qrcode info=abc\tdef"]
4859    for t in tests:
4860        if "FAIL" not in dev.request("DPP_BOOTSTRAP_GEN " + t):
4861            raise Exception("Command accepted unexpectedly")
4862
4863    id = dev.dpp_bootstrap_gen()
4864    uri = dev.request("DPP_BOOTSTRAP_GET_URI %d" % id)
4865    if not uri.startswith("DPP:"):
4866        raise Exception("Could not get URI")
4867    if "FAIL" not in dev.request("DPP_BOOTSTRAP_GET_URI 0"):
4868        raise Exception("Failure not reported")
4869    info = dev.request("DPP_BOOTSTRAP_INFO %d" % id)
4870    if not info.startswith("type=QRCODE"):
4871        raise Exception("Could not get info")
4872    if "FAIL" not in dev.request("DPP_BOOTSTRAP_REMOVE 0"):
4873        raise Exception("Failure not reported")
4874    if "FAIL" in dev.request("DPP_BOOTSTRAP_REMOVE *"):
4875        raise Exception("Failed to remove bootstrap info")
4876    if "FAIL" not in dev.request("DPP_BOOTSTRAP_GET_URI %d" % id):
4877        raise Exception("Failure not reported")
4878    if "FAIL" not in dev.request("DPP_BOOTSTRAP_INFO %d" % id):
4879        raise Exception("Failure not reported")
4880
4881    func = "dpp_bootstrap_gen"
4882    with alloc_fail(dev, 1, "=" + func):
4883        if "FAIL" not in dev.request("DPP_BOOTSTRAP_GEN type=qrcode"):
4884            raise Exception("Command accepted unexpectedly")
4885
4886    with alloc_fail(dev, 1, "dpp_gen_uri;dpp_bootstrap_gen"):
4887        if "FAIL" not in dev.request("DPP_BOOTSTRAP_GEN type=qrcode"):
4888            raise Exception("Command accepted unexpectedly")
4889
4890    with alloc_fail(dev, 1, "get_param"):
4891        dev.request("DPP_BOOTSTRAP_GEN type=qrcode curve=foo")
4892
4893def test_dpp_bootstrap_gen_failures(dev, apdev):
4894    """DPP_BOOTSTRAP_GEN/REMOVE/GET_URI/INFO error cases"""
4895    run_dpp_bootstrap_gen_failures(dev[0])
4896    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured"})
4897    run_dpp_bootstrap_gen_failures(hapd)
4898
4899def test_dpp_listen_continue(dev, apdev):
4900    """DPP and continue listen state"""
4901    check_dpp_capab(dev[0])
4902    check_dpp_capab(dev[1])
4903    id = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
4904    uri = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id)
4905    dev[0].dpp_listen(2412)
4906    time.sleep(5.1)
4907    dev[1].dpp_auth_init(uri=uri)
4908    wait_auth_success(dev[0], dev[1], configurator=dev[1], enrollee=dev[0],
4909                      allow_enrollee_failure=True, stop_responder=True,
4910                      stop_initiator=True)
4911
4912def test_dpp_network_addition_failure(dev, apdev):
4913    """DPP network addition failure"""
4914    try:
4915        run_dpp_network_addition_failure(dev, apdev)
4916    finally:
4917        dev[0].set("dpp_config_processing", "0", allow_fail=True)
4918
4919def run_dpp_network_addition_failure(dev, apdev):
4920    check_dpp_capab(dev[0])
4921    conf_id = dev[0].dpp_configurator_add()
4922    dev[0].set("dpp_config_processing", "1")
4923    cmd = "DPP_CONFIGURATOR_SIGN  conf=sta-dpp configurator=%d" % conf_id
4924    tests = [(1, "=wpas_dpp_add_network"),
4925             (2, "=wpas_dpp_add_network"),
4926             (3, "=wpas_dpp_add_network"),
4927             (4, "=wpas_dpp_add_network"),
4928             (1, "wpa_config_add_network;wpas_dpp_add_network")]
4929    for count, func in tests:
4930        with alloc_fail(dev[0], count, func):
4931            res = dev[0].request(cmd)
4932            if "OK" in res:
4933                ev = dev[0].wait_event(["DPP-NET-ACCESS-KEY"], timeout=2)
4934                if ev is None:
4935                    raise Exception("Config object not processed")
4936            wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4937        dev[0].dump_monitor()
4938
4939    cmd = "DPP_CONFIGURATOR_SIGN  conf=sta-psk pass=%s configurator=%d" % (binascii.hexlify(b"passphrase").decode(), conf_id)
4940    tests = [(1, "wpa_config_set_quoted;wpas_dpp_add_network")]
4941    for count, func in tests:
4942        with alloc_fail(dev[0], count, func):
4943            res = dev[0].request(cmd)
4944            if "OK" in res:
4945                ev = dev[0].wait_event(["DPP-NET-ACCESS-KEY"], timeout=2)
4946                if ev is None:
4947                    raise Exception("Config object not processed")
4948            wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
4949        dev[0].dump_monitor()
4950
4951def test_dpp_two_initiators(dev, apdev):
4952    """DPP and two initiators"""
4953    check_dpp_capab(dev[0])
4954    check_dpp_capab(dev[1])
4955    check_dpp_capab(dev[2])
4956    id = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
4957    uri = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id)
4958    dev[0].dpp_listen(2412)
4959    dev[1].dpp_auth_init(uri=uri)
4960    ev = dev[0].wait_event(["DPP-RX"], timeout=5)
4961    if ev is None:
4962        raise Exeption("No DPP Authentication Request seen")
4963    dev[2].dpp_auth_init(uri=uri)
4964    wait_dpp_fail(dev[0],
4965                  "DPP-FAIL Already in DPP authentication exchange - ignore new one")
4966
4967    ev = dev[0].wait_event(["DPP-CONF-FAILED"], timeout=2)
4968    if ev is None:
4969        raise Exception("DPP configuration result not seen (Enrollee)")
4970    ev = dev[1].wait_event(["DPP-CONF-SENT"], timeout=2)
4971    if ev is None:
4972        raise Exception("DPP configuration result not seen (Responder)")
4973
4974    dev[0].request("DPP_STOP_LISTEN")
4975    dev[1].request("DPP_STOP_LISTEN")
4976    dev[2].request("DPP_STOP_LISTEN")
4977
4978def test_dpp_conf_file_update(dev, apdev, params):
4979    """DPP provisioning updating wpa_supplicant configuration file"""
4980    config = os.path.join(params['logdir'], 'dpp_conf_file_update.conf')
4981    with open(config, "w") as f:
4982        f.write("update_config=1\n")
4983    wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
4984    wpas.interface_add("wlan5", config=config)
4985    check_dpp_capab(wpas)
4986    wpas.set("dpp_config_processing", "1")
4987    run_dpp_qr_code_auth_unicast([wpas, dev[1]], apdev, None,
4988                                 init_extra="conf=sta-dpp",
4989                                 require_conf_success=True,
4990                                 configurator=True)
4991    wpas.interface_remove("wlan5")
4992
4993    with open(config, "r") as f:
4994        res = f.read()
4995    for i in ["network={", "dpp_connector=", "key_mgmt=DPP", "ieee80211w=2",
4996              "dpp_netaccesskey=", "dpp_csign="]:
4997        if i not in res:
4998            raise Exception("Configuration file missing '%s'" % i)
4999
5000    wpas.interface_add("wlan5", config=config)
5001    if len(wpas.list_networks()) != 1:
5002        raise Exception("Unexpected number of networks")
5003
5004def test_dpp_duplicated_auth_resp(dev, apdev):
5005    """DPP and duplicated Authentication Response"""
5006    check_dpp_capab(dev[0])
5007    check_dpp_capab(dev[1])
5008    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
5009    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
5010    dev[0].set("ext_mgmt_frame_handling", "1")
5011    dev[1].set("ext_mgmt_frame_handling", "1")
5012    dev[0].dpp_listen(2412)
5013    dev[1].dpp_auth_init(uri=uri0)
5014
5015    # DPP Authentication Request
5016    rx_process_frame(dev[0])
5017
5018    # DPP Authentication Response
5019    msg = rx_process_frame(dev[1])
5020    frame = binascii.hexlify(msg['frame']).decode()
5021    # Duplicated frame
5022    if "OK" not in dev[1].request("MGMT_RX_PROCESS freq={} datarate={} ssi_signal={} frame={}".format(msg['freq'], msg['datarate'], msg['ssi_signal'], frame)):
5023        raise Exception("MGMT_RX_PROCESS failed")
5024    # Modified frame - nonzero status
5025    if frame[2*32:2*37] != "0010010000":
5026        raise Exception("Could not find Status attribute")
5027    frame2 = frame[0:2*32] + "0010010001" + frame[2*37:]
5028    if "OK" not in dev[1].request("MGMT_RX_PROCESS freq={} datarate={} ssi_signal={} frame={}".format(msg['freq'], msg['datarate'], msg['ssi_signal'], frame2)):
5029        raise Exception("MGMT_RX_PROCESS failed")
5030    frame2 = frame[0:2*32] + "00100100ff" + frame[2*37:]
5031    if "OK" not in dev[1].request("MGMT_RX_PROCESS freq={} datarate={} ssi_signal={} frame={}".format(msg['freq'], msg['datarate'], msg['ssi_signal'], frame2)):
5032        raise Exception("MGMT_RX_PROCESS failed")
5033
5034    # DPP Authentication Confirmation
5035    rx_process_frame(dev[0])
5036
5037    wait_auth_success(dev[0], dev[1])
5038
5039    # DPP Configuration Request
5040    rx_process_frame(dev[1])
5041
5042    # DPP Configuration Response
5043    rx_process_frame(dev[0])
5044
5045    wait_conf_completion(dev[1], dev[0])
5046
5047def test_dpp_duplicated_auth_conf(dev, apdev):
5048    """DPP and duplicated Authentication Confirmation"""
5049    check_dpp_capab(dev[0])
5050    check_dpp_capab(dev[1])
5051    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
5052    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
5053    dev[0].set("ext_mgmt_frame_handling", "1")
5054    dev[1].set("ext_mgmt_frame_handling", "1")
5055    dev[0].dpp_listen(2412)
5056    dev[1].dpp_auth_init(uri=uri0)
5057
5058    # DPP Authentication Request
5059    rx_process_frame(dev[0])
5060
5061    # DPP Authentication Response
5062    rx_process_frame(dev[1])
5063
5064    # DPP Authentication Confirmation
5065    msg = rx_process_frame(dev[0])
5066    # Duplicated frame
5067    if "OK" not in dev[0].request("MGMT_RX_PROCESS freq={} datarate={} ssi_signal={} frame={}".format(msg['freq'], msg['datarate'], msg['ssi_signal'], binascii.hexlify(msg['frame']).decode())):
5068        raise Exception("MGMT_RX_PROCESS failed")
5069
5070    wait_auth_success(dev[0], dev[1])
5071
5072    # DPP Configuration Request
5073    rx_process_frame(dev[1])
5074
5075    # DPP Configuration Response
5076    rx_process_frame(dev[0])
5077
5078    wait_conf_completion(dev[1], dev[0])
5079
5080def test_dpp_enrollee_reject_config(dev, apdev):
5081    """DPP and Enrollee rejecting Config Object"""
5082    check_dpp_capab(dev[0])
5083    check_dpp_capab(dev[1])
5084    dev[0].set("dpp_test", "91")
5085    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
5086    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
5087    dev[0].dpp_listen(2412)
5088    dev[1].dpp_auth_init(uri=uri0, conf="sta-sae", ssid="dpp-legacy",
5089                         passphrase="secret passphrase")
5090    wait_auth_success(dev[0], dev[1], configurator=dev[1], enrollee=dev[0],
5091                      allow_enrollee_failure=True,
5092                      allow_configurator_failure=True)
5093
5094def test_dpp_enrollee_ap_reject_config(dev, apdev):
5095    """DPP and Enrollee AP rejecting Config Object"""
5096    check_dpp_capab(dev[0])
5097    check_dpp_capab(dev[1])
5098    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured"})
5099    check_dpp_capab(hapd)
5100    hapd.set("dpp_test", "91")
5101    conf_id = dev[0].dpp_configurator_add()
5102    id_h = hapd.dpp_bootstrap_gen(chan="81/1", mac=True)
5103    uri = hapd.request("DPP_BOOTSTRAP_GET_URI %d" % id_h)
5104    dev[0].dpp_auth_init(uri=uri, conf="ap-dpp", configurator=conf_id)
5105    wait_auth_success(hapd, dev[0], configurator=dev[0], enrollee=hapd,
5106                      allow_enrollee_failure=True,
5107                      allow_configurator_failure=True)
5108
5109def test_dpp_legacy_and_dpp_akm(dev, apdev):
5110    """DPP and provisoning DPP and legacy AKMs"""
5111    try:
5112        run_dpp_legacy_and_dpp_akm(dev, apdev)
5113    finally:
5114        dev[0].set("dpp_config_processing", "0", allow_fail=True)
5115
5116def run_dpp_legacy_and_dpp_akm(dev, apdev):
5117    check_dpp_capab(dev[0], min_ver=2)
5118    check_dpp_capab(dev[1], min_ver=2)
5119
5120    csign = "30770201010420768240a3fc89d6662d9782f120527fe7fb9edc6366ab0b9c7dde96125cfd250fa00a06082a8648ce3d030107a144034200042908e1baf7bf413cc66f9e878a03e8bb1835ba94b033dbe3d6969fc8575d5eb5dfda1cb81c95cee21d0cd7d92ba30541ffa05cb6296f5dd808b0c1c2a83c0708"
5121    csign_pub = "3059301306072a8648ce3d020106082a8648ce3d030107034200042908e1baf7bf413cc66f9e878a03e8bb1835ba94b033dbe3d6969fc8575d5eb5dfda1cb81c95cee21d0cd7d92ba30541ffa05cb6296f5dd808b0c1c2a83c0708"
5122    ap_connector = "eyJ0eXAiOiJkcHBDb24iLCJraWQiOiJwYWtZbXVzd1dCdWpSYTl5OEsweDViaTVrT3VNT3dzZHRlaml2UG55ZHZzIiwiYWxnIjoiRVMyNTYifQ.eyJncm91cHMiOlt7Imdyb3VwSWQiOiIqIiwibmV0Um9sZSI6ImFwIn1dLCJuZXRBY2Nlc3NLZXkiOnsia3R5IjoiRUMiLCJjcnYiOiJQLTI1NiIsIngiOiIybU5vNXZuRkI5bEw3d1VWb1hJbGVPYzBNSEE1QXZKbnpwZXZULVVTYzVNIiwieSI6IlhzS3dqVHJlLTg5WWdpU3pKaG9CN1haeUttTU05OTl3V2ZaSVl0bi01Q3MifX0.XhjFpZgcSa7G2lHy0OCYTvaZFRo5Hyx6b7g7oYyusLC7C_73AJ4_BxEZQVYJXAtDuGvb3dXSkHEKxREP9Q6Qeg"
5123    ap_netaccesskey = "30770201010420ceba752db2ad5200fa7bc565b9c05c69b7eb006751b0b329b0279de1c19ca67ca00a06082a8648ce3d030107a14403420004da6368e6f9c507d94bef0515a1722578e73430703902f267ce97af4fe51273935ec2b08d3adefbcf588224b3261a01ed76722a630cf7df7059f64862d9fee42b"
5124
5125    ssid = "dpp-both"
5126    passphrase = "secret passphrase"
5127    params = {"ssid": ssid,
5128              "wpa": "2",
5129              "wpa_key_mgmt": "DPP WPA-PSK SAE",
5130              "ieee80211w": "1",
5131              "sae_require_mfp": '1',
5132              "rsn_pairwise": "CCMP",
5133              "wpa_passphrase": passphrase,
5134              "dpp_connector": ap_connector,
5135              "dpp_csign": csign_pub,
5136              "dpp_netaccesskey": ap_netaccesskey}
5137    try:
5138        hapd = hostapd.add_ap(apdev[0], params)
5139    except:
5140        raise HwsimSkip("DPP not supported")
5141
5142    dev[0].request("SET sae_groups ")
5143    conf_id = dev[1].dpp_configurator_add(key=csign)
5144    dev[0].set("dpp_config_processing", "1")
5145    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
5146    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
5147    dev[0].dpp_listen(2412)
5148    dev[1].dpp_auth_init(uri=uri0, conf="sta-psk-sae-dpp", ssid=ssid,
5149                         passphrase=passphrase, configurator=conf_id)
5150    wait_auth_success(dev[0], dev[1], configurator=dev[1], enrollee=dev[0],
5151                      allow_enrollee_failure=True,
5152                      allow_configurator_failure=True)
5153    ev = dev[0].wait_event(["DPP-NETWORK-ID"], timeout=1)
5154    if ev is None:
5155        raise Exception("DPP network profile not generated")
5156    id0 = ev.split(' ')[1]
5157
5158    key_mgmt = dev[0].get_network(id0, "key_mgmt").split(' ')
5159    for m in ["SAE", "WPA-PSK", "DPP"]:
5160        if m not in key_mgmt:
5161            raise Exception("%s missing from key_mgmt" % m)
5162
5163    dev[0].scan_for_bss(hapd.own_addr(), freq=2412)
5164    dev[0].select_network(id0, freq=2412)
5165    dev[0].wait_connected()
5166
5167    dev[0].request("DISCONNECT")
5168    dev[0].wait_disconnected()
5169    hapd.disable()
5170
5171    params = {"ssid": ssid,
5172              "wpa": "2",
5173              "wpa_key_mgmt": "WPA-PSK SAE",
5174              "ieee80211w": "1",
5175              "sae_require_mfp": '1',
5176              "rsn_pairwise": "CCMP",
5177              "wpa_passphrase": passphrase}
5178    hapd2 = hostapd.add_ap(apdev[1], params)
5179
5180    dev[0].request("BSS_FLUSH 0")
5181    dev[0].scan_for_bss(hapd2.own_addr(), freq=2412, force_scan=True,
5182                        only_new=True)
5183    dev[0].select_network(id0, freq=2412)
5184    dev[0].wait_connected()
5185
5186    dev[0].request("DISCONNECT")
5187    dev[0].wait_disconnected()
5188
5189def test_dpp_controller_relay(dev, apdev, params):
5190    """DPP Controller/Relay"""
5191    try:
5192        run_dpp_controller_relay(dev, apdev, params)
5193    finally:
5194        dev[0].set("dpp_config_processing", "0", allow_fail=True)
5195        dev[1].request("DPP_CONTROLLER_STOP")
5196
5197def test_dpp_controller_relay_chirp(dev, apdev, params):
5198    """DPP Controller/Relay with chirping"""
5199    try:
5200        run_dpp_controller_relay(dev, apdev, params, chirp=True)
5201    finally:
5202        dev[0].set("dpp_config_processing", "0", allow_fail=True)
5203        dev[1].request("DPP_CONTROLLER_STOP")
5204
5205def run_dpp_controller_relay(dev, apdev, params, chirp=False):
5206    check_dpp_capab(dev[0], min_ver=2)
5207    check_dpp_capab(dev[1], min_ver=2)
5208    prefix = "dpp_controller_relay"
5209    if chirp:
5210        prefix += "_chirp"
5211    cap_lo = os.path.join(params['logdir'], prefix + ".lo.pcap")
5212
5213    wt = WlantestCapture('lo', cap_lo)
5214
5215    # Controller
5216    conf_id = dev[1].dpp_configurator_add()
5217    dev[1].set("dpp_configurator_params",
5218               "conf=sta-dpp configurator=%d" % conf_id)
5219    id_c = dev[1].dpp_bootstrap_gen()
5220    uri_c = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id_c)
5221    res = dev[1].request("DPP_BOOTSTRAP_INFO %d" % id_c)
5222    pkhash = None
5223    for line in res.splitlines():
5224        name, value = line.split('=')
5225        if name == "pkhash":
5226            pkhash = value
5227            break
5228    if not pkhash:
5229        raise Exception("Could not fetch public key hash from Controller")
5230    if "OK" not in dev[1].request("DPP_CONTROLLER_START"):
5231        raise Exception("Failed to start Controller")
5232
5233    # Relay
5234    params = {"ssid": "unconfigured",
5235              "channel": "6",
5236              "dpp_controller": "ipaddr=127.0.0.1 pkhash=" + pkhash}
5237    if chirp:
5238        params["channel"] = "11"
5239        params["dpp_configurator_connectivity"] = "1"
5240    relay = hostapd.add_ap(apdev[1], params)
5241    check_dpp_capab(relay)
5242
5243    # Enroll Relay to the network
5244    # TODO: Do this over TCP once direct Enrollee-over-TCP case is supported
5245    if chirp:
5246        id_h = relay.dpp_bootstrap_gen(chan="81/11", mac=True)
5247    else:
5248        id_h = relay.dpp_bootstrap_gen(chan="81/6", mac=True)
5249    uri_r = relay.request("DPP_BOOTSTRAP_GET_URI %d" % id_h)
5250    dev[1].dpp_auth_init(uri=uri_r, conf="ap-dpp", configurator=conf_id)
5251    wait_auth_success(relay, dev[1], configurator=dev[1], enrollee=relay)
5252    update_hapd_config(relay)
5253
5254    # Initiate from Enrollee with broadcast DPP Authentication Request or
5255    # using chirping
5256    dev[0].set("dpp_config_processing", "2")
5257    if chirp:
5258        id1 = dev[0].dpp_bootstrap_gen()
5259        uri = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id1)
5260        idc = dev[1].dpp_qr_code(uri)
5261        dev[1].dpp_bootstrap_set(idc, conf="sta-dpp", configurator=conf_id)
5262        if "OK" not in dev[0].request("DPP_CHIRP own=%d iter=5" % id1):
5263            raise Exception("DPP_CHIRP failed")
5264        ev = relay.wait_event(["DPP-RX"], timeout=10)
5265        if ev is None:
5266            raise Exception("Presence Announcement not seen")
5267        if "type=13" not in ev:
5268            raise Exception("Unexpected DPP frame received: " + ev)
5269    else:
5270        dev[0].dpp_auth_init(uri=uri_c, role="enrollee")
5271    wait_auth_success(dev[1], dev[0], configurator=dev[1], enrollee=dev[0],
5272                      allow_enrollee_failure=True,
5273                      allow_configurator_failure=True)
5274    ev = dev[0].wait_event(["DPP-NETWORK-ID"], timeout=1)
5275    if ev is None:
5276        raise Exception("DPP network id not reported")
5277    network = int(ev.split(' ')[1])
5278    dev[0].wait_connected()
5279    dev[0].dump_monitor()
5280    dev[0].request("DISCONNECT")
5281    dev[0].wait_disconnected()
5282    dev[0].dump_monitor()
5283
5284    if "OK" not in dev[0].request("DPP_RECONFIG %s" % network):
5285        raise Exception("Failed to start reconfiguration")
5286    ev = dev[0].wait_event(["DPP-NETWORK-ID"], timeout=15)
5287    if ev is None:
5288        raise Exception("DPP network id not reported for reconfiguration")
5289    network2 = int(ev.split(' ')[1])
5290    if network == network2:
5291        raise Exception("Network ID did not change")
5292    dev[0].wait_connected()
5293
5294    time.sleep(0.5)
5295    wt.close()
5296
5297class MyTCPServer(TCPServer):
5298    def __init__(self, addr, handler):
5299        self.allow_reuse_address = True
5300        TCPServer.__init__(self, addr, handler)
5301
5302class DPPControllerServer(StreamRequestHandler):
5303        def handle(self):
5304            data = self.rfile.read()
5305            # Do not reply
5306
5307def test_dpp_relay_incomplete_connections(dev, apdev):
5308    """DPP Relay and incomplete connections"""
5309    check_dpp_capab(dev[0], min_ver=2)
5310    check_dpp_capab(dev[1], min_ver=2)
5311
5312    id_c = dev[1].dpp_bootstrap_gen()
5313    uri_c = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id_c)
5314    res = dev[1].request("DPP_BOOTSTRAP_INFO %d" % id_c)
5315    pkhash = None
5316    for line in res.splitlines():
5317        name, value = line.split('=')
5318        if name == "pkhash":
5319            pkhash = value
5320            break
5321    if not pkhash:
5322        raise Exception("Could not fetch public key hash from Controller")
5323
5324    params = {"ssid": "unconfigured",
5325              "channel": "6",
5326              "dpp_controller": "ipaddr=127.0.0.1 pkhash=" + pkhash}
5327    hapd = hostapd.add_ap(apdev[0], params)
5328    check_dpp_capab(hapd)
5329
5330    server = MyTCPServer(("127.0.0.1", 8908), DPPControllerServer)
5331    server.timeout = 30
5332
5333    hapd.set("ext_mgmt_frame_handling", "1")
5334    dev[0].dpp_auth_init(uri=uri_c, role="enrollee")
5335    msg = hapd.mgmt_rx()
5336    if msg is None:
5337        raise Exception("MGMT RX wait timed out")
5338    dev[0].request("DPP_STOP_LISTEN")
5339    frame = msg['frame']
5340    for i in range(20):
5341        if i == 14:
5342            time.sleep(20)
5343        addr = struct.pack('6B', 0x02, 0, 0, 0, 0, i)
5344        tmp = frame[0:10] + addr + frame[16:]
5345        hapd.request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=" + binascii.hexlify(tmp).decode())
5346        ev = hapd.wait_event(["DPP-FAIL"], timeout=0.1)
5347        if ev:
5348            raise Exception("DPP relay failed [%d]: %s" % (i + 1, ev))
5349
5350    server.server_close()
5351
5352def test_dpp_tcp(dev, apdev, params):
5353    """DPP over TCP"""
5354    prefix = "dpp_tcp"
5355    cap_lo = os.path.join(params['logdir'], prefix + ".lo.pcap")
5356    try:
5357        run_dpp_tcp(dev[0], dev[1], cap_lo)
5358    finally:
5359        dev[1].request("DPP_CONTROLLER_STOP")
5360
5361def test_dpp_tcp_port(dev, apdev, params):
5362    """DPP over TCP and specified port"""
5363    prefix = "dpp_tcp_port"
5364    cap_lo = os.path.join(params['logdir'], prefix + ".lo.pcap")
5365    try:
5366        run_dpp_tcp(dev[0], dev[1], cap_lo, port="23456")
5367    finally:
5368        dev[1].request("DPP_CONTROLLER_STOP")
5369
5370def test_dpp_tcp_mutual(dev, apdev, params):
5371    """DPP over TCP (mutual)"""
5372    cap_lo = os.path.join(params['prefix'], ".lo.pcap")
5373    try:
5374        run_dpp_tcp(dev[0], dev[1], cap_lo, mutual=True)
5375    finally:
5376        dev[1].request("DPP_CONTROLLER_STOP")
5377
5378def test_dpp_tcp_mutual_hostapd_conf(dev, apdev, params):
5379    """DPP over TCP (mutual, hostapd as Configurator)"""
5380    cap_lo = os.path.join(params['prefix'], ".lo.pcap")
5381    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured"})
5382    run_dpp_tcp(dev[0], hapd, cap_lo, mutual=True)
5383
5384def run_dpp_tcp(dev0, dev1, cap_lo, port=None, mutual=False):
5385    check_dpp_capab(dev0)
5386    check_dpp_capab(dev1)
5387
5388    wt = WlantestCapture('lo', cap_lo)
5389    time.sleep(1)
5390
5391    # Controller
5392    conf_id = dev1.dpp_configurator_add()
5393    dev1.set("dpp_configurator_params",
5394             " conf=sta-dpp configurator=%d" % conf_id)
5395    id_c = dev1.dpp_bootstrap_gen()
5396    uri_c = dev1.request("DPP_BOOTSTRAP_GET_URI %d" % id_c)
5397    res = dev1.request("DPP_BOOTSTRAP_INFO %d" % id_c)
5398    pkhash = None
5399    for line in res.splitlines():
5400        name, value = line.split('=')
5401        if name == "pkhash":
5402            pkhash = value
5403            break
5404    if not pkhash:
5405        raise Exception("Could not fetch public key hash from Controller")
5406    req = "DPP_CONTROLLER_START"
5407    if port:
5408        req += " tcp_port=" + port
5409    if mutual:
5410        req += " qr=mutual"
5411        id0 = dev0.dpp_bootstrap_gen()
5412        uri0 = dev0.request("DPP_BOOTSTRAP_GET_URI %d" % id0)
5413        own = id0
5414    else:
5415        own = None
5416    if "OK" not in dev1.request(req):
5417        raise Exception("Failed to start Controller")
5418
5419    # Initiate from Enrollee with broadcast DPP Authentication Request
5420    dev0.dpp_auth_init(uri=uri_c, own=own, role="enrollee",
5421                       tcp_addr="127.0.0.1", tcp_port=port)
5422
5423    if mutual:
5424        ev = dev0.wait_event(["DPP-RESPONSE-PENDING"], timeout=5)
5425        if ev is None:
5426            raise Exception("Pending response not reported")
5427        ev = dev1.wait_event(["DPP-SCAN-PEER-QR-CODE"], timeout=5)
5428        if ev is None:
5429            raise Exception("QR Code scan for mutual authentication not requested")
5430
5431        id1 = dev1.dpp_qr_code(uri0)
5432
5433        ev = dev0.wait_event(["DPP-AUTH-DIRECTION"], timeout=5)
5434        if ev is None:
5435            raise Exception("DPP authentication direction not indicated (Initiator)")
5436        if "mutual=1" not in ev:
5437            raise Exception("Mutual authentication not used")
5438
5439    wait_auth_success(dev1, dev0, configurator=dev1, enrollee=dev0,
5440                      allow_enrollee_failure=True,
5441                      allow_configurator_failure=True)
5442    time.sleep(0.5)
5443    wt.close()
5444
5445def test_dpp_tcp_conf_init(dev, apdev, params):
5446    """DPP over TCP (Configurator initiates)"""
5447    cap_lo = os.path.join(params['prefix'], ".lo.pcap")
5448    try:
5449        run_dpp_tcp_conf_init(dev[0], dev[1], cap_lo)
5450    finally:
5451        dev[1].request("DPP_CONTROLLER_STOP")
5452
5453def test_dpp_tcp_conf_init_hostapd_enrollee(dev, apdev, params):
5454    """DPP over TCP (Configurator initiates, hostapd as Enrollee)"""
5455    cap_lo = os.path.join(params['prefix'], ".lo.pcap")
5456    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured"})
5457    run_dpp_tcp_conf_init(dev[0], hapd, cap_lo, conf="ap-dpp")
5458
5459def run_dpp_tcp_conf_init(dev0, dev1, cap_lo, port=None, conf="sta-dpp"):
5460    check_dpp_capab(dev0, min_ver=2)
5461    check_dpp_capab(dev1, min_ver=2)
5462
5463    wt = WlantestCapture('lo', cap_lo)
5464    time.sleep(1)
5465
5466    id_c = dev1.dpp_bootstrap_gen()
5467    uri_c = dev1.request("DPP_BOOTSTRAP_GET_URI %d" % id_c)
5468    res = dev1.request("DPP_BOOTSTRAP_INFO %d" % id_c)
5469    req = "DPP_CONTROLLER_START role=enrollee"
5470    if port:
5471        req += " tcp_port=" + port
5472    if "OK" not in dev1.request(req):
5473        raise Exception("Failed to start Controller")
5474
5475    conf_id = dev0.dpp_configurator_add()
5476    dev0.dpp_auth_init(uri=uri_c, role="configurator", conf=conf,
5477                       configurator=conf_id,
5478                       tcp_addr="127.0.0.1", tcp_port=port)
5479    wait_auth_success(dev1, dev0, configurator=dev0, enrollee=dev1,
5480                      allow_enrollee_failure=True,
5481                      allow_configurator_failure=True)
5482    time.sleep(0.5)
5483    wt.close()
5484
5485def test_dpp_tcp_controller_management_hostapd(dev, apdev, params):
5486    """DPP Controller management in hostapd"""
5487    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured"})
5488    check_dpp_capab(hapd)
5489    conf_id = hapd.dpp_configurator_add()
5490    if "OK" not in hapd.request("DPP_CONTROLLER_START"):
5491        raise Exception("Failed to start Controller")
5492    if "FAIL" not in hapd.request("DPP_CONTROLLER_START"):
5493        raise Exception("DPP_CONTROLLER_START succeeded while already running Controller")
5494    hapd.request("DPP_CONTROLLER_STOP")
5495    hapd.dpp_configurator_remove(conf_id)
5496    if "FAIL" not in hapd.request("DPP_CONFIGURATOR_REMOVE %d" % conf_id):
5497        raise Exception("Removal of unknown Configurator accepted")
5498
5499def test_dpp_tcp_controller_management_hostapd2(dev, apdev, params):
5500    """DPP Controller management in hostapd over interface addition/removal"""
5501    check_dpp_capab(dev[0], min_ver=2)
5502    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured"})
5503    check_dpp_capab(hapd, min_ver=2)
5504    hapd2 = hostapd.add_ap(apdev[1], {"ssid": "unconfigured"})
5505    check_dpp_capab(hapd2, min_ver=2)
5506    id_c = hapd.dpp_bootstrap_gen()
5507    uri_c = hapd.request("DPP_BOOTSTRAP_GET_URI %d" % id_c)
5508    if "OK" not in hapd.request("DPP_CONTROLLER_START role=enrollee"):
5509        raise Exception("Failed to start Controller")
5510
5511    conf_id = dev[0].dpp_configurator_add()
5512    dev[0].dpp_auth_init(uri=uri_c, role="configurator", conf="sta-dpp",
5513                       configurator=conf_id, tcp_addr="127.0.0.1")
5514    ev = dev[0].wait_event(["DPP-AUTH-SUCCESS"], timeout=5)
5515    if ev is None:
5516        raise Exception("DPP Authentication did not succeed")
5517    ev = dev[0].wait_event(["DPP-CONF-SENT"], timeout=5)
5518    if ev is None:
5519        raise Exception("DPP Configuration did not succeed")
5520
5521    hapd_global = hostapd.HostapdGlobal(apdev)
5522    hapd_global.remove(apdev[0]['ifname'])
5523
5524    dev[0].dpp_auth_init(uri=uri_c, role="configurator", conf="sta-dpp",
5525                       configurator=conf_id, tcp_addr="127.0.0.1")
5526    ev = dev[0].wait_event(["DPP-AUTH-SUCCESS"], timeout=5)
5527    if ev is not None:
5528        raise Exception("Unexpected DPP Authentication success")
5529
5530def test_dpp_tcp_controller_start_failure(dev, apdev, params):
5531    """DPP Controller startup failure"""
5532    check_dpp_capab(dev[0])
5533
5534    try:
5535        if "OK" not in dev[0].request("DPP_CONTROLLER_START"):
5536            raise Exception("Could not start Controller")
5537        if "OK" in dev[0].request("DPP_CONTROLLER_START"):
5538            raise Exception("Second Controller start not rejected")
5539    finally:
5540        dev[0].request("DPP_CONTROLLER_STOP")
5541
5542    tests = ["dpp_controller_start",
5543             "eloop_sock_table_add_sock;?eloop_register_sock;dpp_controller_start"]
5544    for func in tests:
5545        with alloc_fail(dev[0], 1, func):
5546            if "FAIL" not in dev[0].request("DPP_CONTROLLER_START"):
5547                raise Exception("Failure not reported during OOM")
5548
5549def test_dpp_tcp_init_failure(dev, apdev, params):
5550    """DPP TCP init failure"""
5551    check_dpp_capab(dev[0])
5552    check_dpp_capab(dev[1])
5553    id_c = dev[1].dpp_bootstrap_gen()
5554    uri_c = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id_c)
5555    peer = dev[0].dpp_qr_code(uri_c)
5556    tests = ["dpp_tcp_init",
5557             "eloop_sock_table_add_sock;?eloop_register_sock;dpp_tcp_init",
5558             "dpp_tcp_encaps"]
5559    cmd = "DPP_AUTH_INIT peer=%d tcp_addr=127.0.0.1" % peer
5560    for func in tests:
5561        with alloc_fail(dev[0], 1, func):
5562            if "FAIL" not in dev[0].request(cmd):
5563                raise Exception("DPP_AUTH_INIT accepted during OOM")
5564
5565def test_dpp_controller_rx_failure(dev, apdev, params):
5566    """DPP Controller RX failure"""
5567    check_dpp_capab(dev[0])
5568    check_dpp_capab(dev[1])
5569    try:
5570        run_dpp_controller_rx_failure(dev, apdev)
5571    finally:
5572        dev[0].request("DPP_CONTROLLER_STOP")
5573
5574def run_dpp_controller_rx_failure(dev, apdev):
5575    if "OK" not in dev[0].request("DPP_CONTROLLER_START"):
5576        raise Exception("Could not start Controller")
5577    id_c = dev[0].dpp_bootstrap_gen()
5578    uri_c = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id_c)
5579    peer = dev[1].dpp_qr_code(uri_c)
5580    tests = ["dpp_controller_tcp_cb",
5581             "eloop_sock_table_add_sock;?eloop_register_sock;dpp_controller_tcp_cb",
5582             "dpp_controller_rx",
5583             "dpp_controller_rx_auth_req",
5584             "wpabuf_alloc;=dpp_tcp_send_msg;dpp_controller_rx_auth_req"]
5585    cmd = "DPP_AUTH_INIT peer=%d tcp_addr=127.0.0.1" % peer
5586    for func in tests:
5587        with alloc_fail(dev[0], 1, func):
5588            if "OK" not in dev[1].request(cmd):
5589                raise Exception("Failed to initiate TCP connection")
5590            wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
5591
5592def test_dpp_controller_rx_errors(dev, apdev, params):
5593    """DPP Controller RX error cases"""
5594    check_dpp_capab(dev[0])
5595    check_dpp_capab(dev[1])
5596    try:
5597        run_dpp_controller_rx_errors(dev, apdev)
5598    finally:
5599        dev[0].request("DPP_CONTROLLER_STOP")
5600
5601def run_dpp_controller_rx_errors(dev, apdev):
5602    if "OK" not in dev[0].request("DPP_CONTROLLER_START"):
5603        raise Exception("Could not start Controller")
5604
5605    addr = ("127.0.0.1", 8908)
5606
5607    tests = [b"abc",
5608             b"abcd",
5609             b"\x00\x00\x00\x00",
5610             b"\x00\x00\x00\x01",
5611             b"\x00\x00\x00\x01\x09",
5612             b"\x00\x00\x00\x07\x09\x50\x6f\x9a\x1a\xff\xff",
5613             b"\x00\x00\x00\x07\x09\x50\x6f\x9a\x1a\x01\xff",
5614             b"\x00\x00\x00\x07\x09\x50\x6f\x9a\x1a\x01\x00",
5615             b"\x00\x00\x00\x08\x09\x50\x6f\x9a\x1a\x01\x00\xff",
5616             b"\x00\x00\x00\x01\x0a",
5617             b"\x00\x00\x00\x04\x0a\xff\xff\xff",
5618             b"\x00\x00\x00\x01\x0b",
5619             b"\x00\x00\x00\x08\x0b\xff\xff\xff\xff\xff\xff\xff",
5620             b"\x00\x00\x00\x08\x0b\xff\x00\x00\xff\xff\xff\xff",
5621             b"\x00\x00\x00\x08\x0b\xff\x00\x00\xff\xff\x6c\x00",
5622             b"\x00\x00\x00\x0a\x0b\xff\x00\x00\xff\xff\x6c\x02\xff\xff",
5623             b"\x00\x00\x00\x10\x0b\xff\x00\x00\xff\xff\x6c\x08\xff\xdd\x05\x50\x6f\x9a\x1a\x01",
5624             b"\x00\x00\x00\x12\x0b\xff\x00\x00\xff\xff\x6c\x08\xff\xdd\x05\x50\x6f\x9a\x1a\x01\x00\x00",
5625             b"\x00\x00\x00\x01\xff",
5626             b"\x00\x00\x00\x01\xff\xee"]
5627    #define WLAN_PA_GAS_INITIAL_REQ 10
5628    #define WLAN_PA_GAS_INITIAL_RESP 11
5629
5630    for t in tests:
5631        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
5632                             socket.IPPROTO_TCP)
5633        sock.settimeout(0.1)
5634        sock.connect(addr)
5635        sock.send(t)
5636        sock.shutdown(1)
5637        try:
5638            sock.recv(10)
5639        except socket.timeout:
5640            pass
5641        sock.close()
5642
5643def test_dpp_conn_status_success(dev, apdev):
5644    """DPP connection status - success"""
5645    try:
5646        run_dpp_conn_status(dev, apdev)
5647    finally:
5648        dev[0].set("dpp_config_processing", "0", allow_fail=True)
5649
5650def test_dpp_conn_status_wrong_passphrase(dev, apdev):
5651    """DPP connection status - wrong passphrase"""
5652    try:
5653        run_dpp_conn_status(dev, apdev, result=2)
5654    finally:
5655        dev[0].set("dpp_config_processing", "0", allow_fail=True)
5656
5657def test_dpp_conn_status_no_ap(dev, apdev):
5658    """DPP connection status - no AP"""
5659    try:
5660        run_dpp_conn_status(dev, apdev, result=10)
5661    finally:
5662        dev[0].set("dpp_config_processing", "0", allow_fail=True)
5663
5664def test_dpp_conn_status_connector_mismatch(dev, apdev):
5665    """DPP connection status - invalid Connector"""
5666    try:
5667        run_dpp_conn_status(dev, apdev, result=8)
5668    finally:
5669        dev[0].set("dpp_config_processing", "0", allow_fail=True)
5670
5671def test_dpp_conn_status_assoc_reject(dev, apdev):
5672    """DPP connection status - association rejection"""
5673    try:
5674        dev[0].request("TEST_ASSOC_IE 30020000")
5675        run_dpp_conn_status(dev, apdev, assoc_reject=True)
5676    finally:
5677        dev[0].set("dpp_config_processing", "0", allow_fail=True)
5678
5679def run_dpp_conn_status(dev, apdev, result=0, assoc_reject=False):
5680    check_dpp_capab(dev[0], min_ver=2)
5681    check_dpp_capab(dev[1], min_ver=2)
5682
5683    if result != 10:
5684        if result == 7 or result == 8:
5685            params = {"ssid": "dpp-status",
5686                      "wpa": "2",
5687                      "wpa_key_mgmt": "DPP",
5688                      "ieee80211w": "2",
5689                      "rsn_pairwise": "CCMP",
5690                      "dpp_connector": params1_ap_connector,
5691                      "dpp_csign": params1_csign,
5692                      "dpp_netaccesskey": params1_ap_netaccesskey}
5693        else:
5694            if result == 2:
5695                passphrase = "wrong passphrase"
5696            else:
5697                passphrase = "secret passphrase"
5698            params = hostapd.wpa2_params(ssid="dpp-status",
5699                                         passphrase=passphrase)
5700        try:
5701            hapd = hostapd.add_ap(apdev[0], params)
5702        except:
5703            raise HwsimSkip("DPP not supported")
5704
5705    dev[0].request("SET sae_groups ")
5706    dev[0].set("dpp_config_processing", "2")
5707    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
5708    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
5709
5710    dev[0].dpp_listen(2412)
5711    if result == 7 or result == 8:
5712        conf = 'sta-dpp'
5713        passphrase = None
5714        configurator = dev[1].dpp_configurator_add()
5715    else:
5716        conf = 'sta-psk'
5717        passphrase = "secret passphrase"
5718        configurator = None
5719    dev[1].dpp_auth_init(uri=uri0, conf=conf, ssid="dpp-status",
5720                         passphrase=passphrase, configurator=configurator,
5721                         conn_status=True)
5722    res = wait_auth_success(dev[0], dev[1], configurator=dev[1],
5723                            enrollee=dev[0])
5724    if 'wait_conn_status' not in res:
5725        raise Exception("Configurator did not request connection status")
5726
5727    if assoc_reject and result == 0:
5728        result = 2
5729    ev = dev[1].wait_event(["DPP-CONN-STATUS-RESULT"], timeout=20)
5730    if ev is None:
5731        raise Exception("No connection status reported")
5732    if "timeout" in ev:
5733        raise Exception("Connection status result timeout")
5734    if "result=%d" % result not in ev:
5735        raise Exception("Unexpected connection status result: " + ev)
5736    if "ssid=dpp-status" not in ev:
5737        raise Exception("SSID not reported")
5738
5739    if result == 0:
5740        dev[0].wait_connected()
5741    if result == 10 and "channel_list=" not in ev:
5742        raise Exception("Channel list not reported for no-AP")
5743
5744def test_dpp_conn_status_success_hostapd_configurator(dev, apdev):
5745    """DPP connection status - success with hostapd as Configurator"""
5746    try:
5747        run_dpp_conn_status_hostapd_configurator(dev, apdev)
5748    finally:
5749        dev[0].set("dpp_config_processing", "0", allow_fail=True)
5750
5751def run_dpp_conn_status_hostapd_configurator(dev, apdev):
5752    check_dpp_capab(dev[0])
5753    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured",
5754                                     "channel": "1"})
5755    check_dpp_capab(hapd)
5756    conf_id = hapd.dpp_configurator_add()
5757
5758    cmd = "DPP_CONFIGURATOR_SIGN conf=ap-dpp configurator=%d" % conf_id
5759    res = hapd.request(cmd)
5760    if "FAIL" in res:
5761        raise Exception("Failed to generate own configuration")
5762    update_hapd_config(hapd)
5763
5764    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
5765    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
5766    id1 = hapd.dpp_qr_code(uri0)
5767    res = hapd.request("DPP_BOOTSTRAP_INFO %d" % id1)
5768    if "FAIL" in res:
5769        raise Exception("DPP_BOOTSTRAP_INFO failed")
5770    if "type=QRCODE" not in res:
5771        raise Exception("DPP_BOOTSTRAP_INFO did not report correct type")
5772    if "mac_addr=" + dev[0].own_addr() not in res:
5773        raise Exception("DPP_BOOTSTRAP_INFO did not report correct mac_addr")
5774    dev[0].set("dpp_config_processing", "2")
5775    dev[0].dpp_listen(2412)
5776    hapd.dpp_auth_init(peer=id1, configurator=conf_id, conf="sta-dpp",
5777                       conn_status=True)
5778    res = wait_auth_success(dev[0], hapd, configurator=hapd, enrollee=dev[0])
5779    if 'wait_conn_status' not in res:
5780        raise Exception("Configurator did not request connection status")
5781    ev = hapd.wait_event(["DPP-CONN-STATUS-RESULT"], timeout=20)
5782    if ev is None:
5783        raise Exception("No connection status reported")
5784    if "result=0" not in ev:
5785        raise Exception("Unexpected connection status: " + ev)
5786
5787def test_dpp_mud_url(dev, apdev):
5788    """DPP MUD URL"""
5789    check_dpp_capab(dev[0])
5790    try:
5791        dev[0].set("dpp_name", "Test Enrollee")
5792        dev[0].set("dpp_mud_url", "https://example.com/mud")
5793        run_dpp_qr_code_auth_unicast(dev, apdev, None)
5794    finally:
5795        dev[0].set("dpp_mud_url", "")
5796        dev[0].set("dpp_name", "Test")
5797
5798def test_dpp_mud_url_hostapd(dev, apdev):
5799    """DPP MUD URL from hostapd"""
5800    check_dpp_capab(dev[0])
5801    check_dpp_capab(dev[1])
5802    params = {"ssid": "unconfigured",
5803              "dpp_name": "AP Enrollee",
5804              "dpp_mud_url": "https://example.com/mud"}
5805    hapd = hostapd.add_ap(apdev[0], params)
5806    check_dpp_capab(hapd)
5807
5808    id_h = hapd.dpp_bootstrap_gen(chan="81/1", mac=True)
5809    uri = hapd.request("DPP_BOOTSTRAP_GET_URI %d" % id_h)
5810
5811    conf_id = dev[0].dpp_configurator_add()
5812    dev[0].dpp_auth_init(uri=uri, conf="ap-dpp", configurator=conf_id)
5813    wait_auth_success(hapd, dev[0], configurator=dev[0], enrollee=hapd)
5814    update_hapd_config(hapd)
5815
5816def test_dpp_config_save(dev, apdev, params):
5817    """DPP configuration saving"""
5818    config = os.path.join(params['logdir'], 'dpp_config_save.conf')
5819    run_dpp_config_save(dev, apdev, config, "test", '"test"')
5820
5821def test_dpp_config_save2(dev, apdev, params):
5822    """DPP configuration saving (2)"""
5823    config = os.path.join(params['logdir'], 'dpp_config_save2.conf')
5824    run_dpp_config_save(dev, apdev, config, "\\u0001*", '012a')
5825
5826def test_dpp_config_save3(dev, apdev, params):
5827    """DPP configuration saving (3)"""
5828    config = os.path.join(params['logdir'], 'dpp_config_save3.conf')
5829    run_dpp_config_save(dev, apdev, config, "\\u0001*\\u00c2\\u00bc\\u00c3\\u009e\\u00c3\\u00bf", '012ac2bcc39ec3bf')
5830
5831def run_dpp_config_save(dev, apdev, config, conf_ssid, exp_ssid):
5832    check_dpp_capab(dev[1])
5833    with open(config, "w") as f:
5834        f.write("update_config=1\n" +
5835                "dpp_config_processing=1\n")
5836    wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
5837    wpas.interface_add("wlan5", config=config)
5838    check_dpp_capab(wpas)
5839    conf = '{"wi-fi_tech":"infra", "discovery":{"ssid":"' + conf_ssid + '"},"cred":{"akm":"psk","pass":"secret passphrase"}}'
5840    dev[1].set("dpp_config_obj_override", conf)
5841    dpp_dev = [wpas, dev[1]]
5842    run_dpp_qr_code_auth_unicast(dpp_dev, apdev, "prime256v1",
5843                                 require_conf_success=True)
5844    if "OK" not in wpas.request("SAVE_CONFIG"):
5845        raise Exception("Failed to save configuration file")
5846    with open(config, "r") as f:
5847        data = f.read()
5848        logger.info("Saved configuration:\n" + data)
5849        if 'ssid=' + exp_ssid + '\n' not in data:
5850            raise Exception("SSID not saved")
5851        if 'psk="secret passphrase"' not in data:
5852            raise Exception("Passphtase not saved")
5853
5854def test_dpp_nfc_uri(dev, apdev):
5855    """DPP bootstrapping via NFC URI record"""
5856    check_dpp_capab(dev[0])
5857    check_dpp_capab(dev[1])
5858
5859    id = dev[0].dpp_bootstrap_gen(type="nfc-uri", chan="81/1", mac=True)
5860    uri = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id)
5861    logger.info("Generated URI: " + uri)
5862    info = dev[0].request("DPP_BOOTSTRAP_INFO %d" % id)
5863    logger.info("Bootstrapping info:\n" + info)
5864    if "type=NFC-URI" not in info:
5865        raise Exception("Unexpected bootstrapping info contents")
5866
5867    dev[0].dpp_listen(2412)
5868    conf_id = dev[1].dpp_configurator_add()
5869    dev[1].dpp_auth_init(nfc_uri=uri, configurator=conf_id, conf="sta-dpp")
5870    wait_auth_success(dev[0], dev[1], configurator=dev[1], enrollee=dev[0])
5871
5872def test_dpp_nfc_uri_hostapd(dev, apdev):
5873    """DPP bootstrapping via NFC URI record (hostapd)"""
5874    check_dpp_capab(dev[0])
5875
5876    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured"})
5877    check_dpp_capab(hapd)
5878
5879    id = hapd.dpp_bootstrap_gen(type="nfc-uri", chan="81/1", mac=True)
5880    uri = hapd.request("DPP_BOOTSTRAP_GET_URI %d" % id)
5881    logger.info("Generated URI: " + uri)
5882    info = hapd.request("DPP_BOOTSTRAP_INFO %d" % id)
5883    logger.info("Bootstrapping info:\n" + info)
5884    if "type=NFC-URI" not in info:
5885        raise Exception("Unexpected bootstrapping info contents")
5886
5887    hapd.dpp_listen(2412)
5888    conf_id = dev[0].dpp_configurator_add()
5889    dev[0].dpp_auth_init(nfc_uri=uri, configurator=conf_id, conf="ap-dpp")
5890    wait_auth_success(hapd, dev[0], configurator=dev[0], enrollee=hapd)
5891
5892def test_dpp_nfc_uri_hostapd_tag_read(dev, apdev):
5893    """DPP bootstrapping via NFC URI record (hostapd reading tag)"""
5894    check_dpp_capab(dev[0])
5895
5896    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured"})
5897    check_dpp_capab(hapd)
5898
5899    id = dev[0].dpp_bootstrap_gen(type="nfc-uri", chan="81/1", mac=True)
5900    uri = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id)
5901    info = dev[0].request("DPP_BOOTSTRAP_INFO %d" % id)
5902    conf_id = dev[0].dpp_configurator_add()
5903    dev[0].set("dpp_configurator_params",
5904               "conf=ap-dpp configurator=%d" % conf_id)
5905    dev[0].dpp_listen(2412)
5906
5907    hapd.dpp_auth_init(nfc_uri=uri, role="enrollee")
5908    wait_auth_success(dev[0], hapd, configurator=dev[0], enrollee=hapd)
5909
5910def test_dpp_nfc_negotiated_handover(dev, apdev):
5911    """DPP bootstrapping via NFC negotiated handover"""
5912    run_dpp_nfc_negotiated_handover(dev)
5913
5914def test_dpp_nfc_negotiated_handover_diff_curve(dev, apdev):
5915    """DPP bootstrapping via NFC negotiated handover (different curve)"""
5916    run_dpp_nfc_negotiated_handover(dev, curve0="prime256v1",
5917                                    curve1="secp384r1")
5918
5919def test_dpp_nfc_negotiated_handover_hostapd_sel(dev, apdev):
5920    """DPP bootstrapping via NFC negotiated handover (hostapd as selector)"""
5921    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured",
5922                                     "channel": "6"})
5923    check_dpp_capab(hapd)
5924    run_dpp_nfc_negotiated_handover([dev[0], hapd], conf="ap-dpp")
5925
5926def test_dpp_nfc_negotiated_handover_hostapd_req(dev, apdev):
5927    """DPP bootstrapping via NFC negotiated handover (hostapd as requestor)"""
5928    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured",
5929                                     "channel": "6"})
5930    check_dpp_capab(hapd)
5931    run_dpp_nfc_negotiated_handover([hapd, dev[0]])
5932
5933def run_dpp_nfc_negotiated_handover(dev, curve0=None, curve1=None,
5934                                    conf="sta-dpp"):
5935    check_dpp_capab(dev[0])
5936    check_dpp_capab(dev[1])
5937
5938    id0 = dev[0].dpp_bootstrap_gen(type="nfc-uri", chan="81/6,11", mac=True,
5939                                   curve=curve0)
5940    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
5941    logger.info("Generated URI[0]: " + uri0)
5942    id1 = dev[1].dpp_bootstrap_gen(type="nfc-uri", chan="81/1,6,11", mac=True,
5943                                   curve=curve1)
5944    uri1 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id1)
5945    logger.info("Generated URI[1]: " + uri1)
5946
5947    # dev[0] acting as NFC Handover Requestor
5948    # dev[1] acting as NFC Handover Selector
5949    res = dev[1].request("DPP_NFC_HANDOVER_REQ own=%d uri=%s" % (id1, uri0))
5950    if "FAIL" in res:
5951        raise Exception("Failed to process NFC Handover Request")
5952    info = dev[1].request("DPP_BOOTSTRAP_INFO %d" % id1)
5953    logger.info("Updated local bootstrapping info:\n" + info)
5954    freq = None
5955    for line in info.splitlines():
5956        if line.startswith("use_freq="):
5957            freq = int(line.split('=')[1])
5958    if freq is None:
5959        raise Exception("Selected channel not indicated")
5960    uri1 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id1)
5961    logger.info("Updated URI[1]: " + uri1)
5962    dev[1].dpp_listen(freq)
5963    res = dev[0].request("DPP_NFC_HANDOVER_SEL own=%d uri=%s" % (id0, uri1))
5964    if "FAIL" in res:
5965        raise Exception("Failed to process NFC Handover Select")
5966    peer = int(res)
5967
5968    conf_id = dev[0].dpp_configurator_add()
5969    dev[0].dpp_auth_init(peer=peer, own=id0, configurator=conf_id,
5970                         conf=conf)
5971    wait_auth_success(dev[1], dev[0], configurator=dev[0], enrollee=dev[1])
5972
5973def test_dpp_nfc_errors_hostapd(dev, apdev):
5974    """DPP NFC operation failures in hostapd"""
5975    check_dpp_capab(dev[0])
5976    check_dpp_capab(dev[1])
5977
5978    id0 = dev[0].dpp_bootstrap_gen(type="nfc-uri", chan="81/11", mac=True,
5979                                   curve="secp384r1")
5980    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
5981
5982    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured",
5983                                     "channel": "6"})
5984    check_dpp_capab(hapd)
5985
5986    id_h = hapd.dpp_bootstrap_gen(type="nfc-uri", chan="81/6", mac=True)
5987    uri_h = hapd.request("DPP_BOOTSTRAP_GET_URI %d" % id_h)
5988
5989    tests = ["",
5990             "own=123456789",
5991             "own=%d" % id_h,
5992             "own=%d uri=%s" % (id_h, "foo")]
5993    for t in tests:
5994        if "FAIL" not in hapd.request("DPP_NFC_HANDOVER_REQ " + t):
5995            raise Exception("Invalid DPP_NFC_HANDOVER_REQ accepted")
5996        if "FAIL" not in hapd.request("DPP_NFC_HANDOVER_SEL " + t):
5997            raise Exception("Invalid DPP_NFC_HANDOVER_SEL accepted")
5998
5999    # DPP: Peer (NFC Handover Selector) used different curve
6000    if "FAIL" not in hapd.request("DPP_NFC_HANDOVER_SEL own=%d uri=%s" % (id_h, uri0)):
6001        raise Exception("Invalid DPP_NFC_HANDOVER_SEL accepted")
6002
6003    # DPP: No common channel found
6004    if "FAIL" not in hapd.request("DPP_NFC_HANDOVER_REQ own=%d uri=%s" % (id_h, uri0)):
6005        raise Exception("DPP_NFC_HANDOVER_REQ with local error accepted")
6006
6007def test_dpp_with_p2p_device(dev, apdev):
6008    """DPP exchange when driver uses a separate P2P Device interface"""
6009    check_dpp_capab(dev[0])
6010    with HWSimRadio(use_p2p_device=True) as (radio, iface):
6011        wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
6012        wpas.interface_add(iface)
6013        check_dpp_capab(wpas)
6014        id1 = wpas.dpp_bootstrap_gen(chan="81/1", mac=True)
6015        uri1 = wpas.request("DPP_BOOTSTRAP_GET_URI %d" % id1)
6016        wpas.dpp_listen(2412)
6017        time.sleep(7)
6018        dev[0].dpp_auth_init(uri=uri1)
6019        wait_auth_success(wpas, dev[0], configurator=dev[0], enrollee=wpas,
6020                          allow_enrollee_failure=True)
6021
6022@long_duration_test
6023def test_dpp_chirp(dev, apdev):
6024    """DPP chirp"""
6025    check_dpp_capab(dev[0])
6026    dev[0].flush_scan_cache()
6027
6028    params = {"ssid": "dpp",
6029              "channel": "11"}
6030    hapd = hostapd.add_ap(apdev[0], params)
6031    check_dpp_capab(hapd)
6032    dpp_cc = False
6033
6034    id1 = dev[0].dpp_bootstrap_gen(chan="81/1")
6035    if "OK" not in dev[0].request("DPP_CHIRP own=%d iter=5" % id1):
6036        raise Exception("DPP_CHIRP failed")
6037    chan1 = 0
6038    chan6 = 0
6039    chan11 = 0
6040    for i in range(30):
6041        ev = dev[0].wait_event(["DPP-CHIRP-STOPPED",
6042                                "DPP-TX "], timeout=60)
6043        if ev is None:
6044            raise Exception("DPP chirp stop not reported")
6045        if "DPP-CHIRP-STOPPED" in ev:
6046            break
6047        if "type=13" not in ev:
6048            continue
6049        freq = int(ev.split(' ')[2].split('=')[1])
6050        if freq == 2412:
6051            chan1 += 1
6052        elif freq == 2437:
6053            chan6 += 1
6054        elif freq == 2462:
6055            chan11 += 1
6056        if not dpp_cc:
6057            hapd.set("dpp_configurator_connectivity", "1")
6058            if "OK" not in hapd.request("UPDATE_BEACON"):
6059                raise Exception("UPDATE_BEACON failed")
6060            dpp_cc = True
6061    if chan1 != 5 or chan6 != 5 or chan11 != 1:
6062        raise Exception("Unexpected number of presence announcements sent: %d %d %d" % (chan1, chan6, chan11))
6063    ev = hapd.wait_event(["DPP-CHIRP-RX"], timeout=1)
6064    if ev is None:
6065        raise Exception("No chirp received on the AP")
6066    if "freq=2462" not in ev:
6067        raise Exception("Chirp reception reported on unexpected channel: " + ev)
6068    if "src=" + dev[0].own_addr() not in ev:
6069        raise Exception("Unexpected chirp source reported: " + ev)
6070
6071@long_duration_test
6072def test_dpp_chirp_listen(dev, apdev):
6073    """DPP chirp with listen"""
6074    check_dpp_capab(dev[0])
6075    check_dpp_capab(dev[1])
6076
6077    id1 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
6078    uri = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id1)
6079
6080    if "OK" not in dev[0].request("DPP_CHIRP own=%d iter=2 listen=2412" % id1):
6081        raise Exception("DPP_CHIRP failed")
6082    for i in range(30):
6083        ev = dev[0].wait_event(["DPP-CHIRP-STOPPED",
6084                                "DPP-TX "], timeout=60)
6085        if ev is None:
6086            raise Exception("DPP chirp stop not reported")
6087        if "DPP-CHIRP-STOPPED" in ev:
6088            break
6089
6090def test_dpp_chirp_configurator(dev, apdev):
6091    """DPP chirp with a standalone Configurator"""
6092    check_dpp_capab(dev[0])
6093    check_dpp_capab(dev[1])
6094
6095    id1 = dev[0].dpp_bootstrap_gen(chan="81/1")
6096    uri = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id1)
6097
6098    conf_id = dev[1].dpp_configurator_add()
6099    idc = dev[1].dpp_qr_code(uri)
6100    dev[1].dpp_bootstrap_set(idc, conf="sta-dpp", configurator=conf_id)
6101    dev[1].dpp_listen(2437)
6102
6103    if "OK" not in dev[0].request("DPP_CHIRP own=%d iter=2" % id1):
6104        raise Exception("DPP_CHIRP failed")
6105
6106    ev = dev[1].wait_event(["DPP-RX"], timeout=10)
6107    if ev is None:
6108        raise Exception("Presence Announcement not seen")
6109    if "type=13" not in ev:
6110        raise Exception("Unexpected DPP frame received: " + ev)
6111
6112    ev = dev[1].wait_event(["DPP-TX"], timeout=10)
6113    if ev is None:
6114        raise Exception("Authentication Request TX not seen")
6115    if "type=0" not in ev:
6116        raise Exception("Unexpected DPP frame TX: " + ev)
6117    if "dst=" + dev[0].own_addr() not in ev:
6118        raise Exception("Unexpected Authentication Request destination: " + ev)
6119
6120    wait_auth_success(dev[0], dev[1], dev[1], dev[0])
6121
6122def test_dpp_chirp_ap_as_configurator(dev, apdev):
6123    """DPP chirp with an AP as a standalone Configurator"""
6124    check_dpp_capab(dev[0], min_ver=2)
6125
6126    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured"})
6127    check_dpp_capab(hapd, min_ver=2)
6128
6129    id1 = dev[0].dpp_bootstrap_gen(chan="81/1")
6130    uri = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id1)
6131
6132    conf_id = hapd.dpp_configurator_add()
6133    idc = hapd.dpp_qr_code(uri)
6134    hapd.dpp_bootstrap_set(idc, conf="sta-dpp", configurator=conf_id)
6135    hapd.dpp_listen(2412)
6136
6137    if "OK" not in dev[0].request("DPP_CHIRP own=%d iter=2" % id1):
6138        raise Exception("DPP_CHIRP failed")
6139
6140    wait_auth_success(dev[0], hapd, hapd, dev[0])
6141
6142def test_dpp_chirp_configurator_inits(dev, apdev):
6143    """DPP chirp with a standalone Configurator initiating"""
6144    check_dpp_capab(dev[0])
6145    check_dpp_capab(dev[1])
6146
6147    id1 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
6148    uri = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id1)
6149
6150    conf_id = dev[1].dpp_configurator_add()
6151    idc = dev[1].dpp_qr_code(uri)
6152
6153    if "OK" not in dev[0].request("DPP_CHIRP own=%d iter=2 listen=2412" % id1):
6154        raise Exception("DPP_CHIRP failed")
6155    for i in range(2):
6156        ev = dev[0].wait_event(["DPP-TX "], timeout=10)
6157        if ev is None or "type=13" not in ev:
6158            raise Exception("Presence Announcement not sent")
6159
6160    dev[1].dpp_auth_init(uri=uri, conf="sta-dpp", configurator=conf_id)
6161    wait_auth_success(dev[0], dev[1], dev[1], dev[0])
6162
6163def test_dpp_chirp_ap(dev, apdev):
6164    """DPP chirp by an AP"""
6165    check_dpp_capab(dev[0], min_ver=2)
6166
6167    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured",
6168                                     "start_disabled": "1"})
6169    check_dpp_capab(hapd, min_ver=2)
6170
6171    id_h = hapd.dpp_bootstrap_gen(chan="81/1", mac=True)
6172    uri = hapd.request("DPP_BOOTSTRAP_GET_URI %d" % id_h)
6173
6174    conf_id = dev[0].dpp_configurator_add()
6175    idc = dev[0].dpp_qr_code(uri)
6176    dev[0].dpp_bootstrap_set(idc, conf="ap-dpp", configurator=conf_id)
6177    dev[0].dpp_listen(2437)
6178    if "OK" not in hapd.request("DPP_CHIRP own=%d iter=5" % id_h):
6179        raise Exception("DPP_CHIRP failed")
6180    wait_auth_success(hapd, dev[0], configurator=dev[0], enrollee=hapd,
6181                      timeout=20)
6182    update_hapd_config(hapd)
6183
6184@long_duration_test
6185def test_dpp_chirp_ap_5g(dev, apdev):
6186    """DPP chirp by an AP on 5 GHz"""
6187    check_dpp_capab(dev[0], min_ver=2)
6188
6189    try:
6190        hapd = None
6191        hapd2 = None
6192
6193        params = {"ssid": "unconfigured",
6194                  "country_code": "US",
6195                  "hw_mode": "a",
6196                  "channel": "40",
6197                  "dpp_configurator_connectivity": "1"}
6198        hapd2 = hostapd.add_ap(apdev[1], params)
6199        check_dpp_capab(hapd2, min_ver=2)
6200
6201        params = {"ssid": "unconfigured",
6202                  "country_code": "US",
6203                  "hw_mode": "a",
6204                  "channel": "36",
6205                  "start_disabled": "1"}
6206        hapd = hostapd.add_ap(apdev[0], params)
6207        check_dpp_capab(hapd, min_ver=2)
6208
6209        id_h = hapd.dpp_bootstrap_gen(chan="81/1", mac=True)
6210        uri = hapd.request("DPP_BOOTSTRAP_GET_URI %d" % id_h)
6211
6212        # First, check chirping iteration and timeout
6213        if "OK" not in hapd.request("DPP_CHIRP own=%d iter=2" % id_h):
6214            raise Exception("DPP_CHIRP failed")
6215        chan1 = 0
6216        chan6 = 0
6217        chan40 = 0
6218        chan149 = 0
6219        for i in range(30):
6220            ev = hapd.wait_event(["DPP-CHIRP-STOPPED", "DPP-TX "], timeout=60)
6221            if ev is None:
6222                raise Exception("DPP chirp stop not reported")
6223            if "DPP-CHIRP-STOPPED" in ev:
6224                break
6225            if "type=13" not in ev:
6226                continue
6227            freq = int(ev.split(' ')[2].split('=')[1])
6228            if freq == 2412:
6229                chan1 += 1
6230            elif freq == 2437:
6231                chan6 += 1
6232            elif freq == 5200:
6233                chan40 += 1
6234            elif freq == 5745:
6235                chan149 += 1
6236        if not chan1 or not chan6 or not chan40 or not chan149:
6237            raise Exception("Chirp not sent on all channels")
6238
6239        # Then, check successful chirping
6240        conf_id = dev[0].dpp_configurator_add()
6241        idc = dev[0].dpp_qr_code(uri)
6242        dev[0].dpp_bootstrap_set(idc, conf="ap-dpp", configurator=conf_id)
6243        dev[0].dpp_listen(5200)
6244        if "OK" not in hapd.request("DPP_CHIRP own=%d iter=5" % id_h):
6245            raise Exception("DPP_CHIRP failed")
6246        wait_auth_success(hapd, dev[0], configurator=dev[0], enrollee=hapd,
6247                          timeout=20)
6248        update_hapd_config(hapd)
6249    finally:
6250        clear_regdom(hapd, dev)
6251
6252def test_dpp_chirp_ap_errors(dev, apdev):
6253    """DPP chirp errors in hostapd"""
6254    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured",
6255                                     "start_disabled": "1"})
6256    check_dpp_capab(hapd, min_ver=2)
6257
6258    id_h = hapd.dpp_bootstrap_gen(chan="81/1", mac=True)
6259    uri = hapd.request("DPP_BOOTSTRAP_GET_URI %d" % id_h)
6260    tests = ["",
6261             "own=%d" % (id_h + 1),
6262             "own=%d iter=-1" % id_h,
6263             "own=%d listen=0" % id_h]
6264    for t in tests:
6265        if "FAIL" not in hapd.request("DPP_CHIRP " + t):
6266            raise Exception("Invalid DPP_CHIRP accepted: " + t)
6267    if "OK" not in hapd.request("DPP_CHIRP own=%d iter=5" % id_h):
6268        raise Exception("DPP_CHIRP failed")
6269
6270    hapd.request("DPP_STOP_CHIRP")
6271
6272def start_dpp_pfs_ap(apdev, pfs, sae=False):
6273    params = {"ssid": "dpp",
6274              "wpa": "2",
6275              "wpa_key_mgmt": "DPP",
6276              "dpp_pfs": str(pfs),
6277              "ieee80211w": "2",
6278              "rsn_pairwise": "CCMP",
6279              "dpp_connector": params1_ap_connector,
6280              "dpp_csign": params1_csign,
6281              "dpp_netaccesskey": params1_ap_netaccesskey}
6282    if sae:
6283        params["wpa_key_mgmt"] = "DPP SAE"
6284        params["sae_password"] = "sae-password"
6285    try:
6286        hapd = hostapd.add_ap(apdev, params)
6287    except:
6288        raise HwsimSkip("DPP not supported")
6289    return hapd
6290
6291def run_dpp_pfs_sta(dev, pfs, fail=False, pfs_expected=None, sae=False):
6292    key_mgmt = "DPP SAE" if sae else "DPP"
6293    psk = "sae-password" if sae else None
6294    dev.connect("dpp", key_mgmt=key_mgmt, scan_freq="2412",
6295                ieee80211w="2", dpp_pfs=str(pfs),
6296                dpp_csign=params1_csign,
6297                dpp_connector=params1_sta_connector,
6298                dpp_netaccesskey=params1_sta_netaccesskey,
6299                psk=psk,
6300                wait_connect=not fail)
6301    if fail:
6302        for i in range(2):
6303            ev = dev.wait_event(["CTRL-EVENT-ASSOC-REJECT",
6304                                 "CTRL-EVENT-CONNECTED"], timeout=10)
6305            if ev is None:
6306                raise Exception("Connection result not reported")
6307            if "CTRL-EVENT-CONNECTED" in ev:
6308                raise Exception("Unexpected connection")
6309        dev.request("REMOVE_NETWORK all")
6310    else:
6311        if pfs_expected is not None:
6312            res = dev.get_status_field("dpp_pfs")
6313            pfs_used = res == "1"
6314            if pfs_expected != pfs_used:
6315                raise Exception("Unexpected PFS negotiation result")
6316        dev.request("REMOVE_NETWORK all")
6317        dev.wait_disconnected()
6318    dev.dump_monitor()
6319
6320def test_dpp_pfs_ap_0(dev, apdev):
6321    """DPP PFS AP default"""
6322    check_dpp_capab(dev[0])
6323    hapd = start_dpp_pfs_ap(apdev[0], 0)
6324    run_dpp_pfs_sta(dev[0], 0, pfs_expected=True)
6325    run_dpp_pfs_sta(dev[0], 1, pfs_expected=True)
6326    run_dpp_pfs_sta(dev[0], 2, pfs_expected=False)
6327
6328def test_dpp_pfs_ap_1(dev, apdev):
6329    """DPP PFS AP required"""
6330    check_dpp_capab(dev[0])
6331    hapd = start_dpp_pfs_ap(apdev[0], 1)
6332    run_dpp_pfs_sta(dev[0], 0, pfs_expected=True)
6333    run_dpp_pfs_sta(dev[0], 1, pfs_expected=True)
6334    run_dpp_pfs_sta(dev[0], 2, fail=True)
6335
6336def test_dpp_pfs_ap_2(dev, apdev):
6337    """DPP PFS AP not allowed"""
6338    check_dpp_capab(dev[0])
6339    hapd = start_dpp_pfs_ap(apdev[0], 2)
6340    run_dpp_pfs_sta(dev[0], 0, pfs_expected=False)
6341    run_dpp_pfs_sta(dev[0], 1, fail=True)
6342    run_dpp_pfs_sta(dev[0], 2, pfs_expected=False)
6343
6344def test_dpp_pfs_connect_cmd(dev, apdev):
6345    """DPP PFS and cfg80211 connect command"""
6346    wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
6347    wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
6348    check_dpp_capab(wpas)
6349    hapd = start_dpp_pfs_ap(apdev[0], 0)
6350    run_dpp_pfs_sta(wpas, 0, pfs_expected=True)
6351    run_dpp_pfs_sta(wpas, 1, pfs_expected=True)
6352    run_dpp_pfs_sta(wpas, 2, pfs_expected=False)
6353
6354def test_dpp_pfs_connect_cmd_ap_2(dev, apdev):
6355    """DPP PFS and cfg80211 connect command (PFS not allowed by AP)"""
6356    wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
6357    wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
6358    check_dpp_capab(wpas)
6359    hapd = start_dpp_pfs_ap(apdev[0], 2)
6360    run_dpp_pfs_sta(wpas, 0, pfs_expected=False)
6361    run_dpp_pfs_sta(wpas, 1, fail=True)
6362    run_dpp_pfs_sta(wpas, 2, pfs_expected=False)
6363
6364def test_dpp_pfs_connect_cmd_ap_2_sae(dev, apdev):
6365    """DPP PFS and cfg80211 connect command (PFS not allowed by AP; SAE enabled)"""
6366    wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
6367    wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
6368    check_dpp_capab(wpas)
6369    if "SAE" not in wpas.get_capability("auth_alg"):
6370        raise HwsimSkip("SAE not supported")
6371    hapd = start_dpp_pfs_ap(apdev[0], 2, sae=True)
6372    run_dpp_pfs_sta(wpas, 0, pfs_expected=False, sae=True)
6373    run_dpp_pfs_sta(wpas, 1, fail=True, sae=True)
6374    run_dpp_pfs_sta(wpas, 2, pfs_expected=False, sae=True)
6375
6376def test_dpp_pfs_ap_0_sta_ver1(dev, apdev):
6377    """DPP PFS AP default with version 1 STA"""
6378    check_dpp_capab(dev[0])
6379    dev[0].set("dpp_version_override", "1")
6380    hapd = start_dpp_pfs_ap(apdev[0], 0)
6381    run_dpp_pfs_sta(dev[0], 0, pfs_expected=False)
6382
6383def test_dpp_pfs_errors(dev, apdev):
6384    """DPP PFS error cases"""
6385    check_dpp_capab(dev[0], min_ver=2)
6386    hapd = start_dpp_pfs_ap(apdev[0], 1)
6387    tests = [(1, "dpp_pfs_init"),
6388             (1, "crypto_ecdh_init;dpp_pfs_init"),
6389             (1, "wpabuf_alloc;dpp_pfs_init")]
6390    for count, func in tests:
6391        with alloc_fail(dev[0], count, func):
6392            dev[0].connect("dpp", key_mgmt="DPP", scan_freq="2412",
6393                           ieee80211w="2", dpp_pfs="1",
6394                           dpp_csign=params1_csign,
6395                           dpp_connector=params1_sta_connector,
6396                           dpp_netaccesskey=params1_sta_netaccesskey)
6397            dev[0].request("REMOVE_NETWORK all")
6398            dev[0].wait_disconnected()
6399            dev[0].dump_monitor()
6400            hapd.dump_monitor()
6401
6402def test_dpp_reconfig_connector(dev, apdev):
6403    """DPP reconfiguration connector"""
6404    try:
6405        run_dpp_reconfig_connector(dev, apdev)
6406    finally:
6407        dev[0].set("dpp_config_processing", "0", allow_fail=True)
6408
6409def test_dpp_reconfig_connector_different_groups(dev, apdev):
6410    """DPP reconfiguration connector with different groups"""
6411    try:
6412        run_dpp_reconfig_connector(dev, apdev, conf_curve="secp384r1")
6413    finally:
6414        dev[0].set("dpp_config_processing", "0", allow_fail=True)
6415
6416@long_duration_test
6417def test_dpp_reconfig_retries(dev, apdev):
6418    """DPP reconfiguration retries"""
6419    try:
6420        run_dpp_reconfig_connector(dev, apdev, test_retries=True)
6421        for i in range(4):
6422            ev = dev[0].wait_event(["DPP-TX "], timeout=120)
6423            if ev is None or "type=14" not in ev:
6424                raise Exception("Reconfig Announcement not sent")
6425        dev[0].request("DPP_STOP_LISTEN")
6426    finally:
6427        dev[0].set("dpp_config_processing", "0", allow_fail=True)
6428
6429def run_dpp_reconfig_connector(dev, apdev, conf_curve=None,
6430                               test_retries=False):
6431    check_dpp_capab(dev[0], min_ver=2)
6432    check_dpp_capab(dev[1], min_ver=2)
6433
6434    ssid = "reconfig"
6435    passphrase = "secret passphrase"
6436    passphrase2 = "another secret passphrase"
6437    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
6438    hapd = hostapd.add_ap(apdev[0], params)
6439
6440    dev[0].set("dpp_config_processing", "2")
6441    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
6442    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
6443    dev[0].dpp_listen(2412)
6444    configurator = dev[1].dpp_configurator_add(curve=conf_curve)
6445    conf = 'sta-psk'
6446    dev[1].dpp_auth_init(uri=uri0, conf=conf, ssid=ssid,
6447                         passphrase=passphrase, configurator=configurator,
6448                         conn_status=True)
6449    res = wait_auth_success(dev[0], dev[1], configurator=dev[1],
6450                            enrollee=dev[0])
6451    if 'wait_conn_status' not in res:
6452        raise Exception("Configurator did not request connection status")
6453    ev = dev[1].wait_event(["DPP-CONN-STATUS-RESULT"], timeout=20)
6454    if ev is None:
6455        raise Exception("No connection status reported")
6456    dev[1].dump_monitor()
6457
6458    ev = dev[0].wait_event(["DPP-CONFOBJ-SSID"], timeout=1)
6459    if ev is None:
6460        raise Exception("SSID not reported")
6461    res_ssid = ev.split(' ')[1]
6462    if res_ssid != ssid:
6463        raise Exception("Unexpected SSID value")
6464
6465    ev = dev[0].wait_event(["DPP-CONNECTOR"], timeout=1)
6466    if ev is None:
6467        raise Exception("Connector not reported")
6468    connector = ev.split(' ')[1]
6469
6470    ev = dev[0].wait_event(["DPP-C-SIGN-KEY"], timeout=1)
6471    if ev is None:
6472        raise Exception("C-sign-key not reported")
6473    p = ev.split(' ')
6474    csign = p[1]
6475
6476    ev = dev[0].wait_event(["DPP-NET-ACCESS-KEY"], timeout=1)
6477    if ev is None:
6478        raise Exception("netAccessKey not reported")
6479    p = ev.split(' ')
6480    net_access_key = p[1]
6481    net_access_key_expiry = p[2] if len(p) > 2 else None
6482
6483    ev = dev[0].wait_event(["DPP-NETWORK-ID"], timeout=1)
6484    if ev is None:
6485        raise Exception("DPP network profile not generated")
6486    id = ev.split(' ')[1]
6487
6488    dev[0].wait_connected()
6489
6490    n_key_mgmt = dev[0].get_network(id, "key_mgmt")
6491    if n_key_mgmt != "WPA-PSK FT-PSK WPA-PSK-SHA256":
6492        raise Exception("Unexpected key_mgmt: " + n_key_mgmt)
6493    n_connector = dev[0].get_network(id, "dpp_connector")
6494    if n_connector.strip('"') != connector:
6495        raise Exception("Connector mismatch: %s %s" % (n_connector, connector))
6496    n_csign = dev[0].get_network(id, "dpp_csign")
6497    if n_csign.strip('"') != csign:
6498        raise Exception("csign mismatch: %s %s" % (n_csign, csign))
6499    n_net_access_key = dev[0].get_network(id, "dpp_netaccesskey")
6500    if n_net_access_key.strip('"') != net_access_key:
6501        raise Exception("net_access_key mismatch: %s %s" % (n_net_access_key,
6502                                                            net_access_key))
6503
6504    dev[0].request("DISCONNECT")
6505    dev[0].wait_disconnected()
6506
6507    hapd.disable()
6508    hapd.set("wpa_passphrase", passphrase2)
6509    hapd.enable()
6510
6511    time.sleep(0.1)
6512    dev[0].dump_monitor()
6513    dev[1].dump_monitor()
6514
6515    if test_retries:
6516        dev[1].request("DPP_STOP_LISTEN")
6517        if "OK" not in dev[0].request("DPP_RECONFIG %s iter=10" % id):
6518            raise Exception("Failed to start reconfiguration")
6519        return
6520
6521    dev[1].set("dpp_configurator_params",
6522               "conf=sta-psk ssid=%s pass=%s conn_status=1" % (binascii.hexlify(ssid.encode()).decode(), binascii.hexlify(passphrase2.encode()).decode()))
6523    dev[1].dpp_listen(2437)
6524
6525    if "OK" not in dev[0].request("DPP_RECONFIG %s" % id):
6526        raise Exception("Failed to start reconfiguration")
6527    ev = dev[0].wait_event(["DPP-TX "], timeout=10)
6528    if ev is None or "type=14" not in ev:
6529        raise Exception("Reconfig Announcement not sent")
6530
6531    ev = dev[1].wait_event(["DPP-RX"], timeout=5)
6532    if ev is None:
6533        raise Exception("DPP Reconfig Announcement not received")
6534    if "freq=2437 type=14" not in ev:
6535        raise Exception("Unexpected RX data for Reconfig Announcement: " + ev)
6536
6537    ev = dev[0].wait_event(["DPP-RX"], timeout=5)
6538    if ev is None or "freq=2437 type=15" not in ev:
6539        raise Exception("DPP Reconfig Authentication Request not received")
6540
6541    ev = dev[1].wait_event(["DPP-RX"], timeout=5)
6542    if ev is None or "freq=2437 type=16" not in ev:
6543        raise Exception("DPP Reconfig Authentication Response not received")
6544
6545    ev = dev[0].wait_event(["DPP-RX"], timeout=5)
6546    if ev is None or "freq=2437 type=17" not in ev:
6547        raise Exception("DPP Reconfig Authentication Confirm not received")
6548
6549    ev = dev[0].wait_event(["GAS-QUERY-START"], timeout=5)
6550    if ev is None or "freq=2437" not in ev:
6551        raise Exception("DPP Config Request (GAS) not transmitted")
6552
6553    ev = dev[1].wait_event(["DPP-CONF-REQ-RX"], timeout=5)
6554    if ev is None:
6555        raise Exception("DPP Config Request (GAS) not received")
6556
6557    ev = dev[0].wait_event(["GAS-QUERY-DONE"], timeout=5)
6558    if ev is None or "freq=2437" not in ev:
6559        raise Exception("DPP Config Response (GAS) not received")
6560
6561    ev = dev[1].wait_event(["DPP-RX"], timeout=5)
6562    if ev is None or "freq=2437 type=11" not in ev:
6563        raise Exception("DPP Config Result not received")
6564
6565    ev = dev[1].wait_event(["DPP-CONF-SENT"], timeout=5)
6566    if ev is None:
6567        raise Exception("DPP Config Response (GAS) not transmitted")
6568
6569    ev = dev[0].wait_event(["DPP-CONF-RECEIVED", "DPP-CONF-FAILED"], timeout=5)
6570    if ev is None:
6571        raise Exception("DPP config response reception result not indicated")
6572    if "DPP-CONF-RECEIVED" not in ev:
6573        raise Exception("Reconfiguration failed")
6574
6575    dev[0].wait_connected()
6576
6577    ev = dev[1].wait_event(["DPP-CONN-STATUS-RESULT"], timeout=20)
6578    if ev is None:
6579        raise Exception("No connection status reported")
6580
6581def test_dpp_reconfig_hostapd_configurator(dev, apdev):
6582    """DPP reconfiguration with hostapd as configurator"""
6583    try:
6584        run_dpp_reconfig_hostapd_configurator(dev, apdev)
6585    finally:
6586        dev[0].set("dpp_config_processing", "0", allow_fail=True)
6587
6588def run_dpp_reconfig_hostapd_configurator(dev, apdev):
6589    ssid = "reconfig-ap"
6590    check_dpp_capab(dev[0], min_ver=2)
6591    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured"})
6592    check_dpp_capab(hapd, min_ver=2)
6593    conf_id = hapd.dpp_configurator_add()
6594
6595    cmd = "DPP_CONFIGURATOR_SIGN conf=ap-dpp configurator=%d ssid=%s" % (conf_id, binascii.hexlify(ssid.encode()).decode())
6596    res = hapd.request(cmd)
6597    if "FAIL" in res:
6598        raise Exception("Failed to generate own configuration")
6599    hapd.set("dpp_configurator_connectivity", "1")
6600    update_hapd_config(hapd)
6601
6602    id = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
6603    uri = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id)
6604    dev[0].set("dpp_config_processing", "2")
6605    dev[0].dpp_listen(2412)
6606    hapd.dpp_auth_init(uri=uri, conf="sta-dpp", configurator=conf_id,
6607                       extra="expiry=%d" % (time.time() + 10), ssid=ssid)
6608    wait_auth_success(dev[0], hapd, configurator=hapd, enrollee=dev[0])
6609    ev = dev[0].wait_event(["DPP-NETWORK-ID"], timeout=1)
6610    if ev is None:
6611        raise Exception("DPP network id not reported")
6612    network = int(ev.split(' ')[1])
6613    dev[0].wait_connected()
6614    dev[0].request("DISCONNECT")
6615    dev[0].wait_disconnected()
6616    dev[0].dump_monitor()
6617    time.sleep(10)
6618    if "FAIL" in dev[0].request("PMKSA_FLUSH"):
6619        raise Exception("PMKSA_FLUSH failed")
6620    dev[0].request("RECONNECT")
6621    ev = dev[0].wait_event(["DPP-MISSING-CONNECTOR", "CTRL-EVENT-CONNECTED"],
6622                           timeout=15)
6623    if ev is None or "DPP-MISSING-CONNECTOR" not in ev:
6624        raise Exception("Missing Connector not reported")
6625    if "netAccessKey expired" not in ev:
6626        raise Exception("netAccessKey expiry not indicated")
6627    dev[0].request("DISCONNECT")
6628    dev[0].dump_monitor()
6629
6630    hapd.set("dpp_configurator_params",
6631             "conf=sta-dpp configurator=%d ssid=%s" % (conf_id, binascii.hexlify(ssid.encode()).decode()))
6632
6633    if "OK" not in dev[0].request("DPP_RECONFIG %s" % network):
6634        raise Exception("Failed to start reconfiguration")
6635    ev = dev[0].wait_event(["DPP-NETWORK-ID"], timeout=15)
6636    if ev is None:
6637        raise Exception("DPP network id not reported for reconfiguration")
6638    network2 = int(ev.split(' ')[1])
6639    if network == network2:
6640        raise Exception("Network ID did not change")
6641    dev[0].wait_connected()
6642
6643def test_dpp_qr_code_auth_rand_mac_addr(dev, apdev):
6644    """DPP QR Code and authentication exchange (rand_mac_addr=1)"""
6645    flags = int(dev[0].get_driver_status_field('capa.flags'), 16)
6646    if flags & 0x0000400000000000 == 0:
6647        raise HwsimSkip("Driver does not support random GAS TA")
6648
6649    try:
6650        dev[0].set("gas_rand_mac_addr", "1")
6651        run_dpp_qr_code_auth_unicast(dev, apdev, None)
6652    finally:
6653        dev[0].set("gas_rand_mac_addr", "0")
6654
6655def dpp_sign_cert(cacert, cakey, csr_der):
6656    csr = OpenSSL.crypto.load_certificate_request(OpenSSL.crypto.FILETYPE_ASN1,
6657                                                  csr_der)
6658    cert = OpenSSL.crypto.X509()
6659    cert.set_serial_number(12345)
6660    cert.gmtime_adj_notBefore(-10)
6661    cert.gmtime_adj_notAfter(100000)
6662    cert.set_pubkey(csr.get_pubkey())
6663    dn = csr.get_subject()
6664    cert.set_subject(dn)
6665    cert.set_version(2)
6666    cert.add_extensions([
6667        OpenSSL.crypto.X509Extension(b"basicConstraints", True,
6668                                     b"CA:FALSE"),
6669        OpenSSL.crypto.X509Extension(b"subjectKeyIdentifier", False,
6670                                     b"hash", subject=cert),
6671        OpenSSL.crypto.X509Extension(b"authorityKeyIdentifier", False,
6672                                     b"keyid:always", issuer=cacert),
6673    ])
6674    cert.set_issuer(cacert.get_subject())
6675    cert.sign(cakey, "sha256")
6676    return cert
6677
6678def test_dpp_enterprise(dev, apdev, params):
6679    """DPP and enterprise EAP-TLS provisioning"""
6680    check_dpp_capab(dev[0], min_ver=2)
6681    try:
6682        dev[0].set("dpp_config_processing", "2")
6683        run_dpp_enterprise(dev, apdev, params)
6684    finally:
6685        dev[0].set("dpp_config_processing", "0", allow_fail=True)
6686
6687def run_dpp_enterprise(dev, apdev, params):
6688    if not openssl_imported:
6689        raise HwsimSkip("OpenSSL python method not available")
6690    check_dpp_capab(dev[0])
6691    check_dpp_capab(dev[1])
6692
6693    cert_file = params['prefix'] + ".cert.pem"
6694    pkcs7_file = params['prefix'] + ".pkcs7.der"
6695
6696    params = {"ssid": "dpp-ent",
6697              "wpa": "2",
6698              "wpa_key_mgmt": "WPA-EAP",
6699              "rsn_pairwise": "CCMP",
6700              "ieee8021x": "1",
6701              "eap_server": "1",
6702              "eap_user_file": "auth_serv/eap_user.conf",
6703              "ca_cert": "auth_serv/ec-ca.pem",
6704              "server_cert": "auth_serv/ec-server.pem",
6705              "private_key": "auth_serv/ec-server.key"}
6706    hapd = hostapd.add_ap(apdev[0], params)
6707
6708    with open("auth_serv/ec-ca.pem", "rb") as f:
6709        res = f.read()
6710        cacert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
6711                                                 res)
6712
6713    with open("auth_serv/ec-ca.key", "rb") as f:
6714        res = f.read()
6715        cakey = OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM, res)
6716
6717    conf_id = dev[1].dpp_configurator_add()
6718    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
6719    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
6720    dev[0].dpp_listen(2412)
6721    csrattrs = "MAsGCSqGSIb3DQEJBw=="
6722    id1 = dev[1].dpp_auth_init(uri=uri0, configurator=conf_id, conf="sta-dot1x",
6723                               csrattrs=csrattrs, ssid="dpp-ent")
6724
6725    ev = dev[1].wait_event(["DPP-CSR"], timeout=10)
6726    if ev is None:
6727        raise Exception("Configurator did not receive CSR")
6728    id1_csr = int(ev.split(' ')[1].split('=')[1])
6729    if id1 != id1_csr:
6730        raise Exception("Peer bootstrapping ID mismatch in CSR event")
6731    csr = ev.split(' ')[2]
6732    if not csr.startswith("csr="):
6733        raise Exception("Could not parse CSR event: " + ev)
6734    csr = csr[4:]
6735    csr = base64.b64decode(csr.encode())
6736    logger.info("CSR: " + binascii.hexlify(csr).decode())
6737
6738    cert = dpp_sign_cert(cacert, cakey, csr)
6739    with open(cert_file, 'wb') as f:
6740        f.write(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
6741                                                cert))
6742    subprocess.check_call(['openssl', 'crl2pkcs7', '-nocrl',
6743                           '-certfile', cert_file,
6744                           '-certfile', 'auth_serv/ec-ca.pem',
6745                           '-outform', 'DER', '-out', pkcs7_file])
6746
6747    #caCert = base64.b64encode(b"TODO").decode()
6748    #res = dev[1].request("DPP_CA_SET peer=%d name=caCert value=%s" % (id1, caCert))
6749    #if "OK" not in res:
6750    #    raise Exception("Failed to set caCert")
6751
6752    name = "server.w1.fi"
6753    res = dev[1].request("DPP_CA_SET peer=%d name=trustedEapServerName value=%s" % (id1, name))
6754    if "OK" not in res:
6755        raise Exception("Failed to set trustedEapServerName")
6756
6757    with open(pkcs7_file, 'rb') as f:
6758        pkcs7_der = f.read()
6759        certbag = base64.b64encode(pkcs7_der).decode()
6760    res = dev[1].request("DPP_CA_SET peer=%d name=certBag value=%s" % (id1, certbag))
6761    if "OK" not in res:
6762        raise Exception("Failed to set certBag")
6763
6764    ev = dev[1].wait_event(["DPP-CONF-SENT", "DPP-CONF-FAILED"], timeout=5)
6765    if ev is None:
6766        raise Exception("DPP configuration not completed (Configurator)")
6767    if "DPP-CONF-FAILED" in ev:
6768        raise Exception("DPP configuration did not succeed (Configurator)")
6769
6770    ev = dev[0].wait_event(["DPP-CONF-RECEIVED", "DPP-CONF-FAILED"],
6771                           timeout=1)
6772    if ev is None:
6773        raise Exception("DPP configuration not completed (Enrollee)")
6774    if "DPP-CONF-FAILED" in ev:
6775        raise Exception("DPP configuration did not succeed (Enrollee)")
6776
6777    ev = dev[0].wait_event(["DPP-CERTBAG"], timeout=1)
6778    if ev is None:
6779        raise Exception("DPP-CERTBAG not reported")
6780    certbag = base64.b64decode(ev.split(' ')[1].encode())
6781    if certbag != pkcs7_der:
6782        raise Exception("DPP-CERTBAG mismatch")
6783
6784    #ev = dev[0].wait_event(["DPP-CACERT"], timeout=1)
6785    #if ev is None:
6786    #    raise Exception("DPP-CACERT not reported")
6787
6788    ev = dev[0].wait_event(["DPP-SERVER-NAME"], timeout=1)
6789    if ev is None:
6790        raise Exception("DPP-SERVER-NAME not reported")
6791    if ev.split(' ')[1] != name:
6792        raise Exception("DPP-SERVER-NAME mismatch: " + ev)
6793
6794    ev = dev[0].wait_event(["DPP-NETWORK-ID"], timeout=1)
6795    if ev is None:
6796        raise Exception("DPP network profile not generated")
6797    id = ev.split(' ')[1]
6798
6799    dev[0].wait_connected()
6800
6801def test_dpp_enterprise_reject(dev, apdev, params):
6802    """DPP and enterprise EAP-TLS provisioning and CSR getting rejected"""
6803    check_dpp_capab(dev[0])
6804    check_dpp_capab(dev[1])
6805
6806    conf_id = dev[1].dpp_configurator_add()
6807    id0 = dev[0].dpp_bootstrap_gen(chan="81/1", mac=True)
6808    uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
6809    dev[0].dpp_listen(2412)
6810    csrattrs = "MAsGCSqGSIb3DQEJBw=="
6811    id1 = dev[1].dpp_auth_init(uri=uri0, configurator=conf_id, conf="sta-dot1x",
6812                               csrattrs=csrattrs, ssid="dpp-ent")
6813
6814    ev = dev[1].wait_event(["DPP-CSR"], timeout=10)
6815    if ev is None:
6816        raise Exception("Configurator did not receive CSR")
6817
6818    res = dev[1].request("DPP_CA_SET peer=%d name=status value=5" % id1)
6819    if "OK" not in res:
6820        raise Exception("Failed to set status")
6821
6822    ev = dev[1].wait_event(["DPP-CONF-SENT", "DPP-CONF-FAILED"], timeout=5)
6823    if ev is None:
6824        raise Exception("DPP configuration not completed (Configurator)")
6825    if "DPP-CONF-FAILED" in ev:
6826        raise Exception("DPP configuration did not succeed (Configurator)")
6827
6828    ev = dev[0].wait_event(["DPP-CONF-RECEIVED", "DPP-CONF-FAILED"],
6829                           timeout=1)
6830    if ev is None:
6831        raise Exception("DPP configuration not completed (Enrollee)")
6832    if "DPP-CONF-FAILED" not in ev:
6833        raise Exception("DPP configuration did not fail (Enrollee)")
6834
6835def test_dpp_enterprise_tcp(dev, apdev, params):
6836    """DPP over TCP for enterprise provisioning"""
6837    if not openssl_imported:
6838        raise HwsimSkip("OpenSSL python method not available")
6839
6840    try:
6841        run_dpp_enterprise_tcp(dev, apdev, params)
6842    finally:
6843        dev[1].request("DPP_CONTROLLER_STOP")
6844
6845def run_dpp_enterprise_tcp(dev, apdev, params):
6846    check_dpp_capab(dev[0])
6847    check_dpp_capab(dev[1])
6848
6849    cap_lo = params['prefix'] + ".lo.pcap"
6850
6851    wt = WlantestCapture('lo', cap_lo)
6852    time.sleep(1)
6853
6854    # Controller
6855    conf_id = dev[1].dpp_configurator_add()
6856    csrattrs = "MAsGCSqGSIb3DQEJBw=="
6857    dev[1].set("dpp_configurator_params",
6858               "conf=sta-dot1x configurator=%d csrattrs=%s" % (conf_id, csrattrs))
6859    id_c = dev[1].dpp_bootstrap_gen()
6860    uri_c = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id_c)
6861    res = dev[1].request("DPP_BOOTSTRAP_INFO %d" % id_c)
6862    req = "DPP_CONTROLLER_START"
6863    if "OK" not in dev[1].request(req):
6864        raise Exception("Failed to start Controller")
6865
6866    dev[0].dpp_auth_init(uri=uri_c, role="enrollee", tcp_addr="127.0.0.1")
6867    run_dpp_enterprise_tcp_end(params, dev, wt)
6868
6869def run_dpp_enterprise_tcp_end(params, dev, wt):
6870    cert_file = params['prefix'] + ".cert.pem"
6871    pkcs7_file = params['prefix'] + ".pkcs7.der"
6872
6873    with open("auth_serv/ec-ca.pem", "rb") as f:
6874        res = f.read()
6875        cacert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
6876                                                 res)
6877
6878    with open("auth_serv/ec-ca.key", "rb") as f:
6879        res = f.read()
6880        cakey = OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM, res)
6881
6882    ev = dev[1].wait_event(["DPP-CSR"], timeout=10)
6883    if ev is None:
6884        raise Exception("Configurator did not receive CSR")
6885    id1_csr = int(ev.split(' ')[1].split('=')[1])
6886    csr = ev.split(' ')[2]
6887    if not csr.startswith("csr="):
6888        raise Exception("Could not parse CSR event: " + ev)
6889    csr = csr[4:]
6890    csr = base64.b64decode(csr.encode())
6891    logger.info("CSR: " + binascii.hexlify(csr).decode())
6892
6893    cert = dpp_sign_cert(cacert, cakey, csr)
6894    with open(cert_file, 'wb') as f:
6895        f.write(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
6896                                                cert))
6897    subprocess.check_call(['openssl', 'crl2pkcs7', '-nocrl',
6898                           '-certfile', cert_file,
6899                           '-certfile', 'auth_serv/ec-ca.pem',
6900                           '-outform', 'DER', '-out', pkcs7_file])
6901
6902    with open(pkcs7_file, 'rb') as f:
6903        pkcs7_der = f.read()
6904        certbag = base64.b64encode(pkcs7_der).decode()
6905    res = dev[1].request("DPP_CA_SET peer=%d name=certBag value=%s" % (id1_csr, certbag))
6906    if "OK" not in res:
6907        raise Exception("Failed to set certBag")
6908
6909    ev = dev[1].wait_event(["DPP-CONF-SENT", "DPP-CONF-FAILED"], timeout=5)
6910    if ev is None:
6911        raise Exception("DPP configuration not completed (Configurator)")
6912    if "DPP-CONF-FAILED" in ev:
6913        raise Exception("DPP configuration did not succeed (Configurator)")
6914
6915    ev = dev[0].wait_event(["DPP-CONF-RECEIVED", "DPP-CONF-FAILED"],
6916                           timeout=1)
6917    if ev is None:
6918        raise Exception("DPP configuration not completed (Enrollee)")
6919    if "DPP-CONF-RECEIVED" not in ev:
6920        raise Exception("DPP configuration did not succeed (Enrollee)")
6921
6922    time.sleep(0.5)
6923    wt.close()
6924
6925def test_dpp_enterprise_tcp2(dev, apdev, params):
6926    """DPP over TCP for enterprise provisioning (Controller initiating)"""
6927    if not openssl_imported:
6928        raise HwsimSkip("OpenSSL python method not available")
6929
6930    try:
6931        run_dpp_enterprise_tcp2(dev, apdev, params)
6932    finally:
6933        dev[0].request("DPP_CONTROLLER_STOP")
6934        dev[1].request("DPP_CONTROLLER_STOP")
6935
6936def run_dpp_enterprise_tcp2(dev, apdev, params):
6937    check_dpp_capab(dev[0])
6938    check_dpp_capab(dev[1])
6939
6940    cap_lo = params['prefix'] + ".lo.pcap"
6941    cert_file = params['prefix'] + ".cert.pem"
6942    pkcs7_file = params['prefix'] + ".pkcs7.der"
6943
6944    with open("auth_serv/ec-ca.pem", "rb") as f:
6945        res = f.read()
6946        cacert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
6947                                                 res)
6948
6949    with open("auth_serv/ec-ca.key", "rb") as f:
6950        res = f.read()
6951        cakey = OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM, res)
6952
6953    wt = WlantestCapture('lo', cap_lo)
6954    time.sleep(1)
6955
6956    # Client/Enrollee/Responder
6957    id_e = dev[0].dpp_bootstrap_gen()
6958    uri_e = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id_e)
6959    req = "DPP_CONTROLLER_START"
6960    if "OK" not in dev[0].request(req):
6961        raise Exception("Failed to start Client/Enrollee")
6962
6963    # Controller/Configurator/Initiator
6964    conf_id = dev[1].dpp_configurator_add()
6965    csrattrs = "MAsGCSqGSIb3DQEJBw=="
6966    dev[1].dpp_auth_init(uri=uri_e, role="configurator", configurator=conf_id,
6967                         conf="sta-dot1x", csrattrs=csrattrs,
6968                         tcp_addr="127.0.0.1")
6969
6970    run_dpp_enterprise_tcp_end(params, dev, wt)
6971