eiwd

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

commit b7158e27c40143cfa4dfc7498514fbe5fb611b4d
parent 377d6aa0602618a610237f1315741e88c18de6dd
Author: illiliti <illiliti@protonmail.com>
Date:   Mon, 28 Feb 2022 00:58:54 +0300

Merge tag '1.25'

Release 1.25

Diffstat:
M.gitignore | 1+
MChangeLog | 16++++++++++++++++
MMakefile.am | 11+++++++++--
Mautotests/testDPP/connection_test.py | 16++++++++++++++++
Aautotests/testEncryptedProfiles/connection_test.py | 154+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aautotests/testEncryptedProfiles/hw.conf | 6++++++
Aautotests/testEncryptedProfiles/iwd-secret | 1+
Aautotests/testEncryptedProfiles/main.conf | 2++
Aautotests/testEncryptedProfiles/ssidCCMP.conf | 10++++++++++
Aautotests/testEncryptedProfiles/ssidCCMP.psk | 2++
Aautotests/testScan/remove_iface_test.py | 32++++++++++++++++++++++++++++++++
Mautotests/util/hwsim.py | 19++++++++++++++-----
Mautotests/util/iwd.py | 16++++++++++------
Mautotests/util/wpas.py | 19++++++++++++++-----
Mconfigure.ac | 4++--
Mdoc/device-provisioning-api.txt | 19+++++++++++++++++++
Msrc/dpp-util.c | 255++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Msrc/dpp-util.h | 13+++++++++++++
Msrc/dpp.c | 629++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Msrc/eap-ttls.c | 2+-
Msrc/erp.c | 4++--
Msrc/handshake.h | 39+++++++++++++++++++++------------------
Msrc/hotspot.c | 25++++++++++++++++++++-----
Msrc/iwd-dbus.conf | 4+---
Msrc/iwd.config.rst | 18++++++++++++++++++
Msrc/iwd.network.rst | 6+++++-
Msrc/main.c | 73+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Msrc/manager.c | 87+++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------------
Msrc/netdev.c | 15+++++++++------
Msrc/network.c | 2+-
Msrc/sae.c | 3+++
Msrc/scan.c | 28++++++++++++++++++++++++++--
Msrc/station.c | 10++++++----
Msrc/storage.c | 312++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Msrc/storage.h | 10++++++++++
Msrc/util.h | 4++++
Mtools/hwsim.c | 196++++++++++++++++++++++++++++++++++++++++++-------------------------------------
Atools/iwd-decrypt-profile.c | 212+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mtools/test-runner | 5++++-
Munit/test-dpp.c | 139+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mwired/ead-dbus.conf | 4+---
41 files changed, 2203 insertions(+), 220 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -37,6 +37,7 @@ wired/ead.service tools/hwsim tools/hwsim.1 tools/probe-req +tools/iwd-decrypt-profile unit/test-cmac-aes unit/test-arc4 unit/test-hmac-md5 diff --git a/ChangeLog b/ChangeLog @@ -1,3 +1,19 @@ +ver 1.25: + Fix issue with handling abort of periodic scans. + Fix issue with handling connection when link goes down. + Fix issue with handling operating channel information. + Add support for encrypted network profile storage. + Add support for DPP initiating as a configurator. + +ver 1.24: + Fix issue with handshake and missing rekeying support. + Fix issue with BSS ranking and zero signal strength. + Fix issue with setting OWE IE length correctly. + +ver 1.23: + Fix issue with handling handshake offloading. + Fix issue with at_console and D-Bus policy. + ver 1.22: Fix issue with handling periodic scanning. Fix issue with handling scanning completion. diff --git a/Makefile.am b/Makefile.am @@ -364,7 +364,7 @@ endif endif if TOOLS -noinst_PROGRAMS += tools/probe-req +noinst_PROGRAMS += tools/probe-req tools/iwd-decrypt-profile tools_probe_req_SOURCES = tools/probe-req.c src/mpdu.h src/mpdu.c \ src/ie.h src/ie.c \ @@ -375,6 +375,12 @@ tools_probe_req_SOURCES = tools/probe-req.c src/mpdu.h src/mpdu.c \ tools_probe_req_LDADD = $(ell_ldadd) endif +tools_iwd_decrypt_profile_SOURCES = tools/iwd-decrypt-profile.c \ + src/common.h src/common.c \ + src/crypto.h src/crypto.c \ + src/storage.h src/storage.c +tools_iwd_decrypt_profile_LDADD = ${ell_ldadd} + if HWSIM bin_PROGRAMS += tools/hwsim @@ -384,7 +390,8 @@ tools_hwsim_SOURCES = tools/hwsim.c src/mpdu.h \ src/nl80211util.h src/nl80211util.c \ src/storage.h src/storage.c \ src/common.h src/common.c \ - src/band.h src/band.c + src/band.h src/band.c \ + src/crypto.h src/crypto.c tools_hwsim_LDADD = $(ell_ldadd) if DBUS_POLICY diff --git a/autotests/testDPP/connection_test.py b/autotests/testDPP/connection_test.py @@ -80,6 +80,22 @@ class Test(unittest.TestCase): self.wpas.dpp_enrollee_start(uri) + self.wpas.wait_for_event('DPP-CONF-RECEIVED') + + def test_iwd_as_configurator_initiator(self): + self.hapd.reload() + self.hapd.wait_for_event('AP-ENABLED') + + IWD.copy_to_storage('ssidCCMP.psk') + self.device.autoconnect = True + + condition = 'obj.state == DeviceState.connected' + self.wd.wait_for_object_condition(self.device, condition) + + uri = self.wpas.dpp_enrollee_start(oper_and_channel='81/2') + + self.device.dpp_start_configurator(uri) + self.hapd.wait_for_event('AP-STA-CONNECTED 42:00:00:00:00:00') def setUp(self): diff --git a/autotests/testEncryptedProfiles/connection_test.py b/autotests/testEncryptedProfiles/connection_test.py @@ -0,0 +1,154 @@ +#!/usr/bin/python3 + +import unittest +import sys + +sys.path.append('../util') +import iwd +import os +from iwd import IWD +from iwd import NetworkType +from iwd import PSKAgent + +class Test(unittest.TestCase): + def profile_is_encrypted(self, profile): + with open('/tmp/iwd/' + profile) as f: + contents = f.read() + + if 'Passphrase' in contents: + return False + + return True + + def validate(self, wd): + devices = wd.list_devices(1) + device = devices[0] + + ordered_network = device.get_ordered_network('ssidCCMP') + + self.assertEqual(ordered_network.type, NetworkType.psk) + + condition = 'not obj.connected' + wd.wait_for_object_condition(ordered_network.network_object, condition) + + ordered_network.network_object.connect() + + condition = 'obj.state == DeviceState.connected' + wd.wait_for_object_condition(device, condition) + + device.disconnect() + + condition = 'not obj.connected' + wd.wait_for_object_condition(ordered_network.network_object, condition) + + # Tests that an existing plaintext profile gets encrypted + def test_new_profile(self): + IWD.copy_to_storage('ssidCCMP.psk') + + mtime = os.path.getmtime('/tmp/iwd/' + 'ssidCCMP.psk') + self.assertFalse(self.profile_is_encrypted('ssidCCMP.psk')) + + wd = IWD(True) + + # Make sure profile was accepted + condition = 'len(obj.list_known_networks()) == 1' + wd.wait_for_object_condition(wd, condition) + + # Check the file was modified (should be encrypted now) + self.assertNotEqual(mtime, os.path.getmtime('/tmp/iwd/' + 'ssidCCMP.psk')) + + self.validate(wd) + + self.assertTrue(self.profile_is_encrypted('ssidCCMP.psk')) + + # Tests that a new connection with agent gets written to an encrypted profile + def test_agent_profile(self): + wd = IWD(True) + + psk_agent = PSKAgent("secret123") + wd.register_psk_agent(psk_agent) + + with self.assertRaises(FileNotFoundError): + self.profile_is_encrypted('ssidCCMP.psk') + + self.validate(wd) + + self.assertTrue(self.profile_is_encrypted('ssidCCMP.psk')) + + wd.unregister_psk_agent(psk_agent) + + # Tests that an invalid profile gets re-written after an agent request + def test_invalid_profile_rewritten(self): + bad_config = '[Security]\nPassphrase=incorrect\n' + os.system('echo "%s" > /tmp/iwd/ssidCCMP.psk' % bad_config) + + wd = IWD(True) + + condition = 'len(obj.list_known_networks()) == 1' + wd.wait_for_object_condition(wd, condition) + + # IWD should still encrypt the profile automatically + self.assertTrue(self.profile_is_encrypted('ssidCCMP.psk')) + + # This should fail + with self.assertRaises(iwd.FailedEx): + self.validate(wd) + + psk_agent = PSKAgent("secret123") + wd.register_psk_agent(psk_agent) + + self.validate(wd) + + self.assertTrue(self.profile_is_encrypted('ssidCCMP.psk')) + + # Tests that a profile that doesn't decrypt wont become a known network + def test_decryption_failure(self): + bad_config = \ +''' +[Security] +EncryptedSalt=000102030405060708090a0b0c0d0e0f +EncryptedSecurity=aabbccddeeff00112233445566778899 +''' + os.system('echo "%s" > /tmp/iwd/ssidCCMP.psk' % bad_config) + + wd = IWD(True) + + self.assertEqual(wd.list_known_networks(), []) + + def test_runtime_profile(self): + wd = IWD(True) + + self.assertEqual(wd.list_known_networks(), []) + + # Add profile after IWD starts + IWD.copy_to_storage('ssidCCMP.psk') + + self.validate(wd) + + # Should now be encrypted + self.assertTrue(self.profile_is_encrypted('ssidCCMP.psk')) + + with open('/tmp/iwd/ssidCCMP.psk') as f: + profile = f.read() + + # Edit the profile, corrupting it + profile.replace('EncryptedSecurity=', 'EncryptedSecurity=00') + + devices = wd.list_devices(1) + device = devices[0] + condition = 'obj.state == DeviceState.disconnected' + wd.wait_for_object_condition(device, condition) + + def tearDown(self): + IWD.clear_storage() + + @classmethod + def setUpClass(cls): + os.environ['CREDENTIALS_DIRECTORY'] = '/tmp' + + @classmethod + def tearDownClass(cls): + IWD.clear_storage() + +if __name__ == '__main__': + unittest.main(exit=True) diff --git a/autotests/testEncryptedProfiles/hw.conf b/autotests/testEncryptedProfiles/hw.conf @@ -0,0 +1,6 @@ +[SETUP] +num_radios=2 +start_iwd=0 + +[HOSTAPD] +rad0=ssidCCMP.conf diff --git a/autotests/testEncryptedProfiles/iwd-secret b/autotests/testEncryptedProfiles/iwd-secret @@ -0,0 +1 @@ +secret123 diff --git a/autotests/testEncryptedProfiles/main.conf b/autotests/testEncryptedProfiles/main.conf @@ -0,0 +1,2 @@ +[General] +SystemdEncrypt=iwd-secret diff --git a/autotests/testEncryptedProfiles/ssidCCMP.conf b/autotests/testEncryptedProfiles/ssidCCMP.conf @@ -0,0 +1,10 @@ +hw_mode=g +channel=1 +ssid=ssidCCMP + +wpa=2 +wpa_pairwise=CCMP +wpa_passphrase=secret123 + +ieee80211w=2 +wpa_key_mgmt=WPA-PSK-SHA256 diff --git a/autotests/testEncryptedProfiles/ssidCCMP.psk b/autotests/testEncryptedProfiles/ssidCCMP.psk @@ -0,0 +1,2 @@ +[Security] +Passphrase=secret123 diff --git a/autotests/testScan/remove_iface_test.py b/autotests/testScan/remove_iface_test.py @@ -0,0 +1,32 @@ +#!/usr/bin/python3 + +import unittest +import sys +import os + +sys.path.append('../util') +from iwd import IWD +from config import ctx + +class Test(unittest.TestCase): + def test_connection_success(self): + wd = IWD(True) + + devices = wd.list_devices(1) + device = devices[0] + + device.autoconnect = True + device.scan(wait=False) + + os.system('ifconfig %s down' % device.name) + + @classmethod + def setUpClass(cls): + pass + + @classmethod + def tearDownClass(cls): + IWD.clear_storage() + +if __name__ == '__main__': + unittest.main(exit=True) diff --git a/autotests/util/hwsim.py b/autotests/util/hwsim.py @@ -309,26 +309,35 @@ class RadioList(collections.Mapping): def _interfaces_removed_handler(self, path, interfaces): del _dict[path] - def create(self, name=None, p2p_device=False, iftype_disable=None, - cipher_disable=None): + def create(self, name, p2p_device=False, iftype_disable=None, + cipher_disable=None, wait=True): args = dbus.Dictionary({ + 'Name': name, 'P2P': p2p_device, }, signature='sv') - if name: - args['Name'] = name - if iftype_disable: args['InterfaceTypeDisable'] = iftype_disable if cipher_disable: args['CipherTypeDisable'] = cipher_disable + if not wait: + self._radio_manager.CreateRadio(args, reply_handler=self._success, + error_handler=self._failure) + return None + path = self._radio_manager.CreateRadio(args) obj = Radio(path) self._dict[path] = obj return obj + def _success(self, bla): + pass + + def _failure(self, ex): + pass + class Hwsim(iwd.AsyncOpAbstract): _instances = WeakValueDictionary() diff --git a/autotests/util/iwd.py b/autotests/util/iwd.py @@ -280,8 +280,11 @@ class DeviceProvisioning(IWDDBusAbstract): def start_enrollee(self): return self._iface.StartEnrollee() - def start_configurator(self): - return self._iface.StartConfigurator() + def start_configurator(self, uri=None): + if uri: + return self._iface.ConfigureEnrollee(uri) + else: + return self._iface.StartConfigurator() def stop(self): self._iface.Stop() @@ -450,7 +453,7 @@ class Device(IWDDBusAbstract): self._station_debug._prop_proxy.Set(IWD_STATION_DEBUG_INTERFACE, 'AutoConnect', value) - def scan(self): + def scan(self, wait=True): '''Schedule a network scan. Possible exception: BusyEx @@ -460,7 +463,8 @@ class Device(IWDDBusAbstract): reply_handler=self._success, error_handler=self._failure) - self._wait_for_async_op() + if wait: + self._wait_for_async_op() def disconnect(self): '''Disconnect from the network @@ -667,8 +671,8 @@ class Device(IWDDBusAbstract): def dpp_start_enrollee(self): return self._device_provisioning.start_enrollee() - def dpp_start_configurator(self): - return self._device_provisioning.start_configurator() + def dpp_start_configurator(self, uri=None): + return self._device_provisioning.start_configurator(uri) def dpp_stop(self): return self._device_provisioning.stop() diff --git a/autotests/util/wpas.py b/autotests/util/wpas.py @@ -88,8 +88,6 @@ class Wpas: def handle_eow(): nonlocal key, value, count, event if count == 0: - if key is not None or not value: - raise Exception('Bad event name') key = 'event' elif key is None: if not value: @@ -241,10 +239,17 @@ class Wpas: def set(self, key, value, **kwargs): self._ctrl_request('SET ' + key + ' ' + value, **kwargs) - def dpp_enrollee_start(self, uri=None): + def dpp_enrollee_start(self, uri=None, oper_and_channel=None): + if not oper_and_channel: + oper_and_channel = '81/1' + self._rx_data = [] - self._ctrl_request('DPP_BOOTSTRAP_GEN type=qrcode') - self.wait_for_result() + self._ctrl_request('DPP_BOOTSTRAP_GEN type=qrcode chan=%s' % oper_and_channel) + self._dpp_qr_id = self.wait_for_result() + self._ctrl_request('DPP_BOOTSTRAP_GET_URI %s' % self._dpp_qr_id) + self._dpp_uri = self.wait_for_result() + + print("DPP Enrollee QR: %s" % self._dpp_uri) if uri: self._rx_data = [] @@ -252,6 +257,10 @@ class Wpas: self._dpp_qr_id = self.wait_for_result() self._rx_data = [] self._ctrl_request('DPP_AUTH_INIT peer=%s role=enrollee' % self._dpp_qr_id) + else: + self._ctrl_request('DPP_CHIRP own=%s iter=100' % self._dpp_qr_id) + + return self._dpp_uri def dpp_configurator_create(self, uri): self._rx_data = [] diff --git a/configure.ac b/configure.ac @@ -1,5 +1,5 @@ AC_PREREQ(2.60) -AC_INIT(iwd, 1.22) +AC_INIT(iwd, 1.25) 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.48" + ell_min_version="0.49" else ell_min_version="0.5" fi diff --git a/doc/device-provisioning-api.txt b/doc/device-provisioning-api.txt @@ -37,3 +37,22 @@ Methods string StartEnrollee() net.connman.iwd.NotConfigured net.connman.iwd.NotSupported net.connman.iwd.Busy + + string ConfigureEnrollee(string uri) + + Start a DPP configurator with an enrollees URI. + Only connected station devices are supported and will + only configure the enrollee to the currently connected + network. + + This API is to handle the use case where the enrollee + has shared its URI to IWD (unlike StartConfigurator) + + The URI for IWD is also returned which could be used + in the same way as it is with StartConfigurator(). + + 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/src/dpp-util.c b/src/dpp-util.c @@ -828,7 +828,8 @@ struct l_ecc_point *dpp_point_from_asn1(const uint8_t *asn1, size_t len) return NULL; /* SEQUENCE */ - inner_seq = asn1_der_find_elem(outer_seq, outer_len, 0, &tag, &inner_len); + inner_seq = asn1_der_find_elem(outer_seq, outer_len, 0, &tag, + &inner_len); if (!inner_seq || tag != ASN1_ID_SEQUENCE) return NULL; @@ -859,9 +860,259 @@ struct l_ecc_point *dpp_point_from_asn1(const uint8_t *asn1, size_t len) /* BITSTRING */ key_data = asn1_der_find_elem(outer_seq, outer_len, 1, &tag, &elen); - if (!key_data || tag != ASN1_ID_BIT_STRING || elen > 2) + if (!key_data || tag != ASN1_ID_BIT_STRING || elen < 2) return NULL; return l_ecc_point_from_data(curve, key_data[1], key_data + 2, elen - 2); } + +/* + * Advances 'p' to the next character 'sep' plus one. strchr can be trusted to + * find the next character, but we do need to check that the next character + 1 + * isn't the NULL terminator, i.e. that data actually exists past this point. + */ +#define TOKEN_NEXT(p, sep) \ +({ \ + const char *_next = strchr((p), (sep)); \ + if (_next) { \ + if (*(_next + 1) == '\0') \ + _next = NULL; \ + else \ + _next++; \ + } \ + _next; \ +}) + +/* + * Finds the length of the current token (characters until next 'sep'). If no + * 'sep' is found zero is returned. + */ +#define TOKEN_LEN(p, sep) \ +({ \ + const char *_next = strchr((p), (sep)); \ + if (!_next) \ + _next = (p); \ + (_next - (p)); \ +}) + +/* + * Ensures 'p' points to something resembling a single character followed by + * ':' followed by at least one non-null byte of data. This allows the parse + * loop to safely advance the pointer to each tokens data (pos + 2) + */ +#define TOKEN_OK(p) \ + ((p) && (p)[0] != '\0' && (p)[1] == ':' && (p)[2] != '\0') \ + +static struct scan_freq_set *dpp_parse_class_and_channel(const char *token, + unsigned int len) +{ + const char *pos = token; + char *end; + struct scan_freq_set *freqs = scan_freq_set_new(); + + /* Checking for <operclass>/<channel>,<operclass>/<channel>,... */ + for (; pos && pos < token + len; pos = TOKEN_NEXT(pos, ',')) { + unsigned long r; + uint8_t channel; + uint8_t oper_class; + uint32_t freq; + + /* strtoul accepts minus and plus signs before value */ + if (*pos == '-' || *pos == '+') + goto free_set; + + /* to check uint8_t overflow */ + errno = 0; + r = oper_class = strtoul(pos, &end, 10); + + if (errno == ERANGE || errno == EINVAL) + goto free_set; + /* + * Did strtoul not advance pointer, not reach the next + * token, or overflow? + */ + if (end == pos || *end != '/' || r != oper_class) + goto free_set; + + pos = end + 1; + + if (*pos == '-' || *pos == '+') + goto free_set; + + errno = 0; + r = channel = strtoul(pos, &end, 10); + + if (errno == ERANGE || errno == EINVAL) + goto free_set; + /* + * Same verification as above, but also checks either for + * another pair (,) or end of this token (;) + */ + if (end == pos || (*end != ',' && *end != ';') || r != channel) + goto free_set; + + freq = oci_to_frequency(oper_class, channel); + if (!freq) + goto free_set; + + scan_freq_set_add(freqs, freq); + } + + if (token + len != end) + goto free_set; + + if (scan_freq_set_isempty(freqs)) { +free_set: + scan_freq_set_free(freqs); + return NULL; + } + + return freqs; +} + +static int dpp_parse_mac(const char *str, unsigned int len, uint8_t *mac_out) +{ + uint8_t mac[6]; + unsigned int i; + + if (len != 12) + return -EINVAL; + + for (i = 0; i < 12; i += 2) { + if (!l_ascii_isxdigit(str[i])) + return -EINVAL; + + if (!l_ascii_isxdigit(str[i + 1])) + return -EINVAL; + } + + if (sscanf(str, "%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx", + &mac[0], &mac[1], &mac[2], + &mac[3], &mac[4], &mac[5]) != 6) + return -EINVAL; + + if (!util_is_valid_sta_address(mac)) + return -EINVAL; + + memcpy(mac_out, mac, 6); + + return 0; +} + +static int dpp_parse_version(const char *str, unsigned int len, + uint8_t *version_out) +{ + if (len != 1) + return -EINVAL; + + if (str[0] != '1' && str[0] != '2') + return -EINVAL; + + *version_out = str[0] - '0'; + + return 0; +} + +static struct l_ecc_point *dpp_parse_key(const char *str, unsigned int len) +{ + _auto_(l_free) uint8_t *decoded = NULL; + size_t decoded_len; + + decoded = l_base64_decode(str, len, &decoded_len); + if (!decoded) + return NULL; + + return dpp_point_from_asn1(decoded, decoded_len); +} + +/* + * Parse a bootstrapping URI. This parses the tokens defined in the Easy Connect + * spec, and verifies they are the correct syntax. Some values have extra + * verification: + * - The bootstrapping key is base64 decoded and converted to an l_ecc_point + * - The operating class and channels are checked against the OCI table. + * - The version is checked to be either 1 or 2, as defined by the spec. + * - The MAC is verified to be a valid station address. + */ +struct dpp_uri_info *dpp_parse_uri(const char *uri) +{ + struct dpp_uri_info *info; + const char *pos = uri; + const char *end = uri + strlen(uri) - 1; + int ret = 0; + + if (!l_str_has_prefix(pos, "DPP:")) + return NULL; + + info = l_new(struct dpp_uri_info, 1); + + pos += 4; + + /* EasyConnect 5.2.1 - Bootstrapping information format */ + for (; TOKEN_OK(pos); pos = TOKEN_NEXT(pos, ';')) { + unsigned int len = TOKEN_LEN(pos + 2, ';'); + + if (!len) + goto free_info; + + switch (*pos) { + case 'C': + info->freqs = dpp_parse_class_and_channel(pos + 2, len); + if (!info->freqs) + goto free_info; + break; + case 'M': + ret = dpp_parse_mac(pos + 2, len, info->mac); + if (ret < 0) + goto free_info; + break; + case 'V': + ret = dpp_parse_version(pos + 2, len, &info->version); + if (ret < 0) + goto free_info; + break; + case 'K': + info->boot_public = dpp_parse_key(pos + 2, len); + if (!info->boot_public) + goto free_info; + break; + case 'H': + case 'I': + break; + default: + goto free_info; + } + } + + /* Extra data found after last token */ + if (pos != end) + goto free_info; + + /* The public bootstrapping key is the only required token */ + if (!info->boot_public) + goto free_info; + + return info; + +free_info: + dpp_free_uri_info(info); + return NULL; +} + +void dpp_free_uri_info(struct dpp_uri_info *info) +{ + if (info->freqs) + scan_freq_set_free(info->freqs); + + if (info->boot_public) + l_ecc_point_free(info->boot_public); + + if (info->information) + l_free(info->information); + + if (info->host) + l_free(info->host); + + l_free(info); +} diff --git a/src/dpp-util.h b/src/dpp-util.h @@ -22,6 +22,16 @@ struct l_ecc_point; struct l_ecc_scalar; enum ie_rsn_akm_suite; +struct scan_freq_set; + +struct dpp_uri_info { + struct scan_freq_set *freqs; + struct l_ecc_point *boot_public; + uint8_t mac[6]; + char *information; + uint8_t version; + char *host; +}; enum dpp_frame_type { DPP_FRAME_AUTHENTICATION_REQUEST = 0, @@ -168,3 +178,6 @@ bool dpp_derive_ke(const uint8_t *i_nonce, const uint8_t *r_nonce, uint8_t *dpp_point_to_asn1(const struct l_ecc_point *p, size_t *len_out); struct l_ecc_point *dpp_point_from_asn1(const uint8_t *asn1, size_t len); + +struct dpp_uri_info *dpp_parse_uri(const char *uri); +void dpp_free_uri_info(struct dpp_uri_info *info); diff --git a/src/dpp.c b/src/dpp.c @@ -61,6 +61,9 @@ static struct l_genl_family *nl80211; static uint8_t broadcast[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; static struct l_queue *dpp_list; static uint32_t mlme_watch; +static uint32_t unicast_watch; + +static uint8_t dpp_prefix[] = { 0x04, 0x09, 0x50, 0x6f, 0x9a, 0x1a, 0x01 }; enum dpp_state { DPP_STATE_NOTHING, @@ -83,15 +86,23 @@ struct dpp_sm { uint8_t *own_asn1; size_t own_asn1_len; + uint8_t *peer_asn1; + size_t peer_asn1_len; uint8_t own_boot_hash[32]; + uint8_t peer_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; + struct l_ecc_point *peer_boot_public; enum dpp_state state; + /* + * List of frequencies to jump between. The presence of this list is + * also used to signify that a configurator is an initiator vs responder + */ uint32_t *freqs; size_t freqs_len; size_t freqs_idx; @@ -107,7 +118,9 @@ struct dpp_sm { uint8_t i_nonce[32]; uint8_t e_nonce[32]; + struct l_ecc_scalar *m; uint64_t ke[L_ECC_MAX_DIGITS]; + uint64_t k1[L_ECC_MAX_DIGITS]; uint64_t k2[L_ECC_MAX_DIGITS]; uint64_t auth_tag[L_ECC_MAX_DIGITS]; @@ -127,6 +140,8 @@ struct dpp_sm { uint8_t frame_retry; struct l_dbus_message *pending; + + bool mcast_support : 1; }; static void dpp_free_auth_data(struct dpp_sm *dpp) @@ -145,6 +160,16 @@ static void dpp_free_auth_data(struct dpp_sm *dpp) l_ecc_point_free(dpp->peer_proto_public); dpp->peer_proto_public = NULL; } + + if (dpp->peer_boot_public) { + l_ecc_point_free(dpp->peer_boot_public); + dpp->peer_boot_public = NULL; + } + + if (dpp->m) { + l_ecc_scalar_free(dpp->m); + dpp->m = NULL; + } } static void dpp_reset(struct dpp_sm *dpp) @@ -179,6 +204,11 @@ static void dpp_reset(struct dpp_sm *dpp) dpp->connect_scan_id = 0; } + if (dpp->peer_asn1) { + l_free(dpp->peer_asn1); + dpp->peer_asn1 = NULL; + } + dpp->state = DPP_STATE_NOTHING; dpp->new_freq = 0; dpp->frame_retry = 0; @@ -188,6 +218,7 @@ static void dpp_reset(struct dpp_sm *dpp) 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->k1, dpp->key_len); explicit_bzero(dpp->k2, dpp->key_len); explicit_bzero(dpp->auth_tag, dpp->key_len); @@ -1036,8 +1067,11 @@ static void send_authenticate_response(struct dpp_sm *dpp) * 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); + if (!aes_siv_encrypt(dpp->ke, dpp->key_len, wrapped2_plaintext, + dpp->key_len + 4, NULL, 0, wrapped2)) { + l_error("Failed to encrypt wrapped data"); + return; + } wrapped2_len += 16; @@ -1260,21 +1294,69 @@ static void dpp_presence_announce(struct dpp_sm *dpp) dpp_send_frame(dpp, iov, 2, dpp->current_freq); } +static void dpp_send_authenticate_request(struct dpp_sm *dpp) +{ + uint8_t hdr[32]; + uint8_t attrs[256]; + uint8_t *ptr = attrs; + uint64_t i_proto_key[L_ECC_MAX_DIGITS * 2]; + uint8_t version = 2; + struct iovec iov[2]; + struct station *station = station_find(netdev_get_ifindex(dpp->netdev)); + struct scan_bss *bss = station_get_connected_bss(station); + + l_ecc_point_get_data(dpp->own_proto_public, i_proto_key, + sizeof(i_proto_key)); + + iov[0].iov_len = dpp_build_header(netdev_get_address(dpp->netdev), + dpp->auth_addr, + DPP_FRAME_AUTHENTICATION_REQUEST, hdr); + iov[0].iov_base = hdr; + + ptr += dpp_append_attr(ptr, DPP_ATTR_RESPONDER_BOOT_KEY_HASH, + dpp->peer_boot_hash, 32); + ptr += dpp_append_attr(ptr, DPP_ATTR_INITIATOR_BOOT_KEY_HASH, + dpp->own_boot_hash, 32); + ptr += dpp_append_attr(ptr, DPP_ATTR_INITIATOR_PROTOCOL_KEY, + i_proto_key, dpp->key_len * 2); + ptr += dpp_append_attr(ptr, DPP_ATTR_PROTOCOL_VERSION, &version, 1); + + if (dpp->current_freq != bss->frequency) { + uint8_t pair[2] = { 81, + band_freq_to_channel(bss->frequency, NULL) }; + + ptr += dpp_append_attr(ptr, DPP_ATTR_CHANNEL, pair, 2); + } + + ptr += dpp_append_wrapped_data(hdr + 26, 6, attrs, ptr - attrs, + ptr, sizeof(attrs), dpp->k1, dpp->key_len, 2, + DPP_ATTR_INITIATOR_NONCE, dpp->nonce_len, dpp->i_nonce, + DPP_ATTR_INITIATOR_CAPABILITIES, 1, &dpp->role); + + iov[1].iov_base = attrs; + iov[1].iov_len = ptr - attrs; + + dpp_send_frame(dpp, iov, 2, dpp->current_freq); +} + static void dpp_roc_started(void *user_data) { struct dpp_sm *dpp = user_data; /* * - If a configurator, nothing to do but wait for a request + * (unless multicast frame registration is unsupported in which case + * send an authenticate request now) * - If in the presence state continue sending announcements. * - If authenticating, and this is a result of a channel switch send * the authenticate response now. */ - if (dpp->role == DPP_CAPABILITY_CONFIGURATOR) - return; switch (dpp->state) { case DPP_STATE_PRESENCE: + if (dpp->role == DPP_CAPABILITY_CONFIGURATOR) + return; + if (dpp->pending) { struct l_dbus_message *reply = l_dbus_message_new_method_return(dpp->pending); @@ -1287,6 +1369,19 @@ static void dpp_roc_started(void *user_data) dpp_presence_announce(dpp); break; case DPP_STATE_AUTHENTICATING: + /* + * No multicast frame registration support, jump right into + * sending auth frames. This diverges from the 2.0 spec, but in + * reality the the main path nearly all drivers will hit. + */ + if (dpp->role == DPP_CAPABILITY_CONFIGURATOR) { + if (dpp->mcast_support) + return; + + dpp_send_authenticate_request(dpp); + return; + } + if (dpp->new_freq) { dpp->current_freq = dpp->new_freq; dpp->new_freq = 0; @@ -1400,6 +1495,9 @@ static void authenticate_request(struct dpp_sm *dpp, const uint8_t *from, const void *ad1 = body + 8; uint32_t freq; + if (util_is_broadcast_address(from)) + return; + if (dpp->state != DPP_STATE_PRESENCE) return; @@ -1541,9 +1639,6 @@ static void authenticate_request(struct dpp_sm *dpp, const uint8_t *from, /* Derive keys k2, ke, and R-Auth for authentication response */ - l_ecdh_generate_key_pair(dpp->curve, &dpp->proto_private, - &dpp->own_proto_public); - n = dpp_derive_k2(dpp->peer_proto_public, dpp->proto_private, dpp->k2); if (!n) goto auth_request_failed; @@ -1574,11 +1669,298 @@ auth_request_failed: 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) +static void dpp_send_authenticate_confirm(struct dpp_sm *dpp) +{ + 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), + dpp->auth_addr, + DPP_FRAME_AUTHENTICATION_CONFIRM, hdr); + iov[0].iov_base = hdr; + + ptr += dpp_append_attr(ptr, DPP_ATTR_STATUS, &zero, 1); + ptr += dpp_append_attr(ptr, DPP_ATTR_RESPONDER_BOOT_KEY_HASH, + dpp->peer_boot_hash, 32); + + ptr += dpp_append_wrapped_data(hdr + 26, 6, attrs, ptr - attrs, ptr, + sizeof(attrs), dpp->ke, dpp->key_len, 1, + DPP_ATTR_INITIATOR_AUTH_TAG, dpp->key_len, + dpp->auth_tag); + + iov[1].iov_base = attrs; + iov[1].iov_len = ptr - attrs; + + dpp_send_frame(dpp, iov, 2, dpp->current_freq); +} + +static void authenticate_response(struct dpp_sm *dpp, const uint8_t *from, + const uint8_t *body, size_t body_len) +{ + struct dpp_attr_iter iter; + enum dpp_attribute_type type; + size_t len; + const uint8_t *data; + int status = -1; + const void *r_boot_hash = NULL; + const void *r_proto = NULL; + size_t r_proto_len = 0; + const void *wrapped = NULL; + size_t wrapped_len; + _auto_(l_free) uint8_t *unwrapped1 = NULL; + _auto_(l_free) uint8_t *unwrapped2 = NULL; + const void *r_nonce = NULL; + const void *i_nonce = NULL; + const void *r_auth = NULL; + _auto_(l_ecc_point_free) struct l_ecc_point *r_proto_key = NULL; + _auto_(l_ecc_scalar_free) struct l_ecc_scalar *n = NULL; + const void *ad0 = body + 2; + const void *ad1 = body + 8; + uint64_t r_auth_derived[L_ECC_MAX_DIGITS]; + + l_debug("Authenticate response"); + + if (dpp->state != DPP_STATE_AUTHENTICATING) + return; + + if (dpp->role != DPP_CAPABILITY_CONFIGURATOR) + return; + + if (!dpp->freqs) + return; + + if (memcmp(from, dpp->auth_addr, 6)) + 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_STATUS: + if (len != 1) + return; + + status = l_get_u8(data); + break; + case DPP_ATTR_RESPONDER_BOOT_KEY_HASH: + r_boot_hash = data; + break; + case DPP_ATTR_RESPONDER_PROTOCOL_KEY: + r_proto = data; + r_proto_len = len; + break; + case DPP_ATTR_PROTOCOL_VERSION: + if (len != 1 || l_get_u8(data) != 2) + return; + break; + case DPP_ATTR_WRAPPED_DATA: + wrapped = data; + wrapped_len = len; + break; + default: + break; + } + } + + if (status != DPP_STATUS_OK || !r_boot_hash || !r_proto ) { + l_debug("Auth response bad status or missing attributes"); + return; + } + + r_proto_key = l_ecc_point_from_data(dpp->curve, L_ECC_POINT_TYPE_FULL, + r_proto, r_proto_len); + if (!r_proto_key) { + l_debug("Peers protocol key was invalid"); + return; + } + + n = dpp_derive_k2(r_proto_key, dpp->proto_private, dpp->k2); + + unwrapped1 = dpp_unwrap_attr(ad0, 6, ad1, wrapped - 4 - ad1, dpp->k2, + dpp->key_len, wrapped, wrapped_len, + &wrapped_len); + if (!unwrapped1) { + l_debug("Failed to unwrap primary data"); + return; + } + + wrapped = NULL; + + dpp_attr_iter_init(&iter, unwrapped1, wrapped_len); + + while (dpp_attr_iter_next(&iter, &type, &len, &data)) { + switch (type) { + case DPP_ATTR_RESPONDER_NONCE: + if (len != dpp->nonce_len) + return; + + r_nonce = data; + break; + case DPP_ATTR_INITIATOR_NONCE: + if (len != dpp->nonce_len) + return; + + i_nonce = data; + break; + case DPP_ATTR_RESPONDER_CAPABILITIES: + break; + case DPP_ATTR_WRAPPED_DATA: + wrapped = data; + wrapped_len = len; + break; + default: + break; + } + } + + if (!r_nonce || !i_nonce || !wrapped) { + l_debug("Wrapped data missing attributes"); + return; + } + + if (!dpp_derive_ke(i_nonce, r_nonce, dpp->m, n, dpp->ke)) { + l_debug("Failed to derive ke"); + return; + } + + unwrapped2 = dpp_unwrap_attr(NULL, 0, NULL, 0, dpp->ke, dpp->key_len, + wrapped, wrapped_len, &wrapped_len); + if (!unwrapped2) { + l_debug("Failed to unwrap secondary data"); + return; + } + + dpp_attr_iter_init(&iter, unwrapped2, wrapped_len); + + while (dpp_attr_iter_next(&iter, &type, &len, &data)) { + switch (type) { + case DPP_ATTR_RESPONDER_AUTH_TAG: + if (len != dpp->key_len) + return; + + r_auth = data; + break; + default: + break; + } + } + + if (!r_auth) { + l_debug("R-Auth was not in secondary wrapped data"); + return; + } + + if (!dpp_derive_r_auth(i_nonce, r_nonce, dpp->nonce_len, + dpp->own_proto_public, r_proto_key, + dpp->peer_boot_public, r_auth_derived)) { + l_debug("Failed to derive r_auth"); + return; + } + + if (memcmp(r_auth, r_auth_derived, dpp->key_len)) { + l_debug("R-Auth did not verify"); + return; + } + + if (!dpp_derive_i_auth(r_nonce, i_nonce, dpp->nonce_len, + r_proto_key, dpp->own_proto_public, + dpp->peer_boot_public, dpp->auth_tag)) { + l_debug("Could not derive I-Auth"); + return; + } + + dpp->current_freq = dpp->new_freq; + + dpp_send_authenticate_confirm(dpp); +} + +static void dpp_handle_presence_announcement(struct dpp_sm *dpp, + const uint8_t *from, + const uint8_t *body, + size_t body_len) +{ + struct dpp_attr_iter iter; + enum dpp_attribute_type type; + size_t len; + const uint8_t *data; + const void *r_boot = NULL; + size_t r_boot_len = 0; + uint8_t hash[32]; + + l_debug("Presence announcement "MAC, MAC_STR(from)); + + /* Must be a configurator, in an initiator role, in PRESENCE state */ + if (dpp->state != DPP_STATE_PRESENCE) + return; + + if (dpp->role != DPP_CAPABILITY_CONFIGURATOR) + return; + + if (!dpp->freqs) + return; + + /* + * The URI may not have contained a MAC address, if this announcement + * verifies set auth_addr then. + */ + if (!l_memeqzero(dpp->auth_addr, 6) && + memcmp(from, dpp->auth_addr, 6)) { + l_debug("Unexpected source "MAC" expected "MAC, MAC_STR(from), + MAC_STR(dpp->auth_addr)); + return; + } + + dpp_attr_iter_init(&iter, body + 8, body_len - 8); + + while (dpp_attr_iter_next(&iter, &type, &len, &data)) { + switch (type) { + case DPP_ATTR_RESPONDER_BOOT_KEY_HASH: + r_boot = data; + r_boot_len = len; + break; + default: + break; + } + } + + if (!r_boot || r_boot_len != 32) { + l_debug("No responder boot hash"); + return; + } + + /* Hash what we have for the peer and check its our enrollee */ + dpp_hash(L_CHECKSUM_SHA256, hash, 2, "chirp", strlen("chirp"), + dpp->peer_asn1, dpp->peer_asn1_len); + + if (memcmp(hash, r_boot, sizeof(hash))) { + l_debug("Peers boot hash did not match"); + return; + } + + /* + * This is the peer we expected, save away the address and derive the + * initial keys. + */ + memcpy(dpp->auth_addr, from, 6); + + dpp->state = DPP_STATE_AUTHENTICATING; + + dpp_send_authenticate_request(dpp); + + /* + * Should we wait for an ACK then go offchannel? + */ + if (dpp->current_freq != dpp->new_freq) + dpp_start_offchannel(dpp, dpp->new_freq); +} + +static void dpp_handle_frame(struct dpp_sm *dpp, + const struct mmpdu_header *frame, + const void *body, size_t body_len) { - struct dpp_sm *dpp = user_data; const uint8_t *ptr; /* @@ -1595,6 +1977,9 @@ static void dpp_handle_frame(const struct mmpdu_header *frame, case DPP_FRAME_AUTHENTICATION_REQUEST: authenticate_request(dpp, frame->address_2, body, body_len); break; + case DPP_FRAME_AUTHENTICATION_RESPONSE: + authenticate_response(dpp, frame->address_2, body, body_len); + break; case DPP_FRAME_AUTHENTICATION_CONFIRM: authenticate_confirm(dpp, frame->address_2, body, body_len); break; @@ -1602,6 +1987,10 @@ static void dpp_handle_frame(const struct mmpdu_header *frame, dpp_handle_config_result_frame(dpp, frame->address_2, body, body_len); break; + case DPP_FRAME_PRESENCE_ANNOUNCEMENT: + dpp_handle_presence_announcement(dpp, frame->address_2, + body, body_len); + break; default: l_debug("Unhandled DPP frame %u", *ptr); break; @@ -1661,11 +2050,103 @@ static void dpp_mlme_notify(struct l_genl_msg *msg, void *user_data) dpp_send_frame(dpp, &iov, 1, dpp->current_freq); } +static void dpp_unicast_notify(struct l_genl_msg *msg, void *user_data) +{ + struct dpp_sm *dpp; + const uint64_t *wdev_id = NULL; + struct l_genl_attr attr; + uint16_t type, len, frame_len; + const void *data; + const struct mmpdu_header *mpdu = NULL; + const uint8_t *body; + size_t body_len; + + if (l_genl_msg_get_command(msg) != NL80211_CMD_FRAME) + return; + + if (!l_genl_attr_init(&attr, msg)) + return; + + while (l_genl_attr_next(&attr, &type, &len, &data)) { + switch (type) { + case NL80211_ATTR_WDEV: + if (len != 8) + break; + + wdev_id = data; + break; + + case NL80211_ATTR_FRAME: + mpdu = mpdu_validate(data, len); + if (!mpdu) { + l_warn("Frame didn't validate as MMPDU"); + return; + } + + frame_len = len; + break; + } + } + + if (!wdev_id) { + l_warn("Bad wdev attribute"); + return; + } + + dpp = l_queue_find(dpp_list, match_wdev, wdev_id); + if (!dpp) + return; + + if (!mpdu) { + l_warn("Missing frame data"); + return; + } + + body = mmpdu_body(mpdu); + body_len = (const uint8_t *) mpdu + frame_len - body; + + if (body_len < sizeof(dpp_prefix) || + memcmp(body, dpp_prefix, sizeof(dpp_prefix)) != 0) + return; + + dpp_handle_frame(dpp, mpdu, body, body_len); +} + +static void dpp_frame_watch_cb(struct l_genl_msg *msg, void *user_data) +{ + if (l_genl_msg_get_error(msg) < 0) + l_error("Could not register frame watch type %04x: %i", + L_PTR_TO_UINT(user_data), l_genl_msg_get_error(msg)); +} + +/* + * Special case the frame watch which includes the presence frames since they + * require multicast support. This is only supported by ath9k, so adding + * general support to frame-xchg isn't desireable. + */ +static void dpp_frame_watch(struct dpp_sm *dpp, uint16_t frame_type, + const uint8_t *prefix, size_t prefix_len) +{ + struct l_genl_msg *msg; + + msg = l_genl_msg_new_sized(NL80211_CMD_REGISTER_FRAME, 32 + prefix_len); + + l_genl_msg_append_attr(msg, NL80211_ATTR_WDEV, 8, &dpp->wdev_id); + l_genl_msg_append_attr(msg, NL80211_ATTR_FRAME_TYPE, 2, &frame_type); + l_genl_msg_append_attr(msg, NL80211_ATTR_FRAME_MATCH, + prefix_len, prefix); + if (dpp->mcast_support) + l_genl_msg_append_attr(msg, NL80211_ATTR_RECEIVE_MULTICAST, + 0, NULL); + + l_genl_family_send(nl80211, msg, dpp_frame_watch_cb, + L_UINT_TO_PTR(frame_type), NULL); +} + 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 }; @@ -1675,6 +2156,9 @@ static void dpp_create(struct netdev *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); + dpp->mcast_support = wiphy_has_ext_feature( + wiphy_find_by_wdev(dpp->wdev_id), + NL80211_EXT_FEATURE_MULTICAST_REGISTRATIONS); l_ecdh_generate_key_pair(dpp->curve, &dpp->boot_private, &dpp->boot_public); @@ -1687,9 +2171,8 @@ static void dpp_create(struct netdev *netdev) 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); + dpp_frame_watch(dpp, 0x00d0, dpp_prefix, sizeof(dpp_prefix)); + frame_watch_add(netdev_get_wdev_id(netdev), 0, 0x00d0, dpp_conf_response_prefix, sizeof(dpp_conf_response_prefix), @@ -1813,6 +2296,9 @@ static struct l_dbus_message *dpp_dbus_start_enrollee(struct l_dbus *dbus, dpp->state = DPP_STATE_PRESENCE; dpp->role = DPP_CAPABILITY_ENROLLEE; + l_ecdh_generate_key_pair(dpp->curve, &dpp->proto_private, + &dpp->own_proto_public); + l_debug("DPP Start Enrollee: %s", dpp->uri); dpp->pending = l_dbus_message_ref(message); @@ -1829,9 +2315,66 @@ static struct l_dbus_message *dpp_dbus_start_enrollee(struct l_dbus *dbus, return NULL; } -static struct l_dbus_message *dpp_dbus_start_configurator(struct l_dbus *dbus, +/* + * Set up the configurator for an initiator role. The configurator + * will go offchannel to frequencies advertised by the enrollees URI or, + * if no channels are provided, use a default channel list. + */ +static bool dpp_configurator_start_presence(struct dpp_sm *dpp, const char *uri) +{ + _auto_(l_free) uint32_t *freqs = NULL; + size_t freqs_len = 0; + struct dpp_uri_info *info; + + info = dpp_parse_uri(uri); + if (!info) + return false; + + /* + * Very few drivers actually support registration of multicast frames. + * This renders the presence procedure impossible on most drivers. + * But not all is lost. If the URI contains the MAC and channel + * info we an start going through channels sending auth requests which + * is basically DPP 1.0. Otherwise DPP cannot start. + */ + if (!dpp->mcast_support && + (l_memeqzero(info->mac, 6) || !info->freqs)) { + l_error("No multicast registration support, URI must contain " + "MAC and channel information"); + dpp_free_uri_info(info); + return false; + } + + if (!l_memeqzero(info->mac, 6)) + memcpy(dpp->auth_addr, info->mac, 6); + + if (info->freqs) + freqs = scan_freq_set_to_fixed_array(info->freqs, &freqs_len); + + dpp->peer_boot_public = l_ecc_point_clone(info->boot_public); + dpp->peer_asn1 = dpp_point_to_asn1(info->boot_public, + &dpp->peer_asn1_len); + + dpp_free_uri_info(info); + + if (!dpp->peer_asn1) { + l_debug("Peer boot key did not convert to asn1"); + return false; + } + + dpp_hash(L_CHECKSUM_SHA256, dpp->peer_boot_hash, 1, dpp->peer_asn1, + dpp->peer_asn1_len); + + dpp_start_presence(dpp, freqs, freqs_len); + + return true; +} + +static struct l_dbus_message *dpp_start_configurator_common( + struct l_dbus *dbus, struct l_dbus_message *message, - void *user_data) + void *user_data, + bool responder) { struct dpp_sm *dpp = user_data; struct l_dbus_message *reply; @@ -1840,6 +2383,7 @@ static struct l_dbus_message *dpp_dbus_start_configurator(struct l_dbus *dbus, struct network *network; struct l_settings *settings; struct handshake_state *hs = netdev_get_handshake(dpp->netdev); + const char *uri; /* * For now limit the configurator to only configuring enrollees to the @@ -1863,13 +2407,33 @@ static struct l_dbus_message *dpp_dbus_start_configurator(struct l_dbus *dbus, if (dpp->state != DPP_STATE_NOTHING) return dbus_error_busy(message); + l_ecdh_generate_key_pair(dpp->curve, &dpp->proto_private, + &dpp->own_proto_public); + + dpp->state = DPP_STATE_PRESENCE; + + if (!responder) { + if (!l_dbus_message_get_arguments(message, "s", &uri)) + return dbus_error_invalid_args(message); + + if (!dpp_configurator_start_presence(dpp, uri)) + return dbus_error_invalid_args(message); + + /* Since we have the peer's URI generate the keys now */ + l_getrandom(dpp->i_nonce, dpp->nonce_len); + + dpp->m = dpp_derive_k1(dpp->peer_boot_public, + dpp->proto_private, dpp->k1); + + if (!dpp->mcast_support) + dpp->state = DPP_STATE_AUTHENTICATING; + } else + dpp->current_freq = bss->frequency; + dpp->uri = dpp_generate_uri(dpp->own_asn1, dpp->own_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); @@ -1885,6 +2449,20 @@ static struct l_dbus_message *dpp_dbus_start_configurator(struct l_dbus *dbus, return reply; } +static struct l_dbus_message *dpp_dbus_start_configurator(struct l_dbus *dbus, + struct l_dbus_message *message, + void *user_data) +{ + return dpp_start_configurator_common(dbus, message, user_data, true); +} + +static struct l_dbus_message *dpp_dbus_configure_enrollee(struct l_dbus *dbus, + struct l_dbus_message *message, + void *user_data) +{ + return dpp_start_configurator_common(dbus, message, user_data, false); +} + static struct l_dbus_message *dpp_dbus_stop(struct l_dbus *dbus, struct l_dbus_message *message, void *user_data) @@ -1902,6 +2480,8 @@ static void dpp_setup_interface(struct l_dbus_interface *interface) dpp_dbus_start_enrollee, "s", "", "uri"); l_dbus_interface_method(interface, "StartConfigurator", 0, dpp_dbus_start_configurator, "s", "", "uri"); + l_dbus_interface_method(interface, "ConfigureEnrollee", 0, + dpp_dbus_configure_enrollee, "", "s", "uri"); l_dbus_interface_method(interface, "Stop", 0, dpp_dbus_stop, "", ""); } @@ -1932,6 +2512,11 @@ static int dpp_init(void) mlme_watch = l_genl_family_register(nl80211, "mlme", dpp_mlme_notify, NULL, NULL); + unicast_watch = l_genl_add_unicast_watch(iwd_get_genl(), + NL80211_GENL_NAME, + dpp_unicast_notify, + NULL, NULL); + dpp_list = l_queue_new(); return 0; @@ -1941,8 +2526,12 @@ static void dpp_exit(void) { l_debug(""); + l_dbus_unregister_interface(dbus_get_bus(), IWD_DPP_INTERFACE); + netdev_watch_remove(netdev_watch); + l_genl_remove_unicast_watch(iwd_get_genl(), unicast_watch); + l_genl_family_unregister(nl80211, mlme_watch); mlme_watch = 0; diff --git a/src/eap-ttls.c b/src/eap-ttls.c @@ -375,7 +375,7 @@ static bool avp_iter_next(struct avp_iter *iter) len -= TTLS_AVP_HEADER_LEN; - if (len > end - start) + if ((ptrdiff_t) len > end - start) return false; if (flags & TTLS_AVP_FLAG_V) { diff --git a/src/erp.c b/src/erp.c @@ -114,8 +114,8 @@ static bool erp_tlv_iter_next(struct erp_tlv_iter *iter) { const unsigned char *tlv = iter->tlv + iter->pos; const unsigned char *end = iter->tlv + iter->max; - unsigned int tag; - unsigned int len; + uint8_t tag; + uint8_t len; if (end - tlv < 2) return false; diff --git a/src/handshake.h b/src/handshake.h @@ -164,24 +164,27 @@ struct handshake_state { handshake_event_func_t event_func; }; -#define handshake_event(_hs, event, ...) \ - (__extension__ ({ \ - struct handshake_state *hs = (_hs); \ - bool freed = false; \ - \ - if (hs->event_func && !hs->in_event) { \ - hs->in_event = true; \ - hs->event_func(hs, event, hs->user_data, \ - ##__VA_ARGS__); \ - \ - if (!hs->in_event) { \ - handshake_state_free(hs); \ - freed = true; \ - } else \ - hs->in_event = false; \ - } \ - freed; \ - })) +#define HSID(x) UNIQUE_ID(handshake_, x) + +#define handshake_event(_hs, event, ...) \ + ({ \ + bool HSID(freed) = false; \ + typeof(_hs) HSID(hs) = (_hs); \ + \ + if (HSID(hs)->event_func && !HSID(hs)->in_event) { \ + HSID(hs)->in_event = true; \ + HSID(hs)->event_func(HSID(hs), (event), \ + HSID(hs)->user_data, \ + ##__VA_ARGS__); \ + \ + if (!HSID(hs)->in_event) { \ + handshake_state_free(HSID(hs)); \ + HSID(freed) = true; \ + } else \ + HSID(hs)->in_event = false; \ + } \ + HSID(freed); \ + }) void handshake_state_free(struct handshake_state *s); diff --git a/src/hotspot.c b/src/hotspot.c @@ -95,12 +95,17 @@ static struct l_settings *hotspot_network_open(struct network_info *info) settings = l_settings_new(); - if (!l_settings_load_from_file(settings, config->filename)) { - l_settings_free(settings); - return NULL; - } + if (!l_settings_load_from_file(settings, config->filename)) + goto error; + + if (!storage_decrypt(settings, config->filename, config->name)) + goto error; return settings; + +error: + l_settings_free(settings); + return NULL; } static void hotspot_network_sync(struct network_info *info, @@ -111,7 +116,12 @@ static void hotspot_network_sync(struct network_info *info, struct hs20_config *config = l_container_of(info, struct hs20_config, super); - data = l_settings_to_data(settings, &length); + data = __storage_encrypt(settings, config->name, &length); + if (!data) { + l_error("Unable to sync profile %s", config->filename); + return; + } + write_file(data, length, true, "%s", config->filename); l_free(data); } @@ -338,6 +348,11 @@ static struct hs20_config *hs20_config_new(struct l_settings *settings, goto free_values; } + if (!storage_decrypt(settings, filename, name)) { + l_error("Could not open hotspot profile %s", filename); + goto free_values; + } + config = l_new(struct hs20_config, 1); if (hessid_str) { diff --git a/src/iwd-dbus.conf b/src/iwd-dbus.conf @@ -15,12 +15,10 @@ <policy group="wheel"> <allow send_destination="net.connman.iwd"/> - <allow send_interface="net.connman.iwd.Agent"/> </policy> - <policy at_console="true"> + <policy group="netdev"> <allow send_destination="net.connman.iwd"/> - <allow send_interface="net.connman.iwd.Agent"/> </policy> <policy context="default"> diff --git a/src/iwd.config.rst b/src/iwd.config.rst @@ -188,6 +188,24 @@ The group ``[General]`` contains general settings. by the kernel so if kernels/drivers exist which don't support OCV it can be disabled here. + * - SystemdEncrypt + + **Warning: This is a highly experimental feature** + - Value: Systemd key ID + + Enables network profile encryption using a systemd provided secret key. + Once enabled all PSK/8021x network profiles will be encrypted + automatically. Once the profile is encrypted there is no way of going + back using IWD alone. A tool, **iwd-decrypt-profile**, is provided + assuming the secret is known which will decrypt a profile. This + decrypted profile could manually be set to /var/lib/iwd to 'undo' any + profile encryption, but its going to be a manual process. + + Setting up systemd to provide the secret is left up to the user as IWD + has no way of performing this automatically. The systemd options + required are LoadCredentialEncrypted or SetCredentialEncrypted, and the + secret identifier should be named whatever SystemdEncrypt is set to. + Network ------- diff --git a/src/iwd.network.rst b/src/iwd.network.rst @@ -179,7 +179,11 @@ Network Authentication Settings ------------------------------- The group ``[Security]`` contains settings for Wi-Fi security and -authentication configuration. +authentication configuration. This group can be encrypted by enabling +``SystemdEncrypt``, see *iwd.config* for details on this option. If this +section is encrypted (only contains EncryptedSalt/EncryptedSecurity) it should +not be modified. Modifying these values will result in the inability to +connect to that network. .. list-table:: :header-rows: 0 diff --git a/src/main.c b/src/main.c @@ -29,6 +29,10 @@ #include <errno.h> #include <getopt.h> #include <signal.h> +#include <fcntl.h> +#include <unistd.h> +#include <sys/stat.h> +#include <sys/mman.h> #include <ell/ell.h> #include <ell/useful.h> @@ -45,6 +49,7 @@ #include "src/storage.h" #include "src/anqp.h" #include "src/netconfig.h" +#include "src/crypto.h" #include "src/backtrace.h" @@ -401,6 +406,66 @@ done: return r; } +/* + * Initialize a systemd encryption key for encrypting/decrypting credentials. + */ +static bool setup_system_key(void) +{ + int fd; + struct stat st; + const char *cred_dir; + void *key = NULL; + _auto_(l_free) char *path = NULL; + _auto_(l_free) char *key_id = NULL; + bool r = false; + + key_id = l_settings_get_string(iwd_config, "General", + "SystemdEncrypt"); + if (!key_id) + return true; + + cred_dir = getenv("CREDENTIALS_DIRECTORY"); + if (!cred_dir) { + l_warn("SystemdEncrypt enabled but CREDENTIALS_DIRECTORY not " + "set, check iwd.service file"); + return false; + } + + path = l_strdup_printf("%s/%s", cred_dir, key_id); + + fd = open(path, O_RDONLY, 0); + if (fd < 0) { + l_warn("SystemdEncrypt: Cannot open secret: %s (%d)", + strerror(errno), errno); + return false; + } + + if (fstat(fd, &st) < 0 || st.st_size == 0) + goto close_fd; + + key = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0); + if (key == MAP_FAILED) { + l_warn("SystemdEncrypt: can't mmap secret: %s (%d)", + strerror(errno), errno); + goto close_fd; + } + + if (mlock(key, st.st_size) < 0) { + l_warn("SystemdEncrypt: Failed to mlock secrets file"); + goto unmap; + } + + r = storage_init(key, st.st_size); + munlock(key, st.st_size); + +unmap: + munmap(key, st.st_size); +close_fd: + close(fd); + + return r; +} + int main(int argc, char *argv[]) { int exit_status; @@ -538,12 +603,20 @@ int main(int argc, char *argv[]) NULL, NULL); #endif + if (!setup_system_key()) + goto failed_storage; + exit_status = l_main_run_with_signal(signal_handler, NULL); iwd_modules_exit(); + storage_exit(); + +failed_storage: #ifdef HAVE_DBUS dbus_exit(); l_dbus_destroy(dbus); +#else +(void)NULL; #endif failed_dbus: diff --git a/src/manager.c b/src/manager.c @@ -487,6 +487,20 @@ static void manager_interface_dump_callback(struct l_genl_msg *msg, manager_get_interface_cb(msg, state); } +static void manager_filtered_interface_dump_done(void *user_data) +{ + struct wiphy_setup_state *state = user_data; + + l_debug(""); + + if (!manager_wiphy_check_setup_done(state)) + return; + + /* We decided to keep the the default interface(s) */ + l_debug("Wiphy setup complete: %s", wiphy_get_name(state->wiphy)); + wiphy_setup_state_destroy(state); +} + static bool manager_check_create_interfaces(void *data, void *user_data) { struct wiphy_setup_state *state = data; @@ -494,13 +508,14 @@ static bool manager_check_create_interfaces(void *data, void *user_data) if (!manager_wiphy_check_setup_done(state)) return false; - /* If we are here, there were no interfaces for this phy */ wiphy_setup_state_free(state); return true; } static void manager_interface_dump_done(void *user_data) { + l_debug(""); + l_queue_foreach_remove(pending_wiphys, manager_check_create_interfaces, NULL); } @@ -552,43 +567,59 @@ static void manager_wiphy_filtered_dump_callback(struct l_genl_msg *msg, wiphy_update_from_genl(state->wiphy, msg); } -static void manager_wiphy_dump_done(void *user_data) +static void manager_filtered_wiphy_dump_done(void *user_data) { - const struct l_queue_entry *e; + struct wiphy_setup_state *state = user_data; - for (e = l_queue_get_entries(pending_wiphys); e; e = e->next) { - struct wiphy_setup_state *state = e->data; + l_debug(""); - wiphy_create_complete(state->wiphy); - state->use_default = use_default; + wiphy_create_complete(state->wiphy); + state->use_default = use_default; - /* If whitelist/blacklist were given only try to use existing - * interfaces same as when the driver does not support - * NEW_INTERFACE or DEL_INTERFACE, otherwise the interface - * names will become meaningless after we've created our own - * interface(s). Optimally phy name white/blacklists should - * be used. - */ - if (whitelist_filter || blacklist_filter) - state->use_default = true; + /* + * If whitelist/blacklist were given only try to use existing + * interfaces same as when the driver does not support + * NEW_INTERFACE or DEL_INTERFACE, otherwise the interface + * names will become meaningless after we've created our own + * interface(s). Optimally phy name white/blacklists should + * be used. + */ + if (whitelist_filter || blacklist_filter) + state->use_default = true; - if (!state->use_default) - state->use_default = - wiphy_uses_default_if(state->wiphy); + if (!state->use_default) + state->use_default = wiphy_uses_default_if(state->wiphy); - if (state->use_default) - l_info("Wiphy %s will only use the default interface", - wiphy_get_name(state->wiphy)); - } + if (state->use_default) + l_info("Wiphy %s will only use the default interface", + wiphy_get_name(state->wiphy)); +} + +static void manager_wiphy_dump_done(void *user_data) +{ + const struct l_queue_entry *e; + + l_debug(""); + + for (e = l_queue_get_entries(pending_wiphys); e; e = e->next) + manager_filtered_wiphy_dump_done(e->data); } static int manager_wiphy_filtered_dump(uint32_t wiphy_id, - l_genl_msg_func_t cb, - void *user_data) + l_genl_msg_func_t cb, + struct wiphy_setup_state *state) { struct l_genl_msg *msg; unsigned int wiphy_cmd_id; unsigned int iface_cmd_id; + l_genl_destroy_func_t wiphy_done = manager_wiphy_dump_done; + l_genl_destroy_func_t interface_done = manager_interface_dump_done; + + /* If state is provided, don't try to process other pending states */ + if (state) { + wiphy_done = manager_filtered_wiphy_dump_done; + interface_done = manager_filtered_interface_dump_done; + } /* * Until fixed, a NEW_WIPHY event will not include all the information @@ -599,8 +630,7 @@ static int manager_wiphy_filtered_dump(uint32_t wiphy_id, l_genl_msg_append_attr(msg, NL80211_ATTR_SPLIT_WIPHY_DUMP, 0, NULL); l_genl_msg_append_attr(msg, NL80211_ATTR_WIPHY, 4, &wiphy_id); - wiphy_cmd_id = l_genl_family_dump(nl80211, msg, cb, user_data, - manager_wiphy_dump_done); + wiphy_cmd_id = l_genl_family_dump(nl80211, msg, cb, state, wiphy_done); if (!wiphy_cmd_id) { l_error("Could not dump wiphy %u", wiphy_id); l_genl_msg_unref(msg); @@ -625,8 +655,7 @@ static int manager_wiphy_filtered_dump(uint32_t wiphy_id, iface_cmd_id = l_genl_family_dump(nl80211, msg, manager_interface_dump_callback, - NULL, manager_interface_dump_done); - + state, interface_done); if (!iface_cmd_id) { l_error("Could not dump interface for wiphy %u", wiphy_id); l_genl_family_cancel(nl80211, wiphy_cmd_id); diff --git a/src/netdev.c b/src/netdev.c @@ -838,6 +838,11 @@ static void netdev_connect_free(struct netdev *netdev) netdev->disconnect_cmd_id = 0; } + if (netdev->get_oci_cmd_id) { + l_genl_family_cancel(nl80211, netdev->get_oci_cmd_id); + netdev->get_oci_cmd_id = 0; + } + if (netdev->ft_ds_list) { l_queue_destroy(netdev->ft_ds_list, netdev_ft_ds_entry_free); netdev->ft_ds_list = NULL; @@ -949,11 +954,6 @@ static void netdev_free(void *data) netdev->get_station_cmd_id = 0; } - if (netdev->get_oci_cmd_id) { - l_genl_family_cancel(nl80211, netdev->get_oci_cmd_id); - netdev->get_oci_cmd_id = 0; - } - if (netdev->fw_roam_bss) scan_bss_free(netdev->fw_roam_bss); @@ -2830,7 +2830,7 @@ process_resp_ies: continue; owe_dh = data; - owe_dh_len = len; + owe_dh_len = ie_tlv_iter_get_length(&iter); break; @@ -6199,6 +6199,9 @@ static void netdev_newlink_notify(const struct ifinfomsg *ifi, int bytes) new_up = netdev_get_is_up(netdev); + if (!new_up) + netdev_connect_free(netdev); + /* * If mac_change_cmd_id is set we are in the process of changing the * MAC address and this event is a result of powering down/up. In this diff --git a/src/network.c b/src/network.c @@ -1228,7 +1228,7 @@ static struct l_dbus_message *network_connect_psk(struct network *network, */ bool need_passphrase = bss_is_sae(bss); - if (!network_settings_load(network)) { + if (!network_settings_load(network)) { network->settings = l_settings_new(); network->ask_passphrase = true; } else if (!network->ask_passphrase) diff --git a/src/sae.c b/src/sae.c @@ -24,6 +24,9 @@ #include <config.h> #endif +#define _GNU_SOURCE +#include <stdlib.h> + #include <ell/ell.h> #include "src/missing.h" diff --git a/src/scan.c b/src/scan.c @@ -1372,6 +1372,22 @@ static bool scan_parse_bss_information_elements(struct scan_bss *bss, return have_ssid; } +/* + * Maps 0..100 values to -10000..0 + * + * This isn't really mapping to mBm since the input is unit-less and we have no + * idea what the driver itself does to come up with this 'strength' value but + * this is really the best that can be done for these drivers (its only 4 in + * tree drivers after all). + */ +static int32_t signal_unspec_to_mbm(uint8_t strength) +{ + if (L_WARN_ON(strength > 100)) + return 0; + + return ((int32_t)strength * 100) - 10000; +} + static struct scan_bss *scan_parse_attr_bss(struct l_genl_attr *attr, struct wiphy *wiphy, uint32_t *out_seen_ms_ago) @@ -1414,6 +1430,13 @@ static struct scan_bss *scan_parse_attr_bss(struct l_genl_attr *attr, bss->signal_strength = *((int32_t *) data); break; + case NL80211_BSS_SIGNAL_UNSPEC: + if (len != 1) + goto fail; + + bss->signal_strength = + signal_unspec_to_mbm(l_get_u8(data)); + break; case NL80211_BSS_INFORMATION_ELEMENTS: ies = data; ies_len = len; @@ -1970,9 +1993,10 @@ static void scan_notify(struct l_genl_msg *msg, void *user_data) sr->triggered = false; /* If periodic scan, don't report the abort */ - if (sr->periodic) + if (sr->periodic) { + l_queue_remove(sc->requests, sr); wiphy_radio_work_done(sc->wiphy, sr->work.id); - else + } else scan_finished(sc, -ECANCELED, NULL, NULL, sr); } else if (wiphy_radio_work_is_running(sc->wiphy, sr->work.id)) { diff --git a/src/station.c b/src/station.c @@ -250,8 +250,6 @@ static int station_autoconnect_next(struct station *station) static void station_autoconnect_start(struct station *station) { - l_debug(""); - if (!station->autoconnect_can_start) return; @@ -267,6 +265,8 @@ static void station_autoconnect_start(struct station *station) if (L_WARN_ON(station->autoconnect_list)) l_queue_destroy(station->autoconnect_list, NULL); + l_debug(""); + station->autoconnect_list = l_queue_new(); station_network_foreach(station, network_add_foreach, station); station_autoconnect_next(station); @@ -1478,8 +1478,10 @@ static void station_enter_state(struct station *station, case STATION_STATE_CONNECTING_AUTO: /* Refresh the ordered network list */ network_rank_update(station->connected_network, true); - l_queue_remove(station->networks_sorted, station->connected_network); - l_queue_insert(station->networks_sorted, station->connected_network, + l_queue_remove(station->networks_sorted, + station->connected_network); + l_queue_insert(station->networks_sorted, + station->connected_network, network_rank_compare, NULL); #ifdef HAVE_DBUS diff --git a/src/storage.c b/src/storage.c @@ -39,11 +39,14 @@ #include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> +#include <sys/mman.h> #include <ell/ell.h> +#include "ell/useful.h" #include "src/common.h" #include "src/storage.h" +#include "src/crypto.h" #define STORAGE_DIR_MODE (S_IRUSR | S_IWUSR | S_IXUSR) #define STORAGE_FILE_MODE (S_IRUSR | S_IWUSR) @@ -52,6 +55,8 @@ static char *storage_path = NULL; static char *storage_hotspot_path = NULL; +static uint8_t system_key[32]; +static bool system_key_set = false; static int create_dirs(const char *filename) { @@ -347,24 +352,263 @@ const char *storage_network_ssid_from_path(const char *path, return buf; } +/* Groups requiring encryption (if enabled) */ +static char *encrypt_groups[] = { + "Security", + NULL +}; + +static bool encrypt_group(const char *group) +{ + char **g; + + for (g = encrypt_groups; *g; g++) { + if (!strcmp(*g, group)) + return true; + } + + return false; +} + +/* + * Encrypt needed groups of 'settings' without modifying the object. Returns + * the entire settings object as data, with encrypted groups as a bytestring + * set as the value to [Security].EncryptedSecurity. This also includes any + * embedded groups. + * + * Note: If encryption is not enabled or there is no Security group this is + * effectively l_settings_to_data. + */ +char *__storage_encrypt(const struct l_settings *settings, const char *name, + size_t *out_len) +{ + struct iovec ad[2]; + uint8_t salt[32]; + size_t len; + _auto_(l_settings_free) struct l_settings *to_encrypt = NULL; + _auto_(l_settings_free) struct l_settings *original = NULL; + _auto_(l_free) char *plaintext = NULL; + _auto_(l_free) uint8_t *enc = NULL; + _auto_(l_strv_free) char **groups = NULL; + char **i; + + if (!system_key_set || !l_settings_has_group(settings, "Security")) + return l_settings_to_data(settings, out_len); + + /* + * Make two copies of the settings: One will contain only data to be + * encrypted (to_encrypt), the other will contain data to be left + * unencrypted (original). At the end any encrypted data will be set + * into 'original' as EncryptedSecurity. + */ + to_encrypt = l_settings_clone(settings); + original = l_settings_clone(settings); + + groups = l_settings_get_groups(to_encrypt); + for (i = groups; *i; i++) { + if (encrypt_group(*i)) + l_settings_remove_group(original, *i); + else + l_settings_remove_group(to_encrypt, *i); + } + + l_settings_remove_embedded_groups(original); + + plaintext = l_settings_to_data(to_encrypt, &len); + if (!plaintext) + return NULL; + + l_getrandom(salt, 32); + + ad[0].iov_base = (void *) salt; + ad[0].iov_len = 32; + ad[1].iov_base = (void *) name; + ad[1].iov_len = strlen(name); + + /* + * AES-SIV automatically prepends the IV (16 bytes) to the encrypted + * data. + */ + enc = l_malloc(len + 16); + + if (!aes_siv_encrypt(system_key, sizeof(system_key), plaintext, len, + ad, 2, enc)) { + l_error("Could not encrypt [Security] group"); + return NULL; + } + + l_settings_set_bytes(original, "Security", "EncryptedSalt", salt, 32); + l_settings_set_bytes(original, "Security", "EncryptedSecurity", + enc, len + 16); + + return l_settings_to_data(original, out_len); +} + +/* + * Decrypt data in [Security].EncryptedSecurity. This data also includes + * embedded groups potentially. Once decrypted the data is put back into the + * object. + * + * Note: if encryption is not enabled or there is no Security group settings + * is not modified. + */ +int __storage_decrypt(struct l_settings *settings, const char *ssid, + bool *encrypt) +{ + _auto_(l_settings_free) struct l_settings *security = NULL; + _auto_(l_free) uint8_t *encrypted = NULL; + _auto_(l_free) uint8_t *decrypted = NULL; + _auto_(l_free) uint8_t *salt = NULL; + _auto_(l_strv_free) char **embedded = NULL; + _auto_(l_strv_free) char **groups = NULL; + char **i; + size_t elen, slen; + struct iovec ad[2]; + + if (!system_key_set) + goto done; + + if (!l_settings_has_group(settings, "Security")) + goto done; + + encrypted = l_settings_get_bytes(settings, "Security", + "EncryptedSecurity", &elen); + salt = l_settings_get_bytes(settings, "Security", + "EncryptedSalt", &slen); + + /* + * Either profile has never been loaded after enabling encryption or is + * missing Encrypted{Salt,Security} values. If either are missing this + * profile is corrupted and must be fixed. + */ + if (!(encrypted && salt)) { + /* Profile corrupted */ + if (encrypted || salt) { + l_warn("Profile %s is corrupted reconfigure manually", + ssid); + return -EBADMSG; + } + + if (encrypt) + *encrypt = true; + + return 0; + } + + /* + * AES-SIV automatically verifies the IV (16 bytes) and returns only + * the decrypted data portion. We add one here for the NULL terminator + * since this is always going to be textual data after decryption. + */ + decrypted = l_malloc(elen - 16 + 1); + + ad[0].iov_base = (void *)salt; + ad[0].iov_len = slen; + ad[1].iov_base = (void *)ssid; + ad[1].iov_len = strlen(ssid); + + if (!aes_siv_decrypt(system_key, sizeof(system_key), encrypted, elen, + ad, 2, decrypted)) { + l_error("Could not decrypt %s profile, did the secret change?", + ssid); + return -ENOKEY; + } + + decrypted[elen - 16] = '\0'; + + /* + * Remove any groups that are marked as encrypted (plus embedded), + * and copy the decrypted groups back into settings. + */ + groups = l_settings_get_groups(settings); + for (i = groups; *i; i++) { + if (encrypt_group(*i)) + l_settings_remove_group(settings, *i); + } + + l_settings_remove_embedded_groups(settings); + + /* + * Load decrypted data into existing settings. This is not how the API + * is indended to be used (since this could result in duplicate groups) + * but since the Security group was just removed and EncryptedSecurity + * should only contain a Security group its safe to use it this way. + */ + if (!l_settings_load_from_data(settings, (const char *) decrypted, + elen - 16)) { + l_error("Could not load decrypted security group"); + return -EBADMSG; + } + +done: + if (encrypt) + *encrypt = false; + + return 0; +} + +/* + * Decrypts a network profile (if needed). If profile encryption is enabled + * and the profile is unencrypted it will be encrypted and written back to + * the file system automatically. + * + * 'name' is used for decryption and is used as part of the IV. Callers + * should provide a unique identifier here if available. For example, the + * SSID, consortium name, etc. + */ +bool storage_decrypt(struct l_settings *settings, const char *path, + const char *name) +{ + bool needs_encryption; + _auto_(l_free) char *encrypted = NULL; + size_t elen; + + if (__storage_decrypt(settings, name, &needs_encryption) < 0) + return false; + + if (!needs_encryption) + return true; + + /* Profile never encrypted before. Encrypt and write to disk */ + encrypted = __storage_encrypt(settings, name, &elen); + if (!encrypted) { + l_error("Could not encrypt new profile %s", name); + return false; + } + + if (write_file(encrypted, elen, false, "%s", path) < 0) { + l_error("Failed to write out encrypted profile"); + return false; + } + + l_debug("Encrypted a new profile %s", path); + + return true; +} + struct l_settings *storage_network_open(enum security type, const char *ssid) { struct l_settings *settings; - char *path; + _auto_(l_free) char *path = NULL; if (ssid == NULL) return NULL; path = storage_get_network_file_path(type, ssid); + settings = l_settings_new(); - if (!l_settings_load_from_file(settings, path)) { - l_settings_free(settings); - settings = NULL; - } + if (!l_settings_load_from_file(settings, path)) + goto error; + + if (type != SECURITY_NONE && !storage_decrypt(settings, path, ssid)) + goto error; - l_free(path); return settings; + +error: + l_settings_free(settings); + return NULL; } int storage_network_touch(enum security type, const char *ssid) @@ -388,15 +632,19 @@ int storage_network_touch(enum security type, const char *ssid) void storage_network_sync(enum security type, const char *ssid, struct l_settings *settings) { - char *data; + _auto_(l_free) char *data = NULL; + _auto_(l_free) char *path = NULL; size_t length = 0; - char *path; path = storage_get_network_file_path(type, ssid); - data = l_settings_to_data(settings, &length); + data = __storage_encrypt(settings, ssid, &length); + + if (!data) { + l_error("Unable to sync profile %s", ssid); + return; + } + write_file(data, length, true, "%s", path); - l_free(data); - l_free(path); } int storage_network_remove(enum security type, const char *ssid) @@ -463,3 +711,45 @@ bool storage_is_file(const char *filename) return false; } + +/* + * Initialize a systemd encryption key for encrypting/decrypting credentials. + * This uses the 'extract and expand' concept from RFC 5869 to derive a new + * fixed length key. Note that a 'zero salt' is used in this derivation which + * is handled internally in hkdf_extract(). 'TK' denotes the temporary key + * derived from 'extract' and used as the input to 'expand'. + * + * Inputs: + * IKM - Input keying material of arbitrary length. This is the key + * obtained directly from systemd. + * Outputs: + * OKM - Output key material of 32 bytes + * + * TK = HKDF-Extract(<zero>, IKM) + * OKM = HKDF-Expand(TK, "System Key", 32) + */ +bool storage_init(const uint8_t *key, size_t key_len) +{ + uint8_t tmp[32]; + + if (mlock(system_key, sizeof(system_key)) < 0) + return false; + + if (!hkdf_extract(L_CHECKSUM_SHA256, NULL, 0, 1, tmp, key, key_len)) + return false; + + system_key_set = hkdf_expand(L_CHECKSUM_SHA256, tmp, sizeof(tmp), + "System Key", + system_key, sizeof(system_key)); + + explicit_bzero(tmp, sizeof(tmp)); + return system_key_set; +} + +void storage_exit(void) +{ + if (system_key_set) { + explicit_bzero(system_key, sizeof(system_key)); + munlock(system_key, sizeof(system_key)); + } +} diff --git a/src/storage.h b/src/storage.h @@ -50,3 +50,13 @@ int storage_network_remove(enum security type, const char *ssid); struct l_settings *storage_known_frequencies_load(void); void storage_known_frequencies_sync(struct l_settings *known_freqs); + +int __storage_decrypt(struct l_settings *settings, const char *ssid, + bool *changed); +char *__storage_encrypt(const struct l_settings *settings, const char *ssid, + size_t *out_len); +bool storage_decrypt(struct l_settings *settings, const char *path, + const char *name); + +bool storage_init(const uint8_t *key, size_t key_len); +void storage_exit(void); diff --git a/src/util.h b/src/util.h @@ -26,6 +26,10 @@ #include <stdint.h> #include <unistd.h> +#define ___PASTE(a, b) a ## b +#define __PASTE(a, b) ___PASTE(a, b) +#define UNIQUE_ID(x, id) __PASTE(__unique_prefix_, __PASTE(x, id)) + #define align_len(len, boundary) (((len)+(boundary)-1) & ~((boundary)-1)) #define MAC "%02x:%02x:%02x:%02x:%02x:%02x" diff --git a/tools/hwsim.c b/tools/hwsim.c @@ -35,6 +35,7 @@ #include <net/if_arp.h> #include <ell/ell.h> +#include "ell/useful.h" #include "linux/nl80211.h" @@ -405,7 +406,7 @@ static void list_callback(struct l_genl_msg *msg, void *user_data) } struct radio_info_rec { - uint32_t id; + int32_t id; uint32_t wiphy_id; char alpha2[2]; bool p2p; @@ -415,6 +416,8 @@ struct radio_info_rec { uint8_t addrs[2][ETH_ALEN]; char *name; bool ap_only; + struct l_dbus_message *pending; + uint32_t cmd_id; }; struct interface_info_rec { @@ -428,13 +431,16 @@ struct interface_info_rec { static struct l_queue *radio_info; static struct l_queue *interface_info; -static struct l_dbus_message *pending_create_msg; -static uint32_t pending_create_radio_id; - static void radio_free(void *user_data) { struct radio_info_rec *rec = user_data; + if (rec->cmd_id) + l_genl_family_cancel(nl80211, rec->cmd_id); + + if (rec->pending) + l_dbus_message_unref(rec->pending); + l_free(rec->name); l_free(rec); } @@ -458,7 +464,7 @@ static void hwsim_radio_cache_cleanup(void) static bool radio_info_match_id(const void *a, const void *b) { const struct radio_info_rec *rec = a; - uint32_t id = L_PTR_TO_UINT(b); + int32_t id = L_PTR_TO_INT(b); return rec->id == id; } @@ -512,12 +518,6 @@ static const char *interface_get_path(const struct interface_info_rec *rec) return path; } -static struct l_dbus_message *dbus_error_busy(struct l_dbus_message *msg) -{ - return l_dbus_message_new_error(msg, HWSIM_SERVICE ".InProgress", - "Operation already in progress"); -} - static struct l_dbus_message *dbus_error_failed(struct l_dbus_message *msg) { return l_dbus_message_new_error(msg, HWSIM_SERVICE ".Failed", @@ -603,17 +603,19 @@ static void get_radio_callback(struct l_genl_msg *msg, void *user_data) struct l_genl_attr attr; uint16_t type, len; const void *data; - const char *name = NULL; - const uint32_t *id = NULL; - size_t name_len = 0; - struct radio_info_rec *rec; + _auto_(l_free) char *name = NULL; + const int32_t *id = NULL; + struct radio_info_rec *rec = NULL; uint8_t file_buffer[128]; int bytes, consumed; unsigned int uintval; - bool old; + bool changed = false; + bool new = false; struct radio_info_rec prev_rec; bool name_change = false; const char *path; + struct l_dbus_message *reply; + const struct l_queue_entry *entry; if (!l_genl_attr_init(&attr, msg)) return; @@ -625,11 +627,22 @@ static void get_radio_callback(struct l_genl_msg *msg, void *user_data) break; id = data; + + /* + * ID of -1 denotes a pending creation, so if somehow + * the kernel ID counter reaches an extremely high + * number of radios we just bail. + */ + if (L_WARN_ON(*id < 0)) + return; + break; case HWSIM_ATTR_RADIO_NAME: - name = data; - name_len = len; + if (name) + break; + + name = l_strndup(data, len); break; } } @@ -637,24 +650,37 @@ static void get_radio_callback(struct l_genl_msg *msg, void *user_data) if (!id || !name) return; - rec = l_queue_find(radio_info, radio_info_match_id, L_UINT_TO_PTR(*id)); - if (rec) { - old = true; - memcpy(&prev_rec, rec, sizeof(prev_rec)); + for (entry = l_queue_get_entries(radio_info); entry; + entry = entry->next) { + struct radio_info_rec *r = entry->data; - if (strlen(rec->name) != name_len || - memcmp(rec->name, name, name_len)) - name_change = true; + if (*id == r->id) { + changed = true; + memcpy(&prev_rec, r, sizeof(prev_rec)); - l_free(rec->name); - } else { - old = false; + if (strcmp(r->name, name)) + name_change = true; + + l_free(r->name); + r->name = l_steal_ptr(name); + + rec = r; + break; + } else if (!strcmp(r->name, name)) { + rec = r; + rec->id = *id; + + break; + } + } + + if (!rec) { + new = true; rec = l_new(struct radio_info_rec, 1); rec->id = *id; + rec->name = l_steal_ptr(name); } - rec->name = l_strndup(name, name_len); - l_genl_attr_init(&attr, msg); while (l_genl_attr_next(&attr, &type, &len, &data)) { @@ -726,12 +752,12 @@ static void get_radio_callback(struct l_genl_msg *msg, void *user_data) if (!radio_info) radio_info = l_queue_new(); - if (!old) + if (new) l_queue_push_tail(radio_info, rec); path = radio_get_path(rec); - if (!old) { + if (!changed) { /* Create Dbus object */ if (!l_dbus_object_add_interface(dbus, path, @@ -758,23 +784,24 @@ static void get_radio_callback(struct l_genl_msg *msg, void *user_data) } /* Send pending CreateRadio reply */ - if (pending_create_msg && pending_create_radio_id == rec->id) { - struct l_dbus_message *reply = - l_dbus_message_new_method_return(pending_create_msg); + if (rec->pending) { + reply = l_dbus_message_new_method_return(rec->pending); l_dbus_message_set_arguments(reply, "o", path); - dbus_pending_reply(&pending_create_msg, reply); + dbus_pending_reply(&rec->pending, reply); } return; err_free_radio: - if (!old) - radio_free(rec); + if (rec->pending) + dbus_pending_reply(&rec->pending, + dbus_error_failed(rec->pending)); - if (pending_create_msg && pending_create_radio_id == *id) - dbus_pending_reply(&pending_create_msg, - dbus_error_failed(pending_create_msg)); + if (!new) + l_queue_remove(radio_info, rec); + + radio_free(rec); } static bool radio_ap_only(struct radio_info_rec *rec) @@ -934,7 +961,7 @@ static void del_radio_event(struct l_genl_msg *msg) struct l_genl_attr attr; uint16_t type, len; const void *data; - const uint32_t *id = NULL; + const int32_t *id = NULL; if (!l_genl_attr_init(&attr, msg)) return; @@ -947,6 +974,9 @@ static void del_radio_event(struct l_genl_msg *msg) id = data; + if (L_WARN_ON(*id < 0)) + return; + break; } } @@ -955,7 +985,7 @@ static void del_radio_event(struct l_genl_msg *msg) return; radio = l_queue_find(radio_info, radio_info_match_id, - L_UINT_TO_PTR(*id)); + L_INT_TO_PTR(*id)); if (!radio) return; @@ -1336,11 +1366,7 @@ static void send_frame_callback(struct l_genl_msg *msg, void *user_data) { struct send_frame_info *info = user_data; - if (l_genl_msg_get_error(msg) < 0) - /* Radio address or frequency didn't match */ - l_debug("HWSIM_CMD_FRAME failed for destination %s", - util_address_to_string(info->radio->addrs[0])); - else { + if (l_genl_msg_get_error(msg) == 0) { info->frame->acked = true; info->frame->ack_radio = info->radio; } @@ -1646,44 +1672,27 @@ static void unicast_handler(struct l_genl_msg *msg, void *user_data) static void radio_manager_create_callback(struct l_genl_msg *msg, void *user_data) { + struct radio_info_rec *radio = user_data; struct l_dbus_message *reply; - struct l_genl_attr attr; - struct radio_info_rec *radio; - int err; - - /* - * Note that the radio id is returned in the error field of - * the returned message. - */ - if (l_genl_attr_init(&attr, msg)) - goto error; - err = l_genl_msg_get_error(msg); - if (err < 0) - goto error; + radio->cmd_id = 0; - pending_create_radio_id = err; + if (l_genl_msg_get_error(msg) >= 0) + return; /* - * If the NEW_RADIO event has been received we'll have added the - * radio to radio_info already but we can send the method return - * only now that we know the ID returned by our command. + * In theory pending should always be set. This is to handle the + * NEW_RADIO event coming prior to this callback and this callback + * also having an error. It doesn't seem possible for this to happen, + * but who knows. */ - radio = l_queue_find(radio_info, radio_info_match_id, - L_UINT_TO_PTR(pending_create_radio_id)); - if (radio && pending_create_msg) { - const char *path = radio_get_path(radio); - - reply = l_dbus_message_new_method_return(pending_create_msg); - l_dbus_message_set_arguments(reply, "o", path); - dbus_pending_reply(&pending_create_msg, reply); + if (radio->pending) { + reply = dbus_error_failed(radio->pending); + dbus_pending_reply(&radio->pending, reply); } - return; - -error: - reply = dbus_error_failed(pending_create_msg); - dbus_pending_reply(&pending_create_msg, reply); + l_queue_remove(radio_info, radio); + radio_free(radio); } static struct l_dbus_message *radio_manager_create(struct l_dbus *dbus, @@ -1698,9 +1707,7 @@ static struct l_dbus_message *radio_manager_create(struct l_dbus *dbus, bool p2p = false; const char *disabled_iftypes = NULL; const char *disabled_ciphers = NULL; - - if (pending_create_msg) - return dbus_error_busy(message); + struct radio_info_rec *radio; if (!l_dbus_message_get_arguments(message, "a{sv}", &dict)) goto invalid; @@ -1724,13 +1731,15 @@ static struct l_dbus_message *radio_manager_create(struct l_dbus *dbus, goto invalid; } + if (!name) + goto invalid; + new_msg = l_genl_msg_new(HWSIM_CMD_NEW_RADIO); l_genl_msg_append_attr(new_msg, HWSIM_ATTR_DESTROY_RADIO_ON_CLOSE, 0, NULL); - if (name) - l_genl_msg_append_attr(new_msg, HWSIM_ATTR_RADIO_NAME, - strlen(name) + 1, name); + l_genl_msg_append_attr(new_msg, HWSIM_ATTR_RADIO_NAME, + strlen(name) + 1, name); if (p2p) l_genl_msg_append_attr(new_msg, HWSIM_ATTR_SUPPORT_P2P_DEVICE, @@ -1756,11 +1765,19 @@ static struct l_dbus_message *radio_manager_create(struct l_dbus *dbus, } - l_genl_family_send(hwsim, new_msg, radio_manager_create_callback, - pending_create_msg, NULL); + radio = l_new(struct radio_info_rec, 1); + radio->pending = l_dbus_message_ref(message); + radio->name = l_strdup(name); + radio->id = -1; - pending_create_msg = l_dbus_message_ref(message); - pending_create_radio_id = 0; + if (!radio_info) + radio_info = l_queue_new(); + + l_queue_push_tail(radio_info, radio); + + radio->cmd_id = l_genl_family_send(hwsim, new_msg, + radio_manager_create_callback, + radio, NULL); return NULL; @@ -3092,9 +3109,6 @@ int main(int argc, char *argv[]) l_genl_family_free(nl80211); l_genl_unref(genl); - if (pending_create_msg) - l_dbus_message_unref(pending_create_msg); - l_dbus_destroy(dbus); hwsim_radio_cache_cleanup(); l_queue_destroy(rules, l_free); diff --git a/tools/iwd-decrypt-profile.c b/tools/iwd-decrypt-profile.c @@ -0,0 +1,212 @@ +/* + * + * Wireless daemon for Linux + * + * Copyright (C) 2022 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 + * + */ + +#include <stdio.h> +#include <unistd.h> +#include <fcntl.h> +#include <sys/stat.h> +#include <sys/mman.h> +#include <getopt.h> + +#include <ell/ell.h> + +#include "ell/useful.h" + +#include "src/storage.h" +#include "src/common.h" + +static void usage(void) +{ + printf("decrypt-profile - Decrypt a network profile\n" + "Usage:\n"); + printf("\tdecrypt-profile [--pass | --file] [OPTIONS]\n"); + printf("\n\tEither --pass or --file must be provided. The profile\n"); + printf("\tshould be supplied using --infile.\n"); + printf("\tThe --name argument must be used if the name cannot be\n"); + printf("\tinferred from the input file\n\n"); + printf("Options:\n" + "\t-p, --pass Password/key used to encrypt\n" + "\t-f, --file File containing key\n" + "\t-s, --name Name for associated profile (will\n" + "\t be inferred from --infile if not\n" + "\t provided). For non hotspot networks\n" + "\t this will be the SSID.\n" + "\t-i, --infile Input profile\n" + "\t-o, --outfile Output file for decrypted profile\n" + "\t-h, --help Show help options\n"); + printf("\n"); +} + +static const struct option main_options[] = { + { "pass", required_argument, NULL, 'p' }, + { "file", required_argument, NULL, 'f' }, + { "infile", required_argument, NULL, 'i' }, + { "outfile", required_argument, NULL, 'o' }, + { "name", required_argument, NULL, 'n' }, + { "help", no_argument, NULL, 'h' }, + { } +}; + +static bool secret_from_file(const char *file) +{ + int fd; + struct stat st; + void *data = NULL; + bool r; + + fd = open(file, O_RDONLY, 0); + if (fd < 0) { + printf("Cant open %s (%d)\n", file, fd); + return false; + } + + if (fstat(fd, &st) < 0 || st.st_size == 0) { + close(fd); + return false; + } + + data = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0); + close(fd); + + if (data == MAP_FAILED) + return false; + + r = storage_init(data, st.st_size); + + munmap(data, st.st_size); + + return r; +} + +int main(int argc, char *argv[]) +{ + const char *pass = NULL; + const char *file = NULL; + const char *infile = NULL; + const char *outfile = NULL; + const char *name = NULL; + _auto_(l_free) char *decrypted = NULL; + _auto_(l_settings_free) struct l_settings *settings = NULL; + enum security sec; + int ret = EXIT_FAILURE; + ssize_t len = 0; + int r; + + for (;;) { + int opt; + + opt = getopt_long(argc, argv, "pfhion", main_options, NULL); + if (opt < 0) + break; + + switch (opt) { + case 'p': + pass = optarg; + break; + case 'f': + file = optarg; + break; + case 'i': + infile = optarg; + break; + case 'o': + outfile = optarg; + break; + case 'n': + name = optarg; + break; + case 'h': + usage(); + return EXIT_SUCCESS; + default: + goto failed; + } + } + + if (!file && !pass) { + printf("--file or --pass must be supplied\n\n"); + goto usage; + } + + if (!infile) { + printf("--infile must be supplied\n\n"); + goto usage; + } + + if (!name) { + name = storage_network_ssid_from_path(infile, &sec); + if (!name) { + printf("Can't get name from --infile, use --name\n\n"); + goto usage; + } + } + + settings = l_settings_new(); + + if (!l_settings_load_from_file(settings, infile)) { + printf("Profile is not formatted correctly\n"); + goto failed; + } + + if (pass) { + if (!storage_init((const uint8_t *)pass, strlen(pass))) + goto failed; + } else if (!secret_from_file(file)) + goto failed; + + r = __storage_decrypt(settings, name, NULL); + if (r < 0) { + printf("Unable to decrypt profile (%d)\n", r); + goto failed; + } + + decrypted = l_settings_to_data(settings, (size_t *)&len); + + if (!outfile) + fwrite(decrypted, 1, len, stdout); + else { + int fd = open(outfile, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR); + + if (fd < 0) { + printf("Unable to open %s (%d)\n", outfile, fd); + goto failed; + } + + len = write(fd, decrypted, len); + + close(fd); + + if (len < 0) { + printf("Unable to write to %s (%zd)\n", outfile, len); + goto failed; + } + } + + ret = EXIT_SUCCESS; + +usage: + if (ret != EXIT_SUCCESS) + usage(); + +failed: + return ret; +} diff --git a/tools/test-runner b/tools/test-runner @@ -676,7 +676,10 @@ class Namespace: '--show-leak-kinds=all', '--log-file=/tmp/valgrind.log.%p']) - args.extend(['iwd', '-p', iwd_radios, '-E']) + args.extend(['iwd', '-E']) + + if iwd_radios != '': + args.extend(['-p', iwd_radios]) if self.is_verbose(args[0]): args.append('-d') diff --git a/unit/test-dpp.c b/unit/test-dpp.c @@ -33,6 +33,131 @@ #include "src/util.h" #include "ell/useful.h" +struct dpp_test_info { + const char *uri; + bool expect_fail; + uint32_t expected_freqs[10]; + struct dpp_uri_info result; +}; + +struct dpp_test_info all_values = { + .uri = "DPP:C:81/1,115/36;I:SN=4774LH2b4044;M:5254005828e5;V:2;K:MDkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDIgADURzxmttZoIRIPWGoQMV00XHWCAQIhXruVWOz0NjlkIA=;;", + .result = { + .mac = { 0x52, 0x54, 0x00, 0x58, 0x28, 0xe5 }, + .version = 2, + }, + .expected_freqs = { 2412, 5180, 0 } +}; + +struct dpp_test_info no_type = { + .uri = "C:81/1;K:shouldnotmatter;;", + .expect_fail = true +}; + +struct dpp_test_info empty = { + .uri = "DPP:", + .expect_fail = true +}; + +struct dpp_test_info no_key = { + .uri = "DPP:C:81/1,115/36;I:SN=4774LH2b4044;M:5254005828e5;V:2;;", + .expect_fail = true +}; + +struct dpp_test_info data_after_terminator = { + .uri = "DPP:K:MDkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDIgADURzxmttZoIRIPWGoQMV00XHWCAQIhXruVWOz0NjlkIA=;;C:81/1;;", + .expect_fail = true +}; + +struct dpp_test_info single_terminator = { + .uri = "DPP:K:MDkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDIgADURzxmttZoIRIPWGoQMV00XHWCAQIhXruVWOz0NjlkIA=;", + .expect_fail = true +}; + +struct dpp_test_info no_terminator = { + .uri = "DPP:K:MDkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDIgADURzxmttZoIRIPWGoQMV00XHWCAQIhXruVWOz0NjlkIA=", + .expect_fail = true +}; + +struct dpp_test_info bad_key = { + .uri = "DPP:K:MDkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDIgADURzxmttZoIRIPWGoQMV00XHWCAQIhXruVWOz0;;", + .expect_fail = true +}; + +struct dpp_test_info unexpected_id = { + .uri = "DPP:Z:somedata;K:MDkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDIgADURzxmttZoIRIPWGoQMV00XHWCAQIhXruVWOz0NjlkIA=;;", + .expect_fail = true +}; + +struct dpp_test_info bad_channels[] = { + { + .uri = "DPP:C:;K:MDkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDIgADURzxmttZoIRIPWGoQMV00XHWCAQIhXruVWOz0NjlkIA=;;", + .expect_fail = true + }, + { + .uri = "DPP:C:81;K:MDkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDIgADURzxmttZoIRIPWGoQMV00XHWCAQIhXruVWOz0NjlkIA=;;", + .expect_fail = true + }, + { + .uri = "DPP:C:81/;K:MDkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDIgADURzxmttZoIRIPWGoQMV00XHWCAQIhXruVWOz0NjlkIA=;;", + .expect_fail = true + }, + { + .uri = "DPP:C:81/1,;K:MDkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDIgADURzxmttZoIRIPWGoQMV00XHWCAQIhXruVWOz0NjlkIA=;;", + .expect_fail = true + }, + { + .uri = "DPP:C:81/1,81/;K:MDkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDIgADURzxmttZoIRIPWGoQMV00XHWCAQIhXruVWOz0NjlkIA=;;", + .expect_fail = true + }, + { + .uri = "DPP:C:81/1,/;K:MDkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDIgADURzxmttZoIRIPWGoQMV00XHWCAQIhXruVWOz0NjlkIA=;;", + .expect_fail = true + }, +}; + +static bool verify_info(const struct dpp_uri_info *parsed, + const struct dpp_test_info *result) +{ + const struct dpp_uri_info *expected = &result->result; + uint32_t i; + + assert(!memcmp(parsed->mac, expected->mac, 6)); + assert(parsed->version == expected->version); + assert(parsed->boot_public != NULL); + + for (i = 0; result->expected_freqs[i]; i++) + assert(scan_freq_set_contains(parsed->freqs, + result->expected_freqs[i])); + + return true; +} + +static void test_uri_parse(const void *data) +{ + const struct dpp_test_info *test_info = data; + struct dpp_uri_info *info; + + info = dpp_parse_uri(test_info->uri); + if (test_info->expect_fail) { + assert(info == NULL); + return; + } + + assert(verify_info(info, test_info)); + + dpp_free_uri_info(info); +} + + +static void test_bad_channels(const void *data) +{ + unsigned int i; + + for (i = 0; i < L_ARRAY_SIZE(bad_channels); i++) + test_uri_parse(&bad_channels[i]); +} + /* * B.2 Test Vectors for DPP Authentication Using P-256 for * Responder-only Authentication @@ -148,5 +273,19 @@ int main(int argc, char *argv[]) l_test_add("DPP test key derivation", test_key_derivation, NULL); + l_test_add("DPP URI parse", test_uri_parse, &all_values); + l_test_add("DPP URI no type", test_uri_parse, &no_type); + l_test_add("DPP URI empty", test_uri_parse, &empty); + l_test_add("DPP URI no key", test_uri_parse, &no_key); + l_test_add("DPP URI data after terminator", test_uri_parse, + &data_after_terminator); + l_test_add("DPP URI single terminator", test_uri_parse, + &single_terminator); + l_test_add("DPP URI no terminator", test_uri_parse, + &no_terminator); + l_test_add("DPP URI bad key", test_uri_parse, &bad_key); + l_test_add("DPP URI bad channels", test_bad_channels, &bad_channels); + l_test_add("DPP URI unexpected ID", test_uri_parse, &unexpected_id); + return l_test_run(); } diff --git a/wired/ead-dbus.conf b/wired/ead-dbus.conf @@ -15,12 +15,10 @@ <policy group="wheel"> <allow send_destination="net.connman.ead"/> - <allow send_interface="net.connman.ead.Agent"/> </policy> - <policy at_console="true"> + <policy group="netdev"> <allow send_destination="net.connman.ead"/> - <allow send_interface="net.connman.ead.Agent"/> </policy> <policy context="default">