Пример #1
0
async def command(ctx, remote, vmid):
    loop = ctx.obj['loop']
    config = ctx.obj['config']
    try:
        async with RemoteConnection(loop, config, remote) as conn:
            resource = await get_vmid_resource(conn, remote, vmid)
            if not resource:
                return 1

            termproxy = await resource.termproxy.post()
            path_vncwebsocket = resource.vncwebsocket.path

            websocket_url = URL(
                conn.url).with_path(path_vncwebsocket).with_query({
                    "port":
                    termproxy['port'],
                    "vncticket":
                    termproxy['ticket'],
                })

            if sys.stdin.isatty():
                print('Connecting: %s' % path_vncwebsocket)

            async with conn.session.ws_connect(str(websocket_url),
                                               ssl=aiohttp.Fingerprint(
                                                   conn.binary_fingerprint),
                                               protocols=('binary', )) as ws:
                await WSTerminal(loop, ws, termproxy['user'],
                                 termproxy['ticket']).run()

    except HTTPException as e:
        logging.fatal("HTTP Error: %s", e)
        return 1
Пример #2
0
    async def request(self, method, path, **params):
        url = self._url + path

        data = aiohttp.FormData()
        for k, v in params.items():
            data.add_field(k, v)

        try:
            logging.debug('%s: %s', method, url)
            resp = await self._session.request(method,
                                               url,
                                               data=data,
                                               ssl=aiohttp.Fingerprint(
                                                   self._fingerprint))
            if int(resp.status / 100) != 2:
                raise HTTPException(url, resp.status, resp.reason)
        except aiohttp.client_exceptions.ClientConnectorError as e:
            raise ConnectionException(e)

        return await resp.json()
Пример #3
0
    async def _make_connection(self):
        headers = {}
        cookies = {}
        if self._ticket is not None:
            cookies['PVEAuthCookie'] = urllib.parse.quote_plus(self._ticket)
        if self._csrftoken is not None:
            headers['CSRFPreventionToken'] = self._csrftoken

        try:
            self._session = await aiohttp.ClientSession(
                headers=headers,
                cookies=cookies,
                conn_timeout=self.timeout,
            ).__aenter__()
        except aiohttp.client_exceptions.ClientConnectorError as e:
            raise ConnectionException(e)

        # User supplied a fingerprint use that.
        if self.fingerprint is not None:
            return

        # Get the fingerprint from the remote and verify that.
        bad_fp = b'0' * 32
        exc = None
        try:
            await self._session.get(self._url, ssl=aiohttp.Fingerprint(bad_fp))
        except aiohttp.ServerFingerprintMismatch as e:
            exc = e
        except aiohttp.client_exceptions.ClientConnectorError as e:
            raise ConnectionException(e)

        if exc is not None:
            hex_fp = _binary_fp_to_hex(exc.got)
            if not self._verify_cb(self._host, exc.got, hex_fp):
                # Close the session
                await self._close_connection()

                raise VerifyException("Failed to verify: %s" % hex_fp)

            self._fingerprint = exc.got
Пример #4
0
async def execute(loop, config, args):
    try:
        async with RemoteConnection(loop, config, args['remote_vmid']) as conn:
            resource = await get_vmid_resource('lxc', conn, args['remote_vmid'])
            if not resource:
                return 1

            termproxy = await resource.termproxy.post()
            path_vncwebsocket = resource.vncwebsocket.path

            websocket_url = URL(conn.url).with_path(path_vncwebsocket).with_query({
                "port": termproxy['port'],
                "vncticket": termproxy['ticket'],
            })

            print('Connecting: %s' % path_vncwebsocket)
            async with conn.session.ws_connect(str(websocket_url), ssl=aiohttp.Fingerprint(conn.binary_fingerprint), protocols=('binary',)) as ws:
                await WSTerminal(loop, ws, termproxy['user'], termproxy['ticket']).run()

    except HTTPException as e:
        logging.fatal("HTTP Error: %s", e)
        return 1
