Exemple #1
0
def make_socks5(loop,
                *,
                addr=None,
                auth=None,
                rr=True,
                dst=None,
                r=None,
                ap_factory=None,
                whiter=None):
    addr = addr or aiosocks.Socks5Addr('localhost', 1080)
    auth = auth or aiosocks.Socks5Auth('user', 'pwd')
    dst = dst or ('python.org', 80)

    proto = aiosocks.Socks5Protocol(proxy=addr,
                                    proxy_auth=auth,
                                    dst=dst,
                                    remote_resolve=rr,
                                    loop=loop,
                                    app_protocol_factory=ap_factory,
                                    waiter=whiter)
    proto._stream_writer = mock.Mock()
    proto._stream_writer.drain = make_mocked_coro(True)

    if not isinstance(r, (list, tuple)):
        proto.read_response = mock.Mock(
            side_effect=coro(mock.Mock(return_value=r)))
    else:
        proto.read_response = mock.Mock(
            side_effect=coro(mock.Mock(side_effect=r)))

    proto._get_dst_addr = mock.Mock(
        side_effect=coro(mock.Mock(return_value=(socket.AF_INET,
                                                 '127.0.0.1'))))
    return proto
Exemple #2
0
async def load_github_main():
    auth5 = aiosocks.Socks5Auth("proxyuser1", password="******")
    ba = aiohttp.BasicAuth("login")

    # remote resolve
    conn = ProxyConnector(remote_resolve=True)

    # or locale resolve
    conn = ProxyConnector(remote_resolve=False)

    try:
        with aiohttp.ClientSession(connector=conn, request_class=ProxyClientRequest) as session:
            # socks5 proxy
            async with session.get(
                "http://github.com/", proxy="socks5://127.0.0.1:1080", proxy_auth=auth5
            ) as resp:
                if resp.status == 200:
                    print(await resp.text())
            # http proxy
            async with session.get(
                "http://github.com/", proxy="http://127.0.0.1:8080", proxy_auth=ba
            ) as resp:
                if resp.status == 200:
                    print(await resp.text())
    except aiohttp.ClientProxyConnectionError:
        # connection problem
        print("communication problem")
    except aiohttp.ClientConnectorError:
        # ssl error, certificate error, etc
        print("ssl error, certificate error, etc")
    except aiosocks.SocksError:
        # communication problem
        print("communication problem")
Exemple #3
0
    def test_init(self):
        addr = aiosocks.Socks5Addr('localhost')
        auth = aiosocks.Socks5Auth('usr', 'pwd')
        dst = ('python.org', 80)

        # proxy argument
        with self.assertRaises(AssertionError) as ct:
            conn = aiosocks.create_connection(None, None, auth, dst)
            self.loop.run_until_complete(conn)
        self.assertEqual(str(ct.exception),
                         'proxy must be Socks4Addr() or Socks5Addr() tuple')

        with self.assertRaises(AssertionError) as ct:
            conn = aiosocks.create_connection(None, auth, auth, dst)
            self.loop.run_until_complete(conn)
        self.assertEqual(str(ct.exception),
                         'proxy must be Socks4Addr() or Socks5Addr() tuple')

        # proxy_auth
        with self.assertRaises(AssertionError) as ct:
            conn = aiosocks.create_connection(None, addr, addr, dst)
            self.loop.run_until_complete(conn)
        self.assertIn('proxy_auth must be None or Socks4Auth()',
                      str(ct.exception))

        # dst
        with self.assertRaises(AssertionError) as ct:
            conn = aiosocks.create_connection(None, addr, auth, None)
            self.loop.run_until_complete(conn)
        self.assertIn('invalid dst format, tuple("dst_host", dst_port))',
                      str(ct.exception))

        # addr and auth compatibility
        with self.assertRaises(ValueError) as ct:
            conn = aiosocks.create_connection(None, addr,
                                              aiosocks.Socks4Auth(''), dst)
            self.loop.run_until_complete(conn)
        self.assertIn('proxy is Socks5Addr but proxy_auth is not Socks5Auth',
                      str(ct.exception))

        with self.assertRaises(ValueError) as ct:
            conn = aiosocks.create_connection(None, aiosocks.Socks4Addr(''),
                                              auth, dst)
            self.loop.run_until_complete(conn)
        self.assertIn('proxy is Socks4Addr but proxy_auth is not Socks4Auth',
                      str(ct.exception))

        # test ssl, server_hostname
        with self.assertRaises(ValueError) as ct:
            conn = aiosocks.create_connection(None,
                                              addr,
                                              auth,
                                              dst,
                                              server_hostname='python.org')
            self.loop.run_until_complete(conn)
        self.assertIn('server_hostname is only meaningful with ssl',
                      str(ct.exception))
