brokerClient.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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. "time"
  23. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  24. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  25. )
  26. // Timeouts should be aligned with Broker timeouts.
  27. const (
  28. proxyAnnounceRequestTimeout = 2 * time.Minute
  29. proxyAnswerRequestTimeout = 10 * time.Second
  30. clientOfferRequestTimeout = 10 * time.Second
  31. clientRelayedPacketRequestTimeout = 10 * time.Second
  32. )
  33. // BrokerClient is used to make requests to a broker.
  34. //
  35. // Each BrokerClient maintains a secure broker session. A BrokerClient and its
  36. // session may be used for multiple concurrent requests. Session key material
  37. // is provided by BrokerDialCoordinator and must remain static for the
  38. // lifetime of the BrokerClient.
  39. //
  40. // Round trips between the BrokerClient and broker are provided by
  41. // BrokerClientRoundTripper from BrokerDialCoordinator. The RoundTripper must
  42. // maintain the association between a request payload and the corresponding
  43. // response payload. The canonical RoundTripper is an HTTP client, with
  44. // HTTP/2 or HTTP/3 used to multiplex concurrent requests.
  45. //
  46. // When the BrokerDialCoordinator BrokerClientRoundTripperSucceeded call back
  47. // is invoked, the RoundTripper provider may mark the RoundTripper dial
  48. // properties for replay.
  49. //
  50. // When the BrokerDialCoordinator BrokerClientRoundTripperFailed call back is
  51. // invoked, the RoundTripper provider should clear any replay state and also
  52. // create a new RoundTripper to be returned from BrokerClientRoundTripper.
  53. //
  54. // BrokerClient does not have a Close operation. The user should close the
  55. // provided RoundTripper as appropriate.
  56. //
  57. // The secure session layer includes obfuscation that provides random padding
  58. // and uniformly random payload content. The RoundTripper is expected to add
  59. // its own obfuscation layer; for example, domain fronting.
  60. type BrokerClient struct {
  61. coordinator BrokerDialCoordinator
  62. sessions *InitiatorSessions
  63. }
  64. // NewBrokerClient initializes a new BrokerClient with the provided
  65. // BrokerDialCoordinator.
  66. func NewBrokerClient(coordinator BrokerDialCoordinator) (*BrokerClient, error) {
  67. // A client is expected to use an ephemeral key, and can return a
  68. // zero-value private key. Each proxy should use a peristent key, as the
  69. // corresponding public key is the proxy ID, which is used to credit the
  70. // proxy for its service.
  71. privateKey := coordinator.BrokerClientPrivateKey()
  72. if privateKey.IsZero() {
  73. var err error
  74. privateKey, err = GenerateSessionPrivateKey()
  75. if err != nil {
  76. return nil, errors.Trace(err)
  77. }
  78. }
  79. return &BrokerClient{
  80. coordinator: coordinator,
  81. sessions: NewInitiatorSessions(privateKey),
  82. }, nil
  83. }
  84. // GetBrokerDialCoordinator returns the BrokerDialCoordinator associated with
  85. // the BrokerClient.
  86. func (b *BrokerClient) GetBrokerDialCoordinator() BrokerDialCoordinator {
  87. return b.coordinator
  88. }
  89. // ProxyAnnounce sends a ProxyAnnounce request and returns the response.
  90. func (b *BrokerClient) ProxyAnnounce(
  91. ctx context.Context,
  92. request *ProxyAnnounceRequest) (*ProxyAnnounceResponse, error) {
  93. requestPayload, err := MarshalProxyAnnounceRequest(request)
  94. if err != nil {
  95. return nil, errors.Trace(err)
  96. }
  97. requestCtx, requestCancelFunc := context.WithTimeout(
  98. ctx, common.ValueOrDefault(
  99. b.coordinator.AnnounceRequestTimeout(),
  100. proxyAnnounceRequestTimeout))
  101. defer requestCancelFunc()
  102. responsePayload, err := b.roundTrip(requestCtx, requestPayload)
  103. if err != nil {
  104. return nil, errors.Trace(err)
  105. }
  106. response, err := UnmarshalProxyAnnounceResponse(responsePayload)
  107. if err != nil {
  108. return nil, errors.Trace(err)
  109. }
  110. return response, nil
  111. }
  112. // ClientOffer sends a ClientOffer request and returns the response.
  113. func (b *BrokerClient) ClientOffer(
  114. ctx context.Context,
  115. request *ClientOfferRequest) (*ClientOfferResponse, error) {
  116. requestPayload, err := MarshalClientOfferRequest(request)
  117. if err != nil {
  118. return nil, errors.Trace(err)
  119. }
  120. requestCtx, requestCancelFunc := context.WithTimeout(
  121. ctx, common.ValueOrDefault(
  122. b.coordinator.OfferRequestTimeout(),
  123. clientOfferRequestTimeout))
  124. defer requestCancelFunc()
  125. responsePayload, err := b.roundTrip(requestCtx, requestPayload)
  126. if err != nil {
  127. return nil, errors.Trace(err)
  128. }
  129. response, err := UnmarshalClientOfferResponse(responsePayload)
  130. if err != nil {
  131. return nil, errors.Trace(err)
  132. }
  133. return response, nil
  134. }
  135. // ProxyAnswer sends a ProxyAnswer request and returns the response.
  136. func (b *BrokerClient) ProxyAnswer(
  137. ctx context.Context,
  138. request *ProxyAnswerRequest) (*ProxyAnswerResponse, error) {
  139. requestPayload, err := MarshalProxyAnswerRequest(request)
  140. if err != nil {
  141. return nil, errors.Trace(err)
  142. }
  143. requestCtx, requestCancelFunc := context.WithTimeout(
  144. ctx, common.ValueOrDefault(
  145. b.coordinator.AnswerRequestTimeout(),
  146. proxyAnswerRequestTimeout))
  147. defer requestCancelFunc()
  148. responsePayload, err := b.roundTrip(requestCtx, 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. requestCtx, requestCancelFunc := context.WithTimeout(
  168. ctx, common.ValueOrDefault(
  169. b.coordinator.RelayedPacketRequestTimeout(),
  170. clientRelayedPacketRequestTimeout))
  171. defer requestCancelFunc()
  172. responsePayload, err := b.roundTrip(requestCtx, requestPayload)
  173. if err != nil {
  174. return nil, errors.Trace(err)
  175. }
  176. response, err := UnmarshalClientRelayedPacketResponse(responsePayload)
  177. if err != nil {
  178. return nil, errors.Trace(err)
  179. }
  180. return response, nil
  181. }
  182. func (b *BrokerClient) roundTrip(
  183. ctx context.Context,
  184. request []byte) ([]byte, error) {
  185. // The round tripper may need to establish a transport-level connection;
  186. // or this may already be established.
  187. roundTripper, err := b.coordinator.BrokerClientRoundTripper()
  188. if err != nil {
  189. return nil, errors.Trace(err)
  190. }
  191. // InitiatorSessions.RoundTrip may make serveral round trips with
  192. // roundTripper in order to complete a session establishment handshake.
  193. //
  194. // When there's an active session, only a single round trip is required,
  195. // to exchange the application-level request and response.
  196. //
  197. // When a concurrent BrokerClient request is currently performing a
  198. // session handshake, InitiatorSessions.RoundTrip will await completion
  199. // of that handshake before sending the application-layer request.
  200. //
  201. // Note the waitToShareSession limitation, documented in
  202. // InitiatorSessions.RoundTrip: a new session must complete a full,
  203. // application-level round trip (e.g., ProxyAnnounce/ClientOffer), not
  204. // just the session handshake, before a session becomes ready to share.
  205. //
  206. // Retries are built in to InitiatorSessions.RoundTrip: if there's an
  207. // existing session and it's expired, there will be additional round
  208. // trips to establish a fresh session.
  209. //
  210. // While the round tripper is responsible for maintaining the
  211. // request/response association, the application-level request and
  212. // response are tagged with a RoundTripID which is checked to ensure the
  213. // association is maintained.
  214. waitToShareSession := true
  215. response, err := b.sessions.RoundTrip(
  216. ctx,
  217. roundTripper,
  218. b.coordinator.BrokerPublicKey(),
  219. b.coordinator.BrokerRootObfuscationSecret(),
  220. waitToShareSession,
  221. request)
  222. if err != nil {
  223. // The BrokerDialCoordinator provider should close the existing
  224. // BrokerClientRoundTripper and create a new RoundTripper to return
  225. // in the next BrokerClientRoundTripper call.
  226. //
  227. // The session will be closed, if necessary, by InitiatorSessions.
  228. // It's possible that the session remains valid and only the
  229. // RoundTripper transport layer needs to be reset.
  230. b.coordinator.BrokerClientRoundTripperFailed(roundTripper)
  231. return nil, errors.Trace(err)
  232. }
  233. b.coordinator.BrokerClientRoundTripperSucceeded(roundTripper)
  234. return response, nil
  235. }