brokerClient.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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 peristent 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) (*ClientOfferResponse, error) {
  118. requestPayload, err := MarshalClientOfferRequest(request)
  119. if err != nil {
  120. return nil, errors.Trace(err)
  121. }
  122. requestTimeout := common.ValueOrDefault(
  123. b.coordinator.OfferRequestTimeout(),
  124. clientOfferRequestTimeout)
  125. responsePayload, err := b.roundTrip(
  126. ctx, 0, requestTimeout, requestPayload)
  127. if err != nil {
  128. return nil, errors.Trace(err)
  129. }
  130. response, err := UnmarshalClientOfferResponse(responsePayload)
  131. if err != nil {
  132. return nil, errors.Trace(err)
  133. }
  134. return response, nil
  135. }
  136. // ProxyAnswer sends a ProxyAnswer request and returns the response.
  137. func (b *BrokerClient) ProxyAnswer(
  138. ctx context.Context,
  139. request *ProxyAnswerRequest) (*ProxyAnswerResponse, error) {
  140. requestPayload, err := MarshalProxyAnswerRequest(request)
  141. if err != nil {
  142. return nil, errors.Trace(err)
  143. }
  144. requestTimeout := common.ValueOrDefault(
  145. b.coordinator.AnswerRequestTimeout(),
  146. proxyAnswerRequestTimeout)
  147. responsePayload, err := b.roundTrip(
  148. ctx, 0, requestTimeout, requestPayload)
  149. if err != nil {
  150. return nil, errors.Trace(err)
  151. }
  152. response, err := UnmarshalProxyAnswerResponse(responsePayload)
  153. if err != nil {
  154. return nil, errors.Trace(err)
  155. }
  156. return response, nil
  157. }
  158. // ClientRelayedPacket sends a ClientRelayedPacket request and returns the
  159. // response.
  160. func (b *BrokerClient) ClientRelayedPacket(
  161. ctx context.Context,
  162. request *ClientRelayedPacketRequest) (*ClientRelayedPacketResponse, error) {
  163. requestPayload, err := MarshalClientRelayedPacketRequest(request)
  164. if err != nil {
  165. return nil, errors.Trace(err)
  166. }
  167. requestTimeout := common.ValueOrDefault(
  168. b.coordinator.RelayedPacketRequestTimeout(),
  169. clientRelayedPacketRequestTimeout)
  170. responsePayload, err := b.roundTrip(
  171. ctx, 0, requestTimeout, requestPayload)
  172. if err != nil {
  173. return nil, errors.Trace(err)
  174. }
  175. response, err := UnmarshalClientRelayedPacketResponse(responsePayload)
  176. if err != nil {
  177. return nil, errors.Trace(err)
  178. }
  179. return response, nil
  180. }
  181. func (b *BrokerClient) roundTrip(
  182. ctx context.Context,
  183. requestDelay time.Duration,
  184. requestTimeout time.Duration,
  185. request []byte) ([]byte, error) {
  186. // The round tripper may need to establish a transport-level connection;
  187. // or this may already be established.
  188. roundTripper, err := b.coordinator.BrokerClientRoundTripper()
  189. if err != nil {
  190. return nil, errors.Trace(err)
  191. }
  192. // InitiatorSessions.RoundTrip may make serveral round trips with
  193. // roundTripper in order to complete a session establishment handshake.
  194. //
  195. // When there's an active session, only a single round trip is required,
  196. // to exchange the application-level request and response.
  197. //
  198. // When a concurrent BrokerClient request is currently performing a
  199. // session handshake, InitiatorSessions.RoundTrip will await completion
  200. // of that handshake before sending the application-layer request.
  201. //
  202. // Note the waitToShareSession limitation, documented in
  203. // InitiatorSessions.RoundTrip: a new session must complete a full,
  204. // application-level round trip (e.g., ProxyAnnounce/ClientOffer), not
  205. // just the session handshake, before a session becomes ready to share.
  206. //
  207. // Retries are built in to InitiatorSessions.RoundTrip: if there's an
  208. // existing session and it's expired, there will be additional round
  209. // trips to establish a fresh session.
  210. //
  211. // While the round tripper is responsible for maintaining the
  212. // request/response association, the application-level request and
  213. // response are tagged with a RoundTripID which is checked to ensure the
  214. // association is maintained.
  215. //
  216. // InitiatorSessions.RoundTrip will apply sessionHandshakeTimeout to any
  217. // round trips required for Noise session handshakes; apply requestDelay
  218. // before the application-level request round trip; and apply
  219. // requestTimeout to the network round trip following the delay, if any.
  220. // Any time spent blocking on waitToShareSession is not included in
  221. // requestDelay or requestTimeout.
  222. waitToShareSession := true
  223. sessionHandshakeTimeout := common.ValueOrDefault(
  224. b.coordinator.SessionHandshakeRoundTripTimeout(),
  225. sessionHandshakeRoundTripTimeout)
  226. response, err := b.sessions.RoundTrip(
  227. ctx,
  228. roundTripper,
  229. b.coordinator.BrokerPublicKey(),
  230. b.coordinator.BrokerRootObfuscationSecret(),
  231. waitToShareSession,
  232. sessionHandshakeTimeout,
  233. requestDelay,
  234. requestTimeout,
  235. request)
  236. if err != nil {
  237. var failedError *RoundTripperFailedError
  238. failed := std_errors.As(err, &failedError)
  239. if failed {
  240. // The BrokerDialCoordinator provider should close the existing
  241. // BrokerClientRoundTripper and create a new RoundTripper to return
  242. // in the next BrokerClientRoundTripper call.
  243. //
  244. // The session will be closed, if necessary, by InitiatorSessions.
  245. // It's possible that the session remains valid and only the
  246. // RoundTripper transport layer needs to be reset.
  247. b.coordinator.BrokerClientRoundTripperFailed(roundTripper)
  248. }
  249. return nil, errors.Trace(err)
  250. }
  251. b.coordinator.BrokerClientRoundTripperSucceeded(roundTripper)
  252. return response, nil
  253. }