def _open_proxied_socket(url, options, proxy): hostname, port, resource, is_secure = parse_url(url) if not HAS_PYSOCKS: raise WebSocketException("PySocks module not found.") ptype = socks.SOCKS5 rdns = False if proxy.type == "socks4": ptype = socks.SOCKS4 if proxy.type == "http": ptype = socks.HTTP if proxy.type[-1] == "h": rdns = True sock = socks.create_connection( (hostname, port), proxy_type = ptype, proxy_addr = proxy.host, proxy_port = proxy.port, proxy_rdns = rdns, proxy_username = proxy.auth[0] if proxy.auth else None, proxy_password = proxy.auth[1] if proxy.auth else None, timeout = options.timeout, socket_options = DEFAULT_SOCKET_OPTION + options.sockopt ) if is_secure: if HAVE_SSL: sock = _ssl_socket(sock, options.sslopt, hostname) else: raise WebSocketException("SSL not available.") return sock, (hostname, port, resource)
def connect(self): # Adds support for SOCKS wrapping if self._proxy_scheme in ('socks4', 'socks5'): # define the socks proxy type if self._proxy_scheme == 'socks4': _type = socks.PROXY_TYPE_SOCKS4 elif self._proxy_scheme == 'socks5': _type = socks.PROXY_TYPE_SOCKS5 else: assert False, "this should NEVER happen" self.sock = socks.create_connection( (self.host, self.port), proxy_type=_type, proxy_addr=self._proxy_host, proxy_port=self._proxy_port, timeout=self.timeout ) else: """Connect to the host and port specified in __init__.""" self.sock = socket.create_connection((self.host,self.port), self.timeout) if self._tunnel_host: self._tunnel()
def _connect( self, hostname=None, port=None, username=None, password=None, accept_missing_host_key=None, timeout=None, compress=None, pkey=None, look_for_keys=None, allow_agent=None, key_filename=None, proxy_type=None, proxy_ip=None, proxy_port=None, sock=None): connect_kwargs = dict(self.connect_kwargs) connect_kwargs.update({ k: locals().get(k) for k in self.connect_kwargs if locals().get(k) is not None}) connect_kwargs["port"] = int(connect_kwargs.get("port")) ssh = ExtendedParamikoSSHClient() if bool(self.accept_missing_host_key or accept_missing_host_key): ssh.set_missing_host_key_policy(AutoAddPolicy()) if connect_kwargs.get("pkey") is not None: connect_kwargs["pkey"] = RSAKey.from_private_key( io.StringIO(unicode(connect_kwargs["pkey"]))) proxy_type = proxy_type or self.proxy_type proxy_ip = proxy_ip or self.proxy_ip proxy_port = proxy_port or self.proxy_port if connect_kwargs.get("sock") is not None: pass elif all([proxy_type, proxy_ip, proxy_port]): connect_kwargs["sock"] = create_connection( (connect_kwargs.get("hostname"), connect_kwargs.get("port")), proxy_type, proxy_ip, int(proxy_port)) ssh.connect(**connect_kwargs) return ssh
def open_connection(host, port, conn_timeout = 5.0, default_timeout = 5.0, ssl = False, socks_opts=None): """Open a connection as client to the specified server. If `socks_opts` is None, a direct connection will be made using `socket.create_connection`. Otherwise, a proxied connection will be made using `socks.create_connection`, including socks_opts as keyword arguments. Within that connection, an SSL tunnel will be established if `ssl` is True. """ if socks_opts is None: bare_socket = socket.create_connection((host, port), timeout=conn_timeout) else: bare_socket = socks.create_connection((host, port), timeout=conn_timeout, **socks_opts) if ssl: try: conn_socket = sslcontext.wrap_socket(bare_socket, server_hostname=host) except: bare_socket.close() raise else: conn_socket = bare_socket try: return Connection(conn_socket, default_timeout) except: conn_socket.close() raise
def proxy_create_connection(address, timeout=4, source_address=None): return socks.create_connection(address, proxy_type=socks.PROXY_TYPE_SOCKS5, proxy_addr=self.host, proxy_port=self.port, source_address=source_address, timeout=timeout)
def connect(self): # Adds support for SOCKS wrapping if self._proxy_scheme in ('socks4', 'socks5'): # define the socks proxy type if self._proxy_scheme == 'socks4': _type = socks.PROXY_TYPE_SOCKS4 elif self._proxy_scheme == 'socks5': _type = socks.PROXY_TYPE_SOCKS5 else: assert False, "this should NEVER happen" sock = socks.create_connection( (self.host, self.port), timeout=self.timeout, proxy_type=_type, proxy_addr=self._proxy_host, proxy_port=self._proxy_port ) else: # Add certificate verification sock = socket.create_connection((self.host, self.port), self.timeout) if self._tunnel_host: self.sock = sock self._tunnel() # Wrap socket using verification with the root certs in # trusted_root_certs self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, cert_reqs=self.cert_reqs, ca_certs=self.ca_certs) if self.ca_certs: match_hostname(self.sock.getpeercert(), self.host)
def _connect_to_broker(self, **proxy): """ Attempts to connect to a broker. Upon success will set the response time and whether the response came from the IP address versus the hostname. :param proxy Proxy arguments dictionary(Can be empty) :return: None """ broker_s = None proxy_addr = proxy.get("proxy_addr", None) proxy_port = proxy.get("proxy_port", None) proxy_available = bool(proxy_addr is not None and proxy_port is not None) try: start = datetime.datetime.now() if proxy_available: logger.debug("Using proxy for connection: %s:%s", proxy_addr, proxy_port) broker_s = socks.create_connection((self._host_name, self._port), timeout=1.0, **proxy) else: logger.debug("Not using proxy for connection.") broker_s = socket.create_connection((self._host_name, self._port), timeout=1.0) end = datetime.datetime.now() self._response_from_ip_address = False self._response_time = (end - start).total_seconds() except socket.error as msg: if self._ip_address: try: start = datetime.datetime.now() if proxy_available: logger.debug("Using proxy for connection: %s:%s", proxy_addr, proxy_port) broker_s = socks.create_connection((self._ip_address, self._port), timeout=1.0, **proxy) else: logger.debug("Not using proxy for connection.") broker_s = socket.create_connection((self._ip_address, self._port), timeout=1.0) end = datetime.datetime.now() self._response_from_ip_address = True self._response_time = (end - start).total_seconds() except socket.error as msg: logger.error( "Socket could not be created. Error Code: %s. Message: %s.", msg.errno, msg) else: logger.error( "Socket could not be created. Error Code: %s. Message: %s.", msg.errno, msg) finally: if broker_s is not None: broker_s.close()
def _create_socket(self): return create_connection((self.host, self.port), proxy_type=self.proxy_type, proxy_addr=self.proxy_addr, proxy_port=self.proxy_port, proxy_rdns=self.rdns, proxy_username=self.username, proxy_password=self.password)
def _new_conn(self): """ Establish a new connection via the SOCKS proxy. """ extra_kw = {} if self.source_address: extra_kw['source_address'] = self.source_address if self.socket_options: extra_kw['socket_options'] = self.socket_options try: conn = socks.create_connection( (self.host, self.port), proxy_type=self._socks_options['socks_version'], proxy_addr=self._socks_options['proxy_host'], proxy_port=self._socks_options['proxy_port'], proxy_username=self._socks_options['username'], proxy_password=self._socks_options['password'], timeout=self.timeout, **extra_kw ) except SocketTimeout as e: raise ConnectTimeoutError( "Connection to %s timed out. (connect timeout=%s)" % (self.host, self.timeout), e) except socks.ProxyError as e: # This is fragile as hell, but it seems to be the only way to raise # useful errors here. if e.socket_err: error = e.socket_err if isinstance(error, SocketTimeout): raise ConnectTimeoutError( "Connection to %s timed out. (connect timeout=%s)" % (self._socks_options['proxy_host'], self.timeout), e ) else: raise NewConnectionError( self, "Failed to establish a new connection: %s" % error, error ) else: raise NewConnectionError( self, "Failed to establish a new connection: %s" % e, e ) except SocketError as e: # Defensive: PySocks should catch all these. raise NewConnectionError( self, "Failed to establish a new connection: %s" % e, e) return conn
def create_connection(address, timeout=10): if 'onion' in address[0]: return socks.create_connection(address, timeout=timeout, proxy_type=socks.PROXY_TYPE_SOCKS5, proxy_addr="127.0.0.1", proxy_port=9050) else: return socket.create_connection(address, timeout=timeout)
def _new_conn(self): """ Establish a new connection via the SOCKS proxy. """ extra_kw = {} if self.source_address: extra_kw["source_address"] = self.source_address if self.socket_options: extra_kw["socket_options"] = self.socket_options try: conn = socks.create_connection( (self.host, self.port), proxy_type=self._socks_options["socks_version"], proxy_addr=self._socks_options["proxy_host"], proxy_port=self._socks_options["proxy_port"], proxy_username=self._socks_options["username"], proxy_password=self._socks_options["password"], proxy_rdns=self._socks_options["rdns"], timeout=self.timeout, **extra_kw ) except SocketTimeout: raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % (self.host, self.timeout), ) except socks.ProxyError as e: # This is fragile as hell, but it seems to be the only way to raise # useful errors here. if e.socket_err: error = e.socket_err if isinstance(error, SocketTimeout): raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % (self.host, self.timeout), ) else: raise NewConnectionError( self, "Failed to establish a new connection: %s" % error ) else: raise NewConnectionError( self, "Failed to establish a new connection: %s" % e ) except SocketError as e: # Defensive: PySocks should catch all these. raise NewConnectionError( self, "Failed to establish a new connection: %s" % e ) return conn
def _new_conn(self) -> "socks.socksocket": """ Establish a new connection via the SOCKS proxy. """ extra_kw: Dict[str, Any] = {} if self.source_address: extra_kw["source_address"] = self.source_address if self.socket_options: extra_kw["socket_options"] = self.socket_options try: conn = socks.create_connection( (self.host, self.port), proxy_type=self._socks_options["socks_version"], proxy_addr=self._socks_options["proxy_host"], proxy_port=self._socks_options["proxy_port"], proxy_username=self._socks_options["username"], proxy_password=self._socks_options["password"], proxy_rdns=self._socks_options["rdns"], timeout=self.timeout, **extra_kw, ) except SocketTimeout as e: raise ConnectTimeoutError( self, f"Connection to {self.host} timed out. (connect timeout={self.timeout})", ) from e except socks.ProxyError as e: # This is fragile as hell, but it seems to be the only way to raise # useful errors here. if e.socket_err: error = e.socket_err if isinstance(error, SocketTimeout): raise ConnectTimeoutError( self, f"Connection to {self.host} timed out. (connect timeout={self.timeout})", ) from e else: # Adding `from e` messes with coverage somehow, so it's omitted. # See #2386. raise NewConnectionError( self, f"Failed to establish a new connection: {error}") else: raise NewConnectionError( self, f"Failed to establish a new connection: {e}") from e except OSError as e: # Defensive: PySocks should catch all these. raise NewConnectionError( self, f"Failed to establish a new connection: {e}") from e return conn
def _get_socket(self, host, port, timeout): if self.proxy_addr is None: return SMTP._get_socket(self, host, port, timeout) else: return create_connection((host, port), proxy_type=self.proxy_type, proxy_addr=self.proxy_addr, proxy_port=self.proxy_port, proxy_rdns=self.rdns, proxy_username=self.username, proxy_password=self.password)
def _do_socket_connect(self, connect_timeout, connect_kw): """ Establish a new connection via the SOCKS proxy. """ try: conn = socks.create_connection( (self._host, self._port), proxy_type=self._socks_options['socks_version'], proxy_addr=self._socks_options['proxy_host'], proxy_port=self._socks_options['proxy_port'], proxy_username=self._socks_options['username'], proxy_password=self._socks_options['password'], proxy_rdns=self._socks_options['rdns'], timeout=connect_timeout, **connect_kw ) except SocketTimeout as e: raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % (self._host, connect_timeout), ) except socks.ProxyError as e: # This is fragile as hell, but it seems to be the only way to raise # useful errors here. if e.socket_err: error = e.socket_err if isinstance(error, SocketTimeout): raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % (self._host, connect_timeout), ) else: raise NewConnectionError( self, "Failed to establish a new connection: %s" % error, ) else: raise NewConnectionError( self, "Failed to establish a new connection: %s" % e ) except SocketError as e: # Defensive: PySocks should catch all these. raise NewConnectionError( self, "Failed to establish a new connection: %s" % e ) return conn
def socks_get_socket(self, host, port, timeout): if self.debuglevel > 0: self._print_debug('connect: to', (host, port), self.source_address) return socks.create_connection((host, port), timeout=timeout, source_address=self.source_address, proxy_type=self.proxy_type, proxy_addr=self.proxy_addr, proxy_port=self.proxy_port, proxy_rdns=self.proxy_rdns, proxy_username=self.proxy_username, proxy_password=self.proxy_password, socket_options=self.socket_options)
def _create_socket(self): return socks.create_connection( dest_pair=(self._host, self._port), timeout=self._p_timeout, source_address=self._p_source_address, proxy_type=self._p_proxy_type, proxy_addr=self._p_proxy_addr, proxy_port=self._p_proxy_port, proxy_rdns=self._p_proxy_rdns, proxy_username=self._p_proxy_username, proxy_password=self._p_proxy_password, socket_options=self._p_socket_options, )
def sync_open(self, client): """打开通道""" self.client = client if self.proxy_addr: _logger.info('use proxy on {}:{}'.format(self.proxy_addr, self.proxy_port)) self.conn = socks.create_connection( (self.host, self.port), timeout=1, proxy_addr=self.proxy_addr, proxy_port=self.proxy_port, proxy_username=self.proxy_username, proxy_password=self.proxy_password) else: self.conn = socket.create_connection((self.host, self.port))
def open(self, host, port=0, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, **kwargs): """Connect to a host. The optional second argument is the port number, which defaults to the standard telnet port (23). Don't try to reopen an already connected instance. """ self.eof = 0 if not port: port = telnetlib.TELNET_PORT self.host = host self.port = port self.timeout = timeout sys.audit("telnetlib.Telnet.open", self, host, port) proxy_url = os.environ.get('telnet_proxy') if proxy_url: url_info = urlparse(proxy_url) proxy_args = { 'proxy_type': socks.PROXY_TYPES.get(url_info.scheme.upper()), 'proxy_addr': url_info.hostname, 'proxy_port': url_info.port, 'proxy_username': url_info.username, 'proxy_password': url_info.password } else: proxy_args = {} proxy_args.update(kwargs) print('Trying {}:{}...'.format(host, port)) target_hostname = socket.gethostbyaddr(host)[0] if proxy_args.get('proxy_addr'): self.sock = socks.create_connection((host, port), timeout, **proxy_args) socks_hostname = socket.gethostbyaddr( proxy_args.get('proxy_addr'))[0] print('Connected to {} via {}.'.format(target_hostname, socks_hostname)) else: self.sock = socket.create_connection((host, port), timeout) print('Connected to {}.'.format(target_hostname))
def _new_conn(self): """ Establish a new connection via the SOCKS proxy. """ extra_kw = {} if self.source_address: extra_kw['source_address'] = self.source_address if self.socket_options: extra_kw['socket_options'] = self.socket_options try: conn = socks.create_connection( (self.host, self.port), proxy_type=self._socks_options['socks_version'], proxy_addr=self._socks_options['proxy_host'], proxy_port=self._socks_options['proxy_port'], proxy_username=self._socks_options['username'], proxy_password=self._socks_options['password'], proxy_rdns=self._socks_options['rdns'], timeout=self.timeout, **extra_kw) except SocketTimeout: raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % (self.host, self.timeout)) except socks.ProxyError, e: # This is fragile as hell, but it seems to be the only way to raise # useful errors here. if e.socket_err: error = e.socket_err if isinstance(error, SocketTimeout): raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % (self.host, self.timeout)) else: raise NewConnectionError( self, "Failed to establish a new connection: %s" % error) else: raise NewConnectionError( self, "Failed to establish a new connection: %s" % e)
def connect(self): (proxytype, proxyaddr, proxyport, rdns, username, password) = self.proxyargs rdns = rdns and proxyaddr not in socks4_no_rdns while True: try: sock = socks.create_connection( (self.host, self.port), self.timeout, None, proxytype, proxyaddr, proxyport, rdns, username, password, ((socket.IPPROTO_TCP, socket.TCP_NODELAY, 1), )) break except socks.SOCKS4Error as e: if rdns and "0x5b" in str(e) and not is_ip(self.host): # Maybe a SOCKS4 server that doesn't support remote resolving # Let's try again rdns = False socks4_no_rdns.add(proxyaddr) else: raise self.sock = sock
def _new_conn(self): extra_kw = {} if self.source_address: extra_kw['source_address'] = self.source_address if self.socket_options: extra_kw['socket_options'] = self.socket_options try: conn = socks.create_connection( (self.host, self.port), proxy_type=self._socks_options['socks_version'], proxy_addr=self._socks_options['proxy_host'], proxy_port=self._socks_options['proxy_port'], proxy_username=self._socks_options['username'], proxy_password=self._socks_options['password'], timeout=self.timeout, **extra_kw) except SocketTimeout as e: raise ConnectTimeoutError( self, 'Connection to %s timed out. (connect timeout=%s)' % (self.host, self.timeout)) except socks.ProxyError as e: if e.socket_err: error = e.socket_err if isinstance(error, SocketTimeout): raise ConnectTimeoutError( self, 'Connection to %s timed out. (connect timeout=%s)' % (self.host, self.timeout)) else: raise NewConnectionError( self, 'Failed to establish a new connection: %s' % error) else: raise NewConnectionError( self, 'Failed to establish a new connection: %s' % e) except SocketError as e: raise NewConnectionError( self, 'Failed to establish a new connection: %s' % e) return conn
def do_unwrap_socks(sock, host, port, client_address, req, left_buf=b""): if not g.x_tunnel: return try: remote_sock = socks.create_connection((host, port), proxy_type="socks5h", proxy_addr="127.0.0.1", proxy_port=g.x_tunnel_socks_port, timeout=15) except Exception as e: xlog.warn("do_unwrap_socks connect to x-tunnel for %s:%d proxy fail.", host, port) return if isinstance(req.connection, ssl.SSLSocket): try: # TODO: send SNI remote_ssl_sock = ssl.wrap_socket(remote_sock) except: xlog.warn("do_unwrap_socks ssl_wrap for %s:%d proxy fail.", host, port) return else: remote_ssl_sock = remote_sock # avoid close by req.__del__ req.rfile._close = False req.wfile._close = False req.connection = None if not isinstance(sock, SocketWrap): sock = SocketWrap(sock, client_address[0], client_address[1]) xlog.info("host:%s:%d do_unwrap_socks", host, port) remote_ssl_sock.send(left_buf) sw = SocketWrap(remote_ssl_sock, "x-tunnel", port, host) sock.recved_times = 3 g.pipe_socks.add_socks(sock, sw)
def do_unwrap_socks(sock, host, port, client_address, req, left_buf=""): if not g.x_tunnel: return try: remote_sock = socks.create_connection( (host, port), proxy_type="socks5h", proxy_addr="127.0.0.1", proxy_port=1080, timeout=15 ) except Exception as e: xlog.warn("do_unwrap_socks connect to x-tunnel for %s:%d proxy fail.", host, port) return if isinstance(req.connection, ssl.SSLSocket): try: # TODO: send SNI remote_ssl_sock = ssl.wrap_socket(remote_sock) except: xlog.warn("do_unwrap_socks ssl_wrap for %s:%d proxy fail.", host, port) return else: remote_ssl_sock = remote_sock # avoid close by req.__del__ req.rfile._close = False req.wfile._close = False req.connection = None if not isinstance(sock, SocketWrap): sock = SocketWrap(sock, client_address[0], client_address[1]) xlog.info("host:%s:%d do_unwrap_socks", host, port) remote_ssl_sock.send(left_buf) sw = SocketWrap(remote_ssl_sock, "x-tunnel", port, host) sock.recved_times = 3 g.pipe_socks.add_socks(sock, sw)
def do_unwrap_socks(sock, host, port, client_address, req, left_buf=""): # TODO: bug exist sock.close() return if not g.x_tunnel: return try: remote_sock = socks.create_connection( (host, port), proxy_type="socks5", proxy_addr="127.0.0.1", proxy_port=1080, timeout=15 ) except Exception as e: xlog.warn("do_unwrap_socks connect to x-tunnel for %s:%d proxy fail.", host, port) return if req.path.startswith("https"): try: ssl_sock = ssl.wrap_socket(remote_sock) except: xlog.warn("do_unwrap_socks ssl_wrap for %s:%d proxy fail.", host, port) return else: ssl_sock = remote_sock if not isinstance(sock, SocketWrap): sock = SocketWrap(sock, "x-tunnel", port, host) xlog.info("host:%s:%d do_unwrap_socks", host, port) ssl_sock.send(left_buf) sw = SocketWrap(ssl_sock, client_address[0], client_address[1]) sock.recved_times = 3 g.pipe_socks.add_socks(sock, sw)
# AWSIoTMQTTClient connection configuration myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing myAWSIoTMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec # AWSIoTMQTTClient socket configuration # import pysocks to help us build a socket that supports a proxy configuration import socks # set proxy arguments (for SOCKS5 proxy: proxy_type=2, for HTTP proxy: proxy_type=3) proxy_config = {"proxy_addr":<proxy_addr>, "proxy_port":<proxy_port>, "proxy_type":<proxy_type>} # create anonymous function to handle socket creation socket_factory = lambda: socks.create_connection((host, port), **proxy_config) myAWSIoTMQTTClient.configureSocketFactory(socket_factory) # Connect and subscribe to AWS IoT myAWSIoTMQTTClient.connect() if args.mode == 'both' or args.mode == 'subscribe': myAWSIoTMQTTClient.subscribe(topic, 1, customCallback) time.sleep(2) # Publish to the same topic in a loop forever loopCount = 0 while True: if args.mode == 'both' or args.mode == 'publish': message = {} message['message'] = args.message message['sequence'] = loopCount
def _make_socket(self, ptype, phost, pport, host, port, bind, timeout): return socks.create_connection((host, port), timeout, bind, ptype, phost, pport)
def _(host, port, bind, timeout): return socks.create_connection((host, port), timeout, bind, ptype, phost, pport)
def create_connection(address, proxy=None): if proxy is None: return socket.create_connection(dest_pair(address)) else: return socks.create_connection(dest_pair(address), **socks_map(proxy))
def socket_factory(): return socks.create_connection((host, port), **proxy_config)
def socket_factory(): return socks.create_connection((host, port), **proxy_config) myAWSIoTMQTTClient.configureSocketFactory(socket_factory)