eiwd

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

commit 52d75f5239c3f1328947bee2e527ff386b65c8bd
parent 343df8d99f51a1467f504b777c040eba5d90a859
Author: illiliti <illiliti@protonmail.com>
Date:   Fri, 17 Sep 2021 04:06:06 +0300

Merge tag '1.18'

Release 1.18

Diffstat:
MChangeLog | 6++++++
MTODO | 43++++++++++---------------------------------
Mautotests/testNetconfig/connection_test.py | 6+++---
Mautotests/testNetconfig/static_test.py | 6+++---
Mautotests/testOWE/hw.conf | 3+--
Dautotests/testOWE/renegotiate_test.py | 60------------------------------------------------------------
Dautotests/testOWE/ssidGroup20.conf | 8--------
Mautotests/testP2P/connection_test.py | 26+++++++++++++++-----------
Mautotests/testSAE-roam/connection_test.py | 6+++---
Mautotests/testSAE/autoconnect_test.py | 8++++----
Mautotests/testSAE/connection_test.py | 34+++++++++++++++++++++++++---------
Mautotests/testSAE/failure_test.py | 15++++++++++++---
Mautotests/testSAE/timeout_test.py | 61++++++++++++++++++++++++++++++++++++++++++++++---------------
Mautotests/testSAQuery/connection_test.py | 5++++-
Mautotests/util/hostapd.py | 87+++++++++++++++++++++++++++----------------------------------------------------
Mautotests/util/hwsim.py | 67+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mautotests/util/iwd.py | 2+-
Mautotests/util/testutil.py | 4++--
Mautotests/util/wpas.py | 1+
Mconfigure.ac | 4++--
Mmonitor/main.c | 2+-
Msrc/ap.c | 284+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Msrc/auth-proto.h | 15+++++++++++++++
Msrc/eapol.c | 17+++++++++++++++++
Msrc/fils.c | 2+-
Msrc/handshake.c | 2++
Msrc/handshake.h | 3+++
Msrc/ie.c | 389+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Msrc/ie.h | 43+++++++++++++++++++++++++++++++++++++++++++
Msrc/mpdu.h | 1+
Msrc/netconfig.c | 490++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------
Msrc/netconfig.h | 11+++++++++--
Msrc/netdev.c | 651+++++++++++++++++++++++++++++++++++++++++++++++--------------------------------
Msrc/owe.c | 148++++++++-----------------------------------------------------------------------
Msrc/owe.h | 12+++++-------
Msrc/p2p.c | 13+++++++++++--
Msrc/sae.c | 100++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Msrc/sae.h | 2++
Msrc/scan.c | 33++++++++++++++++++++++++---------
Msrc/scan.h | 3+++
Msrc/station.c | 67+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Msrc/util.h | 14++++++++++++++
Msrc/wsc.c | 1+
Mtools/hwsim.c | 199+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mtools/test-runner | 341+++++++++++++++++++++++++++++++++++++++++--------------------------------------
Munit/test-eapol.c | 6+++---
46 files changed, 2368 insertions(+), 933 deletions(-)

