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