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
566class RIOTest(multinetwork_base.MultiNetworkBaseTest):
567  """Test for IPv6 RFC 4191 route information option
568
569  Relevant kernel commits:
570    upstream:
571      f104a567e673 ipv6: use rt6_get_dflt_router to get default router in rt6_route_rcv
572      bbea124bc99d net: ipv6: Add sysctl for minimum prefix len acceptable in RIOs.
573
574    android-4.9:
575      d860b2e8a7f1 FROMLIST: net: ipv6: Add sysctl for minimum prefix len acceptable in RIOs
576
577    android-4.4:
578      e953f89b8563 net: ipv6: Add sysctl for minimum prefix len acceptable in RIOs.
579
580    android-4.1:
581      84f2f47716cd net: ipv6: Add sysctl for minimum prefix len acceptable in RIOs.
582
583    android-3.18:
584      65f8936934fa net: ipv6: Add sysctl for minimum prefix len acceptable in RIOs.
585
586    android-3.10:
587      161e88ebebc7 net: ipv6: Add sysctl for minimum prefix len acceptable in RIOs.
588
589  """
590
591  def setUp(self):
592    super(RIOTest, self).setUp()
593    self.NETID = random.choice(self.NETIDS)
594    self.IFACE = self.GetInterfaceName(self.NETID)
595    # return sysctls to default values before each test case
596    self.SetAcceptRaRtInfoMinPlen(0)
597    self.SetAcceptRaRtInfoMaxPlen(0)
598    if multinetwork_base.HAVE_ACCEPT_RA_MIN_LFT:
599      self.SetAcceptRaMinLft(0)
600    if multinetwork_base.HAVE_RA_HONOR_PIO_LIFE:
601      self.SetRaHonorPioLife(0)
602
603  def GetRoutingTable(self):
604    if multinetwork_base.HAVE_AUTOCONF_TABLE:
605      return self._TableForNetid(self.NETID)
606    else:
607      # main table
608      return 254
609
610  def SetAcceptRaRtInfoMinPlen(self, plen):
611    self.SetSysctl(
612        "/proc/sys/net/ipv6/conf/%s/accept_ra_rt_info_min_plen"
613        % self.IFACE, plen)
614
615  def GetAcceptRaRtInfoMinPlen(self):
616    return int(self.GetSysctl(
617        "/proc/sys/net/ipv6/conf/%s/accept_ra_rt_info_min_plen" % self.IFACE))
618
619  def SetAcceptRaRtInfoMaxPlen(self, plen):
620    self.SetSysctl(
621        "/proc/sys/net/ipv6/conf/%s/accept_ra_rt_info_max_plen"
622        % self.IFACE, plen)
623
624  def GetAcceptRaRtInfoMaxPlen(self):
625    return int(self.GetSysctl(
626        "/proc/sys/net/ipv6/conf/%s/accept_ra_rt_info_max_plen" % self.IFACE))
627
628  def SetAcceptRaMinLft(self, min_lft):
629    self.SetSysctl(
630        "/proc/sys/net/ipv6/conf/%s/accept_ra_min_lft" % self.IFACE, min_lft)
631
632  def GetAcceptRaMinLft(self):
633    return int(self.GetSysctl(
634        "/proc/sys/net/ipv6/conf/%s/accept_ra_min_lft" % self.IFACE))
635
636  def SetRaHonorPioLife(self, enabled):
637    self.SetSysctl(
638        "/proc/sys/net/ipv6/conf/%s/ra_honor_pio_life" % self.IFACE, enabled)
639
640  def GetRaHonorPioLife(self):
641    return int(self.GetSysctl(
642        "/proc/sys/net/ipv6/conf/%s/ra_honor_pio_life" % self.IFACE))
643
644  def SendRIO(self, rtlifetime, plen, prefix, prf):
645    options = scapy.ICMPv6NDOptRouteInfo(rtlifetime=rtlifetime, plen=plen,
646                                         prefix=prefix, prf=prf)
647    self.SendRA(self.NETID, options=(options,))
648
649  def FindRoutesWithDestination(self, destination):
650    canonical = net_test.CanonicalizeIPv6Address(destination)
651    return [r for _, r in self.iproute.DumpRoutes(6, self.GetRoutingTable())
652            if ('RTA_DST' in r and r['RTA_DST'] == canonical)]
653
654  def FindRoutesWithGateway(self):
655    return [r for _, r in self.iproute.DumpRoutes(6, self.GetRoutingTable())
656            if 'RTA_GATEWAY' in r]
657
658  def CountRoutes(self):
659    return len(self.iproute.DumpRoutes(6, self.GetRoutingTable()))
660
661  def GetRouteExpiration(self, route):
662    return float(route['RTA_CACHEINFO'].expires) / 100.0
663
664  def AssertExpirationInRange(self, routes, lifetime, epsilon):
665    self.assertTrue(routes)
666    found = False
667    # Assert that at least one route in routes has the expected lifetime
668    for route in routes:
669      expiration = self.GetRouteExpiration(route)
670      if expiration < lifetime - epsilon:
671        continue
672      if expiration > lifetime + epsilon:
673        continue
674      found = True
675    self.assertTrue(found)
676
677  def DelRA6(self, prefix, plen):
678    version = 6
679    netid = self.NETID
680    table = self._TableForNetid(netid)
681    router = self._RouterAddress(netid, version)
682    ifindex = self.ifindices[netid]
683    self.iproute._Route(version, iproute.RTPROT_RA, iproute.RTM_DELROUTE,
684                        table, prefix, plen, router, ifindex, None, None)
685
686  def testSetAcceptRaRtInfoMinPlen(self):
687    for plen in range(-1, 130):
688      self.SetAcceptRaRtInfoMinPlen(plen)
689      self.assertEqual(plen, self.GetAcceptRaRtInfoMinPlen())
690
691  def testSetAcceptRaRtInfoMaxPlen(self):
692    for plen in range(-1, 130):
693      self.SetAcceptRaRtInfoMaxPlen(plen)
694      self.assertEqual(plen, self.GetAcceptRaRtInfoMaxPlen())
695
696  @unittest.skipUnless(multinetwork_base.HAVE_AUTOCONF_TABLE,
697                       "need support for per-table autoconf")
698  def testZeroRtLifetime(self):
699    PREFIX = "2001:db8:8901:2300::"
700    RTLIFETIME = 73500
701    PLEN = 56
702    PRF = 0
703    self.SetAcceptRaRtInfoMaxPlen(PLEN)
704    self.SendRIO(RTLIFETIME, PLEN, PREFIX, PRF)
705    # Give the kernel time to notice our RA
706    time.sleep(0.01)
707    self.assertTrue(self.FindRoutesWithDestination(PREFIX))
708    # RIO with rtlifetime = 0 should remove from routing table
709    self.SendRIO(0, PLEN, PREFIX, PRF)
710    # Give the kernel time to notice our RA
711    time.sleep(0.01)
712    self.assertFalse(self.FindRoutesWithDestination(PREFIX))
713
714  def testMinPrefixLenRejection(self):
715    PREFIX = "2001:db8:8902:2345::"
716    RTLIFETIME = 70372
717    PRF = 0
718    # sweep from high to low to avoid spurious failures from late arrivals.
719    for plen in range(130, 1, -1):
720      self.SetAcceptRaRtInfoMinPlen(plen)
721      # RIO with plen < min_plen should be ignored
722      self.SendRIO(RTLIFETIME, plen - 1, PREFIX, PRF)
723    # Give the kernel time to notice our RAs
724    time.sleep(0.1)
725    # Expect no routes
726    routes = self.FindRoutesWithDestination(PREFIX)
727    self.assertFalse(routes)
728
729  def testMaxPrefixLenRejection(self):
730    PREFIX = "2001:db8:8903:2345::"
731    RTLIFETIME = 73078
732    PRF = 0
733    # sweep from low to high to avoid spurious failures from late arrivals.
734    for plen in range(-1, 128, 1):
735      self.SetAcceptRaRtInfoMaxPlen(plen)
736      # RIO with plen > max_plen should be ignored
737      self.SendRIO(RTLIFETIME, plen + 1, PREFIX, PRF)
738    # Give the kernel time to notice our RAs
739    time.sleep(0.1)
740    # Expect no routes
741    routes = self.FindRoutesWithDestination(PREFIX)
742    self.assertFalse(routes)
743
744  @unittest.skipUnless(multinetwork_base.HAVE_AUTOCONF_TABLE,
745                       "need support for per-table autoconf")
746  def testSimpleAccept(self):
747    PREFIX = "2001:db8:8904:2345::"
748    RTLIFETIME = 9993
749    PRF = 0
750    PLEN = 56
751    self.SetAcceptRaRtInfoMinPlen(48)
752    self.SetAcceptRaRtInfoMaxPlen(64)
753    self.SendRIO(RTLIFETIME, PLEN, PREFIX, PRF)
754    # Give the kernel time to notice our RA
755    time.sleep(0.01)
756    routes = self.FindRoutesWithGateway()
757    self.AssertExpirationInRange(routes, RTLIFETIME, 1)
758    self.DelRA6(PREFIX, PLEN)
759
760  @unittest.skipUnless(multinetwork_base.HAVE_AUTOCONF_TABLE,
761                       "need support for per-table autoconf")
762  def testEqualMinMaxAccept(self):
763    PREFIX = "2001:db8:8905:2345::"
764    RTLIFETIME = 6326
765    PLEN = 21
766    PRF = 0
767    self.SetAcceptRaRtInfoMinPlen(PLEN)
768    self.SetAcceptRaRtInfoMaxPlen(PLEN)
769    self.SendRIO(RTLIFETIME, PLEN, PREFIX, PRF)
770    # Give the kernel time to notice our RA
771    time.sleep(0.01)
772    routes = self.FindRoutesWithGateway()
773    self.AssertExpirationInRange(routes, RTLIFETIME, 1)
774    self.DelRA6(PREFIX, PLEN)
775
776  @unittest.skipUnless(multinetwork_base.HAVE_AUTOCONF_TABLE,
777                       "need support for per-table autoconf")
778  def testZeroLengthPrefix(self):
779    PREFIX = "2001:db8:8906:2345::"
780    RTLIFETIME = self.RA_VALIDITY * 2
781    PLEN = 0
782    PRF = 0
783    # Max plen = 0 still allows default RIOs!
784    self.SetAcceptRaRtInfoMaxPlen(PLEN)
785    self.SendRA(self.NETID)
786    # Give the kernel time to notice our RA
787    time.sleep(0.01)
788    default = self.FindRoutesWithGateway()
789    self.AssertExpirationInRange(default, self.RA_VALIDITY, 1)
790    # RIO with prefix length = 0, should overwrite default route lifetime
791    # note that the RIO lifetime overwrites the RA lifetime.
792    self.SendRIO(RTLIFETIME, PLEN, PREFIX, PRF)
793    # Give the kernel time to notice our RA
794    time.sleep(0.01)
795    default = self.FindRoutesWithGateway()
796    self.AssertExpirationInRange(default, RTLIFETIME, 1)
797    self.DelRA6(PREFIX, PLEN)
798
799  @unittest.skipUnless(multinetwork_base.HAVE_AUTOCONF_TABLE,
800                       "need support for per-table autoconf")
801  def testManyRIOs(self):
802    RTLIFETIME = 68012
803    PLEN = 56
804    PRF = 0
805    COUNT = 1000
806    baseline = self.CountRoutes()
807    self.SetAcceptRaRtInfoMaxPlen(56)
808    # Send many RIOs compared to the expected number on a healthy system.
809    for i in range(0, COUNT):
810      prefix = "2001:db8:%x:1100::" % i
811      self.SendRIO(RTLIFETIME, PLEN, prefix, PRF)
812    time.sleep(0.1)
813    self.assertEqual(COUNT + baseline, self.CountRoutes())
814    for i in range(0, COUNT):
815      prefix = "2001:db8:%x:1100::" % i
816      self.DelRA6(prefix, PLEN)
817    # Expect that we can return to baseline config without lingering routes.
818    self.assertEqual(baseline, self.CountRoutes())
819
820  # Contextually, testAcceptRa tests do not belong in RIOTest, but as it
821  # turns out, RIOTest has all the useful helpers defined for these tests.
822  # TODO: Rename test class or merge RIOTest with RATest.
823  @unittest.skipUnless(multinetwork_base.HAVE_ACCEPT_RA_MIN_LFT,
824                       "need support for accept_ra_min_lft")
825  def testAcceptRaMinLftReadWrite(self):
826    self.SetAcceptRaMinLft(500)
827    self.assertEqual(500, self.GetAcceptRaMinLft())
828
829  @unittest.skipUnless(multinetwork_base.HAVE_RA_HONOR_PIO_LIFE,
830                       "need support for ra_honor_pio_life")
831  def testRaHonorPioLifeReadWrite(self):
832    self.assertEqual(0, self.GetRaHonorPioLife())
833    self.SetRaHonorPioLife(1)
834    self.assertEqual(1, self.GetRaHonorPioLife())
835
836  @unittest.skipUnless(multinetwork_base.HAVE_RA_HONOR_PIO_LIFE,
837                       "need support for ra_honor_pio_life")
838  def testRaHonorPioLife(self):
839    self.SetRaHonorPioLife(1)
840
841    # Test setup has sent an initial RA -- expire it.
842    self.SendRA(self.NETID, routerlft=0, piolft=0)
843    time.sleep(0.1) # Give the kernel time to notice our RA
844
845    # Assert that the address was deleted.
846    self.assertIsNone(self.MyAddress(6, self.NETID))
847
848  @unittest.skipUnless(multinetwork_base.HAVE_ACCEPT_RA_MIN_LFT,
849                       "need support for accept_ra_min_lft")
850  def testAcceptRaMinLftRouterLifetime(self):
851    self.SetAcceptRaMinLft(500)
852
853    # Test setup has sent an initial RA. Expire it and test that the RA with
854    # lifetime 0 deletes the default route.
855    self.SendRA(self.NETID, routerlft=0, piolft=0)
856    time.sleep(0.1) # Give the kernel time to notice our RA
857    self.assertEqual([], self.FindRoutesWithGateway())
858
859    # RA with lifetime 400 is ignored
860    self.SendRA(self.NETID, routerlft=400)
861    time.sleep(0.1) # Give the kernel time to notice our RA
862    self.assertEqual([], self.FindRoutesWithGateway())
863
864    # RA with lifetime 600 is processed
865    self.SendRA(self.NETID, routerlft=600)
866    time.sleep(0.1) # Give the kernel time to notice our RA
867    # SendRA sets routerlft to 0 if HAVE_AUTOCONF_TABLE is false...
868    # TODO: Fix this correctly.
869    if multinetwork_base.HAVE_AUTOCONF_TABLE:
870      self.assertEqual(1, len(self.FindRoutesWithGateway()))
871
872  @unittest.skipUnless(multinetwork_base.HAVE_ACCEPT_RA_MIN_LFT,
873                       "need support for accept_ra_min_lft")
874  def testAcceptRaMinLftPIOLifetime(self):
875    self.SetAcceptRaMinLft(500)
876
877    # Test setup has sent an initial RA -- expire it.
878    self.SendRA(self.NETID, routerlft=0, piolft=0)
879    time.sleep(0.1) # Give the kernel time to notice our RA
880    # Check that the prefix route was deleted.
881    prefixroutes = self.FindRoutesWithDestination(self.OnlinkPrefix(6, self.NETID))
882    self.assertEqual([], prefixroutes)
883
884    # Sending a 0-lifetime PIO does not cause the address to be deleted, see
885    # rfc2462#section-5.5.3.
886    address = self.MyAddress(6, self.NETID)
887    self.iproute.DelAddress(address, 64, self.ifindices[self.NETID])
888
889    # PIO with lifetime 400 is ignored
890    self.SendRA(self.NETID, piolft=400)
891    time.sleep(0.1) # Give the kernel time to notice our RA
892    self.assertIsNone(self.MyAddress(6, self.NETID))
893
894    # PIO with lifetime 600 is processed
895    self.SendRA(self.NETID, piolft=600)
896    time.sleep(0.1) # Give the kernel time to notice our RA
897    self.assertIsNotNone(self.MyAddress(6, self.NETID))
898
899  @unittest.skipUnless(multinetwork_base.HAVE_ACCEPT_RA_MIN_LFT,
900                       "need support for accept_ra_min_lft")
901  def testAcceptRaMinLftRIOLifetime(self):
902    PREFIX = "2001:db8:8901:2300::"
903    PLEN = 64
904    PRF = 0
905
906    self.SetAcceptRaRtInfoMaxPlen(PLEN)
907    self.SetAcceptRaMinLft(500)
908
909    # RIO with lifetime 400 is ignored
910    self.SendRIO(400, PLEN, PREFIX, PRF)
911    time.sleep(0.1) # Give the kernel time to notice our RA
912    self.assertFalse(self.FindRoutesWithDestination(PREFIX))
913
914    # RIO with lifetime 600 is processed
915    self.SendRIO(600, PLEN, PREFIX, PRF)
916    time.sleep(0.1) # Give the kernel time to notice our RA
917    self.assertTrue(self.FindRoutesWithDestination(PREFIX))
918
919    # RIO with lifetime 0 deletes the route
920    self.SendRIO(0, PLEN, PREFIX, PRF)
921    time.sleep(0.1) # Give the kernel time to notice our RA
922    self.assertFalse(self.FindRoutesWithDestination(PREFIX))
923
924
925class RATest(multinetwork_base.MultiNetworkBaseTest):
926
927  ND_ROUTER_ADVERT = 134
928  ND_OPT_PREF64 = 38
929  Pref64Option = cstruct.Struct("pref64_option", "!BBH12s",
930                                "type length lft_plc prefix")
931
932  # Android Common Kernels are always based off of an LTS release,
933  # skipping this (always failing due to lack of an ACK specific patch) test
934  # on Linus's kernels (and various other upstream dev branches) allows
935  # for easier testing of Linux rc's and various developer trees.
936  @unittest.skipUnless(net_test.IS_STABLE, "not STABLE/LTS kernel")
937  def testHasAutoconfTable(self):
938    self.assertTrue(multinetwork_base.HAVE_AUTOCONF_TABLE)
939
940  def testDoesNotHaveObsoleteSysctl(self):
941    self.assertFalse(os.path.isfile(
942        "/proc/sys/net/ipv6/route/autoconf_table_offset"))
943
944  @unittest.skipUnless(multinetwork_base.HAVE_AUTOCONF_TABLE,
945                       "no support for per-table autoconf")
946  def testPurgeDefaultRouters(self):
947
948    def CheckIPv6Connectivity(expect_connectivity):
949      for netid in self.NETIDS:
950        s = net_test.UDPSocket(AF_INET6)
951        self.SetSocketMark(s, netid)
952        if expect_connectivity:
953          self.assertTrue(s.sendto(UDP_PAYLOAD, (net_test.IPV6_ADDR, 1234)))
954        else:
955          self.assertRaisesErrno(errno.ENETUNREACH, s.sendto, UDP_PAYLOAD,
956                                 (net_test.IPV6_ADDR, 1234))
957        s.close()
958
959    try:
960      CheckIPv6Connectivity(True)
961      self.SetIPv6SysctlOnAllIfaces("accept_ra", 1)
962      self.SetSysctl("/proc/sys/net/ipv6/conf/all/forwarding", 1)
963      CheckIPv6Connectivity(False)
964    finally:
965      self.SetSysctl("/proc/sys/net/ipv6/conf/all/forwarding", 0)
966      for netid in self.NETIDS:
967        self.SendRA(netid)
968      CheckIPv6Connectivity(True)
969
970  def testOnlinkCommunication(self):
971    """Checks that on-link communication goes direct and not through routers."""
972    for netid in self.tuns:
973      # Send a UDP packet to a random on-link destination.
974      s = net_test.UDPSocket(AF_INET6)
975      iface = self.GetInterfaceName(netid)
976      self.BindToDevice(s, iface)
977      # dstaddr can never be our address because GetRandomDestination only fills
978      # in the lower 32 bits, but our address has 0xff in the byte before that
979      # (since it's constructed from the EUI-64 and so has ff:fe in the middle).
980      dstaddr = self.GetRandomDestination(self.OnlinkPrefix(6, netid))
981      s.sendto(UDP_PAYLOAD, (dstaddr, 53))
982
983      # Expect an NS for that destination on the interface.
984      myaddr = self.MyAddress(6, netid)
985      mymac = self.MyMacAddress(netid)
986      desc, expected = packets.NS(myaddr, dstaddr, mymac)
987      msg = "Sending UDP packet to on-link destination: expecting %s" % desc
988      time.sleep(0.0001)  # Required to make the test work on kernel 3.1(!)
989      self.ExpectPacketOn(netid, msg, expected)
990
991      # Send an NA.
992      tgtmac = "02:00:00:00:%02x:99" % netid
993      _, reply = packets.NA(dstaddr, myaddr, tgtmac)
994      # Don't use ReceivePacketOn, since that uses the router's MAC address as
995      # the source. Instead, construct our own Ethernet header with source
996      # MAC of tgtmac.
997      reply = scapy.Ether(src=tgtmac, dst=mymac) / reply
998      self.ReceiveEtherPacketOn(netid, reply)
999
1000      # Expect the kernel to send the original UDP packet now that the ND cache
1001      # entry has been populated.
1002      sport = s.getsockname()[1]
1003      desc, expected = packets.UDP(6, myaddr, dstaddr, sport=sport)
1004      msg = "After NA response, expecting %s" % desc
1005      self.ExpectPacketOn(netid, msg, expected)
1006
1007      s.close()
1008
1009  # This test documents a known issue: routing tables are never deleted.
1010  @unittest.skipUnless(multinetwork_base.HAVE_AUTOCONF_TABLE,
1011                       "no support for per-table autoconf")
1012  def testLeftoverRoutes(self):
1013    def GetNumRoutes():
1014      with open("/proc/net/ipv6_route") as ipv6_route:
1015        return len(ipv6_route.readlines())
1016
1017    num_routes = GetNumRoutes()
1018    for i in range(10, 20):
1019      try:
1020        self.tuns[i] = self.CreateTunInterface(i)
1021        self.SendRA(i)
1022        self.tuns[i].close()
1023      finally:
1024        del self.tuns[i]
1025    self.assertLess(num_routes, GetNumRoutes())
1026
1027  def SendNdUseropt(self, option):
1028    options = scapy.ICMPv6NDOptRouteInfo(rtlifetime=rtlifetime, plen=plen,
1029                                         prefix=prefix, prf=prf)
1030    self.SendRA(self.NETID, options=(options,))
1031
1032  def MakePref64Option(self, prefix, lifetime):
1033    prefix = inet_pton(AF_INET6, prefix)[:12]
1034    lft_plc = (lifetime & 0xfff8) | 0  # 96-bit prefix length
1035    return self.Pref64Option((self.ND_OPT_PREF64, 2, lft_plc, prefix))
1036
1037  def testPref64UserOption(self):
1038    # Open a netlink socket to receive RTM_NEWNDUSEROPT messages.
1039    s = netlink.NetlinkSocket(netlink.NETLINK_ROUTE, iproute.RTMGRP_ND_USEROPT)
1040
1041    # Send an RA with the PREF64 option.
1042    netid = random.choice(self.NETIDS)
1043    opt = self.MakePref64Option("64:ff9b::", 300)
1044    self.SendRA(netid, options=(opt.Pack(),))
1045
1046    # Check that we get an an RTM_NEWNDUSEROPT message on the socket with the
1047    # expected option.
1048    csocket.SetSocketTimeout(s.sock, 100)
1049    try:
1050      data = s._Recv()
1051    except IOError as e:
1052      self.fail("Should have received an RTM_NEWNDUSEROPT message. "
1053                "Please ensure the kernel supports receiving the "
1054                "PREF64 RA option. Error: %s" % e)
1055    s.close()
1056
1057    # Check that the message is received correctly.
1058    nlmsghdr, data = cstruct.Read(data, netlink.NLMsgHdr)
1059    self.assertEqual(iproute.RTM_NEWNDUSEROPT, nlmsghdr.type)
1060
1061    # Check the option contents.
1062    ndopthdr, data = cstruct.Read(data, iproute.NdUseroptMsg)
1063    self.assertEqual(AF_INET6, ndopthdr.family)
1064    self.assertEqual(self.ND_ROUTER_ADVERT, ndopthdr.icmp_type)
1065    self.assertEqual(len(opt), ndopthdr.opts_len)
1066
1067    actual_opt = self.Pref64Option(data)
1068    self.assertEqual(opt, actual_opt)
1069
1070  def testRaFlags(self):
1071    def GetInterfaceIpv6Flags(iface):
1072      attrs = self.iproute.GetIflaAfSpecificData(iface, AF_INET6)
1073      return int(attrs["IFLA_INET6_FLAGS"])
1074
1075    netid = random.choice(self.NETIDS)
1076    iface = self.GetInterfaceName(netid)
1077    expected = iproute.IF_RS_SENT | iproute.IF_RA_RCVD | iproute.IF_READY
1078    self.assertEqual(expected, GetInterfaceIpv6Flags(iface))
1079
1080    self.SendRA(netid, m=1, o=0)
1081    expected |= iproute.IF_RA_MANAGED
1082    self.assertEqual(expected, GetInterfaceIpv6Flags(iface))
1083
1084    self.SendRA(netid, m=1, o=1)
1085    expected |= iproute.IF_RA_OTHERCONF
1086    self.assertEqual(expected, GetInterfaceIpv6Flags(iface))
1087
1088    self.SendRA(netid, m=0, o=1)
1089    expected &= ~iproute.IF_RA_MANAGED
1090    self.assertEqual(expected, GetInterfaceIpv6Flags(iface))
1091
1092
1093class PMTUTest(multinetwork_base.InboundMarkingTest):
1094
1095  PAYLOAD_SIZE = 1400
1096  dstaddrs = set()
1097
1098  def GetSocketMTU(self, version, s):
1099    if version == 6:
1100      ip6_mtuinfo = s.getsockopt(net_test.SOL_IPV6, csocket.IPV6_PATHMTU, 32)
1101      unused_sockaddr, mtu = struct.unpack("=28sI", ip6_mtuinfo)
1102      return mtu
1103    else:
1104      return s.getsockopt(net_test.SOL_IP, csocket.IP_MTU)
1105
1106  def DisableFragmentationAndReportErrors(self, version, s):
1107    if version == 4:
1108      s.setsockopt(net_test.SOL_IP, csocket.IP_MTU_DISCOVER,
1109                   csocket.IP_PMTUDISC_DO)
1110      s.setsockopt(net_test.SOL_IP, net_test.IP_RECVERR, 1)
1111    else:
1112      s.setsockopt(net_test.SOL_IPV6, csocket.IPV6_DONTFRAG, 1)
1113      s.setsockopt(net_test.SOL_IPV6, net_test.IPV6_RECVERR, 1)
1114
1115  def CheckPMTU(self, version, use_connect, modes):
1116
1117    def SendBigPacket(version, s, dstaddr, netid, payload):
1118      if use_connect:
1119        s.send(payload)
1120      else:
1121        self.SendOnNetid(version, s, dstaddr, 1234, netid, payload, [])
1122
1123    for netid in self.tuns:
1124      for mode in modes:
1125        s = self.BuildSocket(version, net_test.UDPSocket, netid, mode)
1126        self.DisableFragmentationAndReportErrors(version, s)
1127
1128        srcaddr = self.MyAddress(version, netid)
1129        dst_prefix, intermediate = {
1130            4: ("172.19.", "172.16.9.12"),
1131            6: ("2001:db8::", "2001:db8::1")
1132        }[version]
1133
1134        # Run this test often enough (e.g., in presubmits), and eventually
1135        # we'll be unlucky enough to pick the same address twice, in which
1136        # case the test will fail because the kernel will already have seen
1137        # the lower MTU. Don't do this.
1138        dstaddr = self.GetRandomDestination(dst_prefix)
1139        while dstaddr in self.dstaddrs:
1140          dstaddr = self.GetRandomDestination(dst_prefix)
1141        self.dstaddrs.add(dstaddr)
1142
1143        if use_connect:
1144          s.connect((dstaddr, 1234))
1145
1146        payload = self.PAYLOAD_SIZE * b"a"
1147
1148        # Send a packet and receive a packet too big.
1149        SendBigPacket(version, s, dstaddr, netid, payload)
1150        received = self.ReadAllPacketsOn(netid)
1151        self.assertEqual(1, len(received),
1152                          "unexpected packets: %s" % received[1:])
1153        _, toobig = packets.ICMPPacketTooBig(version, intermediate, srcaddr,
1154                                             received[0])
1155        self.ReceivePacketOn(netid, toobig)
1156
1157        # Check that another send on the same socket returns EMSGSIZE.
1158        self.assertRaisesErrno(
1159            errno.EMSGSIZE,
1160            SendBigPacket, version, s, dstaddr, netid, payload)
1161
1162        # If this is a connected socket, make sure the socket MTU was set.
1163        # Note that in IPv4 this only started working in Linux 3.6!
1164        if use_connect:
1165          self.assertEqual(packets.PTB_MTU, self.GetSocketMTU(version, s))
1166
1167        s.close()
1168
1169        # Check that other sockets pick up the PMTU we have been told about by
1170        # connecting another socket to the same destination and getting its MTU.
1171        # This new socket can use any method to select its outgoing interface;
1172        # here we use a mark for simplicity.
1173        s2 = self.BuildSocket(version, net_test.UDPSocket, netid, "mark")
1174        s2.connect((dstaddr, 1234))
1175        self.assertEqual(packets.PTB_MTU, self.GetSocketMTU(version, s2))
1176
1177        # Also check the MTU reported by ip route get, this time using the oif.
1178        routes = self.iproute.GetRoutes(dstaddr, self.ifindices[netid], 0, None)
1179        self.assertTrue(routes)
1180        route = routes[0]
1181        rtmsg, attributes = route
1182        self.assertEqual(iproute.RTN_UNICAST, rtmsg.type)
1183        metrics = attributes["RTA_METRICS"]
1184        self.assertEqual(packets.PTB_MTU, metrics["RTAX_MTU"])
1185
1186        s2.close()
1187
1188  def testIPv4BasicPMTU(self):
1189    """Tests IPv4 path MTU discovery.
1190
1191    Relevant kernel commits:
1192      upstream net-next:
1193        6a66271 ipv4, fib: pass LOOPBACK_IFINDEX instead of 0 to flowi4_iif
1194
1195      android-3.10:
1196        4bc64dd ipv4, fib: pass LOOPBACK_IFINDEX instead of 0 to flowi4_iif
1197    """
1198
1199    self.CheckPMTU(4, True, ["mark", "oif"])
1200    self.CheckPMTU(4, False, ["mark", "oif"])
1201
1202  def testIPv6BasicPMTU(self):
1203    self.CheckPMTU(6, True, ["mark", "oif"])
1204    self.CheckPMTU(6, False, ["mark", "oif"])
1205
1206  def testIPv4UIDPMTU(self):
1207    self.CheckPMTU(4, True, ["uid"])
1208    self.CheckPMTU(4, False, ["uid"])
1209
1210  def testIPv6UIDPMTU(self):
1211    self.CheckPMTU(6, True, ["uid"])
1212    self.CheckPMTU(6, False, ["uid"])
1213
1214  # Making Path MTU Discovery work on unmarked  sockets requires that mark
1215  # reflection be enabled. Otherwise the kernel has no way to know what routing
1216  # table the original packet used, and thus it won't be able to clone the
1217  # correct route.
1218
1219  def testIPv4UnmarkedSocketPMTU(self):
1220    self.SetMarkReflectSysctls(1)
1221    try:
1222      self.CheckPMTU(4, False, [None])
1223    finally:
1224      self.SetMarkReflectSysctls(0)
1225
1226  def testIPv6UnmarkedSocketPMTU(self):
1227    self.SetMarkReflectSysctls(1)
1228    try:
1229      self.CheckPMTU(6, False, [None])
1230    finally:
1231      self.SetMarkReflectSysctls(0)
1232
1233
1234class UidRoutingTest(multinetwork_base.MultiNetworkBaseTest):
1235  """Tests that per-UID routing works properly.
1236
1237  Relevant kernel commits:
1238    upstream net-next:
1239      7d99569460 net: ipv4: Don't crash if passing a null sk to ip_do_redirect.
1240      d109e61bfe net: ipv4: Don't crash if passing a null sk to ip_rt_update_pmtu.
1241      35b80733b3 net: core: add missing check for uid_range in rule_exists.
1242      e2d118a1cb net: inet: Support UID-based routing in IP protocols.
1243      622ec2c9d5 net: core: add UID to flows, rules, and routes
1244      86741ec254 net: core: Add a UID field to struct sock.
1245
1246    android-3.18:
1247      b004e79504 net: ipv4: Don't crash if passing a null sk to ip_rt_update_pmtu.
1248      04c0eace81 net: inet: Support UID-based routing in IP protocols.
1249      18c36d7b71 net: core: add UID to flows, rules, and routes
1250      80e3440721 net: core: Add a UID field to struct sock.
1251      fa8cc2c30c Revert "net: core: Support UID-based routing."
1252      b585141890 Revert "Handle 'sk' being NULL in UID-based routing."
1253      5115ab7514 Revert "net: core: fix UID-based routing build"
1254      f9f4281f79 Revert "ANDROID: net: fib: remove duplicate assignment"
1255
1256    android-4.4:
1257      341965cf10 net: ipv4: Don't crash if passing a null sk to ip_rt_update_pmtu.
1258      344afd627c net: inet: Support UID-based routing in IP protocols.
1259      03441d56d8 net: core: add UID to flows, rules, and routes
1260      eb964bdba7 net: core: Add a UID field to struct sock.
1261      9789b697c6 Revert "net: core: Support UID-based routing."
1262  """
1263
1264  def GetRulesAtPriority(self, version, priority):
1265    rules = self.iproute.DumpRules(version)
1266    out = [(rule, attributes) for rule, attributes in rules
1267           if attributes.get("FRA_PRIORITY", 0) == priority]
1268    return out
1269
1270  def CheckInitialTablesHaveNoUIDs(self, version):
1271    rules = []
1272    for priority in [0, 32766, 32767]:
1273      rules.extend(self.GetRulesAtPriority(version, priority))
1274    for _, attributes in rules:
1275      self.assertNotIn("FRA_UID_RANGE", attributes)
1276
1277  def testIPv4InitialTablesHaveNoUIDs(self):
1278    self.CheckInitialTablesHaveNoUIDs(4)
1279
1280  def testIPv6InitialTablesHaveNoUIDs(self):
1281    self.CheckInitialTablesHaveNoUIDs(6)
1282
1283  @staticmethod
1284  def _Random():
1285    return random.randint(1000000, 2000000)
1286
1287  @staticmethod
1288  def _RandomUid(cls):
1289    return random.randint(cls.UID_RANGE_START, cls.UID_RANGE_END)
1290
1291  def CheckGetAndSetRules(self, version):
1292    start, end = tuple(sorted([self._Random(), self._Random()]))
1293    table = self._Random()
1294    priority = self._Random()
1295
1296    # Can't create a UID range to UID -1 because -1 is INVALID_UID...
1297    self.assertRaisesErrno(
1298        errno.EINVAL,
1299        self.iproute.UidRangeRule, version, True, 100, 0xffffffff, table,
1300        priority)
1301
1302    # ... but -2 is valid.
1303    self.iproute.UidRangeRule(version, True, 100, 0xfffffffe, table, priority)
1304    self.iproute.UidRangeRule(version, False, 100, 0xfffffffe, table, priority)
1305
1306    try:
1307      # Create a UID range rule.
1308      self.iproute.UidRangeRule(version, True, start, end, table, priority)
1309
1310      # Check that deleting the wrong UID range doesn't work.
1311      self.assertRaisesErrno(
1312          errno.ENOENT,
1313          self.iproute.UidRangeRule, version, False, start, end + 1, table,
1314          priority)
1315      self.assertRaisesErrno(errno.ENOENT,
1316        self.iproute.UidRangeRule, version, False, start + 1, end, table,
1317        priority)
1318
1319      # Check that the UID range appears in dumps.
1320      rules = self.GetRulesAtPriority(version, priority)
1321      self.assertTrue(rules)
1322      _, attributes = rules[-1]
1323      self.assertEqual(priority, attributes["FRA_PRIORITY"])
1324      uidrange = attributes["FRA_UID_RANGE"]
1325      self.assertEqual(start, uidrange.start)
1326      self.assertEqual(end, uidrange.end)
1327      self.assertEqual(table, attributes["FRA_TABLE"])
1328    finally:
1329      self.iproute.UidRangeRule(version, False, start, end, table, priority)
1330      self.assertRaisesErrno(
1331          errno.ENOENT,
1332          self.iproute.UidRangeRule, version, False, start, end, table,
1333          priority)
1334
1335    fwmask = 0xfefefefe
1336    try:
1337      # Create a rule without a UID range.
1338      self.iproute.FwmarkRule(version, True, 300, fwmask, 301, priority + 1)
1339
1340      # Check it doesn't have a UID range.
1341      rules = self.GetRulesAtPriority(version, priority + 1)
1342      self.assertTrue(rules)
1343      for _, attributes in rules:
1344        self.assertIn("FRA_TABLE", attributes)
1345        self.assertNotIn("FRA_UID_RANGE", attributes)
1346    finally:
1347      self.iproute.FwmarkRule(version, False, 300, fwmask, 301, priority + 1)
1348
1349    # Test that EEXIST worksfor UID range rules too.
1350    ranges = [(100, 101), (100, 102), (99, 101), (1234, 5678)]
1351    dup = ranges[0]
1352    try:
1353      # Check that otherwise identical rules with different UID ranges can be
1354      # created without EEXIST.
1355      for start, end in ranges:
1356        self.iproute.UidRangeRule(version, True, start, end, table, priority)
1357      # ... but EEXIST is returned if the UID range is identical.
1358      self.assertRaisesErrno(
1359        errno.EEXIST,
1360        self.iproute.UidRangeRule, version, True, dup[0], dup[1], table,
1361        priority)
1362    finally:
1363      # Clean up.
1364      for start, end in ranges + [dup]:
1365        try:
1366          self.iproute.UidRangeRule(version, False, start, end, table,
1367                                    priority)
1368        except IOError:
1369          pass
1370
1371  def testIPv4GetAndSetRules(self):
1372    self.CheckGetAndSetRules(4)
1373
1374  def testIPv6GetAndSetRules(self):
1375    self.CheckGetAndSetRules(6)
1376
1377  def testDeleteErrno(self):
1378    for version in [4, 6]:
1379      table = self._Random()
1380      priority = self._Random()
1381      self.assertRaisesErrno(
1382          errno.EINVAL,
1383          self.iproute.UidRangeRule, version, False, 100, 0xffffffff, table,
1384          priority)
1385
1386  def ExpectNoRoute(self, addr, oif, mark, uid):
1387    # The lack of a route may be either an error, or an unreachable route.
1388    try:
1389      routes = self.iproute.GetRoutes(addr, oif, mark, uid)
1390      rtmsg, _ = routes[0]
1391      self.assertEqual(iproute.RTN_UNREACHABLE, rtmsg.type)
1392    except IOError as e:
1393      if int(e.errno) != int(errno.ENETUNREACH):
1394        raise e
1395
1396  def ExpectRoute(self, addr, oif, mark, uid):
1397    routes = self.iproute.GetRoutes(addr, oif, mark, uid)
1398    rtmsg, _ = routes[0]
1399    self.assertEqual(iproute.RTN_UNICAST, rtmsg.type)
1400
1401  def CheckGetRoute(self, version, addr):
1402    self.ExpectNoRoute(addr, 0, 0, 0)
1403    for netid in self.NETIDS:
1404      uid = self.UidForNetid(netid)
1405      self.ExpectRoute(addr, 0, 0, uid)
1406    self.ExpectNoRoute(addr, 0, 0, 0)
1407
1408  def testIPv4RouteGet(self):
1409    self.CheckGetRoute(4, net_test.IPV4_ADDR)
1410
1411  def testIPv6RouteGet(self):
1412    self.CheckGetRoute(6, net_test.IPV6_ADDR)
1413
1414  def testChangeFdAttributes(self):
1415    netid = random.choice(self.NETIDS)
1416    uid = self._RandomUid(self)
1417    table = self._TableForNetid(netid)
1418    remoteaddr = self.GetRemoteAddress(6)
1419    s = socket(AF_INET6, SOCK_DGRAM, 0)
1420
1421    def CheckSendFails():
1422      self.assertRaisesErrno(errno.ENETUNREACH,
1423                             s.sendto, b"foo", (remoteaddr, 53))
1424    def CheckSendSucceeds():
1425      self.assertEqual(len(b"foo"), s.sendto(b"foo", (remoteaddr, 53)))
1426
1427    CheckSendFails()
1428    self.iproute.UidRangeRule(6, True, uid, uid, table, self.PRIORITY_UID)
1429    try:
1430      CheckSendFails()
1431      os.fchown(s.fileno(), uid, -1)
1432      CheckSendSucceeds()
1433      os.fchown(s.fileno(), -1, -1)
1434      CheckSendSucceeds()
1435      os.fchown(s.fileno(), -1, 12345)
1436      CheckSendSucceeds()
1437      os.fchmod(s.fileno(), 0o777)
1438      CheckSendSucceeds()
1439      os.fchown(s.fileno(), 0, -1)
1440      CheckSendFails()
1441    finally:
1442      self.iproute.UidRangeRule(6, False, uid, uid, table, self.PRIORITY_UID)
1443      s.close()
1444
1445
1446class RulesTest(net_test.NetworkTest):
1447
1448  RULE_PRIORITY = 99999
1449  FWMASK = 0xffffffff
1450
1451  def setUp(self):
1452    self.iproute = iproute.IPRoute()
1453    for version in [4, 6]:
1454      self.iproute.DeleteRulesAtPriority(version, self.RULE_PRIORITY)
1455
1456  def tearDown(self):
1457    for version in [4, 6]:
1458      self.iproute.DeleteRulesAtPriority(version, self.RULE_PRIORITY)
1459
1460  def testRuleDeletionMatchesTable(self):
1461    for version in [4, 6]:
1462      # Add rules with mark 300 pointing at tables 301 and 302.
1463      # This checks for a kernel bug where deletion request for tables > 256
1464      # ignored the table.
1465      self.iproute.FwmarkRule(version, True, 300, self.FWMASK, 301,
1466                              priority=self.RULE_PRIORITY)
1467      self.iproute.FwmarkRule(version, True, 300, self.FWMASK, 302,
1468                              priority=self.RULE_PRIORITY)
1469      # Delete rule with mark 300 pointing at table 302.
1470      self.iproute.FwmarkRule(version, False, 300, self.FWMASK, 302,
1471                              priority=self.RULE_PRIORITY)
1472      # Check that the rule pointing at table 301 is still around.
1473      attributes = [a for _, a in self.iproute.DumpRules(version)
1474                    if a.get("FRA_PRIORITY", 0) == self.RULE_PRIORITY]
1475      self.assertEqual(1, len(attributes))
1476      self.assertEqual(301, attributes[0]["FRA_TABLE"])
1477
1478
1479if __name__ == "__main__":
1480  unittest.main()
1481