def main():
    parser = argparse.ArgumentParser(
        "frag6.py", description="IPv6 fragementation test tool")
    parser.add_argument(
        '--sendif',
        nargs=1,
        required=True,
        help='The interface through which the packet will be sent')
    parser.add_argument('--recvif',
                        nargs=1,
                        required=True,
                        help='The interface on which to check for the packet')
    parser.add_argument('--src',
                        nargs=1,
                        required=True,
                        help='The source IP address')
    parser.add_argument('--to',
                        nargs=1,
                        required=True,
                        help='The destination IP address')
    parser.add_argument('--debug',
                        required=False,
                        action='store_true',
                        help='Enable test debugging')

    args = parser.parse_args()

    # Start sniffing on recvif
    sniffer = Sniffer(args, check_icmp6_error)

    ########################################################################
    #
    # 0-byte first fragment.
    #
    # A:  0-byte fragment payload not allowed. Discarded.
    # R:  ICMPv6 param prob, paramprob header.
    #
    ip6f01 = sp.Ether() / \
     sp.IPv6(src=args.src[0], dst=args.to[0]) / \
     sp.IPv6ExtHdrFragment(offset=0, m=1, id=4)
    if args.debug:
        ip6f01.display()
    sp.sendp(ip6f01, iface=args.sendif[0], verbose=False)

    sleep(0.10)
    sniffer.setEnd()
    sniffer.join()
    if not sniffer.foundCorrectPacket:
        sys.exit(1)

    sys.exit(0)
Example #2
0
def main():
	parser = argparse.ArgumentParser("frag6.py",
		description="IPv6 fragementation test tool")
	parser.add_argument('--sendif', nargs=1,
		required=True,
		help='The interface through which the packet will be sent')
	parser.add_argument('--recvif', nargs=1,
		required=True,
		help='The interface on which to check for the packet')
	parser.add_argument('--src', nargs=1,
		required=True,
		help='The source IP address')
	parser.add_argument('--to', nargs=1,
		required=True,
		help='The destination IP address')
	parser.add_argument('--debug',
		required=False, action='store_true',
		help='Enable test debugging')

	args = parser.parse_args()


	########################################################################
	#
	# Send a sample of pseudo-random fragments into the system in order
	# to test vnet teardown.
	#
	# A:  Cleaned up and freed
	# R:  No panic (ignoring everything else)
	#

	random.seed()
	packets = [];

	for i in range(0,127):
		fid=random.randint(0,0xffff)
		foffset=random.randint(0,0xffff)
		fm=random.randint(0,1)
		fsrc=sp.RandIP6()
		ip6f01 = sp.Ether() / \
			sp.IPv6(src=fsrc, dst=args.to[0]) / \
			sp.IPv6ExtHdrFragment(offset=foffset, m=fm, id=fid) / \
			sp.UDP(dport=3456, sport=6543)
		if args.debug:
			ip6f01.display()
		packets.append(ip6f01)

	for p in packets:
		sp.sendp(p, iface=args.sendif[0], verbose=False)

	sys.exit(0)
Example #3
0
def main():
	parser = argparse.ArgumentParser("frag6.py",
		description="IPv6 fragementation test tool")
	parser.add_argument('--sendif', nargs=1,
		required=True,
		help='The interface through which the packet will be sent')
	parser.add_argument('--recvif', nargs=1,
		required=True,
		help='The interface on which to check for the packet')
	parser.add_argument('--src', nargs=1,
		required=True,
		help='The source IP address')
	parser.add_argument('--to', nargs=1,
		required=True,
		help='The destination IP address')
	parser.add_argument('--debug',
		required=False, action='store_true',
		help='Enable test debugging')

	args = parser.parse_args()


	# Start sniffing on recvif
	sniffer = Sniffer(args, check_icmp6_error)


	########################################################################
	#
	# A single start fragment with payload.
	#
	# A:  Waiting for more data.
	# R:  Timeout / Expiry.
	#
	data = "6" * 1280
	ip6f01 = sp.Ether() / \
		sp.IPv6(src=args.src[0], dst=args.to[0]) / \
		sp.IPv6ExtHdrFragment(offset=0, m=1, id=3) / \
		sp.UDP(dport=3456, sport=6543) / \
		data
	if args.debug :
		ip6f01.display()
	sp.sendp(ip6f01, iface=args.sendif[0], verbose=False)

	# Wait for ICMPv6 error generation on timeout.
	sleep(75)
	sniffer.setEnd()
	sniffer.join()
	if not sniffer.foundCorrectPacket:
		sys.exit(1)

	sys.exit(0)