diff --git a/ChangeLog b/ChangeLog @@ -1,3 +1,9 @@ +ver 1.18: + Add support for Access Point FILS IP Address Assignment IE. + Add support for P2P GO-side 4-way handshake IP allocation. + Add support for forcing SAE group 19 if BSS requires it. + Fix issue with handling faulty SAE duplicate commits. + ver 1.17: Fix issue with sending additional and vendor IEs. Fix issue with IE ordering for 802.11-2020 support. diff --git a/TODO b/TODO @@ -199,11 +199,6 @@ Wireless daemon Priority: Low Complexity: C4 -- Add support for 802.11u. This is required for Passpoint 2.0 support. - - Priority: Low - Complexity: C8 - - Add support for Wireless Network Management (WNM) from 802.11v. Parts of this are needed for Passpoint support. @@ -237,18 +232,6 @@ Wireless daemon Priority: Low Complexity: C4 -- Take EAP MSK size into consideration. - - MSK is mandated to be 64 bytes long, and depending on the AKM, different parts - of the MSK are used to generate keys. Some EAP methods produce MSKs with less - than 64 bytes of useable data. For example, LEAP produces only 16 bytes and - MSCHAPv2 produces 32 bytes. If the AKM requires MSK of a certain size, and - the EAP method does not provide enough data, then the handshake should be - aborted. - - Priority: Medium - Complexity: C2 - - Implement Enrollee Session Overlap Detection after WSC Protocol Run WSC Best Practices v2.0.1, Section 3.15 describes an enhacement to detect @@ -349,24 +332,18 @@ Wireless daemon Priority: Medium Complexity: C4 -- Support Diagnostics interface - The diagnostic interface for a particular Device would contain information - (and possibly operations) that would be meant for diagnostics applications - or other applications that require access to very low level details. Such - applications would be expected how to interpret this information - appropriately. +Network Configuration +===================== - This interface would also be heavily utilized by the Auto-Test framework - in order to more easily ascertain the internal state of the hardware & the - daemon itself. +- Support elements of RFC4436 - DNAv4 - The list of possible information exposed via this interface includes: - - MAC address of the currently connected AP (in a Station) - - MAC addresses of currently connected clients (Adhoc, AP, etc) - - packet error rates or signal strength - - Throughput statistics - - FTM / direction finding operations + Assumption: netconfig is able to save lease information for networks that + have been joined previously and does not release the lease when the network + is left temporarily. - Priority: Medium + Attempt to re-assume the lease via methods described in DNAv4 if we attempt + to rejoin a network and the lease has not expired yet. + + Priority: Low Complexity: C4 diff --git a/autotests/testNetconfig/connection_test.py b/autotests/testNetconfig/connection_test.py @@ -59,9 +59,9 @@ class Test(unittest.TestCase): # TODO: This could be moved into test-runner itself if other tests ever # require this functionality (p2p, FILS, etc.). Since its simple # enough it can stay here for now. - ctx.start_process(['ifconfig', hapd.ifname, '192.168.1.1', 'netmask', '255.255.255.0'], - wait=True) - ctx.start_process(['touch', '/tmp/dhcpd.leases'], wait=True) + ctx.start_process(['ifconfig', hapd.ifname, '192.168.1.1', + 'netmask', '255.255.255.0']).wait() + ctx.start_process(['touch', '/tmp/dhcpd.leases']).wait() cls.dhcpd_pid = ctx.start_process(['dhcpd', '-f', '-cf', '/tmp/dhcpd.conf', '-lf', '/tmp/dhcpd.leases', hapd.ifname], cleanup=remove_lease) diff --git a/autotests/testNetconfig/static_test.py b/autotests/testNetconfig/static_test.py @@ -86,9 +86,9 @@ class Test(unittest.TestCase): # TODO: This could be moved into test-runner itself if other tests ever # require this functionality (p2p, FILS, etc.). Since its simple # enough it can stay here for now. - ctx.start_process(['ifconfig', hapd.ifname, '192.168.1.1', 'netmask', '255.255.255.0'], - wait=True) - ctx.start_process(['touch', '/tmp/dhcpd.leases'], wait=True) + ctx.start_process(['ifconfig', hapd.ifname, '192.168.1.1', + 'netmask', '255.255.255.0']).wait() + ctx.start_process(['touch', '/tmp/dhcpd.leases']).wait() cls.dhcpd_pid = ctx.start_process(['dhcpd', '-f', '-cf', '/tmp/dhcpd.conf', '-lf', '/tmp/dhcpd.leases', hapd.ifname], cleanup=remove_lease) diff --git a/autotests/testOWE/hw.conf b/autotests/testOWE/hw.conf @@ -1,8 +1,7 @@ [SETUP] -num_radios=4 +num_radios=3 hwsim_medium=yes [HOSTAPD] rad0=ssidOWE-1.conf rad1=ssidOWE-2.conf -rad2=ssidGroup20.conf diff --git a/autotests/testOWE/renegotiate_test.py b/autotests/testOWE/renegotiate_test.py @@ -1,60 +0,0 @@ -#!/usr/bin/python3 - -import unittest -import sys - -sys.path.append('../util') -import iwd -from iwd import IWD -from iwd import NetworkType -from hostapd import HostapdCLI -import testutil - -class Test(unittest.TestCase): - - def test_connection_success(self): - hapd = HostapdCLI(config='ssidGroup20.conf') - - wd = IWD() - - devices = wd.list_devices(1) - device = devices[0] - - condition = 'not obj.scanning' - wd.wait_for_object_condition(device, condition) - - device.scan() - - condition = 'not obj.scanning' - wd.wait_for_object_condition(device, condition) - - ordered_network = device.get_ordered_network('ssidGroup20') - - self.assertEqual(ordered_network.type, NetworkType.open) - - 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) - - testutil.test_iface_operstate() - testutil.test_ifaces_connected(device.name, hapd.ifname) - - device.disconnect() - - condition = 'not obj.connected' - wd.wait_for_object_condition(ordered_network.network_object, condition) - - @classmethod - def setUpClass(cls): - pass - - @classmethod - def tearDownClass(cls): - IWD.clear_storage() - -if __name__ == '__main__': - unittest.main(exit=True) diff --git a/autotests/testOWE/ssidGroup20.conf b/autotests/testOWE/ssidGroup20.conf @@ -1,8 +0,0 @@ -ctrl_interface=/var/run/hostapd -hw_mode=g -channel=1 -ssid=ssidGroup20 -wpa=2 -wpa_key_mgmt=OWE -rsn_pairwise=CCMP -owe_groups=20 diff --git a/autotests/testP2P/connection_test.py b/autotests/testP2P/connection_test.py @@ -2,7 +2,6 @@ import unittest import sys -import netifaces import os import time @@ -91,9 +90,10 @@ class Test(unittest.TestCase): wd.wait_for_object_condition(wpas, 'obj.p2p_group is not None', max_wait=3) peer_ifname = wpas.p2p_group['ifname'] + self.assertEqual(wpas.p2p_group['role'], 'GO' if not go else 'client') if not go: - ctx.start_process(['ifconfig', peer_ifname, '192.168.1.20', 'netmask', '255.255.255.0'], wait=True) + ctx.start_process(['ifconfig', peer_ifname, '192.168.1.20', 'netmask', '255.255.255.0']).wait() os.system('> /tmp/dhcp.leases') dhcp = ctx.start_process(['dhcpd', '-f', '-cf', '/tmp/dhcpd.conf', '-lf', '/tmp/dhcp.leases', peer_ifname]) self.dhcp = dhcp @@ -102,22 +102,23 @@ class Test(unittest.TestCase): client = wpas.p2p_clients[request['peer_iface']] self.assertEqual(client['p2p_dev_addr'], wpas_peer['p2p_dev_addr']) else: + self.assertEqual(wpas.p2p_group['ip_addr'], '192.168.1.2') + self.assertEqual(wpas.p2p_group['ip_mask'], '255.255.255.240') + self.assertEqual(wpas.p2p_group['go_ip_addr'], '192.168.1.1') dhcp = ctx.start_process(['dhclient', '-v', '-d', '--no-pid', '-cf', '/dev/null', '-lf', '/tmp/dhcp.leases', '-sf', '/tmp/dhclient-script', peer_ifname]) self.dhcp = dhcp wd.wait_for_object_condition(peer, 'obj.connected', max_wait=15) time.sleep(1) # Give the client time to set the IP - our_ip = netifaces.ifaddresses(peer.connected_interface)[netifaces.AF_INET][0]['addr'] - peer_ip = netifaces.ifaddresses(peer_ifname)[netifaces.AF_INET][0]['addr'] - self.assertEqual(peer.connected_ip, peer_ip) + testutil.test_ip_address_match(peer_ifname, peer.connected_ip) if not go: - self.assertEqual(our_ip, '192.168.1.30') - self.assertEqual(peer_ip, '192.168.1.20') + testutil.test_ip_address_match(peer.connected_interface, '192.168.1.30') + self.assertEqual(peer.connected_ip, '192.168.1.20') else: - self.assertEqual(our_ip, '192.168.1.1') - self.assertEqual(peer_ip, '192.168.1.2') + testutil.test_ip_address_match(peer.connected_interface, '192.168.1.1') + self.assertEqual(peer.connected_ip, '192.168.1.2') testutil.test_iface_operstate(peer.connected_interface) testutil.test_ifaces_connected(peer.connected_interface, peer_ifname) @@ -126,7 +127,7 @@ class Test(unittest.TestCase): if not go: wd.wait_for_object_condition(wpas, 'len(obj.p2p_clients) == 0', max_wait=3) else: - wd.wait_for_object_condition(wpas, 'obj.p2p_group is None', max_wait=3) + wd.wait_for_object_condition(wpas, 'obj.p2p_group is None', max_wait=15) self.assertEqual(peer.connected, False) def setUp(self): @@ -136,7 +137,10 @@ class Test(unittest.TestCase): def tearDown(self): if self.p2p is not None: - self.p2p.enabled = False + try: + self.p2p.enabled = False + except: + pass if self.wpas is not None: self.wpas.clean_up() self.wpas = None diff --git a/autotests/testSAE-roam/connection_test.py b/autotests/testSAE-roam/connection_test.py @@ -125,11 +125,11 @@ class Test(unittest.TestCase): HostapdCLI(config='ft-psk-3.conf') ] ctx.start_process(['ifconfig', cls.bss_hostapd[0].ifname, 'down', 'hw', \ - 'ether', '12:00:00:00:00:01', 'up'], wait=True) + 'ether', '12:00:00:00:00:01', 'up']).wait() ctx.start_process(['ifconfig', cls.bss_hostapd[1].ifname, 'down', 'hw', \ - 'ether', '12:00:00:00:00:02', 'up'], wait=True) + 'ether', '12:00:00:00:00:02', 'up']).wait() ctx.start_process(['ifconfig', cls.bss_hostapd[2].ifname, 'down', 'hw', \ - 'ether', '12:00:00:00:00:03', 'up'], wait=True) + 'ether', '12:00:00:00:00:03', 'up']).wait() # Set interface addresses to those expected by hostapd config files cls.bss_hostapd[0].reload() diff --git a/autotests/testSAE/autoconnect_test.py b/autotests/testSAE/autoconnect_test.py @@ -35,8 +35,8 @@ class Test(unittest.TestCase): wd.wait_for_object_condition(ordered_network.network_object, condition) def test_SAE(self): - self.hostapd.set_value('sae_pwe', '0'); - self.hostapd.set_value('sae_groups', '19'); + self.hostapd.set_value('sae_pwe', '0') + self.hostapd.set_value('sae_groups', '19') self.hostapd.reload() self.hostapd.wait_for_event("AP-ENABLED") @@ -44,8 +44,8 @@ class Test(unittest.TestCase): self.validate_connection(wd) def test_SAE_H2E(self): - self.hostapd.set_value('sae_pwe', '1'); - self.hostapd.set_value('sae_groups', '20'); + self.hostapd.set_value('sae_pwe', '1') + self.hostapd.set_value('sae_groups', '20') self.hostapd.reload() self.hostapd.wait_for_event("AP-ENABLED") wd = IWD(True) diff --git a/autotests/testSAE/connection_test.py b/autotests/testSAE/connection_test.py @@ -25,7 +25,7 @@ class Test(unittest.TestCase): wd.wait_for_object_condition(device, 'not obj.scanning') - device.scan() + device.debug_scan([2412]) wd.wait_for_object_condition(device, 'obj.scanning') wd.wait_for_object_condition(device, 'not obj.scanning') @@ -57,8 +57,21 @@ class Test(unittest.TestCase): wd.unregister_psk_agent(psk_agent) def test_SAE(self): - self.hostapd.set_value('sae_pwe', '0'); - self.hostapd.set_value('sae_groups', '19'); + self.hostapd.set_value('sae_pwe', '0') + self.hostapd.set_value('sae_groups', '19') + self.hostapd.set_value('vendor_elements', '') + self.hostapd.reload() + self.hostapd.wait_for_event("AP-ENABLED") + wd = IWD(True) + self.validate_connection(wd) + wd.clear_storage() + + def test_SAE_force_group_19(self): + self.hostapd.set_value('sae_pwe', '0') + self.hostapd.set_value('sae_groups', '19') + # Vendor data from APs which require group 19 be used first + # TODO: (for all tests) verify the expected group was used + self.hostapd.set_value('vendor_elements', 'dd0cf4f5e8050500000000000000') self.hostapd.reload() self.hostapd.wait_for_event("AP-ENABLED") wd = IWD(True) @@ -66,8 +79,9 @@ class Test(unittest.TestCase): wd.clear_storage() def test_SAE_Group20(self): - self.hostapd.set_value('sae_pwe', '0'); - self.hostapd.set_value('sae_groups', '20'); + self.hostapd.set_value('sae_pwe', '0') + self.hostapd.set_value('sae_groups', '20') + self.hostapd.set_value('vendor_elements', '') self.hostapd.reload() self.hostapd.wait_for_event("AP-ENABLED") wd = IWD(True) @@ -75,8 +89,9 @@ class Test(unittest.TestCase): wd.clear_storage() def test_SAE_H2E(self): - self.hostapd.set_value('sae_pwe', '1'); - self.hostapd.set_value('sae_groups', '19'); + self.hostapd.set_value('sae_pwe', '1') + self.hostapd.set_value('sae_groups', '19') + self.hostapd.set_value('vendor_elements', '') self.hostapd.reload() self.hostapd.wait_for_event("AP-ENABLED") wd = IWD(True) @@ -84,8 +99,9 @@ class Test(unittest.TestCase): wd.clear_storage() def test_SAE_H2E_Group20(self): - self.hostapd.set_value('sae_pwe', '1'); - self.hostapd.set_value('sae_groups', '20'); + self.hostapd.set_value('sae_pwe', '1') + self.hostapd.set_value('sae_groups', '20') + self.hostapd.set_value('vendor_elements', '') self.hostapd.reload() self.hostapd.wait_for_event("AP-ENABLED") wd = IWD(True) diff --git a/autotests/testSAE/failure_test.py b/autotests/testSAE/failure_test.py @@ -8,11 +8,12 @@ import iwd from iwd import IWD from iwd import PSKAgent from iwd import NetworkType +from hostapd import HostapdCLI class Test(unittest.TestCase): - def validate_connection(self, wd): - psk_agent = PSKAgent("InvalidSecret") + def validate_connection(self, wd, passphrase): + psk_agent = PSKAgent(passphrase) wd.register_psk_agent(psk_agent) devices = wd.list_devices(1) @@ -33,7 +34,15 @@ class Test(unittest.TestCase): def test_connection_success(self): wd = IWD(True) - self.validate_connection(wd) + self.validate_connection(wd, 'InvalidSecret') + + def test_no_supported_groups(self): + hostapd = HostapdCLI(config='ssidSAE.conf') + hostapd.set_value('sae_groups', '1') + hostapd.reload() + + wd = IWD(True) + self.validate_connection(wd, 'secret123') @classmethod def setUpClass(cls): diff --git a/autotests/testSAE/timeout_test.py b/autotests/testSAE/timeout_test.py @@ -9,13 +9,12 @@ from iwd import IWD from iwd import PSKAgent from iwd import NetworkType from hwsim import Hwsim +from hostapd import HostapdCLI +from config import ctx class Test(unittest.TestCase): def validate_connection(self, wd): - hwsim = Hwsim() - bss_radio = hwsim.get_radio('rad0') - psk_agent = PSKAgent(["secret123", "secret123"]) wd.register_psk_agent(psk_agent) @@ -30,32 +29,64 @@ class Test(unittest.TestCase): condition = 'not obj.connected' wd.wait_for_object_condition(network.network_object, condition) + network.network_object.connect() + + condition = 'obj.state == DeviceState.connected' + wd.wait_for_object_condition(device, condition) + + def test_not_acked_commit(self): + # + # TODO: This merely forces group 19 by acting as a 'buggy' AP. This is + # needed because the hwsim rule only matches once and must be matched + # on the first commit, not during group negotiation. + # + hostapd = HostapdCLI(config='ssidSAE.conf') + hostapd.set_value('vendor_elements', 'dd0cf4f5e8050500000000000000') + hostapd.set_value('sae_groups', '19') + hostapd.reload() + + hwsim = Hwsim() + bss_radio = hwsim.get_radio('rad0') + rule0 = hwsim.rules.create() rule0.source = bss_radio.addresses[0] - rule0.bidirectional = True rule0.drop = True rule0.prefix = 'b0' + rule0.match = '01 00 00 00 13 00' + rule0.match_offset = 26 + rule0.match_times = 1 + rule0.drop_ack = True rule0.enabled = True - wd.wait(1) - print(rule0) + wd = IWD(True) + self.validate_connection(wd) - with self.assertRaises(iwd.FailedEx): - network.network_object.connect() + rule0.remove() - condition = 'not obj.connected' - wd.wait_for_object_condition(network.network_object, condition) + def test_sta_confirm_not_acked(self): + hostapd = HostapdCLI(config='ssidSAE.conf') + hostapd.set_value('vendor_elements', 'dd0cf4f5e8050500000000000000') + hostapd.set_value('sae_groups', '19') + hostapd.reload() - rule0.prefix = '00' - with self.assertRaises(iwd.FailedEx): - network.network_object.connect() + hwsim = Hwsim() + bss_radio = hwsim.get_radio('rad0') - wd.unregister_psk_agent(psk_agent) + rule0 = hwsim.rules.create() + rule0.source = bss_radio.addresses[0] + rule0.drop = True + rule0.prefix = 'b0' + rule0.match = '02 00 00 00' + rule0.match_offset = 26 + rule0.match_times = 1 + rule0.drop_ack = True + rule0.enabled = True - def test_connection_success(self): wd = IWD(True) self.validate_connection(wd) + rule0.remove() + @classmethod def setUpClass(cls): pass diff --git a/autotests/testSAQuery/connection_test.py b/autotests/testSAQuery/connection_test.py @@ -38,7 +38,10 @@ class Test(unittest.TestCase): # Make AP go down ungracefully, when hostapd comes back up it should # send an unprotected disassociate frame so the client will re-auth. # This will kick off the SA Query procedure - hostapd.ungraceful_restart() + hostapd.interface.set_interface_state('down') + hostapd.interface.set_interface_state('up') + + hostapd.wait_for_event('INTERFACE-ENABLED') condition = 'not obj.connected' wd.wait_for_object_condition(ordered_network.network_object, condition) diff --git a/autotests/util/hostapd.py b/autotests/util/hostapd.py @@ -5,6 +5,7 @@ import socket import select import time from gi.repository import GLib +from weakref import WeakValueDictionary from config import ctx chan_freq_map = [ @@ -29,7 +30,7 @@ ctrl_count = 0 mainloop = GLib.MainLoop() class HostapdCLI(object): - _instances = {} + _instances = WeakValueDictionary() def __new__(cls, config=None, *args, **kwargs): hapd = ctx.hostapd[config] @@ -38,15 +39,17 @@ class HostapdCLI(object): config = hapd.config if not config in cls._instances.keys(): - cls._instances[config] = object.__new__(cls, *args, **kwargs) - cls._instances[config]._initialized = False + obj = object.__new__(cls, *args, **kwargs) + obj._initialized = False + + cls._instances[config] = obj return cls._instances[config] - def _init_hostapd(self, config, reinit=False): + def __init__(self, config=None, *args, **kwargs): global ctrl_count - if self._initialized and not reinit: + if self._initialized: return self._initialized = True @@ -83,9 +86,6 @@ class HostapdCLI(object): ctrl_count = ctrl_count + 1 - def __init__(self, config=None, *args, **kwargs): - self._init_hostapd(config) - def _poll_event(self, event): if not self._data_available(0.25): return False @@ -117,41 +117,29 @@ class HostapdCLI(object): return self.ctrl_sock.recv(4096).decode('utf-8') - def _del_hostapd(self, force=False): - if not self.ctrl_sock: - return - - self.ctrl_sock.close() + def __del__(self): + if self.ctrl_sock: + self.ctrl_sock.close() try: os.remove(self.local_ctrl) except: pass - def __del__(self): - self._del_hostapd() - - HostapdCLI._instances[self.config] = None - - # Check if this is the final instance - destroy = len([hapd for hapd in HostapdCLI._instances.values() if hapd is not None]) == 0 - if destroy: - HostapdCLI._instances = {} - def set_value(self, key, value): cmd = self.cmdline + ['set', key, value] - ctx.start_process(cmd, wait=True) + ctx.start_process(cmd).wait() def wps_push_button(self): - ctx.start_process(self.cmdline + ['wps_pbc'], wait=True) + ctx.start_process(self.cmdline + ['wps_pbc']).wait() def wps_pin(self, pin): cmd = self.cmdline + ['wps_pin', 'any', pin] - ctx.start_process(cmd, wait=True) + ctx.start_process(cmd).wait() def deauthenticate(self, client_address): cmd = self.cmdline + ['deauthenticate', client_address] - ctx.start_process(cmd, wait=True) + ctx.start_process(cmd).wait() def eapol_reauth(self, client_address): cmd = 'IFNAME=' + self.ifname + ' EAPOL_REAUTH ' + client_address @@ -160,12 +148,13 @@ class HostapdCLI(object): def reload(self): # Seemingly all three commands needed for the instance to notice # interface's address change - ctx.start_process(self.cmdline + ['reload'], wait=True) - ctx.start_process(self.cmdline + ['disable'], wait=True) - ctx.start_process(self.cmdline + ['enable'], wait=True) + ctx.start_process(self.cmdline + ['reload']).wait() + ctx.start_process(self.cmdline + ['disable']).wait() + ctx.start_process(self.cmdline + ['enable']).wait() def list_sta(self): - proc = ctx.start_process(self.cmdline + ['list_sta'], wait=True, need_out=True) + proc = ctx.start_process(self.cmdline + ['list_sta']) + proc.wait() if not proc.out: return [] @@ -174,7 +163,7 @@ class HostapdCLI(object): def set_neighbor(self, addr, ssid, nr): cmd = self.cmdline + ['set_neighbor', addr, 'ssid="%s"' % ssid, 'nr=%s' % nr] - ctx.start_process(cmd, wait=True) + ctx.start_process(cmd).wait() def send_bss_transition(self, device, nr_list): # Send a BSS transition to a station (device). nr_list should be an @@ -197,42 +186,25 @@ class HostapdCLI(object): (addr, bss_info, op_class, chan_num, phy_num)] pref += 1 - proc = ctx.start_process(cmd, wait=True, need_out=True) + proc = ctx.start_process(cmd) + proc.wait() if 'OK' not in proc.out: raise Exception('BSS_TM_REQ failed, is hostapd built with CONFIG_WNM_AP=y?') - def ungraceful_restart(self): - ''' - Ungracefully kill and restart hostapd - ''' - ctx.stop_process(ctx.hostapd.process, True) - - self.interface.set_interface_state('down') - self.interface.set_interface_state('up') - - self._del_hostapd(force=True) - - ctx.start_hostapd() - - # Give hostapd a second to start and initialize the control interface - time.sleep(1) - - # New hostapd process, so re-init - self._init_hostapd(config=self.config, reinit=True) - def req_beacon(self, addr, request): ''' Send a RRM Beacon request ''' cmd = self.cmdline + ['req_beacon', addr, request] - ctx.start_process(cmd, wait=True) + ctx.start_process(cmd).wait() @property def bssid(self): cmd = self.cmdline + ['status'] - status = ctx.start_process(cmd, wait=True, need_out=True).out - status = status.split('\n') + proc = ctx.start_process(cmd) + proc.wait() + status = proc.out.split('\n') bssid = [x for x in status if x.startswith('bssid')] bssid = bssid[0].split('=') @@ -241,8 +213,9 @@ class HostapdCLI(object): @property def frequency(self): cmd = self.cmdline + ['status'] - status = ctx.start_process(cmd, wait=True, need_out=True).out - status = status.split('\n') + proc = ctx.start_process(cmd) + proc.wait() + status = proc.out.split('\n') frequency = [x for x in status if x.startswith('freq')][0] frequency = frequency.split('=')[1] diff --git a/autotests/util/hwsim.py b/autotests/util/hwsim.py @@ -3,6 +3,7 @@ import dbus import sys import collections +from weakref import WeakValueDictionary from abc import ABCMeta, abstractmethod from enum import Enum @@ -152,6 +153,38 @@ class Rule(HwsimDBusAbstract): reply_handler=self._success, error_handler=self._failure) self._wait_for_async_op() + @property + def match_times(self): + return self._properties['MatchTimes'] + + @match_times.setter + def match_times(self, value): + self._prop_proxy.Set(self._iface_name, 'MatchTimes', dbus.UInt16(value)) + + @property + def drop_ack(self): + return self._properties(['DropAck']) + + @drop_ack.setter + def drop_ack(self, value): + self._prop_proxy.Set(self._iface_name, 'DropAck', value) + + @property + def match(self): + return self._properties['MatchBytes'] + + @match.setter + def match(self, value): + self._prop_proxy.Set(self._iface_name, 'MatchBytes', dbus.ByteArray.fromhex(value)) + + @property + def match_offset(self): + return self._properties(['MatchBytesOffset']) + + @match_offset.setter + def match_offset(self, value): + self._prop_proxy.Set(self._iface_name, 'MatchBytesOffset', dbus.UInt16(value)) + def remove(self): self._iface.Remove(reply_handler=self._success, error_handler=self._failure) @@ -297,7 +330,25 @@ class RadioList(collections.Mapping): return obj class Hwsim(iwd.AsyncOpAbstract): + _instances = WeakValueDictionary() + + def __new__(cls, namespace=ctx): + key = id(namespace) + + if key not in cls._instances.keys(): + obj = object.__new__(cls) + obj._initialized = False + + cls._instances[key] = obj + + return cls._instances[key] + def __init__(self, namespace=ctx): + if self._initialized: + return + + self._initialized = True + self._bus = namespace.get_bus() self._rule_manager_if = dbus.Interface( @@ -335,14 +386,26 @@ class Hwsim(iwd.AsyncOpAbstract): def object_manager(self): return self._object_manager_if + @staticmethod + def _convert_address(address): + first = int(address[0:2], base=16) + first |= 0x40 + first = format(first, 'x') + + address = first + address[2:] + + return address + def spoof_disassociate(self, radio, freq, station): ''' Send a spoofed disassociate frame to a station ''' + dest = self._convert_address(radio.addresses[0].replace(':', '')) + frame = 'a0 00 3a 01' frame += station.replace(':', '') - frame += radio.addresses[0].replace(':', '') - frame += radio.addresses[0].replace(':', '') + frame += dest + frame += dest frame += '30 01 07 00' self.spoof_frame(radio, freq, station, frame) diff --git a/autotests/util/iwd.py b/autotests/util/iwd.py @@ -1053,7 +1053,7 @@ class IWD(AsyncOpAbstract): # reference so that __del__ gets called when it's released. This is only # done for the root namespace in order to allow testutil to function # correctly in non-namespace tests. - if self.namespace.name == "root": + if self.namespace.name is None: IWD._default_instance = weakref.ref(self) def __del__(self): diff --git a/autotests/util/testutil.py b/autotests/util/testutil.py @@ -169,7 +169,7 @@ def test_ip_connected(tup0, tup1): ip1, ns1 = tup1 try: - ns0.start_process(['ping', '-c', '5', '-i', '0.2', ip1], wait=True, check=True) - ns1.start_process(['ping', '-c', '5', '-i', '0.2', ip0], wait=True, check=True) + ns0.start_process(['ping', '-c', '5', '-i', '0.2', ip1], check=True) + ns1.start_process(['ping', '-c', '5', '-i', '0.2', ip0], check=True) except: raise Exception('Could not ping between %s and %s' % (ip0, ip1)) diff --git a/autotests/util/wpas.py b/autotests/util/wpas.py @@ -159,6 +159,7 @@ class Wpas: elif event['event'] == 'P2P-GROUP-STARTED': event.pop('event') event['ifname'] = event.pop('arg1') + event['role'] = event.pop('arg2') self.p2p_group = event elif event['event'] == 'P2P-GROUP-REMOVED': self.p2p_group = None diff --git a/configure.ac b/configure.ac @@ -1,5 +1,5 @@ AC_PREREQ(2.60) -AC_INIT(iwd, 1.17) +AC_INIT(iwd, 1.18) AC_CONFIG_HEADERS(config.h) AC_CONFIG_AUX_DIR(build-aux) @@ -267,7 +267,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.43" + ell_min_version="0.44" else ell_min_version="0.5" fi diff --git a/monitor/main.c b/monitor/main.c @@ -701,7 +701,7 @@ int main(int argc, char *argv[]) for (;;) { int opt; - opt = getopt_long(argc, argv, "r:w:a:F:i:nvhys", + opt = getopt_long(argc, argv, "r:w:a:F:i:nvhyse", main_options, NULL); if (opt < 0) break; diff --git a/src/ap.c b/src/ap.c @@ -92,6 +92,10 @@ struct ap_state { struct l_dhcp_server *netconfig_dhcp; struct l_rtnl_address *netconfig_addr4; uint32_t rtnl_add_cmd; + uint32_t rtnl_get_gateway4_mac_cmd; + uint32_t rtnl_get_dns4_mac_cmd; + uint8_t netconfig_gateway4_mac[6]; + uint8_t netconfig_dns4_mac[6]; bool started : 1; bool gtk_set : 1; @@ -118,6 +122,8 @@ struct sta_state { struct l_settings *wsc_settings; uint8_t wsc_uuid_e[16]; bool wsc_v2; + struct l_dhcp_lease *ip_alloc_lease; + bool ip_alloc_sent; }; struct ap_wsc_pbc_probe_record { @@ -177,6 +183,10 @@ static void ap_sta_free(void *data) if (sta->gtk_query_cmd_id) l_genl_family_cancel(ap->nl80211, sta->gtk_query_cmd_id); + if (sta->ip_alloc_lease && ap->netconfig_dhcp) + l_dhcp_server_lease_remove(ap->netconfig_dhcp, + sta->ip_alloc_lease); + ap_stop_handshake(sta); l_free(sta); @@ -205,6 +215,16 @@ static void ap_reset(struct ap_state *ap) if (ap->rtnl_add_cmd) l_netlink_cancel(rtnl, ap->rtnl_add_cmd); + if (ap->rtnl_get_gateway4_mac_cmd) { + l_netlink_cancel(rtnl, ap->rtnl_get_gateway4_mac_cmd); + ap->rtnl_get_gateway4_mac_cmd = 0; + } + + if (ap->rtnl_get_dns4_mac_cmd) { + l_netlink_cancel(rtnl, ap->rtnl_get_dns4_mac_cmd); + ap->rtnl_get_dns4_mac_cmd = 0; + } + l_queue_destroy(ap->sta_states, ap_sta_free); if (ap->rates) @@ -264,6 +284,17 @@ static void ap_del_station(struct sta_state *sta, uint16_t reason, ap_stop_handshake(sta); /* + * Expire any DHCP leases owned by this client when it disconnects to + * make it harder for somebody to DoS the IP pool. If the client + * comes back and the lease is still in the expired leases list they + * will get their IP back. + */ + if (ap->netconfig_dhcp) { + sta->ip_alloc_lease = NULL; + l_dhcp_server_expire_by_mac(ap->netconfig_dhcp, sta->addr); + } + + /* * If the event handler tears the AP down, we've made sure above that * a subsequent ap_sta_free(sta) has no need to access sta->ap. */ @@ -839,6 +870,12 @@ static uint32_t ap_send_mgmt_frame(struct ap_state *ap, callback, user_data, NULL, NULL); } +#define IP4_FROM_STR(str) \ + (__extension__ ({ \ + struct in_addr ia; \ + inet_pton(AF_INET, str, &ia) == 1 ? ia.s_addr : 0; \ + })) + static void ap_start_handshake(struct sta_state *sta, bool use_eapol_start, const uint8_t *gtk_rsc) { @@ -863,6 +900,9 @@ static void ap_start_handshake(struct sta_state *sta, bool use_eapol_start, handshake_state_set_gtk(sta->hs, sta->ap->gtk, sta->ap->gtk_index, gtk_rsc); + if (ap->netconfig_dhcp) + sta->hs->support_ip_allocation = true; + sta->sm = eapol_sm_new(sta->hs); if (!sta->sm) { ap_stop_handshake(sta); @@ -882,16 +922,54 @@ error: ap_del_station(sta, MMPDU_REASON_CODE_UNSPECIFIED, true); } +static bool ap_sta_get_dhcp4_lease(struct sta_state *sta) +{ + if (sta->ip_alloc_lease) + return true; + + if (!sta->ap->netconfig_dhcp) + return false; + + sta->ip_alloc_lease = l_dhcp_server_discover(sta->ap->netconfig_dhcp, + 0, NULL, sta->addr); + if (!sta->ip_alloc_lease) { + l_error("l_dhcp_server_discover() failed, see IWD_DHCP_DEBUG " + "output"); + return false; + } + + return true; +} + static void ap_handshake_event(struct handshake_state *hs, enum handshake_event event, void *user_data, ...) { struct sta_state *sta = user_data; + struct ap_state *ap = sta->ap; va_list args; va_start(args, user_data); switch (event) { case HANDSHAKE_EVENT_COMPLETE: + if (sta->ip_alloc_lease) { + if (hs->support_ip_allocation) + sta->ip_alloc_sent = true; + + /* + * Move the lease from offered to active state if the + * client has actually used it. In any case drop our + * reference to the lease, the server owns the lease + * and if we want to keep our reference we'd need to + * react to relevant server events. + */ + if (sta->ip_alloc_sent) + l_dhcp_server_request(ap->netconfig_dhcp, + sta->ip_alloc_lease); + + sta->ip_alloc_lease = NULL; + } + ap_new_rsna(sta); break; case HANDSHAKE_EVENT_FAILED: @@ -900,6 +978,26 @@ static void ap_handshake_event(struct handshake_state *hs, case HANDSHAKE_EVENT_SETTING_KEYS_FAILED: sta->sm = NULL; ap_remove_sta(sta); + break; + case HANDSHAKE_EVENT_P2P_IP_REQUEST: + { + L_AUTO_FREE_VAR(char *, lease_addr_str) = NULL; + L_AUTO_FREE_VAR(char *, lease_netmask_str) = NULL; + char own_addr_str[INET_ADDRSTRLEN]; + + if (!ap_sta_get_dhcp4_lease(sta)) + break; + + lease_addr_str = l_dhcp_lease_get_address(sta->ip_alloc_lease); + lease_netmask_str = + l_dhcp_lease_get_netmask(sta->ip_alloc_lease); + l_rtnl_address_get_address(ap->netconfig_addr4, own_addr_str); + + sta->hs->client_ip_addr = IP4_FROM_STR(lease_addr_str); + sta->hs->subnet_mask = IP4_FROM_STR(lease_netmask_str); + sta->hs->go_ip_addr = IP4_FROM_STR(own_addr_str); + break; + } default: break; } @@ -1308,14 +1406,16 @@ static uint32_t ap_assoc_resp(struct ap_state *ap, struct sta_state *sta, const uint8_t *dest, enum mmpdu_reason_code status_code, bool reassoc, const struct mmpdu_header *req, - size_t req_len, frame_xchg_cb_t callback) + size_t req_len, + const struct ie_fils_ip_addr_request_info * + ip_req_info, frame_xchg_cb_t callback) { const uint8_t *addr = netdev_get_address(ap->netdev); enum mpdu_management_subtype stype = reassoc ? MPDU_MANAGEMENT_SUBTYPE_REASSOCIATION_RESPONSE : MPDU_MANAGEMENT_SUBTYPE_ASSOCIATION_RESPONSE; L_AUTO_FREE_VAR(uint8_t *, mpdu_buf) = - l_malloc(128 + ap_get_extra_ies_len(ap, stype, req, req_len)); + l_malloc(256 + ap_get_extra_ies_len(ap, stype, req, req_len)); struct mmpdu_header *mpdu = (void *) mpdu_buf; struct mmpdu_association_response *resp; size_t ies_len = 0; @@ -1361,6 +1461,64 @@ static uint32_t ap_assoc_resp(struct ap_state *ap, struct sta_state *sta, ies_len += ap_write_extra_ies(ap, stype, req, req_len, resp->ies + ies_len); + if (ip_req_info) { + struct ie_fils_ip_addr_response_info ip_resp_info = {}; + + if (ip_req_info->ipv4 && sta && ap_sta_get_dhcp4_lease(sta)) { + L_AUTO_FREE_VAR(char *, lease_addr_str) = + l_dhcp_lease_get_address(sta->ip_alloc_lease); + L_AUTO_FREE_VAR(char *, lease_netmask_str) = + l_dhcp_lease_get_netmask(sta->ip_alloc_lease); + uint32_t lease_lifetime = + l_dhcp_lease_get_lifetime(sta->ip_alloc_lease); + L_AUTO_FREE_VAR(char *, lease_gateway_str) = + l_dhcp_lease_get_gateway(sta->ip_alloc_lease); + char **lease_dns_str_list = + l_dhcp_lease_get_dns(sta->ip_alloc_lease); + + ip_resp_info.ipv4_addr = IP4_FROM_STR(lease_addr_str); + ip_resp_info.ipv4_prefix_len = + __builtin_popcount(IP4_FROM_STR( + lease_netmask_str)); + + if (lease_lifetime != 0xffffffff) + ip_resp_info.ipv4_lifetime = lease_lifetime; + + if (lease_gateway_str) { + ip_resp_info.ipv4_gateway = + IP4_FROM_STR(lease_gateway_str); + memcpy(ip_resp_info.ipv4_gateway_mac, + ap->netconfig_gateway4_mac, 6); + } + + if (lease_dns_str_list && lease_dns_str_list[0]) { + ip_resp_info.ipv4_dns = + IP4_FROM_STR(lease_dns_str_list[0]); + memcpy(ip_resp_info.ipv4_dns_mac, + ap->netconfig_dns4_mac, 6); + } + + l_strv_free(lease_dns_str_list); + sta->ip_alloc_sent = true; + } else if (ip_req_info->ipv4 || ip_req_info->ipv6) { + /* + * 802.11ai-2016 Section 11.47.3.3: "If the AP is unable + * to assign an IP address in the (Re)Association + * Response frame, then the AP sets the IP address + * assignment pending flag in the IP Address Response + * Control field of the FILS IP Address Assignment + * element to 1 and sets the IP address request timeout + * to 0 in (Re)Association Response frame." + */ + ip_resp_info.response_pending = 1; + ip_resp_info.response_timeout = 0; + } + + ie_build_fils_ip_addr_response(&ip_resp_info, + resp->ies + ies_len); + ies_len += 2 + resp->ies[ies_len + 1]; + } + return ap_send_mgmt_frame(ap, mpdu, resp->ies + ies_len - mpdu_buf, callback, sta); } @@ -1449,6 +1607,8 @@ static void ap_assoc_reassoc(struct sta_state *sta, bool reassoc, struct ie_tlv_iter iter; uint8_t *wsc_data = NULL; ssize_t wsc_data_len; + bool fils_ip_req = false; + struct ie_fils_ip_addr_request_info fils_ip_req_info; if (sta->assoc_resp_cmd_id) return; @@ -1495,6 +1655,17 @@ static void ap_assoc_reassoc(struct sta_state *sta, bool reassoc, rsn = (const uint8_t *) ie_tlv_iter_get_data(&iter) - 2; break; + + case IE_TYPE_FILS_IP_ADDRESS: + if (fils_ip_req || ie_parse_fils_ip_addr_request(&iter, + &fils_ip_req_info) < 0) { + l_debug("Can't parse FILS IP Address Assignment" + " IE, ignoring it"); + break; + } + + fils_ip_req = true; + break; } if (!rates || !ssid || (!wsc_data && !rsn) || @@ -1627,7 +1798,8 @@ static void ap_assoc_reassoc(struct sta_state *sta, bool reassoc, sta->assoc_resp_cmd_id = ap_assoc_resp(ap, sta, sta->addr, 0, reassoc, req, (void *) ies + ies_len - - (void *) req, + (void *) req, fils_ip_req ? + &fils_ip_req_info : NULL, ap_success_assoc_resp_cb); if (!sta->assoc_resp_cmd_id) l_error("Sending success (Re)Association Response failed"); @@ -1660,7 +1832,7 @@ bad_frame: if (!ap_assoc_resp(ap, sta, sta->addr, err, reassoc, req, (void *) ies + ies_len - (void *) req, - ap_fail_assoc_resp_cb)) + NULL, ap_fail_assoc_resp_cb)) l_error("Sending error (Re)Association Response failed"); } @@ -1685,7 +1857,7 @@ static void ap_assoc_req_cb(const struct mmpdu_header *hdr, const void *body, if (!ap_assoc_resp(ap, NULL, from, MMPDU_REASON_CODE_STA_REQ_ASSOC_WITHOUT_AUTH, false, hdr, body + body_len - (void *) hdr, - ap_fail_assoc_resp_cb)) + NULL, ap_fail_assoc_resp_cb)) l_error("Sending error Association Response failed"); return; @@ -1733,7 +1905,7 @@ static void ap_reassoc_req_cb(const struct mmpdu_header *hdr, const void *body, bad_frame: if (!ap_assoc_resp(ap, NULL, from, err, true, hdr, body + body_len - (void *) hdr, - ap_fail_assoc_resp_cb)) + NULL, ap_fail_assoc_resp_cb)) l_error("Sending error Reassociation Response failed"); } @@ -2409,6 +2581,104 @@ static void ap_mlme_notify(struct l_genl_msg *msg, void *user_data) } } +static void ap_get_gateway4_mac_cb(int error, const uint8_t *hwaddr, + size_t hwaddr_len, void *user_data) +{ + struct ap_state *ap = user_data; + + ap->rtnl_get_gateway4_mac_cmd = 0; + + if (error) { + l_debug("Error: %s (%i)", strerror(-error), -error); + return; + } + + if (L_WARN_ON(unlikely(hwaddr_len != 6))) + return; + + l_debug("Resolved mac to " MAC, MAC_STR(hwaddr)); + memcpy(ap->netconfig_gateway4_mac, hwaddr, 6); +} + +static void ap_get_dns4_mac_cb(int error, const uint8_t *hwaddr, + size_t hwaddr_len, void *user_data) +{ + struct ap_state *ap = user_data; + + ap->rtnl_get_dns4_mac_cmd = 0; + + if (error) { + l_debug("Error: %s (%i)", strerror(-error), -error); + return; + } + + if (L_WARN_ON(unlikely(hwaddr_len != 6))) + return; + + l_debug("Resolved mac to " MAC, MAC_STR(hwaddr)); + memcpy(ap->netconfig_dns4_mac, hwaddr, 6); +} + +static void ap_query_macs(struct ap_state *ap, const char *addr_str, + uint8_t prefix_len, const char *gateway_str, + const char **dns_str_list) +{ + uint32_t local = IP4_FROM_STR(addr_str); + uint32_t gateway = 0; + uint32_t dns = 0; + uint32_t ifindex = netdev_get_ifindex(ap->netdev); + + /* + * For simplicity only check the ARP/NDP tables to see if we already + * have the MACs that we need. There doesn't seem to be an API to + * actually resolve addresses that are not in these tables other than + * by triggering IP traffic to those hosts, such as a ping. In a PC + * or mobile device scenario we're likely to have these MACs already, + * otherwise we give up as this is a pretty low-priority feature. + */ + + if (gateway_str) { + gateway = IP4_FROM_STR(gateway_str); + if (L_WARN_ON(unlikely(!gateway))) + return; + + if (gateway == local) + memcpy(ap->netconfig_gateway4_mac, + netdev_get_address(ap->netdev), 6); + else { + ap->rtnl_get_gateway4_mac_cmd = + l_rtnl_neighbor_get_hwaddr(rtnl, ifindex, + AF_INET, &gateway, + ap_get_gateway4_mac_cb, + ap, NULL); + if (!ap->rtnl_get_gateway4_mac_cmd) + l_debug("l_rtnl_neighbor_get_hwaddr() failed " + "for the gateway IP"); + } + } + + if (dns_str_list) { + dns = IP4_FROM_STR(dns_str_list[0]); + if (L_WARN_ON(unlikely(!dns))) + return; + + /* TODO: can also skip query if dns == gateway */ + if (dns == local) + memcpy(ap->netconfig_dns4_mac, + netdev_get_address(ap->netdev), 6); + else if (util_ip_subnet_match(prefix_len, &dns, &local)) { + ap->rtnl_get_dns4_mac_cmd = + l_rtnl_neighbor_get_hwaddr(rtnl, ifindex, + AF_INET, &dns, + ap_get_dns4_mac_cb, + ap, NULL); + if (!ap->rtnl_get_dns4_mac_cmd) + l_debug("l_rtnl_neighbor_get_hwaddr() failed " + "for the DNS IP"); + } + } +} + #define AP_DEFAULT_IPV4_PREFIX_LEN 28 static int ap_setup_netconfig4(struct ap_state *ap, const char **addr_str_list, @@ -2537,6 +2807,8 @@ static int ap_setup_netconfig4(struct ap_state *ap, const char **addr_str_list, ap->netconfig_set_addr4 = false; } + ap_query_macs(ap, addr_str_buf, prefix_len, gateway_str, dns_str_list); + cleanup: l_dhcp_server_destroy(dhcp); l_rtnl_address_free(new_addr); diff --git a/src/auth-proto.h b/src/auth-proto.h @@ -25,6 +25,21 @@ struct auth_proto { bool (*start)(struct auth_proto *ap); void (*free)(struct auth_proto *ap); + /* + * Callback to receive an Authenticate frame. auth-protos should + * return error codes consistent with one another as some are treated + * specially: + * + * 0 indicates success, and that a state transition occurred. + * -ENOMSG or -EBADMSG indicates the message should be ignored silently + * -EAGAIN indicates a retry, and no state transition occurred. Any + * retry is handled by the auth-proto internally + * -EPROTO indicates a fatal error + * Any other < 0 return will be treated as a fatal error + * > 0 indicates a fatal error with status code. This only applies to + * non-sta cases as non-zero status codes are rejected by the + * kernel when in station mode. + */ int (*rx_authenticate)(struct auth_proto *driver, const uint8_t *frame, size_t len); int (*rx_associate)(struct auth_proto *driver, diff --git a/src/eapol.c b/src/eapol.c @@ -1350,6 +1350,23 @@ static void eapol_send_ptk_3_of_4(struct eapol_sm *sm) key_data_len += gtk_kde[1] + 2; } + if (sm->handshake->support_ip_allocation && + !sm->handshake->client_ip_addr) { + handshake_event(sm->handshake, HANDSHAKE_EVENT_P2P_IP_REQUEST); + + /* + * If .support_ip_allocation was set, the + * HANDSHAKE_EVENT_P2P_IP_REQUEST handler is expected to set + * .client_ip_addr if not already set. Check if the handler + * was successful in allocating an address, if it wasn't we'll + * just skip the IP Address Allocation KDE. In either case if + * we need to resend message 3/4 the event callback won't be + * triggered again because the condition above will be false. + */ + if (!sm->handshake->client_ip_addr) + sm->handshake->support_ip_allocation = false; + } + if (sm->handshake->support_ip_allocation) { /* Wi-Fi P2P Technical Specification v1.7 Table 59 */ key_data_buf[key_data_len++] = IE_TYPE_VENDOR_SPECIFIC; diff --git a/src/fils.c b/src/fils.c @@ -289,7 +289,7 @@ static int fils_derive_key_data(struct fils_sm *fils) if (ie_parse_rsne_from_data(fils->hs->supplicant_ie, fils->hs->supplicant_ie[1] + 2, &rsn_info) < 0) - return -EBADMSG; + return -EPROTO; rsn_info.num_pmkids = 1; rsn_info.pmkids = fils->hs->pmk_r1_name; diff --git a/src/handshake.c b/src/handshake.c @@ -106,6 +106,8 @@ void handshake_state_free(struct handshake_state *s) l_free(s->supplicant_rsnxe); l_free(s->mde); l_free(s->fte); + l_free(s->fils_ip_req_ie); + l_free(s->fils_ip_resp_ie); if (s->erp_cache) erp_cache_put(s->erp_cache); diff --git a/src/handshake.h b/src/handshake.h @@ -57,6 +57,7 @@ enum handshake_event { HANDSHAKE_EVENT_REKEY_FAILED, HANDSHAKE_EVENT_EAP_NOTIFY, HANDSHAKE_EVENT_TRANSITION_DISABLE, + HANDSHAKE_EVENT_P2P_IP_REQUEST, }; typedef void (*handshake_event_func_t)(struct handshake_state *hs, @@ -139,6 +140,8 @@ struct handshake_state { uint32_t client_ip_addr; uint32_t subnet_mask; uint32_t go_ip_addr; + uint8_t *fils_ip_req_ie; + uint8_t *fils_ip_resp_ie; void *user_data; void (*free)(struct handshake_state *s); diff --git a/src/ie.c b/src/ie.c @@ -25,6 +25,7 @@ #endif #include <errno.h> +#include <arpa/inet.h> #include <ell/ell.h> @@ -1363,6 +1364,32 @@ bool is_ie_wpa_ie(const uint8_t *data, uint8_t len) return false; } +/* + * List of vendor OUIs (prefixed with a length byte) which require forcing + * the default SAE group. + */ +static const uint8_t use_default_sae_group_ouis[][5] = { + { 0x04, 0xf4, 0xf5, 0xe8, 0x05 }, +}; + +bool is_ie_default_sae_group_oui(const uint8_t *data, uint16_t len) +{ + unsigned int i; + const uint8_t *oui; + + for (i = 0; i < L_ARRAY_SIZE(use_default_sae_group_ouis); i++) { + oui = use_default_sae_group_ouis[i]; + + if (len < oui[0]) + continue; + + if (!memcmp(oui + 1, data, oui[0])) + return true; + } + + return false; +} + int ie_parse_wpa(struct ie_tlv_iter *iter, struct ie_rsn_info *out_info) { const uint8_t *data = iter->data; @@ -2103,3 +2130,365 @@ bool ie_rsnxe_capable(const uint8_t *rsnxe, unsigned int bit) return test_bit(rsnxe + 2, bit); } + +/* 802.11ai-2016 Tables 9-589r, 9-262d, 9-262e */ +enum ie_fils_ip_addr_req_ctrl_bits { + IE_FILS_IP_ADDR_REQ_CTRL_IPV4_MASK = 3 << 0, + IE_FILS_IP_ADDR_REQ_CTRL_IPV4_NONE = 0 << 0, + IE_FILS_IP_ADDR_REQ_CTRL_IPV4_NEW = 2 << 0, + IE_FILS_IP_ADDR_REQ_CTRL_IPV4_SPECIFIC = 3 << 0, + IE_FILS_IP_ADDR_REQ_CTRL_IPV6_MASK = 3 << 2, + IE_FILS_IP_ADDR_REQ_CTRL_IPV6_NONE = 0 << 2, + IE_FILS_IP_ADDR_REQ_CTRL_IPV6_NEW = 2 << 2, + IE_FILS_IP_ADDR_REQ_CTRL_IPV6_SPECIFIC = 3 << 2, + IE_FILS_IP_ADDR_REQ_CTRL_DNS = 1 << 4, +}; + +/* 802.11ai-2016 Table 9-262f */ +enum ie_fils_ip_addr_resp_ctrl_bits { + IE_FILS_IP_ADDR_RESP_CTRL_IP_PENDING = 1 << 0, + IE_FILS_IP_ADDR_RESP_CTRL_IPV4_ASSIGNED = 1 << 1, + IE_FILS_IP_ADDR_RESP_CTRL_IPV4_GW_INCLUDED = 1 << 2, + IE_FILS_IP_ADDR_RESP_CTRL_IPV6_ASSIGNED = 1 << 3, + IE_FILS_IP_ADDR_RESP_CTRL_IPV6_GW_INCLUDED = 1 << 4, + IE_FILS_IP_ADDR_RESP_CTRL_IPV4_LIFETIME_INCLUDED = 1 << 5, + IE_FILS_IP_ADDR_RESP_CTRL_IPV6_LIFETIME_INCLUDED = 1 << 6, +}; + +/* 802.11ai-2016 Table 9-262h */ +enum ie_fils_ip_addr_resp_dns_ctrl_bits { + IE_FILS_IP_ADDR_RESP_DNS_CTRL_IPV4_DNS_INCLUDED = 1 << 0, + IE_FILS_IP_ADDR_RESP_DNS_CTRL_IPV6_DNS_INCLUDED = 1 << 1, + IE_FILS_IP_ADDR_RESP_DNS_CTRL_IPV4_DNS_MAC_INCLUDED = 1 << 2, + IE_FILS_IP_ADDR_RESP_DNS_CTRL_IPV6_DNS_MAC_INCLUDED = 1 << 3, +}; + +int ie_parse_fils_ip_addr_request(struct ie_tlv_iter *iter, + struct ie_fils_ip_addr_request_info *out) +{ + unsigned int len = ie_tlv_iter_get_length(iter); + const uint8_t *data = ie_tlv_iter_get_data(iter); + struct ie_fils_ip_addr_request_info info = {}; + bool ipv4_specific_addr = false; + bool ipv6_specific_addr = false; + + if (len < 1) + return -EMSGSIZE; + + if (L_IN_SET(data[0] & IE_FILS_IP_ADDR_REQ_CTRL_IPV4_MASK, + IE_FILS_IP_ADDR_REQ_CTRL_IPV4_NEW, + IE_FILS_IP_ADDR_REQ_CTRL_IPV4_SPECIFIC)) { + info.ipv4 = true; + ipv4_specific_addr = + (data[0] & IE_FILS_IP_ADDR_REQ_CTRL_IPV4_MASK) == + IE_FILS_IP_ADDR_REQ_CTRL_IPV4_SPECIFIC; + } else if ((data[0] & IE_FILS_IP_ADDR_REQ_CTRL_IPV4_MASK) != + IE_FILS_IP_ADDR_REQ_CTRL_IPV4_NONE) + return -EINVAL; + + if (L_IN_SET(data[0] & IE_FILS_IP_ADDR_REQ_CTRL_IPV6_MASK, + IE_FILS_IP_ADDR_REQ_CTRL_IPV6_NEW, + IE_FILS_IP_ADDR_REQ_CTRL_IPV6_SPECIFIC)) { + info.ipv6 = true; + ipv6_specific_addr = + (data[0] & IE_FILS_IP_ADDR_REQ_CTRL_IPV6_MASK) == + IE_FILS_IP_ADDR_REQ_CTRL_IPV6_SPECIFIC; + } else if ((data[0] & IE_FILS_IP_ADDR_REQ_CTRL_IPV6_MASK) != + IE_FILS_IP_ADDR_REQ_CTRL_IPV6_NONE) + return -EINVAL; + + info.dns = !!(*data++ & IE_FILS_IP_ADDR_REQ_CTRL_DNS); + + if (len < 1 + (ipv4_specific_addr ? 4u : 0u) + + (ipv6_specific_addr ? 16u : 0u)) + return -EMSGSIZE; + + if (ipv4_specific_addr) { + info.ipv4_requested_addr = l_get_u32(data); + data += 4; + + if (!info.ipv4_requested_addr) + return -EINVAL; + } + + if (ipv6_specific_addr) { + memcpy(info.ipv6_requested_addr, data, 16); + data += 16; + + if (l_memeqzero(info.ipv6_requested_addr, 16)) + return -EINVAL; + } + + memcpy(out, &info, sizeof(info)); + return 0; +} + +void ie_build_fils_ip_addr_request( + const struct ie_fils_ip_addr_request_info *info, + uint8_t *to) +{ + uint8_t *len; + uint8_t *ctrl; + + *to++ = IE_TYPE_EXTENSION; + len = to++; + *to++ = IE_TYPE_FILS_IP_ADDRESS & 0xff; + ctrl = to++; + + *ctrl = info->dns ? IE_FILS_IP_ADDR_REQ_CTRL_DNS : 0; + + if (info->ipv4) { + if (info->ipv4_requested_addr) { + l_put_u32(info->ipv4_requested_addr, to); + to += 4; + *ctrl |= IE_FILS_IP_ADDR_REQ_CTRL_IPV4_SPECIFIC; + } else + *ctrl |= IE_FILS_IP_ADDR_REQ_CTRL_IPV4_NEW; + } + + if (info->ipv6) { + if (!l_memeqzero(info->ipv6_requested_addr, 16)) { + memcpy(to, info->ipv6_requested_addr, 16); + to += 16; + *ctrl |= IE_FILS_IP_ADDR_REQ_CTRL_IPV6_SPECIFIC; + } else + *ctrl |= IE_FILS_IP_ADDR_REQ_CTRL_IPV6_NEW; + } + + *len = to - (len + 1); +} + +#define NEXT_FIELD(data, len, size) (__extension__ ({ \ + const uint8_t *_ptr = data; \ + \ + if (len < size) \ + return -EMSGSIZE; \ + \ + data += size; \ + len -= size; \ + _ptr; })) + +int ie_parse_fils_ip_addr_response(struct ie_tlv_iter *iter, + struct ie_fils_ip_addr_response_info *out) +{ + unsigned int len = ie_tlv_iter_get_length(iter); + const uint8_t *data = ie_tlv_iter_get_data(iter); + struct ie_fils_ip_addr_response_info info = {}; + const uint8_t *resp_ctrl; + const uint8_t *dns_ctrl; + const uint8_t *ptr; + + resp_ctrl = NEXT_FIELD(data, len, 2); + dns_ctrl = resp_ctrl + 1; + + info.response_pending = + !!(*resp_ctrl & IE_FILS_IP_ADDR_RESP_CTRL_IP_PENDING); + + if (info.response_pending) { + info.response_timeout = + bit_field(*resp_ctrl, 1, 6); /* seconds */ + return 0; + } + + if (*resp_ctrl & IE_FILS_IP_ADDR_RESP_CTRL_IPV4_ASSIGNED) { + uint32_t netmask; + + ptr = NEXT_FIELD(data, len, 8); + info.ipv4_addr = l_get_u32(ptr); + netmask = l_get_be32(ptr + 4); + info.ipv4_prefix_len = __builtin_popcount(netmask); + + if (!info.ipv4_addr || info.ipv4_prefix_len > 30 || netmask != + util_netmask_from_prefix(info.ipv4_prefix_len)) + return -EINVAL; + } + + if (*resp_ctrl & IE_FILS_IP_ADDR_RESP_CTRL_IPV4_GW_INCLUDED) { + ptr = NEXT_FIELD(data, len, 10); + info.ipv4_gateway = l_get_u32(ptr); + memcpy(info.ipv4_gateway_mac, ptr + 4, 6); + + /* Check gateway is on the same subnet */ + if (info.ipv4_addr && + !util_ip_subnet_match(info.ipv4_prefix_len, + &info.ipv4_addr, + &info.ipv4_gateway)) + return -EINVAL; + } + + if (*resp_ctrl & IE_FILS_IP_ADDR_RESP_CTRL_IPV6_ASSIGNED) { + ptr = NEXT_FIELD(data, len, 17); + memcpy(info.ipv6_addr, ptr, 16); + info.ipv6_prefix_len = ptr[16]; + + if (l_memeqzero(info.ipv6_addr, 16) || + info.ipv6_prefix_len > 126) + return -EINVAL; + } + + if (*resp_ctrl & IE_FILS_IP_ADDR_RESP_CTRL_IPV6_GW_INCLUDED) { + ptr = NEXT_FIELD(data, len, 22); + memcpy(info.ipv6_gateway, ptr, 16); + memcpy(info.ipv6_gateway_mac, ptr + 16, 6); + + /* Check gateway is on the same subnet */ + if (!l_memeqzero(info.ipv6_addr, 16) && + !util_ip_subnet_match(info.ipv6_prefix_len, + info.ipv6_addr, + info.ipv6_gateway)) + return -EINVAL; + } + + if (*resp_ctrl & IE_FILS_IP_ADDR_RESP_CTRL_IPV4_LIFETIME_INCLUDED) + info.ipv4_lifetime = *NEXT_FIELD(data, len, 1); /* seconds */ + + if (*resp_ctrl & IE_FILS_IP_ADDR_RESP_CTRL_IPV6_LIFETIME_INCLUDED) + info.ipv6_lifetime = *NEXT_FIELD(data, len, 1); /* seconds */ + + if (*dns_ctrl & IE_FILS_IP_ADDR_RESP_DNS_CTRL_IPV4_DNS_INCLUDED) { + info.ipv4_dns = l_get_u32(NEXT_FIELD(data, len, 4)); + + if (!info.ipv4_dns) + return -EINVAL; + } + + if (*dns_ctrl & IE_FILS_IP_ADDR_RESP_DNS_CTRL_IPV6_DNS_INCLUDED) { + memcpy(info.ipv6_dns, NEXT_FIELD(data, len, 16), 16); + + if (l_memeqzero(info.ipv6_dns, 16)) + return -EINVAL; + } + + if (*dns_ctrl & IE_FILS_IP_ADDR_RESP_DNS_CTRL_IPV4_DNS_MAC_INCLUDED) + memcpy(info.ipv4_dns_mac, NEXT_FIELD(data, len, 6), 6); + + if (*dns_ctrl & IE_FILS_IP_ADDR_RESP_DNS_CTRL_IPV6_DNS_MAC_INCLUDED) + memcpy(info.ipv6_dns_mac, NEXT_FIELD(data, len, 6), 6); + + memcpy(out, &info, sizeof(info)); + return 0; +} + +void ie_build_fils_ip_addr_response( + const struct ie_fils_ip_addr_response_info *info, + uint8_t *to) +{ + uint8_t *len; + uint8_t *resp_ctrl; + uint8_t *dns_ctrl; + + *to++ = IE_TYPE_EXTENSION; + len = to++; + *to++ = IE_TYPE_FILS_IP_ADDRESS & 0xff; + resp_ctrl = to++; + dns_ctrl = to++; + + *resp_ctrl = 0; + *dns_ctrl = 0; + + if (info->response_pending) { + *resp_ctrl |= IE_FILS_IP_ADDR_RESP_CTRL_IP_PENDING; + *resp_ctrl |= info->response_timeout << 1; + goto done; + } + + if (info->ipv4_addr) { + uint32_t netmask = + util_netmask_from_prefix(info->ipv4_prefix_len); + + *resp_ctrl |= IE_FILS_IP_ADDR_RESP_CTRL_IPV4_ASSIGNED; + + l_put_u32(info->ipv4_addr, to); + l_put_u32(htonl(netmask), to + 4); + to += 8; + } + + if (info->ipv4_gateway) { + *resp_ctrl |= IE_FILS_IP_ADDR_RESP_CTRL_IPV4_GW_INCLUDED; + + l_put_u32(info->ipv4_gateway, to); + memcpy(to + 4, info->ipv4_gateway_mac, 6); + to += 10; + } + + if (!l_memeqzero(info->ipv6_addr, 16)) { + *resp_ctrl |= IE_FILS_IP_ADDR_RESP_CTRL_IPV6_ASSIGNED; + + memcpy(to, info->ipv6_addr, 16); + to[16] = info->ipv6_prefix_len; + to += 17; + } + + if (!l_memeqzero(info->ipv6_gateway, 16)) { + *resp_ctrl |= IE_FILS_IP_ADDR_RESP_CTRL_IPV6_GW_INCLUDED; + + memcpy(to, info->ipv6_gateway, 16); + memcpy(to + 16, info->ipv6_gateway_mac, 6); + to += 22; + } + + if (info->ipv4_lifetime) { + *resp_ctrl |= IE_FILS_IP_ADDR_RESP_CTRL_IPV4_LIFETIME_INCLUDED; + + *to++ = info->ipv4_lifetime; + } + + if (info->ipv6_lifetime) { + *resp_ctrl |= IE_FILS_IP_ADDR_RESP_CTRL_IPV6_LIFETIME_INCLUDED; + + *to++ = info->ipv6_lifetime; + } + + if (info->ipv4_dns) { + *dns_ctrl |= IE_FILS_IP_ADDR_RESP_DNS_CTRL_IPV4_DNS_INCLUDED; + + l_put_u32(info->ipv4_dns, to); + to += 4; + } + + if (!l_memeqzero(info->ipv6_dns, 16)) { + *dns_ctrl |= IE_FILS_IP_ADDR_RESP_DNS_CTRL_IPV6_DNS_INCLUDED; + + memcpy(to, info->ipv6_dns, 16); + to += 16; + } + + if (!l_memeqzero(info->ipv4_dns_mac, 6)) { + *dns_ctrl |= + IE_FILS_IP_ADDR_RESP_DNS_CTRL_IPV4_DNS_MAC_INCLUDED; + + memcpy(to, info->ipv4_dns_mac, 6); + to += 6; + } + + if (!l_memeqzero(info->ipv6_dns_mac, 6)) { + *dns_ctrl |= + IE_FILS_IP_ADDR_RESP_DNS_CTRL_IPV6_DNS_MAC_INCLUDED; + + memcpy(to, info->ipv6_dns_mac, 6); + to += 6; + } + +done: + *len = to - (len + 1); +} + +/* + * Parse Network Cost IE according to: + * https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nct/88f0cdf4-cdf2-4455-b849-4abf1e5c11ac + */ +int ie_parse_network_cost(const void *data, size_t len, + uint16_t *level, uint16_t *flags) +{ + const uint8_t *ie = data; + + if (len < 10 || ie[0] != IE_TYPE_VENDOR_SPECIFIC || ie[1] != 8) + return -ENOMSG; + + if (memcmp(ie + 2, microsoft_oui, 3) || ie[5] != 0x11) + return -ENOMSG; + + *level = l_get_le16(ie + 6); + *flags = l_get_le16(ie + 8); + return 0; +} diff --git a/src/ie.h b/src/ie.h @@ -459,6 +459,33 @@ struct ie_neighbor_report_info { bool bss_transition_pref_present : 1; }; +struct ie_fils_ip_addr_request_info { + bool ipv4 : 1; + uint32_t ipv4_requested_addr; /* Zero if none */ + bool ipv6 : 1; + uint8_t ipv6_requested_addr[16]; /* Zero if none */ + bool dns : 1; +}; + +struct ie_fils_ip_addr_response_info { + bool response_pending : 1; + uint8_t response_timeout; /* Seconds */ + uint32_t ipv4_addr; /* Zero if not provided */ + uint8_t ipv4_prefix_len; + uint32_t ipv4_gateway; /* Zero if not provided */ + uint8_t ipv4_gateway_mac[6]; + uint32_t ipv4_dns; /* Zero if not provided */ + uint8_t ipv4_dns_mac[6]; /* Zero if not provided */ + uint8_t ipv4_lifetime; /* Zero if not provided */ + uint8_t ipv6_addr[16]; /* Zero if not provided */ + uint8_t ipv6_prefix_len; + uint8_t ipv6_gateway[16]; /* Zero if not provided */ + uint8_t ipv6_gateway_mac[6]; + uint8_t ipv6_dns[16]; /* Zero if not provided */ + uint8_t ipv6_dns_mac[6]; /* Zero if not provided */ + uint8_t ipv6_lifetime; /* Zero if not provided */ +}; + extern const unsigned char ieee_oui[3]; extern const unsigned char microsoft_oui[3]; extern const unsigned char wifi_alliance_oui[3]; @@ -524,6 +551,8 @@ int ie_parse_wpa_from_data(const uint8_t *data, size_t len, struct ie_rsn_info *info); bool is_ie_wfa_ie(const uint8_t *data, uint8_t len, uint8_t oi_type); bool is_ie_wpa_ie(const uint8_t *data, uint8_t len); +bool is_ie_default_sae_group_oui(const uint8_t *data, uint16_t len); + bool ie_build_wpa(const struct ie_rsn_info *info, uint8_t *to); int ie_parse_bss_load(struct ie_tlv_iter *iter, uint16_t *out_sta_count, @@ -586,3 +615,17 @@ enum ie_rsnx_capability { }; bool ie_rsnxe_capable(const uint8_t *rsnxe, unsigned int bit); + +int ie_parse_fils_ip_addr_request(struct ie_tlv_iter *iter, + struct ie_fils_ip_addr_request_info *out); +void ie_build_fils_ip_addr_request( + const struct ie_fils_ip_addr_request_info *info, + uint8_t *to); +int ie_parse_fils_ip_addr_response(struct ie_tlv_iter *iter, + struct ie_fils_ip_addr_response_info *out); +void ie_build_fils_ip_addr_response( + const struct ie_fils_ip_addr_response_info *info, + uint8_t *to); + +int ie_parse_network_cost(const void *data, size_t len, + uint16_t *flags, uint16_t *level); diff --git a/src/mpdu.h b/src/mpdu.h @@ -232,6 +232,7 @@ enum mmpdu_status_code { MMPDU_STATUS_CODE_RESTRICT_AUTH_GDB = 106, MMPDU_STATUS_CODE_AUTHORIZATION_DEENABLED = 107, MMPDU_STATUS_CODE_SAE_HASH_TO_ELEMENT = 126, + MMPDU_STATUS_CODE_SAE_PK = 127, }; /* 802.11, Section 8.2.4.1.1, Figure 8-2 */ diff --git a/src/netconfig.c b/src/netconfig.c @@ -47,6 +47,8 @@ #include "src/common.h" #include "src/network.h" #include "src/resolve.h" +#include "src/util.h" +#include "src/ie.h" #include "src/netconfig.h" struct netconfig { @@ -58,6 +60,7 @@ struct netconfig { struct l_rtnl_address *v4_address; char **dns4_overrides; char **dns6_overrides; + struct ie_fils_ip_addr_response_info *fils_override; const struct l_settings *active_settings; @@ -163,28 +166,92 @@ static struct netconfig *netconfig_find(uint32_t ifindex) dest[index++] = *p; \ } while (0) \ +static inline char *netconfig_ipv4_to_string(uint32_t addr) +{ + struct in_addr in_addr = { .s_addr = addr }; + char *addr_str = l_malloc(INET_ADDRSTRLEN); + + if (L_WARN_ON(unlikely(!inet_ntop(AF_INET, &in_addr, addr_str, + INET_ADDRSTRLEN)))) { + l_free(addr_str); + return NULL; + } + + return addr_str; +} + +static inline char *netconfig_ipv6_to_string(const uint8_t *addr) +{ + struct in6_addr in6_addr; + char *addr_str = l_malloc(INET6_ADDRSTRLEN); + + memcpy(in6_addr.__in6_u.__u6_addr8, addr, 16); + + if (L_WARN_ON(unlikely(!inet_ntop(AF_INET6, &in6_addr, addr_str, + INET6_ADDRSTRLEN)))) { + l_free(addr_str); + return NULL; + } + + return addr_str; +} + +static void netconfig_set_neighbor_entry_cb(int error, + uint16_t type, const void *data, + uint32_t len, void *user_data) +{ + if (error) + l_error("l_rtnl_neighbor_set_hwaddr failed: %s (%i)", + strerror(-error), error); +} + static int netconfig_set_dns(struct netconfig *netconfig) { char **dns6_list = NULL; char **dns4_list = NULL; unsigned int n_entries = 0; char **dns_list; + const uint8_t *fils_dns4_mac = NULL; + const uint8_t *fils_dns6_mac = NULL; + const struct ie_fils_ip_addr_response_info *fils = + netconfig->fils_override; if (!netconfig->dns4_overrides && netconfig->rtm_protocol == RTPROT_DHCP) { - const struct l_dhcp_lease *lease = - l_dhcp_client_get_lease(netconfig->dhcp_client); - - if (lease) + const struct l_dhcp_lease *lease; + + if (fils && fils->ipv4_dns) { + dns4_list = l_new(char *, 2); + dns4_list[0] = netconfig_ipv4_to_string(fils->ipv4_dns); + + if (!l_memeqzero(fils->ipv4_dns_mac, 6) && + util_ip_subnet_match( + fils->ipv4_prefix_len, + &fils->ipv4_addr, + &fils->ipv4_dns)) + fils_dns4_mac = fils->ipv4_dns_mac; + } else if ((lease = l_dhcp_client_get_lease( + netconfig->dhcp_client))) dns4_list = l_dhcp_lease_get_dns(lease); } if (!netconfig->dns6_overrides && netconfig->rtm_v6_protocol == RTPROT_DHCP) { - const struct l_dhcp6_lease *lease = - l_dhcp6_client_get_lease(netconfig->dhcp6_client); - - if (lease) + const struct l_dhcp6_lease *lease; + + if (fils && !l_memeqzero(fils->ipv6_dns, + 16)) { + dns6_list = l_new(char *, 2); + dns6_list[0] = netconfig_ipv6_to_string(fils->ipv6_dns); + + if (!l_memeqzero(fils->ipv6_dns_mac, 6) && + util_ip_subnet_match( + fils->ipv6_prefix_len, + fils->ipv6_addr, + fils->ipv6_dns)) + fils_dns6_mac = fils->ipv6_dns_mac; + } else if ((lease = l_dhcp6_client_get_lease( + netconfig->dhcp6_client))) dns6_list = l_dhcp6_lease_get_dns(lease); } @@ -198,15 +265,28 @@ static int netconfig_set_dns(struct netconfig *netconfig) APPEND_STRDUPV(dns_list, n_entries, netconfig->dns4_overrides); APPENDV(dns_list, n_entries, dns4_list); - /* Contents now belong to ret, so not l_strfreev */ - l_free(dns4_list); APPEND_STRDUPV(dns_list, n_entries, netconfig->dns6_overrides); APPENDV(dns_list, n_entries, dns6_list); - /* Contents now belong to ret, so not l_strfreev */ - l_free(dns6_list); - resolve_set_dns(netconfig->resolve, dns_list); + + if (fils_dns4_mac && !l_rtnl_neighbor_set_hwaddr(rtnl, + netconfig->ifindex, AF_INET, + &fils->ipv4_dns, fils_dns4_mac, 6, + netconfig_set_neighbor_entry_cb, NULL, + NULL)) + l_debug("l_rtnl_neighbor_set_hwaddr failed"); + + if (fils_dns6_mac && !l_rtnl_neighbor_set_hwaddr(rtnl, + netconfig->ifindex, AF_INET6, + fils->ipv6_dns, fils_dns6_mac, 6, + netconfig_set_neighbor_entry_cb, NULL, + NULL)) + l_debug("l_rtnl_neighbor_set_hwaddr failed"); + l_strv_free(dns_list); + /* Contents belonged to dns_list, so not l_strfreev */ + l_free(dns4_list); + l_free(dns6_list); return 0; } @@ -270,56 +350,55 @@ static int netconfig_set_domains(struct netconfig *netconfig) } static struct l_rtnl_address *netconfig_get_static4_address( - struct netconfig *netconfig) + const struct l_settings *active_settings) { struct l_rtnl_address *ifaddr = NULL; - char *ip; - char *netmask; + L_AUTO_FREE_VAR(char *, ip) = NULL; + L_AUTO_FREE_VAR(char *, netmask) = NULL; struct in_addr in_addr; - char *broadcast; + L_AUTO_FREE_VAR(char *, broadcast) = NULL; uint32_t prefix_len; - ip = l_settings_get_string(netconfig->active_settings, "IPv4", - "Address"); + ip = l_settings_get_string(active_settings, "IPv4", "Address"); if (!ip) return NULL; - netmask = l_settings_get_string(netconfig->active_settings, - "IPv4", "Netmask"); + netmask = l_settings_get_string(active_settings, "IPv4", "Netmask"); + if (netmask) { + if (inet_pton(AF_INET, netmask, &in_addr) != 1) { + l_error("netconfig: Can't parse IPv4 Netmask"); + return NULL; + } - if (netmask && inet_pton(AF_INET, netmask, &in_addr) > 0) prefix_len = __builtin_popcountl(in_addr.s_addr); - else - prefix_len = 24; - l_free(netmask); + if (ntohl(in_addr.s_addr) != + util_netmask_from_prefix(prefix_len)) { + l_error("netconfig: Invalid IPv4 Netmask"); + return NULL; + } + } else + prefix_len = 24; ifaddr = l_rtnl_address_new(ip, prefix_len); - l_free(ip); - if (!ifaddr) { - l_error("Unable to parse IPv4.Address, ignoring..."); + l_error("netconfig: Unable to parse IPv4.Address"); return NULL; } - broadcast = l_settings_get_string(netconfig->active_settings, - "IPv4", "Broadcast"); - if (broadcast) { - bool r = l_rtnl_address_set_broadcast(ifaddr, broadcast); - l_free(broadcast); - - if (!r) { - l_error("Unable to parse IPv4.Broadcast, ignoring..."); - l_rtnl_address_free(ifaddr); - return NULL; - } + broadcast = l_settings_get_string(active_settings, "IPv4", "Broadcast"); + if (broadcast && !l_rtnl_address_set_broadcast(ifaddr, broadcast)) { + l_error("netconfig: Unable to parse IPv4.Broadcast"); + l_rtnl_address_free(ifaddr); + return NULL; } l_rtnl_address_set_noprefixroute(ifaddr, true); return ifaddr; } -static char *netconfig_ipv4_get_gateway(struct netconfig *netconfig) +static char *netconfig_ipv4_get_gateway(struct netconfig *netconfig, + const uint8_t **out_mac) { const struct l_dhcp_lease *lease; char *gateway; @@ -336,6 +415,19 @@ static char *netconfig_ipv4_get_gateway(struct netconfig *netconfig) return gateway; case RTPROT_DHCP: + if (netconfig->fils_override && + netconfig->fils_override->ipv4_gateway) { + gateway = netconfig_ipv4_to_string( + netconfig->fils_override->ipv4_gateway); + + if (gateway && !l_memeqzero(netconfig->fils_override-> + ipv4_gateway_mac, 6)) + *out_mac = netconfig->fils_override-> + ipv4_gateway_mac; + + return gateway; + } + lease = l_dhcp_client_get_lease(netconfig->dhcp_client); if (!lease) return NULL; @@ -347,15 +439,14 @@ static char *netconfig_ipv4_get_gateway(struct netconfig *netconfig) } static struct l_rtnl_address *netconfig_get_static6_address( - struct netconfig *netconfig) + const struct l_settings *active_settings) { L_AUTO_FREE_VAR(char *, ip); char *p; struct l_rtnl_address *ret; uint32_t prefix_len = 128; - ip = l_settings_get_string(netconfig->active_settings, "IPv6", - "Address"); + ip = l_settings_get_string(active_settings, "IPv6", "Address"); if (!ip) return NULL; @@ -385,14 +476,24 @@ no_prefix_len: } static struct l_rtnl_route *netconfig_get_static6_gateway( - struct netconfig *netconfig) + struct netconfig *netconfig, + const uint8_t **out_mac) { L_AUTO_FREE_VAR(char *, gateway); struct l_rtnl_route *ret; gateway = l_settings_get_string(netconfig->active_settings, "IPv6", "Gateway"); - if (!gateway) + if (!gateway && netconfig->rtm_v6_protocol == RTPROT_DHCP && + netconfig->fils_override && + !l_memeqzero(netconfig->fils_override->ipv6_gateway, + 16)) { + gateway = netconfig_ipv6_to_string( + netconfig->fils_override->ipv6_gateway); + + if (!l_memeqzero(netconfig->fils_override->ipv6_gateway_mac, 6)) + *out_mac = netconfig->fils_override->ipv6_gateway_mac; + } else if (!gateway) return NULL; ret = l_rtnl_route_new_gateway(gateway); @@ -522,7 +623,9 @@ static void netconfig_ifaddr_ipv6_added(struct netconfig *netconfig, l_debug("ifindex %u: ifaddr %s/%u", netconfig->ifindex, ip, ifa->ifa_prefixlen); - if (netconfig->rtm_v6_protocol != RTPROT_DHCP) + if (netconfig->rtm_v6_protocol != RTPROT_DHCP || + (netconfig->fils_override && + !l_memeqzero(netconfig->fils_override->ipv6_addr, 16))) return; inet_pton(AF_INET6, ip, &in6); @@ -624,6 +727,7 @@ static void netconfig_route_add_cmd_cb(int error, uint16_t type, static bool netconfig_ipv4_routes_install(struct netconfig *netconfig) { L_AUTO_FREE_VAR(char *, gateway) = NULL; + const uint8_t *gateway_mac = NULL; struct in_addr in_addr; char ip[INET_ADDRSTRLEN]; char network[INET_ADDRSTRLEN]; @@ -650,7 +754,7 @@ static bool netconfig_ipv4_routes_install(struct netconfig *netconfig) return false; } - gateway = netconfig_ipv4_get_gateway(netconfig); + gateway = netconfig_ipv4_get_gateway(netconfig, &gateway_mac); if (!gateway) { l_debug("No gateway obtained from %s.", netconfig->rtm_protocol == RTPROT_STATIC ? @@ -678,6 +782,24 @@ static bool netconfig_ipv4_routes_install(struct netconfig *netconfig) return false; } + if (gateway_mac) { + /* + * Attempt to use the gateway MAC address received from the AP + * by writing the mapping directly into the netdev's ARP table + * so as to save one data frame roundtrip before first IP + * connections are established. This is very low-priority but + * print error messages just because they may indicate bigger + * problems. + */ + if (!l_rtnl_neighbor_set_hwaddr(rtnl, netconfig->ifindex, + AF_INET, + &netconfig->fils_override->ipv4_gateway, + gateway_mac, 6, + netconfig_set_neighbor_entry_cb, NULL, + NULL)) + l_debug("l_rtnl_neighbor_set_hwaddr failed"); + } + return true; } @@ -710,6 +832,7 @@ static void netconfig_ipv6_ifaddr_add_cmd_cb(int error, uint16_t type, { struct netconfig *netconfig = user_data; struct l_rtnl_route *gateway; + const uint8_t *gateway_mac = NULL; netconfig->addr6_add_cmd_id = 0; @@ -719,13 +842,21 @@ static void netconfig_ipv6_ifaddr_add_cmd_cb(int error, uint16_t type, return; } - gateway = netconfig_get_static6_gateway(netconfig); + gateway = netconfig_get_static6_gateway(netconfig, &gateway_mac); if (gateway) { L_WARN_ON(!l_rtnl_route_add(rtnl, netconfig->ifindex, gateway, netconfig_route_generic_cb, netconfig, NULL)); l_rtnl_route_free(gateway); + + if (gateway_mac && !l_rtnl_neighbor_set_hwaddr(rtnl, + netconfig->ifindex, AF_INET6, + netconfig->fils_override->ipv6_gateway, + gateway_mac, 6, + netconfig_set_neighbor_entry_cb, NULL, + NULL)) + l_debug("l_rtnl_neighbor_set_hwaddr failed"); } netconfig_set_dns(netconfig); @@ -898,14 +1029,45 @@ static void netconfig_ipv4_acd_event(enum l_acd_event event, void *user_data) } } -static void netconfig_ipv4_select_and_install(struct netconfig *netconfig) +static bool netconfig_ipv4_select_and_install(struct netconfig *netconfig) { - char ip[INET6_ADDRSTRLEN]; + bool set_address = (netconfig->rtm_protocol == RTPROT_STATIC); + + if (netconfig->rtm_protocol == RTPROT_DHCP && + netconfig->fils_override && + netconfig->fils_override->ipv4_addr) { + L_AUTO_FREE_VAR(char *, addr_str) = netconfig_ipv4_to_string( + netconfig->fils_override->ipv4_addr); + uint8_t prefix_len = netconfig->fils_override->ipv4_prefix_len; + + if (unlikely(!addr_str)) + return false; + + if (L_WARN_ON(unlikely(!(netconfig->v4_address = + l_rtnl_address_new(addr_str, + prefix_len))))) + return false; + + l_rtnl_address_set_noprefixroute(netconfig->v4_address, true); + set_address = true; + + /* + * TODO: If netconfig->fils_override->ipv4_lifetime is set, + * start a timeout to renew the address using FILS IP Address + * Assignment or perhaps just start the DHCP client at that + * time. + */ + } + + if (set_address) { + char ip[INET6_ADDRSTRLEN]; + + if (L_WARN_ON(!netconfig->v4_address || + !l_rtnl_address_get_address( + netconfig->v4_address, + ip))) + return false; - netconfig->v4_address = netconfig_get_static4_address(netconfig); - if (netconfig->v4_address && - l_rtnl_address_get_address(netconfig->v4_address, ip)) { - netconfig->rtm_protocol = RTPROT_STATIC; netconfig->acd = l_acd_new(netconfig->ifindex); l_acd_set_event_handler(netconfig->acd, netconfig_ipv4_acd_event, netconfig, @@ -926,47 +1088,67 @@ static void netconfig_ipv4_select_and_install(struct netconfig *netconfig) netconfig, NULL))); } - return; + return true; } - netconfig->rtm_protocol = RTPROT_DHCP; - if (l_dhcp_client_start(netconfig->dhcp_client)) - return; + return true; l_error("netconfig: Failed to start DHCPv4 client for interface %u", netconfig->ifindex); + return false; } -static void netconfig_ipv6_select_and_install(struct netconfig *netconfig) +static bool netconfig_ipv6_select_and_install(struct netconfig *netconfig) { struct netdev *netdev = netdev_find(netconfig->ifindex); - struct l_rtnl_address *address; - bool enabled; - - if (!l_settings_get_bool(netconfig->active_settings, "IPv6", - "Enabled", &enabled)) - enabled = ipv6_enabled; + struct l_rtnl_address *address = NULL; - if (!enabled) { + if (netconfig->rtm_v6_protocol == RTPROT_UNSPEC) { l_debug("IPV6 configuration disabled"); - return; + return true; } sysfs_write_ipv6_setting(netdev_get_name(netdev), "disable_ipv6", "0"); - address = netconfig_get_static6_address(netconfig); + if (netconfig->rtm_v6_protocol == RTPROT_STATIC) + address = netconfig_get_static6_address( + netconfig->active_settings); + else if (netconfig->rtm_v6_protocol == RTPROT_DHCP && + netconfig->fils_override && + !l_memeqzero(netconfig->fils_override->ipv6_addr, 16)) { + uint8_t prefix_len = netconfig->fils_override->ipv6_prefix_len; + L_AUTO_FREE_VAR(char *, addr_str) = netconfig_ipv6_to_string( + netconfig->fils_override->ipv6_addr); + + if (unlikely(!addr_str)) + return false; + + if (L_WARN_ON(unlikely(!(address = l_rtnl_address_new(addr_str, + prefix_len))))) + return false; + + l_rtnl_address_set_noprefixroute(address, true); + + /* + * TODO: If netconfig->fils_override->ipv6_lifetime is set, + * start a timeout to renew the address using FILS IP Address + * Assignment or perhaps just start the DHCP client at that + * time. + */ + } + if (address) { - netconfig->rtm_v6_protocol = RTPROT_STATIC; L_WARN_ON(!(netconfig->addr6_add_cmd_id = l_rtnl_ifaddr_add(rtnl, netconfig->ifindex, address, netconfig_ipv6_ifaddr_add_cmd_cb, netconfig, NULL))); l_rtnl_address_free(address); - return; + return true; } - netconfig->rtm_v6_protocol = RTPROT_DHCP; + /* DHCP */ + return true; } static int validate_dns_list(int family, char **dns_list) @@ -998,77 +1180,146 @@ static int validate_dns_list(int family, char **dns_list) return n_valid; } -bool netconfig_configure(struct netconfig *netconfig, +bool netconfig_load_settings(struct netconfig *netconfig, const struct l_settings *active_settings, - const uint8_t *mac_address, - netconfig_notify_func_t notify, void *user_data) + const uint8_t *mac_address) { char *mdns; - char hostname[HOST_NAME_MAX + 1]; bool send_hostname; + bool v6_enabled; + char hostname[HOST_NAME_MAX + 1]; + char **dns4_overrides = NULL; + char **dns6_overrides = NULL; + struct l_rtnl_address *v4_address = NULL; + struct l_rtnl_address *v6_address = NULL; - netconfig->dns4_overrides = l_settings_get_string_list(active_settings, + dns4_overrides = l_settings_get_string_list(active_settings, "IPv4", "DNS", ' '); + if (dns4_overrides) { + int r = validate_dns_list(AF_INET, dns4_overrides); - if (netconfig->dns4_overrides) { - int r = validate_dns_list(AF_INET, netconfig->dns4_overrides); + if (unlikely(r <= 0)) { + l_strfreev(dns4_overrides); + dns4_overrides = NULL; - if (r <= 0) { - l_strfreev(netconfig->dns4_overrides); - netconfig->dns4_overrides = NULL; + if (r < 0) + goto err_dns4; } if (r == 0) l_error("netconfig: Empty IPv4.DNS entry, skipping..."); } - netconfig->dns6_overrides = l_settings_get_string_list(active_settings, + dns6_overrides = l_settings_get_string_list(active_settings, "IPv6", "DNS", ' '); - if (netconfig->dns6_overrides) { - int r = validate_dns_list(AF_INET6, netconfig->dns6_overrides); + if (dns6_overrides) { + int r = validate_dns_list(AF_INET6, dns6_overrides); - if (r <= 0) { - l_strfreev(netconfig->dns6_overrides); - netconfig->dns6_overrides = NULL; + if (unlikely(r <= 0)) { + l_strfreev(dns6_overrides); + dns6_overrides = NULL; + + if (r < 0) + goto err_dns6; } if (r == 0) l_error("netconfig: Empty IPv6.DNS entry, skipping..."); } - netconfig->active_settings = active_settings; - netconfig->notify = notify; - netconfig->user_data = user_data; - - l_dhcp_client_set_address(netconfig->dhcp_client, ARPHRD_ETHER, - mac_address, ETH_ALEN); - l_dhcp6_client_set_address(netconfig->dhcp6_client, ARPHRD_ETHER, - mac_address, ETH_ALEN); - if (!l_settings_get_bool(active_settings, "IPv4", "SendHostname", &send_hostname)) send_hostname = false; if (send_hostname) { - if (gethostname(hostname, sizeof(hostname)) == 0) { - l_dhcp_client_set_hostname( - netconfig->dhcp_client, hostname); - } else { + if (gethostname(hostname, sizeof(hostname)) != 0) { l_warn("netconfig: Unable to get hostname. " "Error %d: %s", errno, strerror(errno)); + send_hostname = false; } } - netconfig_ipv4_select_and_install(netconfig); + mdns = l_settings_get_string(active_settings, + "Network", "MulticastDNS"); - netconfig_ipv6_select_and_install(netconfig); + if (l_settings_has_key(active_settings, "IPv4", "Address")) { + v4_address = netconfig_get_static4_address(active_settings); + + if (unlikely(!v4_address)) { + l_error("netconfig: Can't parse IPv4 address"); + goto err_v4_addr; + } + } + + if (!l_settings_get_bool(active_settings, "IPv6", + "Enabled", &v6_enabled)) + v6_enabled = ipv6_enabled; + + if (l_settings_has_key(active_settings, "IPv6", "Address")) { + v6_address = netconfig_get_static6_address(active_settings); + l_rtnl_address_free(v6_address); + + if (unlikely(!v6_address)) { + l_error("netconfig: Can't parse IPv6 address"); + goto err_v6_addr; + } + } + + /* No more validation steps for now, commit new values */ + + if (v4_address) { + netconfig->v4_address = v4_address; + netconfig->rtm_protocol = RTPROT_STATIC; + } else + netconfig->rtm_protocol = RTPROT_DHCP; + + if (!v6_enabled) + netconfig->rtm_v6_protocol = RTPROT_UNSPEC; + else if (v6_address) + netconfig->rtm_v6_protocol = RTPROT_STATIC; + else + netconfig->rtm_v6_protocol = RTPROT_DHCP; + + if (send_hostname) + l_dhcp_client_set_hostname(netconfig->dhcp_client, hostname); - mdns = l_settings_get_string(active_settings, - "Network", "MulticastDNS"); resolve_set_mdns(netconfig->resolve, mdns); l_free(mdns); + l_dhcp_client_set_address(netconfig->dhcp_client, ARPHRD_ETHER, + mac_address, ETH_ALEN); + l_dhcp6_client_set_address(netconfig->dhcp6_client, ARPHRD_ETHER, + mac_address, ETH_ALEN); + + netconfig->active_settings = active_settings; + netconfig->dns4_overrides = dns4_overrides; + netconfig->dns6_overrides = dns6_overrides; + return true; + +err_v6_addr: + l_rtnl_address_free(v4_address); +err_v4_addr: + l_free(mdns); + l_strfreev(dns6_overrides); +err_dns6: + l_strfreev(dns4_overrides); +err_dns4: + return false; +} + +bool netconfig_configure(struct netconfig *netconfig, + netconfig_notify_func_t notify, void *user_data) +{ + netconfig->notify = notify; + netconfig->user_data = user_data; + + if (unlikely(!netconfig_ipv4_select_and_install(netconfig))) + return false; + + if (unlikely(!netconfig_ipv6_select_and_install(netconfig))) + return false; + return true; } @@ -1120,6 +1371,8 @@ bool netconfig_reset(struct netconfig *netconfig) "disable_ipv6", "1"); } + l_free(l_steal_ptr(netconfig->fils_override)); + return true; } @@ -1137,6 +1390,35 @@ char *netconfig_get_dhcp_server_ipv4(struct netconfig *netconfig) return l_dhcp_lease_get_server_id(lease); } +bool netconfig_get_fils_ip_req(struct netconfig *netconfig, + struct ie_fils_ip_addr_request_info *info) +{ + /* + * Fill in the fields used for building the FILS IP Address Assigment + * IE during connection if we're configured to do automatic network + * configuration (usually DHCP). If we're configured with static + * values return false to mean the IE should not be sent. + */ + if (netconfig->rtm_protocol != RTPROT_DHCP && + netconfig->rtm_v6_protocol != RTPROT_DHCP) + return false; + + memset(info, 0, sizeof(*info)); + info->ipv4 = (netconfig->rtm_protocol == RTPROT_DHCP); + info->ipv6 = (netconfig->rtm_v6_protocol == RTPROT_DHCP); + info->dns = (info->ipv4 && !netconfig->dns4_overrides) || + (info->ipv6 && !netconfig->dns6_overrides); + + return true; +} + +void netconfig_handle_fils_ip_resp(struct netconfig *netconfig, + const struct ie_fils_ip_addr_response_info *info) +{ + l_free(netconfig->fils_override); + netconfig->fils_override = l_memdup(info, sizeof(*info)); +} + struct netconfig *netconfig_new(uint32_t ifindex) { struct netdev *netdev = netdev_find(ifindex); diff --git a/src/netconfig.h b/src/netconfig.h @@ -21,6 +21,8 @@ */ struct netconfig; +struct ie_fils_ip_addr_request_info; +struct ie_fils_ip_addr_response_info; enum netconfig_event { NETCONFIG_EVENT_CONNECTED, @@ -29,14 +31,19 @@ enum netconfig_event { typedef void (*netconfig_notify_func_t)(enum netconfig_event event, void *user_data); -bool netconfig_configure(struct netconfig *netconfig, +bool netconfig_load_settings(struct netconfig *netconfig, const struct l_settings *active_settings, - const uint8_t *mac_address, + const uint8_t *mac_address); +bool netconfig_configure(struct netconfig *netconfig, netconfig_notify_func_t notify, void *user_data); bool netconfig_reconfigure(struct netconfig *netconfig); bool netconfig_reset(struct netconfig *netconfig); char *netconfig_get_dhcp_server_ipv4(struct netconfig *netconfig); +bool netconfig_get_fils_ip_req(struct netconfig *netconfig, + struct ie_fils_ip_addr_request_info *info); +void netconfig_handle_fils_ip_resp(struct netconfig *netconfig, + const struct ie_fils_ip_addr_response_info *info); struct netconfig *netconfig_new(uint32_t ifindex); void netconfig_destroy(struct netconfig *netconfig); diff --git a/src/netdev.c b/src/netdev.c @@ -119,6 +119,7 @@ struct netdev { void *user_data; struct eapol_sm *sm; struct auth_proto *ap; + struct owe_sm *owe_sm; struct handshake_state *handshake; uint32_t connect_cmd_id; uint32_t disconnect_cmd_id; @@ -181,6 +182,7 @@ struct netdev { bool events_ready : 1; bool retry_auth : 1; bool in_reassoc : 1; + bool privacy : 1; }; struct netdev_preauth_state { @@ -292,6 +294,9 @@ static unsigned int netdev_populate_common_ies(struct netdev *netdev, c_iov = iov_ie_append(iov, n_iov, c_iov, hs->vendor_ies); + if (hs->fils_ip_req_ie) + c_iov = iov_ie_append(iov, n_iov, c_iov, hs->fils_ip_req_ie); + return c_iov; } @@ -748,6 +753,11 @@ static void netdev_connect_free(struct netdev *netdev) netdev->ap = NULL; } + if (netdev->owe_sm) { + owe_sm_free(netdev->owe_sm); + netdev->owe_sm = NULL; + } + eapol_preauth_cancel(netdev->index); if (netdev->handshake) { @@ -785,6 +795,7 @@ static void netdev_connect_free(struct netdev *netdev) netdev->ignore_connect_event = false; netdev->expect_connect_failure = false; netdev->cur_rssi_low = false; + netdev->privacy = false; if (netdev->connect_cmd) { l_genl_msg_unref(netdev->connect_cmd); @@ -2089,6 +2100,228 @@ static void netdev_driver_connected(struct netdev *netdev) eapol_register(netdev->sm); } +static unsigned int ie_rsn_akm_suite_to_nl80211(enum ie_rsn_akm_suite akm) +{ + switch (akm) { + case IE_RSN_AKM_SUITE_8021X: + return CRYPTO_AKM_8021X; + case IE_RSN_AKM_SUITE_PSK: + return CRYPTO_AKM_PSK; + case IE_RSN_AKM_SUITE_FT_OVER_8021X: + return CRYPTO_AKM_FT_OVER_8021X; + case IE_RSN_AKM_SUITE_FT_USING_PSK: + return CRYPTO_AKM_FT_USING_PSK; + case IE_RSN_AKM_SUITE_8021X_SHA256: + return CRYPTO_AKM_8021X_SHA256; + case IE_RSN_AKM_SUITE_PSK_SHA256: + return CRYPTO_AKM_PSK_SHA256; + case IE_RSN_AKM_SUITE_TDLS: + return CRYPTO_AKM_TDLS; + case IE_RSN_AKM_SUITE_SAE_SHA256: + return CRYPTO_AKM_SAE_SHA256; + case IE_RSN_AKM_SUITE_FT_OVER_SAE_SHA256: + return CRYPTO_AKM_FT_OVER_SAE_SHA256; + case IE_RSN_AKM_SUITE_AP_PEER_KEY_SHA256: + return CRYPTO_AKM_AP_PEER_KEY_SHA256; + case IE_RSN_AKM_SUITE_8021X_SUITE_B_SHA256: + return CRYPTO_AKM_8021X_SUITE_B_SHA256; + case IE_RSN_AKM_SUITE_8021X_SUITE_B_SHA384: + return CRYPTO_AKM_8021X_SUITE_B_SHA384; + case IE_RSN_AKM_SUITE_FT_OVER_8021X_SHA384: + return CRYPTO_AKM_FT_OVER_8021X_SHA384; + case IE_RSN_AKM_SUITE_FILS_SHA256: + return CRYPTO_AKM_FILS_SHA256; + case IE_RSN_AKM_SUITE_FILS_SHA384: + return CRYPTO_AKM_FILS_SHA384; + case IE_RSN_AKM_SUITE_FT_OVER_FILS_SHA256: + return CRYPTO_AKM_FT_OVER_FILS_SHA256; + case IE_RSN_AKM_SUITE_FT_OVER_FILS_SHA384: + return CRYPTO_AKM_FT_OVER_FILS_SHA384; + case IE_RSN_AKM_SUITE_OWE: + return CRYPTO_AKM_OWE; + case IE_RSN_AKM_SUITE_OSEN: + return CRYPTO_AKM_OSEN; + } + + return 0; +} + +static struct l_genl_msg *netdev_build_cmd_connect(struct netdev *netdev, + struct handshake_state *hs, + const uint8_t *prev_bssid, + const struct iovec *vendor_ies, + size_t num_vendor_ies) +{ + struct netdev_handshake_state *nhs = + l_container_of(hs, struct netdev_handshake_state, super); + uint32_t auth_type = IE_AKM_IS_SAE(hs->akm_suite) ? + NL80211_AUTHTYPE_SAE : + NL80211_AUTHTYPE_OPEN_SYSTEM; + enum mpdu_management_subtype subtype = prev_bssid ? + MPDU_MANAGEMENT_SUBTYPE_REASSOCIATION_REQUEST : + MPDU_MANAGEMENT_SUBTYPE_ASSOCIATION_REQUEST; + struct l_genl_msg *msg; + struct iovec iov[64]; + unsigned int n_iov = L_ARRAY_SIZE(iov); + unsigned int c_iov = 0; + bool is_rsn = hs->supplicant_ie != NULL; + uint8_t owe_dh_ie[5 + L_ECC_SCALAR_MAX_BYTES]; + size_t dh_ie_len; + + msg = l_genl_msg_new_sized(NL80211_CMD_CONNECT, 512); + l_genl_msg_append_attr(msg, NL80211_ATTR_IFINDEX, 4, &netdev->index); + l_genl_msg_append_attr(msg, NL80211_ATTR_WIPHY_FREQ, + 4, &netdev->frequency); + l_genl_msg_append_attr(msg, NL80211_ATTR_MAC, ETH_ALEN, hs->aa); + l_genl_msg_append_attr(msg, NL80211_ATTR_SSID, hs->ssid_len, hs->ssid); + l_genl_msg_append_attr(msg, NL80211_ATTR_AUTH_TYPE, 4, &auth_type); + + switch (nhs->type) { + case CONNECTION_TYPE_SOFTMAC: + case CONNECTION_TYPE_FULLMAC: + break; + case CONNECTION_TYPE_SAE_OFFLOAD: + l_genl_msg_append_attr(msg, NL80211_ATTR_SAE_PASSWORD, + strlen(hs->passphrase), hs->passphrase); + break; + case CONNECTION_TYPE_PSK_OFFLOAD: + l_genl_msg_append_attr(msg, NL80211_ATTR_PMK, 32, hs->pmk); + break; + case CONNECTION_TYPE_8021X_OFFLOAD: + l_genl_msg_append_attr(msg, NL80211_ATTR_WANT_1X_4WAY_HS, + 0, NULL); + } + + if (prev_bssid) + l_genl_msg_append_attr(msg, NL80211_ATTR_PREV_BSSID, ETH_ALEN, + prev_bssid); + + if (netdev->privacy) + l_genl_msg_append_attr(msg, NL80211_ATTR_PRIVACY, 0, NULL); + + l_genl_msg_append_attr(msg, NL80211_ATTR_SOCKET_OWNER, 0, NULL); + + if (is_rsn) { + uint32_t nl_cipher; + uint32_t nl_akm; + uint32_t wpa_version; + + if (hs->pairwise_cipher == IE_RSN_CIPHER_SUITE_CCMP) + nl_cipher = CRYPTO_CIPHER_CCMP; + else + nl_cipher = CRYPTO_CIPHER_TKIP; + + l_genl_msg_append_attr(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE, + 4, &nl_cipher); + + if (hs->group_cipher == IE_RSN_CIPHER_SUITE_CCMP) + nl_cipher = CRYPTO_CIPHER_CCMP; + else + nl_cipher = CRYPTO_CIPHER_TKIP; + + l_genl_msg_append_attr(msg, NL80211_ATTR_CIPHER_SUITE_GROUP, + 4, &nl_cipher); + + if (hs->mfp) { + uint32_t use_mfp = NL80211_MFP_REQUIRED; + l_genl_msg_append_attr(msg, NL80211_ATTR_USE_MFP, + 4, &use_mfp); + } + + nl_akm = ie_rsn_akm_suite_to_nl80211(hs->akm_suite); + if (nl_akm) + l_genl_msg_append_attr(msg, NL80211_ATTR_AKM_SUITES, + 4, &nl_akm); + + if (IE_AKM_IS_SAE(hs->akm_suite)) + wpa_version = NL80211_WPA_VERSION_3; + else if (hs->wpa_ie) + wpa_version = NL80211_WPA_VERSION_1; + else + wpa_version = NL80211_WPA_VERSION_2; + + l_genl_msg_append_attr(msg, NL80211_ATTR_WPA_VERSIONS, + 4, &wpa_version); + + l_genl_msg_append_attr(msg, NL80211_ATTR_CONTROL_PORT, 0, NULL); + c_iov = iov_ie_append(iov, n_iov, c_iov, hs->supplicant_ie); + } + + if (netdev->owe_sm) { + owe_build_dh_ie(netdev->owe_sm, owe_dh_ie, &dh_ie_len); + c_iov = iov_ie_append(iov, n_iov, c_iov, owe_dh_ie); + } + + if (netdev->pae_over_nl80211) + l_genl_msg_append_attr(msg, + NL80211_ATTR_CONTROL_PORT_OVER_NL80211, + 0, NULL); + + c_iov = iov_ie_append(iov, n_iov, c_iov, hs->mde); + c_iov = netdev_populate_common_ies(netdev, hs, msg, iov, n_iov, c_iov); + + mpdu_sort_ies(subtype, iov, c_iov); + + if (vendor_ies && !L_WARN_ON(n_iov - c_iov < num_vendor_ies)) { + memcpy(iov + c_iov, vendor_ies, + sizeof(*vendor_ies) * num_vendor_ies); + c_iov += num_vendor_ies; + } + + if (c_iov) + l_genl_msg_append_attrv(msg, NL80211_ATTR_IE, iov, c_iov); + + return msg; +} + +static void netdev_cmd_connect_cb(struct l_genl_msg *msg, void *user_data) +{ + struct netdev *netdev = user_data; + + netdev->connect_cmd_id = 0; + + if (l_genl_msg_get_error(msg) >= 0) { + /* + * connected should be false if the connect event hasn't come + * in yet. i.e. the CMD_CONNECT ack arrived first (typical). + * Mark the connection as 'connected' + */ + if (!netdev->connected) + netdev_driver_connected(netdev); + + return; + } + + netdev_connect_failed(netdev, NETDEV_RESULT_ASSOCIATION_FAILED, + MMPDU_STATUS_CODE_UNSPECIFIED); +} + +static bool netdev_retry_owe(struct netdev *netdev) +{ + struct iovec iov; + + if (!owe_next_group(netdev->owe_sm)) + return false; + + iov.iov_base = netdev->handshake->vendor_ies; + iov.iov_len = netdev->handshake->vendor_ies_len; + + netdev->connect_cmd = netdev_build_cmd_connect(netdev, + netdev->handshake, NULL, &iov, 1); + + netdev->connect_cmd_id = l_genl_family_send(nl80211, + netdev->connect_cmd, + netdev_cmd_connect_cb, netdev, + NULL); + + if (!netdev->connect_cmd_id) + return false; + + netdev->connect_cmd = NULL; + + return true; +} + static void netdev_connect_event(struct l_genl_msg *msg, struct netdev *netdev) { struct l_genl_attr attr; @@ -2157,6 +2390,14 @@ static void netdev_connect_event(struct l_genl_msg *msg, struct netdev *netdev) goto error; } + if (netdev->owe_sm && status_code && *status_code == + MMPDU_STATUS_CODE_UNSUPP_FINITE_CYCLIC_GROUP) { + if (!netdev_retry_owe(netdev)) + goto error; + + return; + } + /* AP Rejected the authenticate / associate */ if (!status_code || *status_code != 0) goto error; @@ -2170,8 +2411,12 @@ process_resp_ies: if (resp_ies) { const uint8_t *fte = NULL; const uint8_t *qos_set = NULL; + const uint8_t *owe_dh = NULL; + size_t owe_dh_len = 0; size_t qos_len = 0; struct ie_ft_info ft_info; + struct ie_rsn_info info; + bool owe_akm_found = false; ie_tlv_iter_init(&iter, resp_ies, resp_ies_len); @@ -2186,7 +2431,65 @@ process_resp_ies: qos_set = data; qos_len = ie_tlv_iter_get_length(&iter); break; + case IE_TYPE_FILS_IP_ADDRESS: + if (netdev->handshake->fils_ip_resp_ie) { + l_debug("Duplicate response FILS IP " + "Address Assignment IE"); + l_free(netdev->handshake-> + fils_ip_resp_ie); + } + + netdev->handshake->fils_ip_resp_ie = l_memdup( + data - 3, + ie_tlv_iter_get_length(&iter) + 3); + break; + case IE_TYPE_OWE_DH_PARAM: + if (!netdev->owe_sm) + continue; + + owe_dh = data; + owe_dh_len = len; + + break; + + case IE_TYPE_RSN: + if (!netdev->owe_sm) + continue; + + if (ie_parse_rsne(&iter, &info) < 0) { + l_error("could not parse RSN IE"); + goto deauth; + } + + /* + * RFC 8110 Section 4.2 + * An AP agreeing to do OWE MUST include the + * OWE AKM in the RSN element portion of the + * 802.11 association response. + */ + if (info.akm_suites != IE_RSN_AKM_SUITE_OWE) { + l_error("OWE AKM not included"); + goto deauth; + } + + owe_akm_found = true; + + break; + } + } + + if (netdev->owe_sm) { + if (!owe_dh || !owe_akm_found) { + l_error("OWE DH element/RSN not found"); + goto deauth; } + + if (L_WARN_ON(owe_process_dh_ie(netdev->owe_sm, owe_dh, + owe_dh_len) != 0)) + goto deauth; + + owe_sm_free(netdev->owe_sm); + netdev->owe_sm = NULL; } /* FILS handles its own FT key derivation */ @@ -2224,8 +2527,8 @@ process_resp_ies: * Start processing EAPoL frames now that the state machine * has all the input data even in FT mode. */ - if (!eapol_start(netdev->sm)) - goto error; + if (L_WARN_ON(!eapol_start(netdev->sm))) + goto deauth; return; } @@ -2254,54 +2557,8 @@ deauth: netdev, NULL); } -static unsigned int ie_rsn_akm_suite_to_nl80211(enum ie_rsn_akm_suite akm) -{ - switch (akm) { - case IE_RSN_AKM_SUITE_8021X: - return CRYPTO_AKM_8021X; - case IE_RSN_AKM_SUITE_PSK: - return CRYPTO_AKM_PSK; - case IE_RSN_AKM_SUITE_FT_OVER_8021X: - return CRYPTO_AKM_FT_OVER_8021X; - case IE_RSN_AKM_SUITE_FT_USING_PSK: - return CRYPTO_AKM_FT_USING_PSK; - case IE_RSN_AKM_SUITE_8021X_SHA256: - return CRYPTO_AKM_8021X_SHA256; - case IE_RSN_AKM_SUITE_PSK_SHA256: - return CRYPTO_AKM_PSK_SHA256; - case IE_RSN_AKM_SUITE_TDLS: - return CRYPTO_AKM_TDLS; - case IE_RSN_AKM_SUITE_SAE_SHA256: - return CRYPTO_AKM_SAE_SHA256; - case IE_RSN_AKM_SUITE_FT_OVER_SAE_SHA256: - return CRYPTO_AKM_FT_OVER_SAE_SHA256; - case IE_RSN_AKM_SUITE_AP_PEER_KEY_SHA256: - return CRYPTO_AKM_AP_PEER_KEY_SHA256; - case IE_RSN_AKM_SUITE_8021X_SUITE_B_SHA256: - return CRYPTO_AKM_8021X_SUITE_B_SHA256; - case IE_RSN_AKM_SUITE_8021X_SUITE_B_SHA384: - return CRYPTO_AKM_8021X_SUITE_B_SHA384; - case IE_RSN_AKM_SUITE_FT_OVER_8021X_SHA384: - return CRYPTO_AKM_FT_OVER_8021X_SHA384; - case IE_RSN_AKM_SUITE_FILS_SHA256: - return CRYPTO_AKM_FILS_SHA256; - case IE_RSN_AKM_SUITE_FILS_SHA384: - return CRYPTO_AKM_FILS_SHA384; - case IE_RSN_AKM_SUITE_FT_OVER_FILS_SHA256: - return CRYPTO_AKM_FT_OVER_FILS_SHA256; - case IE_RSN_AKM_SUITE_FT_OVER_FILS_SHA384: - return CRYPTO_AKM_FT_OVER_FILS_SHA384; - case IE_RSN_AKM_SUITE_OWE: - return CRYPTO_AKM_OWE; - case IE_RSN_AKM_SUITE_OSEN: - return CRYPTO_AKM_OSEN; - } - - return 0; -} - -static struct l_genl_msg *netdev_build_cmd_associate_common( - struct netdev *netdev) +static struct l_genl_msg *netdev_build_cmd_associate_common( + struct netdev *netdev) { struct handshake_state *hs = netdev->handshake; bool is_rsn = hs->supplicant_ie != NULL; @@ -2387,6 +2644,31 @@ static void netdev_cmd_ft_reassociate_cb(struct l_genl_msg *msg, } } +static bool kernel_will_retry_auth(uint16_t status_code, + uint16_t alg, uint16_t trans) +{ + /* + * Kernel keeps re-trying auth frames until told to stop + * when authentication succeeds and under certain SAE-related + * circumstances. Detect these cases. + */ + + if (status_code == 0) + return true; + + if (alg != MMPDU_AUTH_ALGO_SAE) + return false; + + if (status_code == MMPDU_STATUS_CODE_ANTI_CLOGGING_TOKEN_REQ) + return true; + + if (trans == 1 && (status_code == MMPDU_STATUS_CODE_SAE_PK || + status_code == MMPDU_STATUS_CODE_SAE_HASH_TO_ELEMENT)) + return true; + + return false; +} + static void netdev_authenticate_event(struct l_genl_msg *msg, struct netdev *netdev) { @@ -2450,6 +2732,7 @@ static void netdev_authenticate_event(struct l_genl_msg *msg, if (netdev->ap) { const struct mmpdu_header *hdr; const struct mmpdu_authentication *auth; + bool retry; if (L_WARN_ON(!(hdr = mpdu_validate(frame, frame_len)))) goto auth_error; @@ -2458,10 +2741,42 @@ static void netdev_authenticate_event(struct l_genl_msg *msg, status_code = L_CPU_TO_LE16(auth->status); ret = auth_proto_rx_authenticate(netdev->ap, frame, frame_len); + + /* We have sent another CMD_AUTHENTICATE / CMD_ASSOCIATE */ if (ret == 0 || ret == -EAGAIN) return; - else if (ret > 0) + + retry = kernel_will_retry_auth(status_code, + L_CPU_TO_LE16(auth->algorithm), + L_CPU_TO_LE16(auth->transaction_sequence)); + + /* + * Spec wants us to silently drop these frames, + * if the kernel will keep retrying, let it + */ + if ((ret == -ENOMSG || ret == -EBADMSG) && retry) + return; + + if (ret > 0) status_code = (uint16_t)ret; + + /* + * We have encountered a fatal error, if the kernel wants + * to keep retrying, tell it to stop + */ + if (retry) { + struct l_genl_msg *cmd_deauth; + + netdev->result = NETDEV_RESULT_ASSOCIATION_FAILED; + netdev->last_code = MMPDU_STATUS_CODE_UNSPECIFIED; + cmd_deauth = netdev_build_cmd_deauthenticate(netdev, + MMPDU_REASON_CODE_UNSPECIFIED); + netdev->disconnect_cmd_id = l_genl_family_send(nl80211, + cmd_deauth, + netdev_disconnect_cb, + netdev, NULL); + return; + } } auth_error: @@ -2585,28 +2900,6 @@ assoc_failed: netdev->expect_connect_failure = true; } -static void netdev_cmd_connect_cb(struct l_genl_msg *msg, void *user_data) -{ - struct netdev *netdev = user_data; - - netdev->connect_cmd_id = 0; - - if (l_genl_msg_get_error(msg) >= 0) { - /* - * connected should be false if the connect event hasn't come - * in yet. i.e. the CMD_CONNECT ack arrived first (typical). - * Mark the connection as 'connected' - */ - if (!netdev->connected) - netdev_driver_connected(netdev); - - return; - } - - netdev_connect_failed(netdev, NETDEV_RESULT_ASSOCIATION_FAILED, - MMPDU_STATUS_CODE_UNSPECIFIED); -} - static struct l_genl_msg *netdev_build_cmd_authenticate(struct netdev *netdev, uint32_t auth_type) { @@ -2697,9 +2990,10 @@ static void netdev_new_scan_results_event(struct l_genl_msg *msg, static void netdev_assoc_cb(struct l_genl_msg *msg, void *user_data) { struct netdev *netdev = user_data; + int err = l_genl_msg_get_error(msg); - if (l_genl_msg_get_error(msg) < 0) { - l_error("Error sending CMD_ASSOCIATE"); + if (err < 0) { + l_error("Error sending CMD_ASSOCIATE (%d)", err); netdev_connect_failed(netdev, NETDEV_RESULT_ASSOCIATION_FAILED, MMPDU_STATUS_CODE_UNSPECIFIED); @@ -2760,64 +3054,6 @@ static void netdev_sae_tx_associate(void *user_data) } } -static void netdev_owe_tx_authenticate(void *user_data) -{ - struct netdev *netdev = user_data; - struct l_genl_msg *msg; - - msg = netdev_build_cmd_authenticate(netdev, - NL80211_AUTHTYPE_OPEN_SYSTEM); - - if (!l_genl_family_send(nl80211, msg, netdev_auth_cb, - netdev, NULL)) { - l_genl_msg_unref(msg); - netdev_connect_failed(netdev, - NETDEV_RESULT_AUTHENTICATION_FAILED, - MMPDU_STATUS_CODE_UNSPECIFIED); - return; - } - - netdev->auth_cmd = l_genl_msg_ref(msg); -} - -static void netdev_owe_tx_associate(struct iovec *owe_iov, size_t n_owe_iov, - void *user_data) -{ - struct netdev *netdev = user_data; - struct handshake_state *hs = netdev->handshake; - struct l_genl_msg *msg; - struct iovec iov[64]; - unsigned int n_iov = L_ARRAY_SIZE(iov); - unsigned int c_iov = 0; - enum mpdu_management_subtype subtype = - MPDU_MANAGEMENT_SUBTYPE_ASSOCIATION_REQUEST; - - msg = netdev_build_cmd_associate_common(netdev); - - c_iov = netdev_populate_common_ies(netdev, hs, msg, iov, n_iov, c_iov); - - if (!L_WARN_ON(n_iov - c_iov < n_owe_iov)) { - memcpy(iov + c_iov, owe_iov, sizeof(*owe_iov) * n_owe_iov); - c_iov += n_owe_iov; - } - - mpdu_sort_ies(subtype, iov, c_iov); - - l_genl_msg_append_attrv(msg, NL80211_ATTR_IE, iov, c_iov); - - /* If doing a non-FT Reassociation */ - if (netdev->in_reassoc) - l_genl_msg_append_attr(msg, NL80211_ATTR_PREV_BSSID, 6, - netdev->ap->prev_bssid); - - if (!l_genl_family_send(nl80211, msg, netdev_assoc_cb, - netdev, NULL)) { - l_genl_msg_unref(msg); - netdev_connect_failed(netdev, NETDEV_RESULT_ASSOCIATION_FAILED, - MMPDU_STATUS_CODE_UNSPECIFIED); - } -} - static void netdev_fils_tx_authenticate(const uint8_t *body, size_t body_len, void *user_data) @@ -2885,129 +3121,6 @@ static void netdev_fils_tx_associate(struct iovec *fils_iov, size_t n_fils_iov, } } -static struct l_genl_msg *netdev_build_cmd_connect(struct netdev *netdev, - struct scan_bss *bss, - struct handshake_state *hs, - const uint8_t *prev_bssid, - const struct iovec *vendor_ies, - size_t num_vendor_ies) -{ - struct netdev_handshake_state *nhs = - l_container_of(hs, struct netdev_handshake_state, super); - uint32_t auth_type = IE_AKM_IS_SAE(hs->akm_suite) ? - NL80211_AUTHTYPE_SAE : - NL80211_AUTHTYPE_OPEN_SYSTEM; - enum mpdu_management_subtype subtype = prev_bssid ? - MPDU_MANAGEMENT_SUBTYPE_REASSOCIATION_REQUEST : - MPDU_MANAGEMENT_SUBTYPE_ASSOCIATION_REQUEST; - struct l_genl_msg *msg; - struct iovec iov[64]; - unsigned int n_iov = L_ARRAY_SIZE(iov); - unsigned int c_iov = 0; - bool is_rsn = hs->supplicant_ie != NULL; - - msg = l_genl_msg_new_sized(NL80211_CMD_CONNECT, 512); - l_genl_msg_append_attr(msg, NL80211_ATTR_IFINDEX, 4, &netdev->index); - l_genl_msg_append_attr(msg, NL80211_ATTR_WIPHY_FREQ, - 4, &bss->frequency); - l_genl_msg_append_attr(msg, NL80211_ATTR_MAC, ETH_ALEN, bss->addr); - l_genl_msg_append_attr(msg, NL80211_ATTR_SSID, - bss->ssid_len, bss->ssid); - l_genl_msg_append_attr(msg, NL80211_ATTR_AUTH_TYPE, 4, &auth_type); - - switch (nhs->type) { - case CONNECTION_TYPE_SOFTMAC: - case CONNECTION_TYPE_FULLMAC: - break; - case CONNECTION_TYPE_SAE_OFFLOAD: - l_genl_msg_append_attr(msg, NL80211_ATTR_SAE_PASSWORD, - strlen(hs->passphrase), hs->passphrase); - break; - case CONNECTION_TYPE_PSK_OFFLOAD: - l_genl_msg_append_attr(msg, NL80211_ATTR_PMK, 32, hs->pmk); - break; - case CONNECTION_TYPE_8021X_OFFLOAD: - l_genl_msg_append_attr(msg, NL80211_ATTR_WANT_1X_4WAY_HS, - 0, NULL); - } - - if (prev_bssid) - l_genl_msg_append_attr(msg, NL80211_ATTR_PREV_BSSID, ETH_ALEN, - prev_bssid); - - if (bss->capability & IE_BSS_CAP_PRIVACY) - l_genl_msg_append_attr(msg, NL80211_ATTR_PRIVACY, 0, NULL); - - l_genl_msg_append_attr(msg, NL80211_ATTR_SOCKET_OWNER, 0, NULL); - - if (is_rsn) { - uint32_t nl_cipher; - uint32_t nl_akm; - uint32_t wpa_version; - - if (hs->pairwise_cipher == IE_RSN_CIPHER_SUITE_CCMP) - nl_cipher = CRYPTO_CIPHER_CCMP; - else - nl_cipher = CRYPTO_CIPHER_TKIP; - - l_genl_msg_append_attr(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE, - 4, &nl_cipher); - - if (hs->group_cipher == IE_RSN_CIPHER_SUITE_CCMP) - nl_cipher = CRYPTO_CIPHER_CCMP; - else - nl_cipher = CRYPTO_CIPHER_TKIP; - - l_genl_msg_append_attr(msg, NL80211_ATTR_CIPHER_SUITE_GROUP, - 4, &nl_cipher); - - if (hs->mfp) { - uint32_t use_mfp = NL80211_MFP_REQUIRED; - l_genl_msg_append_attr(msg, NL80211_ATTR_USE_MFP, - 4, &use_mfp); - } - - nl_akm = ie_rsn_akm_suite_to_nl80211(hs->akm_suite); - if (nl_akm) - l_genl_msg_append_attr(msg, NL80211_ATTR_AKM_SUITES, - 4, &nl_akm); - - if (IE_AKM_IS_SAE(hs->akm_suite)) - wpa_version = NL80211_WPA_VERSION_3; - else if (hs->wpa_ie) - wpa_version = NL80211_WPA_VERSION_1; - else - wpa_version = NL80211_WPA_VERSION_2; - - l_genl_msg_append_attr(msg, NL80211_ATTR_WPA_VERSIONS, - 4, &wpa_version); - - l_genl_msg_append_attr(msg, NL80211_ATTR_CONTROL_PORT, 0, NULL); - c_iov = iov_ie_append(iov, n_iov, c_iov, hs->supplicant_ie); - } - - if (netdev->pae_over_nl80211) - l_genl_msg_append_attr(msg, - NL80211_ATTR_CONTROL_PORT_OVER_NL80211, - 0, NULL); - - c_iov = iov_ie_append(iov, n_iov, c_iov, hs->mde); - c_iov = netdev_populate_common_ies(netdev, hs, msg, iov, n_iov, c_iov); - - mpdu_sort_ies(subtype, iov, c_iov); - - if (vendor_ies && !L_WARN_ON(n_iov - c_iov < num_vendor_ies)) { - memcpy(iov + c_iov, vendor_ies, - sizeof(*vendor_ies) * num_vendor_ies); - c_iov += num_vendor_ies; - } - - if (c_iov) - l_genl_msg_append_attrv(msg, NL80211_ATTR_IE, iov, c_iov); - - return msg; -} - struct rtnl_data { struct netdev *netdev; uint8_t addr[ETH_ALEN]; @@ -3382,6 +3495,8 @@ static int netdev_handshake_state_setup_connection_type( NL80211_EXT_FEATURE_4WAY_HANDSHAKE_STA_PSK)) goto psk_offload; + /* fall through */ + case IE_RSN_AKM_SUITE_OWE: if (softmac) goto softmac; @@ -3410,12 +3525,11 @@ static int netdev_handshake_state_setup_connection_type( goto softmac; return -EINVAL; - case IE_RSN_AKM_SUITE_OWE: case IE_RSN_AKM_SUITE_FILS_SHA256: case IE_RSN_AKM_SUITE_FILS_SHA384: case IE_RSN_AKM_SUITE_FT_OVER_FILS_SHA256: case IE_RSN_AKM_SUITE_FT_OVER_FILS_SHA384: - /* FILS and OWE have no offload in any upstream driver */ + /* FILS has no offload in any upstream driver */ if (softmac) goto softmac; @@ -3461,6 +3575,10 @@ static void netdev_connect_common(struct netdev *netdev, bool is_rsn = hs->supplicant_ie != NULL; const uint8_t *prev_bssid = prev_bss ? prev_bss->addr : NULL; + netdev->frequency = bss->frequency; + netdev->privacy = bss->capability & IE_BSS_CAP_PRIVACY; + handshake_state_set_authenticator_address(hs, bss->addr); + if (!is_rsn) goto build_cmd_connect; @@ -3485,12 +3603,14 @@ static void netdev_connect_common(struct netdev *netdev, } } + if (bss->force_default_sae_group) + sae_sm_set_force_group_19(netdev->ap); + break; case IE_RSN_AKM_SUITE_OWE: - netdev->ap = owe_sm_new(hs, netdev_owe_tx_authenticate, - netdev_owe_tx_associate, - netdev); - break; + netdev->owe_sm = owe_sm_new(hs); + + goto build_cmd_connect; case IE_RSN_AKM_SUITE_FILS_SHA256: case IE_RSN_AKM_SUITE_FILS_SHA384: case IE_RSN_AKM_SUITE_FT_OVER_FILS_SHA256: @@ -3501,8 +3621,8 @@ static void netdev_connect_common(struct netdev *netdev, break; default: build_cmd_connect: - cmd_connect = netdev_build_cmd_connect(netdev, bss, hs, - prev_bssid, vendor_ies, num_vendor_ies); + cmd_connect = netdev_build_cmd_connect(netdev, hs, prev_bssid, + vendor_ies, num_vendor_ies); if (!is_offload(hs) && (is_rsn || hs->settings_8021x)) { sm = eapol_sm_new(hs); @@ -3518,13 +3638,10 @@ build_cmd_connect: netdev->user_data = user_data; netdev->handshake = hs; netdev->sm = sm; - netdev->frequency = bss->frequency; netdev->cur_rssi = bss->signal_strength / 100; netdev_rssi_level_init(netdev); netdev_cqm_rssi_update(netdev); - handshake_state_set_authenticator_address(hs, bss->addr); - if (!wiphy_has_ext_feature(netdev->wiphy, NL80211_EXT_FEATURE_CAN_REPLACE_PTK0)) handshake_state_set_no_rekey(hs, true); diff --git a/src/owe.c b/src/owe.c @@ -34,7 +34,6 @@ #include "src/auth-proto.h" struct owe_sm { - struct auth_proto ap; struct handshake_state *hs; const struct l_ecc_curve *curve; struct l_ecc_scalar *private; @@ -42,10 +41,6 @@ struct owe_sm { uint8_t retry; uint16_t group; const unsigned int *ecc_groups; - - owe_tx_authenticate_func_t auth_tx; - owe_tx_associate_func_t assoc_tx; - void *user_data; }; static bool owe_reset(struct owe_sm *owe) @@ -72,62 +67,28 @@ static bool owe_reset(struct owe_sm *owe) return true; } -static void owe_free(struct auth_proto *ap) +void owe_sm_free(struct owe_sm *owe) { - struct owe_sm *owe = l_container_of(ap, struct owe_sm, ap); - l_ecc_scalar_free(owe->private); l_ecc_point_free(owe->public_key); l_free(owe); } -static bool owe_start(struct auth_proto *ap) +void owe_build_dh_ie(struct owe_sm *owe, uint8_t *buf, size_t *len_out) { - struct owe_sm *owe = l_container_of(ap, struct owe_sm, ap); - - owe->auth_tx(owe->user_data); - - return true; -} - -static int owe_rx_authenticate(struct auth_proto *ap, const uint8_t *frame, - size_t frame_len) -{ - struct owe_sm *owe = l_container_of(ap, struct owe_sm, ap); - - uint8_t buf[5 + L_ECC_SCALAR_MAX_BYTES]; - struct iovec iov[3]; - int iov_elems = 0; - size_t len; - - /* - * RFC 8110 Section 4.3 - * A client wishing to do OWE MUST indicate the OWE AKM in the RSN - * element portion of the 802.11 association request ... - */ - iov[iov_elems].iov_base = owe->hs->supplicant_ie; - iov[iov_elems].iov_len = owe->hs->supplicant_ie[1] + 2; - iov_elems++; - /* - * ... and MUST include a Diffie-Hellman Parameter element to its - * 802.11 association request. + * A client wishing to do OWE ... MUST include a Diffie-Hellman + * Parameter element to its 802.11 association request. */ buf[0] = IE_TYPE_EXTENSION; buf[2] = IE_TYPE_OWE_DH_PARAM - 256; l_put_le16(owe->group, buf + 3); /* group */ - len = l_ecc_point_get_x(owe->public_key, buf + 5, + *len_out = l_ecc_point_get_x(owe->public_key, buf + 5, L_ECC_SCALAR_MAX_BYTES); - buf[1] = 3 + len; /* length */ - - iov[iov_elems].iov_base = (void *) buf; - iov[iov_elems].iov_len = buf[1] + 2; - iov_elems++; + buf[1] = 3 + *len_out; /* length */ - owe->assoc_tx(iov, iov_elems, owe->user_data); - - return 0; + *len_out += 5; } /* @@ -220,7 +181,7 @@ failed: return false; } -static bool owe_retry(struct owe_sm *owe) +bool owe_next_group(struct owe_sm *owe) { /* retry with another group, if possible */ owe->retry++; @@ -228,88 +189,23 @@ static bool owe_retry(struct owe_sm *owe) if (!owe_reset(owe)) return false; - l_debug("OWE retrying with group %u", owe->group); - - owe_rx_authenticate(&owe->ap, NULL, 0); - return true; } -static int owe_rx_associate(struct auth_proto *ap, const uint8_t *frame, - size_t len) +int owe_process_dh_ie(struct owe_sm *owe, const uint8_t *dh, size_t len) { - struct owe_sm *owe = l_container_of(ap, struct owe_sm, ap); - - const struct mmpdu_header *mpdu = (const struct mmpdu_header *) frame; - const struct mmpdu_association_response *body = mmpdu_body(mpdu); - struct ie_tlv_iter iter; - size_t owe_dh_len = 0; - const uint8_t *owe_dh = NULL; - struct ie_rsn_info info; - bool akm_found = false; - const void *data; - - if (L_LE16_TO_CPU(body->status_code) == - MMPDU_STATUS_CODE_UNSUPP_FINITE_CYCLIC_GROUP) { - if (!owe_retry(owe)) - goto owe_bad_status; - - return -EAGAIN; - } else if (body->status_code) - goto owe_bad_status; - - ie_tlv_iter_init(&iter, body->ies, (const uint8_t *) mpdu + len - - body->ies); - - while (ie_tlv_iter_next(&iter)) { - uint16_t tag = ie_tlv_iter_get_tag(&iter); - - data = ie_tlv_iter_get_data(&iter); - len = ie_tlv_iter_get_length(&iter); - - switch (tag) { - case IE_TYPE_OWE_DH_PARAM: - owe_dh = data; - owe_dh_len = len; - - break; - case IE_TYPE_RSN: - if (ie_parse_rsne(&iter, &info) < 0) { - l_error("could not parse RSN IE"); - goto invalid_ies; - } - - /* - * RFC 8110 Section 4.2 - * An AP agreeing to do OWE MUST include the OWE AKM in - * the RSN element portion of the 802.11 association - * response. - */ - if (info.akm_suites != IE_RSN_AKM_SUITE_OWE) { - l_error("OWE AKM not included"); - goto invalid_ies; - } - - akm_found = true; - - break; - default: - continue; - } - } - - if (!owe_dh || owe_dh_len < 34 || !akm_found) { + if (!dh || len < 34) { l_error("associate response did not include proper OWE IE's"); goto invalid_ies; } - if (l_get_le16(owe_dh) != owe->group) { + if (l_get_le16(dh) != owe->group) { l_error("associate response contained unsupported group %u", - l_get_le16(owe_dh)); + l_get_le16(dh)); return -EBADMSG; } - if (!owe_compute_keys(owe, owe_dh + 2, owe_dh_len - 2)) { + if (!owe_compute_keys(owe, dh + 2, len - 2)) { l_error("could not compute OWE keys"); return -EBADMSG; } @@ -318,33 +214,19 @@ static int owe_rx_associate(struct auth_proto *ap, const uint8_t *frame, invalid_ies: return MMPDU_STATUS_CODE_INVALID_ELEMENT; - -owe_bad_status: - return L_LE16_TO_CPU(body->status_code); } -struct auth_proto *owe_sm_new(struct handshake_state *hs, - owe_tx_authenticate_func_t auth, - owe_tx_associate_func_t assoc, - void *user_data) +struct owe_sm *owe_sm_new(struct handshake_state *hs) { struct owe_sm *owe = l_new(struct owe_sm, 1); owe->hs = hs; - owe->auth_tx = auth; - owe->assoc_tx = assoc; - owe->user_data = user_data; owe->ecc_groups = l_ecc_supported_ike_groups(); - owe->ap.start = owe_start; - owe->ap.free = owe_free; - owe->ap.rx_authenticate = owe_rx_authenticate; - owe->ap.rx_associate = owe_rx_associate; - if (!owe_reset(owe)) { l_free(owe); return NULL; } - return &owe->ap; + return owe; } diff --git a/src/owe.h b/src/owe.h @@ -23,11 +23,9 @@ struct owe_sm; struct handshake_state; -typedef void (*owe_tx_authenticate_func_t)(void *user_data); -typedef void (*owe_tx_associate_func_t)(struct iovec *ie_iov, size_t iov_len, - void *user_data); +struct owe_sm *owe_sm_new(struct handshake_state *hs); +void owe_sm_free(struct owe_sm *sm); -struct auth_proto *owe_sm_new(struct handshake_state *hs, - owe_tx_authenticate_func_t auth, - owe_tx_associate_func_t assoc, - void *user_data); +void owe_build_dh_ie(struct owe_sm *sm, uint8_t *buf, size_t *len_out); +int owe_process_dh_ie(struct owe_sm *sm, const uint8_t *dh, size_t len); +bool owe_next_group(struct owe_sm *sm); diff --git a/src/p2p.c b/src/p2p.c @@ -1280,6 +1280,7 @@ static void p2p_group_start(struct p2p_device *dev) dev->capability.group_caps |= P2P_GROUP_CAP_GO; dev->capability.group_caps |= P2P_GROUP_CAP_GROUP_FORMATION; + dev->capability.group_caps |= P2P_GROUP_CAP_IP_ALLOCATION; dev->group = ap_start(dev->conn_netdev, config, &p2p_go_ops, NULL, dev); l_settings_free(config); @@ -1331,8 +1332,16 @@ static void p2p_start_client_netconfig(struct p2p_device *dev) } settings = dev->conn_netconfig_settings ?: p2p_dhcp_settings; - netconfig_configure(dev->conn_netconfig, settings, dev->conn_addr, - p2p_netconfig_event_handler, dev); + + if (!netconfig_load_settings(dev->conn_netconfig, settings, + dev->conn_addr) || + !netconfig_configure(dev->conn_netconfig, + p2p_netconfig_event_handler, + dev)) { + p2p_connect_failed(dev); + return; + } + dev->conn_dhcp_timeout = l_timeout_create(p2p_dhcp_timeout_val, p2p_dhcp_timeout, dev, p2p_dhcp_timeout_destroy); diff --git a/src/sae.c b/src/sae.c @@ -83,6 +83,8 @@ struct sae_sm { sae_tx_associate_func_t tx_assoc; void *user_data; enum crypto_sae sae_type; + + bool force_default_group : 1; }; static enum mmpdu_status_code sae_status_code(struct sae_sm *sm) @@ -139,6 +141,24 @@ static int sae_choose_next_group(struct sae_sm *sm) const unsigned int *ecc_groups = l_ecc_supported_ike_groups(); bool reset = sm->group_retry >= 0; + /* + * If this is a buggy AP in which group negotiation is broken use the + * default group 19 and fail if this is a retry. + */ + if (sm->sae_type == CRYPTO_SAE_LOOPING && sm->force_default_group) { + if (sm->group_retry != -1) { + l_warn("Forced default group but was rejected!"); + return -ENOENT; + } + + l_debug("Forcing default SAE group 19"); + + sm->group_retry++; + sm->group = 19; + + goto get_curve; + } + do { sm->group_retry++; @@ -151,6 +171,8 @@ static int sae_choose_next_group(struct sae_sm *sm) sae_reset_state(sm); sm->group = ecc_groups[sm->group_retry]; + +get_curve: sm->curve = l_ecc_curve_from_ike_group(sm->group); return 0; @@ -1137,6 +1159,31 @@ static int sae_verify_confirmed(struct sae_sm *sm, uint16_t trans, return -EBADMSG; /* + * Because of kernel retransmit behavior on missed ACKs plus hostapd's + * incorrect handling of confirm packets while in accepted state the + * following can happen: + * + * 1. Client sends commit, not acked (committed state) + * 2. AP receives commit, sends commit reply (committed state) + * 3. Client retransmits original commit + * 4. Client receives AP's commit, sends confirm (confirmed state) + * 5. AP receives clients retransmitted commit, sends only commit + * 6. AP receives clients confirm and accepts (accepted state) + * 7. Client receives AP's commit and sends both commit + confirm + * (the code below). + * 8. AP receives clients commit while in accepted state, and deauths + * + * Due to this, any commit received while in a confirmed state will be + * ignored by IWD since it is probably caused by this retransmission + * and sending the commit/confirm below would likely cause hostapd to + * deauth us. + * + * As for non-sta (currently not used) we want to keep with the spec. + */ + if (!sm->handshake->authenticator) + return -EBADMSG; + + /* * the protocol instance shall increment Sync, increment Sc, and * transmit its Commit and Confirm (with the new Sc value) messages. */ @@ -1160,10 +1207,32 @@ static int sae_verify_accepted(struct sae_sm *sm, uint16_t trans, { uint16_t sc; - /* spec does not specify what to do here, so print and discard */ - if (trans != SAE_STATE_CONFIRMED) { + /* + * 12.4.8.6.1 Parent process behavior + * + * "Upon receipt of an SAE Commit message... and it is in Accepted + * state, the scalar in the received frame is checked against the + * peer-scalar used in authentication of the existing protocol instance + * (in Accepted state). If it is identical, the frame shall be dropped" + */ + if (trans == SAE_STATE_COMMITTED) { + bool drop; + unsigned int nbytes = l_ecc_curve_get_scalar_bytes(sm->curve); + struct l_ecc_scalar *p_scalar; + + if (len < nbytes + 2) + return -EMSGSIZE; + + p_scalar = l_ecc_scalar_new(sm->curve, frame + 2, nbytes); + + drop = l_ecc_scalars_are_equal(sm->p_scalar, p_scalar); + l_ecc_scalar_free(p_scalar); + + if (drop) + return -EBADMSG; + l_error("received transaction %u in accepted state", trans); - return -EBADMSG; + return -EPROTO; } if (sm->sync > SAE_SYNC_MAX) @@ -1204,10 +1273,28 @@ static int sae_verify_accepted(struct sae_sm *sm, uint16_t trans, return -EAGAIN; } +static const char *sae_state_to_str(enum sae_state state) +{ + switch (state) { + case SAE_STATE_NOTHING: + return "nothing"; + case SAE_STATE_COMMITTED: + return "committed"; + case SAE_STATE_CONFIRMED: + return "confirmed"; + case SAE_STATE_ACCEPTED: + return "accepted"; + } + + return "unknown"; +} + static int sae_verify_packet(struct sae_sm *sm, uint16_t trans, uint16_t status, const uint8_t *frame, size_t len) { + l_debug("rx trans=%u, state=%s", trans, sae_state_to_str(sm->state)); + if (trans != SAE_STATE_COMMITTED && trans != SAE_STATE_CONFIRMED) return -EBADMSG; @@ -1298,6 +1385,13 @@ bool sae_sm_is_h2e(struct auth_proto *ap) return sm->sae_type != CRYPTO_SAE_LOOPING; } +void sae_sm_set_force_group_19(struct auth_proto *ap) +{ + struct sae_sm *sm = l_container_of(ap, struct sae_sm, ap); + + sm->force_default_group = true; +} + static void sae_free(struct auth_proto *ap) { struct sae_sm *sm = l_container_of(ap, struct sae_sm, ap); diff --git a/src/sae.h b/src/sae.h @@ -30,6 +30,8 @@ typedef void (*sae_tx_associate_func_t)(void *user_data); bool sae_sm_is_h2e(struct auth_proto *ap); +void sae_sm_set_force_group_19(struct auth_proto *ap); + struct auth_proto *sae_sm_new(struct handshake_state *hs, sae_tx_authenticate_func_t tx_auth, sae_tx_associate_func_t tx_assoc, diff --git a/src/scan.c b/src/scan.c @@ -911,23 +911,39 @@ static bool start_next_scan_request(struct wiphy_radio_work_item *item) return true; } -static bool scan_parse_vendor_specific(struct scan_bss *bss, const void *data, +static void scan_parse_vendor_specific(struct scan_bss *bss, const void *data, uint16_t len) { - if (!bss->wpa && is_ie_wpa_ie(data, len)) + uint16_t cost_level; + uint16_t cost_flags; + + if (!bss->wpa && is_ie_wpa_ie(data, len)) { bss->wpa = l_memdup(data - 2, len + 2); - else if (!bss->osen && is_ie_wfa_ie(data, len, IE_WFA_OI_OSEN)) + return; + } + + if (!bss->osen && is_ie_wfa_ie(data, len, IE_WFA_OI_OSEN)) { bss->osen = l_memdup(data - 2, len + 2); - else if (is_ie_wfa_ie(data, len, IE_WFA_OI_HS20_INDICATION)) { + return; + } + + if (is_ie_wfa_ie(data, len, IE_WFA_OI_HS20_INDICATION)) { if (ie_parse_hs20_indication_from_data(data - 2, len + 2, &bss->hs20_version, NULL, NULL) < 0) - return false; + return; bss->hs20_capable = true; - } else - return false; + return; + } - return true; + if (!ie_parse_network_cost(data, len, &cost_level, &cost_flags)) { + bss->cost_level = cost_level; + bss->cost_flags = cost_flags; + return; + } + + if (is_ie_default_sae_group_oui(data, len)) + bss->force_default_sae_group = true; } /* @@ -1019,7 +1035,6 @@ static bool scan_parse_bss_information_elements(struct scan_bss *bss, break; case IE_TYPE_VENDOR_SPECIFIC: - /* Interested only in WPA/WFA IE from Vendor data */ scan_parse_vendor_specific(bss, iter.data, iter.len); break; case IE_TYPE_MOBILITY_DOMAIN: diff --git a/src/scan.h b/src/scan.h @@ -83,6 +83,9 @@ struct scan_bss { bool vht_capable : 1; bool anqp_capable : 1; bool hs20_capable : 1; + bool force_default_sae_group : 1; + uint8_t cost_level : 3; + uint8_t cost_flags : 4; }; struct scan_parameters { diff --git a/src/station.c b/src/station.c @@ -755,6 +755,7 @@ static void station_handshake_event(struct handshake_state *hs, case HANDSHAKE_EVENT_COMPLETE: case HANDSHAKE_EVENT_SETTING_KEYS_FAILED: case HANDSHAKE_EVENT_EAP_NOTIFY: + case HANDSHAKE_EVENT_P2P_IP_REQUEST: /* * currently we don't care about any other events. The * netdev_connect_cb will notify us when the connection is @@ -925,6 +926,7 @@ static struct handshake_state *station_handshake_setup(struct station *station, struct handshake_state *hs; const struct iovec *vendor_ies; size_t iov_elems = 0; + struct ie_fils_ip_addr_request_info fils_ip_req; hs = netdev_handshake_state_new(station->netdev); @@ -941,6 +943,16 @@ static struct handshake_state *station_handshake_setup(struct station *station, vendor_ies = network_info_get_extra_ies(info, bss, &iov_elems); handshake_state_set_vendor_ies(hs, vendor_ies, iov_elems); + /* + * It can't hurt to try the FILS IP Address Assigment independent of + * which auth-proto is actually used. + */ + if (station->netconfig && netconfig_get_fils_ip_req(station->netconfig, + &fils_ip_req)) { + hs->fils_ip_req_ie = l_malloc(32); + ie_build_fils_ip_addr_request(&fils_ip_req, hs->fils_ip_req_ie); + } + return hs; not_supported: @@ -2456,14 +2468,44 @@ static void station_connect_ok(struct station *station) network_connected(station->connected_network); - if (station->netconfig) - netconfig_configure(station->netconfig, - network_get_settings( - station->connected_network), - netdev_get_address(station->netdev), - station_netconfig_event_handler, - station); - else + if (station->netconfig) { + if (hs->fils_ip_req_ie && hs->fils_ip_resp_ie) { + struct ie_fils_ip_addr_response_info info; + struct ie_tlv_iter iter; + int r; + + ie_tlv_iter_init(&iter, hs->fils_ip_resp_ie, + hs->fils_ip_resp_ie[1] + 2); + if (!L_WARN_ON(unlikely(!ie_tlv_iter_next(&iter)))) + r = ie_parse_fils_ip_addr_response(&iter, + &info); + else + r = -ENOMSG; + + if (r != 0) + l_debug("Error parsing the FILS IP Address " + "Assignment response: %s (%i)", + strerror(-r), -r); + else if (info.response_pending && + info.response_timeout) + l_debug("FILS IP Address Assignment response " + "is pending (unsupported)"); + else if (info.response_pending) + l_debug("FILS IP Address Assignment failed"); + else { + l_debug("FILS IP Address Assignment response " + "OK"); + netconfig_handle_fils_ip_resp( + station->netconfig, + &info); + } + } + + if (L_WARN_ON(!netconfig_configure(station->netconfig, + station_netconfig_event_handler, + station))) + return; + } else station_enter_state(station, STATION_STATE_CONNECTED); } @@ -2605,6 +2647,12 @@ int __station_connect_network(struct station *station, struct network *network, struct handshake_state *hs; int r; + if (station->netconfig && !netconfig_load_settings( + station->netconfig, + network_get_settings(network), + netdev_get_address(station->netdev))) + return -EINVAL; + hs = station_handshake_setup(station, network, bss); if (!hs) return -ENOTSUP; @@ -3969,6 +4017,9 @@ static struct l_dbus_message *station_debug_scan(struct l_dbus *dbus, freq_set = scan_freq_set_new(); for (i = 0; i < freqs_len; i++) { + if (scan_freq_set_contains(freq_set, (uint32_t)freqs[i])) + continue; + if (!scan_freq_set_add(freq_set, (uint32_t)freqs[i])) { scan_freq_set_free(freq_set); goto invalid_args; diff --git a/src/util.h b/src/util.h @@ -82,9 +82,23 @@ static inline uint32_t util_secure_fill_with_msb(uint32_t val) bool util_ip_prefix_tohl(const char *ip, uint8_t *prefix, uint32_t *start_out, uint32_t *end_out, uint32_t *mask_out); +/* Host byte-order IPv4 netmask */ static inline uint32_t util_netmask_from_prefix(uint8_t prefix_len) { return ~((1ull << (32 - prefix_len)) - 1); } +/* Expects network byte-order (big-endian) addresses */ +static inline bool util_ip_subnet_match(uint8_t prefix_len, + const void *addr1, const void *addr2) +{ + const uint8_t *u8_1 = addr1; + const uint8_t *u8_2 = addr2; + uint8_t pref_bytes = prefix_len / 8; + + return (!pref_bytes || !memcmp(u8_1, u8_2, pref_bytes)) && + !((u8_1[pref_bytes] ^ u8_2[pref_bytes]) & + ~((1u << (8 - (prefix_len % 8))) - 1)); +} + #endif /* __UTIL_H */ diff --git a/src/wsc.c b/src/wsc.c @@ -356,6 +356,7 @@ static int wsc_enrollee_connect(struct wsc_enrollee *wsce, struct scan_bss *bss, handshake_state_set_event_func(hs, wsc_enrollee_handshake_event, wsce); handshake_state_set_8021x_config(hs, settings); + handshake_state_set_ssid(hs, bss->ssid, bss->ssid_len); wsce->eap_settings = settings; request.version2 = true; diff --git a/tools/hwsim.c b/tools/hwsim.c @@ -124,6 +124,7 @@ struct hwsim_rule { bool destination_any : 1; bool bidirectional : 1; bool drop : 1; + bool drop_ack : 1; bool enabled : 1; uint32_t frequency; int priority; @@ -131,6 +132,10 @@ struct hwsim_rule { int delay; uint8_t *prefix; size_t prefix_len; + uint8_t *match; + size_t match_len; + uint16_t match_offset; + int match_times; /* negative value indicates unused */ }; struct hwsim_support { @@ -1169,7 +1174,7 @@ static bool radio_match_addr(const struct radio_info_rec *radio, static void process_rules(const struct radio_info_rec *src_radio, const struct radio_info_rec *dst_radio, - struct hwsim_frame *frame, bool *drop, + struct hwsim_frame *frame, bool ack, bool *drop, uint32_t *delay) { const struct l_queue_entry *rule_entry; @@ -1216,15 +1221,30 @@ static void process_rules(const struct radio_info_rec *src_radio, continue; } + if (rule->match && frame->payload_len >= + rule->match_len + rule->match_offset) { + if (memcmp(rule->match, + frame->payload + rule->match_offset, + rule->match_len)) + continue; + } + /* Rule deemed to match frame, apply any changes */ + if (rule->match_times == 0) + continue; if (rule->signal) frame->signal = rule->signal / 100; - *drop = rule->drop; + /* Don't drop if this is an ACK, unless drop_ack is set */ + if (!ack || (ack && rule->drop_ack)) + *drop = rule->drop; if (delay) *delay = rule->delay; + + if (rule->match_times > 0) + rule->match_times--; } } @@ -1308,7 +1328,7 @@ static void hwsim_frame_unref(struct hwsim_frame *frame) bool drop = false; process_rules(frame->ack_radio, frame->src_radio, - frame, &drop, NULL); + frame, true, &drop, NULL); if (!drop) frame->flags |= HWSIM_TX_STAT_ACK; @@ -1452,7 +1472,8 @@ static void process_frame(struct hwsim_frame *frame) bool drop_mcast = false; if (util_is_broadcast_address(frame->dst_ether_addr)) - process_rules(frame->src_radio, NULL, frame, &drop_mcast, NULL); + process_rules(frame->src_radio, NULL, frame, false, + &drop_mcast, NULL); for (entry = l_queue_get_entries(radio_info); entry; entry = entry->next) { @@ -1492,7 +1513,8 @@ static void process_frame(struct hwsim_frame *frame) continue; } - process_rules(frame->src_radio, radio, frame, &drop, &delay); + process_rules(frame->src_radio, radio, frame, false, + &drop, &delay); if (drop) continue; @@ -2008,6 +2030,8 @@ static struct l_dbus_message *rule_add(struct l_dbus *dbus, rule->destination_any = true; rule->delay = 0; rule->enabled = false; + rule->match_times = -1; + rule->drop_ack = true; if (!rules) rules = l_queue_new(); @@ -2050,6 +2074,9 @@ static struct l_dbus_message *rule_remove(struct l_dbus *dbus, if (rule->prefix) l_free(rule->prefix); + if (rule->match) + l_free(rule->match); + l_free(rule); l_dbus_unregister_object(dbus, path); @@ -2381,6 +2408,90 @@ invalid_args: return dbus_error_invalid_args(message); } +static bool rule_property_get_match(struct l_dbus *dbus, + struct l_dbus_message *message, + struct l_dbus_message_builder *builder, + void *user_data) +{ + struct hwsim_rule *rule = user_data; + size_t i; + + l_dbus_message_builder_enter_array(builder, "y"); + + for (i = 0; i < rule->match_len; i++) + l_dbus_message_builder_append_basic(builder, 'y', + rule->match + i); + + l_dbus_message_builder_leave_array(builder); + + return true; +} + +static struct l_dbus_message *rule_property_set_match( + struct l_dbus *dbus, + struct l_dbus_message *message, + struct l_dbus_message_iter *new_value, + l_dbus_property_complete_cb_t complete, + void *user_data) +{ + struct hwsim_rule *rule = user_data; + struct l_dbus_message_iter iter; + const uint8_t *match; + uint32_t len; + + if (!l_dbus_message_iter_get_variant(new_value, "ay", &iter)) + goto invalid_args; + + if (!l_dbus_message_iter_get_fixed_array(&iter, + (const void **)&match, &len)) + goto invalid_args; + + if (len > HWSIM_MAX_PREFIX_LEN) + goto invalid_args; + + if (rule->match) + l_free(rule->match); + + rule->match = l_memdup(match, len); + rule->match_len = len; + + return l_dbus_message_new_method_return(message); + +invalid_args: + return dbus_error_invalid_args(message); +} + +static bool rule_property_get_match_offset(struct l_dbus *dbus, + struct l_dbus_message *message, + struct l_dbus_message_builder *builder, + void *user_data) +{ + struct hwsim_rule *rule = user_data; + uint16_t val = rule->match_offset; + + l_dbus_message_builder_append_basic(builder, 'q', &val); + + return true; +} + +static struct l_dbus_message *rule_property_set_match_offset( + struct l_dbus *dbus, + struct l_dbus_message *message, + struct l_dbus_message_iter *new_value, + l_dbus_property_complete_cb_t complete, + void *user_data) +{ + struct hwsim_rule *rule = user_data; + uint16_t val; + + if (!l_dbus_message_iter_get_variant(new_value, "q", &val)) + return dbus_error_invalid_args(message); + + rule->match_offset = val; + + return l_dbus_message_new_method_return(message); +} + static bool rule_property_get_enabled(struct l_dbus *dbus, struct l_dbus_message *message, struct l_dbus_message_builder *builder, @@ -2412,6 +2523,68 @@ static struct l_dbus_message *rule_property_set_enabled( return l_dbus_message_new_method_return(message); } +static bool rule_property_get_match_times(struct l_dbus *dbus, + struct l_dbus_message *message, + struct l_dbus_message_builder *builder, + void *user_data) +{ + struct hwsim_rule *rule = user_data; + uint16_t val = rule->match_times; + + l_dbus_message_builder_append_basic(builder, 'q', &val); + + return true; +} + +static struct l_dbus_message *rule_property_set_match_times( + struct l_dbus *dbus, + struct l_dbus_message *message, + struct l_dbus_message_iter *new_value, + l_dbus_property_complete_cb_t complete, + void *user_data) +{ + struct hwsim_rule *rule = user_data; + uint16_t val; + + if (!l_dbus_message_iter_get_variant(new_value, "q", &val)) + return dbus_error_invalid_args(message); + + rule->match_times = val; + + return l_dbus_message_new_method_return(message); +} + +static bool rule_property_get_drop_ack(struct l_dbus *dbus, + struct l_dbus_message *message, + struct l_dbus_message_builder *builder, + void *user_data) +{ + struct hwsim_rule *rule = user_data; + bool bval = rule->drop_ack; + + l_dbus_message_builder_append_basic(builder, 'b', &bval); + + return true; +} + +static struct l_dbus_message *rule_property_set_drop_ack( + struct l_dbus *dbus, + struct l_dbus_message *message, + struct l_dbus_message_iter *new_value, + l_dbus_property_complete_cb_t complete, + void *user_data) +{ + struct hwsim_rule *rule = user_data; + bool bval; + + if (!l_dbus_message_iter_get_variant(new_value, "b", &bval)) + return dbus_error_invalid_args(message); + + rule->drop_ack = bval; + + return l_dbus_message_new_method_return(message); +} + static void setup_rule_interface(struct l_dbus_interface *interface) { l_dbus_interface_method(interface, "Remove", 0, rule_remove, "", ""); @@ -2452,10 +2625,26 @@ static void setup_rule_interface(struct l_dbus_interface *interface) L_DBUS_PROPERTY_FLAG_AUTO_EMIT, "ay", rule_property_get_prefix, rule_property_set_prefix); + l_dbus_interface_property(interface, "MatchBytes", + L_DBUS_PROPERTY_FLAG_AUTO_EMIT, "ay", + rule_property_get_match, + rule_property_set_match); + l_dbus_interface_property(interface, "MatchBytesOffset", + L_DBUS_PROPERTY_FLAG_AUTO_EMIT, "q", + rule_property_get_match_offset, + rule_property_set_match_offset); l_dbus_interface_property(interface, "Enabled", L_DBUS_PROPERTY_FLAG_AUTO_EMIT, "b", rule_property_get_enabled, rule_property_set_enabled); + l_dbus_interface_property(interface, "MatchTimes", + L_DBUS_PROPERTY_FLAG_AUTO_EMIT, "q", + rule_property_get_match_times, + rule_property_set_match_times); + l_dbus_interface_property(interface, "DropAck", + L_DBUS_PROPERTY_FLAG_AUTO_EMIT, "b", + rule_property_get_drop_ack, + rule_property_set_drop_ack); } static void request_name_callback(struct l_dbus *dbus, bool success, diff --git a/tools/test-runner b/tools/test-runner @@ -27,6 +27,7 @@ from collections import namedtuple from time import sleep import dbus.mainloop.glib from gi.repository import GLib +from weakref import WeakValueDictionary libc = ctypes.cdll['libc.so.6'] libc.mount.argtypes = (ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, \ @@ -56,12 +57,9 @@ def dbg(*s, **kwargs): def exit_vm(): if config: - for p in config.ctx.processes: - print("Process %s still running!" % p.name) + for p in Process.get_all(): + print("Process %s still running!" % p.args[0]) p.kill() - p = None - - config.ctx.processes = [] if config.ctx and config.ctx.results: print_results(config.ctx.results) @@ -159,102 +157,103 @@ busconfig.dtd\"> <allow eavesdrop=\"true\"/> </policy> ''' -class Process: - ''' - Start a process. If 'wait' is True the constructor will start - the process and wait for it to exit. No PID is tracked in this - case. - ''' - def __init__(self, args, wait=False, env=None, ctx=None, check=False, - outfile=None, namespace=None, need_out=False, cleanup=None): - self.killed = False - self.args = args - self.wait = wait - self.name = args[0] - self.ret = None - self.ctx = ctx + +class Process(subprocess.Popen): + processes = WeakValueDictionary() + ctx = None + + def __new__(cls, *args, **kwargs): + obj = super().__new__(cls) + cls.processes[id(obj)] = obj + return obj + + def __init__(self, args, namespace=None, outfile=None, env=None, check=False, cleanup=None): self.write_fds = [] self.io_watch = None self.cleanup = cleanup self.verbose = False self.out = '' + self.hup = False + self.killed = False + self.namespace = namespace + + if not self.ctx: + global config + self.ctx = config.ctx + + if self.ctx.is_verbose(args[0], log=False): + self.verbose = True if namespace: - self.args = ['ip', 'netns', 'exec', namespace] - self.args.extend(args) - - if ctx: - # Verbose requested, add stdout/stderr to write FD list. - # This will end up always returning true if logging is - # on which isn't desired so pass log=False as to only - # allow stdout to processes listed in --verbose. - if ctx.is_verbose(self.name, log=False): - self.verbose = True - - # Add output file to FD list - if outfile: - try: - f = open(outfile, 'w') - except Exception as e: - dbg(e) - exit(0) + args = ['ip', 'netns', 'exec', namespace] + args - if ctx.args.log_uid: - os.fchown(f.fileno(), int(ctx.args.log_uid), int(ctx.args.log_gid)) + if outfile: + # outfile is only used by iwmon, in which case we don't want + # to append to an existing file. + self._append_outfile(outfile, append=False) - self.write_fds.append(f) + if self.ctx.args.log: + logfile = '%s/%s/%s' % (self.ctx.args.log, + os.path.basename(os.getcwd()), + args[0]) + self._append_outfile(logfile) - # Add log file to FD list - if ctx.args.log: - test = os.path.basename(os.getcwd()) - test_dir = '%s/%s' % (ctx.args.log, test) + super().__init__(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + env=env, cwd=os.getcwd()) - if not path_exists(test_dir): - os.mkdir(test_dir) - os.chown(test_dir, int(ctx.args.log_uid), - int(ctx.args.log_gid)) + # Set as non-blocking so read() in the IO callback doesn't block forever + fl = fcntl.fcntl(self.stdout, fcntl.F_GETFL) + fcntl.fcntl(self.stdout, fcntl.F_SETFL, fl | os.O_NONBLOCK) - f = open('%s/%s' % (test_dir, args[0]), 'a+') - os.fchown(f.fileno(), int(ctx.args.log_uid), int(ctx.args.log_gid)) - self.write_fds.append(f) + self.io_watch = GLib.io_add_watch(self.stdout, GLib.IO_IN | + GLib.IO_HUP | GLib.IO_ERR, self.process_io) - self.pid = subprocess.Popen(self.args, stdout=subprocess.PIPE, - stderr=subprocess.STDOUT, - env=env, cwd=os.getcwd()) + print("Starting process {}".format(self.args)) - # Set as non-blocking so read() in the IO callback doesn't block forever - fl = fcntl.fcntl(self.pid.stdout, fcntl.F_GETFL) - fcntl.fcntl(self.pid.stdout, fcntl.F_SETFL, fl | os.O_NONBLOCK) + if check: + self.wait(10) + self.killed = True + if self.returncode != 0: + raise subprocess.CalledProcessError(returncode=self.returncode, + cmd=args) - if not wait and not check: - self.io_watch = GLib.io_add_watch(self.pid.stdout, GLib.IO_IN | - GLib.IO_HUP | GLib.IO_ERR, self.io_callback) + @classmethod + def get_all(cls): + return cls.processes.values() - print("Starting process {}".format(self.pid.args)) + @classmethod + def kill_all(cls): + for p in cls.processes.values(): + p.kill() - if not wait and not check: - return + @staticmethod + def _write_io(instance, data, stdout=True): + for f in instance.write_fds: + f.write(data) - Namespace.non_block_wait(self.wait_for_process, 10, 1) - self.killed = True - self.ret = self.pid.returncode + # Write out a separator so multiple process calls per + # test are easer to read. + if instance.hup: + f.write("Terminated: {}\n\n".format(instance.args)) - self.process_io(self.pid.stdout) + f.flush() - self.write_fds = [] + if instance.verbose and stdout: + sys.__stdout__.write(data) + sys.__stdout__.flush() - print("%s returned %d" % (args[0], self.ret)) - if check and self.ret != 0: - raise subprocess.CalledProcessError(returncode=self.ret, cmd=self.args) + @classmethod + def write_separators(cls, sep): + for proc in cls.processes.values(): + if proc.killed: + continue - def wait_for_process(self, timeout): - try: - self.pid.wait(timeout) - return True - except: - return False + cls._write_io(proc, sep, stdout=False) + + def process_io(self, source, condition): + if condition & GLib.IO_HUP: + self.hup = True - def process_io(self, source): data = source.read() if not data: @@ -265,52 +264,61 @@ class Process: # Save data away in case the caller needs it (e.g. list_sta) self.out += data - for f in self.write_fds: - f.write(data) - f.flush() - - if self.verbose: - sys.__stdout__.write(data) - sys.__stdout__.flush() + self._write_io(self, data) return True - def io_callback(self, source, cb_condition): - return self.process_io(source) + def _append_outfile(self, file, append=True): + gid = int(self.ctx.args.log_gid) + uid = int(self.ctx.args.log_uid) + dir = os.path.dirname(file) - def __del__(self): - print("Del process %s" % self.args) + if not path_exists(dir): + os.mkdir(dir) + os.chown(dir, uid, gid) - if not self.killed: - self.kill() + file = os.path.join(dir,file) - def kill(self, force=False): - print("Killing process %s" % self.args) + # If the out file exists, append. Useful for processes like + # hostapd_cli where it is called multiple times independently. + if os.path.isfile(file) and append: + mode = 'a' + else: + mode = 'w' - if self.killed: - return + try: + f = open(os.path.join(dir, file), mode) + except Exception as e: + traceback.print_exc() + exit(0) - if force: - self.pid.kill() - else: - self.pid.terminate() + os.fchown(f.fileno(), uid, gid) + + self.write_fds.append(f) + + def wait_for_socket(self, socket, wait): + Namespace.non_block_wait(os.path.exists, wait, socket) + # Wait for both process termination and HUP signal + def __wait(self, timeout): try: - self.pid.wait(timeout=15) + super().wait(timeout) + if not self.hup: + return False + + return True except: - dbg("Process %s did not complete in 15 seconds!" % self.name) - self.pid.kill() + return False - if self.ctx and self in self.ctx.processes: - self.ctx.processes.remove(self) + # Override wait() so it can do so non-blocking + def wait(self, timeout=10): + Namespace.non_block_wait(self.__wait, timeout, 1) + self._cleanup() + def _cleanup(self): if self.cleanup: self.cleanup() - self.process_io(self.pid.stdout) - - self.ctx = None - self.pid = None self.write_fds = [] if self.io_watch: @@ -320,8 +328,25 @@ class Process: self.cleanup = None self.killed = True - def wait_for_socket(self, socket, wait): - Namespace.non_block_wait(os.path.exists, wait, socket) + # Override kill() + def kill(self, force=False): + if self.killed: + return + + print("Killing process {}".format(self.args)) + + if force: + super().kill() + else: + self.terminate() + + try: + self.wait(timeout=15) + except: + dbg("Process %s did not complete in 15 seconds!" % self.name) + super().kill() + + self._cleanup() def __str__(self): return str(self.args) + '\n' @@ -333,10 +358,10 @@ class Interface: self.config = config def __del__(self): - Process(['iw', 'dev', self.name, 'del'], True) + Process(['iw', 'dev', self.name, 'del']).wait() def set_interface_state(self, state): - Process(['ifconfig', self.name, state], True) + Process(['ifconfig', self.name, state]).wait() class Radio: def __init__(self, name): @@ -360,7 +385,7 @@ class Radio: self.use = use Process(['iw', 'phy', self.name, 'interface', 'add', ifname, - 'type', 'managed'], True) + 'type', 'managed']).wait() return self.interface @@ -381,17 +406,20 @@ class VirtualRadio(Radio): TODO: Using D-Bus to create and destroy radios is more desireable than the command line. ''' - def __init__(self, name, config=None): + + def __init__(self, name, cfg=None): + global config + self.disable_cipher = None self.disable_iftype = None - hwsim = importlib.import_module('hwsim').Hwsim() + self.hwsim = config.hwsim.Hwsim() - if config: - self.disable_iftype = config.get('iftype_disable', None) - self.disable_cipher = config.get('cipher_disable', None) + if cfg: + self.disable_iftype = cfg.get('iftype_disable', None) + self.disable_cipher = cfg.get('cipher_disable', None) - self._radio = hwsim.radios.create(name, p2p_device=True, + self._radio = self.hwsim.radios.create(name, p2p_device=True, iftype_disable=self.disable_iftype, cipher_disable=self.disable_cipher) @@ -463,8 +491,8 @@ class Hostapd: print("Initializing hostapd instances") - ctx.start_process(['ip', 'link', 'set', 'eth0', 'up'], wait=True) - ctx.start_process(['ip', 'link', 'set', 'eth1', 'up'], wait=True) + Process(['ip', 'link', 'set', 'eth0', 'up']).wait() + Process(['ip', 'link', 'set', 'eth1', 'up']).wait() self.global_ctrl_iface = '/var/run/hostapd/ctrl' @@ -495,7 +523,7 @@ class Hostapd: if ctx.is_verbose('hostapd'): args.append('-d') - self.process = ctx.start_process(args) + self.process = Process(args) self.process.wait_for_socket(self.global_ctrl_iface, 30) @@ -503,8 +531,10 @@ class Hostapd: self.process.wait_for_socket(hapd.intf.ctrl_interface, 30) def attach_cli(self): + global config + for hapd in self.instances: - hapd.cli = importlib.import_module('hostapd').HostapdCLI(config=hapd.config) + hapd.cli = config.hostapd.HostapdCLI(config=hapd.config) def _rewrite_config(self, config): ''' @@ -545,13 +575,6 @@ class Hostapd: except: print("Failed to remove %s" % self.global_ctrl_iface) - for hapd in self.instances: - if not hapd.cli: - continue - - hapd.cli._instances[hapd.config] = None - hapd.cli = None - self.instances = None # Hostapd may have already been stopped @@ -570,14 +593,13 @@ dbus_count = 0 class Namespace: def __init__(self, args, name, radios): self.dbus_address = None - self.processes = [] self.name = name self.radios = radios self.args = args - Process(['ip', 'netns', 'add', name], wait=True) + Process(['ip', 'netns', 'add', name]).wait() for r in radios: - Process(['iw', 'phy', r.name, 'set', 'netns', 'name', name], wait=True) + Process(['iw', 'phy', r.name, 'set', 'netns', 'name', name]).wait() self.start_dbus() @@ -589,27 +611,17 @@ class Namespace: self.radios = [] - for p in list(self.processes): - print("Killing process %s" % p.name) - p.kill() - - self.processes = [] + Process.kill_all() def __del__(self): print("Removing namespace %s" % self.name) - Process(['ip', 'netns', 'del', self.name], wait=True) + Process(['ip', 'netns', 'del', self.name]).wait() def get_bus(self): return self._bus def start_process(self, args, env=None, **kwargs): - # Special case for 'root' namespace (aka TestContext) - if self.name == "root": - ns = None - else: - ns = self.name - if not env: env = os.environ.copy() @@ -617,19 +629,14 @@ class Namespace: # In case this process needs DBus... env['DBUS_SYSTEM_BUS_ADDRESS'] = self.dbus_address - p = Process(args, ctx=self, namespace=ns, env=env, **kwargs) - - if not kwargs.get('wait', False): - self.processes.append(p) - - return p + return Process(args, namespace=self.name, env=env, **kwargs) def stop_process(self, p, force=False): p.kill(force) def is_process_running(self, process): - for p in self.processes: - if p.name == process: + for p in Process.get_all(): + if p.namespace == self.name and p.args[0] == process: return True return False @@ -654,7 +661,7 @@ class Namespace: f.write('</busconfig>\n') p = self.start_process(['dbus-daemon', '--config-file=%s' % self.dbus_cfg], - wait=False, cleanup=self._cleanup_dbus) + cleanup=self._cleanup_dbus) p.wait_for_socket(self.dbus_address.split('=')[1], 5) @@ -687,8 +694,7 @@ class Namespace: if self.is_verbose('iwd-acd'): env['IWD_ACD_DEBUG'] = '1' - pid = self.start_process(args, env=env) - return pid + return self.start_process(args, env=env) def is_verbose(self, process, log=True): process = os.path.basename(process) @@ -775,7 +781,7 @@ class Namespace: def __str__(self): ret = 'Namespace: %s\n' % self.name ret += 'Processes:\n' - for p in self.processes: + for p in Process.get_all(): ret += '\t%s' % str(p) ret += 'Radios:\n' @@ -796,8 +802,7 @@ class TestContext(Namespace): such as processes, radios, interfaces and test results. ''' def __init__(self, args): - self.name = "root" - self.processes = [] + self.name = None self.args = args self.hw_config = None self.hostapd = None @@ -865,7 +870,7 @@ class TestContext(Namespace): def start_radios(self): reg_domain = self.hw_config['SETUP'].get('reg_domain', None) if reg_domain: - Process(['iw', 'reg', 'set', reg_domain], True) + Process(['iw', 'reg', 'set', reg_domain]).wait() if self.args.hw: self.discover_radios() @@ -942,7 +947,7 @@ class TestContext(Namespace): print("Ofono or Phonesim not found, skipping test") return - Process(['ifconfig', 'lo', 'up'], wait=True) + Process(['ifconfig', 'lo', 'up']).wait() os.environ['OFONO_PHONESIM_CONFIG'] = '/tmp/phonesim.conf' @@ -1187,6 +1192,8 @@ def start_test(ctx, subtests, rqueue): sys.__stdout__.flush() + Process.write_separators("\n====== %s:%s ======\n\n" % (file, func)) + if not skip: # Run test (setUp/tearDown run automatically) result = t() @@ -1327,7 +1334,7 @@ def post_test(ctx, to_copy): else: os.remove('/tmp/' + f) - Process(['ifconfig', 'lo', 'down'], wait=True) + Process(['ifconfig', 'lo', 'down']).wait() except Exception as e: print("Exception thrown in post_test") finally: @@ -1451,7 +1458,8 @@ def run_unit_tests(ctx, args): units = build_unit_list(args) for u in units: - if ctx.start_process([u], wait=True).ret != 0: + p = ctx.start_process([u]).wait() + if p.returncode != 0: dbg("Unit test %s failed" % os.path.basename(u)) else: dbg("Unit test %s passed" % os.path.basename(u)) @@ -1513,6 +1521,10 @@ def run_tests(): config = importlib.import_module('config') config.ctx = TestContext(args) + # Must import these after config so ctx gets set + config.hwsim = importlib.import_module('hwsim') + config.hostapd = importlib.import_module('hostapd') + if args.log: mount('logdir', args.log, '9p', 0, 'trans=virtio,version=9p2000.L,msize=10240') # Clear out any log files from other test runs @@ -1710,6 +1722,9 @@ class Main: self.args.monitor = os.path.abspath(self.args.monitor) mon_parent_dir = os.path.abspath(os.path.join(self.args.monitor, os.pardir)) + options += ' --log-gid %u' % int(os.environ['SUDO_GID']) + options += ' --log-uid %u' % int(os.environ['SUDO_UID']) + denylist = [ 'auto_tests', 'sub_tests', diff --git a/unit/test-eapol.c b/unit/test-eapol.c @@ -3802,9 +3802,9 @@ static void eapol_ap_sta_handshake_ip_alloc_ok_test(const void *data) handshake_state_set_ssid(s.ap_hs, (void *) ssid, strlen(ssid)); handshake_state_set_pmk(s.ap_hs, psk, 32); s.ap_hs->support_ip_allocation = true; - s.ap_hs->client_ip_addr = 0x01020304; - s.ap_hs->subnet_mask = 0xffff0000; - s.ap_hs->go_ip_addr = 0x01020305; + s.ap_hs->client_ip_addr = L_CPU_TO_BE32(0x01020304); + s.ap_hs->subnet_mask = L_CPU_TO_BE32(0xffff0000); + s.ap_hs->go_ip_addr = L_CPU_TO_BE32(0x01020305); handshake_state_set_authenticator(s.sta_hs, false); handshake_state_set_event_func(s.sta_hs, test_ap_sta_hs_event, &s);