2019-11-01 15:07:44 +01:00
|
|
|
# Copyright 2019 The Matrix.org Foundation C.I.C.
|
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
|
|
|
|
2023-07-18 10:49:21 +02:00
|
|
|
import abc
|
2021-08-11 16:34:59 +02:00
|
|
|
import base64
|
2019-11-01 15:07:44 +01:00
|
|
|
import logging
|
2022-05-13 13:35:31 +02:00
|
|
|
from typing import Optional, Union
|
2019-11-01 15:07:44 +01:00
|
|
|
|
2021-08-11 16:34:59 +02:00
|
|
|
import attr
|
2019-11-01 15:07:44 +01:00
|
|
|
from zope.interface import implementer
|
|
|
|
|
|
|
|
from twisted.internet import defer, protocol
|
|
|
|
from twisted.internet.error import ConnectError
|
2022-05-13 13:35:31 +02:00
|
|
|
from twisted.internet.interfaces import (
|
|
|
|
IAddress,
|
|
|
|
IConnector,
|
|
|
|
IProtocol,
|
|
|
|
IReactorCore,
|
|
|
|
IStreamClientEndpoint,
|
|
|
|
)
|
2021-03-22 18:20:47 +01:00
|
|
|
from twisted.internet.protocol import ClientFactory, Protocol, connectionDone
|
2022-05-13 13:35:31 +02:00
|
|
|
from twisted.python.failure import Failure
|
2019-11-01 15:07:44 +01:00
|
|
|
from twisted.web import http
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
class ProxyConnectError(ConnectError):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
2021-08-11 16:34:59 +02:00
|
|
|
class ProxyCredentials:
|
2023-07-18 10:49:21 +02:00
|
|
|
@abc.abstractmethod
|
|
|
|
def as_proxy_authorization_value(self) -> bytes:
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
|
|
|
|
@attr.s(auto_attribs=True)
|
|
|
|
class BasicProxyCredentials(ProxyCredentials):
|
2022-01-13 14:49:28 +01:00
|
|
|
username_password: bytes
|
2021-08-11 16:34:59 +02:00
|
|
|
|
|
|
|
def as_proxy_authorization_value(self) -> bytes:
|
|
|
|
"""
|
|
|
|
Return the value for a Proxy-Authorization header (i.e. 'Basic abdef==').
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
A transformation of the authentication string the encoded value for
|
|
|
|
a Proxy-Authorization header.
|
|
|
|
"""
|
|
|
|
# Encode as base64 and prepend the authorization type
|
2023-10-24 15:45:21 +02:00
|
|
|
return b"Basic " + base64.b64encode(self.username_password)
|
2021-08-11 16:34:59 +02:00
|
|
|
|
|
|
|
|
2023-07-18 10:49:21 +02:00
|
|
|
@attr.s(auto_attribs=True)
|
|
|
|
class BearerProxyCredentials(ProxyCredentials):
|
|
|
|
access_token: bytes
|
|
|
|
|
|
|
|
def as_proxy_authorization_value(self) -> bytes:
|
|
|
|
"""
|
|
|
|
Return the value for a Proxy-Authorization header (i.e. 'Bearer xxx').
|
|
|
|
"""
|
|
|
|
return b"Bearer " + self.access_token
|
|
|
|
|
|
|
|
|
2019-11-01 15:07:44 +01:00
|
|
|
@implementer(IStreamClientEndpoint)
|
2020-09-04 12:54:56 +02:00
|
|
|
class HTTPConnectProxyEndpoint:
|
2019-11-01 15:07:44 +01:00
|
|
|
"""An Endpoint implementation which will send a CONNECT request to an http proxy
|
|
|
|
|
|
|
|
Wraps an existing HostnameEndpoint for the proxy.
|
|
|
|
|
|
|
|
When we get the connect() request from the connection pool (via the TLS wrapper),
|
|
|
|
we'll first connect to the proxy endpoint with a ProtocolFactory which will make the
|
|
|
|
CONNECT request. Once that completes, we invoke the protocolFactory which was passed
|
|
|
|
in.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
reactor: the Twisted reactor to use for the connection
|
2021-03-22 18:20:47 +01:00
|
|
|
proxy_endpoint: the endpoint to use to connect to the proxy
|
|
|
|
host: hostname that we want to CONNECT to
|
|
|
|
port: port that we want to connect to
|
2021-08-11 16:34:59 +02:00
|
|
|
proxy_creds: credentials to authenticate at proxy
|
2019-11-01 15:07:44 +01:00
|
|
|
"""
|
|
|
|
|
2021-03-22 18:20:47 +01:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
reactor: IReactorCore,
|
|
|
|
proxy_endpoint: IStreamClientEndpoint,
|
|
|
|
host: bytes,
|
|
|
|
port: int,
|
2021-08-11 16:34:59 +02:00
|
|
|
proxy_creds: Optional[ProxyCredentials],
|
2021-03-22 18:20:47 +01:00
|
|
|
):
|
2019-11-01 15:07:44 +01:00
|
|
|
self._reactor = reactor
|
|
|
|
self._proxy_endpoint = proxy_endpoint
|
|
|
|
self._host = host
|
|
|
|
self._port = port
|
2021-08-11 16:34:59 +02:00
|
|
|
self._proxy_creds = proxy_creds
|
2019-11-01 15:07:44 +01:00
|
|
|
|
2022-05-13 13:35:31 +02:00
|
|
|
def __repr__(self) -> str:
|
2019-11-01 15:07:44 +01:00
|
|
|
return "<HTTPConnectProxyEndpoint %s>" % (self._proxy_endpoint,)
|
|
|
|
|
2021-10-28 15:14:42 +02:00
|
|
|
# Mypy encounters a false positive here: it complains that ClientFactory
|
|
|
|
# is incompatible with IProtocolFactory. But ClientFactory inherits from
|
|
|
|
# Factory, which implements IProtocolFactory. So I think this is a bug
|
|
|
|
# in mypy-zope.
|
2022-05-13 13:35:31 +02:00
|
|
|
def connect(self, protocolFactory: ClientFactory) -> "defer.Deferred[IProtocol]": # type: ignore[override]
|
2021-03-22 18:20:47 +01:00
|
|
|
f = HTTPProxiedClientFactory(
|
2021-08-11 16:34:59 +02:00
|
|
|
self._host, self._port, protocolFactory, self._proxy_creds
|
2021-03-22 18:20:47 +01:00
|
|
|
)
|
2019-11-01 15:07:44 +01:00
|
|
|
d = self._proxy_endpoint.connect(f)
|
|
|
|
# once the tcp socket connects successfully, we need to wait for the
|
|
|
|
# CONNECT to complete.
|
|
|
|
d.addCallback(lambda conn: f.on_connection)
|
|
|
|
return d
|
|
|
|
|
|
|
|
|
|
|
|
class HTTPProxiedClientFactory(protocol.ClientFactory):
|
|
|
|
"""ClientFactory wrapper that triggers an HTTP proxy CONNECT on connect.
|
|
|
|
|
|
|
|
Once the CONNECT completes, invokes the original ClientFactory to build the
|
|
|
|
HTTP Protocol object and run the rest of the connection.
|
|
|
|
|
|
|
|
Args:
|
2021-03-22 18:20:47 +01:00
|
|
|
dst_host: hostname that we want to CONNECT to
|
|
|
|
dst_port: port that we want to connect to
|
|
|
|
wrapped_factory: The original Factory
|
2021-08-11 16:34:59 +02:00
|
|
|
proxy_creds: credentials to authenticate at proxy
|
2019-11-01 15:07:44 +01:00
|
|
|
"""
|
|
|
|
|
2021-03-22 18:20:47 +01:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
dst_host: bytes,
|
|
|
|
dst_port: int,
|
|
|
|
wrapped_factory: ClientFactory,
|
2021-08-11 16:34:59 +02:00
|
|
|
proxy_creds: Optional[ProxyCredentials],
|
2021-03-22 18:20:47 +01:00
|
|
|
):
|
2019-11-01 15:07:44 +01:00
|
|
|
self.dst_host = dst_host
|
|
|
|
self.dst_port = dst_port
|
|
|
|
self.wrapped_factory = wrapped_factory
|
2021-08-11 16:34:59 +02:00
|
|
|
self.proxy_creds = proxy_creds
|
2021-10-28 15:14:42 +02:00
|
|
|
self.on_connection: "defer.Deferred[None]" = defer.Deferred()
|
2019-11-01 15:07:44 +01:00
|
|
|
|
2022-05-13 13:35:31 +02:00
|
|
|
def startedConnecting(self, connector: IConnector) -> None:
|
2019-11-01 15:07:44 +01:00
|
|
|
return self.wrapped_factory.startedConnecting(connector)
|
|
|
|
|
2022-05-13 13:35:31 +02:00
|
|
|
def buildProtocol(self, addr: IAddress) -> "HTTPConnectProtocol":
|
2019-11-01 15:07:44 +01:00
|
|
|
wrapped_protocol = self.wrapped_factory.buildProtocol(addr)
|
2021-10-28 15:14:42 +02:00
|
|
|
if wrapped_protocol is None:
|
|
|
|
raise TypeError("buildProtocol produced None instead of a Protocol")
|
2019-11-01 15:07:44 +01:00
|
|
|
|
|
|
|
return HTTPConnectProtocol(
|
2021-03-22 18:20:47 +01:00
|
|
|
self.dst_host,
|
|
|
|
self.dst_port,
|
|
|
|
wrapped_protocol,
|
|
|
|
self.on_connection,
|
2021-08-11 16:34:59 +02:00
|
|
|
self.proxy_creds,
|
2019-11-01 15:07:44 +01:00
|
|
|
)
|
|
|
|
|
2022-05-13 13:35:31 +02:00
|
|
|
def clientConnectionFailed(self, connector: IConnector, reason: Failure) -> None:
|
2019-11-01 15:07:44 +01:00
|
|
|
logger.debug("Connection to proxy failed: %s", reason)
|
|
|
|
if not self.on_connection.called:
|
|
|
|
self.on_connection.errback(reason)
|
|
|
|
return self.wrapped_factory.clientConnectionFailed(connector, reason)
|
|
|
|
|
2022-05-13 13:35:31 +02:00
|
|
|
def clientConnectionLost(self, connector: IConnector, reason: Failure) -> None:
|
2019-11-01 15:07:44 +01:00
|
|
|
logger.debug("Connection to proxy lost: %s", reason)
|
|
|
|
if not self.on_connection.called:
|
|
|
|
self.on_connection.errback(reason)
|
|
|
|
return self.wrapped_factory.clientConnectionLost(connector, reason)
|
|
|
|
|
|
|
|
|
|
|
|
class HTTPConnectProtocol(protocol.Protocol):
|
|
|
|
"""Protocol that wraps an existing Protocol to do a CONNECT handshake at connect
|
|
|
|
|
|
|
|
Args:
|
2021-03-22 18:20:47 +01:00
|
|
|
host: The original HTTP(s) hostname or IPv4 or IPv6 address literal
|
2019-11-01 15:07:44 +01:00
|
|
|
to put in the CONNECT request
|
|
|
|
|
2021-03-22 18:20:47 +01:00
|
|
|
port: The original HTTP(s) port to put in the CONNECT request
|
2019-11-01 15:07:44 +01:00
|
|
|
|
2021-03-22 18:20:47 +01:00
|
|
|
wrapped_protocol: the original protocol (probably HTTPChannel or
|
|
|
|
TLSMemoryBIOProtocol, but could be anything really)
|
2019-11-01 15:07:44 +01:00
|
|
|
|
2021-03-22 18:20:47 +01:00
|
|
|
connected_deferred: a Deferred which will be callbacked with
|
2019-11-01 15:07:44 +01:00
|
|
|
wrapped_protocol when the CONNECT completes
|
2021-03-22 18:20:47 +01:00
|
|
|
|
2021-08-11 16:34:59 +02:00
|
|
|
proxy_creds: credentials to authenticate at proxy
|
2019-11-01 15:07:44 +01:00
|
|
|
"""
|
|
|
|
|
2021-03-22 18:20:47 +01:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
host: bytes,
|
|
|
|
port: int,
|
|
|
|
wrapped_protocol: Protocol,
|
|
|
|
connected_deferred: defer.Deferred,
|
2021-08-11 16:34:59 +02:00
|
|
|
proxy_creds: Optional[ProxyCredentials],
|
2021-03-22 18:20:47 +01:00
|
|
|
):
|
2019-11-01 15:07:44 +01:00
|
|
|
self.host = host
|
|
|
|
self.port = port
|
|
|
|
self.wrapped_protocol = wrapped_protocol
|
|
|
|
self.connected_deferred = connected_deferred
|
2021-08-11 16:34:59 +02:00
|
|
|
self.proxy_creds = proxy_creds
|
2021-03-22 18:20:47 +01:00
|
|
|
|
|
|
|
self.http_setup_client = HTTPConnectSetupClient(
|
2021-08-11 16:34:59 +02:00
|
|
|
self.host, self.port, self.proxy_creds
|
2021-03-22 18:20:47 +01:00
|
|
|
)
|
2019-11-01 15:07:44 +01:00
|
|
|
self.http_setup_client.on_connected.addCallback(self.proxyConnected)
|
|
|
|
|
2022-05-13 13:35:31 +02:00
|
|
|
def connectionMade(self) -> None:
|
2019-11-01 15:07:44 +01:00
|
|
|
self.http_setup_client.makeConnection(self.transport)
|
|
|
|
|
2022-05-13 13:35:31 +02:00
|
|
|
def connectionLost(self, reason: Failure = connectionDone) -> None:
|
2019-11-01 15:07:44 +01:00
|
|
|
if self.wrapped_protocol.connected:
|
|
|
|
self.wrapped_protocol.connectionLost(reason)
|
|
|
|
|
|
|
|
self.http_setup_client.connectionLost(reason)
|
|
|
|
|
|
|
|
if not self.connected_deferred.called:
|
|
|
|
self.connected_deferred.errback(reason)
|
|
|
|
|
2022-05-13 13:35:31 +02:00
|
|
|
def proxyConnected(self, _: Union[None, "defer.Deferred[None]"]) -> None:
|
2019-11-01 15:07:44 +01:00
|
|
|
self.wrapped_protocol.makeConnection(self.transport)
|
|
|
|
|
|
|
|
self.connected_deferred.callback(self.wrapped_protocol)
|
|
|
|
|
|
|
|
# Get any pending data from the http buf and forward it to the original protocol
|
|
|
|
buf = self.http_setup_client.clearLineBuffer()
|
|
|
|
if buf:
|
|
|
|
self.wrapped_protocol.dataReceived(buf)
|
|
|
|
|
2022-05-13 13:35:31 +02:00
|
|
|
def dataReceived(self, data: bytes) -> None:
|
2019-11-01 15:07:44 +01:00
|
|
|
# if we've set up the HTTP protocol, we can send the data there
|
|
|
|
if self.wrapped_protocol.connected:
|
|
|
|
return self.wrapped_protocol.dataReceived(data)
|
|
|
|
|
|
|
|
# otherwise, we must still be setting up the connection: send the data to the
|
|
|
|
# setup client
|
|
|
|
return self.http_setup_client.dataReceived(data)
|
|
|
|
|
|
|
|
|
|
|
|
class HTTPConnectSetupClient(http.HTTPClient):
|
|
|
|
"""HTTPClient protocol to send a CONNECT message for proxies and read the response.
|
|
|
|
|
|
|
|
Args:
|
2021-03-22 18:20:47 +01:00
|
|
|
host: The hostname to send in the CONNECT message
|
|
|
|
port: The port to send in the CONNECT message
|
2021-08-11 16:34:59 +02:00
|
|
|
proxy_creds: credentials to authenticate at proxy
|
2019-11-01 15:07:44 +01:00
|
|
|
"""
|
|
|
|
|
2021-08-11 16:34:59 +02:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
host: bytes,
|
|
|
|
port: int,
|
|
|
|
proxy_creds: Optional[ProxyCredentials],
|
|
|
|
):
|
2019-11-01 15:07:44 +01:00
|
|
|
self.host = host
|
|
|
|
self.port = port
|
2021-08-11 16:34:59 +02:00
|
|
|
self.proxy_creds = proxy_creds
|
2021-10-28 15:14:42 +02:00
|
|
|
self.on_connected: "defer.Deferred[None]" = defer.Deferred()
|
2019-11-01 15:07:44 +01:00
|
|
|
|
2022-05-13 13:35:31 +02:00
|
|
|
def connectionMade(self) -> None:
|
2019-11-01 15:07:44 +01:00
|
|
|
logger.debug("Connected to proxy, sending CONNECT")
|
|
|
|
self.sendCommand(b"CONNECT", b"%s:%d" % (self.host, self.port))
|
2021-03-22 18:20:47 +01:00
|
|
|
|
2021-08-11 16:34:59 +02:00
|
|
|
# Determine whether we need to set Proxy-Authorization headers
|
|
|
|
if self.proxy_creds:
|
|
|
|
# Set a Proxy-Authorization header
|
|
|
|
self.sendHeader(
|
|
|
|
b"Proxy-Authorization",
|
|
|
|
self.proxy_creds.as_proxy_authorization_value(),
|
|
|
|
)
|
2021-03-22 18:20:47 +01:00
|
|
|
|
2019-11-01 15:07:44 +01:00
|
|
|
self.endHeaders()
|
|
|
|
|
2022-05-13 13:35:31 +02:00
|
|
|
def handleStatus(self, version: bytes, status: bytes, message: bytes) -> None:
|
2019-11-01 15:07:44 +01:00
|
|
|
logger.debug("Got Status: %s %s %s", status, message, version)
|
|
|
|
if status != b"200":
|
2021-08-11 16:34:59 +02:00
|
|
|
raise ProxyConnectError(f"Unexpected status on CONNECT: {status!s}")
|
2019-11-01 15:07:44 +01:00
|
|
|
|
2022-05-13 13:35:31 +02:00
|
|
|
def handleEndHeaders(self) -> None:
|
2019-11-01 15:07:44 +01:00
|
|
|
logger.debug("End Headers")
|
|
|
|
self.on_connected.callback(None)
|
|
|
|
|
2022-05-13 13:35:31 +02:00
|
|
|
def handleResponse(self, body: bytes) -> None:
|
2019-11-01 15:07:44 +01:00
|
|
|
pass
|