def main():
    parser = argparse.ArgumentParser(
        "frag6.py", description="IPv6 fragementation test tool")
    parser.add_argument(
        '--sendif',
        nargs=1,
        required=True,
        help='The interface through which the packet will be sent')
    parser.add_argument('--recvif',
                        nargs=1,
                        required=True,
                        help='The interface on which to check for the packet')
    parser.add_argument('--src',
                        nargs=1,
                        required=True,
                        help='The source IP address')
    parser.add_argument('--to',
                        nargs=1,
                        required=True,
                        help='The destination IP address')
    parser.add_argument('--debug',
                        required=False,
                        action='store_true',
                        help='Enable test debugging')

    args = parser.parse_args()

    ########################################################################
    #
    # Send a sample of sequeneced ID fragments into the system in order
    # to test bucket distribution.
    #
    # A:  No overflow at V_ip6_maxfragsperpacket == 64.
    # R:  Stats only, timeout and no ICMPv6 (all ignored).
    #
    packets = []
    data = "66666666"
    for i in range(0, 127):
        ip6f01 = sp.Ether() / \
         sp.IPv6(src=args.src[0], dst=args.to[0]) / \
         sp.IPv6ExtHdrFragment(offset=1, m=1, id=i) / \
         data
        if args.debug:
            ip6f01.display()
        packets.append(ip6f01)

    for p in packets:
        sp.sendp(p, iface=args.sendif[0], verbose=False)

    sys.exit(0)
Example #5
0
def main():
    parser = argparse.ArgumentParser(
        "frag6.py", description="IPv6 fragementation test tool")
    parser.add_argument(
        '--sendif',
        nargs=1,
        required=True,
        help='The interface through which the packet will be sent')
    parser.add_argument('--recvif',
                        nargs=1,
                        required=True,
                        help='The interface on which to check for the packet')
    parser.add_argument('--src',
                        nargs=1,
                        required=True,
                        help='The source IP address')
    parser.add_argument('--to',
                        nargs=1,
                        required=True,
                        help='The destination IP address')
    parser.add_argument('--debug',
                        required=False,
                        action='store_true',
                        help='Enable test debugging')

    args = parser.parse_args()

    ########################################################################
    #
    # Sysctl set to accept (no|maximum 10) fragments.
    #
    # A:  Discarded.
    # R:  Silence (statistics only) or ICMPv6 timeout expiry.
    #
    data = "6" * 1280
    bfid = 0x5001
    for i in range(20):
        fid = bfid + i
        ip6f01 = sp.Ether() / \
         sp.IPv6(src=args.src[0], dst=args.to[0]) / \
         sp.IPv6ExtHdrFragment(offset=0, m=1, id=fid) / \
         sp.UDP(dport=3456, sport=6543) / \
         data
        if args.debug:
            ip6f01.display()
        sp.sendp(ip6f01, iface=args.sendif[0], verbose=False)

    # Wait for possible expiry to happen.
    sleep(75)
    sys.exit(0)
Example #6
0
def get_rstpkt(pkt):
    fake_pkt = None
    if (pkt.ipv4):
        fake_pkt = sp.IP(dst=pkt.src_addr, src=pkt.dst_addr) / sp.TCP(
            dport=pkt.src_port, sport=pkt.dst_port)
    else:
        fake_pkt = sp.IPv6(dst=pkt.src_addr, src=pkt.dst_addr) / sp.TCP(
            dport=pkt.src_port, sport=pkt.dst_port)

    fake_pkt[sp.TCP].flags = 'AR'
    fake_pkt[sp.TCP].ack = pkt.tcp.seq_num + 1
    fake_pkt[sp.TCP].seq = pkt.tcp.ack_num + 1
    fake_pkt[sp.TCP].window = 0
    return fake_pkt
Example #7
0
def check_tcp_rst(args, packet):
    ip6 = packet.getlayer(sp.IPv6)
    if not ip6:
        return False
    oip6 = sp.IPv6(src=args.src[0], dst=args.to[0])
    if ip6.dst != oip6.src:
        return False
    tcp = packet.getlayer(sp.TCP)
    if not tcp:
        return False
    # Is TCP RST?
    if tcp.flags & 0x04:
        #tcp.display()
        return True
    return False
def ICMPPacketTooBig(version, srcaddr, dstaddr, packet):
    if version == 4:
        desc = "ICMPv4 fragmentation needed"
        pkt = (scapy.IP(src=srcaddr, dst=dstaddr, proto=1) /
               scapy.ICMPerror(type=3, code=4) / str(packet)[:64])
        # Only newer versions of scapy understand that since RFC 1191, the last two
        # bytes of a fragmentation needed ICMP error contain the MTU.
        if hasattr(scapy.ICMP, "nexthopmtu"):
            pkt[scapy.ICMPerror].nexthopmtu = PTB_MTU
        else:
            pkt[scapy.ICMPerror].unused = PTB_MTU
        return desc, pkt
    else:
        return ("ICMPv6 Packet Too Big", scapy.IPv6(src=srcaddr, dst=dstaddr) /
                scapy.ICMPv6PacketTooBig(mtu=PTB_MTU) / str(packet)[:1232])
