Exemple #1
0
def icmpping(targets, verbose):

    if targets == []:
        return None

    is_up = []

    if args.icmpecho:
        print("[-] Running ICMP-Echo  host discovery")
        p = scapy.IP(dst=targets) / scapy.ICMP(type="echo-request")

    elif args.icmptime:
        print("[-] Running ICMP-Timestamp host discovery")
        p = scapy.IP(dst=targets) / scapy.ICMP(type="timestamp-request")

    elif args.icmpmask:
        print("[-] Running ICMP-Address-Mask host discovery")
        p = scapy.IP(dst=targets) / scapy.ICMP(type="address-mask-request")

    else:
        print("[-] Running ICMP-Echo + ICMP-Timestamp Host discovery")
        p = scapy.IP(dst=targets)
        p = p / scapy.ICMP(
            seq=1, id=100, type=["echo-request", "timestamp-request"])

    ans, unans = scapy.sr(p, timeout=0.5, retry=1, verbose=verbose)

    for sent, received in ans:
        for i, target_ip in enumerate(targets):
            if received.src == target_ip:
                is_up.append(targets.pop(i))
                if verbose == True:
                    print("[+] {} is up".format(target_ip))

    return is_up
Exemple #2
0
def simple_icmp_packet(pktlen=60,
                       eth_dst='00:01:02:03:04:05',
                       eth_src='00:06:07:08:09:0a',
                       dl_vlan_enable=False,
                       vlan_vid=0,
                       vlan_pcp=0,
                       ip_src='192.168.0.1',
                       ip_dst='192.168.0.2',
                       ip_tos=0,
                       ip_ttl=64,
                       icmp_type=8,
                       icmp_code=0):
    """
    Return a simple ICMP packet

    Supports a few parameters:
    @param len Length of packet in bytes w/o CRC
    @param eth_dst Destinatino MAC
    @param eth_src Source MAC
    @param dl_vlan_enable True if the packet is with vlan, False otherwise
    @param vlan_vid VLAN ID
    @param vlan_pcp VLAN priority
    @param ip_src IP source
    @param ip_dst IP destination
    @param ip_tos IP ToS
    @param ip_ttl IP TTL
    @param icmp_type ICMP type
    @param icmp_code ICMP code

    Generates a simple ICMP ECHO REQUEST.  Users
    shouldn't assume anything about this packet other than that
    it is a valid ethernet/ICMP frame.
    """

    if MINSIZE > pktlen:
        pktlen = MINSIZE

    if (dl_vlan_enable):
        pkt = scapy.Ether(dst=eth_dst, src=eth_src)/ \
            scapy.Dot1Q(prio=vlan_pcp, id=0, vlan=vlan_vid)/ \
            scapy.IP(src=ip_src, dst=ip_dst, ttl=ip_ttl, tos=ip_tos)/ \
            scapy.ICMP(type=icmp_type, code=icmp_code)
    else:
        pkt = scapy.Ether(dst=eth_dst, src=eth_src)/ \
            scapy.IP(src=ip_src, dst=ip_dst, ttl=ip_ttl, tos=ip_tos)/ \
            scapy.ICMP(type=icmp_type, code=icmp_code)

    pkt = pkt / ("0" * (pktlen - len(pkt)))

    return pkt
    def setUp(self):
        """
        Setup class for PingOfDeath.
        """
        # Packet with load < 60000
        self.pkt1 = scapy.IP(src="192.168.0.1") \
                    / scapy.ICMP() / scapy.Raw(load="*")

        # Packet with load > 60000 (attack)
        self.pkt2 = scapy.IP(src="192.168.0.1") \
                   / scapy.ICMP() / scapy.Raw(load="*" * 65535)

        # Initialize PingOfDeath object
        self.ping_of_death = PingOfDeath()
Exemple #4
0
def traceroute():
    ip_addr = []
    for i in range(1, 50):
        icmp = scapy.IP(dst=options.host, ttl=i) / scapy.ICMP()
        b = scapy.sr1(icmp, timeout=3, verbose=False)

        try:  #if b.dst is not in Packet in rare case
            if i == 1:
                src_ip = b.dst
                print "\nSource_IP:%s\n" % src_ip

        except AttributeError:
            pass

        if b is None:
            print "TTL=%s \t*****Router Drops the packet*****" % i

        else:
            if b.src in ip_addr:
                dst_ip = b.src
                print "\nDestination_IP:%s\n" % dst_ip
                break

            print "TTL=%s \tIntermediate_IP=%s" % (i, b.src)
            ip_addr.append(b.src)
    return ip_addr
