Example #1
0
 def __init__(self, hxsServer, ctimeout=4, parentproxy=None):
     basesocket.__init__(self)
     if not isinstance(hxsServer, ParentProxy):
         hxsServer = ParentProxy(hxsServer, hxsServer)
     self.hxsServer = hxsServer
     self.timeout = ctimeout
     if parentproxy and not isinstance(parentproxy, ParentProxy):
         parentproxy = ParentProxy(parentproxy, parentproxy)
     self.parentproxy = parentproxy
     self.PSK = urlparse.parse_qs(self.hxsServer.parse.query).get(
         'PSK', [''])[0]
     self.method = urlparse.parse_qs(self.hxsServer.parse.query).get(
         'method', [DEFAULT_METHOD])[0].lower()
     self.hash_algo = urlparse.parse_qs(self.hxsServer.parse.query).get(
         'hash', [DEFAULT_HASH])[0].upper()
     self.serverid = (self.hxsServer.username, self.hxsServer.hostname)
     self.cipher = None
     self._data_bak = None
     self.readable = 0
     self.writeable = 0
     self.pooled = 0
     # TODO: send custom headers
     self._http_obfs = self.hxsServer.query.get('obfs', [''])[0] == 'http'
     self._http_header = b'GET / HTTP/1.1\r\n'
     self._http_header += b'Host: %s\r\n' % self.hxsServer.query.get(
         'hostname', ['www.baidu.com'])[0].encode()
     self._http_header += b'User-Agent: %s\r\n' % self.hxsServer.query.get(
         'UA', ['curl/7.18.1'])[0].encode()
     self._http_header += b'Upgrade: websocket\r\nConnection: Upgrade\r\n'
     self._http_header += b'Sec-WebSocket-Key: ' + base64.b64encode(
         os.urandom(16))
     self._http_header += b'\r\n\r\n'
     self._header_sent = False
     self._header_received = False
Example #2
0
    def __init__(self, hxsServer, ctimeout, parentproxy, manager):
        if not isinstance(hxsServer, ParentProxy):
            hxsServer = ParentProxy(hxsServer, hxsServer)
        self.hxsServer = hxsServer
        self.name = self.hxsServer.name
        self.timeout = ctimeout
        self._manager = manager
        self._last_ping = 0

        self._sock = None

        if parentproxy and not isinstance(parentproxy, ParentProxy):
            parentproxy = ParentProxy(parentproxy, parentproxy)
        self.parentproxy = parentproxy
        _psk = urlparse.parse_qs(self.hxsServer.parse.query).get('PSK', [''])[0]
        self.method = urlparse.parse_qs(self.hxsServer.parse.query).get('method', [DEFAULT_METHOD])[0].lower()
        self.hash_algo = urlparse.parse_qs(self.hxsServer.parse.query).get('hash', [DEFAULT_HASH])[0].upper()

        self._connection_write_lock = RLock()

        self.__pskcipher = Encryptor(_psk, self.method)
        self.__cipher = None
        self._next_stream_id = 1

        self._client_sock = {}
        self._client_status = {}
        self._stream_status = {}

        self.getKey()
        # start read from hxsocks2 connection
        Thread(target=self.read_from_connection).start()
Example #3
0
 def __init__(self, hxsServer, ctimeout=4, parentproxy=None):
     if not isinstance(hxsServer, ParentProxy):
         hxsServer = ParentProxy(hxsServer, hxsServer)
     self.hxsServer = hxsServer
     self.timeout = ctimeout
     self._sock = None
     self._socketpair_a, self._socketpair_b = socket.socketpair()
     self._socketpair_a.settimeout(5)
     self._socketpair_b.settimeout(5)
     self.fileno = self._socketpair_a.fileno
     if parentproxy and not isinstance(parentproxy, ParentProxy):
         parentproxy = ParentProxy(parentproxy, parentproxy)
     self.parentproxy = parentproxy
     self.PSK = urlparse.parse_qs(self.hxsServer.parse.query).get(
         'PSK', [''])[0]
     self.method = urlparse.parse_qs(self.hxsServer.parse.query).get(
         'method', [DEFAULT_METHOD])[0].lower()
     self.aead = encrypt.is_aead(self.method)
     self.hash_algo = urlparse.parse_qs(self.hxsServer.parse.query).get(
         'hash', [DEFAULT_HASH])[0].upper()
     id_ = urlparse.parse_qs(self.hxsServer.parse.query).get('id', [''])[0]
     self.serverid = (self.hxsServer.username, id_
                      or (self.hxsServer.hostname, self.hxsServer.port))
     self.cipher = None
     self._data_bak = None
     self.readable = 0
     self.writeable = 0
     self.pooled = 0
     self.pooled_at = 0
     self.pool_count = 0
     self.pre_close = 0