Example #9
0
def create_ns(dst_ip, dst_mac, src_ip=None, src_mac=None, tgt_ip=None):
    # Solicitation
    if src_ip is None:
        src_ip = mac2ipv6(router_mac)
    if src_mac is None:
        src_mac = router_mac
    if tgt_ip is None:
        tgt_ip = dst_ip
    ether_head = scapy.Ether(dst=dst_mac, src=src_mac)
    # With solicited node multicast
    ipv6_head = scapy.IPv6(src=src_ip, dst=make_sn_mc(dst_ip))
    icmpv6_ns = scapy.ICMPv6ND_NS(tgt=tgt_ip)
    icmpv6_opt_pref = scapy.ICMPv6NDOptSrcLLAddr(lladdr=src_mac)
    sol = (ether_head / ipv6_head / icmpv6_ns / icmpv6_opt_pref)

    return sol
def main():
    parser = argparse.ArgumentParser(
        "frag6.py", description="IPv6 fragementation test tool")
    parser.add_argument(
        '--sendif',
        nargs=1,
        required=True,
        help='The interface through which the packet will be sent')
    parser.add_argument('--recvif',
                        nargs=1,
                        required=True,
                        help='The interface on which to check for the packet')
    parser.add_argument('--src',
                        nargs=1,
                        required=True,
                        help='The source IP address')
    parser.add_argument('--to',
                        nargs=1,
                        required=True,
                        help='The destination IP address')
    parser.add_argument('--debug',
                        required=False,
                        action='store_true',
                        help='Enable test debugging')

    args = parser.parse_args()

    ########################################################################
    #
    # A single last fragment.
    #
    # A:  Waiting for more data.
    # R:  Timeout / Expiry.
    #
    ip6f01 = sp.Ether() / \
     sp.IPv6(src=args.src[0], dst=args.to[0]) / \
     sp.IPv6ExtHdrFragment(offset=321, m=0, id=8) / \
     sp.UDP(dport=3456, sport=6543)
    if args.debug:
        ip6f01.display()
    sp.sendp(ip6f01, iface=args.sendif[0], verbose=False)

    # Wait for expiration to happen.  We will not see an ICMPv6 as there
    # is no frag with offset=0.
    sleep(75)

    sys.exit(0)
Example #11
0
def main():
	parser = argparse.ArgumentParser("scapyi386.py",
		description="IPv6 Ethernet Dest MAC test")
	parser.add_argument('--sendif', nargs=1,
		required=True,
		help='The interface through which the packet will be sent')
	parser.add_argument('--recvif', nargs=1,
		required=True,
		help='The interface on which to check for the packet')
	parser.add_argument('--src', nargs=1,
		required=True,
		help='The source IP address')
	parser.add_argument('--to', nargs=1,
		required=True,
		help='The destination IP address')
	parser.add_argument('--debug',
		required=False, action='store_true',
		help='Enable test debugging')

	args = parser.parse_args()

	########################################################################
	#
	# A test case to check that IPv6 packets are sent with a proper
	# (resolved) Ethernet Destination MAC address instead of the BCAST one.
	# This was needed as test cases did not work properly on i386 due to a
	# scapy BPF parsing bug. (See PR 239380 and duplicates).
	#
	bcmac = sp.Ether(dst="ff:ff:ff:ff:ff:ff").dst
	data = "6" * 88
	pkt = sp.Ether() / \
		sp.IPv6(src=args.src[0], dst=args.to[0]) / \
		sp.UDP(dport=3456, sport=6543) / \
		data
	sp.sendp(pkt, iface=args.sendif[0], verbose=False)

	eth = pkt.getlayer(sp.Ether)
	if eth is None:
		print("No Ether in packet")
		pkt.display()
		sys.exit(1)
	if eth.dst == bcmac:
		print("Broadcast dMAC on packet")
		eth.display()
		sys.exit(1)

	sys.exit(0)
