How To Create Simple Packet Sniffer Using Python socket module

Namaste Friends,



                                     Friends, Today's Tutorial Is About How To Create Simple Packet Sniffer Using Python Language. or How To Write Python Script For Capturing Packets. or how to extract captured packets manually using python.


Friend, If You Are New in our Blog, Then Don't Forget To Follow Us On Social Media Because We Creates These Types of Tutorials in Every Small Gap.


If You are a beginner in networking, then this tutorials can be difficult to you but friends, don't lose your hope because to increase our knowledge we always needs to try harder.

And You Can Also Read Our Other Networking Posts Also.





Or You Can Also Check Our Complete Project List Here


Networking is always very harder for mostly all persons Because networking concept is very big and complex to understand.


That's why Friends, Today's topic is not so easy for beginner because for this topic, you needs detailed knowledge of networking sockets, packets and data formats.


but don't worry,


i will try my best to explain today's topic in easiest way.

so let's start our tutorial step by step.


Some Basic Queries To Under Stand Networking

Q 1. What is Packet Sniffer?


Ans. Friends, Sniffers are programs that can capture network traffic packets and parse/analyse them for various purposes. In Simple Words, Client Use Special Types Of Data Packets To Interact With Server And Here, we Will Try To Create A Program That Can Captures Those Data Packets and also Analyse Them. Normally,This Types of programs used by pentesters and by network administrative. But For Understanding Networking Concept Clearly, You Can Also Create This Sniffer.

Now, Our Second Query Is

Q 2. How This Programs Works?


Ans. This Programs Run In Very Clear Concept. Every Client Interact With Server Through Sending and receiving special data Packets.  In Simple Words, Every System Needs To Send Packets To Server Address For Any Type Of Request And Server Also Replies his answer In small data Packets. So, These Types Of  Programs Try To Capture Data Packets That are passing or flowing from our local Internet sockets or from our local internet Cables. Here, First, We will capture packets from our networking sockets. and then, we will also extract those packets.

Q 3. How To Capture Packets?


Ans.  If You Are Using  Windows Then, Use This Codes ,


s = socket.socket(socket.AF_INET,socket.SOCK_RAW,socket.IPPROTO_IP)
s.bind(("YOUR_INTERFACE_IP",0))
s.setsockopt(socket.IPPROTO_IP,socket.IP_HDRINCL,1)
s.ioctl(socket.SIO_RCVALL,socket.RCVALL_ON)

or if you are using *nix then, use this code.


s=socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0800))





Here, Its Come Very Important Question, Read Carefully

Q 4. How To Parse/Extract Captured Packets?


Ans. . There Are Several Types Of Data Formats Are Available In Networking, But Here, I Am Going To Describe About Only Some Important And Most Usable Data Formats. In Order To Under These Data Format, Let's Take A Look Of Data Structure Diagrams.

So, Pay Attention To These Diagrams.

Ethernet Frame Format 




ICMP Header Format



IP Header Format




TCP Header Format




UDP Header Format


As you all have seen, every data format is different and every data format store various informations in one packets. Here, In This Tutorials We will Use These Diagrams as reference of data format and we will extract all packet according to these formats.

Here, First We will capture a data packet and then, extract that packets according to its data packet.

So, let's Start our Python Packet Sniffer Coding.


For This Purpose, We will Create 2 Script.

1. For Capturing Packets (pypackets.py)

2. For Extracting Captured Data (pye.py)

So Let's Check Our Demo Codes

1. For Capturing Packets


 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
48
49
50
51
#!/usr/bin/python

# ---------------- READ ME ---------------------------------------------
# This Script is Created Only For Practise And Educational Purpose Only
# This Script Is Created For http://bitforestinfo.blogspot.com
# This Script is Written By
__author__='''

######################################################
                By S.S.B Group                          
######################################################

    Suraj Singh
    Admin
    S.S.B Group
    surajsinghbisht054@gmail.com
    http://bitforestinfo.blogspot.in/

    Note: We Feel Proud To Be Indian
######################################################
'''
import socket,struct,binascii,os
import pye

print pye.__author__

if os.name == "nt":
    s = socket.socket(socket.AF_INET,socket.SOCK_RAW,socket.IPPROTO_IP)
    s.bind(("YOUR_INTERFACE_IP",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))

while True:
    pkt=s.recvfrom(65565)
    unpack=pye.unpack()
    print "\n\n===>> [+] ------------ Ethernet Header----- [+]"
    for i in unpack.eth_header(pkt[0][0:14]).iteritems():
        a,b=i
        print "{} : {} | ".format(a,b),
    print "\n===>> [+] ------------ IP Header ------------[+]"
    for i in unpack.ip_header(pkt[0][14:34]).iteritems():
        a,b=i
        print "{} : {} | ".format(a,b),
    print "\n===>> [+] ------------ Tcp Header ----------- [+]"
    for  i in unpack.tcp_header(pkt[0][34:54]).iteritems():
        a,b=i
        print "{} : {} | ".format(a,b),

    

Here, Above Code will capture Data packets and pass them to other module for extraction.


2. For Extracting Captured Data



  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
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#!usr/bin/python
# Importing Modules
import socket, struct, binascii
__author__='''
# =========================================================================|
#   This Script is Created Only for Practise And Educational Purpose Only
# =========================================================================|

######################################################
   By S.S.B Group       
######################################################

 Suraj Singh
 Admin
 S.S.B Group
 surajsinghbisht054@gmail.com
 http://bitforestinfo.blogspot.com

 Note: We Feel Proud To Be Indian
######################################################

 Sniffing Data Packet Extractor
'''
__headers_support__="""
Ethernet header Extraction
IPv4 header Extraction
Tcp header Extraction
ICMP header Extraction
UDP header Extraction

"""

class unpack:
 def __cinit__(self):
  self.data=None

 # Ethernet Header
 def eth_header(self, data):
  storeobj=data
  storeobj=struct.unpack("!6s6sH",storeobj)
  destination_mac=binascii.hexlify(storeobj[0])
  source_mac=binascii.hexlify(storeobj[1])
  eth_protocol=storeobj[2]
  data={"Destination Mac":destination_mac,
  "Source Mac":source_mac,
  "Protocol":eth_protocol}
  return data

 # ICMP HEADER Extraction
 def icmp_header(self, data):
  icmph=struct.unpack('!BBH', data)
  icmp_type = icmph[0]
  code = icmph[1]
  checksum = icmph[2]
  data={'ICMP Type':icmp_type,
  "Code":code,
  "CheckSum":checksum}
  return data

 # UDP Header Extraction
 def udp_header(self, data):
  storeobj=struct.unpack('!HHHH', data)
  source_port = storeobj[0]
  dest_port = storeobj[1]
  length = storeobj[2]
  checksum = storeobj[3]
  data={"Source Port":source_port,
  "Destination Port":dest_port,
  "Length":length,
  "CheckSum":checksum}
  return data

 # IP Header Extraction
 def ip_header(self, data):
  storeobj=struct.unpack("!BBHHHBBH4s4s", data)
  _version=storeobj[0] 
  _tos=storeobj[1]
  _total_length =storeobj[2]
  _identification =storeobj[3]
  _fragment_Offset =storeobj[4]
  _ttl =storeobj[5]
  _protocol =storeobj[6]
  _header_checksum =storeobj[7]
  _source_address =socket.inet_ntoa(storeobj[8])
  _destination_address =socket.inet_ntoa(storeobj[9])

  data={'Version':_version,
  "Tos":_tos,
  "Total Length":_total_length,
  "Identification":_identification,
  "Fragment":_fragment_Offset,
  "TTL":_ttl,
  "Protocol":_protocol,
  "Header CheckSum":_header_checksum,
  "Source Address":_source_address,
  "Destination Address":_destination_address}
  return data

 # Tcp Header Extraction
 def tcp_header(self, data):
  storeobj=struct.unpack('!HHLLBBHHH',data)
  _source_port =storeobj[0] 
  _destination_port  =storeobj[1]
  _sequence_number  =storeobj[2]
  _acknowledge_number  =storeobj[3]
  _offset_reserved  =storeobj[4]
  _tcp_flag  =storeobj[5]
  _window  =storeobj[6]
  _checksum  =storeobj[7]
  _urgent_pointer =storeobj[8]
  data={"Source Port":_source_port,
  "Destination Port":_destination_port,
  "Sequence Number":_sequence_number,
  "Acknowledge Number":_acknowledge_number,
  "Offset & Reserved":_offset_reserved,
  "Tcp Flag":_tcp_flag,
  "Window":_window,
  "CheckSum":_checksum,
  "Urgent Pointer":_urgent_pointer
  }
  return data 

# Mac Address Formating
def mac_formater(a):
 b = "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" % (ord(a[0]), ord(a[1]), ord(a[2]), ord(a[3]), ord(a[4]) , ord(a[5]))
 return b

def get_host(q):
 try:
  k=socket.gethostbyaddr(q)
 except:
  k='Unknown'
 return k

Here,  These Codes Will Extract Provided Data Packets According To Their Specified Format.



Hence, Our Code Finished Here.

let's see how its working.


here, i am using Ubuntu.

(Run this with root privileges or sudo on Ubuntu)

hmm, its working.... Cool!

Or

If You Want Practical Demo Of These Codes Then Check Below Provided Video.


Features of this script
  • No External Dependencies
  • Using Custom Cython Script For Extracting Header
  • Supported Header: TCP/IP, IPv4 ,UDP, ICMP
  • Fast Header Extraction






Usage:
python pypacket.py (run as administrative privilage)



If You Want Latest Example Of Python Script For Packet Sniffing (pypacket) Click Here: Download Script


And For Other Python Socket Related Tutorials.
You Can Read These Tutorials Also.








Done!

Have a nice day.

Thanks For Reading.

For More Update, Visit Our Blog Regularly. 
, Subscribe Our Blog, 
Follow Us and share it.
For Any Type of Suggestion, Help Or Question
Contact me:
S.S.B
surajsinghbisht054@gmail.com
or Comment Below

Share this

Related Posts

Previous
Next Post »

2 comments

Write comments
20 October 2017 at 10:30 delete

Hey, i don't like it. I advise you to provide commands with it, that what are you doing at which step. What have you done so far is just coding, which is straightforward as looking a program code. The purpose is to understand it. So you better be add something before copy paste something.

Reply
avatar
20 October 2017 at 20:40 delete

Well My Friend, I Know this tutorial is really very hard to understand but my friend, you also need to think about

Q. why these codes are difficult to understand?
Ans. This Tutorial is Difficult Because I want to teach you how you can write new applications, how to solve new problems, how you can do all your work on your own, how to work with the limited material.

Friend, If you really want to be a professional Python programmer in future. Then, Don't Need To Give Excuses To Your Learning Brain Because This Difficulty Level is Nothing against Professionals Projects.

Q. what if even after trying harder, codes are very difficult to understand?

Ans. First, Try to Understand Given Reference Posts Like Ping Sweeper, HTTP Sniffer Script, Banner Grabber. and then, give a try here. Or You Can also ask your Questions to here.


Q. Why I'm Not Simplifying My Codes?
Ans. This Blog is Different From Others, Because Here I'm not also trying to increase your knowledge but also trying to increase your capabilities because other blogs and even my blog, can only help you to understand only basics python programs after that you have to do all your work on your own. and another reason is when I can do it, why you can't (even after providing references, example codes and Support). I am not a Professional, Genius Or Expert.



At The End, A Quote To Ignite Your Mind,

"My message, especially to young people is to have the courage to think differently, courage to invent, to travel the unexplored path, courage to discover the impossible and to conquer the problems and succeed." - APJ Abdul Kalam


Reply
avatar