Exemple #5
0
def IP_Route():

    clear = os.system('clear')

    print("**************************************")
    print("            IP_Record_Route")
    print("**************************************")

    print("Please input your target's IP")
    target = input("[IP_Record_Route]#")
    src_ip = scapy.RandIP()
    num = 0
    try:
        while True:
            packet = scapy.IP(
                src=src_ip,
                dst=target,
                ttl=128,
                options=scapy.IPOption_RR(
                    copy_flag=0,
                    length=39,
                    routers=[
                        '0.0.0.0', '0.0.0.0', '0.0.0.0', '0.0.0.0', '0.0.0.0',
                        '0.0.0.0', '0.0.0.0', '0.0.0.0', '0.0.0.0'
                    ])) / scapy.ICMP() / scapy.Raw(
                        load=b'abcdefghijklmnopqrstuvwabcdefghi')
            scapy.send(packet, verbose=False)
            num += 1
            print("Sent " + str(num) + "packets")
    except KeyboardInterrupt:
        print("Ctrl + C  detected......")
Exemple #6
0
def scapy_send():
    scapy.send(scapy.IP(dst='192.168.1.59') / scapy.ICMP())
    scapy.sendp(scapy.Ether() / scapy.IP(dst='192.168.1.59', ttl=(
        1,
        4,
    )),
                iface='eth0')
Exemple #7
0
    def gwscan_icmp(self, net, ip):
        self.msg('gwscan for net %s, searching gw for %s' % (net, ip))
        lt = self.getmacs(net)
        #		from pprint import pprint as pp
        #		pp(lt)
        #ans,unans = scapy.srp(scapy.Ether(dst='ff:ff:ff:ff:ff:ff') / scapy.IP(dst=ip) / scapy.ICMP(), timeout=5)
        pkt = scapy.Ether(dst=lt['mac_ip'].keys())
        pkt /= scapy.IP(dst=ip)
        pkt /= scapy.ICMP()
        ans, unans = scapy.srp(pkt, timeout=5)
        ret = []
        for b in ans:
            for a in b[1]:
                if a[scapy.ICMP].type == 0 and a[scapy.ICMP].code == 0:
                    mac = a[scapy.Ether].src
                    r_ip = a[scapy.IP].src
                    if mac in lt['mac_ip']:
                        ip = lt['mac_ip'][mac]
                    else:
                        ip = '_UNKNOWN'
                        a.show()
                    ret.append({
                        'ttype': 'ping',
                        'gw_mac': mac,
                        'gw_ip': ip,
                        'r_ip': r_ip
                    })

        self.msg('gwscan finished')
        return ret
Exemple #8
0
def send(data):
    data = base64.b64encode(data)
    app_exfiltrate.log_message(
        'info', "[icmp] Sending {} bytes with ICMP packet".format(len(data)))
    scapy.sendp(scapy.Ether() / scapy.IP(dst=config['target']) / scapy.ICMP() /
                data,
                verbose=0)
Exemple #9
0
def make_ICMP_reply_pkt(data = None, **kwargs):
    pkt = make_MAC_hdr(**kwargs)/make_IP_hdr(**kwargs)/scapy.ICMP(type="echo-reply")
    if data:
        pkt = pkt/data
    else:
        pkt = pkt/("\x00"*56)
    return pkt
Exemple #10
0
def fwd_ip_icmp_slow(args):
    """
    Sends ICMP packet via args.iface interface.
    Forces slow path processing by introducing IP option.
    Receives and checks the forwarded packet.
    Assumes forwarding router decrements TTL
    """
    def filter_f(x):
        return x.src == args.dmac and x.type == 0x0800

    e = sc.Ether(src=args.smac, dst=args.dmac)
    # Add IP option to switch to 'normal' IP processing
    stream_id = sc.IPOption_Stream_Id(security=0xFFFF)
    ip = sc.IP(src=args.sip,
               dst=args.dip,
               options=[sc.IPOption_Stream_Id(security=0xFFFF)])
    icmp = sc.ICMP(type='echo-request')
    pkt = e / ip / icmp

    send_cb = partial(send_packet, args, pkt)
    packets = sc.sniff(iface=args.iface,
                       started_callback=send_cb,
                       stop_filter=filter_f,
                       lfilter=filter_f,
                       timeout=5)
    assert len(packets) > 0
    check_forwarded_ip_packet(pkt, packets[-1])
