client.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. /*
  2. * Copyright (c) 2023, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package inproxy
  20. import (
  21. "context"
  22. "net"
  23. "sync"
  24. "time"
  25. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  26. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  27. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  28. )
  29. const (
  30. clientOfferRetryDelay = 1 * time.Second
  31. clientOfferRetryJitter = 0.3
  32. )
  33. // ClientConn is a network connection to an in-proxy, which is relayed to a
  34. // Psiphon server destination. Psiphon clients use a ClientConn in place of a
  35. // physical TCP or UDP socket connection, passing the ClientConn into tunnel
  36. // protocol dials. ClientConn implements both net.Conn and net.PacketConn,
  37. // with net.PacketConn's ReadFrom/WriteTo behaving as if connected to the
  38. // initial dial address.
  39. type ClientConn struct {
  40. config *ClientConfig
  41. brokerClient *BrokerClient
  42. webRTCConn *WebRTCConn
  43. connectionID ID
  44. relayMutex sync.Mutex
  45. initialRelayPacket []byte
  46. }
  47. // ClientConfig specifies the configuration for a ClientConn dial.
  48. type ClientConfig struct {
  49. // Logger is used to log events.
  50. Logger common.Logger
  51. // EnableWebRTCDebugLogging indicates whether to emit WebRTC debug logs.
  52. EnableWebRTCDebugLogging bool
  53. // BaseAPIParameters should be populated with Psiphon handshake metrics
  54. // parameters. These will be sent to and logger by the broker.
  55. BaseAPIParameters common.APIParameters
  56. // BrokerClient is the BrokerClient to use for broker API calls. The
  57. // BrokerClient may be shared with other client dials, allowing for
  58. // connection and session reuse.
  59. BrokerClient *BrokerClient
  60. // WebRTCDialCoordinator specifies specific WebRTC dial strategies and
  61. // settings; WebRTCDialCoordinator also facilities dial replay by
  62. // receiving callbacks when individual dial steps succeed or fail.
  63. WebRTCDialCoordinator WebRTCDialCoordinator
  64. // ReliableTransport specifies whether to use reliable delivery with the
  65. // underlying WebRTC DataChannel that relays the ClientConn traffic. When
  66. // using a ClientConn to proxy traffic that expects reliable delivery, as
  67. // if the physical network protocol were TCP, specify true. When using a
  68. // ClientConn to proxy traffic that expects unreliable delivery, such as
  69. // QUIC protocols expecting the physical network protocol UDP, specify
  70. // false.
  71. ReliableTransport bool
  72. // DialNetworkProtocol specifies whether the in-proxy will relay TCP or UDP
  73. // traffic.
  74. DialNetworkProtocol NetworkProtocol
  75. // DialAddress is the host:port destination network address the in-proxy
  76. // will relay traffic to.
  77. DialAddress string
  78. // PackedDestinationServerEntry is a signed Psiphon server entry
  79. // corresponding to the destination dial address. This signed server
  80. // entry is sent to the broker, which will use it to validate that the
  81. // server is a valid in-proxy destination.
  82. //
  83. // The expected format is CBOR-encoded protoco.PackedServerEntryFields,
  84. // with the caller invoking ServerEntryFields.RemoveUnsignedFields to
  85. // prune local, unnsigned fields before sending.
  86. PackedDestinationServerEntry []byte
  87. }
  88. // DialClient establishes an in-proxy connection for relaying traffic to the
  89. // specified destination. DialClient first contacts the broker and initiates
  90. // an in-proxy pairing. config.BrokerClient may be shared by multiple dials,
  91. // and may have a preexisting connection and session with the broker.
  92. func DialClient(
  93. ctx context.Context,
  94. config *ClientConfig) (retConn *ClientConn, retErr error) {
  95. // Reset and configure port mapper component, as required. See
  96. // initPortMapper comment.
  97. initPortMapper(config.WebRTCDialCoordinator)
  98. // Future improvements:
  99. //
  100. // - The broker connection and session, when not already established,
  101. // could be established concurrent with the WebRTC offer setup
  102. // (STUN/ICE gathering).
  103. //
  104. // - The STUN state used for NAT discovery could be reused for the WebRTC
  105. // dial.
  106. //
  107. // - A subsequent WebRTC offer setup could be run concurrent with the
  108. // client offer request, in case that request or WebRTC connections
  109. // fails, so that the offer is immediately ready for a retry.
  110. if config.WebRTCDialCoordinator.DiscoverNAT() {
  111. // NAT discovery, using the RFC5780 algorithms is optional and
  112. // conditional on the DiscoverNAT flag. Discovery is performed
  113. // synchronously, so that NAT topology metrics can be reported to the
  114. // broker in the ClientOffer request. For clients, NAT discovery is
  115. // intended to be performed at a low sampling rate, since the RFC5780
  116. // traffic may be unusual(differs from standard STUN requests for
  117. // ICE) and since this step delays the dial. Clients should to cache
  118. // their NAT discovery outcomes, associated with the current network
  119. // by network ID, so metrics can be reported even without a discovery
  120. // step; this is facilitated by WebRTCDialCoordinator.
  121. //
  122. // NAT topology metrics are used by the broker to optimize client and
  123. // in-proxy matching.
  124. //
  125. // For client NAT discovery, port mapping type discovery is skipped
  126. // since port mappings are attempted when preparing the WebRTC offer,
  127. // which also happens before the ClientOffer request.
  128. NATDiscover(
  129. ctx,
  130. &NATDiscoverConfig{
  131. Logger: config.Logger,
  132. WebRTCDialCoordinator: config.WebRTCDialCoordinator,
  133. SkipPortMapping: true,
  134. })
  135. }
  136. var result *clientWebRTCDialResult
  137. for {
  138. // Repeatedly try to establish in-proxy/WebRTC connection until the
  139. // dial context is canceled or times out.
  140. //
  141. // If a broker request fails, the WebRTCDialCoordinator
  142. // BrokerClientRoundTripperFailed callback will be invoked, so the
  143. // Psiphon client will have an opportunity to select new broker
  144. // connection parameters before a retry. Similarly, when STUN servers
  145. // fail, WebRTCDialCoordinator STUNServerAddressFailed will be
  146. // invoked, giving the Psiphon client an opportunity to select new
  147. // STUN server parameter -- although, in this failure case, the
  148. // WebRTC connection attemp can succeed with other ICE candidates or
  149. // no ICE candidates.
  150. err := ctx.Err()
  151. if err != nil {
  152. return nil, errors.Trace(err)
  153. }
  154. var retry bool
  155. result, retry, err = dialClientWebRTCConn(ctx, config)
  156. if err == nil {
  157. break
  158. }
  159. if retry {
  160. config.Logger.WithTraceFields(common.LogFields{"error": err}).Warning("dial failed")
  161. // This delay is intended avoid overloading the broker with
  162. // repeated requests. A jitter is applied to mitigate a traffic
  163. // fingerprint.
  164. brokerCoordinator := config.BrokerClient.GetBrokerDialCoordinator()
  165. common.SleepWithJitter(
  166. ctx,
  167. common.ValueOrDefault(brokerCoordinator.OfferRetryDelay(), clientOfferRetryDelay),
  168. common.ValueOrDefault(brokerCoordinator.OfferRetryJitter(), clientOfferRetryJitter))
  169. continue
  170. }
  171. return nil, errors.Trace(err)
  172. }
  173. return &ClientConn{
  174. config: config,
  175. webRTCConn: result.conn,
  176. connectionID: result.connectionID,
  177. initialRelayPacket: result.relayPacket,
  178. }, nil
  179. }
  180. // GetConnectionID returns the in-proxy connection ID, which the client should
  181. // include with its Psiphon handshake parameters.
  182. func (conn *ClientConn) GetConnectionID() ID {
  183. return conn.connectionID
  184. }
  185. // InitialRelayPacket returns the initial packet in the broker->server
  186. // messaging session. The client must relay these packets to facilitate this
  187. // message exchange. Session security ensures clients cannot decrypt, modify,
  188. // or replay these session packets. The Psiphon client will sent the initial
  189. // packet as a parameter in the Psiphon server handshake request.
  190. func (conn *ClientConn) InitialRelayPacket() []byte {
  191. conn.relayMutex.Lock()
  192. defer conn.relayMutex.Unlock()
  193. relayPacket := conn.initialRelayPacket
  194. conn.initialRelayPacket = nil
  195. return relayPacket
  196. }
  197. // RelayPacket takes any server->broker messaging session packets the client
  198. // receives and relays them back to the broker. RelayPacket returns the next
  199. // broker->server packet, if any, or nil when the message exchange is
  200. // complete. Psiphon clients receive a server->broker packet in the Psiphon
  201. // server handshake response and exchange additional packets in a
  202. // post-handshake Psiphon server request.
  203. //
  204. // If RelayPacket fails, the client should close the ClientConn and redial.
  205. func (conn *ClientConn) RelayPacket(
  206. ctx context.Context, in []byte) ([]byte, error) {
  207. // Future improvement: the client relaying these packets back to the
  208. // broker is potentially an inter-flow fingerprint, alternating between
  209. // the WebRTC flow and the client's broker connection. It may be possible
  210. // to avoid this by having the client connect to the broker via the
  211. // tunnel, resuming its broker session and relaying any further packets.
  212. // Limitation: here, this mutex only ensures that this ClientConn doesn't
  213. // make concurrent ClientRelayedPacket requests. The client must still
  214. // ensure that the packets are delivered in the correct relay sequence.
  215. conn.relayMutex.Lock()
  216. defer conn.relayMutex.Unlock()
  217. // ClientRelayedPacket applies
  218. // BrokerDialCoordinator.RelayedPacketRequestTimeout as the request
  219. // timeout.
  220. relayResponse, err := conn.config.BrokerClient.ClientRelayedPacket(
  221. ctx,
  222. &ClientRelayedPacketRequest{
  223. ConnectionID: conn.connectionID,
  224. PacketFromServer: in,
  225. })
  226. if err != nil {
  227. return nil, errors.Trace(err)
  228. }
  229. return relayResponse.PacketToServer, nil
  230. }
  231. type clientWebRTCDialResult struct {
  232. conn *WebRTCConn
  233. connectionID ID
  234. relayPacket []byte
  235. }
  236. func dialClientWebRTCConn(
  237. ctx context.Context,
  238. config *ClientConfig) (retResult *clientWebRTCDialResult, retRetry bool, retErr error) {
  239. // Initialize the WebRTC offer
  240. doTLSRandomization := config.WebRTCDialCoordinator.DoDTLSRandomization()
  241. trafficShapingParameters := config.WebRTCDialCoordinator.DataChannelTrafficShapingParameters()
  242. clientRootObfuscationSecret := config.WebRTCDialCoordinator.ClientRootObfuscationSecret()
  243. webRTCConn, SDP, SDPMetrics, err := NewWebRTCConnWithOffer(
  244. ctx, &WebRTCConfig{
  245. Logger: config.Logger,
  246. EnableDebugLogging: config.EnableWebRTCDebugLogging,
  247. WebRTCDialCoordinator: config.WebRTCDialCoordinator,
  248. ClientRootObfuscationSecret: clientRootObfuscationSecret,
  249. DoDTLSRandomization: doTLSRandomization,
  250. TrafficShapingParameters: trafficShapingParameters,
  251. ReliableTransport: config.ReliableTransport,
  252. })
  253. if err != nil {
  254. return nil, true, errors.Trace(err)
  255. }
  256. defer func() {
  257. // Cleanup on early return
  258. if retErr != nil {
  259. webRTCConn.Close()
  260. }
  261. }()
  262. // Send the ClientOffer request to the broker
  263. brokerCoordinator := config.BrokerClient.GetBrokerDialCoordinator()
  264. packedBaseParams, err := protocol.EncodePackedAPIParameters(config.BaseAPIParameters)
  265. if err != nil {
  266. return nil, false, errors.Trace(err)
  267. }
  268. // Here, WebRTCDialCoordinator.NATType may be populated from discovery, or
  269. // replayed from a previous run on the same network ID.
  270. // WebRTCDialCoordinator.PortMappingTypes may be populated via
  271. // newWebRTCConnWithOffer.
  272. // ClientOffer applies BrokerDialCoordinator.OfferRequestTimeout as the
  273. // request timeout.
  274. offerResponse, err := config.BrokerClient.ClientOffer(
  275. ctx,
  276. &ClientOfferRequest{
  277. Metrics: &ClientMetrics{
  278. BaseAPIParameters: packedBaseParams,
  279. ProxyProtocolVersion: ProxyProtocolVersion1,
  280. NATType: config.WebRTCDialCoordinator.NATType(),
  281. PortMappingTypes: config.WebRTCDialCoordinator.PortMappingTypes(),
  282. },
  283. CommonCompartmentIDs: brokerCoordinator.CommonCompartmentIDs(),
  284. PersonalCompartmentIDs: brokerCoordinator.PersonalCompartmentIDs(),
  285. ClientOfferSDP: SDP,
  286. ICECandidateTypes: SDPMetrics.ICECandidateTypes,
  287. ClientRootObfuscationSecret: clientRootObfuscationSecret,
  288. DoDTLSRandomization: doTLSRandomization,
  289. TrafficShapingParameters: trafficShapingParameters,
  290. PackedDestinationServerEntry: config.PackedDestinationServerEntry,
  291. NetworkProtocol: config.DialNetworkProtocol,
  292. DestinationAddress: config.DialAddress,
  293. })
  294. if err != nil {
  295. return nil, false, errors.Trace(err)
  296. }
  297. if offerResponse.NoMatch {
  298. return nil, false, errors.TraceNew("no proxy match")
  299. }
  300. if offerResponse.SelectedProxyProtocolVersion != ProxyProtocolVersion1 {
  301. return nil, false, errors.Tracef(
  302. "Unsupported proxy protocol version: %d",
  303. offerResponse.SelectedProxyProtocolVersion)
  304. }
  305. // Establish the WebRTC DataChannel connection
  306. err = webRTCConn.SetRemoteSDP(offerResponse.ProxyAnswerSDP)
  307. if err != nil {
  308. return nil, true, errors.Trace(err)
  309. }
  310. awaitDataChannelCtx, awaitDataChannelCancelFunc := context.WithTimeout(
  311. ctx,
  312. common.ValueOrDefault(
  313. config.WebRTCDialCoordinator.WebRTCAwaitDataChannelTimeout(), dataChannelAwaitTimeout))
  314. defer awaitDataChannelCancelFunc()
  315. err = webRTCConn.AwaitInitialDataChannel(awaitDataChannelCtx)
  316. if err != nil {
  317. return nil, true, errors.Trace(err)
  318. }
  319. return &clientWebRTCDialResult{
  320. conn: webRTCConn,
  321. connectionID: offerResponse.ConnectionID,
  322. relayPacket: offerResponse.RelayPacketToServer,
  323. }, false, nil
  324. }
  325. // GetMetrics implements the common.MetricsSource interface.
  326. func (conn *ClientConn) GetMetrics() common.LogFields {
  327. return conn.webRTCConn.GetMetrics()
  328. }
  329. func (conn *ClientConn) Close() error {
  330. return errors.Trace(conn.webRTCConn.Close())
  331. }
  332. func (conn *ClientConn) IsClosed() bool {
  333. return conn.webRTCConn.IsClosed()
  334. }
  335. func (conn *ClientConn) Read(p []byte) (int, error) {
  336. n, err := conn.webRTCConn.Read(p)
  337. return n, errors.Trace(err)
  338. }
  339. // Write relays p through the in-proxy connection. len(p) should be under
  340. // 32K.
  341. func (conn *ClientConn) Write(p []byte) (int, error) {
  342. n, err := conn.webRTCConn.Write(p)
  343. return n, errors.Trace(err)
  344. }
  345. func (conn *ClientConn) LocalAddr() net.Addr {
  346. return conn.webRTCConn.LocalAddr()
  347. }
  348. func (conn *ClientConn) RemoteAddr() net.Addr {
  349. return conn.webRTCConn.RemoteAddr()
  350. }
  351. func (conn *ClientConn) SetDeadline(t time.Time) error {
  352. return conn.webRTCConn.SetDeadline(t)
  353. }
  354. func (conn *ClientConn) SetReadDeadline(t time.Time) error {
  355. return conn.webRTCConn.SetReadDeadline(t)
  356. }
  357. func (conn *ClientConn) SetWriteDeadline(t time.Time) error {
  358. // Limitation: this is a workaround; webRTCConn doesn't support
  359. // SetWriteDeadline, but common/quic calls SetWriteDeadline on
  360. // net.PacketConns to avoid hanging on EAGAIN when the conn is an actual
  361. // UDP socket. See the comment in common/quic.writeTimeoutUDPConn. In
  362. // this case, the conn is not a UDP socket and that particular
  363. // SetWriteDeadline use case doesn't apply. Silently ignore the deadline
  364. // and report no error.
  365. return nil
  366. }
  367. func (conn *ClientConn) ReadFrom(b []byte) (int, net.Addr, error) {
  368. n, err := conn.webRTCConn.Read(b)
  369. return n, conn.webRTCConn.RemoteAddr(), err
  370. }
  371. func (conn *ClientConn) WriteTo(b []byte, _ net.Addr) (int, error) {
  372. n, err := conn.webRTCConn.Write(b)
  373. return n, err
  374. }