Exemple #4
0
async def test_socks5_auth_ver_err(loop):
    async with FakeSocksSrv(loop, b'\x04\x02') as srv:
        addr = aiosocks.Socks5Addr('127.0.0.1', srv.port)
        auth = aiosocks.Socks5Auth('usr', 'pwd')
        dst = ('python.org', 80)

        with pytest.raises(aiosocks.SocksError) as ct:
            await aiosocks.create_connection(None, addr, auth, dst, loop=loop)
        assert 'invalid version' in str(ct.value)
Exemple #5
0
async def test_socks5_auth_failed(loop):
    async with FakeSocksSrv(loop, b'\x05\x02\x01\x01') as srv:
        addr = aiosocks.Socks5Addr('127.0.0.1', srv.port)
        auth = aiosocks.Socks5Auth('usr', 'pwd')
        dst = ('python.org', 80)

        with pytest.raises(aiosocks.SocksError) as ct:
            await aiosocks.create_connection(None, addr, auth, dst, loop=loop)
        assert 'authentication failed' in str(ct.value)
Exemple #6
0
async def test_socks5_cmd_not_granted(loop):
    async with FakeSocksSrv(loop, b'\x05\x02\x01\x00\x05\x01\x00') as srv:
        addr = aiosocks.Socks5Addr('127.0.0.1', srv.port)
        auth = aiosocks.Socks5Auth('usr', 'pwd')
        dst = ('python.org', 80)

        with pytest.raises(aiosocks.SocksError) as ct:
            await aiosocks.create_connection(None, addr, auth, dst, loop=loop)
        assert 'General SOCKS server failure' in str(ct.value)
Exemple #7
0
async def test_socks5_invalid_address_type(loop):
    async with FakeSocksSrv(loop, b'\x05\x02\x01\x00\x05\x00\x00\xFF') as srv:
        addr = aiosocks.Socks5Addr('127.0.0.1', srv.port)
        auth = aiosocks.Socks5Auth('usr', 'pwd')
        dst = ('python.org', 80)

        with pytest.raises(aiosocks.SocksError) as ct:
            await aiosocks.create_connection(None, addr, auth, dst, loop=loop)
        assert 'invalid data' in str(ct.value)
async def test_connection_fail():
    addr = aiosocks.Socks5Addr('localhost')
    auth = aiosocks.Socks5Auth('usr', 'pwd')
    dst = ('python.org', 80)

    loop_mock = mock.Mock()
    loop_mock.create_connection = make_mocked_coro(raise_exception=OSError())

    with pytest.raises(aiosocks.SocksConnectionError):
        await aiosocks.create_connection(None, addr, auth, dst, loop=loop_mock)
Exemple #9
0
async def test_socks5_atype_domain(loop):
    pld = b'\x05\x02\x01\x00\x05\x00\x00\x03\x0apython.org\x04W'

    async with FakeSocksSrv(loop, pld) as srv:
        addr = aiosocks.Socks5Addr('127.0.0.1', srv.port)
        auth = aiosocks.Socks5Auth('usr', 'pwd')
        dst = ('python.org', 80)

        transport, protocol = await aiosocks.create_connection(
            None, addr, auth, dst, loop=loop)
        assert protocol.proxy_sockname == (b'python.org', 1111)

        transport.close()
Exemple #10
0
    def test_auth_failed(self):
        with fake_socks_srv(self.loop, b'\x05\x02\x01\x01') as port:
            addr = aiosocks.Socks5Addr('127.0.0.1', port)
            auth = aiosocks.Socks5Auth('usr', 'pwd')
            dst = ('python.org', 80)

            with self.assertRaises(aiosocks.SocksError) as ct:
                coro = aiosocks.create_connection(None,
                                                  addr,
                                                  auth,
                                                  dst,
                                                  loop=self.loop)
                self.loop.run_until_complete(coro)
            self.assertIn('authentication failed', str(ct.exception))