Example #12
0
    def PrepareHALRequestSpec(self, req_spec):
        #
        # For now we only have Ah Requests. In future we need to make sure what kind
        # of spec it is.
        #
        if not self.lqp.svc == 3: return

        logger.info("PrepareHALRequestSpec:: RDMA Session: %s Session: %s "
                       "Remote QP: %s Local QP: %s" %\
                       (self.GID(), self.session.GID(), self.rqp.GID(), self.lqp.GID()))
        if (GlobalOptions.dryrun): return

        logger.info("RdmaAhCreate:: src_ip: %s dst_ip: %s src_mac: %s dst_mac: %s proto: %s "
                        "sport: %s dport: %s ah_handle: %d isipv6: %d" %\
                    (self.session.initiator.addr.get(), self.session.responder.addr.get(),
                     self.session.initiator.ep.macaddr.get(), self.session.responder.ep.macaddr.get(),
                     self.session.iflow.proto, self.session.iflow.sport, self.session.iflow.dport,
                     self.ah_handle, self.session.IsIPV6()))

        EthHdr = scapy.Ether(src=self.session.initiator.ep.macaddr.get(),
                             dst=self.session.responder.ep.macaddr.get())
        Dot1qHdr = scapy.Dot1Q(
            vlan=self.session.initiator.ep.intf.encap_vlan_id,
            prio=self.session.iflow.txqos.cos)
        if self.session.IsIPV6():
            IpHdr = scapy.IPv6(src=self.session.initiator.addr.get(),
                               dst=self.session.responder.addr.get(),
                               tc=self.session.iflow.txqos.dscp,
                               plen=0)
        else:
            IpHdr = scapy.IP(
                src=self.session.initiator.addr.get(),
                dst=self.session.responder.addr.get(),
                tos=0,  # keep tos = 0 to not trigger ecn mark
                len=0,
                chksum=0)
        UdpHdr = scapy.UDP(sport=self.session.iflow.sport,
                           dport=self.session.iflow.dport,
                           len=0,
                           chksum=0)

        req_spec.hw_lif_id = self.lqp.pd.ep.intf.lif.hw_lif_id
        req_spec.header_template = bytes(EthHdr / Dot1qHdr / IpHdr / UdpHdr)
        req_spec.ahid = self.ah_handle

        return
Example #13
0
    def _CheckTunnelOutput(self,
                           tunnel,
                           inner_version,
                           local_inner,
                           remote_inner,
                           sa_info=None):
        """Test null-crypt output path over an IPsec interface."""
        if sa_info is None:
            sa_info = tunnel.out_sa
        local_port = _SendPacket(self, tunnel.netid, inner_version,
                                 remote_inner, _TEST_REMOTE_PORT)

        # Read a tunneled IP packet on the underlying (outbound) network
        # verifying that it is an ESP packet.
        pkt = self._ExpectEspPacketOn(tunnel.underlying_netid, sa_info.spi,
                                      sa_info.seq_num, None, tunnel.local,
                                      tunnel.remote)

        # Get and update the IP headers on the inner payload so that we can do a simple
        # comparison of byte data. Unfortunately, due to the scapy version this runs on,
        # we cannot parse past the ESP header to the inner IP header, and thus have to
        # workaround in this manner
        if inner_version == 4:
            ip_hdr_options = {
                'id': scapy.IP(str(pkt.payload)[8:]).id,
                'flags': scapy.IP(str(pkt.payload)[8:]).flags
            }
        else:
            ip_hdr_options = {'fl': scapy.IPv6(str(pkt.payload)[8:]).fl}

        expected = _GetNullAuthCryptTunnelModePkt(inner_version, local_inner,
                                                  tunnel.local, local_port,
                                                  remote_inner, tunnel.remote,
                                                  _TEST_REMOTE_PORT,
                                                  sa_info.spi, sa_info.seq_num,
                                                  ip_hdr_options)

        # Check outer header manually (Avoids having to overwrite outer header's
        # id, flags or flow label)
        self.assertSentPacket(tunnel, sa_info)
        self.assertEquals(expected.src, pkt.src)
        self.assertEquals(expected.dst, pkt.dst)
        self.assertEquals(len(expected), len(pkt))

        # Check everything else
        self.assertEquals(str(expected.payload), str(pkt.payload))
Example #14
0
def send(dstmac, interval, count, lifetime, iface):
    """Generate IPv6 Router Advertisement and send to destination.

    @param dstmac: string HWAddr of the destination ipv6 node.
    @param interval: int Time to sleep between consecutive packets.
    @param count: int Number of packets to be sent.
    @param lifetime: Router lifetime value for the original RA.
    @param iface: string Router's WiFi interface to send packets over.

    """
    while count:
        ra = (scapy.Ether(dst=dstmac) / scapy.IPv6() /
              scapy.ICMPv6ND_RA(routerlifetime=lifetime))
        scapy.sendp(ra, iface=iface)
        count = count - 1
        time.sleep(interval)
        lifetime = lifetime - interval
def check_icmp6_error(args, packet):
    ip6 = packet.getlayer(sp.IPv6)
    if not ip6:
        return False
    oip6 = sp.IPv6(src=args.src[0], dst=args.to[0])
    if ip6.dst != oip6.src:
        return False
    icmp6 = packet.getlayer(sp.ICMPv6DestUnreach)
    if not icmp6:
        return False
    # ICMP6_DST_UNREACH_NOPORT 4
    if icmp6.code != 4:
        return False
    # Should we check the payload as well?
    # We are running in a very isolated environment and nothing else
    # should trigger an ICMPv6 Dest Unreach / Port Unreach so leave it.
    #icmp6.display()
    return True
Example #16
0
def check_icmp6_error_2(args, packet):
    ip6 = packet.getlayer(sp.IPv6)
    if not ip6:
        return False
    oip6 = sp.IPv6(src=args.src[0], dst=args.to[0])
    if ip6.dst != oip6.src:
        return False
    icmp6 = packet.getlayer(sp.ICMPv6TimeExceeded)
    if not icmp6:
        return False
    # ICMP6_TIME_EXCEED_REASSEMBLY 1
    if icmp6.code != 1:
        return False
    # Should we check the payload as well?
    # We are running in a very isolated environment and nothing else
    # should trigger an ICMPv6 Time Exceeded / Frag reassembly so leave it.
    #icmp6.display()
    return True
