connection_test.py (15056B)
1 #!/usr/bin/python3 2 3 import unittest 4 import sys 5 6 sys.path.append('../util') 7 import iwd 8 from iwd import IWD 9 from iwd import PSKAgent 10 from iwd import NetworkType 11 from hostapd import HostapdCLI 12 import testutil 13 from config import ctx 14 import os 15 import socket 16 import datetime, time 17 18 class Test(unittest.TestCase): 19 20 def test_connection_success(self): 21 def check_addr(device): 22 try: 23 # DHCPv6 addresses always have a prefix length of 128 bits, the actual 24 # subnet's prefix length is in the route. 25 testutil.test_ip_address_match(device.name, '3ffe:501:ffff:100::1', 128, 112) 26 except: 27 return False 28 29 return True 30 31 def get_ll_addrs6(ns, ifname): 32 show_ip = ns.start_process(['ip', 'addr', 'show', ifname]) 33 show_ip.wait() 34 for l in show_ip.out.split('\n'): 35 if 'inet6 fe80::' in l: 36 return socket.inet_pton(socket.AF_INET6, l.split(None, 1)[1].split('/', 1)[0]) 37 return None 38 39 os.system("hostname test-sta") 40 IWD.copy_to_storage('auto.psk', name='ap-ns1.psk') 41 wd = IWD(True) 42 43 psk_agent = PSKAgent("secret123") 44 wd.register_psk_agent(psk_agent) 45 46 devices = wd.list_devices(1) 47 device = devices[0] 48 49 ordered_network = device.get_ordered_network('ap-ns1') 50 51 self.assertEqual(ordered_network.type, NetworkType.psk) 52 53 condition = 'not obj.connected' 54 wd.wait_for_object_condition(ordered_network.network_object, condition) 55 56 ordered_network.network_object.connect() 57 58 condition = 'obj.state == DeviceState.connected' 59 wd.wait_for_object_condition(device, condition) 60 connect_time = time.time() 61 62 testutil.test_iface_operstate() 63 64 testutil.test_ip_address_match(device.name, '192.168.1.10', 17, 24) 65 ctx.non_block_wait(check_addr, 10, device, 66 exception=Exception("IPv6 address was not set")) 67 68 # Cannot use test_ifaces_connected() across namespaces (implementation details) 69 testutil.test_ip_connected(('192.168.1.10', ctx), ('192.168.1.1', self.ns1)) 70 71 ifname = str(device.name) 72 router_ll_addr = get_ll_addrs6(self.ns1, self.hapd.ifname) 73 # Since we're in an isolated VM with freshly created interfaces we know any routes 74 # will have been created by IWD and we don't have to allow for pre-existing routes 75 # in the table. 76 # Flags: 1=RTF_UP, 2=RTF_GATEWAY 77 expected_routes4 = { 78 testutil.RouteInfo(gw=socket.inet_pton(socket.AF_INET, '192.168.1.1'), 79 flags=3, ifname=ifname), 80 testutil.RouteInfo(dst=socket.inet_pton(socket.AF_INET, '192.168.0.0'), plen=17, 81 flags=1, ifname=ifname) 82 } 83 expected_routes6 = { 84 # Default router 85 testutil.RouteInfo(gw=router_ll_addr, flags=3, ifname=ifname), 86 # On-link prefix 87 testutil.RouteInfo(dst=socket.inet_pton(socket.AF_INET6, '3ffe:501:ffff:100::'), plen=72, 88 flags=1, ifname=ifname), 89 # Router for an off-link prefix, medium preference 90 testutil.RouteInfo(dst=socket.inet_pton(socket.AF_INET6, '3ffe:501:ffff:300::'), plen=64, 91 gw=router_ll_addr, flags=3, ifname=ifname), 92 # Router for an off-link prefix, high preference 93 testutil.RouteInfo(dst=socket.inet_pton(socket.AF_INET6, '3ffe:501:ffff:400::'), plen=65, 94 gw=router_ll_addr, flags=3, ifname=ifname), 95 # Router for an off-link prefix, low preference 96 testutil.RouteInfo(dst=socket.inet_pton(socket.AF_INET6, '3ffe:501:ffff:500::'), plen=66, 97 gw=router_ll_addr, flags=3, ifname=ifname) 98 } 99 self.maxDiff = None 100 self.assertEqual(expected_routes4, set(testutil.get_routes4(ifname))) 101 self.assertEqual(expected_routes6, set(testutil.get_routes6(ifname))) 102 103 rclog = open('/tmp/resolvconf.log', 'r') 104 entries = rclog.readlines() 105 rclog.close() 106 expected_rclog = ['-a %s.dns\n' % ifname, 'nameserver 192.168.1.2\n', 'nameserver 3ffe:501:ffff:100::2\n'] 107 # Every real resolvconf -a run overwrites the previous settings. Check the last three lines 108 # of our log since we care about the end result here. 109 self.assertEqual(expected_rclog, entries[-3:]) 110 111 leases_file = self.parse_lease_file('/tmp/dhcpd.leases', socket.AF_INET) 112 lease = leases_file['leases'][socket.inet_pton(socket.AF_INET, '192.168.1.10')] 113 self.assertEqual(lease['state'], 'active') 114 self.assertEqual(lease['client-hostname'], 'test-sta') 115 self.assertTrue(lease['starts'] < connect_time) 116 self.assertTrue(lease['ends'] > connect_time) 117 # The T1 is 15 seconds per dhcpd.conf. This is the approximate interval between lease 118 # renewals we should see from the client (+/- 1 second + some jitter). Wait a little 119 # less than twice that time (25s) so that we can expect the lease was renewed strictly 120 # once (not 0 or 2 times) by that time, check that the lease timestamps have changed by 121 # at least 10s so as to leave a lot of margin. 122 renew_time = lease['starts'] + 15 123 now = time.time() 124 ctx.non_block_wait(lambda: False, renew_time + 10 - now, exception=False) 125 126 leases_file = self.parse_lease_file('/tmp/dhcpd.leases', socket.AF_INET) 127 new_lease = leases_file['leases'][socket.inet_pton(socket.AF_INET, '192.168.1.10')] 128 self.assertEqual(new_lease['state'], 'active') 129 self.assertEqual(new_lease['client-hostname'], 'test-sta') 130 self.assertTrue(new_lease['starts'] > lease['starts'] + 10) 131 self.assertTrue(new_lease['starts'] < lease['starts'] + 25) 132 self.assertTrue(new_lease['ends'] > lease['ends'] + 10) 133 self.assertTrue(new_lease['ends'] < lease['ends'] + 25) 134 135 # Now wait another T1 seconds but don't let our DHCP client get its REQUEST out this 136 # time so as to test renew timeouts and resends. The retry interval is 60 seconds 137 # since (T2 - T1) / 2 is shorter than 60s. It is now about 10s since the last 138 # renewal or 5s before the next DHCPREQUEST frame that is going to be lost. We'll 139 # wait T1 seconds, so until about 10s after the failed attempt, we'll check that 140 # there was no renewal by that time, just in case, and we'll re-enable frame delivery. 141 # We'll then wait another 60s and we should see the lease has been successfully 142 # renewed some 10 seconds earlier on the 1st DHCPREQUEST retransmission. 143 # 144 # We can't use hswim to block the frames from reaching the AP because we'd lose 145 # beacons and get disconnected. We also can't drop our subnet route or IP address 146 # because IWD's sendto() call would synchronously error out and the DHCP client 147 # would just give up. Add a false route to break routing to 192.168.1.1 and delete 148 # it afterwards. 149 os.system('ip route add 192.168.1.1/32 dev ' + ifname + ' via 192.168.1.100 preference 0') 150 151 lease = new_lease 152 renew_time = lease['starts'] + 15 153 now = time.time() 154 ctx.non_block_wait(lambda: False, renew_time + 10 - now, exception=False) 155 156 leases_file = self.parse_lease_file('/tmp/dhcpd.leases', socket.AF_INET) 157 new_lease = leases_file['leases'][socket.inet_pton(socket.AF_INET, '192.168.1.10')] 158 self.assertEqual(new_lease['starts'], lease['starts']) 159 160 os.system('ip route del 192.168.1.1/32 dev ' + ifname + ' via 192.168.1.100 preference 0') 161 162 retry_time = lease['starts'] + 75 163 now = time.time() 164 ctx.non_block_wait(lambda: False, retry_time + 10 - now, exception=False) 165 166 leases_file = self.parse_lease_file('/tmp/dhcpd.leases', socket.AF_INET) 167 new_lease = leases_file['leases'][socket.inet_pton(socket.AF_INET, '192.168.1.10')] 168 self.assertEqual(new_lease['state'], 'active') 169 self.assertEqual(lease['client-hostname'], 'test-sta') 170 self.assertTrue(new_lease['starts'] > lease['starts'] + 70) 171 self.assertTrue(new_lease['starts'] < lease['starts'] + 85) 172 self.assertTrue(new_lease['ends'] > lease['ends'] + 70) 173 self.assertTrue(new_lease['ends'] < lease['ends'] + 85) 174 175 device.disconnect() 176 177 condition = 'not obj.connected' 178 wd.wait_for_object_condition(ordered_network.network_object, condition) 179 180 wd.unregister_psk_agent(psk_agent) 181 182 @classmethod 183 def setUpClass(cls): 184 def remove_lease4(): 185 try: 186 os.remove('/tmp/dhcpd.leases') 187 os.remove('/tmp/dhcpd.leases~') 188 except: 189 pass 190 def remove_lease6(): 191 try: 192 os.remove('/tmp/dhcpd6.leases') 193 os.remove('/tmp/dhcpd6.leases~') 194 except: 195 pass 196 197 cls.ns1 = ctx.get_namespace('ns1') 198 cls.hapd = HostapdCLI('ap-ns1.conf') 199 # TODO: This could be moved into test-runner itself if other tests ever 200 # require this functionality (p2p, FILS, etc.). Since its simple 201 # enough it can stay here for now. 202 cls.ns1.start_process(['ip', 'addr','add', '192.168.1.1/17', 203 'dev', cls.hapd.ifname]).wait() 204 cls.ns1.start_process(['touch', '/tmp/dhcpd.leases']).wait() 205 cls.dhcpd_pid = cls.ns1.start_process(['dhcpd', '-f', '-d', '-cf', '/tmp/dhcpd.conf', 206 '-lf', '/tmp/dhcpd.leases', 207 cls.hapd.ifname], cleanup=remove_lease4) 208 209 cls.ns1.start_process(['ip', 'addr', 'add', '3ffe:501:ffff:100::1/72', 210 'dev', cls.hapd.ifname]).wait() 211 cls.ns1.start_process(['touch', '/tmp/dhcpd6.leases']).wait() 212 cls.dhcpd6_pid = cls.ns1.start_process(['dhcpd', '-6', '-f', '-d', 213 '-cf', '/tmp/dhcpd-v6.conf', 214 '-lf', '/tmp/dhcpd6.leases', 215 cls.hapd.ifname], cleanup=remove_lease6) 216 cls.ns1.start_process(['sysctl', 217 'net.ipv6.conf.' + cls.hapd.ifname + '.forwarding=1']).wait() 218 # Send out Router Advertisements telling clients to use DHCPv6. 219 # Note trying to send the RAs from the router's global IPv6 address by adding a 220 # "AdvRASrcAddress { 3ffe:501:ffff:100::1; };" line will fail because the client 221 # and the router interfaces are in the same namespace and Linux won't allow routes 222 # with a non-link-local gateway address that is present on another interface in the 223 # same namespace. 224 config = open('/tmp/radvd.conf', 'w') 225 config.write('interface ' + cls.hapd.ifname + ''' { 226 AdvSendAdvert on; 227 AdvManagedFlag on; 228 prefix 3ffe:501:ffff:100::/72 { AdvAutonomous off; }; 229 route 3ffe:501:ffff:300::/64 {}; 230 route 3ffe:501:ffff:400::/65 { AdvRoutePreference low; }; 231 route 3ffe:501:ffff:500::/66 { AdvRoutePreference high; }; 232 };''') 233 config.close() 234 cls.radvd_pid = cls.ns1.start_process(['radvd', '-n', '-d5', 235 '-p', '/tmp/radvd.pid', '-C', '/tmp/radvd.conf']) 236 237 cls.orig_path = os.environ['PATH'] 238 os.environ['PATH'] = '/tmp/test-bin:' + os.environ['PATH'] 239 IWD.copy_to_storage('resolvconf', '/tmp/test-bin') 240 241 @classmethod 242 def tearDownClass(cls): 243 IWD.clear_storage() 244 cls.ns1.stop_process(cls.dhcpd_pid) 245 cls.dhcpd_pid = None 246 cls.ns1.stop_process(cls.dhcpd6_pid) 247 cls.dhcpd6_pid = None 248 cls.ns1.stop_process(cls.radvd_pid) 249 cls.radvd_pid = None 250 os.system('rm -rf /tmp/radvd.conf /tmp/resolvconf.log /tmp/test-bin') 251 os.environ['PATH'] = cls.orig_path 252 253 @staticmethod 254 def parse_lease_file(path, family): 255 file = open(path, 'r') 256 lines = file.readlines() 257 file.close() 258 259 stack = [[]] 260 statement = [] 261 token = '' 262 for line in lines: 263 whitespace = False 264 quote = False 265 for ch in line: 266 if not quote and ch in ' \t\r\n;{}=#': 267 if len(token): 268 statement.append(token) 269 token = '' 270 if not quote and ch in ';{}': 271 if len(statement): 272 stack[-1].append(statement) 273 statement = [] 274 if ch == '"': 275 quote = not quote 276 elif quote or ch not in ' \t\r\n;{}#': 277 token += ch 278 if ch == '#': 279 continue 280 elif ch == '{': 281 stack.append([]) 282 elif ch == '}': 283 statements = stack.pop() 284 stack[-1][-1].append(statements) 285 if len(token): 286 statement.append(token) 287 token = '' 288 if len(statement): 289 stack[-1].append(statement) 290 statements = stack.pop(0) 291 if len(stack): 292 raise Exception('Unclosed block(s)') 293 294 contents = {'leases':{}} 295 for s in statements: 296 if s[0] == 'lease': 297 ip = socket.inet_pton(family, s[1]) 298 lease = {} 299 for param in s[2]: 300 if param[0] in ('starts', 'ends', 'tstp', 'tsfp', 'atsfp', 'cltt'): 301 weekday = param[1] 302 year, month, day = param[2].split('/') 303 hour, minute, second = param[3].split(':') 304 dt = datetime.datetime( 305 int(year), int(month), int(day), 306 int(hour), int(minute), int(second), 307 tzinfo=datetime.timezone.utc) 308 lease[param[0]] = dt.timestamp() 309 elif param[0:2] == ['binding', 'state']: 310 lease['state'] = param[2] 311 elif param[0:2] == ['hardware', 'ethernet']: 312 lease['hwaddr'] = bytes([int(v, 16) for v in param[2].split(':')]) 313 elif param[0] in ('preferred-life', 'max-life'): 314 lease[param[0]] = int(param[1]) 315 elif param[0] in ('client-hostname'): 316 lease[param[0]] = param[1] 317 contents['leases'][ip] = lease # New entries overwrite older ones 318 elif s[0] == 'server-duid': 319 contents[s[0]] = s[1] 320 return contents 321 322 if __name__ == '__main__': 323 unittest.main(exit=True)