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)
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")
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)
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()
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()
def main(): nfqueue = NetfilterQueue() nfqueue.bind(1, print_and_accept) s = socket.fromfd(nfqueue.get_fd(), socket.AF_UNIX, socket.SOCK_STREAM) try: nfqueue.run_socket(s) except: print('') s.close() nfqueue.unbind()
def main(): q = NetfilterQueue() q.bind(1, callback) s = socket.fromfd(q.get_fd(), socket.AF_INET, socket.SOCK_STREAM) try: q.run_socket(s) except KeyboardInterrupt: q.unbind() print("flushing tables") os.system('iptables -F') os.system('iptables -X')
def start(self): sys.stdout.write('Listening on NFQUEUE %s... \n' % str(QUEUE_NUM)) nfqueue = NetfilterQueue() nfqueue.bind(QUEUE_NUM, self._packet_callback) s = socket.fromfd(nfqueue.get_fd(), socket.AF_UNIX, socket.SOCK_STREAM) try: nfqueue.run_socket(s) except KeyboardInterrupt: sys.stdout.write('Exiting \n') s.close() nfqueue.unbind()
def main(): nfqueue = NetfilterQueue() nfqueue.bind(0, handlePacket) s = socket.fromfd(nfqueue.get_fd(), socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) try: # nfqueue.run() nfqueue.run_socket(s) except KeyboardInterrupt as e: raise e finally: nfqueue.unbind()
def main(): if os.getgid(): print("NFQUEUE requires root permissions.") sys.exit(1) #if args.whitelist and args.domains != ['*']: # print('USAGE: --domains \'*\' --whitelist domain1') # sys.exit(1) iptables_table = 'dns_reject' clean_iptables(iptables_table) log.debug('args.combined_blacklist: {}'.format(args.combined_blacklist)) log.debug('args.hosts: {}'.format(args.hosts)) log.debug('args.domains: {}'.format(args.domains)) global blacklist blacklist = build_domain_list( combined_hosts_and_domains=args.combined_blacklist, domains=args.domains, hosts=args.hosts ) global whitelist whitelist = build_domain_list( combined_hosts_and_domains=args.combined_whitelist, domains=args.whitelist, hosts=['*'] ) log.debug('Blacklist: {}'.format(blacklist)) log.debug('Whitelist: {}'.format(whitelist)) log.debug('Creating IPTable rules for {}'.format(','.join(set(blacklist.keys())))) create_iptables(iptables_table, set(blacklist.keys())) q = NetfilterQueue() q.bind(1, callback) s = socket.fromfd(q.get_fd(), socket.AF_UNIX, socket.SOCK_STREAM) try: #q.try_run() # Main loop q.run_socket(s) except KeyboardInterrupt: s.close() q.unbind() clean_iptables(iptables_table) sys.exit('Closing...')
class Packet_Engin(object): def __init__(self, handler, queue=1): self.evt_base = libevent.Base() self.setup_NFQ(handler, queue) self.nfq_evt = self.add_persist_read_event( self.nfq_fd, self.nfq_event_handler, self) def __del__(self): self.nfq_socket.close() self.nfq.unbind() def setup_NFQ(self, handler, queue): self.nfq = NFQ(queue) self.nfq.bind(queue, handler) self.nfq_fd = self.nfq.get_fd() self.nfq_socket = socket.fromfd(self.nfq_fd, \ socket.AF_UNIX, socket.SOCK_STREAM) self.nfq_socket.setblocking(False) # returned evt must be kept live until you are done with it def add_event(self, fd, flag, cb, cb_data, timeout=0): evt = libevent.Event(self.evt_base, fd, flag, cb, cb_data) evt.add(timeout) return evt def add_persist_read_event(self, fd, cb, cb_data, timeout=0): return self.add_event(fd, libevent.EV_READ | libevent.EV_PERSIST, cb, cb_data, timeout) def add_persist_timer(self, cb, cb_data, timeout): return self.add_event(-1, libevent.EV_TIMEOUT | libevent.EV_PERSIST, cb, cb_data, timeout) @staticmethod def nfq_event_handler(evt, fd, what, self): self.nfq.run_socket(self.nfq_socket) def start(self): self.evt_base.loop()
sys.stderr.write('Error: env QUEUE_NUM must be integer\n') sys.exit(1) def callback(pkt): try: packet = IP(pkt.get_payload()) pprint(packet) pkt.accept() except Exception as e: print 'Error: %s' % str(e) pkt.drop() sys.stdout.write('Listening on NFQUEUE queue-num %s... \n' % str(QUEUE_NUM)) nfqueue = NetfilterQueue() nfqueue.bind(QUEUE_NUM, callback) s = socket.fromfd(nfqueue.get_fd(), socket.AF_UNIX, socket.SOCK_STREAM) try: nfqueue.run_socket(s) except KeyboardInterrupt: sys.stdout.write('Exiting \n') s.close() nfqueue.unbind()
class DropTail: # Description du corps de la classe DropTail: Chute des paquets marqués. # Je figes les attributs, de cette façon je ne peux plus crée d'attribut à la volé. Seul ces attributs peuvent et existeront : __slots__ = "nfqueue", "socket" # Attributs qui sont propre à tous les instance : (vide) # Attributs qui sont propres à l'instance : def __init__(self, list_pktToDrop): self.nfqueue = None self.socket = None #================================================================================================================== # METHODES #================================================================================================================== @staticmethod def print_and_accept(pkt): global dict_drop # Vérification de terminaison pour les threads : f = open(".term.txt", 'r+') line = f.readline() f.seek(0) f.truncate() f.close() line = line.strip('\n') list_key = [] # Si un thread a terminé : if line != '': for cle in dict_drop: if line in cle and dict_drop[cle] == 0: list_key.append(cle) for cle in list_key: # Supression du thread de le dictionnaire : del dict_drop[cle] # Gestion paquets : if (pkt.get_payload_len() == 1500): payload = pkt.get_payload()[53:pkt.get_payload_len()] payload = payload.decode() payload = payload.split('Pr') payload = payload[1] payload = payload.split('/') # Si la décision est : D if (payload[3] == 'D'): client_name = payload[4] decision = payload[3] index_pkt = payload[2] nbTimeToDrop = int(payload[1]) # Clé unique : cle = client_name + index_pkt + decision # Si la clé est connue : if cle in dict_drop: # Si le nombre de chutes est atteint : if dict_drop.get(cle) == 0: pkt.accept() else: dict_drop[cle] = dict_drop.get(cle) - 1 pkt.drop() else: # Ajout de la clé et de la valeur : dict_drop[cle] = nbTimeToDrop if cle in dict_drop: if dict_drop.get(cle) == 0: pkt.accept() else: # On effectue la première chute : dict_drop[cle] = dict_drop.get(cle) - 1 pkt.drop() elif (payload[3] == 'P'): pkt.accept() else: pkt.accept() def nfqueue_app(self): open(".term.txt", 'w').close() self.nfqueue = NetfilterQueue() self.nfqueue.bind(0, self.print_and_accept) self.socket = socket.fromfd(self.nfqueue.get_fd(), socket.AF_UNIX, socket.SOCK_STREAM) try: self.nfqueue.run_socket(self.socket) except KeyboardInterrupt: print('') socket.close() self.nfqueue.unbind()
class MyNfq: def __init__(self, queue_id, args): self.__nfqueue = NetfilterQueue() self.__nfqueue.bind(queue_id, self.__cb) self.__pktlist = [] self.__only_req = args['--req'] self.__only_res = args['--res'] self.__host = args['--host'] self.__dst = args['--dst'] self.__src = args['--src'] self.__socket = socket.fromfd(self.__nfqueue.get_fd(), socket.AF_UNIX, socket.SOCK_STREAM) def __cb(self, pkt): packet = IP(pkt.get_payload()) if packet.proto is 0x06 and packet.haslayer(Raw): if self.__host and not (packet.src in self.__host or packet.dst in self.__host): pkt.accept(); return if self.__src and not packet.src in self.__src: pkt.accept(); return if self.__dst and not packet.dst in self.__dst: pkt.accept(); return is_http = MyNfq.__is_HTTP(packet[TCP].payload.load) if is_http == 'request': if ( self.__only_res ): pkt.accept(); return elif is_http == 'response': if self.__only_req: pkt.accept(); return else: pkt.accept(); return tcp = packet[TCP] line = [is_http, ':', packet.src, '->', packet.dst, ',', tcp.sport, '->', tcp.dport] line = ' '.join(map(str, line)) self.__pktlist.append( {'pkt':pkt, 'oneline':line, 'dissectedpkt':packet}) else: pkt.accept() def get_fd(self): return self.__nfqueue.get_fd() def run(self): self.__nfqueue.run_socket(self.__socket) def unbind(self): self.__nfqueue.unbind() def get_socket(self): return self.__socket def set_socket_timeout(self, sec): self.__socket.settimeout(sec) @staticmethod def __is_HTTP(raw): if re.match(b'^.+ /.* HTTP/.\..\r\n', raw): return 'request' elif re.match(b'^HTTP/.\.. .+ .+\r\n', raw): return 'response' else: return False def get_pktnum(self): return len(self.__pktlist) def get_a_pkt(self, i): try: return self.__pktlist[i] except: pass def get_ranged_pkts(self, first, last): return self.__pktlist[first:last] def accept(self, i): if self.get_pktnum() > 0: self.__pktlist[i]['pkt'].accept() #send(self.__pktlist[i]['dissectedpkt'], verbose=False) #self.__pktlist[i]['pkt'].drop() self.__del_elem(i) def drop(self, i): if self.get_pktnum() > 0: self.__pktlist[i]['pkt'].drop() self.__del_elem(i) def __del_elem(self, i): del(self.__pktlist[i]) def get_payload(self, i): return self.__pktlist[i]['dissectedpkt'][TCP].payload.load.decode() def set_payload(self, i, raw): if raw[-1] != '\n': raw += '\n' bodylen = len(raw.split('\r\n\r\n', 1)[1]) raw = re.sub(r'(Content-Length: )[1-9]+', 'Content-Length: '+str(bodylen), raw) del self.__pktlist[i]['dissectedpkt'][IP].len del self.__pktlist[i]['dissectedpkt'][IP].chksum del self.__pktlist[i]['dissectedpkt'][TCP].chksum self.__pktlist[i]['dissectedpkt'][TCP].payload.load = raw.encode() self.__pktlist[i]['pkt'].set_payload(bytes(self.__pktlist[i]['dissectedpkt'])) def get_rawpkt(self, i): # return str(self.__pktlist[i]['dissected']) return '{0}'.format(self.__pktlist[i]['dissectedpkt'])