1# Test cases for sigma_dut
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 binascii
9import errno
10import fcntl
11import hashlib
12import logging
13logger = logging.getLogger()
14import os
15import socket
16import struct
17import subprocess
18import threading
19import time
20
21import hostapd
22from utils import *
23from hwsim import HWSimRadio
24import hwsim_utils
25from wlantest import Wlantest
26from tshark import run_tshark
27from test_dpp import check_dpp_capab, update_hapd_config, wait_auth_success
28from test_suite_b import check_suite_b_192_capa, suite_b_as_params, suite_b_192_rsa_ap_params
29from test_ap_eap import check_eap_capa, int_eap_server_params, check_domain_match, check_domain_suffix_match
30from test_ap_hs20 import hs20_ap_params
31from test_ap_pmf import check_mac80211_bigtk
32from test_ocv import check_ocv_failure
33
34def check_sigma_dut():
35    if not os.path.exists("./sigma_dut"):
36        raise HwsimSkip("sigma_dut not available")
37
38def to_hex(s):
39    return binascii.hexlify(s.encode()).decode()
40
41def from_hex(s):
42    return binascii.unhexlify(s).decode()
43
44class SigmaDut:
45    def __init__(self, ifname=None, hostapd_logdir=None, cert_path=None,
46                 bridge=None, sae_h2e=False, owe_ptk_workaround=False,
47                 dev=None):
48        if ifname:
49            self.ifname = ifname
50        elif dev:
51            self.ifname = dev.ifname
52        else:
53            raise Exception("SigmaDut.__init__() did not receive ifname")
54        self.ap = False
55        self.dev = dev
56        self.start(hostapd_logdir, cert_path, bridge, sae_h2e,
57                   owe_ptk_workaround)
58
59    def __enter__(self):
60        return self
61
62    def __exit__(self, type, value, traceback):
63        if self.ap:
64            self.cmd_check('ap_reset_default')
65
66        if self.dev:
67            self.dev.set("dpp_config_processing", "0", allow_fail=True)
68            self.dev.set("dpp_connector_privacy_default", "0", allow_fail=True)
69            self.dev.set("sae_pwe", "0", allow_fail=True)
70            self.dev.request("VENDOR_ELEM_REMOVE 14 *")
71
72        self.stop()
73
74    def log_output(self):
75        try:
76            out = self.sigma.stdout.read()
77            if out:
78                logger.debug("sigma_dut stdout: " + str(out.decode()))
79        except IOError as e:
80            if e.errno != errno.EAGAIN:
81                raise
82        try:
83            out = self.sigma.stderr.read()
84            if out:
85                logger.debug("sigma_dut stderr: " + str(out.decode()))
86        except IOError as e:
87            if e.errno != errno.EAGAIN:
88                raise
89
90    def run_cmd(self, cmd, port=9000, timeout=2, dump_dev=None):
91        if cmd.startswith('ap_config_commit'):
92            self.ap = True
93        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
94                             socket.IPPROTO_TCP)
95        sock.settimeout(1 if dump_dev else timeout)
96        addr = ('127.0.0.1', port)
97        sock.connect(addr)
98        sock.send(cmd.encode() + b"\r\n")
99        running = False
100        done = False
101        if dump_dev:
102            for i in range(timeout):
103                dump_dev.dump_monitor()
104                try:
105                    res = sock.recv(1000).decode()
106                    for line in res.splitlines():
107                        if line.startswith("status,RUNNING"):
108                            running = True
109                        elif line.startswith("status,INVALID") or \
110                             line.startswith("status,ERROR") or \
111                             line.startswith("status,COMPLETE"):
112                            done = True
113                            res = line
114                            break
115                except socket.timeout as e:
116                    pass
117        if (not dump_dev) or (running and not done):
118            try:
119                res = sock.recv(1000).decode()
120                for line in res.splitlines():
121                    if line.startswith("status,RUNNING"):
122                        running = True
123                    elif line.startswith("status,INVALID") or \
124                         line.startswith("status,ERROR") or \
125                         line.startswith("status,COMPLETE"):
126                        done = True
127                        res = line
128                        break
129                if running and not done:
130                    # Read the actual response
131                    res = sock.recv(1000).decode()
132            except:
133                res = ''
134                pass
135        sock.close()
136        res = res.rstrip()
137        logger.debug("sigma_dut: '%s' --> '%s'" % (cmd, res))
138        self.log_output()
139        return res
140
141    def cmd_check(self, cmd, port=9000, timeout=2):
142        res = self.run_cmd(cmd, port=port, timeout=timeout)
143        if "COMPLETE" not in res:
144            raise Exception("sigma_dut command failed: " + cmd)
145        return res
146
147    def start(self, hostapd_logdir=None, cert_path=None,
148              bridge=None, sae_h2e=False, owe_ptk_workaround=False):
149        ifname = self.ifname
150        check_sigma_dut()
151        cmd = ['./sigma_dut',
152               '-d',
153               '-M', ifname,
154               '-S', ifname,
155               '-F', '../../hostapd/hostapd',
156               '-G',
157               '-w', '/var/run/wpa_supplicant/',
158               '-j', ifname]
159        if hostapd_logdir:
160            cmd += ['-H', hostapd_logdir]
161        if cert_path:
162            cmd += ['-C', cert_path]
163        if bridge:
164            cmd += ['-b', bridge]
165        if sae_h2e:
166            cmd += ['-2']
167        if owe_ptk_workaround:
168            cmd += ['-3']
169        self.sigma = subprocess.Popen(cmd, stdout=subprocess.PIPE,
170                                      stderr=subprocess.PIPE)
171        for stream in [self.sigma.stdout, self.sigma.stderr]:
172            fd = stream.fileno()
173            fl = fcntl.fcntl(fd, fcntl.F_GETFL)
174            fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
175
176        res = None
177        for i in range(20):
178            try:
179                res = self.run_cmd("HELLO")
180                break
181            except IOError as e:
182                if e.errno != errno.ECONNREFUSED:
183                    raise
184                time.sleep(0.05)
185        if res is None or "errorCode,Unknown command" not in res:
186            raise Exception("Failed to start sigma_dut")
187
188    def stop(self):
189        self.log_output()
190        logger.debug("Terminating sigma_dut process")
191        self.sigma.terminate()
192        try:
193            out, err = self.sigma.communicate(timeout=200)
194            logger.debug("sigma_dut stdout: " + str(out.decode()))
195            logger.debug("sigma_dut stderr: " + str(err.decode()))
196        except subprocess.TimeoutExpired:
197            logger.debug("sigma_dut termination timed out")
198            self.sigma.kill()
199            out, err = self.sigma.communicate()
200            logger.debug("sigma_dut stdout: " + str(out.decode()))
201            logger.debug("sigma_dut stderr: " + str(err.decode()))
202
203        subprocess.call(["ip", "addr", "del", "dev", self.ifname,
204                         "127.0.0.11/24"],
205                        stderr=open('/dev/null', 'w'))
206
207    def wait_connected(self):
208        for i in range(50):
209            res = self.run_cmd("sta_is_connected,interface," + self.ifname)
210            if "connected,1" in res:
211                break
212            time.sleep(0.2)
213        else:
214            raise Exception("Connection did not complete")
215
216def test_sigma_dut_basic(dev, apdev):
217    """sigma_dut basic functionality"""
218    tests = [("ca_get_version", "status,COMPLETE,version,1.0"),
219             ("device_get_info", "status,COMPLETE,vendor"),
220             ("device_list_interfaces,interfaceType,foo", "status,ERROR"),
221             ("device_list_interfaces,interfaceType,802.11",
222              "status,COMPLETE,interfaceType,802.11,interfaceID," + dev[0].ifname)]
223
224    with SigmaDut(dev[0].ifname) as dut:
225        res = dut.run_cmd("UNKNOWN")
226        if "status,INVALID,errorCode,Unknown command" not in res:
227            raise Exception("Unexpected sigma_dut response to unknown command")
228
229        for cmd, response in tests:
230            res = dut.run_cmd(cmd)
231            if response not in res:
232                raise Exception("Unexpected %s response: %s" % (cmd, res))
233
234def test_sigma_dut_open(dev, apdev):
235    """sigma_dut controlled open network association"""
236    ifname = dev[0].ifname
237    with SigmaDut(ifname) as dut:
238        hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
239
240        dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
241        dut.cmd_check("sta_set_encryption,interface,%s,ssid,%s,encpType,none" % (ifname, "open"))
242        dut.cmd_check("sta_associate,interface,%s,ssid,%s" % (ifname, "open"),
243                      timeout=10)
244        dut.wait_connected()
245        dut.cmd_check("sta_get_ip_config,interface," + ifname)
246        dut.cmd_check("sta_disconnect,interface," + ifname)
247        dut.cmd_check("sta_reset_default,interface," + ifname)
248
249def test_sigma_dut_psk_pmf(dev, apdev):
250    """sigma_dut controlled PSK+PMF association"""
251    ifname = dev[0].ifname
252    with SigmaDut(ifname) as dut:
253        ssid = "test-pmf-required"
254        params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
255        params["wpa_key_mgmt"] = "WPA-PSK-SHA256"
256        params["ieee80211w"] = "2"
257        hapd = hostapd.add_ap(apdev[0], params)
258
259        dut.cmd_check("sta_reset_default,interface,%s,prog,PMF" % ifname)
260        dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
261        dut.cmd_check("sta_set_psk,interface,%s,ssid,%s,passphrase,%s,encpType,aes-ccmp,keymgmttype,wpa2,PMF,Required" % (ifname, "test-pmf-required", "12345678"))
262        dut.cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-pmf-required"),
263                      timeout=10)
264        dut.wait_connected()
265        dut.cmd_check("sta_get_ip_config,interface," + ifname)
266        dut.cmd_check("sta_disconnect,interface," + ifname)
267        dut.cmd_check("sta_reset_default,interface," + ifname)
268
269def test_sigma_dut_psk_pmf_bip_cmac_128(dev, apdev):
270    """sigma_dut controlled PSK+PMF association with BIP-CMAC-128"""
271    run_sigma_dut_psk_pmf_cipher(dev, apdev, "BIP-CMAC-128", "AES-128-CMAC")
272
273def test_sigma_dut_psk_pmf_bip_cmac_256(dev, apdev):
274    """sigma_dut controlled PSK+PMF association with BIP-CMAC-256"""
275    run_sigma_dut_psk_pmf_cipher(dev, apdev, "BIP-CMAC-256", "BIP-CMAC-256")
276
277def test_sigma_dut_psk_pmf_bip_gmac_128(dev, apdev):
278    """sigma_dut controlled PSK+PMF association with BIP-GMAC-128"""
279    run_sigma_dut_psk_pmf_cipher(dev, apdev, "BIP-GMAC-128", "BIP-GMAC-128")
280
281def test_sigma_dut_psk_pmf_bip_gmac_256(dev, apdev):
282    """sigma_dut controlled PSK+PMF association with BIP-GMAC-256"""
283    run_sigma_dut_psk_pmf_cipher(dev, apdev, "BIP-GMAC-256", "BIP-GMAC-256")
284
285def test_sigma_dut_psk_pmf_bip_gmac_256_mismatch(dev, apdev):
286    """sigma_dut controlled PSK+PMF association with BIP-GMAC-256 mismatch"""
287    run_sigma_dut_psk_pmf_cipher(dev, apdev, "BIP-GMAC-256", "AES-128-CMAC",
288                                 failure=True)
289
290def run_sigma_dut_psk_pmf_cipher(dev, apdev, sigma_cipher, hostapd_cipher,
291                                 failure=False):
292    ifname = dev[0].ifname
293    with SigmaDut(ifname) as dut:
294        ssid = "test-pmf-required"
295        params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
296        params["wpa_key_mgmt"] = "WPA-PSK-SHA256"
297        params["ieee80211w"] = "2"
298        params["group_mgmt_cipher"] = hostapd_cipher
299        hapd = hostapd.add_ap(apdev[0], params)
300
301        dut.cmd_check("sta_reset_default,interface,%s,prog,PMF" % ifname)
302        dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
303        dut.cmd_check("sta_set_psk,interface,%s,ssid,%s,passphrase,%s,encpType,aes-ccmp,keymgmttype,wpa2,PMF,Required,GroupMgntCipher,%s" % (ifname, "test-pmf-required", "12345678", sigma_cipher))
304        dut.cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-pmf-required"),
305                            timeout=2 if failure else 10)
306        if failure:
307            ev = dev[0].wait_event(["CTRL-EVENT-NETWORK-NOT-FOUND",
308                                    "CTRL-EVENT-CONNECTED"], timeout=10)
309            if ev is None:
310                raise Exception("Network selection result not indicated")
311            if "CTRL-EVENT-CONNECTED" in ev:
312                raise Exception("Unexpected connection")
313            res = dut.run_cmd("sta_is_connected,interface," + ifname)
314            if "connected,1" in res:
315                raise Exception("Connection reported")
316        else:
317            dut.wait_connected()
318            dut.cmd_check("sta_get_ip_config,interface," + ifname)
319
320        dut.cmd_check("sta_disconnect,interface," + ifname)
321        dut.cmd_check("sta_reset_default,interface," + ifname)
322
323def test_sigma_dut_sae(dev, apdev):
324    """sigma_dut controlled SAE association"""
325    check_sae_capab(dev[0])
326
327    ifname = dev[0].ifname
328    with SigmaDut(ifname) as dut:
329        ssid = "test-sae"
330        params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
331        params['wpa_key_mgmt'] = 'SAE'
332        params["ieee80211w"] = "2"
333        params['sae_groups'] = '19 20 21'
334        hapd = hostapd.add_ap(apdev[0], params)
335
336        dut.cmd_check("sta_reset_default,interface,%s" % ifname)
337        dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
338        dut.cmd_check("sta_set_security,interface,%s,ssid,%s,passphrase,%s,type,SAE,encpType,aes-ccmp,keymgmttype,wpa2" % (ifname, "test-sae", "12345678"))
339        dut.cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-sae"),
340                      timeout=10)
341        dut.wait_connected()
342        dut.cmd_check("sta_get_ip_config,interface," + ifname)
343        if dev[0].get_status_field('sae_group') != '19':
344            raise Exception("Expected default SAE group not used")
345        res = dut.cmd_check("sta_get_parameter,interface,%s,Parameter,PMK" % ifname)
346        logger.info("Reported PMK: " + res)
347        if ",PMK," not in res:
348            raise Exception("PMK not reported");
349        if hapd.request("GET_PMK " + dev[0].own_addr()) != res.split(',')[3]:
350            raise Exception("Mismatch in reported PMK")
351        dut.cmd_check("sta_disconnect,interface," + ifname)
352
353        dut.cmd_check("sta_reset_default,interface," + ifname)
354
355        dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
356        dut.cmd_check("sta_set_security,interface,%s,ssid,%s,passphrase,%s,type,SAE,encpType,aes-ccmp,keymgmttype,wpa2,ECGroupID,20" % (ifname, "test-sae", "12345678"))
357        dut.cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-sae"),
358                      timeout=10)
359        dut.wait_connected()
360        dut.cmd_check("sta_get_ip_config,interface," + ifname)
361        if dev[0].get_status_field('sae_group') != '20':
362            raise Exception("Expected SAE group not used")
363        dut.cmd_check("sta_disconnect,interface," + ifname)
364        dut.cmd_check("sta_reset_default,interface," + ifname)
365
366def test_sigma_dut_sae_groups(dev, apdev):
367    """sigma_dut controlled SAE association with group negotiation"""
368    check_sae_capab(dev[0])
369
370    ifname = dev[0].ifname
371    with SigmaDut(ifname) as dut:
372        ssid = "test-sae"
373        params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
374        params['wpa_key_mgmt'] = 'SAE'
375        params["ieee80211w"] = "2"
376        params['sae_groups'] = '19'
377        hapd = hostapd.add_ap(apdev[0], params)
378
379        dut.cmd_check("sta_reset_default,interface,%s" % ifname)
380        dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
381        dut.cmd_check("sta_set_security,interface,%s,ssid,%s,passphrase,%s,type,SAE,encpType,aes-ccmp,keymgmttype,wpa2,ECGroupID,21 20 19" % (ifname, "test-sae", "12345678"))
382        dut.cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-sae"),
383                      timeout=10)
384        dut.wait_connected()
385        dut.cmd_check("sta_get_ip_config,interface," + ifname)
386        if dev[0].get_status_field('sae_group') != '19':
387            raise Exception("Expected default SAE group not used")
388        dut.cmd_check("sta_disconnect,interface," + ifname)
389
390        dut.cmd_check("sta_reset_default,interface," + ifname)
391
392def test_sigma_dut_sae_pmkid_include(dev, apdev):
393    """sigma_dut controlled SAE association with PMKID"""
394    check_sae_capab(dev[0])
395
396    ifname = dev[0].ifname
397    with SigmaDut(ifname) as dut:
398        ssid = "test-sae"
399        params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
400        params['wpa_key_mgmt'] = 'SAE'
401        params["ieee80211w"] = "2"
402        params["sae_confirm_immediate"] = "1"
403        hapd = hostapd.add_ap(apdev[0], params)
404
405        dut.cmd_check("sta_reset_default,interface,%s" % ifname)
406        dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
407        dut.cmd_check("sta_set_security,interface,%s,ssid,%s,passphrase,%s,type,SAE,encpType,aes-ccmp,keymgmttype,wpa2,PMKID_Include,enable" % (ifname, "test-sae", "12345678"))
408        dut.cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-sae"),
409                      timeout=10)
410        dut.wait_connected()
411        dut.cmd_check("sta_reset_default,interface," + ifname)
412
413def test_sigma_dut_sae_password(dev, apdev):
414    """sigma_dut controlled SAE association and long password"""
415    check_sae_capab(dev[0])
416
417    ifname = dev[0].ifname
418    with SigmaDut(ifname) as dut:
419        ssid = "test-sae"
420        params = hostapd.wpa2_params(ssid=ssid)
421        params['sae_password'] = 100*'B'
422        params['wpa_key_mgmt'] = 'SAE'
423        params["ieee80211w"] = "2"
424        hapd = hostapd.add_ap(apdev[0], params)
425
426        dut.cmd_check("sta_reset_default,interface,%s" % ifname)
427        dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
428        dut.cmd_check("sta_set_security,interface,%s,ssid,%s,passphrase,%s,type,SAE,encpType,aes-ccmp,keymgmttype,wpa2" % (ifname, "test-sae", 100*'B'))
429        dut.cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-sae"),
430                      timeout=10)
431        dut.wait_connected()
432        dut.cmd_check("sta_get_ip_config,interface," + ifname)
433        dut.cmd_check("sta_disconnect,interface," + ifname)
434        dut.cmd_check("sta_reset_default,interface," + ifname)
435
436def test_sigma_dut_sae_pw_id(dev, apdev):
437    """sigma_dut controlled SAE association with Password Identifier"""
438    check_sae_capab(dev[0])
439
440    ifname = dev[0].ifname
441    with SigmaDut(ifname) as dut:
442        ssid = "test-sae"
443        params = hostapd.wpa2_params(ssid=ssid)
444        params['wpa_key_mgmt'] = 'SAE'
445        params["ieee80211w"] = "2"
446        params['sae_password'] = 'secret|id=pw id'
447        params['sae_groups'] = '19'
448        hapd = hostapd.add_ap(apdev[0], params)
449
450        dut.cmd_check("sta_reset_default,interface,%s" % ifname)
451        dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
452        dut.cmd_check("sta_set_security,interface,%s,ssid,%s,passphrase,%s,type,SAE,encpType,aes-ccmp,AKMSuiteType,8;9,PasswordID,pw id" % (ifname, "test-sae", "secret"))
453        dut.cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-sae"),
454                      timeout=10)
455        dut.wait_connected()
456        dut.cmd_check("sta_disconnect,interface," + ifname)
457        dut.cmd_check("sta_reset_default,interface," + ifname)
458
459def test_sigma_dut_sae_pw_id_pwe_loop(dev, apdev):
460    """sigma_dut controlled SAE association with Password Identifier and forced PWE looping"""
461    check_sae_capab(dev[0])
462
463    ifname = dev[0].ifname
464    with SigmaDut(dev=dev[0]) as dut:
465        ssid = "test-sae"
466        params = hostapd.wpa2_params(ssid=ssid)
467        params['wpa_key_mgmt'] = 'SAE'
468        params["ieee80211w"] = "2"
469        params['sae_password'] = 'secret|id=pw id'
470        params['sae_groups'] = '19'
471        hapd = hostapd.add_ap(apdev[0], params)
472
473        dut.cmd_check("sta_reset_default,interface,%s" % ifname)
474        dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
475        dut.cmd_check("sta_set_security,interface,%s,ssid,%s,passphrase,%s,type,SAE,encpType,aes-ccmp,AKMSuiteType,8;9,PasswordID,pw id,sae_pwe,looping" % (ifname, "test-sae", "secret"))
476        dut.cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-sae"),
477                      timeout=10)
478        for i in range(3):
479            ev = dev[0].wait_event(["SME: Trying to authenticate",
480                                    "CTRL-EVENT-CONNECTED"], timeout=10)
481            if ev is None:
482                raise Exception("Network selection result not indicated")
483            if "CTRL-EVENT-CONNECTED" in ev:
484                raise Exception("Unexpected connection")
485        res = dut.run_cmd("sta_is_connected,interface," + ifname)
486        if "connected,1" in res:
487            raise Exception("Connection reported")
488        dut.cmd_check("sta_reset_default,interface," + ifname)
489
490def test_sigma_dut_sae_pw_id_ft(dev, apdev):
491    """sigma_dut controlled SAE association with Password Identifier and FT"""
492    run_sigma_dut_sae_pw_id_ft(dev, apdev)
493
494def test_sigma_dut_sae_pw_id_ft_over_ds(dev, apdev):
495    """sigma_dut controlled SAE association with Password Identifier and FT-over-DS"""
496    run_sigma_dut_sae_pw_id_ft(dev, apdev, over_ds=True)
497
498def run_sigma_dut_sae_pw_id_ft(dev, apdev, over_ds=False):
499    check_sae_capab(dev[0])
500
501    ifname = dev[0].ifname
502    with SigmaDut(ifname) as dut:
503        ssid = "test-sae"
504        params = hostapd.wpa2_params(ssid=ssid)
505        params['wpa_key_mgmt'] = 'SAE FT-SAE'
506        params["ieee80211w"] = "2"
507        params['sae_password'] = ['pw1|id=id1', 'pw2|id=id2', 'pw3', 'pw4|id=id4']
508        params['mobility_domain'] = 'aabb'
509        params['ft_over_ds'] = '1' if over_ds else '0'
510        bssid = apdev[0]['bssid'].replace(':', '')
511        params['nas_identifier'] = bssid + '.nas.example.com'
512        params['r1_key_holder'] = bssid
513        params['pmk_r1_push'] = '0'
514        params['r0kh'] = 'ff:ff:ff:ff:ff:ff * 00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff'
515        params['r1kh'] = '00:00:00:00:00:00 00:00:00:00:00:00 00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff'
516        hapd = hostapd.add_ap(apdev[0], params)
517
518        dut.cmd_check("sta_reset_default,interface,%s" % ifname)
519        if over_ds:
520            dut.cmd_check("sta_preset_testparameters,interface,%s,FT_DS,Enable" % ifname)
521        dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
522        dut.cmd_check("sta_set_security,interface,%s,ssid,%s,passphrase,%s,type,SAE,encpType,aes-ccmp,AKMSuiteType,8;9,PasswordID,id2" % (ifname, "test-sae", "pw2"))
523        dut.cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-sae"),
524                      timeout=10)
525        dut.wait_connected()
526
527        bssid = apdev[1]['bssid'].replace(':', '')
528        params['nas_identifier'] = bssid + '.nas.example.com'
529        params['r1_key_holder'] = bssid
530        hapd2 = hostapd.add_ap(apdev[1], params)
531        bssid = hapd2.own_addr()
532        dut.cmd_check("sta_reassoc,interface,%s,Channel,1,bssid,%s" % (ifname, bssid),
533                      timeout=20)
534        dev[0].wait_connected()
535
536        dut.cmd_check("sta_disconnect,interface," + ifname)
537        dut.cmd_check("sta_reset_default,interface," + ifname)
538
539def test_sigma_dut_sta_override_rsne(dev, apdev):
540    """sigma_dut and RSNE override on STA"""
541    ifname = dev[0].ifname
542    with SigmaDut(ifname) as dut:
543        ssid = "test-psk"
544        params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
545        hapd = hostapd.add_ap(apdev[0], params)
546
547        dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
548
549        tests = ["30120100000fac040100000fac040100000fac02",
550                 "30140100000fac040100000fac040100000fac02ffff"]
551        for test in tests:
552            dut.cmd_check("sta_set_security,interface,%s,ssid,%s,type,PSK,passphrase,%s,EncpType,aes-ccmp,KeyMgmtType,wpa2" % (ifname, "test-psk", "12345678"))
553            dut.cmd_check("dev_configure_ie,interface,%s,IE_Name,RSNE,Contents,%s" % (ifname, test))
554            dut.cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-psk"),
555                          timeout=10)
556            dut.wait_connected()
557            dut.cmd_check("sta_disconnect,interface," + ifname)
558            dev[0].dump_monitor()
559
560        dut.cmd_check("sta_set_security,interface,%s,ssid,%s,type,PSK,passphrase,%s,EncpType,aes-ccmp,KeyMgmtType,wpa2" % (ifname, "test-psk", "12345678"))
561        dut.cmd_check("dev_configure_ie,interface,%s,IE_Name,RSNE,Contents,300101" % ifname)
562        dut.cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-psk"),
563                      timeout=10)
564
565        ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"])
566        if ev is None:
567            raise Exception("Association rejection not reported")
568        if "status_code=40" not in ev:
569            raise Exception("Unexpected status code: " + ev)
570
571        dut.cmd_check("sta_reset_default,interface," + ifname)
572
573def test_sigma_dut_ap_psk(dev, apdev):
574    """sigma_dut controlled AP"""
575    with HWSimRadio() as (radio, iface), SigmaDut(iface) as dut:
576        dut.cmd_check("ap_reset_default")
577        dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-psk,MODE,11ng")
578        dut.cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-PSK,PSK,12345678")
579        dut.cmd_check("ap_config_commit,NAME,AP")
580
581        dev[0].connect("test-psk", psk="12345678", scan_freq="2412")
582
583def test_sigma_dut_ap_pskhex(dev, apdev, params):
584    """sigma_dut controlled AP and PSKHEX"""
585    logdir = os.path.join(params['logdir'],
586                          "sigma_dut_ap_pskhex.sigma-hostapd")
587    with HWSimRadio() as (radio, iface), \
588         SigmaDut(iface, hostapd_logdir=logdir) as dut:
589        psk = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
590        dut.cmd_check("ap_reset_default")
591        dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-psk,MODE,11ng")
592        dut.cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-PSK,PSKHEX," + psk)
593        dut.cmd_check("ap_config_commit,NAME,AP")
594
595        dev[0].connect("test-psk", raw_psk=psk, scan_freq="2412")
596
597def test_sigma_dut_ap_psk_sha256(dev, apdev, params):
598    """sigma_dut controlled AP PSK SHA256"""
599    logdir = os.path.join(params['logdir'],
600                          "sigma_dut_ap_psk_sha256.sigma-hostapd")
601    with HWSimRadio() as (radio, iface), \
602         SigmaDut(iface, hostapd_logdir=logdir) as dut:
603        dut.cmd_check("ap_reset_default")
604        dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-psk,MODE,11ng")
605        dut.cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-PSK-256,PSK,12345678")
606        dut.cmd_check("ap_config_commit,NAME,AP")
607
608        dev[0].connect("test-psk", key_mgmt="WPA-PSK-SHA256",
609                       psk="12345678", scan_freq="2412")
610
611def test_sigma_dut_ap_psk_deauth(dev, apdev, params):
612    """sigma_dut controlled AP and deauth commands"""
613    logdir = os.path.join(params['logdir'],
614                          "sigma_dut_ap_psk_deauth.sigma-hostapd")
615    with HWSimRadio() as (radio, iface), \
616         SigmaDut(iface, hostapd_logdir=logdir) as dut:
617        dut.cmd_check("ap_reset_default")
618        dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-psk,MODE,11ng")
619        dut.cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-PSK,PSK,12345678,PMF,Required")
620        dut.cmd_check("ap_config_commit,NAME,AP")
621
622        dev[0].connect("test-psk", key_mgmt="WPA-PSK-SHA256",
623                       psk="12345678", ieee80211w="2", scan_freq="2412")
624        addr = dev[0].own_addr()
625        dev[0].dump_monitor()
626
627        dut.cmd_check("ap_deauth_sta,NAME,AP,sta_mac_address," + addr)
628        ev = dev[0].wait_disconnected()
629        dev[0].dump_monitor()
630        if "locally_generated=1" in ev:
631            raise Exception("Unexpected disconnection reason")
632        dev[0].wait_connected()
633        dev[0].dump_monitor()
634
635        dut.cmd_check("ap_deauth_sta,NAME,AP,sta_mac_address," + addr + ",disconnect,silent")
636        ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=5)
637        if ev and "locally_generated=1" not in ev:
638            raise Exception("Unexpected disconnection")
639
640def test_sigma_dut_eap_ttls(dev, apdev, params):
641    """sigma_dut controlled STA and EAP-TTLS parameters"""
642    check_domain_match(dev[0])
643    logdir = params['logdir']
644
645    with open("auth_serv/ca.pem", "r") as f:
646        with open(os.path.join(logdir, "sigma_dut_eap_ttls.ca.pem"), "w") as f2:
647            f2.write(f.read())
648
649    src = "auth_serv/server.pem"
650    dst = os.path.join(logdir, "sigma_dut_eap_ttls.server.der")
651    hashdst = os.path.join(logdir, "sigma_dut_eap_ttls.server.pem.sha256")
652    subprocess.check_call(["openssl", "x509", "-in", src, "-out", dst,
653                           "-outform", "DER"],
654                          stderr=open('/dev/null', 'w'))
655    with open(dst, "rb") as f:
656        der = f.read()
657    hash = hashlib.sha256(der).digest()
658    with open(hashdst, "w") as f:
659        f.write(binascii.hexlify(hash).decode())
660
661    dst = os.path.join(logdir, "sigma_dut_eap_ttls.incorrect.pem.sha256")
662    with open(dst, "w") as f:
663        f.write(32*"00")
664
665    ssid = "test-wpa2-eap"
666    params = hostapd.wpa2_eap_params(ssid=ssid)
667    hapd = hostapd.add_ap(apdev[0], params)
668
669    ifname = dev[0].ifname
670    with SigmaDut(ifname, cert_path=logdir) as dut:
671        cmd = "sta_set_security,type,eapttls,interface,%s,ssid,%s,keymgmttype,wpa2,encType,AES-CCMP,PairwiseCipher,AES-CCMP-128,trustedRootCA,sigma_dut_eap_ttls.ca.pem,username,DOMAIN\mschapv2 user,password,password" % (ifname, ssid)
672
673        tests = ["",
674                 ",Domain,server.w1.fi",
675                 ",DomainSuffix,w1.fi",
676                 ",DomainSuffix,server.w1.fi",
677                 ",ServerCert,sigma_dut_eap_ttls.server.pem"]
678        for extra in tests:
679            dut.cmd_check("sta_reset_default,interface,%s,prog,WPA3" % ifname)
680            dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
681            dut.cmd_check(cmd + extra)
682            dut.cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, ssid),
683                                timeout=10)
684            dut.wait_connected()
685            dut.cmd_check("sta_get_ip_config,interface," + ifname)
686            dut.cmd_check("sta_disconnect,interface," + ifname)
687            dut.cmd_check("sta_reset_default,interface," + ifname)
688            dev[0].dump_monitor()
689
690        tests = [",Domain,w1.fi",
691                 ",DomainSuffix,example.com",
692                 ",ServerCert,sigma_dut_eap_ttls.incorrect.pem"]
693        for extra in tests:
694            dut.cmd_check("sta_reset_default,interface,%s,prog,WPA3" % ifname)
695            dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
696            dut.cmd_check(cmd + extra)
697            dut.cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, ssid),
698                                timeout=10)
699            ev = dev[0].wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR"], timeout=10)
700            if ev is None:
701                raise Exception("Server certificate error not reported")
702            res = dut.run_cmd("sta_is_connected,interface," + ifname)
703            if "connected,1" in res:
704                raise Exception("Unexpected connection reported")
705            dut.cmd_check("sta_disconnect,interface," + ifname)
706            dut.cmd_check("sta_reset_default,interface," + ifname)
707            dev[0].dump_monitor()
708
709def test_sigma_dut_suite_b(dev, apdev, params):
710    """sigma_dut controlled STA Suite B"""
711    check_suite_b_192_capa(dev)
712    logdir = params['logdir']
713
714    with open("auth_serv/ec2-ca.pem", "r") as f, \
715         open(os.path.join(logdir, "suite_b_ca.pem"), "w") as f2:
716        f2.write(f.read())
717
718    with open("auth_serv/ec2-user.pem", "r") as f, \
719         open("auth_serv/ec2-user.key", "r") as f2, \
720         open(os.path.join(logdir, "suite_b.pem"), "w") as f3:
721        f3.write(f.read())
722        f3.write(f2.read())
723
724    dev[0].flush_scan_cache()
725    params = suite_b_as_params()
726    params['ca_cert'] = 'auth_serv/ec2-ca.pem'
727    params['server_cert'] = 'auth_serv/ec2-server.pem'
728    params['private_key'] = 'auth_serv/ec2-server.key'
729    params['openssl_ciphers'] = 'SUITEB192'
730    hostapd.add_ap(apdev[1], params)
731
732    params = {"ssid": "test-suite-b",
733              "wpa": "2",
734              "wpa_key_mgmt": "WPA-EAP-SUITE-B-192",
735              "rsn_pairwise": "GCMP-256",
736              "group_mgmt_cipher": "BIP-GMAC-256",
737              "ieee80211w": "2",
738              "ieee8021x": "1",
739              'auth_server_addr': "127.0.0.1",
740              'auth_server_port': "18129",
741              'auth_server_shared_secret': "radius",
742              'nas_identifier': "nas.w1.fi"}
743    hapd = hostapd.add_ap(apdev[0], params)
744
745    ifname = dev[0].ifname
746    with SigmaDut(ifname, cert_path=logdir) as dut:
747        dut.cmd_check("sta_reset_default,interface,%s,prog,PMF" % ifname)
748        dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
749        dut.cmd_check("sta_set_security,type,eaptls,interface,%s,ssid,%s,PairwiseCipher,AES-GCMP-256,GroupCipher,AES-GCMP-256,GroupMgntCipher,BIP-GMAC-256,keymgmttype,SuiteB,clientCertificate,suite_b.pem,trustedRootCA,suite_b_ca.pem,CertType,ECC" % (ifname, "test-suite-b"))
750        dut.cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-suite-b"),
751                            timeout=10)
752        dut.wait_connected()
753        dut.cmd_check("sta_get_ip_config,interface," + ifname)
754        dut.cmd_check("sta_disconnect,interface," + ifname)
755        dut.cmd_check("sta_reset_default,interface," + ifname)
756
757def test_sigma_dut_suite_b_rsa(dev, apdev, params):
758    """sigma_dut controlled STA Suite B (RSA)"""
759    check_suite_b_192_capa(dev)
760    logdir = params['logdir']
761
762    with open("auth_serv/rsa3072-ca.pem", "r") as f, \
763         open(os.path.join(logdir, "suite_b_ca_rsa.pem"), "w") as f2:
764        f2.write(f.read())
765
766    with open("auth_serv/rsa3072-user.pem", "r") as f, \
767         open("auth_serv/rsa3072-user.key", "r") as f2, \
768         open(os.path.join(logdir, "suite_b_rsa.pem"), "w") as f3:
769        f3.write(f.read())
770        f3.write(f2.read())
771
772    dev[0].flush_scan_cache()
773    params = suite_b_192_rsa_ap_params()
774    hapd = hostapd.add_ap(apdev[0], params)
775
776    ifname = dev[0].ifname
777    with SigmaDut(ifname, cert_path=logdir) as dut:
778        cmd = "sta_set_security,type,eaptls,interface,%s,ssid,%s,PairwiseCipher,AES-GCMP-256,GroupCipher,AES-GCMP-256,GroupMgntCipher,BIP-GMAC-256,keymgmttype,SuiteB,clientCertificate,suite_b_rsa.pem,trustedRootCA,suite_b_ca_rsa.pem,CertType,RSA" % (ifname, "test-suite-b")
779
780        tests = ["",
781                 ",TLSCipher,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"]
782        tls = dev[0].request("GET tls_library")
783        if "run=BoringSSL" not in tls:
784            tests += [",TLSCipher,TLS_DHE_RSA_WITH_AES_256_GCM_SHA384"]
785        for extra in tests:
786            dut.cmd_check("sta_reset_default,interface,%s,prog,PMF" % ifname)
787            dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
788            dut.cmd_check(cmd + extra)
789            dut.cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-suite-b"),
790                                timeout=10)
791            dev[0].dump_monitor()
792            dut.wait_connected()
793            dev[0].dump_monitor()
794            dut.cmd_check("sta_get_ip_config,interface," + ifname)
795            dut.cmd_check("sta_disconnect,interface," + ifname)
796            dut.cmd_check("sta_reset_default,interface," + ifname)
797            dev[0].dump_monitor()
798
799def test_sigma_dut_ap_suite_b(dev, apdev, params):
800    """sigma_dut controlled AP Suite B"""
801    check_suite_b_192_capa(dev)
802    logdir = os.path.join(params['logdir'],
803                          "sigma_dut_ap_suite_b.sigma-hostapd")
804    params = suite_b_as_params()
805    params['ca_cert'] = 'auth_serv/ec2-ca.pem'
806    params['server_cert'] = 'auth_serv/ec2-server.pem'
807    params['private_key'] = 'auth_serv/ec2-server.key'
808    params['openssl_ciphers'] = 'SUITEB192'
809    hostapd.add_ap(apdev[1], params)
810    with HWSimRadio() as (radio, iface), \
811         SigmaDut(iface, hostapd_logdir=logdir) as dut:
812        dut.cmd_check("ap_reset_default")
813        dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-suite-b,MODE,11ng")
814        dut.cmd_check("ap_set_radius,NAME,AP,IPADDR,127.0.0.1,PORT,18129,PASSWORD,radius")
815        dut.cmd_check("ap_set_security,NAME,AP,KEYMGNT,SuiteB")
816        dut.cmd_check("ap_config_commit,NAME,AP")
817
818        dev[0].connect("test-suite-b", key_mgmt="WPA-EAP-SUITE-B-192",
819                       ieee80211w="2",
820                       openssl_ciphers="SUITEB192",
821                       eap="TLS", identity="tls user",
822                       ca_cert="auth_serv/ec2-ca.pem",
823                       client_cert="auth_serv/ec2-user.pem",
824                       private_key="auth_serv/ec2-user.key",
825                       pairwise="GCMP-256", group="GCMP-256",
826                       scan_freq="2412")
827
828def test_sigma_dut_ap_cipher_gcmp_128(dev, apdev, params):
829    """sigma_dut controlled AP with GCMP-128/BIP-GMAC-128 cipher"""
830    run_sigma_dut_ap_cipher(dev, apdev, params, "AES-GCMP-128", "BIP-GMAC-128",
831                            "GCMP")
832
833def test_sigma_dut_ap_cipher_gcmp_256(dev, apdev, params):
834    """sigma_dut controlled AP with GCMP-256/BIP-GMAC-256 cipher"""
835    run_sigma_dut_ap_cipher(dev, apdev, params, "AES-GCMP-256", "BIP-GMAC-256",
836                            "GCMP-256")
837
838def test_sigma_dut_ap_cipher_ccmp_128(dev, apdev, params):
839    """sigma_dut controlled AP with CCMP-128/BIP-CMAC-128 cipher"""
840    run_sigma_dut_ap_cipher(dev, apdev, params, "AES-CCMP-128", "BIP-CMAC-128",
841                            "CCMP")
842
843def test_sigma_dut_ap_cipher_ccmp_256(dev, apdev, params):
844    """sigma_dut controlled AP with CCMP-256/BIP-CMAC-256 cipher"""
845    run_sigma_dut_ap_cipher(dev, apdev, params, "AES-CCMP-256", "BIP-CMAC-256",
846                            "CCMP-256")
847
848def test_sigma_dut_ap_cipher_ccmp_gcmp_1(dev, apdev, params):
849    """sigma_dut controlled AP with CCMP-128+GCMP-256 ciphers (1)"""
850    run_sigma_dut_ap_cipher(dev, apdev, params, "AES-CCMP-128 AES-GCMP-256",
851                            "BIP-GMAC-256", "CCMP")
852
853def test_sigma_dut_ap_cipher_ccmp_gcmp_2(dev, apdev, params):
854    """sigma_dut controlled AP with CCMP-128+GCMP-256 ciphers (2)"""
855    run_sigma_dut_ap_cipher(dev, apdev, params, "AES-CCMP-128 AES-GCMP-256",
856                            "BIP-GMAC-256", "GCMP-256", "CCMP")
857
858def test_sigma_dut_ap_cipher_gcmp_256_group_ccmp(dev, apdev, params):
859    """sigma_dut controlled AP with GCMP-256/CCMP/BIP-GMAC-256 cipher"""
860    run_sigma_dut_ap_cipher(dev, apdev, params, "AES-GCMP-256", "BIP-GMAC-256",
861                            "GCMP-256", "CCMP", "AES-CCMP-128")
862
863def run_sigma_dut_ap_cipher(dev, apdev, params, ap_pairwise, ap_group_mgmt,
864                            sta_cipher, sta_cipher_group=None, ap_group=None):
865    check_suite_b_192_capa(dev)
866    logdir = os.path.join(params['logdir'],
867                          "sigma_dut_ap_cipher.sigma-hostapd")
868    params = suite_b_as_params()
869    params['ca_cert'] = 'auth_serv/ec2-ca.pem'
870    params['server_cert'] = 'auth_serv/ec2-server.pem'
871    params['private_key'] = 'auth_serv/ec2-server.key'
872    params['openssl_ciphers'] = 'SUITEB192'
873    hostapd.add_ap(apdev[1], params)
874    with HWSimRadio() as (radio, iface), \
875         SigmaDut(iface, hostapd_logdir=logdir) as dut:
876        dut.cmd_check("ap_reset_default")
877        dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-suite-b,MODE,11ng")
878        dut.cmd_check("ap_set_radius,NAME,AP,IPADDR,127.0.0.1,PORT,18129,PASSWORD,radius")
879        cmd = "ap_set_security,NAME,AP,KEYMGNT,SuiteB,PMF,Required,PairwiseCipher,%s,GroupMgntCipher,%s" % (ap_pairwise, ap_group_mgmt)
880        if ap_group:
881            cmd += ",GroupCipher,%s" % ap_group
882        dut.cmd_check(cmd)
883        dut.cmd_check("ap_config_commit,NAME,AP")
884
885        if sta_cipher_group is None:
886            sta_cipher_group = sta_cipher
887        dev[0].connect("test-suite-b", key_mgmt="WPA-EAP-SUITE-B-192",
888                       ieee80211w="2",
889                       openssl_ciphers="SUITEB192",
890                       eap="TLS", identity="tls user",
891                       ca_cert="auth_serv/ec2-ca.pem",
892                       client_cert="auth_serv/ec2-user.pem",
893                       private_key="auth_serv/ec2-user.key",
894                       pairwise=sta_cipher, group=sta_cipher_group,
895                       scan_freq="2412")
896
897def test_sigma_dut_ap_override_rsne(dev, apdev, params):
898    """sigma_dut controlled AP overriding RSNE"""
899    logdir = params['prefix'] + ".sigma-hostapd"
900    with HWSimRadio() as (radio, iface), \
901         SigmaDut(iface, hostapd_logdir=logdir) as dut:
902        dut.cmd_check("ap_reset_default")
903        dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-psk,MODE,11ng")
904        dut.cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-PSK,PSK,12345678")
905        dut.cmd_check("dev_configure_ie,NAME,AP,interface,%s,IE_Name,RSNE,Contents,30180100000fac040200ffffffff000fac040100000fac020c00" % iface)
906        dut.cmd_check("ap_config_commit,NAME,AP")
907
908        dev[0].connect("test-psk", psk="12345678", scan_freq="2412")
909
910def test_sigma_dut_ap_sae(dev, apdev, params):
911    """sigma_dut controlled AP with SAE"""
912    logdir = os.path.join(params['logdir'],
913                          "sigma_dut_ap_sae.sigma-hostapd")
914    check_sae_capab(dev[0])
915    with HWSimRadio() as (radio, iface), \
916         SigmaDut(iface, hostapd_logdir=logdir) as dut:
917        dut.cmd_check("ap_reset_default")
918        dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-sae,MODE,11ng")
919        dut.cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-SAE,PSK,12345678")
920        dut.cmd_check("ap_config_commit,NAME,AP")
921
922        dev[0].request("SET sae_groups ")
923        id = dev[0].connect("test-sae", key_mgmt="SAE", psk="12345678",
924                            ieee80211w="2", scan_freq="2412")
925        if dev[0].get_status_field('sae_group') != '19':
926            raise Exception("Expected default SAE group not used")
927
928        res = dut.cmd_check("ap_get_parameter,name,AP,STA_MAC_Address,%s,Parameter,PMK" % dev[0].own_addr())
929        logger.info("Reported PMK: " + res)
930        if ",PMK," not in res:
931            raise Exception("PMK not reported");
932        if dev[0].get_pmk(id) != res.split(',')[3]:
933            raise Exception("Mismatch in reported PMK")
934
935def test_sigma_dut_ap_sae_confirm_immediate(dev, apdev, params):
936    """sigma_dut controlled AP with SAE Confirm immediate"""
937    logdir = os.path.join(params['logdir'],
938                          "sigma_dut_ap_sae_confirm_immediate.sigma-hostapd")
939    check_sae_capab(dev[0])
940    with HWSimRadio() as (radio, iface), \
941         SigmaDut(iface, hostapd_logdir=logdir) as dut:
942        dut.cmd_check("ap_reset_default")
943        dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-sae,MODE,11ng")
944        dut.cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-SAE,PSK,12345678,SAE_Confirm_Immediate,enable")
945        dut.cmd_check("ap_config_commit,NAME,AP")
946
947        dev[0].request("SET sae_groups ")
948        dev[0].connect("test-sae", key_mgmt="SAE", psk="12345678",
949                       ieee80211w="2", scan_freq="2412")
950        if dev[0].get_status_field('sae_group') != '19':
951            raise Exception("Expected default SAE group not used")
952
953def test_sigma_dut_ap_sae_password(dev, apdev, params):
954    """sigma_dut controlled AP with SAE and long password"""
955    logdir = os.path.join(params['logdir'],
956                          "sigma_dut_ap_sae_password.sigma-hostapd")
957    check_sae_capab(dev[0])
958    with HWSimRadio() as (radio, iface), \
959         SigmaDut(iface, hostapd_logdir=logdir) as dut:
960        dut.cmd_check("ap_reset_default")
961        dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-sae,MODE,11ng")
962        dut.cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-SAE,PSK," + 100*'C')
963        dut.cmd_check("ap_config_commit,NAME,AP")
964
965        dev[0].request("SET sae_groups ")
966        dev[0].connect("test-sae", key_mgmt="SAE", sae_password=100*'C',
967                       ieee80211w="2", scan_freq="2412")
968        if dev[0].get_status_field('sae_group') != '19':
969            raise Exception("Expected default SAE group not used")
970
971def test_sigma_dut_ap_sae_pw_id(dev, apdev, params):
972    """sigma_dut controlled AP with SAE Password Identifier"""
973    logdir = os.path.join(params['logdir'],
974                          "sigma_dut_ap_sae_pw_id.sigma-hostapd")
975    conffile = os.path.join(params['logdir'],
976                            "sigma_dut_ap_sae_pw_id.sigma-conf")
977    check_sae_capab(dev[0])
978    with HWSimRadio() as (radio, iface), \
979         SigmaDut(iface, hostapd_logdir=logdir) as dut:
980        dut.cmd_check("ap_reset_default")
981        dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-sae,MODE,11ng")
982        dut.cmd_check("ap_set_security,NAME,AP,AKMSuiteType,8,SAEPasswords,pw1:id1;pw2:id2;pw3;pw4:id4,PMF,Required")
983        dut.cmd_check("ap_config_commit,NAME,AP")
984
985        with open("/tmp/sigma_dut-ap.conf", "rb") as f, \
986             open(conffile, "wb") as f2:
987            f2.write(f.read())
988
989        dev[0].request("SET sae_groups ")
990        tests = [("pw1", "id1"),
991                 ("pw2", "id2"),
992                 ("pw3", None),
993                 ("pw4", "id4")]
994        for pw, pw_id in tests:
995            dev[0].connect("test-sae", key_mgmt="SAE", sae_password=pw,
996                           sae_password_id=pw_id,
997                           ieee80211w="2", scan_freq="2412")
998            # Allow some time for AP to complete handling of connection
999            # before disconnecting.
1000            time.sleep(0.1)
1001            dev[0].request("REMOVE_NETWORK all")
1002            dev[0].wait_disconnected()
1003            # Allow some time for AP to complete handling of disconnection
1004            # before trying SAE again.
1005            time.sleep(0.1)
1006
1007def test_sigma_dut_ap_sae_pw_id_pwe_loop(dev, apdev, params):
1008    """sigma_dut controlled AP with SAE Password Identifier and forced PWE looping"""
1009    logdir = os.path.join(params['logdir'],
1010                          "sigma_dut_ap_sae_pw_id_pwe_loop.sigma-hostapd")
1011    conffile = os.path.join(params['logdir'],
1012                            "sigma_dut_ap_sae_pw_id_pwe_loop.sigma-conf")
1013    check_sae_capab(dev[0])
1014    with HWSimRadio() as (radio, iface), \
1015         SigmaDut(iface, hostapd_logdir=logdir) as dut:
1016        dut.cmd_check("ap_reset_default")
1017        dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-sae,MODE,11ng")
1018        dut.cmd_check("ap_set_security,NAME,AP,AKMSuiteType,8,SAEPasswords,12345678:pwid,PMF,Required,sae_pwe,looping")
1019        dut.cmd_check("ap_config_commit,NAME,AP")
1020
1021        with open("/tmp/sigma_dut-ap.conf", "rb") as f, \
1022             open(conffile, "wb") as f2:
1023            f2.write(f.read())
1024
1025        dev[0].set("sae_groups", "")
1026        dev[0].connect("test-sae", key_mgmt="SAE", sae_password="12345678",
1027                       sae_password_id="pwid",
1028                       ieee80211w="2", scan_freq="2412", wait_connect=False)
1029        ev = dev[0].wait_event(["CTRL-EVENT-NETWORK-NOT-FOUND",
1030                                "CTRL-EVENT-CONNECTED"], timeout=10)
1031        if ev is None:
1032            raise Exception("Network selection result not indicated")
1033        if "CTRL-EVENT-CONNECTED" in ev:
1034            raise Exception("Unexpected connection")
1035        dev[0].request("REMOVE_NETWORK all")
1036
1037def test_sigma_dut_ap_sae_pw_id_ft(dev, apdev, params):
1038    """sigma_dut controlled AP with SAE Password Identifier and FT"""
1039    logdir = os.path.join(params['logdir'],
1040                          "sigma_dut_ap_sae_pw_id_ft.sigma-hostapd")
1041    conffile = os.path.join(params['logdir'],
1042                            "sigma_dut_ap_sae_pw_id_ft.sigma-conf")
1043    check_sae_capab(dev[0])
1044    with HWSimRadio() as (radio, iface), \
1045         SigmaDut(iface, hostapd_logdir=logdir) as dut:
1046        dut.cmd_check("ap_reset_default")
1047        dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-sae,MODE,11ng,DOMAIN,aabb")
1048        dut.cmd_check("ap_set_security,NAME,AP,AKMSuiteType,8;9,SAEPasswords,pw1:id1;pw2:id2;pw3;pw4:id4,PMF,Required")
1049        dut.cmd_check("ap_config_commit,NAME,AP")
1050
1051        with open("/tmp/sigma_dut-ap.conf", "rb") as f, \
1052             open(conffile, "wb") as f2:
1053            f2.write(f.read())
1054
1055        dev[0].request("SET sae_groups ")
1056        tests = [("pw1", "id1", "SAE"),
1057                 ("pw2", "id2", "FT-SAE"),
1058                 ("pw3", None, "FT-SAE"),
1059                 ("pw4", "id4", "SAE")]
1060        for pw, pw_id, key_mgmt in tests:
1061            dev[0].connect("test-sae", key_mgmt=key_mgmt, sae_password=pw,
1062                           sae_password_id=pw_id,
1063                           ieee80211w="2", scan_freq="2412")
1064            # Allow some time for AP to complete handling of connection
1065            # before disconnecting.
1066            time.sleep(0.1)
1067            dev[0].request("REMOVE_NETWORK all")
1068            dev[0].wait_disconnected()
1069            # Allow some time for AP to complete handling of disconnection
1070            # before trying SAE again.
1071            time.sleep(0.1)
1072
1073def test_sigma_dut_ap_sae_group(dev, apdev, params):
1074    """sigma_dut controlled AP with SAE and specific group"""
1075    logdir = os.path.join(params['logdir'],
1076                          "sigma_dut_ap_sae_group.sigma-hostapd")
1077    check_sae_capab(dev[0])
1078    with HWSimRadio() as (radio, iface), \
1079         SigmaDut(iface, hostapd_logdir=logdir) as dut:
1080        dut.cmd_check("ap_reset_default")
1081        dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-sae,MODE,11ng")
1082        dut.cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-SAE,PSK,12345678,ECGroupID,20")
1083        dut.cmd_check("ap_config_commit,NAME,AP")
1084
1085        dev[0].request("SET sae_groups ")
1086        dev[0].connect("test-sae", key_mgmt="SAE", psk="12345678",
1087                       ieee80211w="2", scan_freq="2412")
1088        if dev[0].get_status_field('sae_group') != '20':
1089            raise Exception("Expected SAE group not used")
1090
1091def test_sigma_dut_ap_psk_sae(dev, apdev, params):
1092    """sigma_dut controlled AP with PSK+SAE"""
1093    check_sae_capab(dev[0])
1094    logdir = os.path.join(params['logdir'],
1095                          "sigma_dut_ap_psk_sae.sigma-hostapd")
1096    with HWSimRadio() as (radio, iface), \
1097         SigmaDut(iface, hostapd_logdir=logdir) as dut:
1098        dut.cmd_check("ap_reset_default")
1099        dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-sae,MODE,11ng")
1100        dut.cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-PSK-SAE,PSK,12345678")
1101        dut.cmd_check("ap_config_commit,NAME,AP")
1102
1103        dev[2].request("SET sae_groups ")
1104        dev[2].connect("test-sae", key_mgmt="SAE", psk="12345678",
1105                       scan_freq="2412", ieee80211w="0", wait_connect=False)
1106        dev[0].request("SET sae_groups ")
1107        dev[0].connect("test-sae", key_mgmt="SAE", psk="12345678",
1108                       scan_freq="2412", ieee80211w="2")
1109        dev[1].connect("test-sae", psk="12345678", scan_freq="2412")
1110
1111        ev = dev[2].wait_event(["CTRL-EVENT-CONNECTED"], timeout=0.1)
1112        dev[2].request("DISCONNECT")
1113        if ev is not None:
1114            raise Exception("Unexpected connection without PMF")
1115
1116def test_sigma_dut_ap_psk_sae_ft(dev, apdev, params):
1117    """sigma_dut controlled AP with PSK, SAE, FT"""
1118    logdir = os.path.join(params['logdir'],
1119                          "sigma_dut_ap_psk_sae_ft.sigma-hostapd")
1120    conffile = os.path.join(params['logdir'],
1121                            "sigma_dut_ap_psk_sae_ft.sigma-conf")
1122    check_sae_capab(dev[0])
1123    with HWSimRadio() as (radio, iface), \
1124         SigmaDut(iface, hostapd_logdir=logdir) as dut:
1125        dut.cmd_check("ap_reset_default,NAME,AP,Program,WPA3")
1126        dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-sae-psk,MODE,11ng,DOMAIN,aabb")
1127        dut.cmd_check("ap_set_security,NAME,AP,AKMSuiteType,2;4;6;8;9,PSK,12345678,PairwiseCipher,AES-CCMP-128,GroupCipher,AES-CCMP-128")
1128        dut.cmd_check("ap_set_wireless,NAME,AP,DOMAIN,0101,FT_OA,Enable")
1129        dut.cmd_check("ap_set_wireless,NAME,AP,FT_BSS_LIST," + apdev[1]['bssid'])
1130        dut.cmd_check("ap_config_commit,NAME,AP")
1131
1132        with open("/tmp/sigma_dut-ap.conf", "rb") as f, \
1133             open(conffile, "wb") as f2:
1134            f2.write(f.read())
1135
1136        dev[0].request("SET sae_groups ")
1137        dev[0].connect("test-sae-psk", key_mgmt="SAE FT-SAE",
1138                       sae_password="12345678", scan_freq="2412")
1139        dev[1].connect("test-sae-psk", key_mgmt="WPA-PSK FT-PSK",
1140                       psk="12345678", scan_freq="2412")
1141        dev[2].connect("test-sae-psk", key_mgmt="WPA-PSK",
1142                       psk="12345678", scan_freq="2412")
1143
1144def test_sigma_dut_owe(dev, apdev):
1145    """sigma_dut controlled OWE station"""
1146    if "OWE" not in dev[0].get_capability("key_mgmt"):
1147        raise HwsimSkip("OWE not supported")
1148
1149    ifname = dev[0].ifname
1150    with SigmaDut(ifname) as dut:
1151        params = {"ssid": "owe",
1152                  "wpa": "2",
1153                  "wpa_key_mgmt": "OWE",
1154                  "ieee80211w": "2",
1155                  "rsn_pairwise": "CCMP"}
1156        hapd = hostapd.add_ap(apdev[0], params)
1157        bssid = hapd.own_addr()
1158
1159        dut.cmd_check("sta_reset_default,interface,%s,prog,WPA3" % ifname)
1160        dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
1161        dut.cmd_check("sta_set_security,interface,%s,ssid,owe,Type,OWE" % ifname)
1162        dut.cmd_check("sta_associate,interface,%s,ssid,owe,channel,1" % ifname,
1163                            timeout=10)
1164        dut.wait_connected()
1165        dut.cmd_check("sta_get_ip_config,interface," + ifname)
1166        res = dut.cmd_check("sta_get_parameter,interface,%s,Parameter,PMK" % ifname)
1167        logger.info("Reported PMK: " + res)
1168        if ",PMK," not in res:
1169            raise Exception("PMK not reported");
1170        if hapd.request("GET_PMK " + dev[0].own_addr()) != res.split(',')[3]:
1171            raise Exception("Mismatch in reported PMK")
1172
1173        dev[0].dump_monitor()
1174        dut.run_cmd("sta_reassoc,interface,%s,Channel,1,bssid,%s" % (ifname, bssid))
1175        dev[0].wait_connected()
1176        dut.cmd_check("sta_disconnect,interface," + ifname)
1177        dev[0].wait_disconnected()
1178        dev[0].dump_monitor()
1179
1180        dut.cmd_check("sta_reset_default,interface,%s,prog,WPA3" % ifname)
1181        dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
1182        dut.cmd_check("sta_set_security,interface,%s,ssid,owe,Type,OWE,ECGroupID,20" % ifname)
1183        dut.cmd_check("sta_associate,interface,%s,ssid,owe,channel,1" % ifname,
1184                            timeout=10)
1185        dut.wait_connected()
1186        dut.cmd_check("sta_get_ip_config,interface," + ifname)
1187        dut.cmd_check("sta_disconnect,interface," + ifname)
1188        dev[0].wait_disconnected()
1189        dev[0].dump_monitor()
1190
1191        dut.cmd_check("sta_reset_default,interface,%s,prog,WPA3" % ifname)
1192        dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
1193        dut.cmd_check("sta_set_security,interface,%s,ssid,owe,Type,OWE,ECGroupID,0" % ifname)
1194        dut.cmd_check("sta_associate,interface,%s,ssid,owe,channel,1" % ifname,
1195                            timeout=10)
1196        ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"], timeout=10)
1197        dut.cmd_check("sta_disconnect,interface," + ifname)
1198        if ev is None:
1199            raise Exception("Association not rejected")
1200        if "status_code=77" not in ev:
1201            raise Exception("Unexpected rejection reason: " + ev)
1202
1203        dut.cmd_check("sta_reset_default,interface," + ifname)
1204
1205def test_sigma_dut_owe_ptk_workaround(dev, apdev):
1206    """sigma_dut controlled OWE station with PTK workaround"""
1207    if "OWE" not in dev[0].get_capability("key_mgmt"):
1208        raise HwsimSkip("OWE not supported")
1209
1210    params = {"ssid": "owe",
1211              "wpa": "2",
1212              "wpa_key_mgmt": "OWE",
1213              "owe_ptk_workaround": "1",
1214              "owe_groups": "20",
1215              "ieee80211w": "2",
1216              "rsn_pairwise": "CCMP"}
1217    hapd = hostapd.add_ap(apdev[0], params)
1218
1219    ifname = dev[0].ifname
1220    with SigmaDut(ifname, owe_ptk_workaround=True) as dut:
1221        dut.cmd_check("sta_reset_default,interface,%s,prog,WPA3" % ifname)
1222        dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
1223        dut.cmd_check("sta_set_security,interface,%s,ssid,owe,Type,OWE,ECGroupID,20" % ifname)
1224        dut.cmd_check("sta_associate,interface,%s,ssid,owe,channel,1" % ifname,
1225                      timeout=10)
1226        dut.wait_connected()
1227        dut.cmd_check("sta_reset_default,interface," + ifname)
1228
1229def test_sigma_dut_ap_owe(dev, apdev, params):
1230    """sigma_dut controlled AP with OWE"""
1231    logdir = os.path.join(params['logdir'],
1232                          "sigma_dut_ap_owe.sigma-hostapd")
1233    if "OWE" not in dev[0].get_capability("key_mgmt"):
1234        raise HwsimSkip("OWE not supported")
1235    with HWSimRadio() as (radio, iface), \
1236         SigmaDut(iface, hostapd_logdir=logdir) as dut:
1237        dut.cmd_check("ap_reset_default,NAME,AP,Program,WPA3")
1238        dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,owe,MODE,11ng")
1239        dut.cmd_check("ap_set_security,NAME,AP,KEYMGNT,OWE")
1240        dut.cmd_check("ap_config_commit,NAME,AP")
1241
1242        id = dev[0].connect("owe", key_mgmt="OWE", ieee80211w="2",
1243                            scan_freq="2412")
1244
1245        res = dut.cmd_check("ap_get_parameter,name,AP,STA_MAC_Address,%s,Parameter,PMK" % dev[0].own_addr())
1246        logger.info("Reported PMK: " + res)
1247        if ",PMK," not in res:
1248            raise Exception("PMK not reported");
1249        if dev[0].get_pmk(id) != res.split(',')[3]:
1250            raise Exception("Mismatch in reported PMK")
1251
1252def test_sigma_dut_ap_owe_ecgroupid(dev, apdev, params):
1253    """sigma_dut controlled AP with OWE and ECGroupID"""
1254    if "OWE" not in dev[0].get_capability("key_mgmt"):
1255        raise HwsimSkip("OWE not supported")
1256    logdir = params['prefix'] + ".sigma-hostapd"
1257    with HWSimRadio() as (radio, iface), \
1258         SigmaDut(iface, hostapd_logdir=logdir) as dut:
1259        dut.cmd_check("ap_reset_default,NAME,AP,Program,WPA3")
1260        dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,owe,MODE,11ng")
1261        dut.cmd_check("ap_set_security,NAME,AP,KEYMGNT,OWE,ECGroupID,20 21,PMF,Required")
1262        dut.cmd_check("ap_config_commit,NAME,AP")
1263
1264        dev[0].connect("owe", key_mgmt="OWE", ieee80211w="2",
1265                       owe_group="20", scan_freq="2412")
1266        dev[0].request("REMOVE_NETWORK all")
1267        dev[0].wait_disconnected()
1268
1269        dev[0].connect("owe", key_mgmt="OWE", ieee80211w="2",
1270                       owe_group="21", scan_freq="2412")
1271        dev[0].request("REMOVE_NETWORK all")
1272        dev[0].wait_disconnected()
1273
1274        dev[0].connect("owe", key_mgmt="OWE", ieee80211w="2",
1275                       owe_group="19", scan_freq="2412", wait_connect=False)
1276        ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"], timeout=10)
1277        dev[0].request("DISCONNECT")
1278        if ev is None:
1279            raise Exception("Association not rejected")
1280        if "status_code=77" not in ev:
1281            raise Exception("Unexpected rejection reason: " + ev)
1282        dev[0].dump_monitor()
1283
1284def test_sigma_dut_ap_owe_ptk_workaround(dev, apdev, params):
1285    """sigma_dut controlled AP with OWE PTK workaround"""
1286    if "OWE" not in dev[0].get_capability("key_mgmt"):
1287        raise HwsimSkip("OWE not supported")
1288    logdir = params['prefix'] + ".sigma-hostapd"
1289    with HWSimRadio() as (radio, iface), \
1290         SigmaDut(iface, owe_ptk_workaround=True, hostapd_logdir=logdir) as dut:
1291        dut.cmd_check("ap_reset_default,NAME,AP,Program,WPA3")
1292        dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,owe,MODE,11ng")
1293        dut.cmd_check("ap_set_security,NAME,AP,KEYMGNT,OWE,ECGroupID,20,PMF,Required")
1294        dut.cmd_check("ap_config_commit,NAME,AP")
1295
1296        dev[0].connect("owe", key_mgmt="OWE", ieee80211w="2",
1297                       owe_group="20", owe_ptk_workaround="1",
1298                       scan_freq="2412")
1299
1300def test_sigma_dut_ap_owe_transition_mode(dev, apdev, params):
1301    """sigma_dut controlled AP with OWE and transition mode"""
1302    if "OWE" not in dev[0].get_capability("key_mgmt"):
1303        raise HwsimSkip("OWE not supported")
1304    logdir = os.path.join(params['logdir'],
1305                          "sigma_dut_ap_owe_transition_mode.sigma-hostapd")
1306    with HWSimRadio() as (radio, iface), \
1307         SigmaDut(iface, hostapd_logdir=logdir) as dut:
1308        dut.cmd_check("ap_reset_default,NAME,AP,Program,WPA3")
1309        dut.cmd_check("ap_set_wireless,NAME,AP,WLAN_TAG,1,CHANNEL,1,SSID,owe,MODE,11ng")
1310        dut.cmd_check("ap_set_security,NAME,AP,WLAN_TAG,1,KEYMGNT,OWE")
1311        dut.cmd_check("ap_set_wireless,NAME,AP,WLAN_TAG,2,CHANNEL,1,SSID,owe,MODE,11ng")
1312        dut.cmd_check("ap_set_security,NAME,AP,WLAN_TAG,2,KEYMGNT,NONE")
1313        dut.cmd_check("ap_config_commit,NAME,AP")
1314
1315        res1 = dut.cmd_check("ap_get_mac_address,NAME,AP,WLAN_TAG,1,Interface,24G")
1316        res2 = dut.cmd_check("ap_get_mac_address,NAME,AP,WLAN_TAG,2,Interface,24G")
1317
1318        dev[0].connect("owe", key_mgmt="OWE", ieee80211w="2",
1319                       scan_freq="2412")
1320        dev[1].connect("owe", key_mgmt="NONE", scan_freq="2412")
1321        if dev[0].get_status_field('bssid') not in res1:
1322            raise Exception("Unexpected ap_get_mac_address WLAN_TAG,1: " + res1)
1323        if dev[1].get_status_field('bssid') not in res2:
1324            raise Exception("Unexpected ap_get_mac_address WLAN_TAG,2: " + res2)
1325
1326def test_sigma_dut_ap_owe_transition_mode_2(dev, apdev, params):
1327    """sigma_dut controlled AP with OWE and transition mode (2)"""
1328    if "OWE" not in dev[0].get_capability("key_mgmt"):
1329        raise HwsimSkip("OWE not supported")
1330    logdir = os.path.join(params['logdir'],
1331                          "sigma_dut_ap_owe_transition_mode_2.sigma-hostapd")
1332    with HWSimRadio() as (radio, iface), \
1333         SigmaDut(iface, hostapd_logdir=logdir) as dut:
1334        dut.cmd_check("ap_reset_default,NAME,AP,Program,WPA3")
1335        dut.cmd_check("ap_set_wireless,NAME,AP,WLAN_TAG,1,CHANNEL,1,SSID,owe,MODE,11ng")
1336        dut.cmd_check("ap_set_security,NAME,AP,WLAN_TAG,1,KEYMGNT,NONE")
1337        dut.cmd_check("ap_set_wireless,NAME,AP,WLAN_TAG,2,CHANNEL,1,MODE,11ng")
1338        dut.cmd_check("ap_set_security,NAME,AP,WLAN_TAG,2,KEYMGNT,OWE")
1339        dut.cmd_check("ap_config_commit,NAME,AP")
1340
1341        res1 = dut.cmd_check("ap_get_mac_address,NAME,AP,WLAN_TAG,1,Interface,24G")
1342        res2 = dut.cmd_check("ap_get_mac_address,NAME,AP,WLAN_TAG,2,Interface,24G")
1343
1344        dev[0].connect("owe", key_mgmt="OWE", ieee80211w="2",
1345                       scan_freq="2412")
1346        dev[1].connect("owe", key_mgmt="NONE", scan_freq="2412")
1347        if dev[0].get_status_field('bssid') not in res2:
1348            raise Exception("Unexpected ap_get_mac_address WLAN_TAG,2: " + res1)
1349        if dev[1].get_status_field('bssid') not in res1:
1350            raise Exception("Unexpected ap_get_mac_address WLAN_TAG,1: " + res2)
1351
1352def dpp_init_enrollee(dev, id1, enrollee_role):
1353    logger.info("Starting DPP initiator/enrollee in a thread")
1354    time.sleep(1)
1355    cmd = "DPP_AUTH_INIT peer=%d role=enrollee" % id1
1356    if enrollee_role == "Configurator":
1357        cmd += " netrole=configurator"
1358    if "OK" not in dev.request(cmd):
1359        raise Exception("Failed to initiate DPP Authentication")
1360    ev = dev.wait_event(["DPP-CONF-RECEIVED"], timeout=5)
1361    if ev is None:
1362        raise Exception("DPP configuration not completed (Enrollee)")
1363    logger.info("DPP initiator/enrollee done")
1364
1365def test_sigma_dut_dpp_qr_resp_1(dev, apdev):
1366    """sigma_dut DPP/QR responder (conf index 1)"""
1367    run_sigma_dut_dpp_qr_resp(dev, apdev, 1)
1368
1369def test_sigma_dut_dpp_qr_resp_2(dev, apdev):
1370    """sigma_dut DPP/QR responder (conf index 2)"""
1371    run_sigma_dut_dpp_qr_resp(dev, apdev, 2)
1372
1373def test_sigma_dut_dpp_qr_resp_3(dev, apdev):
1374    """sigma_dut DPP/QR responder (conf index 3)"""
1375    run_sigma_dut_dpp_qr_resp(dev, apdev, 3)
1376
1377def test_sigma_dut_dpp_qr_resp_4(dev, apdev):
1378    """sigma_dut DPP/QR responder (conf index 4)"""
1379    run_sigma_dut_dpp_qr_resp(dev, apdev, 4)
1380
1381def test_sigma_dut_dpp_qr_resp_5(dev, apdev):
1382    """sigma_dut DPP/QR responder (conf index 5)"""
1383    run_sigma_dut_dpp_qr_resp(dev, apdev, 5)
1384
1385def test_sigma_dut_dpp_qr_resp_6(dev, apdev):
1386    """sigma_dut DPP/QR responder (conf index 6)"""
1387    run_sigma_dut_dpp_qr_resp(dev, apdev, 6)
1388
1389def test_sigma_dut_dpp_qr_resp_7(dev, apdev):
1390    """sigma_dut DPP/QR responder (conf index 7)"""
1391    run_sigma_dut_dpp_qr_resp(dev, apdev, 7)
1392
1393def test_sigma_dut_dpp_qr_resp_8(dev, apdev):
1394    """sigma_dut DPP/QR responder (conf index 8)"""
1395    run_sigma_dut_dpp_qr_resp(dev, apdev, 8)
1396
1397def test_sigma_dut_dpp_qr_resp_9(dev, apdev):
1398    """sigma_dut DPP/QR responder (conf index 9)"""
1399    run_sigma_dut_dpp_qr_resp(dev, apdev, 9)
1400
1401def test_sigma_dut_dpp_qr_resp_10(dev, apdev):
1402    """sigma_dut DPP/QR responder (conf index 10)"""
1403    run_sigma_dut_dpp_qr_resp(dev, apdev, 10)
1404
1405def test_sigma_dut_dpp_qr_resp_11(dev, apdev, params):
1406    """sigma_dut DPP/QR responder (conf index 11)"""
1407    if not os.path.exists("./dpp-ca.py"):
1408        raise HwsimSkip("dpp-ca.py not available")
1409    logdir = params['logdir']
1410    with open("auth_serv/ec-ca.pem", "rb") as f:
1411        res = f.read()
1412    with open(os.path.join(logdir, "dpp-ca.pem"), "wb") as f:
1413        f.write(res)
1414    with open("auth_serv/ec-ca.key", "rb") as f:
1415        res = f.read()
1416    with open(os.path.join(logdir, "dpp-ca.key"), "wb") as f:
1417        f.write(res)
1418    with open(os.path.join(logdir, "dpp-ca-csrattrs"), "wb") as f:
1419        f.write(b'MAsGCSqGSIb3DQEJBw==')
1420    run_sigma_dut_dpp_qr_resp(dev, apdev, 11, cert_path=logdir)
1421
1422def test_sigma_dut_dpp_qr_resp_curve_change(dev, apdev):
1423    """sigma_dut DPP/QR responder (curve change)"""
1424    run_sigma_dut_dpp_qr_resp(dev, apdev, 1, net_access_key_curve="P-384")
1425
1426def test_sigma_dut_dpp_qr_resp_chan_list(dev, apdev):
1427    """sigma_dut DPP/QR responder (channel list override)"""
1428    run_sigma_dut_dpp_qr_resp(dev, apdev, 1, chan_list='81/2 81/6 81/1',
1429                              listen_chan=2)
1430
1431def test_sigma_dut_dpp_qr_resp_status_query(dev, apdev):
1432    """sigma_dut DPP/QR responder status query"""
1433    check_dpp_capab(dev[1])
1434    params = hostapd.wpa2_params(ssid="DPPNET01",
1435                                 passphrase="ThisIsDppPassphrase")
1436    hapd = hostapd.add_ap(apdev[0], params)
1437
1438    try:
1439        dev[1].set("dpp_config_processing", "2")
1440        run_sigma_dut_dpp_qr_resp(dev, apdev, 3, status_query=True)
1441    finally:
1442        dev[1].set("dpp_config_processing", "0", allow_fail=True)
1443
1444def test_sigma_dut_dpp_qr_resp_configurator(dev, apdev):
1445    """sigma_dut DPP/QR responder (configurator provisioning)"""
1446    run_sigma_dut_dpp_qr_resp(dev, apdev, -1, enrollee_role="Configurator")
1447
1448def run_sigma_dut_dpp_qr_resp(dev, apdev, conf_idx, chan_list=None,
1449                              listen_chan=None, status_query=False,
1450                              enrollee_role="STA", cert_path=None,
1451                              net_access_key_curve=None):
1452    min_ver = 3 if net_access_key_curve else 1
1453    check_dpp_capab(dev[0], min_ver=min_ver)
1454    check_dpp_capab(dev[1], min_ver=min_ver)
1455    with SigmaDut(dev[0].ifname, cert_path=cert_path) as dut:
1456        cmd = "dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR"
1457        if chan_list:
1458            cmd += ",DPPChannelList," + chan_list
1459        res = dut.run_cmd(cmd)
1460        if "status,COMPLETE" not in res:
1461            raise Exception("dev_exec_action did not succeed: " + res)
1462        hex = res.split(',')[3]
1463        uri = from_hex(hex)
1464        logger.info("URI from sigma_dut: " + uri)
1465
1466        id1 = dev[1].dpp_qr_code(uri)
1467
1468        t = threading.Thread(target=dpp_init_enrollee, args=(dev[1], id1,
1469                                                             enrollee_role))
1470        t.start()
1471        cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPAuthDirection,Single,DPPProvisioningRole,Configurator,DPPConfEnrolleeRole,%s,DPPSigningKeyECC,P-256,DPPBS,QR,DPPTimeout,6" % enrollee_role
1472        if conf_idx is not None:
1473            cmd += ",DPPConfIndex,%d" % conf_idx
1474        if listen_chan:
1475            cmd += ",DPPListenChannel," + str(listen_chan)
1476        if status_query:
1477            cmd += ",DPPStatusQuery,Yes"
1478        if net_access_key_curve:
1479            cmd += ",DPPNAKECC," + net_access_key_curve
1480        res = dut.run_cmd(cmd, timeout=10)
1481        t.join()
1482        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
1483            raise Exception("Unexpected result: " + res)
1484        if status_query and "StatusResult,0" not in res:
1485            raise Exception("Status query did not succeed: " + res)
1486
1487csign = "30770201010420768240a3fc89d6662d9782f120527fe7fb9edc6366ab0b9c7dde96125cfd250fa00a06082a8648ce3d030107a144034200042908e1baf7bf413cc66f9e878a03e8bb1835ba94b033dbe3d6969fc8575d5eb5dfda1cb81c95cee21d0cd7d92ba30541ffa05cb6296f5dd808b0c1c2a83c0708"
1488csign_pub = "3059301306072a8648ce3d020106082a8648ce3d030107034200042908e1baf7bf413cc66f9e878a03e8bb1835ba94b033dbe3d6969fc8575d5eb5dfda1cb81c95cee21d0cd7d92ba30541ffa05cb6296f5dd808b0c1c2a83c0708"
1489ap_connector = "eyJ0eXAiOiJkcHBDb24iLCJraWQiOiJwYWtZbXVzd1dCdWpSYTl5OEsweDViaTVrT3VNT3dzZHRlaml2UG55ZHZzIiwiYWxnIjoiRVMyNTYifQ.eyJncm91cHMiOlt7Imdyb3VwSWQiOiIqIiwibmV0Um9sZSI6ImFwIn1dLCJuZXRBY2Nlc3NLZXkiOnsia3R5IjoiRUMiLCJjcnYiOiJQLTI1NiIsIngiOiIybU5vNXZuRkI5bEw3d1VWb1hJbGVPYzBNSEE1QXZKbnpwZXZULVVTYzVNIiwieSI6IlhzS3dqVHJlLTg5WWdpU3pKaG9CN1haeUttTU05OTl3V2ZaSVl0bi01Q3MifX0.XhjFpZgcSa7G2lHy0OCYTvaZFRo5Hyx6b7g7oYyusLC7C_73AJ4_BxEZQVYJXAtDuGvb3dXSkHEKxREP9Q6Qeg"
1490ap_netaccesskey = "30770201010420ceba752db2ad5200fa7bc565b9c05c69b7eb006751b0b329b0279de1c19ca67ca00a06082a8648ce3d030107a14403420004da6368e6f9c507d94bef0515a1722578e73430703902f267ce97af4fe51273935ec2b08d3adefbcf588224b3261a01ed76722a630cf7df7059f64862d9fee42b"
1491
1492def start_dpp_ap(apdev):
1493    params = {"ssid": "DPPNET01",
1494              "wpa": "2",
1495              "ieee80211w": "2",
1496              "wpa_key_mgmt": "DPP",
1497              "rsn_pairwise": "CCMP",
1498              "dpp_connector": ap_connector,
1499              "dpp_csign": csign_pub,
1500              "dpp_netaccesskey": ap_netaccesskey}
1501    try:
1502        hapd = hostapd.add_ap(apdev, params)
1503    except:
1504        raise HwsimSkip("DPP not supported")
1505    return hapd
1506
1507def test_sigma_dut_dpp_qr_init_enrollee(dev, apdev):
1508    """sigma_dut DPP/QR initiator as Enrollee"""
1509    check_dpp_capab(dev[0])
1510    check_dpp_capab(dev[1])
1511    hapd = start_dpp_ap(apdev[0])
1512    with SigmaDut(dev[0].ifname, dev=dev[0]) as dut:
1513        dev[0].set("dpp_config_processing", "2")
1514
1515        cmd = "DPP_CONFIGURATOR_ADD key=" + csign
1516        res = dev[1].request(cmd)
1517        if "FAIL" in res:
1518            raise Exception("Failed to add configurator")
1519        conf_id = int(res)
1520
1521        id0 = dev[1].dpp_bootstrap_gen(chan="81/6", mac=True)
1522        uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
1523
1524        dev[1].set("dpp_configurator_params",
1525                   " conf=sta-dpp ssid=%s configurator=%d" % (to_hex("DPPNET01"), conf_id))
1526        cmd = "DPP_LISTEN 2437 role=configurator"
1527        if "OK" not in dev[1].request(cmd):
1528            raise Exception("Failed to start listen operation")
1529
1530        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % to_hex(uri0))
1531        if "status,COMPLETE" not in res:
1532            raise Exception("dev_exec_action did not succeed: " + res)
1533
1534        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Enrollee,DPPBS,QR,DPPTimeout,6,DPPWaitForConnect,Yes", timeout=10)
1535        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK,NetworkIntroResult,OK,NetworkConnectResult,OK" not in res:
1536            raise Exception("Unexpected result: " + res)
1537
1538def test_sigma_dut_dpp_qr_init_enrollee_configurator(dev, apdev):
1539    """sigma_dut DPP/QR initiator as Enrollee (to become Configurator)"""
1540    check_dpp_capab(dev[0])
1541    check_dpp_capab(dev[1])
1542
1543    with SigmaDut(dev[0].ifname, dev=dev[0]) as dut:
1544        cmd = "DPP_CONFIGURATOR_ADD"
1545        res = dev[1].request(cmd)
1546        if "FAIL" in res:
1547            raise Exception("Failed to add configurator")
1548        conf_id = int(res)
1549
1550        id0 = dev[1].dpp_bootstrap_gen(chan="81/6", mac=True)
1551        uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
1552
1553        dev[1].set("dpp_configurator_params",
1554                   " conf=configurator ssid=%s configurator=%d" % (to_hex("DPPNET01"), conf_id))
1555        cmd = "DPP_LISTEN 2437 role=configurator"
1556        if "OK" not in dev[1].request(cmd):
1557            raise Exception("Failed to start listen operation")
1558
1559        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % to_hex(uri0))
1560        if "status,COMPLETE" not in res:
1561            raise Exception("dev_exec_action did not succeed: " + res)
1562
1563        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Enrollee,DPPNetworkRole,Configurator,DPPBS,QR,DPPTimeout,6", timeout=10)
1564        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
1565            raise Exception("Unexpected result: " + res)
1566
1567def test_sigma_dut_dpp_qr_mutual_init_enrollee(dev, apdev):
1568    """sigma_dut DPP/QR (mutual) initiator as Enrollee"""
1569    run_sigma_dut_dpp_qr_mutual_init_enrollee_check(dev, apdev)
1570
1571def test_sigma_dut_dpp_qr_mutual_init_enrollee_check(dev, apdev):
1572    """sigma_dut DPP/QR (mutual) initiator as Enrollee (extra check)"""
1573    run_sigma_dut_dpp_qr_mutual_init_enrollee_check(dev, apdev,
1574                                                    extra="DPPAuthDirection,Mutual,")
1575
1576def test_sigma_dut_dpp_qr_mutual_init_enrollee_mud_url(dev, apdev):
1577    """sigma_dut DPP/QR (mutual) initiator as Enrollee (MUD URL)"""
1578    run_sigma_dut_dpp_qr_mutual_init_enrollee_check(dev, apdev,
1579                                                    mud_url="https://example.com/mud")
1580
1581def run_sigma_dut_dpp_qr_mutual_init_enrollee_check(dev, apdev, extra='',
1582                                                    mud_url=None):
1583    check_dpp_capab(dev[0])
1584    check_dpp_capab(dev[1])
1585    hapd = start_dpp_ap(apdev[0])
1586    ifname = dev[0].ifname
1587    with SigmaDut(ifname, dev=dev[0]) as dut:
1588        dut.cmd_check("sta_reset_default,interface,%s,prog,DPP" % ifname)
1589
1590        cmd = "DPP_CONFIGURATOR_ADD key=" + csign
1591        res = dev[1].request(cmd)
1592        if "FAIL" in res:
1593            raise Exception("Failed to add configurator")
1594        conf_id = int(res)
1595
1596        id0 = dev[1].dpp_bootstrap_gen(chan="81/6", mac=True)
1597        uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
1598
1599        dev[1].set("dpp_configurator_params",
1600                   " conf=sta-dpp ssid=%s configurator=%d" % (to_hex("DPPNET01"), conf_id))
1601        cmd = "DPP_LISTEN 2437 role=configurator qr=mutual"
1602        if "OK" not in dev[1].request(cmd):
1603            raise Exception("Failed to start listen operation")
1604
1605        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR")
1606        if "status,COMPLETE" not in res:
1607            raise Exception("dev_exec_action did not succeed: " + res)
1608        hex = res.split(',')[3]
1609        uri = from_hex(hex)
1610        logger.info("URI from sigma_dut: " + uri)
1611
1612        id1 = dev[1].dpp_qr_code(uri)
1613
1614        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % to_hex(uri0))
1615        if "status,COMPLETE" not in res:
1616            raise Exception("dev_exec_action did not succeed: " + res)
1617
1618        cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,%sDPPProvisioningRole,Enrollee,DPPBS,QR,DPPTimeout,6,DPPWaitForConnect,Yes" % extra
1619        if mud_url:
1620            cmd += ",MUDURL," + mud_url
1621        res = dut.cmd_check(cmd, timeout=10)
1622        dut.cmd_check("sta_reset_default,interface,%s,prog,DPP" % ifname)
1623        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK,NetworkIntroResult,OK,NetworkConnectResult,OK" not in res:
1624            raise Exception("Unexpected result: " + res)
1625
1626        if mud_url:
1627            ev = dev[1].wait_event(["DPP-MUD-URL"], timeout=1)
1628            if ev is None:
1629                raise Exception("DPP MUD URL not reported")
1630            if ev.split(' ')[1] != mud_url:
1631                raise Exception("Unexpected MUD URL value: " + ev)
1632
1633def dpp_init_conf_mutual(dev, id1, conf_id, own_id=None):
1634    time.sleep(1)
1635    logger.info("Starting DPP initiator/configurator in a thread")
1636    cmd = "DPP_AUTH_INIT peer=%d conf=sta-dpp ssid=%s configurator=%d" % (id1, to_hex("DPPNET01"), conf_id)
1637    if own_id is not None:
1638        cmd += " own=%d" % own_id
1639    if "OK" not in dev.request(cmd):
1640        raise Exception("Failed to initiate DPP Authentication")
1641    ev = dev.wait_event(["DPP-CONF-SENT"], timeout=10)
1642    if ev is None:
1643        raise Exception("DPP configuration not completed (Configurator)")
1644    logger.info("DPP initiator/configurator done")
1645
1646def test_sigma_dut_dpp_qr_mutual_resp_enrollee(dev, apdev):
1647    """sigma_dut DPP/QR (mutual) responder as Enrollee"""
1648    run_sigma_dut_dpp_qr_mutual_resp_enrollee(dev, apdev)
1649
1650def test_sigma_dut_dpp_qr_mutual_resp_enrollee_pending(dev, apdev):
1651    """sigma_dut DPP/QR (mutual) responder as Enrollee (response pending)"""
1652    run_sigma_dut_dpp_qr_mutual_resp_enrollee(dev, apdev, ',DPPDelayQRResponse,1')
1653
1654def test_sigma_dut_dpp_qr_mutual_resp_enrollee_connector_privacy(dev, apdev):
1655    """sigma_dut DPP/QR (mutual) responder as Enrollee (Connector Privacy)"""
1656    check_dpp_capab(dev[0], min_ver=3)
1657    check_dpp_capab(dev[1], min_ver=3)
1658    try:
1659        run_sigma_dut_dpp_qr_mutual_resp_enrollee(dev, apdev,
1660                                                  ",DPPPrivNetIntro,Yes")
1661    finally:
1662        dev[0].set("dpp_connector_privacy_default", "0", allow_fail=True)
1663
1664def run_sigma_dut_dpp_qr_mutual_resp_enrollee(dev, apdev, extra=None):
1665    check_dpp_capab(dev[0])
1666    check_dpp_capab(dev[1])
1667    hapd = start_dpp_ap(apdev[0])
1668    with SigmaDut(dev[0].ifname, dev=dev[0]) as dut:
1669        dev[0].set("dpp_config_processing", "2")
1670
1671        cmd = "DPP_CONFIGURATOR_ADD key=" + csign
1672        res = dev[1].request(cmd)
1673        if "FAIL" in res:
1674            raise Exception("Failed to add configurator")
1675        conf_id = int(res)
1676
1677        id0 = dev[1].dpp_bootstrap_gen(chan="81/6", mac=True)
1678        uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
1679
1680        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR")
1681        if "status,COMPLETE" not in res:
1682            raise Exception("dev_exec_action did not succeed: " + res)
1683        hex = res.split(',')[3]
1684        uri = from_hex(hex)
1685        logger.info("URI from sigma_dut: " + uri)
1686
1687        id1 = dev[1].dpp_qr_code(uri)
1688
1689        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % to_hex(uri0))
1690        if "status,COMPLETE" not in res:
1691            raise Exception("dev_exec_action did not succeed: " + res)
1692
1693        t = threading.Thread(target=dpp_init_conf_mutual,
1694                             args=(dev[1], id1, conf_id, id0))
1695        t.start()
1696
1697        cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPAuthDirection,Mutual,DPPProvisioningRole,Enrollee,DPPBS,QR,DPPTimeout,20,DPPWaitForConnect,Yes"
1698        if extra:
1699            cmd += extra
1700        res = dut.run_cmd(cmd, timeout=25)
1701        t.join()
1702        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK,NetworkIntroResult,OK,NetworkConnectResult,OK" not in res:
1703            raise Exception("Unexpected result: " + res)
1704
1705def test_sigma_dut_dpp_qr_mutual_resp_configurator(dev, apdev):
1706    """sigma_dut DPP/QR (mutual) responder as Configurator (NAK from URI)"""
1707    check_dpp_capab(dev[0], min_ver=3)
1708    check_dpp_capab(dev[1], min_ver=3)
1709    with SigmaDut(dev[0].ifname) as dut:
1710        id0 = dev[1].dpp_bootstrap_gen(chan="81/6", mac=True,
1711                                       supported_curves="P-256:P-384:P-521")
1712        uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
1713
1714        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR")
1715        if "status,COMPLETE" not in res:
1716            raise Exception("dev_exec_action did not succeed: " + res)
1717        hex = res.split(',')[3]
1718        uri = from_hex(hex)
1719        logger.info("URI from sigma_dut: " + uri)
1720
1721        id1 = dev[1].dpp_qr_code(uri)
1722
1723        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % to_hex(uri0))
1724        if "status,COMPLETE" not in res:
1725            raise Exception("dev_exec_action did not succeed: " + res)
1726
1727        t = threading.Thread(target=dpp_init_enrollee_mutual,
1728                             args=(dev[1], id1, id0))
1729        t.start()
1730
1731        cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPAuthDirection,Mutual,DPPProvisioningRole,Configurator,DPPConfEnrolleeRole,STA,DPPConfIndex,1,DPPNAKECC,URI,DPPBS,QR,DPPTimeout,20"
1732        res = dut.run_cmd(cmd, timeout=25)
1733        t.join()
1734        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
1735            raise Exception("Unexpected result: " + res)
1736
1737def dpp_resp_conf_mutual(dev, conf_id, uri):
1738    logger.info("Starting DPP responder/configurator in a thread")
1739    dev.set("dpp_configurator_params",
1740            " conf=sta-dpp ssid=%s configurator=%d" % (to_hex("DPPNET01"),
1741                                                       conf_id))
1742    cmd = "DPP_LISTEN 2437 role=configurator qr=mutual"
1743    if "OK" not in dev.request(cmd):
1744        raise Exception("Failed to initiate DPP listen")
1745    if uri:
1746        ev = dev.wait_event(["DPP-SCAN-PEER-QR-CODE"], timeout=10)
1747        if ev is None:
1748            raise Exception("QR Code scan for mutual authentication not requested")
1749        ev = dev.wait_event(["DPP-TX-STATUS"], timeout=10)
1750        if ev is None:
1751            raise Exception("No TX status for response-pending")
1752        time.sleep(0.1)
1753        dev.dpp_qr_code(uri)
1754    ev = dev.wait_event(["DPP-CONF-SENT"], timeout=10)
1755    if ev is None:
1756        raise Exception("DPP configuration not completed (Configurator)")
1757    logger.info("DPP responder/configurator done")
1758
1759def test_sigma_dut_dpp_qr_mutual_init_enrollee(dev, apdev):
1760    """sigma_dut DPP/QR (mutual) initiator as Enrollee"""
1761    run_sigma_dut_dpp_qr_mutual_init_enrollee(dev, apdev, False)
1762
1763def test_sigma_dut_dpp_qr_mutual_init_enrollee_pending(dev, apdev):
1764    """sigma_dut DPP/QR (mutual) initiator as Enrollee (response pending)"""
1765    run_sigma_dut_dpp_qr_mutual_init_enrollee(dev, apdev, True)
1766
1767def run_sigma_dut_dpp_qr_mutual_init_enrollee(dev, apdev, resp_pending):
1768    check_dpp_capab(dev[0])
1769    check_dpp_capab(dev[1])
1770    hapd = start_dpp_ap(apdev[0])
1771    with SigmaDut(dev[0].ifname, dev=dev[0]) as dut:
1772        dev[0].set("dpp_config_processing", "2")
1773
1774        cmd = "DPP_CONFIGURATOR_ADD key=" + csign
1775        res = dev[1].request(cmd)
1776        if "FAIL" in res:
1777            raise Exception("Failed to add configurator")
1778        conf_id = int(res)
1779
1780        id0 = dev[1].dpp_bootstrap_gen(chan="81/6", mac=True)
1781        uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
1782
1783        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR")
1784        if "status,COMPLETE" not in res:
1785            raise Exception("dev_exec_action did not succeed: " + res)
1786        hex = res.split(',')[3]
1787        uri = from_hex(hex)
1788        logger.info("URI from sigma_dut: " + uri)
1789
1790        if not resp_pending:
1791            dev[1].dpp_qr_code(uri)
1792            uri = None
1793
1794        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % to_hex(uri0))
1795        if "status,COMPLETE" not in res:
1796            raise Exception("dev_exec_action did not succeed: " + res)
1797
1798        t = threading.Thread(target=dpp_resp_conf_mutual,
1799                             args=(dev[1], conf_id, uri))
1800        t.start()
1801
1802        time.sleep(1)
1803        cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPProvisioningRole,Enrollee,DPPBS,QR,DPPTimeout,10,DPPWaitForConnect,Yes"
1804        res = dut.run_cmd(cmd, timeout=15)
1805        t.join()
1806        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK,NetworkIntroResult,OK,NetworkConnectResult,OK" not in res:
1807            raise Exception("Unexpected result: " + res)
1808
1809def test_sigma_dut_dpp_qr_init_enrollee_psk(dev, apdev):
1810    """sigma_dut DPP/QR initiator as Enrollee (PSK)"""
1811    check_dpp_capab(dev[0])
1812    check_dpp_capab(dev[1])
1813
1814    params = hostapd.wpa2_params(ssid="DPPNET01",
1815                                 passphrase="ThisIsDppPassphrase")
1816    hapd = hostapd.add_ap(apdev[0], params)
1817
1818    with SigmaDut(dev=dev[0]) as dut:
1819        dev[0].set("dpp_config_processing", "2")
1820
1821        cmd = "DPP_CONFIGURATOR_ADD"
1822        res = dev[1].request(cmd)
1823        if "FAIL" in res:
1824            raise Exception("Failed to add configurator")
1825        conf_id = int(res)
1826
1827        id0 = dev[1].dpp_bootstrap_gen(chan="81/6", mac=True)
1828        uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
1829
1830        dev[1].set("dpp_configurator_params",
1831                   " conf=sta-psk ssid=%s pass=%s configurator=%d" % (to_hex("DPPNET01"), to_hex("ThisIsDppPassphrase"), conf_id))
1832        cmd = "DPP_LISTEN 2437 role=configurator"
1833        if "OK" not in dev[1].request(cmd):
1834            raise Exception("Failed to start listen operation")
1835
1836        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % to_hex(uri0))
1837        if "status,COMPLETE" not in res:
1838            raise Exception("dev_exec_action did not succeed: " + res)
1839
1840        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Enrollee,DPPBS,QR,DPPTimeout,6,DPPWaitForConnect,Yes", timeout=10)
1841        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK,NetworkConnectResult,OK" not in res:
1842            raise Exception("Unexpected result: " + res)
1843
1844def test_sigma_dut_dpp_qr_init_enrollee_sae(dev, apdev):
1845    """sigma_dut DPP/QR initiator as Enrollee (SAE)"""
1846    check_dpp_capab(dev[0])
1847    check_dpp_capab(dev[1])
1848    check_sae_capab(dev[0])
1849
1850    params = hostapd.wpa2_params(ssid="DPPNET01",
1851                                 passphrase="ThisIsDppPassphrase")
1852    params['wpa_key_mgmt'] = 'SAE'
1853    params["ieee80211w"] = "2"
1854    hapd = hostapd.add_ap(apdev[0], params)
1855
1856    with SigmaDut(dev=dev[0]) as dut:
1857        dev[0].set("dpp_config_processing", "2")
1858        dev[0].set("sae_groups", "")
1859
1860        cmd = "DPP_CONFIGURATOR_ADD"
1861        res = dev[1].request(cmd)
1862        if "FAIL" in res:
1863            raise Exception("Failed to add configurator")
1864        conf_id = int(res)
1865
1866        id0 = dev[1].dpp_bootstrap_gen(chan="81/6", mac=True)
1867        uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
1868
1869        dev[1].set("dpp_configurator_params",
1870                   " conf=sta-sae ssid=%s pass=%s configurator=%d" % (to_hex("DPPNET01"), to_hex("ThisIsDppPassphrase"), conf_id))
1871        cmd = "DPP_LISTEN 2437 role=configurator"
1872        if "OK" not in dev[1].request(cmd):
1873            raise Exception("Failed to start listen operation")
1874
1875        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % to_hex(uri0))
1876        if "status,COMPLETE" not in res:
1877            raise Exception("dev_exec_action did not succeed: " + res)
1878
1879        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Enrollee,DPPBS,QR,DPPTimeout,6,DPPWaitForConnect,Yes", timeout=10)
1880        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK,NetworkConnectResult,OK" not in res:
1881            raise Exception("Unexpected result: " + res)
1882
1883def test_sigma_dut_dpp_qr_init_configurator_1(dev, apdev):
1884    """sigma_dut DPP/QR initiator as Configurator (conf index 1)"""
1885    run_sigma_dut_dpp_qr_init_configurator(dev, apdev, 1)
1886
1887def test_sigma_dut_dpp_qr_init_configurator_2(dev, apdev):
1888    """sigma_dut DPP/QR initiator as Configurator (conf index 2)"""
1889    run_sigma_dut_dpp_qr_init_configurator(dev, apdev, 2)
1890
1891def test_sigma_dut_dpp_qr_init_configurator_3(dev, apdev):
1892    """sigma_dut DPP/QR initiator as Configurator (conf index 3)"""
1893    run_sigma_dut_dpp_qr_init_configurator(dev, apdev, 3)
1894
1895def test_sigma_dut_dpp_qr_init_configurator_4(dev, apdev):
1896    """sigma_dut DPP/QR initiator as Configurator (conf index 4)"""
1897    run_sigma_dut_dpp_qr_init_configurator(dev, apdev, 4)
1898
1899def test_sigma_dut_dpp_qr_init_configurator_5(dev, apdev):
1900    """sigma_dut DPP/QR initiator as Configurator (conf index 5)"""
1901    run_sigma_dut_dpp_qr_init_configurator(dev, apdev, 5)
1902
1903def test_sigma_dut_dpp_qr_init_configurator_6(dev, apdev):
1904    """sigma_dut DPP/QR initiator as Configurator (conf index 6)"""
1905    run_sigma_dut_dpp_qr_init_configurator(dev, apdev, 6)
1906
1907def test_sigma_dut_dpp_qr_init_configurator_7(dev, apdev):
1908    """sigma_dut DPP/QR initiator as Configurator (conf index 7)"""
1909    run_sigma_dut_dpp_qr_init_configurator(dev, apdev, 7)
1910
1911def test_sigma_dut_dpp_qr_init_configurator_both(dev, apdev):
1912    """sigma_dut DPP/QR initiator as Configurator or Enrollee (conf index 1)"""
1913    run_sigma_dut_dpp_qr_init_configurator(dev, apdev, 1, "Both")
1914
1915def test_sigma_dut_dpp_qr_init_configurator_neg_freq(dev, apdev):
1916    """sigma_dut DPP/QR initiator as Configurator (neg_freq)"""
1917    run_sigma_dut_dpp_qr_init_configurator(dev, apdev, 1, extra='DPPSubsequentChannel,81/11')
1918
1919def test_sigma_dut_dpp_qr_init_configurator_mud_url(dev, apdev):
1920    """sigma_dut DPP/QR initiator as Configurator (MUD URL)"""
1921    run_sigma_dut_dpp_qr_init_configurator(dev, apdev, 1,
1922                                           mud_url="https://example.com/mud")
1923
1924def test_sigma_dut_dpp_qr_init_configurator_mud_url_nak_change(dev, apdev):
1925    """sigma_dut DPP/QR initiator as Configurator (MUD URL, NAK change)"""
1926    run_sigma_dut_dpp_qr_init_configurator(dev, apdev, 1,
1927                                           mud_url="https://example.com/mud",
1928                                           net_access_key_curve="P-384")
1929
1930def test_sigma_dut_dpp_qr_init_configurator_sign_curve_from_uri(dev, apdev):
1931    """sigma_dut DPP/QR initiator as Configurator (signing key from URI)"""
1932    run_sigma_dut_dpp_qr_init_configurator(dev, apdev, 1,
1933                                           sign_curve_from_uri=True)
1934
1935def test_sigma_dut_dpp_qr_init_configurator_nak_from_uri(dev, apdev):
1936    """sigma_dut DPP/QR initiator as Configurator (NAK from URI)"""
1937    run_sigma_dut_dpp_qr_init_configurator(dev, apdev, 1,
1938                                           net_access_key_curve="URI")
1939
1940def test_sigma_dut_dpp_qr_init_configurator_3rd_party(dev, apdev):
1941    """sigma_dut DPP/QR initiator as Configurator (3rd party info)"""
1942    run_sigma_dut_dpp_qr_init_configurator(dev, apdev, 1,
1943                                           extra="DPP3rdParty,Yes")
1944
1945def test_sigma_dut_dpp_qr_init_configurator_3rd_party_psk(dev, apdev):
1946    """sigma_dut DPP/QR initiator as Configurator (3rd party info with PSK)"""
1947    run_sigma_dut_dpp_qr_init_configurator(dev, apdev, 2,
1948                                           extra="DPP3rdParty,Yes")
1949
1950def run_sigma_dut_dpp_qr_init_configurator(dev, apdev, conf_idx,
1951                                           prov_role="Configurator",
1952                                           extra=None, mud_url=None,
1953                                           net_access_key_curve=None,
1954                                           sign_curve_from_uri=False):
1955    min_ver = 3 if net_access_key_curve else 1
1956    check_dpp_capab(dev[0], min_ver=min_ver)
1957    check_dpp_capab(dev[1], min_ver=min_ver)
1958    with SigmaDut(dev=dev[0]) as dut:
1959        supported_curves = None
1960        sign_curve = "P-256"
1961
1962        if sign_curve_from_uri:
1963            supported_curves = "P-256:P-384:P-521"
1964            sign_curve = "URI"
1965        if net_access_key_curve == "URI":
1966            supported_curves = "P-256:P-384:P-521"
1967
1968        id0 = dev[1].dpp_bootstrap_gen(chan="81/6", mac=True,
1969                                       supported_curves=supported_curves)
1970        uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
1971
1972        if mud_url:
1973            dev[1].set("dpp_mud_url", mud_url)
1974        cmd = "DPP_LISTEN 2437 role=enrollee"
1975        if "OK" not in dev[1].request(cmd):
1976            raise Exception("Failed to start listen operation")
1977
1978        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % to_hex(uri0))
1979        if "status,COMPLETE" not in res:
1980            raise Exception("dev_exec_action did not succeed: " + res)
1981
1982        cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,%s,DPPConfIndex,%d,DPPSigningKeyECC,%s,DPPConfEnrolleeRole,STA,DPPBS,QR,DPPTimeout,6" % (prov_role, conf_idx, sign_curve)
1983        if net_access_key_curve:
1984            cmd += ",DPPNAKECC," + net_access_key_curve
1985        if extra:
1986            cmd += "," + extra
1987        res = dut.run_cmd(cmd)
1988        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
1989            raise Exception("Unexpected result: " + res)
1990        if mud_url and ",MUDURL," + mud_url not in res:
1991            raise Exception("Unexpected result (missing MUD URL): " + res)
1992
1993    dev[1].set("dpp_mud_url", "")
1994
1995def test_sigma_dut_dpp_incompatible_roles_init(dev, apdev):
1996    """sigma_dut DPP roles incompatible (Initiator)"""
1997    check_dpp_capab(dev[0])
1998    check_dpp_capab(dev[1])
1999    with SigmaDut(dev=dev[0]) as dut:
2000        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR")
2001        if "status,COMPLETE" not in res:
2002            raise Exception("dev_exec_action did not succeed: " + res)
2003        hex = res.split(',')[3]
2004        uri = from_hex(hex)
2005        logger.info("URI from sigma_dut: " + uri)
2006
2007        id1 = dev[1].dpp_qr_code(uri)
2008
2009        id0 = dev[1].dpp_bootstrap_gen(chan="81/6", mac=True)
2010        uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
2011
2012        cmd = "DPP_LISTEN 2437 role=enrollee"
2013        if "OK" not in dev[1].request(cmd):
2014            raise Exception("Failed to start listen operation")
2015
2016        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % to_hex(uri0))
2017        if "status,COMPLETE" not in res:
2018            raise Exception("dev_exec_action did not succeed: " + res)
2019
2020        cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Mutual,DPPProvisioningRole,Enrollee,DPPBS,QR,DPPTimeout,6"
2021        res = dut.run_cmd(cmd)
2022        if "BootstrapResult,OK,AuthResult,ROLES_NOT_COMPATIBLE" not in res:
2023            raise Exception("Unexpected result: " + res)
2024
2025def test_sigma_dut_dpp_curves_list(dev, apdev):
2026    """sigma_dut DPP URI curves list override"""
2027    check_dpp_capab(dev[0], min_ver=3)
2028    with SigmaDut(dev=dev[0]) as dut:
2029        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR,DPPURICurves,P-256:P-384:BP-384")
2030        if "status,COMPLETE" not in res:
2031            raise Exception("dev_exec_action did not succeed: " + res)
2032        hex = res.split(',')[3]
2033        uri = from_hex(hex)
2034        logger.info("URI from sigma_dut: " + uri)
2035        if ";B:31" not in uri:
2036            raise Exception("Supported curves override did not work correctly")
2037
2038def test_sigma_dut_dpp_enrollee_does_not_support_signing_curve(dev, apdev):
2039    """sigma_dut DPP and Enrollee URI curves list does not include the curve for C-sign-key"""
2040    check_dpp_capab(dev[0], min_ver=3)
2041    check_dpp_capab(dev[1], min_ver=3)
2042    with SigmaDut(dev=dev[0]) as dut:
2043        id1 = dev[1].dpp_bootstrap_gen(chan="81/6", mac=True,
2044                                       supported_curves="P-256:P-384")
2045        uri = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id1)
2046        dev[1].dpp_listen(2437)
2047
2048        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % to_hex(uri))
2049        if "status,COMPLETE" not in res:
2050            raise Exception("dev_exec_action did not succeed: " + res)
2051
2052        cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Configurator,DPPConfIndex,1,DPPSigningKeyECC,P-521,DPPConfEnrolleeRole,STA,DPPBS,QR,DPPTimeout,6"
2053        res = dut.run_cmd(cmd, timeout=10)
2054        if "status,COMPLETE" not in res:
2055            raise Exception("dev_exec_action did not succeed: " + res)
2056        if "BootstrapResult,OK,AuthResult,OK,ConfResult,FAILED" not in res:
2057            raise Exception("Unexpected result: " + res)
2058        ev = dev[1].wait_event(["DPP-CONF-RECEIVED", "DPP-CONF-FAILED"],
2059                               timeout=20)
2060        if not ev:
2061            raise Exception("Enrollee did not report configuration result")
2062        if "DPP-CONF-RECEIVED" in ev:
2063            raise Exception("Enrollee reported configuration success")
2064
2065def test_sigma_dut_dpp_enrollee_does_not_support_nak_curve(dev, apdev):
2066    """sigma_dut DPP and Enrollee URI curves list does not include the curve for C-sign-key"""
2067    check_dpp_capab(dev[0], min_ver=3)
2068    check_dpp_capab(dev[1], min_ver=3)
2069    with SigmaDut(dev=dev[0]) as dut:
2070        id1 = dev[1].dpp_bootstrap_gen(chan="81/6", mac=True,
2071                                       supported_curves="P-256:P-384")
2072        uri = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id1)
2073        dev[1].dpp_listen(2437)
2074
2075        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % to_hex(uri))
2076        if "status,COMPLETE" not in res:
2077            raise Exception("dev_exec_action did not succeed: " + res)
2078
2079        cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Configurator,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPNAKECC,P-521,DPPConfEnrolleeRole,STA,DPPBS,QR,DPPTimeout,6"
2080        res = dut.run_cmd(cmd, timeout=10)
2081        if "status,COMPLETE" not in res:
2082            raise Exception("dev_exec_action did not succeed: " + res)
2083        ev = dev[1].wait_event(["DPP-CONF-RECEIVED", "DPP-CONF-FAILED"],
2084                               timeout=20)
2085        if not ev:
2086            raise Exception("Enrollee did not report configuration result")
2087        if "DPP-CONF-RECEIVED" in ev:
2088            raise Exception("Enrollee reported configuration success")
2089
2090def dpp_init_enrollee_mutual(dev, id1, own_id):
2091    logger.info("Starting DPP initiator/enrollee in a thread")
2092    time.sleep(1)
2093    cmd = "DPP_AUTH_INIT peer=%d own=%d role=enrollee" % (id1, own_id)
2094    if "OK" not in dev.request(cmd):
2095        raise Exception("Failed to initiate DPP Authentication")
2096    ev = dev.wait_event(["DPP-CONF-RECEIVED",
2097                         "DPP-NOT-COMPATIBLE"], timeout=5)
2098    if ev is None:
2099        raise Exception("DPP configuration not completed (Enrollee)")
2100    logger.info("DPP initiator/enrollee done")
2101
2102def test_sigma_dut_dpp_incompatible_roles_resp(dev, apdev):
2103    """sigma_dut DPP roles incompatible (Responder)"""
2104    check_dpp_capab(dev[0])
2105    check_dpp_capab(dev[1])
2106    with SigmaDut(dev=dev[0]) as dut:
2107        cmd = "dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR"
2108        res = dut.run_cmd(cmd)
2109        if "status,COMPLETE" not in res:
2110            raise Exception("dev_exec_action did not succeed: " + res)
2111        hex = res.split(',')[3]
2112        uri = from_hex(hex)
2113        logger.info("URI from sigma_dut: " + uri)
2114
2115        id1 = dev[1].dpp_qr_code(uri)
2116
2117        id0 = dev[1].dpp_bootstrap_gen(chan="81/6", mac=True)
2118        uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
2119
2120        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % to_hex(uri0))
2121        if "status,COMPLETE" not in res:
2122            raise Exception("dev_exec_action did not succeed: " + res)
2123
2124        t = threading.Thread(target=dpp_init_enrollee_mutual, args=(dev[1], id1, id0))
2125        t.start()
2126        cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPAuthDirection,Mutual,DPPProvisioningRole,Enrollee,DPPBS,QR,DPPTimeout,6"
2127        res = dut.run_cmd(cmd, timeout=10)
2128        t.join()
2129        if "BootstrapResult,OK,AuthResult,ROLES_NOT_COMPATIBLE" not in res:
2130            raise Exception("Unexpected result: " + res)
2131
2132def test_sigma_dut_dpp_qr_enrollee_chirp(dev, apdev):
2133    """sigma_dut DPP/QR as chirping Enrollee"""
2134    run_sigma_dut_dpp_qr_enrollee_chirp(dev, apdev)
2135
2136def test_sigma_dut_dpp_qr_enrollee_chirp_3rd_party_info(dev, apdev):
2137    """sigma_dut DPP/QR as chirping Enrollee (3rd party info in request)"""
2138    run_sigma_dut_dpp_qr_enrollee_chirp(dev, apdev, extra="DPP3rdParty,Yes")
2139
2140def run_sigma_dut_dpp_qr_enrollee_chirp(dev, apdev, extra=None):
2141    check_dpp_capab(dev[0])
2142    check_dpp_capab(dev[1])
2143    hapd = start_dpp_ap(apdev[0])
2144    ifname = dev[0].ifname
2145    with SigmaDut(dev=dev[0]) as dut:
2146        dut.cmd_check("sta_reset_default,interface,%s,prog,DPP" % ifname)
2147        cmd = "dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR"
2148        res = dut.cmd_check(cmd)
2149        if "status,COMPLETE" not in res:
2150            raise Exception("dev_exec_action did not succeed: " + res)
2151        hex = res.split(',')[3]
2152        uri = from_hex(hex)
2153        logger.info("URI from sigma_dut: " + uri)
2154
2155        conf_id = dev[1].dpp_configurator_add(key=csign)
2156        idc = dev[1].dpp_qr_code(uri)
2157        dev[1].dpp_bootstrap_set(idc, conf="sta-dpp", configurator=conf_id,
2158                                 ssid="DPPNET01")
2159        dev[1].dpp_listen(2437)
2160
2161        cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPAuthDirection,Single,DPPProvisioningRole,Enrollee,DPPBS,QR,DPPTimeout,16,DPPWaitForConnect,Yes,DPPChirp,Enable"
2162        if extra:
2163            cmd += "," + extra
2164        res = dut.cmd_check(cmd, timeout=20)
2165        dut.cmd_check("sta_reset_default,interface,%s,prog,DPP" % ifname)
2166        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK,NetworkIntroResult,OK,NetworkConnectResult,OK" not in res:
2167            raise Exception("Unexpected result: " + res)
2168
2169def dpp_enrollee_chirp(dev, id1):
2170    logger.info("Starting chirping Enrollee in a thread")
2171    time.sleep(0.1)
2172    cmd = "DPP_CHIRP own=%d" % id1
2173    if "OK" not in dev.request(cmd):
2174        raise Exception("Failed to initiate DPP chirping")
2175    ev = dev.wait_event(["DPP-CONF-RECEIVED"], timeout=15)
2176    if ev is None:
2177        raise Exception("DPP configuration not completed (Enrollee)")
2178    logger.info("DPP enrollee done")
2179
2180def test_sigma_dut_dpp_qr_configurator_chirp(dev, apdev):
2181    """sigma_dut DPP/QR as Configurator waiting for chirp"""
2182    check_dpp_capab(dev[0])
2183    check_dpp_capab(dev[1])
2184    ifname = dev[0].ifname
2185    with SigmaDut(dev=dev[0]) as dut:
2186        dut.cmd_check("sta_reset_default,interface,%s,prog,DPP" % ifname)
2187
2188        id1 = dev[1].dpp_bootstrap_gen(chan="81/1")
2189        uri = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id1)
2190
2191        res = dut.cmd_check("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % to_hex(uri))
2192        if "status,COMPLETE" not in res:
2193            raise Exception("dev_exec_action did not succeed: " + res)
2194
2195        t = threading.Thread(target=dpp_enrollee_chirp, args=(dev[1], id1))
2196        t.start()
2197        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Configurator,DPPConfIndex,1,DPPConfEnrolleeRole,STA,DPPBS,QR,DPPTimeout,16,DPPChirp,Enable,DPPChirpChannel,6", timeout=20)
2198        t.join()
2199        dut.cmd_check("sta_reset_default,interface,%s,prog,DPP" % ifname)
2200        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
2201            raise Exception("Unexpected result: " + res)
2202
2203def test_sigma_dut_ap_dpp_qr_enrollee_chirp(dev, apdev, params):
2204    """sigma_dut DPP/QR AP as chirping Enrollee"""
2205    check_dpp_capab(dev[0], min_ver=2)
2206    check_dpp_capab(dev[1])
2207    logdir = params['prefix'] + ".sigma-hostapd"
2208    with HWSimRadio() as (radio, iface), \
2209         SigmaDut(iface, hostapd_logdir=logdir) as dut:
2210        try:
2211            dut.cmd_check("ap_reset_default,program,DPP")
2212            cmd = "dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR"
2213            res = dut.cmd_check(cmd)
2214            if "status,COMPLETE" not in res:
2215                raise Exception("dev_exec_action did not succeed: " + res)
2216            hex = res.split(',')[3]
2217            uri = from_hex(hex)
2218            logger.info("URI from sigma_dut: " + uri)
2219
2220            conf_id = dev[0].dpp_configurator_add(key=csign)
2221            idc = dev[0].dpp_qr_code(uri)
2222            dev[0].dpp_bootstrap_set(idc, conf="ap-dpp", configurator=conf_id,
2223                                 ssid="DPPNET01")
2224            dev[0].dpp_listen(2437)
2225
2226            res = dut.cmd_check("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPAuthDirection,Single,DPPProvisioningRole,Enrollee,DPPBS,QR,DPPTimeout,16,DPPChirp,Enable", timeout=20)
2227            if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
2228                raise Exception("Unexpected result: " + res)
2229
2230            dev[1].set("dpp_config_processing", "2")
2231            id = dev[1].dpp_bootstrap_gen(chan="81/6", mac=True)
2232            uri = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id)
2233            dev[1].dpp_listen(2437)
2234            dev[0].dpp_auth_init(uri=uri, conf="sta-dpp", ssid="DPPNET01",
2235                                 configurator=conf_id)
2236            dev[1].wait_connected(timeout=20)
2237        finally:
2238            dev[1].set("dpp_config_processing", "0", allow_fail=True)
2239
2240def test_sigma_dut_dpp_pkex_init_configurator(dev, apdev):
2241    """sigma_dut DPP/PKEX initiator as Configurator"""
2242    check_dpp_capab(dev[0])
2243    check_dpp_capab(dev[1])
2244    with SigmaDut(dev=dev[0]) as dut:
2245        id1 = dev[1].dpp_bootstrap_gen(type="pkex")
2246        cmd = "DPP_PKEX_ADD own=%d identifier=test code=secret" % (id1)
2247        res = dev[1].request(cmd)
2248        if "FAIL" in res:
2249            raise Exception("Failed to set PKEX data (responder)")
2250        cmd = "DPP_LISTEN 2437 role=enrollee"
2251        if "OK" not in dev[1].request(cmd):
2252            raise Exception("Failed to start listen operation")
2253
2254        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPProvisioningRole,Configurator,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,STA,DPPBS,PKEX,DPPPKEXCodeIdentifier,test,DPPPKEXCode,secret,DPPTimeout,6")
2255        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
2256            raise Exception("Unexpected result: " + res)
2257
2258def test_sigma_dut_dpp_pkex_init_configurator_tcp(dev, apdev):
2259    """sigma_dut DPP/PKEX initiator as Configurator (TCP)"""
2260    check_dpp_capab(dev[0], min_ver=3)
2261    check_dpp_capab(dev[1], min_ver=3)
2262    with SigmaDut(dev=dev[0]) as dut:
2263        cmd = "DPP_CONTROLLER_START"
2264        res = dev[1].request(cmd)
2265        if "FAIL" in res:
2266            raise Exception("Failed to start Controller")
2267        id1 = dev[1].dpp_bootstrap_gen(type="pkex")
2268        cmd = "DPP_PKEX_ADD own=%d identifier=test code=secret" % (id1)
2269        res = dev[1].request(cmd)
2270        if "FAIL" in res:
2271            raise Exception("Failed to set PKEX data (responder)")
2272
2273        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPProvisioningRole,Configurator,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,STA,DPPBS,PKEX,DPPPKEXCodeIdentifier,test,DPPPKEXCode,secret,DPPTimeout,6,DPPOverTCP,127.0.0.1")
2274        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
2275            raise Exception("Unexpected result: " + res)
2276
2277def test_sigma_dut_dpp_pkex_init_configurator_tcp_through_relay(dev, apdev):
2278    """sigma_dut DPP/PKEX initiator as Configurator (TCP) through Relay"""
2279    check_dpp_capab(dev[0], min_ver=3)
2280    check_dpp_capab(dev[1], min_ver=3)
2281
2282    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured", "channel": "6"})
2283    check_dpp_capab(hapd)
2284
2285    with SigmaDut(dev=dev[0]) as dut:
2286        # PKEX init (AP Enrollee) over air
2287        id1 = hapd.dpp_bootstrap_gen(type="pkex")
2288        cmd = "DPP_PKEX_ADD own=%d identifier=test code=secret" % (id1)
2289        res =  hapd.request(cmd)
2290        if "FAIL" in res:
2291            raise Exception("Failed to set PKEX data (responder AP)")
2292
2293        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPProvisioningRole,Configurator,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,AP,DPPBS,PKEX,DPPPKEXCodeIdentifier,test,DPPPKEXCode,secret,DPPTimeout,6")
2294        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
2295            raise Exception("Unexpected result: " + res)
2296        update_hapd_config(hapd)
2297
2298        # Relay
2299        port = 8909
2300        pkhash = "05be01e0eb79ae5d2a174d9fc83548638d325f25ee9c5840dfe6dfe8b1ae6517"
2301        params = {"ssid": "unconfigured",
2302                  "channel": "6",
2303                  "dpp_controller": "ipaddr=127.0.0.1 pkhash=" + pkhash,
2304                  "dpp_relay_port": str(port)}
2305        relay = hostapd.add_ap(apdev[1], params)
2306        check_dpp_capab(relay)
2307
2308        # PKEX init (STA Enrollee) through Relay
2309        dev[1].set("dpp_config_processing", "2")
2310        dev[1].dpp_listen(2437)
2311        id1 = dev[1].dpp_bootstrap_gen(type="pkex")
2312        cmd = "DPP_PKEX_ADD own=%d identifier=test code=secret" % (id1)
2313        res = dev[1].request(cmd)
2314        if "FAIL" in res:
2315            raise Exception("Failed to set PKEX data (responder)")
2316
2317        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPProvisioningRole,Configurator,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,STA,DPPBS,PKEX,DPPPKEXCodeIdentifier,test,DPPPKEXCode,secret,DPPTimeout,6,DPPOverTCP,127.0.0.1 tcp_port=8909")
2318        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
2319            raise Exception("Unexpected result: " + res)
2320
2321        ev = dev[1].wait_event(["DPP-NETWORK-ID"], timeout=1)
2322        if ev is None:
2323            raise Exception("DPP network id not reported")
2324        network = int(ev.split(' ')[1])
2325        dev[1].wait_connected()
2326        dev[1].dump_monitor()
2327        dev[1].request("DISCONNECT")
2328        dev[1].wait_disconnected()
2329        dev[1].dump_monitor()
2330        if "OK" not in dev[1].request("DPP_RECONFIG %s" % network):
2331            raise Exception("Failed to start reconfiguration")
2332
2333        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,DPPReconfigure,DPPCryptoIdentifier,P-256,DPPProvisioningRole,Configurator,DPPConfIndex,1,DPPConfEnrolleeRole,STA,DPPTimeout,6,DPPSigningKeyECC,P-256,DPPOverTCP,yes", timeout=10)
2334        if "ReconfigAuthResult,OK,ConfResult,OK" not in res:
2335            raise Exception("Unexpected reconfiguration result: " + res)
2336
2337        ev = dev[1].wait_event(["DPP-NETWORK-ID"], timeout=15)
2338        if ev is None:
2339            raise Exception("DPP network id not reported for reconfiguration")
2340        network2 = int(ev.split(' ')[1])
2341        if network == network2:
2342            raise Exception("Network ID did not change")
2343        dev[1].wait_connected()
2344
2345    dev[1].set("dpp_config_processing", "0", allow_fail=True)
2346
2347def test_sigma_dut_dpp_pkex_init_configurator_tcp_and_wifi(dev, apdev):
2348    """sigma_dut DPP/PKEX initiator as Configurator over TCP and Wi-Fi"""
2349    check_dpp_capab(dev[0], min_ver=3)
2350    check_dpp_capab(dev[1], min_ver=3)
2351
2352    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured", "channel": "6"})
2353    check_dpp_capab(hapd)
2354
2355    with SigmaDut(dev=dev[0]) as dut:
2356        # PKEX init (AP Enrollee) over air
2357        id1 = hapd.dpp_bootstrap_gen(type="pkex")
2358        cmd = "DPP_PKEX_ADD own=%d identifier=test code=secret" % (id1)
2359        res =  hapd.request(cmd)
2360        if "FAIL" in res:
2361            raise Exception("Failed to set PKEX data (responder AP)")
2362
2363        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPProvisioningRole,Configurator,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,AP,DPPBS,PKEX,DPPPKEXCodeIdentifier,test,DPPPKEXCode,secret,DPPTimeout,6")
2364        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
2365            raise Exception("Unexpected result: " + res)
2366        ev = hapd.wait_event(["DPP-CONF-RECEIVED"], timeout=1)
2367        if ev is None:
2368            raise Exception("AP Enrollee did not report success")
2369
2370        # Relay
2371        port = 8908
2372        pkhash = "05be01e0eb79ae5d2a174d9fc83548638d325f25ee9c5840dfe6dfe8b1ae6517"
2373        params = {"ssid": "unconfigured",
2374                  "channel": "6",
2375                  "dpp_controller": "ipaddr=127.0.0.1 pkhash=" + pkhash,
2376                  "dpp_relay_port": str(port)}
2377        relay = hostapd.add_ap(apdev[1], params)
2378        check_dpp_capab(relay)
2379
2380        # PKEX init (STA Enrollee) through Relay
2381        dev[1].dpp_listen(2437)
2382        id1 = dev[1].dpp_bootstrap_gen(type="pkex")
2383        cmd = "DPP_PKEX_ADD own=%d identifier=test code=secret" % (id1)
2384        res = dev[1].request(cmd)
2385        if "FAIL" in res:
2386            raise Exception("Failed to set PKEX data (responder)")
2387
2388        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPProvisioningRole,Configurator,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,STA,DPPBS,PKEX,DPPPKEXCodeIdentifier,test,DPPPKEXCode,secret,DPPTimeout,6,DPPOverTCP,127.0.0.1")
2389        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
2390            raise Exception("Unexpected result: " + res)
2391
2392        ev = dev[1].wait_event(["DPP-CONF-RECEIVED"], timeout=1)
2393        if ev is None:
2394            raise Exception("STA Enrollee did not report success")
2395        dev[1].request("DPP_STOP_LISTEN")
2396        dev[1].dump_monitor()
2397
2398        # PKEX init (STA Enrollee) over air
2399        dev[1].dpp_listen(2437)
2400        id1 = dev[1].dpp_bootstrap_gen(type="pkex")
2401        cmd = "DPP_PKEX_ADD own=%d identifier=test code=secret" % (id1)
2402        res = dev[1].request(cmd)
2403        if "FAIL" in res:
2404            raise Exception("Failed to set PKEX data (responder)")
2405
2406        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPProvisioningRole,Configurator,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,STA,DPPBS,PKEX,DPPPKEXCodeIdentifier,test,DPPPKEXCode,secret,DPPTimeout,6")
2407        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
2408            raise Exception("Unexpected result: " + res)
2409
2410        ev = dev[1].wait_event(["DPP-CONF-RECEIVED"], timeout=1)
2411        if ev is None:
2412            raise Exception("STA(2) Enrollee did not report success")
2413        dev[1].request("DPP_STOP_LISTEN")
2414        dev[1].dump_monitor()
2415
2416        # PKEX init (STA Enrollee) through Relay
2417        dev[1].dpp_listen(2437)
2418        id1 = dev[1].dpp_bootstrap_gen(type="pkex")
2419        cmd = "DPP_PKEX_ADD own=%d identifier=test code=secret" % (id1)
2420        res = dev[1].request(cmd)
2421        if "FAIL" in res:
2422            raise Exception("Failed to set PKEX data (responder)")
2423
2424        # Make things more complex by allowing frames from Relay to be seen on
2425        # the Controller over the air.
2426        dev[0].dpp_listen(2437)
2427
2428        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPProvisioningRole,Configurator,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,STA,DPPBS,PKEX,DPPPKEXCodeIdentifier,test,DPPPKEXCode,secret,DPPTimeout,6,DPPOverTCP,127.0.0.1")
2429        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
2430            raise Exception("Unexpected result: " + res)
2431
2432        ev = dev[1].wait_event(["DPP-CONF-RECEIVED"], timeout=1)
2433        if ev is None:
2434            raise Exception("STA(3) Enrollee did not report success")
2435        dev[1].request("DPP_STOP_LISTEN")
2436        dev[1].dump_monitor()
2437
2438def dpp_pkex_resp_start_on_v1(dev):
2439    while True:
2440        ev = dev.wait_event(["DPP-RX"], timeout=5)
2441        if ev is None:
2442            return
2443        if "type=7" in ev:
2444            logger.info("Starting PKEXv1 responder in a thread")
2445            id1 = dev.dpp_bootstrap_gen(type="pkex")
2446            cmd = "DPP_PKEX_ADD own=%d identifier=test code=secret" % (id1)
2447            res = dev.request(cmd)
2448            if "FAIL" in res:
2449                raise Exception("Failed to set PKEX data (responder)")
2450            return
2451
2452def test_sigma_dut_dpp_pkexv2_init_fallback_to_v1(dev, apdev):
2453    """sigma_dut DPP/PKEXv2 initiator and fallback to v1"""
2454    check_dpp_capab(dev[0], min_ver=3)
2455    with SigmaDut(dev=dev[0]) as dut:
2456        cmd = "DPP_LISTEN 2437 role=enrollee"
2457        if "OK" not in dev[1].request(cmd):
2458            raise Exception("Failed to start listen operation")
2459        t = threading.Thread(target=dpp_pkex_resp_start_on_v1, args=(dev[1],))
2460        t.start()
2461
2462        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPProvisioningRole,Configurator,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,STA,DPPBS,PKEX,DPPPKEXCodeIdentifier,test,DPPPKEXCode,secret,DPPTimeout,30",
2463                            timeout=31)
2464        t.join()
2465        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
2466            raise Exception("Unexpected result: " + res)
2467
2468def test_sigma_dut_dpp_pkex_v1_only(dev, apdev):
2469    """sigma_dut DPP/PKEX as v1 only initiator"""
2470    check_dpp_capab(dev[0])
2471    check_dpp_capab(dev[1])
2472    with SigmaDut(dev=dev[0]) as dut:
2473        id1 = dev[1].dpp_bootstrap_gen(type="pkex")
2474        cmd = "DPP_PKEX_ADD own=%d identifier=test code=secret" % (id1)
2475        res = dev[1].request(cmd)
2476        if "FAIL" in res:
2477            raise Exception("Failed to set PKEX data (responder)")
2478        cmd = "DPP_LISTEN 2437 role=enrollee"
2479        if "OK" not in dev[1].request(cmd):
2480            raise Exception("Failed to start listen operation")
2481
2482        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPProvisioningRole,Configurator,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,STA,DPPBS,PKEXv1,DPPPKEXCodeIdentifier,test,DPPPKEXCode,secret,DPPTimeout,6")
2483        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
2484            raise Exception("Unexpected result: " + res)
2485
2486def test_sigma_dut_dpp_pkex_v1_only_responder(dev, apdev):
2487    """sigma_dut DPP/PKEX as v1 only responder"""
2488    run_sigma_dut_dpp_pkex_responder(dev, apdev, v1=True)
2489
2490def test_sigma_dut_dpp_pkex_responder(dev, apdev):
2491    """sigma_dut DPP/PKEX as responder"""
2492    run_sigma_dut_dpp_pkex_responder(dev, apdev)
2493
2494def dpp_init_enrollee_pkex(dev):
2495    logger.info("Starting DPP PKEX initiator/enrollee in a thread")
2496    time.sleep(1.5)
2497    id = dev.dpp_bootstrap_gen(type="pkex")
2498    cmd = "DPP_PKEX_ADD own=%d init=1 role=enrollee identifier=test code=secret" % id
2499    res = dev.request(cmd)
2500    if "FAIL" in res:
2501        raise Exception("Failed to initiate DPP PKEX")
2502    ev = dev.wait_event(["DPP-CONF-RECEIVED"], timeout=15)
2503    if ev is None:
2504        raise Exception("DPP configuration not completed (Enrollee)")
2505    logger.info("DPP initiator/enrollee done")
2506
2507def run_sigma_dut_dpp_pkex_responder(dev, apdev, v1=False):
2508    check_dpp_capab(dev[0])
2509    check_dpp_capab(dev[1])
2510    with SigmaDut(dev=dev[0]) as dut:
2511        dut.cmd_check("sta_reset_default,interface,%s,prog,DPP" %
2512                            dev[0].ifname)
2513        t = threading.Thread(target=dpp_init_enrollee_pkex, args=(dev[1],))
2514        t.start()
2515        dppbs = "PKEXv1" if v1 else "PKEX"
2516        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPProvisioningRole,Configurator,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,STA,DPPBS,%s,DPPPKEXCodeIdentifier,test,DPPPKEXCode,secret,DPPTimeout,16" % dppbs, timeout=20)
2517        t.join()
2518        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
2519            raise Exception("Unexpected result: " + res)
2520
2521def dpp_init_conf(dev, id1, conf, conf_id, extra):
2522    time.sleep(1)
2523    logger.info("Starting DPP initiator/configurator in a thread")
2524    cmd = "DPP_AUTH_INIT peer=%d conf=%s %s configurator=%d" % (id1, conf, extra, conf_id)
2525    if "OK" not in dev.request(cmd):
2526        raise Exception("Failed to initiate DPP Authentication")
2527    ev = dev.wait_event(["DPP-CONF-SENT"], timeout=5)
2528    if ev is None:
2529        raise Exception("DPP configuration not completed (Configurator)")
2530    logger.info("DPP initiator/configurator done")
2531
2532def test_sigma_dut_ap_dpp_qr(dev, apdev, params):
2533    """sigma_dut controlled AP (DPP)"""
2534    run_sigma_dut_ap_dpp_qr(dev, apdev, params, "ap-dpp", "sta-dpp")
2535
2536def test_sigma_dut_ap_dpp_qr_legacy(dev, apdev, params):
2537    """sigma_dut controlled AP (legacy)"""
2538    run_sigma_dut_ap_dpp_qr(dev, apdev, params, "ap-psk", "sta-psk",
2539                            extra="pass=%s" % to_hex("qwertyuiop"))
2540
2541def test_sigma_dut_ap_dpp_qr_legacy_psk(dev, apdev, params):
2542    """sigma_dut controlled AP (legacy)"""
2543    run_sigma_dut_ap_dpp_qr(dev, apdev, params, "ap-psk", "sta-psk",
2544                            extra="psk=%s" % (32*"12"))
2545
2546def test_sigma_dut_ap_dpp_qr_sae(dev, apdev, params):
2547    """sigma_dut controlled AP (SAE)"""
2548    run_sigma_dut_ap_dpp_qr(dev, apdev, params, "ap-sae", "sta-sae",
2549                            extra="pass=%s" % to_hex("qwertyuiop"))
2550
2551def test_sigma_dut_ap_dpp_qr_dpp_sae(dev, apdev, params):
2552    """sigma_dut controlled AP (DPP+SAE)"""
2553    run_sigma_dut_ap_dpp_qr(dev, apdev, params, "ap-sae-dpp", "sta-sae",
2554                            extra="pass=%s" % to_hex("qwertyuiop"))
2555
2556def test_sigma_dut_ap_dpp_qr_dpp_sae2(dev, apdev, params):
2557    """sigma_dut controlled AP (DPP+SAE)"""
2558    run_sigma_dut_ap_dpp_qr(dev, apdev, params, "ap-sae-dpp", "sta-dpp",
2559                            extra="pass=%s" % to_hex("qwertyuiop"))
2560
2561def test_sigma_dut_ap_dpp_qr_mud_url(dev, apdev, params):
2562    """sigma_dut controlled AP (DPP) with MUD URL"""
2563    run_sigma_dut_ap_dpp_qr(dev, apdev, params, "ap-dpp", "sta-dpp",
2564                            mud_url=True)
2565
2566def run_sigma_dut_ap_dpp_qr(dev, apdev, params, ap_conf, sta_conf, extra="",
2567                            mud_url=False):
2568    check_dpp_capab(dev[0])
2569    if "sae" in sta_conf:
2570        check_sae_capab(dev[1])
2571    logdir = params['prefix'] + ".sigma-hostapd"
2572    with HWSimRadio() as (radio, iface), \
2573         SigmaDut(iface, hostapd_logdir=logdir) as dut:
2574        try:
2575            dut.cmd_check("ap_reset_default,program,DPP")
2576            res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR")
2577            if "status,COMPLETE" not in res:
2578                raise Exception("dev_exec_action did not succeed: " + res)
2579            hex = res.split(',')[3]
2580            uri = from_hex(hex)
2581            logger.info("URI from sigma_dut: " + uri)
2582
2583            cmd = "DPP_CONFIGURATOR_ADD"
2584            res = dev[0].request(cmd)
2585            if "FAIL" in res:
2586                raise Exception("Failed to add configurator")
2587            conf_id = int(res)
2588
2589            id1 = dev[0].dpp_qr_code(uri)
2590
2591            t = threading.Thread(target=dpp_init_conf,
2592                                 args=(dev[0], id1, ap_conf, conf_id, extra))
2593            t.start()
2594            cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPAuthDirection,Single,DPPProvisioningRole,Enrollee,DPPBS,QR,DPPTimeout,6"
2595            if mud_url:
2596                cmd += ",MUDURL,https://example.com/mud"
2597            res = dut.run_cmd(cmd)
2598            t.join()
2599            if "ConfResult,OK" not in res:
2600                raise Exception("Unexpected result: " + res)
2601
2602            id1 = dev[1].dpp_bootstrap_gen(chan="81/1", mac=True)
2603            uri1 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id1)
2604
2605            id0b = dev[0].dpp_qr_code(uri1)
2606
2607            dev[1].set("sae_groups", "")
2608            dev[1].set("dpp_config_processing", "2")
2609            cmd = "DPP_LISTEN 2412"
2610            if "OK" not in dev[1].request(cmd):
2611                raise Exception("Failed to start listen operation")
2612            cmd = "DPP_AUTH_INIT peer=%d conf=%s %s configurator=%d" % (id0b, sta_conf, extra, conf_id)
2613            if "OK" not in dev[0].request(cmd):
2614                raise Exception("Failed to initiate DPP Authentication")
2615            dev[1].wait_connected(timeout=20)
2616        finally:
2617            dev[1].set("dpp_config_processing", "0")
2618
2619def test_sigma_dut_ap_dpp_offchannel(dev, apdev, params):
2620    """sigma_dut controlled AP doing DPP on offchannel"""
2621    check_dpp_capab(dev[0])
2622    logdir = params['prefix'] + ".sigma-hostapd"
2623    with HWSimRadio() as (radio, iface), \
2624         SigmaDut(iface, hostapd_logdir=logdir) as dut:
2625        try:
2626            dut.cmd_check("ap_reset_default,program,DPP")
2627            dut.cmd_check("ap_preset_testparameters,Program,DPP,Oper_Chn,3")
2628            res = dut.cmd_check("dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR")
2629            hex = res.split(',')[3]
2630            uri = from_hex(hex)
2631            logger.info("URI from sigma_dut: " + uri)
2632            if "C:81/3;" not in uri:
2633                raise Exception("Unexpected channel in AP's URI: " + uri)
2634
2635            cmd = "DPP_CONFIGURATOR_ADD"
2636            res = dev[0].request(cmd)
2637            if "FAIL" in res:
2638                raise Exception("Failed to add configurator")
2639            conf_id = int(res)
2640
2641            id0 = dev[0].dpp_bootstrap_gen(chan="81/7", mac=True)
2642            uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
2643            dev[0].set("dpp_configurator_params",
2644                       "conf=ap-dpp ssid=%s configurator=%d" % (to_hex("DPPNET01"), conf_id))
2645            dev[0].dpp_listen(2442)
2646
2647            res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % to_hex(uri0))
2648            if "status,COMPLETE" not in res:
2649                raise Exception("dev_exec_action did not succeed: " + res)
2650
2651            res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Enrollee,DPPBS,QR,DPPTimeout,6")
2652            if "ConfResult,OK" not in res:
2653                raise Exception("Unexpected result: " + res)
2654
2655            id1 = dev[1].dpp_bootstrap_gen(chan="81/1", mac=True)
2656            uri1 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id1)
2657
2658            id0b = dev[0].dpp_qr_code(uri1)
2659
2660            dev[1].set("dpp_config_processing", "2")
2661            cmd = "DPP_LISTEN 2412"
2662            if "OK" not in dev[1].request(cmd):
2663                raise Exception("Failed to start listen operation")
2664            cmd = "DPP_AUTH_INIT peer=%d conf=sta-dpp ssid=%s configurator=%d" % (id0b, to_hex("DPPNET01"), conf_id)
2665            if "OK" not in dev[0].request(cmd):
2666                raise Exception("Failed to initiate DPP Authentication")
2667            dev[1].wait_connected(timeout=20)
2668        finally:
2669            dev[1].set("dpp_config_processing", "0")
2670
2671def test_sigma_dut_ap_dpp_init_mud_url(dev, apdev, params):
2672    """sigma_dut controlled AP doing DPP init with MUD URL"""
2673    check_dpp_capab(dev[0])
2674    logdir = params['prefix'] + ".sigma-hostapd"
2675    with HWSimRadio() as (radio, iface), \
2676         SigmaDut(iface, hostapd_logdir=logdir) as dut:
2677        try:
2678            cmd = "DPP_CONFIGURATOR_ADD"
2679            res = dev[0].request(cmd)
2680            if "FAIL" in res:
2681                raise Exception("Failed to add configurator")
2682            conf_id = int(res)
2683
2684            id0 = dev[0].dpp_bootstrap_gen(chan="81/7", mac=True)
2685            uri0 = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
2686            dev[0].set("dpp_configurator_params",
2687                       "conf=ap-dpp ssid=%s configurator=%d" % (to_hex("DPPNET01"), conf_id))
2688            dev[0].dpp_listen(2442)
2689
2690            dut.cmd_check("ap_reset_default,program,DPP")
2691            res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % to_hex(uri0))
2692            if "status,COMPLETE" not in res:
2693                raise Exception("dev_exec_action did not succeed: " + res)
2694
2695            cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Enrollee,DPPBS,QR,DPPTimeout,6"
2696            mud_url = "https://example.com/mud"
2697            cmd += ",MUDURL," + mud_url
2698            res = dut.run_cmd(cmd)
2699            if "ConfResult,OK" not in res:
2700                raise Exception("Unexpected result: " + res)
2701            ev = dev[0].wait_event(["DPP-MUD-URL"], timeout=10)
2702            if ev is None:
2703                raise Exception("No DPP-MUD-URL reported")
2704            if ev.split(' ')[1] != mud_url:
2705                raise Exception("Incorrect MUD URL reported")
2706
2707            id1 = dev[1].dpp_bootstrap_gen(chan="81/1", mac=True)
2708            uri1 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id1)
2709
2710            id0b = dev[0].dpp_qr_code(uri1)
2711
2712            dev[1].set("dpp_config_processing", "2")
2713            cmd = "DPP_LISTEN 2412"
2714            if "OK" not in dev[1].request(cmd):
2715                raise Exception("Failed to start listen operation")
2716            cmd = "DPP_AUTH_INIT peer=%d conf=sta-dpp ssid=%s configurator=%d" % (id0b, to_hex("DPPNET01"), conf_id)
2717            if "OK" not in dev[0].request(cmd):
2718                raise Exception("Failed to initiate DPP Authentication")
2719            dev[1].wait_connected(timeout=20)
2720        finally:
2721            dev[1].set("dpp_config_processing", "0")
2722
2723def test_sigma_dut_ap_dpp_pkex_responder(dev, apdev, params):
2724    """sigma_dut controlled AP as DPP PKEX responder"""
2725    check_dpp_capab(dev[0])
2726    logdir = os.path.join(params['logdir'],
2727                          "sigma_dut_ap_dpp_pkex_responder.sigma-hostapd")
2728    with HWSimRadio() as (radio, iface), \
2729         SigmaDut(iface, hostapd_logdir=logdir) as dut:
2730        run_sigma_dut_ap_dpp_pkex_responder(dut, dev, apdev)
2731
2732def test_sigma_dut_ap_dpp_pkex_v1_responder(dev, apdev, params):
2733    """sigma_dut controlled AP as DPP PKEXv1 responder"""
2734    check_dpp_capab(dev[0])
2735    logdir = params['prefix'] + ".sigma-hostapd"
2736    with HWSimRadio() as (radio, iface), \
2737         SigmaDut(iface, hostapd_logdir=logdir) as dut:
2738        run_sigma_dut_ap_dpp_pkex_responder(dut, dev, apdev, v1=True)
2739
2740def dpp_init_conf_pkex(dev, conf_id, check_config=True):
2741    logger.info("Starting DPP PKEX initiator/configurator in a thread")
2742    time.sleep(1.5)
2743    id = dev.dpp_bootstrap_gen(type="pkex")
2744    cmd = "DPP_PKEX_ADD own=%d init=1 conf=ap-dpp configurator=%d code=password" % (id, conf_id)
2745    res = dev.request(cmd)
2746    if "FAIL" in res:
2747        raise Exception("Failed to initiate DPP PKEX")
2748    if not check_config:
2749        return
2750    ev = dev.wait_event(["DPP-CONF-SENT"], timeout=15)
2751    if ev is None:
2752        raise Exception("DPP configuration not completed (Configurator)")
2753    logger.info("DPP initiator/configurator done")
2754
2755def run_sigma_dut_ap_dpp_pkex_responder(dut, dev, apdev, v1=False):
2756    dut.cmd_check("ap_reset_default,program,DPP")
2757
2758    cmd = "DPP_CONFIGURATOR_ADD"
2759    res = dev[0].request(cmd)
2760    if "FAIL" in res:
2761        raise Exception("Failed to add configurator")
2762    conf_id = int(res)
2763
2764    t = threading.Thread(target=dpp_init_conf_pkex, args=(dev[0], conf_id))
2765    t.start()
2766    dppbs = "PKEXv1" if v1 else "PKEX"
2767    res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPAuthDirection,Mutual,DPPProvisioningRole,Enrollee,DPPBS,%s,DPPPKEXCode,password,DPPTimeout,16,DPPWaitForConnect,No" % dppbs,
2768                      timeout=20)
2769    t.join()
2770    if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
2771        raise Exception("Unexpected result: " + res)
2772
2773def test_sigma_dut_ap_dpp_pkex_responder_tcp(dev, apdev, params):
2774    """sigma_dut controlled AP as DPP PKEX responder (TCP)"""
2775    check_dpp_capab(dev[0], min_ver=3)
2776    logdir = params['prefix'] + ".sigma-hostapd"
2777    with HWSimRadio() as (radio, iface), \
2778         SigmaDut(iface, hostapd_logdir=logdir) as dut:
2779        run_sigma_dut_ap_dpp_pkex_responder_tcp(dut, dev, apdev)
2780
2781def dpp_init_conf_pkex_tcp(dev, conf_id, check_config=True):
2782    logger.info("Starting DPP PKEX initiator/configurator in a thread")
2783    time.sleep(1.5)
2784    id = dev.dpp_bootstrap_gen(type="pkex")
2785    cmd = "DPP_PKEX_ADD own=%d tcp_addr=127.0.0.1 init=1 conf=ap-dpp configurator=%d code=password" % (id, conf_id)
2786    res = dev.request(cmd)
2787    if "FAIL" in res:
2788        raise Exception("Failed to initiate DPP PKEX")
2789    if not check_config:
2790        return
2791    ev = dev.wait_event(["DPP-CONF-SENT"], timeout=5)
2792    if ev is None:
2793        raise Exception("DPP configuration not completed (Configurator)")
2794    logger.info("DPP initiator/configurator done")
2795
2796def run_sigma_dut_ap_dpp_pkex_responder_tcp(dut, dev, apdev):
2797    dut.cmd_check("ap_reset_default,program,DPP")
2798
2799    cmd = "DPP_CONFIGURATOR_ADD"
2800    res = dev[0].request(cmd)
2801    if "FAIL" in res:
2802        raise Exception("Failed to add configurator")
2803    conf_id = int(res)
2804
2805    t = threading.Thread(target=dpp_init_conf_pkex_tcp, args=(dev[0], conf_id))
2806    t.start()
2807    res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPProvisioningRole,Enrollee,DPPBS,PKEX,DPPPKEXCode,password,DPPOverTCP,yes,DPPTimeout,6,DPPWaitForConnect,No", timeout=10)
2808    t.join()
2809    if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
2810        raise Exception("Unexpected result: " + res)
2811
2812def test_sigma_dut_dpp_pkex_responder_proto(dev, apdev):
2813    """sigma_dut controlled STA as DPP PKEX responder and error case"""
2814    check_dpp_capab(dev[0])
2815    with SigmaDut(dev=dev[0]) as dut:
2816        run_sigma_dut_dpp_pkex_responder_proto(dut, dev, apdev)
2817
2818def run_sigma_dut_dpp_pkex_responder_proto(dut, dev, apdev):
2819    cmd = "DPP_CONFIGURATOR_ADD"
2820    res = dev[1].request(cmd)
2821    if "FAIL" in res:
2822        raise Exception("Failed to add configurator")
2823    conf_id = int(res)
2824
2825    dev[1].set("dpp_test", "44")
2826
2827    t = threading.Thread(target=dpp_init_conf_pkex, args=(dev[1], conf_id,
2828                                                          False))
2829    t.start()
2830    res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPProvisioningRole,Enrollee,DPPBS,PKEX,DPPPKEXCode,password,DPPTimeout,6", timeout=10)
2831    t.join()
2832    if "BootstrapResult,Timeout" not in res:
2833        raise Exception("Unexpected result: " + res)
2834
2835def dpp_proto_init(dev, id1):
2836    time.sleep(1)
2837    logger.info("Starting DPP initiator/configurator in a thread")
2838    cmd = "DPP_CONFIGURATOR_ADD"
2839    res = dev.request(cmd)
2840    if "FAIL" in res:
2841        raise Exception("Failed to add configurator")
2842    conf_id = int(res)
2843
2844    cmd = "DPP_AUTH_INIT peer=%d conf=sta-dpp configurator=%d" % (id1, conf_id)
2845    if "OK" not in dev.request(cmd):
2846        raise Exception("Failed to initiate DPP Authentication")
2847
2848def test_sigma_dut_dpp_proto_initiator(dev, apdev):
2849    """sigma_dut DPP protocol testing - Initiator"""
2850    check_dpp_capab(dev[0])
2851    check_dpp_capab(dev[1])
2852    tests = [("InvalidValue", "AuthenticationRequest", "WrappedData",
2853              "BootstrapResult,OK,AuthResult,Errorsent",
2854              None),
2855             ("InvalidValue", "AuthenticationConfirm", "WrappedData",
2856              "BootstrapResult,OK,AuthResult,Errorsent",
2857              None),
2858             ("MissingAttribute", "AuthenticationRequest", "InitCapabilities",
2859              "BootstrapResult,OK,AuthResult,Errorsent",
2860              "Missing or invalid I-capabilities"),
2861             ("InvalidValue", "AuthenticationConfirm", "InitAuthTag",
2862              "BootstrapResult,OK,AuthResult,Errorsent",
2863              "Mismatching Initiator Authenticating Tag"),
2864             ("MissingAttribute", "ConfigurationResponse", "EnrolleeNonce",
2865              "BootstrapResult,OK,AuthResult,OK,ConfResult,Errorsent",
2866              "Missing or invalid Enrollee Nonce attribute")]
2867    for step, frame, attr, result, fail in tests:
2868        dev[0].request("FLUSH")
2869        dev[1].request("FLUSH")
2870        with SigmaDut(dev=dev[0]) as dut:
2871            run_sigma_dut_dpp_proto_initiator(dut, dev, step, frame, attr,
2872                                              result, fail)
2873
2874def run_sigma_dut_dpp_proto_initiator(dut, dev, step, frame, attr, result,
2875                                      fail):
2876    id0 = dev[1].dpp_bootstrap_gen(chan="81/6", mac=True)
2877    uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
2878
2879    cmd = "DPP_LISTEN 2437 role=enrollee"
2880    if "OK" not in dev[1].request(cmd):
2881        raise Exception("Failed to start listen operation")
2882
2883    res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % to_hex(uri0))
2884    if "status,COMPLETE" not in res:
2885        raise Exception("dev_exec_action did not succeed: " + res)
2886
2887    res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Configurator,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,STA,DPPBS,QR,DPPTimeout,6,DPPStep,%s,DPPFrameType,%s,DPPIEAttribute,%s" % (step, frame, attr),
2888                        timeout=10)
2889    if result not in res:
2890        raise Exception("Unexpected result: " + res)
2891    if fail:
2892        ev = dev[1].wait_event(["DPP-FAIL"], timeout=5)
2893        if ev is None or fail not in ev:
2894            raise Exception("Failure not reported correctly: " + str(ev))
2895
2896    dev[1].request("DPP_STOP_LISTEN")
2897    dev[0].dump_monitor()
2898    dev[1].dump_monitor()
2899
2900def test_sigma_dut_dpp_proto_responder(dev, apdev):
2901    """sigma_dut DPP protocol testing - Responder"""
2902    check_dpp_capab(dev[0])
2903    check_dpp_capab(dev[1])
2904    tests = [("MissingAttribute", "AuthenticationResponse", "DPPStatus",
2905              "BootstrapResult,OK,AuthResult,Errorsent",
2906              "Missing or invalid required DPP Status attribute"),
2907             ("MissingAttribute", "ConfigurationRequest", "EnrolleeNonce",
2908              "BootstrapResult,OK,AuthResult,OK,ConfResult,Errorsent",
2909              "Missing or invalid Enrollee Nonce attribute")]
2910    for step, frame, attr, result, fail in tests:
2911        dev[0].request("FLUSH")
2912        dev[1].request("FLUSH")
2913        with SigmaDut(dev=dev[0]) as dut:
2914            run_sigma_dut_dpp_proto_responder(dut, dev, step, frame, attr,
2915                                              result, fail)
2916
2917def run_sigma_dut_dpp_proto_responder(dut, dev, step, frame, attr, result,
2918                                      fail):
2919    res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR")
2920    if "status,COMPLETE" not in res:
2921        raise Exception("dev_exec_action did not succeed: " + res)
2922    hex = res.split(',')[3]
2923    uri = from_hex(hex)
2924    logger.info("URI from sigma_dut: " + uri)
2925
2926    id1 = dev[1].dpp_qr_code(uri)
2927
2928    t = threading.Thread(target=dpp_proto_init, args=(dev[1], id1))
2929    t.start()
2930    res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPAuthDirection,Single,DPPProvisioningRole,Enrollee,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,STA,DPPBS,QR,DPPTimeout,6,DPPStep,%s,DPPFrameType,%s,DPPIEAttribute,%s" % (step, frame, attr), timeout=10)
2931    t.join()
2932    if result not in res:
2933        raise Exception("Unexpected result: " + res)
2934    if fail:
2935        ev = dev[1].wait_event(["DPP-FAIL"], timeout=5)
2936        if ev is None or fail not in ev:
2937            raise Exception("Failure not reported correctly:" + str(ev))
2938
2939    dev[1].request("DPP_STOP_LISTEN")
2940    dev[0].dump_monitor()
2941    dev[1].dump_monitor()
2942
2943def test_sigma_dut_dpp_proto_stop_at_initiator(dev, apdev):
2944    """sigma_dut DPP protocol testing - Stop at RX on Initiator"""
2945    check_dpp_capab(dev[0])
2946    check_dpp_capab(dev[1])
2947    tests = [("AuthenticationResponse",
2948              "BootstrapResult,OK,AuthResult,Errorsent",
2949              None),
2950             ("ConfigurationRequest",
2951              "BootstrapResult,OK,AuthResult,OK,ConfResult,Errorsent",
2952              None)]
2953    for frame, result, fail in tests:
2954        dev[0].request("FLUSH")
2955        dev[1].request("FLUSH")
2956        with SigmaDut(dev=dev[0]) as dut:
2957            run_sigma_dut_dpp_proto_stop_at_initiator(dut, dev, frame, result,
2958                                                      fail)
2959
2960def run_sigma_dut_dpp_proto_stop_at_initiator(dut, dev, frame, result, fail):
2961    id0 = dev[1].dpp_bootstrap_gen(chan="81/6", mac=True)
2962    uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
2963
2964    cmd = "DPP_LISTEN 2437 role=enrollee"
2965    if "OK" not in dev[1].request(cmd):
2966        raise Exception("Failed to start listen operation")
2967
2968    res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % to_hex(uri0))
2969    if "status,COMPLETE" not in res:
2970        raise Exception("dev_exec_action did not succeed: " + res)
2971
2972    res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Configurator,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,STA,DPPBS,QR,DPPTimeout,6,DPPStep,Timeout,DPPFrameType,%s" % (frame))
2973    if result not in res:
2974        raise Exception("Unexpected result: " + res)
2975    if fail:
2976        ev = dev[1].wait_event(["DPP-FAIL"], timeout=5)
2977        if ev is None or fail not in ev:
2978            raise Exception("Failure not reported correctly: " + str(ev))
2979
2980    dev[1].request("DPP_STOP_LISTEN")
2981    dev[0].dump_monitor()
2982    dev[1].dump_monitor()
2983
2984def test_sigma_dut_dpp_proto_stop_at_initiator_enrollee(dev, apdev):
2985    """sigma_dut DPP protocol testing - Stop at TX on Initiator/Enrollee"""
2986    check_dpp_capab(dev[0])
2987    check_dpp_capab(dev[1])
2988    tests = [("AuthenticationConfirm",
2989              "BootstrapResult,OK,AuthResult,Errorsent,LastFrameReceived,AuthenticationResponse",
2990              None)]
2991    for frame, result, fail in tests:
2992        dev[0].request("FLUSH")
2993        dev[1].request("FLUSH")
2994        with SigmaDut(dev=dev[0]) as dut:
2995            run_sigma_dut_dpp_proto_stop_at_initiator_enrollee(dut, dev, frame,
2996                                                               result, fail)
2997
2998def run_sigma_dut_dpp_proto_stop_at_initiator_enrollee(dut, dev, frame, result,
2999                                                       fail):
3000    id0 = dev[1].dpp_bootstrap_gen(chan="81/6", mac=True)
3001    uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
3002
3003    cmd = "DPP_LISTEN 2437 role=configurator"
3004    if "OK" not in dev[1].request(cmd):
3005        raise Exception("Failed to start listen operation")
3006
3007    res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % to_hex(uri0))
3008    if "status,COMPLETE" not in res:
3009        raise Exception("dev_exec_action did not succeed: " + res)
3010
3011    res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Enrollee,DPPBS,QR,DPPTimeout,6,DPPStep,Timeout,DPPFrameType,%s" % (frame), timeout=10)
3012    if result not in res:
3013        raise Exception("Unexpected result: " + res)
3014    if fail:
3015        ev = dev[1].wait_event(["DPP-FAIL"], timeout=5)
3016        if ev is None or fail not in ev:
3017            raise Exception("Failure not reported correctly: " + str(ev))
3018
3019    dev[1].request("DPP_STOP_LISTEN")
3020    dev[0].dump_monitor()
3021    dev[1].dump_monitor()
3022
3023def test_sigma_dut_dpp_proto_stop_at_responder(dev, apdev):
3024    """sigma_dut DPP protocol testing - Stop at RX on Responder"""
3025    check_dpp_capab(dev[0])
3026    check_dpp_capab(dev[1])
3027    tests = [("AuthenticationRequest",
3028              "BootstrapResult,OK,AuthResult,Errorsent",
3029              None),
3030             ("AuthenticationConfirm",
3031              "BootstrapResult,OK,AuthResult,Errorsent",
3032              None)]
3033    for frame, result, fail in tests:
3034        dev[0].request("FLUSH")
3035        dev[1].request("FLUSH")
3036        with SigmaDut(dev=dev[0]) as dut:
3037            run_sigma_dut_dpp_proto_stop_at_responder(dut, dev, frame, result,
3038                                                      fail)
3039
3040def run_sigma_dut_dpp_proto_stop_at_responder(dut, dev, frame, result, fail):
3041    res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR")
3042    if "status,COMPLETE" not in res:
3043        raise Exception("dev_exec_action did not succeed: " + res)
3044    hex = res.split(',')[3]
3045    uri = from_hex(hex)
3046    logger.info("URI from sigma_dut: " + uri)
3047
3048    id1 = dev[1].dpp_qr_code(uri)
3049
3050    t = threading.Thread(target=dpp_proto_init, args=(dev[1], id1))
3051    t.start()
3052    res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPAuthDirection,Single,DPPProvisioningRole,Enrollee,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,STA,DPPBS,QR,DPPTimeout,6,DPPStep,Timeout,DPPFrameType,%s" % (frame), timeout=10)
3053    t.join()
3054    if result not in res:
3055        raise Exception("Unexpected result: " + res)
3056    if fail:
3057        ev = dev[1].wait_event(["DPP-FAIL"], timeout=5)
3058        if ev is None or fail not in ev:
3059            raise Exception("Failure not reported correctly:" + str(ev))
3060
3061    dev[1].request("DPP_STOP_LISTEN")
3062    dev[0].dump_monitor()
3063    dev[1].dump_monitor()
3064
3065def dpp_proto_init_pkex(dev):
3066    time.sleep(1)
3067    logger.info("Starting DPP PKEX initiator/configurator in a thread")
3068    cmd = "DPP_CONFIGURATOR_ADD"
3069    res = dev.request(cmd)
3070    if "FAIL" in res:
3071        raise Exception("Failed to add configurator")
3072    conf_id = int(res)
3073
3074    id = dev.dpp_bootstrap_gen(type="pkex")
3075
3076    cmd = "DPP_PKEX_ADD own=%d init=1 conf=sta-dpp configurator=%d code=secret" % (id, conf_id)
3077    if "FAIL" in dev.request(cmd):
3078        raise Exception("Failed to initiate DPP PKEX")
3079
3080def test_sigma_dut_dpp_proto_initiator_pkex(dev, apdev):
3081    """sigma_dut DPP protocol testing - Initiator (PKEX)"""
3082    check_dpp_capab(dev[0])
3083    check_dpp_capab(dev[1])
3084    tests = [("InvalidValue", "PKEXCRRequest", "WrappedData",
3085              "BootstrapResult,Errorsent",
3086              None),
3087             ("MissingAttribute", "PKEXExchangeRequest", "FiniteCyclicGroup",
3088              "BootstrapResult,Errorsent",
3089              "Missing or invalid Finite Cyclic Group attribute"),
3090             ("MissingAttribute", "PKEXCRRequest", "BSKey",
3091              "BootstrapResult,Errorsent",
3092              "No valid peer bootstrapping key found")]
3093    for step, frame, attr, result, fail in tests:
3094        dev[0].request("FLUSH")
3095        dev[1].request("FLUSH")
3096        with SigmaDut(dev=dev[0]) as dut:
3097            run_sigma_dut_dpp_proto_initiator_pkex(dut, dev, step, frame, attr,
3098                                                   result, fail)
3099
3100def run_sigma_dut_dpp_proto_initiator_pkex(dut, dev, step, frame, attr, result,
3101                                           fail):
3102    id1 = dev[1].dpp_bootstrap_gen(type="pkex")
3103
3104    cmd = "DPP_PKEX_ADD own=%d code=secret" % (id1)
3105    res = dev[1].request(cmd)
3106    if "FAIL" in res:
3107        raise Exception("Failed to set PKEX data (responder)")
3108
3109    cmd = "DPP_LISTEN 2437 role=enrollee"
3110    if "OK" not in dev[1].request(cmd):
3111        raise Exception("Failed to start listen operation")
3112
3113    res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Configurator,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,STA,DPPBS,PKEX,DPPPKEXCode,secret,DPPTimeout,6,DPPStep,%s,DPPFrameType,%s,DPPIEAttribute,%s" % (step, frame, attr))
3114    if result not in res:
3115        raise Exception("Unexpected result: " + res)
3116    if fail:
3117        ev = dev[1].wait_event(["DPP-FAIL"], timeout=5)
3118        if ev is None or fail not in ev:
3119            raise Exception("Failure not reported correctly: " + str(ev))
3120
3121    dev[1].request("DPP_STOP_LISTEN")
3122    dev[0].dump_monitor()
3123    dev[1].dump_monitor()
3124
3125def test_sigma_dut_dpp_proto_responder_pkex(dev, apdev):
3126    """sigma_dut DPP protocol testing - Responder (PKEX)"""
3127    check_dpp_capab(dev[0])
3128    check_dpp_capab(dev[1])
3129    tests = [("InvalidValue", "PKEXCRResponse", "WrappedData",
3130              "BootstrapResult,Errorsent",
3131              None),
3132             ("MissingAttribute", "PKEXExchangeResponse", "DPPStatus",
3133              "BootstrapResult,Errorsent",
3134              "No DPP Status attribute"),
3135             ("MissingAttribute", "PKEXCRResponse", "BSKey",
3136              "BootstrapResult,Errorsent",
3137              "No valid peer bootstrapping key found")]
3138    for step, frame, attr, result, fail in tests:
3139        dev[0].request("FLUSH")
3140        dev[1].request("FLUSH")
3141        with SigmaDut(dev=dev[0]) as dut:
3142            run_sigma_dut_dpp_proto_responder_pkex(dut, dev, step, frame, attr,
3143                                                   result, fail)
3144
3145def run_sigma_dut_dpp_proto_responder_pkex(dut, dev, step, frame, attr, result,
3146                                           fail):
3147    t = threading.Thread(target=dpp_proto_init_pkex, args=(dev[1],))
3148    t.start()
3149    res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPAuthDirection,Single,DPPProvisioningRole,Enrollee,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,STA,DPPBS,PKEX,DPPPKEXCode,secret,DPPTimeout,6,DPPStep,%s,DPPFrameType,%s,DPPIEAttribute,%s" % (step, frame, attr), timeout=10)
3150    t.join()
3151    if result not in res:
3152        raise Exception("Unexpected result: " + res)
3153    if fail:
3154        ev = dev[1].wait_event(["DPP-FAIL"], timeout=5)
3155        if ev is None or fail not in ev:
3156            raise Exception("Failure not reported correctly:" + str(ev))
3157
3158    dev[1].request("DPP_STOP_LISTEN")
3159    dev[0].dump_monitor()
3160    dev[1].dump_monitor()
3161
3162def init_sigma_dut_dpp_proto_peer_disc_req(dut, dev, apdev):
3163    check_dpp_capab(dev[0])
3164    check_dpp_capab(dev[1])
3165    hapd = start_dpp_ap(apdev[0])
3166    dev[0].set("dpp_config_processing", "2")
3167
3168    cmd = "DPP_CONFIGURATOR_ADD key=" + csign
3169    res = dev[1].request(cmd)
3170    if "FAIL" in res:
3171        raise Exception("Failed to add configurator")
3172    conf_id = int(res)
3173
3174    id0 = dev[1].dpp_bootstrap_gen(chan="81/6", mac=True)
3175    uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
3176
3177    dev[1].set("dpp_configurator_params",
3178               " conf=sta-dpp ssid=%s configurator=%d" % (to_hex("DPPNET01"),
3179                                                          conf_id))
3180    cmd = "DPP_LISTEN 2437 role=configurator"
3181    if "OK" not in dev[1].request(cmd):
3182        raise Exception("Failed to start listen operation")
3183
3184    res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % to_hex(uri0))
3185    if "status,COMPLETE" not in res:
3186        raise Exception("dev_exec_action did not succeed: " + res)
3187
3188def run_sigma_dut_dpp_proto_peer_disc_req(dev, apdev, args):
3189    with SigmaDut(dev=dev[0]) as dut:
3190        init_sigma_dut_dpp_proto_peer_disc_req(dut, dev, apdev)
3191
3192        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Enrollee,DPPBS,QR,DPPTimeout,6,DPPWaitForConnect,Yes,DPPFrameType,PeerDiscoveryRequest," + args, timeout=10)
3193        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK,NetworkIntroResult,Errorsent" not in res:
3194            raise Exception("Unexpected result: " + res)
3195
3196def test_sigma_dut_dpp_proto_peer_disc_req(dev, apdev):
3197    """sigma_dut DPP protocol testing - Peer Discovery Request"""
3198    run_sigma_dut_dpp_proto_peer_disc_req(dev, apdev, "DPPStep,MissingAttribute,DPPIEAttribute,TransactionID")
3199
3200def test_sigma_dut_dpp_proto_peer_disc_req2(dev, apdev):
3201    """sigma_dut DPP protocol testing - Peer Discovery Request (2)"""
3202    check_dpp_capab(dev[0], min_ver=3)
3203    run_sigma_dut_dpp_proto_peer_disc_req(dev, apdev, "DPPStep,MissingAttribute,DPPIEAttribute,ProtocolVersion")
3204
3205def test_sigma_dut_dpp_proto_peer_disc_req3(dev, apdev):
3206    """sigma_dut DPP protocol testing - Peer Discovery Request (e)"""
3207    check_dpp_capab(dev[0], min_ver=3)
3208    run_sigma_dut_dpp_proto_peer_disc_req(dev, apdev, "DPPStep,InvalidValue,DPPIEAttribute,ProtocolVersion")
3209
3210def test_sigma_dut_dpp_self_config(dev, apdev):
3211    """sigma_dut DPP Configurator enrolling an AP and using self-configuration"""
3212    check_dpp_capab(dev[0])
3213
3214    hapd = hostapd.add_ap(apdev[0], {"ssid": "unconfigured"})
3215    check_dpp_capab(hapd)
3216
3217    with SigmaDut(dev=dev[0]) as dut:
3218        dev[0].set("dpp_config_processing", "2")
3219        id = hapd.dpp_bootstrap_gen(chan="81/1", mac=True)
3220        uri = hapd.request("DPP_BOOTSTRAP_GET_URI %d" % id)
3221
3222        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % to_hex(uri))
3223        if "status,COMPLETE" not in res:
3224            raise Exception("dev_exec_action did not succeed: " + res)
3225
3226        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Configurator,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,AP,DPPBS,QR,DPPTimeout,6")
3227        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
3228            raise Exception("Unexpected result: " + res)
3229        update_hapd_config(hapd)
3230
3231        cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPCryptoIdentifier,P-256,DPPBS,QR,DPPAuthRole,Initiator,DPPProvisioningRole,Configurator,DPPAuthDirection,Single,DPPConfIndex,1,DPPTimeout,6,DPPWaitForConnect,Yes,DPPSelfConfigure,Yes"
3232        res = dut.run_cmd(cmd, timeout=10)
3233        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK,NetworkIntroResult,OK,NetworkConnectResult,OK" not in res:
3234            raise Exception("Unexpected result: " + res)
3235
3236def test_sigma_dut_ap_dpp_self_config(dev, apdev, params):
3237    """sigma_dut DPP AP Configurator using self-configuration"""
3238    logdir = os.path.join(params['logdir'],
3239                          "sigma_dut_ap_dpp_self_config.sigma-hostapd")
3240    with HWSimRadio() as (radio, iface), \
3241         SigmaDut(iface, hostapd_logdir=logdir) as dut:
3242        run_sigma_dut_ap_dpp_self_config(dut, dev, apdev)
3243
3244def test_sigma_dut_ap_dpp_self_config_connector_privacy(dev, apdev, params):
3245    """sigma_dut DPP AP Configurator using self-configuration (Connector privacy)"""
3246    check_dpp_capab(dev[0], min_ver=3)
3247    logdir = params['prefix'] + ".sigma-hostapd"
3248    with HWSimRadio() as (radio, iface), \
3249         SigmaDut(iface, hostapd_logdir=logdir) as dut:
3250        dev[0].set("dpp_connector_privacy_default", "1")
3251        run_sigma_dut_ap_dpp_self_config(dut, dev, apdev)
3252
3253def run_sigma_dut_ap_dpp_self_config(dut, dev, apdev):
3254    check_dpp_capab(dev[0])
3255
3256    dut.cmd_check("ap_reset_default,program,DPP")
3257
3258    res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Configurator,DPPConfEnrolleeRole,AP,DPPBS,QR,DPPConfIndex,1,DPPSelfConfigure,Yes,DPPTimeout,6", timeout=10)
3259    if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
3260            raise Exception("Unexpected result: " + res)
3261
3262    dev[0].set("dpp_config_processing", "2")
3263
3264    id = dev[0].dpp_bootstrap_gen(chan="81/11", mac=True)
3265    uri = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id)
3266    cmd = "DPP_LISTEN 2462 role=enrollee"
3267    if "OK" not in dev[0].request(cmd):
3268        raise Exception("Failed to start listen operation")
3269
3270    res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % to_hex(uri))
3271    if "status,COMPLETE" not in res:
3272        raise Exception("dev_exec_action did not succeed: " + res)
3273    cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Configurator,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,STA,DPPBS,QR,DPPTimeout,6"
3274    res = dut.run_cmd(cmd)
3275    if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
3276        raise Exception("Unexpected result: " + res)
3277    dev[0].wait_connected(timeout=20)
3278    dev[0].request("DISCONNECT")
3279    dev[0].wait_disconnected()
3280
3281def test_sigma_dut_ap_dpp_relay(dev, apdev, params):
3282    """sigma_dut DPP AP as Relay to Controller"""
3283    logdir = os.path.join(params['logdir'],
3284                          "sigma_dut_ap_dpp_relay.sigma-hostapd")
3285    with HWSimRadio() as (radio, iface), \
3286         SigmaDut(iface, hostapd_logdir=logdir) as dut:
3287        try:
3288            run_sigma_dut_ap_dpp_relay(dut, dev, apdev)
3289        finally:
3290            dev[1].request("DPP_CONTROLLER_STOP")
3291
3292def run_sigma_dut_ap_dpp_relay(dut, dev, apdev):
3293    check_dpp_capab(dev[0])
3294    check_dpp_capab(dev[1])
3295
3296    # Controller
3297    conf_id = dev[1].dpp_configurator_add()
3298    dev[1].set("dpp_configurator_params",
3299               " conf=sta-dpp configurator=%d" % conf_id)
3300    id_c = dev[1].dpp_bootstrap_gen()
3301    uri_c = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id_c)
3302    res = dev[1].request("DPP_BOOTSTRAP_INFO %d" % id_c)
3303    pkhash = None
3304    for line in res.splitlines():
3305        name, value = line.split('=')
3306        if name == "pkhash":
3307            pkhash = value
3308            break
3309    if not pkhash:
3310        raise Exception("Could not fetch public key hash from Controller")
3311    if "OK" not in dev[1].request("DPP_CONTROLLER_START"):
3312        raise Exception("Failed to start Controller")
3313
3314    dut.cmd_check("ap_reset_default,program,DPP")
3315    dut.cmd_check("ap_preset_testparameters,program,DPP,DPPConfiguratorAddress,127.0.0.1,DPPConfiguratorPKHash," + pkhash)
3316    res = dut.cmd_check("dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR")
3317
3318    dev[0].dpp_auth_init(uri=uri_c, role="enrollee")
3319    wait_auth_success(dev[1], dev[0], configurator=dev[1], enrollee=dev[0],
3320                      timeout=10)
3321
3322def dpp_init_tcp_enrollee(dev, id1):
3323    logger.info("Starting DPP initiator/enrollee (TCP) in a thread")
3324    time.sleep(1)
3325    cmd = "DPP_AUTH_INIT peer=%d role=enrollee tcp_addr=127.0.0.1" % id1
3326    if "OK" not in dev.request(cmd):
3327        raise Exception("Failed to initiate DPP Authentication")
3328    ev = dev.wait_event(["DPP-CONF-RECEIVED"], timeout=5)
3329    if ev is None:
3330        raise Exception("DPP configuration not completed (Enrollee)")
3331    logger.info("DPP initiator/enrollee done")
3332
3333def test_sigma_dut_dpp_tcp_conf_resp(dev, apdev):
3334    """sigma_dut DPP TCP Configurator (Controller) as responder"""
3335    run_sigma_dut_dpp_tcp_conf_resp(dev)
3336
3337def run_sigma_dut_dpp_tcp_conf_resp(dev, status_query=False):
3338    check_dpp_capab(dev[0])
3339    check_dpp_capab(dev[1])
3340    with SigmaDut(dev=dev[0]) as dut:
3341        cmd = "dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR"
3342        res = dut.run_cmd(cmd)
3343        if "status,COMPLETE" not in res:
3344            raise Exception("dev_exec_action did not succeed: " + res)
3345        hex = res.split(',')[3]
3346        uri = from_hex(hex)
3347        logger.info("URI from sigma_dut: " + uri)
3348
3349        id1 = dev[1].dpp_qr_code(uri)
3350
3351        t = threading.Thread(target=dpp_init_tcp_enrollee, args=(dev[1], id1))
3352        t.start()
3353        cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPConfIndex,1,DPPAuthDirection,Single,DPPProvisioningRole,Configurator,DPPConfEnrolleeRole,STA,DPPSigningKeyECC,P-256,DPPBS,QR,DPPOverTCP,yes,DPPTimeout,6"
3354        if status_query:
3355            cmd += ",DPPStatusQuery,Yes"
3356        res = dut.run_cmd(cmd, timeout=10)
3357        t.join()
3358        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
3359            raise Exception("Unexpected result: " + res)
3360        if status_query and "StatusResult,0" not in res:
3361            raise Exception("Status query did not succeed: " + res)
3362
3363def dpp_init_tcp_configurator(dev, id1, conf_id):
3364    logger.info("Starting DPP initiator/configurator (TCP) in a thread")
3365    time.sleep(1)
3366    cmd = "DPP_AUTH_INIT peer=%d role=configurator conf=sta-dpp configurator=%d tcp_addr=127.0.0.1" % (id1, conf_id)
3367    if "OK" not in dev.request(cmd):
3368        raise Exception("Failed to initiate DPP Authentication")
3369    ev = dev.wait_event(["DPP-CONF-SENT"], timeout=5)
3370    if ev is None:
3371        raise Exception("DPP configuration not completed (Configurator)")
3372    logger.info("DPP initiator/configurator done")
3373
3374def test_sigma_dut_dpp_tcp_enrollee_resp(dev, apdev):
3375    """sigma_dut DPP TCP Enrollee (Controller) as responder"""
3376    run_sigma_dut_dpp_tcp_enrollee_resp(dev)
3377
3378def run_sigma_dut_dpp_tcp_enrollee_resp(dev, status_query=False):
3379    check_dpp_capab(dev[0])
3380    check_dpp_capab(dev[1])
3381    with SigmaDut(dev=dev[0]) as dut:
3382        cmd = "dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR"
3383        res = dut.run_cmd(cmd)
3384        if "status,COMPLETE" not in res:
3385            raise Exception("dev_exec_action did not succeed: " + res)
3386        hex = res.split(',')[3]
3387        uri = from_hex(hex)
3388        logger.info("URI from sigma_dut: " + uri)
3389
3390        cmd = "DPP_CONFIGURATOR_ADD"
3391        res = dev[1].request(cmd)
3392        if "FAIL" in res:
3393            raise Exception("Failed to add configurator")
3394        conf_id = int(res)
3395
3396        id1 = dev[1].dpp_qr_code(uri)
3397
3398        t = threading.Thread(target=dpp_init_tcp_configurator, args=(dev[1], id1, conf_id))
3399        t.start()
3400        cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPAuthDirection,Single,DPPProvisioningRole,Enrollee,DPPSigningKeyECC,P-256,DPPBS,QR,DPPOverTCP,yes,DPPTimeout,6"
3401        if status_query:
3402            cmd += ",DPPStatusQuery,Yes"
3403        res = dut.run_cmd(cmd, timeout=10)
3404        t.join()
3405        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
3406            raise Exception("Unexpected result: " + res)
3407        if status_query and "StatusResult,0" not in res:
3408            raise Exception("Status query did not succeed: " + res)
3409
3410def test_sigma_dut_dpp_tcp_enrollee_init(dev, apdev):
3411    """sigma_dut DPP TCP Enrollee as initiator"""
3412    check_dpp_capab(dev[0])
3413    check_dpp_capab(dev[1])
3414    with SigmaDut(dev=dev[0]) as dut:
3415        # Controller
3416        conf_id = dev[1].dpp_configurator_add()
3417        dev[1].set("dpp_configurator_params",
3418                   " conf=sta-dpp configurator=%d" % conf_id)
3419        id_c = dev[1].dpp_bootstrap_gen()
3420        uri_c = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id_c)
3421        if "OK" not in dev[1].request("DPP_CONTROLLER_START"):
3422            raise Exception("Failed to start Controller")
3423
3424        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % to_hex(uri_c))
3425        if "status,COMPLETE" not in res:
3426            raise Exception("dev_exec_action did not succeed: " + res)
3427
3428        cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Enrollee,DPPConfEnrolleeRole,STA,DPPBS,QR,DPPOverTCP,127.0.0.1,DPPTimeout,6"
3429        res = dut.run_cmd(cmd, timeout=10)
3430        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
3431            raise Exception("Unexpected result: " + res)
3432
3433    dev[1].request("DPP_CONTROLLER_STOP")
3434
3435def test_sigma_dut_ap_dpp_tcp_enrollee_init(dev, apdev, params):
3436    """sigma_dut DPP AP as TCP Enrollee/initiator"""
3437    logdir = params['prefix'] + ".sigma-hostapd"
3438    with HWSimRadio() as (radio, iface), \
3439         SigmaDut(iface, hostapd_logdir=logdir) as dut:
3440        try:
3441            run_sigma_dut_ap_dpp_tcp_enrollee_init(dut, dev, apdev)
3442        finally:
3443            dev[1].request("DPP_CONTROLLER_STOP")
3444
3445def run_sigma_dut_ap_dpp_tcp_enrollee_init(dut, dev, apdev):
3446    check_dpp_capab(dev[1])
3447    # Controller
3448    conf_id = dev[1].dpp_configurator_add()
3449    dev[1].set("dpp_configurator_params",
3450               "conf=ap-dpp configurator=%d" % conf_id)
3451    id_c = dev[1].dpp_bootstrap_gen()
3452    uri_c = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id_c)
3453    if "OK" not in dev[1].request("DPP_CONTROLLER_START"):
3454        raise Exception("Failed to start Controller")
3455
3456    dut.cmd_check("ap_reset_default,program,DPP")
3457    dut.cmd_check("ap_preset_testparameters,Program,DPP,NAME,AP,oper_chn,6")
3458    dut.cmd_check("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % to_hex(uri_c))
3459
3460    cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPProvisioningRole,Enrollee,DPPBS,QR,DPPOverTCP,127.0.0.1,DPPTimeout,6"
3461    res = dut.run_cmd(cmd, timeout=10)
3462    if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
3463        raise Exception("Unexpected result: " + res)
3464
3465def test_sigma_dut_dpp_tcp_enrollee_init_mutual(dev, apdev):
3466    """sigma_dut DPP TCP Enrollee as initiator with mutual authentication"""
3467    check_dpp_capab(dev[0], min_ver=2)
3468    check_dpp_capab(dev[1], min_ver=2)
3469    with SigmaDut(dev=dev[0]) as dut:
3470        # Controller
3471        conf_id = dev[1].dpp_configurator_add()
3472        dev[1].set("dpp_configurator_params",
3473                   "conf=sta-dpp configurator=%d" % conf_id)
3474        id_c = dev[1].dpp_bootstrap_gen()
3475        uri_c = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id_c)
3476        if "OK" not in dev[1].request("DPP_CONTROLLER_START"):
3477            raise Exception("Failed to start Controller")
3478
3479        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % to_hex(uri_c))
3480        if "status,COMPLETE" not in res:
3481            raise Exception("dev_exec_action did not succeed: " + res)
3482
3483        cmd = "dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR"
3484        res = dut.cmd_check(cmd)
3485        hex = res.split(',')[3]
3486        uri = from_hex(hex)
3487        logger.info("URI from sigma_dut: " + uri)
3488        id1 = dev[1].dpp_qr_code(uri)
3489
3490        cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Mutual,DPPProvisioningRole,Enrollee,DPPBS,QR,DPPOverTCP,127.0.0.1,DPPTimeout,6"
3491        res = dut.run_cmd(cmd, timeout=10)
3492        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
3493            raise Exception("Unexpected result: " + res)
3494
3495    dev[1].request("DPP_CONTROLLER_STOP")
3496
3497def test_sigma_dut_dpp_tcp_configurator_init_mutual(dev, apdev):
3498    """sigma_dut DPP TCP Configurator as initiator with mutual authentication"""
3499    check_dpp_capab(dev[0], min_ver=2)
3500    check_dpp_capab(dev[1], min_ver=2)
3501    with SigmaDut(dev=dev[0]) as dut:
3502        id_c = dev[1].dpp_bootstrap_gen()
3503        uri_c = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id_c)
3504        if "OK" not in dev[1].request("DPP_CONTROLLER_START role=enrollee"):
3505            raise Exception("Failed to start Controller")
3506
3507        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % to_hex(uri_c))
3508        if "status,COMPLETE" not in res:
3509            raise Exception("dev_exec_action did not succeed: " + res)
3510
3511        cmd = "dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR"
3512        res = dut.cmd_check(cmd)
3513        hex = res.split(',')[3]
3514        uri = from_hex(hex)
3515        logger.info("URI from sigma_dut: " + uri)
3516        id1 = dev[1].dpp_qr_code(uri)
3517
3518        cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Mutual,DPPProvisioningRole,Configurator,DPPConfIndex,1,DPPConfEnrolleeRole,STA,DPPBS,QR,DPPOverTCP,127.0.0.1,DPPTimeout,6"
3519        res = dut.run_cmd(cmd, timeout=10)
3520        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
3521            raise Exception("Unexpected result: " + res)
3522
3523    dev[1].request("DPP_CONTROLLER_STOP")
3524
3525def test_sigma_dut_dpp_tcp_configurator_init_mutual_unsupported_curve(dev, apdev):
3526    """sigma_dut DPP TCP Configurator as initiator with mutual authentication (unsupported curve)"""
3527    check_dpp_capab(dev[0], min_ver=3)
3528    check_dpp_capab(dev[1], min_ver=3)
3529    with SigmaDut(dev=dev[0]) as dut:
3530        id_c = dev[1].dpp_bootstrap_gen(supported_curves="P-256:P-384")
3531        uri_c = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id_c)
3532        if "OK" not in dev[1].request("DPP_CONTROLLER_START role=enrollee"):
3533            raise Exception("Failed to start Controller")
3534
3535        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % to_hex(uri_c))
3536        if "status,COMPLETE" not in res:
3537            raise Exception("dev_exec_action did not succeed: " + res)
3538
3539        cmd = "dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR"
3540        res = dut.cmd_check(cmd)
3541        hex = res.split(',')[3]
3542        uri = from_hex(hex)
3543        logger.info("URI from sigma_dut: " + uri)
3544        id1 = dev[1].dpp_qr_code(uri)
3545
3546        cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Mutual,DPPProvisioningRole,Configurator,DPPConfIndex,1,DPPNAKECC,P-521,DPPConfEnrolleeRole,STA,DPPBS,QR,DPPOverTCP,127.0.0.1,DPPTimeout,6"
3547        res = dut.run_cmd(cmd, timeout=10)
3548        if "BootstrapResult,OK,AuthResult,OK,ConfResult,FAILED" not in res:
3549            raise Exception("Unexpected result: " + res)
3550        ev = dev[1].wait_event(["DPP-FAIL"], timeout=20)
3551        if not ev:
3552            raise Exception("Enrollee did not report configuration result")
3553        if "Configurator rejected configuration" not in ev:
3554            raise Exception("Enrollee did not report configuration rejection")
3555
3556    dev[1].request("DPP_CONTROLLER_STOP")
3557
3558def test_sigma_dut_dpp_tcp_configurator_init_from_uri(dev, apdev):
3559    """sigma_dut DPP TCP Configurator as initiator with addr from URI"""
3560    check_dpp_capab(dev[0], min_ver=2)
3561    check_dpp_capab(dev[1], min_ver=2)
3562    with SigmaDut(dev=dev[0]) as dut:
3563        id_c = dev[1].dpp_bootstrap_gen(host="127.0.0.1")
3564        uri_c = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id_c)
3565        if "OK" not in dev[1].request("DPP_CONTROLLER_START role=enrollee"):
3566            raise Exception("Failed to start Controller")
3567
3568        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % to_hex(uri_c))
3569        if "status,COMPLETE" not in res:
3570            raise Exception("dev_exec_action did not succeed: " + res)
3571
3572        cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Configurator,DPPConfIndex,1,DPPConfEnrolleeRole,STA,DPPBS,QR,DPPOverTCP,from-uri,DPPTimeout,6"
3573        res = dut.run_cmd(cmd, timeout=10)
3574        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
3575            raise Exception("Unexpected result: " + res)
3576
3577    dev[1].request("DPP_CONTROLLER_STOP")
3578
3579def test_sigma_dut_dpp_nfc_handover_requestor_enrollee(dev, apdev):
3580    """sigma_dut DPP/NFC handover requestor as Enrollee"""
3581    check_dpp_capab(dev[0])
3582    check_dpp_capab(dev[1])
3583    hapd = start_dpp_ap(apdev[0])
3584    with SigmaDut(dev=dev[0]) as dut:
3585        dev[0].set("dpp_config_processing", "2")
3586
3587        cmd = "DPP_CONFIGURATOR_ADD key=" + csign
3588        res = dev[1].request(cmd)
3589        if "FAIL" in res:
3590            raise Exception("Failed to add configurator")
3591        conf_id = int(res)
3592        dev[1].set("dpp_configurator_params",
3593                   " conf=sta-dpp ssid=%s configurator=%d" % (to_hex("DPPNET01"), conf_id))
3594
3595        id_own = dev[1].dpp_bootstrap_gen(type="nfc-uri", chan="81/1,6,11",
3596                                          mac=True)
3597        uri_own = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id_own)
3598
3599        res = dut.cmd_check("dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPBS,NFC")
3600        hex = res.split(',')[3]
3601        uri_peer = from_hex(hex)
3602        logger.info("URI from sigma_dut: " + uri_peer)
3603
3604        dut.cmd_check("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,NFC" % to_hex(uri_own))
3605
3606        res = dev[1].request("DPP_NFC_HANDOVER_REQ own=%d uri=%s" % (id_own,
3607                                                                     uri_peer))
3608        if "FAIL" in res:
3609            raise Exception("Failed to process NFC Handover Request")
3610        info = dev[1].request("DPP_BOOTSTRAP_INFO %d" % id_own)
3611        logger.info("Updated local bootstrapping info:\n" + info)
3612        freq = None
3613        for line in info.splitlines():
3614            if line.startswith("use_freq="):
3615                freq = int(line.split('=')[1])
3616        if freq is None:
3617            raise Exception("Selected channel not indicated")
3618        uri1 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id_own)
3619        logger.info("Updated URI[1]: " + uri1)
3620        dev[1].dpp_listen(freq, role="configurator")
3621
3622        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPProvisioningRole,Enrollee,DPPBS,NFC,DPPNFCHandover,Negotiated_Requestor,DPPTimeout,6,DPPWaitForConnect,Yes", timeout=10)
3623        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK,NetworkIntroResult,OK,NetworkConnectResult,OK" not in res:
3624            raise Exception("Unexpected result: " + res)
3625
3626def test_sigma_dut_dpp_nfc_handover_selector_enrollee(dev, apdev):
3627    """sigma_dut DPP/NFC handover selector as Enrollee"""
3628    check_dpp_capab(dev[0])
3629    check_dpp_capab(dev[1])
3630    hapd = start_dpp_ap(apdev[0])
3631    with SigmaDut(dev=dev[0]) as dut:
3632        dev[0].set("dpp_config_processing", "2")
3633
3634        cmd = "DPP_CONFIGURATOR_ADD key=" + csign
3635        res = dev[1].request(cmd)
3636        if "FAIL" in res:
3637            raise Exception("Failed to add configurator")
3638        conf_id = int(res)
3639        dev[1].set("dpp_configurator_params",
3640                   " conf=sta-dpp ssid=%s configurator=%d" % (to_hex("DPPNET01"), conf_id))
3641
3642        id_own = dev[1].dpp_bootstrap_gen(type="nfc-uri", chan="81/1,6,11",
3643                                          mac=True)
3644        uri_own = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id_own)
3645
3646        res = dut.cmd_check("dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPBS,NFC")
3647        hex = res.split(',')[3]
3648        uri_peer = from_hex(hex)
3649        logger.info("URI from sigma_dut: " + uri_peer)
3650
3651        dut.cmd_check("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,NFC" % to_hex(uri_own))
3652
3653        res = dev[1].request("DPP_NFC_HANDOVER_SEL own=%d uri=%s" % (id_own,
3654                                                                     uri_peer))
3655        if "FAIL" in res:
3656            raise Exception("Failed to process NFC Handover Select")
3657        peer = int(res)
3658        dev[1].dpp_auth_init(peer=peer, own=id_own, configurator=conf_id,
3659                             conf="sta-dpp", ssid="DPPNET01")
3660
3661        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPProvisioningRole,Enrollee,DPPBS,NFC,DPPNFCHandover,Negotiated_Selector,DPPTimeout,6,DPPWaitForConnect,Yes", timeout=10)
3662        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK,NetworkIntroResult,OK,NetworkConnectResult,OK" not in res:
3663            raise Exception("Unexpected result: " + res)
3664
3665def test_sigma_dut_dpp_nfc_static_read_enrollee(dev, apdev):
3666    """sigma_dut DPP/NFC read tag as Enrollee"""
3667    check_dpp_capab(dev[0])
3668    check_dpp_capab(dev[1])
3669    hapd = start_dpp_ap(apdev[0])
3670    with SigmaDut(dev=dev[0]) as dut:
3671        dev[0].set("dpp_config_processing", "2")
3672
3673        cmd = "DPP_CONFIGURATOR_ADD key=" + csign
3674        res = dev[1].request(cmd)
3675        if "FAIL" in res:
3676            raise Exception("Failed to add configurator")
3677        conf_id = int(res)
3678        dev[1].set("dpp_configurator_params",
3679                   " conf=sta-dpp ssid=%s configurator=%d" % (to_hex("DPPNET01"), conf_id))
3680
3681        id_own = dev[1].dpp_bootstrap_gen(type="nfc-uri", chan="81/6", mac=True)
3682        uri_own = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id_own)
3683
3684        dut.cmd_check("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,NFC" % to_hex(uri_own))
3685        dev[1].dpp_listen(2437, role="configurator")
3686
3687        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPProvisioningRole,Enrollee,DPPBS,NFC,DPPNFCHandover,Static,DPPTimeout,6,DPPWaitForConnect,Yes", timeout=10)
3688        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK,NetworkIntroResult,OK,NetworkConnectResult,OK" not in res:
3689            raise Exception("Unexpected result: " + res)
3690
3691def test_sigma_dut_dpp_nfc_static_write_enrollee(dev, apdev):
3692    """sigma_dut DPP/NFC write tag as Enrollee"""
3693    check_dpp_capab(dev[0])
3694    check_dpp_capab(dev[1])
3695    hapd = start_dpp_ap(apdev[0])
3696    with SigmaDut(dev=dev[0]) as dut:
3697        dev[0].set("dpp_config_processing", "2")
3698
3699        cmd = "DPP_CONFIGURATOR_ADD key=" + csign
3700        res = dev[1].request(cmd)
3701        if "FAIL" in res:
3702            raise Exception("Failed to add configurator")
3703        conf_id = int(res)
3704        dev[1].set("dpp_configurator_params",
3705                   " conf=sta-dpp ssid=%s configurator=%d" % (to_hex("DPPNET01"), conf_id))
3706
3707        res = dut.cmd_check("dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPBS,NFC")
3708        hex = res.split(',')[3]
3709        uri_peer = from_hex(hex)
3710        logger.info("URI from sigma_dut: " + uri_peer)
3711
3712        dev[1].dpp_auth_init(nfc_uri=uri_peer, configurator=conf_id,
3713                             conf="sta-dpp", ssid="DPPNET01")
3714
3715        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPProvisioningRole,Enrollee,DPPBS,NFC,DPPNFCHandover,Static,DPPTimeout,6,DPPWaitForConnect,Yes", timeout=10)
3716        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK,NetworkIntroResult,OK,NetworkConnectResult,OK" not in res:
3717            raise Exception("Unexpected result: " + res)
3718
3719def test_sigma_dut_dpp_reconfig_enrollee(dev, apdev):
3720    """sigma_dut DPP reconfiguration (Enrollee)"""
3721    check_dpp_capab(dev[0])
3722    check_dpp_capab(dev[1])
3723    hapd = start_dpp_ap(apdev[0])
3724    with SigmaDut(dev=dev[0]) as dut:
3725        cmd = "DPP_CONFIGURATOR_ADD key=" + csign
3726        res = dev[1].request(cmd)
3727        if "FAIL" in res:
3728            raise Exception("Failed to add configurator")
3729        conf_id = int(res)
3730
3731        id0 = dev[1].dpp_bootstrap_gen(chan="81/6", mac=True)
3732        uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
3733
3734        dev[1].set("dpp_configurator_params",
3735                   " conf=sta-dpp ssid=%s configurator=%d" % (to_hex("DPPNET01"), conf_id))
3736        cmd = "DPP_LISTEN 2437 role=configurator"
3737        if "OK" not in dev[1].request(cmd):
3738            raise Exception("Failed to start listen operation")
3739
3740        ifname = dev[0].ifname
3741        dut.cmd_check("sta_reset_default,interface,%s,prog,DPP" % ifname)
3742
3743        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % to_hex(uri0))
3744        if "status,COMPLETE" not in res:
3745            raise Exception("dev_exec_action did not succeed: " + res)
3746
3747        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Enrollee,DPPBS,QR,DPPTimeout,6,DPPWaitForConnect,Yes", timeout=10)
3748        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK,NetworkIntroResult,OK,NetworkConnectResult,OK" not in res:
3749            raise Exception("Unexpected result: " + res)
3750
3751        hapd.disable()
3752        dev[0].dump_monitor()
3753
3754        ssid = "reconfig"
3755        passphrase = "secret passphrase"
3756        params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
3757        hapd = hostapd.add_ap(apdev[0], params)
3758
3759        dev[1].set("dpp_configurator_params",
3760                   "conf=sta-psk ssid=%s pass=%s conn_status=1" % (binascii.hexlify(ssid.encode()).decode(), binascii.hexlify(passphrase.encode()).decode()))
3761        cmd = "DPP_LISTEN 2437 role=configurator"
3762        if "OK" not in dev[1].request(cmd):
3763            raise Exception("Failed to start listen operation")
3764        dev[1].dump_monitor()
3765
3766        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,DPPReconfigure,DPPTimeout,16,DPPWaitForConnect,Yes", timeout=20)
3767        if "status,COMPLETE,ReconfigAuthResult,OK,ConfResult,OK,NetworkConnectResult,OK" not in res:
3768            raise Exception("Unexpected reconfiguration result: " + res)
3769
3770        ev = dev[1].wait_event(["DPP-CONF-SENT"], timeout=15)
3771        if ev is None:
3772            raise Exception("DPP Config Response (reconfig) not transmitted")
3773
3774        dev[0].wait_connected(timeout=20)
3775        ev = dev[1].wait_event(["DPP-CONN-STATUS-RESULT"], timeout=20)
3776        if ev is None:
3777            raise Exception("No connection status reported")
3778        if "result=0" not in ev:
3779            raise Exception("Connection status did not report success: " + ev)
3780
3781        time.sleep(1)
3782        cmd = "DPP_LISTEN 2437 role=configurator"
3783        if "OK" not in dev[1].request(cmd):
3784            raise Exception("Failed to start listen operation")
3785        dev[0].dump_monitor()
3786        dev[1].dump_monitor()
3787
3788        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,DPPReconfigure,DPPTimeout,16,DPPWaitForConnect,Yes", timeout=30)
3789        if "status,COMPLETE,ReconfigAuthResult,OK,ConfResult,OK,NetworkConnectResult,OK" not in res:
3790            raise Exception("Unexpected reconfiguration [2] result: " + res)
3791
3792        ev = dev[1].wait_event(["DPP-CONF-SENT"], timeout=5)
3793        if ev is None:
3794            raise Exception("DPP Config Response (reconfig) not transmitted [2]")
3795
3796        dev[0].wait_connected(timeout=20)
3797
3798def test_sigma_dut_dpp_reconfig_enrollee_sae(dev, apdev):
3799    """sigma_dut DPP reconfiguration using SAE (Enrollee)"""
3800    check_dpp_capab(dev[0])
3801    check_dpp_capab(dev[1])
3802    check_sae_capab(dev[0])
3803    hapd = start_dpp_ap(apdev[0])
3804    with SigmaDut(dev=dev[0]) as dut:
3805        cmd = "DPP_CONFIGURATOR_ADD key=" + csign
3806        res = dev[1].request(cmd)
3807        if "FAIL" in res:
3808            raise Exception("Failed to add configurator")
3809        conf_id = int(res)
3810
3811        id0 = dev[1].dpp_bootstrap_gen(chan="81/6", mac=True)
3812        uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
3813
3814        dev[1].set("dpp_configurator_params",
3815                   "conf=sta-dpp ssid=%s configurator=%d" % (to_hex("DPPNET01"), conf_id))
3816        cmd = "DPP_LISTEN 2437 role=configurator"
3817        if "OK" not in dev[1].request(cmd):
3818            raise Exception("Failed to start listen operation")
3819
3820        ifname = dev[0].ifname
3821        dut.cmd_check("sta_reset_default,interface,%s,prog,DPP" % ifname)
3822
3823        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % to_hex(uri0))
3824        if "status,COMPLETE" not in res:
3825            raise Exception("dev_exec_action did not succeed: " + res)
3826
3827        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Enrollee,DPPBS,QR,DPPTimeout,6,DPPWaitForConnect,Yes", timeout=10)
3828        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK,NetworkIntroResult,OK,NetworkConnectResult,OK" not in res:
3829            raise Exception("Unexpected result: " + res)
3830
3831        hapd.disable()
3832        dev[0].dump_monitor()
3833
3834        hapd = start_sae_pwe_ap(apdev[0], 2, ssid="DPPNET01")
3835
3836        dev[1].set("dpp_configurator_params",
3837                   "conf=sta-sae ssid=%s pass=%s configurator=%d conn_status=1" % (to_hex("DPPNET01"), to_hex("12345678"), conf_id))
3838        cmd = "DPP_LISTEN 2437 role=configurator"
3839        if "OK" not in dev[1].request(cmd):
3840            raise Exception("Failed to start listen operation")
3841        dev[1].dump_monitor()
3842
3843        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,DPPReconfigure,DPPTimeout,16,DPPWaitForConnect,Yes", timeout=20)
3844        if "status,COMPLETE,ReconfigAuthResult,OK,ConfResult,OK,NetworkConnectResult,OK" not in res:
3845            raise Exception("Unexpected reconfiguration result: " + res)
3846
3847        ev = dev[1].wait_event(["DPP-CONF-SENT"], timeout=15)
3848        if ev is None:
3849            raise Exception("DPP Config Response (reconfig) not transmitted")
3850
3851        dev[0].wait_connected(timeout=20)
3852        ev = dev[1].wait_event(["DPP-CONN-STATUS-RESULT"], timeout=20)
3853        if ev is None:
3854            raise Exception("No connection status reported")
3855        if "result=0" not in ev:
3856            raise Exception("Connection status did not report success: " + ev)
3857
3858        time.sleep(1)
3859        cmd = "DPP_LISTEN 2437 role=configurator"
3860        if "OK" not in dev[1].request(cmd):
3861            raise Exception("Failed to start listen operation")
3862        dev[0].dump_monitor()
3863        dev[1].dump_monitor()
3864
3865        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,DPPReconfigure,DPPTimeout,16,DPPWaitForConnect,Yes", timeout=30)
3866        if "status,COMPLETE,ReconfigAuthResult,OK,ConfResult,OK,NetworkConnectResult,OK" not in res:
3867            raise Exception("Unexpected reconfiguration [2] result: " + res)
3868
3869        ev = dev[1].wait_event(["DPP-CONF-SENT"], timeout=5)
3870        if ev is None:
3871            raise Exception("DPP Config Response (reconfig) not transmitted [2]")
3872
3873        dev[0].wait_connected(timeout=20)
3874
3875def test_sigma_dut_dpp_reconfig_configurator(dev, apdev):
3876    """sigma_dut DPP reconfiguration (Configurator)"""
3877    check_dpp_capab(dev[0])
3878    check_dpp_capab(dev[1])
3879    with SigmaDut(dev=dev[0]) as dut:
3880        dev[1].set("dpp_config_processing", "1")
3881        id0 = dev[1].dpp_bootstrap_gen(chan="81/6", mac=True)
3882        uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
3883        cmd = "DPP_LISTEN 2437"
3884        if "OK" not in dev[1].request(cmd):
3885            raise Exception("Failed to start listen operation")
3886
3887        ifname = dev[0].ifname
3888        dut.cmd_check("sta_reset_default,interface,%s,prog,DPP" % ifname)
3889
3890        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % to_hex(uri0))
3891        if "status,COMPLETE" not in res:
3892            raise Exception("dev_exec_action did not succeed: " + res)
3893
3894        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Configurator,DPPConfEnrolleeRole,STA,DPPSigningKeyECC,P-256,DPPConfIndex,1,DPPBS,QR,DPPTimeout,6", timeout=10)
3895        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
3896            raise Exception("Unexpected result: " + res)
3897
3898        dev[0].dump_monitor()
3899
3900        ev = dev[1].wait_event(["DPP-NETWORK-ID"], timeout=1)
3901        if ev is None:
3902            raise Exception("No network profile created")
3903        id = int(ev.split(' ')[1])
3904
3905        ev = dev[1].wait_event(["DPP-TX-STATUS"], timeout=5)
3906        if ev is None:
3907            raise Exception("Configuration Result not sent")
3908        dev[1].dump_monitor()
3909        cmd = "DPP_RECONFIG %d" % id
3910        if "OK" not in dev[1].request(cmd):
3911            raise Exception("Failed to start reconfiguration")
3912
3913        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,DPPReconfigure,DPPProvisioningRole,Configurator,DPPConfEnrolleeRole,STA,DPPSigningKeyECC,P-256,DPPConfIndex,2,DPPListenChannel,6,DPPTimeout,16", timeout=20)
3914        if "status,COMPLETE,ReconfigAuthResult,OK,ConfResult,OK" not in res:
3915            raise Exception("Unexpected reconfiguration result: " + res)
3916
3917        ev = dev[1].wait_event(["DPP-CONF-RECEIVED"], timeout=15)
3918        if ev is None:
3919            raise Exception("DPP Config Response (reconfig) not received")
3920
3921    dev[1].set("dpp_config_processing", "0")
3922
3923def test_sigma_dut_dpp_reconfig_no_proto_ver(dev, apdev):
3924    """sigma_dut DPP reconfiguration (Configurator) - missing Protocol Version"""
3925    run_sigma_dut_dpp_reconfig_proto(dev, apdev, "MissingAttribute")
3926
3927def test_sigma_dut_dpp_reconfig_invalid_proto_ver(dev, apdev):
3928    """sigma_dut DPP reconfiguration (Configurator) - invalid Protocol Version"""
3929    run_sigma_dut_dpp_reconfig_proto(dev, apdev, "InvalidValue")
3930
3931def run_sigma_dut_dpp_reconfig_proto(dev, apdev, dpp_step):
3932    check_dpp_capab(dev[0])
3933    check_dpp_capab(dev[1])
3934    with SigmaDut(dev=dev[0]) as dut:
3935        dev[1].set("dpp_config_processing", "1")
3936        id0 = dev[1].dpp_bootstrap_gen(chan="81/6", mac=True)
3937        uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
3938        cmd = "DPP_LISTEN 2437"
3939        if "OK" not in dev[1].request(cmd):
3940            raise Exception("Failed to start listen operation")
3941
3942        ifname = dev[0].ifname
3943        dut.cmd_check("sta_reset_default,interface,%s,prog,DPP" % ifname)
3944
3945        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % to_hex(uri0))
3946        if "status,COMPLETE" not in res:
3947            raise Exception("dev_exec_action did not succeed: " + res)
3948
3949        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Configurator,DPPConfEnrolleeRole,STA,DPPSigningKeyECC,P-256,DPPConfIndex,1,DPPBS,QR,DPPTimeout,6", timeout=10)
3950        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
3951            raise Exception("Unexpected result: " + res)
3952
3953        dev[0].dump_monitor()
3954
3955        ev = dev[1].wait_event(["DPP-NETWORK-ID"], timeout=1)
3956        if ev is None:
3957            raise Exception("No network profile created")
3958        id = int(ev.split(' ')[1])
3959
3960        ev = dev[1].wait_event(["DPP-TX-STATUS"], timeout=5)
3961        if ev is None:
3962            raise Exception("Configuration Result not sent")
3963        dev[1].dump_monitor()
3964        cmd = "DPP_RECONFIG %d" % id
3965        if "OK" not in dev[1].request(cmd):
3966            raise Exception("Failed to start reconfiguration")
3967
3968        res = dut.run_cmd("dev_exec_action,program,DPP,DPPActionType,DPPReconfigure,DPPProvisioningRole,Configurator,DPPConfEnrolleeRole,STA,DPPSigningKeyECC,P-256,DPPConfIndex,2,DPPStep,%s,DPPFrameType,ReconfigAuthRequest,DPPIEAttribute,ProtocolVersion,DPPListenChannel,6,DPPTimeout,16" % dpp_step, timeout=20)
3969        if "status,COMPLETE,ReconfigAuthResult,Errorsent" not in res:
3970            raise Exception("Unexpected reconfiguration result: " + res)
3971
3972        ev = dev[1].wait_event(["DPP-CONF-RECEIVED"], timeout=5)
3973        if ev is not None:
3974            raise Exception("DPP Config Response (reconfig) received unexpectedly")
3975
3976    dev[1].set("dpp_config_processing", "0")
3977
3978def test_sigma_dut_dpp_pb_sta(dev, apdev):
3979    """sigma_dut DPP/PB station"""
3980    check_dpp_capab(dev[0], min_ver=3)
3981    check_sae_capab(dev[0])
3982
3983    params = {"ssid": "sae",
3984              "dpp_configurator_connectivity": "1",
3985              "wpa": "2",
3986              "wpa_key_mgmt": "SAE",
3987              "ieee80211w": "2",
3988              "rsn_pairwise": "CCMP",
3989              "sae_password": "sae-password"}
3990    hapd = hostapd.add_ap(apdev[0], params)
3991
3992    ifname = dev[0].ifname
3993    with SigmaDut(dev=dev[0]) as dut:
3994        if "OK" not in hapd.request("DPP_PUSH_BUTTON"):
3995            raise Exception("Failed to press push button on the AP")
3996
3997        dut.cmd_check("sta_reset_default,interface,%s,prog,DPP" % ifname)
3998
3999        cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPProvisioningRole,Enrollee,DPPBS,PBBS,DPPTimeout,50,DPPWaitForConnect,Yes"
4000        res = dut.run_cmd(cmd, timeout=60)
4001        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK,NetworkConnectResult,OK" not in res:
4002            raise Exception("Unexpected result: " + res)
4003        ev = hapd.wait_event(["DPP-PB-RESULT"], timeout=1)
4004        if ev is None or "success" not in ev:
4005            raise Exception("Push button bootstrapping did not succeed on AP")
4006
4007def dpp_ap_pb_delayed_start(hapd):
4008    time.sleep(10)
4009    if "OK" not in hapd.request("DPP_PUSH_BUTTON"):
4010        raise Exception("Failed to press push button on the AP")
4011
4012def test_sigma_dut_dpp_pb_sta_first(dev, apdev):
4013    """sigma_dut DPP/PB station first"""
4014    check_dpp_capab(dev[0], min_ver=3)
4015    check_sae_capab(dev[0])
4016
4017    params = {"ssid": "sae",
4018              "dpp_configurator_connectivity": "1",
4019              "wpa": "2",
4020              "wpa_key_mgmt": "SAE",
4021              "ieee80211w": "2",
4022              "rsn_pairwise": "CCMP",
4023              "sae_password": "sae-password"}
4024    hapd = hostapd.add_ap(apdev[0], params)
4025
4026    ifname = dev[0].ifname
4027    with SigmaDut(dev=dev[0]) as dut:
4028        t = threading.Thread(target=dpp_ap_pb_delayed_start, args=(hapd,))
4029        t.start()
4030
4031        dut.cmd_check("sta_reset_default,interface,%s,prog,DPP" % ifname)
4032
4033        cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPProvisioningRole,Enrollee,DPPBS,PBBS,DPPTimeout,50,DPPWaitForConnect,Yes"
4034        res = dut.run_cmd(cmd, timeout=60, dump_dev=dev[0])
4035        t.join()
4036        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK,NetworkConnectResult,OK" not in res:
4037            raise Exception("Unexpected result: " + res)
4038        ev = hapd.wait_event(["DPP-PB-RESULT"], timeout=1)
4039        if ev is None or "success" not in ev:
4040            raise Exception("Push button bootstrapping did not succeed on AP")
4041
4042def dpp_ap_pb_overlap(hapd, hapd2, dev0):
4043    if "OK" not in hapd.request("DPP_PUSH_BUTTON"):
4044        raise Exception("Failed to press push button on the AP")
4045    ev = dev0.wait_event(["DPP-PB-STATUS discovered"], timeout=30)
4046    if ev is None:
4047        raise Exception("Push button status not reported on station")
4048    # Force bootstrap key change since both instances share the same global
4049    # DPP state for PB.
4050    hapd.request("DPP_STOP_LISTEN")
4051    if "OK" not in hapd2.request("DPP_PUSH_BUTTON"):
4052        raise Exception("Failed to press push button on the AP2")
4053
4054def test_sigma_dut_dpp_pb_sta_session_overlap(dev, apdev):
4055    """sigma_dut DPP/PB station session overlap"""
4056    check_dpp_capab(dev[0], min_ver=3)
4057    check_sae_capab(dev[0])
4058
4059    params = {"ssid": "sae",
4060              "dpp_configurator_connectivity": "1",
4061              "wpa": "2",
4062              "wpa_key_mgmt": "SAE",
4063              "ieee80211w": "2",
4064              "rsn_pairwise": "CCMP",
4065              "sae_password": "sae-password"}
4066    hapd = hostapd.add_ap(apdev[0], params)
4067    params = {"ssid": "another sae",
4068              "dpp_configurator_connectivity": "1",
4069              "channel": "11",
4070              "wpa": "2",
4071              "wpa_key_mgmt": "SAE",
4072              "ieee80211w": "2",
4073              "rsn_pairwise": "CCMP",
4074              "sae_password": "sae-password-other"}
4075    hapd2 = hostapd.add_ap(apdev[1], params)
4076
4077    ifname = dev[0].ifname
4078    with SigmaDut(dev=dev[0]) as dut:
4079        dut.cmd_check("sta_reset_default,interface,%s,prog,DPP" % ifname)
4080
4081        t = threading.Thread(target=dpp_ap_pb_overlap,
4082                             args=(hapd, hapd2, dev[0]))
4083        t.start()
4084        cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPProvisioningRole,Enrollee,DPPBS,PBBS,DPPTimeout,50,DPPWaitForConnect,Yes"
4085        res = dut.run_cmd(cmd, timeout=60)
4086        t.join()
4087        if "BootstrapResult,Failed" not in res:
4088            raise Exception("Unexpected result: " + res)
4089
4090def test_sigma_dut_dpp_pb_configurator(dev, apdev):
4091    """sigma_dut DPP/PB Configurator"""
4092    check_dpp_capab(dev[0], min_ver=3)
4093    check_dpp_capab(dev[1], min_ver=3)
4094
4095    ifname = dev[0].ifname
4096    with SigmaDut(dev=dev[0]) as dut:
4097        dut.cmd_check("sta_reset_default,interface,%s,prog,DPP" % ifname)
4098
4099        if "OK" not in dev[1].request("DPP_PUSH_BUTTON"):
4100            raise Exception("Failed to press push button on the STA/Enrollee")
4101
4102        cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPProvisioningRole,Configurator,DPPBS,PBBS,DPPConfEnrolleeRole,STA,DPPConfIndex,1,DPPTimeout,50"
4103        res = dut.run_cmd(cmd, timeout=60)
4104        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
4105            raise Exception("Unexpected result: " + res)
4106        ev = dev[1].wait_event(["DPP-PB-RESULT"], timeout=1)
4107        if ev is None or "success" not in ev:
4108            raise Exception("Push button bootstrapping did not succeed on STA/Enrollee")
4109
4110def test_sigma_dut_dpp_pb_configurator_session_overlap(dev, apdev):
4111    """sigma_dut DPP/PB Configurator session overlap"""
4112    check_dpp_capab(dev[0], min_ver=3)
4113    check_dpp_capab(dev[1], min_ver=3)
4114    check_dpp_capab(dev[2], min_ver=3)
4115
4116    ifname = dev[0].ifname
4117    with SigmaDut(dev=dev[0]) as dut:
4118        dut.cmd_check("sta_reset_default,interface,%s,prog,DPP" % ifname)
4119
4120        if "OK" not in dev[1].request("DPP_PUSH_BUTTON"):
4121            raise Exception("Failed to press push button on the STA/Enrollee")
4122        if "OK" not in dev[2].request("DPP_PUSH_BUTTON"):
4123            raise Exception("Failed to press push button on the STA2/Enrollee")
4124
4125        cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPProvisioningRole,Configurator,DPPBS,PBBS,DPPConfEnrolleeRole,STA,DPPConfIndex,1,DPPTimeout,50"
4126        res = dut.run_cmd(cmd, timeout=60)
4127        if "BootstrapResult,Failed" not in res:
4128            raise Exception("Unexpected result: " + res)
4129
4130def test_sigma_dut_dpp_pb_sta_misbehavior(dev, apdev):
4131    """sigma_dut DPP/PB station misbehavior"""
4132    check_dpp_capab(dev[0], min_ver=3)
4133    check_sae_capab(dev[0])
4134
4135    params = {"ssid": "sae",
4136              "dpp_configurator_connectivity": "1",
4137              "wpa": "2",
4138              "wpa_key_mgmt": "SAE",
4139              "ieee80211w": "2",
4140              "rsn_pairwise": "CCMP",
4141              "sae_password": "sae-password"}
4142    hapd = hostapd.add_ap(apdev[0], params)
4143
4144    ifname = dev[0].ifname
4145    with SigmaDut(dev=dev[0]) as dut:
4146        if "OK" not in hapd.request("DPP_PUSH_BUTTON"):
4147            raise Exception("Failed to press push button on the AP")
4148
4149        dut.cmd_check("sta_reset_default,interface,%s,prog,DPP" % ifname)
4150
4151        cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPProvisioningRole,Enrollee,DPPBS,PBBS,DPPTimeout,50,DPPWaitForConnect,Yes"
4152        cmd += ",DPPStep,InvalidValue,DPPFrameType,PBPresAnnc,DPPIEAttribute,RespBSKeyHash"
4153        res = dut.run_cmd(cmd, timeout=60)
4154        if "BootstrapResult,OK,AuthResult,Timeout" not in res:
4155            raise Exception("Unexpected result: " + res)
4156        ev = hapd.wait_event(["DPP-PB-RESULT"], timeout=1)
4157        if ev is None or "failed" not in ev:
4158            raise Exception("Push button bootstrapping did not fail on AP")
4159
4160def test_sigma_dut_dpp_pb_ap(dev, apdev, params):
4161    """sigma_dut DPP/PB AP (own config)"""
4162    check_dpp_capab(dev[0], min_ver=3)
4163    check_sae_capab(dev[0])
4164
4165    logdir = params['prefix'] + ".sigma-hostapd"
4166    with HWSimRadio() as (radio, iface), \
4167         SigmaDut(iface, hostapd_logdir=logdir) as dut:
4168        dut.cmd_check("ap_reset_default,program,DPP")
4169
4170        dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,6,SSID,test-sae,MODE,11ng")
4171        dut.cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-SAE,PSK,12345678")
4172        dut.cmd_check("ap_config_commit,NAME,AP")
4173
4174        dev[0].set("sae_groups", "")
4175        dev[0].set("dpp_config_processing", "2")
4176        if "OK" not in dev[0].request("DPP_PUSH_BUTTON"):
4177            raise Exception("Failed to press push button on the STA")
4178
4179        cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPProvisioningRole,Configurator,DPPBS,PBBS,DPPTimeout,50"
4180        res = dut.run_cmd(cmd, timeout=60)
4181        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
4182            raise Exception("Unexpected result: " + res)
4183        ev = dev[0].wait_event(["DPP-PB-RESULT"], timeout=1)
4184        if ev is None or "success" not in ev:
4185            raise Exception("Push button bootstrapping did not succeed on STA")
4186        dev[0].wait_connected()
4187
4188def test_sigma_dut_dpp_pb_ap2(dev, apdev, params):
4189    """sigma_dut DPP/PB AP (DPPConfigIndex)"""
4190    check_dpp_capab(dev[0], min_ver=3)
4191    check_sae_capab(dev[0])
4192
4193    logdir = params['prefix'] + ".sigma-hostapd"
4194    with HWSimRadio() as (radio, iface), \
4195         SigmaDut(iface, hostapd_logdir=logdir) as dut:
4196        dut.cmd_check("ap_reset_default,program,DPP")
4197        if "OK" not in dev[0].request("DPP_PUSH_BUTTON"):
4198            raise Exception("Failed to press push button on the STA")
4199
4200        cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPProvisioningRole,Configurator,DPPBS,PBBS,DPPTimeout,50"
4201        cmd += ",DPPConfEnrolleeRole,STA,DPPConfIndex,1"
4202        res = dut.run_cmd(cmd, timeout=60)
4203        if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
4204            raise Exception("Unexpected result: " + res)
4205        ev = dev[0].wait_event(["DPP-PB-RESULT"], timeout=1)
4206        if ev is None or "success" not in ev:
4207            raise Exception("Push button bootstrapping did not succeed on STA")
4208
4209def test_sigma_dut_dpp_pb_ap_misbehavior(dev, apdev, params):
4210    """sigma_dut DPP/PB AP misbehavior)"""
4211    check_dpp_capab(dev[0], min_ver=3)
4212    check_sae_capab(dev[0])
4213
4214    logdir = params['prefix'] + ".sigma-hostapd"
4215    with HWSimRadio() as (radio, iface), \
4216         SigmaDut(iface, hostapd_logdir=logdir) as dut:
4217        dut.cmd_check("ap_reset_default,program,DPP")
4218        if "OK" not in dev[0].request("DPP_PUSH_BUTTON"):
4219            raise Exception("Failed to press push button on the STA")
4220
4221        cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPProvisioningRole,Configurator,DPPBS,PBBS,DPPTimeout,50"
4222        cmd += ",DPPConfEnrolleeRole,STA,DPPConfIndex,1"
4223        cmd += ",DPPStep,InvalidValue,DPPFrameType,PBPAResponse,DPPIEAttribute,InitBSKeyHash"
4224        res = dut.run_cmd(cmd, timeout=60)
4225        if "BootstrapResult,OK,AuthResult,Timeout" not in res:
4226            raise Exception("Unexpected result: " + res)
4227        ev = dev[0].wait_event(["DPP-PB-RESULT"], timeout=1)
4228        if ev is None or "failed" not in ev:
4229            raise Exception("Push button bootstrapping did not fail on STA")
4230
4231def test_sigma_dut_preconfigured_profile(dev, apdev):
4232    """sigma_dut controlled connection using preconfigured profile"""
4233    ifname = dev[0].ifname
4234    with SigmaDut(dev=dev[0]) as dut:
4235        params = hostapd.wpa2_params(ssid="test-psk", passphrase="12345678")
4236        hapd = hostapd.add_ap(apdev[0], params)
4237        dev[0].connect("test-psk", psk="12345678", scan_freq="2412",
4238                       only_add_network=True)
4239
4240        dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
4241        dut.cmd_check("sta_associate,interface,%s,ssid,%s" % (ifname, "test-psk"),
4242                            timeout=10)
4243        dut.wait_connected()
4244        dut.cmd_check("sta_get_ip_config,interface," + ifname)
4245        dut.cmd_check("sta_disconnect,interface," + ifname)
4246        dut.cmd_check("sta_reset_default,interface," + ifname)
4247
4248def test_sigma_dut_wps_pbc(dev, apdev):
4249    """sigma_dut and WPS PBC Enrollee"""
4250    ssid = "test-wps-conf"
4251    hapd = hostapd.add_ap(apdev[0],
4252                          {"ssid": "wps", "eap_server": "1", "wps_state": "2",
4253                           "wpa_passphrase": "12345678", "wpa": "2",
4254                           "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
4255    hapd.request("WPS_PBC")
4256
4257    ifname = dev[0].ifname
4258    with SigmaDut(dev=dev[0]) as dut:
4259        cmd = "start_wps_registration,interface,%s" % ifname
4260        cmd += ",WpsRole,Enrollee"
4261        cmd += ",WpsConfigMethod,PBC"
4262        dut.cmd_check(cmd, timeout=15)
4263
4264        dut.cmd_check("sta_disconnect,interface," + ifname)
4265        hapd.disable()
4266        dut.cmd_check("sta_reset_default,interface," + ifname)
4267
4268    dev[0].flush_scan_cache()
4269
4270def test_sigma_dut_sta_scan_bss(dev, apdev):
4271    """sigma_dut sta_scan_bss"""
4272    hapd = hostapd.add_ap(apdev[0], {"ssid": "test"})
4273    with SigmaDut(dev=dev[0]) as dut:
4274        cmd = "sta_scan_bss,Interface,%s,BSSID,%s" % (dev[0].ifname, \
4275                                                      hapd.own_addr())
4276        res = dut.run_cmd(cmd, timeout=10)
4277        if "ssid,test,bsschannel,1" not in res:
4278            raise Exception("Unexpected result: " + res)
4279
4280def test_sigma_dut_sta_scan_ssid_bssid(dev, apdev):
4281    """sigma_dut sta_scan GetParameter,SSID_BSSID"""
4282    hostapd.add_ap(apdev[0], {"ssid": "abcdef"})
4283    hostapd.add_ap(apdev[1], {"ssid": "qwerty"})
4284    with SigmaDut(dev=dev[0]) as dut:
4285        cmd = "sta_scan,Interface,%s,GetParameter,SSID_BSSID" % dev[0].ifname
4286        res = dut.run_cmd(cmd, timeout=10)
4287        if "abcdef" not in res or "qwerty" not in res:
4288            raise Exception("Unexpected result: " + res)
4289
4290def test_sigma_dut_sta_scan_short_ssid(dev, apdev):
4291    """sigma_dut sta_scan ShortSSID"""
4292    dev[0].flush_scan_cache()
4293    ssid = "test-short-ssid-list"
4294    hapd = hostapd.add_ap(apdev[0], {"ssid": ssid,
4295                                     "ignore_broadcast_ssid": "1"})
4296    bssid = apdev[0]['bssid']
4297    payload = struct.pack('>L', binascii.crc32(ssid.encode()))
4298    val = binascii.hexlify(payload).decode()
4299    with SigmaDut(dev=dev[0]) as dut:
4300        found = False
4301        cmd = "sta_scan,Interface,%s,ChnlFreq,2412,ShortSSID,%s" % (dev[0].ifname, val)
4302        for i in range(10):
4303            dut.cmd_check(cmd, timeout=5)
4304            ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
4305            if ev is None:
4306                raise Exception("Scan did not complete")
4307            if bssid in dev[0].request("SCAN_RESULTS"):
4308                found = True
4309                break
4310
4311    if not found:
4312        raise Exception("AP not found in scan results")
4313
4314def test_sigma_dut_sta_scan_wait_completion(dev, apdev):
4315    """sigma_dut sta_scan WaitCompletion,1"""
4316    with SigmaDut(dev=dev[0]) as dut:
4317        cmd = "sta_scan,Interface,%s,ChnlFreq,2412,WaitCompletion,1" % dev[0].ifname
4318        res = dut.run_cmd(cmd, timeout=10)
4319
4320def test_sigma_dut_ap_osen(dev, apdev, params):
4321    """sigma_dut controlled AP with OSEN"""
4322    logdir = os.path.join(params['logdir'],
4323                          "sigma_dut_ap_osen.sigma-hostapd")
4324    with HWSimRadio() as (radio, iface), \
4325         SigmaDut(iface, hostapd_logdir=logdir) as dut:
4326        dut.cmd_check("ap_reset_default")
4327        dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-hs20,MODE,11ng")
4328        dut.cmd_check("ap_set_radius,NAME,AP,IPADDR,127.0.0.1,PORT,1812,PASSWORD,radius")
4329        dut.cmd_check("ap_set_security,NAME,AP,KEYMGNT,OSEN,PMF,Optional")
4330        dut.cmd_check("ap_config_commit,NAME,AP")
4331
4332        # RSN-OSEN (for OSU)
4333        dev[0].connect("test-hs20", proto="OSEN", key_mgmt="OSEN",
4334                       pairwise="CCMP", group="GTK_NOT_USED",
4335                       eap="WFA-UNAUTH-TLS", identity="osen@example.com",
4336                       ca_cert="auth_serv/ca.pem", scan_freq="2412")
4337
4338def test_sigma_dut_ap_eap_osen(dev, apdev, params):
4339    """sigma_dut controlled AP with EAP+OSEN"""
4340    logdir = os.path.join(params['logdir'],
4341                          "sigma_dut_ap_eap_osen.sigma-hostapd")
4342    with HWSimRadio() as (radio, iface), \
4343         SigmaDut(iface, bridge="ap-br0", hostapd_logdir=logdir) as dut:
4344        try:
4345            dut.cmd_check("ap_reset_default")
4346            dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-hs20,MODE,11ng")
4347            dut.cmd_check("ap_set_radius,NAME,AP,IPADDR,127.0.0.1,PORT,1812,PASSWORD,radius")
4348            dut.cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-ENT-OSEN,PMF,Optional")
4349            dut.cmd_check("ap_config_commit,NAME,AP")
4350
4351            subprocess.call(['brctl', 'setfd', 'ap-br0', '0'])
4352            subprocess.call(['ip', 'link', 'set', 'dev', 'ap-br0', 'up'])
4353
4354            # RSN-OSEN (for OSU)
4355            dev[0].connect("test-hs20", proto="OSEN", key_mgmt="OSEN",
4356                           pairwise="CCMP",
4357                           eap="WFA-UNAUTH-TLS", identity="osen@example.com",
4358                           ca_cert="auth_serv/ca.pem", ieee80211w='2',
4359                           scan_freq="2412")
4360            # RSN-EAP (for data connection)
4361            dev[1].connect("test-hs20", key_mgmt="WPA-EAP", eap="TTLS",
4362                           identity="hs20-test", password="password",
4363                           ca_cert="auth_serv/ca.pem", phase2="auth=MSCHAPV2",
4364                           ieee80211w='2', scan_freq="2412")
4365
4366            hwsim_utils.test_connectivity(dev[0], dev[1], broadcast=False,
4367                                          success_expected=False, timeout=1)
4368
4369        finally:
4370            subprocess.call(['ip', 'link', 'set', 'dev', 'ap-br0', 'down'],
4371                            stderr=open('/dev/null', 'w'))
4372            subprocess.call(['brctl', 'delbr', 'ap-br0'],
4373                            stderr=open('/dev/null', 'w'))
4374
4375def test_sigma_dut_ap_eap(dev, apdev, params):
4376    """sigma_dut controlled AP WPA2-Enterprise"""
4377    logdir = os.path.join(params['logdir'], "sigma_dut_ap_eap.sigma-hostapd")
4378    with HWSimRadio() as (radio, iface), \
4379         SigmaDut(iface, hostapd_logdir=logdir) as dut:
4380        dut.cmd_check("ap_reset_default")
4381        dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-eap,MODE,11ng")
4382        dut.cmd_check("ap_set_radius,NAME,AP,IPADDR,127.0.0.1,PORT,1812,PASSWORD,radius")
4383        dut.cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-ENT")
4384        dut.cmd_check("ap_config_commit,NAME,AP")
4385
4386        dev[0].connect("test-eap", key_mgmt="WPA-EAP", eap="GPSK",
4387                       identity="gpsk user",
4388                       password="abcdefghijklmnop0123456789abcdef",
4389                       scan_freq="2412")
4390
4391def test_sigma_dut_ap_eap_sha256(dev, apdev, params):
4392    """sigma_dut controlled AP WPA2-Enterprise SHA256"""
4393    logdir = os.path.join(params['logdir'],
4394                          "sigma_dut_ap_eap_sha256.sigma-hostapd")
4395    with HWSimRadio() as (radio, iface), \
4396         SigmaDut(iface, hostapd_logdir=logdir) as dut:
4397        dut.cmd_check("ap_reset_default")
4398        dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-eap,MODE,11ng")
4399        dut.cmd_check("ap_set_radius,NAME,AP,IPADDR,127.0.0.1,PORT,1812,PASSWORD,radius")
4400        dut.cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-ENT-256")
4401        dut.cmd_check("ap_config_commit,NAME,AP")
4402
4403        dev[0].connect("test-eap", key_mgmt="WPA-EAP-SHA256", eap="GPSK",
4404                       identity="gpsk user",
4405                       password="abcdefghijklmnop0123456789abcdef",
4406                       scan_freq="2412")
4407
4408def test_sigma_dut_ap_ft_eap(dev, apdev, params):
4409    """sigma_dut controlled AP FT-EAP"""
4410    logdir = os.path.join(params['logdir'], "sigma_dut_ap_ft_eap.sigma-hostapd")
4411    with HWSimRadio() as (radio, iface), \
4412         SigmaDut(iface, hostapd_logdir=logdir) as dut:
4413        dut.cmd_check("ap_reset_default")
4414        dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-ft-eap,MODE,11ng,DOMAIN,0101,FT_OA,Enable")
4415        dut.cmd_check("ap_set_radius,NAME,AP,IPADDR,127.0.0.1,PORT,1812,PASSWORD,radius")
4416        dut.cmd_check("ap_set_security,NAME,AP,KEYMGNT,FT-EAP")
4417        dut.cmd_check("ap_config_commit,NAME,AP")
4418
4419        dev[0].connect("test-ft-eap", key_mgmt="FT-EAP", eap="GPSK",
4420                       identity="gpsk user",
4421                       password="abcdefghijklmnop0123456789abcdef",
4422                       scan_freq="2412")
4423
4424def test_sigma_dut_ap_ft_psk(dev, apdev, params):
4425    """sigma_dut controlled AP FT-PSK"""
4426    logdir = os.path.join(params['logdir'], "sigma_dut_ap_ft_psk.sigma-hostapd")
4427    with HWSimRadio() as (radio, iface), \
4428         SigmaDut(iface, hostapd_logdir=logdir) as dut:
4429        dut.cmd_check("ap_reset_default")
4430        dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-ft-psk,MODE,11ng,DOMAIN,0101,FT_OA,Enable")
4431        dut.cmd_check("ap_set_security,NAME,AP,KEYMGNT,FT-PSK,PSK,12345678")
4432        dut.cmd_check("ap_config_commit,NAME,AP")
4433
4434        dev[0].connect("test-ft-psk", key_mgmt="FT-PSK", psk="12345678",
4435                       scan_freq="2412")
4436
4437def test_sigma_dut_ap_ft_over_ds_psk(dev, apdev, params):
4438    """sigma_dut controlled AP FT-PSK (over-DS)"""
4439    logdir = os.path.join(params['logdir'],
4440                          "sigma_dut_ap_ft_over_ds_psk.sigma-hostapd")
4441    conffile = os.path.join(params['logdir'],
4442                            "sigma_dut_ap_ft_over_ds_psk.sigma-conf")
4443    with HWSimRadio() as (radio, iface), \
4444         SigmaDut(iface, hostapd_logdir=logdir) as dut:
4445        dut.cmd_check("ap_reset_default")
4446        dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-ft-psk,MODE,11ng,DOMAIN,0101,FT_DS,Enable")
4447        dut.cmd_check("ap_set_security,NAME,AP,KEYMGNT,FT-PSK,PSK,12345678")
4448        dut.cmd_check("ap_config_commit,NAME,AP")
4449
4450        with open("/tmp/sigma_dut-ap.conf", "rb") as f, \
4451             open(conffile, "wb") as f2:
4452            f2.write(f.read())
4453
4454        dev[0].connect("test-ft-psk", key_mgmt="FT-PSK", psk="12345678",
4455                       scan_freq="2412")
4456
4457def test_sigma_dut_ap_ent_ft_eap(dev, apdev, params):
4458    """sigma_dut controlled AP WPA-EAP and FT-EAP"""
4459    logdir = os.path.join(params['logdir'],
4460                          "sigma_dut_ap_ent_ft_eap.sigma-hostapd")
4461    with HWSimRadio() as (radio, iface), \
4462         SigmaDut(iface, hostapd_logdir=logdir) as dut:
4463        dut.cmd_check("ap_reset_default")
4464        dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-ent-ft-eap,MODE,11ng,DOMAIN,0101,FT_OA,Enable")
4465        dut.cmd_check("ap_set_radius,NAME,AP,IPADDR,127.0.0.1,PORT,1812,PASSWORD,radius")
4466        dut.cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-ENT-FT-EAP")
4467        dut.cmd_check("ap_config_commit,NAME,AP")
4468
4469        dev[0].connect("test-ent-ft-eap", key_mgmt="FT-EAP", eap="GPSK",
4470                       identity="gpsk user",
4471                       password="abcdefghijklmnop0123456789abcdef",
4472                       scan_freq="2412")
4473        dev[1].connect("test-ent-ft-eap", key_mgmt="WPA-EAP", eap="GPSK",
4474                       identity="gpsk user",
4475                       password="abcdefghijklmnop0123456789abcdef",
4476                       scan_freq="2412")
4477
4478def test_sigma_dut_venue_url(dev, apdev):
4479    """sigma_dut controlled Venue URL fetch"""
4480    ifname = dev[0].ifname
4481    with SigmaDut(dev=dev[0]) as dut:
4482        ssid = "venue"
4483        params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
4484        params["wpa_key_mgmt"] = "WPA-PSK-SHA256"
4485        params["ieee80211w"] = "2"
4486
4487        venue_group = 1
4488        venue_type = 13
4489        venue_info = struct.pack('BB', venue_group, venue_type)
4490        lang1 = "eng"
4491        name1 = "Example venue"
4492        lang2 = "fin"
4493        name2 = "Esimerkkipaikka"
4494        venue1 = struct.pack('B', len(lang1 + name1)) + lang1.encode() + name1.encode()
4495        venue2 = struct.pack('B', len(lang2 + name2)) + lang2.encode() + name2.encode()
4496        venue_name = binascii.hexlify(venue_info + venue1 + venue2)
4497
4498        url1 = "http://example.com/venue"
4499        url2 = "https://example.org/venue-info/"
4500        params["venue_group"] = str(venue_group)
4501        params["venue_type"] = str(venue_type)
4502        params["venue_name"] = [lang1 + ":" + name1, lang2 + ":" + name2]
4503        params["venue_url"] = ["1:" + url1, "2:" + url2]
4504
4505        hapd = hostapd.add_ap(apdev[0], params)
4506
4507        dut.cmd_check("sta_reset_default,interface,%s,prog,PMF" % ifname)
4508        dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
4509        dut.cmd_check("sta_set_psk,interface,%s,ssid,%s,passphrase,%s,encpType,aes-ccmp,keymgmttype,wpa2,PMF,Required" % (ifname, "venue", "12345678"))
4510        dut.cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "venue"),
4511                            timeout=10)
4512        dut.wait_connected()
4513        dut.cmd_check("sta_get_ip_config,interface," + ifname)
4514        dut.cmd_check("sta_hs2_venue_info,interface," + ifname + ",Display,Yes")
4515        dut.cmd_check("sta_disconnect,interface," + ifname)
4516        dut.cmd_check("sta_reset_default,interface," + ifname)
4517
4518def test_sigma_dut_hs20_assoc_24(dev, apdev):
4519    """sigma_dut controlled Hotspot 2.0 connection (2.4 GHz)"""
4520    run_sigma_dut_hs20_assoc(dev, apdev, True)
4521
4522def test_sigma_dut_hs20_assoc_5(dev, apdev):
4523    """sigma_dut controlled Hotspot 2.0 connection (5 GHz)"""
4524    run_sigma_dut_hs20_assoc(dev, apdev, False)
4525
4526def run_sigma_dut_hs20_assoc(dev, apdev, band24):
4527    hapd0 = None
4528    hapd1 = None
4529    try:
4530        bssid0 = apdev[0]['bssid']
4531        params = hs20_ap_params()
4532        params['hessid'] = bssid0
4533        hapd0 = hostapd.add_ap(apdev[0], params)
4534
4535        bssid1 = apdev[1]['bssid']
4536        params = hs20_ap_params()
4537        params['hessid'] = bssid0
4538        params["hw_mode"] = "a"
4539        params["channel"] = "36"
4540        params["country_code"] = "US"
4541        hapd1 = hostapd.add_ap(apdev[1], params)
4542
4543        band = "2.4" if band24 else "5"
4544        exp_bssid = bssid0 if band24 else bssid1
4545        run_sigma_dut_hs20_assoc_2(dev, apdev, band, exp_bssid)
4546    finally:
4547        dev[0].request("DISCONNECT")
4548        if hapd0:
4549            hapd0.request("DISABLE")
4550        if hapd1:
4551            hapd1.request("DISABLE")
4552        subprocess.call(['iw', 'reg', 'set', '00'])
4553        dev[0].flush_scan_cache()
4554
4555def run_sigma_dut_hs20_assoc_2(dev, apdev, band, expect_bssid):
4556    check_eap_capa(dev[0], "MSCHAPV2")
4557    dev[0].flush_scan_cache()
4558
4559    ifname = dev[0].ifname
4560    with SigmaDut(dev=dev[0]) as dut:
4561        dut.cmd_check("sta_reset_default,interface,%s,prog,HS2-R3" % ifname)
4562        dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
4563        dut.cmd_check("sta_add_credential,interface,%s,type,uname_pwd,realm,example.com,username,hs20-test,password,password" % ifname)
4564        res = dut.cmd_check("sta_hs2_associate,interface,%s,band,%s" % (ifname, band),
4565                                  timeout=15)
4566        dut.wait_connected()
4567        dut.cmd_check("sta_get_ip_config,interface," + ifname)
4568        dut.cmd_check("sta_disconnect,interface," + ifname)
4569        dut.cmd_check("sta_reset_default,interface," + ifname)
4570
4571    if "BSSID," + expect_bssid not in res:
4572        raise Exception("Unexpected BSSID: " + res)
4573
4574def test_sigma_dut_ap_hs20(dev, apdev, params):
4575    """sigma_dut controlled AP with Hotspot 2.0 parameters"""
4576    logdir = os.path.join(params['logdir'],
4577                          "sigma_dut_ap_hs20.sigma-hostapd")
4578    conffile = os.path.join(params['logdir'],
4579                            "sigma_dut_ap_hs20.sigma-conf")
4580    with HWSimRadio() as (radio, iface), \
4581         SigmaDut(iface, hostapd_logdir=logdir) as dut:
4582        dut.cmd_check("ap_reset_default,NAME,AP,program,HS2-R3")
4583        dut.cmd_check("ap_set_wireless,NAME,AP,WLAN_TAG,1,CHANNEL,1,SSID,test-hs20,MODE,11ng")
4584        dut.cmd_check("ap_set_radius,NAME,AP,WLAN_TAG,1,IPADDR,127.0.0.1,PORT,1812,PASSWORD,radius")
4585        dut.cmd_check("ap_set_security,NAME,AP,WLAN_TAG,1,KEYMGNT,WPA2-ENT")
4586        dut.cmd_check("ap_set_hs2,NAME,AP,WLAN_TAG,1,HESSID,02:12:34:56:78:9a,NAI_REALM_LIST,1,OPER_NAME,1")
4587        dut.cmd_check("ap_set_hs2,NAME,AP,WLAN_TAG,1,OSU_SERVER_URI,https://example.com/ https://example.org/,OSU_SSID,test-osu,OSU_METHOD,SOAP SOAP,OSU_PROVIDER_LIST,10,OSU_PROVIDER_NAI_LIST,4")
4588        dut.cmd_check("ap_set_hs2,NAME,AP,WLAN_TAG,1,NET_AUTH_TYPE,2")
4589        dut.cmd_check("ap_set_hs2,NAME,AP,WLAN_TAG,1,VENUE_NAME,1")
4590        dut.cmd_check("ap_set_hs2,NAME,AP,WLAN_TAG,1,DOMAIN_LIST,example.com")
4591        dut.cmd_check("ap_set_hs2,NAME,AP,WLAN_TAG,1,OPERATOR_ICON_METADATA,1")
4592        dut.cmd_check("ap_set_wireless,NAME,AP,WLAN_TAG,2,CHANNEL,1,SSID,test-osu,MODE,11ng")
4593        dut.cmd_check("ap_set_security,NAME,AP,WLAN_TAG,2,KEYMGNT,NONE")
4594        dut.cmd_check("ap_set_hs2,NAME,AP,WLAN_TAG,2,OSU,1")
4595        dut.cmd_check("ap_config_commit,NAME,AP")
4596
4597        with open("/tmp/sigma_dut-ap.conf", "rb") as f, \
4598             open(conffile, "wb") as f2:
4599            f2.write(f.read())
4600
4601def test_sigma_dut_eap_ttls_uosc(dev, apdev, params):
4602    """sigma_dut controlled STA and EAP-TTLS with UOSC"""
4603    logdir = params['logdir']
4604
4605    with open("auth_serv/ca.pem", "r") as f:
4606        with open(os.path.join(logdir, "sigma_dut_eap_ttls_uosc.ca.pem"),
4607                  "w") as f2:
4608            f2.write(f.read())
4609
4610    src = "auth_serv/server.pem"
4611    dst = os.path.join(logdir, "sigma_dut_eap_ttls_uosc.server.der")
4612    hashdst = os.path.join(logdir, "sigma_dut_eap_ttls_uosc.server.pem.sha256")
4613    subprocess.check_call(["openssl", "x509", "-in", src, "-out", dst,
4614                           "-outform", "DER"],
4615                          stderr=open('/dev/null', 'w'))
4616    with open(dst, "rb") as f:
4617        der = f.read()
4618    hash = hashlib.sha256(der).digest()
4619    with open(hashdst, "w") as f:
4620        f.write(binascii.hexlify(hash).decode())
4621
4622    dst = os.path.join(logdir, "sigma_dut_eap_ttls_uosc.incorrect.pem.sha256")
4623    with open(dst, "w") as f:
4624        f.write(32*"00")
4625
4626    ssid = "test-wpa2-eap"
4627    params = hostapd.wpa2_eap_params(ssid=ssid)
4628    hapd = hostapd.add_ap(apdev[0], params)
4629
4630    ifname = dev[0].ifname
4631    with SigmaDut(dev=dev[0], cert_path=logdir) as dut:
4632        cmd = "sta_set_security,type,eapttls,interface,%s,ssid,%s,keymgmttype,wpa2,encType,AES-CCMP,PairwiseCipher,AES-CCMP-128,username,DOMAIN\mschapv2 user,password,password,ServerCert,sigma_dut_eap_ttls_uosc.incorrect.pem" % (ifname, ssid)
4633
4634        dut.cmd_check("sta_reset_default,interface,%s,prog,WPA3" % ifname)
4635        dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
4636        dut.cmd_check(cmd)
4637        dut.cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, ssid),
4638                            timeout=10)
4639        ev = dev[0].wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR"], timeout=10)
4640        if ev is None:
4641            raise Exception("Server certificate error not reported")
4642
4643        res = dut.cmd_check("dev_exec_action,program,WPA3,interface,%s,ServerCertTrust,Accept" % ifname)
4644        if "ServerCertTrustResult,Accepted" not in res:
4645            raise Exception("Server certificate trust was not accepted")
4646        dut.wait_connected()
4647        dut.cmd_check("sta_disconnect,interface," + ifname)
4648        dut.cmd_check("sta_reset_default,interface," + ifname)
4649        dev[0].dump_monitor()
4650
4651def test_sigma_dut_eap_ttls_uosc_tod(dev, apdev, params):
4652    """sigma_dut controlled STA and EAP-TTLS with UOSC/TOD-STRICT"""
4653    run_sigma_dut_eap_ttls_uosc_tod(dev, apdev, params, False)
4654
4655def test_sigma_dut_eap_ttls_uosc_tod_tofu(dev, apdev, params):
4656    """sigma_dut controlled STA and EAP-TTLS with UOSC/TOD-TOFU"""
4657    run_sigma_dut_eap_ttls_uosc_tod(dev, apdev, params, True)
4658
4659def run_sigma_dut_eap_ttls_uosc_tod(dev, apdev, params, tofu):
4660    check_tls_tod(dev[0])
4661    logdir = params['logdir']
4662
4663    name = "sigma_dut_eap_ttls_uosc_tod"
4664    if tofu:
4665        name += "_tofu"
4666    with open("auth_serv/ca.pem", "r") as f:
4667        with open(os.path.join(logdir, name + ".ca.pem"), "w") as f2:
4668            f2.write(f.read())
4669
4670    if tofu:
4671        src = "auth_serv/server-certpol2.pem"
4672    else:
4673        src = "auth_serv/server-certpol.pem"
4674    dst = os.path.join(logdir, name + ".server.der")
4675    hashdst = os.path.join(logdir, name + ".server.pem.sha256")
4676    subprocess.check_call(["openssl", "x509", "-in", src, "-out", dst,
4677                           "-outform", "DER"],
4678                          stderr=open('/dev/null', 'w'))
4679    with open(dst, "rb") as f:
4680        der = f.read()
4681    hash = hashlib.sha256(der).digest()
4682    with open(hashdst, "w") as f:
4683        f.write(binascii.hexlify(hash).decode())
4684
4685    ssid = "test-wpa2-eap"
4686    params = int_eap_server_params()
4687    params["ssid"] = ssid
4688    if tofu:
4689        params["server_cert"] = "auth_serv/server-certpol2.pem"
4690        params["private_key"] = "auth_serv/server-certpol2.key"
4691    else:
4692        params["server_cert"] = "auth_serv/server-certpol.pem"
4693        params["private_key"] = "auth_serv/server-certpol.key"
4694    hapd = hostapd.add_ap(apdev[0], params)
4695
4696    ifname = dev[0].ifname
4697    with SigmaDut(dev=dev[0], cert_path=logdir) as dut:
4698        cmd = ("sta_set_security,type,eapttls,interface,%s,ssid,%s,keymgmttype,wpa2,encType,AES-CCMP,PairwiseCipher,AES-CCMP-128,trustedRootCA," + name + ".ca.pem,username,DOMAIN\mschapv2 user,password,password,ServerCert," + name + ".server.pem") % (ifname, ssid)
4699        dut.cmd_check("sta_reset_default,interface,%s,prog,WPA3" % ifname)
4700        dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
4701        dut.cmd_check(cmd)
4702        dut.cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, ssid),
4703                            timeout=10)
4704        dut.wait_connected()
4705        dut.cmd_check("sta_get_ip_config,interface," + ifname)
4706        dut.cmd_check("sta_disconnect,interface," + ifname + ",maintain_profile,1")
4707        dev[0].wait_disconnected()
4708        dev[0].dump_monitor()
4709
4710        hapd.disable()
4711        params = hostapd.wpa2_eap_params(ssid=ssid)
4712        hapd = hostapd.add_ap(apdev[0], params)
4713
4714        dut.cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, ssid),
4715                            timeout=10)
4716        ev = dev[0].wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR"], timeout=10)
4717        if ev is None:
4718            raise Exception("Server certificate error not reported")
4719
4720        res = dut.cmd_check("dev_exec_action,program,WPA3,interface,%s,ServerCertTrust,Accept" % ifname)
4721        if "ServerCertTrustResult,Accepted" in res:
4722            raise Exception("Server certificate trust override was accepted unexpectedly")
4723        dut.cmd_check("sta_reset_default,interface," + ifname)
4724        dev[0].dump_monitor()
4725
4726def test_sigma_dut_eap_ttls_uosc_initial_tod_strict(dev, apdev, params):
4727    """sigma_dut controlled STA and EAP-TTLS with initial UOSC/TOD-STRICT"""
4728    run_sigma_dut_eap_ttls_uosc_initial_tod(dev, apdev, params, False)
4729
4730def test_sigma_dut_eap_ttls_uosc_initial_tod_tofu(dev, apdev, params):
4731    """sigma_dut controlled STA and EAP-TTLS with initial UOSC/TOD-TOFU"""
4732    run_sigma_dut_eap_ttls_uosc_initial_tod(dev, apdev, params, True)
4733
4734def run_sigma_dut_eap_ttls_uosc_initial_tod(dev, apdev, params, tofu):
4735    check_tls_tod(dev[0])
4736    logdir = params['logdir']
4737    name = params['name']
4738    with open("auth_serv/rsa3072-ca.pem", "r") as f:
4739        with open(params['prefix'] + ".ca.pem", "w") as f2:
4740            f2.write(f.read())
4741
4742    if tofu:
4743        src = "auth_serv/server-certpol2.pem"
4744    else:
4745        src = "auth_serv/server-certpol.pem"
4746    dst = params['prefix'] + ".server.der"
4747    hashdst = params['prefix'] + ".server.pem.sha256"
4748    subprocess.check_call(["openssl", "x509", "-in", src, "-out", dst,
4749                           "-outform", "DER"],
4750                          stderr=open('/dev/null', 'w'))
4751    with open(dst, "rb") as f:
4752        der = f.read()
4753    hash = hashlib.sha256(der).digest()
4754    with open(hashdst, "w") as f:
4755        f.write(binascii.hexlify(hash).decode())
4756
4757    ssid = "test-wpa2-eap"
4758    params = int_eap_server_params()
4759    params["ssid"] = ssid
4760    if tofu:
4761        params["server_cert"] = "auth_serv/server-certpol2.pem"
4762        params["private_key"] = "auth_serv/server-certpol2.key"
4763    else:
4764        params["server_cert"] = "auth_serv/server-certpol.pem"
4765        params["private_key"] = "auth_serv/server-certpol.key"
4766    hapd = hostapd.add_ap(apdev[0], params)
4767
4768    ifname = dev[0].ifname
4769    with SigmaDut(dev=dev[0], cert_path=logdir) as dut:
4770        cmd = ("sta_set_security,type,eapttls,interface,%s,ssid,%s,keymgmttype,wpa2,encType,AES-CCMP,PairwiseCipher,AES-CCMP-128,trustedRootCA," + name + ".ca.pem,username,DOMAIN\mschapv2 user,password,password") % (ifname, ssid)
4771        dut.cmd_check("sta_reset_default,interface,%s,prog,WPA3" % ifname)
4772        dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
4773        dut.cmd_check(cmd)
4774        dut.cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, ssid),
4775                            timeout=10)
4776        ev = dev[0].wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR"], timeout=15)
4777        if ev is None:
4778            raise Exception("Server certificate validation failure not reported")
4779
4780        res = dut.cmd_check("dev_exec_action,program,WPA3,interface,%s,ServerCertTrust,Accept" % ifname)
4781        if not tofu and "ServerCertTrustResult,Accepted" in res:
4782            raise Exception("Server certificate trust override was accepted unexpectedly")
4783        if tofu and "ServerCertTrustResult,Accepted" not in res:
4784            raise Exception("Server certificate trust override was not accepted")
4785        dut.cmd_check("sta_reset_default,interface," + ifname)
4786        dev[0].dump_monitor()
4787
4788def test_sigma_dut_eap_ttls_uosc_ca_mistrust(dev, apdev, params):
4789    """sigma_dut controlled STA and EAP-TTLS with UOSC when CA is not trusted"""
4790    check_domain_suffix_match(dev[0])
4791    logdir = params['logdir']
4792
4793    with open("auth_serv/ca.pem", "r") as f:
4794        with open(os.path.join(logdir,
4795                               "sigma_dut_eap_ttls_uosc_ca_mistrust.ca.pem"),
4796                  "w") as f2:
4797            f2.write(f.read())
4798
4799    ssid = "test-wpa2-eap"
4800    params = int_eap_server_params()
4801    params["ssid"] = ssid
4802    params["ca_cert"] = "auth_serv/rsa3072-ca.pem"
4803    params["server_cert"] = "auth_serv/rsa3072-server.pem"
4804    params["private_key"] = "auth_serv/rsa3072-server.key"
4805    hapd = hostapd.add_ap(apdev[0], params)
4806
4807    ifname = dev[0].ifname
4808    with SigmaDut(dev=dev[0], cert_path=logdir) as dut:
4809        cmd = "sta_set_security,type,eapttls,interface,%s,ssid,%s,keymgmttype,wpa2,encType,AES-CCMP,PairwiseCipher,AES-CCMP-128,trustedRootCA,sigma_dut_eap_ttls_uosc_ca_mistrust.ca.pem,username,DOMAIN\mschapv2 user,password,password,domainSuffix,w1.fi" % (ifname, ssid)
4810        dut.cmd_check("sta_reset_default,interface,%s,prog,WPA3" % ifname)
4811        dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
4812        dut.cmd_check(cmd)
4813        dut.cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, ssid),
4814                            timeout=10)
4815        ev = dev[0].wait_event(["CTRL-EVENT-EAP-TLS-CERT-ERROR"], timeout=10)
4816        if ev is None:
4817            raise Exception("Server certificate error not reported")
4818
4819        res = dut.cmd_check("dev_exec_action,program,WPA3,interface,%s,ServerCertTrust,Accept" % ifname)
4820        if "ServerCertTrustResult,Accepted" not in res:
4821            raise Exception("Server certificate trust was not accepted")
4822        dut.wait_connected()
4823        dut.cmd_check("sta_disconnect,interface," + ifname)
4824        dut.cmd_check("sta_reset_default,interface," + ifname)
4825        dev[0].dump_monitor()
4826
4827def test_sigma_dut_eap_aka(dev, apdev, params):
4828    """sigma_dut controlled STA and EAP-AKA parameters"""
4829    logdir = params['logdir']
4830    name = "sigma_dut_eap_aka"
4831    cert_file = name + ".imsi-privacy.pem"
4832
4833    with open("auth_serv/imsi-privacy-cert.pem", "r") as f:
4834        with open(os.path.join(logdir, cert_file), "w") as f2:
4835            f2.write(f.read())
4836
4837    ssid = "test-wpa2-eap"
4838    params = hostapd.wpa2_eap_params(ssid=ssid)
4839    hapd = hostapd.add_ap(apdev[0], params)
4840
4841    ifname = dev[0].ifname
4842    identity = "0232010000000000@wlan.mnc232.mcc02.3gppnetwork.org"
4843    password = "90dca4eda45b53cf0f12d7c9c3bc6a89:cb9cccc4b9258e6dca4760379fb82581:000000000123"
4844    cmd = "sta_set_eapaka,interface,%s,ssid,%s,keymgmttype,wpa2,encpType,AES-CCMP,imsiPrivacyCert,%s,imsiPrivacyCertID,serno=12345,username,%s,password,%s" % (ifname, ssid, cert_file, identity, password)
4845
4846    with SigmaDut(dev=dev[0], cert_path=logdir) as dut:
4847        dut.cmd_check("sta_reset_default,interface,%s,prog,WPA3" % ifname)
4848        dut.cmd_check(cmd)
4849        dut.cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, ssid),
4850                      timeout=10)
4851        dut.wait_connected()
4852        dut.cmd_check("sta_disconnect,interface," + ifname)
4853        dut.cmd_check("sta_reset_default,interface," + ifname)
4854        dev[0].dump_monitor()
4855
4856def start_sae_pwe_ap(apdev, sae_pwe, ssid="test-sae", password="12345678"):
4857    params = hostapd.wpa2_params(ssid=ssid, passphrase=password)
4858    params['wpa_key_mgmt'] = 'SAE'
4859    params["ieee80211w"] = "2"
4860    params['sae_groups'] = '19'
4861    params['sae_pwe'] = str(sae_pwe)
4862    return hostapd.add_ap(apdev, params)
4863
4864def connect_sae_pwe_sta(dut, dev, ifname, extra=None):
4865    dev.dump_monitor()
4866    dut.cmd_check("sta_reset_default,interface,%s" % ifname)
4867    dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
4868    cmd = "sta_set_security,interface,%s,ssid,%s,passphrase,%s,type,SAE,encpType,aes-ccmp,keymgmttype,wpa2" % (ifname, "test-sae", "12345678")
4869    if extra:
4870        cmd += "," + extra
4871    dut.cmd_check(cmd)
4872    dut.cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-sae"),
4873                        timeout=10)
4874    dut.wait_connected()
4875    dut.cmd_check("sta_disconnect,interface," + ifname)
4876    dev.wait_disconnected()
4877    dut.cmd_check("sta_reset_default,interface," + ifname)
4878    dev.dump_monitor()
4879
4880def no_connect_sae_pwe_sta(dut, dev, ifname, extra=None):
4881    dev.dump_monitor()
4882    dut.cmd_check("sta_reset_default,interface,%s" % ifname)
4883    dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
4884    cmd = "sta_set_security,interface,%s,ssid,%s,passphrase,%s,type,SAE,encpType,aes-ccmp,keymgmttype,wpa2" % (ifname, "test-sae", "12345678")
4885    if extra:
4886        cmd += "," + extra
4887    dut.cmd_check(cmd)
4888    dut.cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-sae"),
4889                        timeout=10)
4890    ev = dev.wait_event(["CTRL-EVENT-CONNECTED",
4891                         "CTRL-EVENT-NETWORK-NOT-FOUND"], timeout=10)
4892    if ev is None or "CTRL-EVENT-CONNECTED" in ev:
4893        raise Exception("Unexpected connection result")
4894    dut.cmd_check("sta_reset_default,interface," + ifname)
4895    dev.dump_monitor()
4896
4897def test_sigma_dut_sae_h2e(dev, apdev):
4898    """sigma_dut controlled SAE H2E association (AP using loop+H2E)"""
4899    check_sae_capab(dev[0])
4900
4901    start_sae_pwe_ap(apdev[0], 2)
4902
4903    ifname = dev[0].ifname
4904    with SigmaDut(dev=dev[0], sae_h2e=True) as dut:
4905        connect_sae_pwe_sta(dut, dev[0], ifname)
4906        connect_sae_pwe_sta(dut, dev[0], ifname, extra="sae_pwe,h2e")
4907        connect_sae_pwe_sta(dut, dev[0], ifname, extra="sae_pwe,loop")
4908        res = dut.run_cmd("sta_set_security,interface,%s,ssid,%s,passphrase,%s,type,SAE,encpType,aes-ccmp,keymgmttype,wpa2,sae_pwe,unknown" % (ifname, "test-sae", "12345678"))
4909        if res != "status,ERROR,errorCode,Unsupported sae_pwe value":
4910            raise Exception("Unexpected error result: " + res)
4911
4912def test_sigma_dut_sae_h2e_ap_loop(dev, apdev):
4913    """sigma_dut controlled SAE H2E association (AP using loop-only)"""
4914    check_sae_capab(dev[0])
4915
4916    start_sae_pwe_ap(apdev[0], 0)
4917
4918    ifname = dev[0].ifname
4919    with SigmaDut(dev=dev[0], sae_h2e=True) as dut:
4920        connect_sae_pwe_sta(dut, dev[0], ifname)
4921        connect_sae_pwe_sta(dut, dev[0], ifname, extra="sae_pwe,loop")
4922        no_connect_sae_pwe_sta(dut, dev[0], ifname, extra="sae_pwe,h2e")
4923
4924def test_sigma_dut_sae_h2e_ap_h2e(dev, apdev):
4925    """sigma_dut controlled SAE H2E association (AP using H2E-only)"""
4926    check_sae_capab(dev[0])
4927
4928    start_sae_pwe_ap(apdev[0], 1)
4929
4930    ifname = dev[0].ifname
4931    with SigmaDut(dev=dev[0], sae_h2e=True) as dut:
4932        connect_sae_pwe_sta(dut, dev[0], ifname)
4933        no_connect_sae_pwe_sta(dut, dev[0], ifname, extra="sae_pwe,loop")
4934        connect_sae_pwe_sta(dut, dev[0], ifname, extra="sae_pwe,h2e")
4935
4936def test_sigma_dut_ap_sae_h2e(dev, apdev, params):
4937    """sigma_dut controlled AP with SAE H2E"""
4938    logdir = os.path.join(params['logdir'],
4939                          "sigma_dut_ap_sae_h2e.sigma-hostapd")
4940    check_sae_capab(dev[0])
4941    with HWSimRadio() as (radio, iface), \
4942         SigmaDut(iface, sae_h2e=True, hostapd_logdir=logdir) as dut:
4943        try:
4944            dut.cmd_check("ap_reset_default")
4945            dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-sae,MODE,11ng")
4946            dut.cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-SAE,PSK,12345678")
4947            dut.cmd_check("ap_config_commit,NAME,AP")
4948
4949            for sae_pwe in [0, 1, 2]:
4950                dev[0].request("SET sae_groups ")
4951                dev[0].set("sae_pwe", str(sae_pwe))
4952                dev[0].connect("test-sae", key_mgmt="SAE", psk="12345678",
4953                               ieee80211w="2", scan_freq="2412")
4954                dev[0].request("REMOVE_NETWORK all")
4955                dev[0].wait_disconnected()
4956                dev[0].dump_monitor()
4957        finally:
4958            dev[0].set("sae_pwe", "0")
4959
4960def test_sigma_dut_ap_sae_h2e_only(dev, apdev, params):
4961    """sigma_dut controlled AP with SAE H2E-only"""
4962    logdir = os.path.join(params['logdir'],
4963                          "sigma_dut_ap_sae_h2e.sigma-hostapd")
4964    check_sae_capab(dev[0])
4965    with HWSimRadio() as (radio, iface), \
4966         SigmaDut(iface, sae_h2e=True, hostapd_logdir=logdir) as dut:
4967        try:
4968            dut.cmd_check("ap_reset_default")
4969            dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-sae,MODE,11ng")
4970            dut.cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-SAE,PSK,12345678,sae_pwe,h2e")
4971            dut.cmd_check("ap_config_commit,NAME,AP")
4972
4973            dev[0].request("SET sae_groups ")
4974            dev[0].set("sae_pwe", "1")
4975            dev[0].connect("test-sae", key_mgmt="SAE", psk="12345678",
4976                           ieee80211w="2", scan_freq="2412")
4977            dev[0].request("REMOVE_NETWORK all")
4978            dev[0].wait_disconnected()
4979            dev[0].dump_monitor()
4980
4981            dev[0].set("sae_pwe", "0")
4982            dev[0].connect("test-sae", key_mgmt="SAE", psk="12345678",
4983                           ieee80211w="2", scan_freq="2412", wait_connect=False)
4984            ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
4985                                    "CTRL-EVENT-NETWORK-NOT-FOUND"], timeout=10)
4986            dev[0].request("DISCONNECT")
4987            if ev is None or "CTRL-EVENT-CONNECTED" in ev:
4988                raise Exception("Unexpected connection result")
4989        finally:
4990            dev[0].set("sae_pwe", "0")
4991
4992def test_sigma_dut_ap_sae_loop_only(dev, apdev, params):
4993    """sigma_dut controlled AP with SAE looping-only"""
4994    logdir = os.path.join(params['logdir'],
4995                          "sigma_dut_ap_sae_h2e.sigma-hostapd")
4996    check_sae_capab(dev[0])
4997    with HWSimRadio() as (radio, iface), \
4998         SigmaDut(iface, hostapd_logdir=logdir) as dut:
4999        try:
5000            dut.cmd_check("ap_reset_default")
5001            dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-sae,MODE,11ng")
5002            dut.cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-SAE,PSK,12345678,sae_pwe,loop")
5003            dut.cmd_check("ap_config_commit,NAME,AP")
5004
5005            dev[0].request("SET sae_groups ")
5006            dev[0].set("sae_pwe", "0")
5007            dev[0].connect("test-sae", key_mgmt="SAE", psk="12345678",
5008                           ieee80211w="2", scan_freq="2412")
5009            dev[0].request("REMOVE_NETWORK all")
5010            dev[0].wait_disconnected()
5011            dev[0].dump_monitor()
5012
5013            dev[0].set("sae_pwe", "1")
5014            dev[0].connect("test-sae", key_mgmt="SAE", psk="12345678",
5015                           ieee80211w="2", scan_freq="2412", wait_connect=False)
5016            ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
5017                                    "CTRL-EVENT-NETWORK-NOT-FOUND"], timeout=10)
5018            dev[0].request("DISCONNECT")
5019            if ev is None or "CTRL-EVENT-CONNECTED" in ev:
5020                raise Exception("Unexpected connection result")
5021        finally:
5022            dev[0].set("sae_pwe", "0")
5023
5024def test_sigma_dut_sae_h2e_loop_forcing(dev, apdev):
5025    """sigma_dut controlled SAE H2E misbehavior with looping forced"""
5026    check_sae_capab(dev[0])
5027
5028    ssid = "test-sae"
5029    params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
5030    params['wpa_key_mgmt'] = 'SAE'
5031    params["ieee80211w"] = "2"
5032    params['sae_pwe'] = '1'
5033    hapd = hostapd.add_ap(apdev[0], params)
5034
5035    ifname = dev[0].ifname
5036    with SigmaDut(dev=dev[0]) as dut:
5037        dut.cmd_check("sta_reset_default,interface,%s" % ifname)
5038        dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
5039        dut.cmd_check("sta_set_security,interface,%s,ssid,%s,passphrase,%s,type,SAE,encpType,aes-ccmp,keymgmttype,wpa2,IgnoreH2E_RSNXE_BSSMemSel,1" % (ifname, "test-sae", "12345678"))
5040        dut.cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-sae"),
5041                            timeout=10)
5042        ev = dev[0].wait_event(["SME: Trying to authenticate with"], timeout=10)
5043        if ev is None:
5044            raise Exception("No authentication attempt reported")
5045        ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=0.5)
5046        if ev is not None:
5047            raise Exception("Unexpected connection reported")
5048
5049def test_sigma_dut_sae_h2e_enabled_group_rejected(dev, apdev):
5050    """sigma_dut controlled SAE H2E misbehavior with rejected groups"""
5051    check_sae_capab(dev[0])
5052
5053    ssid = "test-sae"
5054    params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
5055    params['wpa_key_mgmt'] = 'SAE'
5056    params["ieee80211w"] = "2"
5057    params['sae_groups'] = "19 20"
5058    params['sae_pwe'] = '1'
5059    hapd = hostapd.add_ap(apdev[0], params)
5060
5061    ifname = dev[0].ifname
5062    with SigmaDut(dev=dev[0], sae_h2e=True) as dut:
5063        dut.cmd_check("sta_reset_default,interface,%s" % ifname)
5064        dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
5065        dut.cmd_check("sta_set_security,interface,%s,ssid,%s,passphrase,%s,type,SAE,encpType,aes-ccmp,keymgmttype,wpa2,ECGroupID_RGE,19 123" % (ifname, "test-sae", "12345678"))
5066        dut.cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-sae"),
5067                      timeout=10)
5068        ev = dev[0].wait_event(["SME: Trying to authenticate with"], timeout=10)
5069        if ev is None:
5070            raise Exception("No authentication attempt reported")
5071        ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=0.5)
5072        if ev is not None:
5073            raise Exception("Unexpected connection reported")
5074
5075def test_sigma_dut_sae_h2e_rsnxe_mismatch(dev, apdev):
5076    """sigma_dut controlled SAE H2E misbehavior with RSNXE"""
5077    check_sae_capab(dev[0])
5078
5079    ssid = "test-sae"
5080    params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
5081    params['wpa_key_mgmt'] = 'SAE'
5082    params["ieee80211w"] = "2"
5083    params['sae_groups'] = "19"
5084    params['sae_pwe'] = '1'
5085    hapd = hostapd.add_ap(apdev[0], params)
5086
5087    ifname = dev[0].ifname
5088    with SigmaDut(dev=dev[0], sae_h2e=True) as dut:
5089        dut.cmd_check("sta_reset_default,interface,%s" % ifname)
5090        dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
5091        dut.cmd_check("sta_set_security,interface,%s,ssid,%s,passphrase,%s,type,SAE,encpType,aes-ccmp,keymgmttype,wpa2,RSNXE_Content,EapolM2:F40100" % (ifname, "test-sae", "12345678"))
5092        dut.cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-sae"),
5093                            timeout=10)
5094        ev = dev[0].wait_event(["SME: Trying to authenticate with"], timeout=10)
5095        if ev is None:
5096            raise Exception("No authentication attempt reported")
5097        ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=0.5)
5098        if ev is not None:
5099            raise Exception("Unexpected connection reported")
5100
5101def test_sigma_dut_ap_sae_h2e_rsnxe_mismatch(dev, apdev, params):
5102    """sigma_dut controlled SAE H2E AP misbehavior with RSNXE"""
5103    logdir = os.path.join(params['logdir'],
5104                          "sigma_dut_ap_sae_h2e_rsnxe_mismatch.sigma-hostapd")
5105    check_sae_capab(dev[0])
5106    with HWSimRadio() as (radio, iface), \
5107         SigmaDut(iface, hostapd_logdir=logdir) as dut:
5108        try:
5109            dut.cmd_check("ap_reset_default")
5110            dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-sae,MODE,11ng")
5111            dut.cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-SAE,PSK,12345678,sae_pwe,h2e,RSNXE_Content,EapolM3:F40100")
5112            dut.cmd_check("ap_config_commit,NAME,AP")
5113
5114            dev[0].request("SET sae_groups ")
5115            dev[0].set("sae_pwe", "1")
5116            dev[0].connect("test-sae", key_mgmt="SAE", psk="12345678",
5117                           ieee80211w="2", scan_freq="2412", wait_connect=False)
5118            ev = dev[0].wait_event(["Associated with"], timeout=10)
5119            if ev is None:
5120                raise Exception("No indication of association seen")
5121            ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
5122                                    "CTRL-EVENT-DISCONNECTED"], timeout=10)
5123            dev[0].request("DISCONNECT")
5124            if ev is None:
5125                raise Exception("No disconnection seen")
5126            if "CTRL-EVENT-DISCONNECTED" not in ev:
5127                raise Exception("Unexpected connection")
5128        finally:
5129            dev[0].set("sae_pwe", "0")
5130
5131def test_sigma_dut_ap_sae_h2e_group_rejection(dev, apdev, params):
5132    """sigma_dut controlled AP with SAE H2E-only and group rejection"""
5133    logdir = os.path.join(params['logdir'],
5134                          "sigma_dut_ap_sae_h2e_group_rejection.sigma-hostapd")
5135    check_sae_capab(dev[0])
5136    with HWSimRadio() as (radio, iface), \
5137         SigmaDut(iface, hostapd_logdir=logdir) as dut:
5138        try:
5139            dut.cmd_check("ap_reset_default")
5140            dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-sae,MODE,11ng")
5141            dut.cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-SAE,PSK,12345678,sae_pwe,h2e")
5142            dut.cmd_check("ap_config_commit,NAME,AP")
5143
5144            dev[0].request("SET sae_groups 21 20 19")
5145            dev[0].set("sae_pwe", "1")
5146            dev[0].connect("test-sae", key_mgmt="SAE", psk="12345678",
5147                           ieee80211w="2", scan_freq="2412")
5148            addr = dev[0].own_addr()
5149            res = dut.cmd_check("dev_exec_action,program,WPA3,Dest_MAC,%s,Rejected_DH_Groups,1" % addr)
5150            if "DHGroupVerResult,21 20" not in res:
5151                raise Exception("Unexpected dev_exec_action response: " + res)
5152        finally:
5153            dev[0].set("sae_pwe", "0")
5154
5155def test_sigma_dut_ap_sae_h2e_anti_clogging(dev, apdev, params):
5156    """sigma_dut controlled AP with SAE H2E and anti-clogging token"""
5157    logdir = os.path.join(params['logdir'],
5158                          "sigma_dut_ap_sae_h2e_anti_clogging.sigma-hostapd")
5159    check_sae_capab(dev[0])
5160    with HWSimRadio() as (radio, iface), \
5161         SigmaDut(iface, hostapd_logdir=logdir) as dut:
5162        try:
5163            dut.cmd_check("ap_reset_default")
5164            dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-sae,MODE,11ng")
5165            dut.cmd_check("ap_set_security,NAME,AP,KEYMGNT,SAE,PSK,12345678,AntiCloggingThreshold,0")
5166            dut.cmd_check("ap_config_commit,NAME,AP")
5167
5168            dev[0].set("sae_groups", "")
5169            dev[0].set("sae_pwe", "2")
5170            dev[0].connect("test-sae", key_mgmt="SAE", psk="12345678",
5171                           ieee80211w="2", scan_freq="2412")
5172        finally:
5173            dev[0].set("sae_pwe", "0")
5174
5175def test_sigma_dut_ap_5ghz(dev, apdev, params):
5176    """sigma_dut controlled AP on 5 GHz"""
5177    run_sigma_dut_ap_channel(dev, apdev, params, 36, '11na', 5180,
5178                             check_signal="WIDTH=20 MHz")
5179
5180def test_sigma_dut_ap_ht40plus(dev, apdev, params):
5181    """sigma_dut controlled AP and HT40+"""
5182    run_sigma_dut_ap_channel(dev, apdev, params, 36, '11na', 5180,
5183                             extra="width,40", check_signal="WIDTH=40 MHz")
5184
5185def test_sigma_dut_ap_ht40minus(dev, apdev, params):
5186    """sigma_dut controlled AP and HT40-"""
5187    run_sigma_dut_ap_channel(dev, apdev, params, 40, '11na', 5200,
5188                             extra="width,40", check_signal="WIDTH=40 MHz")
5189
5190def test_sigma_dut_ap_vht40(dev, apdev, params):
5191    """sigma_dut controlled AP and VHT40"""
5192    run_sigma_dut_ap_channel(dev, apdev, params, 36, '11ac', 5180,
5193                             extra="width,40", check_signal="WIDTH=40 MHz",
5194                             program="VHT")
5195
5196def test_sigma_dut_ap_vht80(dev, apdev, params):
5197    """sigma_dut controlled AP and VHT80"""
5198    run_sigma_dut_ap_channel(dev, apdev, params, 36, '11ac', 5180,
5199                             extra="width,80", check_signal="WIDTH=80 MHz",
5200                             program="VHT")
5201
5202def run_sigma_dut_ap_channel(dev, apdev, params, channel, mode, scan_freq,
5203                             extra=None, check_signal=None, program=None):
5204    logdir = params['prefix'] + ".sigma-hostapd"
5205    with HWSimRadio() as (radio, iface), \
5206         SigmaDut(iface, hostapd_logdir=logdir) as dut:
5207        try:
5208            subprocess.call(['iw', 'reg', 'set', 'US'])
5209            for i in range(5):
5210                ev = dev[0].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=5)
5211                if ev is None:
5212                    break
5213                if "alpha2=US" in ev:
5214                    break
5215            cmd = "ap_reset_default"
5216            if program:
5217                cmd += ",program," + program
5218            dut.cmd_check(cmd)
5219            cmd = "ap_set_wireless,NAME,AP,CHANNEL,%d,SSID,test-psk,MODE,%s" % (channel, mode)
5220            if extra:
5221                cmd += "," + extra
5222            dut.cmd_check(cmd)
5223            dut.cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-PSK,PSK,12345678")
5224            dut.cmd_check("ap_config_commit,NAME,AP")
5225
5226            with open("/tmp/sigma_dut-ap.conf", "rb") as f:
5227                with open(params['prefix'] + ".sigma-conf", "wb") as f2:
5228                    f2.write(f.read())
5229
5230            dev[0].connect("test-psk", psk="12345678", scan_freq=str(scan_freq))
5231            sig = dev[0].request("SIGNAL_POLL")
5232            logger.info("SIGNAL_POLL:\n" + sig.strip())
5233            dev[0].request("DISCONNECT")
5234            dev[0].wait_disconnected()
5235
5236            if check_signal and check_signal not in sig:
5237                raise Exception("Unexpected SIGNAL_POLL data")
5238        finally:
5239            subprocess.call(['iw', 'reg', 'set', '00'])
5240            dev[0].flush_scan_cache()
5241
5242def test_sigma_dut_beacon_prot(dev, apdev):
5243    """sigma_dut controlled STA and beacon protection"""
5244    ssid = "test-pmf-required"
5245    params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
5246    params["wpa_key_mgmt"] = "WPA-PSK-SHA256"
5247    params["ieee80211w"] = "2"
5248    params["beacon_prot"] = "1"
5249    try:
5250        hapd = hostapd.add_ap(apdev[0], params)
5251    except Exception as e:
5252        if "Failed to enable hostapd interface" in str(e):
5253            raise HwsimSkip("Beacon protection not supported")
5254        raise
5255
5256    ifname = dev[0].ifname
5257    with SigmaDut(dev=dev[0]) as dut:
5258        dut.cmd_check("sta_reset_default,interface,%s,prog,PMF" % ifname)
5259        dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
5260        dut.cmd_check("sta_set_security,interface,%s,ssid,%s,type,PSK,passphrase,%s,encpType,aes-ccmp,keymgmttype,wpa2,PMF,Required,BeaconProtection,1" % (ifname, "test-pmf-required", "12345678"))
5261        dut.cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-pmf-required"),
5262                            timeout=10)
5263        dut.wait_connected()
5264
5265        time.sleep(1)
5266        check_mac80211_bigtk(dev[0], hapd)
5267
5268        dut.cmd_check("sta_reset_default,interface," + ifname)
5269
5270def test_sigma_dut_ap_beacon_prot(dev, apdev, params):
5271    """sigma_dut controlled AP and beacon protection"""
5272    logdir = params['prefix'] + ".sigma-hostapd"
5273
5274    Wlantest.setup(None)
5275    wt = Wlantest()
5276    wt.flush()
5277    wt.add_passphrase("12345678")
5278
5279    with HWSimRadio() as (radio, iface), \
5280         SigmaDut(iface, hostapd_logdir=logdir) as dut:
5281        dut.cmd_check("ap_reset_default")
5282        dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-psk,MODE,11ng")
5283        dut.cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-PSK,PSK,12345678,PMF,Required,BeaconProtection,1")
5284        dut.cmd_check("ap_config_commit,NAME,AP")
5285        bssid = dut.cmd_check("ap_get_mac_address,NAME,AP")
5286        bssid = bssid.split(',')[3]
5287
5288        dev[0].connect("test-psk", key_mgmt="WPA-PSK-SHA256",
5289                       psk="12345678", scan_freq="2412",
5290                       ieee80211w="2", beacon_prot="1")
5291        for i in range(10):
5292            dev[0].dump_monitor()
5293            time.sleep(0.1)
5294
5295    valid_bip = wt.get_bss_counter('valid_bip_mmie', bssid)
5296    invalid_bip = wt.get_bss_counter('invalid_bip_mmie', bssid)
5297    missing_bip = wt.get_bss_counter('missing_bip_mmie', bssid)
5298    logger.info("wlantest BIP counters: valid=%d invalid=%d missing=%d" % (valid_bip, invalid_bip, missing_bip))
5299    if valid_bip < 0 or invalid_bip > 0 or missing_bip > 0:
5300        raise Exception("Unexpected wlantest BIP counters: valid=%d invalid=%d missing=%d" % (valid_bip, invalid_bip, missing_bip))
5301
5302def test_sigma_dut_ap_transition_disable(dev, apdev, params):
5303    """sigma_dut controlled AP and transition disabled indication"""
5304    check_sae_capab(dev[0])
5305    logdir = params['prefix'] + ".sigma-hostapd"
5306
5307    with HWSimRadio() as (radio, iface), \
5308         SigmaDut(iface, hostapd_logdir=logdir) as dut:
5309        dut.cmd_check("ap_reset_default")
5310        dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-sae,MODE,11ng")
5311        dut.cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-SAE,PSK,12345678,PMF,Required,Transition_Disable,1,Transition_Disable_Index,0")
5312        dut.cmd_check("ap_config_commit,NAME,AP")
5313
5314        dev[0].set("sae_groups", "")
5315        dev[0].connect("test-sae", key_mgmt="SAE", psk="12345678",
5316                       ieee80211w="2", scan_freq="2412", wait_connect=False)
5317        ev = dev[0].wait_event(["TRANSITION-DISABLE"], timeout=15)
5318        if ev is None:
5319            raise Exception("Transition disable not indicated")
5320        if ev.split(' ')[1] != "01":
5321            raise Exception("Unexpected transition disable bitmap: " + ev)
5322
5323def test_sigma_dut_ap_transition_disable_change(dev, apdev, params):
5324    """sigma_dut controlled AP and transition disabled indication change"""
5325    check_sae_capab(dev[0])
5326    logdir = params['prefix'] + ".sigma-hostapd"
5327
5328    with HWSimRadio() as (radio, iface), \
5329         SigmaDut(iface, hostapd_logdir=logdir) as dut:
5330        dut.cmd_check("ap_reset_default")
5331        dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-sae,MODE,11ng")
5332        dut.cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-SAE,PSK,12345678,PMF,Required")
5333        dut.cmd_check("ap_config_commit,NAME,AP")
5334        dev[0].set("sae_groups", "")
5335        dev[0].connect("test-sae", key_mgmt="SAE", psk="12345678",
5336                       ieee80211w="2", scan_freq="2412", wait_connect=False)
5337        ev = dev[0].wait_event(["TRANSITION-DISABLE"], timeout=15)
5338        if ev is not None:
5339            raise Exception("Unexpected transition disable indication")
5340        dev[0].request("DISCONNECT")
5341        dev[0].wait_disconnected()
5342        dev[0].dump_monitor()
5343
5344        dut.cmd_check("ap_set_rfeature,NAME,AP,Transition_Disable,1,Transition_Disable_Index,0")
5345        dev[0].request("RECONNECT")
5346        ev = dev[0].wait_event(["TRANSITION-DISABLE"], timeout=15)
5347        if ev is None:
5348            raise Exception("Transition disable not indicated")
5349        if ev.split(' ')[1] != "01":
5350            raise Exception("Unexpected transition disable bitmap: " + ev)
5351
5352def test_sigma_dut_ft_rsnxe_used_mismatch(dev, apdev):
5353    """sigma_dut controlled FT protocol with RSNXE Used mismatch"""
5354    check_sae_capab(dev[0])
5355
5356    ifname = dev[0].ifname
5357    with SigmaDut(dev=dev[0]) as dut:
5358        ssid = "test-sae"
5359        params = hostapd.wpa2_params(ssid=ssid)
5360        params['wpa_key_mgmt'] = 'SAE FT-SAE'
5361        params["ieee80211w"] = "2"
5362        params['sae_password'] = "hello"
5363        params['sae_pwe'] = "2"
5364        params['mobility_domain'] = 'aabb'
5365        bssid = apdev[0]['bssid'].replace(':', '')
5366        params['nas_identifier'] = bssid + '.nas.example.com'
5367        params['r1_key_holder'] = bssid
5368        params['pmk_r1_push'] = '0'
5369        params['r0kh'] = 'ff:ff:ff:ff:ff:ff * 00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff'
5370        params['r1kh'] = '00:00:00:00:00:00 00:00:00:00:00:00 00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff'
5371        hapd = hostapd.add_ap(apdev[0], params)
5372        bssid = hapd.own_addr()
5373
5374        dut.cmd_check("sta_reset_default,interface,%s" % ifname)
5375        dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
5376        dut.cmd_check("sta_set_security,interface,%s,ssid,%s,passphrase,%s,type,SAE,encpType,aes-ccmp,AKMSuiteType,8;9" % (ifname, "test-sae", "hello"))
5377        dut.cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-sae"),
5378                            timeout=10)
5379        dut.wait_connected()
5380        dev[0].dump_monitor()
5381
5382        bssid2 = apdev[1]['bssid'].replace(':', '')
5383        params['nas_identifier'] = bssid2 + '.nas.example.com'
5384        params['r1_key_holder'] = bssid2
5385        hapd2 = hostapd.add_ap(apdev[1], params)
5386        bssid2 = hapd2.own_addr()
5387
5388        dut.cmd_check("sta_reassoc,interface,%s,Channel,1,bssid,%s" % (ifname, bssid2),
5389                            timeout=20)
5390        count = 0
5391        for i in range(5):
5392            ev = dev[0].wait_event(["Trying to associate",
5393                                    "CTRL-EVENT-CONNECTED"], timeout=10)
5394            if ev is None:
5395                raise Exception("Connection timed out")
5396            if "CTRL-EVENT-CONNECTED" in ev:
5397                break
5398            count += 1
5399        dev[0].dump_monitor()
5400        if count != 1:
5401            raise Exception("Unexpected number of association attempts for the first FT protocol exchange (expecting success)")
5402
5403        dut.cmd_check("sta_set_rfeature,interface,%s,prog,WPA3,ReassocReq_RSNXE_Used,1" % ifname)
5404        dut.cmd_check("sta_reassoc,interface,%s,Channel,1,bssid,%s" % (ifname, bssid))
5405        count = 0
5406        for i in range(5):
5407            ev = dev[0].wait_event(["Trying to associate",
5408                                    "CTRL-EVENT-CONNECTED"], timeout=10)
5409            if ev is None:
5410                raise Exception("Connection timed out")
5411            if "CTRL-EVENT-CONNECTED" in ev:
5412                break
5413            count += 1
5414        dev[0].dump_monitor()
5415        if count != 2:
5416            raise Exception("Unexpected number of association attempts for the second FT protocol exchange (expecting failure)")
5417
5418        dut.cmd_check("sta_disconnect,interface," + ifname)
5419        dut.cmd_check("sta_reset_default,interface," + ifname)
5420
5421def test_sigma_dut_ap_ft_rsnxe_used_mismatch(dev, apdev, params):
5422    """sigma_dut controlled AP with FT and RSNXE Used mismatch"""
5423    logdir = params['prefix'] + ".sigma-hostapd"
5424    conffile = params['prefix'] + ".sigma-conf"
5425    check_sae_capab(dev[0])
5426    with HWSimRadio() as (radio, iface), \
5427         SigmaDut(iface, hostapd_logdir=logdir) as dut:
5428        dut.cmd_check("ap_reset_default")
5429        dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-sae,MODE,11ng,DOMAIN,aabb")
5430        dut.cmd_check("ap_set_security,NAME,AP,AKMSuiteType,8;9,SAEPasswords,hello,PMF,Required")
5431        dut.cmd_check("ap_config_commit,NAME,AP")
5432
5433        with open("/tmp/sigma_dut-ap.conf", "rb") as f, \
5434             open(conffile, "wb") as f2:
5435            f2.write(f.read())
5436
5437        dev[0].set("sae_groups", "")
5438        dev[0].connect("test-sae", key_mgmt="FT-SAE", sae_password="hello",
5439                       ieee80211w="2", scan_freq="2412")
5440
5441        dut.cmd_check("ap_set_rfeature,NAME,AP,type,WPA3,ReassocResp_RSNXE_Used,1")
5442        # This would need to be followed by FT protocol roaming test, but
5443        # that is not currently convenient to implement, so for now, this
5444        # test is based on manual inspection of hostapd getting configured
5445        # properly.
5446
5447        dev[0].request("REMOVE_NETWORK all")
5448        dev[0].wait_disconnected()
5449
5450def test_sigma_dut_ocv(dev, apdev):
5451    """sigma_dut controlled STA using OCV"""
5452    check_sae_capab(dev[0])
5453
5454    ifname = dev[0].ifname
5455    with SigmaDut(dev=dev[0]) as dut:
5456        ssid = "test-sae"
5457        params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
5458        params['wpa_key_mgmt'] = 'SAE'
5459        params["ieee80211w"] = "2"
5460        params['sae_groups'] = '19'
5461        params['ocv'] = '1'
5462        hapd = hostapd.add_ap(apdev[0], params)
5463
5464        dut.cmd_check("sta_reset_default,interface,%s,prog,WPA3" % ifname)
5465        dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
5466        dut.cmd_check("sta_set_wireless,interface,%s,program,WPA3,ocvc,1" % ifname)
5467        dut.cmd_check("sta_set_security,interface,%s,ssid,%s,passphrase,%s,type,SAE,encpType,aes-ccmp,keymgmttype,wpa2" % (ifname, "test-sae", "12345678"))
5468        dut.cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-sae"),
5469                            timeout=10)
5470        dut.wait_connected()
5471
5472        dut.cmd_check("sta_reset_default,interface,%s,prog,WPA3" % ifname)
5473        dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
5474        dut.cmd_check("sta_set_wireless,interface,%s,program,WPA3,ocvc,1" % ifname)
5475        dut.cmd_check("sta_set_rfeature,interface,%s,prog,WPA3,OCIFrameType,eapolM2,OCIChannel,11" % ifname)
5476        dut.cmd_check("sta_set_security,interface,%s,ssid,%s,passphrase,%s,type,SAE,encpType,aes-ccmp,keymgmttype,wpa2" % (ifname, "test-sae", "12345678"))
5477        dut.cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-sae"))
5478        ev = hapd.wait_event(["OCV-FAILURE"], timeout=1)
5479        if ev is None:
5480            raise Exception("OCV failure for EAPOL-Key msg 2/4 not reported")
5481        if "addr=" + dev[0].own_addr() not in ev:
5482            raise Exception("Unexpected OCV failure addr: " + ev)
5483        if "frame=eapol-key-m2" not in ev:
5484            raise Exception("Unexpected OCV failure frame: " + ev)
5485        if "error=primary channel mismatch" not in ev:
5486            raise Exception("Unexpected OCV failure error: " + ev)
5487
5488        dut.cmd_check("sta_reset_default,interface," + ifname)
5489
5490def test_sigma_dut_ap_ocv(dev, apdev, params):
5491    """sigma_dut controlled AP using OCV"""
5492    logdir = params['prefix'] + ".sigma-hostapd"
5493    conffile = params['prefix'] + ".sigma-conf"
5494    check_sae_capab(dev[0])
5495    with HWSimRadio() as (radio, iface), \
5496         SigmaDut(iface, hostapd_logdir=logdir) as dut:
5497        dut.cmd_check("ap_reset_default")
5498        dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-sae,MODE,11ng")
5499        dut.cmd_check("ap_set_wireless,NAME,AP,ocvc,1")
5500        dut.cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-SAE,PSK,12345678")
5501        dut.cmd_check("ap_config_commit,NAME,AP")
5502        bssid = dut.cmd_check("ap_get_mac_address,NAME,AP")
5503        bssid = bssid.split(',')[3]
5504
5505        with open("/tmp/sigma_dut-ap.conf", "rb") as f, \
5506             open(conffile, "wb") as f2:
5507            f2.write(f.read())
5508
5509        dev[0].set("sae_groups", "")
5510        dev[0].connect("test-sae", key_mgmt="SAE", psk="12345678",
5511                       ieee80211w="2", ocv="1", scan_freq="2412")
5512        dev[0].request("REMOVE_NETWORK all")
5513        dev[0].wait_disconnected()
5514        dev[0].dump_monitor()
5515
5516        dut.cmd_check("ap_set_rfeature,NAME,AP,type,WPA3,OCIFrameType,eapolM3,OCIChannel,3")
5517        dev[0].connect("test-sae", key_mgmt="SAE", psk="12345678",
5518                       ieee80211w="2", ocv="1", scan_freq="2412",
5519                       wait_connect=False)
5520        check_ocv_failure(dev[0], "EAPOL-Key msg 3/4", "eapol-key-m3", bssid)
5521        dev[0].request("REMOVE_NETWORK all")
5522        dev[0].wait_disconnected()
5523        dev[0].dump_monitor()
5524
5525def test_sigma_dut_gtk_rekey(dev, apdev):
5526    """sigma_dut controlled STA requesting GTK rekeying"""
5527    check_sae_capab(dev[0])
5528
5529    ifname = dev[0].ifname
5530    with SigmaDut(dev=dev[0]) as dut:
5531        ssid = "test-sae"
5532        params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
5533        params['wpa_key_mgmt'] = 'SAE'
5534        params["ieee80211w"] = "2"
5535        params['sae_groups'] = '19'
5536        hapd = hostapd.add_ap(apdev[0], params)
5537
5538        dut.cmd_check("sta_reset_default,interface,%s,prog,WPA3" % ifname)
5539        dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
5540        dut.cmd_check("sta_set_wireless,interface,%s,program,WPA3,ocvc,1" % ifname)
5541        dut.cmd_check("sta_set_security,interface,%s,ssid,%s,passphrase,%s,type,SAE,encpType,aes-ccmp,keymgmttype,wpa2" % (ifname, "test-sae", "12345678"))
5542        dut.cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-sae"),
5543                            timeout=10)
5544        dut.wait_connected()
5545
5546        dev[0].dump_monitor()
5547        dut.cmd_check("dev_exec_action,interface,%s,program,WPA3,KeyRotation,1" % ifname)
5548        ev = dev[0].wait_event(["RSN: Group rekeying completed"], timeout=5)
5549        if ev is None:
5550            raise Exception("GTK rekeying not seen")
5551
5552        dut.cmd_check("sta_reset_default,interface," + ifname)
5553
5554def test_sigma_dut_ap_gtk_rekey(dev, apdev, params):
5555    """sigma_dut controlled AP and requested GTK rekeying"""
5556    logdir = params['prefix'] + ".sigma-hostapd"
5557    check_sae_capab(dev[0])
5558    with HWSimRadio() as (radio, iface), \
5559         SigmaDut(iface, hostapd_logdir=logdir) as dut:
5560        dut.cmd_check("ap_reset_default")
5561        dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-sae,MODE,11ng")
5562        dut.cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-SAE,PSK,12345678")
5563        dut.cmd_check("ap_config_commit,NAME,AP")
5564
5565        dev[0].set("sae_groups", "")
5566        dev[0].connect("test-sae", key_mgmt="SAE", psk="12345678",
5567                       ieee80211w="2", scan_freq="2412")
5568        dev[0].dump_monitor()
5569
5570        dut.cmd_check("dev_exec_action,name,AP,interface,%s,program,WPA3,KeyRotation,1" % iface)
5571
5572        ev = dev[0].wait_event(["RSN: Group rekeying completed"], timeout=5)
5573        if ev is None:
5574            raise Exception("GTK rekeying not seen")
5575
5576def test_sigma_dut_sae_pk(dev, apdev):
5577    """sigma_dut controlled STA using SAE-PK"""
5578    check_sae_pk_capab(dev[0])
5579
5580    ifname = dev[0].ifname
5581    ssid = "SAE-PK test"
5582    pw = "hbbi-f4xq-b45g"
5583    m = "d2e5fa27d1be8897f987f2d480d2af6b"
5584    pk = "MHcCAQEEIAJIGlfnteonDb7rQyP/SGQjwzrZAnfrXIm4280VWajYoAoGCCqGSM49AwEHoUQDQgAEeRkstKQV+FSAMqBayqFknn2nAQsdsh/MhdX6tiHOTAFin/sUMFRMyspPtIu7YvlKdsexhI0jPVhaYZn1jKWhZg=="
5585
5586    with SigmaDut(dev=dev[0]) as dut:
5587        params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
5588        params['wpa_key_mgmt'] = 'SAE'
5589        params["ieee80211w"] = "2"
5590        params['sae_groups'] = '19'
5591        params['sae_password'] = ['%s|pk=%s:%s' % (pw, m, pk)]
5592        hapd = hostapd.add_ap(apdev[0], params)
5593
5594        dut.cmd_check("sta_reset_default,interface,%s,prog,WPA3" % ifname)
5595        dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
5596        dut.cmd_check("sta_set_wireless,interface,%s,program,WPA3" % ifname)
5597        dut.cmd_check("sta_set_security,interface,%s,ssid,%s,passphrase,%s,type,SAE,encpType,aes-ccmp,keymgmttype,wpa2,sae_pk,1" % (ifname, ssid, pw))
5598        dut.cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, ssid),
5599                      timeout=10)
5600        dut.wait_connected()
5601        dev[0].dump_monitor()
5602
5603        dut.cmd_check("sta_reset_default,interface," + ifname)
5604
5605def run_sigma_dut_ap_sae_pk(dut, conffile, dev, ssid, pw, keypair, m, failure,
5606                            status=None, omit=False, immediate=False, sig=None):
5607    dut.cmd_check("ap_reset_default")
5608    dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,%s,MODE,11ng" % ssid)
5609    cmd = "ap_set_security,NAME,AP,AKMSuiteType,8,PairwiseCipher,AES-CCMP-128,GroupCipher,AES-CCMP-128,GroupMgntCipher,BIP-CMAC-128,PMF,Required,PSK,%s,sae_pk,1,Transition_Disable,1,Transition_Disable_Index,0,SAE_PK_KeyPair,%s,SAE_PK_Modifier,%s" % (pw, keypair, m)
5610    if status is not None:
5611        cmd += ",SAE_Commit_StatusCode,%d" % status
5612    if omit:
5613        cmd += ",SAE_PK_Omit,1"
5614    if immediate:
5615        cmd += ",SAE_Confirm_Immediate,1"
5616    if sig:
5617        cmd += ",SAE_PK_KeyPairSigOverride," + sig
5618    dut.cmd_check(cmd)
5619    dut.cmd_check("ap_config_commit,NAME,AP")
5620    bssid = dut.cmd_check("ap_get_mac_address,NAME,AP")
5621    bssid = bssid.split(',')[3]
5622
5623    with open("/tmp/sigma_dut-ap.conf", "rb") as f:
5624        with open(conffile, "ab") as f2:
5625            f2.write(f.read())
5626            f2.write('\n'.encode())
5627
5628    dev.set("sae_groups", "")
5629    dev.connect(ssid, key_mgmt="SAE", sae_password=pw, ieee80211w="2",
5630                scan_freq="2412", wait_connect=False)
5631
5632    ev = dev.wait_event(["CTRL-EVENT-CONNECTED",
5633                         "CTRL-EVENT-SSID-TEMP-DISABLED"], timeout=15)
5634    if ev is None:
5635        raise Exception("No connection result reported")
5636
5637    bss = dev.get_bss(bssid)
5638    if 'flags' not in bss:
5639        raise Exception("Could not get BSS flags from BSS table")
5640    if "[SAE-H2E]" not in bss['flags'] or "[SAE-PK]" not in bss['flags']:
5641        raise Exception("Unexpected BSS flags: " + bss['flags'])
5642
5643    if failure:
5644        if "CTRL-EVENT-CONNECTED" in ev:
5645            raise Exception("Unexpected connection")
5646        dev.request("REMOVE_NETWORK all")
5647    else:
5648        if "CTRL-EVENT-CONNECTED" not in ev:
5649            raise Exception("Connection failed")
5650        dev.request("REMOVE_NETWORK all")
5651        dev.wait_disconnected()
5652    dev.dump_monitor()
5653
5654def test_sigma_dut_ap_sae_pk(dev, apdev, params):
5655    """sigma_dut controlled AP using SAE-PK"""
5656    logdir = params['prefix'] + ".sigma-hostapd"
5657    conffile = params['prefix'] + ".sigma-conf"
5658    check_sae_pk_capab(dev[0])
5659    tests = [("SAEPK-4.7.1.1", "ya3o-zvm2-r4so", "saepk1.pem",
5660              "faa1ef5094bdb4cb2836332ca2c09839", False),
5661             ("SAEPK-4.7.1.2", "xcc2-qwru-yg23", "saepk1.pem",
5662              "b1b30107eb74de2f25afd079bb4196c1", False),
5663             ("SAEPK-4.7.1.3", "skqz-6scq-zcqv", "saepk1.pem",
5664              "4c0ff61465e0f298510254ff54916c71", False),
5665             ("SAEPK-4.7.1.4", "r6em-rya4-tqfa", "saepkP384.pem",
5666              "fb811655209e9edf347a675ddd3e9c82", False),
5667             ("SAEPK-4.7.1.5", "6kjo-umvi-7x3w", "saepkP521.pem",
5668              "cccb76bc0f113ab754826ba9538d66f5", False),
5669             ("SAEPK-5.7.1.1", "sw4h-re63-wgqg", "saepk1.pem",
5670              "0d126f302d85ac809a6a4229dbbe3c75", False),
5671             ("SAEPK-5.7.1.2", "wewq-r4kg-4ioz-xb2p", "saepk1.pem",
5672              "d6b1d8924b1a462677e67b3bbfe73977", False),
5673             ("SAEPK-5.7.1.3", "vb3v-5skk-5eft-v4hu-w2c5", "saepk1.pem",
5674              "41f8cfceb96ebc5c8af9677d22749fad", False),
5675             ("SAEPK-5.7.1.4", "2qsw-6tgy-xnwa-s7lo-75tq-qggr", "saepk1.pem",
5676              "089e8d4a3a79ec637c54dd7bd61972f2", False),
5677             ("SAE-PK test", "hbbi-f4xq-b45g", "saepkP256.pem",
5678              "d2e5fa27d1be8897f987f2d480d2af6b", False),
5679             ("SAE-PK test", "hbbi-f4xq-b457-jje4", "saepkP256.pem",
5680              "d2e5fa27d1be8897f987f2d480d2af6b", False),
5681             ("SAE-PK test", "hbbi-f4xq-b457-jjew-muei", "saepkP256.pem",
5682              "d2e5fa27d1be8897f987f2d480d2af6b", False),
5683             ("SAE-PK test", "hbbi-f4xq-b457-jjew-muey-fod3", "saepkP256.pem",
5684              "d2e5fa27d1be8897f987f2d480d2af6b", False),
5685             ("SAEPK-5.7.1.1", "sw4h-re63-wgqg", "saepk1.pem",
5686              "0d126f302d85ac809a6a4229dbbe3c75", False),
5687             ("SAEPK-5.7.1.10", "tkor-7nb3-r7tv", "saepkP384.pem",
5688              "af1a3df913fc0103f65f105ed1472277", False),
5689             ("SAEPK-5.7.1.11", "yjl3-vfvu-w6r3", "saepkP521.pem",
5690              "24dadf9d253c4169c9647a21cb54fc57", False),
5691             ("SAEPK-5.7.2.1", "rntm-tkrp-xgke", "saepk1.pem",
5692              "cd38ccce3baff627d09bee7b9530d6ce", False),
5693             ("SAEPK-5.7.2.2", "7lt7-7dqt-6abk", "saepk1.pem",
5694              "a22fc8489932597c9e83de62dec02b21", False),
5695             ("SAEPK-5.7.2.3", "sw4h-re63-wgqg", "saepk2.pem",
5696              "1f4a4c7d290d97e0b6ab0cbbbfa0726d", True),
5697             ("SAEPK-5.7.2.4", "rmj3-ya7b-42k4", "saepk1.pem",
5698              "5f65e2bc37f8494de7a605ff615c8b6a", False),
5699             ("SAEPK-5.7.2.4", "rmj3-ya7b-42k4", "saepk2.pem",
5700              "5f65e2bc37f8494de7a605ff615c8b6a", True),
5701             ("SAEPK-5.7.3", "4322-ufus-4bhm", "saepk1.pem",
5702              "21ede99abc46679646693cafe4677d4e", False)]
5703
5704    with HWSimRadio() as (radio, iface), \
5705         SigmaDut(iface, hostapd_logdir=logdir) as dut:
5706        for ssid, pw, keypair, m, failure in tests:
5707            run_sigma_dut_ap_sae_pk(dut, conffile, dev[0], ssid, pw, keypair, m,
5708                                    failure)
5709
5710def test_sigma_dut_ap_sae_pk_misbehavior(dev, apdev, params):
5711    """sigma_dut controlled AP using SAE-PK misbehavior"""
5712    logdir = params['prefix'] + ".sigma-hostapd"
5713    conffile = params['prefix'] + ".sigma-conf"
5714    check_sae_pk_capab(dev[0])
5715    ssid = "SAEPK-4.7.1.1"
5716    pw = "rmj3-ya7b-42k4"
5717    keypair = "saepk1.pem"
5718    m = "faa1ef5094bdb4cb2836332ca2c09839"
5719
5720    with HWSimRadio() as (radio, iface), \
5721         SigmaDut(iface, hostapd_logdir=logdir) as dut:
5722        run_sigma_dut_ap_sae_pk(dut, conffile, dev[0], ssid, pw, keypair, m,
5723                                True, status=126)
5724        run_sigma_dut_ap_sae_pk(dut, conffile, dev[0], ssid, pw, keypair, m,
5725                                True, omit=True)
5726        run_sigma_dut_ap_sae_pk(dut, conffile, dev[0], ssid, pw, keypair, m,
5727                                True, status=126, omit=True, immediate=True)
5728        run_sigma_dut_ap_sae_pk(dut, conffile, dev[0], ssid, pw, keypair, m,
5729                                True, sig="saepk2.pem")
5730
5731def run_sigma_dut_ap_sae_pk_mixed(dut, conffile, dev, ssid, pw, keypair, m,
5732                                  failure):
5733    dut.cmd_check("ap_reset_default")
5734    dut.cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,%s,MODE,11ng" % ssid)
5735    cmd = "ap_set_security,NAME,AP,AKMSuiteType,2;8,PairwiseCipher,AES-CCMP-128,GroupCipher,AES-CCMP-128,GroupMgntCipher,BIP-CMAC-128,PMF,Required,PSK,%s,sae_pk,0,Transition_Disable,0" % (pw)
5736    dut.cmd_check(cmd)
5737    dut.cmd_check("ap_config_commit,NAME,AP")
5738    bssid = dut.cmd_check("ap_get_mac_address,NAME,AP")
5739    bssid = bssid.split(',')[3]
5740
5741    with open("/tmp/sigma_dut-ap.conf", "rb") as f:
5742        with open(conffile, "ab") as f2:
5743            f2.write(f.read())
5744            f2.write('\n'.encode())
5745
5746    dut.cmd_check("ap_set_rfeature,NAME,AP,type,WPA3,Transition_Disable,1,Transition_Disable_Index,0")
5747
5748    dev[0].set("sae_groups", "")
5749    dev[0].connect(ssid, key_mgmt="SAE", sae_password=pw, ieee80211w="2",
5750                   scan_freq="2412")
5751    dev[1].connect(ssid, key_mgmt="WPA-PSK", psk=pw, ieee80211w="2",
5752                   scan_freq="2412")
5753
5754def test_sigma_dut_ap_sae_pk_mixed(dev, apdev, params):
5755    """sigma_dut controlled AP using SAE-PK(disabled) and PSK"""
5756    logdir = params['prefix'] + ".sigma-hostapd"
5757    conffile = params['prefix'] + ".sigma-conf"
5758    check_sae_capab(dev[0])
5759    ssid = "SAEPK-5.7.3"
5760    pw = "4322-ufus-4bhm"
5761    keypair = "saepk1.pem"
5762    m = "21ede99abc46679646693cafe4677d4e"
5763
5764    with HWSimRadio() as (radio, iface), \
5765         SigmaDut(iface, hostapd_logdir=logdir) as dut:
5766        run_sigma_dut_ap_sae_pk_mixed(dut, conffile, dev, ssid, pw, keypair,
5767                                      m, False)
5768
5769def test_sigma_dut_client_privacy(dev, apdev, params):
5770    """sigma_dut client privacy"""
5771    logdir = params['logdir']
5772
5773    ssid = "test"
5774    params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
5775    hapd = hostapd.add_ap(apdev[0], params)
5776
5777    ifname = dev[0].ifname
5778    addr = dev[0].own_addr()
5779    try:
5780        with SigmaDut(dev=dev[0]) as dut:
5781            dut.cmd_check("sta_reset_default,interface,%s,prog,WPA3" % ifname)
5782            dut.cmd_check("sta_set_wireless,interface,%s,program,WPA3,ClientPrivacy,1" % ifname)
5783            cmd = "sta_scan,Interface,%s,ChnlFreq,2412,WaitCompletion,1" % dev[0].ifname
5784            dut.cmd_check(cmd, timeout=10)
5785            time.sleep(2)
5786            dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
5787            dut.cmd_check("sta_set_psk,interface,%s,ssid,%s,passphrase,%s,encpType,aes-ccmp,keymgmttype,wpa2" % (ifname, ssid, "12345678"))
5788            dut.cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, ssid),
5789                          timeout=10)
5790            dut.wait_connected()
5791            dut.cmd_check("sta_get_ip_config,interface," + ifname)
5792            dut.cmd_check("sta_disconnect,interface," + ifname)
5793            dut.cmd_check("sta_reset_default,interface," + ifname)
5794    finally:
5795        dev[0].set("mac_addr", "0", allow_fail=True)
5796        dev[0].set("rand_addr_lifetime", "60", allow_fail=True)
5797        dev[0].request("MAC_RAND_SCAN enable=0 all")
5798        dev[0].set("preassoc_mac_addr", "0", allow_fail=True)
5799        dev[0].set("gas_rand_mac_addr", "0", allow_fail=True)
5800        dev[0].set("gas_rand_addr_lifetime", "60", allow_fail=True)
5801
5802    out = run_tshark(os.path.join(logdir, "hwsim0.pcapng"),
5803                     "wlan.addr == " + addr,
5804                     display=["wlan.ta"])
5805    res = out.splitlines()
5806    if len(res) > 0:
5807        raise Exception("Permanent address used unexpectedly")
5808
5809def test_sigma_dut_wpa3_inject_frame(dev, apdev):
5810    """sigma_dut and WPA3 frame inject"""
5811    check_sae_capab(dev[0])
5812
5813    ifname = dev[0].ifname
5814    with SigmaDut(dev=dev[0]) as dut:
5815        ssid = "test-sae"
5816        params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
5817        params['wpa_key_mgmt'] = 'SAE'
5818        params["ieee80211w"] = "2"
5819        params["ocv"] = "1"
5820        params['sae_groups'] = '19 20 21'
5821        hapd = hostapd.add_ap(apdev[0], params)
5822
5823        dut.cmd_check("sta_reset_default,interface,%s,prog,WPA3" % ifname)
5824        dut.cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
5825        dut.cmd_check("sta_set_wireless,interface,%s,program,WPA3,ocvc,1" % ifname)
5826        dut.cmd_check("sta_set_security,interface,%s,ssid,%s,passphrase,%s,type,SAE,encpType,aes-ccmp,keymgmttype,wpa2" % (ifname, "test-sae", "12345678"))
5827        dut.cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-sae"),
5828                      timeout=10)
5829        dut.wait_connected()
5830        dut.run_cmd("dev_send_frame,interface,%s,program,WPA3,framename,SAQueryReq,OCIChannel,2" % ifname)
5831        dut.run_cmd("dev_send_frame,interface,%s,program,WPA3,framename,SAQueryReq,OCIChannel,1" % ifname)
5832        dut.run_cmd("dev_send_frame,interface,%s,program,WPA3,framename,ReassocReq" % ifname)
5833        hwsim_utils.test_connectivity(dev[0], hapd)
5834        dut.cmd_check("sta_reset_default,interface," + ifname)
5835