Example #17
0
def check_icmp6_error(args, packet):
	ip6 = packet.getlayer(sp.IPv6)
	if not ip6:
		return False
	oip6 = sp.IPv6(src=args.src[0], dst=args.to[0])
	if ip6.dst != oip6.src:
		return False
	icmp6 = packet.getlayer(sp.ICMPv6ParamProblem)
	if not icmp6:
		return False
	# ICMP6_PARAMPROB_HEADER 0
	if icmp6.code != 0:
		return False
	# Should we check the payload as well?
	# We are running in a very isolated environment and nothing else
	# should trigger an ICMPv6 Param Prob so leave it.
	#icmp6.display()
	return True
Example #18
0
def main():
    parser = argparse.ArgumentParser("scapyi386.py",
                                     description="IPv6 Ethernet Dest MAC test")
    parser.add_argument(
        '--sendif',
        nargs=1,
        required=True,
        help='The interface through which the packet will be sent')
    parser.add_argument('--recvif',
                        nargs=1,
                        required=True,
                        help='The interface on which to check for the packet')
    parser.add_argument('--src',
                        nargs=1,
                        required=True,
                        help='The source IP address')
    parser.add_argument('--to',
                        nargs=1,
                        required=True,
                        help='The destination IP address')
    parser.add_argument('--debug',
                        required=False,
                        action='store_true',
                        help='Enable test debugging')
    parser.add_argument('--mldraw01',
                        required=False,
                        action='store_true',
                        help='Multicast Listener Query Raw01')

    args = parser.parse_args()

    pkt = None
    if args.mldraw01:
        pkt = sp.Ether() / \
         sp.IPv6(dst="ff02::1", hlim=1, nh=0) / \
         sp.IPv6ExtHdrHopByHop(options = sp.RouterAlert(value=0)) / \
         sp.ICMPv6MLQuery()
    if pkt is None:
        sys.exit(1)
    if args.debug:
        pkt.display()
    sp.sendp(pkt, iface=args.sendif[0], verbose=False)

    sys.exit(0)
Example #19
0
def DecryptPacketWithNull(packet):
  """Apply null decryption to a packet.

  This performs ESP decapsulation on the given packet. The input packet is
  assumed to be a UDP packet. This function will remove the ESP header and
  trailer bytes from an ESP packet.

  TODO: Support TCP

  Args:
    packet: a scapy.IPv6 or scapy.IP packet

  Returns:
    A tuple of decrypted packet (scapy.IPv6 or scapy.IP) and EspHdr
  """
  esp_hdr, esp_data = cstruct.Read(str(packet.payload), xfrm.EspHdr)
  # Parse and strip ESP trailer.
  pad_len, esp_nexthdr = struct.unpack("BB", esp_data[-2:])
  trailer_len = pad_len + 2 # Add the size of the pad_len and next_hdr fields.
  LayerType = {
          IPPROTO_IPIP: scapy.IP,
          IPPROTO_IPV6: scapy.IPv6,
          IPPROTO_UDP: scapy.UDP}[esp_nexthdr]
  next_layer = LayerType(esp_data[:-trailer_len])
  if esp_nexthdr in [IPPROTO_IPIP, IPPROTO_IPV6]:
    # Tunnel mode decap is simple. Return the inner packet.
    return next_layer, esp_hdr

  # Cut out the ESP header.
  packet.payload = next_layer
  # Fix the IPv4/IPv6 headers.
  if type(packet) is scapy.IPv6:
    packet.nh = IPPROTO_UDP
    packet.plen = None # Recompute packet length.
    packet = scapy.IPv6(str(packet))
  elif type(packet) is scapy.IP:
    packet.proto = IPPROTO_UDP
    packet.len = None # Recompute packet length.
    packet.chksum = None # Recompute IPv4 checksum.
    packet = scapy.IP(str(packet))
  else:
    raise ValueError("First layer in packet should be IPv4 or IPv6: " + repr(packet))
  return packet, esp_hdr
Example #20
0
def send(dstmac, interval, count, lifetime, iface, rtt):
    """Generate IPv6 Router Advertisement and send to destination.

    Args:
      1. dstmac: string HWAddr of the destination ipv6 node.
      2. interval: int Time to sleep between consecutive packets.
      3. count: int Number of packets to be sent.
      4. lifetime: Router lifetime value for the original RA.
      5. iface: string Router's WiFi interface to send packets over.
      6. rtt: retrans timer in the RA packet

    """
    while count:
        ra = (scapy.Ether(dst=dstmac) / scapy.IPv6() /
              scapy.ICMPv6ND_RA(routerlifetime=lifetime, retranstimer=rtt))
        scapy.sendp(ra, iface=iface)
        count = count - 1
        time.sleep(interval)
        lifetime = lifetime - interval