Example #4
0
def create_connection(netloc, ctimeout=None, source_address=None, iplist=None, parentproxy=None, tunnel=False):
    logger.debug('connection.create_connection: %r %r %r' % (netloc, parentproxy, tunnel))
    if parentproxy and not isinstance(parentproxy, ParentProxy):
        logging.warning('parentproxy is not a ParentProxy instance, please check. %s' % parentproxy)
        parentproxy = ParentProxy(parentproxy, parentproxy)
    ctimeout = ctimeout or parentproxy.timeout
    via = parentproxy.get_via() if parentproxy else None
    s = None
    if not parentproxy or not parentproxy.proxy:
        return _create_connection(netloc, ctimeout, iplist=iplist)
    elif parentproxy.scheme == 'http':
        s = create_connection((parentproxy.hostname, parentproxy.port or 80), ctimeout, source_address, parentproxy=via, tunnel=True)
        if tunnel:
            do_tunnel(s, netloc, parentproxy)
    elif parentproxy.scheme == 'https':
        s = create_connection((parentproxy.hostname, parentproxy.port or 443), ctimeout, source_address, parentproxy=via, tunnel=True)
        s = ssl.wrap_socket(s)
        s.do_handshake()
        if tunnel:
            do_tunnel(s, netloc, parentproxy)
    elif parentproxy.scheme == 'ss':
        s = sssocket(parentproxy, ctimeout, via)
        s.connect(netloc)
    elif parentproxy.scheme == 'hxs':
        s = hxssocket(parentproxy, ctimeout, via)
        s.connect(netloc)
    elif parentproxy.scheme == 'sni':
        s = create_connection((parentproxy.hostname, parentproxy.port or 443), ctimeout, source_address, parentproxy=via, tunnel=True)
    elif parentproxy.scheme == 'socks5':
        s = create_connection((parentproxy.hostname, parentproxy.port or 1080), ctimeout, source_address, parentproxy=via, tunnel=True)
        s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        s.sendall(b"\x05\x02\x00\x02" if parentproxy.username else b"\x05\x01\x00")
        data = s.recv(2)
        if data == b'\x05\x02':  # basic auth
            s.sendall(b''.join([b"\x01",
                                chr(len(parentproxy.username)).encode(),
                                parentproxy.username.encode(),
                                chr(len(parentproxy.password)).encode(),
                                parentproxy.password.encode()]))
            data = s.recv(2)
        assert data[1] == b'\x00'  # no auth needed or auth passed
        s.sendall(b''.join([b"\x05\x01\x00\x03",
                            chr(len(netloc[0])).encode(),
                            netloc[0].encode(),
                            struct.pack(b">H", netloc[1])]))
        data = s.recv(4)
        assert data[1] == b'\x00'
        if data[3] == b'\x01':  # read ipv4 addr
            s.recv(4)
        elif data[3] == b'\x03':  # read host addr
            s.recv(ord(s.recv(1)))
        elif data[3] == b'\x04':  # read ipv6 addr
            s.recv(16)
        s.recv(2)  # read port
        s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 0)
    else:
        raise IOError(0, 'parentproxy %s not supported!' % parentproxy.name)
    if s:
        return s
    raise IOError(0, 'create_connection failed!')
Example #5
0
 def __init__(self, ssServer=None, ctimeout=1, parentproxy=None):
     basesocket.__init__(self)
     if ssServer and not isinstance(ssServer, ParentProxy):
         ssServer = ParentProxy(ssServer, ssServer)
     self.ssServer = ssServer
     self.timeout = ctimeout
     if parentproxy and not isinstance(parentproxy, ParentProxy):
         parentproxy = ParentProxy(parentproxy, parentproxy)
     self.parentproxy = parentproxy
     self.crypto = None
     self.connected = False
Example #6
0
 def __init__(self, ssServer, ctimeout=5, parentproxy=None):
     if ssServer and not isinstance(ssServer, ParentProxy):
         ssServer = ParentProxy(ssServer, ssServer)
     self.ssServer = ssServer
     self.timeout = ctimeout
     if parentproxy and not isinstance(parentproxy, ParentProxy):
         parentproxy = ParentProxy(parentproxy, parentproxy)
     self.parentproxy = parentproxy
     self.crypto = None
     self.aead = False
     self._socketpair_a, self._socketpair_b = socket.socketpair()
     self._ota_chunk_idx = 0
     self._thread = None
Example #7
0
def hxssocket(hxsServer, ctimeout=4, parentproxy=None):
    if not isinstance(hxsServer, ParentProxy):
        hxsServer = ParentProxy(hxsServer, hxsServer)
    result = POOL.get(hxsServer.parse.hostname)
    if result:
        logger.debug('hxsocks reusing connection, ' + result[1])
        result[0].pooled = 0
        result[0].settimeout(ctimeout)
        return result[0]
    return _hxssocket(hxsServer, ctimeout, parentproxy)
Example #8
0
 def __init__(self, ssServer=None, ctimeout=1, parentproxy=None):
     basesocket.__init__(self)
     if ssServer and not isinstance(ssServer, ParentProxy):
         ssServer = ParentProxy(ssServer, ssServer)
     self.ssServer = ssServer
     self.timeout = ctimeout
     if parentproxy and not isinstance(parentproxy, ParentProxy):
         parentproxy = ParentProxy(parentproxy, parentproxy)
     self.parentproxy = parentproxy
     self.crypto = None
     self.__ota = False
     self._ota_chunk_idx = 0
     self.connected = False
     # TODO: send custom headers
     self._http_obfs = self.ssServer.query.get('obfs', [''])[0] == 'http'
     self._http_obfs_host = self.ssServer.query.get('hostname',
                                                    ['www.baidu.com'])[0]
     self._http_obfs_ua = self.ssServer.query.get('UA', ['curl/7.18.1'])[0]
     self._header_received = False
Example #9
0
 def __init__(self, hxsServer=None, ctimeout=4, parentproxy=None):
     basesocket.__init__(self)
     if hxsServer and not isinstance(hxsServer, ParentProxy):
         hxsServer = ParentProxy(hxsServer, hxsServer)
     self.hxsServer = hxsServer
     self.timeout = ctimeout
     if parentproxy and not isinstance(parentproxy, ParentProxy):
         parentproxy = ParentProxy(parentproxy, parentproxy)
     self.parentproxy = parentproxy
     if self.hxsServer:
         self.PSK = urlparse.parse_qs(self.hxsServer.parse.query).get(
             'PSK', [''])[0]
         self.method = urlparse.parse_qs(self.hxsServer.parse.query).get(
             'method', [default_method])[0].lower()
         self.serverid = (self.hxsServer.username, self.hxsServer.hostname)
     self.cipher = None
     self.connected = 0
     # value: 0: request not sent
     #        1: request sent, no server response received
     #        2: server response received
     self._data_bak = None
Example #10
0
def hxssocket(hxsServer, ctimeout=4, parentproxy=None):
    if not isinstance(hxsServer, ParentProxy):
        hxsServer = ParentProxy(hxsServer, hxsServer)
    result = POOL.get(hxsServer.name)
    if result:
        logger.debug('hxsocks reusing connection, %s %d' %
                     (result[1], result[0].pool_count))
        result[0].pooled = 0
        result[0]._socketpair_a, result[0]._socketpair_b = socket.socketpair()
        result[0].fileno = result[0]._socketpair_a.fileno
        result[0].settimeout(ctimeout)
        return result[0]
    return _hxssocket(hxsServer, ctimeout, parentproxy)
