def runProxyThreadUL(): global w_sniff, w_ul, config, exFilter, iface_back sniff_flt = "ifIdx==17 and not ip.SrcAddr==127.0.0.1" w_sniff = pydivert.WinDivert(sniff_flt, layer=pydivert.Layer(1)) w_sniff.open() w_ul = pydivert.WinDivert("false") w_ul.open() printh("UL-Thread", "Now on %s" % (str(iface_back)), "green") while True: p = w_sniff.recv() tmp = proxy_func(p.src_addr, 0) if tmp: p.src_addr = tmp p.interface = (13L, 0L) p.direction = pydivert.Direction(0) #0 for OUT_BOUND w_ul.send(p, recalculate_checksum=True) if DBG: print(p.src_addr, p.dst_addr) #for debug pass else: w_sniff.send(p) pass pass pass
def start(self): self.api_thread.start() # Block all ICMP requests (which are sent on Windows by default). # In layman's terms: If we don't do this, our proxy machine tells the client that it can directly connect to the # real gateway if they are on the same network. self.icmp_handle = pydivert.WinDivert(filter="icmp", layer=pydivert.Layer.NETWORK, flags=pydivert.Flag.DROP) self.icmp_handle.open() self.response_handle = pydivert.WinDivert(filter=self.response_filter, layer=pydivert.Layer.NETWORK) self.response_handle.open() self.response_thread.start() if self.mode == "forward" or self.mode == "both": self.request_forward_handle = pydivert.WinDivert( filter=self.request_filter, layer=pydivert.Layer.NETWORK_FORWARD) self.request_forward_handle.open() self.request_forward_thread.start() if self.mode == "local" or self.mode == "both": self.request_local_handle = pydivert.WinDivert( filter=self.request_filter, layer=pydivert.Layer.NETWORK) self.request_local_handle.open() self.request_local_thread.start()
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")
def run(self): self.__isFiltering = True rules_table = self.get_rules() with pydivert.WinDivert() as w: for packet in w: packet_accepted = True for rule in rules_table['rules']: protocols = [] for id in packet.protocol: protocols.append(Utils.resolve_protocol_ID[id]) if (packet.dst_port == Utils.safe_int(rule['port']) or rule['port'] == "*") and \ (packet.dst_addr == rule['ip_source'] or rule['ip_source'] == "*")and \ (rule['protocol'] in protocols or rule['protocol'] == "*"): packet_accepted = False break if packet_accepted: try: w.send(packet) except OSError: pass if not self.__isFiltering: break
def __init__(self): self.my_ip = socket.gethostbyname(socket.gethostname()) self.WinDiv = pydivert.WinDivert( f"ip.DstAddr != {self.my_ip}") # filter self.WinDiv.open() # packets will be captured from now on thread.start_new_thread(self.receive_packets)
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")
def blockTraffic(self): # se filtra todo el tráfico with pydivert.WinDivert("true", 1) as w: for packet in w: # si el tráfico no coincide con la expresión se reenvía if (packet.matches(self.expression, 1) == False): w.send(packet, True)
def reflect( reflect_hosts: List[IPAddressType], shield_ports: List[int], priority: int, ): filter_hosts = ' or '.join( f'{"ipv6" if host.version == 6 else "ip"}.DstAddr == {host}' for host in reflect_hosts) filter_str = f'outbound and (tcp or udp) and ({filter_hosts})' if shield_ports: filter_ports = ' or '.join( f'tcp.DstPort == {port} or udp.DstPort == {port}' for port in shield_ports) filter_str = f'({filter_str}) or ' \ f'(inbound and ({filter_ports}))' with pydivert.WinDivert(filter_str, priority=priority) as wd: for packet in wd: logger.debug('Received packet:\n%r', packet) if packet.is_outbound: (packet.src_addr, packet.dst_addr) = \ (packet.dst_addr, packet.src_addr) packet.direction = pydivert.Direction.INBOUND logger.debug('Reflecting packet:\n%r', packet) wd.send(packet) else: logger.debug('Dropping packet')
def win_main(): if windll.shell32.IsUserAnAdmin() == 0: print("Error: Must be run as administrator !") return filterIP = "tcp.DstPort == " + str(port) + " or tcp.SrcPort == " + str( port) if target is not None: filterIP = "(ip.SrcAddr == " + str( target) + " or ip.DstAddr == " + str( target) + ") and (" + filterIP + ")" print(filterIP) with pydivert.WinDivert(filterIP) as w: try: if not mute: print("[*] Waiting for data") for packet in w: # print(packet) if len(packet.payload) > 0: if (not mute) and packet.dst_port == port: print("Client request: ", packet.payload) if (not mute) and verbose and packet.src_port == port: print("Server traffic: ", packet.payload) packet.payload = xor(packet.payload) if (not mute) and verbose and packet.dst_port == port: print("Client traffic: ", packet.payload) if (not mute) and packet.src_port == port: print("Server Request: ", packet.payload) w.send(packet) except KeyboardInterrupt: if not mute: print("Shutdown...") w.close()
def runProxyThreadDL(data_q): global iface_back, w_dl w_dl = pydivert.WinDivert('false') w_dl.open() printh("DL-Thread", "Now on %s" % (str(iface_back)), "green") count, length = 0, 0 while True: if not data_q.empty(): data = data_q.get() v = memoryview(bytearray(data)) p = pydivert.Packet( v, (17L, 0L), pydivert.Direction(0) #0 for OUT_BOUND ) tmp = proxy_func(p.dst_addr, 1) if tmp: p.dst_addr = tmp w_dl.send(p, recalculate_checksum=True) length += len(data) count += 1 remains = data_q.qsize() print("%d\t%d\t%.2f MB" % (count, remains, length / 1E6)) pass else: if DBG: print('correspondance loss.') pass pass pass pass
def handle_data_channel(self, client_addr, client_port, data_sock): data_conn, _ = data_sock.accept() data_session = self.sessions[client_addr].data_session command = self.sessions[client_addr].data_commands.get() if command in self.server_sends_data: while True: data = data_conn.recv(2048) if not data: break data_session.send(data) data_conn.close() data_session.disconnect() else: with pydivert.WinDivert(f"tcp.SrcPort == {client_port}") as w: for packet in w: if (len(packet.payload) > 1 and packet.tcp.ack and not (packet.tcp.seq_num < data_session.ack)): data_session.register_payload_packet(packet) data_conn.send(packet.payload) elif packet.tcp.fin: data_session.disconnect() data_conn.close() break responses = self.sessions[client_addr].ftp_server.get_response() self.sessions[client_addr].tcp_session.sendall(responses)
def run(self): print("logfile start") #while True: #time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') #data = [time,addr,'normal'] #self.update(data) with pydivert.WinDivert("tcp.DstPort==8888") as w: for packet in w: if re.search(searchPattern, packet.payload): print("find log record") print(packet.payload) addr = packet.src_addr time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') data = [time, addr, 'normal'] self.update.emit(data) elif re.search(ValidateRegex, packet.payload): if re.search(b'token=', packet.payload): print("find log record") addr = packet.src_addr time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') data = [time, addr, 'changePass'] self.update.emit(data) else: print("CSRF detected.") addr = packet.src_addr time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') data = [time, addr, 'abnormal changePass'] self.update.emit(data) w.send(packet)
def receive_syns(src_addr): fltr = f"ip.SrcAddr == {src_addr} and tcp.Syn and tcp.DstPort == {self.fake_port} and inbound" handle_priority = -1 w = pydivert.WinDivert(fltr, priority=handle_priority) w.open() time.sleep(30) w.close()
def initialize_divert(self): """ Initializes Divert such that all packets for the connection will come through us """ self.logger.debug("Engine created with strategy %s (ID %s) to port %s", str(self.strategy).strip(), self.environment_id, self.server_port) self.logger.debug("Initializing Divert") self.divert = pydivert.WinDivert("tcp.DstPort == %d || tcp.SrcPort == %d" % (int(self.server_port), int(self.server_port))) self.divert.open() self.divert_thread = threading.Thread(target=self.run_divert) self.divert_thread.start() maxwait = 100 # 100 time steps of 0.01 seconds for a max wait of 10 seconds i = 0 # Give Divert time to startup, since it's running in background threads # Block the main thread until this is done while not self.divert_thread_started and i < maxwait: time.sleep(0.1) i += 1 self.logger.debug("Divert Initialized after %d", int(i)) return
def validateExpression(self): # crear instancia de WinDivert usando expresión w = pydivert.WinDivert(self.expression) # chequear si la expresión es correcta # se devuelven 3 variables x, y, z = w.check_filter(self.expression) # se retorna únicamente la última variable return z
def run(self): print("thread start/ " + self.name) with pydivert.WinDivert("inbound && icmp && ip.SrcAddr == " + self.addr) as w: for packet in w: data = packet.icmpv4.payload[4:] #print("[ICMP]","INBOUND",data.hex()) self.queue.put(data) self.stat.queue[0] = self.stat.queue[0] + len(data)
def __init__(self, handle: typing.Callable[[pydivert.Packet], None], filter: str, layer: pydivert.Layer = pydivert.Layer.NETWORK, flags: pydivert.Flag = 0) -> None: self.handle = handle self.windivert = pydivert.WinDivert(filter, layer, flags=flags) super().__init__()
def block(): global blocklist with pydivert.WinDivert("ip") as w: #check windivert filter language docs for packet in w: if packet.dst_addr in blocklist: #if dst ip in blocklist, pass pass else: w.send(packet) #send if dst ip not in blocklist
def start_traffic_control(): with pydivert.WinDivert("outbound") as w: for packet in w: #print(chance) c = random.random() if c < chance: print(chance) else: w.send(packet)
def delay(self, sec, duration=10.0): netfil = "tcp.DstPort == 389 or tcp.SrcPort == 389" start = time.time() with pydivert.WinDivert(netfil) as divert: for packet in divert: time.sleep(sec) divert.send(packet) if time.time() - start >= duration: break
def capture_diver(q: Queue): import pydivert # linux support with pydivert.WinDivert(f'{s1} or {d1}', flags=pydivert.Flag.SNIFF) as w: for packet in w: # print(f'Packet: PL={len(packet.payload)} PCKT: {packet} {len(packet.udp.raw)}') q.put_nowait({ 'data': packet.payload, 'incoming': packet.is_inbound, })
def main(): global flt_ctrl, w w = pydivert.WinDivert(flt_ctrl) w.open() while True: packet = w.recv() pkt_q.put(packet) pass pass
def start_traffic_control(self): #start as admin with pydivert.WinDivert(self.network_filter) as w: for packet in w: c = random.random() if self.benchmark_started and ( c < self.chance_of_dropping_packets): pass else: w.send(packet)
def sniff(): while (1): w = pydivert.WinDivert("tcp.DstPort == 80 and tcp.PayloadLength > 0") w.open() # packets will be captured from now on packet = w.recv() # read a single packet print(packet) w.send(packet) # re-inject the packet into the network stack w.close() # stop capturing packets
def doIntercept(): global proxifier print ("[*] Intercepting packet ...") with pydivert.WinDivert("tcp.SrcPort == %s"%int(PORT)) as w: proxifier = True for packet in w: print (">") packet.src_addr = packet.dst_addr w.send(packet, recalculate_checksum=True) proxifier = False break
def put_thread(pkt_q): w = pydivert.WinDivert("inbound and tcp") w.open() while True: packet = w.recv() if packet.dst_addr in PROXY_ADDR: pkt_q.put(packet) else: w.send(packet) pass pass
def dropHTTPUdp(state): global logDrop with pydivert.WinDivert(ScriptConfig.dropProblematic) as w: while keepThreadOpen: try: for packet in w: logDrop(packet, "UDP-QUICk\RDP") except Exception as ex: if not packet is None: logPacket(packet) log(str(ex)) traceback.print_tb(ex.__traceback__)
def run(self): with pydivert.WinDivert( "(udp.SrcPort == 6672 or udp.DstPort == 6672) and ip") as w: for packet in w: dst = packet.ip.dst_addr src = packet.ip.src_addr if packet.is_inbound: self.ips.append(src) else: self.ips.append(dst) w.send(packet)
def sync(packet): #craft DHCP offer #send DHCP offer #wait for request #send ack #add taken ip to list #wait for dhcp discovery with pydivert.WinDivert("tcp.DstPort == 67") as syn: for packet in syn: syn.send(packet) sync(packet)
def main(): global flt_ctrl, w flt_ctrl = "inbound and ifIdx==%d and ip"%(iface_t[0]) if DBG: print(flt_ctrl) w = pydivert.WinDivert(flt_ctrl) w.open() while True: packet = w.recv() pkt_q.put(packet) pass pass