Пример #5
0
    async def login(self, username, password=None, ticket=None):
        if password is None and ticket is None:
            raise ValueError('You need to give either a password or a cookie')

        assert self._session

        url = self._url + '/api2/json/access/ticket'

        data = aiohttp.FormData()
        data.add_field("username", username)
        data.add_field("password", password)
        resp = await self._session.post(url,
                                        data=data,
                                        ssl=aiohttp.Fingerprint(
                                            self._fingerprint))
        if int(resp.status / 100) != 2:
            raise AuthenticationException(url, resp.status, resp.reason)

        json = await resp.json()
        result = json['data']

        self._caps = result['cap']
        self._csrftoken = result['CSRFPreventionToken']
        await self.update_ticket(result['ticket'])
Пример #6
0
def test__merge_ssl_params_fingerprint_conflict():
    fingerprint = aiohttp.Fingerprint(hashlib.sha256(b'123').digest())
    ctx = ssl.SSLContext()
    with pytest.warns(DeprecationWarning):
        with pytest.raises(ValueError):
            _merge_ssl_params(ctx, None, None, fingerprint)
Пример #7
0
def test_fingerprint_check_no_ssl():
    sha256 = hashlib.sha256(b'12345678' * 64).digest()
    fp = aiohttp.Fingerprint(sha256)
    transport = mock.Mock()
    transport.get_extra_info.return_value = None
    assert fp.check(transport) is None
Пример #8
0
def test_fingerprint_md5():
    md5 = hashlib.md5(b'12345678' * 64).digest()
    with pytest.raises(ValueError):
        aiohttp.Fingerprint(md5)
Пример #9
0
def test_fingerprint_sha1():
    sha1 = hashlib.sha1(b'12345678' * 64).digest()
    with pytest.raises(ValueError):
        aiohttp.Fingerprint(sha1)
Пример #10
0
def test_fingerprint_sha256():
    sha256 = hashlib.sha256(b'12345678' * 64).digest()
    fp = aiohttp.Fingerprint(sha256)
    assert fp.fingerprint == sha256
