1#!/usr/bin/python3 2# 3# Copyright 2014 The Android Open Source Project 4# 5# Licensed under the Apache License, Version 2.0 (the "License"); 6# you may not use this file except in compliance with the License. 7# You may obtain a copy of the License at 8# 9# http://www.apache.org/licenses/LICENSE-2.0 10# 11# Unless required by applicable law or agreed to in writing, software 12# distributed under the License is distributed on an "AS IS" BASIS, 13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14# See the License for the specific language governing permissions and 15# limitations under the License. 16 17import cstruct 18import ctypes 19import errno 20import os 21import random 22from socket import * # pylint: disable=wildcard-import 23import struct 24import time # pylint: disable=unused-import 25import unittest 26 27from scapy import all as scapy 28 29import csocket 30import iproute 31import multinetwork_base 32import net_test 33import netlink 34import packets 35 36# For brevity. 37UDP_PAYLOAD = net_test.UDP_PAYLOAD 38 39IPV6_FLOWINFO = 11 40 41SYNCOOKIES_SYSCTL = "/proc/sys/net/ipv4/tcp_syncookies" 42TCP_MARK_ACCEPT_SYSCTL = "/proc/sys/net/ipv4/tcp_fwmark_accept" 43 44 45class OutgoingTest(multinetwork_base.MultiNetworkBaseTest): 46 47 # How many times to run outgoing packet tests. 48 ITERATIONS = 5 49 50 def CheckPingPacket(self, version, netid, routing_mode, packet): 51 s = self.BuildSocket(version, net_test.PingSocket, netid, routing_mode) 52 53 myaddr = self.MyAddress(version, netid) 54 mysockaddr = self.MySocketAddress(version, netid) 55 s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) 56 s.bind((mysockaddr, packets.PING_IDENT)) 57 net_test.SetSocketTos(s, packets.PING_TOS) 58 59 dstaddr = self.GetRemoteAddress(version) 60 dstsockaddr = self.GetRemoteSocketAddress(version) 61 desc, expected = packets.ICMPEcho(version, myaddr, dstaddr) 62 msg = "IPv%d ping: expected %s on %s" % ( 63 version, desc, self.GetInterfaceName(netid)) 64 65 s.sendto(packet + packets.PING_PAYLOAD, (dstsockaddr, 19321)) 66 67 self.ExpectPacketOn(netid, msg, expected) 68 s.close() 69 70 def CheckTCPSYNPacket(self, version, netid, routing_mode): 71 s = self.BuildSocket(version, net_test.TCPSocket, netid, routing_mode) 72 73 myaddr = self.MyAddress(version, netid) 74 dstaddr = self.GetRemoteAddress(version) 75 dstsockaddr = self.GetRemoteSocketAddress(version) 76 desc, expected = packets.SYN(53, version, myaddr, dstaddr, 77 sport=None, seq=None) 78 79 80 # Non-blocking TCP connects always return EINPROGRESS. 81 self.assertRaisesErrno(errno.EINPROGRESS, s.connect, (dstsockaddr, 53)) 82 msg = "IPv%s TCP connect: expected %s on %s" % ( 83 version, desc, self.GetInterfaceName(netid)) 84 self.ExpectPacketOn(netid, msg, expected) 85 s.close() 86 87 def CheckUDPPacket(self, version, netid, routing_mode): 88 s = self.BuildSocket(version, net_test.UDPSocket, netid, routing_mode) 89 90 myaddr = self.MyAddress(version, netid) 91 dstaddr = self.GetRemoteAddress(version) 92 dstsockaddr = self.GetRemoteSocketAddress(version) 93 94 desc, expected = packets.UDP(version, myaddr, dstaddr, sport=None) 95 msg = "IPv%s UDP %%s: expected %s on %s" % ( 96 version, desc, self.GetInterfaceName(netid)) 97 98 s.sendto(UDP_PAYLOAD, (dstsockaddr, 53)) 99 self.ExpectPacketOn(netid, msg % "sendto", expected) 100 101 # IP_UNICAST_IF doesn't seem to work on connected sockets, so no TCP. 102 if routing_mode != "ucast_oif": 103 s.connect((dstsockaddr, 53)) 104 s.send(UDP_PAYLOAD) 105 self.ExpectPacketOn(netid, msg % "connect/send", expected) 106 107 s.close() 108 109 def CheckRawGrePacket(self, version, netid, routing_mode): 110 s = self.BuildSocket(version, net_test.RawGRESocket, netid, routing_mode) 111 112 inner_version = {4: 6, 6: 4}[version] 113 inner_src = self.MyAddress(inner_version, netid) 114 inner_dst = self.GetRemoteAddress(inner_version) 115 inner = bytes(packets.UDP(inner_version, inner_src, inner_dst, sport=None)[1]) 116 117 ethertype = {4: net_test.ETH_P_IP, 6: net_test.ETH_P_IPV6}[inner_version] 118 # A GRE header can be as simple as two zero bytes and the ethertype. 119 packet = struct.pack("!i", ethertype) + inner 120 myaddr = self.MyAddress(version, netid) 121 dstaddr = self.GetRemoteAddress(version) 122 123 s.sendto(packet, (dstaddr, IPPROTO_GRE)) 124 desc, expected = packets.GRE(version, myaddr, dstaddr, ethertype, inner) 125 msg = "Raw IPv%d GRE with inner IPv%d UDP: expected %s on %s" % ( 126 version, inner_version, desc, self.GetInterfaceName(netid)) 127 self.ExpectPacketOn(netid, msg, expected) 128 s.close() 129 130 def CheckOutgoingPackets(self, routing_mode): 131 for _ in range(self.ITERATIONS): 132 for netid in self.tuns: 133 134 self.CheckPingPacket(4, netid, routing_mode, self.IPV4_PING) 135 # Kernel bug. 136 if routing_mode != "oif": 137 self.CheckPingPacket(6, netid, routing_mode, self.IPV6_PING) 138 139 # IP_UNICAST_IF doesn't seem to work on connected sockets, so no TCP. 140 if routing_mode != "ucast_oif": 141 self.CheckTCPSYNPacket(4, netid, routing_mode) 142 self.CheckTCPSYNPacket(6, netid, routing_mode) 143 self.CheckTCPSYNPacket(5, netid, routing_mode) 144 145 self.CheckUDPPacket(4, netid, routing_mode) 146 self.CheckUDPPacket(6, netid, routing_mode) 147 self.CheckUDPPacket(5, netid, routing_mode) 148 149 # Creating raw sockets on non-root UIDs requires properly setting 150 # capabilities, which is hard to do from Python. 151 # IP_UNICAST_IF is not supported on raw sockets. 152 if routing_mode not in ["uid", "ucast_oif"]: 153 self.CheckRawGrePacket(4, netid, routing_mode) 154 self.CheckRawGrePacket(6, netid, routing_mode) 155 156 def testMarkRouting(self): 157 """Checks that socket marking selects the right outgoing interface.""" 158 self.CheckOutgoingPackets("mark") 159 160 def testUidRouting(self): 161 """Checks that UID routing selects the right outgoing interface.""" 162 self.CheckOutgoingPackets("uid") 163 164 def testOifRouting(self): 165 """Checks that oif routing selects the right outgoing interface.""" 166 self.CheckOutgoingPackets("oif") 167 168 def testUcastOifRouting(self): 169 """Checks that ucast oif routing selects the right outgoing interface.""" 170 self.CheckOutgoingPackets("ucast_oif") 171 172 def CheckRemarking(self, version, use_connect): 173 modes = ["mark", "oif", "uid"] 174 # Setting UNICAST_IF on connected sockets does not work. 175 if not use_connect: 176 modes += ["ucast_oif"] 177 178 for mode in modes: 179 s = net_test.UDPSocket(self.GetProtocolFamily(version)) 180 181 # Figure out what packets to expect. 182 sport = net_test.BindRandomPort(version, s) 183 dstaddr = {4: self.IPV4_ADDR, 6: self.IPV6_ADDR}[version] 184 unspec = {4: "0.0.0.0", 6: "::"}[version] # Placeholder. 185 desc, expected = packets.UDP(version, unspec, dstaddr, sport) 186 187 # If we're testing connected sockets, connect the socket on the first 188 # netid now. 189 if use_connect: 190 netid = list(self.tuns.keys())[0] 191 self.SelectInterface(s, netid, mode) 192 s.connect((dstaddr, 53)) 193 expected.src = self.MyAddress(version, netid) 194 195 # For each netid, select that network without closing the socket, and 196 # check that the packets sent on that socket go out on the right network. 197 # 198 # For connected sockets, routing is cached in the socket's destination 199 # cache entry. In this case, we check that selecting the network a second 200 # time on the same socket (except via SO_BINDTODEVICE, or SO_MARK on 5.0+ 201 # kernels) does not change routing, but that subsequently invalidating the 202 # destination cache entry does. This is a bug in the kernel because 203 # re-selecting the netid should cause routing to change, and future 204 # kernels may fix this bug for per-UID routing and ucast_oif routing like 205 # they already have for mark-based routing. But until they do, this 206 # behaviour provides a convenient way to check that InvalidateDstCache 207 # actually works. 208 prevnetid = None 209 for netid in self.tuns: 210 self.SelectInterface(s, netid, mode) 211 if not use_connect: 212 expected.src = self.MyAddress(version, netid) 213 214 def ExpectSendUsesNetid(netid): 215 connected_str = "Connected" if use_connect else "Unconnected" 216 msg = "%s UDPv%d socket remarked using %s: expecting %s on %s" % ( 217 connected_str, version, mode, desc, self.GetInterfaceName(netid)) 218 if use_connect: 219 s.send(UDP_PAYLOAD) 220 else: 221 s.sendto(UDP_PAYLOAD, (dstaddr, 53)) 222 self.ExpectPacketOn(netid, msg, expected) 223 224 # Does this socket have a stale dst cache entry that we need to clear? 225 def SocketHasStaleDstCacheEntry(): 226 if not prevnetid: 227 # This is the first time we're marking the socket. 228 return False 229 if not use_connect: 230 # Non-connected sockets never have dst cache entries. 231 return False 232 if mode in ["uid", "ucast_oif"]: 233 # No kernel invalidates the dst cache entry if the UID or the 234 # UCAST_OIF socket option changes. 235 return True 236 if mode == "oif": 237 # Changing SO_BINDTODEVICE always invalidates the dst cache entry. 238 return False 239 if mode == "mark": 240 # Changing the mark invalidates the dst cache entry in 5.0+. 241 return net_test.LINUX_VERSION < (5, 0, 0) 242 raise AssertionError("%s must be one of %s" % (mode, modes)) 243 244 if SocketHasStaleDstCacheEntry(): 245 ExpectSendUsesNetid(prevnetid) 246 # ... until we invalidate it. 247 self.InvalidateDstCache(version, prevnetid) 248 249 # In any case, future sends must be correct. 250 ExpectSendUsesNetid(netid) 251 252 self.SelectInterface(s, None, mode) 253 prevnetid = netid 254 255 s.close() 256 257 def testIPv4Remarking(self): 258 """Checks that updating the mark on an IPv4 socket changes routing.""" 259 self.CheckRemarking(4, False) 260 self.CheckRemarking(4, True) 261 262 def testIPv6Remarking(self): 263 """Checks that updating the mark on an IPv6 socket changes routing.""" 264 self.CheckRemarking(6, False) 265 self.CheckRemarking(6, True) 266 267 def testIPv6StickyPktinfo(self): 268 for _ in range(self.ITERATIONS): 269 for netid in self.tuns: 270 s = net_test.UDPSocket(AF_INET6) 271 272 # Set a flowlabel. 273 net_test.SetFlowLabel(s, net_test.IPV6_ADDR, 0xdead) 274 s.setsockopt(net_test.SOL_IPV6, net_test.IPV6_FLOWINFO_SEND, 1) 275 276 # Set some destination options. 277 nonce = b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c" 278 dstopts = b"".join([ 279 b"\x11\x02", # Next header=UDP, 24 bytes of options. 280 b"\x01\x06", b"\x00" * 6, # PadN, 6 bytes of padding. 281 b"\x8b\x0c", # ILNP nonce, 12 bytes. 282 nonce 283 ]) 284 s.setsockopt(net_test.SOL_IPV6, IPV6_DSTOPTS, dstopts) 285 s.setsockopt(net_test.SOL_IPV6, IPV6_UNICAST_HOPS, 255) 286 287 pktinfo = multinetwork_base.MakePktInfo(6, None, self.ifindices[netid]) 288 289 # Set the sticky pktinfo option. 290 s.setsockopt(net_test.SOL_IPV6, IPV6_PKTINFO, pktinfo) 291 292 # Specify the flowlabel in the destination address. 293 s.sendto(UDP_PAYLOAD, (net_test.IPV6_ADDR, 53, 0xdead, 0)) 294 295 sport = s.getsockname()[1] 296 srcaddr = self.MyAddress(6, netid) 297 expected = (scapy.IPv6(src=srcaddr, dst=net_test.IPV6_ADDR, 298 fl=0xdead, hlim=255) / 299 scapy.IPv6ExtHdrDestOpt( 300 options=[scapy.PadN(optdata="\x00\x00\x00\x00\x00\x00"), 301 scapy.HBHOptUnknown(otype=0x8b, 302 optdata=nonce)]) / 303 scapy.UDP(sport=sport, dport=53) / 304 UDP_PAYLOAD) 305 msg = "IPv6 UDP using sticky pktinfo: expected UDP packet on %s" % ( 306 self.GetInterfaceName(netid)) 307 self.ExpectPacketOn(netid, msg, expected) 308 s.close() 309 310 def CheckPktinfoRouting(self, version): 311 for _ in range(self.ITERATIONS): 312 for netid in self.tuns: 313 family = self.GetProtocolFamily(version) 314 s = net_test.UDPSocket(family) 315 316 if version == 6: 317 # Create a flowlabel so we can use it. 318 net_test.SetFlowLabel(s, net_test.IPV6_ADDR, 0xbeef) 319 320 # Specify some arbitrary options. 321 # We declare the flowlabel as ctypes.c_uint32 because on a 32-bit 322 # Python interpreter an integer greater than 0x7fffffff (such as our 323 # chosen flowlabel after being passed through htonl) is converted to 324 # long, and _MakeMsgControl doesn't know what to do with longs. 325 cmsgs = [ 326 (net_test.SOL_IPV6, IPV6_HOPLIMIT, 39), 327 (net_test.SOL_IPV6, IPV6_TCLASS, 0x83), 328 (net_test.SOL_IPV6, IPV6_FLOWINFO, ctypes.c_uint(htonl(0xbeef))), 329 ] 330 else: 331 # Support for setting IPv4 TOS and TTL via cmsg only appeared in 3.13. 332 cmsgs = [] 333 s.setsockopt(net_test.SOL_IP, IP_TTL, 39) 334 s.setsockopt(net_test.SOL_IP, IP_TOS, 0x83) 335 336 dstaddr = self.GetRemoteAddress(version) 337 self.SendOnNetid(version, s, dstaddr, 53, netid, UDP_PAYLOAD, cmsgs) 338 339 sport = s.getsockname()[1] 340 srcaddr = self.MyAddress(version, netid) 341 342 desc, expected = packets.UDPWithOptions(version, srcaddr, dstaddr, 343 sport=sport) 344 345 msg = "IPv%d UDP using pktinfo routing: expected %s on %s" % ( 346 version, desc, self.GetInterfaceName(netid)) 347 self.ExpectPacketOn(netid, msg, expected) 348 349 s.close() 350 351 def testIPv4PktinfoRouting(self): 352 self.CheckPktinfoRouting(4) 353 354 def testIPv6PktinfoRouting(self): 355 self.CheckPktinfoRouting(6) 356 357 358class MarkTest(multinetwork_base.InboundMarkingTest): 359 360 def CheckReflection(self, version, gen_packet, gen_reply): 361 """Checks that replies go out on the same interface as the original. 362 363 For each combination: 364 - Calls gen_packet to generate a packet to that IP address. 365 - Writes the packet generated by gen_packet on the given tun 366 interface, causing the kernel to receive it. 367 - Checks that the kernel's reply matches the packet generated by 368 gen_reply. 369 370 Args: 371 version: An integer, 4 or 6. 372 gen_packet: A function taking an IP version (an integer), a source 373 address and a destination address (strings), and returning a scapy 374 packet. 375 gen_reply: A function taking the same arguments as gen_packet, 376 plus a scapy packet, and returning a scapy packet. 377 """ 378 for netid, iif, ip_if, myaddr, remoteaddr in self.Combinations(version): 379 # Generate a test packet. 380 desc, packet = gen_packet(version, remoteaddr, myaddr) 381 382 # Test with mark reflection enabled and disabled. 383 for reflect in [0, 1]: 384 self.SetMarkReflectSysctls(reflect) 385 # HACK: IPv6 ping replies always do a routing lookup with the 386 # interface the ping came in on. So even if mark reflection is not 387 # working, IPv6 ping replies will be properly reflected. Don't 388 # fail when that happens. 389 if reflect or desc == "ICMPv6 echo": 390 reply_desc, reply = gen_reply(version, myaddr, remoteaddr, packet) 391 else: 392 reply_desc, reply = None, None 393 394 msg = self._FormatMessage(iif, ip_if, "reflect=%d" % reflect, 395 desc, reply_desc) 396 self._ReceiveAndExpectResponse(netid, packet, reply, msg) 397 398 def SYNToClosedPort(self, *args): 399 return packets.SYN(999, *args) 400 401 def testIPv4ICMPErrorsReflectMark(self): 402 self.CheckReflection(4, packets.UDP, packets.ICMPPortUnreachable) 403 404 def testIPv6ICMPErrorsReflectMark(self): 405 self.CheckReflection(6, packets.UDP, packets.ICMPPortUnreachable) 406 407 def testIPv4PingRepliesReflectMarkAndTos(self): 408 self.CheckReflection(4, packets.ICMPEcho, packets.ICMPReply) 409 410 def testIPv6PingRepliesReflectMarkAndTos(self): 411 self.CheckReflection(6, packets.ICMPEcho, packets.ICMPReply) 412 413 def testIPv4RSTsReflectMark(self): 414 self.CheckReflection(4, self.SYNToClosedPort, packets.RST) 415 416 def testIPv6RSTsReflectMark(self): 417 self.CheckReflection(6, self.SYNToClosedPort, packets.RST) 418 419 420class TCPAcceptTest(multinetwork_base.InboundMarkingTest): 421 422 MODE_BINDTODEVICE = "SO_BINDTODEVICE" 423 MODE_INCOMING_MARK = "incoming mark" 424 MODE_EXPLICIT_MARK = "explicit mark" 425 MODE_UID = "uid" 426 427 @classmethod 428 def setUpClass(cls): 429 super(TCPAcceptTest, cls).setUpClass() 430 431 # Open a port so we can observe SYN+ACKs. Since it's a dual-stack socket it 432 # will accept both IPv4 and IPv6 connections. We do this here instead of in 433 # each test so we can use the same socket every time. That way, if a kernel 434 # bug causes incoming packets to mark the listening socket instead of the 435 # accepted socket, the test will fail as soon as the next address/interface 436 # combination is tried. 437 cls.listensocket = net_test.IPv6TCPSocket() 438 cls.listenport = net_test.BindRandomPort(6, cls.listensocket) 439 440 def _SetTCPMarkAcceptSysctl(self, value): 441 self.SetSysctl(TCP_MARK_ACCEPT_SYSCTL, value) 442 443 def CheckTCPConnection(self, mode, listensocket, netid, version, 444 myaddr, remoteaddr, packet, reply, msg): 445 establishing_ack = packets.ACK(version, remoteaddr, myaddr, reply)[1] 446 447 # Attempt to confuse the kernel. 448 self.InvalidateDstCache(version, netid) 449 450 self.ReceivePacketOn(netid, establishing_ack) 451 452 # If we're using UID routing, the accept() call has to be run as a UID that 453 # is routed to the specified netid, because the UID of the socket returned 454 # by accept() is the effective UID of the process that calls it. It doesn't 455 # need to be the same UID; any UID that selects the same interface will do. 456 with net_test.RunAsUid(self.UidForNetid(netid)): 457 s, _ = listensocket.accept() 458 459 try: 460 # Check that data sent on the connection goes out on the right interface. 461 desc, data = packets.ACK(version, myaddr, remoteaddr, establishing_ack, 462 payload=UDP_PAYLOAD) 463 s.send(UDP_PAYLOAD) 464 self.ExpectPacketOn(netid, msg + ": expecting %s" % desc, data) 465 self.InvalidateDstCache(version, netid) 466 467 # Keep up our end of the conversation. 468 ack = packets.ACK(version, remoteaddr, myaddr, data)[1] 469 self.InvalidateDstCache(version, netid) 470 self.ReceivePacketOn(netid, ack) 471 472 mark = self.GetSocketMark(s) 473 finally: 474 self.InvalidateDstCache(version, netid) 475 s.close() 476 self.InvalidateDstCache(version, netid) 477 478 if mode == self.MODE_INCOMING_MARK: 479 self.assertEqual(netid, mark & self.NETID_FWMASK, 480 msg + ": Accepted socket: Expected mark %d, got %d" % ( 481 netid, mark)) 482 elif mode != self.MODE_EXPLICIT_MARK: 483 self.assertEqual(0, self.GetSocketMark(listensocket)) 484 485 # Check the FIN was sent on the right interface, and ack it. We don't expect 486 # this to fail because by the time the connection is established things are 487 # likely working, but a) extra tests are always good and b) extra packets 488 # like the FIN (and retransmitted FINs) could cause later tests that expect 489 # no packets to fail. 490 desc, fin = packets.FIN(version, myaddr, remoteaddr, ack) 491 self.ExpectPacketOn(netid, msg + ": expecting %s after close" % desc, fin) 492 493 desc, finack = packets.FIN(version, remoteaddr, myaddr, fin) 494 self.ReceivePacketOn(netid, finack) 495 496 # Since we called close() earlier, the userspace socket object is gone, so 497 # the socket has no UID. If we're doing UID routing, the ack might be routed 498 # incorrectly. Not much we can do here. 499 desc, finackack = packets.ACK(version, myaddr, remoteaddr, finack) 500 self.ExpectPacketOn(netid, msg + ": expecting final ack", finackack) 501 502 def CheckTCP(self, version, modes): 503 """Checks that incoming TCP connections work. 504 505 Args: 506 version: An integer, 4 or 6. 507 modes: A list of modes to excercise. 508 """ 509 for syncookies in [0, 2]: 510 for mode in modes: 511 for netid, iif, ip_if, myaddr, remoteaddr in self.Combinations(version): 512 listensocket = self.listensocket 513 listenport = listensocket.getsockname()[1] 514 515 accept_sysctl = 1 if mode == self.MODE_INCOMING_MARK else 0 516 self._SetTCPMarkAcceptSysctl(accept_sysctl) 517 self.SetMarkReflectSysctls(accept_sysctl) 518 519 bound_dev = iif if mode == self.MODE_BINDTODEVICE else None 520 self.BindToDevice(listensocket, bound_dev) 521 522 mark = netid if mode == self.MODE_EXPLICIT_MARK else 0 523 self.SetSocketMark(listensocket, mark) 524 525 uid = self.UidForNetid(netid) if mode == self.MODE_UID else 0 526 os.fchown(listensocket.fileno(), uid, -1) 527 528 # Generate the packet here instead of in the outer loop, so 529 # subsequent TCP connections use different source ports and 530 # retransmissions from old connections don't confuse subsequent 531 # tests. 532 desc, packet = packets.SYN(listenport, version, remoteaddr, myaddr) 533 534 if mode: 535 reply_desc, reply = packets.SYNACK(version, myaddr, remoteaddr, 536 packet) 537 else: 538 reply_desc, reply = None, None 539 540 extra = "mode=%s, syncookies=%d" % (mode, syncookies) 541 msg = self._FormatMessage(iif, ip_if, extra, desc, reply_desc) 542 reply = self._ReceiveAndExpectResponse(netid, packet, reply, msg) 543 if reply: 544 self.CheckTCPConnection(mode, listensocket, netid, version, myaddr, 545 remoteaddr, packet, reply, msg) 546 547 def testBasicTCP(self): 548 self.CheckTCP(4, [None, self.MODE_BINDTODEVICE, self.MODE_EXPLICIT_MARK]) 549 self.CheckTCP(6, [None, self.MODE_BINDTODEVICE, self.MODE_EXPLICIT_MARK]) 550 551 def testIPv4MarkAccept(self): 552 self.CheckTCP(4, [self.MODE_INCOMING_MARK]) 553 554 def testIPv6MarkAccept(self): 555 self.CheckTCP(6, [self.MODE_INCOMING_MARK]) 556 557 def testIPv4UidAccept(self): 558 self.CheckTCP(4, [self.MODE_UID]) 559 560 def testIPv6UidAccept(self): 561 self.CheckTCP(6, [self.MODE_UID]) 562 563 def testIPv6ExplicitMark(self): 564 self.CheckTCP(6, [self.MODE_EXPLICIT_MARK]) 565 566@unittest.skipUnless(multinetwork_base.HAVE_AUTOCONF_TABLE, 567 "need support for per-table autoconf") 568class RIOTest(multinetwork_base.MultiNetworkBaseTest): 569 """Test for IPv6 RFC 4191 route information option 570 571 Relevant kernel commits: 572 upstream: 573 f104a567e673 ipv6: use rt6_get_dflt_router to get default router in rt6_route_rcv 574 bbea124bc99d net: ipv6: Add sysctl for minimum prefix len acceptable in RIOs. 575 576 android-4.9: 577 d860b2e8a7f1 FROMLIST: net: ipv6: Add sysctl for minimum prefix len acceptable in RIOs 578 579 android-4.4: 580 e953f89b8563 net: ipv6: Add sysctl for minimum prefix len acceptable in RIOs. 581 582 android-4.1: 583 84f2f47716cd net: ipv6: Add sysctl for minimum prefix len acceptable in RIOs. 584 585 android-3.18: 586 65f8936934fa net: ipv6: Add sysctl for minimum prefix len acceptable in RIOs. 587 588 android-3.10: 589 161e88ebebc7 net: ipv6: Add sysctl for minimum prefix len acceptable in RIOs. 590 591 """ 592 593 def setUp(self): 594 super(RIOTest, self).setUp() 595 self.NETID = random.choice(self.NETIDS) 596 self.IFACE = self.GetInterfaceName(self.NETID) 597 # return min/max plen to default values before each test case 598 self.SetAcceptRaRtInfoMinPlen(0) 599 self.SetAcceptRaRtInfoMaxPlen(0) 600 601 def GetRoutingTable(self): 602 return self._TableForNetid(self.NETID) 603 604 def SetAcceptRaRtInfoMinPlen(self, plen): 605 self.SetSysctl( 606 "/proc/sys/net/ipv6/conf/%s/accept_ra_rt_info_min_plen" 607 % self.IFACE, plen) 608 609 def GetAcceptRaRtInfoMinPlen(self): 610 return int(self.GetSysctl( 611 "/proc/sys/net/ipv6/conf/%s/accept_ra_rt_info_min_plen" % self.IFACE)) 612 613 def SetAcceptRaRtInfoMaxPlen(self, plen): 614 self.SetSysctl( 615 "/proc/sys/net/ipv6/conf/%s/accept_ra_rt_info_max_plen" 616 % self.IFACE, plen) 617 618 def GetAcceptRaRtInfoMaxPlen(self): 619 return int(self.GetSysctl( 620 "/proc/sys/net/ipv6/conf/%s/accept_ra_rt_info_max_plen" % self.IFACE)) 621 622 def SendRIO(self, rtlifetime, plen, prefix, prf): 623 options = scapy.ICMPv6NDOptRouteInfo(rtlifetime=rtlifetime, plen=plen, 624 prefix=prefix, prf=prf) 625 self.SendRA(self.NETID, options=(options,)) 626 627 def FindRoutesWithDestination(self, destination): 628 canonical = net_test.CanonicalizeIPv6Address(destination) 629 return [r for _, r in self.iproute.DumpRoutes(6, self.GetRoutingTable()) 630 if ('RTA_DST' in r and r['RTA_DST'] == canonical)] 631 632 def FindRoutesWithGateway(self): 633 return [r for _, r in self.iproute.DumpRoutes(6, self.GetRoutingTable()) 634 if 'RTA_GATEWAY' in r] 635 636 def CountRoutes(self): 637 return len(self.iproute.DumpRoutes(6, self.GetRoutingTable())) 638 639 def GetRouteExpiration(self, route): 640 return float(route['RTA_CACHEINFO'].expires) / 100.0 641 642 def AssertExpirationInRange(self, routes, lifetime, epsilon): 643 self.assertTrue(routes) 644 found = False 645 # Assert that at least one route in routes has the expected lifetime 646 for route in routes: 647 expiration = self.GetRouteExpiration(route) 648 if expiration < lifetime - epsilon: 649 continue 650 if expiration > lifetime + epsilon: 651 continue 652 found = True 653 self.assertTrue(found) 654 655 def DelRA6(self, prefix, plen): 656 version = 6 657 netid = self.NETID 658 table = self._TableForNetid(netid) 659 router = self._RouterAddress(netid, version) 660 ifindex = self.ifindices[netid] 661 self.iproute._Route(version, iproute.RTPROT_RA, iproute.RTM_DELROUTE, 662 table, prefix, plen, router, ifindex, None, None) 663 664 def testSetAcceptRaRtInfoMinPlen(self): 665 for plen in range(-1, 130): 666 self.SetAcceptRaRtInfoMinPlen(plen) 667 self.assertEqual(plen, self.GetAcceptRaRtInfoMinPlen()) 668 669 def testSetAcceptRaRtInfoMaxPlen(self): 670 for plen in range(-1, 130): 671 self.SetAcceptRaRtInfoMaxPlen(plen) 672 self.assertEqual(plen, self.GetAcceptRaRtInfoMaxPlen()) 673 674 def testZeroRtLifetime(self): 675 PREFIX = "2001:db8:8901:2300::" 676 RTLIFETIME = 73500 677 PLEN = 56 678 PRF = 0 679 self.SetAcceptRaRtInfoMaxPlen(PLEN) 680 self.SendRIO(RTLIFETIME, PLEN, PREFIX, PRF) 681 # Give the kernel time to notice our RA 682 time.sleep(0.01) 683 self.assertTrue(self.FindRoutesWithDestination(PREFIX)) 684 # RIO with rtlifetime = 0 should remove from routing table 685 self.SendRIO(0, PLEN, PREFIX, PRF) 686 # Give the kernel time to notice our RA 687 time.sleep(0.01) 688 self.assertFalse(self.FindRoutesWithDestination(PREFIX)) 689 690 def testMinPrefixLenRejection(self): 691 PREFIX = "2001:db8:8902:2345::" 692 RTLIFETIME = 70372 693 PRF = 0 694 # sweep from high to low to avoid spurious failures from late arrivals. 695 for plen in range(130, 1, -1): 696 self.SetAcceptRaRtInfoMinPlen(plen) 697 # RIO with plen < min_plen should be ignored 698 self.SendRIO(RTLIFETIME, plen - 1, PREFIX, PRF) 699 # Give the kernel time to notice our RAs 700 time.sleep(0.1) 701 # Expect no routes 702 routes = self.FindRoutesWithDestination(PREFIX) 703 self.assertFalse(routes) 704 705 def testMaxPrefixLenRejection(self): 706 PREFIX = "2001:db8:8903:2345::" 707 RTLIFETIME = 73078 708 PRF = 0 709 # sweep from low to high to avoid spurious failures from late arrivals. 710 for plen in range(-1, 128, 1): 711 self.SetAcceptRaRtInfoMaxPlen(plen) 712 # RIO with plen > max_plen should be ignored 713 self.SendRIO(RTLIFETIME, plen + 1, PREFIX, PRF) 714 # Give the kernel time to notice our RAs 715 time.sleep(0.1) 716 # Expect no routes 717 routes = self.FindRoutesWithDestination(PREFIX) 718 self.assertFalse(routes) 719 720 def testSimpleAccept(self): 721 PREFIX = "2001:db8:8904:2345::" 722 RTLIFETIME = 9993 723 PRF = 0 724 PLEN = 56 725 self.SetAcceptRaRtInfoMinPlen(48) 726 self.SetAcceptRaRtInfoMaxPlen(64) 727 self.SendRIO(RTLIFETIME, PLEN, PREFIX, PRF) 728 # Give the kernel time to notice our RA 729 time.sleep(0.01) 730 routes = self.FindRoutesWithGateway() 731 self.AssertExpirationInRange(routes, RTLIFETIME, 1) 732 self.DelRA6(PREFIX, PLEN) 733 734 def testEqualMinMaxAccept(self): 735 PREFIX = "2001:db8:8905:2345::" 736 RTLIFETIME = 6326 737 PLEN = 21 738 PRF = 0 739 self.SetAcceptRaRtInfoMinPlen(PLEN) 740 self.SetAcceptRaRtInfoMaxPlen(PLEN) 741 self.SendRIO(RTLIFETIME, PLEN, PREFIX, PRF) 742 # Give the kernel time to notice our RA 743 time.sleep(0.01) 744 routes = self.FindRoutesWithGateway() 745 self.AssertExpirationInRange(routes, RTLIFETIME, 1) 746 self.DelRA6(PREFIX, PLEN) 747 748 def testZeroLengthPrefix(self): 749 PREFIX = "2001:db8:8906:2345::" 750 RTLIFETIME = self.RA_VALIDITY * 2 751 PLEN = 0 752 PRF = 0 753 # Max plen = 0 still allows default RIOs! 754 self.SetAcceptRaRtInfoMaxPlen(PLEN) 755 self.SendRA(self.NETID) 756 # Give the kernel time to notice our RA 757 time.sleep(0.01) 758 default = self.FindRoutesWithGateway() 759 self.AssertExpirationInRange(default, self.RA_VALIDITY, 1) 760 # RIO with prefix length = 0, should overwrite default route lifetime 761 # note that the RIO lifetime overwrites the RA lifetime. 762 self.SendRIO(RTLIFETIME, PLEN, PREFIX, PRF) 763 # Give the kernel time to notice our RA 764 time.sleep(0.01) 765 default = self.FindRoutesWithGateway() 766 self.AssertExpirationInRange(default, RTLIFETIME, 1) 767 self.DelRA6(PREFIX, PLEN) 768 769 def testManyRIOs(self): 770 RTLIFETIME = 68012 771 PLEN = 56 772 PRF = 0 773 COUNT = 1000 774 baseline = self.CountRoutes() 775 self.SetAcceptRaRtInfoMaxPlen(56) 776 # Send many RIOs compared to the expected number on a healthy system. 777 for i in range(0, COUNT): 778 prefix = "2001:db8:%x:1100::" % i 779 self.SendRIO(RTLIFETIME, PLEN, prefix, PRF) 780 time.sleep(0.1) 781 self.assertEqual(COUNT + baseline, self.CountRoutes()) 782 for i in range(0, COUNT): 783 prefix = "2001:db8:%x:1100::" % i 784 self.DelRA6(prefix, PLEN) 785 # Expect that we can return to baseline config without lingering routes. 786 self.assertEqual(baseline, self.CountRoutes()) 787 788class RATest(multinetwork_base.MultiNetworkBaseTest): 789 790 ND_ROUTER_ADVERT = 134 791 ND_OPT_PREF64 = 38 792 Pref64Option = cstruct.Struct("pref64_option", "!BBH12s", 793 "type length lft_plc prefix") 794 795 def testDoesNotHaveObsoleteSysctl(self): 796 self.assertFalse(os.path.isfile( 797 "/proc/sys/net/ipv6/route/autoconf_table_offset")) 798 799 @unittest.skipUnless(multinetwork_base.HAVE_AUTOCONF_TABLE, 800 "no support for per-table autoconf") 801 def testPurgeDefaultRouters(self): 802 803 def CheckIPv6Connectivity(expect_connectivity): 804 for netid in self.NETIDS: 805 s = net_test.UDPSocket(AF_INET6) 806 self.SetSocketMark(s, netid) 807 if expect_connectivity: 808 self.assertTrue(s.sendto(UDP_PAYLOAD, (net_test.IPV6_ADDR, 1234))) 809 else: 810 self.assertRaisesErrno(errno.ENETUNREACH, s.sendto, UDP_PAYLOAD, 811 (net_test.IPV6_ADDR, 1234)) 812 s.close() 813 814 try: 815 CheckIPv6Connectivity(True) 816 self.SetIPv6SysctlOnAllIfaces("accept_ra", 1) 817 self.SetSysctl("/proc/sys/net/ipv6/conf/all/forwarding", 1) 818 CheckIPv6Connectivity(False) 819 finally: 820 self.SetSysctl("/proc/sys/net/ipv6/conf/all/forwarding", 0) 821 for netid in self.NETIDS: 822 self.SendRA(netid) 823 CheckIPv6Connectivity(True) 824 825 def testOnlinkCommunication(self): 826 """Checks that on-link communication goes direct and not through routers.""" 827 for netid in self.tuns: 828 # Send a UDP packet to a random on-link destination. 829 s = net_test.UDPSocket(AF_INET6) 830 iface = self.GetInterfaceName(netid) 831 self.BindToDevice(s, iface) 832 # dstaddr can never be our address because GetRandomDestination only fills 833 # in the lower 32 bits, but our address has 0xff in the byte before that 834 # (since it's constructed from the EUI-64 and so has ff:fe in the middle). 835 dstaddr = self.GetRandomDestination(self.OnlinkPrefix(6, netid)) 836 s.sendto(UDP_PAYLOAD, (dstaddr, 53)) 837 838 # Expect an NS for that destination on the interface. 839 myaddr = self.MyAddress(6, netid) 840 mymac = self.MyMacAddress(netid) 841 desc, expected = packets.NS(myaddr, dstaddr, mymac) 842 msg = "Sending UDP packet to on-link destination: expecting %s" % desc 843 time.sleep(0.0001) # Required to make the test work on kernel 3.1(!) 844 self.ExpectPacketOn(netid, msg, expected) 845 846 # Send an NA. 847 tgtmac = "02:00:00:00:%02x:99" % netid 848 _, reply = packets.NA(dstaddr, myaddr, tgtmac) 849 # Don't use ReceivePacketOn, since that uses the router's MAC address as 850 # the source. Instead, construct our own Ethernet header with source 851 # MAC of tgtmac. 852 reply = scapy.Ether(src=tgtmac, dst=mymac) / reply 853 self.ReceiveEtherPacketOn(netid, reply) 854 855 # Expect the kernel to send the original UDP packet now that the ND cache 856 # entry has been populated. 857 sport = s.getsockname()[1] 858 desc, expected = packets.UDP(6, myaddr, dstaddr, sport=sport) 859 msg = "After NA response, expecting %s" % desc 860 self.ExpectPacketOn(netid, msg, expected) 861 862 s.close() 863 864 # This test documents a known issue: routing tables are never deleted. 865 @unittest.skipUnless(multinetwork_base.HAVE_AUTOCONF_TABLE, 866 "no support for per-table autoconf") 867 def testLeftoverRoutes(self): 868 def GetNumRoutes(): 869 with open("/proc/net/ipv6_route") as ipv6_route: 870 return len(ipv6_route.readlines()) 871 872 num_routes = GetNumRoutes() 873 for i in range(10, 20): 874 try: 875 self.tuns[i] = self.CreateTunInterface(i) 876 self.SendRA(i) 877 self.tuns[i].close() 878 finally: 879 del self.tuns[i] 880 self.assertLess(num_routes, GetNumRoutes()) 881 882 def SendNdUseropt(self, option): 883 options = scapy.ICMPv6NDOptRouteInfo(rtlifetime=rtlifetime, plen=plen, 884 prefix=prefix, prf=prf) 885 self.SendRA(self.NETID, options=(options,)) 886 887 def MakePref64Option(self, prefix, lifetime): 888 prefix = inet_pton(AF_INET6, prefix)[:12] 889 lft_plc = (lifetime & 0xfff8) | 0 # 96-bit prefix length 890 return self.Pref64Option((self.ND_OPT_PREF64, 2, lft_plc, prefix)) 891 892 def testPref64UserOption(self): 893 # Open a netlink socket to receive RTM_NEWNDUSEROPT messages. 894 s = netlink.NetlinkSocket(netlink.NETLINK_ROUTE, iproute.RTMGRP_ND_USEROPT) 895 896 # Send an RA with the PREF64 option. 897 netid = random.choice(self.NETIDS) 898 opt = self.MakePref64Option("64:ff9b::", 300) 899 self.SendRA(netid, options=(opt.Pack(),)) 900 901 # Check that we get an an RTM_NEWNDUSEROPT message on the socket with the 902 # expected option. 903 csocket.SetSocketTimeout(s.sock, 100) 904 try: 905 data = s._Recv() 906 except IOError as e: 907 self.fail("Should have received an RTM_NEWNDUSEROPT message. " 908 "Please ensure the kernel supports receiving the " 909 "PREF64 RA option. Error: %s" % e) 910 s.close() 911 912 # Check that the message is received correctly. 913 nlmsghdr, data = cstruct.Read(data, netlink.NLMsgHdr) 914 self.assertEqual(iproute.RTM_NEWNDUSEROPT, nlmsghdr.type) 915 916 # Check the option contents. 917 ndopthdr, data = cstruct.Read(data, iproute.NdUseroptMsg) 918 self.assertEqual(AF_INET6, ndopthdr.family) 919 self.assertEqual(self.ND_ROUTER_ADVERT, ndopthdr.icmp_type) 920 self.assertEqual(len(opt), ndopthdr.opts_len) 921 922 actual_opt = self.Pref64Option(data) 923 self.assertEqual(opt, actual_opt) 924 925 926 927class PMTUTest(multinetwork_base.InboundMarkingTest): 928 929 PAYLOAD_SIZE = 1400 930 dstaddrs = set() 931 932 def GetSocketMTU(self, version, s): 933 if version == 6: 934 ip6_mtuinfo = s.getsockopt(net_test.SOL_IPV6, csocket.IPV6_PATHMTU, 32) 935 unused_sockaddr, mtu = struct.unpack("=28sI", ip6_mtuinfo) 936 return mtu 937 else: 938 return s.getsockopt(net_test.SOL_IP, csocket.IP_MTU) 939 940 def DisableFragmentationAndReportErrors(self, version, s): 941 if version == 4: 942 s.setsockopt(net_test.SOL_IP, csocket.IP_MTU_DISCOVER, 943 csocket.IP_PMTUDISC_DO) 944 s.setsockopt(net_test.SOL_IP, net_test.IP_RECVERR, 1) 945 else: 946 s.setsockopt(net_test.SOL_IPV6, csocket.IPV6_DONTFRAG, 1) 947 s.setsockopt(net_test.SOL_IPV6, net_test.IPV6_RECVERR, 1) 948 949 def CheckPMTU(self, version, use_connect, modes): 950 951 def SendBigPacket(version, s, dstaddr, netid, payload): 952 if use_connect: 953 s.send(payload) 954 else: 955 self.SendOnNetid(version, s, dstaddr, 1234, netid, payload, []) 956 957 for netid in self.tuns: 958 for mode in modes: 959 s = self.BuildSocket(version, net_test.UDPSocket, netid, mode) 960 self.DisableFragmentationAndReportErrors(version, s) 961 962 srcaddr = self.MyAddress(version, netid) 963 dst_prefix, intermediate = { 964 4: ("172.19.", "172.16.9.12"), 965 6: ("2001:db8::", "2001:db8::1") 966 }[version] 967 968 # Run this test often enough (e.g., in presubmits), and eventually 969 # we'll be unlucky enough to pick the same address twice, in which 970 # case the test will fail because the kernel will already have seen 971 # the lower MTU. Don't do this. 972 dstaddr = self.GetRandomDestination(dst_prefix) 973 while dstaddr in self.dstaddrs: 974 dstaddr = self.GetRandomDestination(dst_prefix) 975 self.dstaddrs.add(dstaddr) 976 977 if use_connect: 978 s.connect((dstaddr, 1234)) 979 980 payload = self.PAYLOAD_SIZE * b"a" 981 982 # Send a packet and receive a packet too big. 983 SendBigPacket(version, s, dstaddr, netid, payload) 984 received = self.ReadAllPacketsOn(netid) 985 self.assertEqual(1, len(received), 986 "unexpected packets: %s" % received[1:]) 987 _, toobig = packets.ICMPPacketTooBig(version, intermediate, srcaddr, 988 received[0]) 989 self.ReceivePacketOn(netid, toobig) 990 991 # Check that another send on the same socket returns EMSGSIZE. 992 self.assertRaisesErrno( 993 errno.EMSGSIZE, 994 SendBigPacket, version, s, dstaddr, netid, payload) 995 996 # If this is a connected socket, make sure the socket MTU was set. 997 # Note that in IPv4 this only started working in Linux 3.6! 998 if use_connect: 999 self.assertEqual(packets.PTB_MTU, self.GetSocketMTU(version, s)) 1000 1001 s.close() 1002 1003 # Check that other sockets pick up the PMTU we have been told about by 1004 # connecting another socket to the same destination and getting its MTU. 1005 # This new socket can use any method to select its outgoing interface; 1006 # here we use a mark for simplicity. 1007 s2 = self.BuildSocket(version, net_test.UDPSocket, netid, "mark") 1008 s2.connect((dstaddr, 1234)) 1009 self.assertEqual(packets.PTB_MTU, self.GetSocketMTU(version, s2)) 1010 1011 # Also check the MTU reported by ip route get, this time using the oif. 1012 routes = self.iproute.GetRoutes(dstaddr, self.ifindices[netid], 0, None) 1013 self.assertTrue(routes) 1014 route = routes[0] 1015 rtmsg, attributes = route 1016 self.assertEqual(iproute.RTN_UNICAST, rtmsg.type) 1017 metrics = attributes["RTA_METRICS"] 1018 self.assertEqual(packets.PTB_MTU, metrics["RTAX_MTU"]) 1019 1020 s2.close() 1021 1022 def testIPv4BasicPMTU(self): 1023 """Tests IPv4 path MTU discovery. 1024 1025 Relevant kernel commits: 1026 upstream net-next: 1027 6a66271 ipv4, fib: pass LOOPBACK_IFINDEX instead of 0 to flowi4_iif 1028 1029 android-3.10: 1030 4bc64dd ipv4, fib: pass LOOPBACK_IFINDEX instead of 0 to flowi4_iif 1031 """ 1032 1033 self.CheckPMTU(4, True, ["mark", "oif"]) 1034 self.CheckPMTU(4, False, ["mark", "oif"]) 1035 1036 def testIPv6BasicPMTU(self): 1037 self.CheckPMTU(6, True, ["mark", "oif"]) 1038 self.CheckPMTU(6, False, ["mark", "oif"]) 1039 1040 def testIPv4UIDPMTU(self): 1041 self.CheckPMTU(4, True, ["uid"]) 1042 self.CheckPMTU(4, False, ["uid"]) 1043 1044 def testIPv6UIDPMTU(self): 1045 self.CheckPMTU(6, True, ["uid"]) 1046 self.CheckPMTU(6, False, ["uid"]) 1047 1048 # Making Path MTU Discovery work on unmarked sockets requires that mark 1049 # reflection be enabled. Otherwise the kernel has no way to know what routing 1050 # table the original packet used, and thus it won't be able to clone the 1051 # correct route. 1052 1053 def testIPv4UnmarkedSocketPMTU(self): 1054 self.SetMarkReflectSysctls(1) 1055 try: 1056 self.CheckPMTU(4, False, [None]) 1057 finally: 1058 self.SetMarkReflectSysctls(0) 1059 1060 def testIPv6UnmarkedSocketPMTU(self): 1061 self.SetMarkReflectSysctls(1) 1062 try: 1063 self.CheckPMTU(6, False, [None]) 1064 finally: 1065 self.SetMarkReflectSysctls(0) 1066 1067 1068class UidRoutingTest(multinetwork_base.MultiNetworkBaseTest): 1069 """Tests that per-UID routing works properly. 1070 1071 Relevant kernel commits: 1072 upstream net-next: 1073 7d99569460 net: ipv4: Don't crash if passing a null sk to ip_do_redirect. 1074 d109e61bfe net: ipv4: Don't crash if passing a null sk to ip_rt_update_pmtu. 1075 35b80733b3 net: core: add missing check for uid_range in rule_exists. 1076 e2d118a1cb net: inet: Support UID-based routing in IP protocols. 1077 622ec2c9d5 net: core: add UID to flows, rules, and routes 1078 86741ec254 net: core: Add a UID field to struct sock. 1079 1080 android-3.18: 1081 b004e79504 net: ipv4: Don't crash if passing a null sk to ip_rt_update_pmtu. 1082 04c0eace81 net: inet: Support UID-based routing in IP protocols. 1083 18c36d7b71 net: core: add UID to flows, rules, and routes 1084 80e3440721 net: core: Add a UID field to struct sock. 1085 fa8cc2c30c Revert "net: core: Support UID-based routing." 1086 b585141890 Revert "Handle 'sk' being NULL in UID-based routing." 1087 5115ab7514 Revert "net: core: fix UID-based routing build" 1088 f9f4281f79 Revert "ANDROID: net: fib: remove duplicate assignment" 1089 1090 android-4.4: 1091 341965cf10 net: ipv4: Don't crash if passing a null sk to ip_rt_update_pmtu. 1092 344afd627c net: inet: Support UID-based routing in IP protocols. 1093 03441d56d8 net: core: add UID to flows, rules, and routes 1094 eb964bdba7 net: core: Add a UID field to struct sock. 1095 9789b697c6 Revert "net: core: Support UID-based routing." 1096 """ 1097 1098 def GetRulesAtPriority(self, version, priority): 1099 rules = self.iproute.DumpRules(version) 1100 out = [(rule, attributes) for rule, attributes in rules 1101 if attributes.get("FRA_PRIORITY", 0) == priority] 1102 return out 1103 1104 def CheckInitialTablesHaveNoUIDs(self, version): 1105 rules = [] 1106 for priority in [0, 32766, 32767]: 1107 rules.extend(self.GetRulesAtPriority(version, priority)) 1108 for _, attributes in rules: 1109 self.assertNotIn("FRA_UID_RANGE", attributes) 1110 1111 def testIPv4InitialTablesHaveNoUIDs(self): 1112 self.CheckInitialTablesHaveNoUIDs(4) 1113 1114 def testIPv6InitialTablesHaveNoUIDs(self): 1115 self.CheckInitialTablesHaveNoUIDs(6) 1116 1117 @staticmethod 1118 def _Random(): 1119 return random.randint(1000000, 2000000) 1120 1121 def CheckGetAndSetRules(self, version): 1122 start, end = tuple(sorted([self._Random(), self._Random()])) 1123 table = self._Random() 1124 priority = self._Random() 1125 1126 # Can't create a UID range to UID -1 because -1 is INVALID_UID... 1127 self.assertRaisesErrno( 1128 errno.EINVAL, 1129 self.iproute.UidRangeRule, version, True, 100, 0xffffffff, table, 1130 priority) 1131 1132 # ... but -2 is valid. 1133 self.iproute.UidRangeRule(version, True, 100, 0xfffffffe, table, priority) 1134 self.iproute.UidRangeRule(version, False, 100, 0xfffffffe, table, priority) 1135 1136 try: 1137 # Create a UID range rule. 1138 self.iproute.UidRangeRule(version, True, start, end, table, priority) 1139 1140 # Check that deleting the wrong UID range doesn't work. 1141 self.assertRaisesErrno( 1142 errno.ENOENT, 1143 self.iproute.UidRangeRule, version, False, start, end + 1, table, 1144 priority) 1145 self.assertRaisesErrno(errno.ENOENT, 1146 self.iproute.UidRangeRule, version, False, start + 1, end, table, 1147 priority) 1148 1149 # Check that the UID range appears in dumps. 1150 rules = self.GetRulesAtPriority(version, priority) 1151 self.assertTrue(rules) 1152 _, attributes = rules[-1] 1153 self.assertEqual(priority, attributes["FRA_PRIORITY"]) 1154 uidrange = attributes["FRA_UID_RANGE"] 1155 self.assertEqual(start, uidrange.start) 1156 self.assertEqual(end, uidrange.end) 1157 self.assertEqual(table, attributes["FRA_TABLE"]) 1158 finally: 1159 self.iproute.UidRangeRule(version, False, start, end, table, priority) 1160 self.assertRaisesErrno( 1161 errno.ENOENT, 1162 self.iproute.UidRangeRule, version, False, start, end, table, 1163 priority) 1164 1165 fwmask = 0xfefefefe 1166 try: 1167 # Create a rule without a UID range. 1168 self.iproute.FwmarkRule(version, True, 300, fwmask, 301, priority + 1) 1169 1170 # Check it doesn't have a UID range. 1171 rules = self.GetRulesAtPriority(version, priority + 1) 1172 self.assertTrue(rules) 1173 for _, attributes in rules: 1174 self.assertIn("FRA_TABLE", attributes) 1175 self.assertNotIn("FRA_UID_RANGE", attributes) 1176 finally: 1177 self.iproute.FwmarkRule(version, False, 300, fwmask, 301, priority + 1) 1178 1179 # Test that EEXIST worksfor UID range rules too. 1180 ranges = [(100, 101), (100, 102), (99, 101), (1234, 5678)] 1181 dup = ranges[0] 1182 try: 1183 # Check that otherwise identical rules with different UID ranges can be 1184 # created without EEXIST. 1185 for start, end in ranges: 1186 self.iproute.UidRangeRule(version, True, start, end, table, priority) 1187 # ... but EEXIST is returned if the UID range is identical. 1188 self.assertRaisesErrno( 1189 errno.EEXIST, 1190 self.iproute.UidRangeRule, version, True, dup[0], dup[1], table, 1191 priority) 1192 finally: 1193 # Clean up. 1194 for start, end in ranges + [dup]: 1195 try: 1196 self.iproute.UidRangeRule(version, False, start, end, table, 1197 priority) 1198 except IOError: 1199 pass 1200 1201 def testIPv4GetAndSetRules(self): 1202 self.CheckGetAndSetRules(4) 1203 1204 def testIPv6GetAndSetRules(self): 1205 self.CheckGetAndSetRules(6) 1206 1207 def testDeleteErrno(self): 1208 for version in [4, 6]: 1209 table = self._Random() 1210 priority = self._Random() 1211 self.assertRaisesErrno( 1212 errno.EINVAL, 1213 self.iproute.UidRangeRule, version, False, 100, 0xffffffff, table, 1214 priority) 1215 1216 def ExpectNoRoute(self, addr, oif, mark, uid): 1217 # The lack of a route may be either an error, or an unreachable route. 1218 try: 1219 routes = self.iproute.GetRoutes(addr, oif, mark, uid) 1220 rtmsg, _ = routes[0] 1221 self.assertEqual(iproute.RTN_UNREACHABLE, rtmsg.type) 1222 except IOError as e: 1223 if int(e.errno) != int(errno.ENETUNREACH): 1224 raise e 1225 1226 def ExpectRoute(self, addr, oif, mark, uid): 1227 routes = self.iproute.GetRoutes(addr, oif, mark, uid) 1228 rtmsg, _ = routes[0] 1229 self.assertEqual(iproute.RTN_UNICAST, rtmsg.type) 1230 1231 def CheckGetRoute(self, version, addr): 1232 self.ExpectNoRoute(addr, 0, 0, 0) 1233 for netid in self.NETIDS: 1234 uid = self.UidForNetid(netid) 1235 self.ExpectRoute(addr, 0, 0, uid) 1236 self.ExpectNoRoute(addr, 0, 0, 0) 1237 1238 def testIPv4RouteGet(self): 1239 self.CheckGetRoute(4, net_test.IPV4_ADDR) 1240 1241 def testIPv6RouteGet(self): 1242 self.CheckGetRoute(6, net_test.IPV6_ADDR) 1243 1244 def testChangeFdAttributes(self): 1245 netid = random.choice(self.NETIDS) 1246 uid = self._Random() 1247 table = self._TableForNetid(netid) 1248 remoteaddr = self.GetRemoteAddress(6) 1249 s = socket(AF_INET6, SOCK_DGRAM, 0) 1250 1251 def CheckSendFails(): 1252 self.assertRaisesErrno(errno.ENETUNREACH, 1253 s.sendto, b"foo", (remoteaddr, 53)) 1254 def CheckSendSucceeds(): 1255 self.assertEqual(len(b"foo"), s.sendto(b"foo", (remoteaddr, 53))) 1256 1257 CheckSendFails() 1258 self.iproute.UidRangeRule(6, True, uid, uid, table, self.PRIORITY_UID) 1259 try: 1260 CheckSendFails() 1261 os.fchown(s.fileno(), uid, -1) 1262 CheckSendSucceeds() 1263 os.fchown(s.fileno(), -1, -1) 1264 CheckSendSucceeds() 1265 os.fchown(s.fileno(), -1, 12345) 1266 CheckSendSucceeds() 1267 os.fchmod(s.fileno(), 0o777) 1268 CheckSendSucceeds() 1269 os.fchown(s.fileno(), 0, -1) 1270 CheckSendFails() 1271 finally: 1272 self.iproute.UidRangeRule(6, False, uid, uid, table, self.PRIORITY_UID) 1273 s.close() 1274 1275 1276class RulesTest(net_test.NetworkTest): 1277 1278 RULE_PRIORITY = 99999 1279 FWMASK = 0xffffffff 1280 1281 def setUp(self): 1282 self.iproute = iproute.IPRoute() 1283 for version in [4, 6]: 1284 self.iproute.DeleteRulesAtPriority(version, self.RULE_PRIORITY) 1285 1286 def tearDown(self): 1287 for version in [4, 6]: 1288 self.iproute.DeleteRulesAtPriority(version, self.RULE_PRIORITY) 1289 1290 def testRuleDeletionMatchesTable(self): 1291 for version in [4, 6]: 1292 # Add rules with mark 300 pointing at tables 301 and 302. 1293 # This checks for a kernel bug where deletion request for tables > 256 1294 # ignored the table. 1295 self.iproute.FwmarkRule(version, True, 300, self.FWMASK, 301, 1296 priority=self.RULE_PRIORITY) 1297 self.iproute.FwmarkRule(version, True, 300, self.FWMASK, 302, 1298 priority=self.RULE_PRIORITY) 1299 # Delete rule with mark 300 pointing at table 302. 1300 self.iproute.FwmarkRule(version, False, 300, self.FWMASK, 302, 1301 priority=self.RULE_PRIORITY) 1302 # Check that the rule pointing at table 301 is still around. 1303 attributes = [a for _, a in self.iproute.DumpRules(version) 1304 if a.get("FRA_PRIORITY", 0) == self.RULE_PRIORITY] 1305 self.assertEqual(1, len(attributes)) 1306 self.assertEqual(301, attributes[0]["FRA_TABLE"]) 1307 1308 1309if __name__ == "__main__": 1310 unittest.main() 1311