eiwd

no dbus iwd with iwctl functionality
git clone https://git.daat.foo/repos/eiwd.git
Log | Files | Refs | Submodules | README | LICENSE

commit 9daf0cc58ed50f1dc3fc2b276df31ef68d168dcd
parent 8aa0783016f465b721aace177aa5c1795c71ad3c
Author: illiliti <illiliti@protonmail.com>
Date:   Thu,  7 Dec 2023 11:53:23 +0300

Merge tag '2.10'

Release 2.10

Diffstat:
MChangeLog | 12++++++++++++
MMakefile.am | 4+++-
MTODO | 2+-
Mautotests/testDPP/connection_test.py | 9+++++++--
Mautotests/testDPP/hostapd.conf | 2+-
Mautotests/testDPP/hw.conf | 5++++-
Aautotests/testDPP/pkex_test.py | 254+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mautotests/testDPP/ssidCCMP.psk | 3+++
Mautotests/testDPP/wpas.conf | 1+
Mautotests/testOWE-transition/connection_test.py | 51++++-----------------------------------------------
Mautotests/testOWE-transition/ssidOWE-2.conf | 2++
Mautotests/testOWE-transition/ssidOWE.conf | 1+
Mautotests/testOWE-transition/ssidOpen-2.conf | 1+
Mautotests/testOWE-transition/ssidOpen.conf | 1+
Mautotests/testPSK-roam/connection_test.py | 33+++------------------------------
Mautotests/testPSK-roam/failed_roam_test.py | 101+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Mautotests/testPSK-roam/ft-psk-ccmp-1.conf | 2++
Mautotests/testPSK-roam/ft-psk-ccmp-2.conf | 2++
Mautotests/testPSK-roam/ft-psk-ccmp-3.conf | 2++
Mautotests/testSAE-AntiClogging/clogging_test.py | 7+++----
Mautotests/testSAE-AntiClogging/ssidSAE-Clogging.conf | 3+++
Mautotests/testSAE/autoconnect_test.py | 6+++---
Mautotests/testSAE/connection_test.py | 9+--------
Mautotests/testSAE/failure_test.py | 9++++++---
Mautotests/testSAE/ssidSAE.conf | 1+
Mautotests/testSAE/timeout_test.py | 16++++++++--------
Mautotests/testWPA2/connection_test.py | 4+---
Mautotests/testWPA2/ssidWPA2.conf | 1+
Mautotests/testWPA2withMFP/connection_test.py | 4+---
Mautotests/testWPA2withMFP/ssidWPA2.conf | 1+
Mautotests/util/hostapd.py | 27++++++++++++++++++++++++++-
Mautotests/util/iwd.py | 152+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mautotests/util/wpas.py | 52++++++++++++++++++++++++++++++++++++++++++++++++++--
Mclient/dbus-proxy.h | 3+++
Mclient/display.c | 2+-
Aclient/dpp-pkex.c | 314+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mconfigure.ac | 4++--
Mdoc/device-provisioning-api.txt | 152++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mmonitor/nlmon.c | 114++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------
Msrc/adhoc.c | 1+
Msrc/ap.c | 13++++++++++---
Msrc/band.c | 3+++
Msrc/crypto.c | 26+++++++++-----------------
Msrc/crypto.h | 2+-
Msrc/dbus.h | 2++
Msrc/dpp-util.c | 380++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Msrc/dpp-util.h | 51++++++++++++++++++++++++++++++++++++++++++++++-----
Msrc/dpp.c | 2089+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Msrc/eap-pwd.c | 22+++++++++++++++++++++-
Msrc/eap.c | 6+++---
Msrc/eapol.c | 2+-
Msrc/erp.c | 29+++++++++++++++++++----------
Msrc/erp.h | 2+-
Msrc/ft.c | 37++++++++++++++++++++++++++-----------
Msrc/ie.c | 46++++++++++++++++++++++++++++++++++++++++++++++
Msrc/ie.h | 2++
Msrc/ip-pool.c | 1+
Msrc/iwd-dbus.conf | 1+
Msrc/iwd.config.rst | 23+++++++++++++++++++----
Msrc/json.h | 2+-
Msrc/main.c | 1+
Msrc/netdev.c | 635+++++++++++++++++++++++++++----------------------------------------------------
Msrc/netdev.h | 1+
Msrc/network.c | 3++-
Msrc/nl80211util.c | 155+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Msrc/nl80211util.h | 32++++++++++++++++++++++++++++++++
Msrc/offchannel.c | 59++++++++++++++++++++++++++++++++++++++++++++++++-----------
Msrc/sae.c | 24+++++++++++++++++++++++-
Msrc/scan.c | 146+++++++++++++++++++++++++++++++++++++++++++++++++++++--------------------------
Msrc/scan.h | 3+++
Msrc/station.c | 308+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------
Msrc/station.h | 2+-
Msrc/wiphy.c | 38++++++++++----------------------------
Msrc/wiphy.h | 8+++-----
Mtest/simple-agent | 2+-
Mtools/run-tests | 12+++++-------
Mtools/runner.py | 7+++++++
Munit/test-band.c | 6+++---
Munit/test-dpp.c | 374++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
79 files changed, 4897 insertions(+), 1028 deletions(-)

diff --git a/ChangeLog b/ChangeLog @@ -1,3 +1,15 @@ +ver 2.10: + Fix issue with buffer overflow for 32 byte SSIDs. + Fix issue with deauthentication before FT work completes. + Fix issue with power save disabling procedure. + +ver 2.9: + Fix issue with handling certain FT failures. + Fix issue with handling user-disabled bands. + Fix issue with handling roam on beacon loss event. + Add support for PKEX configurator. + Add support for PKEX enrollee. + ver 2.8: Fix issue with handling OWE AKM in association reply. diff --git a/Makefile.am b/Makefile.am @@ -315,7 +315,8 @@ client_iwctl_SOURCES = client/main.c \ client/wsc.c client/station.c \ client/diagnostic.c client/diagnostic.h \ client/daemon.c client/daemon.h \ - client/dpp.c client/station-debug.c \ + client/dpp.c client/dpp-pkex.c \ + client/station-debug.c \ src/util.c src/util.h \ src/band.c src/band.h @@ -409,6 +410,7 @@ tools_hwsim_SOURCES = tools/hwsim.c src/mpdu.h \ src/storage.h src/storage.c \ src/common.h src/common.c \ src/band.h src/band.c \ + src/ie.h src/ie.c \ src/crypto.h src/crypto.c tools_hwsim_LDADD = $(ell_ldadd) diff --git a/TODO b/TODO @@ -286,7 +286,7 @@ Wireless daemon - Support OCE mutually non-overlapping channels optimization. OCE Section 3.10 mandates that the STA should scan channels 1, 6 and 11 in - the 2.4Ghz band first, unless it expects to find an AP on a different + the 2.4GHz band first, unless it expects to find an AP on a different channel. Priority: Low diff --git a/autotests/testDPP/connection_test.py b/autotests/testDPP/connection_test.py @@ -148,8 +148,13 @@ class Test(unittest.TestCase): self.rule0.drop = True def tearDown(self): - self.device.disconnect() - self.device.dpp_stop() + # Tests end in various states, don't fail when tearing down. + try: + self.device.disconnect() + self.device.dpp_stop() + except: + pass + self.wpas.dpp_configurator_remove() self.wpas.clean_up() diff --git a/autotests/testDPP/hostapd.conf b/autotests/testDPP/hostapd.conf @@ -1,5 +1,5 @@ hw_mode=g -channel=1 +channel=6 ssid=ssidCCMP wpa=2 diff --git a/autotests/testDPP/hw.conf b/autotests/testDPP/hw.conf @@ -1,5 +1,5 @@ [SETUP] -num_radios=3 +num_radios=4 start_iwd=0 hwsim_medium=yes @@ -8,3 +8,6 @@ rad0=wpas.conf [HOSTAPD] rad1=hostapd.conf + +[NameSpaces] +ns0=rad2 diff --git a/autotests/testDPP/pkex_test.py b/autotests/testDPP/pkex_test.py @@ -0,0 +1,253 @@ +#!/usr/bin/python3 + +import unittest +import sys + +sys.path.append('../util') +from iwd import IWD, SharedCodeAgent +from iwd import DeviceProvisioning +from wpas import Wpas +from hostapd import HostapdCLI +from hwsim import Hwsim +from config import ctx +from time import time +import os + +class Test(unittest.TestCase): + def start_wpas_pkex(self, code, curve=None, **kwargs): + self.wpas.dpp_bootstrap_gen(type='pkex', curve=curve) + self.wpas.dpp_pkex_add(code=code, **kwargs) + if kwargs.get('role', 'configurator') == 'configurator': + self.wpas.dpp_configurator_create() + self.wpas.dpp_listen(2437) + + def stop_wpas_pkex(self): + self.wpas.dpp_pkex_remove() + self.wpas.dpp_stop_listen() + self.wpas.dpp_configurator_remove() + + def start_iwd_pkex_configurator(self, device, agent=False): + self.hapd.reload() + self.hapd.wait_for_event('AP-ENABLED') + + IWD.copy_to_storage('ssidCCMP.psk') + device.autoconnect = True + + condition = 'obj.state == DeviceState.connected' + self.wd.wait_for_object_condition(device, condition) + + if agent: + self.agent = SharedCodeAgent(codes = {"test": "secret123"}) + + device.dpp_pkex_start_configurator(self.agent.path) + else: + device.dpp_pkex_configure_enrollee('secret123', identifier="test") + + # + # WPA Supplicant has awful handling of retransmissions and no-ACK + # conditions. It only handles retransmitting the exchange request when + # there is no-ACK, which makes zero sense since its a broadcast... + # + # So, really, testing against wpa_supplicant is fragile and dependent on + # how the scheduling works out. If IWD doesn't ACK due to being on the + # next frequency or in between offchannel requests wpa_supplicant gets + # into a state where it thinks a PKEX session has been started (having + # received the exchange request) but will only accept commit-reveal + # frames. IWD is unaware because it never got a response so it keeps + # sending exchange requests which are ignored. + # + # Nevertheless we should still test against wpa_supplicant for + # compatibility so attempt to detect this case and restart the + # wpa_supplicant configurator. + # + def restart_wpas_if_needed(self): + i = 0 + + while i < 10: + data = self.wpas.wait_for_event("DPP-RX") + self.assertIn("type=7", data) + + data = self.wpas.wait_for_event("DPP-TX") + self.assertIn("type=8", data) + + data = self.wpas.wait_for_event("DPP-TX-STATUS") + if "result=no-ACK" in data: + self.stop_wpas_pkex() + self.start_wpas_pkex('secret123', identifier="test") + else: + return + + i += 1 + + raise Exception("wpa_supplicant could not complete PKEX after 10 retries") + + def test_pkex_iwd_as_enrollee(self): + self.start_wpas_pkex('secret123', identifier="test") + + self.device[0].dpp_pkex_enroll('secret123', identifier="test") + + self.restart_wpas_if_needed() + + self.wpas.wait_for_event("DPP-AUTH-SUCCESS") + + def test_pkex_iwd_as_enrollee_retransmit(self): + self.rule_reveal_req.enabled = True + + self.start_wpas_pkex('secret123', identifier="test") + + self.device[0].dpp_pkex_enroll('secret123', identifier="test") + + self.restart_wpas_if_needed() + + self.wpas.wait_for_event("DPP-AUTH-SUCCESS") + + def test_pkex_unsupported_version(self): + self.start_wpas_pkex('secret123', identifier="test", version=2) + + now = time() + self.device[0].dpp_pkex_enroll('secret123', identifier="test") + + condition = "obj.started == False" + self.wd.wait_for_object_condition(self.device[0]._sc_device_provisioning, + condition, max_wait=125) + + # Check the enrollee stopped after 2 minutes + elapsed = time() - now + self.assertLess(elapsed, 125) + + def test_pkex_configurator_timeout(self): + self.start_iwd_pkex_configurator(self.device[0]) + + now = time() + + condition = "obj.started == False" + self.wd.wait_for_object_condition(self.device[0]._sc_device_provisioning, + condition, max_wait=125) + + # Check the enrollee stopped after 2 minutes + elapsed = time() - now + self.assertLess(elapsed, 125) + + def test_pkex_iwd_as_configurator(self): + self.start_iwd_pkex_configurator(self.device[0]) + + self.start_wpas_pkex('secret123', identifier="test", initiator=True, + role='enrollee') + + self.wpas.wait_for_event("DPP-AUTH-SUCCESS") + self.wpas.wait_for_event("DPP-CONF-RECEIVED") + + def test_pkex_iwd_as_configurator_retransmit(self): + self.rule_xchg_resp.enabled = True + self.rule_reveal_resp.enabled = True + + self.start_iwd_pkex_configurator(self.device[0]) + + self.start_wpas_pkex('secret123', identifier="test", initiator=True, + role='enrollee') + + self.wpas.wait_for_event("DPP-AUTH-SUCCESS") + self.wpas.wait_for_event("DPP-CONF-RECEIVED") + + def test_pkex_iwd_as_configurator_bad_group(self): + self.start_iwd_pkex_configurator(self.device[0]) + + self.start_wpas_pkex('secret123', identifier="test", initiator=True, + role='enrollee', curve='P-384') + + self.wpas.wait_for_event(f"DPP-RX src={self.device[0].address} freq=2437 type=8") + self.wpas.wait_for_event("DPP-FAIL") + + def test_pkex_iwd_to_iwd(self): + self.start_iwd_pkex_configurator(self.device[0]) + + self.device[1].dpp_pkex_enroll('secret123', identifier="test") + + self.device[1].autoconnect = True + + condition = 'obj.state == DeviceState.connected' + self.wd.wait_for_object_condition(self.device[1], condition) + + # Check additional settings were carried over + with open('/tmp/ns0/ssidCCMP.psk', 'r') as f: + settings = f.read() + + self.assertIn("SendHostname=true", settings) + + def test_pkex_configurator_with_agent(self): + self.start_iwd_pkex_configurator(self.device[0], agent=True) + + self.device[1].dpp_pkex_enroll('secret123', identifier="test") + + self.device[1].autoconnect = True + + condition = 'obj.state == DeviceState.connected' + self.wd.wait_for_object_condition(self.device[1], condition) + + self.agent = None + + def setUp(self): + ns0 = ctx.get_namespace('ns0') + self.wpas = Wpas('wpas.conf') + + self.wd = IWD(True) + self.wd_ns0 = IWD(True, iwd_storage_dir='/tmp/ns0', namespace=ns0) + self.device = [] + self.device.append(self.wd.list_devices(1)[0]) + self.device.append(self.wd_ns0.list_devices(1)[0]) + self.hapd = HostapdCLI('hostapd.conf') + self.hapd.disable() + self.hwsim = Hwsim() + + self.rule_xchg_resp = self.hwsim.rules.create() + self.rule_xchg_resp.prefix = 'd0' + self.rule_xchg_resp.match_offset = 24 + self.rule_xchg_resp.match = '04 09 50 6f 9a 1a 01 08' + self.rule_xchg_resp.match_times = 1 + self.rule_xchg_resp.drop = True + + self.rule_reveal_resp = self.hwsim.rules.create() + self.rule_reveal_resp.prefix = 'd0' + self.rule_reveal_resp.match_offset = 24 + self.rule_reveal_resp.match = '04 09 50 6f 9a 1a 01 0a' + self.rule_reveal_resp.match_times = 1 + self.rule_reveal_resp.drop = True + + self.rule_reveal_req = self.hwsim.rules.create() + self.rule_reveal_req.prefix = 'd0' + self.rule_reveal_req.match_offset = 24 + self.rule_reveal_req.match = '04 09 50 6f 9a 1a 01 09' + self.rule_reveal_req.match_times = 1 + self.rule_reveal_req.drop = True + + def tearDown(self): + # Tests end in various states, don't fail when tearing down. + try: + self.device[0].disconnect() + self.device[0].dpp_pkex_stop() + self.device[1].disconnect() + self.device[1].dpp_pkex_stop() + except: + pass + + self.wpas.dpp_configurator_remove() + self.wpas.clean_up() + + self.wd = None + self.wd_ns0 = None + self.device = None + self.wpas = None + self.hapd = None + self.rule_xchg_resp = None + IWD.clear_storage() + + @classmethod + def setUpClass(cls): + pass + + @classmethod + def tearDownClass(cls): + pass + +if __name__ == '__main__': + unittest.main(exit=True) +\ No newline at end of file diff --git a/autotests/testDPP/ssidCCMP.psk b/autotests/testDPP/ssidCCMP.psk @@ -1,2 +1,5 @@ [Security] Passphrase=secret123 + +[IPv4] +SendHostname=true diff --git a/autotests/testDPP/wpas.conf b/autotests/testDPP/wpas.conf @@ -3,3 +3,4 @@ ctrl_interface=/tmp/rad1-p2p-wpas update_config=0 pmf=2 dpp_config_processing=2 +p2p_disabled=1 diff --git a/autotests/testOWE-transition/connection_test.py b/autotests/testOWE-transition/connection_test.py @@ -47,11 +47,6 @@ class Test(unittest.TestCase): # Normal success case def test_owe_transition(self): - self.hapd_open.set_value('vendor_elements', 'dd15506f9a1c02000000f1000a6f77652d68696464656e') - self.hapd_open.reload() - self.hapd_owe.set_value('vendor_elements', 'dd15506f9a1c02000000f0000a7472616e736974696f6e') - self.hapd_owe.reload() - self.hapd_owe2.disable() self.hapd_open2.disable() @@ -59,15 +54,8 @@ class Test(unittest.TestCase): # Normal success case def test_owe_transition_multi_network(self): - self.hapd_open.set_value('vendor_elements', 'dd15506f9a1c02000000f1000a6f77652d68696464656e') - self.hapd_open.reload() - self.hapd_owe.set_value('vendor_elements', 'dd15506f9a1c02000000f0000a7472616e736974696f6e') - self.hapd_owe.reload() - - self.hapd_open2.set_value('vendor_elements', 'dd17506f9a1c02000000f1000c6f77652d68696464656e2d32') self.hapd_open2.set_value('ssid', 'transition-2') self.hapd_open2.reload() - self.hapd_owe2.set_value('vendor_elements', 'dd17506f9a1c02000000f0000c7472616e736974696f6e2d32') self.hapd_owe2.set_value('ssid', 'owe-hidden-2') self.hapd_owe2.reload() @@ -75,11 +63,6 @@ class Test(unittest.TestCase): # Two pairs of open/OWE BSS's (OWE BSS's have different SSIDs) */ def test_owe_transition_multi_bss(self): - self.hapd_open.set_value('vendor_elements', 'dd15506f9a1c02000000f1000a6f77652d68696464656e') - self.hapd_open.reload() - self.hapd_owe.set_value('vendor_elements', 'dd15506f9a1c02000000f0000a7472616e736974696f6e') - self.hapd_owe.reload() - self.hapd_open2.set_value('vendor_elements', 'dd17506f9a1c02000000f3000c6f77652d68696464656e2d32') self.hapd_open2.set_value('ssid', 'transition') self.hapd_open2.reload() @@ -91,11 +74,6 @@ class Test(unittest.TestCase): # Two pairs of open/OWE BSS's (OWE BSS's have same SSID) */ def test_owe_transition_multi_bss_same_ssid(self): - self.hapd_open.set_value('vendor_elements', 'dd15506f9a1c02000000f1000a6f77652d68696464656e') - self.hapd_open.reload() - self.hapd_owe.set_value('vendor_elements', 'dd15506f9a1c02000000f0000a7472616e736974696f6e') - self.hapd_owe.reload() - self.hapd_open2.set_value('vendor_elements', 'dd15506f9a1c02000000f3000a6f77652d68696464656e') self.hapd_open2.set_value('ssid', 'transition') self.hapd_open2.reload() @@ -107,11 +85,6 @@ class Test(unittest.TestCase): # Normal success autoconnect case def test_owe_transition_autoconnect(self): - self.hapd_open.set_value('vendor_elements', 'dd15506f9a1c02000000f1000a6f77652d68696464656e') - self.hapd_open.reload() - self.hapd_owe.set_value('vendor_elements', 'dd15506f9a1c02000000f0000a7472616e736974696f6e') - self.hapd_owe.reload() - self.hapd_owe2.disable() self.hapd_open2.disable() @@ -124,8 +97,6 @@ class Test(unittest.TestCase): def test_owe_transition_invalid_open_bssid(self): self.hapd_open.set_value('vendor_elements', 'dd15506f9a1c02000000ff000a6f77652d68696464656e') self.hapd_open.reload() - self.hapd_owe.set_value('vendor_elements', 'dd15506f9a1c02000000f0000a7472616e736974696f6e') - self.hapd_owe.reload() self.hapd_owe2.disable() self.hapd_open2.disable() @@ -135,8 +106,6 @@ class Test(unittest.TestCase): # OWE BSS has invalid BSSID in OWE transition element # Expected connection to Open BSS def test_owe_transition_invalid_owe_bssid(self): - self.hapd_open.set_value('vendor_elements', 'dd15506f9a1c02000000f1000a6f77652d68696464656e') - self.hapd_open.reload() self.hapd_owe.set_value('vendor_elements', 'dd15506f9a1c02000000ff000a7472616e736974696f6e') self.hapd_owe.reload() @@ -148,8 +117,6 @@ class Test(unittest.TestCase): # No OWE hidden network exists # Expected connection to Open BSS def test_owe_transition_no_hidden_found(self): - self.hapd_open.set_value('vendor_elements', 'dd15506f9a1c02000000f1000a6f77652d68696464656e') - self.hapd_open.reload() self.hapd_owe.disable() self.hapd_owe2.disable() @@ -160,11 +127,6 @@ class Test(unittest.TestCase): # Directly connect to valid OWE hidden network # Expected connection failure def test_owe_transition_connect_hidden_valid(self): - self.hapd_open.set_value('vendor_elements', 'dd15506f9a1c02000000f1000a6f77652d68696464656e') - self.hapd_open.reload() - self.hapd_owe.set_value('vendor_elements', 'dd15506f9a1c02000000f0000a7472616e736974696f6e') - self.hapd_owe.reload() - self.hapd_owe2.disable() self.hapd_open2.disable() @@ -189,7 +151,6 @@ class Test(unittest.TestCase): def test_owe_transition_band_info(self): self.hapd_open.set_value('vendor_elements', 'dd17506f9a1c02000000f1000a6f77652d68696464656e5103') self.hapd_open.reload() - self.hapd_owe.set_value('vendor_elements', 'dd15506f9a1c02000000f0000a7472616e736974696f6e') self.hapd_owe.set_value('channel', '3') self.hapd_owe.reload() @@ -201,7 +162,6 @@ class Test(unittest.TestCase): def test_owe_transition_wrong_band_info(self): self.hapd_open.set_value('vendor_elements', 'dd17506f9a1c02000000f1000a6f77652d68696464656e5102') self.hapd_open.reload() - self.hapd_owe.set_value('vendor_elements', 'dd15506f9a1c02000000f0000a7472616e736974696f6e') self.hapd_owe.set_value('channel', '3') self.hapd_owe.reload() @@ -212,11 +172,6 @@ class Test(unittest.TestCase): # OWE Transition pair + additional open network with the same SSID def test_owe_transition_extra_open(self): - self.hapd_open.set_value('vendor_elements', 'dd15506f9a1c02000000f1000a6f77652d68696464656e') - self.hapd_open.reload() - self.hapd_owe.set_value('vendor_elements', 'dd15506f9a1c02000000f0000a7472616e736974696f6e') - self.hapd_owe.reload() - self.hapd_open2.set_value('ssid', 'transition') self.hapd_open2.reload() @@ -235,17 +190,19 @@ class Test(unittest.TestCase): def setUp(self): self.wd = IWD(True) self.hapd_owe = HostapdCLI(config='ssidOWE.conf') + self.hapd_owe.default() self.hapd_open = HostapdCLI(config='ssidOpen.conf') + self.hapd_open.default() self.hapd_owe2 = HostapdCLI(config='ssidOWE-2.conf') + self.hapd_owe2.default() self.hapd_open2 = HostapdCLI(config='ssidOpen-2.conf') + self.hapd_open2.default() self.hwsim = Hwsim() def tearDown(self): IWD.clear_storage() - self.hapd_owe.set_value('channel', '1') - self.wd = None self.hapd_open = None self.hapd_owe = None diff --git a/autotests/testOWE-transition/ssidOWE-2.conf b/autotests/testOWE-transition/ssidOWE-2.conf @@ -7,3 +7,5 @@ ieee80211w=1 wpa=2 wpa_key_mgmt=OWE rsn_pairwise=CCMP + +vendor_elements=dd17506f9a1c02000000f0000c7472616e736974696f6e2d32 diff --git a/autotests/testOWE-transition/ssidOWE.conf b/autotests/testOWE-transition/ssidOWE.conf @@ -7,6 +7,7 @@ ieee80211w=1 wpa=2 wpa_key_mgmt=OWE rsn_pairwise=CCMP +vendor_elements=dd15506f9a1c02000000f0000a7472616e736974696f6e # You would conventionally use these options but hostapd does not include an # IE for the OWE network, hence vendor_elements must be used directly diff --git a/autotests/testOWE-transition/ssidOpen-2.conf b/autotests/testOWE-transition/ssidOpen-2.conf @@ -1,3 +1,4 @@ channel=1 ssid=transition-2 bssid=02:00:00:00:f2:00 +vendor_elements=dd17506f9a1c02000000f1000c6f77652d68696464656e2d32 diff --git a/autotests/testOWE-transition/ssidOpen.conf b/autotests/testOWE-transition/ssidOpen.conf @@ -1,6 +1,7 @@ channel=1 ssid=transition bssid=02:00:00:00:f0:00 +vendor_elements=dd15506f9a1c02000000f1000a6f77652d68696464656e # You would conventionally use these options but hostapd does not include an # IE for the OWE network, hence vendor_elements must be used directly diff --git a/autotests/testPSK-roam/connection_test.py b/autotests/testPSK-roam/connection_test.py @@ -93,32 +93,16 @@ class Test(unittest.TestCase): def test_ft_psk(self): wd = IWD(True) - self.bss_hostapd[0].set_value('wpa_key_mgmt', 'FT-PSK') - self.bss_hostapd[0].set_value('ft_over_ds', '0') - self.bss_hostapd[0].set_value('ocv', '1') - self.bss_hostapd[0].reload() - self.bss_hostapd[0].wait_for_event("AP-ENABLED") - - self.bss_hostapd[1].set_value('wpa_key_mgmt', 'FT-PSK') - self.bss_hostapd[1].set_value('ft_over_ds', '0') - self.bss_hostapd[0].set_value('ocv', '1') - self.bss_hostapd[1].reload() - self.bss_hostapd[1].wait_for_event("AP-ENABLED") - self.validate_connection(wd) def test_ft_psk_over_ds(self): wd = IWD(True) - self.bss_hostapd[0].set_value('wpa_key_mgmt', 'FT-PSK') self.bss_hostapd[0].set_value('ft_over_ds', '1') - self.bss_hostapd[0].set_value('ocv', '1') self.bss_hostapd[0].reload() self.bss_hostapd[0].wait_for_event("AP-ENABLED") - self.bss_hostapd[1].set_value('wpa_key_mgmt', 'FT-PSK') self.bss_hostapd[1].set_value('ft_over_ds', '1') - self.bss_hostapd[1].set_value('ocv', '1') self.bss_hostapd[1].reload() self.bss_hostapd[1].wait_for_event("AP-ENABLED") @@ -128,12 +112,10 @@ class Test(unittest.TestCase): wd = IWD(True) self.bss_hostapd[0].set_value('wpa_key_mgmt', 'WPA-PSK') - self.bss_hostapd[0].set_value('ft_over_ds', '0') self.bss_hostapd[0].reload() self.bss_hostapd[0].wait_for_event("AP-ENABLED") self.bss_hostapd[1].set_value('wpa_key_mgmt', 'WPA-PSK') - self.bss_hostapd[1].set_value('ft_over_ds', '0') self.bss_hostapd[1].reload() self.bss_hostapd[1].wait_for_event("AP-ENABLED") @@ -142,18 +124,6 @@ class Test(unittest.TestCase): def test_roam_packet_loss(self): wd = IWD(True) - self.bss_hostapd[0].set_value('wpa_key_mgmt', 'FT-PSK') - self.bss_hostapd[0].set_value('ft_over_ds', '0') - self.bss_hostapd[0].set_value('ocv', '1') - self.bss_hostapd[0].reload() - self.bss_hostapd[0].wait_for_event("AP-ENABLED") - - self.bss_hostapd[1].set_value('wpa_key_mgmt', 'FT-PSK') - self.bss_hostapd[1].set_value('ft_over_ds', '0') - self.bss_hostapd[0].set_value('ocv', '1') - self.bss_hostapd[1].reload() - self.bss_hostapd[1].wait_for_event("AP-ENABLED") - self.validate_connection(wd, pkt_loss=True) def tearDown(self): @@ -166,6 +136,9 @@ class Test(unittest.TestCase): self.rule1.enabled = False self.rule2.enabled = False + for hapd in self.bss_hostapd: + hapd.default() + @classmethod def setUpClass(cls): hwsim = Hwsim() diff --git a/autotests/testPSK-roam/failed_roam_test.py b/autotests/testPSK-roam/failed_roam_test.py @@ -41,18 +41,10 @@ class Test(unittest.TestCase): self.assertRaises(Exception, testutil.test_ifaces_connected, (prev.ifname, device.name, True, True)) - # FT-over-Air failure, should stay connected def test_ft_over_air_failure(self): - self.bss_hostapd[0].set_value('wpa_key_mgmt', 'FT-PSK') - self.bss_hostapd[0].set_value('ft_over_ds', '0') - self.bss_hostapd[0].reload() - self.bss_hostapd[0].wait_for_event("AP-ENABLED") - - self.bss_hostapd[1].set_value('wpa_key_mgmt', 'FT-PSK') - self.bss_hostapd[1].set_value('ft_over_ds', '0') - self.bss_hostapd[1].reload() - self.bss_hostapd[1].wait_for_event("AP-ENABLED") + self.rule2.enabled = True + self.rule3.enabled = True wd = IWD(True) @@ -70,12 +62,85 @@ class Test(unittest.TestCase): self.rule0.enabled = False # IWD should then try BSS 2, and succeed + device.wait_for_event('ft-roam', timeout=60) self.verify_roam(wd, device, self.bss_hostapd[0], self.bss_hostapd[2]) self.bss_hostapd[2].deauthenticate(device.address) + + # FT-over-Air failure with Invalid PMKID, should reassociate + def test_ft_over_air_fallback(self): + self.rule_bss0.signal = -8000 + self.rule_bss0.enabled = True + self.rule_bss1.signal = -7500 + self.rule_bss1.enabled = True + self.rule_bss2.signal = -6000 + self.rule_bss2.enabled = True + + # This will cause this BSS to reject any FT roams as its unable to + # get keys from other APs + self.bss_hostapd[2].set_value('ft_psk_generate_local', '0') + self.bss_hostapd[2].reload() + + wd = IWD(True) + + device = wd.list_devices(1)[0] + + self.connect(wd, device, self.bss_hostapd[0]) + + # IWD should connect, then attempt a roam to BSS 1, which should + # fail and cause a fallback to reassociation + device.wait_for_event('ft-fallback-to-reassoc', timeout=60) + device.wait_for_event('reassoc-roam', timeout=60) + + self.verify_roam(wd, device, self.bss_hostapd[0], self.bss_hostapd[2]) + + # Trigger another roam + self.rule_bss2.signal = -8000 + + device.wait_for_event('ft-roam', timeout=60) + + # Ensure an FT roam back to a properly configured AP works. + self.verify_roam(wd, device, self.bss_hostapd[2], self.bss_hostapd[1]) + + self.bss_hostapd[1].deauthenticate(device.address) + condition = 'obj.state == DeviceState.disconnected' + wd.wait_for_object_condition(device, condition) + + # FT-over-Air failure with Invalid PMKID. The ranking is such that other + # FT candidates are available so it should FT elsewhere rather than + # retry with reassociation + def test_ft_over_air_fallback_retry_ft(self): + self.rule_bss0.signal = -8000 + self.rule_bss0.enabled = True + self.rule_bss1.signal = -7300 + self.rule_bss1.enabled = True + self.rule_bss2.signal = -7100 + self.rule_bss2.enabled = True + + # This will cause this BSS to reject any FT roams as its unable to + # get keys from other APs + self.bss_hostapd[2].set_value('ft_psk_generate_local', '0') + self.bss_hostapd[2].reload() + + wd = IWD(True) + + device = wd.list_devices(1)[0] + + self.connect(wd, device, self.bss_hostapd[0]) + + # IWD should connect, then attempt a roam to BSS 1, which should + # fail and cause the rank to be re-computed. This should then put + # bss 1 as the next candidate (since the FT factor is removed) + device.wait_for_event('ft-fallback-to-reassoc', timeout=60) + device.wait_for_event('ft-roam', timeout=60) + + self.verify_roam(wd, device, self.bss_hostapd[0], self.bss_hostapd[1]) + + self.bss_hostapd[1].deauthenticate(device.address) condition = 'obj.state == DeviceState.disconnected' wd.wait_for_object_condition(device, condition) + def tearDown(self): os.system('ip link set "' + self.bss_hostapd[0].ifname + '" down') os.system('ip link set "' + self.bss_hostapd[1].ifname + '" down') @@ -85,6 +150,13 @@ class Test(unittest.TestCase): self.rule0.enabled = False self.rule1.enabled = False self.rule2.enabled = False + self.rule3.enabled = False + self.rule_bss0.enabled = False + self.rule_bss1.enabled = False + self.rule_bss2.enabled = False + + for hapd in self.bss_hostapd: + hapd.default() @classmethod def setUpClass(cls): @@ -116,13 +188,18 @@ class Test(unittest.TestCase): cls.rule2 = hwsim.rules.create() cls.rule2.source = hwsim.get_radio('rad0').addresses[0] cls.rule2.signal = -8000 - cls.rule2.enabled = True # Causes IWD to first prefer BSS 1 to roam, then BSS 2. cls.rule3 = hwsim.rules.create() cls.rule3.source = hwsim.get_radio('rad2').addresses[0] cls.rule3.signal = -7000 - cls.rule3.enabled = True + + cls.rule_bss0 = hwsim.rules.create() + cls.rule_bss0.source = hwsim.get_radio('rad0').addresses[0] + cls.rule_bss1 = hwsim.rules.create() + cls.rule_bss1.source = hwsim.get_radio('rad1').addresses[0] + cls.rule_bss2 = hwsim.rules.create() + cls.rule_bss2.source = hwsim.get_radio('rad2').addresses[0] @classmethod def tearDownClass(cls): diff --git a/autotests/testPSK-roam/ft-psk-ccmp-1.conf b/autotests/testPSK-roam/ft-psk-ccmp-1.conf @@ -33,7 +33,9 @@ pmk_r1_push=0 # case. Only works with FT-PSK, otherwise brctl needs to be installed and # CONFIG_BRIDGE enabled in the kernel. ft_psk_generate_local=1 +rkh_pull_timeout=50 ft_over_ds=0 ap_table_expiration_time=36000 ap_table_max_size=10 rrm_neighbor_report=1 +ocv=1 diff --git a/autotests/testPSK-roam/ft-psk-ccmp-2.conf b/autotests/testPSK-roam/ft-psk-ccmp-2.conf @@ -33,7 +33,9 @@ pmk_r1_push=0 # case. Only works with FT-PSK, otherwise brctl needs to be installed and # CONFIG_BRIDGE enabled in the kernel. ft_psk_generate_local=1 +rkh_pull_timeout=50 ft_over_ds=0 ap_table_expiration_time=36000 ap_table_max_size=10 rrm_neighbor_report=1 +ocv=1 diff --git a/autotests/testPSK-roam/ft-psk-ccmp-3.conf b/autotests/testPSK-roam/ft-psk-ccmp-3.conf @@ -33,7 +33,9 @@ pmk_r1_push=0 # case. Only works with FT-PSK, otherwise brctl needs to be installed and # CONFIG_BRIDGE enabled in the kernel. ft_psk_generate_local=1 +rkh_pull_timeout=50 ft_over_ds=0 ap_table_expiration_time=36000 ap_table_max_size=10 rrm_neighbor_report=1 +ocv=1 diff --git a/autotests/testSAE-AntiClogging/clogging_test.py b/autotests/testSAE-AntiClogging/clogging_test.py @@ -55,14 +55,13 @@ class Test(unittest.TestCase): wd.clear_storage() def test_SAE(self): - self.hostapd.set_value('sae_pwe', '0'); - self.hostapd.set_value('sae_groups', '19'); - self.hostapd.reload() - self.hostapd.wait_for_event("AP-ENABLED") wd = IWD(True) self.validate_connection(wd) wd.clear_storage() + def setUp(self): + self.hostapd.default() + @classmethod def setUpClass(cls): cls.hostapd = HostapdCLI(config='ssidSAE-Clogging.conf') diff --git a/autotests/testSAE-AntiClogging/ssidSAE-Clogging.conf b/autotests/testSAE-AntiClogging/ssidSAE-Clogging.conf @@ -8,3 +8,5 @@ wpa_pairwise=CCMP sae_password=secret123|mac=ff:ff:ff:ff:ff:ff sae_anti_clogging_threshold=2 ieee80211w=2 +sae_pwe=0 +sae_groups=19 +\ No newline at end of file diff --git a/autotests/testSAE/autoconnect_test.py b/autotests/testSAE/autoconnect_test.py @@ -35,9 +35,6 @@ class Test(unittest.TestCase): wd.wait_for_object_condition(ordered_network.network_object, condition) def test_SAE(self): - self.hostapd.set_value('sae_pwe', '0') - self.hostapd.set_value('sae_groups', '19') - self.hostapd.reload() self.hostapd.wait_for_event("AP-ENABLED") wd = IWD(True) @@ -51,6 +48,9 @@ class Test(unittest.TestCase): wd = IWD(True) self.validate_connection(wd) + def setUp(self): + self.hostapd.default() + @classmethod def setUpClass(cls): cls.hostapd = HostapdCLI(config='ssidSAE.conf') diff --git a/autotests/testSAE/connection_test.py b/autotests/testSAE/connection_test.py @@ -45,16 +45,10 @@ class Test(unittest.TestCase): wd.unregister_psk_agent(psk_agent) def test_SAE(self): - self.hostapd.set_value('sae_pwe', '0') - self.hostapd.set_value('sae_groups', '19') - self.hostapd.set_value('vendor_elements', '') - self.hostapd.reload() self.hostapd.wait_for_event("AP-ENABLED") self.validate_connection(self.wd) def test_SAE_force_group_19(self): - self.hostapd.set_value('sae_pwe', '0') - self.hostapd.set_value('sae_groups', '19') # Vendor data from APs which require group 19 be used first # TODO: (for all tests) verify the expected group was used self.hostapd.set_value('vendor_elements', 'dd0cf4f5e8050500000000000000') @@ -63,7 +57,6 @@ class Test(unittest.TestCase): self.validate_connection(self.wd) def test_SAE_Group20(self): - self.hostapd.set_value('sae_pwe', '0') self.hostapd.set_value('sae_groups', '20') self.hostapd.set_value('vendor_elements', '') self.hostapd.reload() @@ -72,7 +65,6 @@ class Test(unittest.TestCase): def test_SAE_H2E(self): self.hostapd.set_value('sae_pwe', '1') - self.hostapd.set_value('sae_groups', '19') self.hostapd.set_value('vendor_elements', '') self.hostapd.reload() self.hostapd.wait_for_event("AP-ENABLED") @@ -87,6 +79,7 @@ class Test(unittest.TestCase): self.validate_connection(self.wd) def setUp(self): + self.hostapd.default() self.wd = IWD(True) def tearDown(self): diff --git a/autotests/testSAE/failure_test.py b/autotests/testSAE/failure_test.py @@ -37,13 +37,16 @@ class Test(unittest.TestCase): self.validate_connection(wd, 'InvalidSecret') def test_no_supported_groups(self): - hostapd = HostapdCLI(config='ssidSAE.conf') - hostapd.set_value('sae_groups', '1') - hostapd.reload() + self.hostapd.set_value('sae_groups', '1') + self.hostapd.reload() wd = IWD(True) self.validate_connection(wd, 'secret123') + def setUp(self): + self.hostapd = HostapdCLI(config='ssidSAE.conf') + self.hostapd.default() + @classmethod def setUpClass(cls): pass diff --git a/autotests/testSAE/ssidSAE.conf b/autotests/testSAE/ssidSAE.conf @@ -8,3 +8,4 @@ wpa_pairwise=CCMP sae_password=secret123|mac=ff:ff:ff:ff:ff:ff sae_groups=19 ieee80211w=2 +sae_pwe=0 diff --git a/autotests/testSAE/timeout_test.py b/autotests/testSAE/timeout_test.py @@ -40,10 +40,8 @@ class Test(unittest.TestCase): # needed because the hwsim rule only matches once and must be matched # on the first commit, not during group negotiation. # - hostapd = HostapdCLI(config='ssidSAE.conf') - hostapd.set_value('vendor_elements', 'dd0cf4f5e8050500000000000000') - hostapd.set_value('sae_groups', '19') - hostapd.reload() + self.hostapd.set_value('vendor_elements', 'dd0cf4f5e8050500000000000000') + self.hostapd.reload() hwsim = Hwsim() bss_radio = hwsim.get_radio('rad0') @@ -64,10 +62,8 @@ class Test(unittest.TestCase): rule0.remove() def test_sta_confirm_not_acked(self): - hostapd = HostapdCLI(config='ssidSAE.conf') - hostapd.set_value('vendor_elements', 'dd0cf4f5e8050500000000000000') - hostapd.set_value('sae_groups', '19') - hostapd.reload() + self.hostapd.set_value('vendor_elements', 'dd0cf4f5e8050500000000000000') + self.hostapd.reload() hwsim = Hwsim() bss_radio = hwsim.get_radio('rad0') @@ -87,6 +83,10 @@ class Test(unittest.TestCase): rule0.remove() + def setUp(self): + self.hostapd = HostapdCLI(config='ssidSAE.conf') + self.hostapd.default() + @classmethod def setUpClass(cls): pass diff --git a/autotests/testWPA2/connection_test.py b/autotests/testWPA2/connection_test.py @@ -43,9 +43,6 @@ class Test(unittest.TestCase): wd.unregister_psk_agent(psk_agent) def test_ccmp(self): - self.hostapd.set_value('rsn_pairwise', 'CCMP') - self.hostapd.reload() - self.hostapd.wait_for_event("AP-ENABLED") self.validate_connection_success(self.wd) def test_gcmp(self): @@ -67,6 +64,7 @@ class Test(unittest.TestCase): self.validate_connection_success(self.wd) def setUp(self): + self.hostapd.default() self.wd = IWD(True) def tearDown(self): diff --git a/autotests/testWPA2/ssidWPA2.conf b/autotests/testWPA2/ssidWPA2.conf @@ -5,3 +5,4 @@ ssid=ssidWPA2 wpa=2 wpa_pairwise=CCMP wpa_passphrase=secret123 +rsn_pairwise=CCMP diff --git a/autotests/testWPA2withMFP/connection_test.py b/autotests/testWPA2withMFP/connection_test.py @@ -39,9 +39,6 @@ class Test(unittest.TestCase): wd.unregister_psk_agent(psk_agent) def test_cmac(self): - self.hostapd.set_value('group_mgmt_cipher', 'AES-128-CMAC') - self.hostapd.reload() - self.hostapd.wait_for_event("AP-ENABLED") self.validate_connection_success(self.wd) def test_gmac(self): @@ -63,6 +60,7 @@ class Test(unittest.TestCase): self.validate_connection_success(self.wd) def setUp(self): + self.hostapd.default() self.wd = IWD(True) def tearDown(self): diff --git a/autotests/testWPA2withMFP/ssidWPA2.conf b/autotests/testWPA2withMFP/ssidWPA2.conf @@ -8,3 +8,4 @@ wpa_passphrase=secret123 ieee80211w=2 wpa_key_mgmt=WPA-PSK-SHA256 +group_mgmt_cipher=AES-128-CMAC diff --git a/autotests/util/hostapd.py b/autotests/util/hostapd.py @@ -64,7 +64,16 @@ class HostapdCLI(object): hapd = ctx.get_hapd_instance(config) self.interface = hapd.intf - self.config = hapd.config + self._config_path = "/tmp/" + hapd.config + self._default_config = self._get_config(self._config_path) + + # The vendor_elements is somewhat of a special case because you can't + # set it to 'nothing' within the hostapd config. In most cases tests do + # not use this and we don't want to require they unset this value + # during initialization. Default this to '' so set_value won't throw + # an exception. + if self._default_config.get('vendor_elements', None) == None: + self._default_config['vendor_elements'] = '' if not self.interface: raise Exception('config %s not found' % config) @@ -89,6 +98,12 @@ class HostapdCLI(object): ctrl_count = ctrl_count + 1 + def _get_config(self, path): + f = open(path) + lines = f.readlines() + f.close() + return dict([[v.strip() for v in kv] for kv in [l.split('#', 1)[0].split('=', 1) for l in lines] if len(kv) == 2]) + def _handle_data_in(self, sock, *args): newdata = sock.recv(4096) @@ -151,6 +166,10 @@ class HostapdCLI(object): pass def set_value(self, key, value): + # Don't allow new settings, defaults should always be in hostapd config + if self._default_config.get(key, None) == None: + raise Exception("Untracked setting '%s'! Please set default in hostapd config" % key) + cmd = self.cmdline + ['set', key, value] ctx.start_process(cmd).wait() @@ -179,6 +198,12 @@ class HostapdCLI(object): ctx.start_process(self.cmdline + ['disable']).wait() ctx.start_process(self.cmdline + ['enable']).wait() + def default(self): + for k, v in self._default_config.items(): + self.set_value(k, v) + + self.reload() + def disable(self): ctx.start_process(self.cmdline + ['disable']).wait() diff --git a/autotests/util/iwd.py b/autotests/util/iwd.py @@ -42,6 +42,8 @@ IWD_P2P_SERVICE_MANAGER_INTERFACE = 'net.connman.iwd.p2p.ServiceManager' IWD_P2P_WFD_INTERFACE = 'net.connman.iwd.p2p.Display' IWD_STATION_DEBUG_INTERFACE = 'net.connman.iwd.StationDebug' IWD_DPP_INTERFACE = 'net.connman.iwd.DeviceProvisioning' +IWD_DPP_PKEX_INTERFACE = 'net.connman.iwd.SharedCodeDeviceProvisioning' +IWD_SHARED_CODE_AGENT_INTERFACE = 'net.connman.iwd.SharedCodeAgent' IWD_AGENT_MANAGER_PATH = '/net/connman/iwd' IWD_TOP_LEVEL_PATH = '/' @@ -212,6 +214,38 @@ class SignalAgent(dbus.service.Object): def handle_new_level(self, path, level): pass +class SharedCodeAgent(dbus.service.Object): + def __init__(self, codes = {}): + self._path = '/test/agent/' + str(int(round(time.time() * 1000))) + self._codes = codes + + dbus.service.Object.__init__(self, ctx.get_bus(), self._path) + + @property + def path(self): + return self._path + + @dbus.service.method(IWD_SHARED_CODE_AGENT_INTERFACE, + in_signature='', out_signature='') + def Release(self): + print("SharedCodeAgent released") + + @dbus.service.method(IWD_SHARED_CODE_AGENT_INTERFACE, + in_signature='s', out_signature='') + def Cancel(self, reason): + print("SharedCodeAgent canceled (%s)" % reason) + + @dbus.service.method(IWD_SHARED_CODE_AGENT_INTERFACE, + in_signature='s', out_signature='s') + def RequestSharedCode(self, identifier): + print("SharedCodeAgent request for %s" % identifier) + + code = self._codes.get(identifier, None) + if not code: + return NotFoundEx("No code found for %s" % identifier) + + return code + class AdHocDevice(IWDDBusAbstract): ''' Class represents an AdHoc device object: net.connman.iwd.AdHoc @@ -299,6 +333,43 @@ class DeviceProvisioning(IWDDBusAbstract): def role(self): return self._properties['Role'] +class SharedCodeDeviceProvisioning(IWDDBusAbstract): + _iface_name = IWD_DPP_PKEX_INTERFACE + + def start_enrollee(self, code, identifier=None): + args = { + "Code": code + } + + if identifier: + args["Identifier"] = identifier + + self._iface.StartEnrollee(args) + + def start_configurator(self, path): + self._iface.StartConfigurator(dbus.ObjectPath(path)) + + def configure_enrollee(self, code, identifier=None): + args = { + "Code": code + } + + if identifier: + args["Identifier"] = identifier + + self._iface.ConfigureEnrollee(args) + + def stop(self): + self._iface.Stop() + + @property + def started(self): + return self._properties['Started'] + + @property + def role(self): + return self._properties['Role'] + class AccessPointDevice(IWDDBusAbstract): ''' Class represents net.connman.iwd.AccessPoint @@ -375,6 +446,7 @@ class Device(IWDDBusAbstract): self._station_props = None self._station_debug_obj = None self._dpp_obj = None + self._sc_dpp_obj = None self._ap_obj = None IWDDBusAbstract.__init__(self, *args, **kwargs) @@ -408,6 +480,17 @@ class Device(IWDDBusAbstract): return self._dpp_obj @property + def _sc_device_provisioning(self): + if self._properties['Mode'] != 'station': + self._prop_proxy.Set(IWD_DEVICE_INTERFACE, 'Mode', 'station') + + if self._sc_dpp_obj is None: + self._sc_dpp_obj = SharedCodeDeviceProvisioning( + object_path=self._object_path, + namespace=self._namespace) + return self._sc_dpp_obj + + @property def _station_debug(self): if self._properties['Mode'] != 'station': self._prop_proxy.Set(IWD_DEVICE_INTERFACE, 'Mode', 'station') @@ -774,13 +857,76 @@ class Device(IWDDBusAbstract): self._station_debug.wait_for_event(event, timeout) def dpp_start_enrollee(self): - return self._device_provisioning.start_enrollee() + ret = self._device_provisioning.start_enrollee() + + condition = 'obj.started == True' + IWD._wait_for_object_condition(self._device_provisioning, condition) + condition = 'obj.role == "enrollee"' + IWD._wait_for_object_condition(self._device_provisioning, condition) + + return ret def dpp_start_configurator(self, uri=None): - return self._device_provisioning.start_configurator(uri) + ret = self._device_provisioning.start_configurator(uri) + + condition = 'obj.started == True' + IWD._wait_for_object_condition(self._device_provisioning, condition) + condition = 'obj.role == "configurator"' + IWD._wait_for_object_condition(self._device_provisioning, condition) + + return ret + + def dpp_pkex_enroll(self, *args, **kwargs): + ret = self._sc_device_provisioning.start_enrollee(*args, **kwargs) + + condition = 'obj.started == True' + IWD._wait_for_object_condition(self._sc_device_provisioning, condition) + condition = 'obj.role == "enrollee"' + IWD._wait_for_object_condition(self._sc_device_provisioning, condition) + + return ret + + def dpp_pkex_start_configurator(self, *args, **kwargs): + ret = self._sc_device_provisioning.start_configurator(*args, **kwargs) + + condition = 'obj.started == True' + IWD._wait_for_object_condition(self._sc_device_provisioning, condition) + condition = 'obj.role == "configurator"' + IWD._wait_for_object_condition(self._sc_device_provisioning, condition) + + return ret + + def dpp_pkex_configure_enrollee(self, *args, **kwargs): + ret = self._sc_device_provisioning.configure_enrollee(*args, **kwargs) + + condition = 'obj.started == True' + IWD._wait_for_object_condition(self._sc_device_provisioning, condition) + condition = 'obj.role == "configurator"' + IWD._wait_for_object_condition(self._sc_device_provisioning, condition) + + return ret + + def dpp_pkex_stop(self): + ret = self._sc_device_provisioning.stop() + + condition = 'obj.started == False' + IWD._wait_for_object_condition(self._sc_device_provisioning, condition) + + return ret + + def dpp_pkex_register_agent(self, path): + self._sc_device_provisioning.register_agent(path) + + def dpp_pkex_unregister_agent(self): + self._sc_device_provisioning.unregister_agent() def dpp_stop(self): - return self._device_provisioning.stop() + ret = self._device_provisioning.stop() + + condition = 'obj.started == False' + IWD._wait_for_object_condition(self._device_provisioning, condition) + + return ret def __str__(self, prefix = ''): s = prefix + 'Device: ' + self.device_path + '\n'\ diff --git a/autotests/util/wpas.py b/autotests/util/wpas.py @@ -76,7 +76,7 @@ class Wpas: for e in self._rx_data: if event in e: - return self._rx_data + return e return False @@ -273,13 +273,17 @@ class Wpas: return self._dpp_uri - def dpp_configurator_create(self, uri): + def dpp_configurator_create(self, uri=None): self._rx_data = [] self._ctrl_request('DPP_CONFIGURATOR_ADD') self._dpp_conf_id = self.wait_for_result() while not self._dpp_conf_id.isnumeric(): self._dpp_conf_id = self.wait_for_result() + if not uri: + print("DPP Configurator ID: %s" % self._dpp_conf_id) + return + self._rx_data = [] self._ctrl_request('DPP_QR_CODE ' + uri) self._dpp_qr_id = self.wait_for_result() @@ -302,6 +306,50 @@ class Wpas: self.wait_for_event('DPP-AUTH-SUCCESS', timeout=30) self.wait_for_event('DPP-CONF-SENT') + def dpp_bootstrap_gen(self, type='qrcode', curve=None): + cmd = f'DPP_BOOTSTRAP_GEN type={type}' + + if curve: + cmd += f' curve={curve}' + + self._rx_data = [] + self._ctrl_request(cmd) + self._dpp_id = self.wait_for_result() + while not self._dpp_id.isnumeric(): + self._dpp_id = self.wait_for_result() + + def dpp_pkex_add(self, code, identifier=None, version=None, initiator=False, role=None): + cmd = f'DPP_PKEX_ADD own={self._dpp_id}' + + if identifier: + cmd += f' identifier={identifier}' + + if initiator: + cmd += f' init=1' + + if version: + cmd += f' ver={version}' + + if role: + cmd += f' role={role}' + + cmd += f' code={code}' + + self._rx_data = [] + self._ctrl_request(cmd) + + def dpp_pkex_remove(self): + self._rx_data = [] + self._ctrl_request("DPP_PKEX_REMOVE *") + + def dpp_listen(self, freq): + self._rx_data = [] + self._ctrl_request(f'DPP_LISTEN {freq}') + + def dpp_stop_listen(self): + self._rx_data = [] + self._ctrl_request("DPP_STOP_LISTEN") + def dpp_configurator_remove(self): self._ctrl_request('DPP_CONFIGURATOR_REMOVE *') self.wait_for_result() diff --git a/client/dbus-proxy.h b/client/dbus-proxy.h @@ -3,6 +3,7 @@ * Wireless daemon for Linux * * Copyright (C) 2017-2019 Intel Corporation. All rights reserved. + * Copyright (C) 2023, Locus Robotics * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -38,6 +39,8 @@ struct proxy_interface; #define IWD_AP_DIAGNOSTIC_INTERFACE "net.connman.iwd.AccessPointDiagnostic" #define IWD_DAEMON_INTERFACE "net.connman.iwd.Daemon" #define IWD_DPP_INTERFACE "net.connman.iwd.DeviceProvisioning" +#define IWD_DPP_PKEX_INTERFACE \ + "net.connman.iwd.SharedCodeDeviceProvisioning" typedef bool (*proxy_property_match_func_t) (const void *a, const void *b); diff --git a/client/display.c b/client/display.c @@ -633,7 +633,7 @@ static void display_completion_matches(char **matches, int num_matches, l_free(prompt); for (index = 1, line_used = 0; matches[index]; index++) { - if ((line_used + max_length) > LINE_LEN) { + if ((line_used + max_length + 1) >= (LINE_LEN - 1)) { strcpy(&line[line_used], "\n"); display_text(line); diff --git a/client/dpp-pkex.c b/client/dpp-pkex.c @@ -0,0 +1,314 @@ +/* + * + * Wireless daemon for Linux + * + * Copyright (C) 2023 Locus Robotics. All rights reserved. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <stdio.h> +#include <linux/limits.h> + +#include <ell/ell.h> + +#include "client/command.h" +#include "client/dbus-proxy.h" +#include "client/device.h" +#include "client/display.h" +#include "src/util.h" + +struct pkex { + bool started; + char *role; +}; + +static void *pkex_create(void) +{ + return l_new(struct pkex, 1); +} + +static void pkex_destroy(void *data) +{ + struct pkex *pkex = data; + + l_free(pkex->role); + l_free(pkex); +} + +static void display_pkex_inline(const char *margin, const void *data) +{ + const struct proxy_interface *pkex_i = data; + struct proxy_interface *device_i = + proxy_interface_find(IWD_DEVICE_INTERFACE, + proxy_interface_get_path(pkex_i)); + const char *identity; + + if (!device_i) + return; + + identity = proxy_interface_get_identity_str(device_i); + if (!identity) + return; + + display("%s%-*s\n", margin, 20, identity); +} + +static void check_errors_method_callback(struct l_dbus_message *message, + void *user_data) +{ + dbus_message_has_error(message); +} + +static enum cmd_status cmd_list(const char *device_name, char **argv, int argc) +{ + const struct l_queue_entry *entry; + struct l_queue *match = + proxy_interface_find_all(IWD_DPP_PKEX_INTERFACE, NULL, NULL); + + display_table_header("DPP-PKEX-capable Devices", + MARGIN "%-*s", 20, "Name"); + + if (!match) { + display("No DPP-PKEX-capable devices available\n"); + display_table_footer(); + + return CMD_STATUS_DONE; + } + + for (entry = l_queue_get_entries(match); entry; entry = entry->next) { + const struct proxy_interface *pkex = entry->data; + display_pkex_inline(MARGIN, pkex); + } + + display_table_footer(); + + l_queue_destroy(match, NULL); + + return CMD_STATUS_DONE; +} + +static enum cmd_status cmd_enroll_or_configure(const char *device_name, + char **argv, int argc, + const char *method) +{ + const struct proxy_interface *pkex; + const char *code; + const char *id = NULL; + + pkex = device_proxy_find(device_name, IWD_DPP_PKEX_INTERFACE); + if (!pkex) { + display("No pkex pkex on device: '%s'\n", device_name); + return CMD_STATUS_INVALID_VALUE; + } + + if (argc < 1) + return CMD_STATUS_INVALID_ARGS; + + code = argv[0]; + + if (argc > 1) + id = argv[1]; + + if (id) + proxy_interface_method_call(pkex, method, "a{sv}", + check_errors_method_callback, 2, + "Code", "s", code, + "Identifier", "s", id); + else + proxy_interface_method_call(pkex, method, "a{sv}", + check_errors_method_callback, 1, + "Code", "s", code); + + return CMD_STATUS_TRIGGERED; +} + +static enum cmd_status cmd_enroll(const char *device_name, + char **argv, int argc) +{ + return cmd_enroll_or_configure(device_name, argv, argc, + "StartEnrollee"); +} + +static enum cmd_status cmd_configure(const char *device_name, + char **argv, int argc) +{ + return cmd_enroll_or_configure(device_name, argv, argc, + "ConfigureEnrollee"); +} + +static enum cmd_status cmd_stop(const char *device_name, char **argv, int argc) +{ + const struct proxy_interface *pkex_i = + device_proxy_find(device_name, IWD_DPP_PKEX_INTERFACE); + + if (!pkex_i) { + display("No pkex on device: '%s'\n", device_name); + return CMD_STATUS_INVALID_VALUE; + } + + proxy_interface_method_call(pkex_i, "Stop", "", + check_errors_method_callback); + + return CMD_STATUS_TRIGGERED; +} + +static enum cmd_status cmd_show(const char *device_name, + char **argv, int argc) +{ + const struct proxy_interface *proxy = + device_proxy_find(device_name, IWD_DPP_PKEX_INTERFACE); + char *caption = l_strdup_printf("%s: %s", "DPP-PKEX", device_name); + + if (!proxy) { + display("No DPP-PKEX interface on device: '%s'\n", device_name); + return CMD_STATUS_INVALID_VALUE; + } + + proxy_properties_display(proxy, caption, MARGIN, 20, 47); + l_free(caption); + + display_table_footer(); + + return CMD_STATUS_DONE; +} + +static const struct command pkex_commands[] = { + { NULL, "list", NULL, cmd_list, + "List shared code capable devices", true }, + { "<wlan>", "stop", NULL, cmd_stop, "Aborts shared code operations" }, + { "<wlan>", "show", NULL, cmd_show, + "Shows the shared code state", true }, + { "<wlan>", "enroll", "key [identifier]", + cmd_enroll, "Start a shared code enrollee"}, + { "<wlan>", "configure", "key [identifier]", + cmd_configure, + "Start a shared code configurator"}, + { } +}; + +static char *family_arg_completion(const char *text, int state) +{ + return device_arg_completion(text, state, pkex_commands, + IWD_DPP_PKEX_INTERFACE); +} + +static char *entity_arg_completion(const char *text, int state) +{ + return command_entity_arg_completion(text, state, pkex_commands); +} + +static void update_started(void *data, struct l_dbus_message_iter *variant) +{ + struct pkex *pkex = data; + bool value; + + if (!l_dbus_message_iter_get_variant(variant, "b", &value)) { + pkex->started = false; + return; + } + + pkex->started = value; +} + +static const char *started_tostr(const void *data) +{ + const struct pkex *pkex = data; + + return pkex->started ? "yes" : "no"; +} + +static void update_role(void *data, struct l_dbus_message_iter *variant) +{ + struct pkex *pkex = data; + const char *value; + + if (pkex->role) + l_free(pkex->role); + + if (!l_dbus_message_iter_get_variant(variant, "s", &value)) { + pkex->role = NULL; + return; + } + + pkex->role = l_strdup(value); +} + +static const char *role_tostr(const void *data) +{ + const struct pkex *pkex = data; + + return pkex->role; +} + +static const struct proxy_interface_property pkex_properties[] = { + { "Started", "b", update_started, started_tostr }, + { "Role", "s", update_role, role_tostr }, + { } +}; + +static const struct proxy_interface_type_ops pkex_ops = { + .create = pkex_create, + .destroy = pkex_destroy, +}; + +static struct proxy_interface_type pkex_interface_type = { + .interface = IWD_DPP_PKEX_INTERFACE, + .properties = pkex_properties, + .ops = &pkex_ops, +}; + + +static struct command_family pkex_command_family = { + .caption = "Shared Code Device Provisioning (PKEX)", + .name = "pkex", + .command_list = pkex_commands, + .family_arg_completion = family_arg_completion, + .entity_arg_completion = entity_arg_completion, +}; + +static int pkex_command_family_init(void) +{ + command_family_register(&pkex_command_family); + + return 0; +} + +static void pkex_command_family_exit(void) +{ + command_family_unregister(&pkex_command_family); +} + +COMMAND_FAMILY(pkex_command_family, pkex_command_family_init, + pkex_command_family_exit) + +static int pkex_interface_init(void) +{ + proxy_interface_type_register(&pkex_interface_type); + + return 0; +} + +static void pkex_interface_exit(void) +{ + proxy_interface_type_unregister(&pkex_interface_type); +} + +INTERFACE_TYPE(pkex_interface_type, pkex_interface_init, pkex_interface_exit) diff --git a/configure.ac b/configure.ac @@ -1,5 +1,5 @@ AC_PREREQ([2.69]) -AC_INIT([iwd],[2.8]) +AC_INIT([iwd],[2.10]) AC_CONFIG_HEADERS(config.h) AC_CONFIG_AUX_DIR(build-aux) @@ -302,7 +302,7 @@ if (test "${enable_external_ell}" = "yes"); then test "${enable_monitor}" != "no" || test "${enable_wired}" = "yes" || test "${enable_hwsim}" = "yes"); then - ell_min_version="0.58" + ell_min_version="0.61" else ell_min_version="0.5" fi diff --git a/doc/device-provisioning-api.txt b/doc/device-provisioning-api.txt @@ -18,11 +18,9 @@ Methods string StartEnrollee() void Stop() - Stop an enrollee. + Stop an enrollee or configurator that is running. - Possible errors: net.connman.iwd.Busy - net.connman.iwd.Failed - net.connman.iwd.InvalidArguments + Possible errors: net.connman.iwd.NotFound string StartConfigurator() @@ -71,3 +69,149 @@ Properties boolean Started [readonly] Indicates the DPP URI. This property is only available when Started is true. + + +Interface net.connman.iwd.SharedCodeDeviceProvisioning [Experimental] +Object path /net/connman/iwd/{phy0,phy1,...}/{1,2,...} + + void ConfigureEnrollee(a{sv}) + + Starts a DPP configurator using a shared code (and + optionally identifier) set in the dictionary argument. + Valid dictionary keys are: + + string Code + The shared code to use. The code used by both + parties (configurator and enrollee) must match. + + string Identifier + An optional identifier. The identifier used by + both parties must match. Per the DPP spec the + identifier "shall be a UTF-8 string not greater + than eighty (80) octets" + + As with the DeviceProvisioning interface, configurators + must be connected to the network they wish to configure + in order to start. + + Once started a configurator (acting as a responder) will + listen on the currently connected channel for an + enrollee's initial exchange request which will kick off + the shared code bootstrapping protocol (PKEX). Once + completed DPP will start automatically. Only one + enrollee can be configured per call to + ConfigureEnrollee, i.e. once PKEX/DPP has finished + (including failure) the configurator will stop. + + The SharedCode methods have an eventual timeout and will + stop automatically after 2 minutes. + + Possible errors: net.connman.iwd.Busy + net.connman.iwd.NotConnected + net.connman.InvalidArguments + net.connman.NotSupported + + void StartEnrollee(a{sv}) + + Starts a DPP enrollee using a shared code (and + optionally identifier) set in the dictionary argument + (described above in ConfigureEnrollee). + + As with the device provisioning interface, enrollees + must be disconnected in order to start. + + Once started an enrollee (acting as an initiator) will + iterate channels sending out broadcast exchange requests + waiting for a response from a configurator. A response + will kick off the shared code bootstrapping protocol + (PKEX), followed by DPP if successful. Once the + protocols have completed, or failed, the enrollee will + stop. If failed, StartEnrollee will need to be called + again to retry. + + Possible errors: net.connman.iwd.Busy + net.connman.iwd.InvalidArguments + + void StartConfigurator(object agent_path) + + Start a shared code configurator using an agent + (distingushed by 'agent_path') to obtain the shared + code. This method is meant for an automated use case + where a configurator is capable of configuring multiple + enrollees, and distinguishing between them by their + identifier. + + If the agent service disappears during the shared code + exchange it will be stopped, and the protocol will fail. + + This method behaves nearly the same as ConfigureEnrollee + except upon receiving an enrollees first exchange + request the registered agent will be asked for the + shared code using the RequestSharedCode method. + + Though the agent can provide shared codes for multiple + enrollees, this method will only configure a single + enrollee at a time. Once completed it will need to be + called again to configure additional enrollees. + + Possible errors: net.connman.iwd.Busy + net.connman.iwd.NotConnected + net.connman.iwd.NoAgent + net.connman.iwd.NotSupported + + Stop() + + Stop a currently running configurator/enrollee. Note + that this will also interrupt DPP if the protocol has + advanced that far. Since DPP is initiated implicitly + from the shared code APIs it will also be canceled. + Calling Stop() if DPP was started via the + DeviceProvisioning interface will not stop it. + + Possible errors: net.connman.iwd.NotFound + +Properties boolean Started [readonly] + + True if shared code device provisioning is currently + active. (configurator or enrollee is started) + + string Role [readonly, optional] + + Indicates the DPP role. Possible values are "enrollee" + or "configurator". This property is only available when + Started is true. + +SharedCodeAgent hierarchy +========================= + +Service unique name +Interface net.connman.iwd.SharedCodeAgent [Experimental] +Object path freely definable + +Methods void Release() [noreply] + + This method gets called when the service daemon + unregisters the agent. + + string RequestSharedCode(string identifier) + + This method gets called when a shared code is requested + for a particular enrollee, distingushed by the + identifier. The shared code agent should lookup the + identifier and return the shared code, or return an + error if not found. + + Possible Errors: [service].Error.Canceled + [service].Error.NotFound + + void Cancel(string reason) [noreply] + + This method gets called to indicate that the agent + request failed before a reply was returned. The + argument will indicate why the request is being + cancelled and may be "user-canceled", "timed-out" or + "shutdown". + +Examples Requesting a shared code for an enrollee identified by "foo" + + RequestSharedCode("foo") ==> "super_secret_code" diff --git a/monitor/nlmon.c b/monitor/nlmon.c @@ -1394,31 +1394,22 @@ static void print_ie_ht_operation(unsigned int level, const char *label, } static void print_spatial_stream_map(unsigned int level, const char *label, - const uint8_t *map) + const uint8_t *map, + const char **stream_map) { - static const char *spatial_streams[] = { - "0 - MCS 0-7 supported", - "1 - MCS 0-8 supported", - "2 - MCS 0-9 supported", - "3 - No MCS support", - }; + unsigned int i; + unsigned int j = 0; - print_attr(level + 1, "%s 1 Streams: %s", label, - spatial_streams[bit_field(map[0], 0, 2)]); - print_attr(level + 1, "%s 2 Streams: %s", label, - spatial_streams[bit_field(map[0], 2, 2)]); - print_attr(level + 1, "%s 3 Streams: %s", label, - spatial_streams[bit_field(map[0], 4, 2)]); - print_attr(level + 1, "%s 4 Streams: %s", label, - spatial_streams[bit_field(map[0], 6, 2)]); - print_attr(level + 1, "%s 5 Streams: %s", label, - spatial_streams[bit_field(map[1], 0, 2)]); - print_attr(level + 1, "%s 6 Streams: %s", label, - spatial_streams[bit_field(map[1], 2, 2)]); - print_attr(level + 1, "%s 7 Streams: %s", label, - spatial_streams[bit_field(map[1], 4, 2)]); - print_attr(level + 1, "%s 8 Streams: %s", label, - spatial_streams[bit_field(map[1], 6, 2)]); + for (i = 0; i < 8; i++, j += 2) { + unsigned int byte = (i < 4) ? 0 : 1; + uint8_t field = bit_field(map[byte], j % 8, 2); + + if (field == 3) + continue; + + print_attr(level + 1, "%s %u Streams: %s", label, i + 1, + stream_map[field]); + } } static void print_ie_vht_operation(unsigned int level, const char *label, @@ -1430,6 +1421,13 @@ static void print_ie_vht_operation(unsigned int level, const char *label, "2 - 160 Mhz", "3 - 80+80 Mhz", }; + + static const char *spatial_streams[] = { + "MCS 0-7 supported", + "MCS 0-8 supported", + "MCS 0-9 supported", + }; + uint8_t *bytes = (uint8_t *) data; if (size < 5) { @@ -1443,7 +1441,8 @@ static void print_ie_vht_operation(unsigned int level, const char *label, print_attr(level + 1, "Channel Center Frequency 1: %d", bytes[1]); print_attr(level + 1, "Channel Center Frequency 2: %d", bytes[2]); - print_spatial_stream_map(level + 1, "Basic VHT-MCS", bytes + 3); + print_spatial_stream_map(level + 1, "Basic VHT-MCS", bytes + 3, + spatial_streams); } static const char *extended_capabilities_bitfield[80] = { @@ -1656,6 +1655,13 @@ static void print_ie_vht_capabilities(unsigned int level, [29] = "TX Antenna Pattern Consistency", [30 ... 31] = "Extended NSS BW Support", }; + + static const char *spatial_streams[] = { + "MCS 0-7 supported", + "MCS 0-8 supported", + "MCS 0-9 supported", + }; + uint8_t info_mask[] = { 0xf0, 0x18, 0x78, 0x30 }; print_attr(level, "%s: len %u", label, size); @@ -1666,16 +1672,68 @@ static void print_ie_vht_capabilities(unsigned int level, print_ie_bitfield(level + 1, "VHT Capabilities Info", data, info_mask, 4, vht_capabilities_info_bitfield); - print_spatial_stream_map(level + 1, "RxVHT-MCS", data + 4); + print_spatial_stream_map(level + 1, "RxVHT-MCS", data + 4, + spatial_streams); print_attr(level + 1, "Rx Highest Supported Long GI Data Rate: %d", l_get_le16(data + 6) & 0x1f); - print_spatial_stream_map(level + 1, "TxVHT-MCS", data + 8); + print_spatial_stream_map(level + 1, "TxVHT-MCS", data + 8, + spatial_streams); print_attr(level + 1, "Tx Highest Supported Long GI Data Rate: %d", l_get_le16(data + 10) & 0x1f); if (test_bit(data + 4, 61)) print_attr(level + 1, "VHT Extended NSS BW Capable"); } +static void print_ie_he_capabilities(unsigned int level, + const char *label, + const void *data, uint16_t size) +{ + const uint8_t *ptr = data; + uint8_t width_set = bit_field((ptr + 6)[0], 1, 7); + uint8_t mask = 0xff; + + const char *he_channel_width_bitfield[] = { + [0] = "40MHz supported (2.4GHz)", + [1] = "40MHz/80MHz supported (5GHz/6GHz)", + [2] = "160MHz supported (5GHz/6GHz)", + [3] = "160MHz/80+80MHz supported (5GHz/6GHz)", + [4] = "242-tone RUs (2.4GHz)", + [5] = "242-tone RUs (5GHz/6GHz)", + }; + + static const char *spatial_streams[] = { + "MCS 0-7 supported", + "MCS 0-9 supported", + "MCS 0-11 supported", + }; + + print_attr(level, "%s: len %u", label, size); + + print_ie_bitfield(level + 1, "HE supported channel width set", + &width_set, &mask, 1, he_channel_width_bitfield); + + if (test_bit(&width_set, 1) || test_bit(&width_set, 0)) { + print_spatial_stream_map(level + 1, "Rx HE-MCS Map <= 80MHz", + data + 17, spatial_streams); + print_spatial_stream_map(level + 1, "Tx HE-MCS Map <= 80MHz", + data + 19, spatial_streams); + } + + if (test_bit(&width_set, 2)) { + print_spatial_stream_map(level + 1, "Rx HE-MCS Map 160MHz", + data + 21, spatial_streams); + print_spatial_stream_map(level + 1, "Tx HE-MCS Map 160MHz", + data + 23, spatial_streams); + } + + if (test_bit(&width_set, 3)) { + print_spatial_stream_map(level + 1, "Rx HE-MCS Map 80+80MHz", + data + 25, spatial_streams); + print_spatial_stream_map(level + 1, "Tx HE-MCS Map 80+80MHz", + data + 27, spatial_streams); + } +} + static void print_ie_rm_enabled_caps(unsigned int level, const char *label, const void *data, uint16_t size) @@ -2430,6 +2488,8 @@ static struct attr_entry ie_entry[] = { ATTR_CUSTOM, { .function = print_ie_ht_capabilities } }, { IE_TYPE_VHT_CAPABILITIES, "VHT Capabilities", ATTR_CUSTOM, { .function = print_ie_vht_capabilities } }, + { IE_TYPE_HE_CAPABILITIES, "HE Capabilities", + ATTR_CUSTOM, { .function = print_ie_he_capabilities } }, { IE_TYPE_RM_ENABLED_CAPABILITIES, "RM Enabled Capabilities", ATTR_CUSTOM, { .function = print_ie_rm_enabled_caps } }, { IE_TYPE_INTERWORKING, "Interworking", @@ -2701,7 +2761,7 @@ static void print_wsc_configuration_error(unsigned int level, const char *label, "Message timeout", "Registration session timeout", "Device Password Auth Failure", - "60 Ghz channel not supported", + "60 GHz channel not supported", "Public Key Hash Mismatch", }; diff --git a/src/adhoc.c b/src/adhoc.c @@ -25,6 +25,7 @@ #endif #include <linux/rtnetlink.h> +#include <sys/socket.h> #include <linux/if.h> #include <ell/ell.h> diff --git a/src/ap.c b/src/ap.c @@ -392,10 +392,17 @@ static void ap_del_station(struct sta_state *sta, uint16_t reason, bool disassociate) { struct ap_state *ap = sta->ap; + uint32_t ifindex = netdev_get_ifindex(ap->netdev); struct ap_event_station_removed_data event_data; bool send_event = false; + struct l_genl_msg *msg; + uint8_t subtype = disassociate ? + MPDU_MANAGEMENT_SUBTYPE_DISASSOCIATION : + MPDU_MANAGEMENT_SUBTYPE_DEAUTHENTICATION; + + msg = nl80211_build_del_station(ifindex, sta->addr, reason, subtype); + l_genl_family_send(ap->nl80211, msg, NULL, NULL, NULL); - netdev_del_station(ap->netdev, sta->addr, reason, disassociate); sta->associated = false; if (sta->rsna) { @@ -1202,7 +1209,7 @@ static size_t ap_build_country_ie(struct ap_state *ap, uint8_t *out_buf, * and use the same TX power. Any deviation from this results in a new * channel group. * - * TODO: 6Ghz requires operating triplets, not subband triplets. + * TODO: 6GHz requires operating triplets, not subband triplets. */ for (i = 0; i < len; i++) { const struct band_freq_attrs *attr = &list[i]; @@ -3564,7 +3571,7 @@ static bool ap_validate_band_channel(struct ap_state *ap) freq = band_channel_to_freq(ap->channel, ap->band); if (!freq) { l_error("AP invalid band (%s) and channel (%u) combination", - (ap->band & BAND_FREQ_5_GHZ) ? "5Ghz" : "2.4GHz", + (ap->band & BAND_FREQ_5_GHZ) ? "5GHz" : "2.4GHz", ap->channel); return false; } diff --git a/src/band.c b/src/band.c @@ -1260,7 +1260,10 @@ int band_freq_to_ht_chandef(uint32_t freq, const struct band_freq_attrs *attr, * - 40mhz we can base the selection off the channel flags, either * higher or lower. */ +_Pragma("GCC diagnostic push") +_Pragma("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") switch (width) { +_Pragma("GCC diagnostic pop") case BAND_CHANDEF_WIDTH_20: return 0; case BAND_CHANDEF_WIDTH_40: diff --git a/src/crypto.c b/src/crypto.c @@ -439,8 +439,6 @@ free_ctr: return false; } -#define SWAP(a, b) do { int _t = a; a = b; b = _t; } while (0) - static void arc4_set_key(struct arc4_ctx *ctx, unsigned int length, const uint8_t *key) { @@ -626,10 +624,10 @@ bool prf_sha1(const void *key, size_t key_len, /* PRF+ from RFC 5295 Section 3.1.2 (also RFC 4306 Section 2.13) */ bool prf_plus(enum l_checksum_type type, const void *key, size_t key_len, - const char *label, void *out, size_t out_len, + void *out, size_t out_len, size_t n_extra, ...) { - struct iovec iov[n_extra + 3]; + struct iovec iov[n_extra + 2]; uint8_t *t = out; size_t t_len = 0; uint8_t count = 1; @@ -639,24 +637,17 @@ bool prf_plus(enum l_checksum_type type, const void *key, size_t key_len, ssize_t ret; size_t i; - iov[1].iov_base = (void *) label; - iov[1].iov_len = strlen(label); - - /* Include the '\0' from the label in S if extra arguments provided */ - if (n_extra) - iov[1].iov_len += 1; - va_start(va, n_extra); for (i = 0; i < n_extra; i++) { - iov[i + 2].iov_base = va_arg(va, void *); - iov[i + 2].iov_len = va_arg(va, size_t); + iov[i + 1].iov_base = va_arg(va, void *); + iov[i + 1].iov_len = va_arg(va, size_t); } va_end(va); - iov[n_extra + 2].iov_base = &count; - iov[n_extra + 2].iov_len = 1; + iov[n_extra + 1].iov_base = &count; + iov[n_extra + 1].iov_len = 1; hmac = l_checksum_new_hmac(type, key, key_len); if (!hmac) @@ -666,7 +657,7 @@ bool prf_plus(enum l_checksum_type type, const void *key, size_t key_len, iov[0].iov_base = t; iov[0].iov_len = t_len; - if (!l_checksum_updatev(hmac, iov, n_extra + 3)) { + if (!l_checksum_updatev(hmac, iov, n_extra + 2)) { l_checksum_free(hmac); return false; } @@ -876,7 +867,8 @@ bool hkdf_extract(enum l_checksum_type type, const void *key, bool hkdf_expand(enum l_checksum_type type, const void *key, size_t key_len, const char *info, void *out, size_t out_len) { - return prf_plus(type, key, key_len, info, out, out_len, 0); + return prf_plus(type, key, key_len, out, out_len, 1, + info, strlen(info)); } /* diff --git a/src/crypto.h b/src/crypto.h @@ -122,7 +122,7 @@ bool prf_plus_sha1(const void *key, size_t key_len, const void *data, size_t data_len, void *output, size_t size); bool prf_plus(enum l_checksum_type type, const void *key, size_t key_len, - const char *label, void *out, size_t out_len, + void *out, size_t out_len, size_t n_extra, ...); bool hkdf_extract(enum l_checksum_type type, const void *key, size_t key_len, diff --git a/src/dbus.h b/src/dbus.h @@ -44,8 +44,10 @@ #define IWD_AP_DIAGNOSTIC_INTERFACE "net.connman.iwd.AccessPointDiagnostic" #define IWD_STATION_DEBUG_INTERFACE "net.connman.iwd.StationDebug" #define IWD_DPP_INTERFACE "net.connman.iwd.DeviceProvisioning" +#define IWD_DPP_PKEX_INTERFACE "net.connman.iwd.SharedCodeDeviceProvisioning" #define IWD_NETCONFIG_AGENT_INTERFACE \ "net.connman.iwd.NetworkConfigurationAgent" +#define IWD_SHARED_CODE_AGENT_INTERFACE "net.connman.iwd.SharedCodeAgent" #define IWD_BASE_PATH "/net/connman/iwd" #define IWD_AGENT_MANAGER_PATH IWD_BASE_PATH diff --git a/src/dpp-util.c b/src/dpp-util.c @@ -39,6 +39,33 @@ #include "ell/asn1-private.h" #include "src/ie.h" +/* WFA Easy Connect v3.0 C.1 Role-specific Elements for NIST p256 */ +static const uint8_t dpp_pkex_initiator_p256[64] = { + /* X */ + 0x56, 0x26, 0x12, 0xcf, 0x36, 0x48, 0xfe, 0x0b, + 0x07, 0x04, 0xbb, 0x12, 0x22, 0x50, 0xb2, 0x54, + 0xb1, 0x94, 0x64, 0x7e, 0x54, 0xce, 0x08, 0x07, + 0x2e, 0xec, 0xca, 0x74, 0x5b, 0x61, 0x2d, 0x25, + /* Y */ + 0x3e, 0x44, 0xc7, 0xc9, 0x8c, 0x1c, 0xa1, 0x0b, + 0x20, 0x09, 0x93, 0xb2, 0xfd, 0xe5, 0x69, 0xdc, + 0x75, 0xbc, 0xad, 0x33, 0xc1, 0xe7, 0xc6, 0x45, + 0x4d, 0x10, 0x1e, 0x6a, 0x3d, 0x84, 0x3c, 0xa4 +}; + +static const uint8_t dpp_pkex_responder_p256[64] = { + /* X */ + 0x1e, 0xa4, 0x8a, 0xb1, 0xa4, 0xe8, 0x42, 0x39, + 0xad, 0x73, 0x07, 0xf2, 0x34, 0xdf, 0x57, 0x4f, + 0xc0, 0x9d, 0x54, 0xbe, 0x36, 0x1b, 0x31, 0x0f, + 0x59, 0x91, 0x52, 0x33, 0xac, 0x19, 0x9d, 0x76, + /* Y */ + 0xd9, 0xfb, 0xf6, 0xb9, 0xf5, 0xfa, 0xdf, 0x19, + 0x58, 0xd8, 0x3e, 0xc9, 0x89, 0x7a, 0x35, 0xc1, + 0xbd, 0xe9, 0x0b, 0x77, 0x7a, 0xcb, 0x91, 0x2a, + 0xe8, 0x21, 0x3f, 0x47, 0x52, 0x02, 0x4d, 0x67 +}; + static void append_freqs(struct l_string *uri, const uint32_t *freqs, size_t len) { @@ -117,6 +144,40 @@ static uint32_t dpp_parse_akm(char *akms) return akm_out; } +static bool dpp_parse_extra_options(struct dpp_configuration *config, + struct json_iter *extra) +{ + struct json_iter host_val; + struct json_iter hidden_val; + bool hostname = false; + bool hidden = false; + + if (!json_iter_parse(extra, + JSON_OPTIONAL("send_hostname", JSON_PRIMITIVE, + &host_val), + JSON_OPTIONAL("hidden", JSON_PRIMITIVE, &hidden_val), + JSON_UNDEFINED)) + return false; + + /* + * The values are optional in order to support backwards compatibility + * if more are added, but if the key does exist require the type + * matches and fail otherwise. + */ + if (json_iter_is_valid(&host_val) && + !json_iter_get_boolean(&host_val, &hostname)) + return false; + + if (json_iter_is_valid(&hidden_val) && + !json_iter_get_boolean(&hidden_val, &hidden)) + return false; + + config->send_hostname = hostname; + config->hidden = hidden; + + return true; +} + /* * TODO: This handles the most basic configuration. i.e. a configuration object * with ssid/passphrase/akm. @@ -129,6 +190,7 @@ struct dpp_configuration *dpp_parse_configuration_object(const char *json, struct json_iter iter; struct json_iter discovery; struct json_iter cred; + struct json_iter extra; _auto_(l_free) char *tech = NULL; _auto_(l_free) char *ssid = NULL; _auto_(l_free) char *akm = NULL; @@ -145,6 +207,7 @@ struct dpp_configuration *dpp_parse_configuration_object(const char *json, JSON_MANDATORY("wi-fi_tech", JSON_STRING, &tech), JSON_MANDATORY("discovery", JSON_OBJECT, &discovery), JSON_MANDATORY("cred", JSON_OBJECT, &cred), + JSON_OPTIONAL("/net/connman/iwd", JSON_OBJECT, &extra), JSON_UNDEFINED)) goto free_contents; @@ -183,6 +246,11 @@ struct dpp_configuration *dpp_parse_configuration_object(const char *json, if (!config->akm_suites) goto free_config; + if (json_iter_is_valid(&extra)) { + if (!dpp_parse_extra_options(config, &extra)) + l_warn("Extra settings failed to parse!"); + } + json_contents_free(c); return config; @@ -231,10 +299,20 @@ char *dpp_configuration_to_json(struct dpp_configuration *config) config->psk); return l_strdup_printf("{\"wi-fi_tech\":\"infra\"," - "\"discovery\":{\"ssid\":\"%s\"}," - "\"cred\":{\"akm\":\"%s\",%s}}", + "\"discovery\":{" + "\"ssid\":\"%s\"" + "}," + "\"cred\":{" + "\"akm\":\"%s\",%s" + "}," + "\"/net/connman/iwd\":{" + "\"send_hostname\":%s," + "\"hidden\":%s}" + "}", ssid, dpp_akm_to_string(config->akm_suites), - pass_or_psk); + pass_or_psk, + config->send_hostname ? "true" : "false", + config->hidden ? "true" : "false"); } struct dpp_configuration *dpp_configuration_new( @@ -246,6 +324,8 @@ struct dpp_configuration *dpp_configuration_new( _auto_(l_free) char *passphrase = NULL; _auto_(l_free) char *psk = NULL; size_t ssid_len = strlen(ssid); + bool send_hostname; + bool hidden; if (!l_settings_has_group(settings, "Security")) return NULL; @@ -272,6 +352,16 @@ struct dpp_configuration *dpp_configuration_new( config->akm_suites = akm_suite; + if (!l_settings_get_bool(settings, "IPv4", "SendHostname", + &send_hostname)) + send_hostname = false; + + if (!l_settings_get_bool(settings, "Settings", "Hidden", &hidden)) + hidden = false; + + config->send_hostname = send_hostname; + config->hidden = hidden; + return config; } @@ -551,12 +641,14 @@ static bool dpp_hkdf(enum l_checksum_type sha, const void *salt, bool dpp_derive_r_auth(const void *i_nonce, const void *r_nonce, size_t nonce_len, struct l_ecc_point *i_proto, struct l_ecc_point *r_proto, + struct l_ecc_point *i_boot, struct l_ecc_point *r_boot, void *r_auth) { uint64_t pix[L_ECC_MAX_DIGITS]; uint64_t prx[L_ECC_MAX_DIGITS]; uint64_t brx[L_ECC_MAX_DIGITS]; + uint64_t bix[L_ECC_MAX_DIGITS]; size_t keys_len; uint8_t zero = 0; enum l_checksum_type type; @@ -565,24 +657,30 @@ bool dpp_derive_r_auth(const void *i_nonce, const void *r_nonce, l_ecc_point_get_x(r_proto, prx, sizeof(prx)); l_ecc_point_get_x(r_boot, brx, sizeof(brx)); + if (i_boot) + l_ecc_point_get_x(i_boot, bix, sizeof(bix)); + type = dpp_sha_from_key_len(keys_len); /* * R-auth = H(I-nonce | R-nonce | PI.x | PR.x | [ BI.x | ] BR.x | 0) */ - return dpp_hash(type, r_auth, 6, i_nonce, nonce_len, r_nonce, nonce_len, - pix, keys_len, prx, keys_len, brx, keys_len, + return dpp_hash(type, r_auth, 7, i_nonce, nonce_len, r_nonce, nonce_len, + pix, keys_len, prx, keys_len, + bix, i_boot ? keys_len : 0, brx, keys_len, &zero, (size_t) 1); } bool dpp_derive_i_auth(const void *r_nonce, const void *i_nonce, size_t nonce_len, struct l_ecc_point *r_proto, struct l_ecc_point *i_proto, - struct l_ecc_point *r_boot, void *i_auth) + struct l_ecc_point *r_boot, + struct l_ecc_point *i_boot, void *i_auth) { uint64_t prx[L_ECC_MAX_DIGITS]; uint64_t pix[L_ECC_MAX_DIGITS]; uint64_t brx[L_ECC_MAX_DIGITS]; + uint64_t bix[L_ECC_MAX_DIGITS]; size_t keys_len; uint8_t one = 1; enum l_checksum_type type; @@ -591,13 +689,17 @@ bool dpp_derive_i_auth(const void *r_nonce, const void *i_nonce, l_ecc_point_get_x(i_proto, pix, sizeof(pix)); l_ecc_point_get_x(r_boot, brx, sizeof(brx)); + if (i_boot) + l_ecc_point_get_x(i_boot, bix, sizeof(bix)); + type = dpp_sha_from_key_len(keys_len); /* * I-auth = H(R-nonce | I-nonce | PR.x | PI.x | BR.x | [ BI.x | ] 1) */ - return dpp_hash(type, i_auth, 6, r_nonce, nonce_len, i_nonce, nonce_len, + return dpp_hash(type, i_auth, 7, r_nonce, nonce_len, i_nonce, nonce_len, prx, keys_len, pix, keys_len, brx, keys_len, + bix, i_boot ? keys_len : 0, &one, (size_t) 1); } @@ -669,12 +771,13 @@ free_n: bool dpp_derive_ke(const uint8_t *i_nonce, const uint8_t *r_nonce, struct l_ecc_scalar *m, struct l_ecc_scalar *n, - void *ke) + struct l_ecc_point *l, void *ke) { uint8_t nonces[32 + 32]; size_t nonce_len; uint64_t mx_bytes[L_ECC_MAX_DIGITS]; uint64_t nx_bytes[L_ECC_MAX_DIGITS]; + uint64_t lx_bytes[L_ECC_MAX_DIGITS]; uint64_t bk[L_ECC_MAX_DIGITS]; ssize_t key_len; enum l_checksum_type sha; @@ -685,12 +788,15 @@ bool dpp_derive_ke(const uint8_t *i_nonce, const uint8_t *r_nonce, nonce_len = dpp_nonce_len_from_key_len(key_len); sha = dpp_sha_from_key_len(key_len); + if (l) + l_ecc_point_get_x(l, lx_bytes, key_len * 2); + memcpy(nonces, i_nonce, nonce_len); memcpy(nonces + nonce_len, r_nonce, nonce_len); /* bk = HKDF-Extract(I-nonce | R-nonce, M.x | N.x [ | L.x]) */ - if (!hkdf_extract(sha, nonces, nonce_len * 2, 2, bk, mx_bytes, - key_len, nx_bytes, key_len)) + if (!hkdf_extract(sha, nonces, nonce_len * 2, 3, bk, mx_bytes, + key_len, nx_bytes, key_len, lx_bytes, l ? key_len : 0)) return false; /* ke = HKDF-Expand(bk, "DPP Key", length) */ @@ -751,11 +857,11 @@ uint8_t *dpp_point_to_asn1(const struct l_ecc_point *p, size_t *len_out) /* * Set the type to whatever avoids doing p - y when reading in the - * key. Working backwards from l_ecc_point_from_data if Y is odd and - * the type is BIT0 there is no subtraction. Similarly if Y is even + * key. Working backwards from l_ecc_point_from_data if Y is even and + * the type is BIT0 there is no subtraction. Similarly if Y is odd * and the type is BIT1. */ - if (l_ecc_point_y_isodd(p)) + if (!l_ecc_point_y_isodd(p)) point_type = L_ECC_POINT_TYPE_COMPRESSED_BIT0; else point_type = L_ECC_POINT_TYPE_COMPRESSED_BIT1; @@ -1118,3 +1224,251 @@ void dpp_free_uri_info(struct dpp_uri_info *info) l_free(info); } + +/* + * 6.3.4 DPP Authentication Confirm + * + * L = bI * (BR + PR) + */ +struct l_ecc_point *dpp_derive_li(const struct l_ecc_point *boot_public, + const struct l_ecc_point *proto_public, + const struct l_ecc_scalar *boot_private) +{ + const struct l_ecc_curve *curve = l_ecc_point_get_curve(boot_public); + struct l_ecc_point *ret = l_ecc_point_new(curve); + + l_ecc_point_add(ret, boot_public, proto_public); + l_ecc_point_multiply(ret, boot_private, ret); + + return ret; +} + +/* + * 6.3.3 DPP Authentication Response + * + * L = ((bR + pR) modulo q) * BI + */ +struct l_ecc_point *dpp_derive_lr(const struct l_ecc_scalar *boot_private, + const struct l_ecc_scalar *proto_private, + const struct l_ecc_point *peer_public) +{ + const struct l_ecc_curve *curve = l_ecc_point_get_curve(peer_public); + _auto_(l_ecc_scalar_free) struct l_ecc_scalar *order = + l_ecc_curve_get_order(curve); + _auto_(l_ecc_scalar_free) struct l_ecc_scalar *sum = + l_ecc_scalar_new(curve, NULL, 0); + _auto_(l_ecc_point_free) struct l_ecc_point *ret = + l_ecc_point_new(curve); + + if (!l_ecc_scalar_add(sum, boot_private, proto_private, order)) + return NULL; + + if (!l_ecc_point_multiply(ret, sum, peer_public)) + return NULL; + + return l_steal_ptr(ret); +} + + +static struct l_ecc_point *dpp_derive_q(const struct l_ecc_curve *curve, + const uint8_t *p_data, + const char *key, + const char *identifier, + const uint8_t *mac) +{ + _auto_(l_ecc_scalar_free) struct l_ecc_scalar *scalar = NULL; + _auto_(l_ecc_point_free) struct l_ecc_point *ret = NULL; + uint8_t hash[L_ECC_SCALAR_MAX_BYTES]; + unsigned int bytes = l_ecc_curve_get_scalar_bytes(curve); + enum l_checksum_type type = dpp_sha_from_key_len(bytes); + _auto_(l_ecc_point_free) struct l_ecc_point *p = NULL; + struct l_checksum *sha = l_checksum_new(type); + + /* + * "If the Initiator indicates PKEX with a Protocol Version of 1, + * MAC-Initiator shall be the MAC address of the Initiator and the + * Protocol Version shall not be present. Otherwise, MAC-Initiator is + * not present" + * + * (This goes for MAC-Responder as well) + */ + if (mac) + l_checksum_update(sha, mac, 6); + + if (identifier) + l_checksum_update(sha, identifier, strlen(identifier)); + + l_checksum_update(sha, key, strlen(key)); + l_checksum_get_digest(sha, hash, bytes); + l_checksum_free(sha); + + /* Unlikely but can happen */ + scalar = l_ecc_scalar_new(curve, hash, bytes); + if (!scalar) + return NULL; + + p = l_ecc_point_from_data(curve, L_ECC_POINT_TYPE_FULL, + p_data, bytes * 2); + if (!p) + return NULL; + + ret = l_ecc_point_new(curve); + + if (!l_ecc_point_multiply(ret, scalar, p)) + return NULL; + + return l_steal_ptr(ret); +} + +/* + * 5.6.2 PKEX Exchange Phase + * + * Qi = H([MAC-Initiator |] [identifier | ] code) * Pi + */ +struct l_ecc_point *dpp_derive_qi(const struct l_ecc_curve *curve, + const char *key, + const char *identifier, + const uint8_t *mac_initiator) +{ + return dpp_derive_q(curve, dpp_pkex_initiator_p256, key, identifier, + mac_initiator); +} + +/* + * 5.6.2 PKEX Exchange Phase + * + * Qr = H([MAC-Responder |] [identifier | ] code) * Pr + */ +struct l_ecc_point *dpp_derive_qr(const struct l_ecc_curve *curve, + const char *key, + const char *identifier, + const uint8_t *mac_responder) +{ + return dpp_derive_q(curve, dpp_pkex_responder_p256, key, identifier, + mac_responder); +} + +/* + * 5.6.2 PKEX Exchange Phase + * + * z = HKDF(<>, info | M.x | N.x | code, K.x) + */ +bool dpp_derive_z(const uint8_t *mac_i, const uint8_t *mac_r, + const struct l_ecc_point *n, + const struct l_ecc_point *m, + const struct l_ecc_point *k, + const char *key, + const char *identifier, + void *z_out, size_t *z_len) +{ + const struct l_ecc_curve *curve = l_ecc_point_get_curve(n); + size_t bytes = l_ecc_curve_get_scalar_bytes(curve); + enum l_checksum_type sha = dpp_sha_from_key_len(bytes); + uint8_t k_x[L_ECC_SCALAR_MAX_BYTES]; + uint8_t m_x[L_ECC_SCALAR_MAX_BYTES]; + uint8_t n_x[L_ECC_SCALAR_MAX_BYTES]; + uint8_t prk[L_ECC_SCALAR_MAX_BYTES]; + + l_ecc_point_get_x(k, k_x, sizeof(k_x)); + l_ecc_point_get_x(m, m_x, sizeof(m_x)); + l_ecc_point_get_x(n, n_x, sizeof(n_x)); + + hkdf_extract(sha, NULL, 0, 1, prk, k_x, bytes); + + /* HKDF-Extract (since it doesn't take non-string arguments)*/ + prf_plus(sha, prk, bytes, z_out, bytes, 5, mac_i, 6, mac_r, 6, m_x, + bytes, n_x, bytes, key, strlen(key)); + + *z_len = bytes; + + return true; +} + +/* + * 5.6.3 PKEX Commit-Reveal Phase + * + * Initiator derivation: + * u = HMAC(J.x, [MAC-Initiator |] A.x | Y'.x | X.x ) + * + * Responder derivation: + * u' = HMAC(J'.x, [MAC-Initiator |] A'.x | Y.x | X'.x) + */ +bool dpp_derive_u(const struct l_ecc_point *j, + const uint8_t *mac_i, + const struct l_ecc_point *a, + const struct l_ecc_point *y, + const struct l_ecc_point *x, + void *u_out, size_t *u_len) +{ + const struct l_ecc_curve *curve = l_ecc_point_get_curve(y); + uint8_t j_x[L_ECC_SCALAR_MAX_BYTES]; + uint8_t a_x[L_ECC_SCALAR_MAX_BYTES]; + uint8_t y_x[L_ECC_SCALAR_MAX_BYTES]; + uint8_t x_x[L_ECC_SCALAR_MAX_BYTES]; + size_t bytes = l_ecc_curve_get_scalar_bytes(curve); + enum l_checksum_type sha = dpp_sha_from_key_len(bytes); + struct l_checksum *hmac; + + l_ecc_point_get_x(j, j_x, bytes); + l_ecc_point_get_x(a, a_x, bytes); + l_ecc_point_get_x(y, y_x, bytes); + l_ecc_point_get_x(x, x_x, bytes); + + /* u = HMAC(J.x, MAC-Initiator | A.x | Y'.x | X.x)*/ + hmac = l_checksum_new_hmac(sha, j_x, bytes); + l_checksum_update(hmac, mac_i, 6); + l_checksum_update(hmac, a_x, bytes); + l_checksum_update(hmac, y_x, bytes); + l_checksum_update(hmac, x_x, bytes); + l_checksum_get_digest(hmac, u_out, bytes); + l_checksum_free(hmac); + + *u_len = bytes; + + return true; +} + +/* + * 5.6.3 PKEX Commit-Reveal Phase + * + * Initiator derivation: + * v = HMAC(L.x, [MAC-Responder |] B.x | X'.x |Y.x ) + * + * Responder derivation: + * v' = HMAC(L.x, [MAC-Responder |] B'.x | X.x | Y'.x ) + */ +bool dpp_derive_v(const struct l_ecc_point *l, const uint8_t *mac, + const struct l_ecc_point *b, + const struct l_ecc_point *x, + const struct l_ecc_point *y, + void *v_out, size_t *v_len) +{ + const struct l_ecc_curve *curve = l_ecc_point_get_curve(l); + uint8_t l_x[L_ECC_SCALAR_MAX_BYTES]; + uint8_t b_x[L_ECC_SCALAR_MAX_BYTES]; + uint8_t x_x[L_ECC_SCALAR_MAX_BYTES]; + uint8_t y_x[L_ECC_SCALAR_MAX_BYTES]; + size_t bytes = l_ecc_curve_get_scalar_bytes(curve); + enum l_checksum_type sha = dpp_sha_from_key_len(bytes); + struct l_checksum *hmac; + + l_ecc_point_get_x(l, l_x, sizeof(l_x)); + l_ecc_point_get_x(b, b_x, sizeof(b_x)); + l_ecc_point_get_x(x, x_x, sizeof(x_x)); + l_ecc_point_get_x(y, y_x, sizeof(y_x)); + + hmac = l_checksum_new_hmac(sha, l_x, bytes); + + if (mac) + l_checksum_update(hmac, mac, 6); + + l_checksum_update(hmac, b_x, bytes); + l_checksum_update(hmac, x_x, bytes); + l_checksum_update(hmac, y_x, bytes); + l_checksum_get_digest(hmac, v_out, bytes); + l_checksum_free(hmac); + + *v_len = bytes; + + return true; +} diff --git a/src/dpp-util.h b/src/dpp-util.h @@ -40,10 +40,10 @@ enum dpp_frame_type { /* 3 - 4 reserved */ DPP_FRAME_PEER_DISCOVERY_REQUEST = 5, DPP_FRAME_PEER_DISCOVERY_RESPONSE = 6, - DPP_FRAME_PKEX_VERSION1_XCHG_REQUST = 7, + DPP_FRAME_PKEX_VERSION1_XCHG_REQUEST = 7, DPP_FRAME_PKEX_XCHG_RESPONSE = 8, DPP_FRAME_PKEX_COMMIT_REVEAL_REQUEST = 9, - DPP_FRAME_PKEX_COMMIT_REVEAP_RESPONSE = 10, + DPP_FRAME_PKEX_COMMIT_REVEAL_RESPONSE = 10, DPP_FRAME_CONFIGURATION_RESULT = 11, DPP_FRAME_CONNECTION_STATUS_RESULT = 12, DPP_FRAME_PRESENCE_ANNOUNCEMENT = 13, @@ -112,11 +112,15 @@ enum dpp_attribute_type { }; struct dpp_configuration { - uint8_t ssid[32]; + char ssid[33]; size_t ssid_len; uint32_t akm_suites; char *passphrase; char *psk; /* hex string */ + + /* "3rd party extensions" only applicable for two IWD peers */ + bool send_hostname : 1; + bool hidden : 1; }; struct dpp_configuration *dpp_parse_configuration_object(const char *json, @@ -160,12 +164,14 @@ bool dpp_hash(enum l_checksum_type type, uint8_t *out, unsigned int num, ...); bool dpp_derive_r_auth(const void *i_nonce, const void *r_nonce, size_t nonce_len, struct l_ecc_point *i_proto, struct l_ecc_point *r_proto, + struct l_ecc_point *i_boot, struct l_ecc_point *r_boot, void *r_auth); bool dpp_derive_i_auth(const void *r_nonce, const void *i_nonce, size_t nonce_len, struct l_ecc_point *r_proto, struct l_ecc_point *i_proto, - struct l_ecc_point *r_boot, void *i_auth); + struct l_ecc_point *r_boot, + struct l_ecc_point *i_boot, void *i_auth); struct l_ecc_scalar *dpp_derive_k1(const struct l_ecc_point *i_proto_public, const struct l_ecc_scalar *boot_private, void *k1); @@ -174,10 +180,45 @@ struct l_ecc_scalar *dpp_derive_k2(const struct l_ecc_point *i_proto_public, void *k2); bool dpp_derive_ke(const uint8_t *i_nonce, const uint8_t *r_nonce, struct l_ecc_scalar *m, struct l_ecc_scalar *n, - void *ke); + struct l_ecc_point *l, void *ke); uint8_t *dpp_point_to_asn1(const struct l_ecc_point *p, size_t *len_out); struct l_ecc_point *dpp_point_from_asn1(const uint8_t *asn1, size_t len); struct dpp_uri_info *dpp_parse_uri(const char *uri); void dpp_free_uri_info(struct dpp_uri_info *info); + +struct l_ecc_point *dpp_derive_qi(const struct l_ecc_curve *curve, + const char *key, + const char *identifier, + const uint8_t *mac_initiator); +struct l_ecc_point *dpp_derive_qr(const struct l_ecc_curve *curve, + const char *key, + const char *identifier, + const uint8_t *mac_responder); +struct l_ecc_point *dpp_derive_li( + const struct l_ecc_point *boot_public, + const struct l_ecc_point *proto_public, + const struct l_ecc_scalar *boot_private); +struct l_ecc_point *dpp_derive_lr( + const struct l_ecc_scalar *boot_private, + const struct l_ecc_scalar *proto_private, + const struct l_ecc_point *peer_public); +bool dpp_derive_z(const uint8_t *mac_i, const uint8_t *mac_r, + const struct l_ecc_point *n, + const struct l_ecc_point *m, + const struct l_ecc_point *k, + const char *key, + const char *identifier, + void *z_out, size_t *z_len); +bool dpp_derive_u(const struct l_ecc_point *j, + const uint8_t *mac_i, + const struct l_ecc_point *a, + const struct l_ecc_point *y, + const struct l_ecc_point *x, + void *u_out, size_t *u_len); +bool dpp_derive_v(const struct l_ecc_point *l, const uint8_t *mac, + const struct l_ecc_point *b, + const struct l_ecc_point *x, + const struct l_ecc_point *y, + void *v_out, size_t *v_len); diff --git a/src/dpp.c b/src/dpp.c @@ -56,6 +56,8 @@ #define DPP_FRAME_MAX_RETRIES 5 #define DPP_FRAME_RETRY_TIMEOUT 1 +#define DPP_AUTH_PROTO_TIMEOUT 10 +#define DPP_PKEX_PROTO_TIMEOUT 120 static uint32_t netdev_watch; static struct l_genl_family *nl80211; @@ -69,6 +71,8 @@ static uint8_t dpp_prefix[] = { 0x04, 0x09, 0x50, 0x6f, 0x9a, 0x1a, 0x01 }; enum dpp_state { DPP_STATE_NOTHING, DPP_STATE_PRESENCE, + DPP_STATE_PKEX_EXCHANGE, + DPP_STATE_PKEX_COMMIT_REVEAL, DPP_STATE_AUTHENTICATING, DPP_STATE_CONFIGURING, }; @@ -78,10 +82,25 @@ enum dpp_capability { DPP_CAPABILITY_CONFIGURATOR = 0x02, }; +enum dpp_interface { + DPP_INTERFACE_UNBOUND, + DPP_INTERFACE_DPP, + DPP_INTERFACE_PKEX, +}; + +struct pkex_agent { + char *owner; + char *path; + unsigned int disconnect_watch; + uint32_t pending_id; +}; + struct dpp_sm { struct netdev *netdev; char *uri; uint8_t role; + int refcount; + uint32_t station_watch; uint64_t wdev_id; @@ -99,6 +118,9 @@ struct dpp_sm { struct l_ecc_point *peer_boot_public; enum dpp_state state; + enum dpp_interface interface; + + struct pkex_agent *agent; /* * List of frequencies to jump between. The presence of this list is @@ -111,10 +133,11 @@ struct dpp_sm { uint32_t current_freq; uint32_t new_freq; struct scan_freq_set *presence_list; + uint32_t max_roc; uint32_t offchannel_id; - uint8_t auth_addr[6]; + uint8_t peer_addr[6]; uint8_t r_nonce[32]; uint8_t i_nonce[32]; uint8_t e_nonce[32]; @@ -145,18 +168,83 @@ struct dpp_sm { struct l_dbus_message *pending; + /* PKEX-specific values */ + char *pkex_id; + char *pkex_key; + uint8_t pkex_version; + struct l_ecc_point *peer_encr_key; + struct l_ecc_point *pkex_m; + /* Ephemeral key Y' or X' for enrollee or configurator */ + struct l_ecc_point *y_or_x; + /* Ephemeral key pair y/Y or x/X */ + struct l_ecc_point *pkex_public; + struct l_ecc_scalar *pkex_private; + uint8_t z[L_ECC_SCALAR_MAX_BYTES]; + size_t z_len; + uint8_t u[L_ECC_SCALAR_MAX_BYTES]; + size_t u_len; + uint32_t pkex_scan_id; + bool mcast_support : 1; bool roc_started : 1; bool channel_switch : 1; + bool mutual_auth : 1; }; +static const char *dpp_role_to_string(enum dpp_capability role) +{ + switch (role) { + case DPP_CAPABILITY_ENROLLEE: + return "enrollee"; + case DPP_CAPABILITY_CONFIGURATOR: + return "configurator"; + default: + return NULL; + } +} + +static bool dpp_pkex_get_started(struct l_dbus *dbus, + struct l_dbus_message *message, + struct l_dbus_message_builder *builder, + void *user_data) +{ + struct dpp_sm *dpp = user_data; + bool started = (dpp->state != DPP_STATE_NOTHING && + dpp->interface == DPP_INTERFACE_PKEX); + + l_dbus_message_builder_append_basic(builder, 'b', &started); + + return true; +} + +static bool dpp_pkex_get_role(struct l_dbus *dbus, + struct l_dbus_message *message, + struct l_dbus_message_builder *builder, + void *user_data) +{ + struct dpp_sm *dpp = user_data; + const char *role; + + if (dpp->state == DPP_STATE_NOTHING || + dpp->interface != DPP_INTERFACE_PKEX) + return false; + + role = dpp_role_to_string(dpp->role); + if (L_WARN_ON(!role)) + return false; + + l_dbus_message_builder_append_basic(builder, 's', role); + return true; +} + static bool dpp_get_started(struct l_dbus *dbus, struct l_dbus_message *message, struct l_dbus_message_builder *builder, void *user_data) { struct dpp_sm *dpp = user_data; - bool started = (dpp->state != DPP_STATE_NOTHING); + bool started = (dpp->state != DPP_STATE_NOTHING && + dpp->interface == DPP_INTERFACE_DPP); l_dbus_message_builder_append_basic(builder, 'b', &started); @@ -171,19 +259,13 @@ static bool dpp_get_role(struct l_dbus *dbus, struct dpp_sm *dpp = user_data; const char *role; - if (dpp->state == DPP_STATE_NOTHING) + if (dpp->state == DPP_STATE_NOTHING || + dpp->interface != DPP_INTERFACE_DPP) return false; - switch (dpp->role) { - case DPP_CAPABILITY_ENROLLEE: - role = "enrollee"; - break; - case DPP_CAPABILITY_CONFIGURATOR: - role = "configurator"; - break; - default: + role = dpp_role_to_string(dpp->role); + if (L_WARN_ON(!role)) return false; - } l_dbus_message_builder_append_basic(builder, 's', role); return true; @@ -196,7 +278,8 @@ static bool dpp_get_uri(struct l_dbus *dbus, { struct dpp_sm *dpp = user_data; - if (dpp->state == DPP_STATE_NOTHING) + if (dpp->state == DPP_STATE_NOTHING || + dpp->interface != DPP_INTERFACE_DPP) return false; l_dbus_message_builder_append_basic(builder, 's', dpp->uri); @@ -207,12 +290,26 @@ static void dpp_property_changed_notify(struct dpp_sm *dpp) { const char *path = netdev_get_path(dpp->netdev); - l_dbus_property_changed(dbus_get_bus(), path, IWD_DPP_INTERFACE, - "Started"); - l_dbus_property_changed(dbus_get_bus(), path, IWD_DPP_INTERFACE, - "Role"); - l_dbus_property_changed(dbus_get_bus(), path, IWD_DPP_INTERFACE, - "URI"); + switch (dpp->interface) { + case DPP_INTERFACE_DPP: + l_dbus_property_changed(dbus_get_bus(), path, IWD_DPP_INTERFACE, + "Started"); + l_dbus_property_changed(dbus_get_bus(), path, IWD_DPP_INTERFACE, + "Role"); + l_dbus_property_changed(dbus_get_bus(), path, IWD_DPP_INTERFACE, + "URI"); + break; + case DPP_INTERFACE_PKEX: + l_dbus_property_changed(dbus_get_bus(), path, + IWD_DPP_PKEX_INTERFACE, + "Started"); + l_dbus_property_changed(dbus_get_bus(), path, + IWD_DPP_PKEX_INTERFACE, + "Role"); + break; + default: + break; + } } static void *dpp_serialize_iovec(struct iovec *iov, size_t iov_len, @@ -239,6 +336,83 @@ static void *dpp_serialize_iovec(struct iovec *iov, size_t iov_len, return ret; } +static void dpp_free_pending_pkex_data(struct dpp_sm *dpp) +{ + if (dpp->pkex_id) { + l_free(dpp->pkex_id); + dpp->pkex_id = NULL; + } + + if (dpp->pkex_key) { + l_free(dpp->pkex_key); + dpp->pkex_key = NULL; + } + + memset(dpp->peer_addr, 0, sizeof(dpp->peer_addr)); + + if (dpp->peer_encr_key) { + l_ecc_point_free(dpp->peer_encr_key); + dpp->peer_encr_key = NULL; + } +} + +static void pkex_agent_free(void *data) +{ + struct pkex_agent *agent = data; + + l_free(agent->owner); + l_free(agent->path); + l_dbus_remove_watch(dbus_get_bus(), agent->disconnect_watch); + l_free(agent); +} + +static void dpp_agent_cancel(struct dpp_sm *dpp) +{ + struct l_dbus_message *msg; + + const char *reason = "shutdown"; + + msg = l_dbus_message_new_method_call(dbus_get_bus(), + dpp->agent->owner, + dpp->agent->path, + IWD_SHARED_CODE_AGENT_INTERFACE, + "Cancel"); + l_dbus_message_set_arguments(msg, "s", reason); + l_dbus_message_set_no_reply(msg, true); + l_dbus_send(dbus_get_bus(), msg); +} + +static void dpp_agent_release(struct dpp_sm *dpp) +{ + struct l_dbus_message *msg; + + msg = l_dbus_message_new_method_call(dbus_get_bus(), + dpp->agent->owner, + dpp->agent->path, + IWD_SHARED_CODE_AGENT_INTERFACE, + "Release"); + l_dbus_message_set_no_reply(msg, true); + l_dbus_send(dbus_get_bus(), msg); +} + +static void dpp_destroy_agent(struct dpp_sm *dpp) +{ + if (!dpp->agent) + return; + + if (dpp->agent->pending_id) { + dpp_agent_cancel(dpp); + l_dbus_cancel(dbus_get_bus(), dpp->agent->pending_id); + } + + dpp_agent_release(dpp); + + l_debug("Released SharedCodeAgent on path %s", dpp->agent->path); + + pkex_agent_free(dpp->agent); + dpp->agent = NULL; +} + static void dpp_free_auth_data(struct dpp_sm *dpp) { if (dpp->own_proto_public) { @@ -265,6 +439,27 @@ static void dpp_free_auth_data(struct dpp_sm *dpp) l_ecc_scalar_free(dpp->m); dpp->m = NULL; } + + if (dpp->pkex_m) { + l_ecc_point_free(dpp->pkex_m); + dpp->pkex_m = NULL; + } + + if (dpp->y_or_x) { + l_ecc_point_free(dpp->y_or_x); + dpp->y_or_x = NULL; + } + + if (dpp->pkex_public) { + l_ecc_point_free(dpp->pkex_public); + dpp->pkex_public = NULL; + } + + if (dpp->pkex_private) { + l_ecc_scalar_free(dpp->pkex_private); + dpp->pkex_private = NULL; + } + } static void dpp_reset(struct dpp_sm *dpp) @@ -314,10 +509,16 @@ static void dpp_reset(struct dpp_sm *dpp) dpp->retry_timeout = NULL; } + if (dpp->pkex_scan_id) { + scan_cancel(dpp->wdev_id, dpp->pkex_scan_id); + dpp->pkex_scan_id = 0; + } + dpp->state = DPP_STATE_NOTHING; dpp->new_freq = 0; dpp->frame_retry = 0; dpp->frame_cookie = 0; + dpp->pkex_version = 0; explicit_bzero(dpp->r_nonce, dpp->nonce_len); explicit_bzero(dpp->i_nonce, dpp->nonce_len); @@ -326,14 +527,24 @@ static void dpp_reset(struct dpp_sm *dpp) explicit_bzero(dpp->k1, dpp->key_len); explicit_bzero(dpp->k2, dpp->key_len); explicit_bzero(dpp->auth_tag, dpp->key_len); + explicit_bzero(dpp->z, dpp->key_len); + explicit_bzero(dpp->u, dpp->u_len); + + dpp_destroy_agent(dpp); + + dpp_free_pending_pkex_data(dpp); dpp_free_auth_data(dpp); dpp_property_changed_notify(dpp); + + dpp->interface = DPP_INTERFACE_UNBOUND; } static void dpp_free(struct dpp_sm *dpp) { + struct station *station = station_find(netdev_get_ifindex(dpp->netdev)); + dpp_reset(dpp); if (dpp->own_asn1) { @@ -351,6 +562,13 @@ static void dpp_free(struct dpp_sm *dpp) dpp->boot_private = NULL; } + /* + * Since this is called when the netdev goes down, station may already + * be gone in which case the state watch will automatically go away. + */ + if (station) + station_remove_state_watch(station, dpp->station_watch); + l_free(dpp); } @@ -479,12 +697,12 @@ static void dpp_protocol_timeout(struct l_timeout *timeout, void *user_data) dpp_reset(dpp); } -static void dpp_reset_protocol_timer(struct dpp_sm *dpp) +static void dpp_reset_protocol_timer(struct dpp_sm *dpp, uint32_t time) { if (dpp->timeout) - l_timeout_modify(dpp->timeout, 10); + l_timeout_modify(dpp->timeout, time); else - dpp->timeout = l_timeout_create(10, dpp_protocol_timeout, + dpp->timeout = l_timeout_create(time, dpp_protocol_timeout, dpp, NULL); } @@ -591,16 +809,12 @@ static void send_config_result(struct dpp_sm *dpp, const uint8_t *to) static void dpp_write_config(struct dpp_configuration *config, struct network *network) { - char ssid[33]; _auto_(l_settings_free) struct l_settings *settings = l_settings_new(); _auto_(l_free) char *path; _auto_(l_free) uint8_t *psk = NULL; size_t psk_len; - memcpy(ssid, config->ssid, config->ssid_len); - ssid[config->ssid_len] = '\0'; - - path = storage_get_network_file_path(SECURITY_PSK, ssid); + path = storage_get_network_file_path(SECURITY_PSK, config->ssid); if (l_settings_load_from_file(settings, path)) { /* Remove any existing Security keys */ @@ -623,9 +837,15 @@ static void dpp_write_config(struct dpp_configuration *config, network_set_psk(network, psk); } - l_debug("Storing credential for '%s(%s)'", ssid, + if (config->send_hostname) + l_settings_set_bool(settings, "IPv4", "SendHostname", true); + + if (config->hidden) + l_settings_set_bool(settings, "Settings", "Hidden", true); + + l_debug("Storing credential for '%s(%s)'", config->ssid, security_to_str(SECURITY_PSK)); - storage_network_sync(SECURITY_PSK, ssid, settings); + storage_network_sync(SECURITY_PSK, config->ssid, settings); } static void dpp_scan_triggered(int err, void *user_data) @@ -641,13 +861,41 @@ static bool dpp_scan_results(int err, struct l_queue *bss_list, { struct dpp_sm *dpp = userdata; struct station *station = station_find(netdev_get_ifindex(dpp->netdev)); + struct scan_bss *bss; + struct network *network; if (err < 0) - return false; + goto reset; + + if (!bss_list || l_queue_length(bss_list) == 0) + goto reset; + + /* + * The station watch _should_ detect this and reset, which cancels the + * scan. But just in case... + */ + if (L_WARN_ON(station_get_connected_network(station))) + goto reset; + + station_set_scan_results(station, bss_list, freqs, false); + + network = station_network_find(station, dpp->config->ssid, + SECURITY_PSK); + + dpp_reset(dpp); + + if (!network) { + l_debug("Network was not found after scanning"); + return true; + } - station_set_scan_results(station, bss_list, freqs, true); + bss = network_bss_select(network, true); + network_autoconnect(network, bss); return true; + +reset: + return false; } static void dpp_scan_destroy(void *userdata) @@ -685,7 +933,6 @@ static void dpp_handle_config_response_frame(const struct mmpdu_header *frame, struct station *station = station_find(netdev_get_ifindex(dpp->netdev)); struct network *network = NULL; struct scan_bss *bss = NULL; - char ssid[33]; if (dpp->state != DPP_STATE_CONFIGURING) return; @@ -694,7 +941,7 @@ static void dpp_handle_config_response_frame(const struct mmpdu_header *frame, * Can a configuration request come from someone other than who you * authenticated to? */ - if (memcmp(dpp->auth_addr, frame->address_2, 6)) + if (memcmp(dpp->peer_addr, frame->address_2, 6)) return; if (body_len < 19) @@ -814,32 +1061,40 @@ static void dpp_handle_config_response_frame(const struct mmpdu_header *frame, * credentials out and be done */ if (station) { - memcpy(ssid, config->ssid, config->ssid_len); - ssid[config->ssid_len] = '\0'; - - network = station_network_find(station, ssid, SECURITY_PSK); + network = station_network_find(station, config->ssid, + SECURITY_PSK); if (network) bss = network_bss_select(network, true); } dpp_write_config(config, network); - dpp_configuration_free(config); - send_config_result(dpp, dpp->auth_addr); + send_config_result(dpp, dpp->peer_addr); offchannel_cancel(dpp->wdev_id, dpp->offchannel_id); if (network && bss) - __station_connect_network(station, network, bss); + __station_connect_network(station, network, bss, + STATION_STATE_CONNECTING); else if (station) { - dpp->connect_scan_id = scan_active(dpp->wdev_id, NULL, 0, + struct scan_parameters params = {0}; + + params.ssid = (void *) config->ssid; + params.ssid_len = config->ssid_len; + + l_debug("Scanning for %s", config->ssid); + + dpp->connect_scan_id = scan_active_full(dpp->wdev_id, &params, dpp_scan_triggered, dpp_scan_results, dpp, dpp_scan_destroy); - if (dpp->connect_scan_id) + if (dpp->connect_scan_id) { + dpp->config = config; return; + } } + dpp_configuration_free(config); dpp_reset(dpp); } @@ -855,7 +1110,7 @@ static void dpp_send_config_response(struct dpp_sm *dpp, uint8_t status) memset(hdr, 0, sizeof(hdr)); l_put_le16(0x00d0, hdr); - memcpy(hdr + 4, dpp->auth_addr, 6); + memcpy(hdr + 4, dpp->peer_addr, 6); memcpy(hdr + 10, netdev_get_address(dpp->netdev), 6); memcpy(hdr + 16, broadcast, 6); @@ -917,6 +1172,21 @@ static void dpp_send_config_response(struct dpp_sm *dpp, uint8_t status) dpp_send_frame(dpp, iov, 2, dpp->current_freq); } +static bool dpp_check_config_header(const uint8_t *ptr) +{ + /* + * Table 58. General Format of DPP Configuration Request frame + * + * Unfortunately wpa_supplicant hard codes 0x7f as the Query Response + * Info so we need to handle both cases. + */ + return ptr[0] == IE_TYPE_ADVERTISEMENT_PROTOCOL && + ptr[1] == 0x08 && + (ptr[2] == 0x7f || ptr[2] == 0x00) && + ptr[3] == IE_TYPE_VENDOR_SPECIFIC && + ptr[4] == 5; +} + static void dpp_handle_config_request_frame(const struct mmpdu_header *frame, const void *body, size_t body_len, int rssi, void *user_data) @@ -934,8 +1204,6 @@ static void dpp_handle_config_request_frame(const struct mmpdu_header *frame, const uint8_t *e_nonce = NULL; size_t wrapped_len = 0; _auto_(l_free) uint8_t *unwrapped = NULL; - uint8_t hdr_check[] = { IE_TYPE_ADVERTISEMENT_PROTOCOL, 0x08, 0x7f, - IE_TYPE_VENDOR_SPECIFIC, 5 }; struct json_iter jsiter; _auto_(l_free) char *tech = NULL; _auto_(l_free) char *role = NULL; @@ -945,7 +1213,10 @@ static void dpp_handle_config_request_frame(const struct mmpdu_header *frame, return; } - if (memcmp(dpp->auth_addr, frame->address_2, 6)) { + if (dpp->role != DPP_CAPABILITY_CONFIGURATOR) + return; + + if (memcmp(dpp->peer_addr, frame->address_2, 6)) { l_debug("Configuration request not from authenticated peer"); return; } @@ -959,10 +1230,10 @@ static void dpp_handle_config_request_frame(const struct mmpdu_header *frame, dpp->diag_token = *ptr++; - if (memcmp(ptr, hdr_check, sizeof(hdr_check))) + if (!dpp_check_config_header(ptr)) return; - ptr += sizeof(hdr_check); + ptr += 5; if (memcmp(ptr, wifi_alliance_oui, sizeof(wifi_alliance_oui))) return; @@ -1167,7 +1438,7 @@ static void dpp_handle_config_result_frame(struct dpp_sm *dpp, static void send_authenticate_response(struct dpp_sm *dpp) { uint8_t hdr[32]; - uint8_t attrs[256]; + uint8_t attrs[512]; uint8_t *ptr = attrs; uint8_t status = DPP_STATUS_OK; uint64_t r_proto_key[L_ECC_MAX_DIGITS * 2]; @@ -1181,13 +1452,16 @@ static void send_authenticate_response(struct dpp_sm *dpp) sizeof(r_proto_key)); iov[0].iov_len = dpp_build_header(netdev_get_address(dpp->netdev), - dpp->auth_addr, + dpp->peer_addr, DPP_FRAME_AUTHENTICATION_RESPONSE, hdr); iov[0].iov_base = hdr; ptr += dpp_append_attr(ptr, DPP_ATTR_STATUS, &status, 1); ptr += dpp_append_attr(ptr, DPP_ATTR_RESPONDER_BOOT_KEY_HASH, dpp->own_boot_hash, 32); + if (dpp->mutual_auth) + ptr += dpp_append_attr(ptr, DPP_ATTR_INITIATOR_BOOT_KEY_HASH, + dpp->peer_boot_hash, 32); ptr += dpp_append_attr(ptr, DPP_ATTR_RESPONDER_PROTOCOL_KEY, r_proto_key, dpp->key_len * 2); ptr += dpp_append_attr(ptr, DPP_ATTR_PROTOCOL_VERSION, &version, 1); @@ -1241,11 +1515,12 @@ static void authenticate_confirm(struct dpp_sm *dpp, const uint8_t *from, const void *unwrap_key; const void *ad0 = body + 2; const void *ad1 = body + 8; + struct l_ecc_point *bi = NULL; if (dpp->state != DPP_STATE_AUTHENTICATING) return; - if (memcmp(from, dpp->auth_addr, 6)) + if (memcmp(from, dpp->peer_addr, 6)) return; l_debug("authenticate confirm"); @@ -1333,9 +1608,12 @@ static void authenticate_confirm(struct dpp_sm *dpp, const uint8_t *from, goto auth_confirm_failed; } + if (dpp->mutual_auth) + bi = dpp->peer_boot_public; + dpp_derive_i_auth(dpp->r_nonce, dpp->i_nonce, dpp->nonce_len, dpp->own_proto_public, dpp->peer_proto_public, - dpp->boot_public, i_auth_check); + dpp->boot_public, bi, i_auth_check); if (memcmp(i_auth, i_auth_check, i_auth_len)) { l_error("I-Auth did not verify"); @@ -1344,7 +1622,7 @@ static void authenticate_confirm(struct dpp_sm *dpp, const uint8_t *from, l_debug("Authentication successful"); - dpp_reset_protocol_timer(dpp); + dpp_reset_protocol_timer(dpp, DPP_AUTH_PROTO_TIMEOUT); if (dpp->role == DPP_CAPABILITY_ENROLLEE) dpp_configuration_start(dpp, from); @@ -1368,7 +1646,7 @@ static void dpp_auth_request_failed(struct dpp_sm *dpp, struct iovec iov[2]; iov[0].iov_len = dpp_build_header(netdev_get_address(dpp->netdev), - dpp->auth_addr, + dpp->peer_addr, DPP_FRAME_AUTHENTICATION_RESPONSE, hdr); iov[0].iov_base = hdr; @@ -1442,7 +1720,7 @@ static bool dpp_send_authenticate_request(struct dpp_sm *dpp) struct scan_bss *bss = station_get_connected_bss(station); /* Got disconnected by the time the peer was discovered */ - if (!bss) { + if (dpp->role == DPP_CAPABILITY_CONFIGURATOR && !bss) { dpp_reset(dpp); return false; } @@ -1451,7 +1729,7 @@ static bool dpp_send_authenticate_request(struct dpp_sm *dpp) sizeof(i_proto_key)); iov[0].iov_len = dpp_build_header(netdev_get_address(dpp->netdev), - dpp->auth_addr, + dpp->peer_addr, DPP_FRAME_AUTHENTICATION_REQUEST, hdr); iov[0].iov_base = hdr; @@ -1463,7 +1741,8 @@ static bool dpp_send_authenticate_request(struct dpp_sm *dpp) i_proto_key, dpp->key_len * 2); ptr += dpp_append_attr(ptr, DPP_ATTR_PROTOCOL_VERSION, &version, 1); - if (dpp->current_freq != bss->frequency) { + if (dpp->role == DPP_CAPABILITY_CONFIGURATOR && + dpp->current_freq != bss->frequency) { uint8_t pair[2] = { 81, band_freq_to_channel(bss->frequency, NULL) }; @@ -1484,6 +1763,71 @@ static bool dpp_send_authenticate_request(struct dpp_sm *dpp) return true; } +static void dpp_send_pkex_exchange_request(struct dpp_sm *dpp) +{ + uint8_t hdr[32]; + uint8_t attrs[256]; + uint8_t *ptr = attrs; + uint64_t m_data[L_ECC_MAX_DIGITS * 2]; + uint16_t group; + struct iovec iov[2]; + const uint8_t *own_mac = netdev_get_address(dpp->netdev); + + l_put_le16(l_ecc_curve_get_ike_group(dpp->curve), &group); + + iov[0].iov_len = dpp_build_header(own_mac, broadcast, + DPP_FRAME_PKEX_VERSION1_XCHG_REQUEST, hdr); + iov[0].iov_base = hdr; + + ptr += dpp_append_attr(ptr, DPP_ATTR_PROTOCOL_VERSION, + &dpp->pkex_version, 1); + ptr += dpp_append_attr(ptr, DPP_ATTR_FINITE_CYCLIC_GROUP, + &group, 2); + + if (dpp->pkex_id) + ptr += dpp_append_attr(ptr, DPP_ATTR_CODE_IDENTIFIER, + dpp->pkex_id, strlen(dpp->pkex_id)); + + l_ecc_point_get_data(dpp->pkex_m, m_data, sizeof(m_data)); + + ptr += dpp_append_attr(ptr, DPP_ATTR_ENCRYPTED_KEY, + m_data, dpp->key_len * 2); + + iov[1].iov_base = attrs; + iov[1].iov_len = ptr - attrs; + + dpp_send_frame(dpp, iov, 2, dpp->current_freq); +} + +static void dpp_send_commit_reveal_request(struct dpp_sm *dpp) +{ + struct iovec iov[2]; + uint8_t hdr[41]; + uint8_t attrs[512]; + uint8_t *ptr = attrs; + uint8_t zero = 0; + uint8_t a_pub[L_ECC_POINT_MAX_BYTES]; + ssize_t a_len; + + a_len = l_ecc_point_get_data(dpp->boot_public, a_pub, sizeof(a_pub)); + + iov[0].iov_len = dpp_build_header(netdev_get_address(dpp->netdev), + dpp->peer_addr, + DPP_FRAME_PKEX_COMMIT_REVEAL_REQUEST, + hdr); + iov[0].iov_base = hdr; + + ptr += dpp_append_wrapped_data(hdr + 26, 6, &zero, 1, ptr, + sizeof(attrs), dpp->z, dpp->z_len, 2, + DPP_ATTR_BOOTSTRAPPING_KEY, a_len, a_pub, + DPP_ATTR_INITIATOR_AUTH_TAG, dpp->u_len, dpp->u); + + iov[1].iov_base = attrs; + iov[1].iov_len = ptr - attrs; + + dpp_send_frame(dpp, iov, 2, dpp->current_freq); +} + static void dpp_roc_started(void *user_data) { struct dpp_sm *dpp = user_data; @@ -1548,6 +1892,16 @@ static void dpp_roc_started(void *user_data) } break; + case DPP_STATE_PKEX_EXCHANGE: + if (dpp->role == DPP_CAPABILITY_ENROLLEE) + dpp_send_pkex_exchange_request(dpp); + + break; + case DPP_STATE_PKEX_COMMIT_REVEAL: + if (dpp->role == DPP_CAPABILITY_ENROLLEE) + dpp_send_commit_reveal_request(dpp); + + break; default: break; } @@ -1555,7 +1909,7 @@ static void dpp_roc_started(void *user_data) static void dpp_start_offchannel(struct dpp_sm *dpp, uint32_t freq); -static void dpp_presence_timeout(int error, void *user_data) +static void dpp_offchannel_timeout(int error, void *user_data) { struct dpp_sm *dpp = user_data; @@ -1575,6 +1929,21 @@ static void dpp_presence_timeout(int error, void *user_data) goto protocol_failed; switch (dpp->state) { + case DPP_STATE_PKEX_EXCHANGE: + if (dpp->role != DPP_CAPABILITY_CONFIGURATOR || !dpp->agent) + break; + + /* + * We have a pending agent request but it did not arrive in + * time, we cant assume the enrollee will be waiting around + * for our response so cancel the request and continue waiting + * for another request + */ + if (dpp->agent->pending_id) { + dpp_free_pending_pkex_data(dpp); + dpp_agent_cancel(dpp); + } + /* Fall through */ case DPP_STATE_PRESENCE: break; case DPP_STATE_NOTHING: @@ -1582,19 +1951,20 @@ static void dpp_presence_timeout(int error, void *user_data) return; case DPP_STATE_AUTHENTICATING: case DPP_STATE_CONFIGURING: + case DPP_STATE_PKEX_COMMIT_REVEAL: goto next_roc; } dpp->freqs_idx++; if (dpp->freqs_idx >= dpp->freqs_len) { - l_debug("Max retries on presence announcements"); + l_debug("Max retries offchannel"); dpp->freqs_idx = 0; } dpp->current_freq = dpp->freqs[dpp->freqs_idx]; - l_debug("Presence timeout, moving to next frequency %u, duration %u", + l_debug("Offchannel timeout, moving to next frequency %u, duration %u", dpp->current_freq, dpp->dwell); next_roc: @@ -1617,15 +1987,15 @@ static void dpp_start_offchannel(struct dpp_sm *dpp, uint32_t freq) * between canceling and starting the next (e.g. if a scan request is * sitting in the queue). * - * Second, dpp_presence_timeout resets dpp->offchannel_id to zero which - * is why the new ID is saved and only set to dpp->offchannel_id once - * the previous offchannel work is cancelled (i.e. destroy() has been - * called). + * Second, dpp_offchannel_timeout resets dpp->offchannel_id to zero + * which is why the new ID is saved and only set to dpp->offchannel_id + * once the previous offchannel work is cancelled (i.e. destroy() has + * been called). */ uint32_t id = offchannel_start(netdev_get_wdev_id(dpp->netdev), WIPHY_WORK_PRIORITY_OFFCHANNEL, freq, dpp->dwell, dpp_roc_started, - dpp, dpp_presence_timeout); + dpp, dpp_offchannel_timeout); if (dpp->offchannel_id) offchannel_cancel(dpp->wdev_id, dpp->offchannel_id); @@ -1651,6 +2021,8 @@ static void authenticate_request(struct dpp_sm *dpp, const uint8_t *from, _auto_(l_free) uint8_t *unwrapped = NULL; _auto_(l_ecc_scalar_free) struct l_ecc_scalar *m = NULL; _auto_(l_ecc_scalar_free) struct l_ecc_scalar *n = NULL; + _auto_(l_ecc_point_free) struct l_ecc_point *l = NULL; + struct l_ecc_point *bi = NULL; uint64_t k1[L_ECC_MAX_DIGITS]; const void *ad0 = body + 2; const void *ad1 = body + 8; @@ -1659,7 +2031,8 @@ static void authenticate_request(struct dpp_sm *dpp, const uint8_t *from, if (util_is_broadcast_address(from)) return; - if (dpp->state != DPP_STATE_PRESENCE) + if (dpp->state != DPP_STATE_PRESENCE && + dpp->state != DPP_STATE_AUTHENTICATING) return; l_debug("authenticate request"); @@ -1798,6 +2171,12 @@ static void authenticate_request(struct dpp_sm *dpp, const uint8_t *from, memcpy(dpp->i_nonce, i_nonce, i_nonce_len); + if (dpp->mutual_auth) { + l = dpp_derive_lr(dpp->boot_private, dpp->proto_private, + dpp->peer_boot_public); + bi = dpp->peer_boot_public; + } + /* Derive keys k2, ke, and R-Auth for authentication response */ n = dpp_derive_k2(dpp->peer_proto_public, dpp->proto_private, dpp->k2); @@ -1806,18 +2185,18 @@ static void authenticate_request(struct dpp_sm *dpp, const uint8_t *from, l_getrandom(dpp->r_nonce, dpp->nonce_len); - if (!dpp_derive_ke(dpp->i_nonce, dpp->r_nonce, m, n, dpp->ke)) + if (!dpp_derive_ke(dpp->i_nonce, dpp->r_nonce, m, n, l, dpp->ke)) goto auth_request_failed; if (!dpp_derive_r_auth(dpp->i_nonce, dpp->r_nonce, dpp->nonce_len, dpp->peer_proto_public, dpp->own_proto_public, - dpp->boot_public, dpp->auth_tag)) + bi, dpp->boot_public, dpp->auth_tag)) goto auth_request_failed; - memcpy(dpp->auth_addr, from, 6); + memcpy(dpp->peer_addr, from, 6); dpp->state = DPP_STATE_AUTHENTICATING; - dpp_reset_protocol_timer(dpp); + dpp_reset_protocol_timer(dpp, DPP_AUTH_PROTO_TIMEOUT); /* Don't send if the frequency is changing */ if (!dpp->new_freq) @@ -1839,13 +2218,16 @@ static void dpp_send_authenticate_confirm(struct dpp_sm *dpp) uint8_t zero = 0; iov[0].iov_len = dpp_build_header(netdev_get_address(dpp->netdev), - dpp->auth_addr, + dpp->peer_addr, DPP_FRAME_AUTHENTICATION_CONFIRM, hdr); iov[0].iov_base = hdr; ptr += dpp_append_attr(ptr, DPP_ATTR_STATUS, &zero, 1); ptr += dpp_append_attr(ptr, DPP_ATTR_RESPONDER_BOOT_KEY_HASH, dpp->peer_boot_hash, 32); + if (dpp->mutual_auth) + ptr += dpp_append_attr(ptr, DPP_ATTR_INITIATOR_BOOT_KEY_HASH, + dpp->own_boot_hash, 32); ptr += dpp_append_wrapped_data(hdr + 26, 6, attrs, ptr - attrs, ptr, sizeof(attrs), dpp->ke, dpp->key_len, 1, @@ -1878,6 +2260,8 @@ static void authenticate_response(struct dpp_sm *dpp, const uint8_t *from, const void *r_auth = NULL; _auto_(l_ecc_point_free) struct l_ecc_point *r_proto_key = NULL; _auto_(l_ecc_scalar_free) struct l_ecc_scalar *n = NULL; + _auto_(l_ecc_point_free) struct l_ecc_point *l = NULL; + struct l_ecc_point *bi = NULL; const void *ad0 = body + 2; const void *ad1 = body + 8; uint64_t r_auth_derived[L_ECC_MAX_DIGITS]; @@ -1887,13 +2271,10 @@ static void authenticate_response(struct dpp_sm *dpp, const uint8_t *from, if (dpp->state != DPP_STATE_AUTHENTICATING) return; - if (dpp->role != DPP_CAPABILITY_CONFIGURATOR) - return; - if (!dpp->freqs) return; - if (memcmp(from, dpp->auth_addr, 6)) + if (memcmp(from, dpp->peer_addr, 6)) return; dpp_attr_iter_init(&iter, body + 8, body_len - 8); @@ -1982,7 +2363,13 @@ static void authenticate_response(struct dpp_sm *dpp, const uint8_t *from, return; } - if (!dpp_derive_ke(i_nonce, r_nonce, dpp->m, n, dpp->ke)) { + if (dpp->mutual_auth) { + l = dpp_derive_li(dpp->peer_boot_public, r_proto_key, + dpp->boot_private); + bi = dpp->boot_public; + } + + if (!dpp_derive_ke(i_nonce, r_nonce, dpp->m, n, l, dpp->ke)) { l_debug("Failed to derive ke"); return; } @@ -2015,7 +2402,7 @@ static void authenticate_response(struct dpp_sm *dpp, const uint8_t *from, } if (!dpp_derive_r_auth(i_nonce, r_nonce, dpp->nonce_len, - dpp->own_proto_public, r_proto_key, + dpp->own_proto_public, r_proto_key, bi, dpp->peer_boot_public, r_auth_derived)) { l_debug("Failed to derive r_auth"); return; @@ -2028,7 +2415,7 @@ static void authenticate_response(struct dpp_sm *dpp, const uint8_t *from, if (!dpp_derive_i_auth(r_nonce, i_nonce, dpp->nonce_len, r_proto_key, dpp->own_proto_public, - dpp->peer_boot_public, dpp->auth_tag)) { + dpp->peer_boot_public, bi, dpp->auth_tag)) { l_debug("Could not derive I-Auth"); return; } @@ -2037,6 +2424,10 @@ static void authenticate_response(struct dpp_sm *dpp, const uint8_t *from, dpp->current_freq = dpp->new_freq; dpp_send_authenticate_confirm(dpp); + + if (dpp->role == DPP_CAPABILITY_ENROLLEE) + dpp_configuration_start(dpp, from); + } static void dpp_handle_presence_announcement(struct dpp_sm *dpp, @@ -2066,12 +2457,12 @@ static void dpp_handle_presence_announcement(struct dpp_sm *dpp, /* * The URI may not have contained a MAC address, if this announcement - * verifies set auth_addr then. + * verifies set peer_addr then. */ - if (!l_memeqzero(dpp->auth_addr, 6) && - memcmp(from, dpp->auth_addr, 6)) { + if (!l_memeqzero(dpp->peer_addr, 6) && + memcmp(from, dpp->peer_addr, 6)) { l_debug("Unexpected source "MAC" expected "MAC, MAC_STR(from), - MAC_STR(dpp->auth_addr)); + MAC_STR(dpp->peer_addr)); return; } @@ -2106,7 +2497,7 @@ static void dpp_handle_presence_announcement(struct dpp_sm *dpp, * This is the peer we expected, save away the address and derive the * initial keys. */ - memcpy(dpp->auth_addr, from, 6); + memcpy(dpp->peer_addr, from, 6); dpp->state = DPP_STATE_AUTHENTICATING; @@ -2124,74 +2515,979 @@ static void dpp_handle_presence_announcement(struct dpp_sm *dpp, dpp->channel_switch = true; } -static void dpp_handle_frame(struct dpp_sm *dpp, - const struct mmpdu_header *frame, - const void *body, size_t body_len) +static void dpp_pkex_bad_group(struct dpp_sm *dpp, uint16_t group) { - const uint8_t *ptr; + uint16_t own_group = l_ecc_curve_get_ike_group(dpp->curve); /* - * Both handlers offset by 8 bytes to reach the beginning of the DPP - * attributes. Easier checking this in one place, which also covers the - * frame type byte. + * TODO: The spec allows group negotiation, but it is not yet + * implemented. */ - if (body_len < 8) + if (!group) + return; + /* + * Section 5.6.2 + * "If the Responder's offered group offers less security + * than the Initiator's offered group, then the Initiator should + * ignore this message" + */ + if (group < own_group) { + l_debug("Offered group %u is less secure, ignoring", + group); + return; + } + /* + * Section 5.6.2 + * "If the Responder's offered group offers equivalent or better + * security than the Initiator's offered group, then the + * Initiator may choose to abort its original request and try + * another exchange using the group offered by the Responder" + */ + if (group >= own_group) { + l_debug("Offered group %u is the same or more secure, " + " but group negotiation is not supported", group); return; - - ptr = body + 7; - - switch (*ptr) { - case DPP_FRAME_AUTHENTICATION_REQUEST: - authenticate_request(dpp, frame->address_2, body, body_len); - break; - case DPP_FRAME_AUTHENTICATION_RESPONSE: - authenticate_response(dpp, frame->address_2, body, body_len); - break; - case DPP_FRAME_AUTHENTICATION_CONFIRM: - authenticate_confirm(dpp, frame->address_2, body, body_len); - break; - case DPP_FRAME_CONFIGURATION_RESULT: - dpp_handle_config_result_frame(dpp, frame->address_2, - body, body_len); - break; - case DPP_FRAME_PRESENCE_ANNOUNCEMENT: - dpp_handle_presence_announcement(dpp, frame->address_2, - body, body_len); - break; - default: - l_debug("Unhandled DPP frame %u", *ptr); - break; } } -static bool match_wdev(const void *a, const void *b) -{ - const struct dpp_sm *dpp = a; - const uint64_t *wdev_id = b; - - return *wdev_id == dpp->wdev_id; -} - -static void dpp_frame_timeout(struct l_timeout *timeout, void *user_data) +static void dpp_pkex_bad_code(struct dpp_sm *dpp) { - struct dpp_sm *dpp = user_data; - - l_timeout_remove(timeout); - dpp->retry_timeout = NULL; + _auto_(l_ecc_point_free) struct l_ecc_point *qr = NULL; - /* - * ROC has not yet started (in between an ROC timeout and starting a - * new session), this will most likely result in the frame failing to - * send. Just bail out now and the roc_started callback will take care - * of sending this out. - */ - if (!dpp->roc_started) + qr = dpp_derive_qr(dpp->curve, dpp->pkex_key, dpp->pkex_id, + netdev_get_address(dpp->netdev)); + if (!qr || l_ecc_point_is_infinity(qr)) { + l_debug("Qr computed to zero, new code should be provisioned"); return; + } - dpp_frame_retry(dpp); + l_debug("Qr computed successfully but responder indicated otherwise"); } -static void dpp_mlme_notify(struct l_genl_msg *msg, void *user_data) +static void dpp_handle_pkex_exchange_response(struct dpp_sm *dpp, + const uint8_t *from, + const uint8_t *body, size_t body_len) +{ + struct dpp_attr_iter iter; + enum dpp_attribute_type type; + size_t len; + const uint8_t *data; + const uint8_t *status = NULL; + uint8_t version = 0; + const void *identifier = NULL; + size_t identifier_len = 0; + const void *key = NULL; + size_t key_len = 0; + uint16_t group = 0; + _auto_(l_ecc_point_free) struct l_ecc_point *n = NULL; + _auto_(l_ecc_point_free) struct l_ecc_point *j = NULL; + _auto_(l_ecc_point_free) struct l_ecc_point *qr = NULL; + _auto_(l_ecc_point_free) struct l_ecc_point *k = NULL; + const uint8_t *own_addr = netdev_get_address(dpp->netdev); + + l_debug("PKEX response "MAC, MAC_STR(from)); + + if (dpp->state != DPP_STATE_PKEX_EXCHANGE) + return; + + if (dpp->role != DPP_CAPABILITY_ENROLLEE) + return; + + memcpy(dpp->peer_addr, from, 6); + + dpp_attr_iter_init(&iter, body + 8, body_len - 8); + + while (dpp_attr_iter_next(&iter, &type, &len, &data)) { + switch (type) { + case DPP_ATTR_STATUS: + if (len != 1) + return; + + status = data; + break; + case DPP_ATTR_PROTOCOL_VERSION: + if (len != 1) + return; + + version = l_get_u8(data); + break; + case DPP_ATTR_CODE_IDENTIFIER: + identifier = data; + identifier_len = len; + break; + case DPP_ATTR_ENCRYPTED_KEY: + if (len != dpp->key_len * 2) + return; + + key = data; + key_len = len; + break; + case DPP_ATTR_FINITE_CYCLIC_GROUP: + if (len != 2) + return; + + group = l_get_le16(data); + break; + default: + break; + } + } + + if (!status) { + l_debug("No status attribute, ignoring"); + return; + } + + if (!key) { + l_debug("No encrypted key, ignoring"); + return; + } + + if (*status != DPP_STATUS_OK) + goto handle_status; + + if (dpp->pkex_id) { + if (!identifier || identifier_len != strlen(dpp->pkex_id) || + memcmp(dpp->pkex_id, identifier, + identifier_len)) { + l_debug("mismatch identifier, ignoring"); + return; + } + } + + if (version && version != dpp->pkex_version) { + l_debug("PKEX version does not match, igoring"); + return; + } + + n = l_ecc_point_from_data(dpp->curve, L_ECC_POINT_TYPE_FULL, + key, key_len); + if (!n) { + l_debug("failed to parse peers encrypted key"); + goto failed; + } + + qr = dpp_derive_qr(dpp->curve, dpp->pkex_key, dpp->pkex_id, + dpp->peer_addr); + if (!qr) + goto failed; + + dpp->y_or_x = l_ecc_point_new(dpp->curve); + + /* Y' = N - Qr */ + l_ecc_point_inverse(qr); + l_ecc_point_add(dpp->y_or_x, n, qr); + + /* + * "The resulting ephemeral key, denoted Y’, is then checked whether it + * is the point-at-infinity. If it is not valid, the protocol ends + * unsuccessfully" + */ + if (l_ecc_point_is_infinity(dpp->y_or_x)) { + l_debug("Y' computed to infinity, failing"); + goto failed; + } + + k = l_ecc_point_new(dpp->curve); + + /* K = Y' * x */ + l_ecc_point_multiply(k, dpp->pkex_private, dpp->y_or_x); + + dpp_derive_z(own_addr, dpp->peer_addr, n, dpp->pkex_m, k, + dpp->pkex_key, dpp->pkex_id, + dpp->z, &dpp->z_len); + + /* J = a * Y' */ + j = l_ecc_point_new(dpp->curve); + + l_ecc_point_multiply(j, dpp->boot_private, dpp->y_or_x); + + if (!dpp_derive_u(j, own_addr, dpp->boot_public, dpp->y_or_x, + dpp->pkex_public, dpp->u, &dpp->u_len)) { + l_debug("failed to compute u"); + goto failed; + } + + /* + * Now that a response was successfully received, start another + * offchannel with more time for the remainder of the protocol. After + * PKEX, authentication will begin which handles the protocol timeout. + * If the remainder of PKEX (commit-reveal exchange) cannot complete in + * this time it will fail. + */ + dpp->dwell = (dpp->max_roc < 2000) ? dpp->max_roc : 2000; + dpp->state = DPP_STATE_PKEX_COMMIT_REVEAL; + + dpp_property_changed_notify(dpp); + + dpp_start_offchannel(dpp, dpp->current_freq); + + return; + +handle_status: + switch (*status) { + case DPP_STATUS_BAD_GROUP: + dpp_pkex_bad_group(dpp, group); + break; + case DPP_STATUS_BAD_CODE: + dpp_pkex_bad_code(dpp); + break; + default: + l_debug("Unhandled status %u", *status); + break; + } + +failed: + dpp_reset(dpp); +} + +static bool dpp_pkex_start_authentication(struct dpp_sm *dpp) +{ + dpp->uri = dpp_generate_uri(dpp->own_asn1, dpp->own_asn1_len, 2, + netdev_get_address(dpp->netdev), + &dpp->current_freq, 1, NULL, NULL); + + l_ecdh_generate_key_pair(dpp->curve, &dpp->proto_private, + &dpp->own_proto_public); + + l_getrandom(dpp->i_nonce, dpp->nonce_len); + + dpp->peer_asn1 = dpp_point_to_asn1(dpp->peer_boot_public, + &dpp->peer_asn1_len); + + dpp->m = dpp_derive_k1(dpp->peer_boot_public, dpp->proto_private, + dpp->k1); + + dpp_hash(L_CHECKSUM_SHA256, dpp->peer_boot_hash, 1, dpp->peer_asn1, + dpp->peer_asn1_len); + + dpp->state = DPP_STATE_AUTHENTICATING; + dpp->mutual_auth = true; + + dpp_property_changed_notify(dpp); + + if (dpp->role == DPP_CAPABILITY_ENROLLEE) { + dpp->new_freq = dpp->current_freq; + + return dpp_send_authenticate_request(dpp); + } + + return true; +} + +static void dpp_handle_pkex_commit_reveal_response(struct dpp_sm *dpp, + const uint8_t *from, + const uint8_t *body, size_t body_len) +{ + struct dpp_attr_iter iter; + enum dpp_attribute_type type; + size_t len; + const uint8_t *data; + const uint8_t *wrapped = NULL; + size_t wrapped_len = 0; + uint8_t one = 1; + _auto_(l_free) uint8_t *unwrapped = NULL; + size_t unwrapped_len = 0; + const uint8_t *boot_key = NULL; + size_t boot_key_len = 0; + const uint8_t *r_auth = NULL; + uint8_t v[L_ECC_SCALAR_MAX_BYTES]; + size_t v_len; + _auto_(l_ecc_point_free) struct l_ecc_point *l = NULL; + + l_debug("PKEX commit reveal "MAC, MAC_STR(from)); + + if (dpp->state != DPP_STATE_PKEX_COMMIT_REVEAL) + return; + + if (dpp->role != DPP_CAPABILITY_ENROLLEE) + return; + + /* + * The URI may not have contained a MAC address, if this announcement + * verifies set peer_addr then. + */ + if (memcmp(from, dpp->peer_addr, 6)) { + l_debug("Unexpected source "MAC" expected "MAC, MAC_STR(from), + MAC_STR(dpp->peer_addr)); + return; + } + + dpp_attr_iter_init(&iter, body + 8, body_len - 8); + + while (dpp_attr_iter_next(&iter, &type, &len, &data)) { + switch (type) { + case DPP_ATTR_WRAPPED_DATA: + wrapped = data; + wrapped_len = len; + break; + default: + break; + } + } + + if (!wrapped) { + l_debug("No wrapped data"); + return; + } + + unwrapped = dpp_unwrap_attr(body + 2, 6, &one, 1, dpp->z, dpp->z_len, + wrapped, wrapped_len, &unwrapped_len); + if (!unwrapped) { + l_debug("Failed to unwrap Reveal-Commit message"); + return; + } + + dpp_attr_iter_init(&iter, unwrapped, unwrapped_len); + + while (dpp_attr_iter_next(&iter, &type, &len, &data)) { + switch (type) { + case DPP_ATTR_BOOTSTRAPPING_KEY: + if (len != dpp->key_len * 2) + return; + + boot_key = data; + boot_key_len = len; + break; + case DPP_ATTR_RESPONDER_AUTH_TAG: + if (len != 32) + return; + + r_auth = data; + break; + default: + break; + } + } + + dpp->peer_boot_public = l_ecc_point_from_data(dpp->curve, + L_ECC_POINT_TYPE_FULL, + boot_key, boot_key_len); + if (!dpp->peer_boot_public) { + l_debug("Peer public bootstrapping key was invalid"); + goto failed; + } + + /* L = b * X' */ + l = l_ecc_point_new(dpp->curve); + + l_ecc_point_multiply(l, dpp->pkex_private, dpp->peer_boot_public); + + if (!dpp_derive_v(l, dpp->peer_addr, dpp->peer_boot_public, + dpp->pkex_public, dpp->y_or_x, v, &v_len)) { + l_debug("Failed to derive v"); + goto failed; + } + + if (memcmp(v, r_auth, v_len)) { + l_debug("Bootstrapping data did not verify"); + goto failed; + } + + if (dpp_pkex_start_authentication(dpp)) + return; + +failed: + dpp_reset(dpp); +} + +static void dpp_send_bad_group(struct dpp_sm *dpp, const uint8_t *addr) +{ + uint8_t hdr[32]; + uint8_t attrs[256]; + uint8_t *ptr = attrs; + uint16_t group; + uint8_t status = DPP_STATUS_BAD_GROUP; + struct iovec iov[2]; + const uint8_t *own_mac = netdev_get_address(dpp->netdev); + + l_put_le16(l_ecc_curve_get_ike_group(dpp->curve), &group); + + iov[0].iov_len = dpp_build_header(own_mac, addr, + DPP_FRAME_PKEX_XCHG_RESPONSE, hdr); + iov[0].iov_base = hdr; + + ptr += dpp_append_attr(ptr, DPP_ATTR_STATUS, &status, 1); + ptr += dpp_append_attr(ptr, DPP_ATTR_PROTOCOL_VERSION, + &dpp->pkex_version, 1); + ptr += dpp_append_attr(ptr, DPP_ATTR_FINITE_CYCLIC_GROUP, &group, 2); + + iov[1].iov_base = attrs; + iov[1].iov_len = ptr - attrs; + + dpp_send_frame(dpp, iov, 2, dpp->current_freq); +} + +static void dpp_send_bad_code(struct dpp_sm *dpp, const uint8_t *addr) +{ + uint8_t hdr[32]; + uint8_t attrs[256]; + uint8_t *ptr = attrs; + uint8_t status = DPP_STATUS_BAD_CODE; + struct iovec iov[2]; + const uint8_t *own_mac = netdev_get_address(dpp->netdev); + + iov[0].iov_len = dpp_build_header(own_mac, addr, + DPP_FRAME_PKEX_XCHG_RESPONSE, hdr); + iov[0].iov_base = hdr; + + ptr += dpp_append_attr(ptr, DPP_ATTR_STATUS, &status, 1); + ptr += dpp_append_attr(ptr, DPP_ATTR_PROTOCOL_VERSION, + &dpp->pkex_version, 1); + if (dpp->pkex_id) + ptr += dpp_append_attr(ptr, DPP_ATTR_CODE_IDENTIFIER, + dpp->pkex_id, strlen(dpp->pkex_id)); + + iov[1].iov_base = attrs; + iov[1].iov_len = ptr - attrs; + + dpp_send_frame(dpp, iov, 2, dpp->current_freq); +} + +static void dpp_send_pkex_exchange_response(struct dpp_sm *dpp, + struct l_ecc_point *n) +{ + uint8_t hdr[32]; + uint8_t attrs[256]; + uint8_t *ptr = attrs; + uint64_t n_data[L_ECC_MAX_DIGITS * 2]; + uint16_t group; + uint8_t status = DPP_STATUS_OK; + struct iovec iov[2]; + const uint8_t *own_mac = netdev_get_address(dpp->netdev); + + l_put_le16(l_ecc_curve_get_ike_group(dpp->curve), &group); + + iov[0].iov_len = dpp_build_header(own_mac, dpp->peer_addr, + DPP_FRAME_PKEX_XCHG_RESPONSE, hdr); + iov[0].iov_base = hdr; + + ptr += dpp_append_attr(ptr, DPP_ATTR_STATUS, &status, 1); + + if (dpp->pkex_id) + ptr += dpp_append_attr(ptr, DPP_ATTR_CODE_IDENTIFIER, + dpp->pkex_id, strlen(dpp->pkex_id)); + + l_ecc_point_get_data(n, n_data, sizeof(n_data)); + + ptr += dpp_append_attr(ptr, DPP_ATTR_ENCRYPTED_KEY, + n_data, dpp->key_len * 2); + + iov[1].iov_base = attrs; + iov[1].iov_len = ptr - attrs; + + dpp->state = DPP_STATE_PKEX_COMMIT_REVEAL; + + dpp_property_changed_notify(dpp); + + dpp_send_frame(dpp, iov, 2, dpp->current_freq); +} + +static void dpp_process_pkex_exchange_request(struct dpp_sm *dpp, + struct l_ecc_point *m) +{ + _auto_(l_ecc_point_free) struct l_ecc_point *n = NULL; + _auto_(l_ecc_point_free) struct l_ecc_point *qr = NULL; + _auto_(l_ecc_point_free) struct l_ecc_point *qi = NULL; + _auto_(l_ecc_point_free) struct l_ecc_point *k = NULL; + const uint8_t *own_addr = netdev_get_address(dpp->netdev); + + /* Qi = H(MAC-Initiator | [identifier | ] code) * Pi */ + qi = dpp_derive_qi(dpp->curve, dpp->pkex_key, dpp->pkex_id, + dpp->peer_addr); + if (!qi) { + l_debug("could not derive Qi"); + return; + } + + /* X' = M - Qi */ + dpp->y_or_x = l_ecc_point_new(dpp->curve); + + l_ecc_point_inverse(qi); + l_ecc_point_add(dpp->y_or_x, m, qi); + + /* + * "The resulting ephemeral key, denoted X’, is checked whether it is + * the point-at-infinity. If it is not valid, the protocol silently + * fails" + */ + if (l_ecc_point_is_infinity(dpp->y_or_x)) { + l_debug("X' is at infinity, ignore message"); + dpp_reset(dpp); + return; + } + + qr = dpp_derive_qr(dpp->curve, dpp->pkex_key, dpp->pkex_id, own_addr); + if (!qr || l_ecc_point_is_infinity(qr)) { + l_debug("Qr did not derive"); + l_ecc_point_free(dpp->y_or_x); + dpp->y_or_x = NULL; + goto bad_code; + } + + /* + * "The Responder then generates a random ephemeral keypair, y/Y, + * encrypts Y with Qr to obtain the result, denoted N." + */ + l_ecdh_generate_key_pair(dpp->curve, &dpp->pkex_private, + &dpp->pkex_public); + + /* N = Y + Qr */ + n = l_ecc_point_new(dpp->curve); + + l_ecc_point_add(n, dpp->pkex_public, qr); + + /* K = y * X' */ + + k = l_ecc_point_new(dpp->curve); + + l_ecc_point_multiply(k, dpp->pkex_private, dpp->y_or_x); + + /* z = HKDF(<>, info | M.x | N.x | code, K.x) */ + dpp_derive_z(dpp->peer_addr, own_addr, n, m, k, dpp->pkex_key, + dpp->pkex_id, dpp->z, &dpp->z_len); + + dpp_send_pkex_exchange_response(dpp, n); + + return; + +bad_code: + dpp_send_bad_code(dpp, dpp->peer_addr); + return; +} + +static void dpp_pkex_agent_reply(struct l_dbus_message *message, + void *user_data) +{ + struct dpp_sm *dpp = user_data; + const char *error, *text; + const char *code; + + dpp->agent->pending_id = 0; + + l_debug("SharedCodeAgent %s path %s replied", dpp->agent->owner, + dpp->agent->path); + + if (l_dbus_message_get_error(message, &error, &text)) { + l_error("RequestSharedCode(%s) returned %s(\"%s\")", + dpp->pkex_id, error, text); + goto reset; + } + + if (!l_dbus_message_get_arguments(message, "s", &code)) { + l_debug("Invalid arguments, check SharedCodeAgent!"); + goto reset; + } + + dpp->pkex_key = l_strdup(code); + dpp_process_pkex_exchange_request(dpp, dpp->peer_encr_key); + + return; + +reset: + dpp_free_pending_pkex_data(dpp); +} + +static bool dpp_pkex_agent_request(struct dpp_sm *dpp) +{ + struct l_dbus_message *msg; + + if (!dpp->agent) + return false; + + if (L_WARN_ON(dpp->agent->pending_id)) + return false; + + msg = l_dbus_message_new_method_call(dbus_get_bus(), + dpp->agent->owner, + dpp->agent->path, + IWD_SHARED_CODE_AGENT_INTERFACE, + "RequestSharedCode"); + l_dbus_message_set_arguments(msg, "s", dpp->pkex_id); + + + dpp->agent->pending_id = l_dbus_send_with_reply(dbus_get_bus(), + msg, + dpp_pkex_agent_reply, + dpp, NULL); + return dpp->agent->pending_id != 0; +} + +static void dpp_handle_pkex_exchange_request(struct dpp_sm *dpp, + const uint8_t *from, + const uint8_t *body, size_t body_len) +{ + struct dpp_attr_iter iter; + enum dpp_attribute_type type; + size_t len; + const uint8_t *data; + uint8_t version = 0; + uint16_t group = 0; + const void *id = NULL; + size_t id_len = 0; + const void *key = NULL; + size_t key_len = 0; + _auto_(l_ecc_point_free) struct l_ecc_point *m = NULL; + + l_debug("PKEX exchange request "MAC, MAC_STR(from)); + + if (dpp->state != DPP_STATE_PKEX_EXCHANGE) + return; + + if (dpp->role != DPP_CAPABILITY_CONFIGURATOR) + return; + + if (!l_memeqzero(dpp->peer_addr, 6)) { + l_debug("Already configuring enrollee, ignoring"); + return; + } + + dpp_attr_iter_init(&iter, body + 8, body_len - 8); + + while (dpp_attr_iter_next(&iter, &type, &len, &data)) { + switch (type) { + case DPP_ATTR_PROTOCOL_VERSION: + if (len != 1) + return; + + version = l_get_u8(data); + break; + case DPP_ATTR_FINITE_CYCLIC_GROUP: + if (len != 2) + return; + + group = l_get_le16(data); + break; + case DPP_ATTR_CODE_IDENTIFIER: + id = data; + id_len = len; + break; + case DPP_ATTR_ENCRYPTED_KEY: + key = data; + key_len = len; + break; + default: + break; + } + } + + if (!key || !group) { + l_debug("initiator did not provide group or key, ignoring"); + return; + } + + if (group != l_ecc_curve_get_ike_group(dpp->curve)) { + l_debug("initiator is not using the same group"); + goto bad_group; + } + + /* + * If the group isn't the same the key length won't match, so check + * this here after we've determined the groups are equal + */ + if (key_len != dpp->key_len * 2) { + l_debug("Unexpected encrypted key length"); + return; + } + + if (version && version != dpp->pkex_version) { + l_debug("initiator is not using the same version, ignoring"); + return; + } + + if (dpp->pkex_id) { + if (!id || id_len != strlen(dpp->pkex_id) || + memcmp(dpp->pkex_id, id, id_len)) { + l_debug("mismatch identifier, ignoring"); + return; + } + } + + m = l_ecc_point_from_data(dpp->curve, L_ECC_POINT_TYPE_FULL, + key, key_len); + if (!m) { + l_debug("could not parse key from initiator, ignoring"); + return; + } + + memcpy(dpp->peer_addr, from, 6); + + if (!dpp->pkex_key) { + /* + * "If an optional code identifier is used, it shall be a UTF-8 + * string not greater than eighty (80) octets" + */ + if (!id || id_len > 80 || !l_utf8_validate(id, id_len, NULL)) { + l_debug("Configurator started with agent but enrollee " + "sent invalid or no identifier, ignoring"); + return; + } + + dpp->pkex_id = l_strndup(id, id_len); + + /* Need to obtain code from agent */ + if (!dpp_pkex_agent_request(dpp)) { + l_debug("Failed to request code from agent!"); + dpp_free_pending_pkex_data(dpp); + return; + } + + /* Save the encrypted key/identifier for the agent callback */ + + dpp->peer_encr_key = l_steal_ptr(m); + + return; + } + + dpp_process_pkex_exchange_request(dpp, m); + + return; + +bad_group: + dpp_send_bad_group(dpp, from); +} + +static void dpp_send_commit_reveal_response(struct dpp_sm *dpp, + const uint8_t *v, size_t v_len) +{ + uint8_t hdr[32]; + uint8_t attrs[256]; + uint8_t *ptr = attrs; + uint8_t one = 1; + struct iovec iov[2]; + const uint8_t *own_mac = netdev_get_address(dpp->netdev); + uint8_t b_pub[L_ECC_POINT_MAX_BYTES]; + size_t b_len; + + b_len = l_ecc_point_get_data(dpp->boot_public, b_pub, sizeof(b_pub)); + + + iov[0].iov_len = dpp_build_header(own_mac, dpp->peer_addr, + DPP_FRAME_PKEX_COMMIT_REVEAL_RESPONSE, hdr); + iov[0].iov_base = hdr; + + ptr += dpp_append_wrapped_data(hdr + 26, 6, &one, 1, ptr, + sizeof(attrs), dpp->z, dpp->z_len, 2, + DPP_ATTR_BOOTSTRAPPING_KEY, b_len, b_pub, + DPP_ATTR_RESPONDER_AUTH_TAG, v_len, v); + + iov[1].iov_base = attrs; + iov[1].iov_len = ptr - attrs; + + dpp_send_frame(dpp, iov, 2, dpp->current_freq); +} + +static void dpp_handle_pkex_commit_reveal_request(struct dpp_sm *dpp, + const uint8_t *from, + const uint8_t *body, size_t body_len) +{ + struct dpp_attr_iter iter; + enum dpp_attribute_type type; + size_t len; + const uint8_t *data; + const void *wrapped = NULL; + size_t wrapped_len = 0; + _auto_(l_free) uint8_t *unwrapped = NULL; + size_t unwrapped_len; + uint8_t zero = 0; + const void *key = 0; + size_t key_len = 0; + const void *i_auth = NULL; + size_t i_auth_len = 0; + _auto_(l_ecc_point_free) struct l_ecc_point *j = NULL; + _auto_(l_ecc_point_free) struct l_ecc_point *l = NULL; + uint8_t u[L_ECC_SCALAR_MAX_BYTES]; + size_t u_len = 0; + uint8_t v[L_ECC_SCALAR_MAX_BYTES]; + size_t v_len = 0; + const uint8_t *own_addr = netdev_get_address(dpp->netdev); + + l_debug("PKEX commit-reveal request "MAC, MAC_STR(from)); + + if (dpp->state != DPP_STATE_PKEX_COMMIT_REVEAL) + return; + + if (dpp->role != DPP_CAPABILITY_CONFIGURATOR) + return; + + dpp_attr_iter_init(&iter, body + 8, body_len - 8); + + while (dpp_attr_iter_next(&iter, &type, &len, &data)) { + switch (type) { + case DPP_ATTR_WRAPPED_DATA: + wrapped = data; + wrapped_len = len; + break; + default: + break; + } + } + + if (!wrapped) { + l_debug("No wrapped data"); + return; + } + + unwrapped = dpp_unwrap_attr(body + 2, 6, &zero, 1, dpp->z, dpp->z_len, + wrapped, wrapped_len, &unwrapped_len); + if (!unwrapped) { + l_debug("Failed to unwrap attributes"); + return; + } + + dpp_attr_iter_init(&iter, unwrapped, unwrapped_len); + + while (dpp_attr_iter_next(&iter, &type, &len, &data)) { + switch (type) { + case DPP_ATTR_BOOTSTRAPPING_KEY: + if (len != dpp->key_len * 2) + return; + + key = data; + key_len = len; + break; + case DPP_ATTR_INITIATOR_AUTH_TAG: + if (len != 32) + return; + + i_auth = data; + i_auth_len = len; + break; + default: + break; + } + } + + if (!key || !i_auth) { + l_debug("missing attributes"); + return; + } + + dpp->peer_boot_public = l_ecc_point_from_data(dpp->curve, + L_ECC_POINT_TYPE_FULL, key, key_len); + if (!dpp->peer_boot_public) { + l_debug("peers boostrapping key did not validate"); + goto failed; + } + + /* J' = y * A' */ + j = l_ecc_point_new(dpp->curve); + + l_ecc_point_multiply(j, dpp->pkex_private, dpp->peer_boot_public); + + dpp_derive_u(j, dpp->peer_addr, dpp->peer_boot_public, dpp->pkex_public, + dpp->y_or_x, u, &u_len); + + if (memcmp(u, i_auth, i_auth_len)) { + l_debug("Initiator auth tag did not verify"); + goto failed; + } + + /* L' = x * B' */ + l = l_ecc_point_new(dpp->curve); + + l_ecc_point_multiply(l, dpp->boot_private, dpp->y_or_x); + + if (!dpp_derive_v(l, own_addr, dpp->boot_public, dpp->y_or_x, + dpp->pkex_public, v, &v_len)) { + l_debug("Failed to derive v"); + goto failed; + } + + dpp_send_commit_reveal_response(dpp, v, v_len); + + dpp_pkex_start_authentication(dpp); + + return; + +failed: + dpp_reset(dpp); +} + +static void dpp_handle_frame(struct dpp_sm *dpp, + const struct mmpdu_header *frame, + const void *body, size_t body_len) +{ + const uint8_t *ptr; + + /* + * Both handlers offset by 8 bytes to reach the beginning of the DPP + * attributes. Easier checking this in one place, which also covers the + * frame type byte. + */ + if (body_len < 8) + return; + + ptr = body + 7; + + switch (*ptr) { + case DPP_FRAME_AUTHENTICATION_REQUEST: + authenticate_request(dpp, frame->address_2, body, body_len); + break; + case DPP_FRAME_AUTHENTICATION_RESPONSE: + authenticate_response(dpp, frame->address_2, body, body_len); + break; + case DPP_FRAME_AUTHENTICATION_CONFIRM: + authenticate_confirm(dpp, frame->address_2, body, body_len); + break; + case DPP_FRAME_CONFIGURATION_RESULT: + dpp_handle_config_result_frame(dpp, frame->address_2, + body, body_len); + break; + case DPP_FRAME_PRESENCE_ANNOUNCEMENT: + dpp_handle_presence_announcement(dpp, frame->address_2, + body, body_len); + break; + case DPP_FRAME_PKEX_XCHG_RESPONSE: + dpp_handle_pkex_exchange_response(dpp, frame->address_2, body, + body_len); + break; + case DPP_FRAME_PKEX_COMMIT_REVEAL_RESPONSE: + dpp_handle_pkex_commit_reveal_response(dpp, frame->address_2, + body, body_len); + break; + case DPP_FRAME_PKEX_VERSION1_XCHG_REQUEST: + dpp_handle_pkex_exchange_request(dpp, frame->address_2, body, + body_len); + break; + case DPP_FRAME_PKEX_COMMIT_REVEAL_REQUEST: + dpp_handle_pkex_commit_reveal_request(dpp, frame->address_2, + body, body_len); + break; + default: + l_debug("Unhandled DPP frame %u", *ptr); + break; + } +} + +static bool match_wdev(const void *a, const void *b) +{ + const struct dpp_sm *dpp = a; + const uint64_t *wdev_id = b; + + return *wdev_id == dpp->wdev_id; +} + +static void dpp_frame_timeout(struct l_timeout *timeout, void *user_data) +{ + struct dpp_sm *dpp = user_data; + + l_timeout_remove(timeout); + dpp->retry_timeout = NULL; + + /* + * ROC has not yet started (in between an ROC timeout and starting a + * new session), this will most likely result in the frame failing to + * send. Just bail out now and the roc_started callback will take care + * of sending this out. + */ + if (dpp->offchannel_id && !dpp->roc_started) + return; + + dpp_frame_retry(dpp); +} + +static void dpp_mlme_notify(struct l_genl_msg *msg, void *user_data) { struct dpp_sm *dpp; uint64_t wdev_id = 0; @@ -2214,10 +3510,16 @@ static void dpp_mlme_notify(struct l_genl_msg *msg, void *user_data) if (!dpp) return; - if (dpp->state <= DPP_STATE_PRESENCE) + /* + * Don't retransmit for presence or PKEX exchange if an enrollee, both + * are broadcast frames which don't expect an ack. + */ + if (dpp->state == DPP_STATE_NOTHING || + dpp->state == DPP_STATE_PRESENCE || + (dpp->state == DPP_STATE_PKEX_EXCHANGE && + dpp->role == DPP_CAPABILITY_ENROLLEE)) return; - if (dpp->frame_cookie != cookie) return; @@ -2358,19 +3660,87 @@ static void dpp_frame_watch(struct dpp_sm *dpp, uint16_t frame_type, L_UINT_TO_PTR(frame_type), NULL); } +/* + * Station is unaware of DPP's state so we need to handle a few cases here so + * weird stuff doesn't happen: + * + * - While configuring we should stay connected, a disconnection/roam should + * stop DPP since it would fail regardless due to the hardware going idle + * or changing channels since configurators assume all comms will be + * on-channel. + * - While enrolling we should stay disconnected. If station connects during + * enrolling it would cause 2x calls to __station_connect_network after + * DPP finishes. + * + * Other conditions shouldn't ever happen i.e. configuring and going into a + * connecting state or enrolling and going to a disconnected/roaming state. + */ +static void dpp_station_state_watch(enum station_state state, void *user_data) +{ + struct dpp_sm *dpp = user_data; + + if (dpp->state == DPP_STATE_NOTHING) + return; + + switch (state) { + case STATION_STATE_DISCONNECTED: + case STATION_STATE_DISCONNECTING: + case STATION_STATE_ROAMING: + case STATION_STATE_FT_ROAMING: + case STATION_STATE_FW_ROAMING: + if (L_WARN_ON(dpp->role == DPP_CAPABILITY_ENROLLEE)) + dpp_reset(dpp); + + if (dpp->role == DPP_CAPABILITY_CONFIGURATOR) { + l_debug("Disconnected while configuring, stopping DPP"); + dpp_reset(dpp); + } + + break; + case STATION_STATE_CONNECTING: + case STATION_STATE_CONNECTED: + case STATION_STATE_CONNECTING_AUTO: + if (L_WARN_ON(dpp->role == DPP_CAPABILITY_CONFIGURATOR)) + dpp_reset(dpp); + + if (dpp->role == DPP_CAPABILITY_ENROLLEE) { + l_debug("Connecting while enrolling, stopping DPP"); + dpp_reset(dpp); + } + + break; + + /* + * Autoconnect states are fine for enrollees. This makes it nicer for + * the user since they don't need to explicity Disconnect() to disable + * autoconnect, then re-enable it if DPP fails. + */ + case STATION_STATE_AUTOCONNECT_FULL: + case STATION_STATE_AUTOCONNECT_QUICK: + if (L_WARN_ON(dpp->role == DPP_CAPABILITY_CONFIGURATOR)) + dpp_reset(dpp); + + break; + } +} + static void dpp_create(struct netdev *netdev) { struct l_dbus *dbus = dbus_get_bus(); struct dpp_sm *dpp = l_new(struct dpp_sm, 1); uint8_t dpp_conf_response_prefix[] = { 0x04, 0x0b }; uint8_t dpp_conf_request_prefix[] = { 0x04, 0x0a }; + uint64_t wdev_id = netdev_get_wdev_id(netdev); + struct station *station = station_find(netdev_get_ifindex(netdev)); dpp->netdev = netdev; dpp->state = DPP_STATE_NOTHING; - dpp->wdev_id = netdev_get_wdev_id(netdev); + dpp->interface = DPP_INTERFACE_UNBOUND; + dpp->wdev_id = wdev_id; dpp->curve = l_ecc_curve_from_ike_group(19); dpp->key_len = l_ecc_curve_get_scalar_bytes(dpp->curve); dpp->nonce_len = dpp_nonce_len_from_key_len(dpp->key_len); + dpp->max_roc = wiphy_get_max_roc_duration(wiphy_find_by_wdev(wdev_id)); dpp->mcast_support = wiphy_has_ext_feature( wiphy_find_by_wdev(dpp->wdev_id), NL80211_EXT_FEATURE_MULTICAST_REGISTRATIONS); @@ -2385,6 +3755,16 @@ static void dpp_create(struct netdev *netdev) l_dbus_object_add_interface(dbus, netdev_get_path(netdev), IWD_DPP_INTERFACE, dpp); + l_dbus_object_add_interface(dbus, netdev_get_path(netdev), + IWD_DPP_PKEX_INTERFACE, dpp); + /* + * Since both interfaces share the dpp_sm set this to 2. Currently both + * interfaces are added/removed in unison so we _could_ simply omit the + * destroy callback on one of them. But for consistency and future + * proofing use a reference count and the final interface being removed + * will destroy the dpp_sm. + */ + dpp->refcount = 2; dpp_frame_watch(dpp, 0x00d0, dpp_prefix, sizeof(dpp_prefix)); @@ -2397,6 +3777,9 @@ static void dpp_create(struct netdev *netdev) sizeof(dpp_conf_request_prefix), dpp_handle_config_request_frame, dpp, NULL); + dpp->station_watch = station_add_state_watch(station, + dpp_station_state_watch, dpp, NULL); + l_queue_push_tail(dpp_list, dpp); } @@ -2415,6 +3798,9 @@ static void dpp_netdev_watch(struct netdev *netdev, l_dbus_object_remove_interface(dbus_get_bus(), netdev_get_path(netdev), IWD_DPP_INTERFACE); + l_dbus_object_remove_interface(dbus_get_bus(), + netdev_get_path(netdev), + IWD_DPP_PKEX_INTERFACE); break; default: break; @@ -2464,19 +3850,13 @@ static uint32_t *dpp_add_default_channels(struct dpp_sm *dpp, size_t *len_out) static void dpp_start_presence(struct dpp_sm *dpp, uint32_t *limit_freqs, size_t limit_len) { - uint32_t max_roc = wiphy_get_max_roc_duration( - wiphy_find_by_wdev(dpp->wdev_id)); - - if (2000 < max_roc) - max_roc = 2000; - if (limit_freqs) { dpp->freqs = l_memdup(limit_freqs, sizeof(uint32_t) * limit_len); dpp->freqs_len = limit_len; } else dpp->freqs = dpp_add_default_channels(dpp, &dpp->freqs_len); - dpp->dwell = max_roc; + dpp->dwell = (dpp->max_roc < 2000) ? dpp->max_roc : 2000; dpp->freqs_idx = 0; dpp->current_freq = dpp->freqs[0]; @@ -2491,7 +3871,8 @@ static struct l_dbus_message *dpp_dbus_start_enrollee(struct l_dbus *dbus, uint32_t freq = band_channel_to_freq(6, BAND_FREQ_2_4_GHZ); struct station *station = station_find(netdev_get_ifindex(dpp->netdev)); - if (dpp->state != DPP_STATE_NOTHING) + if (dpp->state != DPP_STATE_NOTHING || + dpp->interface != DPP_INTERFACE_UNBOUND) return dbus_error_busy(message); /* @@ -2510,6 +3891,7 @@ static struct l_dbus_message *dpp_dbus_start_enrollee(struct l_dbus *dbus, dpp->state = DPP_STATE_PRESENCE; dpp->role = DPP_CAPABILITY_ENROLLEE; + dpp->interface = DPP_INTERFACE_DPP; l_ecdh_generate_key_pair(dpp->curve, &dpp->proto_private, &dpp->own_proto_public); @@ -2525,8 +3907,6 @@ static struct l_dbus_message *dpp_dbus_start_enrollee(struct l_dbus *dbus, */ dpp_start_presence(dpp, &freq, 1); - scan_periodic_stop(dpp->wdev_id); - dpp_property_changed_notify(dpp); return NULL; @@ -2563,7 +3943,7 @@ static bool dpp_configurator_start_presence(struct dpp_sm *dpp, const char *uri) } if (!l_memeqzero(info->mac, 6)) - memcpy(dpp->auth_addr, info->mac, 6); + memcpy(dpp->peer_addr, info->mac, 6); if (info->freqs) freqs = scan_freq_set_to_fixed_array(info->freqs, &freqs_len); @@ -2621,7 +4001,8 @@ static struct l_dbus_message *dpp_start_configurator_common( if (network_get_security(network) != SECURITY_PSK) return dbus_error_not_supported(message); - if (dpp->state != DPP_STATE_NOTHING) + if (dpp->state != DPP_STATE_NOTHING || + dpp->interface != DPP_INTERFACE_UNBOUND) return dbus_error_busy(message); l_ecdh_generate_key_pair(dpp->curve, &dpp->proto_private, @@ -2653,12 +4034,11 @@ static struct l_dbus_message *dpp_start_configurator_common( netdev_get_address(dpp->netdev), &bss->frequency, 1, NULL, NULL); dpp->role = DPP_CAPABILITY_CONFIGURATOR; + dpp->interface = DPP_INTERFACE_DPP; dpp->config = dpp_configuration_new(settings, network_get_ssid(network), hs->akm_suite); - scan_periodic_stop(dpp->wdev_id); - dpp_property_changed_notify(dpp); l_debug("DPP Start Configurator: %s", dpp->uri); @@ -2690,11 +4070,373 @@ static struct l_dbus_message *dpp_dbus_stop(struct l_dbus *dbus, { struct dpp_sm *dpp = user_data; + l_debug(""); + + if (dpp->interface != DPP_INTERFACE_DPP) + return dbus_error_not_found(message); + + dpp_reset(dpp); + + return l_dbus_message_new_method_return(message); +} + +static void dpp_pkex_scan_trigger(int err, void *user_data) +{ + struct dpp_sm *dpp = user_data; + + if (err < 0) + dpp_reset(dpp); +} + +/* + * Section 5.6.1 + * In lieu of specific channel information obtained in a manner outside + * the scope of this specification, PKEX responders shall select one of + * the following channels: + * - 2.4 GHz: Channel 6 (2.437 GHz) + * - 5 GHz: Channel 44 (5.220 GHz) if local regulations permit + * operation only in the 5.150 - 5.250 GHz band and Channel + * 149 (5.745 GHz) otherwise + */ +static uint32_t *dpp_default_freqs(struct dpp_sm *dpp, size_t *out_len) +{ + struct wiphy *wiphy = wiphy_find_by_wdev(dpp->wdev_id); + uint32_t default_channels[3] = { 2437, 5220, 5745 }; + uint32_t *freqs_out; + size_t len = 0; + + if ((wiphy_get_supported_bands(wiphy) & BAND_FREQ_2_4_GHZ) && + scan_get_band_rank_modifier(BAND_FREQ_2_4_GHZ) != 0) + default_channels[len++] = 2437; + + if ((wiphy_get_supported_bands(wiphy) & BAND_FREQ_5_GHZ) && + scan_get_band_rank_modifier(BAND_FREQ_5_GHZ) != 0) { + default_channels[len++] = 5220; + default_channels[len++] = 5745; + } + + if (!len) { + l_warn("No bands are allowed, check BandModifier* settings!"); + return NULL; + } + + freqs_out = l_memdup(default_channels, sizeof(uint32_t) * len); + *out_len = len; + + return freqs_out; +} + +static bool dpp_pkex_scan_notify(int err, struct l_queue *bss_list, + const struct scan_freq_set *freqs, + void *user_data) +{ + struct dpp_sm *dpp = user_data; + const struct l_queue_entry *e; + _auto_(scan_freq_set_free) struct scan_freq_set *freq_set = NULL; + + if (err < 0) + goto failed; + + freq_set = scan_freq_set_new(); + + if (!bss_list || l_queue_isempty(bss_list)) { + dpp->freqs = dpp_default_freqs(dpp, &dpp->freqs_len); + if (!dpp->freqs) + goto failed; + + l_debug("No BSS's seen, using default frequency list"); + goto start; + } + + for (e = l_queue_get_entries(bss_list); e; e = e->next) { + const struct scan_bss *bss = e->data; + + scan_freq_set_add(freq_set, bss->frequency); + } + + l_debug("Found %u frequencies to search for configurator", + l_queue_length(bss_list)); + + dpp->freqs = scan_freq_set_to_fixed_array(freq_set, &dpp->freqs_len); + +start: + dpp->current_freq = dpp->freqs[0]; + + dpp_reset_protocol_timer(dpp, DPP_PKEX_PROTO_TIMEOUT); + + l_debug("PKEX start enrollee (id=%s)", dpp->pkex_id ?: "unset"); + + dpp_start_offchannel(dpp, dpp->current_freq); + + return false; + +failed: + dpp_reset(dpp); + return false; +} + +static void dpp_pkex_scan_destroy(void *user_data) +{ + struct dpp_sm *dpp = user_data; + + dpp->pkex_scan_id = 0; +} + +static bool dpp_start_pkex_enrollee(struct dpp_sm *dpp, const char *key, + const char *identifier) +{ + _auto_(l_ecc_point_free) struct l_ecc_point *qi = NULL; + + if (identifier) + dpp->pkex_id = l_strdup(identifier); + + dpp->pkex_key = l_strdup(key); + memcpy(dpp->peer_addr, broadcast, 6); + dpp->role = DPP_CAPABILITY_ENROLLEE; + dpp->state = DPP_STATE_PKEX_EXCHANGE; + dpp->interface = DPP_INTERFACE_PKEX; + /* + * In theory a driver could support a lesser duration than 200ms. This + * complicates things since we would need to tack on additional + * offchannel requests to meet the 200ms requirement. This could be done + * but for now use max_roc or 200ms, whichever is less. + */ + dpp->dwell = (dpp->max_roc < 200) ? dpp->max_roc : 200; + /* "DPP R2 devices are expected to use PKEXv1 by default" */ + dpp->pkex_version = 1; + + if (!l_ecdh_generate_key_pair(dpp->curve, &dpp->pkex_private, + &dpp->pkex_public)) + goto failed; + + /* + * "If Qi is the point-at-infinity, the code shall be deleted and the + * user should be notified to provision a new code" + */ + qi = dpp_derive_qi(dpp->curve, dpp->pkex_key, dpp->pkex_id, + netdev_get_address(dpp->netdev)); + if (!qi || l_ecc_point_is_infinity(qi)) { + l_debug("Cannot derive Qi, provision a new code"); + goto failed; + } + + dpp->pkex_m = l_ecc_point_new(dpp->curve); + + if (!l_ecc_point_add(dpp->pkex_m, dpp->pkex_public, qi)) + goto failed; + + dpp_property_changed_notify(dpp); + + /* + * The 'dpp_default_freqs' function returns the default frequencies + * outlined in section 5.6.1. For 2.4/5GHz this is only 3 frequencies + * which is unlikely to result in discovery of a configurator. The spec + * does allow frequencies to be "obtained in a manner outside the scope + * of this specification" which is what is being done here. + * + * This is mainly geared towards IWD-based configurators; banking on the + * fact that they are currently connected to nearby APs. Scanning lets + * us see nearby BSS's which should be the same frequencies as our + * target configurator. + */ + l_debug("Performing scan for frequencies to start PKEX"); + + dpp->pkex_scan_id = scan_active(dpp->wdev_id, NULL, 0, + dpp_pkex_scan_trigger, dpp_pkex_scan_notify, + dpp, dpp_pkex_scan_destroy); + if (!dpp->pkex_scan_id) + goto failed; + + return true; + +failed: + dpp_reset(dpp); + return false; +} + +static bool dpp_parse_pkex_args(struct l_dbus_message *message, + const char **key_out, + const char **id_out) +{ + struct l_dbus_message_iter iter; + struct l_dbus_message_iter variant; + const char *dict_key; + const char *key = NULL; + const char *id = NULL; + + if (!l_dbus_message_get_arguments(message, "a{sv}", &iter)) + return false; + + while (l_dbus_message_iter_next_entry(&iter, &dict_key, &variant)) { + if (!strcmp(dict_key, "Code")) { + if (!l_dbus_message_iter_get_variant(&variant, "s", + &key)) + return false; + } else if (!strcmp(dict_key, "Identifier")) { + if (!l_dbus_message_iter_get_variant(&variant, "s", + &id)) + return false; + } + } + + if (!key) + return false; + + if (id && strlen(id) > 80) + return false; + + *key_out = key; + *id_out = id; + + return true; +} + +static struct l_dbus_message *dpp_dbus_pkex_start_enrollee(struct l_dbus *dbus, + struct l_dbus_message *message, + void *user_data) +{ + struct dpp_sm *dpp = user_data; + const char *key; + const char *id; + struct station *station = station_find(netdev_get_ifindex(dpp->netdev)); + + l_debug(""); + + if (dpp->state != DPP_STATE_NOTHING || + dpp->interface != DPP_INTERFACE_UNBOUND) + return dbus_error_busy(message); + + if (station && station_get_connected_network(station)) + return dbus_error_busy(message); + + if (!dpp_parse_pkex_args(message, &key, &id)) + goto invalid_args; + + if (!dpp_start_pkex_enrollee(dpp, key, id)) + goto invalid_args; + + return l_dbus_message_new_method_return(message); + +invalid_args: + return dbus_error_invalid_args(message); +} + +static void pkex_agent_disconnect(struct l_dbus *dbus, void *user_data) +{ + struct dpp_sm *dpp = user_data; + + l_debug("SharedCodeAgent %s disconnected", dpp->agent->path); + dpp_reset(dpp); +} + +static void dpp_create_agent(struct dpp_sm *dpp, const char *path, + struct l_dbus_message *message) +{ + const char *sender = l_dbus_message_get_sender(message); + + dpp->agent = l_new(struct pkex_agent, 1); + dpp->agent->owner = l_strdup(sender); + dpp->agent->path = l_strdup(path); + dpp->agent->disconnect_watch = l_dbus_add_disconnect_watch( + dbus_get_bus(), + sender, + pkex_agent_disconnect, + dpp, NULL); + + l_debug("Registered a SharedCodeAgent on path %s", path); +} + +static struct l_dbus_message *dpp_start_pkex_configurator(struct dpp_sm *dpp, + const char *key, const char *identifier, + const char *agent_path, + struct l_dbus_message *message) +{ + struct handshake_state *hs = netdev_get_handshake(dpp->netdev); + struct station *station = station_find(netdev_get_ifindex(dpp->netdev)); + struct network *network = station_get_connected_network(station); + struct scan_bss *bss = station_get_connected_bss(station); + const struct l_settings *settings; + + if (dpp->state != DPP_STATE_NOTHING || + dpp->interface != DPP_INTERFACE_UNBOUND) + return dbus_error_busy(message); + + if (!dpp->mcast_support) { + l_debug("Multicast frame registration not supported, cannot " + "start a configurator"); + return dbus_error_not_supported(message); + } + + if (!network || !bss) + return dbus_error_not_connected(message); + + settings = network_get_settings(network); + if (!settings) { + l_debug("No settings for network, is this a known network?"); + return dbus_error_not_configured(message); + } + + if (identifier) + dpp->pkex_id = l_strdup(identifier); + + if (key) + dpp->pkex_key = l_strdup(key); + + if (agent_path) + dpp_create_agent(dpp, agent_path, message); + + dpp->role = DPP_CAPABILITY_CONFIGURATOR; + dpp->state = DPP_STATE_PKEX_EXCHANGE; + dpp->interface = DPP_INTERFACE_PKEX; + dpp->current_freq = bss->frequency; + dpp->pkex_version = 1; + dpp->config = dpp_configuration_new(network_get_settings(network), + network_get_ssid(network), + hs->akm_suite); + + dpp_reset_protocol_timer(dpp, DPP_PKEX_PROTO_TIMEOUT); + dpp_property_changed_notify(dpp); + + if (dpp->pkex_key) + l_debug("Starting PKEX configurator for single enrollee"); + else + l_debug("Starting PKEX configurator with agent"); return l_dbus_message_new_method_return(message); } +static struct l_dbus_message *dpp_dbus_pkex_configure_enrollee( + struct l_dbus *dbus, + struct l_dbus_message *message, + void *user_data) +{ + struct dpp_sm *dpp = user_data; + const char *key; + const char *id; + + l_debug(""); + + if (!dpp_parse_pkex_args(message, &key, &id)) + return dbus_error_invalid_args(message); + + return dpp_start_pkex_configurator(dpp, key, id, NULL, message); +} + +static struct l_dbus_message *dpp_dbus_pkex_start_configurator( + struct l_dbus *dbus, + struct l_dbus_message *message, + void *user_data) +{ + struct dpp_sm *dpp = user_data; + const char *path; + + if (!l_dbus_message_get_arguments(message, "o", &path)) + return dbus_error_invalid_args(message); + + return dpp_start_pkex_configurator(dpp, NULL, NULL, path, message); +} + static void dpp_setup_interface(struct l_dbus_interface *interface) { l_dbus_interface_method(interface, "StartEnrollee", 0, @@ -2713,10 +4455,45 @@ static void dpp_setup_interface(struct l_dbus_interface *interface) l_dbus_interface_property(interface, "URI", 0, "s", dpp_get_uri, NULL); } +static struct l_dbus_message *dpp_dbus_pkex_stop(struct l_dbus *dbus, + struct l_dbus_message *message, void *user_data) +{ + struct dpp_sm *dpp = user_data; + + l_debug(""); + + if (dpp->interface != DPP_INTERFACE_PKEX) + return dbus_error_not_found(message); + + dpp_reset(dpp); + + return l_dbus_message_new_method_return(message); +} + +static void dpp_setup_pkex_interface(struct l_dbus_interface *interface) +{ + l_dbus_interface_method(interface, "StartEnrollee", 0, + dpp_dbus_pkex_start_enrollee, "", "a{sv}", "args"); + l_dbus_interface_method(interface, "Stop", 0, + dpp_dbus_pkex_stop, "", ""); + l_dbus_interface_method(interface, "ConfigureEnrollee", 0, + dpp_dbus_pkex_configure_enrollee, "", "a{sv}", "args"); + l_dbus_interface_method(interface, "StartConfigurator", 0, + dpp_dbus_pkex_start_configurator, "", "o", "path"); + + l_dbus_interface_property(interface, "Started", 0, "b", + dpp_pkex_get_started, NULL); + l_dbus_interface_property(interface, "Role", 0, "s", + dpp_pkex_get_role, NULL); +} + static void dpp_destroy_interface(void *user_data) { struct dpp_sm *dpp = user_data; + if (--dpp->refcount) + return; + l_queue_remove(dpp_list, dpp); dpp_free(dpp); @@ -2735,6 +4512,9 @@ static int dpp_init(void) l_dbus_register_interface(dbus_get_bus(), IWD_DPP_INTERFACE, dpp_setup_interface, dpp_destroy_interface, false); + l_dbus_register_interface(dbus_get_bus(), IWD_DPP_PKEX_INTERFACE, + dpp_setup_pkex_interface, + dpp_destroy_interface, false); mlme_watch = l_genl_family_register(nl80211, "mlme", dpp_mlme_notify, NULL, NULL); @@ -2754,6 +4534,7 @@ static void dpp_exit(void) l_debug(""); l_dbus_unregister_interface(dbus_get_bus(), IWD_DPP_INTERFACE); + l_dbus_unregister_interface(dbus_get_bus(), IWD_DPP_PKEX_INTERFACE); netdev_watch_remove(netdev_watch); diff --git a/src/eap-pwd.c b/src/eap-pwd.c @@ -320,7 +320,27 @@ static void eap_pwd_handle_id(struct eap_state *eap, strlen("EAP-pwd Hunting And Pecking"), pwd_value, nbytes); - if (!(pwd_seed[31] & 1)) + /* + * The RFC requires the point be solved unambiguously (since + * solving for Y results in two solutions). The correct Y value + * is chosen based on the LSB of the pwd-seed: + * + * if (LSB(y) == LSB(pwd-seed)) + * then + * PWE = (x, y) + * else + * PWE = (x, p-y) + * + * The ELL API (somewhat hidden from view here) automatically + * performs a subtraction (P - Y) when: + * - Y is even and BIT1 + * - Y is odd and BIT0 + * + * So we choose the point type which matches the parity of + * pwd-seed. This means a subtraction will be performed (P - Y) + * if the parity of pwd-seed and the computed Y do not match. + */ + if (pwd_seed[31] & 1) pwe = l_ecc_point_from_data(pwd->curve, L_ECC_POINT_TYPE_COMPRESSED_BIT1, pwd_value, nbytes); diff --git a/src/eap.c b/src/eap.c @@ -415,11 +415,8 @@ static const char *eap_type_to_str(enum eap_type type, uint32_t vendor_id, return buf; } -_Pragma("GCC diagnostic push") -_Pragma("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") #define IS_EXPANDED_RESPONSE(id, t) \ (type == EAP_TYPE_EXPANDED && vendor_id == (id) && vendor_type == (t)) -_Pragma("GCC diagnostic pop") #define RESPONSE_IS(t) \ (type == (t) || IS_EXPANDED_RESPONSE(0, (t))) @@ -530,7 +527,10 @@ static void eap_handle_response(struct eap_state *eap, const uint8_t *pkt, if (our_type != EAP_TYPE_EXPANDED) { if (RESPONSE_IS(our_type)) goto handle_response; +_Pragma("GCC diagnostic push") +_Pragma("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") } else if (IS_EXPANDED_RESPONSE(our_vendor_id, our_vendor_type)) +_Pragma("GCC diagnostic pop") goto handle_response; error: diff --git a/src/eapol.c b/src/eapol.c @@ -2531,7 +2531,7 @@ static void eapol_eap_results_cb(const uint8_t *msk_data, size_t msk_len, if (sm->handshake->support_fils && emsk_data && session_id) erp_cache_add(eap_get_identity(sm->eap), session_id, session_len, emsk_data, emsk_len, - (const char *)sm->handshake->ssid); + sm->handshake->ssid, sm->handshake->ssid_len); return; diff --git a/src/erp.c b/src/erp.c @@ -160,13 +160,19 @@ static void erp_cache_entry_destroy(void *data) void erp_cache_add(const char *id, const void *session_id, size_t session_len, const void *emsk, size_t emsk_len, - const char *ssid) + const uint8_t *ssid, size_t ssid_len) { struct erp_cache_entry *entry; if (!unlikely(id || session_id || emsk)) return; + if (!util_ssid_is_utf8(ssid_len, ssid)) + return; + + if (util_ssid_is_hidden(ssid_len, ssid)) + return; + entry = l_new(struct erp_cache_entry, 1); entry->id = l_strdup(id); @@ -174,7 +180,7 @@ void erp_cache_add(const char *id, const void *session_id, entry->emsk_len = emsk_len; entry->session_id = l_memdup(session_id, session_len); entry->session_len = session_len; - entry->ssid = l_strdup(ssid); + entry->ssid = l_strndup((char *) ssid, ssid_len); entry->expire_time = l_time_offset(l_time_now(), ERP_DEFAULT_KEY_LIFETIME_US); @@ -281,8 +287,9 @@ static bool erp_derive_emsk_name(const uint8_t *session_id, size_t session_len, uint16_t eight = L_CPU_TO_BE16(8); char *ascii; - if (!prf_plus(L_CHECKSUM_SHA256, session_id, session_len, "EMSK", - hex, 8, 1, &eight, sizeof(eight))) + if (!prf_plus(L_CHECKSUM_SHA256, session_id, session_len, + hex, 8, 2, "EMSK", strlen("EMSK") + 1, + &eight, sizeof(eight))) return false; ascii = l_util_hexstring(hex, 8); @@ -309,13 +316,15 @@ static bool erp_derive_reauth_keys(const uint8_t *emsk, size_t emsk_len, uint16_t len = L_CPU_TO_BE16(emsk_len); uint8_t cryptosuite = ERP_CRYPTOSUITE_SHA256_128; - if (!prf_plus(L_CHECKSUM_SHA256, emsk, emsk_len, ERP_RRK_LABEL, - r_rk, emsk_len, 1, + if (!prf_plus(L_CHECKSUM_SHA256, emsk, emsk_len, + r_rk, emsk_len, 2, ERP_RRK_LABEL, + strlen(ERP_RRK_LABEL) + 1, &len, sizeof(len))) return false; - if (!prf_plus(L_CHECKSUM_SHA256, r_rk, emsk_len, ERP_RIK_LABEL, - r_ik, emsk_len, 2, + if (!prf_plus(L_CHECKSUM_SHA256, r_rk, emsk_len, + r_ik, emsk_len, 3, ERP_RIK_LABEL, + strlen(ERP_RIK_LABEL) + 1, &cryptosuite, 1, &len, sizeof(len))) return false; @@ -496,8 +505,8 @@ int erp_rx_packet(struct erp_state *erp, const uint8_t *pkt, size_t len) length = L_CPU_TO_BE16(64); if (!prf_plus(L_CHECKSUM_SHA256, erp->r_rk, erp->cache->emsk_len, - ERP_RMSK_LABEL, - erp->rmsk, erp->cache->emsk_len, 2, + erp->rmsk, erp->cache->emsk_len, 3, + ERP_RMSK_LABEL, strlen(ERP_RMSK_LABEL) + 1, &seq, sizeof(seq), &length, sizeof(length))) goto eap_failed; diff --git a/src/erp.h b/src/erp.h @@ -43,7 +43,7 @@ const void *erp_get_rmsk(struct erp_state *erp, size_t *rmsk_len); void erp_cache_add(const char *id, const void *session_id, size_t session_len, const void *emsk, size_t emsk_len, - const char *ssid); + const uint8_t *ssid, size_t ssid_len); void erp_cache_remove(const char *id); diff --git a/src/ft.c b/src/ft.c @@ -58,13 +58,14 @@ struct ft_info { uint32_t frequency; uint32_t ds_frequency; uint32_t offchannel_id; + /* Status of Authenticate/Action frame response, or error (< 0) */ + int status; struct l_timeout *timeout; struct wiphy_radio_work_item work; struct ie_ft_info ft_info; - bool parsed : 1; bool onchannel : 1; }; @@ -526,22 +527,23 @@ static int ft_over_ds_parse_action_response(const uint8_t *frame, if (memcmp(spa, hdr->address_1, 6)) return -EINVAL; - status = l_get_le16(frame + 14); - if (status != 0) - return (int)status; - if (spa_out) *spa_out = spa; if (aa_out) *aa_out = aa; + status = l_get_le16(frame + 14); + if (status != 0) + goto done; + if (ies_out && ies_len) { *ies_out = frame + 16; *ies_len = frame_len - 16; } - return 0; +done: + return (int)status; } int __ft_rx_associate(uint32_t ifindex, const uint8_t *frame, size_t frame_len) @@ -825,7 +827,7 @@ void __ft_rx_action(uint32_t ifindex, const uint8_t *frame, size_t frame_len) ret = ft_over_ds_parse_action_response(frame, frame_len, &spa, &aa, &ies, &ies_len); - if (ret != 0) { + if (ret < 0) { l_debug("Could not parse action response"); return; } @@ -836,13 +838,22 @@ void __ft_rx_action(uint32_t ifindex, const uint8_t *frame, size_t frame_len) return; } + + if (ret != 0) { + l_debug("BSS "MAC" rejected FT action with status=%u", + MAC_STR(info->aa), ret); + info->status = ret; + goto done; + } + if (!ft_parse_ies(info, hs, ies, ies_len)) { l_debug("Could not parse action response IEs"); goto ft_error; } - info->parsed = true; + info->status = ret; +done: l_timeout_remove(info->timeout); info->timeout = NULL; @@ -872,6 +883,7 @@ static struct ft_info *ft_info_new(struct handshake_state *hs, target_bss->rsne[1] + 2); l_getrandom(info->snonce, 32); + info->status = -ENOENT; return info; } @@ -1016,6 +1028,7 @@ void __ft_rx_authenticate(uint32_t ifindex, const uint8_t *frame, if (status != 0) { l_debug("BSS "MAC" rejected FT auth with status=%u", MAC_STR(info->aa), status); + info->status = status; goto cancel; } @@ -1024,7 +1037,7 @@ void __ft_rx_authenticate(uint32_t ifindex, const uint8_t *frame, goto cancel; } - info->parsed = true; + info->status = status; cancel: /* @@ -1164,11 +1177,13 @@ int ft_associate(uint32_t ifindex, const uint8_t *addr) * Either failed or no response. This may have been an FT-over-DS * attempt so clear out the entry so FT-over-Air can try again. */ - if (!info->parsed) { + if (info->status != 0) { + int status = info->status; + l_queue_remove(info_list, info); ft_info_destroy(info); - return -ENOENT; + return status; } ft_prepare_handshake(info, hs); diff --git a/src/ie.c b/src/ie.c @@ -481,6 +481,52 @@ const char *ie_rsn_cipher_suite_to_string(enum ie_rsn_cipher_suite suite) return NULL; } +uint32_t ie_rsn_akm_suite_to_akm(enum ie_rsn_akm_suite akm) +{ + switch (akm) { + case IE_RSN_AKM_SUITE_8021X: + return CRYPTO_AKM_8021X; + case IE_RSN_AKM_SUITE_PSK: + return CRYPTO_AKM_PSK; + case IE_RSN_AKM_SUITE_FT_OVER_8021X: + return CRYPTO_AKM_FT_OVER_8021X; + case IE_RSN_AKM_SUITE_FT_USING_PSK: + return CRYPTO_AKM_FT_USING_PSK; + case IE_RSN_AKM_SUITE_8021X_SHA256: + return CRYPTO_AKM_8021X_SHA256; + case IE_RSN_AKM_SUITE_PSK_SHA256: + return CRYPTO_AKM_PSK_SHA256; + case IE_RSN_AKM_SUITE_TDLS: + return CRYPTO_AKM_TDLS; + case IE_RSN_AKM_SUITE_SAE_SHA256: + return CRYPTO_AKM_SAE_SHA256; + case IE_RSN_AKM_SUITE_FT_OVER_SAE_SHA256: + return CRYPTO_AKM_FT_OVER_SAE_SHA256; + case IE_RSN_AKM_SUITE_AP_PEER_KEY_SHA256: + return CRYPTO_AKM_AP_PEER_KEY_SHA256; + case IE_RSN_AKM_SUITE_8021X_SUITE_B_SHA256: + return CRYPTO_AKM_8021X_SUITE_B_SHA256; + case IE_RSN_AKM_SUITE_8021X_SUITE_B_SHA384: + return CRYPTO_AKM_8021X_SUITE_B_SHA384; + case IE_RSN_AKM_SUITE_FT_OVER_8021X_SHA384: + return CRYPTO_AKM_FT_OVER_8021X_SHA384; + case IE_RSN_AKM_SUITE_FILS_SHA256: + return CRYPTO_AKM_FILS_SHA256; + case IE_RSN_AKM_SUITE_FILS_SHA384: + return CRYPTO_AKM_FILS_SHA384; + case IE_RSN_AKM_SUITE_FT_OVER_FILS_SHA256: + return CRYPTO_AKM_FT_OVER_FILS_SHA256; + case IE_RSN_AKM_SUITE_FT_OVER_FILS_SHA384: + return CRYPTO_AKM_FT_OVER_FILS_SHA384; + case IE_RSN_AKM_SUITE_OWE: + return CRYPTO_AKM_OWE; + case IE_RSN_AKM_SUITE_OSEN: + return CRYPTO_AKM_OSEN; + } + + return 0; +} + /* 802.11, Section 8.4.2.27.2 */ static bool ie_parse_cipher_suite(const uint8_t *data, enum ie_rsn_cipher_suite *out) diff --git a/src/ie.h b/src/ie.h @@ -621,6 +621,8 @@ unsigned char *ie_tlv_builder_finalize(struct ie_tlv_builder *builder, uint32_t ie_rsn_cipher_suite_to_cipher(enum ie_rsn_cipher_suite suite); const char *ie_rsn_cipher_suite_to_string(enum ie_rsn_cipher_suite suite); +uint32_t ie_rsn_akm_suite_to_akm(enum ie_rsn_akm_suite akm); + int ie_parse_rsne(struct ie_tlv_iter *iter, struct ie_rsn_info *info); int ie_parse_rsne_from_data(const uint8_t *data, size_t len, struct ie_rsn_info *info); diff --git a/src/ip-pool.c b/src/ip-pool.c @@ -27,6 +27,7 @@ #include <errno.h> #include <netinet/in.h> #include <arpa/inet.h> +#include <linux/rtnetlink.h> #include <ell/ell.h> diff --git a/src/iwd-dbus.conf b/src/iwd-dbus.conf @@ -12,6 +12,7 @@ <allow send_destination="net.connman.iwd"/> <allow send_interface="net.connman.iwd.Agent"/> <allow send_interface="net.connman.iwd.SignalLevelAgent"/> + <allow send_interface="net.connman.iwd.SharedCodeAgent"/> </policy> <policy group="wheel"> diff --git a/src/iwd.config.rst b/src/iwd.config.rst @@ -122,7 +122,7 @@ The group ``[General]`` contains general settings. - Value: rssi dBm value, from -100 to 1, default: **-70** This value can be used to control how aggressively **iwd** roams when - connected to a 2.4Ghz access point. + connected to a 2.4GHz access point. * - RoamThreshold5G - Value: rssi dBm value, from -100 to 1, default: **-76** @@ -291,22 +291,37 @@ autoconnect purposes. :widths: 20 80 :align: left - * - BandModifier5Ghz + * - BandModifier2_4GHz + - Values: floating point value (default: **1.0**) + + Increase or decrease the preference for 2.4GHz access points by + increasing or decreasing the value of this modifier. + + A value of 0.0 will disable the 2.4GHz band and prevent scanning or + connecting on those frequencies. + + * - BandModifier5GHz - Values: floating point value (default: **1.0**) Increase or decrease the preference for 5GHz access points by increasing or decreasing the value of this modifier. 5GHz networks are already preferred due to their increase throughput / data rate. However, 5GHz networks are highly RSSI sensitive, so it is still possible for IWD to - prefer 2.4Ghz APs in certain circumstances. + prefer 2.4GHz APs in certain circumstances. + + A value of 0.0 will disable the 5GHz band and prevent scanning or + connecting on those frequencies. - * - BandModifier6Ghz + * - BandModifier6GHz - Values: floating point value (default: **1.0**) Increase or decrease the preference for 6GHz access points by increasing or decreasing the value of this modifier. Since 6GHz networks are highly RSSI sensitive, this gives an option to prefer 6GHz APs over 5GHz APs. + A value of 0.0 will disable the 6GHz band and prevent scanning or + connecting on those frequencies. + Scan ---- diff --git a/src/json.h b/src/json.h @@ -85,7 +85,7 @@ void json_iter_init(struct json_iter *iter, struct json_contents *c); * other types are encountered. * * JSON_OPTIONAL string values will point to NULL if not found - * JSON_OPTIONAL objects/primitives can be checked with json_object_is_valid. + * JSON_OPTIONAL objects/primitives can be checked with json_iter_is_valid. */ bool json_iter_parse(struct json_iter *iter, enum json_type type, ...); diff --git a/src/main.c b/src/main.c @@ -33,6 +33,7 @@ #include <unistd.h> #include <sys/stat.h> #include <sys/mman.h> +#include <linux/rtnetlink.h> #include <ell/ell.h> #include <ell/useful.h> diff --git a/src/netdev.c b/src/netdev.c @@ -839,7 +839,6 @@ static void netdev_connect_failed(struct netdev *netdev, uint16_t status_or_reason) { netdev_connect_cb_t connect_cb = netdev->connect_cb; - netdev_event_func_t event_filter = netdev->event_filter; void *connect_data = netdev->user_data; /* Done this way to allow re-entrant netdev_connect calls */ @@ -847,23 +846,101 @@ static void netdev_connect_failed(struct netdev *netdev, if (connect_cb) connect_cb(netdev, result, &status_or_reason, connect_data); - else if (event_filter) { - /* NETDEV_EVENT_DISCONNECT_BY_SME expects a reason code */ - if (result != NETDEV_RESULT_HANDSHAKE_FAILED) - status_or_reason = MMPDU_REASON_CODE_UNSPECIFIED; +} - event_filter(netdev, NETDEV_EVENT_DISCONNECT_BY_SME, - &status_or_reason, - connect_data); +static void netdev_connect_failed_cb(struct l_genl_msg *msg, void *user_data) +{ + struct netdev *netdev = user_data; + + netdev->disconnect_cmd_id = 0; + netdev_connect_failed(netdev, netdev->result, netdev->last_code); +} + +static void netdev_send_and_fail_connection(struct netdev *netdev, + enum netdev_result result, + uint16_t status_code, + struct l_genl_msg *msg) +{ + netdev->result = result; + netdev->last_code = status_code; + + netdev->disconnect_cmd_id = + l_genl_family_send(nl80211, msg, netdev_connect_failed_cb, + netdev, NULL); +} + +static void netdev_disconnect_and_fail_connection(struct netdev *netdev, + enum netdev_result result, + uint16_t status_code) +{ + struct l_genl_msg *msg = nl80211_build_disconnect(netdev->index, + MMPDU_REASON_CODE_UNSPECIFIED); + + netdev_send_and_fail_connection(netdev, result, status_code, msg); +} + +static void netdev_deauth_and_fail_connection(struct netdev *netdev, + enum netdev_result result, + uint16_t status_code) +{ + struct l_genl_msg *msg = nl80211_build_deauthenticate(netdev->index, + netdev->handshake->aa, + MMPDU_REASON_CODE_UNSPECIFIED); + + netdev_send_and_fail_connection(netdev, result, status_code, msg); +} + +/* + * If we have a connection callback pending, either through netdev_connect + * or netdev_reassociate, then invoke that callback with the @result and + * @status_or_reason. Otherwise, invoke the event callback with the @event + * and @status_or_reason. + * + * This is useful for situations where handshaking or setting keys somehow + * fails (perhaps due to rekeying), or if the device is removed / brought + * down when keys are being set as a result of a rekey + */ +static void netdev_disconnected(struct netdev *netdev, + enum netdev_result result, + enum netdev_event event, + uint16_t status_or_reason) +{ + netdev_event_func_t event_filter = netdev->event_filter; + void *event_data = netdev->user_data; + + if (netdev->connect_cb) { + netdev_connect_failed(netdev, result, status_or_reason); + return; } + + netdev_connect_free(netdev); + + if (event_filter) + event_filter(netdev, event, &status_or_reason, event_data); } -static void netdev_disconnect_cb(struct l_genl_msg *msg, void *user_data) +static void netdev_disconnect_by_sme_cb(struct l_genl_msg *msg, void *user_data) { struct netdev *netdev = user_data; netdev->disconnect_cmd_id = 0; - netdev_connect_failed(netdev, netdev->result, netdev->last_code); + netdev_disconnected(netdev, netdev->result, + NETDEV_EVENT_DISCONNECT_BY_SME, netdev->last_code); +} + +static void netdev_disconnect_by_sme(struct netdev *netdev, + enum netdev_result result, + uint16_t reason_code) +{ + struct l_genl_msg *msg = nl80211_build_disconnect(netdev->index, + reason_code); + + netdev->result = result; + netdev->last_code = reason_code; + + netdev->disconnect_cmd_id = l_genl_family_send(nl80211, msg, + netdev_disconnect_by_sme_cb, + netdev, NULL); } static void netdev_free(void *data) @@ -1054,6 +1131,7 @@ static void netdev_cqm_event(struct l_genl_msg *msg, struct netdev *netdev) uint32_t *rssi_event = NULL; int32_t *rssi_val = NULL; uint32_t *pkt_event = NULL; + bool beacon_loss = false; if (!l_genl_attr_init(&attr, msg)) return; @@ -1081,7 +1159,7 @@ static void netdev_cqm_event(struct l_genl_msg *msg, struct netdev *netdev) break; case NL80211_ATTR_CQM_BEACON_LOSS_EVENT: - l_debug("Beacon lost event"); + beacon_loss = true; break; case NL80211_ATTR_CQM_RSSI_LEVEL: @@ -1111,6 +1189,9 @@ static void netdev_cqm_event(struct l_genl_msg *msg, struct netdev *netdev) } else if (pkt_event && netdev->event_filter) netdev->event_filter(netdev, NETDEV_EVENT_PACKET_LOSS_NOTIFY, pkt_event, netdev->user_data); + else if (beacon_loss && netdev->event_filter) + netdev->event_filter(netdev, NETDEV_EVENT_BEACON_LOSS_NOTIFY, + NULL, netdev->user_data); } static void netdev_rekey_offload_event(struct l_genl_msg *msg, @@ -1241,18 +1322,6 @@ static void netdev_cmd_disconnect_cb(struct l_genl_msg *msg, void *user_data) disconnect_cb(netdev, r, disconnect_data); } -static struct l_genl_msg *netdev_build_cmd_disconnect(struct netdev *netdev, - uint16_t reason_code) -{ - struct l_genl_msg *msg; - - msg = l_genl_msg_new_sized(NL80211_CMD_DISCONNECT, 64); - l_genl_msg_append_attr(msg, NL80211_ATTR_IFINDEX, 4, &netdev->index); - l_genl_msg_append_attr(msg, NL80211_ATTR_REASON_CODE, 2, &reason_code); - - return msg; -} - static void netdev_deauthenticate_event(struct l_genl_msg *msg, struct netdev *netdev) { @@ -1260,6 +1329,7 @@ static void netdev_deauthenticate_event(struct l_genl_msg *msg, uint16_t type, len; const void *data; const struct mmpdu_header *hdr = NULL; + const struct mmpdu_deauthentication *deauth; uint16_t reason_code; l_debug(""); @@ -1294,7 +1364,8 @@ static void netdev_deauthenticate_event(struct l_genl_msg *msg, if (!memcmp(hdr->address_2, netdev->addr, sizeof(netdev->addr))) return; - reason_code = l_get_u8(mmpdu_body(hdr)); + deauth = mmpdu_body(hdr); + reason_code = L_LE16_TO_CPU(deauth->reason_code); l_info("deauth event, src="MAC" dest="MAC" bssid="MAC" reason=%u", MAC_STR(hdr->address_2), MAC_STR(hdr->address_1), @@ -1304,66 +1375,6 @@ static void netdev_deauthenticate_event(struct l_genl_msg *msg, MMPDU_STATUS_CODE_UNSPECIFIED); } -static struct l_genl_msg *netdev_build_cmd_deauthenticate(struct netdev *netdev, - uint16_t reason_code) -{ - struct l_genl_msg *msg; - - msg = l_genl_msg_new_sized(NL80211_CMD_DEAUTHENTICATE, 128); - l_genl_msg_append_attr(msg, NL80211_ATTR_IFINDEX, 4, &netdev->index); - l_genl_msg_append_attr(msg, NL80211_ATTR_REASON_CODE, 2, &reason_code); - l_genl_msg_append_attr(msg, NL80211_ATTR_MAC, ETH_ALEN, - netdev->handshake->aa); - - return msg; -} - -static struct l_genl_msg *netdev_build_cmd_del_station(struct netdev *netdev, - const uint8_t *sta, - uint16_t reason_code, - bool disassociate) -{ - struct l_genl_msg *msg; - uint8_t subtype = disassociate ? - MPDU_MANAGEMENT_SUBTYPE_DISASSOCIATION : - MPDU_MANAGEMENT_SUBTYPE_DEAUTHENTICATION; - - msg = l_genl_msg_new_sized(NL80211_CMD_DEL_STATION, 64); - l_genl_msg_append_attr(msg, NL80211_ATTR_IFINDEX, 4, &netdev->index); - l_genl_msg_append_attr(msg, NL80211_ATTR_MAC, 6, sta); - l_genl_msg_append_attr(msg, NL80211_ATTR_MGMT_SUBTYPE, 1, &subtype); - l_genl_msg_append_attr(msg, NL80211_ATTR_REASON_CODE, 2, &reason_code); - - return msg; -} - -static void netdev_del_sta_cb(struct l_genl_msg *msg, void *user_data) -{ - int err = l_genl_msg_get_error(msg); - const char *ext_error; - - if (err >= 0) - return; - - ext_error = l_genl_msg_get_extended_error(msg); - l_error("DEL_STATION failed: %s", - ext_error ? ext_error : strerror(-err)); -} - -int netdev_del_station(struct netdev *netdev, const uint8_t *sta, - uint16_t reason_code, bool disassociate) -{ - struct l_genl_msg *msg; - - msg = netdev_build_cmd_del_station(netdev, sta, reason_code, - disassociate); - - if (!l_genl_family_send(nl80211, msg, netdev_del_sta_cb, NULL, NULL)) - return -EIO; - - return 0; -} - static void netdev_operstate_cb(int error, uint16_t type, const void *data, uint32_t len, void *user_data) @@ -1449,30 +1460,29 @@ static void netdev_setting_keys_failed(struct netdev_handshake_state *nhs, * CMD_DISCONNECT */ if (err == -ENETDOWN) { - netdev_connect_failed(netdev, NETDEV_RESULT_ABORTED, + netdev_disconnected(netdev, NETDEV_RESULT_ABORTED, + NETDEV_EVENT_DISCONNECT_BY_SME, MMPDU_STATUS_CODE_UNSPECIFIED); return; } - msg = netdev_build_cmd_disconnect(netdev, - MMPDU_REASON_CODE_UNSPECIFIED); - netdev->disconnect_cmd_id = l_genl_family_send(nl80211, msg, - netdev_disconnect_cb, - netdev, NULL); + netdev_disconnect_by_sme(netdev, + NETDEV_RESULT_KEY_SETTING_FAILED, + MMPDU_REASON_CODE_UNSPECIFIED); break; case NL80211_IFTYPE_AP: if (err == -ENETDOWN) return; - msg = netdev_build_cmd_del_station(netdev, nhs->super.spa, - MMPDU_REASON_CODE_UNSPECIFIED, false); + msg = nl80211_build_del_station(netdev->index, + nhs->super.spa, MMPDU_REASON_CODE_UNSPECIFIED, + MPDU_MANAGEMENT_SUBTYPE_DEAUTHENTICATION); if (!l_genl_family_send(nl80211, msg, NULL, NULL, NULL)) l_error("error sending DEL_STATION"); break; } - netdev->result = NETDEV_RESULT_KEY_SETTING_FAILED; handshake_event(&nhs->super, HANDSHAKE_EVENT_SETTING_KEYS_FAILED, &err); } @@ -1963,57 +1973,6 @@ error: netdev_setting_keys_failed(nhs, err); } -static struct l_genl_msg *netdev_build_cmd_new_key_pairwise( - struct netdev *netdev, - uint32_t cipher, - const uint8_t *aa, - const uint8_t *tk, - size_t tk_len, - uint8_t key_id) -{ - struct l_genl_msg *msg; - - msg = l_genl_msg_new_sized(NL80211_CMD_NEW_KEY, 512); - - l_genl_msg_append_attr(msg, NL80211_ATTR_KEY_DATA, tk_len, tk); - l_genl_msg_append_attr(msg, NL80211_ATTR_KEY_CIPHER, 4, &cipher); - l_genl_msg_append_attr(msg, NL80211_ATTR_MAC, ETH_ALEN, aa); - l_genl_msg_append_attr(msg, NL80211_ATTR_KEY_IDX, 1, &key_id); - l_genl_msg_append_attr(msg, NL80211_ATTR_IFINDEX, 4, &netdev->index); - - return msg; -} - -static struct l_genl_msg *netdev_build_cmd_new_rx_key_pairwise( - struct netdev *netdev, - uint32_t cipher, - const uint8_t *aa, - const uint8_t *tk, - size_t tk_len, - uint8_t key_id) -{ - uint8_t key_mode = NL80211_KEY_NO_TX; - uint32_t key_type = NL80211_KEYTYPE_PAIRWISE; - struct l_genl_msg *msg; - - msg = l_genl_msg_new_sized(NL80211_CMD_NEW_KEY, 512); - - l_genl_msg_append_attr(msg, NL80211_ATTR_MAC, ETH_ALEN, aa); - l_genl_msg_append_attr(msg, NL80211_ATTR_IFINDEX, 4, &netdev->index); - - l_genl_msg_enter_nested(msg, NL80211_ATTR_KEY); - - l_genl_msg_append_attr(msg, NL80211_KEY_DATA, tk_len, tk); - l_genl_msg_append_attr(msg, NL80211_KEY_CIPHER, 4, &cipher); - l_genl_msg_append_attr(msg, NL80211_KEY_IDX, 1, &key_id); - l_genl_msg_append_attr(msg, NL80211_KEY_MODE, 1, &key_mode); - l_genl_msg_append_attr(msg, NL80211_KEY_TYPE, 4, &key_type); - - l_genl_msg_leave_nested(msg); - - return msg; -} - static void netdev_group_timeout_cb(struct l_timeout *timeout, void *user_data) { struct netdev_handshake_state *nhs = user_data; @@ -2089,9 +2048,9 @@ static void netdev_set_tk(struct handshake_state *hs, uint8_t key_index, if (!netdev_copy_tk(tk_buf, tk, cipher, hs->authenticator)) goto invalid_key; - msg = netdev_build_cmd_new_key_pairwise(netdev, cipher, addr, tk_buf, - crypto_cipher_key_len(cipher), - key_index); + msg = nl80211_build_new_key_pairwise(netdev->index, cipher, addr, + tk_buf, crypto_cipher_key_len(cipher), + key_index); nhs->pairwise_new_key_cmd_id = l_genl_family_send(nl80211, msg, netdev_new_pairwise_key_cb, nhs, NULL); @@ -2123,9 +2082,9 @@ static void netdev_set_ext_tk(struct handshake_state *hs, uint8_t key_idx, if (!netdev_copy_tk(tk_buf, tk, cipher, hs->authenticator)) goto error; - msg = netdev_build_cmd_new_rx_key_pairwise(netdev, cipher, addr, tk_buf, - crypto_cipher_key_len(cipher), - hs->active_tk_index); + msg = nl80211_build_new_rx_key_pairwise(netdev->index, cipher, addr, + tk_buf, crypto_cipher_key_len(cipher), + hs->active_tk_index); nhs->pairwise_new_key_cmd_id = l_genl_family_send(nl80211, msg, netdev_new_rx_pairwise_key_cb, nhs, NULL); @@ -2234,21 +2193,17 @@ void netdev_handshake_failed(struct handshake_state *hs, uint16_t reason_code) netdev->sm = NULL; - netdev->result = NETDEV_RESULT_HANDSHAKE_FAILED; - netdev->last_code = reason_code; - switch (netdev->type) { case NL80211_IFTYPE_STATION: case NL80211_IFTYPE_P2P_CLIENT: - msg = netdev_build_cmd_disconnect(netdev, reason_code); - netdev->disconnect_cmd_id = l_genl_family_send(nl80211, msg, - netdev_disconnect_cb, - netdev, NULL); + netdev_disconnect_by_sme(netdev, NETDEV_RESULT_HANDSHAKE_FAILED, + reason_code); break; case NL80211_IFTYPE_AP: case NL80211_IFTYPE_P2P_GO: - msg = netdev_build_cmd_del_station(netdev, nhs->super.spa, - reason_code, false); + msg = nl80211_build_del_station(netdev->index, nhs->super.spa, + reason_code, + MPDU_MANAGEMENT_SUBTYPE_DEAUTHENTICATION); if (!l_genl_family_send(nl80211, msg, NULL, NULL, NULL)) l_error("error sending DEL_STATION"); } @@ -2278,30 +2233,6 @@ static void hardware_rekey_cb(struct l_genl_msg *msg, void *data) } } -static struct l_genl_msg *netdev_build_cmd_replay_counter(struct netdev *netdev, - const uint8_t *kek, - const uint8_t *kck, - uint64_t replay_ctr) -{ - struct l_genl_msg *msg; - - msg = l_genl_msg_new_sized(NL80211_CMD_SET_REKEY_OFFLOAD, 512); - - l_genl_msg_append_attr(msg, NL80211_ATTR_IFINDEX, 4, &netdev->index); - - l_genl_msg_enter_nested(msg, NL80211_ATTR_REKEY_DATA); - l_genl_msg_append_attr(msg, NL80211_REKEY_DATA_KEK, - NL80211_KEK_LEN, kek); - l_genl_msg_append_attr(msg, NL80211_REKEY_DATA_KCK, - NL80211_KCK_LEN, kck); - l_genl_msg_append_attr(msg, NL80211_REKEY_DATA_REPLAY_CTR, - NL80211_REPLAY_CTR_LEN, &replay_ctr); - - l_genl_msg_leave_nested(msg); - - return msg; -} - static void netdev_set_rekey_offload(uint32_t ifindex, const uint8_t *kek, const uint8_t *kck, @@ -2322,7 +2253,7 @@ static void netdev_set_rekey_offload(uint32_t ifindex, return; l_debug("%d", netdev->index); - msg = netdev_build_cmd_replay_counter(netdev, kek, kck, replay_counter); + msg = nl80211_build_rekey_offload(ifindex, kek, kck, replay_counter); netdev->rekey_offload_cmd_id = l_genl_family_send(nl80211, msg, hardware_rekey_cb, netdev, NULL); @@ -2514,90 +2445,6 @@ static void netdev_driver_connected(struct netdev *netdev) eapol_register(netdev->sm); } -static unsigned int ie_rsn_akm_suite_to_nl80211(enum ie_rsn_akm_suite akm) -{ - switch (akm) { - case IE_RSN_AKM_SUITE_8021X: - return CRYPTO_AKM_8021X; - case IE_RSN_AKM_SUITE_PSK: - return CRYPTO_AKM_PSK; - case IE_RSN_AKM_SUITE_FT_OVER_8021X: - return CRYPTO_AKM_FT_OVER_8021X; - case IE_RSN_AKM_SUITE_FT_USING_PSK: - return CRYPTO_AKM_FT_USING_PSK; - case IE_RSN_AKM_SUITE_8021X_SHA256: - return CRYPTO_AKM_8021X_SHA256; - case IE_RSN_AKM_SUITE_PSK_SHA256: - return CRYPTO_AKM_PSK_SHA256; - case IE_RSN_AKM_SUITE_TDLS: - return CRYPTO_AKM_TDLS; - case IE_RSN_AKM_SUITE_SAE_SHA256: - return CRYPTO_AKM_SAE_SHA256; - case IE_RSN_AKM_SUITE_FT_OVER_SAE_SHA256: - return CRYPTO_AKM_FT_OVER_SAE_SHA256; - case IE_RSN_AKM_SUITE_AP_PEER_KEY_SHA256: - return CRYPTO_AKM_AP_PEER_KEY_SHA256; - case IE_RSN_AKM_SUITE_8021X_SUITE_B_SHA256: - return CRYPTO_AKM_8021X_SUITE_B_SHA256; - case IE_RSN_AKM_SUITE_8021X_SUITE_B_SHA384: - return CRYPTO_AKM_8021X_SUITE_B_SHA384; - case IE_RSN_AKM_SUITE_FT_OVER_8021X_SHA384: - return CRYPTO_AKM_FT_OVER_8021X_SHA384; - case IE_RSN_AKM_SUITE_FILS_SHA256: - return CRYPTO_AKM_FILS_SHA256; - case IE_RSN_AKM_SUITE_FILS_SHA384: - return CRYPTO_AKM_FILS_SHA384; - case IE_RSN_AKM_SUITE_FT_OVER_FILS_SHA256: - return CRYPTO_AKM_FT_OVER_FILS_SHA256; - case IE_RSN_AKM_SUITE_FT_OVER_FILS_SHA384: - return CRYPTO_AKM_FT_OVER_FILS_SHA384; - case IE_RSN_AKM_SUITE_OWE: - return CRYPTO_AKM_OWE; - case IE_RSN_AKM_SUITE_OSEN: - return CRYPTO_AKM_OSEN; - } - - return 0; -} - -static void netdev_append_nl80211_rsn_attributes(struct l_genl_msg *msg, - struct handshake_state *hs) -{ - uint32_t nl_cipher; - uint32_t nl_akm; - uint32_t wpa_version; - - nl_cipher = ie_rsn_cipher_suite_to_cipher(hs->pairwise_cipher); - L_WARN_ON(!nl_cipher); - l_genl_msg_append_attr(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE, - 4, &nl_cipher); - - nl_cipher = ie_rsn_cipher_suite_to_cipher(hs->group_cipher); - L_WARN_ON(!nl_cipher); - l_genl_msg_append_attr(msg, NL80211_ATTR_CIPHER_SUITE_GROUP, - 4, &nl_cipher); - - if (hs->mfp) { - uint32_t use_mfp = NL80211_MFP_REQUIRED; - - l_genl_msg_append_attr(msg, NL80211_ATTR_USE_MFP, 4, &use_mfp); - } - - nl_akm = ie_rsn_akm_suite_to_nl80211(hs->akm_suite); - L_WARN_ON(!nl_akm); - l_genl_msg_append_attr(msg, NL80211_ATTR_AKM_SUITES, 4, &nl_akm); - - if (IE_AKM_IS_SAE(hs->akm_suite)) - wpa_version = NL80211_WPA_VERSION_3; - else if (hs->wpa_ie) - wpa_version = NL80211_WPA_VERSION_1; - else - wpa_version = NL80211_WPA_VERSION_2; - - l_genl_msg_append_attr(msg, NL80211_ATTR_WPA_VERSIONS, - 4, &wpa_version); -} - static struct l_genl_msg *netdev_build_cmd_connect(struct netdev *netdev, struct handshake_state *hs, const uint8_t *prev_bssid, @@ -2654,7 +2501,7 @@ static struct l_genl_msg *netdev_build_cmd_connect(struct netdev *netdev, l_genl_msg_append_attr(msg, NL80211_ATTR_SOCKET_OWNER, 0, NULL); if (is_rsn) { - netdev_append_nl80211_rsn_attributes(msg, hs); + nl80211_append_rsn_attributes(msg, hs); c_iov = iov_ie_append(iov, n_iov, c_iov, hs->supplicant_ie); } @@ -2714,28 +2561,23 @@ static void netdev_cmd_connect_cb(struct l_genl_msg *msg, void *user_data) static bool netdev_retry_owe(struct netdev *netdev) { - struct iovec iov; + struct l_genl_msg *connect_cmd; if (!owe_next_group(netdev->owe_sm)) return false; - iov.iov_base = netdev->handshake->vendor_ies; - iov.iov_len = netdev->handshake->vendor_ies_len; - - netdev->connect_cmd = netdev_build_cmd_connect(netdev, - netdev->handshake, NULL, &iov, 1); + connect_cmd = netdev_build_cmd_connect(netdev, + netdev->handshake, NULL, NULL, 0); - netdev->connect_cmd_id = l_genl_family_send(nl80211, - netdev->connect_cmd, + netdev->connect_cmd_id = l_genl_family_send(nl80211, connect_cmd, netdev_cmd_connect_cb, netdev, NULL); - if (!netdev->connect_cmd_id) - return false; - - netdev->connect_cmd = NULL; + if (netdev->connect_cmd_id > 0) + return true; - return true; + l_genl_msg_unref(connect_cmd); + return false; } static void netdev_connect_event(struct l_genl_msg *msg, struct netdev *netdev) @@ -2981,14 +2823,9 @@ error: return; deauth: - netdev->result = NETDEV_RESULT_ASSOCIATION_FAILED; - netdev->last_code = MMPDU_STATUS_CODE_UNSPECIFIED; - msg = netdev_build_cmd_deauthenticate(netdev, - MMPDU_REASON_CODE_UNSPECIFIED); - netdev->disconnect_cmd_id = l_genl_family_send(nl80211, - msg, - netdev_disconnect_cb, - netdev, NULL); + netdev_disconnect_and_fail_connection(netdev, + NETDEV_RESULT_ASSOCIATION_FAILED, + MMPDU_STATUS_CODE_UNSPECIFIED); } static struct l_genl_msg *netdev_build_cmd_associate_common( @@ -3007,7 +2844,7 @@ static struct l_genl_msg *netdev_build_cmd_associate_common( l_genl_msg_append_attr(msg, NL80211_ATTR_SOCKET_OWNER, 0, NULL); if (is_rsn) - netdev_append_nl80211_rsn_attributes(msg, hs); + nl80211_append_rsn_attributes(msg, hs); if (is_rsn || hs->settings_8021x) { l_genl_msg_append_attr(msg, NL80211_ATTR_CONTROL_PORT, @@ -3029,18 +2866,12 @@ static void netdev_cmd_ft_reassociate_cb(struct l_genl_msg *msg, netdev->connect_cmd_id = 0; - if (l_genl_msg_get_error(msg) < 0) { - struct l_genl_msg *cmd_deauth; + if (l_genl_msg_get_error(msg) >= 0) + return; - netdev->result = NETDEV_RESULT_ASSOCIATION_FAILED; - netdev->last_code = MMPDU_STATUS_CODE_UNSPECIFIED; - cmd_deauth = netdev_build_cmd_deauthenticate(netdev, - MMPDU_REASON_CODE_UNSPECIFIED); - netdev->disconnect_cmd_id = l_genl_family_send(nl80211, - cmd_deauth, - netdev_disconnect_cb, - netdev, NULL); - } + netdev_deauth_and_fail_connection(netdev, + NETDEV_RESULT_ASSOCIATION_FAILED, + MMPDU_STATUS_CODE_UNSPECIFIED); } static bool kernel_will_retry_auth(uint16_t status_code, @@ -3165,16 +2996,9 @@ static void netdev_authenticate_event(struct l_genl_msg *msg, * to keep retrying, tell it to stop */ if (retry) { - struct l_genl_msg *cmd_deauth; - - netdev->result = NETDEV_RESULT_ASSOCIATION_FAILED; - netdev->last_code = MMPDU_STATUS_CODE_UNSPECIFIED; - cmd_deauth = netdev_build_cmd_deauthenticate(netdev, - MMPDU_REASON_CODE_UNSPECIFIED); - netdev->disconnect_cmd_id = l_genl_family_send(nl80211, - cmd_deauth, - netdev_disconnect_cb, - netdev, NULL); + netdev_deauth_and_fail_connection(netdev, + NETDEV_RESULT_ASSOCIATION_FAILED, + MMPDU_STATUS_CODE_UNSPECIFIED); return; } } @@ -3348,25 +3172,22 @@ static void netdev_auth_cb(struct l_genl_msg *msg, void *user_data) l_debug("Error during auth: %d", err); - if (!netdev->auth_cmd || err != -ENOENT) { - netdev_connect_failed(netdev, - NETDEV_RESULT_AUTHENTICATION_FAILED, - MMPDU_STATUS_CODE_UNSPECIFIED); - return; - } + if (!netdev->auth_cmd || err != -ENOENT) + goto failed; /* Kernel can't find the BSS in its cache, scan and retry */ scan_msg = scan_build_trigger_scan_bss(netdev->index, netdev->wiphy, netdev->frequency, hs->ssid, hs->ssid_len); - if (!l_genl_family_send(nl80211, scan_msg, - netdev_scan_cb, netdev, NULL)) { - l_genl_msg_unref(scan_msg); - netdev_connect_failed(netdev, - NETDEV_RESULT_AUTHENTICATION_FAILED, + if (l_genl_family_send(nl80211, scan_msg, + netdev_scan_cb, netdev, NULL) > 0) + return; + + l_genl_msg_unref(scan_msg); +failed: + netdev_connect_failed(netdev, NETDEV_RESULT_AUTHENTICATION_FAILED, MMPDU_STATUS_CODE_UNSPECIFIED); - } } static void netdev_new_scan_results_event(struct l_genl_msg *msg, @@ -3599,19 +3420,16 @@ static void netdev_mac_change_failed(struct netdev *netdev, int error) WATCHLIST_NOTIFY(&netdev_watches, netdev_watch_func_t, netdev, NETDEV_WATCH_EVENT_DOWN); - goto failed; - } else { - /* If the interface is up we can still try and connect */ - l_info("Failed to change the MAC, continuing with connection"); - if (netdev_begin_connection(netdev) < 0) - goto failed; - + netdev_connect_failed(netdev, NETDEV_RESULT_ABORTED, + MMPDU_STATUS_CODE_UNSPECIFIED); return; } -failed: - netdev_connect_failed(netdev, NETDEV_RESULT_ABORTED, - MMPDU_STATUS_CODE_UNSPECIFIED); + /* If the interface is up we can still try and connect */ + l_info("Failed to change the MAC, continuing with connection"); + + if (netdev_begin_connection(netdev) < 0) + l_error("netdev_begin_connection() error in mac_change_failed"); } static void netdev_mac_destroy(void *user_data) @@ -3643,14 +3461,9 @@ static void netdev_mac_power_up_cb(int error, uint16_t type, return; } - /* - * Pick up where we left off in netdev_connect_commmon. - */ - if (netdev_begin_connection(netdev) < 0) { - l_error("Failed to connect after changing MAC"); - netdev_connect_failed(netdev, NETDEV_RESULT_ASSOCIATION_FAILED, - MMPDU_STATUS_CODE_UNSPECIFIED); - } + /* Pick up where we left off in netdev_connect_commmon */ + if (netdev_begin_connection(netdev) < 0) + l_error("netdev_begin_connection() error in mac_power_up_cb"); } static void netdev_mac_power_down_cb(int error, uint16_t type, @@ -3713,7 +3526,8 @@ static int netdev_start_powered_mac_change(struct netdev *netdev) /* No address set in handshake, use per-network MAC generation */ if (l_memeqzero(netdev->handshake->spa, ETH_ALEN)) wiphy_generate_address_from_ssid(netdev->wiphy, - (const char *)netdev->handshake->ssid, + netdev->handshake->ssid, + netdev->handshake->ssid_len, new_addr); else memcpy(new_addr, netdev->handshake->spa, ETH_ALEN); @@ -3864,7 +3678,7 @@ static bool netdev_connection_work_ready(struct wiphy_radio_work_item *item) } if (netdev_begin_connection(netdev) < 0) - goto failed; + return true; return false; @@ -4161,7 +3975,7 @@ int netdev_disconnect(struct netdev *netdev, } if (send_disconnect) { - disconnect = netdev_build_cmd_disconnect(netdev, + disconnect = nl80211_build_disconnect(netdev->index, MMPDU_REASON_CODE_DEAUTH_LEAVING); netdev->disconnect_cmd_id = l_genl_family_send(nl80211, disconnect, netdev_cmd_disconnect_cb, @@ -4690,17 +4504,14 @@ static void netdev_sa_query_timeout(struct l_timeout *timeout, void *user_data) { struct netdev *netdev = user_data; - struct l_genl_msg *msg; l_info("SA Query timed out, connection is invalid. Disconnecting..."); l_timeout_remove(netdev->sa_query_timeout); netdev->sa_query_timeout = NULL; - msg = netdev_build_cmd_disconnect(netdev, - MMPDU_REASON_CODE_PREV_AUTH_NOT_VALID); - netdev->disconnect_cmd_id = l_genl_family_send(nl80211, msg, - netdev_disconnect_cb, netdev, NULL); + netdev_disconnect_by_sme(netdev, NETDEV_RESULT_ABORTED, + MMPDU_REASON_CODE_PREV_AUTH_NOT_VALID); } static void netdev_sa_query_req_cb(struct l_genl_msg *msg, void *user_data) @@ -4950,8 +4761,7 @@ static void netdev_unprot_disconnect_event(struct l_genl_msg *msg, if (!hdr) return; - /* get reason code, first byte of frame */ - reason_code = l_get_u8(mmpdu_body(hdr)); + reason_code = l_get_le16(mmpdu_body(hdr)); l_info("disconnect event, src="MAC" dest="MAC" bssid="MAC" reason=%u", MAC_STR(hdr->address_2), MAC_STR(hdr->address_1), @@ -5054,7 +4864,7 @@ static bool netdev_get_fw_scan_cb(int err, struct l_queue *bss_list, if (err < 0) { l_error("Failed to get scan after roam (%d)", err); - goto failed; + return false; } /* @@ -5066,7 +4876,7 @@ static bool netdev_get_fw_scan_cb(int err, struct l_queue *bss_list, if (!bss) { l_error("Roam target BSS not found in scan results"); - goto failed; + return false; } netdev->fw_roam_bss = bss; @@ -5078,17 +4888,10 @@ static bool netdev_get_fw_scan_cb(int err, struct l_queue *bss_list, return false; } - if (netdev->sm) { - if (!eapol_start(netdev->sm)) - goto failed; - } + if (netdev->sm) + L_WARN_ON(!eapol_start(netdev->sm)); return false; - -failed: - netdev_connect_failed(netdev, NETDEV_RESULT_ABORTED, - MMPDU_REASON_CODE_UNSPECIFIED); - return false; } /* @@ -5118,8 +4921,8 @@ static void netdev_roam_event(struct l_genl_msg *msg, struct netdev *netdev) netdev->operational = false; - if (!l_genl_attr_init(&attr, msg)) - goto failed; + if (L_WARN_ON(!l_genl_attr_init(&attr, msg))) + return; while (l_genl_attr_next(&attr, &type, &len, &data)) { switch (type) { @@ -5134,7 +4937,7 @@ static void netdev_roam_event(struct l_genl_msg *msg, struct netdev *netdev) if (!mac) { l_error("Failed to parse ATTR_MAC from CMD_ROAM"); - goto failed; + return; } /* Handshake completed in firmware, just get the roamed BSS */ @@ -5151,20 +4954,14 @@ static void netdev_roam_event(struct l_genl_msg *msg, struct netdev *netdev) get_fw_scan: handshake_state_set_authenticator_address(netdev->handshake, mac); - if (!scan_get_firmware_scan(netdev->wdev_id, netdev_get_fw_scan_cb, - netdev, NULL)) - goto failed; + if (L_WARN_ON(!scan_get_firmware_scan(netdev->wdev_id, + netdev_get_fw_scan_cb, + netdev, NULL))) + return; if (netdev->event_filter) netdev->event_filter(netdev, NETDEV_EVENT_ROAMING, NULL, netdev->user_data); - - return; -failed: - l_error("Failed to properly handle the ROAM event -- submit logs!"); - netdev_connect_failed(netdev, NETDEV_RESULT_ABORTED, - MMPDU_REASON_CODE_UNSPECIFIED); - } static void netdev_send_sa_query_delay(struct l_timeout *timeout, @@ -6050,6 +5847,44 @@ static void netdev_dellink_notify(const struct ifinfomsg *ifi, int bytes) netdev_free(netdev); } +static void netdev_disable_ps_cb(struct l_genl_msg *msg, void *user_data) +{ + struct netdev *netdev = user_data; + int err = l_genl_msg_get_error(msg); + + netdev->power_save_cmd_id = 0; + + /* Can't do anything about it but inform the user */ + if (err < 0) + l_error("Failed to disable power save for ifindex %u (%s: %d)", + netdev->index, strerror(-err), err); + else + l_debug("Disabled power save for ifindex %u", netdev->index); + + WATCHLIST_NOTIFY(&netdev_watches, netdev_watch_func_t, + netdev, NETDEV_WATCH_EVENT_NEW); + netdev->events_ready = true; +} + +static bool netdev_disable_power_save(struct netdev *netdev) +{ + struct l_genl_msg *msg = l_genl_msg_new(NL80211_CMD_SET_POWER_SAVE); + uint32_t disabled = NL80211_PS_DISABLED; + + l_genl_msg_append_attr(msg, NL80211_ATTR_IFINDEX, 4, &netdev->index); + l_genl_msg_append_attr(msg, NL80211_ATTR_PS_STATE, 4, &disabled); + + netdev->power_save_cmd_id = l_genl_family_send(nl80211, msg, + netdev_disable_ps_cb, + netdev, NULL); + if (!netdev->power_save_cmd_id) { + l_error("Failed to send SET_POWER_SAVE (-EIO)"); + return false; + } + + return true; +} + static void netdev_initial_up_cb(int error, uint16_t type, const void *data, uint32_t len, void *user_data) { @@ -6082,6 +5917,12 @@ static void netdev_initial_up_cb(int error, uint16_t type, const void *data, scan_wdev_add(netdev->wdev_id); + if (wiphy_power_save_disabled(netdev->wiphy)) { + /* Wait to issue EVENT_NEW until power save is disabled */ + if (netdev_disable_power_save(netdev)) + return; + } + WATCHLIST_NOTIFY(&netdev_watches, netdev_watch_func_t, netdev, NETDEV_WATCH_EVENT_NEW); netdev->events_ready = true; @@ -6245,42 +6086,6 @@ static void netdev_get_link(struct netdev *netdev) l_free(rtmmsg); } -static void netdev_disable_ps_cb(struct l_genl_msg *msg, void *user_data) -{ - struct netdev *netdev = user_data; - int err = l_genl_msg_get_error(msg); - - netdev->power_save_cmd_id = 0; - - /* Can't do anything about it but inform the user */ - if (err < 0) - l_error("Failed to disable power save for ifindex %u (%s: %d)", - netdev->index, strerror(-err), err); - else - l_debug("Disabled power save for ifindex %u", netdev->index); - - netdev_get_link(netdev); -} - -static bool netdev_disable_power_save(struct netdev *netdev) -{ - struct l_genl_msg *msg = l_genl_msg_new(NL80211_CMD_SET_POWER_SAVE); - uint32_t disabled = NL80211_PS_DISABLED; - - l_genl_msg_append_attr(msg, NL80211_ATTR_IFINDEX, 4, &netdev->index); - l_genl_msg_append_attr(msg, NL80211_ATTR_PS_STATE, 4, &disabled); - - netdev->power_save_cmd_id = l_genl_family_send(nl80211, msg, - netdev_disable_ps_cb, - netdev, NULL); - if (!netdev->power_save_cmd_id) { - l_error("Failed to send SET_POWER_SAVE (-EIO)"); - return false; - } - - return true; -} - struct netdev *netdev_create_from_genl(struct l_genl_msg *msg, const uint8_t *set_mac) { @@ -6352,12 +6157,6 @@ struct netdev *netdev_create_from_genl(struct l_genl_msg *msg, netdev_setup_interface(netdev); - if (wiphy_power_save_disabled(wiphy)) { - /* Wait to issue GET_LINK until PS is disabled */ - if (netdev_disable_power_save(netdev)) - return netdev; - } - netdev_get_link(netdev); return netdev; diff --git a/src/netdev.h b/src/netdev.h @@ -51,6 +51,7 @@ enum netdev_event { NETDEV_EVENT_RSSI_LEVEL_NOTIFY, NETDEV_EVENT_PACKET_LOSS_NOTIFY, NETDEV_EVENT_FT_ROAMED, + NETDEV_EVENT_BEACON_LOSS_NOTIFY, }; enum netdev_watch_event { diff --git a/src/network.c b/src/network.c @@ -993,7 +993,8 @@ int network_autoconnect(struct network *network, struct scan_bss *bss) return -ENOTSUP; } - return __station_connect_network(station, network, bss); + return __station_connect_network(station, network, bss, + STATION_STATE_CONNECTING_AUTO); close_settings: network_settings_close(network); diff --git a/src/nl80211util.c b/src/nl80211util.c @@ -32,6 +32,8 @@ #include "src/nl80211util.h" #include "src/band.h" +#include "src/ie.h" +#include "src/handshake.h" #include "src/util.h" typedef bool (*attr_handler)(const void *data, uint16_t len, void *o); @@ -284,6 +286,48 @@ done: return ret; } +struct l_genl_msg *nl80211_build_deauthenticate(uint32_t ifindex, + const uint8_t addr[static 6], + uint16_t reason_code) +{ + struct l_genl_msg *msg; + + msg = l_genl_msg_new_sized(NL80211_CMD_DEAUTHENTICATE, 128); + l_genl_msg_append_attr(msg, NL80211_ATTR_IFINDEX, 4, &ifindex); + l_genl_msg_append_attr(msg, NL80211_ATTR_REASON_CODE, 2, &reason_code); + l_genl_msg_append_attr(msg, NL80211_ATTR_MAC, ETH_ALEN, addr); + + return msg; +} + +struct l_genl_msg *nl80211_build_disconnect(uint32_t ifindex, + uint16_t reason_code) +{ + struct l_genl_msg *msg; + + msg = l_genl_msg_new_sized(NL80211_CMD_DISCONNECT, 64); + l_genl_msg_append_attr(msg, NL80211_ATTR_IFINDEX, 4, &ifindex); + l_genl_msg_append_attr(msg, NL80211_ATTR_REASON_CODE, 2, &reason_code); + + return msg; +} + +struct l_genl_msg *nl80211_build_del_station(uint32_t ifindex, + const uint8_t addr[static 6], + uint16_t reason_code, + uint8_t subtype) +{ + struct l_genl_msg *msg; + + msg = l_genl_msg_new_sized(NL80211_CMD_DEL_STATION, 64); + l_genl_msg_append_attr(msg, NL80211_ATTR_IFINDEX, 4, &ifindex); + l_genl_msg_append_attr(msg, NL80211_ATTR_MAC, 6, addr); + l_genl_msg_append_attr(msg, NL80211_ATTR_MGMT_SUBTYPE, 1, &subtype); + l_genl_msg_append_attr(msg, NL80211_ATTR_REASON_CODE, 2, &reason_code); + + return msg; +} + struct l_genl_msg *nl80211_build_new_key_group(uint32_t ifindex, uint32_t cipher, uint8_t key_id, const uint8_t *key, size_t key_len, const uint8_t *ctr, @@ -317,6 +361,79 @@ struct l_genl_msg *nl80211_build_new_key_group(uint32_t ifindex, uint32_t cipher return msg; } +struct l_genl_msg *nl80211_build_new_key_pairwise(uint32_t ifindex, + uint32_t cipher, + const uint8_t addr[static 6], + const uint8_t *tk, + size_t tk_len, + uint8_t key_id) +{ + struct l_genl_msg *msg; + + msg = l_genl_msg_new_sized(NL80211_CMD_NEW_KEY, 512); + + l_genl_msg_append_attr(msg, NL80211_ATTR_KEY_DATA, tk_len, tk); + l_genl_msg_append_attr(msg, NL80211_ATTR_KEY_CIPHER, 4, &cipher); + l_genl_msg_append_attr(msg, NL80211_ATTR_MAC, ETH_ALEN, addr); + l_genl_msg_append_attr(msg, NL80211_ATTR_KEY_IDX, 1, &key_id); + l_genl_msg_append_attr(msg, NL80211_ATTR_IFINDEX, 4, &ifindex); + + return msg; +} + +struct l_genl_msg *nl80211_build_new_rx_key_pairwise(uint32_t ifindex, + uint32_t cipher, + const uint8_t addr[static 6], + const uint8_t *tk, + size_t tk_len, + uint8_t key_id) +{ + uint8_t key_mode = NL80211_KEY_NO_TX; + uint32_t key_type = NL80211_KEYTYPE_PAIRWISE; + struct l_genl_msg *msg; + + msg = l_genl_msg_new_sized(NL80211_CMD_NEW_KEY, 512); + + l_genl_msg_append_attr(msg, NL80211_ATTR_MAC, ETH_ALEN, addr); + l_genl_msg_append_attr(msg, NL80211_ATTR_IFINDEX, 4, &ifindex); + + l_genl_msg_enter_nested(msg, NL80211_ATTR_KEY); + + l_genl_msg_append_attr(msg, NL80211_KEY_DATA, tk_len, tk); + l_genl_msg_append_attr(msg, NL80211_KEY_CIPHER, 4, &cipher); + l_genl_msg_append_attr(msg, NL80211_KEY_IDX, 1, &key_id); + l_genl_msg_append_attr(msg, NL80211_KEY_MODE, 1, &key_mode); + l_genl_msg_append_attr(msg, NL80211_KEY_TYPE, 4, &key_type); + + l_genl_msg_leave_nested(msg); + + return msg; +} + +struct l_genl_msg *nl80211_build_rekey_offload(uint32_t ifindex, + const uint8_t *kek, + const uint8_t *kck, + uint64_t replay_ctr) +{ + struct l_genl_msg *msg; + + msg = l_genl_msg_new_sized(NL80211_CMD_SET_REKEY_OFFLOAD, 512); + + l_genl_msg_append_attr(msg, NL80211_ATTR_IFINDEX, 4, &ifindex); + + l_genl_msg_enter_nested(msg, NL80211_ATTR_REKEY_DATA); + l_genl_msg_append_attr(msg, NL80211_REKEY_DATA_KEK, + NL80211_KEK_LEN, kek); + l_genl_msg_append_attr(msg, NL80211_REKEY_DATA_KCK, + NL80211_KCK_LEN, kck); + l_genl_msg_append_attr(msg, NL80211_REKEY_DATA_REPLAY_CTR, + NL80211_REPLAY_CTR_LEN, &replay_ctr); + + l_genl_msg_leave_nested(msg); + + return msg; +} + static struct l_genl_msg *nl80211_build_set_station(uint32_t ifindex, const uint8_t *addr, struct nl80211_sta_flag_update *flags) @@ -572,3 +689,41 @@ int nl80211_parse_supported_frequencies(struct l_genl_attr *band_freqs, return 0; } + +void nl80211_append_rsn_attributes(struct l_genl_msg *msg, + struct handshake_state *hs) +{ + uint32_t nl_cipher; + uint32_t nl_akm; + uint32_t wpa_version; + + nl_cipher = ie_rsn_cipher_suite_to_cipher(hs->pairwise_cipher); + L_WARN_ON(!nl_cipher); + l_genl_msg_append_attr(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE, + 4, &nl_cipher); + + nl_cipher = ie_rsn_cipher_suite_to_cipher(hs->group_cipher); + L_WARN_ON(!nl_cipher); + l_genl_msg_append_attr(msg, NL80211_ATTR_CIPHER_SUITE_GROUP, + 4, &nl_cipher); + + if (hs->mfp) { + uint32_t use_mfp = NL80211_MFP_REQUIRED; + + l_genl_msg_append_attr(msg, NL80211_ATTR_USE_MFP, 4, &use_mfp); + } + + nl_akm = ie_rsn_akm_suite_to_akm(hs->akm_suite); + L_WARN_ON(!nl_akm); + l_genl_msg_append_attr(msg, NL80211_ATTR_AKM_SUITES, 4, &nl_akm); + + if (IE_AKM_IS_SAE(hs->akm_suite)) + wpa_version = NL80211_WPA_VERSION_3; + else if (hs->wpa_ie) + wpa_version = NL80211_WPA_VERSION_1; + else + wpa_version = NL80211_WPA_VERSION_2; + + l_genl_msg_append_attr(msg, NL80211_ATTR_WPA_VERSIONS, + 4, &wpa_version); +} diff --git a/src/nl80211util.h b/src/nl80211util.h @@ -25,14 +25,43 @@ struct band_chandef; struct scan_freq_set; struct band_freq_attrs; +struct handshake_state; int nl80211_parse_attrs(struct l_genl_msg *msg, int tag, ...); +struct l_genl_msg *nl80211_build_deauthenticate(uint32_t ifindex, + const uint8_t addr[static 6], + uint16_t reason_code); +struct l_genl_msg *nl80211_build_disconnect(uint32_t ifindex, + uint16_t reason_code); + +struct l_genl_msg *nl80211_build_del_station(uint32_t ifindex, + const uint8_t addr[static 6], + uint16_t reason_code, + uint8_t subtype); + struct l_genl_msg *nl80211_build_new_key_group(uint32_t ifindex, uint32_t cipher, uint8_t key_id, const uint8_t *key, size_t key_len, const uint8_t *ctr, size_t ctr_len, const uint8_t *addr); +struct l_genl_msg *nl80211_build_new_key_pairwise(uint32_t ifindex, + uint32_t cipher, + const uint8_t addr[static 6], + const uint8_t *tk, + size_t tk_len, + uint8_t key_id); +struct l_genl_msg *nl80211_build_new_rx_key_pairwise(uint32_t ifindex, + uint32_t cipher, + const uint8_t addr[static 6], + const uint8_t *tk, + size_t tk_len, + uint8_t key_id); + +struct l_genl_msg *nl80211_build_rekey_offload(uint32_t ifindex, + const uint8_t *kek, + const uint8_t *kck, + uint64_t replay_ctr); struct l_genl_msg *nl80211_build_set_station_authorized(uint32_t ifindex, const uint8_t *addr); @@ -62,3 +91,6 @@ int nl80211_parse_supported_frequencies(struct l_genl_attr *band_freqs, struct scan_freq_set *supported_list, struct band_freq_attrs *list, size_t num_channels); + +void nl80211_append_rsn_attributes(struct l_genl_msg *msg, + struct handshake_state *hs); diff --git a/src/offchannel.c b/src/offchannel.c @@ -43,6 +43,7 @@ struct offchannel_info { uint32_t roc_cmd_id; uint64_t roc_cookie; + uint64_t early_cookie; offchannel_started_cb_t started; offchannel_destroy_cb_t destroy; @@ -57,12 +58,12 @@ struct offchannel_info { static struct l_genl_family *nl80211; static struct l_queue *offchannel_list; -static bool match_wdev(const void *a, const void *user_data) +static bool match_id(const void *a, const void *user_data) { const struct offchannel_info *info = a; - const uint64_t *wdev_id = user_data; + uint32_t id = L_PTR_TO_UINT(user_data); - return info->wdev_id == *wdev_id; + return id == info->work.id; } static void offchannel_cancel_roc(struct offchannel_info *info) @@ -98,9 +99,20 @@ static void offchannel_roc_cb(struct l_genl_msg *msg, void *user_data) goto work_done; } - /* This request was cancelled, and ROC needs to be cancelled */ + /* + * If the request was cancelled prior to kernel sending the ACK, + * cancel now. + * + * If the ROC event came before the ACK, call back now since the + * callback was skipped in the notify event. There is the potential that + * an external process issued the ROC, but if the cookies don't match + * here we can be sure it wasn't for us. In this case the notify event + * will behave as normal and call started(). + */ if (info->needs_cancel) offchannel_cancel_roc(info); + else if (info->early_cookie == info->roc_cookie && info->started) + info->started(info->user_data); return; @@ -191,7 +203,8 @@ void offchannel_cancel(uint64_t wdev_id, uint32_t id) else if (ret == false) goto work_done; - info = l_queue_find(offchannel_list, match_wdev, &wdev_id); + + info = l_queue_find(offchannel_list, match_id, L_UINT_TO_PTR(id)); if (!info) return; @@ -245,7 +258,8 @@ work_done: static void offchannel_mlme_notify(struct l_genl_msg *msg, void *user_data) { - struct offchannel_info *info; + struct offchannel_info *info = NULL; + const struct l_queue_entry *e; uint64_t wdev_id; uint64_t cookie; uint8_t cmd; @@ -261,12 +275,35 @@ static void offchannel_mlme_notify(struct l_genl_msg *msg, void *user_data) NL80211_ATTR_UNSPEC) < 0) return; - info = l_queue_find(offchannel_list, match_wdev, &wdev_id); - if (!info) - return; + for (e = l_queue_get_entries(offchannel_list); e; e = e->next) { + struct offchannel_info *i = e->data; - /* ROC must have been started elsewhere, not by IWD */ - if (info->roc_cookie != cookie) + if (i->wdev_id != wdev_id) + continue; + + /* Normal case, kernel has ACK'ed */ + if (i->roc_cookie == cookie) { + info = i; + break; + } + + /* + * If there is a pending request and no ACK yet this could be: + * - an early event coming prior to the ACK + * - an event coming from an external ROC request (we just + * happened to have also sent an ROC request). + * + * We can't tell where the event originated until we recieve our + * ACK so set early_cookie to track it. + */ + if (i->roc_cmd_id != 0 && l_genl_family_request_sent(nl80211, + i->roc_cmd_id)) { + i->early_cookie = cookie; + return; + } + } + + if (!info) return; switch (cmd) { diff --git a/src/sae.c b/src/sae.c @@ -511,7 +511,29 @@ static struct l_ecc_point *sae_compute_pwe(const struct l_ecc_curve *curve, return NULL; } - pwe = l_ecc_point_from_data(curve, !is_odd + 2, x, bytes); + /* + * The 802.11 spec requires the point be solved unambiguously (since + * solving for Y results in two solutions). The correct Y value + * is chosen based on the LSB of the pwd-seed: + * + * if (LSB(y) == LSB(pwd-seed)) + * then + * PWE = (x, y) + * else + * PWE = (x, p-y) + * + * The ELL API (somewhat hidden from view here) automatically + * performs a subtraction (P - Y) when: + * - Y is even and BIT1 + * - Y is odd and BIT0 + * + * So we choose the point type which matches the parity of + * pwd-seed. This means a subtraction will be performed (P - Y) + * if the parity of pwd-seed and the computed Y do not match. + */ + pwe = l_ecc_point_from_data(curve, + is_odd ? L_ECC_POINT_TYPE_COMPRESSED_BIT1 : + L_ECC_POINT_TYPE_COMPRESSED_BIT0, x, bytes); if (!pwe) l_error("computing y failed, was x quadratic residue?"); diff --git a/src/scan.c b/src/scan.c @@ -53,6 +53,7 @@ #include "src/scan.h" /* User configurable options */ +static double RANK_2G_FACTOR; static double RANK_5G_FACTOR; static double RANK_6G_FACTOR; static uint32_t SCAN_MAX_INTERVAL; @@ -106,6 +107,8 @@ struct scan_request { * and save these since there may be additional scan commands to run. */ struct scan_freq_set *freqs_scanned; + /* Entire list of frequencies to scan */ + struct scan_freq_set *scan_freqs; }; struct scan_context { @@ -169,6 +172,7 @@ static void scan_request_free(struct wiphy_radio_work_item *item) l_queue_destroy(sr->cmds, (l_queue_destroy_func_t) l_genl_msg_unref); scan_freq_set_free(sr->freqs_scanned); + scan_freq_set_free(sr->scan_freqs); l_free(sr); } @@ -340,20 +344,6 @@ static bool scan_mac_address_randomization_is_disabled(void) return disabled; } -static struct scan_freq_set *scan_get_allowed_freqs(struct scan_context *sc) -{ - struct scan_freq_set *allowed = scan_freq_set_new(); - - scan_freq_set_merge(allowed, wiphy_get_supported_freqs(sc->wiphy)); - - if (!wiphy_constrain_freq_set(sc->wiphy, allowed)) { - scan_freq_set_free(allowed); - allowed = NULL; - } - - return allowed; -} - static struct l_genl_msg *scan_build_cmd(struct scan_context *sc, bool ignore_flush_flag, bool is_passive, const struct scan_parameters *params, @@ -581,22 +571,25 @@ static void scan_cmds_add(struct scan_request *sr, struct scan_context *sc, bool passive, const struct scan_parameters *params) { + uint32_t bands = BAND_FREQ_2_4_GHZ | BAND_FREQ_5_GHZ | BAND_FREQ_6_GHZ; unsigned int i; struct scan_freq_set *subsets[2] = { 0 }; - struct scan_freq_set *allowed = scan_get_allowed_freqs(sc); const struct scan_freq_set *supported = wiphy_get_supported_freqs(sc->wiphy); /* - * If 6GHz is not possible, or already allowed, or the frequencies are - * explicit don't break up the request. + * No frequencies, just include the entire supported list and let the + * kernel filter out any disabled frequencies */ - if (!(scan_freq_set_get_bands(supported) & BAND_FREQ_6_GHZ) || - (scan_freq_set_get_bands(allowed) & BAND_FREQ_6_GHZ) || - params->freqs) { - scan_freq_set_free(allowed); + if (!params->freqs) + sr->scan_freqs = scan_freq_set_clone(supported, bands); + else + sr->scan_freqs = scan_freq_set_clone(params->freqs, bands); + + /* If 6GHz is not possible or already allowed don't split the request */ + if (wiphy_band_is_disabled(sc->wiphy, BAND_FREQ_6_GHZ) != 1) { scan_build_next_cmd(sr->cmds, sc, passive, - params, params->freqs); + params, sr->scan_freqs); return; } @@ -612,10 +605,8 @@ static void scan_cmds_add(struct scan_request *sr, struct scan_context *sc, * extra 6GHz-only passive scan can be appended to this request * at that time. */ - subsets[0] = scan_freq_set_clone(allowed, BAND_FREQ_2_4_GHZ); - subsets[1] = scan_freq_set_clone(allowed, BAND_FREQ_5_GHZ); - - scan_freq_set_free(allowed); + subsets[0] = scan_freq_set_clone(sr->scan_freqs, BAND_FREQ_2_4_GHZ); + subsets[1] = scan_freq_set_clone(sr->scan_freqs, BAND_FREQ_5_GHZ); for(i = 0; i < L_ARRAY_SIZE(subsets); i++) { if (!scan_freq_set_isempty(subsets[i])) @@ -993,9 +984,43 @@ static void scan_periodic_destroy(void *user_data) sc->sp.id = 0; } +static struct scan_freq_set *scan_periodic_get_freqs(struct scan_context *sc) +{ + uint32_t band_mask = 0; + struct scan_freq_set *freqs; + const struct scan_freq_set *supported = + wiphy_get_supported_freqs(sc->wiphy); + + if (RANK_2G_FACTOR) + band_mask |= BAND_FREQ_2_4_GHZ; + if (RANK_5G_FACTOR) + band_mask |= BAND_FREQ_5_GHZ; + if (RANK_6G_FACTOR) + band_mask |= BAND_FREQ_6_GHZ; + + freqs = scan_freq_set_clone(supported, band_mask); + if (scan_freq_set_isempty(freqs)) { + scan_freq_set_free(freqs); + freqs = NULL; + } + + return freqs; +} + static bool scan_periodic_queue(struct scan_context *sc) { struct scan_parameters params = {}; + struct scan_freq_set *freqs = scan_periodic_get_freqs(sc); + + /* + * If this happens its due to the user disabling all bands. This will + * cause IWD to never issue another periodic scan so warn the user of + * this. + */ + if (L_WARN_ON(!freqs)) + return false; + + params.freqs = freqs; if (sc->sp.needs_active_scan && known_networks_has_hidden()) { params.randomize_mac_addr_hint = true; @@ -1013,6 +1038,8 @@ static bool scan_periodic_queue(struct scan_context *sc) scan_periodic_notify, sc, scan_periodic_destroy); + scan_freq_set_free(freqs); + return sc->sp.id != 0; } @@ -1634,6 +1661,9 @@ static void scan_bss_compute_rank(struct scan_bss *bss) rank = (double)bss->data_rate / max_rate * USHRT_MAX; + if (bss->frequency < 3000) + rank *= RANK_2G_FACTOR; + /* Prefer 5G networks over 2.4G and 6G */ if (bss->frequency >= 4900 && bss->frequency < 5900) rank *= RANK_5G_FACTOR; @@ -1914,9 +1944,8 @@ static void scan_wiphy_watch(struct wiphy *wiphy, struct scan_request *sr = NULL; struct l_genl_msg *msg = NULL; struct scan_parameters params = { 0 }; - struct scan_freq_set *freqs_6ghz; - struct scan_freq_set *allowed; - bool allow_6g; + _auto_(scan_freq_set_free) struct scan_freq_set *freqs_6ghz = NULL; + int disabled; /* Only care about completed regulatory dumps */ if (event != WIPHY_STATE_WATCH_EVENT_REGDOM_DONE) @@ -1930,39 +1959,33 @@ static void scan_wiphy_watch(struct wiphy *wiphy, if (!sr) return; - allowed = scan_get_allowed_freqs(sc); - allow_6g = scan_freq_set_get_bands(allowed) & BAND_FREQ_6_GHZ; - /* * This update did not allow 6GHz, or the original request was * not expecting 6GHz. The periodic scan should now be ended. */ - if (!allow_6g || !sr->split) { + disabled = wiphy_band_is_disabled(wiphy, BAND_FREQ_6_GHZ); + if (scan_freq_set_get_bands(sr->freqs_scanned) & BAND_FREQ_6_GHZ || + disabled == 1 || !sr->split) { scan_get_results(sc, sr, sr->freqs_scanned); - goto free_allowed; + return; } + freqs_6ghz = scan_freq_set_clone(sr->scan_freqs, BAND_FREQ_6_GHZ); + /* * At this point we know there is an ongoing periodic scan. * Create a new 6GHz passive scan request and append to the * command list */ - freqs_6ghz = scan_freq_set_clone(allowed, BAND_FREQ_6_GHZ); - msg = scan_build_cmd(sc, false, true, &params, freqs_6ghz); l_queue_push_tail(sr->cmds, msg); - scan_freq_set_free(freqs_6ghz); - /* * If this periodic scan is at the top of the queue, continue * running it. */ if (l_queue_peek_head(sc->requests) == sr) start_next_scan_request(&sr->work); - -free_allowed: - scan_freq_set_free(allowed); } static struct scan_context *scan_context_new(uint64_t wdev_id) @@ -2306,6 +2329,37 @@ bool scan_get_firmware_scan(uint64_t wdev_id, scan_notify_func_t notify, return true; } +double scan_get_band_rank_modifier(enum band_freq band) +{ + const struct l_settings *config = iwd_get_config(); + double modifier; + char *str, *str_legacy; + + switch (band) { + case BAND_FREQ_2_4_GHZ: + str = "BandModifier2_4GHz"; + str_legacy = "BandModifier2_4Ghz"; + break; + case BAND_FREQ_5_GHZ: + str = "BandModifier5GHz"; + str_legacy = "BandModifier5Ghz"; + break; + case BAND_FREQ_6_GHZ: + str = "BandModifier6GHz"; + str_legacy = "BandModifier6Ghz"; + break; + default: + l_warn("Unhandled band %u", band); + return 0.0; + } + + if (!l_settings_get_double(config, "Rank", str, &modifier) && + !l_settings_get_double(config, "Rank", str_legacy, &modifier)) + modifier = 1.0; + + return modifier; +} + bool scan_wdev_add(uint64_t wdev_id) { struct scan_context *sc; @@ -2355,13 +2409,9 @@ static int scan_init(void) scan_contexts = l_queue_new(); - if (!l_settings_get_double(config, "Rank", "BandModifier5Ghz", - &RANK_5G_FACTOR)) - RANK_5G_FACTOR = 1.0; - - if (!l_settings_get_double(config, "Rank", "BandModifier6Ghz", - &RANK_6G_FACTOR)) - RANK_6G_FACTOR = 1.0; + RANK_2G_FACTOR = scan_get_band_rank_modifier(BAND_FREQ_2_4_GHZ); + RANK_5G_FACTOR = scan_get_band_rank_modifier(BAND_FREQ_5_GHZ); + RANK_6G_FACTOR = scan_get_band_rank_modifier(BAND_FREQ_6_GHZ); if (!l_settings_get_uint(config, "Scan", "InitialPeriodicScanInterval", &SCAN_INIT_INTERVAL)) diff --git a/src/scan.h b/src/scan.h @@ -29,6 +29,7 @@ struct p2p_beacon; struct mmpdu_header; struct wiphy; enum security; +enum band_freq; enum scan_state { SCAN_STATE_NOT_RUNNING, @@ -170,5 +171,7 @@ struct scan_bss *scan_bss_new_from_probe_req(const struct mmpdu_header *mpdu, size_t body_len, uint32_t frequency, int rssi); +double scan_get_band_rank_modifier(enum band_freq band); + bool scan_wdev_add(uint64_t wdev_id); bool scan_wdev_remove(uint64_t wdev_id); diff --git a/src/station.c b/src/station.c @@ -73,6 +73,7 @@ static bool supports_arp_evict_nocarrier; static bool supports_ndisc_evict_nocarrier; static struct watchlist event_watches; static uint32_t known_networks_watch; +static uint32_t allowed_bands; struct station { enum station_state state; @@ -122,6 +123,8 @@ struct station { struct wiphy_radio_work_item ft_work; + uint64_t last_roam_scan; + bool preparing_roam : 1; bool roam_scan_full : 1; bool signal_low : 1; @@ -147,15 +150,18 @@ struct roam_bss { uint8_t addr[6]; uint16_t rank; int32_t signal_strength; + bool ft_failed: 1; }; -static struct roam_bss *roam_bss_from_scan_bss(const struct scan_bss *bss) +static struct roam_bss *roam_bss_from_scan_bss(const struct scan_bss *bss, + uint16_t rank) { struct roam_bss *rbss = l_new(struct roam_bss, 1); memcpy(rbss->addr, bss->addr, 6); - rbss->rank = bss->rank; + rbss->rank = rank; rbss->signal_strength = bss->signal_strength; + rbss->ft_failed = false; return rbss; } @@ -276,9 +282,6 @@ static int station_autoconnect_next(struct station *station) r = network_autoconnect(network, bss); if (!r) { - station_enter_state(station, - STATION_STATE_CONNECTING_AUTO); - if (station->quick_scan_id) { scan_cancel(netdev_get_wdev_id(station->netdev), station->quick_scan_id); @@ -1325,6 +1328,21 @@ static bool station_needs_hidden_network_scan(struct station *station) return !l_queue_isempty(station->hidden_bss_list_sorted); } +static struct scan_freq_set *station_get_allowed_freqs(struct station *station) +{ + const struct scan_freq_set *supported = + wiphy_get_supported_freqs(station->wiphy); + struct scan_freq_set *allowed = scan_freq_set_clone(supported, + allowed_bands); + + if (scan_freq_set_isempty(allowed)) { + scan_freq_set_free(allowed); + allowed = NULL; + } + + return allowed; +} + static uint32_t station_scan_trigger(struct station *station, struct scan_freq_set *freqs, scan_trigger_func_t triggered, @@ -1410,6 +1428,7 @@ static void station_quick_scan_destroy(void *userdata) static int station_quick_scan_trigger(struct station *station) { _auto_(scan_freq_set_free) struct scan_freq_set *known_freq_set = NULL; + _auto_(scan_freq_set_free) struct scan_freq_set *allowed = NULL; bool known_6ghz; if (wiphy_regdom_is_updating(station->wiphy)) { @@ -1432,16 +1451,19 @@ static int station_quick_scan_trigger(struct station *station) * this since its so limited, so return an error which will fall back to * full autoconnect. */ - if (wiphy_get_supported_bands(station->wiphy) & BAND_FREQ_6_GHZ && - wiphy_band_is_disabled(station->wiphy, - BAND_FREQ_6_GHZ) && + if (wiphy_band_is_disabled(station->wiphy, BAND_FREQ_6_GHZ) == 1 && wiphy_country_is_unknown(station->wiphy) && known_6ghz) return -ENOTSUP; - if (!wiphy_constrain_freq_set(station->wiphy, known_freq_set)) { + allowed = station_get_allowed_freqs(station); + if (L_WARN_ON(!allowed)) + return -ENOTSUP; + + scan_freq_set_constrain(known_freq_set, allowed); + + if (scan_freq_set_isempty(known_freq_set)) return -ENOTSUP; - } station->quick_scan_id = station_scan_trigger(station, known_freq_set, @@ -1695,6 +1717,7 @@ static void station_roam_state_clear(struct station *station) station->signal_low = false; station->roam_min_time.tv_sec = 0; station->netconfig_after_roam = false; + station->last_roam_scan = 0; if (station->roam_scan_id) scan_cancel(netdev_get_wdev_id(station->netdev), @@ -1708,6 +1731,9 @@ static void station_roam_state_clear(struct station *station) l_queue_clear(station->roam_bss_list, l_free); ft_clear_authentications(netdev_get_ifindex(station->netdev)); + + if (station->ft_work.id) + wiphy_radio_work_done(station->wiphy, station->ft_work.id); } static void station_reset_connection_state(struct station *station) @@ -2046,6 +2072,20 @@ static void station_netconfig_event_handler(enum netconfig_event event, } } +static bool netconfig_after_roam(struct station *station) +{ + const struct network *network = station_get_connected_network(station); + + /* Netconfig was reset which frees all settings, reload now */ + if (!netconfig_load_settings(station->netconfig, + network_get_settings(network))) + return false; + + return netconfig_configure(station->netconfig, + station_netconfig_event_handler, + station); +} + static void station_roamed(struct station *station) { station->roam_scan_full = false; @@ -2077,9 +2117,7 @@ static void station_roamed(struct station *station) /* Re-enable netconfig if it never finished on the last BSS */ if (station->netconfig_after_roam) { station->netconfig_after_roam = false; - L_WARN_ON(!netconfig_configure(station->netconfig, - station_netconfig_event_handler, - station)); + L_WARN_ON(!netconfig_after_roam(station)); } else station_enter_state(station, STATION_STATE_CONNECTED); } @@ -2117,9 +2155,7 @@ static void station_roam_failed(struct station *station) /* Re-enable netconfig if needed, even on a failed roam */ if (station->netconfig_after_roam) { station->netconfig_after_roam = false; - L_WARN_ON(!netconfig_configure(station->netconfig, - station_netconfig_event_handler, - station)); + L_WARN_ON(!netconfig_after_roam(station)); } /* @@ -2183,10 +2219,14 @@ static int station_transition_reassociate(struct station *station, if (ret < 0) return ret; + l_debug(""); + station->connected_bss = bss; station->preparing_roam = false; station_enter_state(station, STATION_STATE_ROAMING); + station_debug_event(station, "reassoc-roam"); + return 0; } @@ -2278,34 +2318,60 @@ static void station_transition_start(struct station *station); static bool station_ft_work_ready(struct wiphy_radio_work_item *item) { struct station *station = l_container_of(item, struct station, ft_work); - struct roam_bss *rbss = l_queue_pop_head(station->roam_bss_list); - struct scan_bss *bss = network_bss_find_by_addr( - station->connected_network, rbss->addr); + _auto_(l_free) struct roam_bss *rbss = l_queue_pop_head( + station->roam_bss_list); + struct scan_bss *bss; int ret; - l_free(rbss); - /* Very unlikely, but the BSS could have gone away */ + bss = network_bss_find_by_addr(station->connected_network, rbss->addr); if (!bss) goto try_next; ret = ft_associate(netdev_get_ifindex(station->netdev), bss->addr); - if (ret == -ENOENT) { + switch (ret) { + case MMPDU_STATUS_CODE_INVALID_PMKID: + /* + * Re-insert removing FT from the ranking (scan_bss does not + * take into account FT, so we can use that rank directly). + * If the BSS is still the best reassociation will be used, + * otherwise we'll try more FT candidates that are better ranked + */ + rbss->rank = bss->rank; + rbss->ft_failed = true; + + l_debug("Re-inserting BSS "MAC" using reassociation, rank: %u", + MAC_STR(rbss->addr), rbss->rank); + + l_queue_insert(station->roam_bss_list, rbss, + roam_bss_rank_compare, NULL); + + station_debug_event(station, "ft-fallback-to-reassoc"); + + station_transition_start(station); + l_steal_ptr(rbss); + break; + case -ENOENT: station_debug_event(station, "ft-roam-failed"); try_next: station_transition_start(station); - return true; - } else if (ret < 0) - goto assoc_failed; + break; + case 0: + station->connected_bss = bss; + station->preparing_roam = false; + station_enter_state(station, STATION_STATE_FT_ROAMING); - station->connected_bss = bss; - station->preparing_roam = false; - station_enter_state(station, STATION_STATE_FT_ROAMING); + station_debug_event(station, "ft-roam"); - return true; + break; + default: + if (ret > 0) + goto try_next; + + station_roam_failed(station); + break; + } -assoc_failed: - station_roam_failed(station); return true; } @@ -2363,7 +2429,8 @@ done: } static bool station_try_next_transition(struct station *station, - struct scan_bss *bss) + struct scan_bss *bss, + bool no_ft) { struct handshake_state *hs = netdev_get_handshake(station->netdev); struct network *connected = station->connected_network; @@ -2378,7 +2445,7 @@ static bool station_try_next_transition(struct station *station, station->ap_directed_roaming = false; /* Can we use Fast Transition? */ - if (station_can_fast_transition(hs, bss)) + if (station_can_fast_transition(hs, bss) && !no_ft) return station_fast_transition(station, bss); /* Non-FT transition */ @@ -2430,6 +2497,7 @@ static void station_transition_start(struct station *station) { struct roam_bss *rbss; bool roaming = false; + bool connected = (station->state == STATION_STATE_CONNECTED); /* * For each failed attempt pop the BSS leaving the head of the queue @@ -2439,7 +2507,8 @@ static void station_transition_start(struct station *station) struct scan_bss *bss = network_bss_find_by_addr( station->connected_network, rbss->addr); - roaming = station_try_next_transition(station, bss); + roaming = station_try_next_transition(station, bss, + rbss->ft_failed); if (roaming) break; @@ -2457,7 +2526,7 @@ static void station_transition_start(struct station *station) * still should roam in this case but need to restart netconfig once the * roam is finished. */ - if (station->netconfig && station->state != STATION_STATE_CONNECTED) { + if (station->netconfig && !connected) { netconfig_reset(station->netconfig); station->netconfig_after_roam = true; } @@ -2595,7 +2664,7 @@ static bool station_roam_scan_notify(int err, struct l_queue *bss_list, */ station_update_roam_bss(station, bss); - rbss = roam_bss_from_scan_bss(bss); + rbss = roam_bss_from_scan_bss(bss, rank); l_queue_insert(station->roam_bss_list, rbss, roam_bss_rank_compare, NULL); @@ -2635,6 +2704,11 @@ static int station_roam_scan(struct station *station, struct scan_freq_set *freq_set) { struct scan_parameters params = { .freqs = freq_set, .flush = true }; + _auto_(scan_freq_set_free) struct scan_freq_set *allowed = + station_get_allowed_freqs(station); + + if (L_WARN_ON(!allowed)) + return -ENOTSUP; l_debug("ifindex: %u", netdev_get_ifindex(station->netdev)); @@ -2645,8 +2719,16 @@ static int station_roam_scan(struct station *station, params.ssid_len = strlen(ssid); } - if (!freq_set) + if (!freq_set) { station->roam_scan_full = true; + params.freqs = allowed; + } else + scan_freq_set_constrain(freq_set, allowed); + + if (L_WARN_ON(scan_freq_set_isempty(params.freqs))) + return -ENOTSUP; + + station->last_roam_scan = l_time_now(); station->roam_scan_id = scan_active_full(netdev_get_wdev_id(station->netdev), &params, @@ -3016,7 +3098,7 @@ static bool station_try_next_bss(struct station *station) return false; ret = __station_connect_network(station, station->connected_network, - next); + next, station->state); if (ret < 0) return false; @@ -3267,10 +3349,13 @@ static void station_disconnect_event(struct station *station, void *event_data) l_warn("Unexpected disconnect event"); } -#define STATION_PKT_LOSS_THRESHOLD 10 +#define STATION_PKT_LOSS_THRESHOLD 10 +#define LOSS_ROAM_RATE_LIMIT 2 static void station_packets_lost(struct station *station, uint32_t num_pkts) { + uint64_t elapsed; + l_debug("Packets lost event: %u", num_pkts); if (num_pkts < STATION_PKT_LOSS_THRESHOLD) @@ -3281,9 +3366,42 @@ static void station_packets_lost(struct station *station, uint32_t num_pkts) station_debug_event(station, "packet-loss-roam"); + elapsed = l_time_diff(station->last_roam_scan, l_time_now()); + + /* + * If we just issued a roam scan, delay the roam to avoid constant + * scanning. + */ + if (LOSS_ROAM_RATE_LIMIT > l_time_to_secs(elapsed)) { + l_debug("Too many roam attempts in %u second timeframe, " + "delaying roam", LOSS_ROAM_RATE_LIMIT); + + if (station->roam_trigger_timeout) + return; + + station_roam_timeout_rearm(station, LOSS_ROAM_RATE_LIMIT); + + return; + } + station_start_roam(station); } +static void station_beacon_lost(struct station *station) +{ + l_debug("Beacon lost event"); + + if (station_cannot_roam(station)) + return; + + station_debug_event(station, "beacon-loss-roam"); + + if (station->roam_trigger_timeout) + return; + + station_roam_timeout_rearm(station, LOSS_ROAM_RATE_LIMIT); +} + static void station_netdev_event(struct netdev *netdev, enum netdev_event event, void *event_data, void *user_data) { @@ -3328,11 +3446,14 @@ static void station_netdev_event(struct netdev *netdev, enum netdev_event event, station_roamed(station); break; + case NETDEV_EVENT_BEACON_LOSS_NOTIFY: + station_beacon_lost(station); + break; } } int __station_connect_network(struct station *station, struct network *network, - struct scan_bss *bss) + struct scan_bss *bss, enum station_state state) { struct handshake_state *hs; int r; @@ -3359,6 +3480,9 @@ int __station_connect_network(struct station *station, struct network *network, station->connected_bss = bss; station->connected_network = network; + if (station->state != state) + station_enter_state(station, state); + return 0; } @@ -3372,7 +3496,8 @@ static void station_disconnect_onconnect_cb(struct netdev *netdev, bool success, err = __station_connect_network(station, station->connect_pending_network, - station->connect_pending_bss); + station->connect_pending_bss, + STATION_STATE_CONNECTING); station->connect_pending_network = NULL; station->connect_pending_bss = NULL; @@ -3385,8 +3510,6 @@ static void station_disconnect_onconnect_cb(struct netdev *netdev, bool success, #endif return; } - - station_enter_state(station, STATION_STATE_CONNECTING); } static void station_disconnect_onconnect(struct station *station, @@ -3450,12 +3573,11 @@ void station_connect_network(struct station *station, struct network *network, return; } - err = __station_connect_network(station, network, bss); + err = __station_connect_network(station, network, bss, + STATION_STATE_CONNECTING); if (err < 0) goto error; - station_enter_state(station, STATION_STATE_CONNECTING); - station->connect_pending = l_dbus_message_ref(message); station_set_autoconnect(station, true); @@ -3588,6 +3710,7 @@ static struct l_dbus_message *station_dbus_connect_hidden_network( }; const char *ssid; struct network *network; + _auto_(scan_freq_set_free) struct scan_freq_set *allowed = NULL; l_debug(""); @@ -3638,6 +3761,11 @@ not_hidden: return dbus_error_not_hidden(message); } + allowed = station_get_allowed_freqs(station); + if (L_WARN_ON(!allowed)) + return dbus_error_not_supported(message); + + params.freqs = allowed; params.ssid = (const uint8_t *)ssid; params.ssid_len = strlen(ssid); @@ -3663,7 +3791,8 @@ static void station_disconnect_reconnect_cb(struct netdev *netdev, bool success, struct station *station = user_data; if (__station_connect_network(station, station->connected_network, - station->connected_bss) < 0) + station->connected_bss, + STATION_STATE_ROAMING) < 0) station_disassociated(station); } @@ -4261,39 +4390,67 @@ int station_hide_network(struct station *station, struct network *network) return 0; } -static void station_add_one_freq(uint32_t freq, void *user_data) +static void station_add_2_4ghz_freq(uint32_t freq, void *user_data) { - struct station *station = user_data; + struct scan_freq_set *set = user_data; - if (freq > 3000) - scan_freq_set_add(station->scan_freqs_order[1], freq); - else if (!scan_freq_set_contains(station->scan_freqs_order[0], freq)) - scan_freq_set_add(station->scan_freqs_order[2], freq); + /* exclude social channels added in initial scan request */ + if (freq < 3000 && freq != 2412 && freq != 2437 && freq != 2462) + scan_freq_set_add(set, freq); } static void station_fill_scan_freq_subsets(struct station *station) { const struct scan_freq_set *supported = - wiphy_get_supported_freqs(station->wiphy); + wiphy_get_supported_freqs(station->wiphy); + unsigned int subset_idx = 0; /* * Scan the 2.4GHz "social channels" first, 5GHz second, if supported, * all other 2.4GHz channels last. To be refined as needed. */ - station->scan_freqs_order[0] = scan_freq_set_new(); - scan_freq_set_add(station->scan_freqs_order[0], 2412); - scan_freq_set_add(station->scan_freqs_order[0], 2437); - scan_freq_set_add(station->scan_freqs_order[0], 2462); - - station->scan_freqs_order[1] = scan_freq_set_new(); - station->scan_freqs_order[2] = scan_freq_set_new(); - scan_freq_set_foreach(supported, station_add_one_freq, station); - - if (scan_freq_set_isempty(station->scan_freqs_order[1])) { - scan_freq_set_free(station->scan_freqs_order[1]); - station->scan_freqs_order[1] = station->scan_freqs_order[2]; - station->scan_freqs_order[2] = NULL; + if (allowed_bands & BAND_FREQ_2_4_GHZ) { + station->scan_freqs_order[subset_idx] = scan_freq_set_new(); + scan_freq_set_add(station->scan_freqs_order[subset_idx], 2412); + scan_freq_set_add(station->scan_freqs_order[subset_idx], 2437); + scan_freq_set_add(station->scan_freqs_order[subset_idx], 2462); + subset_idx++; + } + + /* + * TODO: It may might sense to split up 5 and 6ghz into separate subsets + * since the channel set is so large. + */ + if (allowed_bands & (BAND_FREQ_5_GHZ | BAND_FREQ_6_GHZ)) { + uint32_t mask = allowed_bands & + (BAND_FREQ_5_GHZ | BAND_FREQ_6_GHZ); + struct scan_freq_set *set = scan_freq_set_clone(supported, + mask); + + /* 5/6ghz didn't add any frequencies */ + if (scan_freq_set_isempty(set)) { + scan_freq_set_free(set); + } else + station->scan_freqs_order[subset_idx++] = set; } + + /* Add remaining 2.4ghz channels to subset */ + if (allowed_bands & BAND_FREQ_2_4_GHZ) { + station->scan_freqs_order[subset_idx] = scan_freq_set_new(); + scan_freq_set_foreach(supported, station_add_2_4ghz_freq, + station->scan_freqs_order[subset_idx]); + } + + /* + * This has the unintended consequence of allowing DBus scans to + * scan the entire spectrum rather than cause IWD to be completely + * non-functional. Rather than prevent DBus scans from working at all + * print a warning here. + */ + if (station->scan_freqs_order[0] == NULL) + l_warn("All supported bands were disabled by user! IWD will not" + " function as expected"); + } static void station_wiphy_watch(struct wiphy *wiphy, @@ -4309,7 +4466,7 @@ static void station_wiphy_watch(struct wiphy *wiphy, /* * The only state that requires special handling is for * quick scans since the previous quick scan was delayed until - * the regulatory domain updated. Try again in case 6Ghz is now + * the regulatory domain updated. Try again in case 6GHz is now * unlocked (unlikely), or advance to full autoconnect. Just in * case this update came during a quick scan, ignore it. */ @@ -4637,7 +4794,7 @@ static bool station_force_roam_scan_notify(int err, struct l_queue *bss_list, /* The various roam routines expect this to be set from scanning */ station->preparing_roam = true; l_queue_push_tail(station->roam_bss_list, - roam_bss_from_scan_bss(target)); + roam_bss_from_scan_bss(target, target->rank)); station_update_roam_bss(station, target); @@ -5139,6 +5296,19 @@ static void station_known_networks_changed(enum known_networks_event event, static int station_init(void) { + if (scan_get_band_rank_modifier(BAND_FREQ_2_4_GHZ)) + allowed_bands |= BAND_FREQ_2_4_GHZ; + if (scan_get_band_rank_modifier(BAND_FREQ_5_GHZ)) + allowed_bands |= BAND_FREQ_5_GHZ; + if (scan_get_band_rank_modifier(BAND_FREQ_6_GHZ)) + allowed_bands |= BAND_FREQ_6_GHZ; + + if (!(allowed_bands & (BAND_FREQ_2_4_GHZ | BAND_FREQ_5_GHZ))) { + l_error("At least 2.4GHz and 5GHz bands must be enabled for " + "IWD to start, check [Rank].BandModifier* setting"); + return -ENOTSUP; + } + station_list = l_queue_new(); netdev_watch = netdev_watch_add(station_netdev_watch, NULL, NULL); #ifdef HAVE_DBUS diff --git a/src/station.h b/src/station.h @@ -89,7 +89,7 @@ void station_remove_event_watch(uint32_t id); bool station_set_autoconnect(struct station *station, bool autoconnect); int __station_connect_network(struct station *station, struct network *network, - struct scan_bss *bss); + struct scan_bss *bss, enum station_state state); void station_connect_network(struct station *station, struct network *network, struct scan_bss *bss, struct l_dbus_message *message); diff --git a/src/wiphy.c b/src/wiphy.c @@ -138,7 +138,6 @@ struct wiphy { bool support_scheduled_scan:1; bool support_rekey_offload:1; - bool support_adhoc_rsn:1; bool support_qos_set_map:1; bool support_cmds_auth_assoc:1; bool support_fw_roam:1; @@ -555,7 +554,7 @@ const struct band_freq_attrs *wiphy_get_frequency_info_list( return bandp->freq_attrs; } -bool wiphy_band_is_disabled(const struct wiphy *wiphy, enum band_freq band) +int wiphy_band_is_disabled(const struct wiphy *wiphy, enum band_freq band) { struct band_freq_attrs attr; unsigned int i; @@ -563,7 +562,7 @@ bool wiphy_band_is_disabled(const struct wiphy *wiphy, enum band_freq band) bandp = wiphy_get_band(wiphy, band); if (!bandp) - return true; + return -ENOTSUP; for (i = 0; i < bandp->freqs_len; i++) { attr = bandp->freq_attrs[i]; @@ -572,10 +571,10 @@ bool wiphy_band_is_disabled(const struct wiphy *wiphy, enum band_freq band) continue; if (!attr.disabled) - return false; + return 0; } - return true; + return 1; } bool wiphy_supports_probe_resp_offload(struct wiphy *wiphy) @@ -662,16 +661,6 @@ uint32_t wiphy_get_max_roc_duration(struct wiphy *wiphy) return wiphy->max_roc_duration; } -bool wiphy_supports_adhoc_rsn(struct wiphy *wiphy) -{ - return wiphy->support_adhoc_rsn; -} - -bool wiphy_can_offchannel_tx(struct wiphy *wiphy) -{ - return wiphy->offchannel_tx_ok; -} - bool wiphy_supports_qos_set_map(struct wiphy *wiphy) { return wiphy->support_qos_set_map; @@ -730,11 +719,6 @@ bool wiphy_power_save_disabled(struct wiphy *wiphy) return false; } -const uint8_t *wiphy_get_permanent_address(struct wiphy *wiphy) -{ - return wiphy->permanent_addr; -} - const uint8_t *wiphy_get_extended_capabilities(struct wiphy *wiphy, uint32_t iftype) { @@ -812,12 +796,13 @@ void wiphy_generate_random_address(struct wiphy *wiphy, uint8_t addr[static 6]) wiphy_address_constrain(wiphy, addr); } -void wiphy_generate_address_from_ssid(struct wiphy *wiphy, const char *ssid, +void wiphy_generate_address_from_ssid(struct wiphy *wiphy, + const uint8_t *ssid, size_t ssid_len, uint8_t addr[static 6]) { struct l_checksum *sha = l_checksum_new(L_CHECKSUM_SHA256); - l_checksum_update(sha, ssid, strlen(ssid)); + l_checksum_update(sha, ssid, ssid_len); l_checksum_update(sha, wiphy->permanent_addr, sizeof(wiphy->permanent_addr)); l_checksum_get_digest(sha, addr, mac_randomize_bytes); @@ -843,7 +828,7 @@ bool wiphy_constrain_freq_set(const struct wiphy *wiphy, if (!band) continue; - for (i = 0; i < band->freqs_len; i++) { + for (i = 1; i <= band->freqs_len; i++) { uint32_t freq; if (!band->freq_attrs[i].supported) @@ -1278,10 +1263,10 @@ static void wiphy_print_basic_info(struct wiphy *wiphy) l_info("\tPermanent Address: "MAC, MAC_STR(wiphy->permanent_addr)); if (wiphy->band_2g) - wiphy_print_band_info(wiphy->band_2g, "2.4Ghz Band"); + wiphy_print_band_info(wiphy->band_2g, "2.4GHz Band"); if (wiphy->band_5g) - wiphy_print_band_info(wiphy->band_5g, "5Ghz Band"); + wiphy_print_band_info(wiphy->band_5g, "5GHz Band"); if (wiphy->band_6g) wiphy_print_band_info(wiphy->band_6g, "6GHz Band"); @@ -1858,9 +1843,6 @@ static void wiphy_parse_attributes(struct wiphy *wiphy, else wiphy->max_scan_ie_len = *((uint16_t *) data); break; - case NL80211_ATTR_SUPPORT_IBSS_RSN: - wiphy->support_adhoc_rsn = true; - break; case NL80211_ATTR_SUPPORTED_IFTYPES: if (l_genl_attr_recurse(&attr, &nested)) parse_supported_iftypes(wiphy, &nested); diff --git a/src/wiphy.h b/src/wiphy.h @@ -109,7 +109,7 @@ const struct band_freq_attrs *wiphy_get_frequency_info_list( enum band_freq band, size_t *size); -bool wiphy_band_is_disabled(const struct wiphy *wiphy, enum band_freq band); +int wiphy_band_is_disabled(const struct wiphy *wiphy, enum band_freq band); bool wiphy_supports_probe_resp_offload(struct wiphy *wiphy); bool wiphy_can_transition_disable(struct wiphy *wiphy); @@ -127,8 +127,6 @@ bool wiphy_supports_iftype(struct wiphy *wiphy, uint32_t iftype); const uint8_t *wiphy_get_supported_rates(struct wiphy *wiphy, enum band_freq band, unsigned int *out_num); -bool wiphy_supports_adhoc_rsn(struct wiphy *wiphy); -bool wiphy_can_offchannel_tx(struct wiphy *wiphy); bool wiphy_supports_qos_set_map(struct wiphy *wiphy); bool wiphy_supports_firmware_roam(struct wiphy *wiphy); const char *wiphy_get_driver(struct wiphy *wiphy); @@ -136,7 +134,6 @@ const char *wiphy_get_name(struct wiphy *wiphy); bool wiphy_uses_default_if(struct wiphy *wiphy); bool wiphy_control_port_enabled(struct wiphy *wiphy); bool wiphy_power_save_disabled(struct wiphy *wiphy); -const uint8_t *wiphy_get_permanent_address(struct wiphy *wiphy); const uint8_t *wiphy_get_extended_capabilities(struct wiphy *wiphy, uint32_t iftype); const uint8_t *wiphy_get_rm_enabled_capabilities(struct wiphy *wiphy); @@ -149,7 +146,8 @@ const uint8_t *wiphy_get_ht_capabilities(const struct wiphy *wiphy, enum band_freq band, size_t *size); void wiphy_generate_random_address(struct wiphy *wiphy, uint8_t addr[static 6]); -void wiphy_generate_address_from_ssid(struct wiphy *wiphy, const char *ssid, +void wiphy_generate_address_from_ssid(struct wiphy *wiphy, + const uint8_t *ssid, size_t ssid_len, uint8_t addr[static 6]); int wiphy_estimate_data_rate(struct wiphy *wiphy, diff --git a/test/simple-agent b/test/simple-agent @@ -54,7 +54,7 @@ class Agent(dbus.service.Object): in_signature='o', out_signature='ss') def RequestUserNameAndPassword(self, path): - print("RequestPrivateKeyPassphrase (%s)" % (path)) + print("RequestUserNameAndPassword (%s)" % (path)) print("Service credentials requested, type cancel to cancel") user = input('User name: ') diff --git a/tools/run-tests b/tools/run-tests @@ -27,8 +27,6 @@ from utils import Process, Namespace, BarChart config = None intf_id = 0 -TEST_MAX_TIMEOUT = 240 - dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) def dbg(*s, **kwargs): @@ -52,7 +50,7 @@ def exit_vm(): p.kill() if config.ctx and config.ctx.results: - success = print_results(config.ctx.results) + success = print_results(config.ctx.results, int(config.ctx.args.timeout)) if config.ctx.args.result: write_results(config.ctx.args.result, config.ctx.results) @@ -917,7 +915,7 @@ def post_test(ctx, to_copy): except: pass -def print_results(results): +def print_results(results, max_timeout): table = PrettyTable(['Test', colored('Passed', 'green'), colored('Failed', 'red'), \ colored('Skipped', 'cyan'), colored('Time', 'yellow')]) @@ -928,7 +926,7 @@ def print_results(results): for test, result in results.items(): - if result.time == TEST_MAX_TIMEOUT: + if result.time == max_timeout: failed = "Timed out" passed = "Timed out" elif result.time == 0: @@ -975,7 +973,7 @@ def run_auto_tests(ctx, args): p.start() # Rather than time each subtest we just time the total but # mutiply the default time by the number of tests being run. - p.join(TEST_MAX_TIMEOUT * len(subtests)) + p.join(int(args.timeout) * len(subtests)) if p.is_alive(): # Timeout @@ -983,7 +981,7 @@ def run_auto_tests(ctx, args): ctx.results[os.path.basename(test)] = SimpleResult(run=0, failures=0, errors=0, - skipped=0, time=TEST_MAX_TIMEOUT) + skipped=0, time=int(args.timeout)) else: ctx.results[os.path.basename(test)] = rqueue.get() diff --git a/tools/runner.py b/tools/runner.py @@ -120,9 +120,12 @@ class RunnerCoreArgParse(ArgumentParser): const=True, action='store', help='Use physical adapters for tests (passthrough)') + + # Hidden options only meant to be passed to the kernel self.add_argument('--testhome', help=SUPPRESS) self.add_argument('--monitor-parent', help=SUPPRESS) self.add_argument('--result-parent', help=SUPPRESS) + self.add_argument('--timeout', help=SUPPRESS) # Prevent --autotest/--unittest from being used together auto_unit_group = self.add_mutually_exclusive_group() @@ -385,6 +388,8 @@ class QemuRunner(RunnerAbstract): self._prepare_outfiles() + self.args.timeout = 240 + if args.hw: if os.path.isfile(args.hw): hw_conf = ConfigParser() @@ -543,6 +548,8 @@ class UmlRunner(RunnerAbstract): self._prepare_outfiles() + self.args.timeout = 1000 + kern_log = "ignore_loglevel" if "kernel" in args.verbose else "quiet" cmd = [args.kernel, 'rootfstype=hostfs', 'ro', 'mem=256M', 'mac80211_hwsim.radios=0', diff --git a/unit/test-band.c b/unit/test-band.c @@ -644,7 +644,7 @@ static void test_6ghz_freqs(const void *data) uint32_t i; enum band_freq band; - for (i = 5955; i < 7115; i += 20) { + for (i = 5955; i <= 7115; i += 20) { assert(band_freq_to_channel(i, &band) != 0); assert(band == BAND_FREQ_6_GHZ); } @@ -654,8 +654,8 @@ static void test_conversions(const void *data) { /* * Test a few invalid channels/frequencies that appear valid but are - * not in the E-4 table. The checks in band.c seem to cover 2.4Ghz and - * 6Ghz very well since there are no gaps, but the 5GHz band has some + * not in the E-4 table. The checks in band.c seem to cover 2.4GHz and + * 6GHz very well since there are no gaps, but the 5GHz band has some * segmentation. */ diff --git a/unit/test-dpp.c b/unit/test-dpp.c @@ -158,28 +158,104 @@ static void test_bad_channels(const void *data) test_uri_parse(&bad_channels[i]); } +struct dpp_test_vector { + /* Initiator values */ + const char *i_proto_public; + const char *i_proto_private; + const char *i_boot_public; + const char *i_boot_private; + const char *i_nonce; + const char *i_auth; + const char *i_asn1; + + /* Responder values */ + const char *r_proto_public; + const char *r_proto_private; + const char *r_boot_public; + const char *r_boot_private; + const char *r_nonce; + const char *r_auth; + const char *r_asn1; + + const char *k1; + const char *k2; + const char *ke; + const char *mx; + const char *nx; + const char *lx; +}; + +/* + * B.1 Test Vectors for DPP Authentication Using P-256 for + * Mutual Authentication + */ +static struct dpp_test_vector mutual_p256 = { + .i_proto_public = "50a532ae2a07207276418d2fa630295d45569be425aa634f02014d00a7d1f61a" + "e14f35a5a858bccad90d126c46594c49ef82655e78888e15a32d916ac2172491", + .i_proto_private = "a87de9afbb406c96e5f79a3df895ecac3ad406f95da66314c8cb3165e0c61783", + /* + * The spec uses a 31 octet Y value, a zero byte was prepended to the + * Y value here otherwise the point cannot be created + */ + .i_boot_public = "88b37ed91938b5197097808a6244847617892046d93b9501afd48fa0f148dfde" + "00f73b6991287884a9c9a33f8e0691f14d44b59811e9d8242d010270b0d33ec0", + .i_boot_private = "15b2a83c5a0a38b61f2aa8200ee4994b8afdc01c58507d10d0a38f7eedf051bb", + .i_nonce = "13f4602a16daeb69712263b9c46cba31", + .i_auth = "d34944bb4b1f05caebda762c6e4ae034c819ec2f62a57dcfade2473876e007b2", + .i_asn1 = "3039301306072a8648ce3d020106082a8648ce3d0301070322000288b37ed919" + "38b5197097808a6244847617892046d93b9501afd48fa0f148dfde", + + .r_proto_public = "5e3fb3576884887f17c3203d8a3a6c2fac722ef0e2201b61ac73bc655c709a90" + "2d4b030669fb9eff8b0a79fa7c1a172ac2a92c626256963f9274dc90682c81e5", + .r_proto_private = "f798ed2e19286f6a6efe210b1863badb99af2a14b497634dbfd2a97394fb5aa5", + .r_boot_public = "09c585a91b4df9fd25a045201885c39cc5cfae397ddaeda957dec57fa0e3503f" + "52bf05968198a2f92883e96a386d767579883302dbf292105c90a43694c2fd5c", + .r_boot_private = "54ce181a98525f217216f59b245f60e9df30ac7f6b26c939418cfc3c42d1afa0", + .r_nonce = "3d0cfb011ca916d796f7029ff0b43393", + .r_auth = "a725abe6dc66ccf3aa3d6d61a19932fcbb0799ed09ff78e5bc6d4ea5ef8e8670", + .r_asn1 = "3039301306072a8648ce3d020106082a8648ce3d0301070322000209c585a91b" + "4df9fd25a045201885c39cc5cfae397ddaeda957dec57fa0e3503f", + + .k1 = "3d832a02ed6d7fc1dc96d2eceab738cf01c0028eb256be33d5a21a720bfcf949", + .k2 = "ca08bdeeef838ddf897a5f01f20bb93dc5a895cb86788ca8c00a7664899bc310", + .ke = "b6db65526c9a0174c3bed56f7e614f3a656233c078693249ac3516425127e5d5", + .mx = "dde2878117d69745be4f916a2dd14269d783d1d788c603bb8746beabbd1dbbbc", + .nx = "92118478b75c21c2c59340c842b5bce560a535f60bc37a75fe390d738c58d8e8", + .lx = "fb737234c973cc3a36e64e5170a32f12089d198c73c2fd85a53d0b282530fd02" +}; + /* * B.2 Test Vectors for DPP Authentication Using P-256 for * Responder-only Authentication */ -const char *i_proto_public_bytes = "50a532ae2a07207276418d2fa630295d45569be425aa634f02014d00a7d1f61a"; -const char *r_boot_public_bytes = "09c585a91b4df9fd25a045201885c39cc5cfae397ddaeda957dec57fa0e3503f"; -const char *r_boot_private_bytes = "54ce181a98525f217216f59b245f60e9df30ac7f6b26c939418cfc3c42d1afa0"; -const char *r_proto_private_bytes = "f798ed2e19286f6a6efe210b1863badb99af2a14b497634dbfd2a97394fb5aa5"; -const char *r_proto_public_bytes = "5e3fb3576884887f17c3203d8a3a6c2fac722ef0e2201b61ac73bc655c709a90"; -const char *k1_bytes = "3d832a02ed6d7fc1dc96d2eceab738cf01c0028eb256be33d5a21a720bfcf949"; -const char *k2_bytes = "ca08bdeeef838ddf897a5f01f20bb93dc5a895cb86788ca8c00a7664899bc310"; -const char *ke_bytes = "c8882a8ab30c878467822534138c704ede0ab1e873fe03b601a7908463fec87a"; -const char *mx_bytes = "dde2878117d69745be4f916a2dd14269d783d1d788c603bb8746beabbd1dbbbc"; -const char *nx_bytes = "92118478b75c21c2c59340c842b5bce560a535f60bc37a75fe390d738c58d8e8"; -const char *i_nonce_bytes = "13f4602a16daeb69712263b9c46cba31"; -const char *r_nonce_bytes = "3d0cfb011ca916d796f7029ff0b43393"; -const char *i_auth_bytes = "787d1189b526448d2901e7f6c22775ce514fce52fc886c1e924f2fbb8d97b210"; -const char *r_auth_bytes = "43509ef7137d8c2fbe66d802ae09dedd94d41b8cbfafb4954782014ff4a3f91c"; +static struct dpp_test_vector responder_only_p256 = { + .i_proto_public = "50a532ae2a07207276418d2fa630295d45569be425aa634f02014d00a7d1f61a" + "e14f35a5a858bccad90d126c46594c49ef82655e78888e15a32d916ac2172491", + .i_nonce = "13f4602a16daeb69712263b9c46cba31", + .i_auth = "787d1189b526448d2901e7f6c22775ce514fce52fc886c1e924f2fbb8d97b210", + + .r_proto_public = "5e3fb3576884887f17c3203d8a3a6c2fac722ef0e2201b61ac73bc655c709a90" + "2d4b030669fb9eff8b0a79fa7c1a172ac2a92c626256963f9274dc90682c81e5", + .r_proto_private = "f798ed2e19286f6a6efe210b1863badb99af2a14b497634dbfd2a97394fb5aa5", + .r_boot_public = "09c585a91b4df9fd25a045201885c39cc5cfae397ddaeda957dec57fa0e3503f" + "52bf05968198a2f92883e96a386d767579883302dbf292105c90a43694c2fd5c", + .r_boot_private = "54ce181a98525f217216f59b245f60e9df30ac7f6b26c939418cfc3c42d1afa0", + .r_nonce = "3d0cfb011ca916d796f7029ff0b43393", + .r_auth = "43509ef7137d8c2fbe66d802ae09dedd94d41b8cbfafb4954782014ff4a3f91c", + .r_asn1 = "3039301306072a8648ce3d020106082a8648ce3d0301070322000209c585a91b" + "4df9fd25a045201885c39cc5cfae397ddaeda957dec57fa0e3503f", + + .k1 = "3d832a02ed6d7fc1dc96d2eceab738cf01c0028eb256be33d5a21a720bfcf949", + .k2 = "ca08bdeeef838ddf897a5f01f20bb93dc5a895cb86788ca8c00a7664899bc310", + .ke = "c8882a8ab30c878467822534138c704ede0ab1e873fe03b601a7908463fec87a", + .mx = "dde2878117d69745be4f916a2dd14269d783d1d788c603bb8746beabbd1dbbbc", + .nx = "92118478b75c21c2c59340c842b5bce560a535f60bc37a75fe390d738c58d8e8", +}; #define HEX2BUF(s, buf, _len) { \ - unsigned char *_tmp = l_util_from_hexstring(s, NULL); \ - memcpy(buf, _tmp, _len); \ + size_t _len_out; \ + unsigned char *_tmp = l_util_from_hexstring(s, &_len_out); \ + memcpy(buf, _tmp, _len_out); \ l_free(_tmp); \ } @@ -192,8 +268,12 @@ const char *r_auth_bytes = "43509ef7137d8c2fbe66d802ae09dedd94d41b8cbfafb4954782 static void test_key_derivation(const void *data) { - uint64_t tmp[L_ECC_MAX_DIGITS]; + const struct dpp_test_vector *vector = data; + + uint64_t tmp[L_ECC_MAX_DIGITS * 2]; const struct l_ecc_curve *curve = l_ecc_curve_from_ike_group(19); + _auto_(l_ecc_point_free) struct l_ecc_point *i_boot_public = NULL; + _auto_(l_ecc_scalar_free) struct l_ecc_scalar *i_boot_private = NULL; _auto_(l_ecc_point_free) struct l_ecc_point *i_proto_public = NULL; _auto_(l_ecc_point_free) struct l_ecc_point *r_boot_public = NULL; _auto_(l_ecc_scalar_free) struct l_ecc_scalar *r_boot_private = NULL; @@ -201,6 +281,8 @@ static void test_key_derivation(const void *data) _auto_(l_ecc_point_free) struct l_ecc_point *r_proto_public = NULL; _auto_(l_ecc_scalar_free) struct l_ecc_scalar *m = NULL; _auto_(l_ecc_scalar_free) struct l_ecc_scalar *n = NULL; + _auto_(l_ecc_point_free) struct l_ecc_point *l = NULL; + _auto_(l_ecc_point_free) struct l_ecc_point *from_asn1 = NULL; uint64_t k1[L_ECC_MAX_DIGITS]; uint64_t k2[L_ECC_MAX_DIGITS]; uint64_t ke[L_ECC_MAX_DIGITS]; @@ -208,60 +290,258 @@ static void test_key_derivation(const void *data) uint8_t r_nonce[16]; uint64_t r_auth[L_ECC_MAX_DIGITS]; uint64_t i_auth[L_ECC_MAX_DIGITS]; + _auto_(l_free) uint8_t *asn1 = NULL; + size_t asn1_len; - HEX2BUF(i_proto_public_bytes, tmp, 32); + HEX2BUF(vector->i_proto_public, tmp, 64); i_proto_public = l_ecc_point_from_data(curve, - L_ECC_POINT_TYPE_COMPLIANT, - tmp, 32); + L_ECC_POINT_TYPE_FULL, + tmp, 64); assert(i_proto_public); - HEX2BUF(r_boot_public_bytes, tmp, 32); + HEX2BUF(vector->r_boot_public, tmp, 64); r_boot_public = l_ecc_point_from_data(curve, - L_ECC_POINT_TYPE_COMPLIANT, - tmp, 32); + L_ECC_POINT_TYPE_FULL, + tmp, 64); assert(r_boot_public); - HEX2BUF(r_proto_public_bytes, tmp, 32); + if (vector->i_boot_public) { + HEX2BUF(vector->i_boot_public, tmp, 64); + i_boot_public = l_ecc_point_from_data(curve, + L_ECC_POINT_TYPE_FULL, + tmp, 64); + assert(i_boot_public); + } + + if (vector->i_boot_private) { + HEX2BUF(vector->i_boot_private, tmp, 32); + i_boot_private = l_ecc_scalar_new(curve, tmp, 32); + assert(i_boot_private); + } + + HEX2BUF(vector->r_asn1, tmp, sizeof(tmp)); + asn1 = dpp_point_to_asn1(r_boot_public, &asn1_len); + + from_asn1 = dpp_point_from_asn1(asn1, asn1_len); + + assert(l_ecc_points_are_equal(from_asn1, r_boot_public)); + + assert(asn1_len == 59); + assert(memcmp(tmp, asn1, asn1_len) == 0); + + if (vector->i_asn1) { + HEX2BUF(vector->i_asn1, tmp, sizeof(tmp)); + asn1 = dpp_point_to_asn1(i_boot_public, &asn1_len); + + from_asn1 = dpp_point_from_asn1(asn1, asn1_len); + + assert(l_ecc_points_are_equal(from_asn1, i_boot_public)); + + assert(asn1_len == 59); + assert(memcmp(tmp, asn1, asn1_len) == 0); + } + + + HEX2BUF(vector->r_proto_public, tmp, 64); r_proto_public = l_ecc_point_from_data(curve, - L_ECC_POINT_TYPE_COMPLIANT, - tmp, 32); + L_ECC_POINT_TYPE_FULL, + tmp, 64); assert(r_proto_public); - HEX2BUF(r_boot_private_bytes, tmp, 32); + HEX2BUF(vector->r_boot_private, tmp, 32); r_boot_private = l_ecc_scalar_new(curve, tmp, 32); assert(r_boot_private); - HEX2BUF(r_proto_private_bytes, tmp, 32); + HEX2BUF(vector->r_proto_private, tmp, 32); r_proto_private = l_ecc_scalar_new(curve, tmp, 32); assert(r_proto_private); m = dpp_derive_k1(i_proto_public, r_boot_private, k1); assert(m); - CHECK_FROM_STR(k1_bytes, k1, 32); + CHECK_FROM_STR(vector->k1, k1, 32); l_ecc_scalar_get_data(m, tmp, sizeof(tmp)); - CHECK_FROM_STR(mx_bytes, tmp, 32); + CHECK_FROM_STR(vector->mx, tmp, 32); n = dpp_derive_k2(i_proto_public, r_proto_private, k2); assert(n); - CHECK_FROM_STR(k2_bytes, k2, 32); + CHECK_FROM_STR(vector->k2, k2, 32); l_ecc_scalar_get_data(n, tmp, sizeof(tmp)); - CHECK_FROM_STR(nx_bytes, tmp, 32); + CHECK_FROM_STR(vector->nx, tmp, 32); + + if (vector->lx) { + /* Check initiator derivation */ + l = dpp_derive_li(r_boot_public, r_proto_public, + i_boot_private); + assert(l); + l_ecc_point_get_x(l, tmp, sizeof(tmp)); + CHECK_FROM_STR(vector->lx, tmp, 32); + l_ecc_point_free(l); + l = NULL; + + /* Check responder derivation */ + l = dpp_derive_lr(r_boot_private, r_proto_private, + i_boot_public); + assert(l); + l_ecc_point_get_x(l, tmp, sizeof(tmp)); + CHECK_FROM_STR(vector->lx, tmp, 32); + + } - HEX2BUF(i_nonce_bytes, i_nonce, 16); - HEX2BUF(r_nonce_bytes, r_nonce, 16); - dpp_derive_ke(i_nonce, r_nonce, m, n, ke); + HEX2BUF(vector->i_nonce, i_nonce, 16); + HEX2BUF(vector->r_nonce, r_nonce, 16); + dpp_derive_ke(i_nonce, r_nonce, m, n, l, ke); - CHECK_FROM_STR(ke_bytes, ke, 32); + CHECK_FROM_STR(vector->ke, ke, 32); dpp_derive_r_auth(i_nonce, r_nonce, 16, i_proto_public, r_proto_public, - r_boot_public, r_auth); - CHECK_FROM_STR(r_auth_bytes, r_auth, 32); + i_boot_public, r_boot_public, r_auth); + CHECK_FROM_STR(vector->r_auth, r_auth, 32); dpp_derive_i_auth(r_nonce, i_nonce, 16, r_proto_public, i_proto_public, - r_boot_public, i_auth); - CHECK_FROM_STR(i_auth_bytes, i_auth, 32); + r_boot_public, i_boot_public, i_auth); + CHECK_FROM_STR(vector->i_auth, i_auth, 32); +} + +struct dpp_pkex_test_vector { + uint8_t mac_i[6]; + uint8_t mac_r[6]; + const char *identifier; + const char *key; + + const char *i_boot_public; + const char *i_boot_private; + const char *qix; + + const char *r_boot_public; + const char *r_boot_private; + const char *qrx; + + const char *mx; + const char *nx; + + const char *k; + const char *j; + const char *ax; + const char *yx; + const char *xx; + const char *bx; + const char *lx; + + const char *z; + const char *u; + const char *v; +}; + +/* + * Appendix D PKEX Test Vector for NIST p256 + */ +static struct dpp_pkex_test_vector pkex_vector = { + .mac_i = { 0xac, 0x64, 0x91, 0xf4, 0x52, 0x07 }, + .mac_r = { 0x6e, 0x5e, 0xce, 0x6e, 0xf3, 0xdd }, + .identifier = "joes_key", + .key = "thisisreallysecret", + + .i_boot_public = "0ad58864754c812685ff3a52a573c1d72c72c4ebed98f3915622d4dfc84a438d" + "7e81429aac49ddec75ad6521db9c74074e30b5eb2ba53693c9341b79be14e101", + .i_boot_private = "5941b51acfc702cdc1c347264beb2920db88eb1a0bf03a211868b1632233c269", + .qix = "2867c4e080980dbad5099a8f821e8729679c5c714888c0bd9c7e8e4048c5fa5e", + + .r_boot_public = "977b7fa39779a81429febb12e1dc5e20a7e017c4bc7437090e57c966a2b0e8a3" + "9d2b62733947639763f64c7b6708c1e0857becb7e24fc195248b5b06036cf792", + .r_boot_private = "2ae8956293f49986b6d0b8169a86805d9232babb5f6813fdfe96f19d59536c60", + .qrx = "134af1c41c8e7d974c647cc2bfca30b036966959f9044e90f673d756706e624c", + + .mx = "bcca8e23e5c05032ae6051ca6392f7c4a4b4f9fe13e8126132d070e552848176", + .nx = "0a91e0728809bb8191ea36d0a1d5602bf36ab6708fbfd063e2511e533b534020", + + .k = "7415e1c68611f0443cc345d136984e488c6a26d3d5482fa67e9841a03a87c78f", + .j = "31c1b9ab31d9c2f278b35b5c29d180dfeaf76d585ede9c0dd91cb66149db572e", + .ax = "0ad58864754c812685ff3a52a573c1d72c72c4ebed98f3915622d4dfc84a438d", + .yx = "a9972a94f143740df31c7a61124d01a4e949d0fdcede61369f4c6b097aeb18b5", + .xx = "740ab9f0c173507b0081b475b275de6a3060cf434b6a65f0b0144a1dbf913310", + .bx = "977b7fa39779a81429febb12e1dc5e20a7e017c4bc7437090e57c966a2b0e8a3", + .lx = "bc5f3128b0b997079a23ead63cf502ef4f7526602269620377b79bce20e03d44", + + .z = "5271dee915cf7b1908747d8edb8394442411c5183ee38b79ebef399c08738e0b", + .u = "598c3d8dcccea2d43259068d542a907442f07e8cbcfb3fb49faac12eb2fee5b6", + .v = "b2833ce21ab4e42c082111a5dd232334e48019f66b2e274f521fe2f7dfa11999", +}; + +static void test_pkex_key_derivation(const void *user_data) +{ + const struct dpp_pkex_test_vector *vector = user_data; + const struct l_ecc_curve *curve = l_ecc_curve_from_ike_group(19); + uint64_t tmp[L_ECC_MAX_DIGITS * 2]; + _auto_(l_ecc_point_free) struct l_ecc_point *qi = NULL; + _auto_(l_ecc_point_free) struct l_ecc_point *qr = NULL; + _auto_(l_ecc_point_free) struct l_ecc_point *n = NULL; + _auto_(l_ecc_point_free) struct l_ecc_point *m = NULL; + _auto_(l_ecc_point_free) struct l_ecc_point *j = NULL; + _auto_(l_ecc_point_free) struct l_ecc_point *k = NULL; + _auto_(l_ecc_point_free) struct l_ecc_point *a = NULL; + _auto_(l_ecc_point_free) struct l_ecc_point *y = NULL; + _auto_(l_ecc_point_free) struct l_ecc_point *x = NULL; + _auto_(l_ecc_point_free) struct l_ecc_point *b = NULL; + _auto_(l_ecc_point_free) struct l_ecc_point *l = NULL; + size_t len; + + qi = dpp_derive_qi(curve, vector->key, vector->identifier, + vector->mac_i); + l_ecc_point_get_x(qi, tmp, sizeof(tmp)); + CHECK_FROM_STR(vector->qix, tmp, 32); + + qr = dpp_derive_qr(curve, vector->key, vector->identifier, + vector->mac_r); + l_ecc_point_get_x(qr, tmp, sizeof(tmp)); + CHECK_FROM_STR(vector->qrx, tmp, 32); + + HEX2BUF(vector->nx, tmp, 32); + n = l_ecc_point_from_data(curve, L_ECC_POINT_TYPE_COMPLIANT, tmp, 32); + assert(n); + + HEX2BUF(vector->mx, tmp, 32); + m = l_ecc_point_from_data(curve, L_ECC_POINT_TYPE_COMPLIANT, tmp, 32); + assert(m); + + HEX2BUF(vector->k, tmp, 32); + k = l_ecc_point_from_data(curve, L_ECC_POINT_TYPE_COMPLIANT, tmp, 32); + assert(k); + + dpp_derive_z(vector->mac_i, vector->mac_r, n, m, k, vector->key, + vector->identifier, tmp, &len); + CHECK_FROM_STR(vector->z, tmp, 32); + + HEX2BUF(vector->j, tmp, 32); + j = l_ecc_point_from_data(curve, L_ECC_POINT_TYPE_COMPLIANT, tmp, 32); + assert(j); + + HEX2BUF(vector->ax, tmp, 32); + a = l_ecc_point_from_data(curve, L_ECC_POINT_TYPE_COMPLIANT, tmp, 32); + assert(a); + + HEX2BUF(vector->yx, tmp, 32); + y = l_ecc_point_from_data(curve, L_ECC_POINT_TYPE_COMPLIANT, tmp, 32); + assert(y); + + HEX2BUF(vector->xx, tmp, 32); + x = l_ecc_point_from_data(curve, L_ECC_POINT_TYPE_COMPLIANT, tmp, 32); + assert(x); + + dpp_derive_u(j, vector->mac_i, a, y, x, tmp, &len); + CHECK_FROM_STR(vector->u, tmp, 32); + + HEX2BUF(vector->bx, tmp, 32); + b = l_ecc_point_from_data(curve, L_ECC_POINT_TYPE_COMPLIANT, tmp, 32); + assert(b); + + HEX2BUF(vector->lx, tmp, 32); + l = l_ecc_point_from_data(curve, L_ECC_POINT_TYPE_COMPLIANT, tmp, 32); + assert(l); + + dpp_derive_v(l, vector->mac_r, b, x, y, tmp, &len); + CHECK_FROM_STR(vector->v, tmp, 32); } int main(int argc, char *argv[]) @@ -269,9 +549,17 @@ int main(int argc, char *argv[]) l_test_init(&argc, &argv); if (l_checksum_is_supported(L_CHECKSUM_SHA256, true) && - l_getrandom_is_supported()) - l_test_add("DPP test key derivation", - test_key_derivation, NULL); + l_getrandom_is_supported()) { + l_test_add("DPP test responder-only key derivation", + test_key_derivation, + &responder_only_p256); + l_test_add("DPP test mutual key derivation", + test_key_derivation, + &mutual_p256); + l_test_add("DPP test PKEX key derivation", + test_pkex_key_derivation, + &pkex_vector); + } l_test_add("DPP URI parse", test_uri_parse, &all_values); l_test_add("DPP URI no type", test_uri_parse, &no_type);