client.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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. // MustUpgrade is a callback that is invoked when a MustUpgrade flag is
  94. // received from the broker. When MustUpgrade is received, the client
  95. // should be stopped and the user should be prompted to upgrade before
  96. // restarting the client.
  97. //
  98. // In Psiphon, MustUpgrade may be ignored when not running in
  99. // in-proxy-only personal pairing mode, as other tunnel protocols remain
  100. // available.
  101. MustUpgrade func()
  102. }
  103. // DialClient establishes an in-proxy connection for relaying traffic to the
  104. // specified destination. DialClient first contacts the broker and initiates
  105. // an in-proxy pairing. config.BrokerClient may be shared by multiple dials,
  106. // and may have a preexisting connection and session with the broker.
  107. func DialClient(
  108. ctx context.Context,
  109. config *ClientConfig) (retConn *ClientConn, retErr error) {
  110. // Configure the value returned by ClientConn.RemoteAddr. If no
  111. // config.RemoteAddrOverride is specified, RemoteAddr will return a
  112. // zero-value, non-nil net.Addr. The underlying webRTCConn.RemoteAddr
  113. // returns only nil.
  114. var remoteAddr net.Addr
  115. var addrPort netip.AddrPort
  116. if config.RemoteAddrOverride != "" {
  117. // ParseAddrPort does not perform any domain resolution. The addr
  118. // portion must be an IP address.
  119. var err error
  120. addrPort, err = netip.ParseAddrPort(config.RemoteAddrOverride)
  121. if err != nil {
  122. return nil, errors.Trace(err)
  123. }
  124. }
  125. switch config.DialNetworkProtocol {
  126. case NetworkProtocolTCP:
  127. remoteAddr = net.TCPAddrFromAddrPort(addrPort)
  128. case NetworkProtocolUDP:
  129. remoteAddr = net.UDPAddrFromAddrPort(addrPort)
  130. default:
  131. return nil, errors.TraceNew("unexpected DialNetworkProtocol")
  132. }
  133. // Reset and configure port mapper component, as required. See
  134. // initPortMapper comment.
  135. initPortMapper(config.WebRTCDialCoordinator)
  136. // Future improvements:
  137. //
  138. // - The broker connection and session, when not already established,
  139. // could be established concurrent with the WebRTC offer setup
  140. // (STUN/ICE gathering).
  141. //
  142. // - The STUN state used for NAT discovery could be reused for the WebRTC
  143. // dial.
  144. //
  145. // - A subsequent WebRTC offer setup could be run concurrent with the
  146. // client offer request, in case that request or WebRTC connections
  147. // fails, so that the offer is immediately ready for a retry.
  148. if config.WebRTCDialCoordinator.DiscoverNAT() {
  149. // NAT discovery, using the RFC5780 algorithms is optional and
  150. // conditional on the DiscoverNAT flag. Discovery is performed
  151. // synchronously, so that NAT topology metrics can be reported to the
  152. // broker in the ClientOffer request. For clients, NAT discovery is
  153. // intended to be performed at a low sampling rate, since the RFC5780
  154. // traffic may be unusual(differs from standard STUN requests for
  155. // ICE) and since this step delays the dial. Clients should to cache
  156. // their NAT discovery outcomes, associated with the current network
  157. // by network ID, so metrics can be reported even without a discovery
  158. // step; this is facilitated by WebRTCDialCoordinator.
  159. //
  160. // NAT topology metrics are used by the broker to optimize client and
  161. // in-proxy matching.
  162. //
  163. // For client NAT discovery, port mapping type discovery is skipped
  164. // since port mappings are attempted when preparing the WebRTC offer,
  165. // which also happens before the ClientOffer request.
  166. NATDiscover(
  167. ctx,
  168. &NATDiscoverConfig{
  169. Logger: config.Logger,
  170. WebRTCDialCoordinator: config.WebRTCDialCoordinator,
  171. SkipPortMapping: true,
  172. })
  173. }
  174. var result *clientWebRTCDialResult
  175. for {
  176. // Repeatedly try to establish in-proxy/WebRTC connection until the
  177. // dial context is canceled or times out.
  178. //
  179. // If a broker request fails, the WebRTCDialCoordinator
  180. // BrokerClientRoundTripperFailed callback will be invoked, so the
  181. // Psiphon client will have an opportunity to select new broker
  182. // connection parameters before a retry. Similarly, when STUN servers
  183. // fail, WebRTCDialCoordinator STUNServerAddressFailed will be
  184. // invoked, giving the Psiphon client an opportunity to select new
  185. // STUN server parameter -- although, in this failure case, the
  186. // WebRTC connection attempt can succeed with other ICE candidates or
  187. // no ICE candidates.
  188. err := ctx.Err()
  189. if err != nil {
  190. return nil, errors.Trace(err)
  191. }
  192. var retry bool
  193. result, retry, err = dialClientWebRTCConn(ctx, config)
  194. if err == nil {
  195. break
  196. }
  197. if retry {
  198. config.Logger.WithTraceFields(common.LogFields{"error": err}).Warning("dial failed")
  199. // This delay is intended avoid overloading the broker with
  200. // repeated requests. A jitter is applied to mitigate a traffic
  201. // fingerprint.
  202. brokerCoordinator := config.BrokerClient.GetBrokerDialCoordinator()
  203. common.SleepWithJitter(
  204. ctx,
  205. common.ValueOrDefault(brokerCoordinator.OfferRetryDelay(), clientOfferRetryDelay),
  206. common.ValueOrDefault(brokerCoordinator.OfferRetryJitter(), clientOfferRetryJitter))
  207. continue
  208. }
  209. return nil, errors.Trace(err)
  210. }
  211. return &ClientConn{
  212. config: config,
  213. webRTCConn: result.conn,
  214. connectionID: result.connectionID,
  215. initialRelayPacket: result.relayPacket,
  216. remoteAddr: remoteAddr,
  217. }, nil
  218. }
  219. // GetConnectionID returns the in-proxy connection ID, which the client should
  220. // include with its Psiphon handshake parameters.
  221. func (conn *ClientConn) GetConnectionID() ID {
  222. return conn.connectionID
  223. }
  224. // InitialRelayPacket returns the initial packet in the broker->server
  225. // messaging session. The client must relay these packets to facilitate this
  226. // message exchange. Session security ensures clients cannot decrypt, modify,
  227. // or replay these session packets. The Psiphon client will sent the initial
  228. // packet as a parameter in the Psiphon server handshake request.
  229. func (conn *ClientConn) InitialRelayPacket() []byte {
  230. conn.relayMutex.Lock()
  231. defer conn.relayMutex.Unlock()
  232. relayPacket := conn.initialRelayPacket
  233. conn.initialRelayPacket = nil
  234. return relayPacket
  235. }
  236. // RelayPacket takes any server->broker messaging session packets the client
  237. // receives and relays them back to the broker. RelayPacket returns the next
  238. // broker->server packet, if any, or nil when the message exchange is
  239. // complete. Psiphon clients receive a server->broker packet in the Psiphon
  240. // server handshake response and exchange additional packets in a
  241. // post-handshake Psiphon server request.
  242. //
  243. // If RelayPacket fails, the client should close the ClientConn and redial.
  244. func (conn *ClientConn) RelayPacket(
  245. ctx context.Context, in []byte) ([]byte, error) {
  246. // Future improvement: the client relaying these packets back to the
  247. // broker is potentially an inter-flow fingerprint, alternating between
  248. // the WebRTC flow and the client's broker connection. It may be possible
  249. // to avoid this by having the client connect to the broker via the
  250. // tunnel, resuming its broker session and relaying any further packets.
  251. // Limitation: here, this mutex only ensures that this ClientConn doesn't
  252. // make concurrent ClientRelayedPacket requests. The client must still
  253. // ensure that the packets are delivered in the correct relay sequence.
  254. conn.relayMutex.Lock()
  255. defer conn.relayMutex.Unlock()
  256. // ClientRelayedPacket applies
  257. // BrokerDialCoordinator.RelayedPacketRequestTimeout as the request
  258. // timeout.
  259. relayResponse, err := conn.config.BrokerClient.ClientRelayedPacket(
  260. ctx,
  261. &ClientRelayedPacketRequest{
  262. ConnectionID: conn.connectionID,
  263. PacketFromServer: in,
  264. })
  265. if err != nil {
  266. return nil, errors.Trace(err)
  267. }
  268. return relayResponse.PacketToServer, nil
  269. }
  270. type clientWebRTCDialResult struct {
  271. conn *webRTCConn
  272. connectionID ID
  273. relayPacket []byte
  274. }
  275. func dialClientWebRTCConn(
  276. ctx context.Context,
  277. config *ClientConfig) (retResult *clientWebRTCDialResult, retRetry bool, retErr error) {
  278. brokerCoordinator := config.BrokerClient.GetBrokerDialCoordinator()
  279. personalCompartmentIDs := brokerCoordinator.PersonalCompartmentIDs()
  280. // In personal pairing mode, RFC 1918/4193 private IP addresses are
  281. // included in SDPs.
  282. hasPersonalCompartmentIDs := len(personalCompartmentIDs) > 0
  283. // Initialize the WebRTC offer
  284. doTLSRandomization := config.WebRTCDialCoordinator.DoDTLSRandomization()
  285. trafficShapingParameters := config.WebRTCDialCoordinator.DataChannelTrafficShapingParameters()
  286. clientRootObfuscationSecret := config.WebRTCDialCoordinator.ClientRootObfuscationSecret()
  287. webRTCConn, SDP, SDPMetrics, err := newWebRTCConnWithOffer(
  288. ctx, &webRTCConfig{
  289. Logger: config.Logger,
  290. EnableDebugLogging: config.EnableWebRTCDebugLogging,
  291. WebRTCDialCoordinator: config.WebRTCDialCoordinator,
  292. ClientRootObfuscationSecret: clientRootObfuscationSecret,
  293. DoDTLSRandomization: doTLSRandomization,
  294. TrafficShapingParameters: trafficShapingParameters,
  295. ReliableTransport: config.ReliableTransport,
  296. },
  297. hasPersonalCompartmentIDs)
  298. if err != nil {
  299. return nil, true, errors.Trace(err)
  300. }
  301. defer func() {
  302. // Cleanup on early return
  303. if retErr != nil {
  304. webRTCConn.Close()
  305. }
  306. }()
  307. // Send the ClientOffer request to the broker
  308. packedBaseParams, err := protocol.EncodePackedAPIParameters(config.BaseAPIParameters)
  309. if err != nil {
  310. return nil, false, errors.Trace(err)
  311. }
  312. // Here, WebRTCDialCoordinator.NATType may be populated from discovery, or
  313. // replayed from a previous run on the same network ID.
  314. // WebRTCDialCoordinator.PortMappingTypes may be populated via
  315. // newWebRTCConnWithOffer.
  316. // ClientOffer applies BrokerDialCoordinator.OfferRequestTimeout as the
  317. // request timeout.
  318. offerResponse, err := config.BrokerClient.ClientOffer(
  319. ctx,
  320. &ClientOfferRequest{
  321. Metrics: &ClientMetrics{
  322. BaseAPIParameters: packedBaseParams,
  323. ProxyProtocolVersion: proxyProtocolVersion,
  324. NATType: config.WebRTCDialCoordinator.NATType(),
  325. PortMappingTypes: config.WebRTCDialCoordinator.PortMappingTypes(),
  326. },
  327. CommonCompartmentIDs: brokerCoordinator.CommonCompartmentIDs(),
  328. PersonalCompartmentIDs: personalCompartmentIDs,
  329. ClientOfferSDP: SDP,
  330. ICECandidateTypes: SDPMetrics.iceCandidateTypes,
  331. ClientRootObfuscationSecret: clientRootObfuscationSecret,
  332. DoDTLSRandomization: doTLSRandomization,
  333. TrafficShapingParameters: trafficShapingParameters,
  334. PackedDestinationServerEntry: config.PackedDestinationServerEntry,
  335. NetworkProtocol: config.DialNetworkProtocol,
  336. DestinationAddress: config.DialAddress,
  337. })
  338. if err != nil {
  339. return nil, false, errors.Trace(err)
  340. }
  341. // MustUpgrade has precedence over other cases to ensure the callback is
  342. // invoked. No retry when rate/entry limited or must upgrade; do retry on
  343. // no-match, as a match may soon appear.
  344. if offerResponse.MustUpgrade {
  345. if config.MustUpgrade != nil {
  346. config.MustUpgrade()
  347. }
  348. return nil, false, errors.TraceNew("must upgrade")
  349. } else if offerResponse.Limited {
  350. return nil, false, errors.TraceNew("limited")
  351. } else if offerResponse.NoMatch {
  352. return nil, true, errors.TraceNew("no match")
  353. }
  354. if offerResponse.SelectedProxyProtocolVersion < MinimumProxyProtocolVersion ||
  355. offerResponse.SelectedProxyProtocolVersion > proxyProtocolVersion {
  356. return nil, false, errors.Tracef(
  357. "Unsupported proxy protocol version: %d",
  358. offerResponse.SelectedProxyProtocolVersion)
  359. }
  360. // Establish the WebRTC DataChannel connection
  361. err = webRTCConn.SetRemoteSDP(
  362. offerResponse.ProxyAnswerSDP, hasPersonalCompartmentIDs)
  363. if err != nil {
  364. return nil, true, errors.Trace(err)
  365. }
  366. awaitDataChannelCtx, awaitDataChannelCancelFunc := context.WithTimeout(
  367. ctx,
  368. common.ValueOrDefault(
  369. config.WebRTCDialCoordinator.WebRTCAwaitDataChannelTimeout(), dataChannelAwaitTimeout))
  370. defer awaitDataChannelCancelFunc()
  371. err = webRTCConn.AwaitInitialDataChannel(awaitDataChannelCtx)
  372. if err != nil {
  373. return nil, true, errors.Trace(err)
  374. }
  375. return &clientWebRTCDialResult{
  376. conn: webRTCConn,
  377. connectionID: offerResponse.ConnectionID,
  378. relayPacket: offerResponse.RelayPacketToServer,
  379. }, false, nil
  380. }
  381. // GetMetrics implements the common.MetricsSource interface.
  382. func (conn *ClientConn) GetMetrics() common.LogFields {
  383. return conn.webRTCConn.GetMetrics()
  384. }
  385. func (conn *ClientConn) Close() error {
  386. return errors.Trace(conn.webRTCConn.Close())
  387. }
  388. func (conn *ClientConn) IsClosed() bool {
  389. return conn.webRTCConn.IsClosed()
  390. }
  391. func (conn *ClientConn) Read(p []byte) (int, error) {
  392. n, err := conn.webRTCConn.Read(p)
  393. return n, errors.Trace(err)
  394. }
  395. // Write relays p through the in-proxy connection. len(p) should be under
  396. // 32K.
  397. func (conn *ClientConn) Write(p []byte) (int, error) {
  398. n, err := conn.webRTCConn.Write(p)
  399. return n, errors.Trace(err)
  400. }
  401. func (conn *ClientConn) LocalAddr() net.Addr {
  402. return conn.webRTCConn.LocalAddr()
  403. }
  404. func (conn *ClientConn) RemoteAddr() net.Addr {
  405. // Do not return conn.webRTCConn.RemoteAddr(), which is always nil.
  406. return conn.remoteAddr
  407. }
  408. func (conn *ClientConn) SetDeadline(t time.Time) error {
  409. return conn.webRTCConn.SetDeadline(t)
  410. }
  411. func (conn *ClientConn) SetReadDeadline(t time.Time) error {
  412. return conn.webRTCConn.SetReadDeadline(t)
  413. }
  414. func (conn *ClientConn) SetWriteDeadline(t time.Time) error {
  415. // Limitation: this is a workaround; webRTCConn doesn't support
  416. // SetWriteDeadline, but common/quic calls SetWriteDeadline on
  417. // net.PacketConns to avoid hanging on EAGAIN when the conn is an actual
  418. // UDP socket. See the comment in common/quic.writeTimeoutUDPConn. In
  419. // this case, the conn is not a UDP socket and that particular
  420. // SetWriteDeadline use case doesn't apply. Silently ignore the deadline
  421. // and report no error.
  422. return nil
  423. }
  424. func (conn *ClientConn) ReadFrom(b []byte) (int, net.Addr, error) {
  425. n, err := conn.webRTCConn.Read(b)
  426. return n, conn.webRTCConn.RemoteAddr(), err
  427. }
  428. func (conn *ClientConn) WriteTo(b []byte, _ net.Addr) (int, error) {
  429. n, err := conn.webRTCConn.Write(b)
  430. return n, err
  431. }