client.go 18 KB

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