Example #21
0
 def ExpectProbe(self, is_unicast, addr):
     version = 6 if ":" in addr else 4
     if version == 6:
         llsrc = self.MyMacAddress(self.netid)
         if is_unicast:
             src = self.MyLinkLocalAddress(self.netid)
             dst = addr
         else:
             solicited = inet_pton(AF_INET6, addr)
             last3bytes = tuple([ord(b) for b in solicited[-3:]])
             dst = "ff02::1:ff%02x:%02x%02x" % last3bytes
             src = self.MyAddress(6, self.netid)
         expected = (scapy.IPv6(src=src, dst=dst) /
                     scapy.ICMPv6ND_NS(tgt=addr) /
                     scapy.ICMPv6NDOptSrcLLAddr(lladdr=llsrc))
         msg = "%s probe" % ("Unicast" if is_unicast else "Multicast")
         self.ExpectPacketOn(self.netid, msg, expected)
     else:
         raise NotImplementedError
    def testIPv6StickyPktinfo(self):
        for _ in xrange(self.ITERATIONS):
            for netid in self.tuns:
                s = net_test.UDPSocket(AF_INET6)

                # Set a flowlabel.
                net_test.SetFlowLabel(s, net_test.IPV6_ADDR, 0xdead)
                s.setsockopt(net_test.SOL_IPV6, net_test.IPV6_FLOWINFO_SEND, 1)

                # Set some destination options.
                nonce = "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c"
                dstopts = "".join([
                    "\x11\x02",  # Next header=UDP, 24 bytes of options.
                    "\x01\x06",
                    "\x00" * 6,  # PadN, 6 bytes of padding.
                    "\x8b\x0c",  # ILNP nonce, 12 bytes.
                    nonce
                ])
                s.setsockopt(net_test.SOL_IPV6, IPV6_DSTOPTS, dstopts)
                s.setsockopt(net_test.SOL_IPV6, IPV6_UNICAST_HOPS, 255)

                pktinfo = multinetwork_base.MakePktInfo(
                    6, None, self.ifindices[netid])

                # Set the sticky pktinfo option.
                s.setsockopt(net_test.SOL_IPV6, IPV6_PKTINFO, pktinfo)

                # Specify the flowlabel in the destination address.
                s.sendto(UDP_PAYLOAD, (net_test.IPV6_ADDR, 53, 0xdead, 0))

                sport = s.getsockname()[1]
                srcaddr = self.MyAddress(6, netid)
                expected = (scapy.IPv6(
                    src=srcaddr, dst=net_test.IPV6_ADDR, fl=0xdead, hlim=255) /
                            scapy.IPv6ExtHdrDestOpt(options=[
                                scapy.PadN(optdata="\x00\x00\x00\x00\x00\x00"),
                                scapy.HBHOptUnknown(otype=0x8b, optdata=nonce)
                            ]) / scapy.UDP(sport=sport, dport=53) /
                            UDP_PAYLOAD)
                msg = "IPv6 UDP using sticky pktinfo: expected UDP packet on %s" % (
                    self.GetInterfaceName(netid))
                self.ExpectPacketOn(netid, msg, expected)
Example #23
0
def get_icmp_unreachable_pkt(pkt):
    p = None
    icmp = None
    if pkt.ipv4:
        p = sp.IP(dst=pkt.src_addr, src=pkt.dst_addr)
        icmp = sp.ICMP()
        # ICMP type=3 code=3 port Unreachable
        icmp.type = 3
        icmp.code = 3
    else:
        p = sp.IPv6(dst=pkt.src_addr, src=pkt.dst_addr)
        icmp = sp.ICMPv6DestUnreach()
        # ICMP type=1 code=4 port Unreachable
        icmp.type = 1
        icmp.code = 4

    if pkt.ip.packet_len >= 64:
        return p / icmp / (bytes(pkt.raw)[0:64])
    else:
        return p / icmp / (bytes(pkt.raw))
Example #24
0
 def ReceiveUnicastAdvertisement(self,
                                 addr,
                                 mac,
                                 srcaddr=None,
                                 dstaddr=None,
                                 S=1,
                                 O=0,
                                 R=1):
     version = 6 if ":" in addr else 4
     if srcaddr is None:
         srcaddr = addr
     if dstaddr is None:
         dstaddr = self.MyLinkLocalAddress(self.netid)
     if version == 6:
         packet = (scapy.Ether(src=mac, dst=self.MyMacAddress(self.netid)) /
                   scapy.IPv6(src=srcaddr, dst=dstaddr) /
                   scapy.ICMPv6ND_NA(tgt=addr, S=S, O=O, R=R) /
                   scapy.ICMPv6NDOptDstLLAddr(lladdr=mac))
         self.ReceiveEtherPacketOn(self.netid, packet)
     else:
         raise NotImplementedError