Exemple #11
0
def packet_handler(packet):
    global memberDataLatest
    print(memberDataLatest)
    raw_pkt = scp.raw(packet)
    enableFlag = False
    if(b'Peer1' in raw_pkt and 'Peer1' in acceptedMembers):
        enableFlag = True
        idx = raw_pkt.index("Peer1")
        data = str(raw_pkt[idx+5:]).strip().split(',')
        msg2 = raw_pkt[idx:].strip()
        name = "Peer1"
    if(b'Peer2' in raw_pkt and 'Peer2' in acceptedMembers):
        enableFlag = True
        idx = raw_pkt.index("Peer2")
        data = str(raw_pkt[idx+5:]).strip().split(',')
        msg2 = raw_pkt[idx:].strip()
        name = "Peer2"
    if(b'Peer3' in raw_pkt and 'Peer3' in acceptedMembers):
        enableFlag = True
        idx = raw_pkt.index("Peer3")
        data = str(raw_pkt[idx+5:]).strip().split(',')
        msg2 = raw_pkt[idx:].strip()
        name = "Peer3"
    if ((b'Peer1' in raw_pkt) or (b'Peer2' in raw_pkt) or (b'Peer3' in raw_pkt)) and enableFlag:
        mData = data
        if int(mData[0]) > memberDataLatest[name]:
            memberDataLatest[name] = int(mData[0])
            mData[-1] = str(time.time())
            memberData[name].append(mData)
            for member in members:
                pkt = scp.IP(dst=members[member])/scp.ICMP()/scp.Raw(load=msg2)
                scp.send(pkt)
            if len(memberData[name]) > bufferSize:
                memberData[name].pop(0)
Exemple #12
0
def fwd_ip_icmp_fast(args):
    """
    Sends ICMP packet via args.iface interface.
    Receives and checks the forwarded packet.
    Assumes forwarding router decrements TTL
    """
    def filter_f(x):
        return x.src == args.dmac and x.type == 0x0800

    e = sc.Ether(src=args.smac, dst=args.dmac)
    ip = sc.IP(src=args.sip, dst=args.dip)
    icmp = sc.ICMP(type='echo-request')
    pkt = e / ip / icmp

    send_cb = partial(send_packet, args, pkt)
    packets = sc.sniff(iface=args.iface,
                       started_callback=send_cb,
                       stop_filter=filter_f,
                       lfilter=filter_f,
                       timeout=5)
    assert len(packets) > 0
    fwd_pkt = packets[-1]
    try:
        check_forwarded_ip_packet(pkt, fwd_pkt)
    except Exception as e:
        print('Original packet:')
        pkt.show()
        print('Forwarded packet:')
        fwd_pkt.show()
        for a_packet in packets:
            a_packet.summary()
        raise Exception from e
Exemple #13
0
def sender():
    global mode
    while(1):
        #generate GPS location
        print("MODE: ",mode)
        if mode == "explore":
            GPIO.output(18,GPIO.HIGH)
            time.sleep(0.1)
            GPIO.output(18,GPIO.LOW)
        if mode == "emergency":
            GPIO.output(18,GPIO.HIGH)
        global myseq
        lat = randint(0,10)
        lon = randint(0, 10)
        ts = time.time()
        try:
            msg = myname+","+str(myseq)+","+str(lat)+","+str(lon)+","+str(ts)
            myseq += 1
            for member in members:
                packet = scp.IP(dst=members[member])/scp.ICMP()/scp.Raw(load=msg)
                #scp.sendp(packet, iface='wlan0')
                #print("Sent "+msg)
                scp.send(packet)
        except:
            print('cannot send message')
        #print("before i go to sleep")
        time.sleep(delay)
