Using Scapy to extract packet data

Scapy is a packet manipulation tool for networks, written in Python. It can forge or decode packets, send them on the wire, capture them, and match requests and replies. We can use scapy to extract the TXT records as follows:

From scapy.all import  * 
import base64 
 
network_packets = rdpcap('gnome.pcap') 
decoded_commands = [] 
decoded_data ="" 
for packet in network_packets: 
    if DNSQR in packet: 
        if packet[DNS].id == 0x1337: 
            decoded_data = base64.b64decode(str(packet[DNS].an.rdata)) 
        if 'FILE:' in decoded_data: 
                        continue 
        else: 
                decoded_commands.append(decoded_data) 
for command in decoded_commands: 
        if len(command)>1: 
                print command.rstrip() 

By merely using 15 lines of code in Python, we can extract the data we want. The first two lines are header imports, which will give the python script the functionality from base64 and scapy. Next, we have the following:

network_packets = rdpcap('gnome.pcap') 
decoded_commands = [] 
decoded_data =""

In the preceding code segment, we are reading a PCAP file, gnome.pcap, from the current working directory and also declaring a list named decoded_commands and a string variable named decoded_data. Next, we have the following code:

for packet in network_packets: 
    if DNSQR in packet: 
        if packet[DNS].id == 0x1337: 
            decoded_data = base64.b64decode(str(packet[DNS].an.rdata)) 

The for loop will traverse the packets one after the other, and if the packet is of the DNS type, it will check whether the packet ID matches 0x1337. If it does, it pulls the TXT record data using packet[DNS].an.rdata, converts it into a string, and decodes it from base64 to normal text and in case the decoded data contains FILE: the execution should continue else the decoded_data is appended to decoded_command:

if 'FILE:' in decoded_data:
continue
else:
decoded_commands.append(decoded_data) for command in decoded_commands: if len(command)>1: print command.rstrip()

The preceding section appends the decoded data into the decoded_command list and loops over the list while printing all the elements of the list whose length is greater than 1 (to avoid empty lines). Running the script gives us the following output:

Well, this looks like output from the iwlist scan command. The output of a system command is not something to be expected in the DNS responses. This denotes that the system under observation was compromised and the attacker used DNS for command and control.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset