def __pcap_to_df(pcap_file: str) -> pd.DataFrame: with open(pcap_file, "rb") as f: _pcap = pcap.Reader(f) ref_time = None data = [] for ts, buf in _pcap: eth = ethernet.Ethernet(buf) ip = eth.data tcp = ip.data if ref_time is None: ref_time = ts direction = 1 if tcp.sport == 22 else -1 data.append({ "time": (ts - ref_time) * 1000, "size": direction * ip.len }) if len(data) == 0: data.append({"time": 0, "size": 0}) return pd.DataFrame(data, columns=["time", "size"])
def main(): # Ethernet header eth = ethernet.Ethernet() eth.src = "\x00\x0c\x29\xdf\xe3\xca" eth.dst = "\x00\x0c\x29\x29\x85\xdc" eth.type = ethernet.ETH_TYPE_IP # IP header ipp = ip.IP() ipp.src = socket.inet_aton("172.168.177.133") ipp.dst = socket.inet_aton("172.168.177.136") ipp.p = ip.IP_PROTO_TCP # TCP header tcpp = tcp.TCP() tcpp.sport = 60001 tcpp.dport = 80 tcpp.flags = tcp.TH_SYN tcpp.sum = 0 tcpp.data = "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x10" ipp.data = tcpp ipp.len = len(ipp.pack()) ipp.sum = 0 eth.data = ipp # open sockets using the socket handler sock_l2 = SocketHndl(iface_name="eth2", mode=SocketHndl.MODE_LAYER_2) # send raw bytes sock_l2.send(eth.pack())
def recv_arp(self, timeout): s = socket.socket(socket.PF_PACKET, socket.SOCK_RAW) iface = self.conf.CHALLENGER_INTERFACE s.bind((iface, ethernet.ETH_TYPE_ARP)) s.settimeout(timeout) data = s.recv(1024) answer = ethernet.Ethernet(data) arp_p = answer.data return myarp(arp_p)
def make_ncn_lldp_frame(switch_id, port_id, marker, src_mac='\x11\x22\x33\x44\x55\x66', dst_mac='\xaa\xbb\xcc\xdd\xee\xff'): payload = ( make_lldp_tlv(LLDP_TYPE_CHASSIS_ID, lldp_local_value(switch_id)) + make_lldp_tlv(LLDP_TYPE_PORT_ID, lldp_local_value(port_id)) + make_lldp_tlv(LLDP_TYPE_TTL, '\x00\x00') + make_lldp_tlv(LLDP_TYPE_CUSTOM, OPENFLOW_OUI + marker) + make_lldp_tlv(LLDP_TYPE_END, '')) return eth.Ethernet(src=src_mac, dst=dst_mac, type=0x88cc, data=payload)
def send_arp(self, arp_p, eth): mac = self.get_mac() packet = ethernet.Ethernet() packet.src = myeth.eth_aton(mac) packet.dst = eth packet.data = arp_p packet.type = ethernet.ETH_TYPE_ARP s = socket.socket(socket.PF_PACKET, socket.SOCK_RAW) iface = self.conf.CHALLENGER_INTERFACE s.bind((iface, ethernet.ETH_TYPE_ARP)) s.send(str(packet))
def on_cdp_packet(header, data): ether_frame = ethernet.Ethernet(data) cdp_packet = ether_frame.cdp cdp_info = {} for info in cdp_packet.data: cdp_info.update({info.type: info.data}) addresses = [ socket.inet_ntoa(x.data) for x in cdp_info[cdp.CDP_ADDRESS] ] print "Hey, %s is at %s." % (cdp_info[cdp.CDP_DEVID], ", ".join(addresses))
def buildArp(addr): arp_p = arp.ARP() arp_p.sha = eth_aton(mac) # sender hardware addr arp_p.spa = socket.inet_aton(inet) # sender ip addr arp_p.tha = ETH_ADDR_UNSPEC # dest hardware addr arp_p.tpa = socket.inet_aton(addr) # ip addr of request arp_p.op = arp.ARP_OP_REQUEST packet = ethernet.Ethernet() packet.src = eth_aton(mac) packet.dst = ETH_ADDR_BROADCAST packet.data = arp_p packet.type = ethernet.ETH_TYPE_ARP if debug: print dpkt.hexdump(str(packet)) return packet
def buildArpReply(pair): arp_p = arp.ARP() arp_p.sha = eth_aton(pair.smac) # sender hardware addr arp_p.spa = socket.inet_aton(pair.sip) # sender ip addr arp_p.tha = eth_aton(pair.rmac) # dest hardware addr arp_p.tpa = socket.inet_aton(pair.rip) # ip addr of request arp_p.op = arp.ARP_OP_REPLY packet = ethernet.Ethernet() packet.src = eth_aton(pair.smac) packet.dst = socket.inet_aton(pair.sip) packet.data = arp_p packet.type = ethernet.ETH_TYPE_ARP if debug: print dpkt.hexdump(str(packet)) return packet
def on_cdp_packet(header, data): ether_frame = ethernet.Ethernet(data) # The Start of the CDP Packet is at byte position 22, but the important data starts at byte 26. # Let's also grab the len of the entire frame eth_len = len(ether_frame) start_of_cdp = 22 start_of_cdp_data = 26 # Start Iterating through the packet until we find the appropriate typeID fields. counter = start_of_cdp_data while counter < eth_len: # Grab first two bytes, these are the TYPEID of the CDP Packet typeid = 256 * ord(data[counter]) + ord(data[counter + 1]) # Grab the next two bytes which represent the length of this setion of the CDP Packet length = 256 * ord(data[counter + 2]) + ord(data[counter + 3]) # print "Typeid: "+str(typeid) + " Length: "+str(length) # Finally, let's grab the entire data portion. This part houses the information fields cdp_field = data[counter + 4:counter + length] # We are only looking for the Device ID (i.e., Switchname) and the Port ID that we are connected to. # However, this code can grab and parse any other data that we received. if typeid == 1: #print "Device ID Found: "+cdp_field switch_name = cdp_field elif typeid == 3: #print "Port ID Found: "+cdp_field port_id = cdp_field elif typeid == 6: #print "Switch Type Found: "+cdp_field switch_type = cdp_field # Let's increment past that current field and move to the next "TYPEID" location counter = counter + length print "\nWe are currently attached to: " + switch_name + " which is a: " + switch_type + " on Port: " + port_id
def parse_pcaps(): """ Iterates over all pcap files, registers all ports that are contacted before target port is reached, per file. """ # get pcap files from directory ports = {} pcap_file_names = get_pcap_files() for pcap_file_name in pcap_file_names: # print("reading %s" % pcap_file_name) f = open(pcap_file_name) pcap_file = pcap.Reader(f) # iterate over all packets inside pcap for ts, buf in pcap_file: eth = ethernet.Ethernet(buf) ip = eth.data # only process TCP packets if (type(ip.data) is tcp.TCP and ip.data.flags == 2): tcp_packet = ip.data port = tcp_packet.dport # stop iteration if target port is found if (port in [80]): break # otherwise, increment counter else: if port in ports: ports[port] += 1 else: ports[port] = 1 f.close() # convert dict to list of tuples so it can be sorted ports_list = [] for port in ports: port_tuple = (port, ports[port]) ports_list.append(port_tuple) # sort list return sorted(ports_list, key=lambda x: x[1], reverse=True)
def on_cdp_packet(header, data): global inventory global escape global numpackets global debug numpackets += 1 if debug: print "Captured %d packets" % numpackets ether_frame = ethernet.Ethernet(data) cdp_packet = ether_frame["cdp"] src = binascii.hexlify(ether_frame["src"]) src_mac = ':'.join(src[i:i + 2] for i in range(0, 12, 2)) cdp_info = {} for info in cdp_packet.data: cdp_info.update({info['type']: info['data']}) if cdp.CDP_ADDRESS in cdp_info.keys(): addresses = [ socket.inet_ntoa(x.data) for x in cdp_info[cdp.CDP_ADDRESS] ] if len(addresses) < 2: address = addresses[0] else: address = "" output = {'ID': cdp_info[cdp.CDP_DEVID], 'IP': address, 'Port': cdp_info[cdp.CDP_PORTID], \ 'Version': cdp_info[cdp.CDP_VERSION], \ 'Platform':cdp_info[cdp.CDP_PLATFORM], "Source_MAC": src_mac} if debug: print output if output["Source_MAC"] in inventory.keys( ): # if there is record in inventory if output == inventory[ output["Source_MAC"]]: # if records are identical escape = True if debug: print "Captured duplicate packet. Exiting." else: inventory[output["Source_MAC"]] = output
def build_arp_reply(self, rec_mac, rec_ip, send_mac, impersonate_ip): """ Build an ARP-Reply-Packet """ # (1) Building the ARP-Packet arp_p = arp.ARP() # sender's hardware address arp_p.sha = dnet.eth_aton(send_mac) # sender's protocol address arp_p.spa = socket.inet_aton(impersonate_ip) # target's hardware address arp_p.tha = dnet.eth_aton(rec_mac) # target's protocol address arp_p.tpa = socket.inet_aton(rec_ip) # type of operation arp_p.op = arp.ARP_OP_REPLY # (2) Building the wrapping Ethernet-Packet packet = ethernet.Ethernet() # sender's hardware address packet.src = dnet.eth_aton(send_mac) # target's hardware address packet.dst = dnet.eth_aton(rec_mac) # payload (ARP-Packet) packet.data = arp_p # type of ethernet packet packet.type = ethernet.ETH_TYPE_ARP return packet
def parse_pcaps(): """ Iterate over all pcap files and check whether target ports were opened or closed Returns a tuple of (<total_scans>, <open_ports_count>) """ # get pcap files from directory pcap_file_names = get_pcap_files() total_scans = 0 open_target_ports = 0 # iterate over pcap file for pcap_file_name in pcap_file_names: f = open(pcap_file_name) pcap_file = pcap.Reader(f) total_scans += 1 # iterate over all packets inside pcap for ts, buf in pcap_file: eth = ethernet.Ethernet(buf) ip = eth.data # only process TCP packets try: if (type(ip.data) is tcp.TCP and ip.data.sport in target_ports): # SYN,ACK flag indicates that port is open if (ip.data.flags == 18): open_target_ports += 1 print("Found open port %d with flag %d" % (ip.data.sport, ip.data.flags)) break except: pass f.close() return (total_scans, open_target_ports)
print "Results..." while 1: data = s.recv(1024) if debug: print dpkt.hexdump(data) sys.stdout.flush() answer = ethernet.Ethernet(data) arp_p = answer.data orig = socket.inet_ntoa( arp_p.spa ) mac_add = eth_ntoa( arp_p.sha) dest = socket.inet_ntoa( arp_p.tpa ) if debug:print dpkt.hexdump( str(arp_p) ) if arp_p.op != arp.ARP_OP_REQUEST: if dest == inet: print "Anser: %s is at %s" % (orig,mac_add) else: print "Not for me.. Origin:%s Target:%s Answer:%s" % (orig, dest,mac_add)
from dpkt import ethernet sysintf = 'eth0' hw = dnet.eth(sysintf) intf = dnet.intf() # build a dhcp discover packet to request an ip d = dhcp.DHCP(chaddr=hw.get(), xid=1337, op=dhcp.DHCPDISCOVER, opts=((dhcp.DHCP_OP_REQUEST, ''), (dhcp.DHCP_OPT_REQ_IP, ''), (dhcp.DHCP_OPT_ROUTER, ''), (dhcp.DHCP_OPT_NETMASK, ''), (dhcp.DHCP_OPT_DNS_SVRS, ''))) # build udp packet u = udp.UDP(dport=67, sport=68, data=d) u.ulen = len(u) # build ip packet i = ip.IP(dst=dnet.ip_aton('255.255.255.255'), src=intf.get(sysintf)['addr'].ip, data=u, p=ip.IP_PROTO_UDP) i.len = len(i) # build ethernet frame e = ethernet.Ethernet(dst=dnet.ETH_ADDR_BROADCAST, src=hw.get(), data=i) # send the data out hw.send(str(e))
# Get local ip src_ip = socket.inet_pton(socket.AF_INET, interface.getnet()) # Generate broadcast ip and eth_addr broadcast_ip = socket.inet_pton(socket.AF_INET, '255.255.255.255') broadcast_eth_addr = b'\xFF\xFF\xFF\xFF\xFF\xFF' # build a dhcp discover packet to request an ip d = dhcp.DHCP(xid=1337, op=dhcp.DHCPDISCOVER, opts=((dhcp.DHCP_OP_REQUEST, b''), (dhcp.DHCP_OPT_REQ_IP, b''), (dhcp.DHCP_OPT_ROUTER, b''), (dhcp.DHCP_OPT_NETMASK, b''), (dhcp.DHCP_OPT_DNS_SVRS, b''))) # build udp packet u = udp.UDP(dport=67, sport=68, data=d) u.ulen = len(u) # build ip packet i = ip.IP(dst=broadcast_ip, src=src_ip, data=u, p=ip.IP_PROTO_UDP) i.len = len(i) # build ethernet frame e = ethernet.Ethernet(dst=broadcast_eth_addr, data=i) # Inject the packet (send it out) interface.sendpacket(bytes(e)) print('DHCP request sent!')
def _filter_pcap(self, output_pcap): """Using a provided file with XML flow summaries, create a new PCAP file with the flows in the XML file. :param output_pcap: Path for the new PCAP file. """ try: print("Opening file: {0}".format(self._pcap)) f = open(self._pcap) raw_pcap = pcap.Reader(f) pckt_num = 0 for ts, buf in raw_pcap: pckt_num += 1 if not pckt_num % 1000: # Print every thousandth packets, just to monitor # progress. print("\tProcessing packet #{0}".format(pckt_num)) # Loop through packets in PCAP file eth = ethernet.Ethernet(buf) if eth.type != ETH_TYPE_IP: # We are only interested in IP packets continue ip = eth.data ip_src = socket.inet_ntop(socket.AF_INET, ip.src) ip_dst = socket.inet_ntop(socket.AF_INET, ip.dst) ip_proto = ip.p match = False for flow in self._raw_data: # Does this packet match a flow in the raw data? if ((ip_src == flow["source"] and ip_dst == flow["destination"]) or (ip_src == flow["destination"] and ip_dst == flow["source"])): if ip_proto == IP_PROTO_TCP and flow[ "protocolName"] == "tcp_ip": tcp = ip.data if self._check_port_num(tcp.sport, tcp.dport, flow["sourcePort"], flow["destinationPort"]): if self._check_timestamp( ts, flow["startDateTime"], flow["stopDateTime"]): # We have found a match, stop looping match = True break elif ip_proto == IP_PROTO_UDP and flow[ "protocolName"] == "udp_ip": udp = ip.data if self._check_port_num(udp.sport, udp.dport, flow["sourcePort"], flow["destinationPort"]): if self._check_timestamp( ts, flow["startDateTime"], flow["stopDateTime"]): # We have found a match, stop looping match = True break elif ip_proto == IP_PROTO_ICMP and flow[ "protocolName"] == "icmp_ip": if self._check_timestamp(ts, flow["startDateTime"], flow["stopDateTime"]): # We have found a match, stop looping break match = True elif ip_proto == IP_PROTO_IGMP and flow[ "protocolName"] == "igmp": if self._check_timestamp(ts, flow["startDateTime"], flow["stopDateTime"]): # We have found a match, stop looping match = True break if match: # The packet matches the flow. Append the packet data # to the new PCAP file and move onto the next packet. try: print( "\tWrting packet to file: {0}".format(output_pcap)) f_out = open(output_pcap, "ab") pcap_out = pcap.Writer(f_out) pcap_out.writepkt(buf, ts=ts) except: exc_type, exc_value, exc_traceback = sys.exc_info() print("ERROR writing to file: {0}.\n\t" "Exception: {1}, {2}, {3}".format( output_pcap, exc_type, exc_value, exc_traceback)) sys.exit(1) finally: f_out.close except: exc_type, exc_value, exc_traceback = sys.exc_info() print("ERROR reading from file: {0}.\n\tException: {1}, " "{2}, {3}".format(self._pcap, exc_type, exc_value, exc_traceback)) sys.exit(1) finally: f.close()
# Boston, MA 02110-1301, USA. """ This modules provides classes used for packet processing. """ from abc import ABCMeta import socket import struct from dpkt import dpkt, ethernet, ip, udp from . import vxfld_pb2 # Protocol version VERSION = 3 # UDP header byte length BASE_PKT_SIZE = len(ethernet.Ethernet()) + len(ip.IP()) + len(udp.UDP()) class MsgType(object): """ VXFLD message type. """ # pylint: disable=too-few-public-methods UNKNOWN = 0 # Never used REFRESH = 1 # vxrd <-> vxsnd packet PROXY = 2 # vxsnd <-> vxsnd packet for flooding and proxing SYNC = 3 # vxsnd <-> vxsnd packet for database syncing def __init__(self): raise NotImplementedError
s = sum(array.array('H',pkt)) s = (s >> 16) + (s & 0xffff) s += s >> 16 s = ~s if sys.byteorder == 'little': s = (s >> 8 & 0xff) | s << 8 return s & 0xffff tmp_packet =b'\x00\x12\xc0\x02\xac\x56\x00\x12\xc0\x00\x00\x00\x08\x00\x45\x00\x00\x2e\x00\x00\x40\x00\x40\x06\x00\x00\x0a\x0a\x58\x00\x0a\x0a\x58\xac\x00\x00\x00\x50\x00\x00\x00\x00\x00\x00\x00\x00\x50\x10\x00\x10\x00\x00\x00\x00\x41\x43\x4b\x73\x77\x66' def getOnebyte(): tmp = randint(0,255) return tmp.to_bytes(1,byteorder='big',signed=False) eth = ethernet.Ethernet() eth.src = b'\x00\x12\xc0\x02\xac' + getOnebyte() eth.dst = b'x00\x12\xc0\x00\x00\x00' eth_ip = ip.IP() ip_tcp = tcp.TCP() ip_tcp.sport = 8080 ip_tcp.dport = 80 ip_tcp.seq = 0x01 ip_tcp.ack =0x88 ip_tcp.flags = tcp.TH_SYN
from dpkt import pcap,ethernet,UnpackError,tcp,ip from sys import argv def parseIP(hexstring): attackip = [] for i in range(0, len(hexstring), 2): attackip.append(str(int(hexstring[i:i + 2], 16))) print attackip[0] + '.' + attackip[1] + '.' + attackip[2] + '.' + attackip[3] f=open(argv[1],"rb") pcap = pcap.Reader(f) dict = {} for ts, buf in pcap: try: eth = ethernet.Ethernet(buf) except UnpackError: continue if eth.type != ethernet.ETH_TYPE_IP: continue ip = eth.data if ip.p == 6: packet = ip.data if packet.flags & tcp.TH_SYN != 0: if ip.src not in dict: dict[ip.src] = {'SYN': 0, 'SYN+ACK': 0} if ip.dst not in dict: dict[ip.dst] = {'SYN': 0, 'SYN+ACK': 0} if packet.flags & tcp.TH_ACK != 0: dict[ip.dst]['SYN+ACK'] += 1 else: