tests: mode=mesh in STATUS
[mech_eap.git] / tests / hwsim / test_wpas_mesh.py
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
7 import logging
8 logger = logging.getLogger()
9 import os
10 import struct
11 import subprocess
12 import time
13
14 import hwsim_utils
15 import hostapd
16 from wpasupplicant import WpaSupplicant
17 from utils import HwsimSkip, alloc_fail, fail_test, wait_fail_trigger
18 from tshark import run_tshark
19
20 def check_mesh_support(dev, secure=False):
21     if "MESH" not in dev.get_capability("modes"):
22         raise HwsimSkip("Driver does not support mesh")
23     if secure and "SAE" not in dev.get_capability("auth_alg"):
24         raise HwsimSkip("SAE not supported")
25
26 def check_mesh_scan(dev, params, other_started=False, beacon_int=0):
27     if not other_started:
28         dev.dump_monitor()
29     id = dev.request("SCAN " + params)
30     if "FAIL" in id:
31         raise Exception("Failed to start scan")
32     id = int(id)
33
34     if other_started:
35         ev = dev.wait_event(["CTRL-EVENT-SCAN-STARTED"])
36         if ev is None:
37             raise Exception("Other scan did not start")
38         if "id=" + str(id) in ev:
39             raise Exception("Own scan id unexpectedly included in start event")
40
41         ev = dev.wait_event(["CTRL-EVENT-SCAN-RESULTS"])
42         if ev is None:
43             raise Exception("Other scan did not complete")
44         if "id=" + str(id) in ev:
45             raise Exception(
46                 "Own scan id unexpectedly included in completed event")
47
48     ev = dev.wait_event(["CTRL-EVENT-SCAN-STARTED"])
49     if ev is None:
50         raise Exception("Scan did not start")
51     if "id=" + str(id) not in ev:
52         raise Exception("Scan id not included in start event")
53
54     ev = dev.wait_event(["CTRL-EVENT-SCAN-RESULTS"])
55     if ev is None:
56         raise Exception("Scan did not complete")
57     if "id=" + str(id) not in ev:
58         raise Exception("Scan id not included in completed event")
59
60     res = dev.request("SCAN_RESULTS")
61
62     if res.find("[MESH]") < 0:
63         raise Exception("Scan did not contain a MESH network")
64
65     bssid = res.splitlines()[1].split(' ')[0]
66     bss = dev.get_bss(bssid)
67     if bss is None:
68         raise Exception("Could not get BSS entry for mesh")
69     if 'mesh_capability' not in bss:
70         raise Exception("mesh_capability missing from BSS entry")
71     if beacon_int:
72         if 'beacon_int' not in bss:
73             raise Exception("beacon_int missing from BSS entry")
74         if str(beacon_int) != bss['beacon_int']:
75             raise Exception("Unexpected beacon_int in BSS entry: " + bss['beacon_int'])
76
77 def check_mesh_group_added(dev):
78     ev = dev.wait_event(["MESH-GROUP-STARTED"])
79     if ev is None:
80         raise Exception("Test exception: Couldn't join mesh")
81
82
83 def check_mesh_group_removed(dev):
84     ev = dev.wait_event(["MESH-GROUP-REMOVED"])
85     if ev is None:
86         raise Exception("Test exception: Couldn't leave mesh")
87
88
89 def check_mesh_peer_connected(dev, timeout=10):
90     ev = dev.wait_event(["MESH-PEER-CONNECTED"], timeout=timeout)
91     if ev is None:
92         raise Exception("Test exception: Remote peer did not connect.")
93
94
95 def check_mesh_peer_disconnected(dev):
96     ev = dev.wait_event(["MESH-PEER-DISCONNECTED"])
97     if ev is None:
98         raise Exception("Test exception: Peer disconnect event not detected.")
99
100
101 def test_wpas_add_set_remove_support(dev):
102     """wpa_supplicant MESH add/set/remove network support"""
103     check_mesh_support(dev[0])
104     id = dev[0].add_network()
105     dev[0].set_network(id, "mode", "5")
106     dev[0].remove_network(id)
107
108 def add_open_mesh_network(dev, freq="2412", start=True, beacon_int=0,
109                           basic_rates=None, chwidth=0):
110     id = dev.add_network()
111     dev.set_network(id, "mode", "5")
112     dev.set_network_quoted(id, "ssid", "wpas-mesh-open")
113     dev.set_network(id, "key_mgmt", "NONE")
114     if freq:
115         dev.set_network(id, "frequency", freq)
116     if chwidth > 0:
117         dev.set_network(id, "max_oper_chwidth", str(chwidth))
118     if beacon_int:
119         dev.set_network(id, "beacon_int", str(beacon_int))
120     if basic_rates:
121         dev.set_network(id, "mesh_basic_rates", basic_rates)
122     if start:
123         dev.mesh_group_add(id)
124     return id
125
126 def test_wpas_mesh_group_added(dev):
127     """wpa_supplicant MESH group add"""
128     check_mesh_support(dev[0])
129     add_open_mesh_network(dev[0])
130
131     # Check for MESH-GROUP-STARTED event
132     check_mesh_group_added(dev[0])
133
134
135 def test_wpas_mesh_group_remove(dev):
136     """wpa_supplicant MESH group remove"""
137     check_mesh_support(dev[0])
138     add_open_mesh_network(dev[0])
139     # Check for MESH-GROUP-STARTED event
140     check_mesh_group_added(dev[0])
141     dev[0].mesh_group_remove()
142     # Check for MESH-GROUP-REMOVED event
143     check_mesh_group_removed(dev[0])
144     dev[0].mesh_group_remove()
145
146 def test_wpas_mesh_peer_connected(dev):
147     """wpa_supplicant MESH peer connected"""
148     check_mesh_support(dev[0])
149     add_open_mesh_network(dev[0], beacon_int=160)
150     add_open_mesh_network(dev[1], beacon_int=160)
151
152     # Check for mesh joined
153     check_mesh_group_added(dev[0])
154     check_mesh_group_added(dev[1])
155
156     # Check for peer connected
157     check_mesh_peer_connected(dev[0])
158     check_mesh_peer_connected(dev[1])
159
160
161 def test_wpas_mesh_peer_disconnected(dev):
162     """wpa_supplicant MESH peer disconnected"""
163     check_mesh_support(dev[0])
164     add_open_mesh_network(dev[0])
165     add_open_mesh_network(dev[1])
166
167     # Check for mesh joined
168     check_mesh_group_added(dev[0])
169     check_mesh_group_added(dev[1])
170
171     # Check for peer connected
172     check_mesh_peer_connected(dev[0])
173     check_mesh_peer_connected(dev[1])
174
175     # Remove group on dev 1
176     dev[1].mesh_group_remove()
177     # Device 0 should get a disconnection event
178     check_mesh_peer_disconnected(dev[0])
179
180
181 def test_wpas_mesh_mode_scan(dev):
182     """wpa_supplicant MESH scan support"""
183     check_mesh_support(dev[0])
184     add_open_mesh_network(dev[0])
185     add_open_mesh_network(dev[1], beacon_int=175)
186
187     # Check for mesh joined
188     check_mesh_group_added(dev[0])
189     check_mesh_group_added(dev[1])
190
191     # Check for Mesh scan
192     check_mesh_scan(dev[0], "use_id=1", beacon_int=175)
193
194 def test_wpas_mesh_open(dev, apdev):
195     """wpa_supplicant open MESH network connectivity"""
196     check_mesh_support(dev[0])
197     add_open_mesh_network(dev[0], freq="2462", basic_rates="60 120 240")
198     add_open_mesh_network(dev[1], freq="2462", basic_rates="60 120 240")
199
200     # Check for mesh joined
201     check_mesh_group_added(dev[0])
202     check_mesh_group_added(dev[1])
203
204     # Check for peer connected
205     check_mesh_peer_connected(dev[0])
206     check_mesh_peer_connected(dev[1])
207
208     # Test connectivity 0->1 and 1->0
209     hwsim_utils.test_connectivity(dev[0], dev[1])
210
211     state = dev[0].get_status_field("wpa_state")
212     if state != "COMPLETED":
213         raise Exception("Unexpected wpa_state on dev0: " + state)
214     state = dev[1].get_status_field("wpa_state")
215     if state != "COMPLETED":
216         raise Exception("Unexpected wpa_state on dev1: " + state)
217
218     mode = dev[0].get_status_field("mode")
219     if mode != "mesh":
220         raise Exception("Unexpected mode: " + mode)
221
222 def test_wpas_mesh_open_no_auto(dev, apdev):
223     """wpa_supplicant open MESH network connectivity"""
224     check_mesh_support(dev[0])
225     id = add_open_mesh_network(dev[0], start=False)
226     dev[0].set_network(id, "dot11MeshMaxRetries", "16")
227     dev[0].set_network(id, "dot11MeshRetryTimeout", "255")
228     dev[0].mesh_group_add(id)
229
230     id = add_open_mesh_network(dev[1], start=False)
231     dev[1].set_network(id, "no_auto_peer", "1")
232     dev[1].mesh_group_add(id)
233
234     # Check for mesh joined
235     check_mesh_group_added(dev[0])
236     check_mesh_group_added(dev[1])
237
238     # Check for peer connected
239     check_mesh_peer_connected(dev[0], timeout=30)
240     check_mesh_peer_connected(dev[1])
241
242     # Test connectivity 0->1 and 1->0
243     hwsim_utils.test_connectivity(dev[0], dev[1])
244
245 def test_mesh_open_no_auto2(dev, apdev):
246     """Open mesh network connectivity, no_auto on both peers"""
247     check_mesh_support(dev[0])
248     id = add_open_mesh_network(dev[0], start=False)
249     dev[0].set_network(id, "no_auto_peer", "1")
250     dev[0].mesh_group_add(id)
251
252     id = add_open_mesh_network(dev[1], start=False)
253     dev[1].set_network(id, "no_auto_peer", "1")
254     dev[1].mesh_group_add(id)
255
256     check_mesh_group_added(dev[0])
257     check_mesh_group_added(dev[1])
258
259     ev = dev[0].wait_event(["will not initiate new peer link"], timeout=10)
260     if ev is None:
261         raise Exception("Missing no-initiate message")
262     addr1 = dev[1].own_addr()
263     if "OK" not in dev[0].request("MESH_PEER_ADD " + addr1):
264         raise Exception("MESH_PEER_ADD failed")
265     if "FAIL" not in dev[0].request("MESH_PEER_ADD ff:ff:ff:ff:ff:ff"):
266         raise Exception("MESH_PEER_ADD with unknown STA succeeded")
267     check_mesh_peer_connected(dev[0], timeout=30)
268     check_mesh_peer_connected(dev[1])
269     if "FAIL" not in dev[0].request("MESH_PEER_ADD " + addr1):
270         raise Exception("MESH_PEER_ADD succeeded for connected STA")
271     hwsim_utils.test_connectivity(dev[0], dev[1])
272
273 def add_mesh_secure_net(dev, psk=True, pmf=False, pairwise=None, group=None):
274     id = dev.add_network()
275     dev.set_network(id, "mode", "5")
276     dev.set_network_quoted(id, "ssid", "wpas-mesh-sec")
277     dev.set_network(id, "key_mgmt", "SAE")
278     dev.set_network(id, "frequency", "2412")
279     if psk:
280         dev.set_network_quoted(id, "psk", "thisismypassphrase!")
281     if pmf:
282         dev.set_network(id, "ieee80211w", "2")
283     if pairwise:
284         dev.set_network(id, "pairwise", pairwise)
285     if group:
286         dev.set_network(id, "group", group)
287     return id
288
289 def test_wpas_mesh_secure(dev, apdev):
290     """wpa_supplicant secure MESH network connectivity"""
291     check_mesh_support(dev[0], secure=True)
292     dev[0].request("SET sae_groups ")
293     id = add_mesh_secure_net(dev[0])
294     dev[0].mesh_group_add(id)
295
296     dev[1].request("SET sae_groups ")
297     id = add_mesh_secure_net(dev[1])
298     dev[1].mesh_group_add(id)
299
300     # Check for mesh joined
301     check_mesh_group_added(dev[0])
302     check_mesh_group_added(dev[1])
303
304     # Check for peer connected
305     check_mesh_peer_connected(dev[0])
306     check_mesh_peer_connected(dev[1])
307
308     # Test connectivity 0->1 and 1->0
309     hwsim_utils.test_connectivity(dev[0], dev[1])
310
311     state = dev[0].get_status_field("wpa_state")
312     if state != "COMPLETED":
313         raise Exception("Unexpected wpa_state on dev0: " + state)
314     state = dev[1].get_status_field("wpa_state")
315     if state != "COMPLETED":
316         raise Exception("Unexpected wpa_state on dev1: " + state)
317
318 def test_mesh_secure_pmf(dev, apdev):
319     """Secure mesh network connectivity with PMF enabled"""
320     check_mesh_support(dev[0], secure=True)
321     dev[0].request("SET sae_groups ")
322     id = add_mesh_secure_net(dev[0], pmf=True)
323     dev[0].mesh_group_add(id)
324
325     dev[1].request("SET sae_groups ")
326     id = add_mesh_secure_net(dev[1], pmf=True)
327     dev[1].mesh_group_add(id)
328
329     # Check for mesh joined
330     check_mesh_group_added(dev[0])
331     check_mesh_group_added(dev[1])
332
333     # Check for peer connected
334     check_mesh_peer_connected(dev[0])
335     check_mesh_peer_connected(dev[1])
336
337     # Test connectivity 0->1 and 1->0
338     hwsim_utils.test_connectivity(dev[0], dev[1])
339
340 def run_mesh_secure(dev, cipher):
341     if cipher not in dev[0].get_capability("pairwise"):
342         raise HwsimSkip("Cipher %s not supported" % cipher)
343     check_mesh_support(dev[0], secure=True)
344     dev[0].request("SET sae_groups ")
345     id = add_mesh_secure_net(dev[0], pairwise=cipher, group=cipher)
346     dev[0].mesh_group_add(id)
347
348     dev[1].request("SET sae_groups ")
349     id = add_mesh_secure_net(dev[1], pairwise=cipher, group=cipher)
350     dev[1].mesh_group_add(id)
351
352     # Check for mesh joined
353     check_mesh_group_added(dev[0])
354     check_mesh_group_added(dev[1])
355
356     # Check for peer connected
357     check_mesh_peer_connected(dev[0])
358     check_mesh_peer_connected(dev[1])
359
360     # Test connectivity 0->1 and 1->0
361     hwsim_utils.test_connectivity(dev[0], dev[1])
362
363 def test_mesh_secure_ccmp(dev, apdev):
364     """Secure mesh with CCMP"""
365     run_mesh_secure(dev, "CCMP")
366
367 def test_mesh_secure_gcmp(dev, apdev):
368     """Secure mesh with GCMP"""
369     run_mesh_secure(dev, "GCMP")
370
371 def test_mesh_secure_gcmp_256(dev, apdev):
372     """Secure mesh with GCMP-256"""
373     run_mesh_secure(dev, "GCMP-256")
374
375 def test_mesh_secure_ccmp_256(dev, apdev):
376     """Secure mesh with CCMP-256"""
377     run_mesh_secure(dev, "CCMP-256")
378
379 def test_mesh_secure_invalid_pairwise_cipher(dev, apdev):
380     """Secure mesh and invalid group cipher"""
381     check_mesh_support(dev[0], secure=True)
382     dev[0].request("SET sae_groups ")
383     id = add_mesh_secure_net(dev[0], pairwise="TKIP", group="CCMP")
384     if dev[0].mesh_group_add(id) != None:
385         raise Exception("Unexpected group add success")
386     ev = dev[0].wait_event(["mesh: Invalid pairwise cipher"], timeout=1)
387     if ev is None:
388         raise Exception("Invalid pairwise cipher not reported")
389
390 def test_mesh_secure_invalid_group_cipher(dev, apdev):
391     """Secure mesh and invalid group cipher"""
392     check_mesh_support(dev[0], secure=True)
393     dev[0].request("SET sae_groups ")
394     id = add_mesh_secure_net(dev[0], pairwise="CCMP", group="TKIP")
395     if dev[0].mesh_group_add(id) != None:
396         raise Exception("Unexpected group add success")
397     ev = dev[0].wait_event(["mesh: Invalid group cipher"], timeout=1)
398     if ev is None:
399         raise Exception("Invalid group cipher not reported")
400
401 def test_wpas_mesh_secure_sae_group_mismatch(dev, apdev):
402     """wpa_supplicant secure MESH and SAE group mismatch"""
403     check_mesh_support(dev[0], secure=True)
404     addr0 = dev[0].p2p_interface_addr()
405     addr1 = dev[1].p2p_interface_addr()
406     addr2 = dev[2].p2p_interface_addr()
407
408     dev[0].request("SET sae_groups 19 25")
409     id = add_mesh_secure_net(dev[0])
410     dev[0].mesh_group_add(id)
411
412     dev[1].request("SET sae_groups 19")
413     id = add_mesh_secure_net(dev[1])
414     dev[1].mesh_group_add(id)
415
416     dev[2].request("SET sae_groups 26")
417     id = add_mesh_secure_net(dev[2])
418     dev[2].mesh_group_add(id)
419
420     check_mesh_group_added(dev[0])
421     check_mesh_group_added(dev[1])
422     check_mesh_group_added(dev[2])
423
424     ev = dev[0].wait_event(["MESH-PEER-CONNECTED"])
425     if ev is None:
426         raise Exception("Remote peer did not connect")
427     if addr1 not in ev:
428         raise Exception("Unexpected peer connected: " + ev)
429
430     ev = dev[1].wait_event(["MESH-PEER-CONNECTED"])
431     if ev is None:
432         raise Exception("Remote peer did not connect")
433     if addr0 not in ev:
434         raise Exception("Unexpected peer connected: " + ev)
435
436     ev = dev[2].wait_event(["MESH-PEER-CONNECTED"], timeout=1)
437     if ev is not None:
438         raise Exception("Unexpected peer connection at dev[2]: " + ev)
439
440     ev = dev[0].wait_event(["MESH-PEER-CONNECTED"], timeout=0.1)
441     if ev is not None:
442         raise Exception("Unexpected peer connection: " + ev)
443
444     ev = dev[1].wait_event(["MESH-PEER-CONNECTED"], timeout=0.1)
445     if ev is not None:
446         raise Exception("Unexpected peer connection: " + ev)
447
448     dev[0].request("SET sae_groups ")
449     dev[1].request("SET sae_groups ")
450     dev[2].request("SET sae_groups ")
451
452 def test_wpas_mesh_secure_sae_group_negotiation(dev, apdev):
453     """wpa_supplicant secure MESH and SAE group negotiation"""
454     check_mesh_support(dev[0], secure=True)
455     addr0 = dev[0].own_addr()
456     addr1 = dev[1].own_addr()
457
458     #dev[0].request("SET sae_groups 21 20 25 26")
459     dev[0].request("SET sae_groups 25")
460     id = add_mesh_secure_net(dev[0])
461     dev[0].mesh_group_add(id)
462
463     dev[1].request("SET sae_groups 19 25")
464     id = add_mesh_secure_net(dev[1])
465     dev[1].mesh_group_add(id)
466
467     check_mesh_group_added(dev[0])
468     check_mesh_group_added(dev[1])
469
470     check_mesh_peer_connected(dev[0])
471     check_mesh_peer_connected(dev[1])
472
473     dev[0].request("SET sae_groups ")
474     dev[1].request("SET sae_groups ")
475
476 def test_wpas_mesh_secure_sae_missing_password(dev, apdev):
477     """wpa_supplicant secure MESH and missing SAE password"""
478     check_mesh_support(dev[0], secure=True)
479     id = add_mesh_secure_net(dev[0], psk=False)
480     dev[0].set_network(id, "psk", "8f20b381f9b84371d61b5080ad85cac3c61ab3ca9525be5b2d0f4da3d979187a")
481     dev[0].mesh_group_add(id)
482     ev = dev[0].wait_event(["MESH-GROUP-STARTED", "Could not join mesh"],
483                            timeout=5)
484     if ev is None:
485         raise Exception("Timeout on mesh start event")
486     if "MESH-GROUP-STARTED" in ev:
487         raise Exception("Unexpected mesh group start")
488     ev = dev[0].wait_event(["MESH-GROUP-STARTED"], timeout=0.1)
489     if ev is not None:
490         raise Exception("Unexpected mesh group start")
491
492 def test_wpas_mesh_secure_no_auto(dev, apdev):
493     """wpa_supplicant secure MESH network connectivity"""
494     check_mesh_support(dev[0], secure=True)
495     dev[0].request("SET sae_groups 19")
496     id = add_mesh_secure_net(dev[0])
497     dev[0].mesh_group_add(id)
498
499     dev[1].request("SET sae_groups 19")
500     id = add_mesh_secure_net(dev[1])
501     dev[1].set_network(id, "no_auto_peer", "1")
502     dev[1].mesh_group_add(id)
503
504     # Check for mesh joined
505     check_mesh_group_added(dev[0])
506     check_mesh_group_added(dev[1])
507
508     # Check for peer connected
509     check_mesh_peer_connected(dev[0], timeout=30)
510     check_mesh_peer_connected(dev[1])
511
512     # Test connectivity 0->1 and 1->0
513     hwsim_utils.test_connectivity(dev[0], dev[1])
514
515     dev[0].request("SET sae_groups ")
516     dev[1].request("SET sae_groups ")
517
518 def test_wpas_mesh_secure_dropped_frame(dev, apdev):
519     """Secure mesh network connectivity when the first plink Open is dropped"""
520     check_mesh_support(dev[0], secure=True)
521
522     dev[0].request("SET ext_mgmt_frame_handling 1")
523     dev[0].request("SET sae_groups ")
524     id = add_mesh_secure_net(dev[0])
525     dev[0].mesh_group_add(id)
526
527     dev[1].request("SET sae_groups ")
528     id = add_mesh_secure_net(dev[1])
529     dev[1].mesh_group_add(id)
530
531     # Check for mesh joined
532     check_mesh_group_added(dev[0])
533     check_mesh_group_added(dev[1])
534
535     # Drop the first Action frame (plink Open) to test unexpected order of
536     # Confirm/Open messages.
537     count = 0
538     while True:
539         count += 1
540         if count > 10:
541             raise Exception("Did not see Action frames")
542         rx_msg = dev[0].mgmt_rx()
543         if rx_msg is None:
544             raise Exception("MGMT-RX timeout")
545         if rx_msg['subtype'] == 13:
546             logger.info("Drop the first Action frame")
547             break
548         if "OK" not in dev[0].request("MGMT_RX_PROCESS freq={} datarate={} ssi_signal={} frame={}".format(rx_msg['freq'], rx_msg['datarate'], rx_msg['ssi_signal'], rx_msg['frame'].encode('hex'))):
549             raise Exception("MGMT_RX_PROCESS failed")
550
551     dev[0].request("SET ext_mgmt_frame_handling 0")
552
553     # Check for peer connected
554     check_mesh_peer_connected(dev[0])
555     check_mesh_peer_connected(dev[1])
556
557     # Test connectivity 0->1 and 1->0
558     hwsim_utils.test_connectivity(dev[0], dev[1])
559
560 def test_mesh_secure_fail(dev, apdev):
561     """Secure mesh network connectivity failure"""
562     check_mesh_support(dev[0], secure=True)
563     dev[0].request("SET sae_groups ")
564     id = add_mesh_secure_net(dev[0], pmf=True)
565     dev[0].mesh_group_add(id)
566
567     dev[1].request("SET sae_groups ")
568     id = add_mesh_secure_net(dev[1], pmf=True)
569
570     with fail_test(dev[0], 1, "wpa_driver_nl80211_sta_add;mesh_mpm_auth_peer"):
571         dev[1].mesh_group_add(id)
572
573         check_mesh_group_added(dev[0])
574         check_mesh_group_added(dev[1])
575
576         check_mesh_peer_connected(dev[0])
577         check_mesh_peer_connected(dev[1])
578
579 def test_wpas_mesh_ctrl(dev):
580     """wpa_supplicant ctrl_iface mesh command error cases"""
581     check_mesh_support(dev[0])
582     if "FAIL" not in dev[0].request("MESH_GROUP_ADD 123"):
583         raise Exception("Unexpected MESH_GROUP_ADD success")
584     id = dev[0].add_network()
585     if "FAIL" not in dev[0].request("MESH_GROUP_ADD %d" % id):
586         raise Exception("Unexpected MESH_GROUP_ADD success")
587     dev[0].set_network(id, "mode", "5")
588     dev[0].set_network(id, "key_mgmt", "WPA-PSK")
589     if "FAIL" not in dev[0].request("MESH_GROUP_ADD %d" % id):
590         raise Exception("Unexpected MESH_GROUP_ADD success")
591
592     if "FAIL" not in dev[0].request("MESH_GROUP_REMOVE foo"):
593         raise Exception("Unexpected MESH_GROUP_REMOVE success")
594
595 def test_wpas_mesh_dynamic_interface(dev):
596     """wpa_supplicant mesh with dynamic interface"""
597     check_mesh_support(dev[0])
598     mesh0 = None
599     mesh1 = None
600     try:
601         mesh0 = dev[0].request("MESH_INTERFACE_ADD ifname=mesh0")
602         if "FAIL" in mesh0:
603             raise Exception("MESH_INTERFACE_ADD failed")
604         mesh1 = dev[1].request("MESH_INTERFACE_ADD")
605         if "FAIL" in mesh1:
606             raise Exception("MESH_INTERFACE_ADD failed")
607
608         wpas0 = WpaSupplicant(ifname=mesh0)
609         wpas1 = WpaSupplicant(ifname=mesh1)
610         logger.info(mesh0 + " address " + wpas0.get_status_field("address"))
611         logger.info(mesh1 + " address " + wpas1.get_status_field("address"))
612
613         add_open_mesh_network(wpas0)
614         add_open_mesh_network(wpas1)
615         check_mesh_group_added(wpas0)
616         check_mesh_group_added(wpas1)
617         check_mesh_peer_connected(wpas0)
618         check_mesh_peer_connected(wpas1)
619         hwsim_utils.test_connectivity(wpas0, wpas1)
620
621         # Must not allow MESH_GROUP_REMOVE on dynamic interface
622         if "FAIL" not in wpas0.request("MESH_GROUP_REMOVE " + mesh0):
623             raise Exception("Invalid MESH_GROUP_REMOVE accepted")
624         if "FAIL" not in wpas1.request("MESH_GROUP_REMOVE " + mesh1):
625             raise Exception("Invalid MESH_GROUP_REMOVE accepted")
626
627         # Must not allow MESH_GROUP_REMOVE on another radio interface
628         if "FAIL" not in wpas0.request("MESH_GROUP_REMOVE " + mesh1):
629             raise Exception("Invalid MESH_GROUP_REMOVE accepted")
630         if "FAIL" not in wpas1.request("MESH_GROUP_REMOVE " + mesh0):
631             raise Exception("Invalid MESH_GROUP_REMOVE accepted")
632
633         wpas0.remove_ifname()
634         wpas1.remove_ifname()
635
636         if "OK" not in dev[0].request("MESH_GROUP_REMOVE " + mesh0):
637             raise Exception("MESH_GROUP_REMOVE failed")
638         if "OK" not in dev[1].request("MESH_GROUP_REMOVE " + mesh1):
639             raise Exception("MESH_GROUP_REMOVE failed")
640
641         if "FAIL" not in dev[0].request("MESH_GROUP_REMOVE " + mesh0):
642             raise Exception("Invalid MESH_GROUP_REMOVE accepted")
643         if "FAIL" not in dev[1].request("MESH_GROUP_REMOVE " + mesh1):
644             raise Exception("Invalid MESH_GROUP_REMOVE accepted")
645
646         logger.info("Make sure another dynamic group can be added")
647         mesh0 = dev[0].request("MESH_INTERFACE_ADD ifname=mesh0")
648         if "FAIL" in mesh0:
649             raise Exception("MESH_INTERFACE_ADD failed")
650         mesh1 = dev[1].request("MESH_INTERFACE_ADD")
651         if "FAIL" in mesh1:
652             raise Exception("MESH_INTERFACE_ADD failed")
653
654         wpas0 = WpaSupplicant(ifname=mesh0)
655         wpas1 = WpaSupplicant(ifname=mesh1)
656         logger.info(mesh0 + " address " + wpas0.get_status_field("address"))
657         logger.info(mesh1 + " address " + wpas1.get_status_field("address"))
658
659         add_open_mesh_network(wpas0)
660         add_open_mesh_network(wpas1)
661         check_mesh_group_added(wpas0)
662         check_mesh_group_added(wpas1)
663         check_mesh_peer_connected(wpas0)
664         check_mesh_peer_connected(wpas1)
665         hwsim_utils.test_connectivity(wpas0, wpas1)
666     finally:
667         if mesh0:
668             dev[0].request("MESH_GROUP_REMOVE " + mesh0)
669         if mesh1:
670             dev[1].request("MESH_GROUP_REMOVE " + mesh1)
671
672 def test_wpas_mesh_max_peering(dev, apdev, params):
673     """Mesh max peering limit"""
674     check_mesh_support(dev[0])
675     try:
676         dev[0].request("SET max_peer_links 1")
677
678         # first, connect dev[0] and dev[1]
679         add_open_mesh_network(dev[0])
680         add_open_mesh_network(dev[1])
681         for i in range(2):
682             ev = dev[i].wait_event(["MESH-PEER-CONNECTED"])
683             if ev is None:
684                 raise Exception("dev%d did not connect with any peer" % i)
685
686         # add dev[2] which will try to connect with both dev[0] and dev[1],
687         # but can complete connection only with dev[1]
688         add_open_mesh_network(dev[2])
689         for i in range(1, 3):
690             ev = dev[i].wait_event(["MESH-PEER-CONNECTED"])
691             if ev is None:
692                 raise Exception("dev%d did not connect the second peer" % i)
693
694         ev = dev[0].wait_event(["MESH-PEER-CONNECTED"], timeout=1)
695         if ev is not None:
696             raise Exception("dev0 connection beyond max peering limit")
697
698         ev = dev[2].wait_event(["MESH-PEER-CONNECTED"], timeout=0.1)
699         if ev is not None:
700             raise Exception("dev2 reported unexpected peering: " + ev)
701
702         for i in range(3):
703             dev[i].mesh_group_remove()
704             check_mesh_group_removed(dev[i])
705     finally:
706         dev[0].request("SET max_peer_links 99")
707
708     addr0 = dev[0].own_addr()
709     addr1 = dev[1].own_addr()
710     addr2 = dev[2].own_addr()
711
712     capfile = os.path.join(params['logdir'], "hwsim0.pcapng")
713     filt = "wlan.fc.type_subtype == 8"
714     out = run_tshark(capfile, filt, [ "wlan.sa", "wlan.mesh.config.cap" ])
715     pkts = out.splitlines()
716     one = [ 0, 0, 0 ]
717     zero = [ 0, 0, 0 ]
718     for pkt in pkts:
719         addr, cap = pkt.split('\t')
720         cap = int(cap, 16)
721         if addr == addr0:
722             idx = 0
723         elif addr == addr1:
724             idx = 1
725         elif addr == addr2:
726             idx = 2
727         else:
728             continue
729         if cap & 0x01:
730             one[idx] += 1
731         else:
732             zero[idx] += 1
733     logger.info("one: " + str(one))
734     logger.info("zero: " + str(zero))
735     if zero[0] == 0:
736         raise Exception("Accepting Additional Mesh Peerings not cleared")
737     if one[0] == 0:
738         raise Exception("Accepting Additional Mesh Peerings was not set in the first Beacon frame")
739     if zero[1] > 0 or zero[2] > 0 or one[1] == 0 or one[2] == 0:
740         raise Exception("Unexpected value in Accepting Additional Mesh Peerings from other STAs")
741
742 def test_wpas_mesh_open_5ghz(dev, apdev):
743     """wpa_supplicant open MESH network on 5 GHz band"""
744     try:
745         _test_wpas_mesh_open_5ghz(dev, apdev)
746     finally:
747         subprocess.call(['iw', 'reg', 'set', '00'])
748         dev[0].flush_scan_cache()
749         dev[1].flush_scan_cache()
750
751 def _test_wpas_mesh_open_5ghz(dev, apdev):
752     check_mesh_support(dev[0])
753     subprocess.call(['iw', 'reg', 'set', 'US'])
754     for i in range(2):
755         for j in range(5):
756             ev = dev[i].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=5)
757             if ev is None:
758                 raise Exception("No regdom change event")
759             if "alpha2=US" in ev:
760                 break
761         add_open_mesh_network(dev[i], freq="5180")
762
763     # Check for mesh joined
764     check_mesh_group_added(dev[0])
765     check_mesh_group_added(dev[1])
766
767     # Check for peer connected
768     check_mesh_peer_connected(dev[0])
769     check_mesh_peer_connected(dev[1])
770
771     # Test connectivity 0->1 and 1->0
772     hwsim_utils.test_connectivity(dev[0], dev[1])
773
774 def test_wpas_mesh_open_vht_80p80(dev, apdev):
775     """wpa_supplicant open MESH network on VHT 80+80 MHz channel"""
776     try:
777         _test_wpas_mesh_open_vht_80p80(dev, apdev)
778     finally:
779         subprocess.call(['iw', 'reg', 'set', '00'])
780         dev[0].flush_scan_cache()
781         dev[1].flush_scan_cache()
782
783 def _test_wpas_mesh_open_vht_80p80(dev, apdev):
784     check_mesh_support(dev[0])
785     subprocess.call(['iw', 'reg', 'set', 'US'])
786     for i in range(2):
787         for j in range(5):
788             ev = dev[i].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=5)
789             if ev is None:
790                 raise Exception("No regdom change event")
791             if "alpha2=US" in ev:
792                 break
793         add_open_mesh_network(dev[i], freq="5180", chwidth=3)
794
795     # Check for mesh joined
796     check_mesh_group_added(dev[0])
797     check_mesh_group_added(dev[1])
798
799     # Check for peer connected
800     check_mesh_peer_connected(dev[0])
801     check_mesh_peer_connected(dev[1])
802
803     # Test connectivity 0->1 and 1->0
804     hwsim_utils.test_connectivity(dev[0], dev[1])
805
806     sig = dev[0].request("SIGNAL_POLL").splitlines()
807     if "WIDTH=80+80 MHz" not in sig:
808         raise Exception("Unexpected SIGNAL_POLL value(2): " + str(sig))
809     if "CENTER_FRQ1=5210" not in sig:
810         raise Exception("Unexpected SIGNAL_POLL value(3): " + str(sig))
811     if "CENTER_FRQ2=5775" not in sig:
812         raise Exception("Unexpected SIGNAL_POLL value(4): " + str(sig))
813
814     sig = dev[1].request("SIGNAL_POLL").splitlines()
815     if "WIDTH=80+80 MHz" not in sig:
816         raise Exception("Unexpected SIGNAL_POLL value(2b): " + str(sig))
817     if "CENTER_FRQ1=5210" not in sig:
818         raise Exception("Unexpected SIGNAL_POLL value(3b): " + str(sig))
819     if "CENTER_FRQ2=5775" not in sig:
820         raise Exception("Unexpected SIGNAL_POLL value(4b): " + str(sig))
821
822 def test_mesh_open_vht_160(dev, apdev):
823     """Open mesh network on VHT 160 MHz channel"""
824     try:
825         _test_mesh_open_vht_160(dev, apdev)
826     finally:
827         subprocess.call(['iw', 'reg', 'set', '00'])
828         dev[0].flush_scan_cache()
829         dev[1].flush_scan_cache()
830
831 def _test_mesh_open_vht_160(dev, apdev):
832     check_mesh_support(dev[0])
833     subprocess.call(['iw', 'reg', 'set', 'ZA'])
834     for i in range(2):
835         for j in range(5):
836             ev = dev[i].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=5)
837             if ev is None:
838                 raise Exception("No regdom change event")
839             if "alpha2=ZA" in ev:
840                 break
841
842         cmd = subprocess.Popen(["iw", "reg", "get"], stdout=subprocess.PIPE)
843         reg = cmd.stdout.read()
844         if "@ 160)" not in reg:
845             raise HwsimSkip("160 MHz channel not supported in regulatory information")
846
847         add_open_mesh_network(dev[i], freq="5520", chwidth=2)
848
849     # Check for mesh joined
850     check_mesh_group_added(dev[0])
851     check_mesh_group_added(dev[1])
852
853     # Check for peer connected
854     check_mesh_peer_connected(dev[0])
855     check_mesh_peer_connected(dev[1])
856
857     # Test connectivity 0->1 and 1->0
858     hwsim_utils.test_connectivity(dev[0], dev[1])
859
860     sig = dev[0].request("SIGNAL_POLL").splitlines()
861     if "WIDTH=160 MHz" not in sig:
862         raise Exception("Unexpected SIGNAL_POLL value(2): " + str(sig))
863     if "FREQUENCY=5520" not in sig:
864         raise Exception("Unexpected SIGNAL_POLL value(3): " + str(sig))
865
866     sig = dev[1].request("SIGNAL_POLL").splitlines()
867     if "WIDTH=160 MHz" not in sig:
868         raise Exception("Unexpected SIGNAL_POLL value(2b): " + str(sig))
869     if "FREQUENCY=5520" not in sig:
870         raise Exception("Unexpected SIGNAL_POLL value(3b): " + str(sig))
871
872 def test_wpas_mesh_password_mismatch(dev, apdev):
873     """Mesh network and one device with mismatching password"""
874     check_mesh_support(dev[0], secure=True)
875     dev[0].request("SET sae_groups ")
876     id = add_mesh_secure_net(dev[0])
877     dev[0].mesh_group_add(id)
878
879     dev[1].request("SET sae_groups ")
880     id = add_mesh_secure_net(dev[1])
881     dev[1].mesh_group_add(id)
882
883     dev[2].request("SET sae_groups ")
884     id = add_mesh_secure_net(dev[2])
885     dev[2].set_network_quoted(id, "psk", "wrong password")
886     dev[2].mesh_group_add(id)
887
888     # The two peers with matching password need to be able to connect
889     check_mesh_group_added(dev[0])
890     check_mesh_group_added(dev[1])
891     check_mesh_peer_connected(dev[0])
892     check_mesh_peer_connected(dev[1])
893
894     ev = dev[2].wait_event(["MESH-SAE-AUTH-FAILURE"], timeout=20)
895     if ev is None:
896         raise Exception("dev2 did not report auth failure (1)")
897     ev = dev[2].wait_event(["MESH-SAE-AUTH-FAILURE"], timeout=20)
898     if ev is None:
899         raise Exception("dev2 did not report auth failure (2)")
900
901     count = 0
902     ev = dev[0].wait_event(["MESH-SAE-AUTH-FAILURE"], timeout=1)
903     if ev is None:
904         logger.info("dev0 did not report auth failure")
905     else:
906         if "addr=" + dev[2].own_addr() not in ev:
907             raise Exception("Unexpected peer address in dev0 event: " + ev)
908         count += 1
909
910     ev = dev[1].wait_event(["MESH-SAE-AUTH-FAILURE"], timeout=1)
911     if ev is None:
912         logger.info("dev1 did not report auth failure")
913     else:
914         if "addr=" + dev[2].own_addr() not in ev:
915             raise Exception("Unexpected peer address in dev1 event: " + ev)
916         count += 1
917
918     hwsim_utils.test_connectivity(dev[0], dev[1])
919
920     for i in range(2):
921         try:
922             hwsim_utils.test_connectivity(dev[i], dev[2], timeout=1)
923             raise Exception("Data connectivity test passed unexpectedly")
924         except Exception, e:
925             if "data delivery failed" not in str(e):
926                 raise
927
928     if count == 0:
929         raise Exception("Neither dev0 nor dev1 reported auth failure")
930
931 def test_wpas_mesh_password_mismatch_retry(dev, apdev, params):
932     """Mesh password mismatch and retry [long]"""
933     if not params['long']:
934         raise HwsimSkip("Skip test case with long duration due to --long not specified")
935     check_mesh_support(dev[0], secure=True)
936     dev[0].request("SET sae_groups ")
937     id = add_mesh_secure_net(dev[0])
938     dev[0].mesh_group_add(id)
939
940     dev[1].request("SET sae_groups ")
941     id = add_mesh_secure_net(dev[1])
942     dev[1].set_network_quoted(id, "psk", "wrong password")
943     dev[1].mesh_group_add(id)
944
945     # Check for mesh joined
946     check_mesh_group_added(dev[0])
947     check_mesh_group_added(dev[1])
948
949     for i in range(4):
950         ev = dev[0].wait_event(["MESH-SAE-AUTH-FAILURE"], timeout=20)
951         if ev is None:
952             raise Exception("dev0 did not report auth failure (%d)" % i)
953         ev = dev[1].wait_event(["MESH-SAE-AUTH-FAILURE"], timeout=20)
954         if ev is None:
955             raise Exception("dev1 did not report auth failure (%d)" % i)
956
957     ev = dev[0].wait_event(["MESH-SAE-AUTH-BLOCKED"], timeout=10)
958     if ev is None:
959         raise Exception("dev0 did not report auth blocked")
960     ev = dev[1].wait_event(["MESH-SAE-AUTH-BLOCKED"], timeout=10)
961     if ev is None:
962         raise Exception("dev1 did not report auth blocked")
963
964 def test_mesh_wpa_auth_init_oom(dev, apdev):
965     """Secure mesh network setup failing due to wpa_init() OOM"""
966     check_mesh_support(dev[0], secure=True)
967     dev[0].request("SET sae_groups ")
968     with alloc_fail(dev[0], 1, "wpa_init"):
969         id = add_mesh_secure_net(dev[0])
970         dev[0].mesh_group_add(id)
971         ev = dev[0].wait_event(["MESH-GROUP-STARTED"], timeout=0.2)
972         if ev is not None:
973             raise Exception("Unexpected mesh group start during OOM")
974
975 def test_mesh_wpa_init_fail(dev, apdev):
976     """Secure mesh network setup local failure"""
977     check_mesh_support(dev[0], secure=True)
978     dev[0].request("SET sae_groups ")
979
980     with fail_test(dev[0], 1, "os_get_random;=__mesh_rsn_auth_init"):
981         id = add_mesh_secure_net(dev[0])
982         dev[0].mesh_group_add(id)
983         wait_fail_trigger(dev[0], "GET_FAIL")
984
985     dev[0].dump_monitor()
986     with alloc_fail(dev[0], 1, "mesh_rsn_auth_init"):
987         id = add_mesh_secure_net(dev[0])
988         dev[0].mesh_group_add(id)
989         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
990
991     dev[0].dump_monitor()
992     with fail_test(dev[0], 1, "os_get_random;mesh_rsn_init_ampe_sta"):
993         id = add_mesh_secure_net(dev[0])
994         dev[0].mesh_group_add(id)
995         dev[1].request("SET sae_groups ")
996         id = add_mesh_secure_net(dev[1])
997         dev[1].mesh_group_add(id)
998         wait_fail_trigger(dev[0], "GET_FAIL")
999
1000 def test_wpas_mesh_reconnect(dev, apdev):
1001     """Secure mesh network plink counting during reconnection"""
1002     check_mesh_support(dev[0])
1003     try:
1004         _test_wpas_mesh_reconnect(dev)
1005     finally:
1006         dev[0].request("SET max_peer_links 99")
1007
1008 def _test_wpas_mesh_reconnect(dev):
1009     dev[0].request("SET max_peer_links 2")
1010     dev[0].request("SET sae_groups ")
1011     id = add_mesh_secure_net(dev[0])
1012     dev[0].set_network(id, "beacon_int", "100")
1013     dev[0].mesh_group_add(id)
1014     dev[1].request("SET sae_groups ")
1015     id = add_mesh_secure_net(dev[1])
1016     dev[1].mesh_group_add(id)
1017     check_mesh_group_added(dev[0])
1018     check_mesh_group_added(dev[1])
1019     check_mesh_peer_connected(dev[0])
1020     check_mesh_peer_connected(dev[1])
1021
1022     for i in range(3):
1023         # Drop incoming management frames to avoid handling link close
1024         dev[0].request("SET ext_mgmt_frame_handling 1")
1025         dev[1].mesh_group_remove()
1026         check_mesh_group_removed(dev[1])
1027         dev[1].request("FLUSH")
1028         dev[0].request("SET ext_mgmt_frame_handling 0")
1029         id = add_mesh_secure_net(dev[1])
1030         dev[1].mesh_group_add(id)
1031         check_mesh_group_added(dev[1])
1032         check_mesh_peer_connected(dev[1])
1033         dev[0].dump_monitor()
1034         dev[1].dump_monitor()
1035
1036 def test_wpas_mesh_gate_forwarding(dev, apdev, p):
1037     """Mesh forwards traffic to unknown sta to mesh gates"""
1038     addr0 = dev[0].own_addr()
1039     addr1 = dev[1].own_addr()
1040     addr2 = dev[2].own_addr()
1041     external_sta = '02:11:22:33:44:55'
1042
1043     # start 3 node connected mesh
1044     check_mesh_support(dev[0])
1045     for i in range(3):
1046         add_open_mesh_network(dev[i])
1047         check_mesh_group_added(dev[i])
1048     for i in range(3):
1049         check_mesh_peer_connected(dev[i])
1050
1051     hwsim_utils.test_connectivity(dev[0], dev[1])
1052     hwsim_utils.test_connectivity(dev[1], dev[2])
1053     hwsim_utils.test_connectivity(dev[0], dev[2])
1054
1055     # dev0 and dev1 are mesh gates
1056     subprocess.call(['iw', 'dev', dev[0].ifname, 'set', 'mesh_param',
1057                      'mesh_gate_announcements=1'])
1058     subprocess.call(['iw', 'dev', dev[1].ifname, 'set', 'mesh_param',
1059                      'mesh_gate_announcements=1'])
1060
1061     # wait for gate announcement frames
1062     time.sleep(1)
1063
1064     # data frame from dev2 -> external sta should be sent to both gates
1065     dev[2].request("DATA_TEST_CONFIG 1")
1066     dev[2].request("DATA_TEST_TX {} {} 0".format(external_sta, addr2))
1067     dev[2].request("DATA_TEST_CONFIG 0")
1068
1069     capfile = os.path.join(p['logdir'], "hwsim0.pcapng")
1070     filt = "wlan.sa==%s && wlan_mgt.fixed.mesh_addr5==%s" % (addr2,
1071                                                              external_sta)
1072     for i in range(15):
1073         da = run_tshark(capfile, filt, [ "wlan.da" ])
1074         if addr0 in da and addr1 in da:
1075             logger.debug("Frames seen in tshark iteration %d" % i)
1076             break
1077         time.sleep(0.3)
1078
1079     if addr0 not in da:
1080         raise Exception("Frame to gate %s not observed" % addr0)
1081     if addr1 not in da:
1082         raise Exception("Frame to gate %s not observed" % addr1)
1083
1084 def test_wpas_mesh_pmksa_caching(dev, apdev):
1085     """Secure mesh network and PMKSA caching"""
1086     check_mesh_support(dev[0], secure=True)
1087     dev[0].request("SET sae_groups ")
1088     id = add_mesh_secure_net(dev[0])
1089     dev[0].mesh_group_add(id)
1090
1091     dev[1].request("SET sae_groups ")
1092     id = add_mesh_secure_net(dev[1])
1093     dev[1].mesh_group_add(id)
1094
1095     # Check for mesh joined
1096     check_mesh_group_added(dev[0])
1097     check_mesh_group_added(dev[1])
1098
1099     # Check for peer connected
1100     check_mesh_peer_connected(dev[0])
1101     check_mesh_peer_connected(dev[1])
1102
1103     addr0 = dev[0].own_addr()
1104     addr1 = dev[1].own_addr()
1105     pmksa0 = dev[0].get_pmksa(addr1)
1106     pmksa1 = dev[1].get_pmksa(addr0)
1107     if pmksa0 is None or pmksa1 is None:
1108         raise Exception("No PMKSA cache entry created")
1109     if pmksa0['pmkid'] != pmksa1['pmkid']:
1110         raise Exception("PMKID mismatch in PMKSA cache entries")
1111
1112     if "OK" not in dev[0].request("MESH_PEER_REMOVE " + addr1):
1113         raise Exception("Failed to remove peer")
1114     pmksa0b = dev[0].get_pmksa(addr1)
1115     if pmksa0b is None:
1116         raise Exception("PMKSA cache entry not maintained")
1117     time.sleep(0.1)
1118
1119     if "FAIL" not in dev[0].request("MESH_PEER_ADD " + addr1):
1120         raise Exception("MESH_PEER_ADD unexpectedly succeeded in no_auto_peer=0 case")
1121
1122 def test_wpas_mesh_pmksa_caching2(dev, apdev):
1123     """Secure mesh network and PMKSA caching with no_auto_peer=1"""
1124     check_mesh_support(dev[0], secure=True)
1125     addr0 = dev[0].own_addr()
1126     addr1 = dev[1].own_addr()
1127     dev[0].request("SET sae_groups ")
1128     id = add_mesh_secure_net(dev[0])
1129     dev[0].set_network(id, "no_auto_peer", "1")
1130     dev[0].mesh_group_add(id)
1131
1132     dev[1].request("SET sae_groups ")
1133     id = add_mesh_secure_net(dev[1])
1134     dev[1].set_network(id, "no_auto_peer", "1")
1135     dev[1].mesh_group_add(id)
1136
1137     # Check for mesh joined
1138     check_mesh_group_added(dev[0])
1139     check_mesh_group_added(dev[1])
1140
1141     # Check for peer connected
1142     ev = dev[0].wait_event(["will not initiate new peer link"], timeout=10)
1143     if ev is None:
1144         raise Exception("Missing no-initiate message")
1145     if "OK" not in dev[0].request("MESH_PEER_ADD " + addr1):
1146         raise Exception("MESH_PEER_ADD failed")
1147     check_mesh_peer_connected(dev[0])
1148     check_mesh_peer_connected(dev[1])
1149
1150     pmksa0 = dev[0].get_pmksa(addr1)
1151     pmksa1 = dev[1].get_pmksa(addr0)
1152     if pmksa0 is None or pmksa1 is None:
1153         raise Exception("No PMKSA cache entry created")
1154     if pmksa0['pmkid'] != pmksa1['pmkid']:
1155         raise Exception("PMKID mismatch in PMKSA cache entries")
1156
1157     if "OK" not in dev[0].request("MESH_PEER_REMOVE " + addr1):
1158         raise Exception("Failed to remove peer")
1159     pmksa0b = dev[0].get_pmksa(addr1)
1160     if pmksa0b is None:
1161         raise Exception("PMKSA cache entry not maintained")
1162
1163     ev = dev[0].wait_event(["will not initiate new peer link"], timeout=10)
1164     if ev is None:
1165         raise Exception("Missing no-initiate message (2)")
1166     if "OK" not in dev[0].request("MESH_PEER_ADD " + addr1):
1167         raise Exception("MESH_PEER_ADD failed (2)")
1168     check_mesh_peer_connected(dev[0])
1169     check_mesh_peer_connected(dev[1])
1170
1171     pmksa0c = dev[0].get_pmksa(addr1)
1172     pmksa1c = dev[1].get_pmksa(addr0)
1173     if pmksa0c is None or pmksa1c is None:
1174         raise Exception("No PMKSA cache entry created (2)")
1175     if pmksa0c['pmkid'] != pmksa1c['pmkid']:
1176         raise Exception("PMKID mismatch in PMKSA cache entries")
1177     if pmksa0['pmkid'] != pmksa0c['pmkid']:
1178         raise Exception("PMKID changed")
1179
1180     hwsim_utils.test_connectivity(dev[0], dev[1])
1181
1182 def test_wpas_mesh_pmksa_caching_no_match(dev, apdev):
1183     """Secure mesh network and PMKSA caching with no PMKID match"""
1184     check_mesh_support(dev[0], secure=True)
1185     addr0 = dev[0].own_addr()
1186     addr1 = dev[1].own_addr()
1187     dev[0].request("SET sae_groups ")
1188     id = add_mesh_secure_net(dev[0])
1189     dev[0].set_network(id, "no_auto_peer", "1")
1190     dev[0].mesh_group_add(id)
1191
1192     dev[1].request("SET sae_groups ")
1193     id = add_mesh_secure_net(dev[1])
1194     dev[1].set_network(id, "no_auto_peer", "1")
1195     dev[1].mesh_group_add(id)
1196
1197     # Check for mesh joined
1198     check_mesh_group_added(dev[0])
1199     check_mesh_group_added(dev[1])
1200
1201     # Check for peer connected
1202     ev = dev[0].wait_event(["will not initiate new peer link"], timeout=10)
1203     if ev is None:
1204         raise Exception("Missing no-initiate message")
1205     if "OK" not in dev[0].request("MESH_PEER_ADD " + addr1):
1206         raise Exception("MESH_PEER_ADD failed")
1207     check_mesh_peer_connected(dev[0])
1208     check_mesh_peer_connected(dev[1])
1209
1210     pmksa0 = dev[0].get_pmksa(addr1)
1211     pmksa1 = dev[1].get_pmksa(addr0)
1212     if pmksa0 is None or pmksa1 is None:
1213         raise Exception("No PMKSA cache entry created")
1214     if pmksa0['pmkid'] != pmksa1['pmkid']:
1215         raise Exception("PMKID mismatch in PMKSA cache entries")
1216
1217     if "OK" not in dev[0].request("MESH_PEER_REMOVE " + addr1):
1218         raise Exception("Failed to remove peer")
1219
1220     if "OK" not in dev[1].request("PMKSA_FLUSH"):
1221         raise Exception("Failed to flush PMKSA cache")
1222
1223     ev = dev[0].wait_event(["will not initiate new peer link"], timeout=10)
1224     if ev is None:
1225         raise Exception("Missing no-initiate message (2)")
1226     if "OK" not in dev[0].request("MESH_PEER_ADD " + addr1):
1227         raise Exception("MESH_PEER_ADD failed (2)")
1228     check_mesh_peer_connected(dev[0])
1229     check_mesh_peer_connected(dev[1])
1230
1231     pmksa0c = dev[0].get_pmksa(addr1)
1232     pmksa1c = dev[1].get_pmksa(addr0)
1233     if pmksa0c is None or pmksa1c is None:
1234         raise Exception("No PMKSA cache entry created (2)")
1235     if pmksa0c['pmkid'] != pmksa1c['pmkid']:
1236         raise Exception("PMKID mismatch in PMKSA cache entries")
1237     if pmksa0['pmkid'] == pmksa0c['pmkid']:
1238         raise Exception("PMKID did not change")
1239
1240     hwsim_utils.test_connectivity(dev[0], dev[1])
1241
1242 def test_mesh_pmksa_caching_oom(dev, apdev):
1243     """Secure mesh network and PMKSA caching failing due to OOM"""
1244     check_mesh_support(dev[0], secure=True)
1245     addr0 = dev[0].own_addr()
1246     addr1 = dev[1].own_addr()
1247     dev[0].request("SET sae_groups ")
1248     id = add_mesh_secure_net(dev[0])
1249     dev[0].set_network(id, "no_auto_peer", "1")
1250     dev[0].mesh_group_add(id)
1251
1252     dev[1].request("SET sae_groups ")
1253     id = add_mesh_secure_net(dev[1])
1254     dev[1].set_network(id, "no_auto_peer", "1")
1255     dev[1].mesh_group_add(id)
1256
1257     # Check for mesh joined
1258     check_mesh_group_added(dev[0])
1259     check_mesh_group_added(dev[1])
1260
1261     # Check for peer connected
1262     ev = dev[0].wait_event(["will not initiate new peer link"], timeout=10)
1263     if ev is None:
1264         raise Exception("Missing no-initiate message")
1265     if "OK" not in dev[0].request("MESH_PEER_ADD " + addr1):
1266         raise Exception("MESH_PEER_ADD failed")
1267     check_mesh_peer_connected(dev[0])
1268     check_mesh_peer_connected(dev[1])
1269
1270     if "OK" not in dev[0].request("MESH_PEER_REMOVE " + addr1):
1271         raise Exception("Failed to remove peer")
1272     pmksa0b = dev[0].get_pmksa(addr1)
1273     if pmksa0b is None:
1274         raise Exception("PMKSA cache entry not maintained")
1275
1276     ev = dev[0].wait_event(["will not initiate new peer link"], timeout=10)
1277     if ev is None:
1278         raise Exception("Missing no-initiate message (2)")
1279
1280     with alloc_fail(dev[0], 1, "wpa_auth_sta_init;mesh_rsn_auth_sae_sta"):
1281         if "OK" not in dev[0].request("MESH_PEER_ADD " + addr1):
1282             raise Exception("MESH_PEER_ADD failed (2)")
1283         wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
1284
1285 def test_mesh_oom(dev, apdev):
1286     """Mesh network setup failing due to OOM"""
1287     check_mesh_support(dev[0], secure=True)
1288     dev[0].request("SET sae_groups ")
1289
1290     with alloc_fail(dev[0], 1, "mesh_config_create"):
1291         add_open_mesh_network(dev[0])
1292         ev = dev[0].wait_event(["Failed to init mesh"])
1293         if ev is None:
1294             raise Exception("Init failure not reported")
1295
1296     with alloc_fail(dev[0], 4, "=wpa_supplicant_mesh_init"):
1297         add_open_mesh_network(dev[0], basic_rates="60 120 240")
1298         ev = dev[0].wait_event(["Failed to init mesh"])
1299         if ev is None:
1300             raise Exception("Init failure not reported")
1301
1302     for i in range(1, 66):
1303         dev[0].dump_monitor()
1304         logger.info("Test instance %d" % i)
1305         try:
1306             with alloc_fail(dev[0], i, "wpa_supplicant_mesh_init"):
1307                 add_open_mesh_network(dev[0])
1308                 wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
1309                 ev = dev[0].wait_event(["Failed to init mesh",
1310                                         "MESH-GROUP-STARTED"])
1311                 if ev is None:
1312                     raise Exception("Init failure not reported")
1313         except Exception, e:
1314             if i < 15:
1315                 raise
1316             logger.info("Ignore no-oom for i=%d" % i)
1317
1318     with alloc_fail(dev[0], 5, "=wpa_supplicant_mesh_init"):
1319         id = add_mesh_secure_net(dev[0])
1320         dev[0].mesh_group_add(id)
1321         ev = dev[0].wait_event(["Failed to init mesh"])
1322         if ev is None:
1323             raise Exception("Init failure not reported")
1324
1325 def test_mesh_add_interface_oom(dev):
1326     """wpa_supplicant mesh with dynamic interface addition failing"""
1327     check_mesh_support(dev[0])
1328     for i in range(1, 3):
1329         mesh = None
1330         try:
1331             with alloc_fail(dev[0], i, "wpas_mesh_add_interface"):
1332                 mesh = dev[0].request("MESH_INTERFACE_ADD").strip()
1333         finally:
1334             if mesh and mesh != "FAIL":
1335                 dev[0].request("MESH_GROUP_REMOVE " + mesh)
1336
1337 def test_mesh_scan_oom(dev):
1338     """wpa_supplicant mesh scan results and OOM"""
1339     check_mesh_support(dev[0])
1340     add_open_mesh_network(dev[0])
1341     check_mesh_group_added(dev[0])
1342     for i in range(5):
1343         dev[1].scan(freq="2412")
1344         res = dev[1].request("SCAN_RESULTS")
1345         if "[MESH]" in res:
1346             break
1347     for r in res.splitlines():
1348         if "[MESH]" in r:
1349             break
1350     bssid = r.split('\t')[0]
1351
1352     bss = dev[1].get_bss(bssid)
1353     if bss is None:
1354         raise Exception("Could not get BSS entry for mesh")
1355
1356     for i in range(1, 3):
1357         with alloc_fail(dev[1], i, "mesh_attr_text"):
1358             bss = dev[1].get_bss(bssid)
1359             if bss and "mesh_id" in bss:
1360                 raise Exception("Unexpected BSS result during OOM")
1361
1362 def test_mesh_drv_fail(dev, apdev):
1363     """Mesh network setup failing due to driver command failure"""
1364     check_mesh_support(dev[0], secure=True)
1365     dev[0].request("SET sae_groups ")
1366
1367     with fail_test(dev[0], 1, "nl80211_join_mesh"):
1368         add_open_mesh_network(dev[0])
1369         ev = dev[0].wait_event(["mesh join error"])
1370         if ev is None:
1371             raise Exception("Join failure not reported")
1372
1373     dev[0].dump_monitor()
1374     with fail_test(dev[0], 1, "wpa_driver_nl80211_if_add"):
1375         if "FAIL" not in dev[0].request("MESH_INTERFACE_ADD").strip():
1376             raise Exception("Interface added unexpectedly")
1377
1378     dev[0].dump_monitor()
1379     with fail_test(dev[0], 1, "wpa_driver_nl80211_init_mesh"):
1380         add_open_mesh_network(dev[0])
1381         ev = dev[0].wait_event(["Could not join mesh"])
1382         if ev is None:
1383             raise Exception("Join failure not reported")
1384
1385 def test_mesh_sae_groups_invalid(dev, apdev):
1386     """Mesh with invalid SAE group configuration"""
1387     check_mesh_support(dev[0], secure=True)
1388
1389     dev[0].request("SET sae_groups 25")
1390     id = add_mesh_secure_net(dev[0])
1391     dev[0].mesh_group_add(id)
1392
1393     dev[1].request("SET sae_groups 123 122 121")
1394     id = add_mesh_secure_net(dev[1])
1395     dev[1].mesh_group_add(id)
1396
1397     check_mesh_group_added(dev[0])
1398     check_mesh_group_added(dev[1])
1399
1400     ev = dev[0].wait_event(["new peer notification"], timeout=10)
1401     if ev is None:
1402         raise Exception("dev[0] did not see peer")
1403     ev = dev[1].wait_event(["new peer notification"], timeout=10)
1404     if ev is None:
1405         raise Exception("dev[1] did not see peer")
1406
1407     ev = dev[0].wait_event(["MESH-PEER-CONNECTED"], timeout=0.1)
1408     if ev is not None:
1409         raise Exception("Unexpected connection(0)")
1410
1411     ev = dev[1].wait_event(["MESH-PEER-CONNECTED"], timeout=0.01)
1412     if ev is not None:
1413         raise Exception("Unexpected connection(1)")
1414
1415     # Additional coverage in mesh_rsn_sae_group() with non-zero
1416     # wpa_s->mesh_rsn->sae_group_index.
1417     dev[0].dump_monitor()
1418     dev[1].dump_monitor()
1419     id = add_mesh_secure_net(dev[2])
1420     dev[2].mesh_group_add(id)
1421     check_mesh_group_added(dev[2])
1422     check_mesh_peer_connected(dev[0])
1423     check_mesh_peer_connected(dev[2])
1424     ev = dev[1].wait_event(["new peer notification"], timeout=10)
1425     if ev is None:
1426         raise Exception("dev[1] did not see peer(2)")
1427     dev[0].dump_monitor()
1428     dev[1].dump_monitor()
1429     dev[2].dump_monitor()
1430
1431     dev[0].request("SET sae_groups ")
1432     dev[1].request("SET sae_groups ")
1433
1434 def test_mesh_sae_failure(dev, apdev):
1435     """Mesh and local SAE failures"""
1436     check_mesh_support(dev[0], secure=True)
1437
1438     dev[0].request("SET sae_groups ")
1439     dev[1].request("SET sae_groups ")
1440
1441     funcs = [ (1, "=mesh_rsn_auth_sae_sta", True),
1442               (1, "mesh_rsn_build_sae_commit;mesh_rsn_auth_sae_sta", False),
1443               (1, "auth_sae_init_committed;mesh_rsn_auth_sae_sta", True),
1444               (1, "=mesh_rsn_protect_frame", True),
1445               (2, "=mesh_rsn_protect_frame", True),
1446               (1, "aes_siv_encrypt;mesh_rsn_protect_frame", True),
1447               (1, "=mesh_rsn_process_ampe", True),
1448               (1, "aes_siv_decrypt;mesh_rsn_process_ampe", True) ]
1449     for count, func, success in funcs:
1450         id = add_mesh_secure_net(dev[0])
1451         dev[0].mesh_group_add(id)
1452
1453         with alloc_fail(dev[1], count, func):
1454             id = add_mesh_secure_net(dev[1])
1455             dev[1].mesh_group_add(id)
1456             check_mesh_group_added(dev[0])
1457             check_mesh_group_added(dev[1])
1458             if success:
1459                 # retry is expected to work
1460                 check_mesh_peer_connected(dev[0])
1461                 check_mesh_peer_connected(dev[1])
1462             else:
1463                 wait_fail_trigger(dev[1], "GET_ALLOC_FAIL")
1464         dev[0].mesh_group_remove()
1465         dev[1].mesh_group_remove()
1466         check_mesh_group_removed(dev[0])
1467         check_mesh_group_removed(dev[1])
1468
1469 def test_mesh_failure(dev, apdev):
1470     """Mesh and local failures"""
1471     check_mesh_support(dev[0])
1472
1473     funcs = [ (1, "ap_sta_add;mesh_mpm_add_peer", True),
1474               (1, "wpabuf_alloc;mesh_mpm_send_plink_action", True) ]
1475     for count, func, success in funcs:
1476         add_open_mesh_network(dev[0])
1477
1478         with alloc_fail(dev[1], count, func):
1479             add_open_mesh_network(dev[1])
1480             check_mesh_group_added(dev[0])
1481             check_mesh_group_added(dev[1])
1482             if success:
1483                 # retry is expected to work
1484                 check_mesh_peer_connected(dev[0])
1485                 check_mesh_peer_connected(dev[1])
1486             else:
1487                 wait_fail_trigger(dev[1], "GET_ALLOC_FAIL")
1488         dev[0].mesh_group_remove()
1489         dev[1].mesh_group_remove()
1490         check_mesh_group_removed(dev[0])
1491         check_mesh_group_removed(dev[1])
1492
1493     funcs = [ (1, "mesh_mpm_init_link", True) ]
1494     for count, func, success in funcs:
1495         add_open_mesh_network(dev[0])
1496
1497         with fail_test(dev[1], count, func):
1498             add_open_mesh_network(dev[1])
1499             check_mesh_group_added(dev[0])
1500             check_mesh_group_added(dev[1])
1501             if success:
1502                 # retry is expected to work
1503                 check_mesh_peer_connected(dev[0])
1504                 check_mesh_peer_connected(dev[1])
1505             else:
1506                 wait_fail_trigger(dev[1], "GET_FAIL")
1507         dev[0].mesh_group_remove()
1508         dev[1].mesh_group_remove()
1509         check_mesh_group_removed(dev[0])
1510         check_mesh_group_removed(dev[1])
1511
1512 def test_mesh_invalid_frequency(dev, apdev):
1513     """Mesh and invalid frequency configuration"""
1514     check_mesh_support(dev[0])
1515     add_open_mesh_network(dev[0], freq=None)
1516     ev = dev[0].wait_event(["MESH-GROUP-STARTED",
1517                             "Could not join mesh"])
1518     if ev is None or "Could not join mesh" not in ev:
1519         raise Exception("Mesh join failure not reported")
1520     dev[0].request("REMOVE_NETWORK all")
1521
1522     add_open_mesh_network(dev[0], freq="2413")
1523     ev = dev[0].wait_event(["MESH-GROUP-STARTED",
1524                             "Could not join mesh"])
1525     if ev is None or "Could not join mesh" not in ev:
1526         raise Exception("Mesh join failure not reported")
1527
1528 def test_mesh_default_beacon_int(dev, apdev):
1529     """Mesh and default beacon interval"""
1530     check_mesh_support(dev[0])
1531     try:
1532         dev[0].request("SET beacon_int 200")
1533         add_open_mesh_network(dev[0])
1534         check_mesh_group_added(dev[0])
1535     finally:
1536         dev[0].request("SET beacon_int 0")
1537
1538 def test_mesh_scan_parse_error(dev, apdev):
1539     """Mesh scan element parse error"""
1540     check_mesh_support(dev[0])
1541     params = { "ssid": "open",
1542                "beacon_int": "2000" }
1543     hapd = hostapd.add_ap(apdev[0], params)
1544     bssid = apdev[0]['bssid']
1545     hapd.set('vendor_elements', 'dd0201')
1546     for i in range(10):
1547         dev[0].scan(freq=2412)
1548         if bssid in dev[0].request("SCAN_RESULTS"):
1549             break
1550     # This will fail in IE parsing due to the truncated IE in the Probe
1551     # Response frame.
1552     bss = dev[0].request("BSS " + bssid)
1553
1554 def test_mesh_missing_mic(dev, apdev):
1555     """Secure mesh network and missing MIC"""
1556     check_mesh_support(dev[0], secure=True)
1557
1558     dev[0].request("SET ext_mgmt_frame_handling 1")
1559     dev[0].request("SET sae_groups ")
1560     id = add_mesh_secure_net(dev[0])
1561     dev[0].mesh_group_add(id)
1562
1563     dev[1].request("SET sae_groups ")
1564     id = add_mesh_secure_net(dev[1])
1565     dev[1].mesh_group_add(id)
1566
1567     # Check for mesh joined
1568     check_mesh_group_added(dev[0])
1569     check_mesh_group_added(dev[1])
1570
1571     count = 0
1572     remove_mic = True
1573     while True:
1574         count += 1
1575         if count > 15:
1576             raise Exception("Did not see Action frames")
1577         rx_msg = dev[0].mgmt_rx()
1578         if rx_msg is None:
1579             ev = dev[1].wait_event(["MESH-PEER-CONNECTED"], timeout=0.01)
1580             if ev:
1581                 break
1582             raise Exception("MGMT-RX timeout")
1583         if rx_msg['subtype'] == 13:
1584             payload = rx_msg['payload']
1585             frame = rx_msg['frame']
1586             (categ, action) = struct.unpack('BB', payload[0:2])
1587             if categ == 15 and action == 1 and remove_mic:
1588                 # Mesh Peering Open
1589                 pos = frame.find('\x8c\x10')
1590                 if not pos:
1591                     raise Exception("Could not find MIC element")
1592                 logger.info("Found MIC at %d" % pos)
1593                 # Remove MIC
1594                 rx_msg['frame'] = frame[0:pos]
1595                 remove_mic = False
1596         if "OK" not in dev[0].request("MGMT_RX_PROCESS freq={} datarate={} ssi_signal={} frame={}".format(rx_msg['freq'], rx_msg['datarate'], rx_msg['ssi_signal'], rx_msg['frame'].encode('hex'))):
1597             raise Exception("MGMT_RX_PROCESS failed")
1598         ev = dev[1].wait_event(["MESH-PEER-CONNECTED"], timeout=0.01)
1599         if ev:
1600             break
1601
1602 def test_mesh_pmkid_mismatch(dev, apdev):
1603     """Secure mesh network and PMKID mismatch"""
1604     check_mesh_support(dev[0], secure=True)
1605     addr0 = dev[0].own_addr()
1606     addr1 = dev[1].own_addr()
1607     dev[0].request("SET sae_groups ")
1608     id = add_mesh_secure_net(dev[0])
1609     dev[0].set_network(id, "no_auto_peer", "1")
1610     dev[0].mesh_group_add(id)
1611
1612     dev[1].request("SET sae_groups ")
1613     id = add_mesh_secure_net(dev[1])
1614     dev[1].set_network(id, "no_auto_peer", "1")
1615     dev[1].mesh_group_add(id)
1616
1617     # Check for mesh joined
1618     check_mesh_group_added(dev[0])
1619     check_mesh_group_added(dev[1])
1620
1621     # Check for peer connected
1622     ev = dev[0].wait_event(["will not initiate new peer link"], timeout=10)
1623     if ev is None:
1624         raise Exception("Missing no-initiate message")
1625     if "OK" not in dev[0].request("MESH_PEER_ADD " + addr1):
1626         raise Exception("MESH_PEER_ADD failed")
1627     check_mesh_peer_connected(dev[0])
1628     check_mesh_peer_connected(dev[1])
1629
1630     if "OK" not in dev[0].request("MESH_PEER_REMOVE " + addr1):
1631         raise Exception("Failed to remove peer")
1632
1633     ev = dev[0].wait_event(["will not initiate new peer link"], timeout=10)
1634     if ev is None:
1635         raise Exception("Missing no-initiate message (2)")
1636     dev[0].dump_monitor()
1637     dev[1].dump_monitor()
1638     dev[0].request("SET ext_mgmt_frame_handling 1")
1639     if "OK" not in dev[0].request("MESH_PEER_ADD " + addr1):
1640         raise Exception("MESH_PEER_ADD failed (2)")
1641
1642     count = 0
1643     break_pmkid = True
1644     while True:
1645         count += 1
1646         if count > 50:
1647             raise Exception("Did not see Action frames")
1648         rx_msg = dev[0].mgmt_rx()
1649         if rx_msg is None:
1650             ev = dev[1].wait_event(["MESH-PEER-CONNECTED"], timeout=0.1)
1651             if ev:
1652                 break
1653             raise Exception("MGMT-RX timeout")
1654         if rx_msg['subtype'] == 13:
1655             payload = rx_msg['payload']
1656             frame = rx_msg['frame']
1657             (categ, action) = struct.unpack('BB', payload[0:2])
1658             if categ == 15 and action == 1 and break_pmkid:
1659                 # Mesh Peering Open
1660                 pos = frame.find('\x75\x14')
1661                 if not pos:
1662                     raise Exception("Could not find Mesh Peering Management element")
1663                 logger.info("Found Mesh Peering Management element at %d" % pos)
1664                 # Break PMKID to hit "Mesh RSN: Invalid PMKID (Chosen PMK did
1665                 # not match calculated PMKID)"
1666                 rx_msg['frame'] = frame[0:pos + 6] + '\x00\x00\x00\x00' + frame[pos + 10:]
1667                 break_pmkid = False
1668         if "OK" not in dev[0].request("MGMT_RX_PROCESS freq={} datarate={} ssi_signal={} frame={}".format(rx_msg['freq'], rx_msg['datarate'], rx_msg['ssi_signal'], rx_msg['frame'].encode('hex'))):
1669             raise Exception("MGMT_RX_PROCESS failed")
1670         ev = dev[1].wait_event(["MESH-PEER-CONNECTED"], timeout=0.01)
1671         if ev:
1672             break
1673
1674 def test_mesh_peering_proto(dev, apdev):
1675     """Mesh peering management protocol testing"""
1676     check_mesh_support(dev[0])
1677
1678     dev[0].request("SET ext_mgmt_frame_handling 1")
1679     add_open_mesh_network(dev[0], beacon_int=160)
1680     add_open_mesh_network(dev[1], beacon_int=160)
1681
1682     count = 0
1683     test = 1
1684     while True:
1685         count += 1
1686         if count > 50:
1687             raise Exception("Did not see Action frames")
1688         rx_msg = dev[0].mgmt_rx()
1689         if rx_msg is None:
1690             ev = dev[1].wait_event(["MESH-PEER-CONNECTED"], timeout=0.01)
1691             if ev:
1692                 break
1693             raise Exception("MGMT-RX timeout")
1694         if rx_msg['subtype'] == 13:
1695             payload = rx_msg['payload']
1696             frame = rx_msg['frame']
1697             (categ, action) = struct.unpack('BB', payload[0:2])
1698             if categ == 15 and action == 1 and test == 1:
1699                 # Mesh Peering Open
1700                 pos = frame.find('\x75\x04')
1701                 if not pos:
1702                     raise Exception("Could not find Mesh Peering Management element")
1703                 logger.info("Found Mesh Peering Management element at %d" % pos)
1704                 # Remove the element to hit
1705                 # "MPM: No Mesh Peering Management element"
1706                 rx_msg['frame'] = frame[0:pos]
1707                 test += 1
1708             elif categ == 15 and action == 1 and test == 2:
1709                 # Mesh Peering Open
1710                 pos = frame.find('\x72\x0e')
1711                 if not pos:
1712                     raise Exception("Could not find Mesh ID element")
1713                 logger.info("Found Mesh ID element at %d" % pos)
1714                 # Remove the element to hit
1715                 # "MPM: No Mesh ID or Mesh Configuration element"
1716                 rx_msg['frame'] = frame[0:pos] + frame[pos + 16:]
1717                 test += 1
1718             elif categ == 15 and action == 1 and test == 3:
1719                 # Mesh Peering Open
1720                 pos = frame.find('\x72\x0e')
1721                 if not pos:
1722                     raise Exception("Could not find Mesh ID element")
1723                 logger.info("Found Mesh ID element at %d" % pos)
1724                 # Replace Mesh ID to hit "MPM: Mesh ID or Mesh Configuration
1725                 # element do not match local MBSS"
1726                 rx_msg['frame'] = frame[0:pos] + '\x72\x0etest-test-test' + frame[pos + 16:]
1727                 test += 1
1728             elif categ == 15 and action == 1 and test == 4:
1729                 # Mesh Peering Open
1730                 # Remove IEs to hit
1731                 # "MPM: Ignore too short action frame 1 ie_len 0"
1732                 rx_msg['frame'] = frame[0:26]
1733                 test += 1
1734             elif categ == 15 and action == 1 and test == 5:
1735                 # Mesh Peering Open
1736                 # Truncate IEs to hit
1737                 # "MPM: Failed to parse PLINK IEs"
1738                 rx_msg['frame'] = frame[0:30]
1739                 test += 1
1740             elif categ == 15 and action == 1 and test == 6:
1741                 # Mesh Peering Open
1742                 pos = frame.find('\x75\x04')
1743                 if not pos:
1744                     raise Exception("Could not find Mesh Peering Management element")
1745                 logger.info("Found Mesh Peering Management element at %d" % pos)
1746                 # Truncate the element to hit
1747                 # "MPM: Invalid peer mgmt ie" and
1748                 # "MPM: Mesh parsing rejected frame"
1749                 rx_msg['frame'] = frame[0:pos] + '\x75\x00\x00\x00' + frame[pos + 6:]
1750                 test += 1
1751         if "OK" not in dev[0].request("MGMT_RX_PROCESS freq={} datarate={} ssi_signal={} frame={}".format(rx_msg['freq'], rx_msg['datarate'], rx_msg['ssi_signal'], rx_msg['frame'].encode('hex'))):
1752             raise Exception("MGMT_RX_PROCESS failed")
1753         ev = dev[1].wait_event(["MESH-PEER-CONNECTED"], timeout=0.01)
1754         if ev:
1755             break
1756
1757     if test != 7:
1758         raise Exception("Not all test frames completed")
1759
1760 def test_mesh_mpm_init_proto(dev, apdev):
1761     """Mesh peering management protocol testing for peer addition"""
1762     check_mesh_support(dev[0])
1763     add_open_mesh_network(dev[0])
1764     check_mesh_group_added(dev[0])
1765     dev[0].dump_monitor()
1766
1767     dev[0].request("SET ext_mgmt_frame_handling 1")
1768
1769     addr = "020000000100"
1770     hdr = "d000ac00020000000000" + addr + addr + "1000"
1771     fixed = "0f010000"
1772     supp_rates = "010802040b168c129824"
1773     ext_supp_rates = "3204b048606c"
1774     mesh_id = "720e777061732d6d6573682d6f70656e"
1775     mesh_conf = "710701010001000009"
1776     mpm = "75040000079d"
1777     ht_capab = "2d1a7c001bffff000000000000000000000100000000000000000000"
1778     ht_oper = "3d160b000000000000000000000000000000000000000000"
1779
1780     dev[0].request("NOTE no supported rates")
1781     frame = hdr + fixed + ext_supp_rates + mesh_id + mesh_conf + mpm + ht_capab + ht_oper
1782     if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % frame):
1783         raise Exception("MGMT_RX_PROCESS failed")
1784
1785     dev[0].request("NOTE Invalid supported rates element length 33+0")
1786     long_supp_rates = "012100112233445566778899aabbccddeeff00112233445566778899aabbccddeeff00"
1787     frame = hdr + fixed + long_supp_rates + mesh_id + mesh_conf + mpm + ht_capab + ht_oper
1788     if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % frame):
1789         raise Exception("MGMT_RX_PROCESS failed")
1790
1791     dev[0].request("NOTE Too short mesh config")
1792     short_mesh_conf = "710401010001"
1793     frame = hdr + fixed + supp_rates + mesh_id + short_mesh_conf + mpm + ht_capab + ht_oper
1794     if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % frame):
1795         raise Exception("MGMT_RX_PROCESS failed")
1796
1797     dev[0].request("NOTE Add STA failure")
1798     frame = hdr + fixed + supp_rates + ext_supp_rates + mesh_id + mesh_conf + mpm + ht_capab + ht_oper
1799     with fail_test(dev[0], 1, "wpa_driver_nl80211_sta_add"):
1800         if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % frame):
1801             raise Exception("MGMT_RX_PROCESS failed")
1802
1803     dev[0].request("NOTE Send Action failure")
1804     with fail_test(dev[0], 1, "driver_nl80211_send_action"):
1805         if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % frame):
1806             raise Exception("MGMT_RX_PROCESS failed")
1807
1808     dev[0].request("NOTE Set STA failure")
1809     addr = "020000000101"
1810     hdr = "d000ac00020000000000" + addr + addr + "1000"
1811     frame = hdr + fixed + supp_rates + ext_supp_rates + mesh_id + mesh_conf + mpm + ht_capab + ht_oper
1812     with fail_test(dev[0], 2, "wpa_driver_nl80211_sta_add"):
1813         if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % frame):
1814             raise Exception("MGMT_RX_PROCESS failed")
1815
1816     dev[0].request("NOTE ap_sta_add OOM")
1817     addr = "020000000102"
1818     hdr = "d000ac00020000000000" + addr + addr + "1000"
1819     frame = hdr + fixed + supp_rates + ext_supp_rates + mesh_id + mesh_conf + mpm + ht_capab + ht_oper
1820     with alloc_fail(dev[0], 1, "ap_sta_add"):
1821         if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % frame):
1822             raise Exception("MGMT_RX_PROCESS failed")
1823
1824     dev[0].request("NOTE hostapd_get_aid() failure")
1825     addr = "020000000103"
1826     hdr = "d000ac00020000000000" + addr + addr + "1000"
1827     frame = hdr + fixed + supp_rates + ext_supp_rates + mesh_id + mesh_conf + mpm + ht_capab + ht_oper
1828     with fail_test(dev[0], 1, "hostapd_get_aid"):
1829         if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % frame):
1830             raise Exception("MGMT_RX_PROCESS failed")
1831
1832     if "OK" not in dev[0].request("MESH_PEER_REMOVE 02:00:00:00:01:00"):
1833         raise Exception("Failed to remove peer")
1834     if "FAIL" not in dev[0].request("MESH_PEER_REMOVE 02:00:00:00:01:02"):
1835         raise Exception("Unexpected MESH_PEER_REMOVE success")
1836     if "FAIL" not in dev[1].request("MESH_PEER_REMOVE 02:00:00:00:01:02"):
1837         raise Exception("Unexpected MESH_PEER_REMOVE success(2)")
1838     if "FAIL" not in dev[1].request("MESH_PEER_ADD 02:00:00:00:01:02"):
1839         raise Exception("Unexpected MESH_PEER_ADD success")
1840
1841 def test_mesh_holding(dev, apdev):
1842     """Mesh MPM FSM and HOLDING state event OPN_ACPT"""
1843     check_mesh_support(dev[0])
1844     add_open_mesh_network(dev[0])
1845     add_open_mesh_network(dev[1])
1846     check_mesh_group_added(dev[0])
1847     check_mesh_group_added(dev[1])
1848     check_mesh_peer_connected(dev[0])
1849     check_mesh_peer_connected(dev[1])
1850
1851     addr0 = dev[0].own_addr()
1852     addr1 = dev[1].own_addr()
1853
1854     dev[0].request("SET ext_mgmt_frame_handling 1")
1855     if "OK" not in dev[0].request("MESH_PEER_REMOVE " + addr1):
1856         raise Exception("Failed to remove peer")
1857
1858     rx_msg = dev[0].mgmt_rx()
1859     if rx_msg is None:
1860         raise Exception("MGMT-RX timeout")
1861     if rx_msg['subtype'] != 13:
1862         raise Exception("Unexpected management frame")
1863     payload = rx_msg['payload']
1864     (categ, action) = struct.unpack('BB', payload[0:2])
1865     if categ != 0x0f or action != 0x03:
1866         raise Exception("Did not see Mesh Peering Close")
1867
1868     peer_lid = payload[-6:-4].encode("hex")
1869     my_lid = payload[-4:-2].encode("hex")
1870
1871     # Drop Mesh Peering Close and instead, process an unexpected Mesh Peering
1872     # Open to trigger transmission of another Mesh Peering Close in the HOLDING
1873     # state based on an OPN_ACPT event.
1874
1875     dst = addr0.replace(':', '')
1876     src = addr1.replace(':', '')
1877     hdr = "d000ac00" + dst + src + src + "1000"
1878     fixed = "0f010000"
1879     supp_rates = "010802040b168c129824"
1880     ext_supp_rates = "3204b048606c"
1881     mesh_id = "720e777061732d6d6573682d6f70656e"
1882     mesh_conf = "710701010001000009"
1883     mpm = "7504" + my_lid + peer_lid
1884     ht_capab = "2d1a7c001bffff000000000000000000000100000000000000000000"
1885     ht_oper = "3d160b000000000000000000000000000000000000000000"
1886
1887     frame = hdr + fixed + supp_rates + ext_supp_rates + mesh_id + mesh_conf + mpm + ht_capab + ht_oper
1888     if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % frame):
1889         raise Exception("MGMT_RX_PROCESS failed")
1890     time.sleep(0.1)
1891
1892 def test_mesh_cnf_rcvd_event_cls_acpt(dev, apdev):
1893     """Mesh peering management protocol testing - CLS_ACPT event in CNF_RCVD"""
1894     check_mesh_support(dev[0])
1895     add_open_mesh_network(dev[0])
1896     check_mesh_group_added(dev[0])
1897     dev[0].dump_monitor()
1898
1899     dev[0].request("SET ext_mgmt_frame_handling 1")
1900     add_open_mesh_network(dev[1])
1901     check_mesh_group_added(dev[1])
1902
1903     addr0 = dev[0].own_addr()
1904     addr1 = dev[1].own_addr()
1905
1906     rx_msg = dev[0].mgmt_rx()
1907     # Drop Mesh Peering Open
1908
1909     rx_msg = dev[0].mgmt_rx()
1910     # Allow Mesh Peering Confirm to go through
1911     if "OK" not in dev[0].request("MGMT_RX_PROCESS freq={} datarate={} ssi_signal={} frame={}".format(rx_msg['freq'], rx_msg['datarate'], rx_msg['ssi_signal'], rx_msg['frame'].encode('hex'))):
1912         raise Exception("MGMT_RX_PROCESS failed")
1913
1914     payload = rx_msg['payload']
1915     peer_lid = payload[51:53].encode("hex")
1916     my_lid = payload[53:55].encode("hex")
1917
1918     dst = addr0.replace(':', '')
1919     src = addr1.replace(':', '')
1920     hdr = "d000ac00" + dst + src + src + "1000"
1921     fixed = "0f03"
1922     mesh_id = "720e777061732d6d6573682d6f70656e"
1923     mpm = "75080000" + peer_lid + my_lid + "3700"
1924     frame = hdr + fixed + mesh_id + mpm
1925
1926     # Inject Mesh Peering Close to hit "state CNF_RCVD event CLS_ACPT" to
1927     # HOLDING transition.
1928     if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=" + frame):
1929         raise Exception("MGMT_RX_PROCESS failed")
1930
1931 def test_mesh_opn_snt_event_cls_acpt(dev, apdev):
1932     """Mesh peering management protocol testing - CLS_ACPT event in OPN_SNT"""
1933     check_mesh_support(dev[0])
1934     add_open_mesh_network(dev[0])
1935     check_mesh_group_added(dev[0])
1936     dev[0].dump_monitor()
1937
1938     dev[0].request("SET ext_mgmt_frame_handling 1")
1939     add_open_mesh_network(dev[1])
1940     check_mesh_group_added(dev[1])
1941
1942     addr0 = dev[0].own_addr()
1943     addr1 = dev[1].own_addr()
1944
1945     rx_msg = dev[0].mgmt_rx()
1946     # Drop Mesh Peering Open
1947
1948     rx_msg = dev[0].mgmt_rx()
1949     # Drop Mesh Peering Confirm
1950
1951     payload = rx_msg['payload']
1952     peer_lid = "0000"
1953     my_lid = payload[53:55].encode("hex")
1954
1955     dst = addr0.replace(':', '')
1956     src = addr1.replace(':', '')
1957     hdr = "d000ac00" + dst + src + src + "1000"
1958     fixed = "0f03"
1959     mesh_id = "720e777061732d6d6573682d6f70656e"
1960     mpm = "75080000" + peer_lid + my_lid + "3700"
1961     frame = hdr + fixed + mesh_id + mpm
1962
1963     # Inject Mesh Peering Close to hit "state OPN_SNTevent CLS_ACPT" to
1964     # HOLDING transition.
1965     if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=" + frame):
1966         raise Exception("MGMT_RX_PROCESS failed")