Exemple #14
0
def do_ping(dst: str, net_scan=True) -> bool:
    '''check if its FQDN then resolv if its IP then do ping one time
    '''
    global online_hosts
    # packet = scapy.IP(dst="192.168.0." + str(dst), ttl=20)/scapy.ICMP()
    t1 = time.perf_counter()
    packet = scapy.IP(dst=dst) / scapy.ICMP()
    # answered, unanswered = scapy.sr(packet, timeout=TIMEOUT)
    scapy.sr1(packet, timeout=TIMEOUT)
    reply = scapy.sr1(packet, timeout=TIMEOUT)
    # print(answered, unanswered)
    if reply:
        if net_scan:
            print(f"{Fore.GREEN}host {dst} is alived{Fore.RESET}")

        else:
            t2 = time.perf_counter()
            print(
                f"{Fore.GREEN}pinging {dst}, rtt is {str(t2-t1)[0:4]}{Fore.RESET}"
            )
        return True
    else:
        if not net_scan:

            print(
                f"{Fore.BLUE}Timeout waiting for {packet[scapy.IP].dst}{Fore.RESET}"
            )
        return False
Exemple #15
0
def IP_Data_Flow():

    clear = os.system('clear')

    print("**************************************")
    print("            IP_Flow")
    print("**************************************")

    print("Please input your target's IP")
    target = input("[IP_Flow]#")
    src_ip = scapy.RandIP()
    num = 0
    try:
        while True:
            packet = scapy.IP(src=src_ip,
                              dst=target,
                              options=[
                                  scapy.IPOption_Stream_Id(copy_flag=1),
                                  scapy.IPOption_EOL(),
                                  scapy.IPOption_EOL()
                              ]) / scapy.ICMP()
            scapy.send(packet, verbose=False)
            num += 1
            print("Sent" + str(num) + "packets")
    except KeyboardInterrupt:
        print("Ctrl + C detected ......")
Exemple #16
0
 def ICMP_scan(self, ip):
     try:
         if "/24" in ip:
             new_ip = ip.split(".")
             for i in range(1, 100):
                 threading.Thread(
                     target=self.ICMP_scan,
                     args=(new_ip[0] + "." + new_ip[1] + "." + new_ip[2] +
                           "." + str(i), )).start()
             time.sleep(1)
             for i in range(100, 255):
                 threading.Thread(
                     target=self.ICMP_scan,
                     args=(new_ip[0] + "." + new_ip[1] + "." + new_ip[2] +
                           "." + str(i), )).start()
             time.sleep(1)
         else:
             icmp_packet = scapy.Ether() / scapy.IP(dst=ip) / scapy.ICMP()
             answered = scapy.srp1(icmp_packet,
                                   timeout=int(self.time),
                                   verbose=False)[0]
             client_dict = {
                 "ip": answered[scapy.IP].src,
                 "mac": answered[scapy.Ether].src,
                 "Ver": str(answered[scapy.IP].version)
             }  #answered[scapy.IP].version
             self.client_list_ICMP.append(client_dict)
     except TypeError:
         pass
 def ping(self):
     """
     check if host is up
     :return: True / False
     """
     packet = scapy.IP(dst=self.ip, ttl=20)/scapy.ICMP()
     reply = scapy.sr1(packet, timeout=PING_TIMEOUT, verbose=False)
     return bool(reply)
def pingIP(ip, active_ips):
	packet = scapy.IP(dst=ip, ttl=20)/scapy.ICMP()
	reply = scapy.sr1(packet, timeout=1, verbose=False)
	
	if not (reply is None):
		print ip, " is up."
		active_ips.append(ip)
	return
Exemple #19
0
def PingHost(host, _timeout):
    pkt = scapy.IP(dst=host) / scapy.ICMP()
    rply = scapy.sr1(pkt, verbose=0, timeout=_timeout)
    CustomPrint(" -  \t\tPING\t", "WHITE", False)
    if rply is None:
        CustomPrint("unsuccessful", "RED")
    else:
        CustomPrint("successful", "GREEN")
Exemple #20
0
def icmp_ping(target):
    """ICMP Ping Scan, a basic port scan using ICMP echo requests, replies indicate the source is alive."""
    ans, unans = scapy.sr(scapy.IP(dst=str(target)) / scapy.ICMP(), timeout=10)
    output = [["IP Address"]]
    for r in ans:
        d = [r[1].src]
        output.append(d)
    table = AsciiTable(output)
    print(table.table)
