connectproxyclient.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. # Copyright 2019 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import base64
  15. import logging
  16. from typing import Optional, Union
  17. import attr
  18. from zope.interface import implementer
  19. from twisted.internet import defer, protocol
  20. from twisted.internet.error import ConnectError
  21. from twisted.internet.interfaces import (
  22. IAddress,
  23. IConnector,
  24. IProtocol,
  25. IReactorCore,
  26. IStreamClientEndpoint,
  27. )
  28. from twisted.internet.protocol import ClientFactory, Protocol, connectionDone
  29. from twisted.python.failure import Failure
  30. from twisted.web import http
  31. logger = logging.getLogger(__name__)
  32. class ProxyConnectError(ConnectError):
  33. pass
  34. @attr.s(auto_attribs=True)
  35. class ProxyCredentials:
  36. username_password: bytes
  37. def as_proxy_authorization_value(self) -> bytes:
  38. """
  39. Return the value for a Proxy-Authorization header (i.e. 'Basic abdef==').
  40. Returns:
  41. A transformation of the authentication string the encoded value for
  42. a Proxy-Authorization header.
  43. """
  44. # Encode as base64 and prepend the authorization type
  45. return b"Basic " + base64.encodebytes(self.username_password)
  46. @implementer(IStreamClientEndpoint)
  47. class HTTPConnectProxyEndpoint:
  48. """An Endpoint implementation which will send a CONNECT request to an http proxy
  49. Wraps an existing HostnameEndpoint for the proxy.
  50. When we get the connect() request from the connection pool (via the TLS wrapper),
  51. we'll first connect to the proxy endpoint with a ProtocolFactory which will make the
  52. CONNECT request. Once that completes, we invoke the protocolFactory which was passed
  53. in.
  54. Args:
  55. reactor: the Twisted reactor to use for the connection
  56. proxy_endpoint: the endpoint to use to connect to the proxy
  57. host: hostname that we want to CONNECT to
  58. port: port that we want to connect to
  59. proxy_creds: credentials to authenticate at proxy
  60. """
  61. def __init__(
  62. self,
  63. reactor: IReactorCore,
  64. proxy_endpoint: IStreamClientEndpoint,
  65. host: bytes,
  66. port: int,
  67. proxy_creds: Optional[ProxyCredentials],
  68. ):
  69. self._reactor = reactor
  70. self._proxy_endpoint = proxy_endpoint
  71. self._host = host
  72. self._port = port
  73. self._proxy_creds = proxy_creds
  74. def __repr__(self) -> str:
  75. return "<HTTPConnectProxyEndpoint %s>" % (self._proxy_endpoint,)
  76. # Mypy encounters a false positive here: it complains that ClientFactory
  77. # is incompatible with IProtocolFactory. But ClientFactory inherits from
  78. # Factory, which implements IProtocolFactory. So I think this is a bug
  79. # in mypy-zope.
  80. def connect(self, protocolFactory: ClientFactory) -> "defer.Deferred[IProtocol]": # type: ignore[override]
  81. f = HTTPProxiedClientFactory(
  82. self._host, self._port, protocolFactory, self._proxy_creds
  83. )
  84. d = self._proxy_endpoint.connect(f)
  85. # once the tcp socket connects successfully, we need to wait for the
  86. # CONNECT to complete.
  87. d.addCallback(lambda conn: f.on_connection)
  88. return d
  89. class HTTPProxiedClientFactory(protocol.ClientFactory):
  90. """ClientFactory wrapper that triggers an HTTP proxy CONNECT on connect.
  91. Once the CONNECT completes, invokes the original ClientFactory to build the
  92. HTTP Protocol object and run the rest of the connection.
  93. Args:
  94. dst_host: hostname that we want to CONNECT to
  95. dst_port: port that we want to connect to
  96. wrapped_factory: The original Factory
  97. proxy_creds: credentials to authenticate at proxy
  98. """
  99. def __init__(
  100. self,
  101. dst_host: bytes,
  102. dst_port: int,
  103. wrapped_factory: ClientFactory,
  104. proxy_creds: Optional[ProxyCredentials],
  105. ):
  106. self.dst_host = dst_host
  107. self.dst_port = dst_port
  108. self.wrapped_factory = wrapped_factory
  109. self.proxy_creds = proxy_creds
  110. self.on_connection: "defer.Deferred[None]" = defer.Deferred()
  111. def startedConnecting(self, connector: IConnector) -> None:
  112. return self.wrapped_factory.startedConnecting(connector)
  113. def buildProtocol(self, addr: IAddress) -> "HTTPConnectProtocol":
  114. wrapped_protocol = self.wrapped_factory.buildProtocol(addr)
  115. if wrapped_protocol is None:
  116. raise TypeError("buildProtocol produced None instead of a Protocol")
  117. return HTTPConnectProtocol(
  118. self.dst_host,
  119. self.dst_port,
  120. wrapped_protocol,
  121. self.on_connection,
  122. self.proxy_creds,
  123. )
  124. def clientConnectionFailed(self, connector: IConnector, reason: Failure) -> None:
  125. logger.debug("Connection to proxy failed: %s", reason)
  126. if not self.on_connection.called:
  127. self.on_connection.errback(reason)
  128. return self.wrapped_factory.clientConnectionFailed(connector, reason)
  129. def clientConnectionLost(self, connector: IConnector, reason: Failure) -> None:
  130. logger.debug("Connection to proxy lost: %s", reason)
  131. if not self.on_connection.called:
  132. self.on_connection.errback(reason)
  133. return self.wrapped_factory.clientConnectionLost(connector, reason)
  134. class HTTPConnectProtocol(protocol.Protocol):
  135. """Protocol that wraps an existing Protocol to do a CONNECT handshake at connect
  136. Args:
  137. host: The original HTTP(s) hostname or IPv4 or IPv6 address literal
  138. to put in the CONNECT request
  139. port: The original HTTP(s) port to put in the CONNECT request
  140. wrapped_protocol: the original protocol (probably HTTPChannel or
  141. TLSMemoryBIOProtocol, but could be anything really)
  142. connected_deferred: a Deferred which will be callbacked with
  143. wrapped_protocol when the CONNECT completes
  144. proxy_creds: credentials to authenticate at proxy
  145. """
  146. def __init__(
  147. self,
  148. host: bytes,
  149. port: int,
  150. wrapped_protocol: Protocol,
  151. connected_deferred: defer.Deferred,
  152. proxy_creds: Optional[ProxyCredentials],
  153. ):
  154. self.host = host
  155. self.port = port
  156. self.wrapped_protocol = wrapped_protocol
  157. self.connected_deferred = connected_deferred
  158. self.proxy_creds = proxy_creds
  159. self.http_setup_client = HTTPConnectSetupClient(
  160. self.host, self.port, self.proxy_creds
  161. )
  162. self.http_setup_client.on_connected.addCallback(self.proxyConnected)
  163. def connectionMade(self) -> None:
  164. self.http_setup_client.makeConnection(self.transport)
  165. def connectionLost(self, reason: Failure = connectionDone) -> None:
  166. if self.wrapped_protocol.connected:
  167. self.wrapped_protocol.connectionLost(reason)
  168. self.http_setup_client.connectionLost(reason)
  169. if not self.connected_deferred.called:
  170. self.connected_deferred.errback(reason)
  171. def proxyConnected(self, _: Union[None, "defer.Deferred[None]"]) -> None:
  172. self.wrapped_protocol.makeConnection(self.transport)
  173. self.connected_deferred.callback(self.wrapped_protocol)
  174. # Get any pending data from the http buf and forward it to the original protocol
  175. buf = self.http_setup_client.clearLineBuffer()
  176. if buf:
  177. self.wrapped_protocol.dataReceived(buf)
  178. def dataReceived(self, data: bytes) -> None:
  179. # if we've set up the HTTP protocol, we can send the data there
  180. if self.wrapped_protocol.connected:
  181. return self.wrapped_protocol.dataReceived(data)
  182. # otherwise, we must still be setting up the connection: send the data to the
  183. # setup client
  184. return self.http_setup_client.dataReceived(data)
  185. class HTTPConnectSetupClient(http.HTTPClient):
  186. """HTTPClient protocol to send a CONNECT message for proxies and read the response.
  187. Args:
  188. host: The hostname to send in the CONNECT message
  189. port: The port to send in the CONNECT message
  190. proxy_creds: credentials to authenticate at proxy
  191. """
  192. def __init__(
  193. self,
  194. host: bytes,
  195. port: int,
  196. proxy_creds: Optional[ProxyCredentials],
  197. ):
  198. self.host = host
  199. self.port = port
  200. self.proxy_creds = proxy_creds
  201. self.on_connected: "defer.Deferred[None]" = defer.Deferred()
  202. def connectionMade(self) -> None:
  203. logger.debug("Connected to proxy, sending CONNECT")
  204. self.sendCommand(b"CONNECT", b"%s:%d" % (self.host, self.port))
  205. # Determine whether we need to set Proxy-Authorization headers
  206. if self.proxy_creds:
  207. # Set a Proxy-Authorization header
  208. self.sendHeader(
  209. b"Proxy-Authorization",
  210. self.proxy_creds.as_proxy_authorization_value(),
  211. )
  212. self.endHeaders()
  213. def handleStatus(self, version: bytes, status: bytes, message: bytes) -> None:
  214. logger.debug("Got Status: %s %s %s", status, message, version)
  215. if status != b"200":
  216. raise ProxyConnectError(f"Unexpected status on CONNECT: {status!s}")
  217. def handleEndHeaders(self) -> None:
  218. logger.debug("End Headers")
  219. self.on_connected.callback(None)
  220. def handleResponse(self, body: bytes) -> None:
  221. pass