def is_valid_ipv4_address(address): try: socket.inet_pton(socket.AF_INET, address) except AttributeError: # no inet_pton here, sorry try: socket.inet_aton(address) except socket.error: return False return address.count('.') == 3 except socket.error: # not a valid address return False return True
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 InitializeSockect(self): self.MulticastSockect = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.MulticastSockect.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.MulticastSockect.bind((self.MCAST_GRP, self.MCAST_PORT)) mreq = struct.pack("4s", socket.inet_aton(self.MCAST_GRP), socket.INADDR_ANY) self.MulticastSockect.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) self.CreateReceiveThreat()
def listenforElectionMessage(self): # Thread 6 server_address = ('', LCRPort) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TCP socket sock.bind(server_address) # Bind to the server address sock.listen() # Listening for LCR Election messages on Port: LCRPort while True: connection, server_address = sock.accept() # Wait for a connection received_ip = connection.recv(1024) received_ip = received_ip.decode() # Otherwise it is a IP and election is still running sleep(2) if socket.inet_aton(received_ip) == socket.inet_aton(host_ip_address): # If received own ID. I'm the leader print("Leader Election: I'm the new leader") self.isLeader = True self.sendnewLeaderMessage() # Inform other servers about the new leader print('Checking for orderlist updates on member servers') self.getLatestOrderlistfromServer() if len(self.clientlist) > 0: print('Checking for orderlist updates on clients') self.getLatestOrderlistfromClient() if self.ordernumber > 0: print('Restarting orderlist update thread') thread = threading.Thread(target=self.sendOrderlistUpdate) thread.start() elif socket.inet_aton(received_ip) > socket.inet_aton(host_ip_address): # e.g 192.168.0.100 > 192.168.0.50, if received IP is higher pass on to neighbor ipID = received_ip.split('.') hostID = host_ip_address.split('.') print('Received ID ', ipID[3], ' > ', hostID[3], '. Passing higher IP to neighbour') sendElectionmessage(received_ip) else: ipID = received_ip.split('.') hostID = host_ip_address.split('.') print('Received ID ', ipID[3], ' < ', hostID[3], ' Not passing to neighbour')
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 listenMulticastLeaderCheck(self): # Thread 9 # Multicast to detect Leader multicast_group = '224.3.29.71' server_address = ('', 5009) sock = socket.socket(AF_INET, SOCK_DGRAM) sock.bind(server_address) group = socket.inet_aton(multicast_group) # add socket to the multicast group mreq = struct.pack('4sL', group, socket.INADDR_ANY) sock.setsockopt(IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) while True: data, address = sock.recvfrom(128) if self.isLeader: response = 'True' else: response = 'False' sock.sendto(response.encode(), address)
def listenMulticast(self): # Thread 7: Multicast to detect Leader and add to serverlist multicast_group = '224.3.29.71' server_address = ('', MulticastServerPort) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(server_address) # Tell the operating system to add the socket to the multicast group on all interfaces. group = socket.inet_aton(multicast_group) mreq = struct.pack('4sL', group, socket.INADDR_ANY) sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) # Receive/respond loop while True: data, address = sock.recvfrom(128) if self.isLeader: # If Leader than responds with "True" response = 'True' else: response = 'False' sock.sendto(response.encode(), address) if self.isLeader is True: if len(self.serverlist) == 0: # If there is no server in the list add and send update self.serverlist.append((address, False)) # Add new connection self.updateServerList(self.serverlist) # Overwrite serverlist with updated one self.sendUpdatedServerList() # Send updated list to all servers else: # check if the connection is already in the list for x in range(len(self.serverlist)): connection_and_leader = self.serverlist[x] replica_server_adress, isLeader = connection_and_leader # split up tuple into sinlge variables if replica_server_adress == address: # Check if connection is already in list break else: self.serverlist.append((address, False)) # Add new connection self.updateServerList(self.serverlist) # Overwrite serverlist with updated one self.sendUpdatedServerList() # Send updated list to all servers break if len(self.clientlist) > 0: # If Clients exists update new server with client list self.sendUpdatedClientList()
def listenClientMulticast(self): # Thread 9 # Listen for Client multicast messages and response with isLeaderValue # this function is for clients to discover the leader server and connect to leader server multicast_group = '224.3.29.71' server_address = ('', MulticastClientPort) sock = socket.socket(AF_INET, SOCK_DGRAM) # UDP socket sock.bind(server_address) # Bind to the server address group = socket.inet_aton(multicast_group) # Add to multicast group. mreq = struct.pack('4sL', group, socket.INADDR_ANY) sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) # Receive/respond loop # Listen to Client Multicast Address: while True: data, address = sock.recvfrom(128) if self.isLeader: response = 'True' else: response = 'False' sock.sendto(response.encode(), address)
sctpa_ack_seq, sctpa_check, sctpa_urg_ptr, ) # ----------------------------------------------------------------------------------------------------------------------- # ip header ip_ihl = 5 ip_ver = 4 ip_tos = 0 ip_tot_len = 0 ip_id = 54321 ip_frag_off = 0 ip_ttl = 255 ip_proto = socket.IPPROTO_TCP ip_check = 0 ip_saddr = socket.inet_aton(source_ip) ip_daddr = socket.inet_aton(dest_ip) ip_ihl_ver = (ip_ver << 4) + ip_ihl ip_header = pack( "!BBHHHBBH4s4s", ip_ihl_ver, ip_tos, ip_tot_len, ip_id, ip_frag_off, ip_ttl, ip_proto, ip_check, ip_saddr, ip_daddr ) # tcp заголовок tcp_source = 1234 tcp_dest = 80 tcp_seq = 454 tcp_ack_seq = 0 tcp_doff = 5
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)
sctpa_header = pack('!BHHHLLHH', sctpa_flags, sctpa_window, sctpa_sport, sctpa_dport, sctpa_seq, sctpa_ack_seq, sctpa_check, sctpa_urg_ptr) #----------------------------------------------------------------------------------------------------------------------- # ip header ip_ihl = 5 ip_ver = 4 ip_tos = 0 ip_tot_len = 0 ip_id = 54321 ip_frag_off = 0 ip_ttl = 255 ip_proto = socket.IPPROTO_TCP ip_check = 0 ip_saddr = socket.inet_aton(source_ip) ip_daddr = socket.inet_aton(dest_ip) ip_ihl_ver = (ip_ver << 4) + ip_ihl ip_header = pack('!BBHHHBBH4s4s', ip_ihl_ver, ip_tos, ip_tot_len, ip_id, ip_frag_off, ip_ttl, ip_proto, ip_check, ip_saddr, ip_daddr) # tcp заголовок tcp_source = 1234 tcp_dest = 80 tcp_seq = 454 tcp_ack_seq = 0 tcp_doff = 5 tcp_fin = 0