def ping_packet(seq=0, src=DEFAULT_SOURCE_IP, dst=DEFAULT_DEST_IP, length=-1): icmp_packet = ICMP(seq=seq, type=8, code=0) / "XXXXXX" icmp_packet = ICMP(icmp_packet.do_build()) # Force checksum calculation icmp_length = length if length == -1: icmp_length = len(icmp_packet) ping = LLC(dsap=0xaa, ssap=0xaa, ctrl=0x03) \ / SNAP(OUI=0x000000, code=ETH_P_IP) \ / IP(src=src, dst=dst, len=(20 + icmp_length)) \ / icmp_packet return ping
def _create_icmp(self, pg, memif, num): pkts = [] for i in range(num): pkt = (Ether(dst=pg.local_mac, src=pg.remote_mac) / IP(src=pg.remote_ip4, dst=memif.ip4_addr) / ICMP(id=memif.if_id, type='echo-request', seq=i)) pkts.append(pkt) return pkts
def _create_icmp(self, pg, memif, num): pkts = [] for i in range(num): pkt = (Ether(dst=pg.local_mac, src=pg.remote_mac) / IP( src=pg.remote_ip4, dst=str(memif.ip_prefix.network_address)) / ICMP(id=memif.if_id, type="echo-request", seq=i)) pkts.append(pkt) return pkts
def router_icmp_a(testname): hs = TESTS[testname].host_s router = TESTS[testname].router r_mac = info.get("router_mac", router, hs) r_ip = info.get("router_ip", hs) s_mac = info.get("host_mac", hs) s_ip = info.get("host_ip", hs) return [Ether(src=s_mac, dst=r_mac) / IP(src=s_ip, dst=r_ip) / ICMP()]
def main(): while True: command = input("# Enter command: ") pinger = IP(dst='localhost') / ICMP(id=0x0001, seq=0x1) / command send(pinger) rx = sniff(count=1, timeout=2) print(rx[0][Raw].load.decode('utf-8'))
def create_stream(self, src_if, packet_sizes, traffic_type=0, ipv6=0, proto=-1, ports=0, fragments=False): """ Create input packet stream for defined interface using hosts or deleted_hosts list. :param object src_if: Interface to create packet stream for. :param list packet_sizes: List of required packet sizes. :param traffic_type: 1: ICMP packet, 2: IPv6 with EH, 0: otherwise. :return: Stream of packets. """ pkts = [] if self.flows.__contains__(src_if): src_hosts = self.hosts_by_pg_idx[src_if.sw_if_index] for dst_if in self.flows[src_if]: dst_hosts = self.hosts_by_pg_idx[dst_if.sw_if_index] n_int = len(dst_hosts) * len(src_hosts) for i in range(0, n_int): dst_host = dst_hosts[i / len(src_hosts)] src_host = src_hosts[i % len(src_hosts)] pkt_info = self.create_packet_info(src_if, dst_if) if ipv6 == 1: pkt_info.ip = 1 elif ipv6 == 0: pkt_info.ip = 0 else: pkt_info.ip = random.choice([0, 1]) if proto == -1: pkt_info.proto = random.choice(self.proto[self.IP]) else: pkt_info.proto = proto payload = self.info_to_payload(pkt_info) p = Ether(dst=dst_host.mac, src=src_host.mac) if pkt_info.ip: p /= IPv6(dst=dst_host.ip6, src=src_host.ip6) if fragments: p /= IPv6ExtHdrFragment(offset=64, m=1) else: if fragments: p /= IP(src=src_host.ip4, dst=dst_host.ip4, flags=1, frag=64) else: p /= IP(src=src_host.ip4, dst=dst_host.ip4) if traffic_type == self.ICMP: if pkt_info.ip: p /= ICMPv6EchoRequest(type=self.icmp6_type, code=self.icmp6_code) else: p /= ICMP(type=self.icmp4_type, code=self.icmp4_code) else: p /= self.create_upper_layer(i, pkt_info.proto, ports) p /= Raw(payload) pkt_info.data = p.copy() size = random.choice(packet_sizes) self.extend_packet(p, size) pkts.append(p) return pkts
def main(): args = TrafficScriptArg( ['tx_dst_mac', 'rx_dst_mac', 'inner_src_ip', 'inner_dst_ip', 'outer_src_ip', 'outer_dst_ip']) tx_if = args.get_arg('tx_if') rx_if = args.get_arg('rx_if') tx_dst_mac = args.get_arg('tx_dst_mac') rx_dst_mac = args.get_arg('rx_dst_mac') inner_src_ip = args.get_arg('inner_src_ip') inner_dst_ip = args.get_arg('inner_dst_ip') outer_src_ip = args.get_arg('outer_src_ip') outer_dst_ip = args.get_arg('outer_dst_ip') rxq = RxQueue(rx_if) txq = TxQueue(tx_if) sent_packets = [] tx_pkt_raw = Ether(dst=tx_dst_mac) / \ IP(src=inner_src_ip, dst=inner_dst_ip) / \ ICMP() sent_packets.append(tx_pkt_raw) txq.send(tx_pkt_raw) ether = rxq.recv(2) if ether is None: raise RuntimeError("ICMP echo Rx timeout") # Check RX headers if ether.dst != rx_dst_mac: raise RuntimeError("Matching of received destination MAC unsuccessful.") logger.debug("Comparison of received destination MAC: OK.") if ether['IP'].src != outer_src_ip: raise RuntimeError("Matching of received outer source IP unsuccessful.") logger.debug("Comparison of received outer source IP: OK.") if ether['IP'].dst != outer_dst_ip: raise RuntimeError( "Matching of received outer destination IP unsuccessful.") logger.debug("Comparison of received outer destination IP: OK.") if ether['IP'].proto != IP_PROTOS.gre: raise RuntimeError("IP protocol is no GRE.") logger.debug("Comparison of received GRE protocol: OK.") if ether['IP']['GRE']['IP'].src != inner_src_ip: raise RuntimeError("Matching of received inner source IP unsuccessful.") logger.debug("Comparison of received inner source IP: OK.") if ether['IP']['GRE']['IP'].dst != inner_dst_ip: raise RuntimeError( "Matching of received inner destination IP unsuccessful.") logger.debug("Comparison of received inner destination IP: OK.") sys.exit(0)
def verify_capture(self, dst_ip_if, src_ip_if, capture, reverse): last_info = dict() for i in self.interfaces: last_info[i.sw_if_index] = None dst_ip_sw_if_index = dst_ip_if.sw_if_index return for packet in capture: l3 = IP if packet.haslayer(IP) else IPv6 ip = packet[l3] if packet.haslayer(UDP): l4 = UDP else: if packet.haslayer(ICMP): l4 = ICMP else: l4 = ICMPv6Unknown # Scapy IPv6 stuff is too smart for its own good. # So we do this and coerce the ICMP into unknown type if packet.haslayer(UDP): data = str(packet[UDP][Raw]) else: if l3 == IP: data = str(ICMP(str(packet[l3].payload))[Raw]) else: data = str(ICMPv6Unknown(str(packet[l3].payload)).msgbody) udp_or_icmp = packet[l3].payload payload_info = self.payload_to_info(data) packet_index = payload_info.index self.assertEqual(payload_info.dst, dst_ip_sw_if_index) next_info = self.get_next_packet_info_for_interface2( payload_info.src, dst_ip_sw_if_index, last_info[payload_info.src]) last_info[payload_info.src] = next_info self.assertTrue(next_info is not None) self.assertEqual(packet_index, next_info.index) saved_packet = next_info.data self.assertTrue(next_info is not None) # MAC: src, dst if not reverse: self.assertEqual(packet.src, dst_ip_if.local_mac) host = dst_ip_if.host_by_mac(packet.dst) # IP: src, dst # self.assertEqual(ip.src, src_ip_if.remote_ip4) if saved_packet is not None: self.assertEqual(ip.src, saved_packet[l3].src) self.assertEqual(ip.dst, saved_packet[l3].dst) if l4 == UDP: self.assertEqual(udp_or_icmp.sport, saved_packet[l4].sport) self.assertEqual(udp_or_icmp.dport, saved_packet[l4].dport) else: print("Saved packet is none")
def reply(pkt): """ Reply to the packet which the sniffer capture. """ if pkt[ICMP].type == 8: ip = IP() ip.dst = pkt[IP].src ip.src = pkt[IP].dst icmp = ICMP() icmp.id = pkt[ICMP].id icmp.seq = pkt[ICMP].seq icmp.type = 0 raw = Raw() raw.load = pkt[Raw].load send(ip / icmp / raw)
def discover_hosts(self, hosts): """ Host discovery of a list of hosts. """ active_hosts = [] for target in hosts: ans, _ = sr(IP(dst=target) / ICMP(), verbose=False, timeout=5) for host in ans: _, b = host active_hosts.append(b.src) # Append active host return active_hosts
def check_host(self, host): """ Check if host is online """ try: ip = IP(dst=host) icmp = ICMP() sr1(ip / icmp, verbose=False, timeout=1) return True except Exception: return False
def handle_check_ping( pkt): # the third method which checking if we are under attack global FLAG3 if pkt[ARP].op != 2: # check whether the our arp packet is:"is at" packet, if not we don't need to continue with it... return r = srp(Ether(dst=pkt[ARP].hwsrc) / IP(dst=pkt[ARP].psrc) / ICMP(), timeout=0.5) if len(r[1]) != 0: FLAG3 = 1
def build_own_packet(src, dst, message): """ Creates packet to be sent in the network. :param message: string message to be send :param src: source address :param dst: destination address :return: packet with layer 3, 4 and the message -> IP / ICMP / Message. """ return IP(src=src, dst=dst) / ICMP() / message
def active_host(ipaddr: str) -> bool: """Ping a target host using the specified IPv4 address. Return true if target responds to our ICMP probe""" packet = IP(dst=ipaddr) / ICMP() response = sr1(packet, timeout=5, verbose=0) if response: return True else: return False
def sourcenat_test_icmp_echo4_conf(self): sports = [1234, 1235] dports = [6661, 6662] for nbr, remote_host in enumerate(self.pg1.remote_hosts): IP46 = IP client_addr = self.pg0.remote_hosts[0].ip4 remote_addr = self.pg1.remote_hosts[nbr].ip4 src_nat_addr = self.pg2.remote_hosts[0].ip4 # ping from pods to outside network p1 = ( Ether(dst=self.pg0.local_mac, src=self.pg0.remote_hosts[0].mac) / IP46(src=client_addr, dst=remote_addr) / ICMP(type=8, id=0xfeed) / Raw()) rxs = self.send_and_expect( self.pg0, p1 * N_PKTS, self.pg1) for rx in rxs: self.assertEqual(rx[IP46].src, src_nat_addr) self.assert_packet_checksums_valid(rx) received_id = rx[0][ICMP].id # ping reply from outside to pods p2 = ( Ether(dst=self.pg1.local_mac, src=self.pg1.remote_hosts[nbr].mac) / IP46(src=remote_addr, dst=src_nat_addr) / ICMP(type=0, id=received_id)) rxs = self.send_and_expect( self.pg1, p2 * N_PKTS, self.pg0) for rx in rxs: self.assert_packet_checksums_valid(rx) self.assertEqual(rx[IP46].src, remote_addr) self.assertEqual(rx[ICMP].id, 0xfeed)
def checkhost(ip): # Function to check if target is up conf.verb = 0 # Hide output try: ping = sr1(IP(dst=ip) / ICMP()) # Ping the target print(ping) print("\n[*] Target is Up, Beginning Scan...") except Exception: # If ping fails print("\n[!] Couldn't Resolve Target") print("[!] Exiting...") sys.exit(1)
def getOS(ip_addr): ttl_values = {32: "Windows", 60: "MAC OS", 64: "Linux", 128: "Windows", 255: "Linux 2.4 Kernal"} ans = scapy.sr1(IP(dst=str(ip_addr)) / ICMP(), timeout=1, verbose=0) if ans: if ans.ttl in ttl_values: return ttl_values.get(ans.ttl) else: return "could not figure the OS version" else: return "Packets could not send successfully"
def check_if_host_is_up(ip): try: print("Setting up ping for IP " + ip + ".") ping = sr1(IP(dst=ip) / ICMP(), timeout=10, iface="eth0", verbose=False) print("Ping successful! Beginning scan...") except Exception as e: print("Couldn't ping! Exiting...") print("The error: " + str(e)) traceback.print_exc() sys.exit(1)
def getOSInfo(self): pack = IP(dst=self.ipAddr) / ICMP() resp = sr1(pack, timeout=TIMEOUT, verbose=False) if resp == None: return elif IP in resp: if resp.getlayer(IP).ttl in self.OS2TTL: self.potentialOS = self.OS2TTL[resp.getlayer(IP).ttl] else: self.potentialOS = ["unknown"]
def send_icmp_packet(self, timeout=1.0): """ Sends an ICMP echo-request. Layer 2 content is not specified, that will be handled by the OS. Returns true if the device responded to the request, false otherwise :param int timeout: maximum time to wait for a ICMP echo-reply :return boolean: True if device answered, False otherwise """ ans, _ = sr(IP(dst=self.device.ip) / ICMP(), timeout=timeout) return len(ans)
def is_up(ip): """ Tests if host is up """ #return True icmp = IP(dst=ip) / ICMP() resp = sr1(icmp, timeout=0.5) if resp == None: #return False return True else: return True
def forward10packets_a(testname): hs = TESTS[testname].host_s hr = TESTS[testname].host_r router = TESTS[testname].router r_mac = info.get("router_mac", router, hs) target_ip = info.get("host_ip", hr) s_mac = info.get("host_mac", hs) s_ip = info.get("host_ip", hs) return [ Ether(src=s_mac, dst=r_mac) / IP(src=s_ip, dst=target_ip) / ICMP() ] * 10
def checar_TTL(ipsrc, ttl): if IPTEST(ipsrc).iptype() == 'PRIVATE': return if ipsrc not in ttl_values: pkt = sr1(IP(dst=ipsrc) / ICMP(), retry=0, timeout=1, verbose=0) ttl_values[ipsrc] = pkt.ttl if abs(int(ttl) - int(ttl_values[ipsrc])) > THRESH: print(f'\n[!] Se detecto paquete posiblemente spoofed desde: {ipsrc}') print(f'[!] TTL: {ttl}, TTL Real: {str(ttl_values[ipsrc])}')
def gen_ipv4(): mac0, ip0 = b'@WRJ_1', '10.0.1.2' ip1 = '10.0.2.2' packets = GRATUITOUS_ARPS + [ # TTL == 1 Ether(src=mac0, dst=IFACE_MAC[0]) / Dot1Q(id=IN, vlan=0) / IP(src=ip0, dst=ip1, ttl=1), Ether(src=IFACE_MAC[0], dst=mac0) / Dot1Q(id=OUT, vlan=0) / IP(src=IFACE_IPV4[0], dst=ip0, ttl=64, id=0, flags=['DF']) / ICMP(type='time-exceeded', code='ttl-zero-during-transit'), # ICMP Echo Request Ether(src=mac0, dst=IFACE_MAC[0]) / Dot1Q(id=IN, vlan=0) / IP(src=ip0, dst=IFACE_IPV4[0]) / ICMP(type='echo-request', id=1, seq=2) / b'hello', Ether(src=IFACE_MAC[0], dst=mac0) / Dot1Q(id=OUT, vlan=0) / IP(src=IFACE_IPV4[0], dst=ip0, ttl=64) / ICMP(type='echo-reply', id=1, seq=2) / b'hello', ] wrpcap("ipv4.pcap", packets)
def print_pkt(pkt): if (pkt[ICMP].type == 8): eth = Ether() eth.dst = pkt[Ether].src eth.src = pkt[Ether].dst ip = IP() ip.dst = pkt[IP].src ip.src = pkt[IP].dst ip.ihl = pkt[IP].ihl icmp = ICMP() icmp.id = pkt[ICMP].id icmp.seq = pkt[ICMP].seq icmp.type = 0 raw = Raw() raw.load = pkt[Raw].load send(eth / ip / icmp / raw)
def get_client_OS(ip): # get the OS of client in the possible_ttl_values = {32 : "Windows", 60: "Mac OS", 64: "Linux", 128: "Windows", 255: "Linux 2.4 Kernal"} sent_packet = IP(dst = str(ip)) / ICMP() answer_packet = scapy.sr1(sent_packet, timeout = 2, verbose = False) if answer_packet: if answer_packet.ttl in possible_ttl_values: return possible_ttl_values.get(answer_packet.ttl) else: return "Could not figure the OS" else: return "Packets could not be sent"
def ping_echo_request_to(host, ttl=255, timeout=1): cur_time = time.time() answer = sr1(IP(dst=host, ttl=ttl) / ICMP(), verbose=0, timeout=timeout) if answer and answer[ICMP].type == EchoReply: rtt = (time.time() - cur_time) * 1000 global rtts rtts.append(rtt) else: global loss_packets loss_packets += 1
def tracerout1(url): """makes a tracerout request using rising TTLs""" ip_list = [] req = IP(dst=url) / ICMP(type="echo-request") # makes a ping request packet1 = sr1(req) # sends the ping request ip = packet1.src # saves the ip of the ip real_packet = IP(dst=url, ttl=1) / ICMP( type="echo-request") # makes the first packet got = sr1(real_packet, timeout=0.8) # sends it counter = 2 if got: ip_list.append(got.src) while got.src != ip: # sends the request with rising TTL real_packet[IP].ttl = counter got = sr1(real_packet, timeout=0.8) if got: ip_list.append(got.src) counter += 1 # ip_list.append(ip) print ip_list
def check_TTL(ipsrc, ttl): if IPTEST(ipsrc).iptype() == 'PRIVATE': return if ipsrc not in ttl_values: pkt = sr1(IP(dst=ipsrc) / ICMP(), retry=0, timeout=1, verbose=0) ttl_values[ipsrc] = pkt.ttl if abs(int(ttl) - int(ttl_values[ipsrc])) > THRESH: print(f'\n[!] Detected Possible Spoofed Packet From: {ipsrc}') print(f'[!] TTL: {ttl}, Actual TTL: {str(ttl_values[ipsrc])}')
def ping(): #随机产生一个1-65535的IP的id位 ip_id=randint(1,65535) #随机产生一个1-65535的icmp的id位 icmp_id=randint(1,65535) #随机产生一个1-65535的icmp的序列号 icmp_seq=randint(1,65535) pkt = IP(dst='192.168.214.129', ttl=64, id=ip_id) / ICMP(id=icmp_id, seq=icmp_seq) # 发送包,超时时间为1秒,如果对端没有响应,则返回None,有响应则返回响应包 res = sr1(pkt, timeout=1, verbose=False) return res
def icmp_ping(host): """ ICMP Ping """ data = 'University' # Classical ICMP Ping can be emulated using the following command: ans, unans = sr(IP(dst=host) / ICMP() / Raw(load=data), timeout=2) # Information on live hosts can be collected with the following request: for s, r in ans: l = r[Raw].load print(l)