Exemple #11
0
    def test_init(self):
        addr = aiosocks.Socks5Addr('localhost', 1080)
        auth = aiosocks.Socks5Auth('user', 'pwd')
        dst = ('python.org', 80)

        with self.assertRaises(ValueError):
            aiosocks.Socks5Protocol(None,
                                    None,
                                    dst,
                                    loop=self.loop,
                                    waiter=None,
                                    app_protocol_factory=None)

        with self.assertRaises(ValueError):
            aiosocks.Socks5Protocol(None,
                                    auth,
                                    dst,
                                    loop=self.loop,
                                    waiter=None,
                                    app_protocol_factory=None)

        with self.assertRaises(ValueError):
            aiosocks.Socks5Protocol(aiosocks.Socks4Addr('host'),
                                    auth,
                                    dst,
                                    loop=self.loop,
                                    waiter=None,
                                    app_protocol_factory=None)

        with self.assertRaises(ValueError):
            aiosocks.Socks5Protocol(addr,
                                    aiosocks.Socks4Auth('l'),
                                    dst,
                                    loop=self.loop,
                                    waiter=None,
                                    app_protocol_factory=None)

        aiosocks.Socks5Protocol(addr,
                                None,
                                dst,
                                loop=self.loop,
                                waiter=None,
                                app_protocol_factory=None)
        aiosocks.Socks5Protocol(addr,
                                auth,
                                dst,
                                loop=self.loop,
                                waiter=None,
                                app_protocol_factory=None)
Exemple #12
0
def test_socks4_ctor(loop):
    addr = aiosocks.Socks4Addr('localhost', 1080)
    auth = aiosocks.Socks4Auth('user')
    dst = ('python.org', 80)

    with pytest.raises(ValueError):
        aiosocks.Socks4Protocol(None,
                                None,
                                dst,
                                loop=loop,
                                waiter=None,
                                app_protocol_factory=None)

    with pytest.raises(ValueError):
        aiosocks.Socks4Protocol(None,
                                auth,
                                dst,
                                loop=loop,
                                waiter=None,
                                app_protocol_factory=None)

    with pytest.raises(ValueError):
        aiosocks.Socks4Protocol(aiosocks.Socks5Addr('host'),
                                auth,
                                dst,
                                loop=loop,
                                waiter=None,
                                app_protocol_factory=None)

    with pytest.raises(ValueError):
        aiosocks.Socks4Protocol(addr,
                                aiosocks.Socks5Auth('l', 'p'),
                                dst,
                                loop=loop,
                                waiter=None,
                                app_protocol_factory=None)

    aiosocks.Socks4Protocol(addr,
                            None,
                            dst,
                            loop=loop,
                            waiter=None,
                            app_protocol_factory=None)
    aiosocks.Socks4Protocol(addr,
                            auth,
                            dst,
                            loop=loop,
                            waiter=None,
                            app_protocol_factory=None)
Exemple #13
0
async def test_socks5_connect_success_usr_pwd(loop):
    pld = b'\x05\x02\x01\x00\x05\x00\x00\x01\x01\x01\x01\x01\x04Wtest'

    async with FakeSocksSrv(loop, pld) as srv:
        addr = aiosocks.Socks5Addr('127.0.0.1', srv.port)
        auth = aiosocks.Socks5Auth('usr', 'pwd')
        dst = ('python.org', 80)

        transport, protocol = await aiosocks.create_connection(
            None, addr, auth, dst, loop=loop)
        assert protocol.proxy_sockname == ('1.1.1.1', 1111)

        data = await protocol._stream_reader.read(4)
        assert data == b'test'
        transport.close()
Exemple #14
0
    def test_connection_fail(self):
        addr = aiosocks.Socks5Addr('localhost')
        auth = aiosocks.Socks5Auth('usr', 'pwd')
        dst = ('python.org', 80)

        loop_mock = mock.Mock()
        loop_mock.create_connection = fake_coroutine(OSError())

        with self.assertRaises(aiosocks.SocksConnectionError):
            conn = aiosocks.create_connection(None,
                                              addr,
                                              auth,
                                              dst,
                                              loop=loop_mock)
            self.loop.run_until_complete(conn)
Exemple #15
0
    def test_cmd_not_granted(self):
        with fake_socks_srv(self.loop,
                            b'\x05\x02\x01\x00\x05\x01\x00') as port:
            addr = aiosocks.Socks5Addr('127.0.0.1', port)
            auth = aiosocks.Socks5Auth('usr', 'pwd')
            dst = ('python.org', 80)

            with self.assertRaises(aiosocks.SocksError) as ct:
                coro = aiosocks.create_connection(None,
                                                  addr,
                                                  auth,
                                                  dst,
                                                  loop=self.loop)
                self.loop.run_until_complete(coro)
            self.assertIn('General SOCKS server failure', str(ct.exception))
