1# wpa_supplicant mesh mode tests
2# Copyright (c) 2014, cozybit Inc.
3#
4# This software may be distributed under the terms of the BSD license.
5# See README for more details.
6
7import logging
8logger = logging.getLogger()
9import os
10import struct
11import subprocess
12import time
13import json
14import binascii
15
16import hwsim_utils
17import hostapd
18from wpasupplicant import WpaSupplicant
19from utils import *
20from tshark import run_tshark, run_tshark_json
21from test_sae import build_sae_commit, sae_rx_commit_token_req
22from hwsim_utils import set_group_map
23
24def check_mesh_support(dev, secure=False):
25    if "MESH" not in dev.get_capability("modes"):
26        raise HwsimSkip("Driver does not support mesh")
27    if secure:
28        check_sae_capab(dev)
29
30def check_mesh_scan(dev, params, other_started=False, beacon_int=0):
31    if not other_started:
32        dev.dump_monitor()
33    id = dev.request("SCAN " + params)
34    if "FAIL" in id:
35        raise Exception("Failed to start scan")
36    id = int(id)
37
38    if other_started:
39        ev = dev.wait_event(["CTRL-EVENT-SCAN-STARTED"])
40        if ev is None:
41            raise Exception("Other scan did not start")
42        if "id=" + str(id) in ev:
43            raise Exception("Own scan id unexpectedly included in start event")
44
45        ev = dev.wait_event(["CTRL-EVENT-SCAN-RESULTS"])
46        if ev is None:
47            raise Exception("Other scan did not complete")
48        if "id=" + str(id) in ev:
49            raise Exception(
50                "Own scan id unexpectedly included in completed event")
51
52    ev = dev.wait_event(["CTRL-EVENT-SCAN-STARTED"])
53    if ev is None:
54        raise Exception("Scan did not start")
55    if "id=" + str(id) not in ev:
56        raise Exception("Scan id not included in start event")
57
58    ev = dev.wait_event(["CTRL-EVENT-SCAN-RESULTS"])
59    if ev is None:
60        raise Exception("Scan did not complete")
61    if "id=" + str(id) not in ev:
62        raise Exception("Scan id not included in completed event")
63
64    res = dev.request("SCAN_RESULTS")
65
66    if res.find("[MESH]") < 0:
67        raise Exception("Scan did not contain a MESH network")
68
69    bssid = res.splitlines()[1].split(' ')[0]
70    bss = dev.get_bss(bssid)
71    if bss is None:
72        raise Exception("Could not get BSS entry for mesh")
73    if 'mesh_id' not in bss:
74        raise Exception("mesh_id missing from BSS entry")
75    if bss['mesh_id'] != "wpas-mesh-open":
76        raise Exception("Incorrect mesh_id: " + bss['mesh_id'])
77    if 'mesh_capability' not in bss:
78        raise Exception("mesh_capability missing from BSS entry")
79    if beacon_int:
80        if 'beacon_int' not in bss:
81            raise Exception("beacon_int missing from BSS entry")
82        if str(beacon_int) != bss['beacon_int']:
83            raise Exception("Unexpected beacon_int in BSS entry: " + bss['beacon_int'])
84    if '[MESH]' not in bss['flags']:
85        raise Exception("BSS output did not include MESH flag")
86
87def check_dfs_started(dev, timeout=10):
88    ev = dev.wait_event(["DFS-CAC-START"], timeout=timeout)
89    if ev is None:
90        raise Exception("Test exception: CAC did not start")
91
92def check_dfs_finished(dev, timeout=70):
93    ev = dev.wait_event(["DFS-CAC-COMPLETED"], timeout=timeout)
94    if ev is None:
95        raise Exception("Test exception: CAC did not finish")
96
97def check_mesh_radar_handling_finished(dev, timeout=75):
98    ev = dev.wait_event(["CTRL-EVENT-CHANNEL-SWITCH", "MESH-GROUP-STARTED"],
99                        timeout=timeout)
100    if ev is None:
101        raise Exception("Test exception: Couldn't join mesh")
102
103def check_mesh_group_added(dev, timeout=10):
104    ev = dev.wait_event(["MESH-GROUP-STARTED"], timeout=timeout)
105    if ev is None:
106        raise Exception("Test exception: Couldn't join mesh")
107
108
109def check_mesh_group_removed(dev):
110    ev = dev.wait_event(["MESH-GROUP-REMOVED"])
111    if ev is None:
112        raise Exception("Test exception: Couldn't leave mesh")
113
114def check_regdom_change(dev, timeout=10):
115    ev = dev.wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=timeout)
116    if ev is None:
117        raise Exception("Test exception: No regdom change happened.")
118
119def check_mesh_peer_connected(dev, timeout=10):
120    ev = dev.wait_event(["MESH-PEER-CONNECTED"], timeout=timeout)
121    if ev is None:
122        raise Exception("Test exception: Remote peer did not connect.")
123
124
125def check_mesh_peer_disconnected(dev):
126    ev = dev.wait_event(["MESH-PEER-DISCONNECTED"])
127    if ev is None:
128        raise Exception("Test exception: Peer disconnect event not detected.")
129
130def check_mesh_joined2(dev):
131    check_mesh_group_added(dev[0])
132    check_mesh_group_added(dev[1])
133
134def check_mesh_connected2(dev, timeout0=10, connectivity=False):
135    check_mesh_peer_connected(dev[0], timeout=timeout0)
136    check_mesh_peer_connected(dev[1])
137    if connectivity:
138        hwsim_utils.test_connectivity(dev[0], dev[1])
139
140def check_mesh_joined_connected(dev, connectivity=False, timeout0=10):
141    check_mesh_joined2(dev)
142    check_mesh_connected2(dev, timeout0=timeout0, connectivity=connectivity)
143
144def test_wpas_add_set_remove_support(dev):
145    """wpa_supplicant MESH add/set/remove network support"""
146    check_mesh_support(dev[0])
147    id = dev[0].add_network()
148    dev[0].set_network(id, "mode", "5")
149    dev[0].remove_network(id)
150
151def add_open_mesh_network(dev, freq="2412", start=True, beacon_int=0,
152                          basic_rates=None, chwidth=-1, disable_vht=False,
153                          disable_ht40=False):
154    id = dev.add_network()
155    dev.set_network(id, "mode", "5")
156    dev.set_network_quoted(id, "ssid", "wpas-mesh-open")
157    dev.set_network(id, "key_mgmt", "NONE")
158    if freq:
159        dev.set_network(id, "frequency", freq)
160    if chwidth > -1:
161        dev.set_network(id, "max_oper_chwidth", str(chwidth))
162    if beacon_int:
163        dev.set_network(id, "beacon_int", str(beacon_int))
164    if basic_rates:
165        dev.set_network(id, "mesh_basic_rates", basic_rates)
166    if disable_vht:
167        dev.set_network(id, "disable_vht", "1")
168    if disable_ht40:
169        dev.set_network(id, "disable_ht40", "1")
170    if start:
171        dev.mesh_group_add(id)
172    return id
173
174def test_wpas_mesh_group_added(dev):
175    """wpa_supplicant MESH group add"""
176    check_mesh_support(dev[0])
177    add_open_mesh_network(dev[0])
178
179    # Check for MESH-GROUP-STARTED event
180    check_mesh_group_added(dev[0])
181
182
183def test_wpas_mesh_group_remove(dev):
184    """wpa_supplicant MESH group remove"""
185    check_mesh_support(dev[0])
186    add_open_mesh_network(dev[0])
187    # Check for MESH-GROUP-STARTED event
188    check_mesh_group_added(dev[0])
189    dev[0].mesh_group_remove()
190    # Check for MESH-GROUP-REMOVED event
191    check_mesh_group_removed(dev[0])
192    dev[0].mesh_group_remove()
193
194def dfs_simulate_radar(dev):
195    logger.info("Trigger a simulated radar event")
196    phyname = dev.get_driver_status_field("phyname")
197    radar_file = '/sys/kernel/debug/ieee80211/' + phyname + '/hwsim/dfs_simulate_radar'
198    with open(radar_file, 'w') as f:
199        f.write('1')
200
201@long_duration_test
202def test_mesh_peer_connected_dfs(dev):
203    """Mesh peer connected (DFS)"""
204    dev[0].set("country", "DE")
205    dev[1].set("country", "DE")
206
207    check_regdom_change(dev[0])
208    check_regdom_change(dev[1])
209
210    check_mesh_support(dev[0])
211    add_open_mesh_network(dev[0], freq="5500", beacon_int=160)
212    add_open_mesh_network(dev[1], freq="5500", beacon_int=160)
213    check_dfs_started(dev[0])
214    check_dfs_finished(dev[0])
215    check_mesh_joined_connected(dev, timeout0=10)
216
217    dfs_simulate_radar(dev[0])
218
219    check_mesh_radar_handling_finished(dev[0], timeout=75)
220
221    dev[0].set("country", "00")
222    dev[1].set("country", "00")
223
224    check_regdom_change(dev[0])
225    check_regdom_change(dev[1])
226
227def test_wpas_mesh_peer_connected(dev):
228    """wpa_supplicant MESH peer connected"""
229    check_mesh_support(dev[0])
230    add_open_mesh_network(dev[0], beacon_int=160)
231    add_open_mesh_network(dev[1], beacon_int=160)
232    check_mesh_joined_connected(dev)
233
234def test_wpas_mesh_peer_disconnected(dev):
235    """wpa_supplicant MESH peer disconnected"""
236    check_mesh_support(dev[0])
237    add_open_mesh_network(dev[0])
238    add_open_mesh_network(dev[1])
239    check_mesh_joined_connected(dev)
240
241    # Remove group on dev 1
242    dev[1].mesh_group_remove()
243    # Device 0 should get a disconnection event
244    check_mesh_peer_disconnected(dev[0])
245
246
247def test_wpas_mesh_mode_scan(dev):
248    """wpa_supplicant MESH scan support"""
249    check_mesh_support(dev[0])
250    dev[0].flush_scan_cache()
251    add_open_mesh_network(dev[0])
252    add_open_mesh_network(dev[1], beacon_int=175)
253
254    check_mesh_joined2(dev)
255
256    # Check for Mesh scan
257    check_mesh_scan(dev[0], "use_id=1 freq=2412", beacon_int=175)
258
259def test_wpas_mesh_open(dev, apdev):
260    """wpa_supplicant open MESH network connectivity"""
261    check_mesh_support(dev[0])
262    add_open_mesh_network(dev[0], freq="2462", basic_rates="60 120 240")
263    add_open_mesh_network(dev[1], freq="2462", basic_rates="60 120 240")
264
265    check_mesh_joined_connected(dev, connectivity=True)
266
267    state = dev[0].get_status_field("wpa_state")
268    if state != "COMPLETED":
269        raise Exception("Unexpected wpa_state on dev0: " + state)
270    state = dev[1].get_status_field("wpa_state")
271    if state != "COMPLETED":
272        raise Exception("Unexpected wpa_state on dev1: " + state)
273
274    mode = dev[0].get_status_field("mode")
275    if mode != "mesh":
276        raise Exception("Unexpected mode: " + mode)
277
278    peer = dev[1].own_addr()
279    sta1 = dev[0].get_sta(peer)
280
281    dev[0].scan(freq="2462")
282    bss = dev[0].get_bss(dev[1].own_addr())
283    if bss and 'ie' in bss and "ff0724" in bss['ie']:
284        sta = dev[0].request("STA " + dev[1].own_addr())
285        logger.info("STA info:\n" + sta.rstrip())
286        if "[HE]" not in sta:
287            raise Exception("Missing STA HE flag")
288        if "[VHT]" in sta:
289            raise Exception("Unexpected STA VHT flag")
290
291    time.sleep(1.1)
292    sta2 = dev[0].get_sta(peer)
293    if 'connected_time' not in sta1 or 'connected_time' not in sta2:
294        raise Exception("connected_time not reported for peer")
295    ct1 = int(sta1['connected_time'])
296    ct2 = int(sta2['connected_time'])
297    if ct2 <= ct1:
298        raise Exception("connected_time did not increment")
299
300def test_wpas_mesh_open_no_auto(dev, apdev):
301    """wpa_supplicant open MESH network connectivity"""
302    check_mesh_support(dev[0])
303    id = add_open_mesh_network(dev[0], start=False)
304    dev[0].set_network(id, "dot11MeshMaxRetries", "16")
305    dev[0].set_network(id, "dot11MeshRetryTimeout", "255")
306    dev[0].mesh_group_add(id)
307
308    id = add_open_mesh_network(dev[1], start=False)
309    dev[1].set_network(id, "no_auto_peer", "1")
310    dev[1].mesh_group_add(id)
311
312    check_mesh_joined_connected(dev, connectivity=True, timeout0=30)
313
314def test_mesh_open_no_auto2(dev, apdev):
315    """Open mesh network connectivity, no_auto on both peers"""
316    check_mesh_support(dev[0])
317    id = add_open_mesh_network(dev[0], start=False)
318    dev[0].set_network(id, "no_auto_peer", "1")
319    dev[0].mesh_group_add(id)
320
321    id = add_open_mesh_network(dev[1], start=False)
322    dev[1].set_network(id, "no_auto_peer", "1")
323    dev[1].mesh_group_add(id)
324
325    check_mesh_joined2(dev)
326
327    ev = dev[0].wait_event(["will not initiate new peer link"], timeout=10)
328    if ev is None:
329        raise Exception("Missing no-initiate message")
330    addr1 = dev[1].own_addr()
331    if "OK" not in dev[0].request("MESH_PEER_ADD " + addr1):
332        raise Exception("MESH_PEER_ADD failed")
333    if "FAIL" not in dev[0].request("MESH_PEER_ADD ff:ff:ff:ff:ff:ff"):
334        raise Exception("MESH_PEER_ADD with unknown STA succeeded")
335    check_mesh_connected2(dev, timeout0=30)
336    if "FAIL" not in dev[0].request("MESH_PEER_ADD " + addr1):
337        raise Exception("MESH_PEER_ADD succeeded for connected STA")
338    hwsim_utils.test_connectivity(dev[0], dev[1])
339
340def test_mesh_open_rssi_threshold(dev, apdev):
341    """Open mesh network with RSSI threshold"""
342    check_mesh_support(dev[0])
343
344    _test_mesh_open_rssi_threshold(dev, apdev, -255, -255)
345    _test_mesh_open_rssi_threshold(dev, apdev, 0, 0)
346    _test_mesh_open_rssi_threshold(dev, apdev, 1, 0)
347
348def _test_mesh_open_rssi_threshold(dev, apdev, value, expected):
349    id = add_open_mesh_network(dev[0], start=False)
350    dev[0].set_network(id, "mesh_rssi_threshold", str(value))
351    dev[0].mesh_group_add(id)
352    check_mesh_group_added(dev[0])
353
354    cmd = subprocess.Popen(["iw", "dev", dev[0].ifname, "get", "mesh_param",
355                            "mesh_rssi_threshold"], stdout=subprocess.PIPE)
356    out, err = cmd.communicate()
357    mesh_rssi_threshold = int(out.decode().split(" ")[0])
358
359    dev[0].mesh_group_remove()
360    check_mesh_group_removed(dev[0])
361
362    if mesh_rssi_threshold != expected:
363        raise Exception("mesh_rssi_threshold should be " + str(expected) +
364                        ": " + str(mesh_rssi_threshold))
365
366def add_mesh_secure_net(dev, psk=True, pmf=False, pairwise=None, group=None,
367                        group_mgmt=None,
368                        sae_password=False, sae_password_id=None, ocv=False):
369    id = dev.add_network()
370    dev.set_network(id, "mode", "5")
371    dev.set_network_quoted(id, "ssid", "wpas-mesh-sec")
372    dev.set_network(id, "key_mgmt", "SAE")
373    dev.set_network(id, "frequency", "2412")
374    if sae_password:
375        dev.set_network_quoted(id, "sae_password", "thisismypassphrase!")
376    if sae_password_id:
377        dev.set_network_quoted(id, "sae_password_id", sae_password_id)
378    if psk:
379        dev.set_network_quoted(id, "psk", "thisismypassphrase!")
380    if pmf:
381        dev.set_network(id, "ieee80211w", "2")
382    if pairwise:
383        dev.set_network(id, "pairwise", pairwise)
384    if group:
385        dev.set_network(id, "group", group)
386    if group_mgmt:
387        dev.set_network(id, "group_mgmt", group_mgmt)
388    if ocv:
389        try:
390            dev.set_network(id, "ocv", "1")
391        except Exception as e:
392            if "SET_NETWORK failed" in str(e):
393                raise HwsimSkip("OCV not supported")
394            raise
395    return id
396
397def test_wpas_mesh_secure(dev, apdev):
398    """wpa_supplicant secure MESH network connectivity"""
399    check_mesh_support(dev[0], secure=True)
400    dev[0].request("SET sae_groups ")
401    id = add_mesh_secure_net(dev[0])
402    dev[0].mesh_group_add(id)
403
404    dev[1].request("SET sae_groups ")
405    id = add_mesh_secure_net(dev[1])
406    dev[1].mesh_group_add(id)
407
408    check_mesh_joined_connected(dev, connectivity=True)
409
410    state = dev[0].get_status_field("wpa_state")
411    if state != "COMPLETED":
412        raise Exception("Unexpected wpa_state on dev0: " + state)
413    state = dev[1].get_status_field("wpa_state")
414    if state != "COMPLETED":
415        raise Exception("Unexpected wpa_state on dev1: " + state)
416
417def test_wpas_mesh_secure_sae_password(dev, apdev):
418    """wpa_supplicant secure mesh using sae_password"""
419    check_mesh_support(dev[0], secure=True)
420    dev[0].request("SET sae_groups ")
421    id = add_mesh_secure_net(dev[0], psk=False, sae_password=True)
422    dev[0].mesh_group_add(id)
423
424    dev[1].request("SET sae_groups ")
425    id = add_mesh_secure_net(dev[1])
426    dev[1].mesh_group_add(id)
427
428    check_mesh_joined_connected(dev, connectivity=True)
429
430def test_mesh_secure_pmf(dev, apdev):
431    """Secure mesh network connectivity with PMF enabled"""
432    check_mesh_support(dev[0], secure=True)
433    dev[0].request("SET sae_groups ")
434    id = add_mesh_secure_net(dev[0], pmf=True)
435    dev[0].mesh_group_add(id)
436
437    dev[1].request("SET sae_groups ")
438    id = add_mesh_secure_net(dev[1], pmf=True)
439    dev[1].mesh_group_add(id)
440
441    check_mesh_joined_connected(dev, connectivity=True)
442
443def test_mesh_secure_ocv(dev, apdev):
444    """Secure mesh network connectivity with OCV enabled"""
445    check_mesh_support(dev[0], secure=True)
446    dev[0].request("SET sae_groups ")
447    id = add_mesh_secure_net(dev[0], pmf=True, ocv=True)
448    dev[0].mesh_group_add(id)
449    dev[1].request("SET sae_groups ")
450    id = add_mesh_secure_net(dev[1], pmf=True, ocv=True)
451    dev[1].mesh_group_add(id)
452
453    check_mesh_joined_connected(dev, connectivity=True)
454
455def test_mesh_secure_ocv_compat(dev, apdev):
456    """Secure mesh network where only one peer has OCV enabled"""
457    check_mesh_support(dev[0], secure=True)
458    dev[0].request("SET sae_groups ")
459    id = add_mesh_secure_net(dev[0], pmf=True, ocv=True)
460    dev[0].mesh_group_add(id)
461    dev[1].request("SET sae_groups ")
462    id = add_mesh_secure_net(dev[1], pmf=True, ocv=False)
463    dev[1].mesh_group_add(id)
464
465    check_mesh_joined_connected(dev, connectivity=True)
466
467def set_reg(dev, country):
468    subprocess.call(['iw', 'reg', 'set', country])
469    for i in range(2):
470        for j in range(5):
471            ev = dev[i].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=5)
472            if ev is None:
473                raise Exception("No regdom change event")
474            if "alpha2=" + country in ev:
475                break
476
477def clear_reg_setting(dev):
478    dev[0].request("MESH_GROUP_REMOVE " + dev[0].ifname)
479    dev[1].request("MESH_GROUP_REMOVE " + dev[1].ifname)
480    clear_regdom_dev(dev)
481    dev[0].flush_scan_cache()
482    dev[1].flush_scan_cache()
483
484def test_mesh_secure_ocv_mix_legacy(dev, apdev):
485    """Mesh network with a VHT STA and a legacy STA under OCV"""
486    try:
487        run_mesh_secure_ocv_mix_legacy(dev, apdev)
488    finally:
489        clear_reg_setting(dev)
490
491def run_mesh_secure_ocv_mix_legacy(dev, apdev):
492    check_mesh_support(dev[0], secure=True)
493    set_reg(dev, 'AZ')
494
495    dev[0].request("SET sae_groups ")
496    id = add_mesh_secure_net(dev[0], pmf=True, ocv=True)
497    dev[0].set_network(id, "frequency", "5200")
498    dev[0].set_network(id, "max_oper_chwidth", "2")
499    dev[0].mesh_group_add(id)
500
501    dev[1].request("SET sae_groups ")
502    id = add_mesh_secure_net(dev[1], pmf=True, ocv=True)
503    dev[1].set_network(id, "frequency", "5200")
504    dev[1].set_network(id, "disable_vht", "1")
505    dev[1].set_network(id, "disable_ht40", "1")
506    dev[1].mesh_group_add(id)
507
508    check_mesh_joined_connected(dev, connectivity=True)
509
510def test_mesh_secure_ocv_mix_ht(dev, apdev):
511    """Mesh network with a VHT STA and a HT STA under OCV"""
512    try:
513        run_mesh_secure_ocv_mix_ht(dev, apdev)
514    finally:
515        clear_reg_setting(dev)
516
517def run_mesh_secure_ocv_mix_ht(dev, apdev):
518    check_mesh_support(dev[0], secure=True)
519    set_reg(dev, 'AZ')
520
521    dev[0].request("SET sae_groups ")
522    id = add_mesh_secure_net(dev[0], pmf=True, ocv=True)
523    dev[0].set_network(id, "frequency", "5200")
524    dev[0].set_network(id, "max_oper_chwidth", "2")
525    dev[0].mesh_group_add(id)
526
527    dev[1].request("SET sae_groups ")
528    id = add_mesh_secure_net(dev[1], pmf=True, ocv=True)
529    dev[1].set_network(id, "frequency", "5200")
530    dev[1].set_network(id, "disable_vht", "1")
531    dev[1].mesh_group_add(id)
532
533    check_mesh_joined_connected(dev, connectivity=True)
534
535def run_mesh_secure(dev, cipher, pmf=False, group_mgmt=None):
536    if cipher not in dev[0].get_capability("pairwise"):
537        raise HwsimSkip("Cipher %s not supported" % cipher)
538    check_mesh_support(dev[0], secure=True)
539    dev[0].request("SET sae_groups ")
540    id = add_mesh_secure_net(dev[0], pairwise=cipher, group=cipher, pmf=pmf,
541                             group_mgmt=group_mgmt)
542    dev[0].mesh_group_add(id)
543
544    dev[1].request("SET sae_groups ")
545    id = add_mesh_secure_net(dev[1], pairwise=cipher, group=cipher, pmf=pmf,
546                             group_mgmt=group_mgmt)
547    dev[1].mesh_group_add(id)
548
549    check_mesh_joined_connected(dev, connectivity=True)
550
551def test_mesh_secure_ccmp(dev, apdev):
552    """Secure mesh with CCMP"""
553    run_mesh_secure(dev, "CCMP")
554
555def test_mesh_secure_gcmp(dev, apdev):
556    """Secure mesh with GCMP"""
557    run_mesh_secure(dev, "GCMP")
558
559def test_mesh_secure_gcmp_256(dev, apdev):
560    """Secure mesh with GCMP-256"""
561    run_mesh_secure(dev, "GCMP-256")
562
563def test_mesh_secure_ccmp_256(dev, apdev):
564    """Secure mesh with CCMP-256"""
565    run_mesh_secure(dev, "CCMP-256")
566
567def test_mesh_secure_ccmp_cmac(dev, apdev):
568    """Secure mesh with CCMP-128 and BIP-CMAC-128"""
569    run_mesh_secure(dev, "CCMP", pmf=True, group_mgmt="AES-128-CMAC")
570
571def test_mesh_secure_gcmp_gmac(dev, apdev):
572    """Secure mesh with GCMP-128 and BIP-GMAC-128"""
573    run_mesh_secure(dev, "GCMP", pmf=True, group_mgmt="BIP-GMAC-128")
574
575def test_mesh_secure_ccmp_256_cmac_256(dev, apdev):
576    """Secure mesh with CCMP-256 and BIP-CMAC-256"""
577    run_mesh_secure(dev, "CCMP-256", pmf=True, group_mgmt="BIP-CMAC-256")
578
579def test_mesh_secure_gcmp_256_gmac_256(dev, apdev):
580    """Secure mesh with GCMP-256 and BIP-GMAC-256"""
581    run_mesh_secure(dev, "GCMP-256", pmf=True, group_mgmt="BIP-GMAC-256")
582
583def test_mesh_secure_invalid_pairwise_cipher(dev, apdev):
584    """Secure mesh and invalid group cipher"""
585    check_mesh_support(dev[0], secure=True)
586    skip_without_tkip(dev[0])
587    dev[0].request("SET sae_groups ")
588    id = add_mesh_secure_net(dev[0], pairwise="TKIP", group="CCMP")
589    if dev[0].mesh_group_add(id) != None:
590        raise Exception("Unexpected group add success")
591    ev = dev[0].wait_event(["mesh: Invalid pairwise cipher"], timeout=1)
592    if ev is None:
593        raise Exception("Invalid pairwise cipher not reported")
594
595def test_mesh_secure_invalid_group_cipher(dev, apdev):
596    """Secure mesh and invalid group cipher"""
597    skip_without_tkip(dev[0])
598    check_mesh_support(dev[0], secure=True)
599    dev[0].request("SET sae_groups ")
600    id = add_mesh_secure_net(dev[0], pairwise="CCMP", group="TKIP")
601    if dev[0].mesh_group_add(id) != None:
602        raise Exception("Unexpected group add success")
603    ev = dev[0].wait_event(["mesh: Invalid group cipher"], timeout=1)
604    if ev is None:
605        raise Exception("Invalid group cipher not reported")
606
607def test_wpas_mesh_secure_sae_group_mismatch(dev, apdev):
608    """wpa_supplicant secure MESH and SAE group mismatch"""
609    check_mesh_support(dev[0], secure=True)
610    addr0 = dev[0].p2p_interface_addr()
611    addr1 = dev[1].p2p_interface_addr()
612    addr2 = dev[2].p2p_interface_addr()
613
614    dev[0].request("SET sae_groups 19 25")
615    id = add_mesh_secure_net(dev[0])
616    dev[0].mesh_group_add(id)
617
618    dev[1].request("SET sae_groups 19")
619    id = add_mesh_secure_net(dev[1])
620    dev[1].mesh_group_add(id)
621
622    dev[2].request("SET sae_groups 20")
623    id = add_mesh_secure_net(dev[2])
624    dev[2].mesh_group_add(id)
625
626    check_mesh_group_added(dev[0])
627    check_mesh_group_added(dev[1])
628    check_mesh_group_added(dev[2])
629
630    ev = dev[0].wait_event(["MESH-PEER-CONNECTED"])
631    if ev is None:
632        raise Exception("Remote peer did not connect")
633    if addr1 not in ev:
634        raise Exception("Unexpected peer connected: " + ev)
635
636    ev = dev[1].wait_event(["MESH-PEER-CONNECTED"])
637    if ev is None:
638        raise Exception("Remote peer did not connect")
639    if addr0 not in ev:
640        raise Exception("Unexpected peer connected: " + ev)
641
642    ev = dev[2].wait_event(["MESH-PEER-CONNECTED"], timeout=1)
643    if ev is not None:
644        raise Exception("Unexpected peer connection at dev[2]: " + ev)
645
646    ev = dev[0].wait_event(["MESH-PEER-CONNECTED"], timeout=0.1)
647    if ev is not None:
648        raise Exception("Unexpected peer connection: " + ev)
649
650    ev = dev[1].wait_event(["MESH-PEER-CONNECTED"], timeout=0.1)
651    if ev is not None:
652        raise Exception("Unexpected peer connection: " + ev)
653
654    dev[0].request("SET sae_groups ")
655    dev[1].request("SET sae_groups ")
656    dev[2].request("SET sae_groups ")
657
658def test_wpas_mesh_secure_sae_group_negotiation(dev, apdev):
659    """wpa_supplicant secure MESH and SAE group negotiation"""
660    check_mesh_support(dev[0], secure=True)
661    addr0 = dev[0].own_addr()
662    addr1 = dev[1].own_addr()
663
664    #dev[0].request("SET sae_groups 21 20 25 26")
665    dev[0].request("SET sae_groups 20")
666    id = add_mesh_secure_net(dev[0])
667    dev[0].mesh_group_add(id)
668
669    dev[1].request("SET sae_groups 19 20")
670    id = add_mesh_secure_net(dev[1])
671    dev[1].mesh_group_add(id)
672
673    check_mesh_joined_connected(dev)
674
675    dev[0].request("SET sae_groups ")
676    dev[1].request("SET sae_groups ")
677
678def test_wpas_mesh_secure_sae_missing_password(dev, apdev):
679    """wpa_supplicant secure MESH and missing SAE password"""
680    check_mesh_support(dev[0], secure=True)
681    id = add_mesh_secure_net(dev[0], psk=False)
682    dev[0].set_network(id, "psk", "8f20b381f9b84371d61b5080ad85cac3c61ab3ca9525be5b2d0f4da3d979187a")
683    dev[0].mesh_group_add(id)
684    ev = dev[0].wait_event(["MESH-GROUP-STARTED", "Could not join mesh"],
685                           timeout=5)
686    if ev is None:
687        raise Exception("Timeout on mesh start event")
688    if "MESH-GROUP-STARTED" in ev:
689        raise Exception("Unexpected mesh group start")
690    ev = dev[0].wait_event(["MESH-GROUP-STARTED"], timeout=0.1)
691    if ev is not None:
692        raise Exception("Unexpected mesh group start")
693
694def test_wpas_mesh_secure_no_auto(dev, apdev):
695    """wpa_supplicant secure MESH network connectivity"""
696    check_mesh_support(dev[0], secure=True)
697    dev[0].request("SET sae_groups 19")
698    id = add_mesh_secure_net(dev[0])
699    dev[0].mesh_group_add(id)
700
701    dev[1].request("SET sae_groups 19")
702    id = add_mesh_secure_net(dev[1])
703    dev[1].set_network(id, "no_auto_peer", "1")
704    dev[1].mesh_group_add(id)
705
706    check_mesh_joined_connected(dev, connectivity=True)
707
708    dev[0].request("SET sae_groups ")
709    dev[1].request("SET sae_groups ")
710
711def test_wpas_mesh_secure_dropped_frame(dev, apdev):
712    """Secure mesh network connectivity when the first plink Open is dropped"""
713    check_mesh_support(dev[0], secure=True)
714
715    dev[0].request("SET ext_mgmt_frame_handling 1")
716    dev[0].request("SET sae_groups ")
717    id = add_mesh_secure_net(dev[0])
718    dev[0].mesh_group_add(id)
719
720    dev[1].request("SET sae_groups ")
721    id = add_mesh_secure_net(dev[1])
722    dev[1].mesh_group_add(id)
723
724    check_mesh_joined2(dev)
725
726    # Drop the first Action frame (plink Open) to test unexpected order of
727    # Confirm/Open messages.
728    count = 0
729    while True:
730        count += 1
731        if count > 10:
732            raise Exception("Did not see Action frames")
733        rx_msg = dev[0].mgmt_rx()
734        if rx_msg is None:
735            raise Exception("MGMT-RX timeout")
736        if rx_msg['subtype'] == 13:
737            logger.info("Drop the first Action frame")
738            break
739        if "OK" not in dev[0].request("MGMT_RX_PROCESS freq={} datarate={} ssi_signal={} frame={}".format(
740            rx_msg['freq'], rx_msg['datarate'], rx_msg['ssi_signal'], binascii.hexlify(rx_msg['frame']).decode())):
741            raise Exception("MGMT_RX_PROCESS failed")
742
743    dev[0].request("SET ext_mgmt_frame_handling 0")
744
745    check_mesh_connected2(dev, connectivity=True)
746
747def test_mesh_secure_fail(dev, apdev):
748    """Secure mesh network connectivity failure"""
749    check_mesh_support(dev[0], secure=True)
750    dev[0].request("SET sae_groups ")
751    id = add_mesh_secure_net(dev[0], pmf=True)
752    dev[0].mesh_group_add(id)
753
754    dev[1].request("SET sae_groups ")
755    id = add_mesh_secure_net(dev[1], pmf=True)
756
757    with fail_test(dev[0], 1, "wpa_driver_nl80211_sta_add;mesh_mpm_auth_peer"):
758        dev[1].mesh_group_add(id)
759
760        check_mesh_joined_connected(dev)
761
762def test_wpas_mesh_ctrl(dev):
763    """wpa_supplicant ctrl_iface mesh command error cases"""
764    check_mesh_support(dev[0])
765    if "FAIL" not in dev[0].request("MESH_GROUP_ADD 123"):
766        raise Exception("Unexpected MESH_GROUP_ADD success")
767    id = dev[0].add_network()
768    if "FAIL" not in dev[0].request("MESH_GROUP_ADD %d" % id):
769        raise Exception("Unexpected MESH_GROUP_ADD success")
770    dev[0].set_network(id, "mode", "5")
771    dev[0].set_network(id, "key_mgmt", "WPA-PSK")
772    if "FAIL" not in dev[0].request("MESH_GROUP_ADD %d" % id):
773        raise Exception("Unexpected MESH_GROUP_ADD success")
774
775    if "FAIL" not in dev[0].request("MESH_GROUP_REMOVE foo"):
776        raise Exception("Unexpected MESH_GROUP_REMOVE success")
777
778def test_wpas_mesh_dynamic_interface(dev):
779    """wpa_supplicant mesh with dynamic interface"""
780    check_mesh_support(dev[0])
781    mesh0 = None
782    mesh1 = None
783    try:
784        mesh0 = dev[0].request("MESH_INTERFACE_ADD ifname=mesh0")
785        if "FAIL" in mesh0:
786            raise Exception("MESH_INTERFACE_ADD failed")
787        mesh1 = dev[1].request("MESH_INTERFACE_ADD")
788        if "FAIL" in mesh1:
789            raise Exception("MESH_INTERFACE_ADD failed")
790
791        wpas0 = WpaSupplicant(ifname=mesh0)
792        wpas1 = WpaSupplicant(ifname=mesh1)
793        logger.info(mesh0 + " address " + wpas0.get_status_field("address"))
794        logger.info(mesh1 + " address " + wpas1.get_status_field("address"))
795
796        add_open_mesh_network(wpas0)
797        add_open_mesh_network(wpas1)
798        check_mesh_joined_connected([wpas0, wpas1], connectivity=True)
799
800        # Must not allow MESH_GROUP_REMOVE on dynamic interface
801        if "FAIL" not in wpas0.request("MESH_GROUP_REMOVE " + mesh0):
802            raise Exception("Invalid MESH_GROUP_REMOVE accepted")
803        if "FAIL" not in wpas1.request("MESH_GROUP_REMOVE " + mesh1):
804            raise Exception("Invalid MESH_GROUP_REMOVE accepted")
805
806        # Must not allow MESH_GROUP_REMOVE on another radio interface
807        if "FAIL" not in wpas0.request("MESH_GROUP_REMOVE " + mesh1):
808            raise Exception("Invalid MESH_GROUP_REMOVE accepted")
809        if "FAIL" not in wpas1.request("MESH_GROUP_REMOVE " + mesh0):
810            raise Exception("Invalid MESH_GROUP_REMOVE accepted")
811
812        wpas0.remove_ifname()
813        wpas1.remove_ifname()
814
815        if "OK" not in dev[0].request("MESH_GROUP_REMOVE " + mesh0):
816            raise Exception("MESH_GROUP_REMOVE failed")
817        if "OK" not in dev[1].request("MESH_GROUP_REMOVE " + mesh1):
818            raise Exception("MESH_GROUP_REMOVE failed")
819
820        if "FAIL" not in dev[0].request("MESH_GROUP_REMOVE " + mesh0):
821            raise Exception("Invalid MESH_GROUP_REMOVE accepted")
822        if "FAIL" not in dev[1].request("MESH_GROUP_REMOVE " + mesh1):
823            raise Exception("Invalid MESH_GROUP_REMOVE accepted")
824
825        logger.info("Make sure another dynamic group can be added")
826        mesh0 = dev[0].request("MESH_INTERFACE_ADD ifname=mesh0")
827        if "FAIL" in mesh0:
828            raise Exception("MESH_INTERFACE_ADD failed")
829        mesh1 = dev[1].request("MESH_INTERFACE_ADD")
830        if "FAIL" in mesh1:
831            raise Exception("MESH_INTERFACE_ADD failed")
832
833        wpas0 = WpaSupplicant(ifname=mesh0)
834        wpas1 = WpaSupplicant(ifname=mesh1)
835        logger.info(mesh0 + " address " + wpas0.get_status_field("address"))
836        logger.info(mesh1 + " address " + wpas1.get_status_field("address"))
837
838        add_open_mesh_network(wpas0)
839        add_open_mesh_network(wpas1)
840        check_mesh_joined_connected([wpas0, wpas1], connectivity=True)
841    finally:
842        if mesh0:
843            dev[0].request("MESH_GROUP_REMOVE " + mesh0)
844        if mesh1:
845            dev[1].request("MESH_GROUP_REMOVE " + mesh1)
846
847def test_wpas_mesh_dynamic_interface_remove(dev):
848    """wpa_supplicant mesh with dynamic interface and removal"""
849    wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
850    wpas.interface_add("wlan5")
851    check_mesh_support(wpas)
852    mesh5 = wpas.request("MESH_INTERFACE_ADD ifname=mesh5")
853    if "FAIL" in mesh5:
854        raise Exception("MESH_INTERFACE_ADD failed")
855
856    wpas5 = WpaSupplicant(ifname=mesh5)
857    logger.info(mesh5 + " address " + wpas5.get_status_field("address"))
858    add_open_mesh_network(wpas5)
859    add_open_mesh_network(dev[0])
860    check_mesh_joined_connected([wpas5, dev[0]], connectivity=True)
861
862    # Remove the main interface while mesh interface is in use
863    wpas.interface_remove("wlan5")
864
865def test_wpas_mesh_max_peering(dev, apdev, params):
866    """Mesh max peering limit"""
867    check_mesh_support(dev[0])
868    try:
869        dev[0].request("SET max_peer_links 1")
870
871        # first, connect dev[0] and dev[1]
872        add_open_mesh_network(dev[0])
873        add_open_mesh_network(dev[1])
874        for i in range(2):
875            ev = dev[i].wait_event(["MESH-PEER-CONNECTED"])
876            if ev is None:
877                raise Exception("dev%d did not connect with any peer" % i)
878
879        # add dev[2] which will try to connect with both dev[0] and dev[1],
880        # but can complete connection only with dev[1]
881        add_open_mesh_network(dev[2])
882        for i in range(1, 3):
883            ev = dev[i].wait_event(["MESH-PEER-CONNECTED"])
884            if ev is None:
885                raise Exception("dev%d did not connect the second peer" % i)
886
887        ev = dev[0].wait_event(["MESH-PEER-CONNECTED"], timeout=1)
888        if ev is not None:
889            raise Exception("dev0 connection beyond max peering limit")
890
891        ev = dev[2].wait_event(["MESH-PEER-CONNECTED"], timeout=0.1)
892        if ev is not None:
893            raise Exception("dev2 reported unexpected peering: " + ev)
894
895        for i in range(3):
896            dev[i].mesh_group_remove()
897            check_mesh_group_removed(dev[i])
898    finally:
899        dev[0].request("SET max_peer_links 99")
900
901    addr0 = dev[0].own_addr()
902    addr1 = dev[1].own_addr()
903    addr2 = dev[2].own_addr()
904
905    capfile = os.path.join(params['logdir'], "hwsim0.pcapng")
906    filt = "wlan.fc.type_subtype == 8"
907    out = run_tshark(capfile, filt, ["wlan.sa", "wlan.mesh.config.cap"])
908    pkts = out.splitlines()
909    one = [0, 0, 0]
910    zero = [0, 0, 0]
911    all_cap_one = True
912    for pkt in pkts:
913        addr, cap = pkt.split('\t')
914        cap = int(cap, 16)
915        if cap != 1:
916            all_cap_one = False
917        if addr == addr0:
918            idx = 0
919        elif addr == addr1:
920            idx = 1
921        elif addr == addr2:
922            idx = 2
923        else:
924            continue
925        if cap & 0x01:
926            one[idx] += 1
927        else:
928            zero[idx] += 1
929    logger.info("one: " + str(one))
930    logger.info("zero: " + str(zero))
931    if all_cap_one:
932        # It looks like tshark parser was broken at some point for
933        # wlan.mesh.config.cap which is now (tshark 2.6.3) pointing to incorrect
934        # field (same as wlan.mesh.config.ps_protocol). This used to work with
935        # tshark 2.2.6.
936        #
937        # For now, assume the capability field ends up being the last octet of
938        # the frame.
939        one = [0, 0, 0]
940        zero = [0, 0, 0]
941        addrs = [addr0, addr1, addr2]
942        for idx in range(3):
943            addr = addrs[idx]
944            out = run_tshark_json(capfile, filt + " && wlan.sa == " + addr)
945            pkts = json.loads(out)
946            for pkt in pkts:
947                wlan = pkt["_source"]["layers"]["wlan"]
948                if "wlan.tagged.all" not in wlan:
949                    continue
950
951                tagged = wlan["wlan.tagged.all"]
952                if "wlan.tag" not in tagged:
953                    continue
954
955                wlan_tag = tagged["wlan.tag"]
956                if "wlan.mesh.config.ps_protocol_raw" not in wlan_tag:
957                    continue
958
959                frame = pkt["_source"]["layers"]["frame_raw"][0]
960                cap_offset = wlan_tag["wlan.mesh.config.ps_protocol_raw"][1] + 6
961                cap = int(frame[(cap_offset * 2):(cap_offset * 2 + 2)], 16)
962                if cap & 0x01:
963                    one[idx] += 1
964                else:
965                    zero[idx] += 1
966        logger.info("one: " + str(one))
967        logger.info("zero: " + str(zero))
968    if zero[0] == 0:
969        raise Exception("Accepting Additional Mesh Peerings not cleared")
970    if one[0] == 0:
971        raise Exception("Accepting Additional Mesh Peerings was not set in the first Beacon frame")
972    if zero[1] > 0 or zero[2] > 0 or one[1] == 0 or one[2] == 0:
973        raise Exception("Unexpected value in Accepting Additional Mesh Peerings from other STAs")
974
975def test_wpas_mesh_open_5ghz(dev, apdev):
976    """wpa_supplicant open MESH network on 5 GHz band"""
977    try:
978        _test_wpas_mesh_open_5ghz(dev, apdev)
979    finally:
980        clear_reg_setting(dev)
981
982def _test_wpas_mesh_open_5ghz(dev, apdev):
983    check_mesh_support(dev[0])
984    subprocess.call(['iw', 'reg', 'set', 'US'])
985    for i in range(2):
986        for j in range(5):
987            ev = dev[i].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=5)
988            if ev is None:
989                raise Exception("No regdom change event")
990            if "alpha2=US" in ev:
991                break
992        add_open_mesh_network(dev[i], freq="5180")
993
994    check_mesh_joined_connected(dev, connectivity=True)
995
996    dev[0].mesh_group_remove()
997    dev[1].mesh_group_remove()
998    check_mesh_group_removed(dev[0])
999    check_mesh_group_removed(dev[1])
1000    dev[0].dump_monitor()
1001    dev[1].dump_monitor()
1002
1003def test_wpas_mesh_open_5ghz_chan140(dev, apdev):
1004    """Mesh BSS on 5 GHz band channel 140"""
1005    try:
1006        _test_wpas_mesh_open_5ghz_chan140(dev, apdev)
1007    finally:
1008        clear_reg_setting(dev)
1009
1010def _test_wpas_mesh_open_5ghz_chan140(dev, apdev):
1011    check_mesh_support(dev[0])
1012    subprocess.call(['iw', 'reg', 'set', 'ZA'])
1013    for i in range(2):
1014        for j in range(5):
1015            ev = dev[i].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=5)
1016            if ev is None:
1017                raise Exception("No regdom change event")
1018            if "alpha2=ZA" in ev:
1019                break
1020        add_open_mesh_network(dev[i], freq="5700")
1021
1022    check_mesh_joined_connected(dev, connectivity=True)
1023
1024    dev[0].mesh_group_remove()
1025    dev[1].mesh_group_remove()
1026    check_mesh_group_removed(dev[0])
1027    check_mesh_group_removed(dev[1])
1028    dev[0].dump_monitor()
1029    dev[1].dump_monitor()
1030
1031def test_wpas_mesh_open_ht40(dev, apdev):
1032    """Mesh and HT40 support difference"""
1033    try:
1034        _test_wpas_mesh_open_ht40(dev, apdev)
1035    finally:
1036        dev[0].request("MESH_GROUP_REMOVE " + dev[0].ifname)
1037        dev[1].request("MESH_GROUP_REMOVE " + dev[1].ifname)
1038        dev[2].request("MESH_GROUP_REMOVE " + dev[2].ifname)
1039        clear_regdom_dev(dev)
1040        dev[0].flush_scan_cache()
1041        dev[1].flush_scan_cache()
1042        dev[2].flush_scan_cache()
1043
1044def _test_wpas_mesh_open_ht40(dev, apdev):
1045    check_mesh_support(dev[0])
1046    subprocess.call(['iw', 'reg', 'set', 'US'])
1047    for i in range(3):
1048        for j in range(5):
1049            ev = dev[i].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=5)
1050            if ev is None:
1051                raise Exception("No regdom change event")
1052            if "alpha2=US" in ev:
1053                break
1054        add_open_mesh_network(dev[i], freq="5180", disable_vht=True,
1055                              disable_ht40=(i == 2))
1056
1057    check_mesh_group_added(dev[0])
1058    check_mesh_group_added(dev[1])
1059    check_mesh_group_added(dev[2])
1060
1061    check_mesh_peer_connected(dev[0])
1062    check_mesh_peer_connected(dev[1])
1063    check_mesh_peer_connected(dev[2])
1064
1065    hwsim_utils.test_connectivity(dev[0], dev[1])
1066    hwsim_utils.test_connectivity(dev[0], dev[2])
1067    hwsim_utils.test_connectivity(dev[1], dev[2])
1068
1069    dev[0].mesh_group_remove()
1070    dev[1].mesh_group_remove()
1071    dev[2].mesh_group_remove()
1072    check_mesh_group_removed(dev[0])
1073    check_mesh_group_removed(dev[1])
1074    check_mesh_group_removed(dev[2])
1075    dev[0].dump_monitor()
1076    dev[1].dump_monitor()
1077    dev[2].dump_monitor()
1078
1079def test_wpas_mesh_open_vht40(dev, apdev):
1080    """wpa_supplicant open MESH network on VHT 40 MHz channel"""
1081    try:
1082        _test_wpas_mesh_open_vht40(dev, apdev)
1083    finally:
1084        clear_reg_setting(dev)
1085
1086def _test_wpas_mesh_open_vht40(dev, apdev):
1087    check_mesh_support(dev[0])
1088    subprocess.call(['iw', 'reg', 'set', 'US'])
1089    for i in range(2):
1090        for j in range(5):
1091            ev = dev[i].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=5)
1092            if ev is None:
1093                raise Exception("No regdom change event")
1094            if "alpha2=US" in ev:
1095                break
1096        add_open_mesh_network(dev[i], freq="5180", chwidth=0)
1097
1098    check_mesh_joined_connected(dev, connectivity=True)
1099
1100    sig = dev[0].request("SIGNAL_POLL").splitlines()
1101    if "WIDTH=40 MHz" not in sig:
1102        raise Exception("Unexpected SIGNAL_POLL value(2): " + str(sig))
1103    if "CENTER_FRQ1=5190" not in sig:
1104        raise Exception("Unexpected SIGNAL_POLL value(3): " + str(sig))
1105
1106    sig = dev[1].request("SIGNAL_POLL").splitlines()
1107    if "WIDTH=40 MHz" not in sig:
1108        raise Exception("Unexpected SIGNAL_POLL value(2b): " + str(sig))
1109    if "CENTER_FRQ1=5190" not in sig:
1110        raise Exception("Unexpected SIGNAL_POLL value(3b): " + str(sig))
1111
1112    dev[0].scan(freq="5180")
1113    bss = dev[0].get_bss(dev[1].own_addr())
1114    if bss and 'ie' in bss and "ff0724" in bss['ie']:
1115        sta = dev[0].request("STA " + dev[1].own_addr())
1116        logger.info("STA info:\n" + sta.rstrip())
1117        if "[HT][VHT][HE]" not in sta:
1118            raise Exception("Missing STA flags")
1119
1120    dev[0].mesh_group_remove()
1121    dev[1].mesh_group_remove()
1122    check_mesh_group_removed(dev[0])
1123    check_mesh_group_removed(dev[1])
1124    dev[0].dump_monitor()
1125    dev[1].dump_monitor()
1126
1127def test_wpas_mesh_open_vht20(dev, apdev):
1128    """wpa_supplicant open MESH network on VHT 20 MHz channel"""
1129    try:
1130        _test_wpas_mesh_open_vht20(dev, apdev)
1131    finally:
1132        clear_reg_setting(dev)
1133
1134def _test_wpas_mesh_open_vht20(dev, apdev):
1135    check_mesh_support(dev[0])
1136    subprocess.call(['iw', 'reg', 'set', 'US'])
1137    for i in range(2):
1138        for j in range(5):
1139            ev = dev[i].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=5)
1140            if ev is None:
1141                raise Exception("No regdom change event")
1142            if "alpha2=US" in ev:
1143                break
1144        add_open_mesh_network(dev[i], freq="5180", chwidth=0, disable_ht40=True)
1145
1146    check_mesh_joined_connected(dev, connectivity=True)
1147
1148    sig = dev[0].request("SIGNAL_POLL").splitlines()
1149    if "WIDTH=20 MHz" not in sig:
1150        raise Exception("Unexpected SIGNAL_POLL value(2): " + str(sig))
1151    if "CENTER_FRQ1=5180" not in sig:
1152        raise Exception("Unexpected SIGNAL_POLL value(3): " + str(sig))
1153
1154    sig = dev[1].request("SIGNAL_POLL").splitlines()
1155    if "WIDTH=20 MHz" not in sig:
1156        raise Exception("Unexpected SIGNAL_POLL value(2b): " + str(sig))
1157    if "CENTER_FRQ1=5180" not in sig:
1158        raise Exception("Unexpected SIGNAL_POLL value(3b): " + str(sig))
1159
1160    dev[0].mesh_group_remove()
1161    dev[1].mesh_group_remove()
1162    check_mesh_group_removed(dev[0])
1163    check_mesh_group_removed(dev[1])
1164    dev[0].dump_monitor()
1165    dev[1].dump_monitor()
1166
1167def test_wpas_mesh_open_vht_80p80(dev, apdev):
1168    """wpa_supplicant open MESH network on VHT 80+80 MHz channel"""
1169    try:
1170        _test_wpas_mesh_open_vht_80p80(dev, apdev)
1171    finally:
1172        clear_reg_setting(dev)
1173
1174def _test_wpas_mesh_open_vht_80p80(dev, apdev):
1175    check_mesh_support(dev[0])
1176    subprocess.call(['iw', 'reg', 'set', 'US'])
1177    for i in range(2):
1178        for j in range(5):
1179            ev = dev[i].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=5)
1180            if ev is None:
1181                raise Exception("No regdom change event")
1182            if "alpha2=US" in ev:
1183                break
1184        add_open_mesh_network(dev[i], freq="5180", chwidth=3)
1185
1186    check_mesh_joined_connected(dev, connectivity=True)
1187
1188    sig = dev[0].request("SIGNAL_POLL").splitlines()
1189    if "WIDTH=80+80 MHz" not in sig:
1190        raise Exception("Unexpected SIGNAL_POLL value(2): " + str(sig))
1191    if "CENTER_FRQ1=5210" not in sig:
1192        raise Exception("Unexpected SIGNAL_POLL value(3): " + str(sig))
1193    if "CENTER_FRQ2=5775" not in sig:
1194        raise Exception("Unexpected SIGNAL_POLL value(4): " + str(sig))
1195
1196    sig = dev[1].request("SIGNAL_POLL").splitlines()
1197    if "WIDTH=80+80 MHz" not in sig:
1198        raise Exception("Unexpected SIGNAL_POLL value(2b): " + str(sig))
1199    if "CENTER_FRQ1=5210" not in sig:
1200        raise Exception("Unexpected SIGNAL_POLL value(3b): " + str(sig))
1201    if "CENTER_FRQ2=5775" not in sig:
1202        raise Exception("Unexpected SIGNAL_POLL value(4b): " + str(sig))
1203
1204    dev[0].mesh_group_remove()
1205    dev[1].mesh_group_remove()
1206    check_mesh_group_removed(dev[0])
1207    check_mesh_group_removed(dev[1])
1208    dev[0].dump_monitor()
1209    dev[1].dump_monitor()
1210
1211def test_mesh_open_vht_160(dev, apdev):
1212    """Open mesh network on VHT 160 MHz channel"""
1213    try:
1214        _test_mesh_open_vht_160(dev, apdev)
1215    finally:
1216        clear_reg_setting(dev)
1217
1218def _test_mesh_open_vht_160(dev, apdev):
1219    check_mesh_support(dev[0])
1220    subprocess.call(['iw', 'reg', 'set', 'ZA'])
1221    for i in range(2):
1222        for j in range(5):
1223            ev = dev[i].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=5)
1224            if ev is None:
1225                raise Exception("No regdom change event")
1226            if "alpha2=ZA" in ev:
1227                break
1228
1229        cmd = subprocess.Popen(["iw", "reg", "get"], stdout=subprocess.PIPE)
1230        out, err = cmd.communicate()
1231        found = False
1232        for entry in out.splitlines():
1233            entry = entry.decode()
1234            if "@ 160)" in entry and "DFS" not in entry:
1235                found = True
1236                break
1237        if not found:
1238            raise HwsimSkip("160 MHz channel without DFS not supported in regulatory information")
1239
1240        add_open_mesh_network(dev[i], freq="5520", chwidth=2)
1241
1242    check_mesh_joined_connected(dev, connectivity=True)
1243    dev[0].dump_monitor()
1244    dev[1].dump_monitor()
1245
1246    sig = dev[0].request("SIGNAL_POLL").splitlines()
1247    if "WIDTH=160 MHz" not in sig:
1248        raise Exception("Unexpected SIGNAL_POLL value(2): " + str(sig))
1249    if "FREQUENCY=5520" not in sig:
1250        raise Exception("Unexpected SIGNAL_POLL value(3): " + str(sig))
1251
1252    sig = dev[1].request("SIGNAL_POLL").splitlines()
1253    if "WIDTH=160 MHz" not in sig:
1254        raise Exception("Unexpected SIGNAL_POLL value(2b): " + str(sig))
1255    if "FREQUENCY=5520" not in sig:
1256        raise Exception("Unexpected SIGNAL_POLL value(3b): " + str(sig))
1257
1258    dev[0].mesh_group_remove()
1259    dev[1].mesh_group_remove()
1260    check_mesh_group_removed(dev[0])
1261    check_mesh_group_removed(dev[1])
1262    dev[0].dump_monitor()
1263    dev[1].dump_monitor()
1264
1265def test_wpas_mesh_password_mismatch(dev, apdev):
1266    """Mesh network and one device with mismatching password"""
1267    check_mesh_support(dev[0], secure=True)
1268    dev[0].request("SET sae_groups ")
1269    id = add_mesh_secure_net(dev[0])
1270    dev[0].mesh_group_add(id)
1271
1272    dev[1].request("SET sae_groups ")
1273    id = add_mesh_secure_net(dev[1])
1274    dev[1].mesh_group_add(id)
1275
1276    dev[2].request("SET sae_groups ")
1277    id = add_mesh_secure_net(dev[2])
1278    dev[2].set_network_quoted(id, "psk", "wrong password")
1279    dev[2].mesh_group_add(id)
1280
1281    # The two peers with matching password need to be able to connect
1282    check_mesh_joined_connected(dev)
1283
1284    ev = dev[2].wait_event(["MESH-SAE-AUTH-FAILURE"], timeout=20)
1285    if ev is None:
1286        raise Exception("dev2 did not report auth failure (1)")
1287    ev = dev[2].wait_event(["MESH-SAE-AUTH-FAILURE"], timeout=20)
1288    if ev is None:
1289        raise Exception("dev2 did not report auth failure (2)")
1290    dev[2].dump_monitor()
1291
1292    count = 0
1293    ev = dev[0].wait_event(["MESH-SAE-AUTH-FAILURE"], timeout=5)
1294    if ev is None:
1295        logger.info("dev0 did not report auth failure")
1296    else:
1297        if "addr=" + dev[2].own_addr() not in ev:
1298            raise Exception("Unexpected peer address in dev0 event: " + ev)
1299        count += 1
1300    dev[0].dump_monitor()
1301
1302    ev = dev[1].wait_event(["MESH-SAE-AUTH-FAILURE"], timeout=5)
1303    if ev is None:
1304        logger.info("dev1 did not report auth failure")
1305    else:
1306        if "addr=" + dev[2].own_addr() not in ev:
1307            raise Exception("Unexpected peer address in dev1 event: " + ev)
1308        count += 1
1309    dev[1].dump_monitor()
1310
1311    hwsim_utils.test_connectivity(dev[0], dev[1])
1312
1313    for i in range(2):
1314        try:
1315            hwsim_utils.test_connectivity(dev[i], dev[2], timeout=1)
1316            raise Exception("Data connectivity test passed unexpectedly")
1317        except Exception as e:
1318            if "data delivery failed" not in str(e):
1319                raise
1320
1321    if count == 0:
1322        raise Exception("Neither dev0 nor dev1 reported auth failure")
1323
1324@long_duration_test
1325def test_wpas_mesh_password_mismatch_retry(dev, apdev):
1326    """Mesh password mismatch and retry"""
1327    check_mesh_support(dev[0], secure=True)
1328    dev[0].request("SET sae_groups ")
1329    id = add_mesh_secure_net(dev[0])
1330    dev[0].mesh_group_add(id)
1331
1332    dev[1].request("SET sae_groups ")
1333    id = add_mesh_secure_net(dev[1])
1334    dev[1].set_network_quoted(id, "psk", "wrong password")
1335    dev[1].mesh_group_add(id)
1336
1337    check_mesh_joined2(dev)
1338
1339    for i in range(4):
1340        ev = dev[0].wait_event(["MESH-SAE-AUTH-FAILURE"], timeout=20)
1341        if ev is None:
1342            raise Exception("dev0 did not report auth failure (%d)" % i)
1343        ev = dev[1].wait_event(["MESH-SAE-AUTH-FAILURE"], timeout=20)
1344        if ev is None:
1345            raise Exception("dev1 did not report auth failure (%d)" % i)
1346
1347    ev = dev[0].wait_event(["MESH-SAE-AUTH-BLOCKED"], timeout=10)
1348    if ev is None:
1349        raise Exception("dev0 did not report auth blocked")
1350    ev = dev[1].wait_event(["MESH-SAE-AUTH-BLOCKED"], timeout=10)
1351    if ev is None:
1352        raise Exception("dev1 did not report auth blocked")
1353
1354def test_mesh_wpa_auth_init_oom(dev, apdev):
1355    """Secure mesh network setup failing due to wpa_init() OOM"""
1356    check_mesh_support(dev[0], secure=True)
1357    dev[0].request("SET sae_groups ")
1358    with alloc_fail(dev[0], 1, "wpa_init"):
1359        id = add_mesh_secure_net(dev[0])
1360        dev[0].mesh_group_add(id)
1361        ev = dev[0].wait_event(["MESH-GROUP-STARTED"], timeout=0.2)
1362        if ev is not None:
1363            raise Exception("Unexpected mesh group start during OOM")
1364
1365def test_mesh_wpa_init_fail(dev, apdev):
1366    """Secure mesh network setup local failure"""
1367    check_mesh_support(dev[0], secure=True)
1368    check_mesh_support(dev[1], secure=True)
1369    check_mesh_support(dev[2], secure=True)
1370    dev[0].request("SET sae_groups ")
1371
1372    with fail_test(dev[0], 1, "os_get_random;=__mesh_rsn_auth_init"):
1373        id = add_mesh_secure_net(dev[0])
1374        dev[0].mesh_group_add(id)
1375        wait_fail_trigger(dev[0], "GET_FAIL")
1376
1377    dev[0].dump_monitor()
1378    with alloc_fail(dev[0], 1, "mesh_rsn_auth_init"):
1379        id = add_mesh_secure_net(dev[0])
1380        dev[0].mesh_group_add(id)
1381        wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
1382
1383    dev[0].dump_monitor()
1384    with fail_test(dev[0], 1, "os_get_random;mesh_rsn_init_ampe_sta"):
1385        id = add_mesh_secure_net(dev[0])
1386        dev[0].mesh_group_add(id)
1387        dev[1].request("SET sae_groups ")
1388        id = add_mesh_secure_net(dev[1])
1389        dev[1].mesh_group_add(id)
1390        wait_fail_trigger(dev[0], "GET_FAIL")
1391
1392    with fail_test(dev[0], 2, "=omac1_aes_vector;aes_siv_encrypt"):
1393        id = add_mesh_secure_net(dev[2])
1394        dev[0].mesh_group_add(id)
1395        dev[2].request("SET sae_groups ")
1396        id = add_mesh_secure_net(dev[2])
1397        dev[2].mesh_group_add(id)
1398        wait_fail_trigger(dev[0], "GET_FAIL")
1399
1400def test_wpas_mesh_reconnect(dev, apdev):
1401    """Secure mesh network plink counting during reconnection"""
1402    check_mesh_support(dev[0])
1403    try:
1404        _test_wpas_mesh_reconnect(dev)
1405    finally:
1406        dev[0].request("SET max_peer_links 99")
1407
1408def _test_wpas_mesh_reconnect(dev):
1409    dev[0].request("SET max_peer_links 2")
1410    dev[0].request("SET sae_groups ")
1411    id = add_mesh_secure_net(dev[0])
1412    dev[0].set_network(id, "beacon_int", "100")
1413    dev[0].mesh_group_add(id)
1414    dev[1].request("SET sae_groups ")
1415    id = add_mesh_secure_net(dev[1])
1416    dev[1].mesh_group_add(id)
1417    check_mesh_joined_connected(dev)
1418
1419    for i in range(3):
1420        # Drop incoming management frames to avoid handling link close
1421        dev[0].request("SET ext_mgmt_frame_handling 1")
1422        dev[1].mesh_group_remove()
1423        check_mesh_group_removed(dev[1])
1424        dev[1].request("FLUSH")
1425        dev[0].request("SET ext_mgmt_frame_handling 0")
1426        id = add_mesh_secure_net(dev[1])
1427        dev[1].mesh_group_add(id)
1428        check_mesh_group_added(dev[1])
1429        check_mesh_peer_connected(dev[1])
1430        dev[0].dump_monitor()
1431        dev[1].dump_monitor()
1432
1433def test_wpas_mesh_gate_forwarding(dev, apdev, p):
1434    """Mesh forwards traffic to unknown sta to mesh gates"""
1435    addr0 = dev[0].own_addr()
1436    addr1 = dev[1].own_addr()
1437    addr2 = dev[2].own_addr()
1438    external_sta = '02:11:22:33:44:55'
1439
1440    # start 3 node connected mesh
1441    check_mesh_support(dev[0])
1442    for i in range(3):
1443        add_open_mesh_network(dev[i])
1444        check_mesh_group_added(dev[i])
1445    for i in range(3):
1446        check_mesh_peer_connected(dev[i])
1447
1448    hwsim_utils.test_connectivity(dev[0], dev[1])
1449    hwsim_utils.test_connectivity(dev[1], dev[2])
1450    hwsim_utils.test_connectivity(dev[0], dev[2])
1451
1452    # dev0 and dev1 are mesh gates
1453    subprocess.call(['iw', 'dev', dev[0].ifname, 'set', 'mesh_param',
1454                     'mesh_gate_announcements=1'])
1455    subprocess.call(['iw', 'dev', dev[1].ifname, 'set', 'mesh_param',
1456                     'mesh_gate_announcements=1'])
1457
1458    # wait for gate announcement frames
1459    time.sleep(1)
1460
1461    # data frame from dev2 -> external sta should be sent to both gates
1462    dev[2].request("DATA_TEST_CONFIG 1")
1463    dev[2].request("DATA_TEST_TX {} {} 0".format(external_sta, addr2))
1464    dev[2].request("DATA_TEST_CONFIG 0")
1465
1466    capfile = os.path.join(p['logdir'], "hwsim0.pcapng")
1467    filt = "wlan.sa==%s && wlan_mgt.fixed.mesh_addr5==%s" % (addr2,
1468                                                             external_sta)
1469    time.sleep(4)
1470    for i in range(5):
1471        da = run_tshark(capfile, filt, ["wlan.da"])
1472        if addr0 in da and addr1 in da:
1473            logger.debug("Frames seen in tshark iteration %d" % i)
1474            break
1475        time.sleep(0.5)
1476
1477    if addr0 not in da and addr1 not in da:
1478        filt = "wlan.sa==%s" % addr2
1479        mesh = run_tshark(capfile, filt, ["wlan.mesh.control_field"])
1480        if "1" not in mesh:
1481            # Wireshark regression in mesh control field parsing:
1482            # https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=15521
1483            raise HwsimSkip("tshark bug 15521")
1484    if addr0 not in da:
1485        raise Exception("Frame to gate %s not observed" % addr0)
1486    if addr1 not in da:
1487        raise Exception("Frame to gate %s not observed" % addr1)
1488
1489def test_wpas_mesh_pmksa_caching(dev, apdev):
1490    """Secure mesh network and PMKSA caching"""
1491    check_mesh_support(dev[0], secure=True)
1492    dev[0].request("SET sae_groups ")
1493    id = add_mesh_secure_net(dev[0])
1494    dev[0].mesh_group_add(id)
1495
1496    dev[1].request("SET sae_groups ")
1497    id = add_mesh_secure_net(dev[1])
1498    dev[1].mesh_group_add(id)
1499
1500    check_mesh_joined_connected(dev)
1501
1502    addr0 = dev[0].own_addr()
1503    addr1 = dev[1].own_addr()
1504    pmksa0 = dev[0].get_pmksa(addr1)
1505    pmksa1 = dev[1].get_pmksa(addr0)
1506    if pmksa0 is None or pmksa1 is None:
1507        raise Exception("No PMKSA cache entry created")
1508    if pmksa0['pmkid'] != pmksa1['pmkid']:
1509        raise Exception("PMKID mismatch in PMKSA cache entries")
1510
1511    if "OK" not in dev[0].request("MESH_PEER_REMOVE " + addr1):
1512        raise Exception("Failed to remove peer")
1513    pmksa0b = dev[0].get_pmksa(addr1)
1514    if pmksa0b is None:
1515        raise Exception("PMKSA cache entry not maintained")
1516    time.sleep(0.1)
1517
1518    if "FAIL" not in dev[0].request("MESH_PEER_ADD " + addr1):
1519        raise Exception("MESH_PEER_ADD unexpectedly succeeded in no_auto_peer=0 case")
1520
1521def test_wpas_mesh_pmksa_caching2(dev, apdev):
1522    """Secure mesh network and PMKSA caching with no_auto_peer=1"""
1523    check_mesh_support(dev[0], secure=True)
1524    addr0 = dev[0].own_addr()
1525    addr1 = dev[1].own_addr()
1526    dev[0].request("SET sae_groups ")
1527    id = add_mesh_secure_net(dev[0])
1528    dev[0].set_network(id, "no_auto_peer", "1")
1529    dev[0].mesh_group_add(id)
1530
1531    dev[1].request("SET sae_groups ")
1532    id = add_mesh_secure_net(dev[1])
1533    dev[1].set_network(id, "no_auto_peer", "1")
1534    dev[1].mesh_group_add(id)
1535
1536    check_mesh_joined2(dev)
1537
1538    # Check for peer connected
1539    ev = dev[0].wait_event(["will not initiate new peer link"], timeout=10)
1540    if ev is None:
1541        raise Exception("Missing no-initiate message")
1542    if "OK" not in dev[0].request("MESH_PEER_ADD " + addr1):
1543        raise Exception("MESH_PEER_ADD failed")
1544    check_mesh_connected2(dev)
1545
1546    pmksa0 = dev[0].get_pmksa(addr1)
1547    pmksa1 = dev[1].get_pmksa(addr0)
1548    if pmksa0 is None or pmksa1 is None:
1549        raise Exception("No PMKSA cache entry created")
1550    if pmksa0['pmkid'] != pmksa1['pmkid']:
1551        raise Exception("PMKID mismatch in PMKSA cache entries")
1552
1553    if "OK" not in dev[0].request("MESH_PEER_REMOVE " + addr1):
1554        raise Exception("Failed to remove peer")
1555    pmksa0b = dev[0].get_pmksa(addr1)
1556    if pmksa0b is None:
1557        raise Exception("PMKSA cache entry not maintained")
1558
1559    ev = dev[0].wait_event(["will not initiate new peer link"], timeout=10)
1560    if ev is None:
1561        raise Exception("Missing no-initiate message (2)")
1562    if "OK" not in dev[0].request("MESH_PEER_ADD " + addr1):
1563        raise Exception("MESH_PEER_ADD failed (2)")
1564    check_mesh_connected2(dev)
1565
1566    pmksa0c = dev[0].get_pmksa(addr1)
1567    pmksa1c = dev[1].get_pmksa(addr0)
1568    if pmksa0c is None or pmksa1c is None:
1569        raise Exception("No PMKSA cache entry created (2)")
1570    if pmksa0c['pmkid'] != pmksa1c['pmkid']:
1571        raise Exception("PMKID mismatch in PMKSA cache entries")
1572    if pmksa0['pmkid'] != pmksa0c['pmkid']:
1573        raise Exception("PMKID changed")
1574
1575    hwsim_utils.test_connectivity(dev[0], dev[1])
1576
1577def test_wpas_mesh_pmksa_caching_no_match(dev, apdev):
1578    """Secure mesh network and PMKSA caching with no PMKID match"""
1579    check_mesh_support(dev[0], secure=True)
1580    addr0 = dev[0].own_addr()
1581    addr1 = dev[1].own_addr()
1582    dev[0].request("SET sae_groups ")
1583    id = add_mesh_secure_net(dev[0])
1584    dev[0].set_network(id, "no_auto_peer", "1")
1585    dev[0].mesh_group_add(id)
1586
1587    dev[1].request("SET sae_groups ")
1588    id = add_mesh_secure_net(dev[1])
1589    dev[1].set_network(id, "no_auto_peer", "1")
1590    dev[1].mesh_group_add(id)
1591
1592    check_mesh_joined2(dev)
1593
1594    # Check for peer connected
1595    ev = dev[0].wait_event(["will not initiate new peer link"], timeout=10)
1596    if ev is None:
1597        raise Exception("Missing no-initiate message")
1598    if "OK" not in dev[0].request("MESH_PEER_ADD " + addr1):
1599        raise Exception("MESH_PEER_ADD failed")
1600    check_mesh_connected2(dev)
1601
1602    pmksa0 = dev[0].get_pmksa(addr1)
1603    pmksa1 = dev[1].get_pmksa(addr0)
1604    if pmksa0 is None or pmksa1 is None:
1605        raise Exception("No PMKSA cache entry created")
1606    if pmksa0['pmkid'] != pmksa1['pmkid']:
1607        raise Exception("PMKID mismatch in PMKSA cache entries")
1608
1609    if "OK" not in dev[0].request("MESH_PEER_REMOVE " + addr1):
1610        raise Exception("Failed to remove peer")
1611
1612    if "OK" not in dev[1].request("PMKSA_FLUSH"):
1613        raise Exception("Failed to flush PMKSA cache")
1614
1615    ev = dev[0].wait_event(["will not initiate new peer link"], timeout=10)
1616    if ev is None:
1617        raise Exception("Missing no-initiate message (2)")
1618    if "OK" not in dev[0].request("MESH_PEER_ADD " + addr1):
1619        raise Exception("MESH_PEER_ADD failed (2)")
1620    check_mesh_connected2(dev)
1621
1622    pmksa0c = dev[0].get_pmksa(addr1)
1623    pmksa1c = dev[1].get_pmksa(addr0)
1624    if pmksa0c is None or pmksa1c is None:
1625        raise Exception("No PMKSA cache entry created (2)")
1626    if pmksa0c['pmkid'] != pmksa1c['pmkid']:
1627        raise Exception("PMKID mismatch in PMKSA cache entries")
1628    if pmksa0['pmkid'] == pmksa0c['pmkid']:
1629        raise Exception("PMKID did not change")
1630
1631    hwsim_utils.test_connectivity(dev[0], dev[1])
1632
1633def test_mesh_pmksa_caching_oom(dev, apdev):
1634    """Secure mesh network and PMKSA caching failing due to OOM"""
1635    check_mesh_support(dev[0], secure=True)
1636    addr0 = dev[0].own_addr()
1637    addr1 = dev[1].own_addr()
1638    dev[0].request("SET sae_groups ")
1639    id = add_mesh_secure_net(dev[0])
1640    dev[0].set_network(id, "no_auto_peer", "1")
1641    dev[0].mesh_group_add(id)
1642
1643    dev[1].request("SET sae_groups ")
1644    id = add_mesh_secure_net(dev[1])
1645    dev[1].set_network(id, "no_auto_peer", "1")
1646    dev[1].mesh_group_add(id)
1647
1648    check_mesh_joined2(dev)
1649
1650    # Check for peer connected
1651    ev = dev[0].wait_event(["will not initiate new peer link"], timeout=10)
1652    if ev is None:
1653        raise Exception("Missing no-initiate message")
1654    if "OK" not in dev[0].request("MESH_PEER_ADD " + addr1):
1655        raise Exception("MESH_PEER_ADD failed")
1656    check_mesh_connected2(dev)
1657
1658    if "OK" not in dev[0].request("MESH_PEER_REMOVE " + addr1):
1659        raise Exception("Failed to remove peer")
1660    pmksa0b = dev[0].get_pmksa(addr1)
1661    if pmksa0b is None:
1662        raise Exception("PMKSA cache entry not maintained")
1663
1664    ev = dev[0].wait_event(["will not initiate new peer link"], timeout=10)
1665    if ev is None:
1666        raise Exception("Missing no-initiate message (2)")
1667
1668    with alloc_fail(dev[0], 1, "wpa_auth_sta_init;mesh_rsn_auth_sae_sta"):
1669        if "OK" not in dev[0].request("MESH_PEER_ADD " + addr1):
1670            raise Exception("MESH_PEER_ADD failed (2)")
1671        wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
1672
1673def test_wpas_mesh_pmksa_caching_ext(dev, apdev):
1674    """Secure mesh network and PMKSA caching and external storage"""
1675    check_mesh_support(dev[0], secure=True)
1676    dev[0].request("SET sae_groups ")
1677    id = add_mesh_secure_net(dev[0])
1678    dev[0].mesh_group_add(id)
1679
1680    dev[1].request("SET sae_groups ")
1681    id = add_mesh_secure_net(dev[1])
1682    dev[1].mesh_group_add(id)
1683
1684    check_mesh_joined_connected(dev)
1685    dev[0].dump_monitor()
1686    dev[1].dump_monitor()
1687
1688    addr0 = dev[0].own_addr()
1689    addr1 = dev[1].own_addr()
1690    pmksa0 = dev[0].get_pmksa(addr1)
1691    pmksa1 = dev[1].get_pmksa(addr0)
1692    if pmksa0 is None or pmksa1 is None:
1693        raise Exception("No PMKSA cache entry created")
1694    if pmksa0['pmkid'] != pmksa1['pmkid']:
1695        raise Exception("PMKID mismatch in PMKSA cache entries")
1696
1697    res1 = dev[1].request("MESH_PMKSA_GET any")
1698    res2 = dev[1].request("MESH_PMKSA_GET " + addr0)
1699    logger.info("MESH_PMKSA_GET: " + res1)
1700    if "UNKNOWN COMMAND" in res1:
1701        raise HwsimSkip("MESH_PMKSA_GET not supported in the build")
1702    logger.info("MESH_PMKSA_GET: " + res2)
1703    if pmksa0['pmkid'] not in res1:
1704        raise Exception("PMKID not included in PMKSA entry")
1705    if res1 != res2:
1706        raise Exception("Unexpected difference in MESH_PMKSA_GET output")
1707
1708    dev[1].mesh_group_remove()
1709    check_mesh_group_removed(dev[1])
1710    check_mesh_peer_disconnected(dev[0])
1711    dev[0].dump_monitor()
1712    dev[1].dump_monitor()
1713    res = dev[1].get_pmksa(addr0)
1714    if res is not None:
1715        raise Exception("Unexpected PMKSA cache entry remaining")
1716
1717    time.sleep(0.1)
1718    if "OK" not in dev[1].request("MESH_PMKSA_ADD " + res2):
1719        raise Exception("MESH_PMKSA_ADD failed")
1720    dev[1].mesh_group_add(id)
1721    check_mesh_group_added(dev[1])
1722    check_mesh_peer_connected(dev[1])
1723    check_mesh_peer_connected(dev[0])
1724    time.sleep(0.1)
1725    dev[0].dump_monitor()
1726    dev[1].dump_monitor()
1727    pmksa1b = dev[1].get_pmksa(addr0)
1728    if pmksa1b is None:
1729        raise Exception("No PMKSA cache entry created after external storage restore")
1730    if pmksa1['pmkid'] != pmksa1b['pmkid']:
1731        raise Exception("PMKID mismatch in PMKSA cache entries after external storage restore")
1732
1733    res3 = dev[1].request("MESH_PMKSA_GET " + addr0)
1734    logger.info("MESH_PMKSA_GET: " + res3)
1735    # Require other fields to be equal, but allow remaining time to be smaller.
1736    r2 = res2.split()
1737    r3 = res3.split()
1738    if r2[0] != r3[0] or r2[1] != r3[1] or r2[2] != r3[2] or \
1739       int(r3[3]) > int(r2[3]):
1740        raise Exception("Unexpected change in MESH_PMKSA_GET result")
1741
1742    hwsim_utils.test_connectivity(dev[0], dev[1])
1743
1744    res = dev[1].request("MESH_PMKSA_GET foo")
1745    if "FAIL" not in res:
1746        raise Exception("Invalid MESH_PMKSA_GET accepted")
1747
1748    dev[1].mesh_group_remove()
1749    check_mesh_group_removed(dev[1])
1750    dev[0].dump_monitor()
1751    dev[1].dump_monitor()
1752    dev[1].request("REMOVE_NETWORK all")
1753    res = dev[1].request("MESH_PMKSA_GET any")
1754    if "FAIL" not in res:
1755        raise Exception("MESH_PMKSA_GET accepted when not in mesh")
1756
1757    tests = ["foo",
1758             "02:02:02:02:02:02",
1759             "02:02:02:02:02:02 q",
1760             "02:02:02:02:02:02 c3d51a7ccfca0c6d5287291a7169d79b",
1761             "02:02:02:02:02:02 c3d51a7ccfca0c6d5287291a7169d79b q",
1762             "02:02:02:02:02:02 c3d51a7ccfca0c6d5287291a7169d79b 1bed4fa22ece7997ca1bdc8b829019fe63acac91cba3405522c24c91f7cfb49f",
1763             "02:02:02:02:02:02 c3d51a7ccfca0c6d5287291a7169d79b 1bed4fa22ece7997ca1bdc8b829019fe63acac91cba3405522c24c91f7cfb49f q"]
1764    for t in tests:
1765        if "FAIL" not in dev[1].request("MESH_PMKSA_ADD " + t):
1766            raise Exception("Invalid MESH_PMKSA_ADD accepted")
1767
1768def test_mesh_oom(dev, apdev):
1769    """Mesh network setup failing due to OOM"""
1770    check_mesh_support(dev[0], secure=True)
1771    dev[0].request("SET sae_groups ")
1772
1773    with alloc_fail(dev[0], 1, "mesh_config_create"):
1774        add_open_mesh_network(dev[0])
1775        ev = dev[0].wait_event(["Failed to init mesh"])
1776        if ev is None:
1777            raise Exception("Init failure not reported")
1778
1779    with alloc_fail(dev[0], 2, "=wpa_supplicant_mesh_init"):
1780        add_open_mesh_network(dev[0], basic_rates="60 120 240")
1781        ev = dev[0].wait_event(["Failed to init mesh"])
1782        if ev is None:
1783            raise Exception("Init failure not reported")
1784
1785    for i in range(1, 66):
1786        dev[0].dump_monitor()
1787        logger.info("Test instance %d" % i)
1788        try:
1789            with alloc_fail(dev[0], i, "wpa_supplicant_mesh_init"):
1790                add_open_mesh_network(dev[0])
1791                wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
1792                ev = dev[0].wait_event(["Failed to init mesh",
1793                                        "MESH-GROUP-STARTED"])
1794                if ev is None:
1795                    raise Exception("Init failure not reported")
1796        except Exception as e:
1797            if i < 15:
1798                raise
1799            logger.info("Ignore no-oom for i=%d" % i)
1800
1801    with alloc_fail(dev[0], 2, "=wpa_supplicant_mesh_init"):
1802        id = add_mesh_secure_net(dev[0])
1803        dev[0].mesh_group_add(id)
1804        ev = dev[0].wait_event(["Failed to init mesh"])
1805        if ev is None:
1806            raise Exception("Init failure not reported")
1807
1808def test_mesh_add_interface_oom(dev):
1809    """wpa_supplicant mesh with dynamic interface addition failing"""
1810    check_mesh_support(dev[0])
1811    for i in range(1, 3):
1812        mesh = None
1813        try:
1814            with alloc_fail(dev[0], i, "wpas_mesh_add_interface"):
1815                mesh = dev[0].request("MESH_INTERFACE_ADD").strip()
1816        finally:
1817            if mesh and mesh != "FAIL":
1818                dev[0].request("MESH_GROUP_REMOVE " + mesh)
1819
1820def test_mesh_scan_oom(dev):
1821    """wpa_supplicant mesh scan results and OOM"""
1822    check_mesh_support(dev[0])
1823    add_open_mesh_network(dev[0])
1824    check_mesh_group_added(dev[0])
1825    for i in range(5):
1826        dev[1].scan(freq="2412")
1827        res = dev[1].request("SCAN_RESULTS")
1828        if "[MESH]" in res:
1829            break
1830    for r in res.splitlines():
1831        if "[MESH]" in r:
1832            break
1833    bssid = r.split('\t')[0]
1834
1835    bss = dev[1].get_bss(bssid)
1836    if bss is None:
1837        raise Exception("Could not get BSS entry for mesh")
1838
1839    for i in range(1, 3):
1840        with alloc_fail(dev[1], i, "mesh_attr_text"):
1841            bss = dev[1].get_bss(bssid)
1842            if bss and "mesh_id" in bss:
1843                raise Exception("Unexpected BSS result during OOM")
1844
1845def test_mesh_drv_fail(dev, apdev):
1846    """Mesh network setup failing due to driver command failure"""
1847    check_mesh_support(dev[0], secure=True)
1848    dev[0].request("SET sae_groups ")
1849
1850    with fail_test(dev[0], 1, "nl80211_join_mesh"):
1851        add_open_mesh_network(dev[0])
1852        ev = dev[0].wait_event(["mesh join error"])
1853        if ev is None:
1854            raise Exception("Join failure not reported")
1855
1856    dev[0].dump_monitor()
1857    with fail_test(dev[0], 1, "wpa_driver_nl80211_if_add"):
1858        if "FAIL" not in dev[0].request("MESH_INTERFACE_ADD").strip():
1859            raise Exception("Interface added unexpectedly")
1860
1861    dev[0].dump_monitor()
1862    with fail_test(dev[0], 1, "wpa_driver_nl80211_init_mesh"):
1863        add_open_mesh_network(dev[0])
1864        ev = dev[0].wait_event(["Could not join mesh"])
1865        if ev is None:
1866            raise Exception("Join failure not reported")
1867
1868def test_mesh_sae_groups_invalid(dev, apdev):
1869    """Mesh with invalid SAE group configuration"""
1870    check_mesh_support(dev[0], secure=True)
1871
1872    dev[0].request("SET sae_groups 20")
1873    id = add_mesh_secure_net(dev[0])
1874    dev[0].mesh_group_add(id)
1875
1876    dev[1].request("SET sae_groups 123 122 121")
1877    id = add_mesh_secure_net(dev[1])
1878    dev[1].mesh_group_add(id)
1879
1880    check_mesh_joined2(dev)
1881
1882    ev = dev[0].wait_event(["new peer notification"], timeout=10)
1883    if ev is None:
1884        raise Exception("dev[0] did not see peer")
1885    ev = dev[1].wait_event(["new peer notification"], timeout=10)
1886    if ev is None:
1887        raise Exception("dev[1] did not see peer")
1888
1889    ev = dev[0].wait_event(["MESH-PEER-CONNECTED"], timeout=0.1)
1890    if ev is not None:
1891        raise Exception("Unexpected connection(0)")
1892
1893    ev = dev[1].wait_event(["MESH-PEER-CONNECTED"], timeout=0.01)
1894    if ev is not None:
1895        raise Exception("Unexpected connection(1)")
1896
1897    # Additional coverage in mesh_rsn_sae_group() with non-zero
1898    # wpa_s->mesh_rsn->sae_group_index.
1899    dev[0].dump_monitor()
1900    dev[1].dump_monitor()
1901    dev[2].request("SET sae_groups ")
1902    id = add_mesh_secure_net(dev[2])
1903    dev[2].mesh_group_add(id)
1904    check_mesh_group_added(dev[2])
1905    check_mesh_peer_connected(dev[0])
1906    check_mesh_peer_connected(dev[2])
1907    ev = dev[1].wait_event(["new peer notification"], timeout=10)
1908    if ev is None:
1909        raise Exception("dev[1] did not see peer(2)")
1910    dev[0].dump_monitor()
1911    dev[1].dump_monitor()
1912    dev[2].dump_monitor()
1913
1914    dev[0].request("SET sae_groups ")
1915    dev[1].request("SET sae_groups ")
1916    dev[2].request("SET sae_groups ")
1917
1918def test_mesh_sae_failure(dev, apdev):
1919    """Mesh and local SAE failures"""
1920    check_mesh_support(dev[0], secure=True)
1921
1922    dev[0].request("SET sae_groups ")
1923    dev[1].request("SET sae_groups ")
1924
1925    funcs = [(1, "=mesh_rsn_auth_sae_sta", True),
1926             (1, "mesh_rsn_build_sae_commit;mesh_rsn_auth_sae_sta", False),
1927             (1, "auth_sae_init_committed;mesh_rsn_auth_sae_sta", True),
1928             (1, "=mesh_rsn_protect_frame", True),
1929             (2, "=mesh_rsn_protect_frame", True),
1930             (1, "aes_siv_encrypt;mesh_rsn_protect_frame", True),
1931             (1, "=mesh_rsn_process_ampe", True),
1932             (1, "aes_siv_decrypt;mesh_rsn_process_ampe", True)]
1933    for count, func, success in funcs:
1934        id = add_mesh_secure_net(dev[0])
1935        dev[0].mesh_group_add(id)
1936
1937        with alloc_fail(dev[1], count, func):
1938            id = add_mesh_secure_net(dev[1])
1939            dev[1].mesh_group_add(id)
1940            check_mesh_joined2(dev)
1941            if success:
1942                # retry is expected to work
1943                check_mesh_connected2(dev)
1944            else:
1945                wait_fail_trigger(dev[1], "GET_ALLOC_FAIL")
1946        dev[0].mesh_group_remove()
1947        dev[1].mesh_group_remove()
1948        check_mesh_group_removed(dev[0])
1949        check_mesh_group_removed(dev[1])
1950
1951def test_mesh_failure(dev, apdev):
1952    """Mesh and local failures"""
1953    check_mesh_support(dev[0])
1954
1955    funcs = [(1, "ap_sta_add;mesh_mpm_add_peer", True),
1956             (1, "wpabuf_alloc;mesh_mpm_send_plink_action", True)]
1957    for count, func, success in funcs:
1958        add_open_mesh_network(dev[0])
1959
1960        with alloc_fail(dev[1], count, func):
1961            add_open_mesh_network(dev[1])
1962            check_mesh_joined2(dev)
1963            if success:
1964                # retry is expected to work
1965                check_mesh_connected2(dev)
1966            else:
1967                wait_fail_trigger(dev[1], "GET_ALLOC_FAIL")
1968        dev[0].mesh_group_remove()
1969        dev[1].mesh_group_remove()
1970        check_mesh_group_removed(dev[0])
1971        check_mesh_group_removed(dev[1])
1972
1973    funcs = [(1, "mesh_mpm_init_link", True)]
1974    for count, func, success in funcs:
1975        add_open_mesh_network(dev[0])
1976
1977        with fail_test(dev[1], count, func):
1978            add_open_mesh_network(dev[1])
1979            check_mesh_joined2(dev)
1980            if success:
1981                # retry is expected to work
1982                check_mesh_connected2(dev)
1983            else:
1984                wait_fail_trigger(dev[1], "GET_FAIL")
1985        dev[0].mesh_group_remove()
1986        dev[1].mesh_group_remove()
1987        check_mesh_group_removed(dev[0])
1988        check_mesh_group_removed(dev[1])
1989
1990def test_mesh_invalid_frequency(dev, apdev):
1991    """Mesh and invalid frequency configuration"""
1992    check_mesh_support(dev[0])
1993    add_open_mesh_network(dev[0], freq=None)
1994    ev = dev[0].wait_event(["MESH-GROUP-STARTED",
1995                            "Could not join mesh"])
1996    if ev is None or "Could not join mesh" not in ev:
1997        raise Exception("Mesh join failure not reported")
1998    dev[0].request("REMOVE_NETWORK all")
1999
2000    add_open_mesh_network(dev[0], freq="2413")
2001    ev = dev[0].wait_event(["MESH-GROUP-STARTED",
2002                            "Could not join mesh"])
2003    if ev is None or "Could not join mesh" not in ev:
2004        raise Exception("Mesh join failure not reported")
2005
2006def test_mesh_default_beacon_int(dev, apdev):
2007    """Mesh and default beacon interval"""
2008    check_mesh_support(dev[0])
2009    try:
2010        dev[0].request("SET beacon_int 200")
2011        add_open_mesh_network(dev[0])
2012        check_mesh_group_added(dev[0])
2013    finally:
2014        dev[0].request("SET beacon_int 0")
2015
2016def test_mesh_scan_parse_error(dev, apdev):
2017    """Mesh scan element parse error"""
2018    check_mesh_support(dev[0])
2019    params = {"ssid": "open",
2020              "beacon_int": "2000"}
2021    hapd = hostapd.add_ap(apdev[0], params)
2022    bssid = apdev[0]['bssid']
2023    hapd.set('vendor_elements', 'dd0201')
2024    for i in range(10):
2025        dev[0].scan(freq=2412)
2026        if bssid in dev[0].request("SCAN_RESULTS"):
2027            break
2028    # This will fail in IE parsing due to the truncated IE in the Probe
2029    # Response frame.
2030    bss = dev[0].request("BSS " + bssid)
2031
2032def test_mesh_missing_mic(dev, apdev):
2033    """Secure mesh network and missing MIC"""
2034    check_mesh_support(dev[0], secure=True)
2035
2036    dev[0].request("SET ext_mgmt_frame_handling 1")
2037    dev[0].request("SET sae_groups ")
2038    id = add_mesh_secure_net(dev[0])
2039    dev[0].mesh_group_add(id)
2040
2041    dev[1].request("SET sae_groups ")
2042    id = add_mesh_secure_net(dev[1])
2043    dev[1].mesh_group_add(id)
2044
2045    check_mesh_joined2(dev)
2046
2047    count = 0
2048    remove_mic = True
2049    while True:
2050        count += 1
2051        if count > 15:
2052            raise Exception("Did not see Action frames")
2053        rx_msg = dev[0].mgmt_rx()
2054        if rx_msg is None:
2055            ev = dev[1].wait_event(["MESH-PEER-CONNECTED"], timeout=0.01)
2056            if ev:
2057                break
2058            raise Exception("MGMT-RX timeout")
2059        if rx_msg['subtype'] == 13:
2060            payload = rx_msg['payload']
2061            frame = rx_msg['frame']
2062            (categ, action) = struct.unpack('BB', payload[0:2])
2063            if categ == 15 and action == 1 and remove_mic:
2064                # Mesh Peering Open
2065                pos = frame.find(b'\x8c\x10')
2066                if not pos:
2067                    raise Exception("Could not find MIC element")
2068                logger.info("Found MIC at %d" % pos)
2069                # Remove MIC
2070                rx_msg['frame'] = frame[0:pos]
2071                remove_mic = False
2072        if "OK" not in dev[0].request("MGMT_RX_PROCESS freq={} datarate={} ssi_signal={} frame={}".format(
2073            rx_msg['freq'], rx_msg['datarate'], rx_msg['ssi_signal'], binascii.hexlify(rx_msg['frame']).decode())):
2074            raise Exception("MGMT_RX_PROCESS failed")
2075        ev = dev[1].wait_event(["MESH-PEER-CONNECTED"], timeout=0.01)
2076        if ev:
2077            break
2078
2079def test_mesh_pmkid_mismatch(dev, apdev):
2080    """Secure mesh network and PMKID mismatch"""
2081    check_mesh_support(dev[0], secure=True)
2082    addr0 = dev[0].own_addr()
2083    addr1 = dev[1].own_addr()
2084    dev[0].request("SET sae_groups ")
2085    id = add_mesh_secure_net(dev[0])
2086    dev[0].set_network(id, "no_auto_peer", "1")
2087    dev[0].mesh_group_add(id)
2088
2089    dev[1].request("SET sae_groups ")
2090    id = add_mesh_secure_net(dev[1])
2091    dev[1].set_network(id, "no_auto_peer", "1")
2092    dev[1].mesh_group_add(id)
2093
2094    check_mesh_joined2(dev)
2095
2096    # Check for peer connected
2097    ev = dev[0].wait_event(["will not initiate new peer link"], timeout=10)
2098    if ev is None:
2099        raise Exception("Missing no-initiate message")
2100    if "OK" not in dev[0].request("MESH_PEER_ADD " + addr1):
2101        raise Exception("MESH_PEER_ADD failed")
2102    check_mesh_connected2(dev)
2103
2104    if "OK" not in dev[0].request("MESH_PEER_REMOVE " + addr1):
2105        raise Exception("Failed to remove peer")
2106
2107    ev = dev[0].wait_event(["will not initiate new peer link"], timeout=10)
2108    if ev is None:
2109        raise Exception("Missing no-initiate message (2)")
2110    dev[0].dump_monitor()
2111    dev[1].dump_monitor()
2112    dev[0].request("SET ext_mgmt_frame_handling 1")
2113    if "OK" not in dev[0].request("MESH_PEER_ADD " + addr1):
2114        raise Exception("MESH_PEER_ADD failed (2)")
2115
2116    count = 0
2117    break_pmkid = True
2118    while True:
2119        count += 1
2120        if count > 50:
2121            raise Exception("Did not see Action frames")
2122        rx_msg = dev[0].mgmt_rx()
2123        if rx_msg is None:
2124            ev = dev[1].wait_event(["MESH-PEER-CONNECTED"], timeout=0.1)
2125            if ev:
2126                break
2127            raise Exception("MGMT-RX timeout")
2128        if rx_msg['subtype'] == 13:
2129            payload = rx_msg['payload']
2130            frame = rx_msg['frame']
2131            (categ, action) = struct.unpack('BB', payload[0:2])
2132            if categ == 15 and action == 1 and break_pmkid:
2133                # Mesh Peering Open
2134                pos = frame.find(b'\x75\x14')
2135                if not pos:
2136                    raise Exception("Could not find Mesh Peering Management element")
2137                logger.info("Found Mesh Peering Management element at %d" % pos)
2138                # Break PMKID to hit "Mesh RSN: Invalid PMKID (Chosen PMK did
2139                # not match calculated PMKID)"
2140                rx_msg['frame'] = frame[0:pos + 6] + b'\x00\x00\x00\x00' + frame[pos + 10:]
2141                break_pmkid = False
2142        if "OK" not in dev[0].request("MGMT_RX_PROCESS freq={} datarate={} ssi_signal={} frame={}".format(
2143            rx_msg['freq'], rx_msg['datarate'], rx_msg['ssi_signal'], binascii.hexlify(rx_msg['frame']).decode())):
2144            raise Exception("MGMT_RX_PROCESS failed")
2145        ev = dev[1].wait_event(["MESH-PEER-CONNECTED"], timeout=0.01)
2146        if ev:
2147            break
2148
2149def test_mesh_peering_proto(dev, apdev):
2150    """Mesh peering management protocol testing"""
2151    check_mesh_support(dev[0])
2152
2153    dev[0].request("SET ext_mgmt_frame_handling 1")
2154    add_open_mesh_network(dev[0], beacon_int=160)
2155    add_open_mesh_network(dev[1], beacon_int=160)
2156
2157    count = 0
2158    test = 1
2159    while True:
2160        count += 1
2161        if count > 50:
2162            raise Exception("Did not see Action frames")
2163        rx_msg = dev[0].mgmt_rx()
2164        if rx_msg is None:
2165            ev = dev[1].wait_event(["MESH-PEER-CONNECTED"], timeout=0.01)
2166            if ev:
2167                break
2168            raise Exception("MGMT-RX timeout")
2169        if rx_msg['subtype'] == 13:
2170            payload = rx_msg['payload']
2171            frame = rx_msg['frame']
2172            (categ, action) = struct.unpack('BB', payload[0:2])
2173            if categ == 15 and action == 1 and test == 1:
2174                # Mesh Peering Open
2175                pos = frame.find(b'\x75\x04')
2176                if not pos:
2177                    raise Exception("Could not find Mesh Peering Management element")
2178                logger.info("Found Mesh Peering Management element at %d" % pos)
2179                # Remove the element to hit
2180                # "MPM: No Mesh Peering Management element"
2181                rx_msg['frame'] = frame[0:pos]
2182                test += 1
2183            elif categ == 15 and action == 1 and test == 2:
2184                # Mesh Peering Open
2185                pos = frame.find(b'\x72\x0e')
2186                if not pos:
2187                    raise Exception("Could not find Mesh ID element")
2188                logger.info("Found Mesh ID element at %d" % pos)
2189                # Remove the element to hit
2190                # "MPM: No Mesh ID or Mesh Configuration element"
2191                rx_msg['frame'] = frame[0:pos] + frame[pos + 16:]
2192                test += 1
2193            elif categ == 15 and action == 1 and test == 3:
2194                # Mesh Peering Open
2195                pos = frame.find(b'\x72\x0e')
2196                if not pos:
2197                    raise Exception("Could not find Mesh ID element")
2198                logger.info("Found Mesh ID element at %d" % pos)
2199                # Replace Mesh ID to hit "MPM: Mesh ID or Mesh Configuration
2200                # element do not match local MBSS"
2201                rx_msg['frame'] = frame[0:pos] + b'\x72\x0etest-test-test' + frame[pos + 16:]
2202                test += 1
2203            elif categ == 15 and action == 1 and test == 4:
2204                # Mesh Peering Open
2205                # Remove IEs to hit
2206                # "MPM: Ignore too short action frame 1 ie_len 0"
2207                rx_msg['frame'] = frame[0:26]
2208                test += 1
2209            elif categ == 15 and action == 1 and test == 5:
2210                # Mesh Peering Open
2211                # Truncate IEs to hit
2212                # "MPM: Failed to parse PLINK IEs"
2213                rx_msg['frame'] = frame[0:30]
2214                test += 1
2215            elif categ == 15 and action == 1 and test == 6:
2216                # Mesh Peering Open
2217                pos = frame.find(b'\x75\x04')
2218                if not pos:
2219                    raise Exception("Could not find Mesh Peering Management element")
2220                logger.info("Found Mesh Peering Management element at %d" % pos)
2221                # Truncate the element to hit
2222                # "MPM: Invalid peer mgmt ie" and
2223                # "MPM: Mesh parsing rejected frame"
2224                rx_msg['frame'] = frame[0:pos] + b'\x75\x00\x00\x00' + frame[pos + 6:]
2225                test += 1
2226        if "OK" not in dev[0].request("MGMT_RX_PROCESS freq={} datarate={} ssi_signal={} frame={}".format(
2227            rx_msg['freq'], rx_msg['datarate'], rx_msg['ssi_signal'], binascii.hexlify(rx_msg['frame']).decode())):
2228            raise Exception("MGMT_RX_PROCESS failed")
2229        ev = dev[1].wait_event(["MESH-PEER-CONNECTED"], timeout=0.01)
2230        if ev:
2231            break
2232
2233    if test != 7:
2234        raise Exception("Not all test frames completed")
2235
2236def test_mesh_mpm_init_proto(dev, apdev):
2237    """Mesh peering management protocol testing for peer addition"""
2238    check_mesh_support(dev[0])
2239    add_open_mesh_network(dev[0])
2240    check_mesh_group_added(dev[0])
2241    dev[0].dump_monitor()
2242
2243    dev[0].request("SET ext_mgmt_frame_handling 1")
2244
2245    addr = "020000000100"
2246    hdr = "d000ac00020000000000" + addr + addr + "1000"
2247    fixed = "0f010000"
2248    supp_rates = "010802040b168c129824"
2249    ext_supp_rates = "3204b048606c"
2250    mesh_id = "720e777061732d6d6573682d6f70656e"
2251    mesh_conf = "710701010001000009"
2252    mpm = "75040000079d"
2253    ht_capab = "2d1a7c001bffff000000000000000000000100000000000000000000"
2254    ht_oper = "3d160b000000000000000000000000000000000000000000"
2255
2256    dev[0].request("NOTE no supported rates")
2257    frame = hdr + fixed + ext_supp_rates + mesh_id + mesh_conf + mpm + ht_capab + ht_oper
2258    if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % frame):
2259        raise Exception("MGMT_RX_PROCESS failed")
2260
2261    dev[0].request("NOTE Invalid supported rates element length 33+0")
2262    long_supp_rates = "012100112233445566778899aabbccddeeff00112233445566778899aabbccddeeff00"
2263    frame = hdr + fixed + long_supp_rates + mesh_id + mesh_conf + mpm + ht_capab + ht_oper
2264    if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % frame):
2265        raise Exception("MGMT_RX_PROCESS failed")
2266
2267    dev[0].request("NOTE Too short mesh config")
2268    short_mesh_conf = "710401010001"
2269    frame = hdr + fixed + supp_rates + mesh_id + short_mesh_conf + mpm + ht_capab + ht_oper
2270    if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % frame):
2271        raise Exception("MGMT_RX_PROCESS failed")
2272
2273    dev[0].request("NOTE Add STA failure")
2274    frame = hdr + fixed + supp_rates + ext_supp_rates + mesh_id + mesh_conf + mpm + ht_capab + ht_oper
2275    with fail_test(dev[0], 1, "wpa_driver_nl80211_sta_add"):
2276        if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % frame):
2277            raise Exception("MGMT_RX_PROCESS failed")
2278
2279    dev[0].request("NOTE Send Action failure")
2280    with fail_test(dev[0], 1, "driver_nl80211_send_action"):
2281        if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % frame):
2282            raise Exception("MGMT_RX_PROCESS failed")
2283
2284    dev[0].request("NOTE Set STA failure")
2285    addr = "020000000101"
2286    hdr = "d000ac00020000000000" + addr + addr + "1000"
2287    frame = hdr + fixed + supp_rates + ext_supp_rates + mesh_id + mesh_conf + mpm + ht_capab + ht_oper
2288    with fail_test(dev[0], 2, "wpa_driver_nl80211_sta_add"):
2289        if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % frame):
2290            raise Exception("MGMT_RX_PROCESS failed")
2291
2292    dev[0].request("NOTE ap_sta_add OOM")
2293    addr = "020000000102"
2294    hdr = "d000ac00020000000000" + addr + addr + "1000"
2295    frame = hdr + fixed + supp_rates + ext_supp_rates + mesh_id + mesh_conf + mpm + ht_capab + ht_oper
2296    with alloc_fail(dev[0], 1, "ap_sta_add"):
2297        if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % frame):
2298            raise Exception("MGMT_RX_PROCESS failed")
2299
2300    dev[0].request("NOTE hostapd_get_aid() failure")
2301    addr = "020000000103"
2302    hdr = "d000ac00020000000000" + addr + addr + "1000"
2303    frame = hdr + fixed + supp_rates + ext_supp_rates + mesh_id + mesh_conf + mpm + ht_capab + ht_oper
2304    with fail_test(dev[0], 1, "hostapd_get_aid"):
2305        if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % frame):
2306            raise Exception("MGMT_RX_PROCESS failed")
2307
2308    if "OK" not in dev[0].request("MESH_PEER_REMOVE 02:00:00:00:01:00"):
2309        raise Exception("Failed to remove peer")
2310    if "FAIL" not in dev[0].request("MESH_PEER_REMOVE 02:00:00:00:01:02"):
2311        raise Exception("Unexpected MESH_PEER_REMOVE success")
2312    if "FAIL" not in dev[1].request("MESH_PEER_REMOVE 02:00:00:00:01:02"):
2313        raise Exception("Unexpected MESH_PEER_REMOVE success(2)")
2314    if "FAIL" not in dev[1].request("MESH_PEER_ADD 02:00:00:00:01:02"):
2315        raise Exception("Unexpected MESH_PEER_ADD success")
2316
2317def test_mesh_holding(dev, apdev):
2318    """Mesh MPM FSM and HOLDING state event OPN_ACPT"""
2319    check_mesh_support(dev[0])
2320    add_open_mesh_network(dev[0])
2321    add_open_mesh_network(dev[1])
2322    check_mesh_joined_connected(dev)
2323
2324    addr0 = dev[0].own_addr()
2325    addr1 = dev[1].own_addr()
2326
2327    dev[0].request("SET ext_mgmt_frame_handling 1")
2328    if "OK" not in dev[0].request("MESH_PEER_REMOVE " + addr1):
2329        raise Exception("Failed to remove peer")
2330
2331    rx_msg = dev[0].mgmt_rx()
2332    if rx_msg is None:
2333        raise Exception("MGMT-RX timeout")
2334    if rx_msg['subtype'] != 13:
2335        raise Exception("Unexpected management frame")
2336    payload = rx_msg['payload']
2337    (categ, action) = struct.unpack('BB', payload[0:2])
2338    if categ != 0x0f or action != 0x03:
2339        raise Exception("Did not see Mesh Peering Close")
2340
2341    peer_lid = binascii.hexlify(payload[-6:-4]).decode()
2342    my_lid = binascii.hexlify(payload[-4:-2]).decode()
2343
2344    # Drop Mesh Peering Close and instead, process an unexpected Mesh Peering
2345    # Open to trigger transmission of another Mesh Peering Close in the HOLDING
2346    # state based on an OPN_ACPT event.
2347
2348    dst = addr0.replace(':', '')
2349    src = addr1.replace(':', '')
2350    hdr = "d000ac00" + dst + src + src + "1000"
2351    fixed = "0f010000"
2352    supp_rates = "010802040b168c129824"
2353    ext_supp_rates = "3204b048606c"
2354    mesh_id = "720e777061732d6d6573682d6f70656e"
2355    mesh_conf = "710701010001000009"
2356    mpm = "7504" + my_lid + peer_lid
2357    ht_capab = "2d1a7c001bffff000000000000000000000100000000000000000000"
2358    ht_oper = "3d160b000000000000000000000000000000000000000000"
2359
2360    frame = hdr + fixed + supp_rates + ext_supp_rates + mesh_id + mesh_conf + mpm + ht_capab + ht_oper
2361    if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % frame):
2362        raise Exception("MGMT_RX_PROCESS failed")
2363    time.sleep(0.1)
2364
2365def test_mesh_cnf_rcvd_event_cls_acpt(dev, apdev):
2366    """Mesh peering management protocol testing - CLS_ACPT event in CNF_RCVD"""
2367    check_mesh_support(dev[0])
2368    add_open_mesh_network(dev[0])
2369    check_mesh_group_added(dev[0])
2370    dev[0].dump_monitor()
2371
2372    dev[0].request("SET ext_mgmt_frame_handling 1")
2373    add_open_mesh_network(dev[1])
2374    check_mesh_group_added(dev[1])
2375
2376    addr0 = dev[0].own_addr()
2377    addr1 = dev[1].own_addr()
2378
2379    rx_msg = dev[0].mgmt_rx()
2380    # Drop Mesh Peering Open
2381
2382    rx_msg = dev[0].mgmt_rx()
2383    # Allow Mesh Peering Confirm to go through
2384    if "OK" not in dev[0].request("MGMT_RX_PROCESS freq={} datarate={} ssi_signal={} frame={}".format(
2385        rx_msg['freq'], rx_msg['datarate'], rx_msg['ssi_signal'], binascii.hexlify(rx_msg['frame']).decode())):
2386        raise Exception("MGMT_RX_PROCESS failed")
2387
2388    payload = rx_msg['payload']
2389    peer_lid = binascii.hexlify(payload[51:53]).decode()
2390    my_lid = binascii.hexlify(payload[53:55]).decode()
2391
2392    dst = addr0.replace(':', '')
2393    src = addr1.replace(':', '')
2394    hdr = "d000ac00" + dst + src + src + "1000"
2395    fixed = "0f03"
2396    mesh_id = "720e777061732d6d6573682d6f70656e"
2397    mpm = "75080000" + peer_lid + my_lid + "3700"
2398    frame = hdr + fixed + mesh_id + mpm
2399
2400    # Inject Mesh Peering Close to hit "state CNF_RCVD event CLS_ACPT" to
2401    # HOLDING transition.
2402    if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=" + frame):
2403        raise Exception("MGMT_RX_PROCESS failed")
2404
2405def test_mesh_opn_snt_event_cls_acpt(dev, apdev):
2406    """Mesh peering management protocol testing - CLS_ACPT event in OPN_SNT"""
2407    check_mesh_support(dev[0])
2408    add_open_mesh_network(dev[0])
2409    check_mesh_group_added(dev[0])
2410    dev[0].dump_monitor()
2411
2412    dev[0].request("SET ext_mgmt_frame_handling 1")
2413    add_open_mesh_network(dev[1])
2414    check_mesh_group_added(dev[1])
2415
2416    addr0 = dev[0].own_addr()
2417    addr1 = dev[1].own_addr()
2418
2419    rx_msg = dev[0].mgmt_rx()
2420    # Drop Mesh Peering Open
2421
2422    rx_msg = dev[0].mgmt_rx()
2423    # Drop Mesh Peering Confirm
2424
2425    payload = rx_msg['payload']
2426    peer_lid = "0000"
2427    my_lid = binascii.hexlify(payload[53:55]).decode()
2428
2429    dst = addr0.replace(':', '')
2430    src = addr1.replace(':', '')
2431    hdr = "d000ac00" + dst + src + src + "1000"
2432    fixed = "0f03"
2433    mesh_id = "720e777061732d6d6573682d6f70656e"
2434    mpm = "75080000" + peer_lid + my_lid + "3700"
2435    frame = hdr + fixed + mesh_id + mpm
2436
2437    # Inject Mesh Peering Close to hit "state OPN_SNTevent CLS_ACPT" to
2438    # HOLDING transition.
2439    if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=" + frame):
2440        raise Exception("MGMT_RX_PROCESS failed")
2441
2442def test_mesh_select_network(dev):
2443    """Mesh network and SELECT_NETWORK"""
2444    check_mesh_support(dev[0])
2445    id0 = add_open_mesh_network(dev[0], start=False)
2446    id1 = add_open_mesh_network(dev[1], start=False)
2447    dev[0].select_network(id0)
2448    dev[1].select_network(id1)
2449    check_mesh_joined_connected(dev, connectivity=True)
2450
2451def test_mesh_forwarding(dev):
2452    """Mesh with two stations that can't reach each other directly"""
2453    try:
2454        set_group_map(dev[0], 1)
2455        set_group_map(dev[1], 3)
2456        set_group_map(dev[2], 2)
2457        check_mesh_support(dev[0])
2458        for i in range(3):
2459            add_open_mesh_network(dev[i])
2460            check_mesh_group_added(dev[i])
2461        for i in range(3):
2462            check_mesh_peer_connected(dev[i])
2463
2464        hwsim_utils.test_connectivity(dev[0], dev[1])
2465        hwsim_utils.test_connectivity(dev[1], dev[2])
2466        hwsim_utils.test_connectivity(dev[0], dev[2])
2467    finally:
2468        # reset groups
2469        set_group_map(dev[0], 1)
2470        set_group_map(dev[1], 1)
2471        set_group_map(dev[2], 1)
2472
2473def test_mesh_forwarding_secure(dev):
2474    """Mesh with two stations that can't reach each other directly (RSN)"""
2475    check_mesh_support(dev[0], secure=True)
2476    try:
2477        set_group_map(dev[0], 1)
2478        set_group_map(dev[1], 3)
2479        set_group_map(dev[2], 2)
2480        for i in range(3):
2481            dev[i].request("SET sae_groups ")
2482            id = add_mesh_secure_net(dev[i])
2483            dev[i].mesh_group_add(id)
2484            check_mesh_group_added(dev[i])
2485        for i in range(3):
2486            check_mesh_peer_connected(dev[i])
2487
2488        hwsim_utils.test_connectivity(dev[0], dev[1])
2489        hwsim_utils.test_connectivity(dev[1], dev[2])
2490        hwsim_utils.test_connectivity(dev[0], dev[2])
2491    finally:
2492        # reset groups
2493        set_group_map(dev[0], 1)
2494        set_group_map(dev[1], 1)
2495        set_group_map(dev[2], 1)
2496
2497def test_mesh_sae_anti_clogging(dev, apdev):
2498    """Mesh using SAE and anti-clogging"""
2499    try:
2500        run_mesh_sae_anti_clogging(dev, apdev)
2501    finally:
2502        stop_monitor(apdev[1]["ifname"])
2503
2504def run_mesh_sae_anti_clogging(dev, apdev):
2505    check_mesh_support(dev[0], secure=True)
2506    check_mesh_support(dev[1], secure=True)
2507    check_mesh_support(dev[2], secure=True)
2508
2509    sock = start_monitor(apdev[1]["ifname"])
2510    radiotap = radiotap_build()
2511
2512    dev[0].request("SET sae_groups 21")
2513    id = add_mesh_secure_net(dev[0])
2514    dev[0].mesh_group_add(id)
2515    check_mesh_group_added(dev[0])
2516
2517    # This flood of SAE authentication frames is from not yet known mesh STAs,
2518    # so the messages get dropped.
2519    addr0 = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
2520    for i in range(16):
2521        addr = binascii.unhexlify("f2%010x" % i)
2522        frame = build_sae_commit(addr0, addr)
2523        sock.send(radiotap + frame)
2524
2525    dev[1].request("SET sae_groups 21")
2526    id = add_mesh_secure_net(dev[1])
2527    dev[1].mesh_group_add(id)
2528    check_mesh_group_added(dev[1])
2529    check_mesh_connected2(dev)
2530
2531    # Inject Beacon frames to make the sources of the second flood known to the
2532    # target.
2533    bcn1 = binascii.unhexlify("80000000" + "ffffffffffff")
2534    bcn2 = binascii.unhexlify("0000dd20c44015840500e80310000000010882848b968c1298240301010504000200003204b048606c30140100000fac040100000fac040100000fac0800002d1afe131bffff0000000000000000000001000000000000000000003d16010000000000ffff0000000000000000000000000000720d777061732d6d6573682d736563710701010001010009")
2535    for i in range(16):
2536        addr = binascii.unhexlify("f4%010x" % i)
2537        frame = bcn1 + addr + addr + bcn2
2538        sock.send(radiotap + frame)
2539
2540    # This flood of SAE authentication frames is from known mesh STAs, so the
2541    # target will need to process these.
2542    for i in range(16):
2543        addr = binascii.unhexlify("f4%010x" % i)
2544        frame = build_sae_commit(addr0, addr)
2545        sock.send(radiotap + frame)
2546
2547    dev[2].request("SET sae_groups 21")
2548    id = add_mesh_secure_net(dev[2])
2549    dev[2].mesh_group_add(id)
2550    check_mesh_group_added(dev[2])
2551    check_mesh_peer_connected(dev[2])
2552    check_mesh_peer_connected(dev[0])
2553
2554def test_mesh_link_probe(dev, apdev, params):
2555    """Mesh link probing"""
2556    addr0 = dev[0].own_addr()
2557    addr1 = dev[1].own_addr()
2558    addr2 = dev[2].own_addr()
2559
2560    check_mesh_support(dev[0])
2561    for i in range(3):
2562        add_open_mesh_network(dev[i])
2563        check_mesh_group_added(dev[i])
2564    for i in range(3):
2565        check_mesh_peer_connected(dev[i])
2566        check_mesh_peer_connected(dev[i])
2567
2568    res = dev[0].request("MESH_LINK_PROBE " + addr1)
2569    if "FAIL" in res:
2570        raise HwsimSkip("MESH_LINK_PROBE kernel side support missing")
2571    dev[0].request("MESH_LINK_PROBE " + addr2 + " payload=aabbccdd")
2572    dev[1].request("MESH_LINK_PROBE " + addr0 + " payload=bbccddee")
2573    dev[1].request("MESH_LINK_PROBE " + addr2 + " payload=ccddeeff")
2574    dev[2].request("MESH_LINK_PROBE " + addr0 + " payload=aaaa")
2575    dev[2].request("MESH_LINK_PROBE " + addr1 + " payload=000102030405060708090a0b0c0d0e0f")
2576
2577    capfile = os.path.join(params['logdir'], "hwsim0.pcapng")
2578    filt = "wlan.fc == 0x8803"
2579    for i in range(10):
2580        out = run_tshark(capfile, filt, ["wlan.sa", "wlan.da"])
2581        if len(out.splitlines()) >= 6:
2582            break
2583        time.sleep(0.5)
2584    for i in [addr0, addr1, addr2]:
2585        for j in [addr0, addr1, addr2]:
2586            if i == j:
2587                continue
2588            if i + "\t" + j not in out:
2589                raise Exception("Did not see probe %s --> %s" % (i, j))
2590
2591def test_wpas_mesh_sae_inject(dev, apdev):
2592    """wpa_supplicant secure mesh and injected SAE messages"""
2593    check_mesh_support(dev[0], secure=True)
2594    dev[0].set("sae_groups", "")
2595    add_mesh_secure_net(dev[0])
2596    dev[0].mesh_group_add(id)
2597
2598    dev[1].set("sae_groups", "")
2599    add_mesh_secure_net(dev[1])
2600    dev[1].mesh_group_add(id)
2601
2602    check_mesh_joined_connected(dev, connectivity=True)
2603
2604    addr0 = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
2605    addr1 = binascii.unhexlify(dev[1].own_addr().replace(':', ''))
2606
2607    try:
2608        sock = start_monitor(apdev[1]["ifname"])
2609        radiotap = radiotap_build()
2610
2611        frame = build_sae_commit(addr1, addr0)
2612        for i in range(5):
2613            sock.send(radiotap + frame)
2614        time.sleep(10)
2615    finally:
2616        stop_monitor(apdev[1]["ifname"])
2617
2618def test_wpas_mesh_secure_6ghz_320(dev, apdev):
2619    """wpa_supplicant secure 6 GHz mesh network connectivity in 320 MHz"""
2620    check_mesh_support(dev[0], secure=True)
2621    check_mesh_support(dev[1], secure=True)
2622
2623    try:
2624        # CA enables 320 MHz channels without NO-IR restriction
2625        set_reg(dev, 'CA')
2626
2627        dev[0].set("sae_groups", "")
2628        id = add_mesh_secure_net(dev[0])
2629        dev[0].set_network(id, "frequency", "5975")
2630        dev[0].set_network(id, "max_oper_chwidth", "9")
2631        dev[0].mesh_group_add(id)
2632
2633        dev[1].set("sae_groups", "")
2634        id = add_mesh_secure_net(dev[1])
2635        dev[1].set_network(id, "frequency", "5975")
2636        dev[1].set_network(id, "max_oper_chwidth", "9")
2637        dev[1].mesh_group_add(id)
2638
2639        check_mesh_joined_connected(dev, connectivity=True)
2640
2641        state = dev[0].get_status_field("wpa_state")
2642        if state != "COMPLETED":
2643            raise Exception("Unexpected wpa_state on dev0: " + state)
2644        state = dev[1].get_status_field("wpa_state")
2645        if state != "COMPLETED":
2646            raise Exception("Unexpected wpa_state on dev1: " + state)
2647    finally:
2648        clear_reg_setting(dev)
2649