No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 
 
 

296 líneas
10 KiB

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