Exemple #16
0
 def __init__(self,
              address,
              port,
              login=None,
              password=None,
              timeout=10,
              loop=None):
     super().__init__(timeout)
     self.close()
     addr = aiosocks.Socks5Addr(address, port)
     if login and password:
         auth = aiosocks.Socks5Auth(login, password=password)
     else:
         auth = None
     conn = self.connector(proxy=addr, proxy_auth=auth, loop=loop)
     self.session = aiohttp.ClientSession(connector=conn)
Exemple #17
0
async def test_create_connection_init():
    addr = aiosocks.Socks5Addr('localhost')
    auth = aiosocks.Socks5Auth('usr', 'pwd')
    dst = ('python.org', 80)

    # proxy argument
    with pytest.raises(AssertionError) as ct:
        await aiosocks.create_connection(None, None, auth, dst)
    assert 'proxy must be Socks4Addr() or Socks5Addr() tuple' in str(ct.value)

    with pytest.raises(AssertionError) as ct:
        await aiosocks.create_connection(None, auth, auth, dst)
    assert 'proxy must be Socks4Addr() or Socks5Addr() tuple' in str(ct.value)

    # proxy_auth
    with pytest.raises(AssertionError) as ct:
        await aiosocks.create_connection(None, addr, addr, dst)
    assert 'proxy_auth must be None or Socks4Auth()' in str(ct.value)

    # dst
    with pytest.raises(AssertionError) as ct:
        await aiosocks.create_connection(None, addr, auth, None)
    assert 'invalid dst format, tuple("dst_host", dst_port))' in str(ct.value)

    # addr and auth compatibility
    with pytest.raises(ValueError) as ct:
        await aiosocks.create_connection(None, addr, aiosocks.Socks4Auth(''),
                                         dst)
    assert 'proxy is Socks5Addr but proxy_auth is not Socks5Auth' \
           in str(ct.value)

    with pytest.raises(ValueError) as ct:
        await aiosocks.create_connection(None, aiosocks.Socks4Addr(''), auth,
                                         dst)
    assert 'proxy is Socks4Addr but proxy_auth is not Socks4Auth' \
           in str(ct.value)

    # test ssl, server_hostname
    with pytest.raises(ValueError) as ct:
        await aiosocks.create_connection(None,
                                         addr,
                                         auth,
                                         dst,
                                         server_hostname='python.org')
    assert 'server_hostname is only meaningful with ssl' in str(ct.value)
async def test_negotiate_fail():
    addr = aiosocks.Socks5Addr('localhost')
    auth = aiosocks.Socks5Auth('usr', 'pwd')
    dst = ('python.org', 80)

    loop_mock = mock.Mock()
    loop_mock.create_connection = make_mocked_coro((mock.Mock(), mock.Mock()))

    with mock.patch('aiosocks.asyncio.Future') as future_mock:
        future_mock.side_effect = make_mocked_coro(
            raise_exception=aiosocks.SocksError())

        with pytest.raises(aiosocks.SocksError):
            await aiosocks.create_connection(None,
                                             addr,
                                             auth,
                                             dst,
                                             loop=loop_mock)
Exemple #19
0
 async def proxy_request(self, url, **kwargs):
     post = kwargs.get('post')
     post = True if post != {} else False
     post_data = kwargs.get('post_data')
     headers = kwargs.get('headers')
     j = kwargs.get('j')
     j = True if j != {} else False
     proxy_addr = aiosocks.Socks5Addr('', 1080)
     proxy_auth = aiosocks.Socks5Auth('', password='')
     proxy_connection = aiosocks.connector.SocksConnector(
         proxy=proxy_addr, proxy_auth=proxy_auth, remote_resolve=True)
     with aiohttp.ClientSession(connector=proxy_connection) as session:
         async with session.post(url,
                                 data=post_data if post else None,
                                 headers=headers) as resp:
             if j:
                 return await resp.json()
             else:
                 return await resp.text()
async def test_open_connection():
    addr = aiosocks.Socks5Addr('localhost')
    auth = aiosocks.Socks5Auth('usr', 'pwd')
    dst = ('python.org', 80)

    transp, proto = mock.Mock(), mock.Mock()
    reader, writer = mock.Mock(), mock.Mock()

    proto.app_protocol.reader, proto.app_protocol.writer = reader, writer

    loop_mock = mock.Mock()
    loop_mock.create_connection = make_mocked_coro((transp, proto))

    with mock.patch('aiosocks.asyncio.Future') as future_mock:
        future_mock.side_effect = make_mocked_coro(True)
        r, w = await aiosocks.open_connection(addr, auth, dst, loop=loop_mock)

    assert reader is r
    assert writer is w
