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