Let us sniff the packets using the sniff() function of Scapy and define a callback function, modify_packet_header(), which adds an extra header of certain packets.
Listing 8.3 gives the code for adding an extra header in HTTP packets, as follows:
#!/usr/bin/env python # Python Network Programming Cookbook, Second Edition -- Chapter - 8 # This program is optimized for Python 2.7.12 and Python 3.5.2. # It may run on any other version with/without modifications. from scapy.all import * def modify_packet_header(pkt): """ Parse the header and add an extra header""" if pkt.haslayer(TCP) and pkt.getlayer(TCP).dport == 80
and pkt.haslayer(Raw): hdr = pkt[TCP].payload.__dict__ extra_item = {'Extra Header' : ' extra value'} hdr.update(extra_item) send_hdr = ' '.join(hdr) pkt[TCP].payload = send_hdr pkt.show() del pkt[IP].chksum send(pkt) if __name__ == '__main__': # start sniffing sniff(filter="tcp and ( port 80 )", prn=modify_packet_header)
If you run this script, it will show a captured packet; print the modified version of it and send it to the network, as shown in the following output. This can be verified by other packet capturing tools such as tcpdump or wireshark:
$ python 8_3_add_extra_http_header_in_sniffed_packet.py ###[ Ethernet ]### dst = 52:54:00:12:35:02 src = 08:00:27:95:0d:1a type = 0x800 ###[ IP ]### version = 4L ihl = 5L tos = 0x0 len = 525 id = 13419 flags = DF frag = 0L ttl = 64 proto = tcp chksum = 0x171 src = 10.0.2.15 dst = 82.94.164.162 options ###[ TCP ]### sport = 49273 dport = www seq = 107715690 ack = 216121024 dataofs = 5L reserved = 0L flags = PA window = 6432 chksum = 0x50f urgptr = 0 options = [] ###[ Raw ]### load = 'Extra Header sent_time fields aliastypes post_transforms underlayer fieldtype time initialized overloaded_fields packetfields payload default_fields' . Sent 1 packets.