Exemple #21
0
    def test_negotiate_fail(self, future_mock):
        addr = aiosocks.Socks5Addr('localhost')
        auth = aiosocks.Socks5Auth('usr', 'pwd')
        dst = ('python.org', 80)

        loop_mock = mock.Mock()
        loop_mock.create_connection = fake_coroutine(
            (mock.Mock(), mock.Mock()))

        fut = fake_coroutine(aiosocks.SocksError())
        future_mock.side_effect = fut.side_effect

        with self.assertRaises(aiosocks.SocksError):
            conn = aiosocks.create_connection(None,
                                              addr,
                                              auth,
                                              dst,
                                              loop=loop_mock)
            self.loop.run_until_complete(conn)
Exemple #22
0
    def test_atype_domain(self):
        with fake_socks_srv(
                self.loop,
                b'\x05\x02\x01\x00\x05\x00\x00\x03\x0apython.org\x04W'
        ) as port:
            addr = aiosocks.Socks5Addr('127.0.0.1', port)
            auth = aiosocks.Socks5Auth('usr', 'pwd')
            dst = ('python.org', 80)

            coro = aiosocks.create_connection(None,
                                              addr,
                                              auth,
                                              dst,
                                              loop=self.loop)
            transport, protocol = self.loop.run_until_complete(coro)

            self.assertEqual(protocol.proxy_sockname, (b'python.org', 1111))

            transport.close()
Exemple #23
0
    def test_open_connection(self, future_mock):
        addr = aiosocks.Socks5Addr('localhost')
        auth = aiosocks.Socks5Auth('usr', 'pwd')
        dst = ('python.org', 80)

        transp, proto = mock.Mock(), mock.Mock()
        reader, writer = mock.Mock(), mock.Mock()

        proto.app_protocol.reader, proto.app_protocol.writer = reader, writer

        loop_mock = mock.Mock()
        loop_mock.create_connection = fake_coroutine((transp, proto))

        fut = fake_coroutine(True)
        future_mock.side_effect = fut.side_effect

        conn = aiosocks.open_connection(addr, auth, dst, loop=loop_mock)
        r, w = self.loop.run_until_complete(conn)

        self.assertIs(reader, r)
        self.assertIs(writer, w)
Exemple #24
0
    def test_connect_success_anonymous(self):
        with fake_socks_srv(
                self.loop,
                b'\x05\x00\x05\x00\x00\x01\x01\x01\x01\x01\x04Wtest') as port:
            addr = aiosocks.Socks5Addr('127.0.0.1', port)
            auth = aiosocks.Socks5Auth('usr', 'pwd')
            dst = ('python.org', 80)

            coro = aiosocks.create_connection(None,
                                              addr,
                                              auth,
                                              dst,
                                              loop=self.loop)
            transport, protocol = self.loop.run_until_complete(coro)

            self.assertEqual(protocol.proxy_sockname, ('1.1.1.1', 1111))

            data = self.loop.run_until_complete(
                protocol._stream_reader.read(4))
            self.assertEqual(data, b'test')

            transport.close()
Exemple #25
0
def proxied_connection(dst,
                       proxy_type=None,
                       addr=None,
                       port=None,
                       rdns=True,
                       username=None,
                       password=None):
    if proxy_type == 'SOCKS4':
        socks4_addr = aiosocks.Socks4Addr(addr, port)
        socks4_auth = aiosocks.Socks4Auth(username)
        return aiosocks.open_connection(socks4_addr,
                                        socks4_auth,
                                        dst,
                                        remote_resolve=rdns)
    elif proxy_type == 'SOCKS5':
        socks5_addr = aiosocks.Socks5Addr(addr, port)
        socks5_auth = aiosocks.Socks5Auth(username, password)
        return aiosocks.open_connection(socks5_addr,
                                        socks5_auth,
                                        dst,
                                        remote_resolve=rdns)
    else:
        return asyncio.open_connection(*dst)
Exemple #26
0
def test_socks5_auth1():
    with pytest.raises(ValueError):
        aiosocks.Socks5Auth(None, '')
Exemple #27
0
def test_socks5_auth2():
    with pytest.raises(ValueError):
        aiosocks.Socks5Auth('', None)
Exemple #28
0
def test_socks5_auth4():
    auth = aiosocks.Socks5Auth('usrё', 'pwdё', encoding='utf-8')
    assert auth.login == b'usr\xd1\x91'
    assert auth.password == b'pwd\xd1\x91'
Exemple #29
0
def test_socks5_auth3():
    auth = aiosocks.Socks5Auth('usr', 'pwd', encoding='ascii')
    assert auth.login == b'usr'
    assert auth.password == b'pwd'