程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Scapy: write your own network packet capturing tool in Python

編輯:Python


With Python More and more popular , It is also used more and more in the field of security . For example, you can use requests Module writing Web Request tool ; use sockets To write TCP Network communication program ; Parsing and generating byte streams can use struct modular . It is more common to parse and process network packets in the field of network security , Often


We will use tcpdump and wireshark(tshark). But if you want to write your own program for processing , You need more flexible language packs ( library ), This is what this article will introduce Scapy.

summary

Scapy Is used to parse the underlying network packets Python Modules and interactive programs , The program carries out Abstract packaging for the underlying package processing , It makes the processing of network packets very simple . This class library can have a very wide range of use cases in the field of network security , Can be used for exploit development 、 The data reveal that 、 Network monitoring 、 Intrusion detection and traffic analysis capture .Scapy Integration with data visualization and report generation , Results and data can be easily displayed .

Scapy The basic idea of domain specific language is to propose a domain specific language , So that the wired format can be carried out easily and quickly (Wire Format) management .

Installation and operation

Scapy Can pass pip install :

pip install scapy

You can also install through the distribution's package manager , such as yum, But the version may be too old and out of date .

It can also be directly from the official warehouse clone Source code installation :

git clone github /secdev/scapy

then , Can simply run :

cd scapy

./run_scapy


Usage examples

analysis PCAP Grab the bag

use Scapy The easiest thing to do is read PCAP file . Let's download Wireshark Of sip-rtp-opus-hybrid.pcap Example PCAP Data package as an example :

use rdpcap() Function introduced PCAP file , A function that reads its contents :

>>> pkts = rdpcap("sip-rtp-opus-hybrid.pcap")

>>> pkts

<sip-rtp-opus-hybrid.pcap: TCP:0 UDP:7 ICMP:0 Other:0>


For more detailed reading PCAP The data in the file , have access to PcapReader Read packets iteratively from open file handles , One bag at a time ,bing Instantiated object :

>>> fd = open("sip-rtp-opus-hybrid.pcap", "rb")

>>> reader = PcapReader(fd)

>>> reader

<scapy.utils.PcapReader at 0x7f913c7c24e0>

>>> for CC in reader:

...: print(CC)

...:


>>> fd.close()

As shown above , Each packet is provided in a wired format .Scapy Stack each packet in a network layer .Scapy The layer object corresponds to the network protocol and its wired format .

Get the first packet and check IP Whether the layer is available :

>>> first= CC[0]

>>> first.haslayer(IP)

True

>>> IP in first

True

To parse packets from a particular layer , It can be indexed by the desired layer , And let Scapy Print all fields :


To print a packet in hexadecimal , have access to hexdump() function :

>>> hexdump(first)


To fully parse and output a packet perfectly , Need to call show() Method :

>>> first.show()


You can see , The above failed to parse SI load . This is because Scapy It mainly deals with binary protocols The lower part of the network stack , and SIP No . However, a third-party module can be introduced to parse some application layer protocols , such as HTTP agreement .

Real time packet capturing and parsing

For example, you can read packets with pre captured data PCAP file , If you want to do some packet sniffing , If the system is ready to use the network interface in hybrid mode , You can call sniff() Get some data packets from the network card :

>>> for CC in sniff(count=5):

...: CC.show()

...:


Scapy And can also be used in Wireshark(tshark)、tcpdump identical BPF Syntax to filter sniffed packets and many other tools support :

>>> for CC in sniff(filter="udp", count=5):

...: CC.show()

...:

To save the captured packets to PCAP For further analysis , have access to wrpcap() Function to export to a file :

>>> capture = sniff(filter="udp", count=5)

>>> capture

<Sniffed: TCP:0 UDP:5 ICMP:0 Other:0>

>>> wrpcap("udp.pcap", capture)

send out ping package

Besides sniffing ( Capture and parse ) Network packet , but Scapy It also supports generating data packets for various active spoofing : Network scanning 、 Server probe 、 By sending malformed requests to attack the system, etc .

Let's try ping One server , It involves sending a to the service ICMP Data packets :

>>> CC = IP(dst="XXX") / ICMP()

>>> CC.show()


And then call sr1() function , Can send a ICMP Data packets ( namely ping), Wait for the return packet to return :

>>> rr=sr1(CC)

Begin emission:

Finished sending 1 packets.

...*

Received 4 packets, got 1 answers, remaining 0 packets

>>> rr


The above got the correct ICMP reply .

To send multiple packets and receive responses ( For example, implement ping scanning ), It can be used sr() function . Send multiple packets , But wait for a single response . You can also use sr1_flood() function .

The network protocol layer is out of order

Scapy By overloading Python“/” Operator to implement layer stacking , No longer do not enforce execution in network layer order , To achieve the desired human order ( This is useful in some tests and Applications ).


>>> CC=ICMP() / UDP() / IP() / IP()

>>> CC

<ICMP |<UDP |<IP frag=0 proto=ipencap |<IP |>>>>

>>> CC.show()

###[ ICMP ]###

type= echo-request

code= 0

chksum= None

id= 0x0

seq= 0x0

###[ UDP ]###

sport= domain

dport= domain

len= None

chksum= None

###[ IP ]###

version= 4

ihl= None

tos= 0x0

len= None

id= 1

flags=

frag= 0

ttl= 64

proto= ipv4

chksum= None

src= 127.0.0.1

dst= 127.0.0.1

\options\

###[ IP ]###

version= 4

ihl= None

tos= 0x0

len= None

id= 1

flags=

frag= 0

ttl= 64

proto= hopopt

chksum= None

src= 127.0.0.1

dst= 127.0.0.1

\options\

>>> hexdump(CC)

WARNING: No IP underlayer to compute checksum. Leaving null.

0000 08 00 F7 65 00 00 00 00 00 35 00 35 00 30 00 00 ...e.....5.5.0..

0010 45 00 00 28 00 01 00 00 40 04 7C CF 7F 00 00 01 E..([email protected]|.....

0020 7F 00 00 01 45 00 00 14 00 01 00 00 40 00 7C E7 [email protected]|.

0030 7F 00 00 01 7F 00 00 01


Designed like this , The main purpose is to generate arbitrary network packets ( Deliberately damaged ), Used for vulnerability testing research or exploitation . Of course, for users who are not familiar with this area , It is strongly recommended not to try easily , So as not to cause problems .

Data visualization

Scapy Also support passing PyX( Modules need to be pre installed ) Visualizing data . A graph that can be output as a packet or a list of packets (PostScript/PDF Format ):

>>> xxCC[404].pdfdump(layer_shift=1)

>>> xxCC[404].psdump("/tmp/xxCC.eps",layer_shift=1)


Fuzzy testing

Utilization function fuzz() You can generate random test values using fast build, use fuzzy templates and send them circularly for testing . In the following example ,IP Laminar normal ,UDP and NTP Cambium fuzz.UDP The checksum will be correct ,UDP The target port will be NTP Overload is 123, also NTP The version will be forced to 4, All other ports will be randomized :

send(IP(dst="target")/fuzz(UDP()/NTP(version=4)),loop=1)

................^C

Sent 16 packets.

summary

throw away a brick in order to get a gem , Here we introduce some basic Scapy purpose , Of course, it's just scapy The tip of the iceberg in the huge function , Please refer to the official documentation for more usage .

As far as I know, some tools have been used at present scapy package :

Trackerjacker: WiFi Network mapper


Wifiphisher: Wifi Access point creation tool


Sshame:SSH Public key brute force decryptor


ISF: Utilization framework of industrial system .


There are some more special uses that you need hacker To further explore .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved