brokerClient.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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. std_errors "errors"
  23. "time"
  24. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  25. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  26. )
  27. // Timeouts should be aligned with Broker timeouts.
  28. const (
  29. sessionHandshakeRoundTripTimeout = 10 * time.Second
  30. proxyAnnounceRequestTimeout = 2 * time.Minute
  31. proxyAnswerRequestTimeout = 10 * time.Second
  32. clientOfferRequestTimeout = 10 * time.Second
  33. clientRelayedPacketRequestTimeout = 10 * time.Second
  34. )
  35. // BrokerClient is used to make requests to a broker.
  36. //
  37. // Each BrokerClient maintains a secure broker session. A BrokerClient and its
  38. // session may be used for multiple concurrent requests. Session key material
  39. // is provided by BrokerDialCoordinator and must remain static for the
  40. // lifetime of the BrokerClient.
  41. //
  42. // Round trips between the BrokerClient and broker are provided by
  43. // BrokerClientRoundTripper from BrokerDialCoordinator. The RoundTripper must
  44. // maintain the association between a request payload and the corresponding
  45. // response payload. The canonical RoundTripper is an HTTP client, with
  46. // HTTP/2 or HTTP/3 used to multiplex concurrent requests.
  47. //
  48. // When the BrokerDialCoordinator BrokerClientRoundTripperSucceeded call back
  49. // is invoked, the RoundTripper provider may mark the RoundTripper dial
  50. // properties for replay.
  51. //
  52. // When the BrokerDialCoordinator BrokerClientRoundTripperFailed call back is
  53. // invoked, the RoundTripper provider should clear any replay state and also
  54. // create a new RoundTripper to be returned from BrokerClientRoundTripper.
  55. //
  56. // BrokerClient does not have a Close operation. The user should close the
  57. // provided RoundTripper as appropriate.
  58. //
  59. // The secure session layer includes obfuscation that provides random padding
  60. // and uniformly random payload content. The RoundTripper is expected to add
  61. // its own obfuscation layer; for example, domain fronting.
  62. type BrokerClient struct {
  63. coordinator BrokerDialCoordinator
  64. sessions *InitiatorSessions
  65. }
  66. // NewBrokerClient initializes a new BrokerClient with the provided
  67. // BrokerDialCoordinator.
  68. func NewBrokerClient(coordinator BrokerDialCoordinator) (*BrokerClient, error) {
  69. // A client is expected to use an ephemeral key, and can return a
  70. // zero-value private key. Each proxy should use a persistent key, as the
  71. // corresponding public key is the proxy ID, which is used to credit the
  72. // proxy for its service.
  73. privateKey := coordinator.BrokerClientPrivateKey()
  74. if privateKey.IsZero() {
  75. var err error
  76. privateKey, err = GenerateSessionPrivateKey()
  77. if err != nil {
  78. return nil, errors.Trace(err)
  79. }
  80. }
  81. return &BrokerClient{
  82. coordinator: coordinator,
  83. sessions: NewInitiatorSessions(privateKey),
  84. }, nil
  85. }
  86. // GetBrokerDialCoordinator returns the BrokerDialCoordinator associated with
  87. // the BrokerClient.
  88. func (b *BrokerClient) GetBrokerDialCoordinator() BrokerDialCoordinator {
  89. return b.coordinator
  90. }
  91. // ProxyAnnounce sends a ProxyAnnounce request and returns the response.
  92. func (b *BrokerClient) ProxyAnnounce(
  93. ctx context.Context,
  94. requestDelay time.Duration,
  95. request *ProxyAnnounceRequest) (*ProxyAnnounceResponse, error) {
  96. requestPayload, err := MarshalProxyAnnounceRequest(request)
  97. if err != nil {
  98. return nil, errors.Trace(err)
  99. }
  100. requestTimeout := common.ValueOrDefault(
  101. b.coordinator.AnnounceRequestTimeout(),
  102. proxyAnnounceRequestTimeout)
  103. responsePayload, _, err := b.roundTrip(
  104. ctx, requestDelay, requestTimeout, requestPayload)
  105. if err != nil {
  106. return nil, errors.Trace(err)
  107. }
  108. response, err := UnmarshalProxyAnnounceResponse(responsePayload)
  109. if err != nil {
  110. return nil, errors.Trace(err)
  111. }
  112. return response, nil
  113. }
  114. // ClientOffer sends a ClientOffer request and returns the response.
  115. func (b *BrokerClient) ClientOffer(
  116. ctx context.Context,
  117. request *ClientOfferRequest,
  118. hasPersonalCompartmentIDs bool) (*ClientOfferResponse, error) {
  119. requestPayload, err := MarshalClientOfferRequest(request)
  120. if err != nil {
  121. return nil, errors.Trace(err)
  122. }
  123. var offerRequestTimeout time.Duration
  124. if hasPersonalCompartmentIDs {
  125. offerRequestTimeout = b.coordinator.OfferRequestPersonalTimeout()
  126. } else {
  127. offerRequestTimeout = b.coordinator.OfferRequestTimeout()
  128. }
  129. requestTimeout := common.ValueOrDefault(
  130. offerRequestTimeout,
  131. clientOfferRequestTimeout)
  132. responsePayload, roundTripper, err := b.roundTrip(
  133. ctx, 0, requestTimeout, requestPayload)
  134. if err != nil {
  135. return nil, errors.Trace(err)
  136. }
  137. response, err := UnmarshalClientOfferResponse(responsePayload)
  138. if err != nil {
  139. return nil, errors.Trace(err)
  140. }
  141. if response.NoMatch {
  142. // Signal the no match event, which may trigger broker rotation. As
  143. // with BrokerClientRoundTripperSucceeded/Failed callbacks, the
  144. // RoundTripper used is passed in to ensure the correct broker client
  145. // is reset.
  146. b.coordinator.BrokerClientNoMatch(roundTripper)
  147. }
  148. return response, nil
  149. }
  150. // ProxyAnswer sends a ProxyAnswer request and returns the response.
  151. func (b *BrokerClient) ProxyAnswer(
  152. ctx context.Context,
  153. request *ProxyAnswerRequest) (*ProxyAnswerResponse, error) {
  154. requestPayload, err := MarshalProxyAnswerRequest(request)
  155. if err != nil {
  156. return nil, errors.Trace(err)
  157. }
  158. requestTimeout := common.ValueOrDefault(
  159. b.coordinator.AnswerRequestTimeout(),
  160. proxyAnswerRequestTimeout)
  161. responsePayload, _, err := b.roundTrip(
  162. ctx, 0, requestTimeout, requestPayload)
  163. if err != nil {
  164. return nil, errors.Trace(err)
  165. }
  166. response, err := UnmarshalProxyAnswerResponse(responsePayload)
  167. if err != nil {
  168. return nil, errors.Trace(err)
  169. }
  170. return response, nil
  171. }
  172. // ClientRelayedPacket sends a ClientRelayedPacket request and returns the
  173. // response.
  174. func (b *BrokerClient) ClientRelayedPacket(
  175. ctx context.Context,
  176. request *ClientRelayedPacketRequest) (*ClientRelayedPacketResponse, error) {
  177. requestPayload, err := MarshalClientRelayedPacketRequest(request)
  178. if err != nil {
  179. return nil, errors.Trace(err)
  180. }
  181. requestTimeout := common.ValueOrDefault(
  182. b.coordinator.RelayedPacketRequestTimeout(),
  183. clientRelayedPacketRequestTimeout)
  184. responsePayload, _, err := b.roundTrip(
  185. ctx, 0, requestTimeout, requestPayload)
  186. if err != nil {
  187. return nil, errors.Trace(err)
  188. }
  189. response, err := UnmarshalClientRelayedPacketResponse(responsePayload)
  190. if err != nil {
  191. return nil, errors.Trace(err)
  192. }
  193. return response, nil
  194. }
  195. func (b *BrokerClient) roundTrip(
  196. ctx context.Context,
  197. requestDelay time.Duration,
  198. requestTimeout time.Duration,
  199. request []byte) ([]byte, RoundTripper, error) {
  200. // The round tripper may need to establish a transport-level connection;
  201. // or this may already be established.
  202. roundTripper, err := b.coordinator.BrokerClientRoundTripper()
  203. if err != nil {
  204. return nil, nil, errors.Trace(err)
  205. }
  206. // InitiatorSessions.RoundTrip may make serveral round trips with
  207. // roundTripper in order to complete a session establishment handshake.
  208. //
  209. // When there's an active session, only a single round trip is required,
  210. // to exchange the application-level request and response.
  211. //
  212. // When a concurrent BrokerClient request is currently performing a
  213. // session handshake, InitiatorSessions.RoundTrip will await completion
  214. // of that handshake before sending the application-layer request.
  215. //
  216. // This waitToShareSession functionality may be disabled with
  217. // BrokerDialCoordinator.DisableWaitToShareSession, in which case
  218. // concurrent Noise session handshakes may proceed; all concurrent
  219. // sessions/requests may complete successfully and the last session to be
  220. // established is retained by InitiatorSessions for reuse.
  221. //
  222. // Note the waitToShareSession isReadyToShare limitation, documented in
  223. // InitiatorSessions.RoundTrip: a new session must complete a full,
  224. // application-level round trip (e.g., ProxyAnnounce/ClientOffer), not
  225. // just the session handshake, before a session becomes ready to share.
  226. //
  227. // Retries are built in to InitiatorSessions.RoundTrip: if there's an
  228. // existing session and it's expired, there will be additional round
  229. // trips to establish a fresh session.
  230. //
  231. // While the round tripper is responsible for maintaining the
  232. // request/response association, the application-level request and
  233. // response are tagged with a RoundTripID which is checked to ensure the
  234. // association is maintained.
  235. //
  236. // InitiatorSessions.RoundTrip will apply sessionHandshakeTimeout to any
  237. // round trips required for Noise session handshakes; apply requestDelay
  238. // before the application-level request round trip; and apply
  239. // requestTimeout to the network round trip following the delay, if any.
  240. // Any time spent blocking on waitToShareSession is not included in
  241. // requestDelay or requestTimeout.
  242. waitToShareSession := !b.coordinator.DisableWaitToShareSession()
  243. sessionHandshakeTimeout := common.ValueOrDefault(
  244. b.coordinator.SessionHandshakeRoundTripTimeout(),
  245. sessionHandshakeRoundTripTimeout)
  246. response, err := b.sessions.RoundTrip(
  247. ctx,
  248. roundTripper,
  249. b.coordinator.BrokerPublicKey(),
  250. b.coordinator.BrokerRootObfuscationSecret(),
  251. waitToShareSession,
  252. sessionHandshakeTimeout,
  253. requestDelay,
  254. requestTimeout,
  255. request)
  256. if err != nil {
  257. var failedError *RoundTripperFailedError
  258. failed := std_errors.As(err, &failedError)
  259. if failed {
  260. // The BrokerDialCoordinator provider should close the existing
  261. // BrokerClientRoundTripper and create a new RoundTripper to return
  262. // in the next BrokerClientRoundTripper call.
  263. //
  264. // The session will be closed, if necessary, by InitiatorSessions.
  265. // It's possible that the session remains valid and only the
  266. // RoundTripper transport layer needs to be reset.
  267. b.coordinator.BrokerClientRoundTripperFailed(roundTripper)
  268. }
  269. return nil, nil, errors.Trace(err)
  270. }
  271. b.coordinator.BrokerClientRoundTripperSucceeded(roundTripper)
  272. return response, roundTripper, nil
  273. }