Example #25
0
    def generate(self, ip_dst=None, eth_dst=None):
        """Generates a Ping6 packet (i.e., Echo Request)

        Args:
            ip_dst: IPv6 destination address (Optional)
            eth_dst: Ethernet (layer 2) destination address (Optional)
        """
        # Overwrite standard fields if desired
        ip6_dst = (ip_dst if ip_dst is not None else self.dst_ipv6)
        hw_dst = (eth_dst if eth_dst is not None else self.dst_mac)

        # Create IPv6 layer
        base = scapy.IPv6(dst=ip6_dst, src=self.src_ipv6)
        echo_request = scapy.ICMPv6EchoRequest(data=PING6_DATA)

        ip6 = base / echo_request

        # Create Ethernet layer
        ethernet = scapy.Ether(src=self.src_mac, dst=hw_dst)

        self.packet = ethernet / ip6
        return self.packet
Example #26
0
    def generate(self,
                 lifetime,
                 enableDNS=False,
                 dns_lifetime=0,
                 ip_dst=None,
                 eth_dst=None):
        """Generates a Router Advertisement (RA) packet (ICMP over IPv6).

        Args:
            lifetime: RA lifetime
            enableDNS: Add RDNSS option to RA (Optional)
            dns_lifetime: Set DNS server lifetime (Optional)
            ip_dst: IPv6 destination address (Optional)
            eth_dst: Ethernet (layer 2) destination address (Optional)
        """
        # Overwrite standard fields if desired
        ip6_dst = (ip_dst if ip_dst is not None else RA_IP)
        hw_dst = (eth_dst if eth_dst is not None else RA_MAC)

        # Create IPv6 layer
        base = scapy.IPv6(dst=ip6_dst, src=self.src_ipv6)
        router_solicitation = scapy.ICMPv6ND_RA(routerlifetime=lifetime)
        src_ll_addr = scapy.ICMPv6NDOptSrcLLAddr(lladdr=self.src_mac)
        prefix = scapy.ICMPv6NDOptPrefixInfo(prefixlen=RA_PREFIX_LEN,
                                             prefix=RA_PREFIX)
        if enableDNS:
            rndss = scapy.ICMPv6NDOptRDNSS(lifetime=dns_lifetime,
                                           dns=[self.src_ipv6],
                                           len=DNS_LEN)
            ip6 = base / router_solicitation / src_ll_addr / prefix / rndss
        else:
            ip6 = base / router_solicitation / src_ll_addr / prefix

        # Create Ethernet layer
        ethernet = scapy.Ether(src=self.src_mac, dst=hw_dst)

        self.packet = ethernet / ip6
        return self.packet
Example #27
0
def gen_pkt_to_switch(
        test,  # something that inherits from FbossBaseSystemTest
        src_eth="00:11:22:33:44:55",
        dst_eth=None,  # fill in from switch
        src_ip=None,  # fill in based on v6=True
        dst_ip=None,  # fill in with switch's inband interface
        src_port=12345,
        dst_port=54321):
    # are we using v6?   Assume yes until told otherwise
    v6 = True if dst_ip is None else is_v6(dst_ip)
    if src_ip is None:
        src_ip = 'fe80:1:2:3:4::1' if v6 else '1.2.3.4'
    else:
        v6 = is_v6(src_ip)

    if dst_ip is None or dst_eth is None:
        with test.test_topology.switch_thrift() as client:
            interfaces = client.getAllInterfaces()
        test.assertGreater(len(interfaces), 0, "No interfaces found!?")
        if DOWNLINK_VLAN in interfaces:
            interface = interfaces[DOWNLINK_VLAN]
        else:
            # grab an interface, doesn't matter which one because
            # they all share the same MAC (currently)
            interface = next(iter(interfaces.values()))
        if dst_eth is None:
            dst_eth = interface.mac
        if dst_ip is None:
            dst_ip = _get_first_router_ip(test, interface, v6)
    frame = scapy.Ether(src=src_eth, dst=dst_eth)
    if v6 or ':' in dst_ip:
        pkt = scapy.IPv6(src=src_ip, dst=dst_ip)
    else:
        pkt = scapy.IP(src=src_ip, dst=dst_ip)
    segment = scapy.TCP(sport=src_port, dport=dst_port)
    pkt = frame / pkt / segment
    test.log.info("Creating packet %s" % repr(pkt))
    return bytes(pkt)  # return raw packet in bytes
