Save Python raw TCP/IP packet into pcap file

Namaste Friends,



In Today's Tutorial, I am going to show you how we can save various types of protocol packets including TCP/IP raw packet into pcap file.


Introduction


Friends, Many times during different types of networking projects we have to save our created or Captured raw packets into Pcap files so that we can analyze it with Wireshark. So, Today I am going to show you how you can do it. basically, we just going to create a class object that will provide us a simple way to write packets into pcap files.

Pre-requested Requirement

  • Python Syntax
  • Python Struct Module
  • Basic Networking Protocols Info 


How it's Going to work.


Actually, here I am going to create a class that will handle required operations to make a valid Pcap file and saves packets inside that pcap file.

Required Operation

1. Save Pcap Global Header
2. Attach a header with all Network packets.

For Pcap Structure Info Click here

Example Code:


1. First Import Required Modules

# import module
import struct
import time

2. Assign Required Values

#     Pcap Global Header Format :
#                       ( magic number + 
#                         major version number + 
#                         minor version number + 
#                         GMT to local correction +
#                         accuracy of timestamps + 
#                         max length of captured #packets, in octets +
#                         data link type) 
#
#

PCAP_GLOBAL_HEADER_FMT = '@ I H H i I I I '


# Global Header Values
PCAP_MAGICAL_NUMBER = 2712847316
PCAP_MJ_VERN_NUMBER = 2
PCAP_MI_VERN_NUMBER = 4
PCAP_LOCAL_CORECTIN = 0
PCAP_ACCUR_TIMSTAMP = 0
PCAP_MAX_LENGTH_CAP = 65535
PCAP_DATA_LINK_TYPE = 1

3. Create Pcap Class

class Pcap:

 def __init__(self, filename, link_type=PCAP_DATA_LINK_TYPE):
  self.pcap_file = open(filename, 'wb') 
  self.pcap_file.write(struct.pack('@ I H H i I I I ', PCAP_MAGICAL_NUMBER, PCAP_MJ_VERN_NUMBER, PCAP_MI_VERN_NUMBER, PCAP_LOCAL_CORECTIN, PCAP_ACCUR_TIMSTAMP, PCAP_MAX_LENGTH_CAP, link_type))
  print "[+] Link Type : {}".format(link_type)

 def writelist(self, data=[]):
  for i in data:
   self.write(i)
  return

 def write(self, data):
  ts_sec, ts_usec = map(int, str(time.time()).split('.'))
  length = len(data)
  self.pcap_file.write(struct.pack('@ I I I I', ts_sec, ts_usec, length, length))
  self.pcap_file.write(data)

 def close(self):
  self.pcap_file.close()


4. Final Codes.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# import module
import struct
import time

#     Pcap Global Header Format :
#                       ( magic number + 
#                         major version number + 
#                         minor version number + 
#                         GMT to local correction +
#                         accuracy of timestamps + 
#                         max length of captured #packets, in octets +
#                         data link type) 
#
#

PCAP_GLOBAL_HEADER_FMT = '@ I H H i I I I '


# Global Header Values
PCAP_MAGICAL_NUMBER = 2712847316
PCAP_MJ_VERN_NUMBER = 2
PCAP_MI_VERN_NUMBER = 4
PCAP_LOCAL_CORECTIN = 0
PCAP_ACCUR_TIMSTAMP = 0
PCAP_MAX_LENGTH_CAP = 65535
PCAP_DATA_LINK_TYPE = 1

class Pcap:

 def __init__(self, filename, link_type=PCAP_DATA_LINK_TYPE):
  self.pcap_file = open(filename, 'wb') # 4 + 2 + 2 + 4 + 4 + 4 + 4
  self.pcap_file.write(struct.pack('@ I H H i I I I ', PCAP_MAGICAL_NUMBER, PCAP_MJ_VERN_NUMBER, PCAP_MI_VERN_NUMBER, PCAP_LOCAL_CORECTIN, PCAP_ACCUR_TIMSTAMP, PCAP_MAX_LENGTH_CAP, link_type))
  print "[+] Link Type : {}".format(link_type)

 def writelist(self, data=[]):
  for i in data:
   self.write(i)
  return

 def write(self, data):
  ts_sec, ts_usec = map(int, str(time.time()).split('.'))
  length = len(data)
  self.pcap_file.write(struct.pack('@ I I I I', ts_sec, ts_usec, length, length))
  self.pcap_file.write(data)

 def close(self):
  self.pcap_file.close()


Want Test Run?


Paste Below Codes at the bottom of class


if __name__=='__main__':

    # import modules
    import socket
    import struct
    import binascii
    import os

    # Create Socket 
    if os.name == "nt":
        s = socket.socket(socket.AF_INET,socket.SOCK_RAW,socket.IPPROTO_IP)
        s.bind((raw_input("[+] YOUR_INTERFACE : "),0))
        s.setsockopt(socket.IPPROTO_IP,socket.IP_HDRINCL,1)
        s.ioctl(socket.SIO_RCVALL,socket.RCVALL_ON)
    else:
        s=socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0800))

    # Create Object
    p = Pcap('temp.pcap')

    while True:

        # Sniff Packet
        pkt=s.recvfrom(65565)
        
        # Save captured packets into pcap file
        p.write(pkt[0])

        # flush data
        p.pcap_file.flush()

    # close file
    p.close()



Now, Open temp.pcap file with Wireshark! and Done.


I hope you enjoyed this tutorial.

Written By:
                   SSB

Share this

Related Posts

Previous
Next Post »