github.com/n00py/Slackor@v0.0.0-20200610224921-d007fcea1740/impacket/examples/ping.py (about) 1 #!/usr/bin/env python 2 # SECUREAUTH LABS. Copyright 2018 SecureAuth Corporation. All rights reserved. 3 # 4 # This software is provided under under a slightly modified version 5 # of the Apache Software License. See the accompanying LICENSE file 6 # for more information. 7 # 8 # Simple ICMP ping. 9 # 10 # This implementation of ping uses the ICMP echo and echo-reply packets 11 # to check the status of a host. If the remote host is up, it should reply 12 # to the echo probe with an echo-reply packet. 13 # Note that this isn't a definite test, as in the case the remote host is up 14 # but refuses to reply the probes. 15 # Also note that the user must have special access to be able to open a raw 16 # socket, which this program requires. 17 # 18 # Authors: 19 # Gerardo Richarte <gera@coresecurity.com> 20 # Javier Kohen <jkohen@coresecurity.com> 21 # 22 # Reference for: 23 # ImpactPacket: IP, ICMP, DATA. 24 # ImpactDecoder. 25 26 import select 27 import socket 28 import time 29 import sys 30 31 from impacket import ImpactDecoder, ImpactPacket 32 33 if len(sys.argv) < 3: 34 print("Use: %s <src ip> <dst ip>" % sys.argv[0]) 35 sys.exit(1) 36 37 src = sys.argv[1] 38 dst = sys.argv[2] 39 40 # Create a new IP packet and set its source and destination addresses. 41 42 ip = ImpactPacket.IP() 43 ip.set_ip_src(src) 44 ip.set_ip_dst(dst) 45 46 # Create a new ICMP packet of type ECHO. 47 48 icmp = ImpactPacket.ICMP() 49 icmp.set_icmp_type(icmp.ICMP_ECHO) 50 51 # Include a 156-character long payload inside the ICMP packet. 52 icmp.contains(ImpactPacket.Data("A"*156)) 53 54 # Have the IP packet contain the ICMP packet (along with its payload). 55 ip.contains(icmp) 56 57 # Open a raw socket. Special permissions are usually required. 58 s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) 59 s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) 60 61 seq_id = 0 62 while 1: 63 # Give the ICMP packet the next ID in the sequence. 64 seq_id += 1 65 icmp.set_icmp_id(seq_id) 66 67 # Calculate its checksum. 68 icmp.set_icmp_cksum(0) 69 icmp.auto_checksum = 1 70 71 # Send it to the target host. 72 s.sendto(ip.get_packet(), (dst, 0)) 73 74 # Wait for incoming replies. 75 if s in select.select([s],[],[],1)[0]: 76 reply = s.recvfrom(2000)[0] 77 78 # Use ImpactDecoder to reconstruct the packet hierarchy. 79 rip = ImpactDecoder.IPDecoder().decode(reply) 80 # Extract the ICMP packet from its container (the IP packet). 81 ricmp = rip.child() 82 83 # If the packet matches, report it to the user. 84 if rip.get_ip_dst() == src and rip.get_ip_src() == dst and icmp.ICMP_ECHOREPLY == ricmp.get_icmp_type(): 85 print("Ping reply for sequence #%d" % ricmp.get_icmp_id()) 86 87 time.sleep(1)