eiwd

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

commit ac7c84b1722f042f345c6cc7a22d2abf67b27f5c
parent 74000397bb7db98c14c6150a850cd0f675dd057e
Author: illiliti <illiliti@protonmail.com>
Date:   Mon, 10 Jan 2022 19:48:16 +0300

Merge tag '1.21'

Release 1.21

Diffstat:
M.gitignore | 2++
MChangeLog | 4++++
MMakefile.am | 40++++++++++++++++++++++++++++++++--------
Aautotests/testDPP/connection_test.py | 73+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aautotests/testDPP/hostapd.conf | 7+++++++
Aautotests/testDPP/hw.conf | 9+++++++++
Aautotests/testDPP/ssidCCMP.psk | 2++
Aautotests/testDPP/wpas.conf | 5+++++
Mautotests/testHotspot/hw.conf | 6++----
Aautotests/testHotspot/main.conf | 2++
Dautotests/testHotspot/ssidWPA2-2.conf | 9---------
Dautotests/testHotspot/ssidWPA2-3.conf | 9---------
Aautotests/testOWE-transition/ssidOWE-2.conf | 9+++++++++
Aautotests/testOWE-transition/ssidOpen-2.conf | 3+++
Mautotests/testP2P/connection_test.py | 20++++++++++++++------
Mautotests/testPSK-roam/connection_test.py | 4++++
Mautotests/util/iwd.py | 57++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mautotests/util/wpas.py | 40+++++++++++++++++++++++++++++++++++++---
Mclient/dbus-proxy.h | 1+
Aclient/dpp.c | 233+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mconfigure.ac | 4++--
Adoc/device-provisioning.txt | 39+++++++++++++++++++++++++++++++++++++++
Adoc/main.conf | 44++++++++++++++++++++++++++++++++++++++++++++
Ashared/jsmn.h | 468+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Msrc/ap.c | 9+++++----
Msrc/band.c | 193+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Msrc/band.h | 10++++++++++
Msrc/crypto.c | 18+++++++++++-------
Msrc/crypto.h | 10+++++-----
Msrc/dbus.h | 1+
Asrc/dpp-util.c | 785+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/dpp-util.h | 169+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/dpp.c | 1665+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Msrc/handshake.c | 1+
Msrc/ie.h | 1+
Asrc/json.c | 270+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/json.h | 83+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Msrc/netdev.c | 34+++++++++++++++++++++++++++++-----
Asrc/offchannel.c | 323+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/offchannel.h | 29+++++++++++++++++++++++++++++
Msrc/p2p.c | 35++++++++++++++++++-----------------
Msrc/rrm.c | 11++++++-----
Msrc/scan.c | 356+------------------------------------------------------------------------------
Msrc/scan.h | 25+------------------------
Msrc/station.c | 15++++++++-------
Msrc/util.c | 194+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Msrc/util.h | 17+++++++++++++++++
Msrc/wiphy.c | 32++++++++++++++++++++------------
Msrc/wiphy.h | 2+-
Msrc/wsc.c | 21+++++++++++----------
Mtools/hwsim.c | 230+++++++++++++++++++++++++++++++++++++++----------------------------------------
Mtools/test-runner | 19++++++++++++++-----
Aunit/test-dpp.c | 149+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aunit/test-json.c | 264+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
54 files changed, 5443 insertions(+), 618 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -57,6 +57,8 @@ unit/test-eap-sim unit/test-client unit/test-p2p unit/test-band +unit/test-dpp +unit/test-json unit/cert-*.pem unit/cert-*.csr unit/cert-*.srl diff --git a/ChangeLog b/ChangeLog @@ -1,3 +1,7 @@ +ver 1.21: + Fix issue with handling disconnect events issued by AP. + Add experimental support for DPP feature. + ver 1.20: Fix issue with handling Hotspot 2.0 requirements. Add support for evict_nocarrier setting during roaming. diff --git a/Makefile.am b/Makefile.am @@ -248,6 +248,10 @@ src_iwd_SOURCES = src/main.c linux/nl80211.h src/iwd.h src/missing.h \ src/ip-pool.h src/ip-pool.c \ src/band.h src/band.c \ src/sysfs.h src/sysfs.c \ + src/offchannel.h src/offchannel.c \ + src/dpp-util.h src/dpp-util.c \ + src/json.h src/json.c \ + src/dpp.c \ $(eap_sources) \ $(builtin_sources) @@ -296,7 +300,8 @@ client_iwctl_SOURCES = client/main.c \ client/properties.h client/properties.c \ client/wsc.c client/station.c \ client/diagnostic.c client/diagnostic.h \ - client/daemon.c client/daemon.h + client/daemon.c client/daemon.h \ + client/dpp.c client_iwctl_LDADD = $(ell_ldadd) $(READLINE_LIBS) @@ -321,7 +326,8 @@ monitor_iwmon_SOURCES = monitor/main.c linux/nl80211.h \ src/eapolutil.h src/eapolutil.c \ src/nl80211cmd.h src/nl80211cmd.c \ src/p2putil.c src/p2putil.h \ - src/anqputil.h src/anqputil.c + src/anqputil.h src/anqputil.c \ + src/band.h src/band.c monitor_iwmon_LDADD = $(ell_ldadd) if MANUAL_PAGES @@ -336,6 +342,7 @@ wired_ead_SOURCES = wired/main.c wired/ethdev.h wired/ethdev.c \ wired/network.h wired/network.c \ wired/dbus.h wired/dbus.c \ src/module.h src/module.c \ + src/band.h src/band.c \ $(eap_sources) wired_ead_LDADD = $(ell_ldadd) wired_ead_DEPENDENCIES = $(ell_dependencies) @@ -363,7 +370,8 @@ tools_probe_req_SOURCES = tools/probe-req.c src/mpdu.h src/mpdu.c \ src/ie.h src/ie.c \ src/nl80211util.h src/nl80211util.c \ src/util.h src/util.c \ - src/common.h src/common.c + src/common.h src/common.c \ + src/band.h src/band.c tools_probe_req_LDADD = $(ell_ldadd) endif @@ -372,8 +380,11 @@ bin_PROGRAMS += tools/hwsim tools_hwsim_SOURCES = tools/hwsim.c src/mpdu.h \ src/util.h src/util.c \ + src/nl80211cmd.h src/nl80211cmd.c \ + src/nl80211util.h src/nl80211util.c \ src/storage.h src/storage.c \ - src/common.h src/common.c + src/common.h src/common.c \ + src/band.h src/band.c tools_hwsim_LDADD = $(ell_ldadd) if DBUS_POLICY @@ -391,7 +402,8 @@ unit_tests = unit/test-cmac-aes \ unit/test-crypto unit/test-eapol unit/test-mpdu \ unit/test-ie unit/test-util unit/test-ssid-security \ unit/test-arc4 unit/test-wsc unit/test-eap-mschapv2 \ - unit/test-eap-sim unit/test-sae unit/test-p2p unit/test-band + unit/test-eap-sim unit/test-sae unit/test-p2p unit/test-band \ + unit/test-dpp unit/test-json if CLIENT unit_tests += unit/test-client @@ -483,7 +495,7 @@ unit_test_eapol_DEPENDENCIES = $(ell_dependencies) \ unit/cert-client-key-pkcs8.pem \ unit/tls-settings.8021x -unit_test_util_SOURCES = src/util.h src/util.c \ +unit_test_util_SOURCES = src/util.h src/util.c src/band.c src/band.h \ unit/test-util.c unit_test_util_LDADD = $(ell_ldadd) @@ -540,21 +552,33 @@ unit_test_p2p_SOURCES = unit/test-p2p.c src/wscutil.h src/wscutil.c \ src/crypto.h src/crypto.c \ src/ie.h src/ie.c \ src/util.h src/util.c \ - src/p2putil.h src/p2putil.c + src/p2putil.h src/p2putil.c \ + src/band.h src/band.c unit_test_p2p_LDADD = $(ell_ldadd) +unit_test_dpp_SOURCES = unit/test-dpp.c src/dpp-util.h src/dpp-util.c \ + src/band.h src/band.c \ + src/util.h src/util.c src/crypto.h \ + src/crypto.c src/json.h src/json.c +unit_test_dpp_LDADD = $(ell_ldadd) + +unit_test_json_SOURCES = unit/test-json.c src/json.h src/json.c shared/jsmn.h +unit_test_json_LDADD = $(ell_ldadd) + TESTS = $(unit_tests) EXTRA_DIST = src/genbuiltin src/iwd.service.in src/net.connman.iwd.service \ wired/ead.service.in wired/net.connman.ead.service \ src/80-iwd.link src/pkcs8.conf unit/gencerts.cnf \ + doc/main.conf \ $(manual_pages) $(patsubst %.1,%.rst, \ $(patsubst %.5,%.rst, \ $(patsubst %.8,%.rst,$(manual_pages)))) AM_CFLAGS = $(ell_cflags) -fvisibility=hidden \ -DUNITDIR=\""$(top_srcdir)/unit/"\" \ - -DCERTDIR=\""$(top_builddir)/unit/"\" + -DCERTDIR=\""$(top_builddir)/unit/"\" \ + -DJSMN_PARENT_LINKS -DJSMN_STRICT if DBUS AM_CFLAGS += -DHAVE_DBUS diff --git a/autotests/testDPP/connection_test.py b/autotests/testDPP/connection_test.py @@ -0,0 +1,73 @@ +#!/usr/bin/python3 + +import unittest +import sys + +sys.path.append('../util') +from iwd import IWD +from wpas import Wpas +from hostapd import HostapdCLI + +class Test(unittest.TestCase): + + def test_iwd_as_enrollee(self): + wpas = Wpas('wpas.conf') + + wd = IWD(True) + + devices = wd.list_devices(1) + device = devices[0] + device.autoconnect = True + + uri = device.dpp_start_enrollee() + + wpas.dpp_configurator_create(uri) + wpas.dpp_configurator_start('ssidCCMP', 'secret123') + + condition = 'obj.state == DeviceState.connected' + wd.wait_for_object_condition(device, condition) + + device.disconnect() + device.dpp_stop() + + del wpas + + def test_iwd_as_configurator(self): + IWD.copy_to_storage('ssidCCMP.psk') + + wpas = Wpas('wpas.conf') + hapd = HostapdCLI('hostapd.conf') + + wd = IWD(True) + + devices = wd.list_devices(1) + device = devices[0] + device.autoconnect = True + + condition = 'obj.state == DeviceState.connected' + wd.wait_for_object_condition(device, condition) + + uri = device.dpp_start_configurator() + + wpas.dpp_enrollee_start(uri) + + hapd.wait_for_event('AP-STA-CONNECTED 42:00:00:00:00:00') + + device.disconnect() + device.dpp_stop() + + del wpas + + def tearDown(self): + IWD.clear_storage() + + @classmethod + def setUpClass(cls): + pass + + @classmethod + def tearDownClass(cls): + pass + +if __name__ == '__main__': + unittest.main(exit=True) diff --git a/autotests/testDPP/hostapd.conf b/autotests/testDPP/hostapd.conf @@ -0,0 +1,7 @@ +hw_mode=g +channel=1 +ssid=ssidCCMP + +wpa=2 +wpa_pairwise=CCMP +wpa_passphrase=secret123 diff --git a/autotests/testDPP/hw.conf b/autotests/testDPP/hw.conf @@ -0,0 +1,9 @@ +[SETUP] +num_radios=3 +start_iwd=0 + +[WPA_SUPPLICANT] +rad0=wpas.conf + +[HOSTAPD] +rad1=hostapd.conf diff --git a/autotests/testDPP/ssidCCMP.psk b/autotests/testDPP/ssidCCMP.psk @@ -0,0 +1,2 @@ +[Security] +Passphrase=secret123 diff --git a/autotests/testDPP/wpas.conf b/autotests/testDPP/wpas.conf @@ -0,0 +1,5 @@ +ctrl_interface=/tmp/rad1-p2p-wpas + +update_config=1 +pmf=2 +dpp_config_processing=2 diff --git a/autotests/testHotspot/hw.conf b/autotests/testHotspot/hw.conf @@ -1,11 +1,9 @@ [SETUP] -num_radios=6 +num_radios=4 start_iwd=0 hwsim_medium=yes [HOSTAPD] rad0=ssidHotspot.conf rad1=ssidWPA2-1.conf -rad2=ssidWPA2-2.conf -rad3=ssidWPA2-3.conf -rad4=ssidHotspotUnconfigured.conf +rad2=ssidHotspotUnconfigured.conf diff --git a/autotests/testHotspot/main.conf b/autotests/testHotspot/main.conf @@ -0,0 +1,2 @@ +[Scan] +DisableMacAddressRandomization=true diff --git a/autotests/testHotspot/ssidWPA2-2.conf b/autotests/testHotspot/ssidWPA2-2.conf @@ -1,9 +0,0 @@ -ctrl_interface=/var/run/hostapd -hw_mode=g -channel=3 -ssid=ssidWPA2-2 - -wpa=2 -wpa_pairwise=CCMP -wpa_passphrase=secret123 -beacon_int=10 diff --git a/autotests/testHotspot/ssidWPA2-3.conf b/autotests/testHotspot/ssidWPA2-3.conf @@ -1,9 +0,0 @@ -ctrl_interface=/var/run/hostapd -hw_mode=g -channel=4 -ssid=ssidWPA2-3 - -wpa=2 -wpa_pairwise=CCMP -wpa_passphrase=secret123 -beacon_int=10 diff --git a/autotests/testOWE-transition/ssidOWE-2.conf b/autotests/testOWE-transition/ssidOWE-2.conf @@ -0,0 +1,9 @@ +ssid=owe-hidden-2 +bssid=02:00:00:00:f3:00 +channel=1 +ignore_broadcast_ssid=1 +ieee80211w=1 + +wpa=2 +wpa_key_mgmt=OWE +rsn_pairwise=CCMP diff --git a/autotests/testOWE-transition/ssidOpen-2.conf b/autotests/testOWE-transition/ssidOpen-2.conf @@ -0,0 +1,3 @@ +channel=1 +ssid=transition-2 +bssid=02:00:00:00:f2:00 diff --git a/autotests/testP2P/connection_test.py b/autotests/testP2P/connection_test.py @@ -12,6 +12,8 @@ from config import ctx from wpas import Wpas class Test(unittest.TestCase): + leases_path = '/tmp/dhcp.lease' + def test_1_client_go_neg_responder(self): self.p2p_connect_test(preauthorize=False, go=False) @@ -92,10 +94,11 @@ class Test(unittest.TestCase): peer_ifname = wpas.p2p_group['ifname'] self.assertEqual(wpas.p2p_group['role'], 'GO' if not go else 'client') + os.system('> ' + self.leases_path) + if not go: ctx.start_process(['ip', 'addr', 'add','dev', peer_ifname, '192.168.1.20/255.255.255.0']).wait() - os.system('> /tmp/dhcp.leases') - dhcp = ctx.start_process(['dhcpd', '-f', '-cf', '/tmp/dhcpd.conf', '-lf', '/tmp/dhcp.leases', peer_ifname]) + dhcp = ctx.start_process(['dhcpd', '-f', '-cf', '/tmp/dhcpd.conf', '-lf', self.leases_path, peer_ifname]) self.dhcp = dhcp wd.wait_for_object_condition(wpas, 'len(obj.p2p_clients) == 1', max_wait=3) @@ -105,12 +108,17 @@ class Test(unittest.TestCase): self.assertEqual(wpas.p2p_group['ip_addr'], '192.168.1.2') self.assertEqual(wpas.p2p_group['ip_mask'], '255.255.255.240') self.assertEqual(wpas.p2p_group['go_ip_addr'], '192.168.1.1') - dhcp = ctx.start_process(['dhclient', '-v', '-d', '--no-pid', '-cf', '/dev/null', '-lf', '/tmp/dhcp.leases', - '-sf', '/tmp/dhclient-script', peer_ifname]) + + extra_params = [] + if ctx.is_verbose('dhclient'): + extra_params.append('-v') + + dhcp = ctx.start_process(['dhclient', '-d', '--no-pid', '-cf', '/dev/null', '-lf', self.leases_path, + '-sf', '/tmp/dhclient-script'] + extra_params + [peer_ifname]) self.dhcp = dhcp wd.wait_for_object_condition(peer, 'obj.connected', max_wait=15) - time.sleep(1) # Give the client time to set the IP + time.sleep(5) # Give the client time to set the IP testutil.test_ip_address_match(peer_ifname, peer.connected_ip) if not go: @@ -146,7 +154,7 @@ class Test(unittest.TestCase): self.wpas = None if self.dhcp is not None: ctx.stop_process(self.dhcp) - for path in ['/tmp/dhcp.leases']: + for path in [self.leases_path, self.leases_path + '~']: if os.path.exists(path): os.remove(path) diff --git a/autotests/testPSK-roam/connection_test.py b/autotests/testPSK-roam/connection_test.py @@ -100,6 +100,10 @@ class Test(unittest.TestCase): self.assertRaises(Exception, testutil.test_ifaces_connected, (self.bss_hostapd[1].ifname, device.name, True, True)) + self.bss_hostapd[0].deauthenticate(device.address) + condition = 'obj.state == DeviceState.disconnected' + wd.wait_for_object_condition(device, condition) + def test_ft_psk(self): wd = IWD(True) diff --git a/autotests/util/iwd.py b/autotests/util/iwd.py @@ -40,6 +40,7 @@ IWD_P2P_PEER_INTERFACE = 'net.connman.iwd.p2p.Peer' IWD_P2P_SERVICE_MANAGER_INTERFACE = 'net.connman.iwd.p2p.ServiceManager' IWD_P2P_WFD_INTERFACE = 'net.connman.iwd.p2p.Display' IWD_STATION_DEBUG_INTERFACE = 'net.connman.iwd.StationDebug' +IWD_DPP_INTERFACE = 'net.connman.iwd.DeviceProvisioning' IWD_AGENT_MANAGER_PATH = '/net/connman/iwd' IWD_TOP_LEVEL_PATH = '/' @@ -231,8 +232,6 @@ class StationDebug(IWDDBusAbstract): _iface_name = IWD_STATION_DEBUG_INTERFACE def __init__(self, *args, **kwargs): - self._debug_props = None - self._debug_iface = None self._last_event = None self._last_event_data = [] @@ -272,6 +271,20 @@ class StationDebug(IWDDBusAbstract): self._last_event_data = None self._last_event = None +class DeviceProvisioning(IWDDBusAbstract): + ''' + Class represents net.connman.iwd.DeviceProvisioning + ''' + _iface_name = IWD_DPP_INTERFACE + + def start_enrollee(self): + return self._iface.StartEnrollee() + + def start_configurator(self): + return self._iface.StartConfigurator() + + def stop(self): + self._iface.Stop() class Device(IWDDBusAbstract): ''' @@ -284,11 +297,11 @@ class Device(IWDDBusAbstract): self._wps_manager_if = None self._station_if = None self._station_props = None + self._station_debug_obj = None + self._dpp_obj = None IWDDBusAbstract.__init__(self, *args, **kwargs) - self._station_debug = StationDebug(*args, **kwargs) - @property def _wps_manager(self): if self._wps_manager_if is None: @@ -306,6 +319,28 @@ class Device(IWDDBusAbstract): IWD_STATION_INTERFACE) return self._station_if + @property + def _device_provisioning(self): + if self._properties['Mode'] != 'station': + self._prop_proxy.Set(IWD_DEVICE_INTERFACE, 'Mode', 'station') + + if self._dpp_obj is None: + self._dpp_obj = DeviceProvisioning(object_path=self._object_path, + namespace=self._namespace) + + return self._dpp_obj + + @property + def _station_debug(self): + if self._properties['Mode'] != 'station': + self._prop_proxy.Set(IWD_DEVICE_INTERFACE, 'Mode', 'station') + + if self._station_debug_obj is None: + self._station_debug_obj = StationDebug(object_path=self._object_path, + namespace=self._namespace) + + return self._station_debug_obj + def _station_properties(self): if self._station_props is not None: return self._station_props @@ -332,6 +367,9 @@ class Device(IWDDBusAbstract): for name, value in changed.items(): self._station_props[name] = value + if name == 'Mode' and value != 'station': + self._station_debug_obj = None + @property def device_path(self): ''' @@ -626,6 +664,15 @@ class Device(IWDDBusAbstract): def wait_for_event(self, event, timeout=10): self._station_debug.wait_for_event(event, timeout) + def dpp_start_enrollee(self): + return self._device_provisioning.start_enrollee() + + def dpp_start_configurator(self): + return self._device_provisioning.start_configurator() + + def dpp_stop(self): + return self._device_provisioning.stop() + def __str__(self, prefix = ''): return prefix + 'Device: ' + self.device_path + '\n'\ + prefix + '\tName:\t\t' + self.name + '\n'\ @@ -663,7 +710,7 @@ class Network(IWDDBusAbstract): Connect to the network. Request the device implied by the object path to connect to specified network. - Possible exception: AbortedEx + Possible exception: AbortedEx BusyEx FailedEx NoAgentEx diff --git a/autotests/util/wpas.py b/autotests/util/wpas.py @@ -3,6 +3,7 @@ import os import socket from gi.repository import GLib from config import ctx +import binascii ctrl_count = 0 @@ -70,13 +71,21 @@ class Wpas: while True: context.iteration(may_block=True) - if event in self._rx_data: - GLib.source_remove(timeout) - return self._rx_data + if not event and len(self._rx_data) >= 1: + return self._rx_data[0] + + 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_result(self, timeout=10): + self._rx_data = [] + return self.wait_for_event(None, timeout=timeout) + def _event_parse(self, line): # Unescape event parameter values in '', other escaping rules not implemented key = None @@ -241,6 +250,31 @@ class Wpas: def set(self, key, value, **kwargs): self._ctrl_request('SET ' + key + ' ' + value, **kwargs) + def dpp_enrollee_start(self, uri=None): + self._ctrl_request('DPP_BOOTSTRAP_GEN type=qrcode') + self.wait_for_result() + + if uri: + self._ctrl_request('DPP_QR_CODE ' + uri) + self._dpp_qr_id = self.wait_for_result() + self._ctrl_request('DPP_AUTH_INIT peer=%s role=enrollee' % self._dpp_qr_id) + + def dpp_configurator_create(self, uri): + self._ctrl_request('DPP_CONFIGURATOR_ADD') + self._dpp_conf_id = self.wait_for_result() + self._ctrl_request('DPP_QR_CODE ' + uri) + 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): + 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') + self.wait_for_event('DPP-CONF-SENT') + # 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/client/dbus-proxy.h b/client/dbus-proxy.h @@ -36,6 +36,7 @@ struct proxy_interface; #define IWD_STATION_DIAGNOSTIC_INTERFACE "net.connman.iwd.StationDiagnostic" #define IWD_AP_DIAGNOSTIC_INTERFACE "net.connman.iwd.AccessPointDiagnostic" #define IWD_DAEMON_INTERFACE "net.connman.iwd.Daemon" +#define IWD_DPP_INTERFACE "net.connman.iwd.DeviceProvisioning" typedef bool (*proxy_property_match_func_t) (const void *a, const void *b); diff --git a/client/dpp.c b/client/dpp.c @@ -0,0 +1,233 @@ +/* + * + * Wireless daemon for Linux + * + * Copyright (C) 2021 Intel Corporation. All rights reserved. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <stdio.h> +#include <linux/limits.h> + +#include <ell/ell.h> + +#include "client/command.h" +#include "client/dbus-proxy.h" +#include "client/device.h" +#include "client/display.h" + +static struct proxy_interface_type dpp_interface_type = { + .interface = IWD_DPP_INTERFACE, +}; + +static void check_errors_method_callback(struct l_dbus_message *message, + void *user_data) +{ + dbus_message_has_error(message); +} + +static void get_uri_method_callback(struct l_dbus_message *message, + void *user_data) +{ + FILE *f; + L_AUTO_FREE_VAR(char *, cmd) = NULL; + char *uri; + char readbuf[PATH_MAX]; + char *s = readbuf; + + if (dbus_message_has_error(message)) + return; + + if (!l_dbus_message_get_arguments(message, "s", &uri)) { + display("Error getting URI"); + return; + } + + display("%s\n\n", uri); + + if (system("which qrencode > /dev/null 2>&1")) + return; + + cmd = l_strdup_printf("qrencode -t UTF8 -o - \"%s\"", uri); + + f = popen(cmd, "r"); + + while ((s = fgets(s, PATH_MAX, f))) + display("%s", s); + + display("\n"); + + pclose(f); +} + +static void display_dpp_inline(const char *margin, const void *data) +{ + const struct proxy_interface *dpp_i = data; + struct proxy_interface *device_i = + proxy_interface_find(IWD_DEVICE_INTERFACE, + proxy_interface_get_path(dpp_i)); + const char *identity; + + if (!device_i) + return; + + identity = proxy_interface_get_identity_str(device_i); + if (!identity) + return; + + display("%s%-*s\n", margin, 20, identity); +} + +static enum cmd_status cmd_list(const char *device_name, char **argv, int argc) +{ + const struct l_queue_entry *entry; + struct l_queue *match = + proxy_interface_find_all(IWD_DPP_INTERFACE, NULL, NULL); + + display_table_header("DPP-capable Devices", MARGIN "%-*s", 20, "Name"); + + if (!match) { + display("No DPP-capable devices available\n"); + display_table_footer(); + + return CMD_STATUS_DONE; + } + + for (entry = l_queue_get_entries(match); entry; entry = entry->next) { + const struct proxy_interface *dpp = entry->data; + display_dpp_inline(MARGIN, dpp); + } + + display_table_footer(); + + l_queue_destroy(match, NULL); + + return CMD_STATUS_DONE; +} + +static enum cmd_status cmd_start_enrollee(const char *device_name, + char **argv, int argc) +{ + const struct proxy_interface *dpp_i; + + dpp_i = device_proxy_find(device_name, IWD_DPP_INTERFACE); + if (!dpp_i) { + display("No dpp on device: '%s'\n", device_name); + return CMD_STATUS_INVALID_VALUE; + } + + proxy_interface_method_call(dpp_i, "StartEnrollee", "", + get_uri_method_callback); + + return CMD_STATUS_TRIGGERED; +} + +static enum cmd_status cmd_start_configurator(const char *device_name, + char **argv, int argc) +{ + const struct proxy_interface *dpp_i; + + dpp_i = device_proxy_find(device_name, IWD_DPP_INTERFACE); + if (!dpp_i) { + display("No dpp on device: '%s'\n", device_name); + return CMD_STATUS_INVALID_VALUE; + } + + proxy_interface_method_call(dpp_i, "StartConfigurator", "", + get_uri_method_callback); + + return CMD_STATUS_TRIGGERED; +} + +static enum cmd_status cmd_stop(const char *device_name, + char **argv, int argc) +{ + const struct proxy_interface *dpp_i = + device_proxy_find(device_name, IWD_DPP_INTERFACE); + + if (!dpp_i) { + display("No dpp on device: '%s'\n", device_name); + return CMD_STATUS_INVALID_VALUE; + } + + proxy_interface_method_call(dpp_i, "Stop", "", + check_errors_method_callback); + + return CMD_STATUS_TRIGGERED; +} + +static const struct command dpp_commands[] = { + { NULL, "list", NULL, cmd_list, "List DPP-capable devices", true }, + { "<wlan>", "start-enrollee", NULL, cmd_start_enrollee, + "Starts a DPP Enrollee" }, + { "<wlan>", "start-configurator", NULL, cmd_start_configurator, + "Starts a DPP Configurator" }, + { "<wlan>", "stop", NULL, cmd_stop, "Aborts DPP operations" }, + { } +}; + +static char *family_arg_completion(const char *text, int state) +{ + return device_arg_completion(text, state, dpp_commands, + IWD_DPP_INTERFACE); +} + +static char *entity_arg_completion(const char *text, int state) +{ + return command_entity_arg_completion(text, state, dpp_commands); +} + +static struct command_family dpp_command_family = { + .caption = "Device Provisioning", + .name = "dpp", + .command_list = dpp_commands, + .family_arg_completion = family_arg_completion, + .entity_arg_completion = entity_arg_completion, +}; + +static int dpp_command_family_init(void) +{ + command_family_register(&dpp_command_family); + + return 0; +} + +static void dpp_command_family_exit(void) +{ + command_family_unregister(&dpp_command_family); +} + +COMMAND_FAMILY(dpp_command_family, dpp_command_family_init, + dpp_command_family_exit) + +static int dpp_interface_init(void) +{ + proxy_interface_type_register(&dpp_interface_type); + + return 0; +} + +static void dpp_interface_exit(void) +{ + proxy_interface_type_unregister(&dpp_interface_type); +} + +INTERFACE_TYPE(dpp_interface_type, dpp_interface_init, dpp_interface_exit) diff --git a/configure.ac b/configure.ac @@ -1,5 +1,5 @@ AC_PREREQ(2.60) -AC_INIT(iwd, 1.20) +AC_INIT(iwd, 1.21) 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.46" + ell_min_version="0.47" else ell_min_version="0.5" fi diff --git a/doc/device-provisioning.txt b/doc/device-provisioning.txt @@ -0,0 +1,39 @@ +Device Provisioning hierarchy +============================= + +Service net.connman.iwd +Interface net.connman.iwd.DeviceProvisioning [Experimental] +Object path /net/connman/iwd/{phy0,phy1,...}/{1,2,...} + +Methods string StartEnrollee() + + Start a DPP enrollee. Currently only station devices are + supported. + + Returns the enrollees URI + + Possible errors: net.connman.iwd.InvalidArguments + net.connman.iwd.AlreadyExists + net.connman.iwd.NotAvailable + + void Stop() + + Stop an enrollee. + + Possible errors: net.connman.iwd.Busy + net.connman.iwd.Failed + net.connman.iwd.InvalidArguments + + string StartConfigurator() + + Start a DPP configurator. Currently only connected + station devices are supported, and will only configure + the enrollee to the currently connected network. + + Returns the configurator URI + + Possible errors: net.connman.iwd.NotAvailable + net.connman.iwd.NotConnected + net.connman.iwd.NotConfigured + net.connman.iwd.NotSupported + net.connman.iwd.Busy diff --git a/doc/main.conf b/doc/main.conf @@ -0,0 +1,44 @@ +# For complete description of supported configuration options, refer to +# 'man 5 iwd.config'. + +[General] +# iwd is capable of performing network configuration on its own, including +# DHCPv4 based address configuration. By default this behavior is +# disabled, and an external service such as NetworkManager, systemd-network +# or dhcpclient is required. Uncomment the following line if you want iwd +# to manage network interface configuration. +# +#EnableNetworkConfiguration=true +# +# iwd can randomize your WiFi card's MAC address for additional privacy. By +# default, this behavior is disabled and the MAC address assigned by the +# kernel driver is used. The address will be stable when connecting +# to a saved network profile, so as to not interfere with any MAC filtering +# rules that exist on the network. +# If a randomized MAC address is desired, uncomment the setting line below: +# +#AddressRandomization=network +# +# Options below control the roaming thresholds on 2.4 & 5G bands. +# Normally the default values are a good compromise that avoids excessive +# scanning while maintaining good link quality. +# +#RoamThreshold=-70 +#RoamThreshold5G=-76 +# +[Network] +# If EnableNetworkConfiguration=true is set, iwd forwards DNS information to +# the system resolving service. The currently supported services are: +# - systemd-resolved ["systemd"] +# - openresolv / resolvconf ["resolvconf"] +# +# If not set, the value "systemd" is used by default. Uncomment the value +# below if you are using openresolv: +# +#NameResolvingService=resolvconf +# +# iwd's support for IPv6 is still experimental and is disabled by default. +# If you want to try it anyway, uncomment the setting below. Note that +# configuration via SLAAC is currently not supported (DHCPv6 only). +# +#EnableIPv6=true diff --git a/shared/jsmn.h b/shared/jsmn.h @@ -0,0 +1,468 @@ +/* + * MIT License + * + * Copyright (c) 2010 Serge Zaitsev + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#ifndef JSMN_H +#define JSMN_H + +#include <stddef.h> + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef JSMN_STATIC +#define JSMN_API static +#else +#define JSMN_API extern +#endif + +/** + * JSON type identifier. Basic types are: + * o Object + * o Array + * o String + * o Other primitive: number, boolean (true/false) or null + */ +typedef enum { + JSMN_UNDEFINED = 0, + JSMN_OBJECT = 1, + JSMN_ARRAY = 2, + JSMN_STRING = 3, + JSMN_PRIMITIVE = 4 +} jsmntype_t; + +enum jsmnerr { + /* Not enough tokens were provided */ + JSMN_ERROR_NOMEM = -1, + /* Invalid character inside JSON string */ + JSMN_ERROR_INVAL = -2, + /* The string is not a full JSON packet, more bytes expected */ + JSMN_ERROR_PART = -3 +}; + +/** + * JSON token description. + * type type (object, array, string etc.) + * start start position in JSON data string + * end end position in JSON data string + */ +typedef struct { + jsmntype_t type; + int start; + int end; + int size; +#ifdef JSMN_PARENT_LINKS + int parent; +#endif +} jsmntok_t; + +/** + * JSON parser. Contains an array of token blocks available. Also stores + * the string being parsed now and current position in that string. + */ +typedef struct { + unsigned int pos; /* offset in the JSON string */ + unsigned int toknext; /* next token to allocate */ + int toksuper; /* superior token node, e.g. parent object or array */ +} jsmn_parser; + +/** + * Create JSON parser over an array of tokens + */ +JSMN_API void jsmn_init(jsmn_parser *parser); + +/** + * Run JSON parser. It parses a JSON data string into and array of tokens, each + * describing + * a single JSON object. + */ +JSMN_API int jsmn_parse(jsmn_parser *parser, const char *js, const size_t len, + jsmntok_t *tokens, const unsigned int num_tokens); + +#ifndef JSMN_HEADER +/** + * Allocates a fresh unused token from the token pool. + */ +static jsmntok_t *jsmn_alloc_token(jsmn_parser *parser, jsmntok_t *tokens, + const size_t num_tokens) { + jsmntok_t *tok; + if (parser->toknext >= num_tokens) { + return NULL; + } + tok = &tokens[parser->toknext++]; + tok->start = tok->end = -1; + tok->size = 0; +#ifdef JSMN_PARENT_LINKS + tok->parent = -1; +#endif + return tok; +} + +/** + * Fills token type and boundaries. + */ +static void jsmn_fill_token(jsmntok_t *token, const jsmntype_t type, + const int start, const int end) { + token->type = type; + token->start = start; + token->end = end; + token->size = 0; +} + +/** + * Fills next available token with JSON primitive. + */ +static int jsmn_parse_primitive(jsmn_parser *parser, const char *js, + const size_t len, jsmntok_t *tokens, + const size_t num_tokens) { + jsmntok_t *token; + int start; + + start = parser->pos; + + for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) { + switch (js[parser->pos]) { +#ifndef JSMN_STRICT + /* In strict mode primitive must be followed by "," or "}" or "]" */ + case ':': +#endif + case '\t': + case '\r': + case '\n': + case ' ': + case ',': + case ']': + case '}': + goto found; + } + if (js[parser->pos] < 32 || js[parser->pos] >= 127) { + parser->pos = start; + return JSMN_ERROR_INVAL; + } + } +#ifdef JSMN_STRICT + /* In strict mode primitive must be followed by a comma/object/array */ + parser->pos = start; + return JSMN_ERROR_PART; +#endif + +found: + if (tokens == NULL) { + parser->pos--; + return 0; + } + token = jsmn_alloc_token(parser, tokens, num_tokens); + if (token == NULL) { + parser->pos = start; + return JSMN_ERROR_NOMEM; + } + jsmn_fill_token(token, JSMN_PRIMITIVE, start, parser->pos); +#ifdef JSMN_PARENT_LINKS + token->parent = parser->toksuper; +#endif + parser->pos--; + return 0; +} + +/** + * Fills next token with JSON string. + */ +static int jsmn_parse_string(jsmn_parser *parser, const char *js, + const size_t len, jsmntok_t *tokens, + const size_t num_tokens) { + jsmntok_t *token; + + int start = parser->pos; + + parser->pos++; + + /* Skip starting quote */ + for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) { + char c = js[parser->pos]; + + /* Quote: end of string */ + if (c == '\"') { + if (tokens == NULL) { + return 0; + } + token = jsmn_alloc_token(parser, tokens, num_tokens); + if (token == NULL) { + parser->pos = start; + return JSMN_ERROR_NOMEM; + } + jsmn_fill_token(token, JSMN_STRING, start + 1, parser->pos); +#ifdef JSMN_PARENT_LINKS + token->parent = parser->toksuper; +#endif + return 0; + } + + /* Backslash: Quoted symbol expected */ + if (c == '\\' && parser->pos + 1 < len) { + int i; + parser->pos++; + switch (js[parser->pos]) { + /* Allowed escaped symbols */ + case '\"': + case '/': + case '\\': + case 'b': + case 'f': + case 'r': + case 'n': + case 't': + break; + /* Allows escaped symbol \uXXXX */ + case 'u': + parser->pos++; + for (i = 0; i < 4 && parser->pos < len && js[parser->pos] != '\0'; + i++) { + /* If it isn't a hex character we have an error */ + if (!((js[parser->pos] >= 48 && js[parser->pos] <= 57) || /* 0-9 */ + (js[parser->pos] >= 65 && js[parser->pos] <= 70) || /* A-F */ + (js[parser->pos] >= 97 && js[parser->pos] <= 102))) { /* a-f */ + parser->pos = start; + return JSMN_ERROR_INVAL; + } + parser->pos++; + } + parser->pos--; + break; + /* Unexpected symbol */ + default: + parser->pos = start; + return JSMN_ERROR_INVAL; + } + } + } + parser->pos = start; + return JSMN_ERROR_PART; +} + +/** + * Parse JSON string and fill tokens. + */ +JSMN_API int jsmn_parse(jsmn_parser *parser, const char *js, const size_t len, + jsmntok_t *tokens, const unsigned int num_tokens) { + int r; + int i; + jsmntok_t *token; + int count = parser->toknext; + + for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) { + char c; + jsmntype_t type; + + c = js[parser->pos]; + switch (c) { + case '{': + case '[': + count++; + if (tokens == NULL) { + break; + } + token = jsmn_alloc_token(parser, tokens, num_tokens); + if (token == NULL) { + return JSMN_ERROR_NOMEM; + } + if (parser->toksuper != -1) { + jsmntok_t *t = &tokens[parser->toksuper]; +#ifdef JSMN_STRICT + /* In strict mode an object or array can't become a key */ + if (t->type == JSMN_OBJECT) { + return JSMN_ERROR_INVAL; + } +#endif + t->size++; +#ifdef JSMN_PARENT_LINKS + token->parent = parser->toksuper; +#endif + } + token->type = (c == '{' ? JSMN_OBJECT : JSMN_ARRAY); + token->start = parser->pos; + parser->toksuper = parser->toknext - 1; + break; + case '}': + case ']': + if (tokens == NULL) { + break; + } + type = (c == '}' ? JSMN_OBJECT : JSMN_ARRAY); +#ifdef JSMN_PARENT_LINKS + if (parser->toknext < 1) { + return JSMN_ERROR_INVAL; + } + token = &tokens[parser->toknext - 1]; + for (;;) { + if (token->start != -1 && token->end == -1) { + if (token->type != type) { + return JSMN_ERROR_INVAL; + } + token->end = parser->pos + 1; + parser->toksuper = token->parent; + break; + } + if (token->parent == -1) { + if (token->type != type || parser->toksuper == -1) { + return JSMN_ERROR_INVAL; + } + break; + } + token = &tokens[token->parent]; + } +#else + for (i = parser->toknext - 1; i >= 0; i--) { + token = &tokens[i]; + if (token->start != -1 && token->end == -1) { + if (token->type != type) { + return JSMN_ERROR_INVAL; + } + parser->toksuper = -1; + token->end = parser->pos + 1; + break; + } + } + /* Error if unmatched closing bracket */ + if (i == -1) { + return JSMN_ERROR_INVAL; + } + for (; i >= 0; i--) { + token = &tokens[i]; + if (token->start != -1 && token->end == -1) { + parser->toksuper = i; + break; + } + } +#endif + break; + case '\"': + r = jsmn_parse_string(parser, js, len, tokens, num_tokens); + if (r < 0) { + return r; + } + count++; + if (parser->toksuper != -1 && tokens != NULL) { + tokens[parser->toksuper].size++; + } + break; + case '\t': + case '\r': + case '\n': + case ' ': + break; + case ':': + parser->toksuper = parser->toknext - 1; + break; + case ',': + if (tokens != NULL && parser->toksuper != -1 && + tokens[parser->toksuper].type != JSMN_ARRAY && + tokens[parser->toksuper].type != JSMN_OBJECT) { +#ifdef JSMN_PARENT_LINKS + parser->toksuper = tokens[parser->toksuper].parent; +#else + for (i = parser->toknext - 1; i >= 0; i--) { + if (tokens[i].type == JSMN_ARRAY || tokens[i].type == JSMN_OBJECT) { + if (tokens[i].start != -1 && tokens[i].end == -1) { + parser->toksuper = i; + break; + } + } + } +#endif + } + break; +#ifdef JSMN_STRICT + /* In strict mode primitives are: numbers and booleans */ + case '-': + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case 't': + case 'f': + case 'n': + /* And they must not be keys of the object */ + if (tokens != NULL && parser->toksuper != -1) { + const jsmntok_t *t = &tokens[parser->toksuper]; + if (t->type == JSMN_OBJECT || + (t->type == JSMN_STRING && t->size != 0)) { + return JSMN_ERROR_INVAL; + } + } +#else + /* In non-strict mode every unquoted value is a primitive */ + default: +#endif + r = jsmn_parse_primitive(parser, js, len, tokens, num_tokens); + if (r < 0) { + return r; + } + count++; + if (parser->toksuper != -1 && tokens != NULL) { + tokens[parser->toksuper].size++; + } + break; + +#ifdef JSMN_STRICT + /* Unexpected char in strict mode */ + default: + return JSMN_ERROR_INVAL; +#endif + } + } + + if (tokens != NULL) { + for (i = parser->toknext - 1; i >= 0; i--) { + /* Unmatched opened object or array */ + if (tokens[i].start != -1 && tokens[i].end == -1) { + return JSMN_ERROR_PART; + } + } + } + + return count; +} + +/** + * Creates a new parser based over a given buffer with an array of tokens + * available. + */ +JSMN_API void jsmn_init(jsmn_parser *parser) { + parser->pos = 0; + parser->toknext = 0; + parser->toksuper = -1; +} + +#endif /* JSMN_HEADER */ + +#ifdef __cplusplus +} +#endif + +#endif /* JSMN_H */ diff --git a/src/ap.c b/src/ap.c @@ -57,6 +57,7 @@ #include "src/ap.h" #include "src/storage.h" #include "src/diagnostic.h" +#include "src/band.h" struct ap_state { struct netdev *netdev; @@ -895,7 +896,7 @@ static uint32_t ap_send_mgmt_frame(struct ap_state *ap, frame_xchg_cb_t callback, void *user_data) { - uint32_t ch_freq = scan_channel_to_freq(ap->channel, SCAN_BAND_2_4_GHZ); + uint32_t ch_freq = band_channel_to_freq(ap->channel, BAND_FREQ_2_4_GHZ); uint64_t wdev_id = netdev_get_wdev_id(ap->netdev); struct iovec iov[2]; @@ -2318,7 +2319,7 @@ static struct l_genl_msg *ap_build_cmd_start_ap(struct ap_state *ap) uint32_t nl_akm = CRYPTO_AKM_PSK; uint32_t wpa_version = NL80211_WPA_VERSION_2; uint32_t auth_type = NL80211_AUTHTYPE_OPEN_SYSTEM; - uint32_t ch_freq = scan_channel_to_freq(ap->channel, SCAN_BAND_2_4_GHZ); + uint32_t ch_freq = band_channel_to_freq(ap->channel, BAND_FREQ_2_4_GHZ); uint32_t ch_width = NL80211_CHAN_WIDTH_20; unsigned int i; @@ -3066,8 +3067,8 @@ static int ap_load_config(struct ap_state *ap, const struct l_settings *config, if (!l_settings_get_uint(config, "General", "Channel", &uintval) || - !scan_channel_to_freq(uintval, - SCAN_BAND_2_4_GHZ)) { + !band_channel_to_freq(uintval, + BAND_FREQ_2_4_GHZ)) { l_error("AP Channel value unsupported"); return -EINVAL; } diff --git a/src/band.c b/src/band.c @@ -923,3 +923,196 @@ int oci_from_chandef(const struct band_chandef *own, uint8_t oci[static 3]) return -ENOENT; } + +uint8_t band_freq_to_channel(uint32_t freq, enum band_freq *out_band) +{ + uint32_t channel = 0; + + if (freq >= 2412 && freq <= 2484) { + if (freq == 2484) + channel = 14; + else { + channel = freq - 2407; + + if (channel % 5) + return 0; + + channel /= 5; + } + + if (out_band) + *out_band = BAND_FREQ_2_4_GHZ; + + return channel; + } + + if (freq >= 5005 && freq < 5900) { + if (freq % 5) + return 0; + + channel = (freq - 5000) / 5; + + if (out_band) + *out_band = BAND_FREQ_5_GHZ; + + return channel; + } + + if (freq >= 4905 && freq < 5000) { + if (freq % 5) + return 0; + + channel = (freq - 4000) / 5; + + if (out_band) + *out_band = BAND_FREQ_5_GHZ; + + return channel; + } + + return 0; +} + +uint32_t band_channel_to_freq(uint8_t channel, enum band_freq band) +{ + if (band == BAND_FREQ_2_4_GHZ) { + if (channel >= 1 && channel <= 13) + return 2407 + 5 * channel; + + if (channel == 14) + return 2484; + } + + if (band == BAND_FREQ_5_GHZ) { + if (channel >= 1 && channel <= 179) + return 5000 + 5 * channel; + + if (channel >= 181 && channel <= 199) + return 4000 + 5 * channel; + } + + return 0; +} + +static const char *const oper_class_us_codes[] = { + "US", "CA" +}; + +static const char *const oper_class_eu_codes[] = { + "AL", "AM", "AT", "AZ", "BA", "BE", "BG", "BY", "CH", "CY", "CZ", "DE", + "DK", "EE", "EL", "ES", "FI", "FR", "GE", "HR", "HU", "IE", "IS", "IT", + "LI", "LT", "LU", "LV", "MD", "ME", "MK", "MT", "NL", "NO", "PL", "PT", + "RO", "RS", "RU", "SE", "SI", "SK", "TR", "UA", "UK" +}; + +/* Annex E, table E-1 */ +static const uint8_t oper_class_us_to_global[] = { + [1] = 115, [2] = 118, [3] = 124, [4] = 121, + [5] = 125, [6] = 103, [7] = 103, [8] = 102, + [9] = 102, [10] = 101, [11] = 101, [12] = 81, + [13] = 94, [14] = 95, [15] = 96, [22] = 116, + [23] = 119, [24] = 122, [25] = 126, [26] = 126, + [27] = 117, [28] = 120, [29] = 123, [30] = 127, + [31] = 127, [32] = 83, [33] = 84, [34] = 180, + /* 128 - 130 is a 1 to 1 mapping */ +}; + +/* Annex E, table E-2 */ +static const uint8_t oper_class_eu_to_global[] = { + [1] = 115, [2] = 118, [3] = 121, [4] = 81, + [5] = 116, [6] = 119, [7] = 122, [8] = 117, + [9] = 120, [10] = 123, [11] = 83, [12] = 84, + [17] = 125, [18] = 130, + /* 128 - 130 is a 1 to 1 mapping */ +}; + +/* Annex E, table E-3 */ +static const uint8_t oper_class_jp_to_global[] = { + [1] = 115, [2] = 112, [3] = 112, [4] = 112, + [5] = 112, [6] = 112, [7] = 109, [8] = 109, + [9] = 109, [10] = 109, [11] = 109, [12] = 113, + [13] = 113, [14] = 113, [15] = 113, [16] = 110, + [17] = 110, [18] = 110, [19] = 110, [20] = 110, + [21] = 114, [22] = 114, [23] = 114, [24] = 114, + [25] = 111, [26] = 111, [27] = 111, [28] = 111, + [29] = 111, [30] = 81, [31] = 82, [32] = 118, + [33] = 118, [34] = 121, [35] = 121, [36] = 116, + [37] = 119, [38] = 119, [39] = 122, [40] = 122, + [41] = 117, [42] = 120, [43] = 120, [44] = 123, + [45] = 123, [46] = 104, [47] = 104, [48] = 104, + [49] = 104, [50] = 104, [51] = 105, [52] = 105, + [53] = 105, [54] = 105, [55] = 105, [56] = 83, + [57] = 84, [58] = 121, [59] = 180, + /* 128 - 130 is a 1 to 1 mapping */ +}; + +/* Annex E, table E-4 (only 2.4GHz and 4.9 / 5GHz bands) */ +static const enum band_freq oper_class_to_band_global[] = { + [81 ... 84] = BAND_FREQ_2_4_GHZ, + [104 ... 130] = BAND_FREQ_5_GHZ, +}; + +/* Annex E, table E-5 */ +static const uint8_t oper_class_cn_to_global[] = { + [1] = 115, [2] = 118, [3] = 125, [4] = 116, + [5] = 119, [6] = 126, [7] = 81, [8] = 83, + [9] = 84, + /* 128 - 130 is a 1 to 1 mapping */ +}; + +enum band_freq band_oper_class_to_band(const uint8_t *country, + uint8_t oper_class) +{ + unsigned int i; + int table = 0; + + if (country && country[2] >= 1 && country[2] <= 5) + table = country[2]; + else if (country) { + for (i = 0; i < L_ARRAY_SIZE(oper_class_us_codes); i++) + if (!memcmp(oper_class_us_codes[i], country, 2)) { + /* Use table E-1 */ + table = 1; + break; + } + + for (i = 0; i < L_ARRAY_SIZE(oper_class_eu_codes); i++) + if (!memcmp(oper_class_eu_codes[i], country, 2)) { + /* Use table E-2 */ + table = 2; + break; + } + + if (!memcmp("JP", country, 2)) + /* Use table E-3 */ + table = 3; + + if (!memcmp("CN", country, 2)) + /* Use table E-5 */ + table = 5; + } + + switch (table) { + case 1: + if (oper_class < L_ARRAY_SIZE(oper_class_us_to_global)) + oper_class = oper_class_us_to_global[oper_class]; + break; + case 2: + if (oper_class < L_ARRAY_SIZE(oper_class_eu_to_global)) + oper_class = oper_class_eu_to_global[oper_class]; + break; + case 3: + if (oper_class < L_ARRAY_SIZE(oper_class_jp_to_global)) + oper_class = oper_class_jp_to_global[oper_class]; + break; + case 5: + if (oper_class < L_ARRAY_SIZE(oper_class_cn_to_global)) + oper_class = oper_class_cn_to_global[oper_class]; + break; + } + + if (oper_class < L_ARRAY_SIZE(oper_class_to_band_global)) + return oper_class_to_band_global[oper_class]; + else + return 0; +} diff --git a/src/band.h b/src/band.h @@ -36,6 +36,11 @@ enum band_chandef_width { BAND_CHANDEF_WIDTH_160, }; +enum band_freq { + BAND_FREQ_2_4_GHZ = 0x1, + BAND_FREQ_5_GHZ = 0x2, +}; + struct band_chandef { uint32_t frequency; uint32_t channel_width; @@ -76,3 +81,8 @@ int oci_to_frequency(uint32_t operating_class, uint32_t channel); int oci_verify(const uint8_t oci[static 3], const struct band_chandef *own); int oci_from_chandef(const struct band_chandef *own, uint8_t oci[static 3]); + +uint8_t band_freq_to_channel(uint32_t freq, enum band_freq *out_band); +uint32_t band_channel_to_freq(uint8_t channel, enum band_freq band); +enum band_freq band_oper_class_to_band(const uint8_t *country, + uint8_t oper_class); diff --git a/src/crypto.c b/src/crypto.c @@ -321,16 +321,18 @@ static bool s2v(struct l_checksum *cmac, struct iovec *iov, size_t iov_len, /* * RFC 5297 Section 2.6 - SIV Encrypt */ -bool aes_siv_encrypt(const uint8_t *key, size_t key_len, const uint8_t *in, +bool aes_siv_encrypt(const void *key, size_t key_len, const void *in, size_t in_len, struct iovec *ad, size_t num_ad, - uint8_t *out) + void *out) { struct l_checksum *cmac; struct l_cipher *ctr; struct iovec iov[num_ad + 1]; uint8_t v[16]; - memcpy(iov, ad, sizeof(struct iovec) * num_ad); + if (ad) + memcpy(iov, ad, sizeof(struct iovec) * num_ad); + iov[num_ad].iov_base = (void *)in; iov[num_ad].iov_len = in_len; num_ad++; @@ -374,9 +376,9 @@ free_ctr: return false; } -bool aes_siv_decrypt(const uint8_t *key, size_t key_len, const uint8_t *in, +bool aes_siv_decrypt(const void *key, size_t key_len, const void *in, size_t in_len, struct iovec *ad, size_t num_ad, - uint8_t *out) + void *out) { struct l_checksum *cmac; struct l_cipher *ctr; @@ -387,7 +389,9 @@ bool aes_siv_decrypt(const uint8_t *key, size_t key_len, const uint8_t *in, if (in_len < 16) return false; - memcpy(iov, ad, sizeof(struct iovec) * num_ad); + if (ad) + memcpy(iov, ad, sizeof(struct iovec) * num_ad); + iov[num_ad].iov_base = (void *)out; iov[num_ad].iov_len = in_len - 16; num_ad++; @@ -860,7 +864,7 @@ bool hkdf_extract(enum l_checksum_type type, const void *key, return (ret == (int) dlen); } -bool hkdf_expand(enum l_checksum_type type, const uint8_t *key, size_t key_len, +bool hkdf_expand(enum l_checksum_type type, const void *key, size_t key_len, const char *info, void *out, size_t out_len) { return prf_plus(type, key, key_len, info, out, out_len, 0); diff --git a/src/crypto.h b/src/crypto.h @@ -83,12 +83,12 @@ bool aes_wrap(const uint8_t *kek, const uint8_t *in, size_t len, uint8_t *out); bool arc4_skip(const uint8_t *key, size_t key_len, size_t skip, const uint8_t *in, size_t len, uint8_t *out); -bool aes_siv_encrypt(const uint8_t *key, size_t key_len, const uint8_t *in, +bool aes_siv_encrypt(const void *key, size_t key_len, const void *in, size_t in_len, struct iovec *ad, size_t num_ad, - uint8_t *out); -bool aes_siv_decrypt(const uint8_t *key, size_t key_len, const uint8_t *in, + void *out); +bool aes_siv_decrypt(const void *key, size_t key_len, const void *in, size_t in_len, struct iovec *ad, size_t num_ad, - uint8_t *out); + void *out); int crypto_cipher_key_len(enum crypto_cipher cipher); int crypto_cipher_tk_bits(enum crypto_cipher cipher); @@ -122,7 +122,7 @@ bool prf_plus(enum l_checksum_type type, const void *key, size_t key_len, bool hkdf_extract(enum l_checksum_type type, const void *key, size_t key_len, uint8_t num_args, void *out, ...); -bool hkdf_expand(enum l_checksum_type type, const uint8_t *key, size_t key_len, +bool hkdf_expand(enum l_checksum_type type, const void *key, size_t key_len, const char *info, void *out, size_t out_len); bool crypto_derive_pairwise_ptk(const uint8_t *pmk, size_t pmk_len, diff --git a/src/dbus.h b/src/dbus.h @@ -43,6 +43,7 @@ #define IWD_STATION_DIAGNOSTIC_INTERFACE "net.connman.iwd.StationDiagnostic" #define IWD_AP_DIAGNOSTIC_INTERFACE "net.connman.iwd.AccessPointDiagnostic" #define IWD_STATION_DEBUG_INTERFACE "net.connman.iwd.StationDebug" +#define IWD_DPP_INTERFACE "net.connman.iwd.DeviceProvisioning" #define IWD_BASE_PATH "/net/connman/iwd" #define IWD_AGENT_MANAGER_PATH IWD_BASE_PATH diff --git a/src/dpp-util.c b/src/dpp-util.c @@ -0,0 +1,785 @@ +/* + * + * Wireless daemon for Linux + * + * Copyright (C) 2021 Intel Corporation. All rights reserved. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <stdio.h> + +#include <errno.h> + +#include <ell/ell.h> + +#include "src/dpp-util.h" +#include "src/util.h" +#include "src/band.h" +#include "src/crypto.h" +#include "src/json.h" +#include "ell/useful.h" +#include "src/ie.h" + +static void append_freqs(struct l_string *uri, + const uint32_t *freqs, size_t len) +{ + size_t i; + enum band_freq band; + + l_string_append_printf(uri, "C:"); + + for (i = 0; i < len; i++) { + uint8_t oper_class; + uint8_t channel = band_freq_to_channel(freqs[i], &band); + + /* For now use global operating classes */ + if (band == BAND_FREQ_2_4_GHZ) + oper_class = 81; + else + oper_class = 115; + + l_string_append_printf(uri, "%u/%u", oper_class, channel); + + if (i != len - 1) + l_string_append_c(uri, ','); + } + + l_string_append_c(uri, ';'); +} + +char *dpp_generate_uri(const uint8_t *asn1, size_t asn1_len, uint8_t version, + const uint8_t *mac, const uint32_t *freqs, + size_t freqs_len, const char *info, const char *host) +{ + struct l_string *uri = l_string_new(256); + char *base64; + + base64 = l_base64_encode(asn1, asn1_len, 0); + + l_string_append_printf(uri, "DPP:K:%s;", base64); + l_free(base64); + + if (mac) + l_string_append_printf(uri, "M:%02x%02x%02x%02x%02x%02x;", + MAC_STR(mac)); + + if (freqs) + append_freqs(uri, freqs, freqs_len); + + if (info) + l_string_append_printf(uri, "I:%s;", info); + + if (host) + l_string_append_printf(uri, "H:%s;", host); + + if (version) + l_string_append_printf(uri, "V:%u;", version); + + l_string_append_c(uri, ';'); + + return l_string_unwrap(uri); +} + +static uint32_t dpp_parse_akm(char *akms) +{ + _auto_(l_strv_free) char **split = l_strsplit(akms, '+'); + char **i = split; + uint32_t akm_out = 0; + + while (*i) { + if (!strncmp(*i, "psk", 3)) + akm_out |= IE_RSN_AKM_SUITE_PSK; + else if (!strncmp(*i, "sae", 3)) + akm_out |= IE_RSN_AKM_SUITE_SAE_SHA256; + + i++; + } + + return akm_out; +} + +/* + * TODO: This handles the most basic configuration. i.e. a configuration object + * with ssid/passphrase/akm. + */ +struct dpp_configuration *dpp_parse_configuration_object(const char *json, + size_t json_len) +{ + struct dpp_configuration *config; + struct json_contents *c; + struct json_iter iter; + struct json_iter discovery; + struct json_iter cred; + _auto_(l_free) char *tech = NULL; + _auto_(l_free) char *ssid = NULL; + _auto_(l_free) char *akm = NULL; + _auto_(l_free) char *pass = NULL; + _auto_(l_free) char *psk = NULL; + + c = json_contents_new(json, json_len); + if (!c) + return NULL; + + json_iter_init(&iter, c); + + if (!json_iter_parse(&iter, + JSON_MANDATORY("wi-fi_tech", JSON_STRING, &tech), + JSON_MANDATORY("discovery", JSON_OBJECT, &discovery), + JSON_MANDATORY("cred", JSON_OBJECT, &cred), + JSON_UNDEFINED)) + goto free_contents; + + if (!tech || strncmp(tech, "infra", 5)) + goto free_contents; + + if (!json_iter_parse(&discovery, + JSON_MANDATORY("ssid", JSON_STRING, &ssid), + JSON_UNDEFINED)) + goto free_contents; + + if (!ssid || !util_ssid_is_utf8(strlen(ssid),(const uint8_t *)ssid)) + goto free_contents; + + if (!json_iter_parse(&cred, + JSON_MANDATORY("akm", JSON_STRING, &akm), + JSON_OPTIONAL("pass", JSON_STRING, &pass), + JSON_OPTIONAL("psk", JSON_STRING, &psk), + JSON_UNDEFINED)) + goto free_contents; + + if (!pass && (!psk || strlen(psk) != 64)) + goto free_contents; + + config = l_new(struct dpp_configuration, 1); + + if (pass) + config->passphrase = l_steal_ptr(pass); + else + config->psk = l_steal_ptr(psk); + + memcpy(config->ssid, ssid, strlen(ssid)); + config->ssid_len = strlen(ssid); + + config->akm_suites = dpp_parse_akm(akm); + if (!config->akm_suites) + goto free_config; + + json_contents_free(c); + + return config; + +free_config: + dpp_configuration_free(config); +free_contents: + json_contents_free(c); + return NULL; +} + +/* + * The DPP spec does not specify a difference between FT AKMs and their normal + * counterpart. Because of this any FT AKM will just result in the standard + * 'psk' or 'sae' AKM. + */ +static const char *dpp_akm_to_string(enum ie_rsn_akm_suite akm_suite) +{ + switch (akm_suite) { + case IE_RSN_AKM_SUITE_PSK: + case IE_RSN_AKM_SUITE_FT_USING_PSK: + case IE_RSN_AKM_SUITE_PSK_SHA256: + return "psk"; + case IE_RSN_AKM_SUITE_SAE_SHA256: + case IE_RSN_AKM_SUITE_FT_OVER_SAE_SHA256: + return "sae"; + default: + return NULL; + } +} + +char *dpp_configuration_to_json(struct dpp_configuration *config) +{ + _auto_(l_free) char *pass_or_psk; + _auto_(l_free) char *ssid; + + ssid = l_malloc(config->ssid_len + 1); + memcpy(ssid, config->ssid, config->ssid_len); + ssid[config->ssid_len] = '\0'; + + if (config->passphrase) + pass_or_psk = l_strdup_printf("\"pass\":\"%s\"", + config->passphrase); + else + pass_or_psk = l_strdup_printf("\"psk\":\"%s\"", + config->psk); + + return l_strdup_printf("{\"wi-fi_tech\":\"infra\"," + "\"discovery\":{\"ssid\":\"%s\"}," + "\"cred\":{\"akm\":\"%s\",%s}}", + ssid, dpp_akm_to_string(config->akm_suites), + pass_or_psk); +} + +struct dpp_configuration *dpp_configuration_new( + const struct l_settings *settings, + const char *ssid, + enum ie_rsn_akm_suite akm_suite) +{ + struct dpp_configuration *config; + _auto_(l_free) char *passphrase = NULL; + _auto_(l_free) char *psk = NULL; + size_t ssid_len = strlen(ssid); + + if (!l_settings_has_group(settings, "Security")) + return NULL; + + passphrase = l_settings_get_string(settings, "Security", "Passphrase"); + if (!passphrase) { + psk = l_settings_get_string(settings, "Security", + "PreSharedKey"); + if (!psk) + return NULL; + } + + config = l_new(struct dpp_configuration, 1); + + memcpy(config->ssid, ssid, ssid_len); + config->ssid[ssid_len] = '\0'; + config->ssid_len = ssid_len; + + if (passphrase) + config->passphrase = l_steal_ptr(passphrase); + else + config->psk = l_steal_ptr(psk); + + + config->akm_suites = akm_suite; + + return config; +} + +void dpp_configuration_free(struct dpp_configuration *config) +{ + if (config->passphrase) + l_free(config->passphrase); + + if (config->psk) + l_free(config->psk); + + l_free(config); +} + +void dpp_attr_iter_init(struct dpp_attr_iter *iter, const uint8_t *pdu, + size_t len) +{ + iter->pos = pdu; + iter->end = pdu + len; +} + +bool dpp_attr_iter_next(struct dpp_attr_iter *iter, + enum dpp_attribute_type *type_out, size_t *len_out, + const uint8_t **data_out) +{ + enum dpp_attribute_type type; + size_t len; + + if (iter->pos + 4 > iter->end) + return false; + + type = l_get_le16(iter->pos); + len = l_get_le16(iter->pos + 2); + + iter->pos += 4; + + if (iter->pos + len > iter->end) + return false; + + *type_out = type; + *len_out = len; + *data_out = iter->pos; + + iter->pos += len; + + return true; +} + +size_t dpp_append_attr(uint8_t *to, enum dpp_attribute_type type, + void *attr, size_t attr_len) +{ + l_put_le16(type, to); + l_put_le16(attr_len, to + 2); + memcpy(to + 4, attr, attr_len); + + return attr_len + 4; +} + +/* + * The use of ad0/ad1 differs with different protocol frame types, which is why + * this is left up to the caller to pass the correct AD bytes. The usage is + * defined in: + * + * 6.3.1.4 Protocol Conventions (for authentication) + * 6.4.1 Overview (for configuration) + * + */ +uint8_t *dpp_unwrap_attr(const void *ad0, size_t ad0_len, const void *ad1, + size_t ad1_len, const void *key, size_t key_len, + const void *wrapped, size_t wrapped_len, + size_t *unwrapped_len) +{ + struct iovec ad[2]; + uint8_t *unwrapped; + size_t ad_size = 0; + + if (ad0) { + ad[ad_size].iov_base = (void *) ad0; + ad[ad_size].iov_len = ad0_len; + ad_size++; + } + + if (ad1) { + ad[ad_size].iov_base = (void *) ad1; + ad[ad_size].iov_len = ad1_len; + ad_size++; + } + + unwrapped = l_malloc(wrapped_len - 16); + + if (!aes_siv_decrypt(key, key_len, wrapped, wrapped_len, ad, ad_size, + unwrapped)) { + l_free(unwrapped); + return NULL; + } + + *unwrapped_len = wrapped_len - 16; + + return unwrapped; +} + +/* + * Encrypt DPP attributes encapsulated in DPP wrapped data. + * + * ad0/ad0_len - frame specific AD0 component + * ad1/ad0_len - frame specific AD1 component + * to - buffer to encrypt data. + * to_len - size of 'to' + * key - key used to encrypt + * key_len - size of 'key' + * num_attrs - number of attributes listed (type, length, data triplets) + * ... - List of attributes, Type, Length, and data + */ +size_t dpp_append_wrapped_data(const void *ad0, size_t ad0_len, + const void *ad1, size_t ad1_len, + uint8_t *to, size_t to_len, + const void *key, size_t key_len, + size_t num_attrs, ...) +{ + size_t i; + size_t attrs_len = 0; + _auto_(l_free) uint8_t *plaintext = NULL; + uint8_t *ptr; + struct iovec ad[2]; + size_t ad_size = 0; + va_list va; + + va_start(va, num_attrs); + + /* Count up total attributes length */ + for (i = 0; i < num_attrs; i++) { + va_arg(va, enum dpp_attribute_type); + attrs_len += va_arg(va, size_t) + 4; + va_arg(va, void*); + } + + if (to_len < attrs_len + 4 + 16) + return false; + + plaintext = l_malloc(attrs_len); + + ptr = plaintext; + + va_end(va); + + va_start(va, num_attrs); + + /* Build up plaintext attributes */ + for (i = 0; i < num_attrs; i++) { + enum dpp_attribute_type type = va_arg(va, + enum dpp_attribute_type); + size_t l = va_arg(va, size_t); + void *p = va_arg(va, void *); + + l_put_le16(type, ptr); + ptr += 2; + l_put_le16(l, ptr); + ptr += 2; + memcpy(ptr, p, l); + ptr += l; + } + + va_end(va); + + ptr = to; + + l_put_le16(DPP_ATTR_WRAPPED_DATA, ptr); + ptr += 2; + l_put_le16(attrs_len + 16, ptr); + ptr += 2; + + if (ad0) { + ad[ad_size].iov_base = (void *) ad0; + ad[ad_size].iov_len = ad0_len; + ad_size++; + } + + if (ad1) { + ad[ad_size].iov_base = (void *) ad1; + ad[ad_size].iov_len = ad1_len; + ad_size++; + } + + if (!aes_siv_encrypt(key, key_len, plaintext, attrs_len, + ad, ad_size, ptr)) + return 0; + + return attrs_len + 4 + 16; +} + +/* + * EasyConnect 2.0 Table 3. Key and Nonce Length Dependency on Prime Length + */ +static enum l_checksum_type dpp_sha_from_key_len(size_t len) +{ + if (len == 32) + return L_CHECKSUM_SHA256; + else if (len == 48) + return L_CHECKSUM_SHA384; + else if (len == 64) + return L_CHECKSUM_SHA512; + else + return L_CHECKSUM_NONE; + +} + +size_t dpp_nonce_len_from_key_len(size_t len) +{ + if (len == 32) + return 16; + else if (len == 48) + return 24; + else if (len == 64) + return 32; + else + return 0; +} + +/* + * 3.2.2 + * H() + */ +bool dpp_hash(enum l_checksum_type type, uint8_t *out, unsigned int num, ...) +{ + struct l_checksum *sha = l_checksum_new(type); + size_t hsize = l_checksum_digest_length(type); + unsigned int i; + + va_list va; + + va_start(va, num); + + for (i = 0; i < num; i++) { + void *data = va_arg(va, void *); + size_t len = va_arg(va, size_t); + + l_checksum_update(sha, data, len); + } + + va_end(va); + + l_checksum_get_digest(sha, out, hsize); + l_checksum_free(sha); + + return true; +} + +/* + * 3.2.2 + * + * HKDF is defined as: + * + * key = HKDF(salt, info, ikm) + * = HKDF-Expand(HKDF-Extract(salt, ikm), info, len) + * + * Note: A NULL 'salt' means a zero'ed buffer and 'salt_len' should still be + * set for this zero'ed buffer length. + */ +static bool dpp_hkdf(enum l_checksum_type sha, const void *salt, + size_t salt_len, const char *info, const void *ikm, + size_t ikm_len, void *out, size_t out_len) +{ + uint8_t tmp[64]; + uint8_t zero_salt[64] = { 0 }; + size_t hash_len = l_checksum_digest_length(sha); + + if (!salt) + salt = zero_salt; + + if (!hkdf_extract(sha, salt, salt_len, 1, tmp, + ikm, ikm_len)) + return false; + + return hkdf_expand(sha, tmp, hash_len, info, out, out_len); +} + +bool dpp_derive_r_auth(const void *i_nonce, const void *r_nonce, + size_t nonce_len, struct l_ecc_point *i_proto, + struct l_ecc_point *r_proto, + struct l_ecc_point *r_boot, + void *r_auth) +{ + uint64_t pix[L_ECC_MAX_DIGITS]; + uint64_t prx[L_ECC_MAX_DIGITS]; + uint64_t brx[L_ECC_MAX_DIGITS]; + size_t keys_len; + uint8_t zero = 0; + enum l_checksum_type type; + + keys_len = l_ecc_point_get_x(i_proto, pix, sizeof(pix)); + l_ecc_point_get_x(r_proto, prx, sizeof(prx)); + l_ecc_point_get_x(r_boot, brx, sizeof(brx)); + + type = dpp_sha_from_key_len(keys_len); + + /* + * R-auth = H(I-nonce | R-nonce | PI.x | PR.x | [ BI.x | ] BR.x | 0) + */ + return dpp_hash(type, r_auth, 6, i_nonce, nonce_len, r_nonce, nonce_len, + pix, keys_len, prx, keys_len, brx, keys_len, &zero, 1); +} + +bool dpp_derive_i_auth(const void *r_nonce, const void *i_nonce, + size_t nonce_len, struct l_ecc_point *r_proto, + struct l_ecc_point *i_proto, + struct l_ecc_point *r_boot, void *i_auth) +{ + uint64_t prx[L_ECC_MAX_DIGITS]; + uint64_t pix[L_ECC_MAX_DIGITS]; + uint64_t brx[L_ECC_MAX_DIGITS]; + size_t keys_len; + uint8_t one = 1; + enum l_checksum_type type; + + keys_len = l_ecc_point_get_x(r_proto, prx, sizeof(prx)); + l_ecc_point_get_x(i_proto, pix, sizeof(pix)); + l_ecc_point_get_x(r_boot, brx, sizeof(brx)); + + type = dpp_sha_from_key_len(keys_len); + + /* + * I-auth = H(R-nonce | I-nonce | PR.x | PI.x | BR.x | [ BI.x | ] 1) + */ + return dpp_hash(type, i_auth, 6, r_nonce, nonce_len, i_nonce, nonce_len, + prx, keys_len, pix, keys_len, brx, keys_len, &one, 1); +} + +/* + * Derives key k1. This returns the intermediate secret M.x used in deriving + * key ke. + */ +struct l_ecc_scalar *dpp_derive_k1(const struct l_ecc_point *i_proto_public, + const struct l_ecc_scalar *boot_private, + void *k1) +{ + struct l_ecc_scalar *m; + uint64_t mx_bytes[L_ECC_MAX_DIGITS]; + ssize_t key_len; + enum l_checksum_type sha; + + if (!l_ecdh_generate_shared_secret(boot_private, i_proto_public, &m)) + return NULL; + + key_len = l_ecc_scalar_get_data(m, mx_bytes, sizeof(mx_bytes)); + if (key_len < 0) + goto free_m; + + sha = dpp_sha_from_key_len(key_len); + + if (!dpp_hkdf(sha, NULL, key_len, "first intermediate key", mx_bytes, + key_len, k1, key_len)) + goto free_m; + + return m; + +free_m: + l_ecc_scalar_free(m); + return NULL; +} + +/* + * Derives key k2. This returns the intermediate secret N.x used in deriving + * key ke. + */ +struct l_ecc_scalar *dpp_derive_k2(const struct l_ecc_point *i_proto_public, + const struct l_ecc_scalar *proto_private, + void *k2) +{ + struct l_ecc_scalar *n; + uint64_t nx_bytes[L_ECC_MAX_DIGITS]; + ssize_t key_len; + enum l_checksum_type sha; + + if (!l_ecdh_generate_shared_secret(proto_private, i_proto_public, &n)) + return NULL; + + key_len = l_ecc_scalar_get_data(n, nx_bytes, sizeof(nx_bytes)); + if (key_len < 0) + goto free_n; + + sha = dpp_sha_from_key_len(key_len); + + if (!dpp_hkdf(sha, NULL, key_len, "second intermediate key", nx_bytes, + key_len, k2, key_len)) + goto free_n; + + return n; + +free_n: + l_ecc_scalar_free(n); + return NULL; +} + +bool dpp_derive_ke(const uint8_t *i_nonce, const uint8_t *r_nonce, + struct l_ecc_scalar *m, struct l_ecc_scalar *n, + void *ke) +{ + uint8_t nonces[32 + 32]; + size_t nonce_len; + uint64_t mx_bytes[L_ECC_MAX_DIGITS]; + uint64_t nx_bytes[L_ECC_MAX_DIGITS]; + uint64_t bk[L_ECC_MAX_DIGITS]; + ssize_t key_len; + enum l_checksum_type sha; + + key_len = l_ecc_scalar_get_data(m, mx_bytes, sizeof(mx_bytes)); + l_ecc_scalar_get_data(n, nx_bytes, sizeof(nx_bytes)); + + nonce_len = dpp_nonce_len_from_key_len(key_len); + sha = dpp_sha_from_key_len(key_len); + + memcpy(nonces, i_nonce, nonce_len); + memcpy(nonces + nonce_len, r_nonce, nonce_len); + + /* bk = HKDF-Extract(I-nonce | R-nonce, M.x | N.x [ | L.x]) */ + if (!hkdf_extract(sha, nonces, nonce_len * 2, 2, bk, mx_bytes, + key_len, nx_bytes, key_len)) + return false; + + /* ke = HKDF-Expand(bk, "DPP Key", length) */ + 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 }; + +/* 1.2.840.10045.3.1.7 (prime256v1) */ +static uint8_t ec_p256_oid[] = { 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 }; + +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; + 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; + + switch (key_size) { + case 32: + type_oid = ec_p256_oid; + type_oid_len = sizeof(ec_p256_oid); + break; + case 48: + type_oid = ec_p384_oid; + type_oid_len = sizeof(ec_p384_oid); + break; + default: + return NULL; + } + + ret = l_ecc_point_get_x(p, x, sizeof(x)); + if (ret < 0 || ret != key_size) + return NULL; + + len = 2 + sizeof(ec_oid) + 2 + type_oid_len + 2 + key_size + 4; + + if (L_WARN_ON(len > 128)) + return NULL; + + asn1 = l_malloc(len + 2); + ptr = asn1; + + *ptr++ = ASN1_ID_SEQUENCE; + /* Length of both OIDs and key, plus tag/len bytes */ + *ptr++ = len; + + *ptr++ = ASN1_ID_SEQUENCE; + + len = sizeof(ec_oid) + type_oid_len + 4; + + *ptr++ = len; + + *ptr++ = ASN1_ID_OID; + *ptr++ = sizeof(ec_oid); + memcpy(ptr, ec_oid, sizeof(ec_oid)); + ptr += sizeof(ec_oid); + + *ptr++ = ASN1_ID_OID; + *ptr++ = type_oid_len; + memcpy(ptr, type_oid, type_oid_len); + ptr += type_oid_len; + + *ptr++ = ASN1_ID_BIT_STRING; + *ptr++ = key_size + 2; + *ptr++ = 0x00; + *ptr++ = 0x03; + memcpy(ptr, x, key_size); + ptr += key_size; + + if (len_out) + *len_out = ptr - asn1; + + return asn1; +} diff --git a/src/dpp-util.h b/src/dpp-util.h @@ -0,0 +1,169 @@ +/* + * + * Wireless daemon for Linux + * + * Copyright (C) 2021 Intel Corporation. All rights reserved. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ +struct l_ecc_point; +struct l_ecc_scalar; +enum ie_rsn_akm_suite; + +enum dpp_frame_type { + DPP_FRAME_AUTHENTICATION_REQUEST = 0, + DPP_FRAME_AUTHENTICATION_RESPONSE = 1, + DPP_FRAME_AUTHENTICATION_CONFIRM = 2, + /* 3 - 4 reserved */ + DPP_FRAME_PEER_DISCOVERY_REQUEST = 5, + DPP_FRAME_PEER_DISCOVERY_RESPONSE = 6, + DPP_FRAME_PKEX_VERSION1_XCHG_REQUST = 7, + DPP_FRAME_PKEX_XCHG_RESPONSE = 8, + DPP_FRAME_PKEX_COMMIT_REVEAL_REQUEST = 9, + DPP_FRAME_PKEX_COMMIT_REVEAP_RESPONSE = 10, + DPP_FRAME_CONFIGURATION_RESULT = 11, + DPP_FRAME_CONNECTION_STATUS_RESULT = 12, + DPP_FRAME_PRESENCE_ANNOUNCEMENT = 13, + DPP_FRAME_RECONF_ANNOUNCEMENT = 14, + DPP_FRAME_RECONF_AUTHENTICATION_REQUEST = 15, + DPP_FRAME_RECONF_AUTHENTICATION_RESPONSE = 16, + DPP_FRAME_RECONF_AUTHENTICATION_CONFIRM = 17, + DPP_FRAME_PKEX_XCHG_REQUEST = 18, + /* 19 - 255 reserved */ +}; + +enum dpp_status { + DPP_STATUS_OK, + DPP_STATUS_NOT_COMPATIBLE, + DPP_STATUS_AUTH_FAILURE, + DPP_STATUS_BAD_CODE, + DPP_STATUS_BAD_GROUP, + DPP_STATUS_CONFIGURE_FAILURE, + DPP_STATUS_RESPONSE_PENDING, + DPP_STATUS_INVALID_CONNECTOR, + DPP_STATUS_NO_MATCH, + DPP_STATUS_CONFIG_REJECTED, + DPP_STATUS_NO_AP, + DPP_STATUS_CONFIGURE_PENDING, + DPP_STATUS_CSR_NEEDED, + DPP_STATUS_CSR_BAD, + DPP_STATUS_NEW_KEY_NEEDED, +}; + +enum dpp_attribute_type { + /* 0000 - 0FFF reserved */ + DPP_ATTR_STATUS = 0x1000, + DPP_ATTR_INITIATOR_BOOT_KEY_HASH = 0x1001, + DPP_ATTR_RESPONDER_BOOT_KEY_HASH = 0x1002, + DPP_ATTR_INITIATOR_PROTOCOL_KEY = 0x1003, + DPP_ATTR_WRAPPED_DATA = 0x1004, + DPP_ATTR_INITIATOR_NONCE = 0x1005, + DPP_ATTR_INITIATOR_CAPABILITIES = 0x1006, + DPP_ATTR_RESPONDER_NONCE = 0x1007, + DPP_ATTR_RESPONDER_CAPABILITIES = 0x1008, + DPP_ATTR_RESPONDER_PROTOCOL_KEY = 0x1009, + DPP_ATTR_INITIATOR_AUTH_TAG = 0x100a, + DPP_ATTR_RESPONDER_AUTH_TAG = 0x100b, + DPP_ATTR_CONFIGURATION_OBJECT = 0x100c, + DPP_ATTR_CONNECTOR = 0x100d, + DPP_ATTR_CONFIGURATION_REQUEST = 0x100e, + DPP_ATTR_BOOTSTRAPPING_KEY = 0x100f, + /* 1010 - 1011 reserved */ + DPP_ATTR_FINITE_CYCLIC_GROUP = 0x1012, + DPP_ATTR_ENCRYPTED_KEY = 0x1013, + DPP_ATTR_ENROLLEE_NONCE = 0x1014, + DPP_ATTR_CODE_IDENTIFIER = 0x1015, + DPP_ATTR_TRANSACTION_ID = 0x1016, + DPP_ATTR_BOOTSTRAPPING_INFO = 0x1017, + DPP_ATTR_CHANNEL = 0x1018, + DPP_ATTR_PROTOCOL_VERSION = 0x1019, + DPP_ATTR_ENVELOPED_DATA = 0x101a, + DPP_ATTR_SEND_CONN_STATUS = 0x101b, + DPP_ATTR_CONN_STATUS = 0x101c, + DPP_ATTR_RECONFIGURATION_FLAGS = 0x101d, + DPP_ATTR_C_SIGN_KEY_HASH = 0x101e, + DPP_ATTR_CSR_ATTRIBUTES_REQUEST = 0x101f, + DPP_ATTR_ANONCE = 0x1020, + DPP_ATTR_EID = 0x1021, + DPP_ATTR_CONFIGURATOR_NONCE = 0x1022, +}; + +struct dpp_configuration { + uint8_t ssid[32]; + size_t ssid_len; + uint32_t akm_suites; + char *passphrase; + char *psk; /* hex string */ +}; + +struct dpp_configuration *dpp_parse_configuration_object(const char *json, + size_t json_len); +struct dpp_configuration *dpp_configuration_new( + const struct l_settings *settings, + const char *ssid, + enum ie_rsn_akm_suite akm_suite); +char *dpp_configuration_to_json(struct dpp_configuration *config); +void dpp_configuration_free(struct dpp_configuration *conf); + +struct dpp_attr_iter { + const uint8_t *pos; + const uint8_t *end; +}; + +void dpp_attr_iter_init(struct dpp_attr_iter *iter, const uint8_t *pdu, + size_t len); +bool dpp_attr_iter_next(struct dpp_attr_iter *iter, + enum dpp_attribute_type *type, size_t *len, + const uint8_t **data); +uint8_t *dpp_unwrap_attr(const void *ad0, size_t ad0_len, const void *ad1, + size_t ad1_len, const void *key, size_t key_len, + const void *wrapped, size_t wrapped_len, + size_t *unwrapped_len); +size_t dpp_append_attr(uint8_t *to, enum dpp_attribute_type type, + void *attr, size_t attr_len); +size_t dpp_append_wrapped_data(const void *ad0, size_t ad0_len, const void *ad1, + size_t ad1_len, uint8_t *to, size_t to_len, + const void *key, size_t key_len, + size_t num_attrs, ...); + +char *dpp_generate_uri(const uint8_t *asn1, size_t asn1_len, uint8_t version, + const uint8_t *mac, const uint32_t *freqs, + size_t freqs_len, const char *info, const char *host); + +size_t dpp_nonce_len_from_key_len(size_t len); + +bool dpp_hash(enum l_checksum_type type, uint8_t *out, unsigned int num, ...); + +bool dpp_derive_r_auth(const void *i_nonce, const void *r_nonce, + size_t nonce_len, struct l_ecc_point *i_proto, + struct l_ecc_point *r_proto, + struct l_ecc_point *r_boot, + void *r_auth); +bool dpp_derive_i_auth(const void *r_nonce, const void *i_nonce, + size_t nonce_len, struct l_ecc_point *r_proto, + struct l_ecc_point *i_proto, + struct l_ecc_point *r_boot, void *i_auth); +struct l_ecc_scalar *dpp_derive_k1(const struct l_ecc_point *i_proto_public, + const struct l_ecc_scalar *boot_private, + void *k1); +struct l_ecc_scalar *dpp_derive_k2(const struct l_ecc_point *i_proto_public, + const struct l_ecc_scalar *proto_private, + void *k2); +bool dpp_derive_ke(const uint8_t *i_nonce, const uint8_t *r_nonce, + struct l_ecc_scalar *m, struct l_ecc_scalar *n, + void *ke); + +uint8_t *dpp_point_to_asn1(const struct l_ecc_point *p, size_t *len_out); diff --git a/src/dpp.c b/src/dpp.c @@ -0,0 +1,1665 @@ +/* + * + * Wireless daemon for Linux + * + * Copyright (C) 2021 Intel Corporation. All rights reserved. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <errno.h> + +#include <ell/ell.h> + +#include "linux/nl80211.h" + +#include "src/dbus.h" +#include "src/netdev.h" +#include "src/module.h" +#include "src/dpp-util.h" +#include "src/band.h" +#include "src/frame-xchg.h" +#include "src/offchannel.h" +#include "src/wiphy.h" +#include "src/ie.h" +#include "src/iwd.h" +#include "src/util.h" +#include "src/crypto.h" +#include "src/mpdu.h" +#include "ell/useful.h" +#include "src/common.h" +#include "src/json.h" +#include "src/storage.h" +#include "src/station.h" +#include "src/scan.h" +#include "src/network.h" +#include "src/handshake.h" + +static uint32_t netdev_watch; +static struct l_genl_family *nl80211; +static uint8_t broadcast[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; + +enum dpp_state { + DPP_STATE_NOTHING, + DPP_STATE_PRESENCE, + DPP_STATE_AUTHENTICATING, + DPP_STATE_CONFIGURING, +}; + +enum dpp_capability { + DPP_CAPABILITY_ENROLLEE = 0x01, + DPP_CAPABILITY_CONFIGURATOR = 0x02, +}; + +struct dpp_sm { + struct netdev *netdev; + char *uri; + uint8_t role; + + uint64_t wdev_id; + + uint8_t *pub_asn1; + size_t pub_asn1_len; + uint8_t pub_boot_hash[32]; + const struct l_ecc_curve *curve; + size_t key_len; + size_t nonce_len; + struct l_ecc_scalar *boot_private; + struct l_ecc_point *boot_public; + + enum dpp_state state; + + uint32_t *freqs; + size_t freqs_len; + size_t freqs_idx; + uint32_t dwell; + uint32_t current_freq; + struct scan_freq_set *presence_list; + + uint32_t offchannel_id; + + uint8_t auth_addr[6]; + uint8_t r_nonce[32]; + uint8_t i_nonce[32]; + uint8_t e_nonce[32]; + + uint64_t ke[L_ECC_MAX_DIGITS]; + uint64_t k2[L_ECC_MAX_DIGITS]; + + struct l_ecc_scalar *proto_private; + struct l_ecc_point *proto_public; + + struct l_ecc_point *i_proto_public; + + uint8_t diag_token; + + /* Timeout of either auth/config protocol */ + struct l_timeout *timeout; + + struct dpp_configuration *config; +}; + +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->proto_private) { + l_ecc_scalar_free(dpp->proto_private); + dpp->proto_private = NULL; + } + + if (dpp->i_proto_public) { + l_ecc_point_free(dpp->i_proto_public); + dpp->i_proto_public = NULL; + } +} + +static void dpp_reset(struct dpp_sm *dpp) +{ + if (dpp->uri) { + l_free(dpp->uri); + dpp->uri = NULL; + } + + if (dpp->freqs) { + l_free(dpp->freqs); + dpp->freqs = NULL; + } + + if (dpp->offchannel_id) { + offchannel_cancel(dpp->wdev_id, dpp->offchannel_id); + dpp->offchannel_id = 0; + } + + if (dpp->timeout) { + l_timeout_remove(dpp->timeout); + dpp->timeout = NULL; + } + + if (dpp->config) { + dpp_configuration_free(dpp->config); + dpp->config = NULL; + } + + dpp->state = DPP_STATE_NOTHING; + + 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); + + dpp_free_auth_data(dpp); +} + +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->boot_public) { + l_ecc_point_free(dpp->boot_public); + dpp->boot_public = NULL; + } + + if (dpp->boot_private) { + l_ecc_scalar_free(dpp->boot_private); + dpp->boot_private = NULL; + } + + l_free(dpp); +} + +static void dpp_send_frame_cb(struct l_genl_msg *msg, void *user_data) +{ + if (l_genl_msg_get_error(msg) < 0) + l_error("Error sending frame"); +} + +static void dpp_send_frame(uint64_t wdev_id, 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_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)) + l_error("Could not send CMD_FRAME"); +} + +static size_t dpp_build_header(const uint8_t *src, const uint8_t *dest, + enum dpp_frame_type type, + uint8_t buf[static 32]) +{ + uint8_t *ptr = buf + 24; + + memset(buf, 0, 32); + + l_put_le16(0x00d0, buf); + memcpy(buf + 4, dest, 6); + memcpy(buf + 10, src, 6); + memcpy(buf + 16, broadcast, 6); + + *ptr++ = 0x04; /* Category: Public */ + *ptr++ = 0x09; /* Action: Vendor specific usage */ + memcpy(ptr, wifi_alliance_oui, 3); + ptr += 3; + *ptr++ = 0x1a; /* WiFi Alliance DPP OI type */ + *ptr++ = 1; /* Cryptosuite */ + *ptr++ = type; + + return ptr - buf; +} + +static size_t dpp_build_config_header(const uint8_t *src, const uint8_t *dest, + uint8_t diag_token, + uint8_t buf[static 37]) +{ + uint8_t *ptr = buf + 24; + + memset(buf, 0, 37); + + l_put_le16(0x00d0, buf); + memcpy(buf + 4, dest, 6); + memcpy(buf + 10, src, 6); + memcpy(buf + 16, broadcast, 6); + + *ptr++ = 0x04; /* Public */ + *ptr++ = 0x0a; /* Action */ + *ptr++ = diag_token; + + *ptr++ = IE_TYPE_ADVERTISEMENT_PROTOCOL; + *ptr++ = 8; /* len */ + *ptr++ = 0x00; + *ptr++ = IE_TYPE_VENDOR_SPECIFIC; + *ptr++ = 5; + memcpy(ptr, wifi_alliance_oui, 3); + ptr += 3; + *ptr++ = 0x1a; + *ptr++ = 1; + + return ptr - buf; +} + +static void dpp_protocol_timeout(struct l_timeout *timeout, void *user_data) +{ + struct dpp_sm *dpp = user_data; + + l_debug("DPP timed out"); + + dpp_reset(dpp); +} + +static void dpp_reset_protocol_timer(struct dpp_sm *dpp) +{ + if (dpp->timeout) + l_timeout_modify(dpp->timeout, 10); + else + dpp->timeout = l_timeout_create(10, dpp_protocol_timeout, + dpp, NULL); +} + +/* + * The configuration protocols use of AD components is somewhat confusing + * since the request/response frames are of a different format than the rest. + * In addition there are situations where the components length is zero yet it + * is still passed as such to AES-SIV. + * + * For the configuration request/response frames: + * + * "AAD for use with AES-SIV for protected messages in the DPP Configuration + * protocol shall consist of all octets in the Query Request and Query Response + * fields up to the first octet of the Wrapped Data attribute, which is the last + * attribute in a DPP Configuration frame. When the number of octets of AAD is + * zero, the number of components of AAD passed to AES-SIV is zero." + * + * - For configuration requests the optional query request field is not + * included, therefore no AAD data is passed. (dpp_configuration_start) + * + * - The configuration response does contain a query response field which is + * 5 bytes. (dpp_handle_config_response_frame) + * + * For the configuration result/status, the same rules are used as the + * authentication protocol. This is reiterated in section 6.4.1. + * + * - For the configuration result there is some confusion as to exactly how the + * second AAD component should be passed (since the spec specifically + * mentions using two components). There are no attributes prior to the + * wrapped data component meaning the length would be zero. + * Hostapd/wpa_supplicant pass a zero length AAD component to AES-SIV which + * does effect the resulting encryption/decryption so this is also what IWD + * will do to remain compliant with it. + */ +static void dpp_configuration_start(struct dpp_sm *dpp, const uint8_t *addr) +{ + const char *json = "{\"name\":\"IWD\",\"wi-fi_tech\":\"infra\"," + "\"netRole\":\"sta\"}"; + struct iovec iov[3]; + uint8_t hdr[37]; + uint8_t attrs[512]; + size_t json_len = strlen(json); + uint8_t *ptr = attrs; + + l_getrandom(&dpp->diag_token, 1); + + iov[0].iov_len = dpp_build_config_header( + netdev_get_address(dpp->netdev), + addr, dpp->diag_token, hdr); + iov[0].iov_base = hdr; + + l_getrandom(dpp->e_nonce, dpp->nonce_len); + + /* length */ + ptr += 2; + + /* + * "AAD for use with AES-SIV for protected messages in the DPP + * Configuration protocol shall consist of all octets in the Query + * Request and Query Response fields up to the first octet of the + * Wrapped Data attribute" + * + * In this case there is no query request/response fields, nor any + * attributes besides wrapped data meaning zero AD components. + */ + ptr += dpp_append_wrapped_data(NULL, 0, NULL, 0, ptr, sizeof(attrs), + dpp->ke, dpp->key_len, 2, + DPP_ATTR_ENROLLEE_NONCE, dpp->nonce_len, dpp->e_nonce, + DPP_ATTR_CONFIGURATION_REQUEST, json_len, json); + + l_put_le16(ptr - attrs - 2, attrs); + + iov[1].iov_base = attrs; + iov[1].iov_len = ptr - attrs; + + dpp->state = DPP_STATE_CONFIGURING; + + dpp_send_frame(dpp->wdev_id, iov, 2, dpp->current_freq); +} + +static void send_config_result(struct dpp_sm *dpp, const uint8_t *to) +{ + uint8_t hdr[32]; + struct iovec iov[2]; + uint8_t attrs[256]; + uint8_t *ptr = attrs; + uint8_t zero = 0; + + iov[0].iov_len = dpp_build_header(netdev_get_address(dpp->netdev), to, + DPP_FRAME_CONFIGURATION_RESULT, hdr); + iov[0].iov_base = hdr; + + ptr += dpp_append_wrapped_data(hdr + 26, 6, attrs, 0, ptr, + sizeof(attrs), dpp->ke, dpp->key_len, 2, + DPP_ATTR_STATUS, 1, &zero, + DPP_ATTR_ENROLLEE_NONCE, dpp->nonce_len, dpp->e_nonce); + + iov[1].iov_base = attrs; + iov[1].iov_len = ptr - attrs; + + dpp_send_frame(dpp->wdev_id, iov, 2, dpp->current_freq); +} + +static void dpp_write_config(struct dpp_configuration *config) +{ + _auto_(l_free) char *ssid = l_malloc(config->ssid_len + 1); + _auto_(l_settings_free) struct l_settings *settings = l_settings_new(); + _auto_(l_free) char *path; + + memcpy(ssid, config->ssid, config->ssid_len); + ssid[config->ssid_len] = '\0'; + + path = storage_get_network_file_path(SECURITY_PSK, ssid); + + if (l_settings_load_from_file(settings, path)) { + /* Remove any existing Security keys */ + l_settings_remove_group(settings, "Security"); + } + + if (config->passphrase) + l_settings_set_string(settings, "Security", "Passphrase", + config->passphrase); + else if (config->psk) + l_settings_set_string(settings, "Security", "PreSharedKey", + config->psk); + + l_debug("Storing credential for '%s(%s)'", ssid, + security_to_str(SECURITY_PSK)); + storage_network_sync(SECURITY_PSK, ssid, settings); +} + +static void dpp_handle_config_response_frame(const struct mmpdu_header *frame, + const void *body, size_t body_len, + int rssi, void *user_data) +{ + struct dpp_sm *dpp = user_data; + const uint8_t *ptr = body; + uint16_t status; + uint16_t fragmented; /* Fragmented/Comeback delay field */ + uint8_t adv_protocol_element[] = { 0x6C, 0x08, 0x7F }; + uint8_t adv_protocol_id[] = { 0xDD, 0x05, 0x50, 0x6F, + 0x9A, 0x1A, 0x01 }; + uint16_t query_len; + struct dpp_attr_iter iter; + enum dpp_attribute_type type; + size_t len; + const uint8_t *data; + const char *json = NULL; + size_t json_len = 0; + int dstatus = -1; + const uint8_t *wrapped = NULL; + const uint8_t *e_nonce = NULL; + size_t wrapped_len = 0; + _auto_(l_free) uint8_t *unwrapped = NULL; + struct dpp_configuration *config; + + if (dpp->state != DPP_STATE_CONFIGURING) + return; + + /* + * Can a configuration request come from someone other than who you + * authenticated to? + */ + if (memcmp(dpp->auth_addr, frame->address_2, 6)) + return; + + if (body_len < 19) + return; + + ptr += 2; + + if (*ptr++ != dpp->diag_token) + return; + + status = l_get_le16(ptr); + ptr += 2; + + if (status != 0) { + l_debug("Bad configuration status %u", status); + return; + } + + fragmented = l_get_le16(ptr); + ptr += 2; + + /* + * TODO: handle 0x0001 (fragmented), as well as comeback delay. + */ + if (fragmented != 0) { + l_debug("Fragmented messages not currently supported"); + return; + } + + if (memcmp(ptr, adv_protocol_element, sizeof(adv_protocol_element))) { + l_debug("Invalid Advertisement protocol element"); + return; + } + + ptr += sizeof(adv_protocol_element); + + if (memcmp(ptr, adv_protocol_id, sizeof(adv_protocol_id))) { + l_debug("Invalid Advertisement protocol ID"); + return; + } + + ptr += sizeof(adv_protocol_id); + + query_len = l_get_le16(ptr); + ptr += 2; + + if (query_len > body_len - 19) + return; + + dpp_attr_iter_init(&iter, ptr, query_len); + + while (dpp_attr_iter_next(&iter, &type, &len, &data)) { + switch (type) { + case DPP_ATTR_STATUS: + dstatus = l_get_u8(data); + break; + case DPP_ATTR_WRAPPED_DATA: + wrapped = data; + wrapped_len = len; + break; + default: + /* + * TODO: CSR Attribute + */ + break; + } + } + + if (dstatus != DPP_STATUS_OK || !wrapped) { + l_debug("Bad status or missing attributes"); + return; + } + + unwrapped = dpp_unwrap_attr(ptr, wrapped - ptr - 4, NULL, 0, dpp->ke, + dpp->key_len, wrapped, wrapped_len, + &wrapped_len); + if (!unwrapped) { + l_debug("Failed to unwrap"); + return; + } + + dpp_attr_iter_init(&iter, unwrapped, wrapped_len); + + while (dpp_attr_iter_next(&iter, &type, &len, &data)) { + switch (type) { + case DPP_ATTR_ENROLLEE_NONCE: + if (len != dpp->nonce_len) + break; + + if (memcmp(data, dpp->e_nonce, dpp->nonce_len)) + break; + + e_nonce = data; + break; + case DPP_ATTR_CONFIGURATION_OBJECT: + json = (const char *)data; + json_len = len; + break; + default: + break; + } + } + + if (!json || !e_nonce) { + l_debug("No configuration object in response"); + return; + } + + config = dpp_parse_configuration_object(json, json_len); + if (!config) { + l_error("Configuration object did not parse"); + 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. + */ + + dpp_configuration_free(config); + + send_config_result(dpp, dpp->auth_addr); +} + +static void dpp_send_config_response(struct dpp_sm *dpp) +{ + _auto_(l_free) char *json; + 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; + + l_put_le16(0x00d0, hdr); + memcpy(hdr + 4, dpp->auth_addr, 6); + memcpy(hdr + 10, netdev_get_address(dpp->netdev), 6); + memcpy(hdr + 16, broadcast, 6); + + *ptr++ = 0x04; + *ptr++ = 0x0b; + *ptr++ = dpp->diag_token; + l_put_le16(0, ptr); /* status */ + ptr += 2; + l_put_le16(0, ptr); /* fragmented (no) */ + ptr += 2; + *ptr++ = IE_TYPE_ADVERTISEMENT_PROTOCOL; + *ptr++ = 0x08; + *ptr++ = 0x7f; + *ptr++ = IE_TYPE_VENDOR_SPECIFIC; + *ptr++ = 5; + memcpy(ptr, wifi_alliance_oui, sizeof(wifi_alliance_oui)); + ptr += sizeof(wifi_alliance_oui); + *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; + + ptr = attrs; + + ptr += 2; /* length */ + + ptr += dpp_append_attr(ptr, DPP_ATTR_STATUS, &zero, 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); + + 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); +} + +static void dpp_handle_config_request_frame(const struct mmpdu_header *frame, + const void *body, size_t body_len, + int rssi, void *user_data) +{ + struct dpp_sm *dpp = user_data; + const uint8_t *ptr = body; + struct dpp_attr_iter iter; + enum dpp_attribute_type type; + size_t len; + const uint8_t *data; + const char *json = NULL; + size_t json_len = 0; + struct json_contents *c; + const uint8_t *wrapped = NULL; + const uint8_t *e_nonce = NULL; + size_t wrapped_len = 0; + _auto_(l_free) uint8_t *unwrapped = NULL; + uint8_t hdr_check[] = { IE_TYPE_ADVERTISEMENT_PROTOCOL, 0x08, 0x7f, + IE_TYPE_VENDOR_SPECIFIC, 5 }; + + if (dpp->state != DPP_STATE_AUTHENTICATING) { + l_debug("Configuration request in wrong state"); + return; + } + + if (memcmp(dpp->auth_addr, frame->address_2, 6)) { + l_debug("Configuration request not from authenticated peer"); + return; + } + + if (body_len < 15) { + l_debug("Configuration request data not long enough"); + return; + } + + ptr += 2; + + dpp->diag_token = *ptr++; + + if (memcmp(ptr, hdr_check, sizeof(hdr_check))) + return; + + ptr += sizeof(hdr_check); + + if (memcmp(ptr, wifi_alliance_oui, sizeof(wifi_alliance_oui))) + return; + + ptr += sizeof(wifi_alliance_oui); + + if (*ptr != 0x1a && *(ptr + 1) != 1) + return; + + ptr += 2; + + len = l_get_le16(ptr); + ptr += 2; + + if (len > body_len - 15) + return; + + dpp_attr_iter_init(&iter, ptr, len); + + while (dpp_attr_iter_next(&iter, &type, &len, &data)) { + switch (type) { + case DPP_ATTR_WRAPPED_DATA: + wrapped = data; + wrapped_len = len; + break; + default: + /* Wrapped data should be only attribute */ + return; + } + } + + if (!wrapped) { + l_debug("Wrapped data missing"); + return; + } + + unwrapped = dpp_unwrap_attr(NULL, 0, NULL, 0, dpp->ke, + dpp->key_len, wrapped, wrapped_len, + &wrapped_len); + if (!unwrapped) { + l_debug("Failed to unwrap"); + return; + } + + dpp_attr_iter_init(&iter, unwrapped, wrapped_len); + + while (dpp_attr_iter_next(&iter, &type, &len, &data)) { + switch (type) { + case DPP_ATTR_ENROLLEE_NONCE: + if (len != dpp->nonce_len) + break; + + e_nonce = data; + break; + case DPP_ATTR_CONFIGURATION_REQUEST: + json = (const char *)data; + json_len = len; + break; + default: + break; + } + } + + if (!json || !e_nonce) { + l_debug("No configuration object in response"); + 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_contents_free(c); + + memcpy(dpp->e_nonce, e_nonce, dpp->nonce_len); + + dpp->state = DPP_STATE_CONFIGURING; + + dpp_send_config_response(dpp); +} + +static void dpp_handle_config_result_frame(struct dpp_sm *dpp, + const uint8_t *from, const void *body, + size_t body_len) +{ + struct dpp_attr_iter iter; + enum dpp_attribute_type type; + size_t len; + const uint8_t *data; + int status = -1; + const void *e_nonce = NULL; + const void *wrapped = NULL; + size_t wrapped_len; + _auto_(l_free) void *unwrapped = NULL; + + if (dpp->state != DPP_STATE_CONFIGURING) + return; + + dpp_attr_iter_init(&iter, body + 8, body_len - 8); + + while (dpp_attr_iter_next(&iter, &type, &len, &data)) { + switch (type) { + case DPP_ATTR_WRAPPED_DATA: + wrapped = data; + wrapped_len = len; + break; + default: + /* Wrapped data should be only attribute */ + return; + } + } + + if (!wrapped) + return; + + unwrapped = dpp_unwrap_attr(body + 2, wrapped - body - 6, wrapped, 0, + dpp->ke, dpp->key_len, wrapped, + wrapped_len, &wrapped_len); + if (!unwrapped) { + l_debug("Failed to unwrap DPP configuration result"); + return; + } + + dpp_attr_iter_init(&iter, unwrapped, wrapped_len); + + while (dpp_attr_iter_next(&iter, &type, &len, &data)) { + switch (type) { + case DPP_ATTR_STATUS: + status = l_get_u8(data); + break; + case DPP_ATTR_ENROLLEE_NONCE: + e_nonce = data; + break; + default: + break; + } + } + + if (status != DPP_STATUS_OK || !e_nonce) + l_debug("Enrollee signaled a failed configuration"); + else + l_debug("Configuration success"); + + dpp_reset(dpp); +} + +/* + * The Authentication protocol has a consistent use of AD components, and this + * use is defined in 6.3.1.4: + * + * "Invocations of AES-SIV in the DPP Authentication protocol that produce + * ciphertext that is part of an additional AES-SIV invocation do not use AAD; + * in other words, the number of AAD components is set to zero. All other + * invocations of AES-SIV in the DPP Authentication protocol shall pass a vector + * of AAD having two components of AAD in the following order: (1) the DPP + * header, as defined in Table 30, from the OUI field (inclusive) to the DPP + * Frame Type field (inclusive); and (2) all octets in a DPP Public Action frame + * after the DPP Frame Type field up to and including the last octet of the last + * attribute before the Wrapped Data attribute" + * + * In practice you see this as AD0 being some offset in the frame (offset to the + * OUI). For outgoing packets this is 26 bytes offset since the header is built + * manually. For incoming packets the offset is 2 bytes. The length is always + * 6 bytes for AD0. + * + * The AD1 data is always the start of the attributes, and length is the number + * of bytes from these attributes to wrapped data. e.g. + * + * ad1 = attrs + * ad1_len = ptr - attrs + */ +static void send_authenticate_response(struct dpp_sm *dpp, void *r_auth) +{ + uint8_t hdr[32]; + uint8_t attrs[256]; + uint8_t *ptr = attrs; + uint8_t status = DPP_STATUS_OK; + uint64_t r_proto_key[L_ECC_MAX_DIGITS * 2]; + uint8_t version = 2; + struct iovec iov[3]; + uint8_t wrapped2_plaintext[dpp->key_len + 4]; + uint8_t wrapped2[dpp->key_len + 16 + 8]; + size_t wrapped2_len; + + l_ecc_point_get_data(dpp->proto_public, r_proto_key, + sizeof(r_proto_key)); + + iov[0].iov_len = dpp_build_header(netdev_get_address(dpp->netdev), + dpp->auth_addr, + DPP_FRAME_AUTHENTICATION_RESPONSE, hdr); + iov[0].iov_base = hdr; + + ptr += dpp_append_attr(ptr, DPP_ATTR_STATUS, &status, 1); + ptr += dpp_append_attr(ptr, DPP_ATTR_RESPONDER_BOOT_KEY_HASH, + dpp->pub_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); + + /* Wrap up secondary data (R-Auth) */ + wrapped2_len = dpp_append_attr(wrapped2_plaintext, + DPP_ATTR_RESPONDER_AUTH_TAG, + r_auth, dpp->key_len); + /* + * "Invocations of AES-SIV in the DPP Authentication protocol that + * produce ciphertext that is part of an additional AES-SIV invocation + * do not use AAD; in other words, the number of AAD components is set + * to zero."" + */ + aes_siv_encrypt(dpp->ke, dpp->key_len, wrapped2_plaintext, + dpp->key_len + 4, NULL, 0, wrapped2); + + wrapped2_len += 16; + + ptr += dpp_append_wrapped_data(hdr + 26, 6, attrs, ptr - attrs, + ptr, sizeof(attrs), dpp->k2, dpp->key_len, 4, + DPP_ATTR_RESPONDER_NONCE, dpp->nonce_len, dpp->r_nonce, + DPP_ATTR_INITIATOR_NONCE, dpp->nonce_len, dpp->i_nonce, + DPP_ATTR_RESPONDER_CAPABILITIES, 1, &dpp->role, + DPP_ATTR_WRAPPED_DATA, wrapped2_len, wrapped2); + + 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); +} + +static void authenticate_confirm(struct dpp_sm *dpp, const uint8_t *from, + const uint8_t *body, size_t body_len) +{ + struct dpp_attr_iter iter; + enum dpp_attribute_type type; + size_t len; + const uint8_t *data; + int status = -1; + const uint8_t *r_boot_hash = NULL; + const void *wrapped = NULL; + const uint8_t *i_auth = NULL; + size_t i_auth_len; + _auto_(l_free) uint8_t *unwrapped = NULL; + size_t wrapped_len = 0; + uint64_t i_auth_check[L_ECC_MAX_DIGITS]; + const void *unwrap_key; + const void *ad0 = body + 2; + const void *ad1 = body + 8; + + if (dpp->state != DPP_STATE_AUTHENTICATING) + return; + + if (memcmp(from, dpp->auth_addr, 6)) + return; + + l_debug("authenticate confirm"); + + dpp_attr_iter_init(&iter, body + 8, body_len - 8); + + while (dpp_attr_iter_next(&iter, &type, &len, &data)) { + switch (type) { + case DPP_ATTR_STATUS: + status = l_get_u8(data); + break; + case DPP_ATTR_RESPONDER_BOOT_KEY_HASH: + r_boot_hash = data; + /* + * Spec requires this, but does not mention if anything + * is to be done with it. + */ + break; + case DPP_ATTR_INITIATOR_BOOT_KEY_HASH: + /* No mutual authentication */ + break; + case DPP_ATTR_WRAPPED_DATA: + wrapped = data; + wrapped_len = len; + break; + default: + break; + } + } + + if (!r_boot_hash || !wrapped) { + l_debug("Attributes missing from authenticate confirm"); + return; + } + + /* + * "The Responder obtains the DPP Authentication Confirm frame and + * checks the value of the DPP Status field. If the value of the DPP + * Status field is STATUS_NOT_COMPATIBLE or STATUS_AUTH_FAILURE, the + * Responder unwraps the wrapped data portion of the frame using k2" + */ + if (status == DPP_STATUS_OK) + unwrap_key = dpp->ke; + else if (status == DPP_STATUS_NOT_COMPATIBLE || + status == DPP_STATUS_AUTH_FAILURE) + unwrap_key = dpp->k2; + else + goto auth_confirm_failed; + + unwrapped = dpp_unwrap_attr(ad0, 6, ad1, wrapped - 4 - ad1, + unwrap_key, dpp->key_len, wrapped, wrapped_len, + &wrapped_len); + if (!unwrapped) + goto auth_confirm_failed; + + if (status != DPP_STATUS_OK) { + /* + * "If unwrapping is successful, the Responder should generate + * an alert indicating the reason for the protocol failure." + */ + l_debug("Authentication failed due to status %s", + status == DPP_STATUS_NOT_COMPATIBLE ? + "NOT_COMPATIBLE" : "AUTH_FAILURE"); + goto auth_confirm_failed; + } + + dpp_attr_iter_init(&iter, unwrapped, wrapped_len); + + while (dpp_attr_iter_next(&iter, &type, &len, &data)) { + switch (type) { + case DPP_ATTR_INITIATOR_AUTH_TAG: + i_auth = data; + i_auth_len = len; + break; + case DPP_ATTR_RESPONDER_NONCE: + /* Only if error */ + break; + default: + break; + } + } + + if (!i_auth || i_auth_len != dpp->key_len) { + l_debug("I-Auth missing from wrapped data"); + goto auth_confirm_failed; + } + + dpp_derive_i_auth(dpp->r_nonce, dpp->i_nonce, dpp->nonce_len, + dpp->proto_public, dpp->i_proto_public, + dpp->boot_public, i_auth_check); + + if (memcmp(i_auth, i_auth_check, i_auth_len)) { + l_error("I-Auth did not verify"); + goto auth_confirm_failed; + } + + l_debug("Authentication successful"); + + dpp_reset_protocol_timer(dpp); + + if (dpp->role == DPP_CAPABILITY_ENROLLEE) + dpp_configuration_start(dpp, from); + + return; + +auth_confirm_failed: + dpp->state = DPP_STATE_PRESENCE; + dpp_free_auth_data(dpp); +} + +static void dpp_auth_request_failed(struct dpp_sm *dpp, + enum dpp_status status, + void *k1) +{ + uint8_t hdr[32]; + uint8_t attrs[128]; + uint8_t *ptr = attrs; + uint8_t version = 2; + uint8_t s = status; + struct iovec iov[2]; + + iov[0].iov_len = dpp_build_header(netdev_get_address(dpp->netdev), + dpp->auth_addr, + DPP_FRAME_AUTHENTICATION_RESPONSE, hdr); + iov[0].iov_base = hdr; + + 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); + + ptr += dpp_append_attr(ptr, DPP_ATTR_PROTOCOL_VERSION, &version, 1); + + ptr += dpp_append_wrapped_data(hdr + 26, 6, attrs, ptr - attrs, + ptr, sizeof(attrs) - (ptr - attrs), k1, dpp->key_len, 2, + DPP_ATTR_INITIATOR_NONCE, dpp->nonce_len, dpp->i_nonce, + DPP_ATTR_RESPONDER_CAPABILITIES, 1, &dpp->role); + + 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); +} + +static bool dpp_check_roles(struct dpp_sm *dpp, uint8_t peer_capa) +{ + if (dpp->role == DPP_CAPABILITY_ENROLLEE && + !(peer_capa & DPP_CAPABILITY_CONFIGURATOR)) + return false; + else if (dpp->role == DPP_CAPABILITY_CONFIGURATOR && + !(peer_capa & DPP_CAPABILITY_ENROLLEE)) + return false; + + return true; +} + +static void authenticate_request(struct dpp_sm *dpp, const uint8_t *from, + const uint8_t *body, size_t body_len) +{ + struct dpp_attr_iter iter; + enum dpp_attribute_type type; + size_t len; + const uint8_t *data; + const uint8_t *r_boot = NULL; + const uint8_t *i_boot = NULL; + const uint8_t *i_proto = NULL; + const void *wrapped = NULL; + const uint8_t *i_nonce = NULL; + uint8_t i_capa = 0; + size_t r_boot_len = 0, i_proto_len = 0, wrapped_len = 0; + size_t i_nonce_len = 0; + _auto_(l_free) uint8_t *unwrapped = NULL; + _auto_(l_ecc_scalar_free) struct l_ecc_scalar *m = NULL; + _auto_(l_ecc_scalar_free) struct l_ecc_scalar *n = NULL; + 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; + + if (dpp->state != DPP_STATE_PRESENCE) + return; + + l_debug("authenticate request"); + + dpp_attr_iter_init(&iter, body + 8, body_len - 8); + + while (dpp_attr_iter_next(&iter, &type, &len, &data)) { + switch (type) { + case DPP_ATTR_INITIATOR_BOOT_KEY_HASH: + i_boot = data; + /* + * This attribute is required by the spec, but only + * used for mutual authentication. + */ + break; + case DPP_ATTR_RESPONDER_BOOT_KEY_HASH: + r_boot = data; + r_boot_len = len; + break; + case DPP_ATTR_INITIATOR_PROTOCOL_KEY: + i_proto = data; + i_proto_len = len; + break; + case DPP_ATTR_WRAPPED_DATA: + /* I-Nonce/I-Capabilities part of wrapped data */ + wrapped = data; + wrapped_len = len; + break; + + /* Optional attributes */ + case DPP_ATTR_PROTOCOL_VERSION: + if (l_get_u8(data) != 2) { + l_debug("Protocol version did not match"); + return; + } + + 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; + default: + break; + } + } + + if (!r_boot || !i_boot || !i_proto || !wrapped) + goto auth_request_failed; + + if (r_boot_len != 32 || memcmp(dpp->pub_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, + L_ECC_POINT_TYPE_FULL, + i_proto, i_proto_len); + if (!dpp->i_proto_public) { + l_debug("Initiators protocol key invalid"); + goto auth_request_failed; + } + + m = dpp_derive_k1(dpp->i_proto_public, dpp->boot_private, k1); + if (!m) + goto auth_request_failed; + + unwrapped = dpp_unwrap_attr(ad0, 6, ad1, wrapped - 4 - ad1, + k1, dpp->key_len, wrapped, wrapped_len, &wrapped_len); + if (!unwrapped) + goto auth_request_failed; + + dpp_attr_iter_init(&iter, unwrapped, wrapped_len); + + while (dpp_attr_iter_next(&iter, &type, &len, &data)) { + switch (type) { + case DPP_ATTR_INITIATOR_NONCE: + i_nonce = data; + i_nonce_len = len; + break; + case DPP_ATTR_INITIATOR_CAPABILITIES: + /* + * "If the Responder is not capable of supporting the + * role indicated by the Initiator, it shall respond + * with a DPP Authentication Response frame indicating + * failure by adding the DPP Status field set to + * STATUS_NOT_COMPATIBLE" + */ + i_capa = l_get_u8(data); + + if (!dpp_check_roles(dpp, i_capa)) { + l_debug("Peer does not support required role"); + dpp_auth_request_failed(dpp, + DPP_STATUS_NOT_COMPATIBLE, k1); + goto auth_request_failed; + } + + break; + default: + break; + } + } + + if (i_nonce_len != dpp->nonce_len) { + l_debug("I-Nonce has unexpected length %zu", i_nonce_len); + goto auth_request_failed; + } + + memcpy(dpp->i_nonce, i_nonce, i_nonce_len); + + /* Derive keys k2, ke, and R-Auth for authentication response */ + + l_ecdh_generate_key_pair(dpp->curve, &dpp->proto_private, + &dpp->proto_public); + + n = dpp_derive_k2(dpp->i_proto_public, dpp->proto_private, dpp->k2); + if (!n) + goto auth_request_failed; + + l_getrandom(dpp->r_nonce, dpp->nonce_len); + + if (!dpp_derive_ke(dpp->i_nonce, dpp->r_nonce, m, n, dpp->ke)) + 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)) + goto auth_request_failed; + + memcpy(dpp->auth_addr, from, 6); + + dpp->state = DPP_STATE_AUTHENTICATING; + dpp_reset_protocol_timer(dpp); + + send_authenticate_response(dpp, r_auth); + + return; + +auth_request_failed: + dpp->state = DPP_STATE_PRESENCE; + dpp_free_auth_data(dpp); +} + +static void dpp_handle_frame(const struct mmpdu_header *frame, + const void *body, size_t body_len, + int rssi, void *user_data) +{ + struct dpp_sm *dpp = user_data; + const uint8_t *ptr; + + /* + * Both handlers offset by 8 bytes to reach the beginning of the DPP + * attributes. Easier checking this in one place, which also covers the + * frame type byte. + */ + if (body_len < 8) + return; + + ptr = body + 7; + + switch (*ptr) { + case DPP_FRAME_AUTHENTICATION_REQUEST: + authenticate_request(dpp, frame->address_2, body, body_len); + break; + case DPP_FRAME_AUTHENTICATION_CONFIRM: + authenticate_confirm(dpp, frame->address_2, body, body_len); + break; + case DPP_FRAME_CONFIGURATION_RESULT: + dpp_handle_config_result_frame(dpp, frame->address_2, + body, body_len); + break; + default: + l_debug("Unhandled DPP frame %u", *ptr); + break; + } +} + +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->pub_asn1, dpp->pub_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 presense annoucement on frequency %u and waiting %u", + dpp->current_freq, dpp->dwell); + + dpp_send_frame(netdev_get_wdev_id(netdev), iov, 2, dpp->current_freq); +} + +static void dpp_roc_started(void *user_data) +{ + struct dpp_sm *dpp = user_data; + + /* + * If not in presence procedure or in a configurator role, just stay + * on channel. + */ + if (dpp->state != DPP_STATE_PRESENCE || + dpp->role == DPP_CAPABILITY_CONFIGURATOR) + return; + + dpp_presence_announce(dpp); +} + +static void dpp_create(struct netdev *netdev) +{ + struct l_dbus *dbus = dbus_get_bus(); + struct dpp_sm *dpp = l_new(struct dpp_sm, 1); + uint8_t dpp_prefix[] = { 0x04, 0x09, 0x50, 0x6f, 0x9a, 0x1a, 0x01 }; + uint8_t dpp_conf_response_prefix[] = { 0x04, 0x0b }; + uint8_t dpp_conf_request_prefix[] = { 0x04, 0x0a }; + + dpp->netdev = netdev; + dpp->state = DPP_STATE_NOTHING; + dpp->wdev_id = netdev_get_wdev_id(netdev); + dpp->curve = l_ecc_curve_from_ike_group(19); + dpp->key_len = l_ecc_curve_get_scalar_bytes(dpp->curve); + dpp->nonce_len = dpp_nonce_len_from_key_len(dpp->key_len); + + 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_hash(L_CHECKSUM_SHA256, dpp->pub_boot_hash, 1, + dpp->pub_asn1, dpp->pub_asn1_len); + + l_dbus_object_add_interface(dbus, netdev_get_path(netdev), + IWD_DPP_INTERFACE, dpp); + + frame_watch_add(netdev_get_wdev_id(netdev), 0, 0x00d0, dpp_prefix, + sizeof(dpp_prefix), dpp_handle_frame, + dpp, NULL); + frame_watch_add(netdev_get_wdev_id(netdev), 0, 0x00d0, + dpp_conf_response_prefix, + sizeof(dpp_conf_response_prefix), + dpp_handle_config_response_frame, dpp, NULL); + frame_watch_add(netdev_get_wdev_id(netdev), 0, 0x00d0, + dpp_conf_request_prefix, + sizeof(dpp_conf_request_prefix), + dpp_handle_config_request_frame, dpp, NULL); +} + +static void dpp_netdev_watch(struct netdev *netdev, + enum netdev_watch_event event, void *userdata) +{ + switch (event) { + case NETDEV_WATCH_EVENT_NEW: + case NETDEV_WATCH_EVENT_UP: + if (netdev_get_iftype(netdev) == NETDEV_IFTYPE_STATION && + netdev_get_is_up(netdev)) + dpp_create(netdev); + break; + case NETDEV_WATCH_EVENT_DEL: + case NETDEV_WATCH_EVENT_DOWN: + l_dbus_object_remove_interface(dbus_get_bus(), + netdev_get_path(netdev), + IWD_DPP_INTERFACE); + break; + default: + break; + } +} + +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 + */ +static uint32_t *dpp_add_default_channels(struct dpp_sm *dpp, size_t *len_out) +{ + struct wiphy *wiphy = wiphy_find_by_wdev( + netdev_get_wdev_id(dpp->netdev)); + const struct scan_freq_set *list = wiphy_get_supported_freqs(wiphy); + uint32_t freq; + + if (!dpp->presence_list) + dpp->presence_list = scan_freq_set_new(); + + scan_freq_set_add(dpp->presence_list, band_channel_to_freq(6, + BAND_FREQ_2_4_GHZ)); + /* + * "5 GHz: Channel 44 (5.220 GHz) if local regulations permit operation + * only in the 5.150 - 5.250 GHz band and Channel 149 (5.745 GHz) + * otherwise" + */ + freq = band_channel_to_freq(149, BAND_FREQ_5_GHZ); + + if (scan_freq_set_contains(list, freq)) + scan_freq_set_add(dpp->presence_list, freq); + else + scan_freq_set_add(dpp->presence_list, + band_channel_to_freq(44, BAND_FREQ_5_GHZ)); + + /* TODO: 60GHz: Channel 2 */ + + return scan_freq_set_to_fixed_array(dpp->presence_list, len_out); +} + +/* + * TODO: There is an entire procedure defined in the spec where you increase + * the ROC timeout with each unsuccessful iteration of channels, wait on channel + * for long periods of time etc. Due to offchannel issues in the kernel this + * procedure is not being fully implemented. In reality doing this would result + * in quite terrible DPP performance anyways. + */ +static void dpp_start_presence(struct dpp_sm *dpp, uint32_t *limit_freqs, + size_t limit_len) +{ + uint32_t max_roc = wiphy_get_max_roc_duration( + wiphy_find_by_wdev(dpp->wdev_id)); + + if (2000 < max_roc) + max_roc = 2000; + + if (limit_freqs) { + dpp->freqs = l_memdup(limit_freqs, sizeof(uint32_t) * limit_len); + dpp->freqs_len = limit_len; + } else + dpp->freqs = dpp_add_default_channels(dpp, &dpp->freqs_len); + + dpp->dwell = max_roc; + dpp->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); +} + +static struct l_dbus_message *dpp_dbus_start_enrollee(struct l_dbus *dbus, + struct l_dbus_message *message, + void *user_data) +{ + struct dpp_sm *dpp = user_data; + uint32_t freq = band_channel_to_freq(6, BAND_FREQ_2_4_GHZ); + struct l_dbus_message *reply; + + if (dpp->state != DPP_STATE_NOTHING) + return dbus_error_busy(message); + + dpp->uri = dpp_generate_uri(dpp->pub_asn1, dpp->pub_asn1_len, 2, + netdev_get_address(dpp->netdev), &freq, + 1, NULL, NULL); + + dpp->state = DPP_STATE_PRESENCE; + dpp->role = DPP_CAPABILITY_ENROLLEE; + + l_debug("DPP Start Enrollee: %s", dpp->uri); + + /* + * Going off spec here. Select a single channel to send presence + * announcements on. This will be advertised in the URI. The full + * presence procedure can be implemented if it is ever needed. + */ + dpp_start_presence(dpp, &freq, 1); + + reply = l_dbus_message_new_method_return(message); + + l_dbus_message_set_arguments(reply, "s", dpp->uri); + + return reply; +} + +static struct l_dbus_message *dpp_dbus_start_configurator(struct l_dbus *dbus, + struct l_dbus_message *message, + void *user_data) +{ + struct dpp_sm *dpp = user_data; + struct l_dbus_message *reply; + struct station *station = station_find(netdev_get_ifindex(dpp->netdev)); + struct scan_bss *bss; + struct network *network; + struct l_settings *settings; + struct handshake_state *hs = netdev_get_handshake(dpp->netdev); + + /* + * For now limit the configurator to only configuring enrollees to the + * currently connected network. + */ + if (!station) + return dbus_error_not_available(message); + + bss = station_get_connected_bss(station); + network = station_get_connected_network(station); + if (!bss || !network) + return dbus_error_not_connected(message); + + settings = network_get_settings(network); + if (!settings) + return dbus_error_not_configured(message); + + if (network_get_security(network) != SECURITY_PSK) + return dbus_error_not_supported(message); + + if (dpp->state != DPP_STATE_NOTHING) + return dbus_error_busy(message); + + dpp->uri = dpp_generate_uri(dpp->pub_asn1, dpp->pub_asn1_len, 2, + netdev_get_address(dpp->netdev), + &bss->frequency, 1, NULL, NULL); + + dpp->state = DPP_STATE_PRESENCE; + dpp->role = DPP_CAPABILITY_CONFIGURATOR; + dpp->current_freq = bss->frequency; + dpp->config = dpp_configuration_new(settings, + network_get_ssid(network), + hs->akm_suite); + + l_debug("DPP Start Configurator: %s", dpp->uri); + + reply = l_dbus_message_new_method_return(message); + + l_dbus_message_set_arguments(reply, "s", dpp->uri); + + return reply; +} + +static struct l_dbus_message *dpp_dbus_stop(struct l_dbus *dbus, + struct l_dbus_message *message, + void *user_data) +{ + struct dpp_sm *dpp = user_data; + + dpp_reset(dpp); + + return l_dbus_message_new_method_return(message); +} + +static void dpp_setup_interface(struct l_dbus_interface *interface) +{ + l_dbus_interface_method(interface, "StartEnrollee", 0, + dpp_dbus_start_enrollee, "s", "", "uri"); + l_dbus_interface_method(interface, "StartConfigurator", 0, + dpp_dbus_start_configurator, "s", "", "uri"); + l_dbus_interface_method(interface, "Stop", 0, + dpp_dbus_stop, "", ""); +} + +static void dpp_destroy_interface(void *user_data) +{ + struct dpp_sm *dpp = user_data; + + dpp_free(dpp); +} + +static int dpp_init(void) +{ + nl80211 = l_genl_family_new(iwd_get_genl(), NL80211_GENL_NAME); + if (!nl80211) { + l_error("Failed to obtain nl80211"); + return -EIO; + } + + netdev_watch = netdev_watch_add(dpp_netdev_watch, NULL, NULL); + + l_dbus_register_interface(dbus_get_bus(), IWD_DPP_INTERFACE, + dpp_setup_interface, + dpp_destroy_interface, false); + return 0; +} + +static void dpp_exit(void) +{ + l_debug(""); + + netdev_watch_remove(netdev_watch); +} + +IWD_MODULE(dpp, dpp_init, dpp_exit); +IWD_MODULE_DEPENDS(dpp, netdev); diff --git a/src/handshake.c b/src/handshake.c @@ -115,6 +115,7 @@ void handshake_state_free(struct handshake_state *s) l_free(s->fte); l_free(s->fils_ip_req_ie); l_free(s->fils_ip_resp_ie); + l_free(s->vendor_ies); if (s->erp_cache) erp_cache_put(s->erp_cache); diff --git a/src/ie.h b/src/ie.h @@ -292,6 +292,7 @@ enum ie_vendor_wfa_oi_type { IE_WFA_OI_OSEN = 0x12, IE_WFA_OI_OWE_TRANSITION = 0x1c, IE_WFA_OI_ROAMING_SELECTION = 0x1d, + IE_WFA_OI_CONFIGURATOR_CONNECTIVITY = 0x1e, }; enum ie_advertisement_id { diff --git a/src/json.c b/src/json.c @@ -0,0 +1,270 @@ +/* + * + * Wireless daemon for Linux + * + * Copyright (C) 2021 Intel Corporation. All rights reserved. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <errno.h> + +#include <ell/ell.h> + +#include "src/json.h" + +#include "shared/jsmn.h" + +/* Max number of tokens supported. Increase if larger objects are expected */ +#define JSON_DEFAULT_TOKENS 30 + +#define TOK_LEN(token) (token)->end - (token)->start +#define TOK_PTR(json, token) (void *)((json) + (token)->start) +#define TOK_TO_STR(json, token) \ +({ \ + char *_tmp = l_malloc(TOK_LEN((token)) + 1); \ + memcpy(_tmp, TOK_PTR((json), (token)), TOK_LEN((token))); \ + _tmp[TOK_LEN((token))] = '\0'; \ + _tmp; \ +}) + +#define ITER_END(iter) \ + (((iter)->contents->tokens + (iter)->start) + (iter)->count) + +struct json_contents { + const char *json; + size_t json_len; + jsmntok_t *tokens; + int tokens_len; + jsmn_parser *p; +}; + +static jsmntok_t *next_key_in_parent(struct json_iter *iter, jsmntok_t *current) +{ + int parent = current->parent; + + /* iterate the list and stop on the first token with the same parent */ + while (++current < ITER_END(iter)) { + if (current->parent == parent) + return 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) +{ + jsmntok_t *next = next_key_in_parent(iter, object - 1); + + /* End of token list */ + if (!next) + next = ITER_END(iter); + + return next - object - 1; +} + +static void iter_recurse(struct json_iter *iter, jsmntok_t *object, + 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); +} + +struct json_contents *json_contents_new(const char *json, size_t json_len) +{ + struct json_contents *c = l_new(struct json_contents, 1); + + c->json = json; + c->json_len = json_len; + c->p = l_new(jsmn_parser, 1); + c->tokens = l_new(jsmntok_t, JSON_DEFAULT_TOKENS); + + jsmn_init(c->p); + c->tokens_len = jsmn_parse(c->p, c->json, c->json_len, + c->tokens, JSON_DEFAULT_TOKENS); + if (c->tokens_len < 0) { + json_contents_free(c); + return NULL; + } + + return c; +} + +void json_iter_init(struct json_iter *iter, struct json_contents *c) +{ + iter->contents = c; + iter->start = 0; + iter->count = c->tokens_len; +} + +void json_contents_free(struct json_contents *c) +{ + l_free(c->p); + l_free(c->tokens); + l_free(c); +} + +struct json_arg { + enum json_type type; + void *value; + jsmntok_t *v; +}; + +static void push_arg(struct l_queue *q, enum json_type type, + void *value, jsmntok_t *v) +{ + struct json_arg *arg = l_new(struct json_arg, 1); + + arg->type = type; + arg->value = value; + arg->v = v; + + l_queue_push_head(q, arg); +} + +static void assign_arg(void *data, void *user_data) +{ + struct json_iter *iter = user_data; + struct json_arg *arg = data; + struct json_contents *c = iter->contents; + char **sval; + struct json_iter *oval; + + switch (arg->type) { + case JSON_STRING: + sval = arg->value; + + *sval = arg->v ? TOK_TO_STR(c->json, arg->v) : NULL; + + break; + case JSON_OBJECT: + oval = arg->value; + + if (!arg->v) + oval->start = -1; + else + iter_recurse(iter, arg->v, oval); + + break; + default: + /* Types are verified earlier, this should never happen */ + return; + } + + l_free(arg); +} + +bool json_iter_parse(struct json_iter *iter, enum json_type type, ...) +{ + struct json_contents *c = iter->contents; + va_list va; + int i; + int num = c->tokens->size; + jsmntok_t *next; + struct l_queue *args; + + if (iter->start == -1) + return false; + + args = l_queue_new(); + + va_start(va, type); + + while (true) { + enum json_flag flag; + char *key; + void *value; + jsmntok_t *v = NULL; + void *ptr; + size_t len; + + /* Check the type is supported before wasting any cycles */ + switch (type) { + case JSON_UNDEFINED: + goto done; + case JSON_STRING: + case JSON_OBJECT: + break; + default: + goto error; + } + + key = va_arg(va, char *); + value = va_arg(va, void *); + flag = va_arg(va, enum json_flag); + + /* First key */ + next = c->tokens + iter->start + 1; + + /* Iterate over this objects keys */ + for (i = 0; i < num; i++) { + ptr = TOK_PTR(c->json, next); + len = TOK_LEN(next); + + if (next + 1 > ITER_END(iter)) + goto error; + + if (strlen(key) == len && !memcmp(ptr, key, len)) { + /* Key found but the wrong value type */ + if ((next + 1)->type != (jsmntype_t)type) + goto error; + + v = next + 1; + break; + } + + next = next_key_in_parent(iter, next); + if (!next) + break; + } + + if (flag == JSON_FLAG_MANDATORY && !v) + goto error; + + /* + * Still push even if an optional value doesn't exist (!v) so + * the caller can check if it was found or not. + */ + if (value) + push_arg(args, type, value, v); + + type = va_arg(va, enum json_type); + } + +done: + va_end(va); + + l_queue_foreach(args, assign_arg, iter); + l_queue_destroy(args, NULL); + + return true; + +error: + l_queue_destroy(args, l_free); + return false; +} diff --git a/src/json.h b/src/json.h @@ -0,0 +1,83 @@ +/* + * + * Wireless daemon for Linux + * + * Copyright (C) 2021 Intel Corporation. All rights reserved. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +struct json_iter; + +/* + * Identical to JSMN types + */ +enum json_type { + JSON_UNDEFINED = 0, + JSON_OBJECT = 1, + JSON_ARRAY = 2, + JSON_STRING = 3, + JSON_PRIMITIVE = 4 +}; + +enum json_flag { + JSON_FLAG_MANDATORY = 1, + JSON_FLAG_OPTIONAL = 2, +}; + +struct json_iter { + struct json_contents *contents; + int start; + int count; +}; + +#define JSON_MANDATORY(key, type, out) \ + (type), (key), (out), JSON_FLAG_MANDATORY + +#define JSON_OPTIONAL(key, type, out) \ + (type), (key), (out), JSON_FLAG_OPTIONAL + +#define json_iter_is_valid(iter) ((iter)->start != -1) + +struct json_contents *json_contents_new(const char *json, size_t json_len); +void json_contents_free(struct json_contents *c); + +void json_iter_init(struct json_iter *iter, struct json_contents *c); + +/* + * Parse an arbitrary number of key/value pairs from a JSON iterator. Initially + * a new JSON contents object should be created with json_contents_new() and, + * when done, freed with json_contents_free. + * + * Iterators can be initialized with the json_contents object. Nested object + * iterators are also parsed with this function. + * + * 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); + * + * String values should be of type char ** and must be freed + * Object values should be of type struct json_iter * + * + * 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. + */ +bool json_iter_parse(struct json_iter *iter, enum json_type type, ...); diff --git a/src/netdev.c b/src/netdev.c @@ -1165,8 +1165,7 @@ static void netdev_disconnect_event(struct l_genl_msg *msg, l_debug(""); - if (!netdev->connected || netdev->disconnect_cmd_id > 0 || - netdev->in_ft || netdev->in_reassoc) + if (!netdev->connected || netdev->disconnect_cmd_id > 0) return; if (!l_genl_attr_init(&attr, msg)) { @@ -1190,6 +1189,13 @@ static void netdev_disconnect_event(struct l_genl_msg *msg, } } + /* + * Only ignore this event if issued by the kernel since this is + * normal when using CMD_AUTH/ASSOC. + */ + if (!disconnect_by_ap && (netdev->in_ft || netdev->in_reassoc)) + return; + l_info("Received Deauthentication event, reason: %hu, from_ap: %s", reason_code, disconnect_by_ap ? "true" : "false"); @@ -3171,6 +3177,7 @@ static void netdev_associate_event(struct l_genl_msg *msg, if (!netdev->ap) { netdev->associated = true; + netdev->in_reassoc = false; return; } @@ -3386,7 +3393,19 @@ static void netdev_sae_tx_authenticate(const uint8_t *body, return; } - netdev->auth_cmd = l_genl_msg_ref(msg); + /* + * Sometimes due to the way the scheduling works out, netdev_auth_cb + * is sent after the SAE Authentication reply from the AP arrives. + * Do not leak auth_cmd if this occurs. Note that if auth_cmd is not + * NULL and we are here, there's no further reason to save off auth_cmd. + * This is done only if the kernel's cache lacks the BSS we are trying + * to communicate with. + */ + if (netdev->auth_cmd) { + l_genl_msg_unref(netdev->auth_cmd); + netdev->auth_cmd = NULL; + } else + netdev->auth_cmd = l_genl_msg_ref(msg); } static void netdev_sae_tx_associate(void *user_data) @@ -3443,7 +3462,12 @@ static void netdev_fils_tx_authenticate(const uint8_t *body, return; } - netdev->auth_cmd = l_genl_msg_ref(msg); + /* See comment in netdev_sae_tx_authenticate */ + if (netdev->auth_cmd) { + l_genl_msg_unref(netdev->auth_cmd); + netdev->auth_cmd = NULL; + } else + netdev->auth_cmd = l_genl_msg_ref(msg); } static void netdev_fils_tx_associate(struct iovec *fils_iov, size_t n_fils_iov, @@ -4181,7 +4205,7 @@ int netdev_join_adhoc(struct netdev *netdev, const char *ssid, { struct l_genl_msg *cmd; uint32_t ifindex = netdev->index; - uint32_t ch_freq = scan_channel_to_freq(6, SCAN_BAND_2_4_GHZ); + uint32_t ch_freq = band_channel_to_freq(6, BAND_FREQ_2_4_GHZ); uint32_t ch_type = NL80211_CHAN_HT20; if (netdev->type != NL80211_IFTYPE_ADHOC) { diff --git a/src/offchannel.c b/src/offchannel.c @@ -0,0 +1,323 @@ +/* + * + * Wireless daemon for Linux + * + * Copyright (C) 2021 Intel Corporation. All rights reserved. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <errno.h> + +#include <ell/ell.h> + +#include "linux/nl80211.h" + +#include "src/offchannel.h" +#include "src/wiphy.h" +#include "src/nl80211util.h" +#include "src/iwd.h" +#include "src/module.h" + +struct offchannel_info { + uint64_t wdev_id; + uint32_t freq; + uint32_t duration; + + uint32_t roc_cmd_id; + uint64_t roc_cookie; + + offchannel_started_cb_t started; + offchannel_destroy_cb_t destroy; + void *user_data; + int error; + + struct wiphy_radio_work_item work; + + bool needs_cancel : 1; +}; + +static struct l_genl_family *nl80211; +static struct l_queue *offchannel_list; + +static bool match_wdev(const void *a, const void *user_data) +{ + const struct offchannel_info *info = a; + const uint64_t *wdev_id = user_data; + + return info->wdev_id == *wdev_id; +} + +static void offchannel_cancel_roc(struct offchannel_info *info) +{ + struct l_genl_msg *msg; + + msg = l_genl_msg_new(NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL); + + l_genl_msg_append_attr(msg, NL80211_ATTR_WDEV, 8, &info->wdev_id); + l_genl_msg_append_attr(msg, NL80211_ATTR_COOKIE, 8, &info->roc_cookie); + + /* Nothing much can be done if this fails */ + if (!l_genl_family_send(nl80211, msg, NULL, NULL, NULL)) + l_genl_msg_unref(msg); +} + +static void offchannel_roc_cb(struct l_genl_msg *msg, void *user_data) +{ + struct offchannel_info *info = user_data; + + info->error = l_genl_msg_get_error(msg); + info->roc_cmd_id = 0; + + if (info->error < 0) { + l_debug("Error from CMD_REMAIN_ON_CHANNEL (%d)", info->error); + goto work_done; + } + + info->error = nl80211_parse_attrs(msg, NL80211_ATTR_COOKIE, + &info->roc_cookie, NL80211_ATTR_UNSPEC); + if (info->error < 0) { + l_error("Could not parse ROC cookie"); + goto work_done; + } + + /* This request was cancelled, and ROC needs to be cancelled */ + if (info->needs_cancel) + offchannel_cancel_roc(info); + + return; + +work_done: + wiphy_radio_work_done(wiphy_find_by_wdev(info->wdev_id), info->work.id); +} + +static bool offchannel_work_ready(struct wiphy_radio_work_item *item) +{ + struct l_genl_msg *msg; + struct offchannel_info *info = l_container_of(item, + struct offchannel_info, work); + + msg = l_genl_msg_new(NL80211_CMD_REMAIN_ON_CHANNEL); + + l_genl_msg_append_attr(msg, NL80211_ATTR_WDEV, 8, &info->wdev_id); + l_genl_msg_append_attr(msg, NL80211_ATTR_WIPHY_FREQ, 4, &info->freq); + l_genl_msg_append_attr(msg, NL80211_ATTR_DURATION, 4, &info->duration); + + info->roc_cmd_id = l_genl_family_send(nl80211, msg, offchannel_roc_cb, + info, NULL); + if (!info->roc_cmd_id) { + info->error = -EIO; + l_genl_msg_unref(msg); + return true; + } + + l_queue_push_head(offchannel_list, info); + + return false; +} + +static void offchannel_work_destroy(struct wiphy_radio_work_item *item) +{ + struct offchannel_info *info = l_container_of(item, + struct offchannel_info, work); + + if (info->destroy) + info->destroy(info->error, info->user_data); + + l_queue_remove(offchannel_list, info); + l_free(info); +} + +static const struct wiphy_radio_work_item_ops offchannel_work_ops = { + .do_work = offchannel_work_ready, + .destroy = offchannel_work_destroy, +}; + +uint32_t offchannel_start(uint64_t wdev_id, uint32_t freq, uint32_t duration, + offchannel_started_cb_t started, void *user_data, + offchannel_destroy_cb_t destroy) +{ + struct offchannel_info *info = l_new(struct offchannel_info, 1); + + info->wdev_id = wdev_id; + info->freq = freq; + info->duration = duration; + info->started = started; + info->destroy = destroy; + info->user_data = user_data; + /* + * Set error as cancelled in case this work gets cancelled prior to + * the wiphy work starting. + */ + info->error = -ECANCELED; + + return wiphy_radio_work_insert(wiphy_find_by_wdev(wdev_id), + &info->work, 1, &offchannel_work_ops); +} + +void offchannel_cancel(uint64_t wdev_id, uint32_t id) +{ + struct wiphy *wiphy = wiphy_find_by_wdev(wdev_id); + struct offchannel_info *info; + int ret; + + if (!wiphy) + return; + + /* + * Exit if work does not exist, if it hasn't started 'done' the work, + * otherwise decide how the work needs to be canceled. + */ + ret = wiphy_radio_work_is_running(wiphy, id); + if (ret < 0) + return; + else if (ret == false) + goto work_done; + + info = l_queue_find(offchannel_list, match_wdev, &wdev_id); + if (!info) + return; + + if (info->roc_cmd_id) { + /* + * If the command hasn't left the genl queue it can be cancelled + * without any further action. Otherwise command has been sent + * to the kernel and we must wait until ROC starts and cancel at + * that time. + */ + if (!l_genl_family_request_sent(nl80211, info->roc_cmd_id)) { + l_genl_family_cancel(nl80211, info->roc_cmd_id); + info->roc_cmd_id = 0; + goto work_done; + } + + /* Lets the ROC callback know it needs to cancel the request */ + info->needs_cancel = true; + + goto destroy; + } + + /* + * Something weird must have happened on the kernel side. This error + * will already be handled in offchannel_roc_cb but warn here to inform + * the user. + */ + if (L_WARN_ON(!info->roc_cookie)) + return; + + /* + * At this point we know ROC has at least been queued (potentially not + * started) and can be cancelled. The work will be completed once the + * kernel sends the cancel ROC event. + */ + offchannel_cancel_roc(info); + +destroy: + if (info->destroy) + info->destroy(-ECANCELED, info->user_data); + + info->destroy = NULL; + info->started = NULL; + info->user_data = NULL; + + return; + +work_done: + wiphy_radio_work_done(wiphy, id); +} + +static void offchannel_mlme_notify(struct l_genl_msg *msg, void *user_data) +{ + struct offchannel_info *info; + uint64_t wdev_id; + uint64_t cookie; + uint8_t cmd; + + cmd = l_genl_msg_get_command(msg); + + if (cmd != NL80211_CMD_REMAIN_ON_CHANNEL && + cmd != NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL) + return; + + if (nl80211_parse_attrs(msg, NL80211_ATTR_WDEV, &wdev_id, + NL80211_ATTR_COOKIE, &cookie, + NL80211_ATTR_UNSPEC) < 0) + return; + + info = l_queue_find(offchannel_list, match_wdev, &wdev_id); + if (!info) + return; + + /* ROC must have been started elsewhere, not by IWD */ + if (info->roc_cookie != cookie) + return; + + switch (cmd) { + case NL80211_CMD_REMAIN_ON_CHANNEL: + if (info->started) + info->started(info->user_data); + + break; + case NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL: + info->error = 0; + + wiphy_radio_work_done(wiphy_find_by_wdev(info->wdev_id), + info->work.id); + break; + default: + return; + } +} + +static int offchannel_init(void) +{ + struct l_genl *genl = iwd_get_genl(); + + nl80211 = l_genl_family_new(genl, NL80211_GENL_NAME); + if (!nl80211) { + l_error("Failed to obtain nl80211"); + return -EIO; + } + + if (!l_genl_family_register(nl80211, "mlme", offchannel_mlme_notify, + NULL, NULL)) { + l_error("Failed to register for MLME"); + l_genl_family_free(nl80211); + nl80211 = NULL; + + return -EIO; + } + + offchannel_list = l_queue_new(); + + return 0; +} + +static void offchannel_exit(void) +{ + l_debug(""); + + l_genl_family_free(nl80211); + nl80211 = NULL; + + l_queue_destroy(offchannel_list, l_free); +} + +IWD_MODULE(offchannel, offchannel_init, offchannel_exit); diff --git a/src/offchannel.h b/src/offchannel.h @@ -0,0 +1,29 @@ +/* + * + * Wireless daemon for Linux + * + * Copyright (C) 2021 Intel Corporation. All rights reserved. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +typedef void (*offchannel_started_cb_t)(void *user_data); +typedef void (*offchannel_destroy_cb_t)(int error, void *user_data); + +uint32_t offchannel_start(uint64_t wdev_id, uint32_t freq, uint32_t duration, + offchannel_started_cb_t started, void *user_data, + offchannel_destroy_cb_t destroy); +void offchannel_cancel(uint64_t wdev_id, uint32_t id); diff --git a/src/p2p.c b/src/p2p.c @@ -61,6 +61,7 @@ #include "src/netconfig.h" #include "src/ap.h" #include "src/p2p.h" +#include "src/band.h" struct p2p_device { uint64_t wdev_id; @@ -808,7 +809,7 @@ static void p2p_peer_frame_xchg(struct p2p_peer *peer, struct iovec *tx_body, memcpy(frame + 1, tx_body, sizeof(struct iovec) * iov_cnt); freq = own_channel ? - scan_channel_to_freq(dev->listen_channel, SCAN_BAND_2_4_GHZ) : + band_channel_to_freq(dev->listen_channel, BAND_FREQ_2_4_GHZ) : peer->bss->frequency; va_start(args, cb); @@ -2098,14 +2099,14 @@ static void p2p_add_freq_func(uint32_t freq, void *user_data) { struct p2p_channel_entries *channel_entry = user_data; uint8_t channel; - enum scan_band band; + enum band_freq band; if (channel_entry->n_channels >= MAX_CHANNELS) return; - channel = scan_freq_to_channel(freq, &band); + channel = band_freq_to_channel(freq, &band); - if (band != scan_oper_class_to_band((const uint8_t *) "XX\x4", + if (band != band_oper_class_to_band((const uint8_t *) "XX\x4", channel_entry->oper_class)) return; @@ -2225,10 +2226,10 @@ static bool p2p_go_negotiation_confirm_cb(const struct mmpdu_header *mpdu, */ p2p_device_interface_create(dev); } else { - enum scan_band band = scan_oper_class_to_band( + enum band_freq band = band_oper_class_to_band( (const uint8_t *) info.operating_channel.country, info.operating_channel.oper_class); - uint32_t frequency = scan_channel_to_freq( + uint32_t frequency = band_channel_to_freq( info.operating_channel.channel_num, band); @@ -2594,7 +2595,7 @@ static bool p2p_go_negotiation_resp_cb(const struct mmpdu_header *mpdu, int r; struct iovec iov[16]; int iov_len = 0; - enum scan_band band; + enum band_freq band; uint32_t frequency; l_debug(""); @@ -2747,10 +2748,10 @@ static bool p2p_go_negotiation_resp_cb(const struct mmpdu_header *mpdu, memcpy(&confirm_info.group_id, &dev->go_group_id, sizeof(struct p2p_group_id_attr)); } else { - band = scan_oper_class_to_band( + band = band_oper_class_to_band( (const uint8_t *) resp_info.operating_channel.country, resp_info.operating_channel.oper_class); - frequency = scan_channel_to_freq( + frequency = band_channel_to_freq( resp_info.operating_channel.channel_num, band); if (!frequency) { @@ -3448,8 +3449,8 @@ static void p2p_device_roc_start(struct p2p_device *dev) * channel than on any other channel and then we listen for a * potential GO Negotiation restart on our listen channel. */ - listen_freq = scan_channel_to_freq(dev->listen_channel, - SCAN_BAND_2_4_GHZ); + listen_freq = band_channel_to_freq(dev->listen_channel, + BAND_FREQ_2_4_GHZ); msg = l_genl_msg_new_sized(NL80211_CMD_REMAIN_ON_CHANNEL, 64); l_genl_msg_append_attr(msg, NL80211_ATTR_WDEV, 8, &dev->wdev_id); @@ -3813,7 +3814,7 @@ static bool p2p_device_scan_start(struct p2p_device *dev) for (i = 0; i < L_ARRAY_SIZE(channels_social); i++) { int chan = channels_social[i]; - uint32_t freq = scan_channel_to_freq(chan, SCAN_BAND_2_4_GHZ); + uint32_t freq = band_channel_to_freq(chan, BAND_FREQ_2_4_GHZ); scan_freq_set_add(params.freqs, freq); } @@ -3830,7 +3831,7 @@ static bool p2p_device_scan_start(struct p2p_device *dev) for (i = 0; i < dev->chans_per_scan; i++) { int idx = dev->scan_chan_idx++; int chan = channels_scan_2_4_other[idx]; - uint32_t freq = scan_channel_to_freq(chan, SCAN_BAND_2_4_GHZ); + uint32_t freq = band_channel_to_freq(chan, BAND_FREQ_2_4_GHZ); if (dev->scan_chan_idx >= L_ARRAY_SIZE(channels_scan_2_4_other)) { @@ -4001,7 +4002,7 @@ static void p2p_device_send_probe_resp(struct p2p_device *dev, iov[iov_len].iov_base = NULL; - freq = scan_channel_to_freq(dev->listen_channel, SCAN_BAND_2_4_GHZ); + freq = band_channel_to_freq(dev->listen_channel, BAND_FREQ_2_4_GHZ); frame_xchg_start(dev->wdev_id, iov, freq, 0, 0, false, 0, p2p_probe_resp_done, dev, NULL, NULL); l_debug("Probe Response tx queued"); @@ -4023,7 +4024,7 @@ static void p2p_device_probe_cb(const struct mmpdu_header *mpdu, ssize_t wsc_len; struct scan_bss *bss; struct p2p_channel_attr *channel; - enum scan_band band; + enum band_freq band; uint32_t frequency; bool from_conn_peer; @@ -4086,9 +4087,9 @@ static void p2p_device_probe_cb(const struct mmpdu_header *mpdu, else goto p2p_free; - band = scan_oper_class_to_band((const uint8_t *) channel->country, + band = band_oper_class_to_band((const uint8_t *) channel->country, channel->oper_class); - frequency = scan_channel_to_freq(channel->channel_num, band); + frequency = band_channel_to_freq(channel->channel_num, band); if (!frequency) goto p2p_free; diff --git a/src/rrm.c b/src/rrm.c @@ -41,6 +41,7 @@ #include "src/nl80211util.h" #include "src/wiphy.h" #include "src/frame-xchg.h" +#include "src/band.h" #include "linux/nl80211.h" @@ -278,7 +279,7 @@ static size_t build_report_for_bss(struct rrm_beacon_req_info *beacon, struct rrm_beacon_report *report = (struct rrm_beacon_report *) to; report->oper_class = beacon->oper_class; - report->channel = scan_freq_to_channel(bss->frequency, NULL); + report->channel = band_freq_to_channel(bss->frequency, NULL); report->scan_start_time = L_CPU_TO_LE64(beacon->scan_start_time); report->duration = L_CPU_TO_LE16(beacon->duration); report->frame_info = rrm_phy_type(bss); @@ -310,7 +311,7 @@ static size_t build_report_for_bss(struct rrm_beacon_req_info *beacon, static bool bss_in_request_range(struct rrm_beacon_req_info *beacon, struct scan_bss *bss) { - uint8_t channel = scan_freq_to_channel(bss->frequency, NULL); + uint8_t channel = band_freq_to_channel(bss->frequency, NULL); /* Must be a table measurement */ if (beacon->channel == 0 || beacon->channel == 255) @@ -436,10 +437,10 @@ static void rrm_handle_beacon_scan(struct rrm_state *rrm, .duration = beacon->duration, .duration_mandatory = test_bit(&beacon->info.mode, 4), }; - enum scan_band band = scan_oper_class_to_band(NULL, beacon->oper_class); + enum band_freq band = band_oper_class_to_band(NULL, beacon->oper_class); uint32_t freq; - freq = scan_channel_to_freq(beacon->channel, band); + freq = band_channel_to_freq(beacon->channel, band); scan_freq_set_add(freqs, freq); if (passive) @@ -485,7 +486,7 @@ static bool rrm_verify_beacon_request(const uint8_t *request, size_t len) } /* Check this is a valid operating class */ - if (!scan_oper_class_to_band(NULL, request[0])) + if (!band_oper_class_to_band(NULL, request[0])) return false; return true; diff --git a/src/scan.c b/src/scan.c @@ -1097,6 +1097,9 @@ static void scan_parse_vendor_specific(struct scan_bss *bss, const void *data, return; } + if (is_ie_wfa_ie(data, len, IE_WFA_OI_CONFIGURATOR_CONNECTIVITY)) + bss->dpp_configurator = true; + if (!ie_parse_network_cost(data, len, &cost_level, &cost_flags)) { bss->cost_level = cost_level; bss->cost_flags = cost_flags; @@ -2014,359 +2017,6 @@ bool scan_get_firmware_scan(uint64_t wdev_id, scan_notify_func_t notify, return true; } -uint8_t scan_freq_to_channel(uint32_t freq, enum scan_band *out_band) -{ - uint32_t channel = 0; - - if (freq >= 2412 && freq <= 2484) { - if (freq == 2484) - channel = 14; - else { - channel = freq - 2407; - - if (channel % 5) - return 0; - - channel /= 5; - } - - if (out_band) - *out_band = SCAN_BAND_2_4_GHZ; - - return channel; - } - - if (freq >= 5005 && freq < 5900) { - if (freq % 5) - return 0; - - channel = (freq - 5000) / 5; - - if (out_band) - *out_band = SCAN_BAND_5_GHZ; - - return channel; - } - - if (freq >= 4905 && freq < 5000) { - if (freq % 5) - return 0; - - channel = (freq - 4000) / 5; - - if (out_band) - *out_band = SCAN_BAND_5_GHZ; - - return channel; - } - - return 0; -} - -uint32_t scan_channel_to_freq(uint8_t channel, enum scan_band band) -{ - if (band == SCAN_BAND_2_4_GHZ) { - if (channel >= 1 && channel <= 13) - return 2407 + 5 * channel; - - if (channel == 14) - return 2484; - } - - if (band == SCAN_BAND_5_GHZ) { - if (channel >= 1 && channel <= 179) - return 5000 + 5 * channel; - - if (channel >= 181 && channel <= 199) - return 4000 + 5 * channel; - } - - return 0; -} - -static const char *const oper_class_us_codes[] = { - "US", "CA" -}; - -static const char *const oper_class_eu_codes[] = { - "AL", "AM", "AT", "AZ", "BA", "BE", "BG", "BY", "CH", "CY", "CZ", "DE", - "DK", "EE", "EL", "ES", "FI", "FR", "GE", "HR", "HU", "IE", "IS", "IT", - "LI", "LT", "LU", "LV", "MD", "ME", "MK", "MT", "NL", "NO", "PL", "PT", - "RO", "RS", "RU", "SE", "SI", "SK", "TR", "UA", "UK" -}; - -/* Annex E, table E-1 */ -static const uint8_t oper_class_us_to_global[] = { - [1] = 115, [2] = 118, [3] = 124, [4] = 121, - [5] = 125, [6] = 103, [7] = 103, [8] = 102, - [9] = 102, [10] = 101, [11] = 101, [12] = 81, - [13] = 94, [14] = 95, [15] = 96, [22] = 116, - [23] = 119, [24] = 122, [25] = 126, [26] = 126, - [27] = 117, [28] = 120, [29] = 123, [30] = 127, - [31] = 127, [32] = 83, [33] = 84, [34] = 180, - /* 128 - 130 is a 1 to 1 mapping */ -}; - -/* Annex E, table E-2 */ -static const uint8_t oper_class_eu_to_global[] = { - [1] = 115, [2] = 118, [3] = 121, [4] = 81, - [5] = 116, [6] = 119, [7] = 122, [8] = 117, - [9] = 120, [10] = 123, [11] = 83, [12] = 84, - [17] = 125, [18] = 130, - /* 128 - 130 is a 1 to 1 mapping */ -}; - -/* Annex E, table E-3 */ -static const uint8_t oper_class_jp_to_global[] = { - [1] = 115, [2] = 112, [3] = 112, [4] = 112, - [5] = 112, [6] = 112, [7] = 109, [8] = 109, - [9] = 109, [10] = 109, [11] = 109, [12] = 113, - [13] = 113, [14] = 113, [15] = 113, [16] = 110, - [17] = 110, [18] = 110, [19] = 110, [20] = 110, - [21] = 114, [22] = 114, [23] = 114, [24] = 114, - [25] = 111, [26] = 111, [27] = 111, [28] = 111, - [29] = 111, [30] = 81, [31] = 82, [32] = 118, - [33] = 118, [34] = 121, [35] = 121, [36] = 116, - [37] = 119, [38] = 119, [39] = 122, [40] = 122, - [41] = 117, [42] = 120, [43] = 120, [44] = 123, - [45] = 123, [46] = 104, [47] = 104, [48] = 104, - [49] = 104, [50] = 104, [51] = 105, [52] = 105, - [53] = 105, [54] = 105, [55] = 105, [56] = 83, - [57] = 84, [58] = 121, [59] = 180, - /* 128 - 130 is a 1 to 1 mapping */ -}; - -/* Annex E, table E-4 (only 2.4GHz and 4.9 / 5GHz bands) */ -static const enum scan_band oper_class_to_band_global[] = { - [81 ... 84] = SCAN_BAND_2_4_GHZ, - [104 ... 130] = SCAN_BAND_5_GHZ, -}; - -/* Annex E, table E-5 */ -static const uint8_t oper_class_cn_to_global[] = { - [1] = 115, [2] = 118, [3] = 125, [4] = 116, - [5] = 119, [6] = 126, [7] = 81, [8] = 83, - [9] = 84, - /* 128 - 130 is a 1 to 1 mapping */ -}; - -enum scan_band scan_oper_class_to_band(const uint8_t *country, - uint8_t oper_class) -{ - unsigned int i; - int table = 0; - - if (country && country[2] >= 1 && country[2] <= 5) - table = country[2]; - else if (country) { - for (i = 0; i < L_ARRAY_SIZE(oper_class_us_codes); i++) - if (!memcmp(oper_class_us_codes[i], country, 2)) { - /* Use table E-1 */ - table = 1; - break; - } - - for (i = 0; i < L_ARRAY_SIZE(oper_class_eu_codes); i++) - if (!memcmp(oper_class_eu_codes[i], country, 2)) { - /* Use table E-2 */ - table = 2; - break; - } - - if (!memcmp("JP", country, 2)) - /* Use table E-3 */ - table = 3; - - if (!memcmp("CN", country, 2)) - /* Use table E-5 */ - table = 5; - } - - switch (table) { - case 1: - if (oper_class < L_ARRAY_SIZE(oper_class_us_to_global)) - oper_class = oper_class_us_to_global[oper_class]; - break; - case 2: - if (oper_class < L_ARRAY_SIZE(oper_class_eu_to_global)) - oper_class = oper_class_eu_to_global[oper_class]; - break; - case 3: - if (oper_class < L_ARRAY_SIZE(oper_class_jp_to_global)) - oper_class = oper_class_jp_to_global[oper_class]; - break; - case 5: - if (oper_class < L_ARRAY_SIZE(oper_class_cn_to_global)) - oper_class = oper_class_cn_to_global[oper_class]; - break; - } - - if (oper_class < L_ARRAY_SIZE(oper_class_to_band_global)) - return oper_class_to_band_global[oper_class]; - else - return 0; -} - -struct scan_freq_set { - uint16_t channels_2ghz; - struct l_uintset *channels_5ghz; -}; - -struct scan_freq_set *scan_freq_set_new(void) -{ - struct scan_freq_set *ret = l_new(struct scan_freq_set, 1); - - /* 802.11-2012, 8.4.2.10 hints that 200 is the largest channel number */ - ret->channels_5ghz = l_uintset_new_from_range(1, 200); - - return ret; -} - -void scan_freq_set_free(struct scan_freq_set *freqs) -{ - l_uintset_free(freqs->channels_5ghz); - l_free(freqs); -} - -bool scan_freq_set_add(struct scan_freq_set *freqs, uint32_t freq) -{ - enum scan_band band; - uint8_t channel; - - channel = scan_freq_to_channel(freq, &band); - if (!channel) - return false; - - switch (band) { - case SCAN_BAND_2_4_GHZ: - freqs->channels_2ghz |= 1 << (channel - 1); - return true; - case SCAN_BAND_5_GHZ: - return l_uintset_put(freqs->channels_5ghz, channel); - } - - return false; -} - -bool scan_freq_set_contains(const struct scan_freq_set *freqs, uint32_t freq) -{ - enum scan_band band; - uint8_t channel; - - channel = scan_freq_to_channel(freq, &band); - if (!channel) - return false; - - switch (band) { - case SCAN_BAND_2_4_GHZ: - return freqs->channels_2ghz & (1 << (channel - 1)); - case SCAN_BAND_5_GHZ: - return l_uintset_contains(freqs->channels_5ghz, channel); - } - - return false; -} - -uint32_t scan_freq_set_get_bands(struct scan_freq_set *freqs) -{ - uint32_t bands = 0; - uint32_t max; - - if (freqs->channels_2ghz) - bands |= SCAN_BAND_2_4_GHZ; - - max = l_uintset_get_max(freqs->channels_5ghz); - - if (l_uintset_find_min(freqs->channels_5ghz) <= max) - bands |= SCAN_BAND_5_GHZ; - - return bands; -} - -static void scan_channels_5ghz_add(uint32_t channel, void *user_data) -{ - struct l_uintset *to = user_data; - - l_uintset_put(to, channel); -} - -void scan_freq_set_merge(struct scan_freq_set *to, - const struct scan_freq_set *from) -{ - to->channels_2ghz |= from->channels_2ghz; - - l_uintset_foreach(from->channels_5ghz, scan_channels_5ghz_add, - to->channels_5ghz); -} - -bool scan_freq_set_isempty(const struct scan_freq_set *set) -{ - if (set->channels_2ghz == 0 && l_uintset_isempty(set->channels_5ghz)) - return true; - - return false; -} - -struct channels_5ghz_foreach_data { - scan_freq_set_func_t func; - void *user_data; -}; - -static void scan_channels_5ghz_frequency(uint32_t channel, void *user_data) -{ - const struct channels_5ghz_foreach_data *channels_5ghz_data = user_data; - uint32_t freq; - - freq = scan_channel_to_freq(channel, SCAN_BAND_5_GHZ); - - channels_5ghz_data->func(freq, channels_5ghz_data->user_data); -} - -void scan_freq_set_foreach(const struct scan_freq_set *freqs, - scan_freq_set_func_t func, void *user_data) -{ - struct channels_5ghz_foreach_data data = { }; - uint8_t channel; - uint32_t freq; - - if (unlikely(!freqs || !func)) - return; - - data.func = func; - data.user_data = user_data; - - l_uintset_foreach(freqs->channels_5ghz, scan_channels_5ghz_frequency, - &data); - - if (!freqs->channels_2ghz) - return; - - for (channel = 1; channel <= 14; channel++) { - if (freqs->channels_2ghz & (1 << (channel - 1))) { - freq = scan_channel_to_freq(channel, SCAN_BAND_2_4_GHZ); - - func(freq, user_data); - } - } -} - -void scan_freq_set_constrain(struct scan_freq_set *set, - const struct scan_freq_set *constraint) -{ - struct l_uintset *intersection; - - intersection = l_uintset_intersect(constraint->channels_5ghz, - set->channels_5ghz); - if (!intersection) - /* This shouldn't ever be the case. */ - return; - - l_uintset_free(set->channels_5ghz); - set->channels_5ghz = intersection; - - set->channels_2ghz &= constraint->channels_2ghz; -} - bool scan_wdev_add(uint64_t wdev_id) { struct scan_context *sc; diff --git a/src/scan.h b/src/scan.h @@ -29,11 +29,6 @@ struct p2p_beacon; struct mmpdu_header; struct wiphy; -enum scan_band { - SCAN_BAND_2_4_GHZ = 0x1, - SCAN_BAND_5_GHZ = 0x2, -}; - enum scan_state { SCAN_STATE_NOT_RUNNING, SCAN_STATE_PASSIVE, @@ -90,6 +85,7 @@ struct scan_bss { bool hs20_dgaf_disable : 1; uint8_t cost_level : 3; uint8_t cost_flags : 4; + bool dpp_configurator : 1; }; struct scan_parameters { @@ -112,7 +108,6 @@ typedef bool (*scan_notify_func_t)(int err, struct l_queue *bss_list, const struct scan_freq_set *freqs, void *userdata); typedef void (*scan_destroy_func_t)(void *userdata); -typedef void (*scan_freq_set_func_t)(uint32_t freq, void *userdata); static inline int scan_bss_addr_cmp(const struct scan_bss *a1, const struct scan_bss *a2) @@ -172,23 +167,5 @@ struct scan_bss *scan_bss_new_from_probe_req(const struct mmpdu_header *mpdu, size_t body_len, uint32_t frequency, int rssi); -uint8_t scan_freq_to_channel(uint32_t freq, enum scan_band *out_band); -uint32_t scan_channel_to_freq(uint8_t channel, enum scan_band band); -enum scan_band scan_oper_class_to_band(const uint8_t *country, - uint8_t oper_class); - -struct scan_freq_set *scan_freq_set_new(void); -void scan_freq_set_free(struct scan_freq_set *freqs); -bool scan_freq_set_add(struct scan_freq_set *freqs, uint32_t freq); -bool scan_freq_set_contains(const struct scan_freq_set *freqs, uint32_t freq); -uint32_t scan_freq_set_get_bands(struct scan_freq_set *freqs); -void scan_freq_set_foreach(const struct scan_freq_set *freqs, - scan_freq_set_func_t func, void *user_data); -void scan_freq_set_merge(struct scan_freq_set *to, - const struct scan_freq_set *from); -void scan_freq_set_constrain(struct scan_freq_set *set, - const struct scan_freq_set *constraint); -bool scan_freq_set_isempty(const struct scan_freq_set *set); - bool scan_wdev_add(uint64_t wdev_id); bool scan_wdev_remove(uint64_t wdev_id); diff --git a/src/station.c b/src/station.c @@ -58,6 +58,7 @@ #include "src/diagnostic.h" #include "src/frame-xchg.h" #include "src/sysfs.h" +#include "src/band.h" static struct l_queue *station_list; static uint32_t netdev_watch; @@ -1660,9 +1661,9 @@ static int station_roam_scan(struct station *station, struct scan_freq_set *freq_set); static uint32_t station_freq_from_neighbor_report(const uint8_t *country, - struct ie_neighbor_report_info *info, enum scan_band *out_band) + struct ie_neighbor_report_info *info, enum band_freq *out_band) { - enum scan_band band; + enum band_freq band; uint32_t freq; if (info->oper_class == 0) { @@ -1674,9 +1675,9 @@ static uint32_t station_freq_from_neighbor_report(const uint8_t *country, * use channels in two disjoint ranges. */ if (info->channel_num >= 1 && info->channel_num <= 14) - band = SCAN_BAND_2_4_GHZ; + band = BAND_FREQ_2_4_GHZ; else if (info->channel_num >= 36 && info->channel_num <= 169) - band = SCAN_BAND_5_GHZ; + band = BAND_FREQ_5_GHZ; else { l_debug("Ignored: 0 oper class with an unusual " "channel number"); @@ -1684,7 +1685,7 @@ static uint32_t station_freq_from_neighbor_report(const uint8_t *country, return 0; } } else { - band = scan_oper_class_to_band(country, info->oper_class); + band = band_oper_class_to_band(country, info->oper_class); if (!band) { l_debug("Ignored: unsupported oper class"); @@ -1692,7 +1693,7 @@ static uint32_t station_freq_from_neighbor_report(const uint8_t *country, } } - freq = scan_channel_to_freq(info->channel_num, band); + freq = band_channel_to_freq(info->channel_num, band); if (!freq) { l_debug("Ignored: unsupported channel"); @@ -1725,7 +1726,7 @@ static void parse_neighbor_report(struct station *station, while (ie_tlv_iter_next(&iter)) { struct ie_neighbor_report_info info; uint32_t freq; - enum scan_band band; + enum band_freq band; const uint8_t *cc = NULL; if (ie_tlv_iter_get_tag(&iter) != IE_TYPE_NEIGHBOR_REPORT) diff --git a/src/util.c b/src/util.c @@ -35,6 +35,7 @@ #include "ell/useful.h" #include "src/util.h" +#include "src/band.h" const char *util_ssid_to_utf8(size_t len, const uint8_t *ssid) { @@ -309,3 +310,196 @@ bool util_ip_prefix_tohl(const char *ip, uint8_t *prefix_out, return true; } + +struct scan_freq_set { + uint16_t channels_2ghz; + struct l_uintset *channels_5ghz; +}; + +struct scan_freq_set *scan_freq_set_new(void) +{ + struct scan_freq_set *ret = l_new(struct scan_freq_set, 1); + + /* 802.11-2012, 8.4.2.10 hints that 200 is the largest channel number */ + ret->channels_5ghz = l_uintset_new_from_range(1, 200); + + return ret; +} + +void scan_freq_set_free(struct scan_freq_set *freqs) +{ + l_uintset_free(freqs->channels_5ghz); + l_free(freqs); +} + +bool scan_freq_set_add(struct scan_freq_set *freqs, uint32_t freq) +{ + enum band_freq band; + uint8_t channel; + + channel = band_freq_to_channel(freq, &band); + if (!channel) + return false; + + switch (band) { + case BAND_FREQ_2_4_GHZ: + freqs->channels_2ghz |= 1 << (channel - 1); + return true; + case BAND_FREQ_5_GHZ: + return l_uintset_put(freqs->channels_5ghz, channel); + } + + return false; +} + +bool scan_freq_set_contains(const struct scan_freq_set *freqs, uint32_t freq) +{ + enum band_freq band; + uint8_t channel; + + channel = band_freq_to_channel(freq, &band); + if (!channel) + return false; + + switch (band) { + case BAND_FREQ_2_4_GHZ: + return freqs->channels_2ghz & (1 << (channel - 1)); + case BAND_FREQ_5_GHZ: + return l_uintset_contains(freqs->channels_5ghz, channel); + } + + return false; +} + +uint32_t scan_freq_set_get_bands(struct scan_freq_set *freqs) +{ + uint32_t bands = 0; + uint32_t max; + + if (freqs->channels_2ghz) + bands |= BAND_FREQ_2_4_GHZ; + + max = l_uintset_get_max(freqs->channels_5ghz); + + if (l_uintset_find_min(freqs->channels_5ghz) <= max) + bands |= BAND_FREQ_5_GHZ; + + return bands; +} + +static void scan_channels_5ghz_add(uint32_t channel, void *user_data) +{ + struct l_uintset *to = user_data; + + l_uintset_put(to, channel); +} + +void scan_freq_set_merge(struct scan_freq_set *to, + const struct scan_freq_set *from) +{ + to->channels_2ghz |= from->channels_2ghz; + + l_uintset_foreach(from->channels_5ghz, scan_channels_5ghz_add, + to->channels_5ghz); +} + +bool scan_freq_set_isempty(const struct scan_freq_set *set) +{ + if (set->channels_2ghz == 0 && l_uintset_isempty(set->channels_5ghz)) + return true; + + return false; +} + +struct channels_5ghz_foreach_data { + scan_freq_set_func_t func; + void *user_data; +}; + +static void scan_channels_5ghz_frequency(uint32_t channel, void *user_data) +{ + const struct channels_5ghz_foreach_data *channels_5ghz_data = user_data; + uint32_t freq; + + freq = band_channel_to_freq(channel, BAND_FREQ_5_GHZ); + + channels_5ghz_data->func(freq, channels_5ghz_data->user_data); +} + +void scan_freq_set_foreach(const struct scan_freq_set *freqs, + scan_freq_set_func_t func, void *user_data) +{ + struct channels_5ghz_foreach_data data = { }; + uint8_t channel; + uint32_t freq; + + if (unlikely(!freqs || !func)) + return; + + data.func = func; + data.user_data = user_data; + + l_uintset_foreach(freqs->channels_5ghz, scan_channels_5ghz_frequency, + &data); + + if (!freqs->channels_2ghz) + return; + + for (channel = 1; channel <= 14; channel++) { + if (freqs->channels_2ghz & (1 << (channel - 1))) { + freq = band_channel_to_freq(channel, BAND_FREQ_2_4_GHZ); + + func(freq, user_data); + } + } +} + +void scan_freq_set_constrain(struct scan_freq_set *set, + const struct scan_freq_set *constraint) +{ + struct l_uintset *intersection; + + intersection = l_uintset_intersect(constraint->channels_5ghz, + set->channels_5ghz); + if (!intersection) + /* This shouldn't ever be the case. */ + return; + + l_uintset_free(set->channels_5ghz); + set->channels_5ghz = intersection; + + set->channels_2ghz &= constraint->channels_2ghz; +} + +static void add_foreach(uint32_t freq, void *user_data) +{ + uint32_t **list = user_data; + + **list = freq; + + *list = *list + 1; +} + +uint32_t *scan_freq_set_to_fixed_array(const struct scan_freq_set *set, + size_t *len_out) +{ + uint8_t count = 0; + uint32_t *freqs; + + count = __builtin_popcount(set->channels_2ghz) + + l_uintset_size(set->channels_5ghz); + + if (!count) + return NULL; + + freqs = l_new(uint32_t, count); + + scan_freq_set_foreach(set, add_foreach, &freqs); + + /* Move pointer back to start of list */ + freqs -= count; + + *len_out = count; + + return freqs; +} diff --git a/src/util.h b/src/util.h @@ -101,4 +101,21 @@ static inline bool util_ip_subnet_match(uint8_t prefix_len, ~((1u << (8 - (prefix_len % 8))) - 1)); } +typedef void (*scan_freq_set_func_t)(uint32_t freq, void *userdata); + +struct scan_freq_set *scan_freq_set_new(void); +void scan_freq_set_free(struct scan_freq_set *freqs); +bool scan_freq_set_add(struct scan_freq_set *freqs, uint32_t freq); +bool scan_freq_set_contains(const struct scan_freq_set *freqs, uint32_t freq); +uint32_t scan_freq_set_get_bands(struct scan_freq_set *freqs); +void scan_freq_set_foreach(const struct scan_freq_set *freqs, + scan_freq_set_func_t func, void *user_data); +void scan_freq_set_merge(struct scan_freq_set *to, + const struct scan_freq_set *from); +void scan_freq_set_constrain(struct scan_freq_set *set, + const struct scan_freq_set *constraint); +bool scan_freq_set_isempty(const struct scan_freq_set *set); +uint32_t *scan_freq_set_to_fixed_array(const struct scan_freq_set *set, + size_t *len_out); + #endif /* __UTIL_H */ diff --git a/src/wiphy.c b/src/wiphy.c @@ -118,6 +118,7 @@ struct wiphy { char regdom_country[2]; /* Work queue for this radio */ struct l_queue *work; + bool work_in_callback; bool support_scheduled_scan:1; bool support_rekey_offload:1; @@ -430,10 +431,10 @@ uint32_t wiphy_get_supported_bands(struct wiphy *wiphy) uint32_t bands = 0; if (wiphy->band_2g) - bands |= SCAN_BAND_2_4_GHZ; + bands |= BAND_FREQ_2_4_GHZ; if (wiphy->band_5g) - bands |= SCAN_BAND_5_GHZ; + bands |= BAND_FREQ_5_GHZ; return bands; } @@ -776,16 +777,16 @@ int wiphy_estimate_data_rate(struct wiphy *wiphy, const void *ht_capabilities = NULL; const void *ht_operation = NULL; const struct band *bandp; - enum scan_band band; + enum band_freq band; - if (scan_freq_to_channel(bss->frequency, &band) == 0) + if (band_freq_to_channel(bss->frequency, &band) == 0) return -ENOTSUP; switch (band) { - case SCAN_BAND_2_4_GHZ: + case BAND_FREQ_2_4_GHZ: bandp = wiphy->band_2g; break; - case SCAN_BAND_5_GHZ: + case BAND_FREQ_5_GHZ: bandp = wiphy->band_5g; break; default: @@ -1936,14 +1937,19 @@ static void wiphy_radio_work_next(struct wiphy *wiphy) work->priority = INT_MIN; l_debug("Starting work item %u", work->id); + + wiphy->work_in_callback = true; done = work->ops->do_work(work); + wiphy->work_in_callback = false; if (done) { work->id = 0; l_queue_remove(wiphy->work, work); + wiphy->work_in_callback = true; destroy_work(work); + wiphy->work_in_callback = false; wiphy_radio_work_next(wiphy); } @@ -1973,7 +1979,7 @@ uint32_t wiphy_radio_work_insert(struct wiphy *wiphy, l_queue_insert(wiphy->work, item, insert_by_priority, NULL); - if (l_queue_length(wiphy->work) == 1) + if (l_queue_length(wiphy->work) == 1 && !wiphy->work_in_callback) wiphy_radio_work_next(wiphy); return item->id; @@ -2011,20 +2017,22 @@ void wiphy_radio_work_done(struct wiphy *wiphy, uint32_t id) item->id = 0; + wiphy->work_in_callback = true; destroy_work(item); + wiphy->work_in_callback = false; if (next) wiphy_radio_work_next(wiphy); } -bool wiphy_radio_work_is_running(struct wiphy *wiphy, uint32_t id) +int wiphy_radio_work_is_running(struct wiphy *wiphy, uint32_t id) { - struct wiphy_radio_work_item *item = l_queue_peek_head(wiphy->work); - + struct wiphy_radio_work_item *item = l_queue_find(wiphy->work, match_id, + L_UINT_TO_PTR(id)); if (!item) - return false; + return -ENOENT; - return item->id == id; + return item == l_queue_peek_head(wiphy->work) ? 1 : 0; } static int wiphy_init(void) diff --git a/src/wiphy.h b/src/wiphy.h @@ -130,4 +130,4 @@ uint32_t wiphy_radio_work_insert(struct wiphy *wiphy, int priority, const struct wiphy_radio_work_item_ops *ops); void wiphy_radio_work_done(struct wiphy *wiphy, uint32_t id); -bool wiphy_radio_work_is_running(struct wiphy *wiphy, uint32_t id); +int wiphy_radio_work_is_running(struct wiphy *wiphy, uint32_t id); diff --git a/src/wsc.c b/src/wsc.c @@ -46,6 +46,7 @@ #include "src/iwd.h" #include "src/network.h" #include "src/wsc.h" +#include "src/band.h" #define WALK_TIME 120 @@ -299,14 +300,14 @@ static void wsc_enrollee_handshake_event(struct handshake_state *hs, static inline enum wsc_rf_band freq_to_rf_band(uint32_t freq) { - enum scan_band band; + enum band_freq band; - scan_freq_to_channel(freq, &band); + band_freq_to_channel(freq, &band); switch (band) { - case SCAN_BAND_2_4_GHZ: + case BAND_FREQ_2_4_GHZ: return WSC_RF_BAND_2_4_GHZ; - case SCAN_BAND_5_GHZ: + case BAND_FREQ_5_GHZ: return WSC_RF_BAND_5_0_GHZ; } @@ -731,7 +732,7 @@ static bool push_button_scan_results(int err, struct l_queue *bss_list, for (bss_entry = l_queue_get_entries(bss_list); bss_entry; bss_entry = bss_entry->next) { struct scan_bss *bss = bss_entry->data; - enum scan_band band; + enum band_freq band; int err; l_debug("bss '%s' with SSID: %s, freq: %u", @@ -762,10 +763,10 @@ static bool push_button_scan_results(int err, struct l_queue *bss_list, WSC_DEVICE_PASSWORD_ID_PUSH_BUTTON) continue; - scan_freq_to_channel(bss->frequency, &band); + band_freq_to_channel(bss->frequency, &band); switch (band) { - case SCAN_BAND_2_4_GHZ: + case BAND_FREQ_2_4_GHZ: if (bss_2g) { l_debug("2G Session overlap error"); goto session_overlap; @@ -775,7 +776,7 @@ static bool push_button_scan_results(int err, struct l_queue *bss_list, memcpy(uuid_2g, probe_response.uuid_e, 16); break; - case SCAN_BAND_5_GHZ: + case BAND_FREQ_5_GHZ: if (bss_5g) { l_debug("5G Session overlap error"); goto session_overlap; @@ -994,9 +995,9 @@ static bool wsc_initiate_scan(struct wsc_station_dbus *wsc, req.primary_device_type.subcategory = 0; bands = wiphy_get_supported_bands(wiphy); - if (bands & SCAN_BAND_2_4_GHZ) + if (bands & BAND_FREQ_2_4_GHZ) req.rf_bands |= WSC_RF_BAND_2_4_GHZ; - if (bands & SCAN_BAND_5_GHZ) + if (bands & BAND_FREQ_5_GHZ) req.rf_bands |= WSC_RF_BAND_5_0_GHZ; req.association_state = WSC_ASSOCIATION_STATE_NOT_ASSOCIATED; diff --git a/tools/hwsim.c b/tools/hwsim.c @@ -42,6 +42,8 @@ #include "src/storage.h" #include "src/mpdu.h" #include "src/crypto.h" +#include "src/nl80211util.h" +#include "src/nl80211cmd.h" #define HWSIM_SERVICE "net.connman.hwsim" @@ -412,6 +414,7 @@ struct radio_info_rec { int channels; uint8_t addrs[2][ETH_ALEN]; char *name; + bool ap_only; }; struct interface_info_rec { @@ -419,6 +422,7 @@ struct interface_info_rec { struct radio_info_rec *radio_rec; uint8_t addr[ETH_ALEN]; char *name; + uint32_t iftype; }; static struct l_queue *radio_info; @@ -773,44 +777,48 @@ err_free_radio: dbus_error_failed(pending_create_msg)); } -static void get_wiphy_callback(struct l_genl_msg *msg, void *user_data) +static bool radio_ap_only(struct radio_info_rec *rec) { - struct l_genl_attr attr; - uint16_t type, len; - const void *data; - const char *name = NULL; - uint16_t name_len = 0; - const uint32_t *id = NULL; - struct radio_info_rec *rec; + const struct l_queue_entry *i; + unsigned int n = 0; + bool have_ap = false; - if (!l_genl_attr_init(&attr, msg)) - return; + for (i = l_queue_get_entries(interface_info); i; i = i->next) { + struct interface_info_rec *interface = i->data; - while (l_genl_attr_next(&attr, &type, &len, &data)) { - switch (type) { - case NL80211_ATTR_WIPHY: - id = data; - break; - case NL80211_ATTR_WIPHY_NAME: - name = data; - name_len = len; - break; - } + if (interface->radio_rec != rec) + continue; + + if (interface->iftype == NL80211_IFTYPE_AP) + have_ap = true; + + n += 1; } - if (!name || !id) + return n == 1 && have_ap; +} + +static void get_wiphy_callback(struct l_genl_msg *msg, void *user_data) +{ + const char *name; + uint32_t id; + struct radio_info_rec *rec; + + if (nl80211_parse_attrs(msg, NL80211_ATTR_WIPHY, &id, + NL80211_ATTR_WIPHY_NAME, &name, + NL80211_ATTR_UNSPEC) < 0) return; rec = l_queue_find(radio_info, radio_info_match_wiphy_id, - L_UINT_TO_PTR(*id)); + L_UINT_TO_PTR(id)); if (!rec) return; - if (strlen(rec->name) == name_len && !memcmp(rec->name, name, name_len)) + if (!strcmp(rec->name, name)) return; l_free(rec->name); - rec->name = l_strndup(name, name_len); + rec->name = l_strdup(name); l_dbus_property_changed(dbus, radio_get_path(rec), HWSIM_RADIO_INTERFACE, "Name"); @@ -818,14 +826,11 @@ static void get_wiphy_callback(struct l_genl_msg *msg, void *user_data) static void get_interface_callback(struct l_genl_msg *msg, void *user_data) { - struct l_genl_attr attr; - uint16_t type, len; - const void *data; - const uint8_t *addr = NULL; - const uint32_t *wiphy_id = NULL; - const uint32_t *ifindex = NULL; - const char *ifname = NULL; - size_t ifname_len = 0; + uint32_t ifindex; + uint32_t wiphy_id; + uint32_t iftype; + const uint8_t *addr; + const char *ifname; struct interface_info_rec *rec; struct radio_info_rec *radio_rec; bool old; @@ -833,57 +838,28 @@ static void get_interface_callback(struct l_genl_msg *msg, void *user_data) struct interface_info_rec prev_rec; bool name_change = false; - if (!l_genl_attr_init(&attr, msg)) - return; - - while (l_genl_attr_next(&attr, &type, &len, &data)) { - switch (type) { - case NL80211_ATTR_MAC: - if (len != ETH_ALEN) - break; - - addr = data; - break; - - case NL80211_ATTR_WIPHY: - if (len != 4) - break; - - wiphy_id = data; - break; - - case NL80211_ATTR_IFINDEX: - if (len != 4) - break; - - ifindex = data; - break; - - case NL80211_ATTR_IFNAME: - ifname = data; - ifname_len = len; - break; - } - } - - if (!addr || !wiphy_id || !ifindex || !ifname) + if (nl80211_parse_attrs(msg, NL80211_ATTR_IFINDEX, &ifindex, + NL80211_ATTR_IFNAME, &ifname, + NL80211_ATTR_WIPHY, &wiphy_id, + NL80211_ATTR_IFTYPE, &iftype, + NL80211_ATTR_MAC, &addr, + NL80211_ATTR_UNSPEC) < 0) return; radio_rec = l_queue_find(radio_info, radio_info_match_wiphy_id, - L_UINT_TO_PTR(*wiphy_id)); + L_UINT_TO_PTR(wiphy_id)); if (!radio_rec) /* This is not a hwsim interface, don't track it */ return; rec = l_queue_find(interface_info, interface_info_match_id, - L_UINT_TO_PTR(*ifindex)); + L_UINT_TO_PTR(ifindex)); if (rec) { old = true; memcpy(&prev_rec, rec, sizeof(prev_rec)); - if (strlen(rec->name) != ifname_len || - memcmp(rec->name, ifname, ifname_len)) + if (strcmp(rec->name, ifname)) name_change = true; l_free(rec->name); @@ -892,12 +868,13 @@ static void get_interface_callback(struct l_genl_msg *msg, void *user_data) rec = l_new(struct interface_info_rec, 1); - rec->id = *ifindex; + rec->id = ifindex; rec->radio_rec = radio_rec; } memcpy(rec->addr, addr, ETH_ALEN); - rec->name = l_strndup(ifname, ifname_len); + rec->name = l_strdup(ifname); + rec->iftype = iftype; if (!interface_info) interface_info = l_queue_new(); @@ -933,6 +910,8 @@ static void get_interface_callback(struct l_genl_msg *msg, void *user_data) HWSIM_INTERFACE_INTERFACE, "Name"); } + + radio_rec->ap_only = radio_ap_only(radio_rec); } static bool interface_info_destroy_by_radio(void *data, void *user_data) @@ -987,33 +966,43 @@ static void del_radio_event(struct l_genl_msg *msg) radio_free(radio); } -static void del_interface_event(struct l_genl_msg *msg) +static void set_interface_event(struct l_genl_msg *msg) { struct interface_info_rec *interface; - struct l_genl_attr attr; - uint16_t type, len; - const void *data; - const uint32_t *ifindex = NULL; + uint32_t ifindex; + uint32_t iftype; - if (!l_genl_attr_init(&attr, msg)) + if (nl80211_parse_attrs(msg, NL80211_ATTR_IFINDEX, &ifindex, + NL80211_ATTR_IFTYPE, &iftype, + NL80211_ATTR_UNSPEC) < 0) return; - while (l_genl_attr_next(&attr, &type, &len, &data)) { - switch (type) { - case NL80211_ATTR_IFINDEX: - if (len != 4) - break; + interface = l_queue_find(interface_info, interface_info_match_id, + L_UINT_TO_PTR(ifindex)); + if (!interface) + return; - ifindex = data; - break; - } - } + if (interface->iftype == iftype) + return; + + l_debug("Interface iftype changed for ifindex: %u, iftype: %u", + ifindex, iftype); + interface->iftype = iftype; - if (!ifindex) + interface->radio_rec->ap_only = radio_ap_only(interface->radio_rec); +} + +static void del_interface_event(struct l_genl_msg *msg) +{ + struct interface_info_rec *interface; + uint32_t ifindex; + + if (nl80211_parse_attrs(msg, NL80211_ATTR_IFINDEX, &ifindex, + NL80211_ATTR_UNSPEC) < 0) return; interface = l_queue_find(interface_info, interface_info_match_id, - L_UINT_TO_PTR(*ifindex)); + L_UINT_TO_PTR(ifindex)); if (!interface) return; @@ -1051,11 +1040,9 @@ static void hwsim_config(struct l_genl_msg *msg, void *user_data) static void nl80211_config_notify(struct l_genl_msg *msg, void *user_data) { - uint8_t cmd; + uint8_t cmd = l_genl_msg_get_command(msg); - cmd = l_genl_msg_get_command(msg); - - l_debug("Notification of command %u", cmd); + l_debug("Config notification %s(%u)", nl80211cmd_to_string(cmd), cmd); switch (cmd) { case NL80211_CMD_NEW_WIPHY: @@ -1064,6 +1051,9 @@ static void nl80211_config_notify(struct l_genl_msg *msg, void *user_data) case NL80211_CMD_NEW_INTERFACE: get_interface_callback(msg, NULL); break; + case NL80211_CMD_SET_INTERFACE: + set_interface_event(msg); + break; case NL80211_CMD_DEL_INTERFACE: del_interface_event(msg); break; @@ -1432,20 +1422,6 @@ error: return false; } -struct interface_match_data { - struct radio_info_rec *radio; - const uint8_t *addr; -}; - -static bool interface_info_match_dst(const void *a, const void *b) -{ - const struct interface_info_rec *rec = a; - const struct interface_match_data *dst = b; - - return rec->radio_rec == dst->radio && - !memcmp(rec->addr, dst->addr, ETH_ALEN); -} - static void frame_delay_callback(struct l_timeout *timeout, void *user_data) { struct send_frame_info *send_info = user_data; @@ -1470,17 +1446,24 @@ static void process_frame(struct hwsim_frame *frame) { const struct l_queue_entry *entry; bool drop_mcast = false; + bool beacon = false; if (util_is_broadcast_address(frame->dst_ether_addr)) process_rules(frame->src_radio, NULL, frame, false, &drop_mcast, NULL); + if (frame->payload_len >= 2 && + frame->payload[0] == 0x80 && + frame->payload[1] == 0x00) + beacon = true; + for (entry = l_queue_get_entries(radio_info); entry; entry = entry->next) { struct radio_info_rec *radio = entry->data; struct send_frame_info *send_info; bool drop = drop_mcast; uint32_t delay = 0; + const struct l_queue_entry *i; if (radio == frame->src_radio) continue; @@ -1500,16 +1483,20 @@ static void process_frame(struct hwsim_frame *frame) * at least one interface with this specific address. */ if (!util_is_broadcast_address(frame->dst_ether_addr)) { - struct interface_match_data match_data = { - radio, - frame->dst_ether_addr, - }; - struct interface_info_rec *interface = - l_queue_find(interface_info, - interface_info_match_dst, - &match_data); - - if (!interface) + for (i = l_queue_get_entries(interface_info); + i; i = i->next) { + struct interface_info_rec *interface = i->data; + + if (interface->radio_rec != radio) + continue; + + if (!memcmp(interface->addr, + frame->dst_ether_addr, + ETH_ALEN)) + break; + } + + if (!i) continue; } @@ -1519,6 +1506,13 @@ static void process_frame(struct hwsim_frame *frame) if (drop) continue; + /* + * Don't bother sending beacons to other AP interfaces + * if the AP interface is the only one on this phy + */ + if (beacon && radio->ap_only) + continue; + send_info = l_new(struct send_frame_info, 1); send_info->radio = radio; send_info->frame = hwsim_frame_ref(frame); @@ -3070,6 +3064,8 @@ int main(int argc, char *argv[]) return EXIT_FAILURE; l_log_set_stderr(); + l_debug_enable("*"); + exit_status = EXIT_FAILURE; printf("Wireless simulator ver %s\n", VERSION); diff --git a/tools/test-runner b/tools/test-runner @@ -1100,7 +1100,6 @@ def build_test_list(args): ''' tests = [] test_root = args.testhome + '/autotests' - full_list = sorted(os.listdir(test_root)) # Run all tests if not args.auto_tests: @@ -1108,10 +1107,16 @@ def build_test_list(args): if args.shell: return [test_root + '/shell'] - # Pair down any non-tests and append full path - tests = [test_root + '/' + t for t in full_list if t.startswith('test')] + # Get list of all autotests (committed in git) + tests = os.popen('git -C %s ls-files autotests/ | cut -f2 -d"/" \ + | grep "test*" | uniq' % args.testhome).read() \ + .strip().split('\n') + tests = [test_root + '/' + t for t in tests] else: print("Generating partial test list") + + full_list = sorted(os.listdir(test_root)) + for t in args.auto_tests.split(','): path = '%s/%s' % (test_root, t) if t.endswith('+'): @@ -1291,7 +1296,8 @@ def pre_test(ctx, test, copied): subtests = [f for f in files if f.startswith('test') or \ os.path.splitext(f)[0].endswith('test')] # Everything else (except .py files) - to_copy = [f for f in list(set(files) - set(subtests)) if not f.endswith('.py')] + to_copy = [f for f in list(set(files) - set(subtests)) if not f.endswith('.py') \ + and f != '__pycache__'] for f in to_copy: if os.path.isdir(f): shutil.copytree(f, '/tmp/' + f) @@ -1380,7 +1386,10 @@ def post_test(ctx, to_copy): allowed = ['phonesim.conf', 'certs', 'secrets', 'iwd'] for f in [f for f in os.listdir('/tmp') if f not in allowed]: dbg("File %s was not cleaned up!" % f) - os.remove('/tmp/' + f) + try: + os.remove('/tmp/' + f) + except: + pass def print_results(results): table = PrettyTable(['Test', colored('Passed', 'green'), colored('Failed', 'red'), \ diff --git a/unit/test-dpp.c b/unit/test-dpp.c @@ -0,0 +1,149 @@ +/* + * + * Wireless daemon for Linux + * + * Copyright (C) 2021 Intel Corporation. All rights reserved. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <assert.h> +#include <stdio.h> + +#include <ell/ell.h> + +#include "src/dpp-util.h" +#include "src/util.h" +#include "ell/useful.h" + +/* + * B.2 Test Vectors for DPP Authentication Using P-256 for + * Responder-only Authentication + */ +const char *i_proto_public_bytes = "50a532ae2a07207276418d2fa630295d45569be425aa634f02014d00a7d1f61a"; +const char *r_boot_public_bytes = "09c585a91b4df9fd25a045201885c39cc5cfae397ddaeda957dec57fa0e3503f"; +const char *r_boot_private_bytes = "54ce181a98525f217216f59b245f60e9df30ac7f6b26c939418cfc3c42d1afa0"; +const char *r_proto_private_bytes = "f798ed2e19286f6a6efe210b1863badb99af2a14b497634dbfd2a97394fb5aa5"; +const char *r_proto_public_bytes = "5e3fb3576884887f17c3203d8a3a6c2fac722ef0e2201b61ac73bc655c709a90"; +const char *k1_bytes = "3d832a02ed6d7fc1dc96d2eceab738cf01c0028eb256be33d5a21a720bfcf949"; +const char *k2_bytes = "ca08bdeeef838ddf897a5f01f20bb93dc5a895cb86788ca8c00a7664899bc310"; +const char *ke_bytes = "c8882a8ab30c878467822534138c704ede0ab1e873fe03b601a7908463fec87a"; +const char *mx_bytes = "dde2878117d69745be4f916a2dd14269d783d1d788c603bb8746beabbd1dbbbc"; +const char *nx_bytes = "92118478b75c21c2c59340c842b5bce560a535f60bc37a75fe390d738c58d8e8"; +const char *i_nonce_bytes = "13f4602a16daeb69712263b9c46cba31"; +const char *r_nonce_bytes = "3d0cfb011ca916d796f7029ff0b43393"; +const char *i_auth_bytes = "787d1189b526448d2901e7f6c22775ce514fce52fc886c1e924f2fbb8d97b210"; +const char *r_auth_bytes = "43509ef7137d8c2fbe66d802ae09dedd94d41b8cbfafb4954782014ff4a3f91c"; + +#define HEX2BUF(s, buf, _len) { \ + unsigned char *_tmp = l_util_from_hexstring(s, NULL); \ + memcpy(buf, _tmp, _len); \ + l_free(_tmp); \ +} + +#define CHECK_FROM_STR(str, bytes, __len) \ +({ \ + uint64_t __tmp[L_ECC_MAX_DIGITS]; \ + HEX2BUF(str, __tmp, __len); \ + assert(!memcmp(bytes, __tmp, __len)); \ +}) + +static void test_key_derivation(const void *data) +{ + uint64_t tmp[L_ECC_MAX_DIGITS]; + const struct l_ecc_curve *curve = l_ecc_curve_from_ike_group(19); + _auto_(l_ecc_point_free) struct l_ecc_point *i_proto_public = NULL; + _auto_(l_ecc_point_free) struct l_ecc_point *r_boot_public = NULL; + _auto_(l_ecc_scalar_free) struct l_ecc_scalar *r_boot_private = NULL; + _auto_(l_ecc_scalar_free) struct l_ecc_scalar *r_proto_private = NULL; + _auto_(l_ecc_point_free) struct l_ecc_point *r_proto_public = NULL; + _auto_(l_ecc_scalar_free) struct l_ecc_scalar *m = NULL; + _auto_(l_ecc_scalar_free) struct l_ecc_scalar *n = NULL; + uint64_t k1[L_ECC_MAX_DIGITS]; + uint64_t k2[L_ECC_MAX_DIGITS]; + uint64_t ke[L_ECC_MAX_DIGITS]; + uint8_t i_nonce[16]; + uint8_t r_nonce[16]; + uint64_t r_auth[L_ECC_MAX_DIGITS]; + uint64_t i_auth[L_ECC_MAX_DIGITS]; + + HEX2BUF(i_proto_public_bytes, tmp, 32); + i_proto_public = l_ecc_point_from_data(curve, + L_ECC_POINT_TYPE_COMPLIANT, + tmp, 32); + assert(i_proto_public); + + HEX2BUF(r_boot_public_bytes, tmp, 32); + r_boot_public = l_ecc_point_from_data(curve, + L_ECC_POINT_TYPE_COMPLIANT, + tmp, 32); + assert(r_boot_public); + + HEX2BUF(r_proto_public_bytes, tmp, 32); + r_proto_public = l_ecc_point_from_data(curve, + L_ECC_POINT_TYPE_COMPLIANT, + tmp, 32); + assert(r_proto_public); + + HEX2BUF(r_boot_private_bytes, tmp, 32); + r_boot_private = l_ecc_scalar_new(curve, tmp, 32); + assert(r_boot_private); + + HEX2BUF(r_proto_private_bytes, tmp, 32); + r_proto_private = l_ecc_scalar_new(curve, tmp, 32); + assert(r_proto_private); + + m = dpp_derive_k1(i_proto_public, r_boot_private, k1); + assert(m); + + CHECK_FROM_STR(k1_bytes, k1, 32); + l_ecc_scalar_get_data(m, tmp, sizeof(tmp)); + CHECK_FROM_STR(mx_bytes, tmp, 32); + + n = dpp_derive_k2(i_proto_public, r_proto_private, k2); + assert(n); + + CHECK_FROM_STR(k2_bytes, k2, 32); + l_ecc_scalar_get_data(n, tmp, sizeof(tmp)); + CHECK_FROM_STR(nx_bytes, tmp, 32); + + HEX2BUF(i_nonce_bytes, i_nonce, 16); + HEX2BUF(r_nonce_bytes, r_nonce, 16); + dpp_derive_ke(i_nonce, r_nonce, m, n, ke); + + CHECK_FROM_STR(ke_bytes, ke, 32); + + dpp_derive_r_auth(i_nonce, r_nonce, 16, i_proto_public, r_proto_public, + r_boot_public, r_auth); + CHECK_FROM_STR(r_auth_bytes, r_auth, 32); + + dpp_derive_i_auth(r_nonce, i_nonce, 16, r_proto_public, i_proto_public, + r_boot_public, i_auth); + CHECK_FROM_STR(i_auth_bytes, i_auth, 32); +} + +int main(int argc, char *argv[]) +{ + l_test_init(&argc, &argv); + + 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 @@ -0,0 +1,264 @@ +/* + * + * Wireless daemon for Linux + * + * Copyright (C) 2021 Intel Corporation. All rights reserved. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <stdio.h> +#include <assert.h> + +#include <ell/ell.h> + +#include "src/json.h" +#include "ell/useful.h" + +struct json_contents; + + +/* + * Object: + * { "test": "<smile emoji>" } + */ +static void test_json_unicode(const void *data) +{ + struct json_iter iter; + _auto_(l_free)char *v; + uint8_t expected[] = { 0xF0, 0x9F, 0x98, 0x80, 0 }; + + uint8_t s[] = { '{', '"', 't', 'e', 's', 't', '"', ':', + '"', 0xf0, 0x9f, 0x98, 0x80, '"', '}', 0 }; + struct json_contents *c = json_contents_new((const char *)s, sizeof(s)); + + json_iter_init(&iter, c); + assert(json_iter_parse(&iter, JSON_MANDATORY("test", JSON_STRING, &v), + JSON_UNDEFINED)); + + assert(!strcmp(v, (char *)expected)); + + json_contents_free(c); +} + +static void test_json_escaped_unicode(const void *data) +{ + struct json_iter iter; + _auto_(l_free)char *v; + char *s = "{\"test\":\"\\uD8F0\"}"; + char expected[] = "\\uD8F0"; + struct json_contents *c = json_contents_new(s, strlen(s)); + + json_iter_init(&iter, c); + assert(json_iter_parse(&iter, JSON_MANDATORY("test", JSON_STRING, &v), + JSON_UNDEFINED)); + + assert(!strcmp(v, expected)); + + json_contents_free(c); +} + +/* + * 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) +{ + char json[] = "{\"wi-fi_tech\":\"infra\"," + "\"discovery\":" + "{\"ssid\":\"somessid\"}," + "\"cred\":" + "{\"akm\":\"psk\"," + "\"pass\":\"somepassphrase\"}}"; + _auto_(l_free)char *tech; + _auto_(l_free)char *ssid; + _auto_(l_free)char *akm; + _auto_(l_free)char *pass; + _auto_(l_free)char *opt_not_found; + struct json_iter objnotfound; + struct json_iter discovery; + struct json_iter cred; + struct json_iter iter; + struct json_contents *c = json_contents_new(json, strlen(json)); + + json_iter_init(&iter, c); + assert(json_iter_parse(&iter, + JSON_MANDATORY("wi-fi_tech", JSON_STRING, &tech), + JSON_MANDATORY("discovery", JSON_OBJECT, &discovery), + JSON_MANDATORY("cred", JSON_OBJECT, &cred), + JSON_OPTIONAL("notfound", JSON_STRING, &opt_not_found), + JSON_OPTIONAL("objnotfound", JSON_OBJECT, &objnotfound), + JSON_UNDEFINED)); + + assert(opt_not_found == NULL); + assert(!json_iter_is_valid(&objnotfound)); + + assert(!strcmp(tech, "infra")); + + assert(json_iter_parse(&discovery, + JSON_MANDATORY("ssid", JSON_STRING, &ssid), + JSON_UNDEFINED)); + + assert(!strcmp(ssid, "somessid")); + + assert(json_iter_parse(&cred, + JSON_MANDATORY("akm", JSON_STRING, &akm), + JSON_MANDATORY("pass", JSON_STRING, &pass), + JSON_UNDEFINED)); + assert(!strcmp(akm, "psk")); + assert(!strcmp(pass, "somepassphrase")); + + json_contents_free(c); +} + +/* + * Tests empty objects parse successfully + */ +static void test_json_empty_objects(const void *data) +{ + char empty[] = "{}"; + char nested_empty[] = "{\"empty\":{}}"; + struct json_iter nested_iter; + struct json_iter iter; + struct json_contents *c = json_contents_new(empty, strlen(empty)); + + json_iter_init(&iter, c); + assert(json_iter_parse(&iter, JSON_UNDEFINED)); + + assert(json_iter_parse(&iter, + JSON_OPTIONAL("optional", JSON_OBJECT, NULL), + JSON_UNDEFINED)); + + assert(!json_iter_parse(&iter, + JSON_MANDATORY("optional", JSON_OBJECT, NULL), + JSON_UNDEFINED)); + json_contents_free(c); + + c = json_contents_new(nested_empty, strlen(nested_empty)); + json_iter_init(&iter, c); + assert(json_iter_parse(&iter, + JSON_MANDATORY("empty", JSON_OBJECT, &nested_iter), + JSON_UNDEFINED)); + assert(json_iter_parse(&nested_iter, JSON_UNDEFINED)); + assert(!json_iter_parse(&nested_iter, + JSON_MANDATORY("mandatory", JSON_OBJECT, NULL), + JSON_UNDEFINED)); + json_contents_free(c); +} + +/* + * Tests that expected key/values can be provided in an order different than + * they appear in the JSON string. + */ +static void test_json_out_of_order(const void *data) +{ + char object[] = "{\"key1\":{},\"key2\":\"val2\",\"key3\":\"val3\"}"; + struct json_iter iter; + struct json_contents *c = json_contents_new(object, strlen(object)); + + json_iter_init(&iter, c); + assert(json_iter_parse(&iter, + JSON_OPTIONAL("nonexist1", JSON_STRING, NULL), + JSON_MANDATORY("key3", JSON_STRING, NULL), + JSON_MANDATORY("key2", JSON_STRING, NULL), + JSON_OPTIONAL("nonexist2", JSON_OBJECT, NULL), + JSON_MANDATORY("key1", JSON_OBJECT, NULL), + JSON_UNDEFINED)); + json_contents_free(c); +} + +/* + * Tests that the token bounds checking works. + */ +static void test_json_larger_object(const void *data) +{ + char json[] = "{\"test1\":\"tester1\"," + "\"test2\":\"tester2\"," + "\"test3\":\"tester3\"," + "\"test4\":\"tester4\"," + "\"test5\":\"tester5\"," + "\"test6\":\"tester6\"," + "\"test7\":\"tester7\"," + "\"test8\":\"tester8\"," + "\"test9\":\"tester9\"," + "\"test10\":\"tester10\"," + "\"test11\":\"tester11\"," + "\"test12\":\"tester12\"," + "\"test13\":\"tester13\"}"; + + struct json_iter iter; + struct json_contents *c = json_contents_new(json, strlen(json)); + + json_iter_init(&iter, c); + assert(json_iter_parse(&iter, + JSON_MANDATORY("test13", JSON_STRING, NULL), + JSON_UNDEFINED)); + json_contents_free(c); +} + +int main(int argc, char *argv[]) +{ + l_test_init(&argc, &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); + + return l_test_run(); +}