Example #28
0
 def test_tcpv6(self):
     import loxi.of12 as ofp
     self.maxDiff = None
     pkt = scapy.Ether(dst='00:01:02:03:04:05', src='00:06:07:08:09:0a')/ \
         scapy.IPv6(src="::1", dst="::2", nh=6, tc=2 | (32 << 2), fl=7)/ \
         scapy.TCP(sport=1234, dport=80)
     expected = [
         ofp.oxm.eth_dst([0x00, 0x01, 0x02, 0x03, 0x04, 0x05]),
         ofp.oxm.eth_src([0x00, 0x06, 0x07, 0x08, 0x09, 0x0a]),
         ofp.oxm.eth_type(0x86dd),
         ofp.oxm.vlan_vid(ofp.OFP_VLAN_NONE),
         ofp.oxm.ip_proto(6),
         ofp.oxm.ip_dscp(32),
         ofp.oxm.ip_ecn(2),
         ofp.oxm.ipv6_src("\x00" * 15 + "\x01"),
         ofp.oxm.ipv6_dst("\x00" * 15 + "\x02"),
         ofp.oxm.ipv6_flabel(7),
         ofp.oxm.tcp_src(1234),
         ofp.oxm.tcp_dst(80)
     ]
     result = parse.packet_to_flow_match_v3(pkt).oxm_list
     self.assertEquals([x.show() for x in expected],
                       [x.show() for x in result])
Example #29
0
def main():
    intf = sys.argv[1]
    ipv6_src = sys.argv[2]
    ipv6_dst = sys.argv[3]

    ipv6_main = sp.IPv6(dst=ipv6_dst, src=ipv6_src)

    padding = 8
    fid = random.randint(0, 100000)
    frag_0 = sp.IPv6ExtHdrFragment(id=fid, nh=UDP_PROTO, m=1, offset=0)
    foff_1 = (int)(padding / 8)
    frag_1 = sp.IPv6ExtHdrFragment(id=fid, nh=UDP_PROTO, m=0, offset=foff_1)

    pkt1_opts = sp.AH(nh=AH_PROTO, payloadlen=200) \
            / sp.Raw('XXXX' * 199) \
            / sp.AH(nh=FRAG_PROTO, payloadlen=1) \
            / frag_1

    pkt0 = sp.Ether() / ipv6_main / frag_0 / sp.Raw('A' * padding)
    pkt1 = sp.Ether() / ipv6_main / pkt1_opts / sp.Raw('B' * padding)

    sp.sendp(pkt0, iface=intf, verbose=False)
    sp.sendp(pkt1, iface=intf, verbose=False)
Example #30
0
def main():
    parser = argparse.ArgumentParser(
        "frag6.py", description="IPv6 fragementation test tool")
    parser.add_argument(
        '--sendif',
        nargs=1,
        required=True,
        help='The interface through which the packet will be sent')
    parser.add_argument('--recvif',
                        nargs=1,
                        required=True,
                        help='The interface on which to check for the packet')
    parser.add_argument('--src',
                        nargs=1,
                        required=True,
                        help='The source IP address')
    parser.add_argument('--to',
                        nargs=1,
                        required=True,
                        help='The destination IP address')
    parser.add_argument('--debug',
                        required=False,
                        action='store_true',
                        help='Enable test debugging')

    args = parser.parse_args()

    # Start sniffing on recvif
    sniffer = Sniffer(args, check_icmp6_error)
    sniffer2 = Sniffer(args, check_icmp6_error_2)

    ########################################################################
    #
    # A fragment with payload and offset set to add up to >64k when
    # another frag with offset=0 arrives and has an unfrag part.
    # This is us checking for all fragments queued already when the
    # one with off=0 arrives.  Note:  unless the off=0 has its own problem
    # it will be queued and off!=0 ones might be expunged with param prob.
    #
    # A:  Reassembly failure, timeout after
    # R:  ICMPv6 param prob, param header (1st frag)
    # R:  ICMPv6 time exceeded (2nd frag, as off=0)
    #
    data = "6" * 15
    ip6f01 = \
     sp.Ether() / \
     sp.IPv6(src=args.src[0], dst=args.to[0]) / \
     sp.IPv6ExtHdrFragment(offset=0x1ffc, m=0, id=8) / \
     sp.UDP(dport=3456, sport=6543) / \
     data
    data = "6" * 8
    ip6f02 = \
     sp.Ether() / \
     sp.IPv6(src=args.src[0], dst=args.to[0]) / \
     sp.IPv6ExtHdrDestOpt(options = \
         sp.PadN(optdata="\x00\x00\x00\x00\x00\x00")) / \
     sp.IPv6ExtHdrFragment(offset=0, m=1, id=8) / \
     sp.UDP(dport=3456, sport=6543) / \
     data
    if args.debug:
        ip6f01.display()
        ip6f02.display()
    sp.sendp(ip6f01, iface=args.sendif[0], verbose=False)
    sp.sendp(ip6f02, iface=args.sendif[0], verbose=False)

    sleep(1.00)
    sniffer.setEnd()
    sniffer.join()
    if not sniffer.foundCorrectPacket:
        sys.exit(1)
    sleep(75)
    sniffer2.setEnd()
    sniffer2.join()
    if not sniffer2.foundCorrectPacket:
        sys.exit(1)

    sys.exit(0)