client.go 17 KB

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