Example #11
0
    def __init__(self):
        self.logger = logging.getLogger('FW_Lite')
        self.version = SConfigParser()
        self.userconf = SConfigParser()
        self.reload()
        self.UPDATE_INTV = 6
        self.timeout = self.userconf.dgetint('fgfwproxy', 'timeout', 4)
        ParentProxy.DEFAULT_TIMEOUT = self.timeout
        self.parentlist = ParentProxyList()
        self.HOSTS = defaultdict(list)
        self.GUI = '-GUI' in sys.argv
        self.rproxy = self.userconf.dgetbool('fgfwproxy', 'rproxy', False)

        listen = self.userconf.dget('fgfwproxy', 'listen', '8118')
        if listen.isdigit():
            self.listen = ('127.0.0.1', int(listen))
        else:
            self.listen = (listen.rsplit(':', 1)[0], int(listen.rsplit(':', 1)[1]))

        try:
            self.local_ip = set(socket.gethostbyname_ex(socket.gethostname())[2])
        except:
            try:
                csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                csock.connect(('8.8.8.8', 53))
                (addr, port) = csock.getsockname()
                csock.close()
                self.local_ip = set([addr])
            except socket.error:
                self.local_ip = set(['127.0.0.1'])
        ip = self.local_ip.pop()
        self.local_ip.add(ip)
        self.PAC = '''\
function FindProxyForURL(url, host) {
if (isPlainHostName(host) ||
    host.indexOf('127.') == 0 ||
    host.indexOf('192.168.') == 0 ||
    host.indexOf('10.') == 0 ||
    shExpMatch(host, 'localhost.*'))
    {
        return 'DIRECT';
    }
return "PROXY %s:%s; DIRECT";}''' % (ip, self.listen[1])
        if self.userconf.dget('fgfwproxy', 'pac', ''):
            if os.path.isfile(self.userconf.dget('fgfwproxy', 'pac', '')):
                self.PAC = open(self.userconf.dget('fgfwproxy', 'pac', '')).read()
            else:
                self.PAC = '''\
function FindProxyForURL(url, host) {
if (isPlainHostName(host) ||
    host.indexOf('127.') == 0 ||
    host.indexOf('192.168.') == 0 ||
    host.indexOf('10.') == 0 ||
    shExpMatch(host, 'localhost.*'))
    {
        return 'DIRECT';
    }
return "PROXY %s; DIRECT";}''' % self.userconf.dget('fgfwproxy', 'pac', '')
        self.PAC = self.PAC.encode()

        if self.userconf.dget('FGFW_Lite', 'logfile', ''):
            path = self.userconf.dget('FGFW_Lite', 'logfile', '')
            dirname = os.path.dirname(path)
            if dirname and not os.path.exists(dirname):
                os.makedirs(dirname)
            formatter = logging.Formatter('FW-Lite %(asctime)s %(levelname)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
            hdlr = logging.handlers.RotatingFileHandler(path, maxBytes=1048576, backupCount=5)
            hdlr.setFormatter(formatter)
            self.logger.addHandler(hdlr)

        self.region = set(x.upper() for x in self.userconf.dget('fgfwproxy', 'region', '').split('|') if x.strip())
        self.profiles = len(self.userconf.dget('fgfwproxy', 'profile', '13'))
        self.xheaders = self.userconf.dgetbool('fgfwproxy', 'xheaders', False)

        if self.userconf.dget('fgfwproxy', 'parentproxy', ''):
            self.addparentproxy('direct', '%s 0' % self.userconf.dget('fgfwproxy', 'parentproxy', ''))
            self.addparentproxy('local', 'direct 100')
        else:
            self.addparentproxy('direct', 'direct 0')

        ParentProxy.set_via(self.parentlist.direct)

        for k, v in self.userconf.items('parents'):
            if '6Rc59g0jFlTppvel' in v:
                self.userconf.remove_option('parents', k)
                self.confsave()
                continue
            self.addparentproxy(k, v)

        if not self.rproxy and len([k for k in self.parentlist.httpsparents() if k.httpspriority < 100]) == 0:
            self.logger.warning('No parent proxy available!')

        self.maxretry = self.userconf.dgetint('fgfwproxy', 'maxretry', 4)

        def addhost(host, ip):
            try:
                ipo = ip_address(ip)
                if isinstance(ipo, IPv4Address):
                    self.HOSTS[host].append((2, ip))
                else:
                    self.HOSTS[host].append((10, ip))
            except Exception:
                self.logging.warning('unsupported host: %s' % ip)

        for host, ip in self.userconf.items('hosts'):
            addhost(host, ip)

        if os.path.isfile('./fgfw-lite/hosts'):
            for line in open('./fgfw-lite/hosts'):
                line = line.strip()
                if line and not line.startswith('#'):
                    try:
                        ip, host = line.split()
                        addhost(host, ip)
                    except Exception as e:
                        self.logger.warning('%s %s' % (e, line))
        self.localdns = parse_hostport(self.userconf.dget('dns', 'localdns', '8.8.8.8:53' if self.rproxy else '223.5.5.5:53'))
        self.remotedns = self.localdns if self.rproxy else parse_hostport(self.userconf.dget('dns', 'remotedns', '208.67.222.222:5353'))
        self.REDIRECTOR = redirector(self)
        self.PARENT_PROXY = get_proxy(self)
        self.resolver = resolver.get_resolver(self.localdns, self.remotedns,
                                              ParentProxy('self', 'http://127.0.0.1:%d' % self.listen[1]),
                                              self.PARENT_PROXY.force)
Example #12
0
    def __init__(self):
        self.logger = logging.getLogger('FW_Lite')
        self.version = SConfigParser()
        self.userconf = SConfigParser()
        self.reload()
        self.UPDATE_INTV = 6
        self.timeout = self.userconf.dgetint('fgfwproxy', 'timeout', 4)
        ParentProxy.DEFAULT_TIMEOUT = self.timeout
        self.parentlist = ParentProxyList()
        self.HOSTS = defaultdict(list)
        self.GUI = '-GUI' in sys.argv
        self.rproxy = self.userconf.dgetbool('fgfwproxy', 'rproxy', False)

        listen = self.userconf.dget('fgfwproxy', 'listen', '8118')
        if listen.isdigit():
            self.listen = ('127.0.0.1', int(listen))
        else:
            self.listen = (listen.rsplit(':',
                                         1)[0], int(listen.rsplit(':', 1)[1]))

        try:
            self.local_ip = set(
                socket.gethostbyname_ex(socket.gethostname())[2])
        except:
            try:
                csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                csock.connect(('8.8.8.8', 53))
                (addr, port) = csock.getsockname()
                csock.close()
                self.local_ip = set([addr])
            except socket.error:
                self.local_ip = set(['127.0.0.1'])
        ip = self.local_ip.pop()
        self.local_ip.add(ip)
        self.PAC = '''\
function FindProxyForURL(url, host) {
if (isPlainHostName(host) ||
    host.indexOf('127.') == 0 ||
    host.indexOf('192.168.') == 0 ||
    host.indexOf('10.') == 0 ||
    shExpMatch(host, 'localhost.*'))
    {
        return 'DIRECT';
    }
return "PROXY %s:%s; DIRECT";}''' % (ip, self.listen[1])
        if self.userconf.dget('fgfwproxy', 'pac', ''):
            if os.path.isfile(self.userconf.dget('fgfwproxy', 'pac', '')):
                self.PAC = open(self.userconf.dget('fgfwproxy', 'pac',
                                                   '')).read()
            else:
                self.PAC = '''\
function FindProxyForURL(url, host) {
if (isPlainHostName(host) ||
    host.indexOf('127.') == 0 ||
    host.indexOf('192.168.') == 0 ||
    host.indexOf('10.') == 0 ||
    shExpMatch(host, 'localhost.*'))
    {
        return 'DIRECT';
    }
return "PROXY %s; DIRECT";}''' % self.userconf.dget('fgfwproxy', 'pac', '')
        self.PAC = self.PAC.encode()

        if self.userconf.dget('FGFW_Lite', 'logfile', ''):
            path = self.userconf.dget('FGFW_Lite', 'logfile', '')
            dirname = os.path.dirname(path)
            if dirname and not os.path.exists(dirname):
                os.makedirs(dirname)
            formatter = logging.Formatter(
                'FW-Lite %(asctime)s %(levelname)s %(message)s',
                datefmt='%Y-%m-%d %H:%M:%S')
            hdlr = logging.handlers.RotatingFileHandler(path,
                                                        maxBytes=1048576,
                                                        backupCount=5)
            hdlr.setFormatter(formatter)
            self.logger.addHandler(hdlr)

        self.region = set(
            x.upper()
            for x in self.userconf.dget('fgfwproxy', 'region', '').split('|')
            if x.strip())
        self.profiles = len(self.userconf.dget('fgfwproxy', 'profile', '13'))
        self.xheaders = self.userconf.dgetbool('fgfwproxy', 'xheaders', False)

        if self.userconf.dget('fgfwproxy', 'parentproxy', ''):
            self.addparentproxy(
                'direct',
                '%s 0' % self.userconf.dget('fgfwproxy', 'parentproxy', ''))
            self.addparentproxy('local', 'direct 100')
        else:
            self.addparentproxy('direct', 'direct 0')

        ParentProxy.set_via(self.parentlist.direct)

        for k, v in self.userconf.items('parents'):
            if '6Rc59g0jFlTppvel' in v:
                self.userconf.remove_option('parents', k)
                self.confsave()
                continue
            self.addparentproxy(k, v)

        if not self.rproxy and len([
                k for k in self.parentlist.httpsparents()
                if k.httpspriority < 100
        ]) == 0:
            self.logger.warning('No parent proxy available!')

        self.maxretry = self.userconf.dgetint('fgfwproxy', 'maxretry', 4)

        def addhost(host, ip):
            try:
                ipo = ip_address(ip)
                if isinstance(ipo, IPv4Address):
                    self.HOSTS[host].append((2, ip))
                else:
                    self.HOSTS[host].append((10, ip))
            except Exception:
                self.logging.warning('unsupported host: %s' % ip)

        for host, ip in self.userconf.items('hosts'):
            addhost(host, ip)

        if os.path.isfile('./fgfw-lite/hosts'):
            for line in open('./fgfw-lite/hosts'):
                line = line.strip()
                if line and not line.startswith('#'):
                    try:
                        ip, host = line.split()
                        addhost(host, ip)
                    except Exception as e:
                        self.logger.warning('%s %s' % (e, line))
        self.localdns = parse_hostport(
            self.userconf.dget(
                'dns', 'localdns',
                '8.8.8.8:53' if self.rproxy else '223.5.5.5:53'))
        self.remotedns = self.localdns if self.rproxy else parse_hostport(
            self.userconf.dget('dns', 'remotedns', '208.67.222.222:5353'))
        self.REDIRECTOR = redirector(self)
        self.PARENT_PROXY = get_proxy(self)
        self.resolver = resolver.get_resolver(
            self.localdns, self.remotedns,
            ParentProxy('self', 'http://127.0.0.1:%d' % self.listen[1]),
            self.PARENT_PROXY.force)
Example #13
0
def create_connection(netloc,
                      ctimeout=None,
                      source_address=None,
                      iplist=None,
                      parentproxy=None,
                      tunnel=False):
    if not isinstance(parentproxy, ParentProxy):
        logger.warning(
            'parentproxy is not a ParentProxy instance, please check.')
        if parentproxy is None:
            parentproxy = 'direct'
        parentproxy = ParentProxy(parentproxy, parentproxy)
    ctimeout = ctimeout or parentproxy.timeout
    via = parentproxy.get_via()
    s = None
    if not parentproxy.proxy:
        return _create_connection(netloc, ctimeout, iplist=iplist)
    elif parentproxy.scheme == 'http':
        s = create_connection((parentproxy.hostname, parentproxy.port or 80),
                              ctimeout,
                              source_address,
                              parentproxy=via,
                              tunnel=True)
        if tunnel:
            do_tunnel(s, netloc, parentproxy)
    elif parentproxy.scheme == 'ss':
        from sssocket import sssocket
        s = sssocket(parentproxy, ctimeout, via)
        s.connect(netloc)
    elif parentproxy.scheme == 'hxs':
        from hxsocks import hxssocket
        s = hxssocket(parentproxy, ctimeout, via)
        s.connect(netloc)
    elif parentproxy.scheme == 'socks5':
        s = create_connection((parentproxy.hostname, parentproxy.port or 1080),
                              ctimeout,
                              source_address,
                              parentproxy=via,
                              tunnel=True)
        s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        s.sendall(
            b"\x05\x02\x00\x02" if parentproxy.username else b"\x05\x01\x00")
        data = s.recv(2)
        if data == b'\x05\x02':  # basic auth
            s.sendall(b''.join([
                b"\x01",
                chr(len(parentproxy.username)).encode(),
                parentproxy.username.encode(),
                chr(len(parentproxy.password)).encode(),
                parentproxy.password.encode()
            ]))
            data = s.recv(2)
        assert data[1] == b'\x00'  # no auth needed or auth passed
        s.sendall(b''.join([
            b"\x05\x01\x00\x03",
            chr(len(netloc[0])).encode(), netloc[0].encode(),
            struct.pack(b">H", netloc[1])
        ]))
        data = s.recv(4)
        assert data[1] == b'\x00'
        if data[3] == b'\x01':  # read ipv4 addr
            s.recv(4)
        elif data[3] == b'\x03':  # read host addr
            s.recv(ord(s.recv(1)))
        elif data[3] == b'\x04':  # read ipv6 addr
            s.recv(16)
        s.recv(2)  # read port
        s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 0)
    else:
        raise IOError(0, 'parentproxy %s not supported!' % parentproxy.name)
    if s:
        return s
    raise IOError(0, 'create_connection failed!')