Пример #11
0
'''
PING_TARGET = os.environ.get('PING_TARGET', '1.1.1.1')
PING_COUNT = int(os.environ.get('PING_COUNT', 3))
PING_SIZE = int(os.environ.get('PING_SIZE', 50))
PING_INTERVAL = int(os.environ.get('PING_INTERVAL', 120))

import warnings
warnings.simplefilter("ignore")
import aiohttp

from binascii import a2b_hex, b2a_hex

ssl_check = True
if isinstance(ROUTER_SSL, str) and len(ROUTER_SSL) == 64:
    # presume this is a fingerprint
    ssl_check = aiohttp.Fingerprint(a2b_hex(ROUTER_SSL))
elif ROUTER_SSL in ['no', 'false']:
    ssl_check = False
elif ROUTER_SSL in ['yes', 'true']:
    ssl_check = True
else:
    raise Exception(f"ROUTER_SSL {ROUTER_SSL} is invalid")

influx_auth = {}
if INFLUX_USERNAME or INFLUX_PASSWORD:
    influx_auth.update({
        'username': INFLUX_USERNAME,
        'password': INFLUX_PASSWORD,
    })

from aioedgeos import *
Пример #12
0
class TestProxy(unittest.TestCase):
    fingerprint = aiohttp.Fingerprint(hashlib.sha256(b"foo").digest())
    response_mock_attrs = {
        'status': 200,
    }
    mocked_response = mock.Mock(**response_mock_attrs)
    clientrequest_mock_attrs = {
        'return_value._hashfunc.return_value.digest.return_value': fingerprint,
        'return_value.fingerprint': fingerprint,
        'return_value.send.return_value.start':
        make_mocked_coro(mocked_response),
    }

    def setUp(self):
        self.loop = asyncio.new_event_loop()
        asyncio.set_event_loop(None)

    def tearDown(self):
        # just in case if we have transport close callbacks
        self.loop.stop()
        self.loop.run_forever()
        self.loop.close()
        gc.collect()

    @mock.patch('aiohttp.connector.ClientRequest')
    def test_connect(self, ClientRequestMock):
        req = ClientRequest('GET',
                            URL('http://www.python.org'),
                            proxy=URL('http://proxy.example.com'),
                            loop=self.loop)
        self.assertEqual(str(req.proxy), 'http://proxy.example.com')

        # mock all the things!
        connector = aiohttp.TCPConnector(loop=self.loop)
        connector._resolve_host = make_mocked_coro([mock.MagicMock()])

        proto = mock.Mock(**{
            'transport.get_extra_info.return_value': False,
        })
        self.loop.create_connection = make_mocked_coro(
            (proto.transport, proto))
        conn = self.loop.run_until_complete(connector.connect(req))
        self.assertEqual(req.url, URL('http://www.python.org'))
        self.assertIs(conn._protocol, proto)
        self.assertIs(conn.transport, proto.transport)

        ClientRequestMock.assert_called_with(
            'GET',
            URL('http://proxy.example.com'),
            auth=None,
            headers={'Host': 'www.python.org'},
            loop=self.loop,
            ssl=None)

    @mock.patch('aiohttp.connector.ClientRequest')
    def test_proxy_headers(self, ClientRequestMock):
        req = ClientRequest('GET',
                            URL('http://www.python.org'),
                            proxy=URL('http://proxy.example.com'),
                            proxy_headers={'Foo': 'Bar'},
                            loop=self.loop)
        self.assertEqual(str(req.proxy), 'http://proxy.example.com')

        # mock all the things!
        connector = aiohttp.TCPConnector(loop=self.loop)
        connector._resolve_host = make_mocked_coro([mock.MagicMock()])

        proto = mock.Mock(**{
            'transport.get_extra_info.return_value': False,
        })
        self.loop.create_connection = make_mocked_coro(
            (proto.transport, proto))
        conn = self.loop.run_until_complete(connector.connect(req))
        self.assertEqual(req.url, URL('http://www.python.org'))
        self.assertIs(conn._protocol, proto)
        self.assertIs(conn.transport, proto.transport)

        ClientRequestMock.assert_called_with('GET',
                                             URL('http://proxy.example.com'),
                                             auth=None,
                                             headers={
                                                 'Host': 'www.python.org',
                                                 'Foo': 'Bar'
                                             },
                                             loop=self.loop,
                                             ssl=None)

    @mock.patch('aiohttp.connector.ClientRequest', **clientrequest_mock_attrs)
    def test_connect_req_verify_ssl_true(self, ClientRequestMock):
        req = ClientRequest(
            'GET',
            URL('https://www.python.org'),
            proxy=URL('http://proxy.example.com'),
            loop=self.loop,
            ssl=True,
        )

        proto = mock.Mock()
        connector = aiohttp.TCPConnector(loop=self.loop)
        connector._create_proxy_connection = mock.MagicMock(
            side_effect=connector._create_proxy_connection)
        connector._create_direct_connection = mock.MagicMock(
            side_effect=connector._create_direct_connection)
        connector._resolve_host = make_mocked_coro([mock.MagicMock()])

        self.loop.create_connection = make_mocked_coro(
            (proto.transport, proto))
        self.loop.run_until_complete(connector.connect(req))

        connector._create_proxy_connection.assert_called_with(req, traces=None)
        ((proxy_req, ), _) = connector._create_direct_connection.call_args
        proxy_req.send.assert_called_with(mock.ANY)

    @mock.patch('aiohttp.connector.ClientRequest', **clientrequest_mock_attrs)
    def test_connect_req_verify_ssl_false(self, ClientRequestMock):
        req = ClientRequest(
            'GET',
            URL('https://www.python.org'),
            proxy=URL('http://proxy.example.com'),
            loop=self.loop,
            ssl=False,
        )

        proto = mock.Mock()
        connector = aiohttp.TCPConnector(loop=self.loop)
        connector._create_proxy_connection = mock.MagicMock(
            side_effect=connector._create_proxy_connection)
        connector._create_direct_connection = mock.MagicMock(
            side_effect=connector._create_direct_connection)
        connector._resolve_host = make_mocked_coro([mock.MagicMock()])

        self.loop.create_connection = make_mocked_coro(
            (proto.transport, proto))
        self.loop.run_until_complete(connector.connect(req))

        connector._create_proxy_connection.assert_called_with(req, traces=None)
        ((proxy_req, ), _) = connector._create_direct_connection.call_args
        proxy_req.send.assert_called_with(mock.ANY)

    def test_proxy_auth(self):
        with self.assertRaises(ValueError) as ctx:
            ClientRequest('GET',
                          URL('http://python.org'),
                          proxy=URL('http://proxy.example.com'),
                          proxy_auth=('user', 'pass'),
                          loop=mock.Mock())
        self.assertEqual(
            ctx.exception.args[0],
            "proxy_auth must be None or BasicAuth() tuple",
        )

    @mock.patch('aiohttp.client_reqrep.StreamWriter')
    def _test_connect_request_with_unicode_host(self, Request_mock):
        loop = mock.Mock()
        request = ClientRequest("CONNECT", URL("http://éé.com/"), loop=loop)

        request.response_class = mock.Mock()
        request.write_bytes = mock.Mock()
        request.write_bytes.return_value = asyncio.Future(loop=loop)
        request.write_bytes.return_value.set_result(None)
        request.send(mock.Mock())

        Request_mock.assert_called_with(mock.ANY,
                                        mock.ANY,
                                        "xn--9caa.com:80",
                                        mock.ANY,
                                        loop=loop)

    def test_proxy_dns_error(self):
        connector = aiohttp.TCPConnector(loop=self.loop)
        connector._resolve_host = make_mocked_coro(
            raise_exception=OSError('dont take it serious'))

        req = ClientRequest(
            'GET',
            URL('http://www.python.org'),
            proxy=URL('http://proxy.example.com'),
            loop=self.loop,
        )
        expected_headers = dict(req.headers)
        with self.assertRaises(aiohttp.ClientConnectorError):
            self.loop.run_until_complete(connector.connect(req))
        self.assertEqual(req.url.path, '/')
        self.assertEqual(dict(req.headers), expected_headers)

    def test_proxy_connection_error(self):
        connector = aiohttp.TCPConnector(loop=self.loop)
        connector._resolve_host = make_mocked_coro([{
            'hostname':
            'www.python.org',
            'host':
            '127.0.0.1',
            'port':
            80,
            'family':
            socket.AF_INET,
            'proto':
            0,
            'flags':
            socket.AI_NUMERICHOST
        }])
        connector._loop.create_connection = make_mocked_coro(
            raise_exception=OSError('dont take it serious'))

        req = ClientRequest(
            'GET',
            URL('http://www.python.org'),
            proxy=URL('http://proxy.example.com'),
            loop=self.loop,
        )
        with self.assertRaises(aiohttp.ClientProxyConnectionError):
            self.loop.run_until_complete(connector.connect(req))

    @mock.patch('aiohttp.connector.ClientRequest')
    def test_auth(self, ClientRequestMock):
        proxy_req = ClientRequest('GET',
                                  URL('http://proxy.example.com'),
                                  auth=aiohttp.helpers.BasicAuth(
                                      'user', 'pass'),
                                  loop=self.loop)
        ClientRequestMock.return_value = proxy_req
        self.assertIn('AUTHORIZATION', proxy_req.headers)
        self.assertNotIn('PROXY-AUTHORIZATION', proxy_req.headers)

        connector = aiohttp.TCPConnector(loop=self.loop)
        connector._resolve_host = make_mocked_coro([mock.MagicMock()])

        tr, proto = mock.Mock(), mock.Mock()
        self.loop.create_connection = make_mocked_coro((tr, proto))

        req = ClientRequest(
            'GET',
            URL('http://www.python.org'),
            proxy=URL('http://proxy.example.com'),
            proxy_auth=aiohttp.helpers.BasicAuth('user', 'pass'),
            loop=self.loop,
        )
        self.assertNotIn('AUTHORIZATION', req.headers)
        self.assertNotIn('PROXY-AUTHORIZATION', req.headers)
        conn = self.loop.run_until_complete(connector.connect(req))

        self.assertEqual(req.url, URL('http://www.python.org'))
        self.assertNotIn('AUTHORIZATION', req.headers)
        self.assertIn('PROXY-AUTHORIZATION', req.headers)
        self.assertNotIn('AUTHORIZATION', proxy_req.headers)
        self.assertNotIn('PROXY-AUTHORIZATION', proxy_req.headers)

        ClientRequestMock.assert_called_with('GET',
                                             URL('http://proxy.example.com'),
                                             auth=aiohttp.helpers.BasicAuth(
                                                 'user', 'pass'),
                                             loop=mock.ANY,
                                             headers=mock.ANY,
                                             ssl=None)
        conn.close()

    def test_auth_utf8(self):
        proxy_req = ClientRequest('GET',
                                  URL('http://proxy.example.com'),
                                  auth=aiohttp.helpers.BasicAuth(
                                      'юзер', 'пасс', 'utf-8'),
                                  loop=self.loop)
        self.assertIn('AUTHORIZATION', proxy_req.headers)

    @mock.patch('aiohttp.connector.ClientRequest')
    def test_auth_from_url(self, ClientRequestMock):
        proxy_req = ClientRequest('GET',
                                  URL('http://*****:*****@proxy.example.com'),
                                  loop=self.loop)
        ClientRequestMock.return_value = proxy_req
        self.assertIn('AUTHORIZATION', proxy_req.headers)
        self.assertNotIn('PROXY-AUTHORIZATION', proxy_req.headers)

        connector = aiohttp.TCPConnector(loop=self.loop)
        connector._resolve_host = make_mocked_coro([mock.MagicMock()])

        tr, proto = mock.Mock(), mock.Mock()
        self.loop.create_connection = make_mocked_coro((tr, proto))

        req = ClientRequest(
            'GET',
            URL('http://www.python.org'),
            proxy=URL('http://*****:*****@proxy.example.com'),
            loop=self.loop,
        )
        self.assertNotIn('AUTHORIZATION', req.headers)
        self.assertNotIn('PROXY-AUTHORIZATION', req.headers)
        conn = self.loop.run_until_complete(connector.connect(req))

        self.assertEqual(req.url, URL('http://www.python.org'))
        self.assertNotIn('AUTHORIZATION', req.headers)
        self.assertIn('PROXY-AUTHORIZATION', req.headers)
        self.assertNotIn('AUTHORIZATION', proxy_req.headers)
        self.assertNotIn('PROXY-AUTHORIZATION', proxy_req.headers)

        ClientRequestMock.assert_called_with(
            'GET',
            URL('http://*****:*****@proxy.example.com'),
            auth=None,
            loop=mock.ANY,
            headers=mock.ANY,
            ssl=None)
        conn.close()

    @mock.patch('aiohttp.connector.ClientRequest')
    def test_https_connect(self, ClientRequestMock):
        proxy_req = ClientRequest('GET',
                                  URL('http://proxy.example.com'),
                                  loop=self.loop)
        ClientRequestMock.return_value = proxy_req

        proxy_resp = ClientResponse('get', URL('http://proxy.example.com'))
        proxy_resp._loop = self.loop
        proxy_req.send = send_mock = mock.Mock()
        send_mock.return_value = proxy_resp
        proxy_resp.start = make_mocked_coro(mock.Mock(status=200))

        connector = aiohttp.TCPConnector(loop=self.loop)
        connector._resolve_host = make_mocked_coro([{
            'hostname': 'hostname',
            'host': '127.0.0.1',
            'port': 80,
            'family': socket.AF_INET,
            'proto': 0,
            'flags': 0
        }])

        tr, proto = mock.Mock(), mock.Mock()
        self.loop.create_connection = make_mocked_coro((tr, proto))

        req = ClientRequest(
            'GET',
            URL('https://www.python.org'),
            proxy=URL('http://proxy.example.com'),
            loop=self.loop,
        )
        self.loop.run_until_complete(connector._create_connection(req))

        self.assertEqual(req.url.path, '/')
        self.assertEqual(proxy_req.method, 'CONNECT')
        self.assertEqual(proxy_req.url, URL('https://www.python.org'))
        tr.close.assert_called_once_with()
        tr.get_extra_info.assert_called_with('socket', default=None)

        self.loop.run_until_complete(proxy_req.close())
        proxy_resp.close()
        self.loop.run_until_complete(req.close())

    @mock.patch('aiohttp.connector.ClientRequest')
    def test_https_connect_certificate_error(self, ClientRequestMock):
        proxy_req = ClientRequest('GET',
                                  URL('http://proxy.example.com'),
                                  loop=self.loop)
        ClientRequestMock.return_value = proxy_req

        proxy_resp = ClientResponse('get', URL('http://proxy.example.com'))
        proxy_resp._loop = self.loop
        proxy_req.send = send_mock = mock.Mock()
        send_mock.return_value = proxy_resp
        proxy_resp.start = make_mocked_coro(mock.Mock(status=200))

        connector = aiohttp.TCPConnector(loop=self.loop)
        connector._resolve_host = make_mocked_coro([{
            'hostname': 'hostname',
            'host': '127.0.0.1',
            'port': 80,
            'family': socket.AF_INET,
            'proto': 0,
            'flags': 0
        }])

        seq = 0

        @asyncio.coroutine
        def create_connection(*args, **kwargs):
            nonlocal seq
            seq += 1

            # connection to http://proxy.example.com
            if seq == 1:
                return mock.Mock(), mock.Mock()
            # connection to https://www.python.org
            elif seq == 2:
                raise ssl.CertificateError
            else:
                assert False

        self.loop.create_connection = create_connection

        req = ClientRequest(
            'GET',
            URL('https://www.python.org'),
            proxy=URL('http://proxy.example.com'),
            loop=self.loop,
        )
        with self.assertRaises(aiohttp.ClientConnectorCertificateError):
            self.loop.run_until_complete(connector._create_connection(req))

    @mock.patch('aiohttp.connector.ClientRequest')
    def test_https_connect_ssl_error(self, ClientRequestMock):
        proxy_req = ClientRequest('GET',
                                  URL('http://proxy.example.com'),
                                  loop=self.loop)
        ClientRequestMock.return_value = proxy_req

        proxy_resp = ClientResponse('get', URL('http://proxy.example.com'))
        proxy_resp._loop = self.loop
        proxy_req.send = send_mock = mock.Mock()
        send_mock.return_value = proxy_resp
        proxy_resp.start = make_mocked_coro(mock.Mock(status=200))

        connector = aiohttp.TCPConnector(loop=self.loop)
        connector._resolve_host = make_mocked_coro([{
            'hostname': 'hostname',
            'host': '127.0.0.1',
            'port': 80,
            'family': socket.AF_INET,
            'proto': 0,
            'flags': 0
        }])

        seq = 0

        @asyncio.coroutine
        def create_connection(*args, **kwargs):
            nonlocal seq
            seq += 1

            # connection to http://proxy.example.com
            if seq == 1:
                return mock.Mock(), mock.Mock()
            # connection to https://www.python.org
            elif seq == 2:
                raise ssl.SSLError
            else:
                assert False

        self.loop.create_connection = create_connection

        req = ClientRequest(
            'GET',
            URL('https://www.python.org'),
            proxy=URL('http://proxy.example.com'),
            loop=self.loop,
        )
        with self.assertRaises(aiohttp.ClientConnectorSSLError):
            self.loop.run_until_complete(connector._create_connection(req))

    @mock.patch('aiohttp.connector.ClientRequest')
    def test_https_connect_runtime_error(self, ClientRequestMock):
        proxy_req = ClientRequest('GET',
                                  URL('http://proxy.example.com'),
                                  loop=self.loop)
        ClientRequestMock.return_value = proxy_req

        proxy_resp = ClientResponse('get', URL('http://proxy.example.com'))
        proxy_resp._loop = self.loop
        proxy_req.send = send_mock = mock.Mock()
        send_mock.return_value = proxy_resp
        proxy_resp.start = make_mocked_coro(mock.Mock(status=200))

        connector = aiohttp.TCPConnector(loop=self.loop)
        connector._resolve_host = make_mocked_coro([{
            'hostname': 'hostname',
            'host': '127.0.0.1',
            'port': 80,
            'family': socket.AF_INET,
            'proto': 0,
            'flags': 0
        }])

        tr, proto = mock.Mock(), mock.Mock()
        tr.get_extra_info.return_value = None
        self.loop.create_connection = make_mocked_coro((tr, proto))

        req = ClientRequest(
            'GET',
            URL('https://www.python.org'),
            proxy=URL('http://proxy.example.com'),
            loop=self.loop,
        )
        with self.assertRaisesRegex(
                RuntimeError, "Transport does not expose socket instance"):
            self.loop.run_until_complete(connector._create_connection(req))

        self.loop.run_until_complete(proxy_req.close())
        proxy_resp.close()
        self.loop.run_until_complete(req.close())

    @mock.patch('aiohttp.connector.ClientRequest')
    def test_https_connect_http_proxy_error(self, ClientRequestMock):
        proxy_req = ClientRequest('GET',
                                  URL('http://proxy.example.com'),
                                  loop=self.loop)
        ClientRequestMock.return_value = proxy_req

        proxy_resp = ClientResponse('get', URL('http://proxy.example.com'))
        proxy_resp._loop = self.loop
        proxy_req.send = send_mock = mock.Mock()
        send_mock.return_value = proxy_resp
        proxy_resp.start = make_mocked_coro(
            mock.Mock(status=400, reason='bad request'))

        connector = aiohttp.TCPConnector(loop=self.loop)
        connector._resolve_host = make_mocked_coro([{
            'hostname': 'hostname',
            'host': '127.0.0.1',
            'port': 80,
            'family': socket.AF_INET,
            'proto': 0,
            'flags': 0
        }])

        tr, proto = mock.Mock(), mock.Mock()
        tr.get_extra_info.return_value = None
        self.loop.create_connection = make_mocked_coro((tr, proto))

        req = ClientRequest(
            'GET',
            URL('https://www.python.org'),
            proxy=URL('http://proxy.example.com'),
            loop=self.loop,
        )
        with self.assertRaisesRegex(aiohttp.ClientHttpProxyError,
                                    "400, message='bad request'"):
            self.loop.run_until_complete(connector._create_connection(req))

        self.loop.run_until_complete(proxy_req.close())
        proxy_resp.close()
        self.loop.run_until_complete(req.close())

    @mock.patch('aiohttp.connector.ClientRequest')
    def test_https_connect_resp_start_error(self, ClientRequestMock):
        proxy_req = ClientRequest('GET',
                                  URL('http://proxy.example.com'),
                                  loop=self.loop)
        ClientRequestMock.return_value = proxy_req

        proxy_resp = ClientResponse('get', URL('http://proxy.example.com'))
        proxy_resp._loop = self.loop
        proxy_req.send = send_mock = mock.Mock()
        send_mock.return_value = proxy_resp
        proxy_resp.start = make_mocked_coro(
            raise_exception=OSError("error message"))

        connector = aiohttp.TCPConnector(loop=self.loop)
        connector._resolve_host = make_mocked_coro([{
            'hostname': 'hostname',
            'host': '127.0.0.1',
            'port': 80,
            'family': socket.AF_INET,
            'proto': 0,
            'flags': 0
        }])

        tr, proto = mock.Mock(), mock.Mock()
        tr.get_extra_info.return_value = None
        self.loop.create_connection = make_mocked_coro((tr, proto))

        req = ClientRequest(
            'GET',
            URL('https://www.python.org'),
            proxy=URL('http://proxy.example.com'),
            loop=self.loop,
        )
        with self.assertRaisesRegex(OSError, "error message"):
            self.loop.run_until_complete(connector._create_connection(req))

    @mock.patch('aiohttp.connector.ClientRequest')
    def test_request_port(self, ClientRequestMock):
        proxy_req = ClientRequest('GET',
                                  URL('http://proxy.example.com'),
                                  loop=self.loop)
        ClientRequestMock.return_value = proxy_req

        connector = aiohttp.TCPConnector(loop=self.loop)
        connector._resolve_host = make_mocked_coro([{
            'hostname': 'hostname',
            'host': '127.0.0.1',
            'port': 80,
            'family': socket.AF_INET,
            'proto': 0,
            'flags': 0
        }])

        tr, proto = mock.Mock(), mock.Mock()
        tr.get_extra_info.return_value = None
        self.loop.create_connection = make_mocked_coro((tr, proto))

        req = ClientRequest(
            'GET',
            URL('http://*****:*****@mock.patch('aiohttp.connector.ClientRequest')
    def test_https_connect_pass_ssl_context(self, ClientRequestMock):
        proxy_req = ClientRequest('GET',
                                  URL('http://proxy.example.com'),
                                  loop=self.loop)
        ClientRequestMock.return_value = proxy_req

        proxy_resp = ClientResponse('get', URL('http://proxy.example.com'))
        proxy_resp._loop = self.loop
        proxy_req.send = send_mock = mock.Mock()
        send_mock.return_value = proxy_resp
        proxy_resp.start = make_mocked_coro(mock.Mock(status=200))

        connector = aiohttp.TCPConnector(loop=self.loop)
        connector._resolve_host = make_mocked_coro([{
            'hostname': 'hostname',
            'host': '127.0.0.1',
            'port': 80,
            'family': socket.AF_INET,
            'proto': 0,
            'flags': 0
        }])

        tr, proto = mock.Mock(), mock.Mock()
        self.loop.create_connection = make_mocked_coro((tr, proto))

        req = ClientRequest(
            'GET',
            URL('https://www.python.org'),
            proxy=URL('http://proxy.example.com'),
            loop=self.loop,
        )
        self.loop.run_until_complete(connector._create_connection(req))

        self.loop.create_connection.assert_called_with(
            mock.ANY,
            ssl=connector._make_ssl_context(True),
            sock=mock.ANY,
            server_hostname='www.python.org')

        self.assertEqual(req.url.path, '/')
        self.assertEqual(proxy_req.method, 'CONNECT')
        self.assertEqual(proxy_req.url, URL('https://www.python.org'))
        tr.close.assert_called_once_with()
        tr.get_extra_info.assert_called_with('socket', default=None)

        self.loop.run_until_complete(proxy_req.close())
        proxy_resp.close()
        self.loop.run_until_complete(req.close())

    @mock.patch('aiohttp.connector.ClientRequest')
    def test_https_auth(self, ClientRequestMock):
        proxy_req = ClientRequest('GET',
                                  URL('http://proxy.example.com'),
                                  auth=aiohttp.helpers.BasicAuth(
                                      'user', 'pass'),
                                  loop=self.loop)
        ClientRequestMock.return_value = proxy_req

        proxy_resp = ClientResponse('get', URL('http://proxy.example.com'))
        proxy_resp._loop = self.loop
        proxy_req.send = send_mock = mock.Mock()
        send_mock.return_value = proxy_resp
        proxy_resp.start = make_mocked_coro(mock.Mock(status=200))

        connector = aiohttp.TCPConnector(loop=self.loop)
        connector._resolve_host = make_mocked_coro([{
            'hostname': 'hostname',
            'host': '127.0.0.1',
            'port': 80,
            'family': socket.AF_INET,
            'proto': 0,
            'flags': 0
        }])

        tr, proto = mock.Mock(), mock.Mock()
        self.loop.create_connection = make_mocked_coro((tr, proto))

        self.assertIn('AUTHORIZATION', proxy_req.headers)
        self.assertNotIn('PROXY-AUTHORIZATION', proxy_req.headers)

        req = ClientRequest('GET',
                            URL('https://www.python.org'),
                            proxy=URL('http://proxy.example.com'),
                            loop=self.loop)
        self.assertNotIn('AUTHORIZATION', req.headers)
        self.assertNotIn('PROXY-AUTHORIZATION', req.headers)
        self.loop.run_until_complete(connector._create_connection(req))

        self.assertEqual(req.url.path, '/')
        self.assertNotIn('AUTHORIZATION', req.headers)
        self.assertNotIn('PROXY-AUTHORIZATION', req.headers)
        self.assertNotIn('AUTHORIZATION', proxy_req.headers)
        self.assertIn('PROXY-AUTHORIZATION', proxy_req.headers)

        connector._resolve_host.assert_called_with('proxy.example.com',
                                                   80,
                                                   traces=None)

        self.loop.run_until_complete(proxy_req.close())
        proxy_resp.close()
        self.loop.run_until_complete(req.close())