eiwd

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

commit 95b6022177ffad5887b10db21ac4c5c6d44271a8
parent 9afb453920df105d6b72d6ead7833be01d373f94
Author: illiliti <illiliti@protonmail.com>
Date:   Wed, 26 Jan 2022 15:00:08 +0300

Merge tag '1.22'

Release 1.22

Diffstat:
MAUTHORS | 1+
MChangeLog | 6++++++
MMakefile.am | 2+-
Mautotests/testDPP/connection_test.py | 105++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------
Mautotests/testDPP/hw.conf | 1+
Mautotests/testPSK-roam/connection_test.py | 2++
Mautotests/testPSK-roam/main.conf | 3+++
Aautotests/testPSK-roam/roam_ap_disconnect_test.py | 101+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mautotests/util/hostapd.py | 4++++
Mautotests/util/wpas.py | 62+++++++++++++++++++++++++++++++++++++++-----------------------
Mconfigure.ac | 4++--
Rdoc/device-provisioning.txt -> doc/device-provisioning-api.txt | 0
Msrc/adhoc.c | 2+-
Msrc/agent.c | 2--
Msrc/anqputil.c | 2+-
Msrc/ap.c | 24++++++++++++++++--------
Msrc/backtrace.c | 3++-
Msrc/backtrace.h | 2+-
Msrc/band.c | 10+++++-----
Msrc/crypto.c | 15++++++++-------
Msrc/dpp-util.c | 138+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------
Msrc/dpp-util.h | 1+
Msrc/dpp.c | 645+++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------
Msrc/eap-gtc.c | 2--
Msrc/eap-peap.c | 8++++----
Msrc/eap-pwd.c | 18++++++++++++++++--
Msrc/eap-tls-common.c | 4++--
Msrc/eap-ttls.c | 2+-
Msrc/eap-wsc.c | 2+-
Msrc/eapol.c | 8++++----
Msrc/eapolutil.h | 2+-
Msrc/erp.c | 8++++----
Msrc/fils.c | 2+-
Msrc/frame-xchg.c | 11++++++-----
Msrc/ft.c | 7++++---
Msrc/handshake.c | 7++++++-
Msrc/handshake.h | 24++++++++++++++++++------
Msrc/ie.c | 2+-
Msrc/ie.h | 2+-
Msrc/iwd.config.rst | 2+-
Msrc/json.c | 238++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Msrc/json.h | 24+++++++++++++++++++++---
Msrc/main.c | 2+-
Msrc/manager.c | 6+++---
Msrc/mpdu.c | 1+
Msrc/netconfig.c | 13+++++++------
Msrc/netdev.c | 55++++++++++++++++++++++++++++++-------------------------
Msrc/network.c | 4++--
Msrc/nl80211util.c | 12++++++++++++
Msrc/offchannel.c | 5+++--
Msrc/p2p.c | 12+++++++-----
Msrc/p2putil.h | 4++--
Msrc/sae.c | 9+++++----
Msrc/scan.c | 283+++++++++++++++++++++++++++++++++++++++++++++----------------------------------
Msrc/simauth.h | 4++--
Msrc/station.c | 35++++++++++++++++++++++++-----------
Msrc/util.c | 4++--
Msrc/wiphy.c | 15++++++++-------
Msrc/wiphy.h | 6++++++
Msrc/wsc.c | 4++--
Msrc/wscutil.c | 5+++--
Mtools/test-runner | 1+
Munit/test-dpp.c | 5++++-
Munit/test-json.c | 343++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
64 files changed, 1752 insertions(+), 584 deletions(-)

