1# wpa_supplicant config file
2# Copyright (c) 2014, Jouni Malinen <j@w1.fi>
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
10
11from wpasupplicant import WpaSupplicant
12import hostapd
13from utils import *
14
15config_checks = [("ap_scan", "0"),
16                 ("update_config", "1"),
17                 ("device_name", "name"),
18                 ("eapol_version", "2"),
19                 ("wps_priority", "5"),
20                 ("ip_addr_go", "192.168.1.1"),
21                 ("ip_addr_mask", "255.255.255.0"),
22                 ("ip_addr_start", "192.168.1.10"),
23                 ("ip_addr_end", "192.168.1.20"),
24                 ("disable_scan_offload", "1"),
25                 ("fast_reauth", "0"),
26                 ("uuid", "6aeae5e3-c1fc-4e76-8293-7346e1d1459d"),
27                 ("manufacturer", "MANUF"),
28                 ("model_name", "MODEL"),
29                 ("model_number", "MODEL NUM"),
30                 ("serial_number", "123qwerty"),
31                 ("device_type", "1234-0050F204-4321"),
32                 ("os_version", "01020304"),
33                 ("config_methods", "label push_button"),
34                 ("wps_cred_processing", "1"),
35                 ("wps_vendor_ext_m1", "000137100100020001"),
36                 ("p2p_listen_reg_class", "81"),
37                 ("p2p_listen_channel", "6"),
38                 ("p2p_oper_reg_class", "82"),
39                 ("p2p_oper_channel", "14"),
40                 ("p2p_go_intent", "14"),
41                 ("p2p_ssid_postfix", "foobar"),
42                 ("persistent_reconnect", "1"),
43                 ("p2p_intra_bss", "0"),
44                 ("p2p_group_idle", "2"),
45                 ("p2p_passphrase_len", "63"),
46                 ("p2p_pref_chan", "81:1,82:14,81:11"),
47                 ("p2p_no_go_freq", "2412-2432,2462,5000-6000"),
48                 ("p2p_add_cli_chan", "1"),
49                 ("p2p_optimize_listen_chan", "1"),
50                 ("p2p_go_ht40", "1"),
51                 ("p2p_go_vht", "1"),
52                 ("p2p_go_ctwindow", "1"),
53                 ("p2p_disabled", "1"),
54                 ("p2p_no_group_iface", "1"),
55                 ("p2p_ignore_shared_freq", "1"),
56                 ("p2p_cli_probe", "1"),
57                 ("p2p_go_freq_change_policy", "0"),
58                 ("country", "FI"),
59                 ("bss_max_count", "123"),
60                 ("bss_expiration_age", "45"),
61                 ("bss_expiration_scan_count", "17"),
62                 ("filter_ssids", "1"),
63                 ("filter_rssi", "-10"),
64                 ("max_num_sta", "3"),
65                 ("disassoc_low_ack", "1"),
66                 ("hs20", "1"),
67                 ("interworking", "1"),
68                 ("hessid", "02:03:04:05:06:07"),
69                 ("access_network_type", "7"),
70                 ("pbc_in_m1", "1"),
71                 ("wps_nfc_dev_pw_id", "12345"),
72                 ("wps_nfc_dh_pubkey", "1234567890ABCDEF"),
73                 ("wps_nfc_dh_privkey", "FF1234567890ABCDEFFF"),
74                 ("ext_password_backend", "test"),
75                 ("p2p_go_max_inactivity", "9"),
76                 ("auto_interworking", "1"),
77                 ("okc", "1"),
78                 ("pmf", "1"),
79                 ("dtim_period", "3"),
80                 ("beacon_int", "102"),
81                 ("sae_groups", "5 19"),
82                 ("ap_vendor_elements", "dd0411223301"),
83                 ("ignore_old_scan_res", "1"),
84                 ("freq_list", "2412 2437"),
85                 ("scan_cur_freq", "1"),
86                 ("sched_scan_interval", "13"),
87                 ("external_sim", "1"),
88                 ("tdls_external_control", "1"),
89                 ("wowlan_triggers", "any"),
90                 ("bgscan", '"simple:30:-45:300"'),
91                 ("p2p_search_delay", "123"),
92                 ("mac_addr", "2"),
93                 ("rand_addr_lifetime", "123456789"),
94                 ("preassoc_mac_addr", "1"),
95                 ("gas_rand_addr_lifetime", "567"),
96                 ("gas_rand_mac_addr", "2"),
97                 ("key_mgmt_offload", "0"),
98                 ("user_mpm", "0"),
99                 ("max_peer_links", "17"),
100                 ("cert_in_cb", "0"),
101                 ("mesh_max_inactivity", "31"),
102                 ("dot11RSNASAERetransPeriod", "19"),
103                 ("passive_scan", "1"),
104                 ("reassoc_same_bss_optim", "1"),
105                 ("wpa_rsc_relaxation", "0"),
106                 ("sched_scan_plans", "10:100 20:200 30"),
107                 ("non_pref_chan", "81:5:10:2 81:1:0:2 81:9:0:2"),
108                 ("mbo_cell_capa", "1"),
109                 ("gas_address3", "1"),
110                 ("ftm_responder", "1"),
111                 ("ftm_initiator", "1"),
112                 ("pcsc_reader", "foo"),
113                 ("pcsc_pin", "1234"),
114                 ("driver_param", "testing"),
115                 ("dot11RSNAConfigPMKLifetime", "43201"),
116                 ("dot11RSNAConfigPMKReauthThreshold", "71"),
117                 ("dot11RSNAConfigSATimeout", "61"),
118                 ("sec_device_type", "12345-0050F204-54321"),
119                 ("autoscan", "exponential:3:300"),
120                 ("osu_dir", "/tmp/osu"),
121                 ("fst_group_id", "bond0"),
122                 ("fst_priority", "5"),
123                 ("fst_llt", "7"),
124                 ("go_interworking", "1"),
125                 ("go_access_network_type", "2"),
126                 ("go_internet", "1"),
127                 ("go_venue_group", "3"),
128                 ("go_venue_type", "4"),
129                 ("p2p_device_random_mac_addr", "1"),
130                 ("p2p_device_persistent_mac_addr", "02:12:34:56:78:9a"),
131                 ("p2p_interface_random_mac_addr", "1"),
132                 ("openssl_ciphers", "DEFAULT")]
133
134def supported_param(capa, field):
135    mesh_params = ["user_mpm", "max_peer_links", "mesh_max_inactivity"]
136    if field in mesh_params and not capa['mesh']:
137        return False
138
139    sae_params = ["dot11RSNASAERetransPeriod"]
140    if field in sae_params and not capa['sae']:
141        return False
142
143    return True
144
145def check_config(capa, config):
146    with open(config, "r") as f:
147        data = f.read()
148    if "ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=" not in data:
149        raise Exception("Missing ctrl_interface")
150    if "blob-base64-foo={" not in data:
151        raise Exception("Missing blob")
152    if "cred={" not in data:
153        raise Exception("Missing cred")
154    if "network={" not in data:
155        raise Exception("Missing network")
156    for field, value in config_checks:
157        if supported_param(capa, field):
158            if "\n" + field + "=" + value + "\n" not in data:
159                raise Exception("Missing value: " + field)
160    return data
161
162def test_wpas_config_file(dev, apdev, params):
163    """wpa_supplicant config file parsing/writing"""
164    config = os.path.join(params['logdir'], 'wpas_config_file.conf')
165    if os.path.exists(config):
166        try:
167            os.remove(config)
168        except:
169            pass
170        try:
171            os.rmdir(config)
172        except:
173            pass
174
175    wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
176    try:
177        wpas.interface_add("wlan5", config=config)
178        initialized = True
179    except:
180        initialized = False
181    if initialized:
182        raise Exception("Missing config file did not result in an error")
183
184    try:
185        with open(config, "w") as f:
186            f.write("update_config=1 \t\r\n")
187            f.write("# foo\n")
188            f.write("\n")
189            f.write(" \t\reapol_version=2")
190            for i in range(0, 100):
191                f.write("                    ")
192            f.write("foo\n")
193            f.write("device_name=name#foo\n")
194            f.write("network={\n")
195            f.write("\tkey_mgmt=NONE\n")
196            f.write('\tssid="hello"\n')
197            f.write('\tgroup=GCMP # "foo"\n')
198            f.write("}\n")
199
200        wpas.interface_add("wlan5", config=config)
201        capa = {}
202        capa['mesh'] = "MESH" in wpas.get_capability("modes")
203        capa['sae'] = "SAE" in wpas.get_capability("auth_alg")
204
205        id = wpas.add_network()
206        wpas.set_network_quoted(id, "ssid", "foo")
207        wpas.set_network_quoted(id, "psk", "12345678")
208        wpas.set_network(id, "bssid", "00:11:22:33:44:55")
209        wpas.set_network(id, "proto", "RSN")
210        wpas.set_network(id, "key_mgmt", "WPA-PSK-SHA256")
211        wpas.set_network(id, "pairwise", "CCMP")
212        wpas.set_network(id, "group", "CCMP")
213        wpas.set_network(id, "auth_alg", "OPEN")
214
215        id = wpas.add_cred()
216        wpas.set_cred(id, "priority", "3")
217        wpas.set_cred(id, "sp_priority", "6")
218        wpas.set_cred(id, "update_identifier", "4")
219        wpas.set_cred(id, "ocsp", "1")
220        wpas.set_cred(id, "eap", "TTLS")
221        wpas.set_cred(id, "req_conn_capab", "6:1234")
222        wpas.set_cred_quoted(id, "realm", "example.com")
223        wpas.set_cred_quoted(id, "provisioning_sp", "example.com")
224        wpas.set_cred_quoted(id, "domain", "example.com")
225        wpas.set_cred_quoted(id, "domain_suffix_match", "example.com")
226        wpas.set_cred_quoted(id, "home_ois", "112233,445566")
227        wpas.set_cred_quoted(id, "required_home_ois", "112233")
228        wpas.set_cred_quoted(id, "roaming_consortiums",
229                             "112233,aabbccddee,445566")
230        wpas.set_cred_quoted(id, "roaming_partner",
231                             "roaming.example.net,1,127,*")
232        wpas.set_cred_quoted(id, "ca_cert", "/tmp/ca.pem")
233        wpas.set_cred_quoted(id, "username", "user")
234        wpas.set_cred_quoted(id, "password", "secret")
235        ev = wpas.wait_event(["CRED-MODIFIED 0 password"])
236
237        wpas.request("SET blob foo 12345678")
238
239        for field, value in config_checks:
240            if supported_param(capa, field):
241                wpas.set(field, value)
242
243        if "OK" not in wpas.request("SAVE_CONFIG"):
244            raise Exception("Failed to save configuration file")
245        if "OK" not in wpas.global_request("SAVE_CONFIG"):
246            raise Exception("Failed to save configuration file")
247
248        wpas.interface_remove("wlan5")
249        data1 = check_config(capa, config)
250        if "group=GCMP" not in data1:
251            raise Exception("Network block group parameter with a comment not present")
252
253        wpas.interface_add("wlan5", config=config)
254        if len(wpas.list_networks()) != 2:
255            raise Exception("Unexpected number of networks")
256        res = wpas.request("LIST_CREDS")
257        logger.info("Credentials:\n" + res)
258        if len(res.splitlines()) != 2:
259            raise Exception("Unexpected number of credentials")
260
261        val = wpas.get_cred(0, "roaming_consortiums")
262        if val != "112233,aabbccddee,445566":
263            raise Exception("Unexpected roaming_consortiums value: " + val)
264
265        if "OK" not in wpas.request("SAVE_CONFIG"):
266            raise Exception("Failed to save configuration file")
267        data2 = check_config(capa, config)
268
269        if data1 != data2:
270            logger.debug(data1)
271            logger.debug(data2)
272            raise Exception("Unexpected configuration change")
273
274        wpas.request("SET update_config 0")
275        wpas.global_request("SET update_config 0")
276        if "OK" in wpas.request("SAVE_CONFIG"):
277            raise Exception("SAVE_CONFIG succeeded unexpectedly")
278        if "OK" in wpas.global_request("SAVE_CONFIG"):
279            raise Exception("SAVE_CONFIG (global) succeeded unexpectedly")
280
281        # replace the config file with a directory to break writing/renaming
282        os.remove(config)
283        os.mkdir(config)
284        wpas.request("SET update_config 1")
285        wpas.global_request("SET update_config 1")
286        if "OK" in wpas.request("SAVE_CONFIG"):
287            raise Exception("SAVE_CONFIG succeeded unexpectedly")
288        if "OK" in wpas.global_request("SAVE_CONFIG"):
289            raise Exception("SAVE_CONFIG (global) succeeded unexpectedly")
290
291    finally:
292        try:
293            os.rmdir(config)
294        except:
295            pass
296        if not wpas.ifname:
297            wpas.interface_add("wlan5")
298        wpas.dump_monitor()
299        wpas.request("SET country 00")
300        wpas.wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=1)
301
302    country = False
303    for i in range(5):
304        ev = dev[0].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=1)
305        if ev is None:
306            break
307        if "alpha2=FI" in ev:
308            country = True
309        if country and "type=WORLD" in ev:
310            break
311
312def test_wpas_config_file_wps(dev, apdev):
313    """wpa_supplicant config file parsing/writing with WPS"""
314    config = "/tmp/test_wpas_config_file.conf"
315    if os.path.exists(config):
316        os.remove(config)
317
318    params = {"ssid": "test-wps", "eap_server": "1", "wps_state": "2",
319              "skip_cred_build": "1", "extra_cred": "wps-ctrl-cred"}
320    hapd = hostapd.add_ap(apdev[0]['ifname'], params)
321
322    wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
323
324    try:
325        with open(config, "w") as f:
326            f.write("update_config=1\n")
327
328        wpas.interface_add("wlan5", config=config)
329
330        hapd.request("WPS_PIN any 12345670")
331        wpas.scan_for_bss(apdev[0]['bssid'], freq="2412")
332        wpas.request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
333        ev = wpas.wait_event(["WPS-FAIL"], timeout=10)
334        if ev is None:
335            raise Exception("WPS-FAIL event timed out")
336
337        with open(config, "r") as f:
338            data = f.read()
339            logger.info("Configuration file contents: " + data)
340            if "network=" in data:
341                raise Exception("Unexpected network block in configuration data")
342
343    finally:
344        try:
345            os.remove(config)
346        except:
347            pass
348        try:
349            os.remove(config + ".tmp")
350        except:
351            pass
352        try:
353            os.rmdir(config)
354        except:
355            pass
356
357def test_wpas_config_file_wps2(dev, apdev):
358    """wpa_supplicant config file parsing/writing with WPS (2)"""
359    config = "/tmp/test_wpas_config_file.conf"
360    if os.path.exists(config):
361        os.remove(config)
362
363    params = {"ssid": "test-wps", "eap_server": "1", "wps_state": "2",
364              "skip_cred_build": "1", "extra_cred": "wps-ctrl-cred2"}
365    hapd = hostapd.add_ap(apdev[0]['ifname'], params)
366
367    wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
368
369    try:
370        with open(config, "w") as f:
371            f.write("update_config=1\n")
372
373        wpas.interface_add("wlan5", config=config)
374
375        hapd.request("WPS_PIN any 12345670")
376        wpas.scan_for_bss(apdev[0]['bssid'], freq="2412")
377        wpas.request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
378        ev = wpas.wait_event(["WPS-SUCCESS"], timeout=10)
379        if ev is None:
380            raise Exception("WPS-SUCCESS event timed out")
381
382        with open(config, "r") as f:
383            data = f.read()
384            logger.info("Configuration file contents: " + data)
385
386            with open(config, "r") as f:
387                data = f.read()
388                if "network=" not in data:
389                    raise Exception("Missing network block in configuration data")
390                if "ssid=410a420d430044" not in data:
391                    raise Exception("Unexpected ssid parameter value")
392
393    finally:
394        try:
395            os.remove(config)
396        except:
397            pass
398        try:
399            os.remove(config + ".tmp")
400        except:
401            pass
402        try:
403            os.rmdir(config)
404        except:
405            pass
406
407def test_wpas_config_file_set_psk(dev):
408    """wpa_supplicant config file parsing/writing with arbitrary PSK value"""
409    config = "/tmp/test_wpas_config_file.conf"
410    if os.path.exists(config):
411        os.remove(config)
412
413    wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
414
415    try:
416        with open(config, "w") as f:
417            f.write("update_config=1\n")
418
419        wpas.interface_add("wlan5", config=config)
420
421        id = wpas.add_network()
422        wpas.set_network_quoted(id, "ssid", "foo")
423        if "OK" in wpas.request('SET_NETWORK %d psk "12345678"\n}\nmodel_name=foobar\nnetwork={\n#\"' % id):
424            raise Exception("Invalid psk value accepted")
425
426        if "OK" not in wpas.request("SAVE_CONFIG"):
427            raise Exception("Failed to save configuration file")
428
429        with open(config, "r") as f:
430            data = f.read()
431            logger.info("Configuration file contents: " + data)
432            if "model_name" in data:
433                raise Exception("Unexpected parameter added to configuration")
434
435        wpas.interface_remove("wlan5")
436        wpas.interface_add("wlan5", config=config)
437
438    finally:
439        try:
440            os.remove(config)
441        except:
442            pass
443        try:
444            os.remove(config + ".tmp")
445        except:
446            pass
447        try:
448            os.rmdir(config)
449        except:
450            pass
451
452def test_wpas_config_file_set_cred(dev):
453    """wpa_supplicant config file parsing/writing with arbitrary cred values"""
454    config = "/tmp/test_wpas_config_file.conf"
455    if os.path.exists(config):
456        os.remove(config)
457
458    wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
459
460    try:
461        with open(config, "w") as f:
462            f.write("update_config=1\n")
463
464        wpas.interface_add("wlan5", config=config)
465
466        id = wpas.add_cred()
467        wpas.set_cred_quoted(id, "username", "hello")
468        fields = ["username", "milenage", "imsi", "password", "realm",
469                  "phase1", "phase2", "provisioning_sp"]
470        for field in fields:
471            if "FAIL" not in wpas.request('SET_CRED %d %s "hello"\n}\nmodel_name=foobar\ncred={\n#\"' % (id, field)):
472                raise Exception("Invalid %s value accepted" % field)
473
474        if "OK" not in wpas.request("SAVE_CONFIG"):
475            raise Exception("Failed to save configuration file")
476
477        with open(config, "r") as f:
478            data = f.read()
479            logger.info("Configuration file contents: " + data)
480            if "model_name" in data:
481                raise Exception("Unexpected parameter added to configuration")
482
483        wpas.interface_remove("wlan5")
484        wpas.interface_add("wlan5", config=config)
485
486    finally:
487        try:
488            os.remove(config)
489        except:
490            pass
491        try:
492            os.remove(config + ".tmp")
493        except:
494            pass
495        try:
496            os.rmdir(config)
497        except:
498            pass
499
500def test_wpas_config_file_set_global(dev):
501    """wpa_supplicant config file parsing/writing with arbitrary global values"""
502    config = "/tmp/test_wpas_config_file.conf"
503    if os.path.exists(config):
504        os.remove(config)
505
506    wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
507
508    try:
509        with open(config, "w") as f:
510            f.write("update_config=1\n")
511
512        wpas.interface_add("wlan5", config=config)
513
514        fields = ["model_name", "device_name", "ctrl_interface_group",
515                  "opensc_engine_path", "pkcs11_engine_path",
516                  "pkcs11_module_path", "openssl_ciphers", "pcsc_reader",
517                  "pcsc_pin", "driver_param", "manufacturer", "model_name",
518                  "model_number", "serial_number", "config_methods",
519                  "p2p_ssid_postfix", "autoscan", "ext_password_backend",
520                  "osu_dir", "wowlan_triggers", "fst_group_id",
521                  "sched_scan_plans", "non_pref_chan"]
522        for field in fields:
523            if "FAIL" not in wpas.request('SET %s hello\nmodel_name=foobar' % field):
524                raise Exception("Invalid %s value accepted" % field)
525
526        if "OK" not in wpas.request("SAVE_CONFIG"):
527            raise Exception("Failed to save configuration file")
528
529        with open(config, "r") as f:
530            data = f.read()
531            logger.info("Configuration file contents: " + data)
532            if "model_name" in data:
533                raise Exception("Unexpected parameter added to configuration")
534
535        wpas.interface_remove("wlan5")
536        wpas.interface_add("wlan5", config=config)
537
538    finally:
539        try:
540            os.remove(config)
541        except:
542            pass
543        try:
544            os.remove(config + ".tmp")
545        except:
546            pass
547        try:
548            os.rmdir(config)
549        except:
550            pass
551
552def test_wpas_config_file_key_mgmt(dev, apdev, params):
553    """wpa_supplicant config file writing and key_mgmt values"""
554    check_fils_capa(dev[0])
555    config = os.path.join(params['logdir'],
556                          'wpas_config_file_key_mgmt.conf')
557    if os.path.exists(config):
558        os.remove(config)
559
560    wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
561
562    with open(config, "w") as f:
563        f.write("update_config=1\n")
564
565    wpas.interface_add("wlan5", config=config)
566
567    from test_dpp import params1_csign, params1_sta_connector, params1_sta_netaccesskey, check_dpp_capab
568
569    check_dpp_capab(wpas)
570
571    id = wpas.add_network()
572    wpas.set_network_quoted(id, "ssid", "foo")
573    wpas.set_network(id, "key_mgmt", "DPP")
574    wpas.set_network(id, "ieee80211w", "2")
575    wpas.set_network_quoted(id, "dpp_csign", params1_csign)
576    wpas.set_network_quoted(id, "dpp_connector", params1_sta_connector)
577    wpas.set_network_quoted(id, "dpp_netaccesskey", params1_sta_netaccesskey)
578    if "OK" not in wpas.request("SAVE_CONFIG"):
579        raise Exception("Failed to save configuration file")
580
581    with open(config, "r") as f:
582        data = f.read()
583        logger.info("Configuration file contents: " + data)
584        if "key_mgmt=DPP" not in data:
585            raise Exception("Missing key_mgmt")
586        if 'dpp_connector="' + params1_sta_connector + '"' not in data:
587            raise Exception("Missing dpp_connector")
588        if 'dpp_netaccesskey="' + params1_sta_netaccesskey + '"' not in data:
589            raise Exception("Missing dpp_netaccesskey")
590        if 'dpp_csign="' + params1_csign + '"' not in data:
591            raise Exception("Missing dpp_csign")
592
593    wpas.set_network(id, "dpp_csign", "NULL")
594    wpas.set_network(id, "dpp_connector", "NULL")
595    wpas.set_network(id, "dpp_netaccesskey", "NULL")
596    wpas.set_network_quoted(id, "psk", "12345678")
597    wpas.set_network(id, "ieee80211w", "0")
598
599    tests = ["WPA-PSK", "WPA-EAP", "IEEE8021X", "NONE", "WPA-NONE", "FT-PSK",
600             "FT-EAP", "FT-EAP-SHA384", "WPA-PSK-SHA256", "WPA-EAP-SHA256",
601             "SAE", "FT-SAE", "OSEN", "WPA-EAP-SUITE-B",
602             "WPA-EAP-SUITE-B-192", "FILS-SHA256", "FILS-SHA384",
603             "FT-FILS-SHA256", "FT-FILS-SHA384", "OWE", "DPP"]
604    supported_key_mgmts = dev[0].get_capability("key_mgmt")
605    for key_mgmt in tests:
606        if key_mgmt == "WPA-EAP-SUITE-B-192" and key_mgmt not in supported_key_mgmts:
607            logger.info("Skip unsupported " + key_mgmt)
608            continue
609        wpas.set_network(id, "key_mgmt", key_mgmt)
610        if "OK" not in wpas.request("SAVE_CONFIG"):
611            raise Exception("Failed to save configuration file")
612        with open(config, "r") as f:
613            data = f.read()
614            logger.info("Configuration file contents: " + data)
615            if "key_mgmt=" + key_mgmt not in data:
616                raise Exception("Missing key_mgmt " + key_mgmt)
617
618    wpas.interface_remove("wlan5")
619    wpas.interface_add("wlan5", config=config)
620
621def check_network_config(config, network_expected, check=None):
622    with open(config, "r") as f:
623        data = f.read()
624        logger.info("Configuration file contents:\n" + data.rstrip())
625        if network_expected and "network=" not in data:
626            raise Exception("Missing network block in configuration data")
627        if not network_expected and "network=" in data:
628            raise Exception("Unexpected network block in configuration data")
629        if check and check not in data:
630            raise Exception("Missing " + check)
631
632def test_wpas_config_file_sae(dev, apdev, params):
633    """wpa_supplicant config file writing with SAE"""
634    config = os.path.join(params['logdir'], 'wpas_config_file_sae.conf')
635    with open(config, "w") as f:
636        f.write("update_config=1\n")
637    wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
638    wpas.interface_add("wlan5", config=config)
639    check_sae_capab(wpas)
640
641    # Valid SAE configuration with sae_password
642    wpas.connect("test-sae", sae_password="sae-password", key_mgmt="SAE",
643                 only_add_network=True)
644    wpas.save_config()
645    check_network_config(config, True, check="key_mgmt=SAE")
646
647    wpas.request("REMOVE_NETWORK all")
648    wpas.save_config()
649    check_network_config(config, False)
650
651    # Valid SAE configuration with psk
652    wpas.connect("test-sae", psk="sae-password", key_mgmt="SAE",
653                 only_add_network=True)
654    wpas.save_config()
655    check_network_config(config, True, check="key_mgmt=SAE")
656    wpas.request("REMOVE_NETWORK all")
657
658    # Invalid PSK configuration with sae_password
659    wpas.connect("test-psk", sae_password="sae-password", key_mgmt="WPA-PSK",
660                 only_add_network=True)
661    wpas.save_config()
662    check_network_config(config, False)
663
664    # Invalid SAE configuration with raw_psk
665    wpas.connect("test-sae", raw_psk=32*"00", key_mgmt="SAE",
666                 only_add_network=True)
667    wpas.save_config()
668    check_network_config(config, False)
669
670def test_wpas_config_update_without_file(dev, apdev):
671    """wpa_supplicant SAVE_CONFIG without config file"""
672    wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
673    wpas.interface_add("wlan5")
674    wpas.set("update_config", "1")
675    if "FAIL" not in wpas.request("SAVE_CONFIG"):
676        raise Exception("SAVE_CONFIG accepted unexpectedly")
677
678def test_wpas_config_file_invalid_network(dev, apdev, params):
679    """wpa_supplicant config file parsing of an invalid network"""
680    config = params['prefix'] + '.conf.wlan5'
681    wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
682    with open(config, "w") as f:
683        f.write("network={\n")
684        f.write("\tunknown=UNKNOWN\n")
685        f.write("}\n")
686    success = False
687    try:
688        wpas.interface_add("wlan5", config=config)
689        success = True
690    except Exception as e:
691        if str(e) != "Failed to add a dynamic wpa_supplicant interface":
692            raise
693
694    if success:
695        raise Exception("Interface addition succeeded with invalid configuration")
696
697def test_wpas_config_range_check(dev, apdev):
698    """wpa_supplicant configuration parser range checking"""
699    tests = [("eapol_version", 0, 4),
700             ("max_peer_links", -1, 256),
701             ("mesh_fwding", -1, 2),
702             ("auto_uuid", -1, 2),
703             ("device_name", 33*'A', None),
704             ("manufacturer", 65*'A', None),
705             ("model_name", 33*'A', None),
706             ("model_number", 33*'A', None),
707             ("serial_number", 33*'A', None),
708             ("wps_cred_processing", -1, 3),
709             ("wps_cred_add_sae", -1, 2),
710             ("p2p_go_intent", -1, 16),
711             ("persistent_reconnect", -1, 2),
712             ("p2p_intra_bss", -1, 2),
713             ("p2p_go_freq_change_policy", -1, 4),
714             ("p2p_passphrase_len", 7, 64),
715             ("p2p_add_cli_chan", -1, 2),
716             ("p2p_optimize_listen_chan", -1, 2),
717             ("p2p_go_ctwindow", -1, 128),
718             ("p2p_ignore_shared_freq", -1, 2),
719             ("p2p_cli_probe", -1, 2),
720             ("filter_ssids", -1, 2),
721             ("filter_rssi", -101, 1),
722             ("ap_isolate", -1, 2),
723             ("disassoc_low_ack", -1, 2),
724             ("hs20", -1, 2),
725             ("interworking", -1, 2),
726             ("access_network_type", -1, 16),
727             ("go_interworking", -1, 2),
728             ("go_access_network_type", -1, 16),
729             ("go_internet", -1, 2),
730             ("go_venue_group", -1, 256),
731             ("go_venue_type", -1, 256),
732             ("pbc_in_m1", -1, 2),
733             ("wps_nfc_dev_pw_id", 15, 65536),
734             ("auto_interworking", -1, 2),
735             ("sae_check_mfp", -1, 2),
736             ("sae_pwe", -1, 4),
737             ("sae_pmkid_in_assoc", -1, 2),
738             ("ignore_old_scan_res", -1, 2),
739             ("mac_addr", -1, 3),
740             ("preassoc_mac_addr", -1, 3),
741             ("fst_group_id", "", 129*"A"),
742             ("fst_priority", 0, 256),
743             ("fst_llt", 0, 2**32),
744             ("cert_in_cb", -1, 2),
745             ("wpa_rsc_relaxation", -1, 2),
746             ("mbo_cell_capa", 0, 4),
747             ("disassoc_imminent_rssi_threshold", -121, 1),
748             ("oce", -1, 4),
749             ("ftm_responder", -1, 2),
750             ("ftm_initiator", -1, 2),
751             ("gas_rand_mac_addr", -1, 3),
752             ("dpp_config_processing", -1, 3),
753             ("dpp_connector_privacy_default", -1, 2),
754             ("coloc_intf_reporting", -1, 2),
755             ("disable_btm", -1, 2),
756             ("extended_key_id", -1, 2),
757             ("wowlan_disconnect_on_deinit", -1, 2),
758             ("force_kdk_derivation", -1, 2),
759             ("pasn_corrupt_mic", -1, 2),
760             ("mld_force_single_link", -1, 2),
761             ("mld_connect_band_pref", -1, 5),
762             ("ft_prepend_pmkid", -1, 2)]
763    for name, value1, value2 in tests:
764        if "OK" in dev[0].request(f"SET {name} {value1}"):
765            raise Exception(f"Invalid SET command accepted: {name}={value1}")
766        if value2 is not None:
767            if "OK" in dev[0].request(f"SET {name} {value2}"):
768                raise Exception(f"Invalid SET command accepted: {name}={value2}")
769
770    id = dev[0].add_network()
771    tests = [("ssid", '"' + 33*"A" + '"', None),
772             ("scan_ssid", -1, 2),
773             ("ht", -1, 2),
774             ("vht", -1, 2),
775             ("he", -1, 2),
776             ("ht40", -2, 2),
777             ("max_oper_chwidth", -2, 4),
778             ("mode", -1, 6),
779             ("no_auto_peer", -1, 2),
780             ("mesh_fwding", -1, 2),
781             ("mesh_rssi_threshold", -256, 2),
782             ("proactive_key_caching", -2, 2),
783             ("disabled", -1, 3),
784             ("ieee80211w", -1, 3),
785             ("mixed_cell", -1, 2),
786             ("frequency", -1, 70201),
787             ("fixed_freq", -1, 2),
788             ("enable_edmg", -1, 2),
789             ("edmg_channel", 8, 14),
790             ("acs", -1, 2),
791             ("wpa_deny_ptk0_rekey", -1, 3),
792             ("ignore_broadcast_ssid", -1, 3),
793             ("disable_ht", -1, 2),
794             ("disable_ht40", -1, 2),
795             ("disable_sgi", -1, 2),
796             ("disable_ldpc", -1, 2),
797             ("ht40_intolerant", -1, 2),
798             ("tx_stbc", -2, 2),
799             ("rx_stbc", -2, 4),
800             ("disable_max_amsdu", -2, 2),
801             ("ampdu_factor", -2, 4),
802             ("ampdu_density", -2, 8),
803             ("disable_vht", -1, 2),
804             ("vht_rx_mcs_nss_1", -2, 4),
805             ("vht_rx_mcs_nss_2", -2, 4),
806             ("vht_rx_mcs_nss_3", -2, 4),
807             ("vht_rx_mcs_nss_4", -2, 4),
808             ("vht_rx_mcs_nss_5", -2, 4),
809             ("vht_rx_mcs_nss_6", -2, 4),
810             ("vht_rx_mcs_nss_7", -2, 4),
811             ("vht_rx_mcs_nss_8", -2, 4),
812             ("vht_tx_mcs_nss_1", -2, 4),
813             ("vht_tx_mcs_nss_2", -2, 4),
814             ("vht_tx_mcs_nss_3", -2, 4),
815             ("vht_tx_mcs_nss_4", -2, 4),
816             ("vht_tx_mcs_nss_5", -2, 4),
817             ("vht_tx_mcs_nss_6", -2, 4),
818             ("vht_tx_mcs_nss_7", -2, 4),
819             ("vht_tx_mcs_nss_8", -2, 4),
820             ("disable_he", -1, 2),
821             ("macsec_policy", -1, 2),
822             ("macsec_integ_only", -1, 2),
823             ("macsec_replay_protect", -1, 2),
824             ("macsec_offload", -1, 3),
825             ("macsec_port", -1, 65535),
826             ("mka_priority", -1, 256),
827             ("macsec_csindex", -1, 2),
828             ("roaming_consortium_selection", 16*"00", None),
829             ("mac_addr", -2, 4),
830             ("pbss", -1, 3),
831             ("wps_disabled", -1, 2),
832             ("fils_dh_group", -1, 65536),
833             ("dpp_pfs", -1, 3),
834             ("dpp_connector_privacy", -1, 2),
835             ("owe_group", -1, 65536),
836             ("owe_only", -1, 2),
837             ("owe_ptk_workaround", -1, 2),
838             ("multi_ap_backhaul_sta", -1, 2),
839             ("ft_eap_pmksa_caching", -1, 2),
840             ("beacon_prot", -1, 2),
841             ("transition_disable", -1, 256),
842             ("sae_pk", -1, 3),
843             ("disable_eht", -1, 2),
844             ("enable_4addr_mode", -1, 2)]
845    for name, value1, value2 in tests:
846        if "OK" in dev[0].request(f"SET_NETWORK {id} {name} {value1}"):
847            raise Exception(f"Invalid SET_NETWORK command accepted: {name}={value1}")
848        if value2 is not None:
849            if "OK" in dev[0].request(f"SET_NETWORK {id} {name} {value2}"):
850                raise Exception(f"Invalid SET_NETWORK command accepted: {name}={value2}")
851