Example #14
0
    def __init__(self):
        self.logger = logging.getLogger('config')
        self.logger.setLevel(logging.INFO)
        hdr = logging.StreamHandler()
        formatter = logging.Formatter(
            '%(asctime)s %(name)s:%(levelname)s %(message)s',
            datefmt='%H:%M:%S')
        hdr.setFormatter(formatter)
        self.logger.addHandler(hdr)

        self.version = SConfigParser()
        self.userconf = SConfigParser()
        self.reload()
        self.UPDATE_INTV = 6
        self.timeout = self.userconf.dgetint('fgfwproxy', 'timeout', 3)
        ParentProxy.DEFAULT_TIMEOUT = self.timeout
        self.parentlist = ParentProxyList()
        self.HOSTS = defaultdict(list)
        self.GUI = '-GUI' in sys.argv
        self.rproxy = self.userconf.dgetbool('fgfwproxy', 'rproxy', False)

        listen = self.userconf.dget('fgfwproxy', 'listen', '8118')
        if listen.isdigit():
            self.listen = ('127.0.0.1', int(listen))
        else:
            self.listen = (listen.rsplit(':',
                                         1)[0], int(listen.rsplit(':', 1)[1]))

        try:
            csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            csock.connect(('8.8.8.8', 53))
            (addr, port) = csock.getsockname()
            csock.close()
            self.local_ip = addr
        except socket.error:
            self.local_ip = '127.0.0.1'

        ip = self.local_ip
        self.PAC = PAC.replace('__PROXY__',
                               'PROXY %s:%s' % (ip, self.listen[1]))
        if self.userconf.dget('fgfwproxy', 'pac', ''):
            if os.path.isfile(self.userconf.dget('fgfwproxy', 'pac', '')):
                self.PAC = open(self.userconf.dget('fgfwproxy', 'pac',
                                                   '')).read()

        self.PAC = self.PAC.encode()

        if self.userconf.dget('FGFW_Lite', 'logfile', ''):
            path = self.userconf.dget('FGFW_Lite', 'logfile', '')
            dirname = os.path.dirname(path)
            if dirname and not os.path.exists(dirname):
                os.makedirs(dirname)
            formatter = logging.Formatter(
                'FW-Lite %(asctime)s %(levelname)s %(message)s',
                datefmt='%Y-%m-%d %H:%M:%S')
            hdlr = logging.handlers.RotatingFileHandler(path,
                                                        maxBytes=1048576,
                                                        backupCount=5)
            hdlr.setFormatter(formatter)
            self.logger.addHandler(hdlr)

        self.region = set(
            x.upper()
            for x in self.userconf.dget('fgfwproxy', 'region', '').split('|')
            if x.strip())
        self.profile_num = len(self.userconf.dget('fgfwproxy', 'profile',
                                                  '13'))
        self.xheaders = self.userconf.dgetbool('fgfwproxy', 'xheaders', False)

        if self.userconf.dget('fgfwproxy', 'parentproxy', ''):
            self.addparentproxy(
                'direct',
                '%s 0' % self.userconf.dget('fgfwproxy', 'parentproxy', ''))
            self.addparentproxy('local', 'direct 100')
        else:
            self.addparentproxy('direct', 'direct 0')

        ParentProxy.set_via(self.parentlist.direct)

        for k, v in self.userconf.items('parents'):
            if '6Rc59g0jFlTppvel' in v:
                self.userconf.remove_option('parents', k)
                self.confsave()
                continue
            self.addparentproxy(k, v)

        if not self.rproxy and len([
                k for k in self.parentlist.httpsparents()
                if k.httpspriority < 100
        ]) == 0:
            self.logger.warning('No parent proxy available!')

        self.maxretry = self.userconf.dgetint('fgfwproxy', 'maxretry', 4)

        def addhost(host, ip):
            try:
                ipo = ip_address(ip)
                if isinstance(ipo, IPv4Address):
                    self.HOSTS[host].append((2, ip))
                else:
                    self.HOSTS[host].append((10, ip))
            except Exception:
                self.logger.warning('unsupported host: %s' % ip)
                sys.stderr.write(traceback.format_exc() + '\n')
                sys.stderr.flush()

        for host, ip in self.userconf.items('hosts'):
            addhost(host, ip)

        if os.path.isfile('./fgfw-lite/hosts'):
            for line in open('./fgfw-lite/hosts'):
                line = line.strip()
                if line and not line.startswith('#'):
                    try:
                        ip, host = line.split()
                        addhost(host, ip)
                    except Exception as e:
                        self.logger.warning('%s %s' % (e, line))

        localdns = self.userconf.dget('dns', 'localdns', '')
        # get local dns setting from system
        if not localdns:
            if sys.platform.startswith('win'):
                import subprocess
                localdns = subprocess.check_output(
                    ['nslookup',
                     '127.0.0.1']).splitlines()[1].split()[1].decode()
            elif sys.platform == 'linux2':
                lst = []
                with open('/etc/resolv.conf') as f:
                    for line in f:
                        if line.startswith('nameserver'):
                            lst.append(line.split()[1])
                localdns = '|'.join(lst)
            else:
                localdns = '119.29.29.29'
        self.logger.info('localdns: ' + localdns)
        self.localdns = [
            parse_hostport(dns, 53) for dns in localdns.split('|')
        ]
        remotedns = localdns if self.rproxy else self.userconf.dget(
            'dns', 'remotedns', '8.8.8.8')
        self.logger.info('remotedns: ' + remotedns)
        self.remotedns = [
            parse_hostport(dns, 53) for dns in remotedns.split('|')
        ]

        self.REDIRECTOR = redirector(self)
        self.GET_PROXY = get_proxy(self)
        bad_ip = set(self.userconf.dget('dns', 'bad_ip', '').split('|'))
        self.resolver = resolver.get_resolver(
            self.localdns,
            self.remotedns,
            proxy=ParentProxy('self', 'http://127.0.0.1:%d' % self.listen[1]),
            apfilter=[self.GET_PROXY.gfwlist, self.GET_PROXY.local],
            bad_ip=bad_ip)
Example #15
0
 def __init__(self, proxy, target, server_address):
     self.proxy = ParentProxy('', proxy)
     self.target = target
     self.addr = server_address
     logger.info('starting tcp forward from %s(local) to %s(remote) via %s' % (server_address, target, self.proxy))
     ThreadingTCPServer.__init__(self, server_address, tcp_tunnel_handler)