diff --git a/AUTHORS b/AUTHORS @@ -33,3 +33,4 @@ Michael Johnson <mjohnson459@gmail.com> Matt Oberle <matt.r.oberle@gmail.com> Marc-Antoine Perennou <Marc-Antoine@Perennou.com> Torsten Schmitz <noreply.torsten@gmail.com> +Diederik de Haas <didi.debian@cknow.org> diff --git a/ChangeLog b/ChangeLog @@ -1,3 +1,9 @@ +ver 1.22: + Fix issue with handling periodic scanning. + Fix issue with handling scanning completion. + Fix issue with handling scanning for OWE auto-connect. + Add support for additional DPP features. + ver 1.21: Fix issue with handling disconnect events issued by AP. Add experimental support for DPP feature. diff --git a/Makefile.am b/Makefile.am @@ -142,7 +142,7 @@ ell_sources = ell/private.h \ ell/dhcp6-transport.c \ ell/acd.c -ell_shared = ell/useful.h +ell_shared = ell/useful.h ell/asn1-private.h ell_libell_internal_la_SOURCES = $(ell_headers) $(ell_sources) $(ell_shared) endif diff --git a/autotests/testDPP/connection_test.py b/autotests/testDPP/connection_test.py @@ -7,58 +7,107 @@ sys.path.append('../util') from iwd import IWD from wpas import Wpas from hostapd import HostapdCLI +from hwsim import Hwsim class Test(unittest.TestCase): - def test_iwd_as_enrollee(self): - wpas = Wpas('wpas.conf') + self.device.autoconnect = True + self.hapd.reload() + + uri = self.device.dpp_start_enrollee() - wd = IWD(True) + self.wpas.dpp_configurator_create(uri) + self.wpas.dpp_configurator_start('ssidCCMP', 'secret123') - devices = wd.list_devices(1) - device = devices[0] - device.autoconnect = True + condition = 'obj.state == DeviceState.connected' + self.wd.wait_for_object_condition(self.device, condition) - uri = device.dpp_start_enrollee() + def test_iwd_as_enrollee_channel_switch(self): + self.device.autoconnect = True + self.hapd.reload() - wpas.dpp_configurator_create(uri) - wpas.dpp_configurator_start('ssidCCMP', 'secret123') + uri = self.device.dpp_start_enrollee() + + self.wpas.dpp_configurator_create(uri) + self.wpas.dpp_configurator_start('ssidCCMP', 'secret123', freq=2462) condition = 'obj.state == DeviceState.connected' - wd.wait_for_object_condition(device, condition) + self.wd.wait_for_object_condition(self.device, condition) - device.disconnect() - device.dpp_stop() + def test_iwd_as_enrollee_scan_after(self): + self.wpas.disconnect() + uri = self.device.dpp_start_enrollee() - del wpas + self.wpas.dpp_configurator_create(uri) + self.wpas.dpp_configurator_start('ssidCCMP', 'secret123') - def test_iwd_as_configurator(self): - IWD.copy_to_storage('ssidCCMP.psk') + self.hapd.reload() + + with self.assertRaises(Exception): + self.device.get_ordered_network('ssidCCMP', scan_if_needed=False) - wpas = Wpas('wpas.conf') - hapd = HostapdCLI('hostapd.conf') + self.hapd.wait_for_event('AP-ENABLED') - wd = IWD(True) + self.device.autoconnect = True + + condition = 'obj.state == DeviceState.connected' + self.wd.wait_for_object_condition(self.device, condition) - devices = wd.list_devices(1) - device = devices[0] - device.autoconnect = True + def test_iwd_as_enrollee_no_ack(self): + self.rule0.enabled = True + self.device.autoconnect = True + self.hapd.reload() + + uri = self.device.dpp_start_enrollee() + + self.wpas.dpp_configurator_create(uri) + self.wpas.dpp_configurator_start('ssidCCMP', 'secret123') + + condition = 'obj.state == DeviceState.connected' + self.wd.wait_for_object_condition(self.device, condition) + + def test_iwd_as_configurator(self): + self.hapd.reload() + self.hapd.wait_for_event('AP-ENABLED') + + IWD.copy_to_storage('ssidCCMP.psk') + self.device.autoconnect = True condition = 'obj.state == DeviceState.connected' - wd.wait_for_object_condition(device, condition) + self.wd.wait_for_object_condition(self.device, condition) - uri = device.dpp_start_configurator() + uri = self.device.dpp_start_configurator() - wpas.dpp_enrollee_start(uri) + self.wpas.dpp_enrollee_start(uri) - hapd.wait_for_event('AP-STA-CONNECTED 42:00:00:00:00:00') + self.hapd.wait_for_event('AP-STA-CONNECTED 42:00:00:00:00:00') - device.disconnect() - device.dpp_stop() + def setUp(self): + self.wd = IWD(True) + self.device = self.wd.list_devices(1)[0] + self.wpas = Wpas('wpas.conf') + self.hapd = HostapdCLI('hostapd.conf') + self.hapd.disable() + self.hwsim = Hwsim() - del wpas + self.rule0 = self.hwsim.rules.create() + self.rule0.prefix = 'd0' + self.rule0.match_offset = 24 + self.rule0.match = '04 09 50 6f 9a 1a 01 01' + self.rule0.match_times = 1 + self.rule0.drop = True def tearDown(self): + print("calling Disconnect()") + self.device.disconnect() + self.device.dpp_stop() + self.wpas.dpp_configurator_remove() + + self.wd = None + self.device = None + self.wpas = None + self.hapd = None + self.rule0 = None IWD.clear_storage() @classmethod diff --git a/autotests/testDPP/hw.conf b/autotests/testDPP/hw.conf @@ -1,6 +1,7 @@ [SETUP] num_radios=3 start_iwd=0 +hwsim_medium=yes [WPA_SUPPLICANT] rad0=wpas.conf diff --git a/autotests/testPSK-roam/connection_test.py b/autotests/testPSK-roam/connection_test.py @@ -203,6 +203,8 @@ class Test(unittest.TestCase): def tearDownClass(cls): IWD.clear_storage() cls.bss_hostapd = None + cls.rule0.enabled = False + cls.rule0.remove() if __name__ == '__main__': unittest.main(exit=True) diff --git a/autotests/testPSK-roam/main.conf b/autotests/testPSK-roam/main.conf @@ -1,2 +1,5 @@ [Scan] DisableMacAddressRandomization=true + +[General] +RoamRetryInterval=1 diff --git a/autotests/testPSK-roam/roam_ap_disconnect_test.py b/autotests/testPSK-roam/roam_ap_disconnect_test.py @@ -0,0 +1,101 @@ +#! /usr/bin/python3 + +import unittest +import sys, os + +sys.path.append('../util') +from iwd import IWD +from iwd import NetworkType +from hwsim import Hwsim +from hostapd import HostapdCLI + +class Test(unittest.TestCase): + # + # Tests a crash reported where multiple roam scans combined with an AP + # disconnect result in a crash getting scan results. + # + def validate(self): + wd = IWD(True) + device = wd.list_devices(1)[0] + + ordered_network = device.get_ordered_network('TestFT', full_scan=True) + + self.assertEqual(ordered_network.type, NetworkType.psk) + + condition = 'not obj.connected' + wd.wait_for_object_condition(ordered_network.network_object, condition) + + device.connect_bssid(self.bss_hostapd[0].bssid) + + condition = 'obj.state == DeviceState.connected' + wd.wait_for_object_condition(device, condition) + + # Since both BSS's have low signal, the roam should fail and trigger + # another roam scan. + device.wait_for_event('no-roam-candidates', timeout=30) + device.wait_for_event('roam-scan-triggered', timeout=30) + + # Hostapd sends disconnect + self.bss_hostapd[0].disable() + + # IWD should recover, and not crash + condition = 'obj.state == DeviceState.disconnected' + wd.wait_for_object_condition(device, condition) + + def test_ap_disconnect_no_neighbors(self): + self.validate() + + def test_ap_disconnect_neighbors(self): + self.bss_hostapd[0].set_neighbor('12:00:00:00:00:02', 'TestFT', + '1200000000028f0000005102060603000000') + self.bss_hostapd[1].set_neighbor('12:00:00:00:00:01', 'TestFT', + '1200000000018f0000005101060603000000') + + self.validate() + + def setUp(self): + self.bss_hostapd[0].reload() + self.bss_hostapd[0].wait_for_event("AP-ENABLED") + + 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') + os.system('ip link set "' + self.bss_hostapd[0].ifname + '" up') + os.system('ip link set "' + self.bss_hostapd[1].ifname + '" up') + + self.bss_hostapd[0].remove_neighbor(self.bss_hostapd[1].bssid) + self.bss_hostapd[1].remove_neighbor(self.bss_hostapd[0].bssid) + + @classmethod + def setUpClass(cls): + hwsim = Hwsim() + + IWD.copy_to_storage('TestFT.psk') + + cls.bss_hostapd = [ HostapdCLI(config='ft-psk-ccmp-1.conf'), + HostapdCLI(config='ft-psk-ccmp-2.conf') ] + cls.bss_hostapd[1].disable() + + cls.bss_hostapd[0].set_value('ocv', '0') + cls.bss_hostapd[0].set_value('ieee80211w', '0') + + cls.rule0 = hwsim.rules.create() + cls.rule0.source = 'any' + cls.rule0.bidirectional = True + cls.rule0.signal = -8000 + cls.rule0.enabled = True + + # Set interface addresses to those expected by hostapd config files + os.system('ip link set dev "' + cls.bss_hostapd[0].ifname + '" down') + os.system('ip link set dev "' + cls.bss_hostapd[0].ifname + '" addr 12:00:00:00:00:01 up') + os.system('ip link set dev "' + cls.bss_hostapd[1].ifname + '" down') + os.system('ip link set dev "' + cls.bss_hostapd[1].ifname + '" addr 12:00:00:00:00:02 up') + + @classmethod + def tearDownClass(cls): + IWD.clear_storage() + cls.bss_hostapd = None + cls.rule0.remove() + +if __name__ == '__main__': + unittest.main(exit=True) diff --git a/autotests/util/hostapd.py b/autotests/util/hostapd.py @@ -168,6 +168,10 @@ class HostapdCLI(object): cmd = self.cmdline + ['set_neighbor', addr, 'ssid="%s"' % ssid, 'nr=%s' % nr] ctx.start_process(cmd).wait() + def remove_neighbor(self, addr): + cmd = self.cmdline + ['remove_neighbor', addr] + ctx.start_process(cmd).wait() + def send_bss_transition(self, device, nr_list): # Send a BSS transition to a station (device). nr_list should be an # array of tuples containing the BSS address and neighbor report. diff --git a/autotests/util/wpas.py b/autotests/util/wpas.py @@ -58,29 +58,20 @@ class Wpas: 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 wait_for_event(self, event, timeout=10): - self._wait_timed_out = False - - def wait_timeout_cb(): - self._wait_timed_out = True - return False - - timeout = GLib.timeout_add_seconds(timeout, wait_timeout_cb) - context = ctx.mainloop.get_context() + def _check_event(self, event): + if not event and len(self._rx_data) >= 1: + print("returning %s" % self._rx_data[0]) + return self._rx_data[0] - while True: - context.iteration(may_block=True) + for e in self._rx_data: + if event in e: + return self._rx_data - if not event and len(self._rx_data) >= 1: - return self._rx_data[0] + return False - for e in self._rx_data: - if event in e: - GLib.source_remove(timeout) - return self._rx_data - - if self._wait_timed_out: - raise TimeoutError('waiting for wpas event timed out') + def wait_for_event(self, event, timeout=10): + self._rx_data = [] + return ctx.non_block_wait(self._check_event, timeout, event) def wait_for_result(self, timeout=10): self._rx_data = [] @@ -251,30 +242,55 @@ class Wpas: self._ctrl_request('SET ' + key + ' ' + value, **kwargs) def dpp_enrollee_start(self, uri=None): + self._rx_data = [] self._ctrl_request('DPP_BOOTSTRAP_GEN type=qrcode') self.wait_for_result() if uri: + self._rx_data = [] self._ctrl_request('DPP_QR_CODE ' + uri) self._dpp_qr_id = self.wait_for_result() + self._rx_data = [] self._ctrl_request('DPP_AUTH_INIT peer=%s role=enrollee' % self._dpp_qr_id) def dpp_configurator_create(self, uri): + 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() + + self._rx_data = [] self._ctrl_request('DPP_QR_CODE ' + uri) self._dpp_qr_id = self.wait_for_result() + while not self._dpp_conf_id.isnumeric(): + self._dpp_qr_id = self.wait_for_result() print("DPP Configurator ID: %s. DPP QR ID: %s" % (self._dpp_conf_id, self._dpp_qr_id)) - def dpp_configurator_start(self, ssid, passphrase): + def dpp_configurator_start(self, ssid, passphrase, freq=None): ssid = binascii.hexlify(ssid.encode()).decode() passphrase = binascii.hexlify(passphrase.encode()).decode() - self._ctrl_request('DPP_AUTH_INIT peer=%s conf=sta-psk ssid=%s pass=%s' % (self._dpp_qr_id, ssid, passphrase)) - self.wait_for_event('DPP-AUTH-SUCCESS') + cmd = 'DPP_AUTH_INIT peer=%s conf=sta-psk ssid=%s pass=%s ' % (self._dpp_qr_id, ssid, passphrase) + + if freq: + cmd += 'neg_freq=%u ' % freq + + self._rx_data = [] + self._ctrl_request(cmd) + self.wait_for_event('DPP-AUTH-SUCCESS', timeout=30) self.wait_for_event('DPP-CONF-SENT') + def dpp_configurator_remove(self): + self._ctrl_request('DPP_CONFIGURATOR_REMOVE *') + self.wait_for_result() + self._ctrl_request('DPP_BOOTSTRAP_REMOVE *') + self.wait_for_result() + + def disconnect(self): + self._ctrl_request('DISCONNECT') + # Probably needed: remove references to self so that the GC can call __del__ automatically def clean_up(self): if self.io_watch is not None: diff --git a/configure.ac b/configure.ac @@ -1,5 +1,5 @@ AC_PREREQ(2.60) -AC_INIT(iwd, 1.21) +AC_INIT(iwd, 1.22) AC_CONFIG_HEADERS(config.h) AC_CONFIG_AUX_DIR(build-aux) @@ -268,7 +268,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.47" + ell_min_version="0.48" else ell_min_version="0.5" fi diff --git a/doc/device-provisioning.txt b/doc/device-provisioning-api.txt diff --git a/src/adhoc.c b/src/adhoc.c @@ -668,7 +668,7 @@ static void sta_append(void *data, void *user_data) { struct sta_state *sta = data; struct l_dbus_message_builder *builder = user_data; - const char* macstr; + const char *macstr; if (!sta->authenticated) return; diff --git a/src/agent.c b/src/agent.c @@ -290,8 +290,6 @@ static void agent_send_next_request(struct agent *agent) #endif pending->message = NULL; - - return; } #ifdef HAVE_DBUS diff --git a/src/anqputil.c b/src/anqputil.c @@ -48,7 +48,7 @@ bool anqp_iter_next(struct anqp_iter *iter, uint16_t *id, uint16_t *len, if (iter->pos + 4 >= iter->max) return false; - if (anqp + l_get_le16(anqp + 2) > end) + if (l_get_le16(anqp + 2) > end - anqp) return false; *id = l_get_le16(anqp); diff --git a/src/ap.c b/src/ap.c @@ -207,16 +207,22 @@ static void ap_reset(struct ap_state *ap) ap->authorized_macs_num = 0; } - if (ap->mlme_watch) + if (ap->mlme_watch) { l_genl_family_unregister(ap->nl80211, ap->mlme_watch); + ap->mlme_watch = 0; + } frame_watch_wdev_remove(netdev_get_wdev_id(netdev)); - if (ap->start_stop_cmd_id) + if (ap->start_stop_cmd_id) { l_genl_family_cancel(ap->nl80211, ap->start_stop_cmd_id); + ap->start_stop_cmd_id = 0; + } - if (ap->rtnl_add_cmd) + if (ap->rtnl_add_cmd) { l_netlink_cancel(rtnl, ap->rtnl_add_cmd); + ap->rtnl_add_cmd = 0; + } if (ap->rtnl_get_gateway4_mac_cmd) { l_netlink_cancel(rtnl, ap->rtnl_get_gateway4_mac_cmd); @@ -228,12 +234,12 @@ static void ap_reset(struct ap_state *ap) ap->rtnl_get_dns4_mac_cmd = 0; } - l_queue_destroy(ap->sta_states, ap_sta_free); + l_queue_destroy(l_steal_ptr(ap->sta_states), ap_sta_free); if (ap->rates) - l_uintset_free(ap->rates); + l_uintset_free(l_steal_ptr(ap->rates)); - l_queue_destroy(ap->wsc_pbc_probes, l_free); + l_queue_destroy(l_steal_ptr(ap->wsc_pbc_probes), l_free); l_timeout_remove(ap->wsc_pbc_timeout); ap->started = false; @@ -258,7 +264,8 @@ static bool ap_event_done(struct ap_state *ap, bool prev_in_event) ap->in_event = prev_in_event; if (!prev_in_event && ap->free_pending) { - ap_free(ap); + l_genl_family_free(ap->nl80211); + l_free(ap); return true; } @@ -3386,12 +3393,13 @@ free_ap: /* Free @ap without a graceful shutdown */ void ap_free(struct ap_state *ap) { + ap_reset(ap); + if (ap->in_event) { ap->free_pending = true; return; } - ap_reset(ap); l_genl_family_free(ap->nl80211); l_free(ap); } diff --git a/src/backtrace.c b/src/backtrace.c @@ -162,7 +162,7 @@ static void signal_handler(int signo) exit(EXIT_FAILURE); } -void __iwd_backtrace_init() +void __iwd_backtrace_init(void) { static char path[PATH_MAX]; static char cwd[PATH_MAX]; @@ -174,6 +174,7 @@ void __iwd_backtrace_init() len = readlink("/proc/self/exe", path, sizeof(path) - 1); if (len > 0) { int i; + path[len] = '\0'; for (i = len - 1; i >= 0; i--) { diff --git a/src/backtrace.h b/src/backtrace.h @@ -20,6 +20,6 @@ * */ #ifdef HAVE_BACKTRACE -void __iwd_backtrace_init(); +void __iwd_backtrace_init(void); void __iwd_backtrace_print(unsigned int offset); #endif diff --git a/src/band.c b/src/band.c @@ -151,11 +151,11 @@ static const int32_t ht_vht_base_rssi[] = { * nsds = [52, 108, 234, 468] * * for nsd in nsds: - * rates = [] - * for i in xrange(0, 10): - * data_rate = (nsd * rfactors[i] * nbpscs[i]) / 0.004 - * rates.append(int(data_rate) * 1000) - * print('rates for nsd: ' + nsd + ': ' + rates) + * rates = [] + * for i in xrange(0, 10): + * data_rate = (nsd * rfactors[i] * nbpscs[i]) / 0.004 + * rates.append(int(data_rate) * 1000) + * print('rates for nsd: ' + nsd + ': ' + rates) */ static const uint64_t ht_vht_rates[4][10] = { diff --git a/src/crypto.c b/src/crypto.c @@ -72,8 +72,9 @@ const unsigned char crypto_dh5_generator[] = { 0x2 }; size_t crypto_dh5_generator_size = sizeof(crypto_dh5_generator); static bool hmac_common(enum l_checksum_type type, - const void *key, size_t key_len, - const void *data, size_t data_len, void *output, size_t size) + const void *key, size_t key_len, + const void *data, size_t data_len, + void *output, size_t size) { struct l_checksum *hmac; @@ -438,9 +439,9 @@ free_ctr: return false; } -#define SWAP(a,b) do { int _t = a; a = b; b = _t; } while (0) +#define SWAP(a, b) do { int _t = a; a = b; b = _t; } while (0) -static void arc4_set_key(struct arc4_ctx *ctx, unsigned length, +static void arc4_set_key(struct arc4_ctx *ctx, unsigned int length, const uint8_t *key) { unsigned int i, j, k; @@ -458,8 +459,8 @@ static void arc4_set_key(struct arc4_ctx *ctx, unsigned length, ctx->i = ctx->j = 0; } -static void arc4_crypt(struct arc4_ctx *ctx, unsigned length, uint8_t *dst, - const uint8_t *src) +static void arc4_crypt(struct arc4_ctx *ctx, unsigned int length, + uint8_t *dst, const uint8_t *src) { uint8_t i, j; @@ -470,7 +471,7 @@ static void arc4_crypt(struct arc4_ctx *ctx, unsigned length, uint8_t *dst, SWAP(ctx->S[i], ctx->S[j]); if (!dst || !src) continue; - *dst++ = *src++ ^ ctx->S[ (ctx->S[i] + ctx->S[j]) & 0xff ]; + *dst++ = *src++ ^ ctx->S[(ctx->S[i] + ctx->S[j]) & 0xff]; } ctx->i = i; ctx->j = j; } diff --git a/src/dpp-util.c b/src/dpp-util.c @@ -36,6 +36,7 @@ #include "src/crypto.h" #include "src/json.h" #include "ell/useful.h" +#include "ell/asn1-private.h" #include "src/ie.h" static void append_freqs(struct l_string *uri, @@ -155,7 +156,7 @@ struct dpp_configuration *dpp_parse_configuration_object(const char *json, JSON_UNDEFINED)) goto free_contents; - if (!ssid || !util_ssid_is_utf8(strlen(ssid),(const uint8_t *)ssid)) + if (!ssid || !util_ssid_is_utf8(strlen(ssid), (const uint8_t *) ssid)) goto free_contents; if (!json_iter_parse(&cred, @@ -297,7 +298,7 @@ bool dpp_attr_iter_next(struct dpp_attr_iter *iter, const uint8_t **data_out) { enum dpp_attribute_type type; - size_t len; + uint16_t len; if (iter->pos + 4 > iter->end) return false; @@ -307,7 +308,7 @@ bool dpp_attr_iter_next(struct dpp_attr_iter *iter, iter->pos += 4; - if (iter->pos + len > iter->end) + if (iter->end - iter->pos < len) return false; *type_out = type; @@ -694,46 +695,47 @@ bool dpp_derive_ke(const uint8_t *i_nonce, const uint8_t *r_nonce, return hkdf_expand(sha, bk, key_len, "DPP Key", ke, key_len); } -#define ASN1_ID(class, pc, tag) (((class) << 6) | ((pc) << 5) | (tag)) - -#define ASN1_ID_SEQUENCE ASN1_ID(0, 1, 0x10) -#define ASN1_ID_BIT_STRING ASN1_ID(0, 0, 0x03) -#define ASN1_ID_OID ASN1_ID(0, 0, 0x06) - /* * Values derived from OID definitions in https://www.secg.org/sec2-v2.pdf * Appendix A.2.1 * * 1.2.840.10045.2.1 (ecPublicKey) */ -static uint8_t ec_oid[] = { 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01 }; +static struct asn1_oid ec_oid = { + .asn1_len = 7, + .asn1 = { 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01 } +}; /* 1.2.840.10045.3.1.7 (prime256v1) */ -static uint8_t ec_p256_oid[] = { 0x2a, 0x86, 0x48, 0xce, - 0x3d, 0x03, 0x01, 0x07 }; +static struct asn1_oid ec_p256_oid = { + .asn1_len = 8, + .asn1 = { 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07 } +}; + /* 1.3.132.0.34 (secp384r1) */ -static uint8_t ec_p384_oid[] = { 0x2B, 0x81, 0x04, 0x00, 0x22 }; +static struct asn1_oid ec_p384_oid = { + .asn1_len = 5, + .asn1 = { 0x2B, 0x81, 0x04, 0x00, 0x22 } +}; uint8_t *dpp_point_to_asn1(const struct l_ecc_point *p, size_t *len_out) { uint8_t *asn1; uint8_t *ptr; - uint8_t *type_oid; - size_t type_oid_len; + struct asn1_oid *key_type; const struct l_ecc_curve *curve = l_ecc_point_get_curve(p); ssize_t key_size = l_ecc_curve_get_scalar_bytes(curve); uint64_t x[L_ECC_MAX_DIGITS]; ssize_t ret; size_t len; + uint8_t point_type; switch (key_size) { case 32: - type_oid = ec_p256_oid; - type_oid_len = sizeof(ec_p256_oid); + key_type = &ec_p256_oid; break; case 48: - type_oid = ec_p384_oid; - type_oid_len = sizeof(ec_p384_oid); + key_type = &ec_p384_oid; break; default: return NULL; @@ -743,7 +745,18 @@ uint8_t *dpp_point_to_asn1(const struct l_ecc_point *p, size_t *len_out) if (ret < 0 || ret != key_size) return NULL; - len = 2 + sizeof(ec_oid) + 2 + type_oid_len + 2 + key_size + 4; + len = 2 + ec_oid.asn1_len + 2 + key_type->asn1_len + 2 + key_size + 4; + + /* + * 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 + * and the type is BIT1. + */ + if (l_ecc_point_y_isodd(p)) + point_type = L_ECC_POINT_TYPE_COMPRESSED_BIT0; + else + point_type = L_ECC_POINT_TYPE_COMPRESSED_BIT1; if (L_WARN_ON(len > 128)) return NULL; @@ -757,24 +770,24 @@ uint8_t *dpp_point_to_asn1(const struct l_ecc_point *p, size_t *len_out) *ptr++ = ASN1_ID_SEQUENCE; - len = sizeof(ec_oid) + type_oid_len + 4; + len = ec_oid.asn1_len + key_type->asn1_len + 4; *ptr++ = len; *ptr++ = ASN1_ID_OID; - *ptr++ = sizeof(ec_oid); - memcpy(ptr, ec_oid, sizeof(ec_oid)); - ptr += sizeof(ec_oid); + *ptr++ = ec_oid.asn1_len; + memcpy(ptr, ec_oid.asn1, ec_oid.asn1_len); + ptr += ec_oid.asn1_len; *ptr++ = ASN1_ID_OID; - *ptr++ = type_oid_len; - memcpy(ptr, type_oid, type_oid_len); - ptr += type_oid_len; + *ptr++ = key_type->asn1_len; + memcpy(ptr, key_type->asn1, key_type->asn1_len); + ptr += key_type->asn1_len; *ptr++ = ASN1_ID_BIT_STRING; *ptr++ = key_size + 2; *ptr++ = 0x00; - *ptr++ = 0x03; + *ptr++ = point_type; memcpy(ptr, x, key_size); ptr += key_size; @@ -783,3 +796,72 @@ uint8_t *dpp_point_to_asn1(const struct l_ecc_point *p, size_t *len_out) return asn1; } + +/* + * Only checking for the ASN.1 form: + * + * SEQUENCE { + * SEQUENCE { + * OBJECT IDENTIFIER ecPublicKey + * OBJECT IDENTIFIER key type (p256/p384) + * } + * BITSTRING (key data) + * } + */ +struct l_ecc_point *dpp_point_from_asn1(const uint8_t *asn1, size_t len) +{ + + const uint8_t *outer_seq; + size_t outer_len; + const uint8_t *inner_seq; + size_t inner_len; + const uint8_t *elem; + const uint8_t *key_data; + size_t elen = 0; + uint8_t tag; + unsigned int curve_num; + const struct l_ecc_curve *curve; + + /* SEQUENCE */ + outer_seq = asn1_der_find_elem(asn1, len, 0, &tag, &outer_len); + if (!outer_seq || tag != ASN1_ID_SEQUENCE) + return NULL; + + /* SEQUENCE */ + inner_seq = asn1_der_find_elem(outer_seq, outer_len, 0, &tag, &inner_len); + if (!inner_seq || tag != ASN1_ID_SEQUENCE) + return NULL; + + /* OBJECT IDENTIFIER (ecPublicKey) */ + elem = asn1_der_find_elem(inner_seq, inner_len, 0, &tag, &elen); + if (!elem || tag != ASN1_ID_OID) + return NULL; + + /* Check that this OID is ecPublicKey */ + if (!asn1_oid_eq(&ec_oid, elen, elem)) + return NULL; + + elem = asn1_der_find_elem(inner_seq, inner_len, 1, &tag, &elen); + if (!elem || tag != ASN1_ID_OID) + return NULL; + + /* Check if ELL supports this curve */ + if (asn1_oid_eq(&ec_p256_oid, elen, elem)) + curve_num = 19; + else if (asn1_oid_eq(&ec_p384_oid, elen, elem)) + curve_num = 20; + else + return NULL; + + curve = l_ecc_curve_from_ike_group(curve_num); + if (!curve) + return NULL; + + /* BITSTRING */ + key_data = asn1_der_find_elem(outer_seq, outer_len, 1, &tag, &elen); + if (!key_data || tag != ASN1_ID_BIT_STRING || elen > 2) + return NULL; + + return l_ecc_point_from_data(curve, key_data[1], + key_data + 2, elen - 2); +} diff --git a/src/dpp-util.h b/src/dpp-util.h @@ -167,3 +167,4 @@ bool dpp_derive_ke(const uint8_t *i_nonce, const uint8_t *r_nonce, 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); diff --git a/src/dpp.c b/src/dpp.c @@ -30,6 +30,7 @@ #include "linux/nl80211.h" +#include "src/missing.h" #include "src/dbus.h" #include "src/netdev.h" #include "src/module.h" @@ -51,10 +52,15 @@ #include "src/scan.h" #include "src/network.h" #include "src/handshake.h" +#include "src/nl80211util.h" + +#define DPP_FRAME_MAX_RETRIES 5 static uint32_t netdev_watch; static struct l_genl_family *nl80211; static uint8_t broadcast[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; +static struct l_queue *dpp_list; +static uint32_t mlme_watch; enum dpp_state { DPP_STATE_NOTHING, @@ -75,9 +81,9 @@ struct dpp_sm { uint64_t wdev_id; - uint8_t *pub_asn1; - size_t pub_asn1_len; - uint8_t pub_boot_hash[32]; + uint8_t *own_asn1; + size_t own_asn1_len; + uint8_t own_boot_hash[32]; const struct l_ecc_curve *curve; size_t key_len; size_t nonce_len; @@ -91,6 +97,7 @@ struct dpp_sm { size_t freqs_idx; uint32_t dwell; uint32_t current_freq; + uint32_t new_freq; struct scan_freq_set *presence_list; uint32_t offchannel_id; @@ -102,11 +109,12 @@ struct dpp_sm { uint64_t ke[L_ECC_MAX_DIGITS]; uint64_t k2[L_ECC_MAX_DIGITS]; + uint64_t auth_tag[L_ECC_MAX_DIGITS]; struct l_ecc_scalar *proto_private; - struct l_ecc_point *proto_public; + struct l_ecc_point *own_proto_public; - struct l_ecc_point *i_proto_public; + struct l_ecc_point *peer_proto_public; uint8_t diag_token; @@ -114,13 +122,18 @@ struct dpp_sm { struct l_timeout *timeout; struct dpp_configuration *config; + uint32_t connect_scan_id; + uint64_t frame_cookie; + uint8_t frame_retry; + + struct l_dbus_message *pending; }; static void dpp_free_auth_data(struct dpp_sm *dpp) { - if (dpp->proto_public) { - l_ecc_point_free(dpp->proto_public); - dpp->proto_public = NULL; + if (dpp->own_proto_public) { + l_ecc_point_free(dpp->own_proto_public); + dpp->own_proto_public = NULL; } if (dpp->proto_private) { @@ -128,9 +141,9 @@ static void dpp_free_auth_data(struct dpp_sm *dpp) dpp->proto_private = NULL; } - if (dpp->i_proto_public) { - l_ecc_point_free(dpp->i_proto_public); - dpp->i_proto_public = NULL; + if (dpp->peer_proto_public) { + l_ecc_point_free(dpp->peer_proto_public); + dpp->peer_proto_public = NULL; } } @@ -161,13 +174,22 @@ static void dpp_reset(struct dpp_sm *dpp) dpp->config = NULL; } + if (dpp->connect_scan_id) { + scan_cancel(dpp->wdev_id, dpp->connect_scan_id); + dpp->connect_scan_id = 0; + } + dpp->state = DPP_STATE_NOTHING; + dpp->new_freq = 0; + dpp->frame_retry = 0; + dpp->frame_cookie = 0; explicit_bzero(dpp->r_nonce, dpp->nonce_len); explicit_bzero(dpp->i_nonce, dpp->nonce_len); explicit_bzero(dpp->e_nonce, dpp->nonce_len); explicit_bzero(dpp->ke, dpp->key_len); explicit_bzero(dpp->k2, dpp->key_len); + explicit_bzero(dpp->auth_tag, dpp->key_len); dpp_free_auth_data(dpp); } @@ -176,9 +198,9 @@ static void dpp_free(struct dpp_sm *dpp) { dpp_reset(dpp); - if (dpp->pub_asn1) { - l_free(dpp->pub_asn1); - dpp->pub_asn1 = NULL; + if (dpp->own_asn1) { + l_free(dpp->own_asn1); + dpp->own_asn1 = NULL; } if (dpp->boot_public) { @@ -196,25 +218,36 @@ static void dpp_free(struct dpp_sm *dpp) static void dpp_send_frame_cb(struct l_genl_msg *msg, void *user_data) { - if (l_genl_msg_get_error(msg) < 0) + struct dpp_sm *dpp = user_data; + + if (l_genl_msg_get_error(msg) < 0) { l_error("Error sending frame"); + return; + } + + if (nl80211_parse_attrs(msg, NL80211_ATTR_COOKIE, &dpp->frame_cookie, + NL80211_ATTR_UNSPEC) < 0) + l_error("Error parsing frame cookie"); } -static void dpp_send_frame(uint64_t wdev_id, struct iovec *iov, size_t iov_len, - uint32_t freq) +static void dpp_send_frame(struct dpp_sm *dpp, + struct iovec *iov, size_t iov_len, + uint32_t freq) { struct l_genl_msg *msg; msg = l_genl_msg_new_sized(NL80211_CMD_FRAME, 512); - l_genl_msg_append_attr(msg, NL80211_ATTR_WDEV, 8, &wdev_id); + l_genl_msg_append_attr(msg, NL80211_ATTR_WDEV, 8, &dpp->wdev_id); l_genl_msg_append_attr(msg, NL80211_ATTR_WIPHY_FREQ, 4, &freq); l_genl_msg_append_attr(msg, NL80211_ATTR_OFFCHANNEL_TX_OK, 0, NULL); l_genl_msg_append_attrv(msg, NL80211_ATTR_FRAME, iov, iov_len); l_debug("Sending frame on frequency %u", freq); - if (!l_genl_family_send(nl80211, msg, dpp_send_frame_cb, NULL, NULL)) + if (!l_genl_family_send(nl80211, msg, dpp_send_frame_cb, dpp, NULL)) { l_error("Could not send CMD_FRAME"); + l_genl_msg_unref(msg); + } } static size_t dpp_build_header(const uint8_t *src, const uint8_t *dest, @@ -363,7 +396,7 @@ static void dpp_configuration_start(struct dpp_sm *dpp, const uint8_t *addr) dpp->state = DPP_STATE_CONFIGURING; - dpp_send_frame(dpp->wdev_id, iov, 2, dpp->current_freq); + dpp_send_frame(dpp, iov, 2, dpp->current_freq); } static void send_config_result(struct dpp_sm *dpp, const uint8_t *to) @@ -386,14 +419,17 @@ static void send_config_result(struct dpp_sm *dpp, const uint8_t *to) iov[1].iov_base = attrs; iov[1].iov_len = ptr - attrs; - dpp_send_frame(dpp->wdev_id, iov, 2, dpp->current_freq); + dpp_send_frame(dpp, iov, 2, dpp->current_freq); } -static void dpp_write_config(struct dpp_configuration *config) +static void dpp_write_config(struct dpp_configuration *config, + struct network *network) { - _auto_(l_free) char *ssid = l_malloc(config->ssid_len + 1); + 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'; @@ -405,18 +441,57 @@ static void dpp_write_config(struct dpp_configuration *config) l_settings_remove_group(settings, "Security"); } - if (config->passphrase) + if (config->passphrase) { l_settings_set_string(settings, "Security", "Passphrase", config->passphrase); - else if (config->psk) + if (network) + network_set_passphrase(network, config->passphrase); + + } else if (config->psk) { l_settings_set_string(settings, "Security", "PreSharedKey", config->psk); + psk = l_util_from_hexstring(config->psk, &psk_len); + + if (network) + network_set_psk(network, psk); + } + l_debug("Storing credential for '%s(%s)'", ssid, security_to_str(SECURITY_PSK)); storage_network_sync(SECURITY_PSK, ssid, settings); } +static void dpp_scan_triggered(int err, void *user_data) +{ + /* Not much can be done in this case */ + if (err < 0) + l_error("Failed to trigger DPP scan"); +} + +static bool dpp_scan_results(int err, struct l_queue *bss_list, + const struct scan_freq_set *freqs, + void *userdata) +{ + struct dpp_sm *dpp = userdata; + struct station *station = station_find(netdev_get_ifindex(dpp->netdev)); + + if (err < 0) + return false; + + station_set_scan_results(station, bss_list, freqs, true); + + return true; +} + +static void dpp_scan_destroy(void *userdata) +{ + struct dpp_sm *dpp = userdata; + + dpp->connect_scan_id = 0; + dpp_reset(dpp); +} + static void dpp_handle_config_response_frame(const struct mmpdu_header *frame, const void *body, size_t body_len, int rssi, void *user_data) @@ -441,6 +516,10 @@ static void dpp_handle_config_response_frame(const struct mmpdu_header *frame, size_t wrapped_len = 0; _auto_(l_free) uint8_t *unwrapped = NULL; struct dpp_configuration *config; + 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; @@ -564,31 +643,51 @@ static void dpp_handle_config_response_frame(const struct mmpdu_header *frame, return; } - dpp_write_config(config); /* - * TODO: Depending on the info included in the configuration object a - * limited scan could be issued to get autoconnect to trigger faster. - * In addition this network may already be in past scan results and - * could be joined immediately. - * - * For now just wait for autoconnect. + * We should have a station device, but if not DPP can write the + * 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); + if (network) + bss = network_bss_select(network, true); + } + + dpp_write_config(config, network); dpp_configuration_free(config); send_config_result(dpp, dpp->auth_addr); + + offchannel_cancel(dpp->wdev_id, dpp->offchannel_id); + + if (network && bss) + __station_connect_network(station, network, bss); + else if (station) { + dpp->connect_scan_id = scan_active(dpp->wdev_id, NULL, 0, + dpp_scan_triggered, + dpp_scan_results, dpp, + dpp_scan_destroy); + if (dpp->connect_scan_id) + return; + } + + dpp_reset(dpp); } -static void dpp_send_config_response(struct dpp_sm *dpp) +static void dpp_send_config_response(struct dpp_sm *dpp, uint8_t status) { - _auto_(l_free) char *json; + _auto_(l_free) char *json = NULL; struct iovec iov[3]; uint8_t hdr[41]; uint8_t attrs[512]; size_t json_len; - uint8_t zero = 0; uint8_t *ptr = hdr + 24; + memset(hdr, 0, sizeof(hdr)); + l_put_le16(0x00d0, hdr); memcpy(hdr + 4, dpp->auth_addr, 6); memcpy(hdr + 10, netdev_get_address(dpp->netdev), 6); @@ -611,9 +710,6 @@ static void dpp_send_config_response(struct dpp_sm *dpp) *ptr++ = 0x1a; *ptr++ = 1; - json = dpp_configuration_to_json(dpp->config); - json_len = strlen(json); - iov[0].iov_base = hdr; iov[0].iov_len = ptr - hdr; @@ -621,19 +717,38 @@ static void dpp_send_config_response(struct dpp_sm *dpp) ptr += 2; /* length */ - ptr += dpp_append_attr(ptr, DPP_ATTR_STATUS, &zero, 1); + ptr += dpp_append_attr(ptr, DPP_ATTR_STATUS, &status, 1); - ptr += dpp_append_wrapped_data(attrs + 2, ptr - attrs - 2, NULL, 0, ptr, - sizeof(attrs), dpp->ke, dpp->key_len, 2, - DPP_ATTR_ENROLLEE_NONCE, dpp->nonce_len, dpp->e_nonce, - DPP_ATTR_CONFIGURATION_OBJECT, json_len, json); + /* + * There are several failure status codes that can be used (defined in + * 6.4.3.1), each with their own set of attributes that should be + * included. For now IWD's basic DPP implementation will assume + * STATUS_CONFIGURE_FAILURE which only includes the E-Nonce. + */ + if (status == DPP_STATUS_OK) { + json = dpp_configuration_to_json(dpp->config); + json_len = strlen(json); + + ptr += dpp_append_wrapped_data(attrs + 2, ptr - attrs - 2, + NULL, 0, ptr, sizeof(attrs), + dpp->ke, dpp->key_len, 2, + DPP_ATTR_ENROLLEE_NONCE, + dpp->nonce_len, dpp->e_nonce, + DPP_ATTR_CONFIGURATION_OBJECT, + json_len, json); + } else + ptr += dpp_append_wrapped_data(attrs + 2, ptr - attrs - 2, + NULL, 0, ptr, sizeof(attrs), + dpp->ke, dpp->key_len, 2, + DPP_ATTR_ENROLLEE_NONCE, + dpp->nonce_len, dpp->e_nonce); l_put_le16(ptr - attrs - 2, attrs); iov[1].iov_base = attrs; iov[1].iov_len = ptr - attrs; - dpp_send_frame(dpp->wdev_id, iov, 2, dpp->current_freq); + dpp_send_frame(dpp, iov, 2, dpp->current_freq); } static void dpp_handle_config_request_frame(const struct mmpdu_header *frame, @@ -655,6 +770,9 @@ static void dpp_handle_config_request_frame(const struct mmpdu_header *frame, _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; if (dpp->state != DPP_STATE_AUTHENTICATING) { l_debug("Configuration request in wrong state"); @@ -747,25 +865,47 @@ static void dpp_handle_config_request_frame(const struct mmpdu_header *frame, return; } - /* - * TODO: Full JSON type support (arrays/numbers) is not yet implemented. - * Just verify the JSON is valid for now. There really isn't much need - * to parse this anyhow since IWD only supports configuring stations. - * If this request is for anything else it will fail regardless. - */ c = json_contents_new(json, json_len); if (!c) { json_contents_free(c); return; } + json_iter_init(&jsiter, c); + + /* + * Check mandatory values (Table 7). There isn't much that can be done + * with these, but the spec requires they be included. + */ + if (!json_iter_parse(&jsiter, + JSON_MANDATORY("name", JSON_STRING, NULL), + JSON_MANDATORY("wi-fi_tech", JSON_STRING, &tech), + JSON_MANDATORY("netRole", JSON_STRING, &role), + JSON_UNDEFINED)) + goto configure_failure; + + if (strcmp(tech, "infra")) + goto configure_failure; + + if (strcmp(role, "sta")) + goto configure_failure; + json_contents_free(c); memcpy(dpp->e_nonce, e_nonce, dpp->nonce_len); dpp->state = DPP_STATE_CONFIGURING; - dpp_send_config_response(dpp); + dpp_send_config_response(dpp, DPP_STATUS_OK); + + return; + +configure_failure: + dpp_send_config_response(dpp, DPP_STATUS_CONFIGURE_FAILURE); + /* + * The other peer is still authenticated, and can potentially send + * additional requests so keep this session alive. + */ } static void dpp_handle_config_result_frame(struct dpp_sm *dpp, @@ -858,7 +998,7 @@ static void dpp_handle_config_result_frame(struct dpp_sm *dpp, * ad1 = attrs * ad1_len = ptr - attrs */ -static void send_authenticate_response(struct dpp_sm *dpp, void *r_auth) +static void send_authenticate_response(struct dpp_sm *dpp) { uint8_t hdr[32]; uint8_t attrs[256]; @@ -871,7 +1011,7 @@ static void send_authenticate_response(struct dpp_sm *dpp, void *r_auth) uint8_t wrapped2[dpp->key_len + 16 + 8]; size_t wrapped2_len; - l_ecc_point_get_data(dpp->proto_public, r_proto_key, + l_ecc_point_get_data(dpp->own_proto_public, r_proto_key, sizeof(r_proto_key)); iov[0].iov_len = dpp_build_header(netdev_get_address(dpp->netdev), @@ -881,7 +1021,7 @@ static void send_authenticate_response(struct dpp_sm *dpp, void *r_auth) ptr += dpp_append_attr(ptr, DPP_ATTR_STATUS, &status, 1); ptr += dpp_append_attr(ptr, DPP_ATTR_RESPONDER_BOOT_KEY_HASH, - dpp->pub_boot_hash, 32); + dpp->own_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); @@ -889,7 +1029,7 @@ static void send_authenticate_response(struct dpp_sm *dpp, void *r_auth) /* Wrap up secondary data (R-Auth) */ wrapped2_len = dpp_append_attr(wrapped2_plaintext, DPP_ATTR_RESPONDER_AUTH_TAG, - r_auth, dpp->key_len); + dpp->auth_tag, dpp->key_len); /* * "Invocations of AES-SIV in the DPP Authentication protocol that * produce ciphertext that is part of an additional AES-SIV invocation @@ -911,8 +1051,7 @@ static void send_authenticate_response(struct dpp_sm *dpp, void *r_auth) iov[1].iov_base = attrs; iov[1].iov_len = ptr - attrs; - dpp_send_frame(netdev_get_wdev_id(dpp->netdev), iov, 2, - dpp->current_freq); + dpp_send_frame(dpp, iov, 2, dpp->current_freq); } static void authenticate_confirm(struct dpp_sm *dpp, const uint8_t *from, @@ -1026,7 +1165,7 @@ static void authenticate_confirm(struct dpp_sm *dpp, const uint8_t *from, } dpp_derive_i_auth(dpp->r_nonce, dpp->i_nonce, dpp->nonce_len, - dpp->proto_public, dpp->i_proto_public, + dpp->own_proto_public, dpp->peer_proto_public, dpp->boot_public, i_auth_check); if (memcmp(i_auth, i_auth_check, i_auth_len)) { @@ -1066,7 +1205,7 @@ static void dpp_auth_request_failed(struct dpp_sm *dpp, ptr += dpp_append_attr(ptr, DPP_ATTR_STATUS, &s, 1); ptr += dpp_append_attr(ptr, DPP_ATTR_RESPONDER_BOOT_KEY_HASH, - dpp->pub_boot_hash, 32); + dpp->own_boot_hash, 32); ptr += dpp_append_attr(ptr, DPP_ATTR_PROTOCOL_VERSION, &version, 1); @@ -1078,8 +1217,7 @@ static void dpp_auth_request_failed(struct dpp_sm *dpp, iov[1].iov_base = attrs; iov[1].iov_len = ptr - attrs; - dpp_send_frame(netdev_get_wdev_id(dpp->netdev), iov, 2, - dpp->current_freq); + dpp_send_frame(dpp, iov, 2, dpp->current_freq); } static bool dpp_check_roles(struct dpp_sm *dpp, uint8_t peer_capa) @@ -1094,6 +1232,151 @@ static bool dpp_check_roles(struct dpp_sm *dpp, uint8_t peer_capa) return true; } +static void dpp_presence_announce(struct dpp_sm *dpp) +{ + struct netdev *netdev = dpp->netdev; + uint8_t hdr[32]; + uint8_t attrs[32 + 4]; + uint8_t hash[32]; + uint8_t *ptr = attrs; + const uint8_t *addr = netdev_get_address(netdev); + struct iovec iov[2]; + + iov[0].iov_len = dpp_build_header(addr, broadcast, + DPP_FRAME_PRESENCE_ANNOUNCEMENT, hdr); + iov[0].iov_base = hdr; + + dpp_hash(L_CHECKSUM_SHA256, hash, 2, "chirp", strlen("chirp"), + dpp->own_asn1, dpp->own_asn1_len); + + ptr += dpp_append_attr(ptr, DPP_ATTR_RESPONDER_BOOT_KEY_HASH, hash, 32); + + iov[1].iov_base = attrs; + iov[1].iov_len = ptr - attrs; + + l_debug("Sending presence announcement on frequency %u and waiting %u", + dpp->current_freq, dpp->dwell); + + dpp_send_frame(dpp, iov, 2, dpp->current_freq); +} + +static void dpp_roc_started(void *user_data) +{ + struct dpp_sm *dpp = user_data; + + /* + * - If a configurator, nothing to do but wait for a request + * - If in the presence state continue sending announcements. + * - If authenticating, and this is a result of a channel switch send + * the authenticate response now. + */ + if (dpp->role == DPP_CAPABILITY_CONFIGURATOR) + return; + + switch (dpp->state) { + case DPP_STATE_PRESENCE: + if (dpp->pending) { + struct l_dbus_message *reply = + l_dbus_message_new_method_return(dpp->pending); + + l_dbus_message_set_arguments(reply, "s", dpp->uri); + + dbus_pending_reply(&dpp->pending, reply); + } + + dpp_presence_announce(dpp); + break; + case DPP_STATE_AUTHENTICATING: + if (dpp->new_freq) { + dpp->current_freq = dpp->new_freq; + dpp->new_freq = 0; + send_authenticate_response(dpp); + } + + break; + default: + break; + } +} + +static void dpp_start_offchannel(struct dpp_sm *dpp, uint32_t freq); + +static void dpp_presence_timeout(int error, void *user_data) +{ + struct dpp_sm *dpp = user_data; + + dpp->offchannel_id = 0; + + /* + * If cancelled this is likely due to netdev going down or from Stop(). + * Otherwise there was some other problem which is probably not + * recoverable. + */ + if (error == -ECANCELED) + return; + else if (error == -EIO) + goto next_roc; + else if (error < 0) + goto protocol_failed; + + switch (dpp->state) { + case DPP_STATE_PRESENCE: + break; + case DPP_STATE_NOTHING: + /* Protocol already terminated */ + return; + case DPP_STATE_AUTHENTICATING: + case DPP_STATE_CONFIGURING: + goto next_roc; + } + + dpp->freqs_idx++; + + if (dpp->freqs_idx >= dpp->freqs_len) { + l_debug("Max retries on presence announcements"); + dpp->freqs_idx = 0; + } + + dpp->current_freq = dpp->freqs[dpp->freqs_idx]; + + l_debug("Presence timeout, moving to next frequency %u, duration %u", + dpp->current_freq, dpp->dwell); + +next_roc: + dpp_start_offchannel(dpp, dpp->current_freq); + + return; + +protocol_failed: + dpp_reset(dpp); +} + +static void dpp_start_offchannel(struct dpp_sm *dpp, uint32_t freq) +{ + /* + * This needs to be handled carefully for a few reasons: + * + * First, the next offchannel operation needs to be started prior to + * canceling an existing one. This is so the offchannel work can + * continue uninterrupted without any other work items starting in + * 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). + */ + uint32_t id = offchannel_start(netdev_get_wdev_id(dpp->netdev), + freq, dpp->dwell, dpp_roc_started, + dpp, dpp_presence_timeout); + + if (dpp->offchannel_id) + offchannel_cancel(dpp->wdev_id, dpp->offchannel_id); + + dpp->offchannel_id = id; +} + static void authenticate_request(struct dpp_sm *dpp, const uint8_t *from, const uint8_t *body, size_t body_len) { @@ -1113,9 +1396,9 @@ static void authenticate_request(struct dpp_sm *dpp, const uint8_t *from, _auto_(l_ecc_scalar_free) struct l_ecc_scalar *m = NULL; _auto_(l_ecc_scalar_free) struct l_ecc_scalar *n = NULL; uint64_t k1[L_ECC_MAX_DIGITS]; - uint64_t r_auth[L_ECC_MAX_DIGITS]; const void *ad0 = body + 2; const void *ad1 = body + 8; + uint32_t freq; if (dpp->state != DPP_STATE_PRESENCE) return; @@ -1155,20 +1438,38 @@ static void authenticate_request(struct dpp_sm *dpp, const uint8_t *from, } break; - /* - * TODO: Go on this channel for remainder of auth protocol. - * - * "the Responder determines whether it can use the requested - * channel for the following exchanges. If so, it sends the DPP - * Authentication Response frame on that channel. If not, it - * discards the DPP Authentication Request frame without - * replying to it." - * - * For the time being this feature is not being implemented and - * the frame will be dropped. - */ + case DPP_ATTR_CHANNEL: - return; + if (len != 2) + return; + + freq = oci_to_frequency(l_get_u8(data), + l_get_u8(data + 1)); + + if (freq == dpp->current_freq) + break; + + /* + * Configurators are already connected to a network, so + * to preserve wireless performance the enrollee will + * be required to be on this channel, not a channel it + * requests. + */ + if (dpp->role == DPP_CAPABILITY_CONFIGURATOR) + return; + + /* + * Otherwise, as an enrollee, we can jump to whatever + * channel the configurator requests + */ + dpp->new_freq = freq; + + l_debug("Configurator requested a new frequency %u", + dpp->new_freq); + + dpp_start_offchannel(dpp, dpp->new_freq); + + break; default: break; } @@ -1177,21 +1478,21 @@ static void authenticate_request(struct dpp_sm *dpp, const uint8_t *from, if (!r_boot || !i_boot || !i_proto || !wrapped) goto auth_request_failed; - if (r_boot_len != 32 || memcmp(dpp->pub_boot_hash, + if (r_boot_len != 32 || memcmp(dpp->own_boot_hash, r_boot, r_boot_len)) { l_debug("Responder boot key hash failed to verify"); goto auth_request_failed; } - dpp->i_proto_public = l_ecc_point_from_data(dpp->curve, + dpp->peer_proto_public = l_ecc_point_from_data(dpp->curve, L_ECC_POINT_TYPE_FULL, i_proto, i_proto_len); - if (!dpp->i_proto_public) { + if (!dpp->peer_proto_public) { l_debug("Initiators protocol key invalid"); goto auth_request_failed; } - m = dpp_derive_k1(dpp->i_proto_public, dpp->boot_private, k1); + m = dpp_derive_k1(dpp->peer_proto_public, dpp->boot_private, k1); if (!m) goto auth_request_failed; @@ -1241,9 +1542,9 @@ static void authenticate_request(struct dpp_sm *dpp, const uint8_t *from, /* Derive keys k2, ke, and R-Auth for authentication response */ l_ecdh_generate_key_pair(dpp->curve, &dpp->proto_private, - &dpp->proto_public); + &dpp->own_proto_public); - n = dpp_derive_k2(dpp->i_proto_public, dpp->proto_private, dpp->k2); + n = dpp_derive_k2(dpp->peer_proto_public, dpp->proto_private, dpp->k2); if (!n) goto auth_request_failed; @@ -1253,8 +1554,8 @@ static void authenticate_request(struct dpp_sm *dpp, const uint8_t *from, goto auth_request_failed; if (!dpp_derive_r_auth(dpp->i_nonce, dpp->r_nonce, dpp->nonce_len, - dpp->i_proto_public, dpp->proto_public, - dpp->boot_public, r_auth)) + dpp->peer_proto_public, dpp->own_proto_public, + dpp->boot_public, dpp->auth_tag)) goto auth_request_failed; memcpy(dpp->auth_addr, from, 6); @@ -1262,7 +1563,9 @@ static void authenticate_request(struct dpp_sm *dpp, const uint8_t *from, dpp->state = DPP_STATE_AUTHENTICATING; dpp_reset_protocol_timer(dpp); - send_authenticate_response(dpp, r_auth); + /* Don't send if the frequency is changing */ + if (!dpp->new_freq) + send_authenticate_response(dpp); return; @@ -1305,47 +1608,57 @@ static void dpp_handle_frame(const struct mmpdu_header *frame, } } -static void dpp_presence_announce(struct dpp_sm *dpp) +static bool match_wdev(const void *a, const void *b) { - struct netdev *netdev = dpp->netdev; - uint8_t hdr[32]; - uint8_t attrs[32 + 4]; - uint8_t hash[32]; - uint8_t *ptr = attrs; - const uint8_t *addr = netdev_get_address(netdev); - struct iovec iov[2]; - - iov[0].iov_len = dpp_build_header(addr, broadcast, - DPP_FRAME_PRESENCE_ANNOUNCEMENT, hdr); - iov[0].iov_base = hdr; + const struct dpp_sm *dpp = a; + const uint64_t *wdev_id = b; - dpp_hash(L_CHECKSUM_SHA256, hash, 2, "chirp", strlen("chirp"), - dpp->pub_asn1, dpp->pub_asn1_len); - - ptr += dpp_append_attr(ptr, DPP_ATTR_RESPONDER_BOOT_KEY_HASH, hash, 32); + return *wdev_id == dpp->wdev_id; +} - iov[1].iov_base = attrs; - iov[1].iov_len = ptr - attrs; +static void dpp_mlme_notify(struct l_genl_msg *msg, void *user_data) +{ + struct dpp_sm *dpp; + uint64_t wdev_id = 0; + uint64_t cookie = 0; + bool ack = false; + struct iovec iov; + uint8_t cmd = l_genl_msg_get_command(msg); + + if (cmd != NL80211_CMD_FRAME_TX_STATUS) + return; - l_debug("Sending presense annoucement on frequency %u and waiting %u", - dpp->current_freq, dpp->dwell); + if (nl80211_parse_attrs(msg, NL80211_ATTR_WDEV, &wdev_id, + NL80211_ATTR_COOKIE, &cookie, + NL80211_ATTR_ACK, &ack, + NL80211_ATTR_FRAME, &iov, + NL80211_ATTR_UNSPEC) < 0) + return; - dpp_send_frame(netdev_get_wdev_id(netdev), iov, 2, dpp->current_freq); -} + dpp = l_queue_find(dpp_list, match_wdev, &wdev_id); + if (!dpp) + return; -static void dpp_roc_started(void *user_data) -{ - struct dpp_sm *dpp = user_data; + if (dpp->state <= DPP_STATE_PRESENCE) + return; /* - * If not in presence procedure or in a configurator role, just stay - * on channel. + * Only want to handle the no-ACK case. Re-transmitting an ACKed + * frame likely wont do any good, at least in the case of DPP. */ - if (dpp->state != DPP_STATE_PRESENCE || - dpp->role == DPP_CAPABILITY_CONFIGURATOR) + if (dpp->frame_cookie != cookie || ack) return; - dpp_presence_announce(dpp); + if (dpp->frame_retry > DPP_FRAME_MAX_RETRIES) { + dpp_reset(dpp); + return; + } + + l_debug("No ACK from peer, re-transmitting"); + + dpp->frame_retry++; + + dpp_send_frame(dpp, &iov, 1, dpp->current_freq); } static void dpp_create(struct netdev *netdev) @@ -1366,10 +1679,10 @@ static void dpp_create(struct netdev *netdev) l_ecdh_generate_key_pair(dpp->curve, &dpp->boot_private, &dpp->boot_public); - dpp->pub_asn1 = dpp_point_to_asn1(dpp->boot_public, &dpp->pub_asn1_len); + dpp->own_asn1 = dpp_point_to_asn1(dpp->boot_public, &dpp->own_asn1_len); - dpp_hash(L_CHECKSUM_SHA256, dpp->pub_boot_hash, 1, - dpp->pub_asn1, dpp->pub_asn1_len); + dpp_hash(L_CHECKSUM_SHA256, dpp->own_boot_hash, 1, + dpp->own_asn1, dpp->own_asn1_len); l_dbus_object_add_interface(dbus, netdev_get_path(netdev), IWD_DPP_INTERFACE, dpp); @@ -1385,6 +1698,8 @@ static void dpp_create(struct netdev *netdev) dpp_conf_request_prefix, sizeof(dpp_conf_request_prefix), dpp_handle_config_request_frame, dpp, NULL); + + l_queue_push_tail(dpp_list, dpp); } static void dpp_netdev_watch(struct netdev *netdev, @@ -1408,56 +1723,6 @@ static void dpp_netdev_watch(struct netdev *netdev, } } -static void dpp_presence_timeout(int error, void *user_data) -{ - struct dpp_sm *dpp = user_data; - - /* - * If cancelled this is likely due to netdev going down or from Stop(). - * Otherwise there was some other problem which is probably not - * recoverable. - */ - if (error == -ECANCELED) - return; - else if (error == -EIO) - goto next_roc; - else if (error < 0) - goto protocol_failed; - - switch (dpp->state) { - case DPP_STATE_PRESENCE: - break; - case DPP_STATE_NOTHING: - /* Protocol already terminated */ - return; - case DPP_STATE_AUTHENTICATING: - case DPP_STATE_CONFIGURING: - goto next_roc; - } - - dpp->freqs_idx++; - - if (dpp->freqs_idx >= dpp->freqs_len) { - l_debug("Max retries on presence announcements"); - dpp->freqs_idx = 0; - } - - dpp->current_freq = dpp->freqs[dpp->freqs_idx]; - - l_debug("Presence timeout, moving to next frequency %u, duration %u", - dpp->current_freq, dpp->dwell); - -next_roc: - dpp->offchannel_id = offchannel_start(netdev_get_wdev_id(dpp->netdev), - dpp->current_freq, dpp->dwell, dpp_roc_started, - dpp, dpp_presence_timeout); - return; - -protocol_failed: - dpp_reset(dpp); - return; -} - /* * EasyConnect 2.0 - 6.2.2 */ @@ -1517,9 +1782,7 @@ static void dpp_start_presence(struct dpp_sm *dpp, uint32_t *limit_freqs, dpp->freqs_idx = 0; dpp->current_freq = dpp->freqs[0]; - dpp->offchannel_id = offchannel_start(netdev_get_wdev_id(dpp->netdev), - dpp->current_freq, dpp->dwell, dpp_roc_started, - dpp, dpp_presence_timeout); + dpp_start_offchannel(dpp, dpp->current_freq); } static struct l_dbus_message *dpp_dbus_start_enrollee(struct l_dbus *dbus, @@ -1528,12 +1791,22 @@ static struct l_dbus_message *dpp_dbus_start_enrollee(struct l_dbus *dbus, { struct dpp_sm *dpp = user_data; uint32_t freq = band_channel_to_freq(6, BAND_FREQ_2_4_GHZ); - struct l_dbus_message *reply; + struct station *station = station_find(netdev_get_ifindex(dpp->netdev)); if (dpp->state != DPP_STATE_NOTHING) return dbus_error_busy(message); - dpp->uri = dpp_generate_uri(dpp->pub_asn1, dpp->pub_asn1_len, 2, + /* + * Station isn't actually required for DPP itself, although this will + * prevent connecting to the network once configured. + */ + if (station && station_get_connected_network(station)) { + l_warn("cannot be enrollee while connected, please disconnect"); + return dbus_error_busy(message); + } else if (!station) + l_debug("No station device, continuing anyways..."); + + dpp->uri = dpp_generate_uri(dpp->own_asn1, dpp->own_asn1_len, 2, netdev_get_address(dpp->netdev), &freq, 1, NULL, NULL); @@ -1542,6 +1815,8 @@ static struct l_dbus_message *dpp_dbus_start_enrollee(struct l_dbus *dbus, l_debug("DPP Start Enrollee: %s", dpp->uri); + dpp->pending = l_dbus_message_ref(message); + /* * Going off spec here. Select a single channel to send presence * announcements on. This will be advertised in the URI. The full @@ -1549,11 +1824,9 @@ static struct l_dbus_message *dpp_dbus_start_enrollee(struct l_dbus *dbus, */ dpp_start_presence(dpp, &freq, 1); - reply = l_dbus_message_new_method_return(message); - - l_dbus_message_set_arguments(reply, "s", dpp->uri); + scan_periodic_stop(dpp->wdev_id); - return reply; + return NULL; } static struct l_dbus_message *dpp_dbus_start_configurator(struct l_dbus *dbus, @@ -1590,7 +1863,7 @@ static struct l_dbus_message *dpp_dbus_start_configurator(struct l_dbus *dbus, if (dpp->state != DPP_STATE_NOTHING) return dbus_error_busy(message); - dpp->uri = dpp_generate_uri(dpp->pub_asn1, dpp->pub_asn1_len, 2, + dpp->uri = dpp_generate_uri(dpp->own_asn1, dpp->own_asn1_len, 2, netdev_get_address(dpp->netdev), &bss->frequency, 1, NULL, NULL); @@ -1601,6 +1874,8 @@ static struct l_dbus_message *dpp_dbus_start_configurator(struct l_dbus *dbus, network_get_ssid(network), hs->akm_suite); + scan_periodic_stop(dpp->wdev_id); + l_debug("DPP Start Configurator: %s", dpp->uri); reply = l_dbus_message_new_method_return(message); @@ -1635,6 +1910,8 @@ static void dpp_destroy_interface(void *user_data) { struct dpp_sm *dpp = user_data; + l_queue_remove(dpp_list, dpp); + dpp_free(dpp); } @@ -1651,6 +1928,12 @@ static int dpp_init(void) l_dbus_register_interface(dbus_get_bus(), IWD_DPP_INTERFACE, dpp_setup_interface, dpp_destroy_interface, false); + + mlme_watch = l_genl_family_register(nl80211, "mlme", dpp_mlme_notify, + NULL, NULL); + + dpp_list = l_queue_new(); + return 0; } @@ -1659,6 +1942,14 @@ static void dpp_exit(void) l_debug(""); netdev_watch_remove(netdev_watch); + + l_genl_family_unregister(nl80211, mlme_watch); + mlme_watch = 0; + + l_genl_family_free(nl80211); + nl80211 = NULL; + + l_queue_destroy(dpp_list, (l_queue_destroy_func_t) dpp_free); } IWD_MODULE(dpp, dpp_init, dpp_exit); diff --git a/src/eap-gtc.c b/src/eap-gtc.c @@ -67,8 +67,6 @@ static void eap_gtc_handle_request(struct eap_state *eap, eap_method_respond(eap, response, 5 + secret_len); eap_method_success(eap); - - return; } static int eap_gtc_check_settings(struct l_settings *settings, diff --git a/src/eap-peap.c b/src/eap-peap.c @@ -473,10 +473,10 @@ static bool eap_peap_tunnel_ready(struct eap_state *eap, struct peap_state *peap_state = eap_tls_common_get_variant_data(eap); /* - * PEAPv1: draft-josefsson-pppext-eap-tls-eap-05, Section 2.1.1 - * - * Cleartext Success/Failure packets MUST be silently discarded once TLS - * tunnel has been brought up. + * PEAPv1: draft-josefsson-pppext-eap-tls-eap-05, Section 2.1.1 + * + * Cleartext Success/Failure packets MUST be silently discarded once + * TLS tunnel has been brought up. */ eap_discard_success_and_failure(eap, true); diff --git a/src/eap-pwd.c b/src/eap-pwd.c @@ -598,8 +598,8 @@ static void eap_pwd_send_ack(struct eap_state *eap) } #define FRAG_BYTES(mtu, remaining) \ - ((mtu - EAP_PWD_HDR_LEN) < remaining) ? (mtu - EAP_PWD_HDR_LEN) : \ - remaining + (((mtu - EAP_PWD_HDR_LEN) < remaining) ? (mtu - EAP_PWD_HDR_LEN) : \ + remaining) static void eap_pwd_handle_request(struct eap_state *eap, const uint8_t *pkt, size_t len) @@ -669,6 +669,14 @@ static void eap_pwd_handle_request(struct eap_state *eap, /* remove length of Total-Length parameter (2) */ pwd->rx_frag_total = l_get_be16(pkt + 1) - 2; + + if (pwd->rx_frag_total < len - 2) { + l_error("Total-Length too small for remaining length"); + pwd->rx_frag_total = 0; + + return; + } + pwd->rx_frag_buf = l_malloc(pwd->rx_frag_total); /* skip copying Total-Length for easier processing later */ @@ -687,6 +695,12 @@ static void eap_pwd_handle_request(struct eap_state *eap, /* more rx fragments */ if (pwd->rx_frag_buf) { + if (pwd->rx_frag_total - pwd->rx_frag_count < + (uint16_t) len - 1) { + l_error("Not enough room for fragment (%zu)", len - 1); + return; + + } /* continue building packet (not including PWD-Exch byte) */ memcpy(pwd->rx_frag_buf + pwd->rx_frag_count, pkt + 1, len - 1); pwd->rx_frag_count += (len - 1); diff --git a/src/eap-tls-common.c b/src/eap-tls-common.c @@ -725,8 +725,8 @@ void eap_tls_common_handle_request(struct eap_state *eap, proceed: if (eap_tls->tx_pdu_buf) { /* - * tx_pdu_buf is used for the re-transmission and needs to be - * cleared on a new request. + * tx_pdu_buf is used for the re-transmission and needs to be + * cleared on a new request. */ databuf_free(eap_tls->tx_pdu_buf); eap_tls->tx_pdu_buf = NULL; diff --git a/src/eap-ttls.c b/src/eap-ttls.c @@ -375,7 +375,7 @@ static bool avp_iter_next(struct avp_iter *iter) len -= TTLS_AVP_HEADER_LEN; - if (start + len > end) + if (len > end - start) return false; if (flags & TTLS_AVP_FLAG_V) { diff --git a/src/eap-wsc.c b/src/eap-wsc.c @@ -223,7 +223,7 @@ static uint8_t *encrypted_settings_decrypt(struct eap_wsc_state *wsc, * * Account for the IV being in the beginning 16 bytes */ - if (len < 16 ) + if (len < 16) return NULL; encrypted_len = len - 16; diff --git a/src/eapol.c b/src/eapol.c @@ -2389,12 +2389,12 @@ static void eapol_eap_complete_cb(enum eap_result result, void *user_data) sm->eap = NULL; handshake_failed(sm, MMPDU_REASON_CODE_IEEE8021X_FAILED); return; - } else { - if (install_pmk) - install_pmk(sm->handshake, sm->handshake->pmk, - sm->handshake->pmk_len); } + if (install_pmk) + install_pmk(sm->handshake, sm->handshake->pmk, + sm->handshake->pmk_len); + eap_reset(sm->eap); if (sm->handshake->authenticator) { diff --git a/src/eapolutil.h b/src/eapolutil.h @@ -70,7 +70,7 @@ struct eapol_frame { #define EAPOL_KEY_DATA(ek, mic_len) ((ek)->key_data + (mic_len) + 2) /* gets frame length (not including key data) */ -#define EAPOL_FRAME_LEN(mic_len) sizeof(struct eapol_key) + (mic_len) + 2 +#define EAPOL_FRAME_LEN(mic_len) (sizeof(struct eapol_key) + (mic_len) + 2) struct eapol_key { struct eapol_header header; diff --git a/src/erp.c b/src/erp.c @@ -117,21 +117,21 @@ static bool erp_tlv_iter_next(struct erp_tlv_iter *iter) unsigned int tag; unsigned int len; - if (iter->pos + 2 >= iter->max) + if (end - tlv < 2) return false; tag = *tlv++; /* - * These two tags are not actually TLVs (they are just type-value). Both - * are 32-bit integers. + * These two tags are not actually TLVs (they are just type-value). + * Both are 32-bit integers. */ if (tag != ERP_TV_RMSK_LIFETIME && tag != ERP_TV_RRK_LIFETIME) len = *tlv++; else len = 4; - if (tlv + len > end) + if (len > end - tlv) return false; iter->tag = tag; diff --git a/src/fils.c b/src/fils.c @@ -222,7 +222,7 @@ static int fils_derive_key_data(struct fils_sm *fils) /* * IEEE 802.11ai - 12.12.2.6.2 (Re)Association Request for FILS key - * confirmation + * confirmation * * Key-Auth = HMAC-Hash(ICK, SNonce || ANonce || STA-MAC || AP-BSSID) */ diff --git a/src/frame-xchg.c b/src/frame-xchg.c @@ -726,10 +726,10 @@ static bool frame_watch_remove_by_handler(uint64_t wdev_id, uint32_t group_id, frame_watch_cb_t handler, void *user_data) { - struct watch_group_match_info group_info = - { group_id == 0 ? 0 : wdev_id, group_id }; - struct frame_watch_handler_check_info handler_info = - { wdev_id, handler, user_data }; + struct watch_group_match_info group_info = { + group_id == 0 ? 0 : wdev_id, group_id }; + struct frame_watch_handler_check_info handler_info = { + wdev_id, handler, user_data }; struct watch_group *group = l_queue_find(watch_groups, frame_watch_group_match, &group_info); @@ -1213,7 +1213,8 @@ uint32_t frame_xchg_startv(uint64_t wdev_id, struct iovec *frame, uint32_t freq, * wait on channel) are introduced. */ return wiphy_radio_work_insert(wiphy_find_by_wdev(wdev_id), - &fx->work, 0, &work_ops); + &fx->work, WIPHY_WORK_PRIORITY_FRAME, + &work_ops); } static bool frame_xchg_cancel_by_wdev(void *data, void *user_data) diff --git a/src/ft.c b/src/ft.c @@ -640,9 +640,10 @@ static int ft_rx_authenticate(struct auth_proto *ap, const uint8_t *frame, * FT Protocol. */ if (!ft_parse_authentication_resp_frame(frame, frame_len, ft->hs->spa, - ft->hs->aa, ft->hs->aa, 2, &status_code, - &ies, &ies_len)) - goto auth_error; + ft->hs->aa, ft->hs->aa, + 2, &status_code, + &ies, &ies_len)) + goto auth_error; /* AP Rejected the authenticate / associate */ if (status_code != 0) diff --git a/src/handshake.c b/src/handshake.c @@ -44,7 +44,7 @@ #include "src/erp.h" #include "src/band.h" -static inline unsigned int n_ecc_groups() +static inline unsigned int n_ecc_groups(void) { const unsigned int *groups = l_ecc_supported_ike_groups(); unsigned int j = 0; @@ -107,6 +107,11 @@ void handshake_state_free(struct handshake_state *s) { __typeof__(s->free) destroy = s->free; + if (s->in_event) { + s->in_event = false; + return; + } + l_free(s->authenticator_ie); l_free(s->supplicant_ie); l_free(s->authenticator_rsnxe); diff --git a/src/handshake.h b/src/handshake.h @@ -159,17 +159,29 @@ struct handshake_state { void *user_data; void (*free)(struct handshake_state *s); + bool in_event; handshake_event_func_t event_func; }; -#define handshake_event(hs, event, ...) \ - do { \ - if (!(hs)->event_func) \ - break; \ +#define handshake_event(_hs, event, ...) \ + (__extension__ ({ \ + struct handshake_state *hs = (_hs); \ + bool freed = false; \ \ - (hs)->event_func((hs), event, (hs)->user_data, ##__VA_ARGS__); \ - } while (0) + if (hs->event_func && !hs->in_event) { \ + hs->in_event = true; \ + hs->event_func(hs, event, hs->user_data, \ + ##__VA_ARGS__); \ + \ + if (!hs->in_event) { \ + handshake_state_free(hs); \ + freed = true; \ + } else \ + hs->in_event = false; \ + } \ + freed; \ + })) void handshake_state_free(struct handshake_state *s); diff --git a/src/ie.c b/src/ie.c @@ -923,7 +923,7 @@ static bool ie_build_cipher_suite(uint8_t *data, const uint8_t *oui, memcpy((data), (oui), 3); \ (data)[3] = (id); \ return true; \ - } while(0) + } while (0) /* 802.11-2016, Section 9.4.2.25.3 */ static bool ie_build_rsn_akm_suite(uint8_t *data, enum ie_rsn_akm_suite suite) diff --git a/src/ie.h b/src/ie.h @@ -355,7 +355,7 @@ enum ie_rsn_akm_suite { (akm == IE_RSN_AKM_SUITE_FT_OVER_FILS_SHA384)) #define IE_LEN(ie) \ - (ie) ? (ie)[1] + 2 : 0 + ((ie) ? (ie)[1] + 2 : 0) struct ie_tlv_iter { unsigned int max; diff --git a/src/iwd.config.rst b/src/iwd.config.rst @@ -205,7 +205,7 @@ The group ``[Network]`` contains network configuration related settings. Sets the global default that tells **iwd** whether it should configure IPv6 addresses and routes (either provided via static settings, Router Advertisements or DHCPv6 protocol). This setting is disabled - by default. This setting can also be overriden on a per-network basis. + by default. This setting can also be overridden on a per-network basis. * - NameResolvingService - Values: resolvconf, **systemd** diff --git a/src/json.c b/src/json.c @@ -33,9 +33,9 @@ #include "shared/jsmn.h" /* Max number of tokens supported. Increase if larger objects are expected */ -#define JSON_DEFAULT_TOKENS 30 +#define JSON_DEFAULT_TOKENS 60 -#define TOK_LEN(token) (token)->end - (token)->start +#define TOK_LEN(token) ((token)->end - (token)->start) #define TOK_PTR(json, token) (void *)((json) + (token)->start) #define TOK_TO_STR(json, token) \ ({ \ @@ -69,30 +69,37 @@ static jsmntok_t *next_key_in_parent(struct json_iter *iter, jsmntok_t *current) return NULL; } -/* - * 'object' is expected to be a value, so object - 1 is its key. Find - * the next key who's parent matches the parent of object - 1. The - * token preceeding this next key will mark the end of 'object'. - */ -static int find_object_tokens(struct json_iter *iter, jsmntok_t *object) +static int count_tokens_in_container(struct json_iter *iter, + jsmntok_t *container) { - jsmntok_t *next = next_key_in_parent(iter, object - 1); + int idx = container - iter->contents->tokens; + jsmntok_t *contents; - /* End of token list */ - if (!next) - next = ITER_END(iter); + for (contents = ++container; contents < ITER_END(iter); contents++) + if (contents->parent < idx) + break; - return next - object - 1; + return contents - container; } -static void iter_recurse(struct json_iter *iter, jsmntok_t *object, +static void iter_recurse(struct json_iter *iter, jsmntok_t *token, struct json_iter *child) { struct json_contents *c = iter->contents; child->contents = c; - child->start = object - c->tokens; - child->count = find_object_tokens(iter, object); + child->start = token - c->tokens; + child->current = child->start; + child->count = count_tokens_in_container(iter, token); + + /* + * Add one to include the object/array token itself. This is required + * since 'current' points to the container initially. Only after a call + * to json_iter_next() will 'current' point to the first token in the + * container. + */ + if (token->type == JSMN_OBJECT || token->type == JSMN_ARRAY) + child->count++; } struct json_contents *json_contents_new(const char *json, size_t json_len) @@ -153,7 +160,7 @@ static void assign_arg(void *data, void *user_data) struct json_arg *arg = data; struct json_contents *c = iter->contents; char **sval; - struct json_iter *oval; + struct json_iter *iter_val; switch (arg->type) { case JSON_STRING: @@ -163,12 +170,14 @@ static void assign_arg(void *data, void *user_data) break; case JSON_OBJECT: - oval = arg->value; + case JSON_PRIMITIVE: + case JSON_ARRAY: + iter_val = arg->value; if (!arg->v) - oval->start = -1; + iter_val->start = -1; else - iter_recurse(iter, arg->v, oval); + iter_recurse(iter, arg->v, iter_val); break; default: @@ -191,6 +200,9 @@ bool json_iter_parse(struct json_iter *iter, enum json_type type, ...) if (iter->start == -1) return false; + if (c->tokens[iter->start].type != JSMN_OBJECT) + return false; + args = l_queue_new(); va_start(va, type); @@ -209,6 +221,8 @@ bool json_iter_parse(struct json_iter *iter, enum json_type type, ...) goto done; case JSON_STRING: case JSON_OBJECT: + case JSON_PRIMITIVE: + case JSON_ARRAY: break; default: goto error; @@ -268,3 +282,187 @@ error: l_queue_destroy(args, l_free); return false; } + +static bool iter_get_primitive_data(struct json_iter *iter, void **ptr, + size_t *len) +{ + struct json_contents *c = iter->contents; + jsmntok_t *t = c->tokens + iter->current; + + if (t->type != JSMN_PRIMITIVE) + return false; + + *ptr = TOK_PTR(c->json, t); + *len = TOK_LEN(t); + + return true; +} + +bool json_iter_get_int(struct json_iter *iter, int *i) +{ + void *ptr; + size_t len; + long r; + int t; + char *endp; + + if (!iter_get_primitive_data(iter, &ptr, &len)) + return false; + + if (!len) + return false; + + errno = 0; + + t = r = strtol(ptr, &endp, 10); + if (endp != ptr + len) + return false; + + if (errno == ERANGE || errno == EINVAL || r != t) + return false; + + if (i) + *i = r; + + return true; +} + +bool json_iter_get_uint(struct json_iter *iter, unsigned int *i) +{ + void *ptr; + size_t len; + unsigned long r; + unsigned int t; + char *endp; + + if (!iter_get_primitive_data(iter, &ptr, &len)) + return false; + + if (!len || *((char *) ptr) == '-') + return false; + + errno = 0; + + t = r = strtoul(ptr, &endp, 10); + if (endp != ptr + len) + return false; + + if (errno == ERANGE || errno == EINVAL || r != t) + return false; + + if (i) + *i = r; + + return true; +} + +bool json_iter_get_boolean(struct json_iter *iter, bool *b) +{ + void *ptr; + size_t len; + + if (!iter_get_primitive_data(iter, &ptr, &len)) + return false; + + if (len == 4 && !memcmp(ptr, "true", 4)) { + if (b) + *b = true; + + return true; + } else if (len == 5 && !memcmp(ptr, "false", 5)) { + if (b) + *b = false; + + return true; + } + + return false; +} + +bool json_iter_get_null(struct json_iter *iter) +{ + void *ptr; + size_t len; + + if (!iter_get_primitive_data(iter, &ptr, &len)) + return false; + + if (len == 4 && !memcmp(ptr, "null", 4)) + return true; + + return false; +} + +bool json_iter_get_container(struct json_iter *iter, + struct json_iter *container) +{ + struct json_contents *c = iter->contents; + jsmntok_t *t = c->tokens + iter->current; + + if (t->type != JSMN_OBJECT && t->type != JSMN_ARRAY) + return false; + + if (container) + iter_recurse(iter, t, container); + + return true; +} + +bool json_iter_get_string(struct json_iter *iter, char **s) +{ + struct json_contents *c = iter->contents; + jsmntok_t *t = c->tokens + iter->current; + + if (t->type != JSMN_STRING) + return false; + + if (s) + *s = TOK_TO_STR(c->json, t); + + return true; +} + +enum json_type json_iter_get_type(struct json_iter *iter) +{ + struct json_contents *c = iter->contents; + jsmntok_t *t = c->tokens + iter->current; + + return (enum json_type) t->type; +} + +bool json_iter_next(struct json_iter *iter) +{ + struct json_contents *c = iter->contents; + jsmntok_t *t = c->tokens + iter->current; + int inc = 1; + + if (c->tokens[iter->start].type != JSMN_ARRAY) + return false; + + /* + * If this is the initial iteration skip this and just increment + * current by 1 since this iterator points to a container which needs to + * be advanced to the first token.. + * + * In addition primitive types and empty containers will have a size + * of 1, so no special handling is needed there. + * + * For non-empty containers 'current' needs to be advanced by all the + * containers child tokens, plus the container itself. + * + * This check ensures: + * 1. It is not the initial iteration + * 2. This is a container + * 3. The container is not empty + */ + if (iter->current != iter->start && ((t->type == JSMN_OBJECT || + t->type == JSMN_ARRAY) && t->size)) + inc = count_tokens_in_container(iter, t) + 1; + + if (c->tokens + iter->current + inc >= ITER_END(iter)) + return false; + + iter->current += inc; + + return true; +} diff --git a/src/json.h b/src/json.h @@ -42,6 +42,7 @@ struct json_iter { struct json_contents *contents; int start; int count; + int current; }; #define JSON_MANDATORY(key, type, out) \ @@ -68,16 +69,33 @@ void json_iter_init(struct json_iter *iter, struct json_contents *c); * Arguments should be specified using JSON_MANDATORY or JSON_OPTIONAL: * * r = json_iter_parse(iter, JSON_MANDATORY("mykey", JSON_STRING, &strvalue), - * JSON_OPTIONAL("optkey", JSON_STRING, &optvalue), - * JSON_UNDEFINED); + * JSON_OPTIONAL("optkey", JSON_STRING, &optvalue), + * JSON_UNDEFINED); * * String values should be of type char ** and must be freed * Object values should be of type struct json_iter * + * Primitive types (numbers, booleans, null) should be of type + * struct json_iter *. This is to allow the caller to distinguish + * between the actual value type after parsing using a getter for + * the expected type (get_uint/get_int/get_boolean etc.). In + * addition this lets the caller use JSON_OPTIONAL and check post + * json_iter_parse if the iterator is valid (json_iter_is_valid). * * No other types are supported at this time, and json_iter_parse will fail if * other types are encountered. * * JSON_OPTIONAL string values will point to NULL if not found - * JSON_OPTIONAL objects can be checked with json_object_not_found. + * JSON_OPTIONAL objects/primitives can be checked with json_object_is_valid. */ bool json_iter_parse(struct json_iter *iter, enum json_type type, ...); + +bool json_iter_get_int(struct json_iter *iter, int *i); +bool json_iter_get_uint(struct json_iter *iter, unsigned int *i); +bool json_iter_get_boolean(struct json_iter *iter, bool *b); +bool json_iter_get_null(struct json_iter *iter); +bool json_iter_get_container(struct json_iter *iter, + struct json_iter *container); +bool json_iter_get_string(struct json_iter *iter, char **s); + +enum json_type json_iter_get_type(struct json_iter *iter); +bool json_iter_next(struct json_iter *iter); diff --git a/src/main.c b/src/main.c @@ -269,7 +269,7 @@ static void print_koption(const void *key, void *value, void *user_data) #define ADD_OPTIONAL(opt) \ l_hashmap_replace(optional, opt, &r, NULL) -static int check_crypto() +static int check_crypto(void) { int r = 0; struct l_hashmap *options = l_hashmap_string_new(); diff --git a/src/manager.c b/src/manager.c @@ -196,7 +196,7 @@ static void manager_create_interfaces(struct wiphy_setup_state *state) struct l_genl_msg *msg; char ifname[10]; uint32_t iftype; - unsigned cmd_id; + unsigned int cmd_id; if (state->aborted) return; @@ -341,7 +341,7 @@ static void manager_get_interface_cb(struct l_genl_msg *msg, void *user_data) uint64_t wdev; const char *ifname; struct l_genl_msg *del_msg; - unsigned cmd_id; + unsigned int cmd_id; char *pattern; unsigned int i; bool whitelisted = false, blacklisted = false; @@ -703,7 +703,7 @@ static void manager_config_notify(struct l_genl_msg *msg, void *user_data) case NL80211_CMD_NEW_INTERFACE: /* * Interfaces are normally dumped on the NEW_WIPHY events and - * and we have nothing to do here. But check if by any chance + * we have nothing to do here. But check if by any chance * we've queried this wiphy and it was still busy initialising, * in that case retry the setup now that an interface, likely * the initial default one, has been added. diff --git a/src/mpdu.c b/src/mpdu.c @@ -364,6 +364,7 @@ static bool validate_mgmt_ies(const uint8_t *ies, size_t ies_len, while (ie_tlv_iter_next(&iter)) { int i = 0; + tag = ie_tlv_iter_get_tag(&iter); /* Check that the tag is part of the valid set */ diff --git a/src/netconfig.c b/src/netconfig.c @@ -236,7 +236,8 @@ static char **netconfig_get_dns_list(struct netconfig *netconfig, int af, return dns_list; } - if (!(lease = l_dhcp_client_get_lease(netconfig->dhcp_client))) + lease = l_dhcp_client_get_lease(netconfig->dhcp_client); + if (!lease) return NULL; return l_dhcp_lease_get_dns(lease); @@ -264,8 +265,8 @@ static char **netconfig_get_dns_list(struct netconfig *netconfig, int af, return dns_list; } - if (!(lease = l_dhcp6_client_get_lease( - netconfig->dhcp6_client))) + lease = l_dhcp6_client_get_lease(netconfig->dhcp6_client); + if (!lease) return NULL; return l_dhcp6_lease_get_dns(lease); @@ -1226,9 +1227,9 @@ static bool netconfig_ipv4_select_and_install(struct netconfig *netconfig) if (unlikely(!addr_str)) return false; - if (L_WARN_ON(unlikely(!(netconfig->v4_address = - l_rtnl_address_new(addr_str, - prefix_len))))) + netconfig->v4_address = l_rtnl_address_new(addr_str, + prefix_len); + if (L_WARN_ON(!netconfig->v4_address)) return false; l_rtnl_address_set_noprefixroute(netconfig->v4_address, true); diff --git a/src/netdev.c b/src/netdev.c @@ -1482,7 +1482,9 @@ static void try_handshake_complete(struct netdev_handshake_state *nhs) if (nhs->ptk_installed && nhs->gtk_installed && nhs->igtk_installed && !nhs->complete) { nhs->complete = true; - handshake_event(&nhs->super, HANDSHAKE_EVENT_COMPLETE); + + if (handshake_event(&nhs->super, HANDSHAKE_EVENT_COMPLETE)) + return; if (nhs->netdev->type == NL80211_IFTYPE_STATION || nhs->netdev->type == NL80211_IFTYPE_P2P_CLIENT) @@ -2006,7 +2008,9 @@ static void netdev_group_timeout_cb(struct l_timeout *timeout, void *user_data) nhs->netdev->index); nhs->complete = true; - handshake_event(&nhs->super, HANDSHAKE_EVENT_COMPLETE); + + if (handshake_event(&nhs->super, HANDSHAKE_EVENT_COMPLETE)) + return; netdev_connect_ok(nhs->netdev); } @@ -2155,7 +2159,9 @@ static void netdev_set_pmk_cb(struct l_genl_msg *msg, void *user_data) return; } - handshake_event(netdev->handshake, HANDSHAKE_EVENT_SETTING_KEYS); + if (handshake_event(netdev->handshake, HANDSHAKE_EVENT_SETTING_KEYS)) + return; + netdev_connect_ok(netdev); } @@ -2710,6 +2716,7 @@ static void netdev_connect_event(struct l_genl_msg *msg, struct netdev *netdev) struct ie_tlv_iter iter; const uint8_t *resp_ies = NULL; size_t resp_ies_len; + struct handshake_state *hs = netdev->handshake; l_debug(""); @@ -2809,15 +2816,13 @@ process_resp_ies: qos_len = ie_tlv_iter_get_length(&iter); break; case IE_TYPE_FILS_IP_ADDRESS: - if (netdev->handshake->fils_ip_resp_ie) { + if (hs->fils_ip_resp_ie) { l_debug("Duplicate response FILS IP " "Address Assignment IE"); - l_free(netdev->handshake-> - fils_ip_resp_ie); + l_free(hs->fils_ip_resp_ie); } - netdev->handshake->fils_ip_resp_ie = l_memdup( - data - 3, + hs->fils_ip_resp_ie = l_memdup(data - 3, ie_tlv_iter_get_length(&iter) + 3); break; case IE_TYPE_OWE_DH_PARAM: @@ -2871,7 +2876,7 @@ process_resp_ies: if (fte) { uint32_t kck_len = - handshake_state_get_kck_len(netdev->handshake); + handshake_state_get_kck_len(hs); /* * If we are here, then most likely we have a FullMac * hw performing initial mobility association. We need @@ -2881,8 +2886,8 @@ process_resp_ies: */ if (ie_parse_fast_bss_transition_from_data(fte, fte[1] + 2, kck_len, &ft_info) >= 0) { - handshake_state_set_fte(netdev->handshake, fte); - handshake_state_set_kh_ids(netdev->handshake, + handshake_state_set_fte(hs, fte); + handshake_state_set_kh_ids(hs, ft_info.r0khid, ft_info.r0khid_len, ft_info.r1khid); @@ -2897,22 +2902,20 @@ process_resp_ies: } if (netdev->sm) { - if (!netdev->handshake->chandef) { + if (!hs->chandef) { if (netdev_get_oci(netdev) < 0) goto deauth; } else if (!eapol_start(netdev->sm)) - goto deauth; + goto deauth; return; } /* Allow station to sync the PSK to disk */ - if (is_offload(netdev->handshake)) - handshake_event(netdev->handshake, - HANDSHAKE_EVENT_SETTING_KEYS); + if (is_offload(hs) && handshake_event(hs, HANDSHAKE_EVENT_SETTING_KEYS)) + return; netdev_connect_ok(netdev); - return; error: @@ -3109,7 +3112,8 @@ static void netdev_authenticate_event(struct l_genl_msg *msg, const struct mmpdu_authentication *auth; bool retry; - if (L_WARN_ON(!(hdr = mpdu_validate(frame, frame_len)))) + hdr = mpdu_validate(frame, frame_len); + if (L_WARN_ON(!hdr)) goto auth_error; auth = mmpdu_body(hdr); @@ -3219,7 +3223,8 @@ static void netdev_associate_event(struct l_genl_msg *msg, const struct mmpdu_header *hdr; const struct mmpdu_association_response *assoc; - if (L_WARN_ON(!(hdr = mpdu_validate(frame, frame_len)))) + hdr = mpdu_validate(frame, frame_len); + if (L_WARN_ON(!hdr)) goto assoc_failed; assoc = mmpdu_body(hdr); @@ -4040,8 +4045,8 @@ build_cmd_connect: NL80211_EXT_FEATURE_CAN_REPLACE_PTK0)) handshake_state_set_no_rekey(hs, true); - wiphy_radio_work_insert(netdev->wiphy, &netdev->work, 1, - &connect_work_ops); + wiphy_radio_work_insert(netdev->wiphy, &netdev->work, + WIPHY_WORK_PRIORITY_CONNECT, &connect_work_ops); } int netdev_connect(struct netdev *netdev, struct scan_bss *bss, @@ -4620,8 +4625,8 @@ int netdev_fast_transition(struct netdev *netdev, netdev_get_oci, netdev); memcpy(netdev->ap->prev_bssid, orig_bss->addr, ETH_ALEN); - wiphy_radio_work_insert(netdev->wiphy, &netdev->work, 1, - &ft_work_ops); + wiphy_radio_work_insert(netdev->wiphy, &netdev->work, + WIPHY_WORK_PRIORITY_CONNECT, &ft_work_ops); return 0; } @@ -4661,8 +4666,8 @@ int netdev_fast_transition_over_ds(struct netdev *netdev, netdev); memcpy(netdev->ap->prev_bssid, orig_bss->addr, ETH_ALEN); - wiphy_radio_work_insert(netdev->wiphy, &netdev->work, 1, - &ft_work_ops); + wiphy_radio_work_insert(netdev->wiphy, &netdev->work, + WIPHY_WORK_PRIORITY_CONNECT, &ft_work_ops); return 0; } diff --git a/src/network.c b/src/network.c @@ -998,8 +998,8 @@ bool network_bss_add(struct network *network, struct scan_bss *bss) /* Done if BSS is not HS20 or we already have network_info set */ if (!bss->hs20_capable) return true; - else - network->is_hs20 = true; + + network->is_hs20 = true; if (network->info) return true; diff --git a/src/nl80211util.c b/src/nl80211util.c @@ -118,6 +118,16 @@ static bool extract_flag(const void *data, uint16_t len, void *o) return true; } +static bool extract_iovec(const void *data, uint16_t len, void *o) +{ + struct iovec *iov = o; + + iov->iov_base = (void *) data; + iov->iov_len = len; + + return true; +} + static attr_handler handler_for_type(enum nl80211_attrs type) { switch (type) { @@ -145,6 +155,8 @@ static attr_handler handler_for_type(enum nl80211_attrs type) case NL80211_ATTR_CENTER_FREQ1: case NL80211_ATTR_CENTER_FREQ2: return extract_uint32; + case NL80211_ATTR_FRAME: + return extract_iovec; default: break; } diff --git a/src/offchannel.c b/src/offchannel.c @@ -168,8 +168,9 @@ uint32_t offchannel_start(uint64_t wdev_id, uint32_t freq, uint32_t duration, */ info->error = -ECANCELED; - return wiphy_radio_work_insert(wiphy_find_by_wdev(wdev_id), - &info->work, 1, &offchannel_work_ops); + return wiphy_radio_work_insert(wiphy_find_by_wdev(wdev_id), &info->work, + WIPHY_WORK_PRIORITY_OFFCHANNEL, + &offchannel_work_ops); } void offchannel_cancel(uint64_t wdev_id, uint32_t id) diff --git a/src/p2p.c b/src/p2p.c @@ -942,7 +942,7 @@ static void p2p_group_event(enum ap_event_type type, const void *event_data, p2p_clear_association_req(&req_info); if (dev->conn_own_wfd) - wfd_data = ie_tlv_extract_p2p_payload(data->assoc_ies, + wfd_data = ie_tlv_extract_wfd_payload(data->assoc_ies, data->assoc_ies_len, &wfd_data_len); @@ -1070,8 +1070,9 @@ static size_t p2p_group_write_p2p_ie(struct p2p_device *dev, * Response frame if the received Probe Request frame does * not contain a P2P IE." */ - if (!(tmp = ie_tlv_extract_p2p_payload(req->ies, req_ies_len, - &req_p2p_data_size))) + tmp = ie_tlv_extract_p2p_payload(req->ies, req_ies_len, + &req_p2p_data_size); + if (!tmp) return 0; info.capability = dev->capability; @@ -1601,8 +1602,9 @@ static void p2p_peer_provision_done(int err, struct wsc_credentials_info *creds, p2p_connection_reset(dev); return; - } else - goto error; + } + + goto error; } if (strlen(creds[0].ssid) != bss->ssid_len || diff --git a/src/p2putil.h b/src/p2putil.h @@ -121,8 +121,8 @@ enum p2p_public_action_frame_type { /* Table 75 */ enum p2p_action_frame_type { P2P_ACTION_NOTICE_OF_ABSENCE = 0, - P2P_ACTION_PRESENCE_REQ = 1, - P2P_ACTION_PRESENCE_RESP = 2, + P2P_ACTION_PRESENCE_REQ = 1, + P2P_ACTION_PRESENCE_RESP = 2, P2P_ACTION_GO_DISCOVERABILITY_REQ = 3, }; diff --git a/src/sae.c b/src/sae.c @@ -413,6 +413,7 @@ static struct l_ecc_point *sae_compute_pwe(const struct l_ecc_curve *curve, struct l_ecc_scalar *qnr; uint8_t qnr_bin[L_ECC_SCALAR_MAX_BYTES] = {0}; struct l_ecc_point *pwe; + unsigned int bytes = l_ecc_curve_get_scalar_bytes(curve); /* create qr/qnr prior to beginning hunting-and-pecking loop */ qr = sae_new_residue(curve, true); @@ -438,7 +439,7 @@ static struct l_ecc_point *sae_compute_pwe(const struct l_ecc_curve *curve, * Set base to either dummy or password, depending on found's * value. * A non-secure version would be: - * base = (found ? dummy : password); + * base = (found ? dummy : password); */ util_secure_select(found, dummy, (uint8_t *)password, base, base_len); @@ -493,7 +494,7 @@ 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, sizeof(x)); + pwe = l_ecc_point_from_data(curve, !is_odd + 2, x, bytes); if (!pwe) l_error("computing y failed, was x quadratic residue?"); @@ -729,7 +730,7 @@ static int sae_process_commit(struct sae_sm *sm, const uint8_t *from, * * NOTE: We use hkdf_extract here since it is just an hmac invocation * and it handles the case of the zero key for us. - */ + */ if (sm->sae_type != CRYPTO_SAE_LOOPING && sm->rejected_groups) { salt = sm->rejected_groups + 1; salt_len = sm->rejected_groups[0] * sizeof(uint16_t); @@ -999,7 +1000,7 @@ static int sae_verify_committed(struct sae_sm *sm, uint16_t transaction, * checking that the group matches here, e.g. * * if (l_get_le16(frame) != sm->group) - * return false; + * return false; * * According to 802.11 Section 12.4.8.6.4: * diff --git a/src/scan.c b/src/scan.c @@ -69,7 +69,6 @@ struct scan_periodic { scan_trigger_func_t trigger; scan_notify_func_t callback; void *userdata; - bool retry:1; uint32_t id; bool needs_active_scan:1; }; @@ -80,7 +79,21 @@ struct scan_request { scan_notify_func_t callback; void *userdata; scan_destroy_func_t destroy; + bool canceled : 1; /* Is scan_cancel being called on this request? */ bool passive:1; /* Active or Passive scan? */ + bool started : 1; /* Has TRIGGER_SCAN succeeded at least once? */ + bool periodic : 1; /* Started as a periodic scan? */ + /* + * Set to true if the TRIGGER_SCAN command at the head of the 'cmds' + * queue was acked by the kernel indicating that the scan request was + * successful. May be set and cleared multiple times during a + * the scan_request lifetime (as each command in the 'cmds' queue is + * issued to the kernel). Will be false if the current request + * was not started due to an -EBUSY error from the kernel. Also will + * be false when the scan is complete and GET_SCAN is pending. + */ + bool triggered : 1; + bool in_callback : 1; /* Scan request complete, re-entrancy guard */ struct l_queue *cmds; /* The time the current scan was started. Reported in TRIGGER_SCAN */ uint64_t start_time_tsf; @@ -106,18 +119,6 @@ struct scan_context { * roamed automatically. */ unsigned int get_fw_scan_cmd_id; - /* - * Whether the top request in the queue has triggered the current - * scan. May be set and cleared multiple times during a single - * request. May be false when the current request is waiting due - * to an EBUSY or an external scan (sr->cmds non-empty), when - * start_cmd_id is non-zero and for a brief moment when GET_SCAN - * is running. - */ - bool triggered:1; - /* Whether any commands from current request's queue have started */ - bool started:1; - bool work_started:1; struct wiphy *wiphy; }; @@ -164,13 +165,15 @@ static void scan_request_free(struct wiphy_radio_work_item *item) static void scan_request_failed(struct scan_context *sc, struct scan_request *sr, int err) { - l_queue_remove(sc->requests, sr); + sr->in_callback = true; if (sr->trigger) sr->trigger(err, sr->userdata); else if (sr->callback) sr->callback(err, NULL, NULL, sr->userdata); + sr->in_callback = false; + l_queue_remove(sc->requests, sr); wiphy_radio_work_done(sc->wiphy, sr->work.id); } @@ -236,8 +239,6 @@ static void scan_request_triggered(struct l_genl_msg *msg, void *userdata) return; } - l_queue_remove(sc->requests, sr); - scan_request_failed(sc, sr, err); l_error("Received error during CMD_TRIGGER_SCAN: %s (%d)", @@ -250,8 +251,8 @@ static void scan_request_triggered(struct l_genl_msg *msg, void *userdata) l_debug("%s scan triggered for wdev %" PRIx64, sr->passive ? "Passive" : "Active", sc->wdev_id); - sc->triggered = true; - sc->started = true; + sr->triggered = true; + sr->started = true; l_genl_msg_unref(l_queue_pop_head(sr->cmds)); if (sr->trigger) { @@ -562,6 +563,7 @@ static int scan_request_send_trigger(struct scan_context *sc, struct scan_request *sr) { struct l_genl_msg *cmd = l_queue_peek_head(sr->cmds); + if (!cmd) return -ENOMSG; @@ -607,6 +609,7 @@ static struct scan_request *scan_request_new(struct scan_context *sc, static uint32_t scan_common(uint64_t wdev_id, bool passive, const struct scan_parameters *params, + int priority, scan_trigger_func_t trigger, scan_notify_func_t notify, void *userdata, scan_destroy_func_t destroy) @@ -625,7 +628,8 @@ static uint32_t scan_common(uint64_t wdev_id, bool passive, l_queue_push_tail(sc->requests, sr); - return wiphy_radio_work_insert(sc->wiphy, &sr->work, 2, &work_ops); + return wiphy_radio_work_insert(sc->wiphy, &sr->work, + priority, &work_ops); } uint32_t scan_passive(uint64_t wdev_id, struct scan_freq_set *freqs, @@ -634,8 +638,8 @@ uint32_t scan_passive(uint64_t wdev_id, struct scan_freq_set *freqs, { struct scan_parameters params = { .freqs = freqs }; - return scan_common(wdev_id, true, &params, trigger, notify, - userdata, destroy); + return scan_common(wdev_id, true, &params, WIPHY_WORK_PRIORITY_SCAN, + trigger, notify, userdata, destroy); } uint32_t scan_passive_full(uint64_t wdev_id, @@ -644,8 +648,8 @@ uint32_t scan_passive_full(uint64_t wdev_id, scan_notify_func_t notify, void *userdata, scan_destroy_func_t destroy) { - return scan_common(wdev_id, true, params, trigger, - notify, userdata, destroy); + return scan_common(wdev_id, true, params, WIPHY_WORK_PRIORITY_SCAN, + trigger, notify, userdata, destroy); } uint32_t scan_active(uint64_t wdev_id, uint8_t *extra_ie, size_t extra_ie_size, @@ -658,7 +662,7 @@ uint32_t scan_active(uint64_t wdev_id, uint8_t *extra_ie, size_t extra_ie_size, params.extra_ie = extra_ie; params.extra_ie_size = extra_ie_size; - return scan_common(wdev_id, false, &params, + return scan_common(wdev_id, false, &params, WIPHY_WORK_PRIORITY_SCAN, trigger, notify, userdata, destroy); } @@ -667,7 +671,7 @@ uint32_t scan_active_full(uint64_t wdev_id, scan_trigger_func_t trigger, scan_notify_func_t notify, void *userdata, scan_destroy_func_t destroy) { - return scan_common(wdev_id, false, params, + return scan_common(wdev_id, false, params, WIPHY_WORK_PRIORITY_SCAN, trigger, notify, userdata, destroy); } @@ -795,7 +799,8 @@ uint32_t scan_owe_hidden(uint64_t wdev_id, struct l_queue *list, done: l_queue_push_tail(sc->requests, sr); - return wiphy_radio_work_insert(sc->wiphy, &sr->work, 2, &work_ops); + return wiphy_radio_work_insert(sc->wiphy, &sr->work, + WIPHY_WORK_PRIORITY_SCAN, &work_ops); } bool scan_cancel(uint64_t wdev_id, uint32_t id) @@ -813,23 +818,33 @@ bool scan_cancel(uint64_t wdev_id, uint32_t id) if (!sr) return false; + /* We're in the callback and about to be removed, invoke destroy now */ + if (sr->in_callback) + goto call_destroy; + /* If already triggered, just zero out the callback */ - if (sr == l_queue_peek_head(sc->requests) && sc->triggered) { - l_debug("Scan is at the top of the queue and triggered"); + if (sr->triggered) { + l_debug("Scan has been triggered, wait for it to complete"); sr->callback = NULL; - - if (sr->destroy) { - sr->destroy(sr->userdata); - sr->destroy = NULL; - } - - return true; + goto call_destroy; } - /* If we already sent the trigger command, cancel the scan */ - if (sr == l_queue_peek_head(sc->requests)) { - l_debug("Scan is at the top of the queue, but not triggered"); + /* + * Takes care of the following cases: + * 1. If TRIGGER_SCAN is in flight + * 2. TRIGGER_SCAN sent but bounced with -EBUSY + * 3. Scan request is done but GET_SCAN is still pending + * + * For case 3, we can easily cancel the command and proceed with the + * other pending requests. For case 1 & 2, the subsequent pending + * request might bounce off with an -EBUSY. + */ + if (wiphy_radio_work_is_running(sc->wiphy, sr->work.id)) { + l_debug("Scan is already started"); + + /* l_genl_family_cancel will trigger destroy callbacks */ + sr->canceled = true; if (sc->start_cmd_id) l_genl_family_cancel(nl80211, sc->start_cmd_id); @@ -838,15 +853,21 @@ bool scan_cancel(uint64_t wdev_id, uint32_t id) l_genl_family_cancel(nl80211, sc->get_scan_cmd_id); sc->start_cmd_id = 0; - l_queue_remove(sc->requests, sr); - sc->started = false; - sc->work_started = false; - } else - l_queue_remove(sc->requests, sr); + sc->get_scan_cmd_id = 0; + } + l_queue_remove(sc->requests, sr); wiphy_radio_work_done(sc->wiphy, sr->work.id); return true; + +call_destroy: + if (sr->destroy) { + sr->destroy(sr->userdata); + sr->destroy = NULL; + } + + return true; } static void scan_periodic_triggered(int err, void *user_data) @@ -878,29 +899,41 @@ static bool scan_periodic_notify(int err, struct l_queue *bss_list, return false; } +static void scan_periodic_destroy(void *user_data) +{ + struct scan_context *sc = user_data; + + sc->sp.id = 0; +} + static bool scan_periodic_queue(struct scan_context *sc) { - if (!l_queue_isempty(sc->requests)) { - sc->sp.retry = true; - return false; - } + struct scan_parameters params = {}; + struct scan_request *sr; if (sc->sp.needs_active_scan && known_networks_has_hidden()) { - struct scan_parameters params = { - .randomize_mac_addr_hint = true - }; + params.randomize_mac_addr_hint = true; sc->sp.needs_active_scan = false; - - sc->sp.id = scan_active_full(sc->wdev_id, &params, - scan_periodic_triggered, - scan_periodic_notify, sc, NULL); + sc->sp.id = scan_common(sc->wdev_id, false, &params, + WIPHY_WORK_PRIORITY_PERIODIC_SCAN, + scan_periodic_triggered, + scan_periodic_notify, sc, + scan_periodic_destroy); } else - sc->sp.id = scan_passive(sc->wdev_id, NULL, - scan_periodic_triggered, - scan_periodic_notify, sc, NULL); + sc->sp.id = scan_common(sc->wdev_id, true, &params, + WIPHY_WORK_PRIORITY_PERIODIC_SCAN, + scan_periodic_triggered, + scan_periodic_notify, sc, + scan_periodic_destroy); + + if (!sc->sp.id) + return false; - return sc->sp.id != 0; + sr = l_queue_peek_tail(sc->requests); + sr->periodic = true; + + return true; } static bool scan_periodic_is_disabled(void) @@ -926,7 +959,7 @@ void scan_periodic_start(uint64_t wdev_id, scan_trigger_func_t trigger, sc = l_queue_find(scan_contexts, scan_context_match, &wdev_id); if (!sc) { - l_error("scan_periodic_start called without scan_wdev_add"); + l_error("%s called without scan_wdev_add", __func__); return; } @@ -970,7 +1003,6 @@ bool scan_periodic_stop(uint64_t wdev_id) sc->sp.trigger = NULL; sc->sp.callback = NULL; sc->sp.userdata = NULL; - sc->sp.retry = false; sc->sp.needs_active_scan = false; return true; @@ -985,11 +1017,8 @@ uint64_t scan_get_triggered_time(uint64_t wdev_id, uint32_t id) if (!sc) return 0; - if (!sc->triggered) - return 0; - sr = l_queue_find(sc->requests, scan_request_match, L_UINT_TO_PTR(id)); - if (!sr) + if (!sr || !sr->triggered) return 0; return sr->start_time_tsf; @@ -999,7 +1028,17 @@ static void scan_periodic_timeout(struct l_timeout *timeout, void *user_data) { struct scan_context *sc = user_data; - l_debug("scan_periodic_timeout: %" PRIx64, sc->wdev_id); + l_debug("%" PRIx64, sc->wdev_id); + + /* + * Timeout triggered before periodic scan could even start, just rearm + * with the same interval. + */ + if (sc->sp.id) { + l_debug("Periodic scan timer called before scan could start!"); + scan_periodic_rearm(sc); + return; + } sc->sp.interval *= 2; if (sc->sp.interval > SCAN_MAX_INTERVAL) @@ -1033,23 +1072,14 @@ static bool start_next_scan_request(struct wiphy_radio_work_item *item) struct scan_request, work); struct scan_context *sc = sr->sc; - sc->work_started = true; - if (sc->state != SCAN_STATE_NOT_RUNNING) return false; if (!scan_request_send_trigger(sc, sr)) return false; - sc->work_started = false; - scan_request_failed(sc, sr, -EIO); - if (sc->sp.retry) { - sc->sp.retry = false; - scan_periodic_queue(sc); - } - return true; } @@ -1691,34 +1721,34 @@ static void scan_finished(struct scan_context *sc, struct scan_request *sr) { bool new_owner = false; + scan_notify_func_t callback = sr ? sr->callback : sc->sp.callback; + void *userdata = sr ? sr->userdata : sc->sp.userdata; if (bss_list) discover_hidden_network_bsses(sc, bss_list); - if (sr) { - l_queue_remove(sc->requests, sr); - sc->started = false; - sc->work_started = false; + if (sr) + sr->in_callback = true; - if (sr->callback) - new_owner = sr->callback(err, bss_list, - freqs, sr->userdata); - - /* - * Can start a new scan now that we've removed this one from - * the queue. If this were an external scan request (sr NULL) - * then the SCAN_FINISHED or SCAN_ABORTED handler would have - * taken care of sending the next command for a new or ongoing - * scan, or scheduling the next periodic scan. - */ - wiphy_radio_work_done(sc->wiphy, sr->work.id); - } else if (sc->sp.callback) - new_owner = sc->sp.callback(err, bss_list, - freqs, sc->sp.userdata); + if (callback) + new_owner = callback(err, bss_list, freqs, userdata); if (bss_list && !new_owner) l_queue_destroy(bss_list, (l_queue_destroy_func_t) scan_bss_free); + + if (!sr) + return; + + /* + * Can start a new scan now that we've removed this one from the + * queue. If this were an external scan request (sr NULL) then the + * SCAN_FINISHED or SCAN_ABORTED handler would have taken care of + * sending the next command for a new or ongoing scan. + */ + sr->in_callback = false; + l_queue_remove(sc->requests, sr); + wiphy_radio_work_done(sc->wiphy, sr->work.id); } static void get_scan_done(void *user) @@ -1730,7 +1760,7 @@ static void get_scan_done(void *user) sc->get_scan_cmd_id = 0; - if (l_queue_peek_head(sc->requests) == results->sr) + if (!results->sr || !results->sr->canceled) scan_finished(sc, 0, results->bss_list, results->freqs, results->sr); else @@ -1799,8 +1829,6 @@ static void scan_notify(struct l_genl_msg *msg, void *user_data) cmd = l_genl_msg_get_command(msg); - l_debug("Scan notification %s(%u)", nl80211cmd_to_string(cmd), cmd); - if (nl80211_parse_attrs(msg, NL80211_ATTR_WDEV, &wdev_id, NL80211_ATTR_WIPHY, &wiphy_id, NL80211_ATTR_UNSPEC) < 0) @@ -1810,6 +1838,8 @@ static void scan_notify(struct l_genl_msg *msg, void *user_data) if (!sc) return; + l_debug("Scan notification %s(%u)", nl80211cmd_to_string(cmd), cmd); + if (!l_genl_attr_init(&attr, msg)) return; @@ -1835,16 +1865,14 @@ static void scan_notify(struct l_genl_msg *msg, void *user_data) struct l_genl_msg *scan_msg; struct scan_results *results; bool send_next = false; + bool retry = false; bool get_results = false; - if (sc->state == SCAN_STATE_NOT_RUNNING) - break; - sc->state = SCAN_STATE_NOT_RUNNING; /* Was this our own scan or an external scan */ - if (sc->triggered) { - sc->triggered = false; + if (sr && sr->triggered) { + sr->triggered = false; if (!sr->callback) { scan_finished(sc, -ECANCELED, NULL, NULL, sr); @@ -1868,28 +1896,31 @@ static void scan_notify(struct l_genl_msg *msg, void *user_data) if (sc->sp.callback) get_results = true; - /* An external scan may have flushed our results */ - if (sc->started && scan_parse_flush_flag_from_msg(msg)) + /* + * Drop the ongoing scan if an external scan flushed + * our results. Otherwise, try to retry the trigger + * request if it failed with an -EBUSY. + */ + if (sr && sr->started && + scan_parse_flush_flag_from_msg(msg)) scan_finished(sc, -EAGAIN, NULL, NULL, sr); else - send_next = true; + retry = true; sr = NULL; } /* - * Send the next command of an ongoing request, or continue with - * a previously busy scan attempt due to an external scan. A - * temporary scan_request object is used (rather than 'sr') - * because the state of 'sr' tells us if the results should - * be used either as normal scan results, or to take advantage - * of the external scan as a 'free' periodic scan of sorts. + * Send the next command of an ongoing request, or continue + * with a previously busy scan attempt due to an external + * scan. */ - if (sc->work_started && send_next) { + if (send_next || retry) { struct scan_request *next = l_queue_peek_head( sc->requests); - if (next) + if (next && wiphy_radio_work_is_running(sc->wiphy, + next->work.id)) start_next_scan_request(&next->work); } @@ -1926,16 +1957,25 @@ static void scan_notify(struct l_genl_msg *msg, void *user_data) break; case NL80211_CMD_SCAN_ABORTED: - if (sc->state == SCAN_STATE_NOT_RUNNING) - break; - sc->state = SCAN_STATE_NOT_RUNNING; - if (sc->triggered) { - sc->triggered = false; + /* + * If there's nothing pending, then most likely an external + * scan got aborted. We don't care, ignore. + */ + if (!sr) + break; + + if (sr->triggered) { + sr->triggered = false; - scan_finished(sc, -ECANCELED, NULL, NULL, sr); - } else { + /* If periodic scan, don't report the abort */ + if (sr->periodic) + wiphy_radio_work_done(sc->wiphy, sr->work.id); + else + scan_finished(sc, -ECANCELED, NULL, NULL, sr); + } else if (wiphy_radio_work_is_running(sc->wiphy, + sr->work.id)) { /* * If this was an external scan that got aborted * we may be able to now queue our own scan although @@ -1943,8 +1983,7 @@ static void scan_notify(struct l_genl_msg *msg, void *user_data) * hardware or the driver because of another activity * starting in which case we should just get an EBUSY. */ - if (sc->work_started) - start_next_scan_request(&sr->work); + start_next_scan_request(&sr->work); } break; @@ -2087,7 +2126,7 @@ static int scan_init(void) return 0; } -static void scan_exit() +static void scan_exit(void) { l_queue_destroy(scan_contexts, (l_queue_destroy_func_t) scan_context_free); diff --git a/src/simauth.h b/src/simauth.h @@ -125,7 +125,7 @@ struct iwd_sim_auth *iwd_sim_auth_find(bool sim, bool aka); * @param data User data * * @return Transaction ID, used to cancel the request if needed - * < 0 in case of an error + * < 0 in case of an error */ int sim_auth_check_milenage(struct iwd_sim_auth *auth, const uint8_t *rand, const uint8_t *autn, @@ -141,7 +141,7 @@ int sim_auth_check_milenage(struct iwd_sim_auth *auth, * @param data User data * * @return Transaction ID, used to cancel the request if needed - * < 0 in case of an error + * < 0 in case of an error */ int sim_auth_run_gsm(struct iwd_sim_auth *auth, const uint8_t *rands, int num_rands, sim_auth_run_gsm_cb_t cb, void *data); diff --git a/src/station.c b/src/station.c @@ -239,9 +239,10 @@ static int station_autoconnect_next(struct station *station) } return 0; - } else - l_debug("autoconnect: network_autoconnect: %s (%d)", - strerror(-r), r); + } + + l_debug("autoconnect: network_autoconnect: %s (%d)", + strerror(-r), r); } return -ENOENT; @@ -1107,7 +1108,7 @@ build_ie: * any offload features are detected (since IWD prefers to use offload). */ info.ocvc = !disable_ocv && bss_info.ocvc && info.mfpc && - !wiphy_can_offload(wiphy);; + !wiphy_can_offload(wiphy); /* * IEEE 802.11-2020 9.4.2.24.4 states extended key IDs can only be used @@ -1232,10 +1233,13 @@ static bool new_scan_results(int err, struct l_queue *bss_list, if (err) return false; - station_set_scan_results(station, bss_list, freqs, true); + station_set_scan_results(station, bss_list, freqs, false); station_process_owe_transition_networks(station); + station->autoconnect_can_start = true; + station_autoconnect_start(station); + return true; } @@ -1304,10 +1308,13 @@ static bool station_quick_scan_results(int err, struct l_queue *bss_list, if (err) goto done; - station_set_scan_results(station, bss_list, freqs, true); + station_set_scan_results(station, bss_list, freqs, false); station_process_owe_transition_networks(station); + station->autoconnect_can_start = true; + station_autoconnect_start(station); + done: if (station->state == STATION_STATE_AUTOCONNECT_QUICK) /* @@ -1587,6 +1594,8 @@ bool station_set_autoconnect(struct station *station, bool autoconnect) static void station_roam_state_clear(struct station *station) { + l_debug("%u", netdev_get_ifindex(station->netdev)); + l_timeout_remove(station->roam_trigger_timeout); station->roam_trigger_timeout = NULL; station->preparing_roam = false; @@ -1611,6 +1620,8 @@ static void station_reset_connection_state(struct station *station) struct l_dbus *dbus = dbus_get_bus(); #endif + l_debug("%u", netdev_get_ifindex(station->netdev)); + if (!network) return; @@ -1901,9 +1912,9 @@ static void station_ft_ds_action_start(struct station *station) continue; /* - * Fire and forget. Netdev will maintain a cache of responses and - * when the time comes these can be referenced for a roam - */ + * Fire and forget. Netdev will maintain a cache of responses + * and when the time comes these can be referenced for a roam + */ netdev_fast_transition_over_ds_action(station->netdev, bss); } } @@ -2255,6 +2266,8 @@ static void station_roam_scan_triggered(int err, void *user_data) return; } + station_debug_event(station, "roam-scan-triggered"); + /* * Do not update the Scanning property as we won't be updating the * list of networks. @@ -2615,7 +2628,7 @@ static void station_ap_directed_roam(struct station *station, pos += 12; } - if (req_mode & WNM_REQUEST_MODE_ESS_DISASSOCIATION_IMMINENT ) { + if (req_mode & WNM_REQUEST_MODE_ESS_DISASSOCIATION_IMMINENT) { uint8_t url_len; if (pos + 1 > body_len) @@ -2639,7 +2652,7 @@ static void station_ap_directed_roam(struct station *station, if (req_mode & WNM_REQUEST_MODE_PREFERRED_CANDIDATE_LIST) { l_debug("roam: AP sent a preferred candidate list"); station_neighbor_report_cb(station->netdev, 0, body + pos, - body_len - pos,station); + body_len - pos, station); } else { l_debug("roam: AP did not include a preferred candidate list"); if (station_roam_scan(station, NULL) < 0) diff --git a/src/util.c b/src/util.c @@ -39,7 +39,7 @@ const char *util_ssid_to_utf8(size_t len, const uint8_t *ssid) { - static char buf[3* 32 + 1]; + static char buf[3 * 32 + 1]; size_t i = 0, pos = 0; const uint8_t *start = ssid, *end; @@ -136,7 +136,7 @@ bool util_string_to_address(const char *str, uint8_t *out_addr) if (str[i + 2] != ':') return false; - } + } if (!l_ascii_isxdigit(str[i])) return false; diff --git a/src/wiphy.c b/src/wiphy.c @@ -209,14 +209,14 @@ static bool wiphy_can_connect_sae(struct wiphy *wiphy) * TODO: No support for CMD_EXTERNAL_AUTH yet. */ return false; - } else { - /* Case (2) */ - if (wiphy_has_ext_feature(wiphy, - NL80211_EXT_FEATURE_SAE_OFFLOAD)) - return true; - - return false; } + + /* Case (2) */ + if (wiphy_has_ext_feature(wiphy, + NL80211_EXT_FEATURE_SAE_OFFLOAD)) + return true; + + return false; } enum ie_rsn_akm_suite wiphy_select_akm(struct wiphy *wiphy, @@ -918,6 +918,7 @@ static void wiphy_print_band_info(struct band *band, const char *name) if (band->ht_supported) { uint8_t max_nss = bit_field(band->ht_mcs_set[12], 2, 2) + 1; + l_info("\t\tHT Capabilities:"); if (test_bit(band->ht_capabilities, 1)) diff --git a/src/wiphy.h b/src/wiphy.h @@ -45,6 +45,12 @@ struct wiphy_radio_work_item { const struct wiphy_radio_work_item_ops *ops; }; +#define WIPHY_WORK_PRIORITY_FRAME 0 +#define WIPHY_WORK_PRIORITY_OFFCHANNEL 0 +#define WIPHY_WORK_PRIORITY_CONNECT 1 +#define WIPHY_WORK_PRIORITY_SCAN 2 +#define WIPHY_WORK_PRIORITY_PERIODIC_SCAN 3 + enum wiphy_state_watch_event { WIPHY_STATE_WATCH_EVENT_POWERED, WIPHY_STATE_WATCH_EVENT_RFKILLED, diff --git a/src/wsc.c b/src/wsc.c @@ -555,7 +555,7 @@ static void wsc_store_credentials(struct wsc_credentials_info *creds, else l_settings_set_bytes(settings, "Security", "PreSharedKey", creds[i].psk, - sizeof(creds[i].psk)); + sizeof(creds[i].psk)); } l_debug("Storing credential for '%s(%s)'", ssid, @@ -664,7 +664,7 @@ static void wsc_check_can_connect(struct wsc_station_dbus *wsc, case STATION_STATE_AUTOCONNECT_QUICK: case STATION_STATE_AUTOCONNECT_FULL: case STATION_STATE_ROAMING: - l_warn("wsc_check_can_connect: invalid station state"); + l_warn("%s: invalid station state", __func__); break; } error: diff --git a/src/wscutil.c b/src/wscutil.c @@ -61,7 +61,7 @@ bool wsc_wfa_ext_iter_next(struct wsc_wfa_ext_iter *iter) len = *start; start += 1; - if (start + len > end) + if (len > end - start) return false; iter->type = type; @@ -98,7 +98,7 @@ bool wsc_attr_iter_next(struct wsc_attr_iter *iter) len = l_get_be16(start); start += 2; - if (start + len > end) + if (len > end - start) return false; iter->type = type; @@ -1751,6 +1751,7 @@ static uint8_t *wsc_attr_builder_free(struct wsc_attr_builder *builder, if (builder->curlen > 0) { uint8_t *bytes = builder->buf + builder->offset; + l_put_be16(builder->curlen - 4, bytes + 2); builder->offset += builder->curlen; builder->curlen = 0; diff --git a/tools/test-runner b/tools/test-runner @@ -673,6 +673,7 @@ class Namespace: if self.args.valgrind: args.extend(['valgrind', '--leak-check=full', '--track-origins=yes', + '--show-leak-kinds=all', '--log-file=/tmp/valgrind.log.%p']) args.extend(['iwd', '-p', iwd_radios, '-E']) diff --git a/unit/test-dpp.c b/unit/test-dpp.c @@ -143,7 +143,10 @@ int main(int argc, char *argv[]) { l_test_init(&argc, &argv); - l_test_add("DPP test key derivation", test_key_derivation, NULL); + if (l_checksum_is_supported(L_CHECKSUM_SHA256, true) && + l_getrandom_is_supported()) + l_test_add("DPP test key derivation", + test_key_derivation, NULL); return l_test_run(); } diff --git a/unit/test-json.c b/unit/test-json.c @@ -76,42 +76,6 @@ static void test_json_escaped_unicode(const void *data) } /* - * Tests that unsupported types will not parse - */ -static void test_json_unsupported_types(const void *data) -{ - /* - * Valid JSON objects but currently unsupported types - */ - char arrays[] = "{\"test\":[1, 2, 3, 4]}"; - char integers[] = "{\"test\": 10 }"; - char bools[] = "{\"test\": true}"; - - struct json_iter iter; - struct json_contents *c = json_contents_new(arrays, strlen(arrays)); - - json_iter_init(&iter, c); - assert(!json_iter_parse(&iter, - JSON_MANDATORY("test", JSON_ARRAY, NULL), - JSON_UNDEFINED)); - json_contents_free(c); - - c = json_contents_new(integers, strlen(integers)); - json_iter_init(&iter, c); - assert(!json_iter_parse(&iter, - JSON_MANDATORY("test", JSON_PRIMITIVE, NULL), - JSON_UNDEFINED)); - json_contents_free(c); - - c = json_contents_new(bools, strlen(bools)); - json_iter_init(&iter, c); - assert(!json_iter_parse(&iter, - JSON_MANDATORY("test", JSON_PRIMITIVE, NULL), - JSON_UNDEFINED)); - json_contents_free(c); -} - -/* * Basic test string values and nested objects */ static void test_json(const void *data) @@ -248,6 +212,309 @@ static void test_json_larger_object(const void *data) json_contents_free(c); } +static void check_primitives(struct json_iter *i, struct json_iter *ui, + struct json_iter *t, struct json_iter *f, + struct json_iter *null, struct json_iter *obj) +{ + + int i_val; + unsigned int ui_val; + bool b_val; + + assert(json_iter_is_valid(i)); + assert(!json_iter_get_uint(i, NULL)); + assert(!json_iter_get_boolean(i, NULL)); + assert(!json_iter_get_null(i)); + assert(!json_iter_next(i)); + assert(json_iter_get_int(i, &i_val)); + assert(i_val == -10); + + assert(json_iter_is_valid(ui)); + assert(!json_iter_get_boolean(ui, NULL)); + assert(!json_iter_get_null(ui)); + assert(!json_iter_next(ui)); + assert(json_iter_get_int(ui, &i_val)); + assert(json_iter_get_uint(ui, &ui_val)); + assert(i_val == 10 && ui_val == 10); + + assert(json_iter_is_valid(t)); + assert(!json_iter_get_null(t)); + assert(!json_iter_get_int(t, NULL)); + assert(!json_iter_get_uint(t, NULL)); + assert(!json_iter_next(t)); + assert(json_iter_get_boolean(t, &b_val)); + assert(b_val == true); + + assert(json_iter_is_valid(f)); + assert(!json_iter_get_null(f)); + assert(!json_iter_get_int(f, NULL)); + assert(!json_iter_get_uint(f, NULL)); + assert(!json_iter_next(f)); + assert(json_iter_get_boolean(f, &b_val)); + assert(b_val == false); + + assert(json_iter_is_valid(null)); + assert(!json_iter_get_int(null, NULL)); + assert(!json_iter_get_uint(null, NULL)); + assert(!json_iter_get_boolean(null, NULL)); + assert(!json_iter_next(null)); + assert(json_iter_get_null(null)); + + if (obj) { + assert(json_iter_is_valid(obj)); + assert(!json_iter_next(obj)); + assert(json_iter_parse(obj, + JSON_MANDATORY("null_val", JSON_PRIMITIVE, null), + JSON_MANDATORY("false_val", JSON_PRIMITIVE, f), + JSON_MANDATORY("true_val", JSON_PRIMITIVE, t), + JSON_MANDATORY("int_val", JSON_PRIMITIVE, i), + JSON_MANDATORY("uint_val", JSON_PRIMITIVE, ui), + JSON_UNDEFINED)); + + check_primitives(i, ui, t, f, null, NULL); + } +} + +static void test_json_primitives(const void *data) +{ + char json[] = "{\"int_val\": -10," + "\"uint_val\": 10," + "\"true_val\": true," + "\"false_val\": false," + "\"null_val\": null," + "\"obj_val\":{" + "\"int_val\": -10," + "\"uint_val\": 10," + "\"true_val\": true," + "\"false_val\": false," + "\"null_val\": null}}"; + struct json_contents *c = json_contents_new(json, strlen(json)); + struct json_iter outer, inner, null, f, t, i, ui; + struct json_iter not_found; + + json_iter_init(&outer, c); + assert(json_iter_parse(&outer, + JSON_MANDATORY("obj_val", JSON_OBJECT, &inner), + JSON_MANDATORY("null_val", JSON_PRIMITIVE, &null), + JSON_MANDATORY("false_val", JSON_PRIMITIVE, &f), + JSON_MANDATORY("true_val", JSON_PRIMITIVE, &t), + JSON_MANDATORY("int_val", JSON_PRIMITIVE, &i), + JSON_MANDATORY("uint_val", JSON_PRIMITIVE, &ui), + JSON_OPTIONAL("not_found", JSON_PRIMITIVE, &not_found), + JSON_UNDEFINED)); + + assert(!json_iter_is_valid(&not_found)); + + check_primitives(&i, &ui, &t, &f, &null, &inner); + + json_contents_free(c); +} + +static void test_json_arrays(const void *data) +{ + unsigned int ui; + int i; + bool b; + int count; + char json[] = "{\"uint_array\":[1, 2, 3, 4, 5, 6]," + "\"int_array\":[-1, -2, -3, -4, -5, -6]," + "\"bool_array\":[true, false, true, false]," + "\"null_array\":[null, null, null, null]," + "\"obj_array\":[{}, {\"key\":\"value\", \"key2\":\"value2\"}]," + "\"mixed_array\":[1, -1, true, false, null, \"string\"]}"; + + struct json_iter iter; + struct json_iter i_array, ui_array, b_array, n_array, + m_array, obj_array; + struct json_contents *c = json_contents_new(json, strlen(json)); + + json_iter_init(&iter, c); + assert(json_iter_parse(&iter, + JSON_MANDATORY("mixed_array", JSON_ARRAY, &m_array), + JSON_MANDATORY("null_array", JSON_ARRAY, &n_array), + JSON_MANDATORY("bool_array", JSON_ARRAY, &b_array), + JSON_MANDATORY("int_array", JSON_ARRAY, &i_array), + JSON_MANDATORY("uint_array", JSON_ARRAY, &ui_array), + JSON_MANDATORY("obj_array", JSON_ARRAY, &obj_array), + JSON_UNDEFINED)); + + count = 1; + + while (json_iter_next(&ui_array)) { + assert(json_iter_get_type(&ui_array) == JSON_PRIMITIVE); + assert(!json_iter_parse(&ui_array, JSON_UNDEFINED)); + assert(json_iter_get_uint(&ui_array, &ui)); + assert(ui == (unsigned int) count); + count++; + } + + count = -1; + + while (json_iter_next(&i_array)) { + assert(json_iter_get_type(&i_array) == JSON_PRIMITIVE); + assert(!json_iter_parse(&i_array, JSON_UNDEFINED)); + assert(json_iter_get_int(&i_array, &i)); + assert(i == count); + count--; + } + + count = 0; + + while (json_iter_next(&b_array)) { + assert(json_iter_get_type(&b_array) == JSON_PRIMITIVE); + assert(!json_iter_parse(&b_array, JSON_UNDEFINED)); + assert(json_iter_get_boolean(&b_array, &b)); + assert(b == count % 2 ? false : true); + count++; + } + + count = 0; + + while (json_iter_next(&n_array)) { + assert(json_iter_get_type(&n_array) == JSON_PRIMITIVE); + assert(!json_iter_parse(&n_array, JSON_UNDEFINED)); + assert(json_iter_get_null(&n_array)); + count++; + } + + assert(count == 4); + + count = 0; + + while (json_iter_next(&m_array)) { + _auto_(l_free) char *str = NULL; + + switch (count) { + case 0: + assert(json_iter_get_type(&m_array) == JSON_PRIMITIVE); + assert(json_iter_get_uint(&m_array, &ui)); + assert(ui == 1); + break; + case 1: + assert(json_iter_get_type(&m_array) == JSON_PRIMITIVE); + assert(json_iter_get_int(&m_array, &i)); + assert(i == -1); + break; + case 2: + case 3: + assert(json_iter_get_type(&m_array) == JSON_PRIMITIVE); + assert(json_iter_get_boolean(&m_array, &b)); + assert(b == count % 2 ? false : true); + break; + case 4: + assert(json_iter_get_type(&m_array) == JSON_PRIMITIVE); + assert(json_iter_get_null(&m_array)); + break; + case 5: + assert(json_iter_get_type(&m_array) == JSON_STRING); + assert(json_iter_get_string(&m_array, &str)); + assert(!strcmp(str, "string")); + break; + } + + count++; + } + + count = 0; + + assert(!json_iter_parse(&obj_array, JSON_UNDEFINED)); + + while (json_iter_next(&obj_array)) { + struct json_iter object; + + assert(json_iter_get_type(&obj_array) == JSON_OBJECT); + assert(json_iter_get_container(&obj_array, &object)); + + switch (count) { + case 0: + assert(json_iter_parse(&object, JSON_UNDEFINED)); + break; + case 1: + assert(json_iter_parse(&object, + JSON_MANDATORY("key", JSON_STRING, NULL), + JSON_UNDEFINED)); + break; + } + + count++; + } + + assert(count == 2); + + json_contents_free(c); +} + +static void test_json_nested_arrays(const void *data) +{ + char json[] = "{\"array\":[[], {}, [1, 2], {\"key\":\"value\"}, [\"one\",\"two\"]]}"; + int count = 0; + struct json_iter iter; + struct json_iter array; + struct json_iter inner; + struct json_contents *c = json_contents_new(json, strlen(json)); + + json_iter_init(&iter, c); + assert(json_iter_parse(&iter, + JSON_MANDATORY("array", JSON_ARRAY, &array), + JSON_UNDEFINED)); + + while (json_iter_next(&array)) { + int count2 = 0; + + assert(json_iter_get_container(&array, &inner)); + + while (json_iter_next(&inner)) { + _auto_(l_free) char *str = NULL; + + switch (count) { + case 0: + case 1: + assert(false); + break; + case 4: + assert(json_iter_get_type(&inner) == + JSON_STRING); + assert(json_iter_get_string(&inner, &str)); + + if (count2 == 0) + assert(!strcmp("one", str)); + else + assert(!strcmp("two", str)); + + break; + } + + count2++; + } + + switch (count) { + case 0: + assert(count2 == 0); + break; + case 1: + assert(count2 == 0); + break; + case 2: + assert(count2 == 2); + break; + case 3: + assert(count2 == 0); + break; + case 4: + assert(count2 == 2); + break; + default: + break; + } + + count++; + } + + assert(count == 5); + + json_contents_free(c); +} + int main(int argc, char *argv[]) { l_test_init(&argc, &argv); @@ -255,10 +522,12 @@ int main(int argc, char *argv[]) l_test_add("json unicode", test_json_unicode, NULL); l_test_add("json escaped unicode", test_json_escaped_unicode, NULL); l_test_add("json nested objects", test_json, NULL); - l_test_add("json unsupported types", test_json_unsupported_types, NULL); l_test_add("json empty objects", test_json_empty_objects, NULL); l_test_add("json parse out of order", test_json_out_of_order, NULL); l_test_add("json larger object", test_json_larger_object, NULL); + l_test_add("json test primitives", test_json_primitives, NULL); + l_test_add("json test arrays", test_json_arrays, NULL); + l_test_add("json test nested arrays", test_json_nested_arrays, NULL); return l_test_run(); }