Exemple #21
0
def icmp_er(ip):
    icmp = sc.IP(dst=ip) / sc.ICMP()
    resp = sc.sr1(icmp, timeout=.5)
    if resp == None:
        stat = '\033[911m-\033[0m'
    else:
        stat = '\033[92m+\033[0m'

    return ip + stat
 def test_detect_icmp(self):
     """
     Test detect_icmp.
     """
     broadcast_addr = "ff:ff:ff:ff:ff:ff"
     pkt = scapy.IP(src="127.0.0.1") / scapy.Ether(dst=broadcast_addr) / scapy.ICMP(type=8)
     self.recon_obj.detect_icmp(packet=pkt)
     count = self.recon_obj.icmp_scan["127.0.0.1"]["count"]
     self.assertEqual(count, 1)
 def rr_icmp(self, dst):
     pkt = scapy.IP(dst=dst,
                    proto=1,
                    options=scapy.IPOption('\x01\x07\x27\x04' +
                                           '\x00' * 36))
     pkt /= scapy.ICMP()
     intr_icmp = scapy.sr1(pkt, timeout=2)
     if intr_icmp is not '':
         return intr_icmp.options[0].routers
Exemple #24
0
 def __init__(self, dst):
     self.burstSize = 30
     self.retryNumber = 3
     self.timeout = 0.5#segs?
     self.maxTtl = 30
     self.destination = sp.Net(dst)
     self.echoRequests = sp.IP(dst=self.destination, ttl=(1,self.maxTtl)) / sp.ICMP()
     self.traced = []
     self.trace()
Exemple #25
0
def ping(ip):
    icmp_packet = scapy.ICMP()
    ip = scapy.IP(dst=ip)
    ping = ip / icmp_packet
    result = scapy.sr1(ping, timeout=0.5, verbose=0)
    if result == None:
        return False
    else:
        return True
Exemple #26
0
    def probeICMP(self):
        p = scapy.IP(dst=self.target)/scapy.ICMP()
        res = scapy.sr1(p, timeout = self.timeout)
        hops = None

        if res:
            hops = res.ttl
        
        self.probeResults["ICMP"] = hops
        return hops
Exemple #27
0
def ping(send_if, dst_ip, args):
    ether = sp.Ether()
    ip = sp.IP(dst=dst_ip)
    icmp = sp.ICMP(type='echo-request')
    raw = sp.Raw(str(PAYLOAD_MAGIC))

    if args.send_tos:
        ip.tos = int(args.send_tos[0])

    req = ether / ip / icmp / raw
    sp.sendp(req, iface=send_if, verbose=False)
def ICMPReply(version, srcaddr, dstaddr, packet):
    ip = _GetIpLayer(version)
    # Scapy doesn't provide an ICMP echo reply constructor.
    icmpv4_reply = lambda **kwargs: scapy.ICMP(type=0, **kwargs)
    icmp = {4: icmpv4_reply, 6: scapy.ICMPv6EchoReply}[version]
    packet = (ip(src=srcaddr, dst=dstaddr) /
              icmp(id=PING_IDENT, seq=PING_SEQ) / PING_PAYLOAD)
    # IPv6 only started copying the tclass to echo replies in 3.14.
    if version == 4 or net_test.LINUX_VERSION >= (3, 14):
        _SetPacketTos(packet, PING_TOS)
    return ("ICMPv%d echo reply" % version, packet)
Exemple #29
0
 def SendTimeExceeded(self, version, packet):
     if version == 4:
         src = packet.getlayer(scapy.IP).src
         self.SendPacket(
             scapy.IP(src=self.INTERMEDIATE_IPV4, dst=src) /
             scapy.ICMP(type=11, code=0) / packet)
     elif version == 6:
         src = packet.getlayer(scapy.IPv6).src
         self.SendPacket(
             scapy.IPv6(src=self.INTERMEDIATE_IPV6, dst=src) /
             scapy.ICMPv6TimeExceeded(code=0) / packet)
def ping(intf):
    global sent_ping

    ether = sp.Ether()
    ip = sp.IP(dst="203.0.113.2", src="198.51.100.2")
    icmp = sp.ICMP(type='echo-request')
    raw = sp.raw(bytes.fromhex('00010203'))

    req = ether / ip / icmp / raw
    sp.sendp(req, iface=intf, verbose=False)
    sent_ping = time.time()