brokerClient.go 11 KB

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