inproxy.go 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292
  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 psiphon
  20. import (
  21. "bytes"
  22. "context"
  23. "encoding/binary"
  24. std_errors "errors"
  25. "fmt"
  26. "io"
  27. "net"
  28. "net/http"
  29. "net/netip"
  30. "strconv"
  31. "sync"
  32. "sync/atomic"
  33. "syscall"
  34. "time"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/fragmentor"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/inproxy"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  40. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  41. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  42. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/resolver"
  43. "github.com/cespare/xxhash"
  44. "golang.org/x/net/bpf"
  45. )
  46. // InproxyBrokerClientManager manages an InproxyBrokerClientInstance, an
  47. // in-proxy broker client, and its associated broker dial parameters, that
  48. // may be shared by multiple client dials or proxy instances. There is no
  49. // explicit close operation for the managed InproxyBrokerClientInstance.
  50. //
  51. // Once used, the current InproxyBrokerClientInstance and its broker client is
  52. // left actively connected to the broker, to minimize transport round trips
  53. // for additional requests.
  54. //
  55. // The InproxyBrokerClientManager and its components implement a replay system
  56. // for broker client dials. As one broker client is shared access multiple
  57. // client in-proxy dials, the broker dial parameters are replayed
  58. // independently from tunnel dial parameters.
  59. //
  60. // The NewInproxyBrokerClientInstance layer provides a fixed association
  61. // between a broker client and its broker dial parameters, ensuring that
  62. // in-proxy success/failure callbacks reference the correct replay parameters
  63. // when setting or clearing replay.
  64. //
  65. // A new InproxyBrokerClientInstance, including the broker dial parameters and
  66. // broker client, is instantiated when the active network ID changes, using
  67. // tactics for the new network.
  68. type InproxyBrokerClientManager struct {
  69. config *Config
  70. isProxy bool
  71. mutex sync.Mutex
  72. networkID string
  73. brokerClientInstance *InproxyBrokerClientInstance
  74. }
  75. // NewInproxyBrokerClientManager creates a new InproxyBrokerClientManager.
  76. // NewInproxyBrokerClientManager does not perform any network operations; the
  77. // managed InproxyBrokerClientInstance is initialized when used for a round
  78. // trip.
  79. func NewInproxyBrokerClientManager(
  80. config *Config, isProxy bool) *InproxyBrokerClientManager {
  81. b := &InproxyBrokerClientManager{
  82. config: config,
  83. isProxy: isProxy,
  84. }
  85. // b.brokerClientInstance is initialized on demand, when getBrokerClient
  86. // is called.
  87. return b
  88. }
  89. // TacticsApplied implements the TacticsAppliedReceiver interface, and is
  90. // called when tactics have changed, which triggers a broker client reset in
  91. // order to apply potentially changed parameters.
  92. func (b *InproxyBrokerClientManager) TacticsApplied() error {
  93. b.mutex.Lock()
  94. defer b.mutex.Unlock()
  95. // TODO: as a future future enhancement, don't reset when the tactics
  96. // brokerSpecs.Hash() is unchanged?
  97. return errors.Trace(b.reset())
  98. }
  99. // GetBrokerClient returns the current, shared broker client and its
  100. // corresponding dial parametrers (for metrics logging). If there is no
  101. // current broker client, if the network ID differs from the network ID
  102. // associated with the previous broker client, a new broker client is
  103. // initialized.
  104. func (b *InproxyBrokerClientManager) GetBrokerClient(
  105. networkID string) (*inproxy.BrokerClient, *InproxyBrokerDialParameters, error) {
  106. b.mutex.Lock()
  107. defer b.mutex.Unlock()
  108. if b.brokerClientInstance == nil || b.networkID != networkID {
  109. err := b.reset()
  110. if err != nil {
  111. return nil, nil, errors.Trace(err)
  112. }
  113. }
  114. // The b.brokerClientInstance.brokerClient is wired up to refer back to
  115. // b.brokerClientInstance.brokerDialParams/roundTripper, etc.
  116. return b.brokerClientInstance.brokerClient,
  117. b.brokerClientInstance.brokerDialParams,
  118. nil
  119. }
  120. func (b *InproxyBrokerClientManager) resetBrokerClientOnRoundTripperFailed(
  121. brokerClientInstance *InproxyBrokerClientInstance) error {
  122. b.mutex.Lock()
  123. defer b.mutex.Unlock()
  124. if b.brokerClientInstance != brokerClientInstance {
  125. // Ignore the reset if the signal comes from the non-current
  126. // brokerClientInstance, which may occur when multiple in-flight
  127. // round trips fail in close proximity.
  128. return nil
  129. }
  130. return errors.Trace(b.reset())
  131. }
  132. func (b *InproxyBrokerClientManager) reset() error {
  133. // Assumes b.mutex lock is held.
  134. if b.brokerClientInstance != nil {
  135. // Close the existing broker client. This will close all underlying
  136. // network connections, interrupting any in-flight requests. This
  137. // close is invoked in the resetBrokerClientOnRoundTripperFailed
  138. // case, where it's expected that the round tripped has permanently
  139. // failed.
  140. b.brokerClientInstance.Close()
  141. }
  142. // Any existing broker client is removed, even if
  143. // NewInproxyBrokerClientInstance fails. This ensures, for example, that
  144. // an existing broker client is removed when its spec is no longer
  145. // available in tactics.
  146. b.networkID = ""
  147. b.brokerClientInstance = nil
  148. networkID := b.config.GetNetworkID()
  149. brokerClientInstance, err := NewInproxyBrokerClientInstance(
  150. b.config, b, networkID, b.isProxy)
  151. if err != nil {
  152. return errors.Trace(err)
  153. }
  154. b.networkID = networkID
  155. b.brokerClientInstance = brokerClientInstance
  156. return nil
  157. }
  158. // InproxyBrokerClientInstance pairs an inproxy.BrokerClient instance with an
  159. // implementation of the inproxy.BrokerDialCoordinator interface and the
  160. // associated, underlying broker dial parameters. InproxyBrokerClientInstance
  161. // implements broker client dial replay.
  162. type InproxyBrokerClientInstance struct {
  163. config *Config
  164. brokerClientManager *InproxyBrokerClientManager
  165. networkID string
  166. brokerClientPrivateKey inproxy.SessionPrivateKey
  167. brokerClient *inproxy.BrokerClient
  168. brokerPublicKey inproxy.SessionPublicKey
  169. brokerRootObfuscationSecret inproxy.ObfuscationSecret
  170. brokerDialParams *InproxyBrokerDialParameters
  171. replayEnabled bool
  172. isReplay bool
  173. roundTripper *InproxyBrokerRoundTripper
  174. personalCompartmentIDs []inproxy.ID
  175. commonCompartmentIDs []inproxy.ID
  176. sessionHandshakeTimeout time.Duration
  177. announceRequestTimeout time.Duration
  178. announceDelay time.Duration
  179. announceDelayJitter float64
  180. answerRequestTimeout time.Duration
  181. offerRequestTimeout time.Duration
  182. offerRetryDelay time.Duration
  183. offerRetryJitter float64
  184. relayedPacketRequestTimeout time.Duration
  185. replayRetainFailedProbability float64
  186. replayUpdateFrequency time.Duration
  187. mutex sync.Mutex
  188. lastStoreReplay time.Time
  189. }
  190. // NewInproxyBrokerClientInstance creates a new InproxyBrokerClientInstance.
  191. // NewInproxyBrokerClientManager does not perform any network operations; the
  192. // new InproxyBrokerClientInstance is initialized when used for a round
  193. // trip.
  194. func NewInproxyBrokerClientInstance(
  195. config *Config,
  196. brokerClientManager *InproxyBrokerClientManager,
  197. networkID string,
  198. isProxy bool) (*InproxyBrokerClientInstance, error) {
  199. p := config.GetParameters().Get()
  200. defer p.Close()
  201. // Select common or personal compartment IDs.
  202. commonCompartmentIDs, personalCompartmentIDs, err := prepareCompartmentIDs(config, p, isProxy)
  203. if err != nil {
  204. return nil, errors.Trace(err)
  205. }
  206. // Select the broker to use, optionally favoring brokers with replay
  207. // data.
  208. var brokerSpecs parameters.InproxyBrokerSpecsValue
  209. if isProxy {
  210. brokerSpecs = p.InproxyBrokerSpecs(
  211. parameters.InproxyProxyBrokerSpecs, parameters.InproxyBrokerSpecs)
  212. } else {
  213. brokerSpecs = p.InproxyBrokerSpecs(
  214. parameters.InproxyClientBrokerSpecs, parameters.InproxyBrokerSpecs)
  215. }
  216. if len(brokerSpecs) == 0 {
  217. return nil, errors.TraceNew("no broker specs")
  218. }
  219. // To ensure personal compartment ID client/proxy rendezvous at same
  220. // broker, simply pick the first configured broker.
  221. //
  222. // Limitations: there's no failover or load balancing for the personal
  223. // compartment ID case; and this logic assumes that the broker spec
  224. // tactics are the same for the client and proxy.
  225. if len(personalCompartmentIDs) > 0 {
  226. brokerSpecs = brokerSpecs[:1]
  227. }
  228. now := time.Now()
  229. // Prefer a broker with replay data.
  230. // Replay is disabled when the TTL, InproxyReplayBrokerDialParametersTTL,
  231. // is 0.
  232. ttl := p.Duration(parameters.InproxyReplayBrokerDialParametersTTL)
  233. replayEnabled := ttl > 0 &&
  234. !config.DisableReplay &&
  235. prng.FlipWeightedCoin(p.Float(parameters.InproxyReplayBrokerDialParametersProbability))
  236. brokerSpec, brokerDialParams, err :=
  237. ShuffleAndGetNetworkReplayParameters[parameters.InproxyBrokerSpec, InproxyBrokerDialParameters](
  238. networkID,
  239. replayEnabled,
  240. brokerSpecs,
  241. func(spec *parameters.InproxyBrokerSpec) string { return spec.BrokerPublicKey },
  242. func(spec *parameters.InproxyBrokerSpec, dialParams *InproxyBrokerDialParameters) bool {
  243. return dialParams.LastUsedTimestamp.After(now.Add(-ttl)) &&
  244. bytes.Equal(dialParams.LastUsedBrokerSpecHash, hashBrokerSpec(spec))
  245. })
  246. if err != nil {
  247. NoticeWarning("ShuffleAndGetNetworkReplayParameters failed: %v", errors.Trace(err))
  248. // When there's an error, try to continue, using a random broker spec
  249. // and no replay dial parameters.
  250. brokerSpec = brokerSpecs[prng.Intn(len(brokerSpecs)-1)]
  251. }
  252. // Generate new broker dial parameters if not replaying. Later, isReplay
  253. // is used to report the replay metric.
  254. isReplay := brokerDialParams != nil
  255. if !isReplay {
  256. brokerDialParams, err = MakeInproxyBrokerDialParameters(config, p, networkID, brokerSpec)
  257. if err != nil {
  258. return nil, errors.Trace(err)
  259. }
  260. } else {
  261. brokerDialParams.brokerSpec = brokerSpec
  262. err := brokerDialParams.prepareDialConfigs(config, p, networkID, true, nil)
  263. if err != nil {
  264. return nil, errors.Trace(err)
  265. }
  266. }
  267. // Load broker key material.
  268. brokerPublicKey, err := inproxy.SessionPublicKeyFromString(brokerSpec.BrokerPublicKey)
  269. if err != nil {
  270. return nil, errors.Trace(err)
  271. }
  272. brokerRootObfuscationSecret, err := inproxy.ObfuscationSecretFromString(brokerSpec.BrokerRootObfuscationSecret)
  273. if err != nil {
  274. return nil, errors.Trace(err)
  275. }
  276. roundTripper := NewInproxyBrokerRoundTripper(p, brokerDialParams)
  277. // Clients always generate an ephemeral session key pair. Proxies may opt
  278. // to use a long-lived key pair for proxied traffic attribution.
  279. var brokerClientPrivateKey inproxy.SessionPrivateKey
  280. if isProxy && config.InproxyProxySessionPrivateKey != "" {
  281. brokerClientPrivateKey, err = inproxy.SessionPrivateKeyFromString(config.InproxyProxySessionPrivateKey)
  282. if err != nil {
  283. return nil, errors.Trace(err)
  284. }
  285. } else {
  286. brokerClientPrivateKey, err = inproxy.GenerateSessionPrivateKey()
  287. if err != nil {
  288. return nil, errors.Trace(err)
  289. }
  290. }
  291. // InproxyBrokerClientInstance implements the
  292. // inproxy.BrokerDialCoordinator interface and passes itself to
  293. // inproxy.NewBrokerClient in order to provide the round tripper, key
  294. // material, compartment IDs, timeouts, and other configuration to the
  295. // in-proxy broker client.
  296. //
  297. // Timeouts are not replayed, but snapshots are stored in the
  298. // InproxyBrokerClientInstance for efficient lookup.
  299. b := &InproxyBrokerClientInstance{
  300. config: config,
  301. brokerClientManager: brokerClientManager,
  302. networkID: networkID,
  303. brokerClientPrivateKey: brokerClientPrivateKey,
  304. brokerPublicKey: brokerPublicKey,
  305. brokerRootObfuscationSecret: brokerRootObfuscationSecret,
  306. brokerDialParams: brokerDialParams,
  307. replayEnabled: replayEnabled,
  308. isReplay: isReplay,
  309. roundTripper: roundTripper,
  310. personalCompartmentIDs: personalCompartmentIDs,
  311. commonCompartmentIDs: commonCompartmentIDs,
  312. sessionHandshakeTimeout: p.Duration(parameters.InproxySessionHandshakeRoundTripTimeout),
  313. announceRequestTimeout: p.Duration(parameters.InproxyProxyAnnounceRequestTimeout),
  314. announceDelay: p.Duration(parameters.InproxyProxyAnnounceDelay),
  315. announceDelayJitter: p.Float(parameters.InproxyProxyAnnounceDelayJitter),
  316. answerRequestTimeout: p.Duration(parameters.InproxyProxyAnswerRequestTimeout),
  317. offerRequestTimeout: p.Duration(parameters.InproxyClientOfferRequestTimeout),
  318. offerRetryDelay: p.Duration(parameters.InproxyClientOfferRetryDelay),
  319. offerRetryJitter: p.Float(parameters.InproxyClientOfferRetryJitter),
  320. relayedPacketRequestTimeout: p.Duration(parameters.InproxyClientRelayedPacketRequestTimeout),
  321. replayRetainFailedProbability: p.Float(parameters.InproxyReplayBrokerRetainFailedProbability),
  322. replayUpdateFrequency: p.Duration(parameters.InproxyReplayBrokerUpdateFrequency),
  323. }
  324. // Initialize broker client. This will start with a fresh broker session.
  325. //
  326. // When resetBrokerClientOnRoundTripperFailed is invoked due to a failure
  327. // at the transport level -- TLS or domain fronting --
  328. // NewInproxyBrokerClientInstance is invoked, resetting both the broker
  329. // client round tripper and the broker session. As a future enhancement,
  330. // consider distinguishing between transport and session errors and
  331. // retaining a valid established session when only the transport needs to
  332. // be reset/retried.
  333. b.brokerClient, err = inproxy.NewBrokerClient(b)
  334. if err != nil {
  335. return nil, errors.Trace(err)
  336. }
  337. return b, nil
  338. }
  339. func prepareCompartmentIDs(
  340. config *Config,
  341. p parameters.ParametersAccessor,
  342. isProxy bool) ([]inproxy.ID, []inproxy.ID, error) {
  343. // Personal compartment IDs are loaded from the tunnel-core config; these
  344. // are set by the external app based on user input/configuration of IDs
  345. // generated by or obtained from personal proxies. Both clients and
  346. // proxies send personal compartment IDs to the in-proxy broker. For
  347. // clients, when personal compartment IDs are configured, no common
  348. // compartment IDs are prepared, ensuring matches with only proxies that
  349. // supply the corresponding personal compartment IDs.
  350. //
  351. // Common compartment IDs are obtained from tactics and merged with
  352. // previously learned IDs stored in the local datastore. When new IDs are
  353. // obtained from tactics, the merged list is written back to the
  354. // datastore. This allows for schemes where common compartment IDs are
  355. // distributed to sets of clients, then removed from distibution, and
  356. // still used to match proxies to those sets of clients. Only clients
  357. // send common compartment IDs to the in-proxy broker. Proxies are
  358. // automatically assigned to common compartments by the broker.
  359. //
  360. // Maximum compartment ID list lengths are enforced to ensure broker
  361. // request sizes don't grow unbounded.
  362. //
  363. // Limitation: currently, in max length trimming, new common compartment
  364. // IDs take precedence over older IDs.
  365. maxCompartmentIDListLength := p.Int(parameters.InproxyMaxCompartmentIDListLength)
  366. configPersonalCompartmentIDs := config.InproxyProxyPersonalCompartmentIDs
  367. if !isProxy {
  368. configPersonalCompartmentIDs = config.InproxyClientPersonalCompartmentIDs
  369. }
  370. personalCompartmentIDs, err := inproxy.IDsFromStrings(configPersonalCompartmentIDs)
  371. if err != nil {
  372. return nil, nil, errors.Trace(err)
  373. }
  374. if len(personalCompartmentIDs) > maxCompartmentIDListLength {
  375. // Trim the list. It's not expected that user-configured personal
  376. // compartment ID lists will exceed the max length.
  377. //
  378. // TODO: shuffle before trimming? Prioritize previous matches?
  379. personalCompartmentIDs = personalCompartmentIDs[:maxCompartmentIDListLength]
  380. }
  381. var commonCompartmentIDs []inproxy.ID
  382. if !isProxy && len(personalCompartmentIDs) == 0 {
  383. tacticsCommonCompartmentIDs := p.InproxyCompartmentIDs(parameters.InproxyCommonCompartmentIDs)
  384. knownCommonCompartmentIDs, err := LoadInproxyCommonCompartmentIDs()
  385. if err != nil {
  386. NoticeWarning("LoadInproxyCommonCompartmentIDs failed: %v", errors.Trace(err))
  387. // Continue with only the tactics common compartment IDs.
  388. }
  389. newCompartmentIDs := make([]string, 0, len(tacticsCommonCompartmentIDs))
  390. for _, compartmentID := range tacticsCommonCompartmentIDs {
  391. // TODO: faster lookup?
  392. if !common.Contains(knownCommonCompartmentIDs, compartmentID) {
  393. newCompartmentIDs = append(newCompartmentIDs, compartmentID)
  394. }
  395. }
  396. if len(newCompartmentIDs) > 0 {
  397. newCompartmentIDs = append(newCompartmentIDs, knownCommonCompartmentIDs...)
  398. // Locally store more than InproxyMaxCompartmentIDListLength known
  399. // common compartment IDs, in case the request limit parameter is
  400. // increased in the future.
  401. // maxPersistedCommonCompartmentIDListLength still limits the
  402. // length of the list to cap local memory and disk impact.
  403. maxPersistedCommonCompartmentIDListLength := 500 // ~16K
  404. if maxCompartmentIDListLength > maxPersistedCommonCompartmentIDListLength {
  405. maxPersistedCommonCompartmentIDListLength = maxCompartmentIDListLength
  406. }
  407. if len(newCompartmentIDs) > maxPersistedCommonCompartmentIDListLength {
  408. newCompartmentIDs = newCompartmentIDs[:maxPersistedCommonCompartmentIDListLength]
  409. }
  410. err := StoreInproxyCommonCompartmentIDs(newCompartmentIDs)
  411. if err != nil {
  412. NoticeWarning("StoreInproxyCommonCompartmentIDs failed: %v", errors.Trace(err))
  413. // Continue without persisting new common compartment IDs.
  414. }
  415. knownCommonCompartmentIDs = newCompartmentIDs
  416. }
  417. commonCompartmentIDs, err = inproxy.IDsFromStrings(knownCommonCompartmentIDs)
  418. if err != nil {
  419. return nil, nil, errors.Trace(err)
  420. }
  421. if len(commonCompartmentIDs) > maxCompartmentIDListLength {
  422. // TODO: shuffle before trimming? Prioritize previous matches?
  423. commonCompartmentIDs = commonCompartmentIDs[:maxCompartmentIDListLength]
  424. }
  425. }
  426. return commonCompartmentIDs, personalCompartmentIDs, nil
  427. }
  428. // Close closes the broker client round tripped, including closing all
  429. // underlying network connections, which will interrupt any in-flight round
  430. // trips.
  431. func (b *InproxyBrokerClientInstance) Close() error {
  432. err := b.roundTripper.Close()
  433. return errors.Trace(err)
  434. }
  435. // Implements the inproxy.BrokerDialCoordinator interface.
  436. func (b *InproxyBrokerClientInstance) NetworkID() string {
  437. return b.networkID
  438. }
  439. // Implements the inproxy.BrokerDialCoordinator interface.
  440. func (b *InproxyBrokerClientInstance) NetworkType() inproxy.NetworkType {
  441. return getInproxyNetworkType(GetNetworkType(b.networkID))
  442. }
  443. // Implements the inproxy.BrokerDialCoordinator interface.
  444. func (b *InproxyBrokerClientInstance) CommonCompartmentIDs() []inproxy.ID {
  445. return b.commonCompartmentIDs
  446. }
  447. // Implements the inproxy.BrokerDialCoordinator interface.
  448. func (b *InproxyBrokerClientInstance) PersonalCompartmentIDs() []inproxy.ID {
  449. return b.personalCompartmentIDs
  450. }
  451. // Implements the inproxy.BrokerDialCoordinator interface.
  452. func (b *InproxyBrokerClientInstance) BrokerClientPrivateKey() inproxy.SessionPrivateKey {
  453. return b.brokerClientPrivateKey
  454. }
  455. // Implements the inproxy.BrokerDialCoordinator interface.
  456. func (b *InproxyBrokerClientInstance) BrokerPublicKey() inproxy.SessionPublicKey {
  457. return b.brokerPublicKey
  458. }
  459. // Implements the inproxy.BrokerDialCoordinator interface.
  460. func (b *InproxyBrokerClientInstance) BrokerRootObfuscationSecret() inproxy.ObfuscationSecret {
  461. return b.brokerRootObfuscationSecret
  462. }
  463. // Implements the inproxy.BrokerDialCoordinator interface.
  464. func (b *InproxyBrokerClientInstance) BrokerClientRoundTripper() (inproxy.RoundTripper, error) {
  465. // Returns the same round tripper for the lifetime of the
  466. // inproxy.BrokerDialCoordinator, ensuring all requests for one in-proxy
  467. // dial or proxy relay use the same broker, as is necessary due to the
  468. // broker state for the proxy announce/answer, client broker/server
  469. // relay, etc.
  470. return b.roundTripper, nil
  471. }
  472. // Implements the inproxy.BrokerDialCoordinator interface.
  473. func (b *InproxyBrokerClientInstance) BrokerClientRoundTripperSucceeded(roundTripper inproxy.RoundTripper) {
  474. b.mutex.Lock()
  475. defer b.mutex.Unlock()
  476. if rt, ok := roundTripper.(*InproxyBrokerRoundTripper); !ok || rt != b.roundTripper {
  477. // Passing in the round tripper obtained from BrokerClientRoundTripper
  478. // is just used for sanity check in this implementation, since each
  479. // InproxyBrokerClientInstance has exactly one round tripper.
  480. NoticeError("BrokerClientRoundTripperSucceeded: roundTripper instance mismatch")
  481. return
  482. }
  483. // Set replay or extend the broker dial parameters replay TTL after a
  484. // success. With tunnel dial parameters, the replay TTL is extended after
  485. // every successful tunnel connection. Since there are potentially more
  486. // and more frequent broker round trips one tunnel dial, the TTL is only
  487. // extended after some target duration has elapsed, to avoid excessive
  488. // datastore writes.
  489. now := time.Now()
  490. if b.replayEnabled && now.Sub(b.lastStoreReplay) > b.replayUpdateFrequency {
  491. b.brokerDialParams.LastUsedTimestamp = time.Now()
  492. err := SetNetworkReplayParameters[InproxyBrokerDialParameters](
  493. b.networkID, b.brokerDialParams.brokerSpec.BrokerPublicKey, b.brokerDialParams)
  494. if err != nil {
  495. NoticeWarning("StoreBrokerDialParameters failed: %v", errors.Trace(err))
  496. // Continue without persisting replay changes.
  497. } else {
  498. b.lastStoreReplay = now
  499. }
  500. }
  501. // Verify/extend the resolver cache entry for any resolved domain after a
  502. // success.
  503. //
  504. // Limitation: currently this re-extends regardless of how long ago the DNS
  505. // resolve happened.
  506. resolver := b.config.GetResolver()
  507. if resolver != nil {
  508. resolver.VerifyCacheExtension(b.brokerDialParams.FrontingDialAddress)
  509. }
  510. }
  511. // Implements the inproxy.BrokerDialCoordinator interface.
  512. func (b *InproxyBrokerClientInstance) BrokerClientRoundTripperFailed(roundTripper inproxy.RoundTripper) {
  513. b.mutex.Lock()
  514. defer b.mutex.Unlock()
  515. if rt, ok := roundTripper.(*InproxyBrokerRoundTripper); !ok || rt != b.roundTripper {
  516. // Passing in the round tripper obtained from BrokerClientRoundTripper
  517. // is just used for sanity check in this implementation, since each
  518. // InproxyBrokerClientInstance has exactly one round tripper.
  519. NoticeError("BrokerClientRoundTripperFailed: roundTripper instance mismatch")
  520. return
  521. }
  522. // Delete any persistent replay dial parameters. Unlike with the success
  523. // case, consecutive, repeated deletes shouldn't write to storage, so
  524. // they are not avoided.
  525. if b.replayEnabled &&
  526. !prng.FlipWeightedCoin(b.replayRetainFailedProbability) {
  527. // Limitation: there's a race condition with multiple
  528. // InproxyBrokerClientInstances writing to the replay datastore for
  529. // the same broker, such as in the case where there's a dual-mode
  530. // in-proxy client and proxy; this delete could potentially clobber a
  531. // concurrent fresh replay store after a success.
  532. //
  533. // TODO: add an additional storage key distinguisher for each instance?
  534. err := DeleteNetworkReplayParameters[InproxyBrokerDialParameters](
  535. b.networkID, b.brokerDialParams.brokerSpec.BrokerPublicKey)
  536. if err != nil {
  537. NoticeWarning("DeleteBrokerDialParameters failed: %v", errors.Trace(err))
  538. // Continue without resetting replay.
  539. }
  540. }
  541. // Invoke resetBrokerClientOnRoundTripperFailed to signal the
  542. // InproxyBrokerClientManager to create a new
  543. // InproxyBrokerClientInstance, with new dial parameters and a new round
  544. // tripper, after a failure.
  545. //
  546. // This InproxyBrokerClientInstance doesn't change its dial parameters or
  547. // round tripper to ensure that any concurrent usage retains affinity
  548. // with the same parameters and broker.
  549. //
  550. // Limitation: a transport-level failure may unnecessarily reset the
  551. // broker session state; see comment in NewInproxyBrokerClientInstance.
  552. err := b.brokerClientManager.resetBrokerClientOnRoundTripperFailed(b)
  553. if err != nil {
  554. NoticeWarning("reset broker client failed: %v", errors.Trace(err))
  555. // Continue with old broker client instance.
  556. }
  557. }
  558. // Implements the inproxy.BrokerDialCoordinator interface.
  559. func (b *InproxyBrokerClientInstance) AnnounceRequestTimeout() time.Duration {
  560. return b.announceRequestTimeout
  561. }
  562. // Implements the inproxy.BrokerDialCoordinator interface.
  563. func (b *InproxyBrokerClientInstance) SessionHandshakeRoundTripTimeout() time.Duration {
  564. return b.sessionHandshakeTimeout
  565. }
  566. // Implements the inproxy.BrokerDialCoordinator interface.
  567. func (b *InproxyBrokerClientInstance) AnnounceDelay() time.Duration {
  568. return b.announceDelay
  569. }
  570. // Implements the inproxy.BrokerDialCoordinator interface.
  571. func (b *InproxyBrokerClientInstance) AnnounceDelayJitter() float64 {
  572. return b.announceDelayJitter
  573. }
  574. // Implements the inproxy.BrokerDialCoordinator interface.
  575. func (b *InproxyBrokerClientInstance) AnswerRequestTimeout() time.Duration {
  576. return b.answerRequestTimeout
  577. }
  578. // Implements the inproxy.BrokerDialCoordinator interface.
  579. func (b *InproxyBrokerClientInstance) OfferRequestTimeout() time.Duration {
  580. return b.offerRequestTimeout
  581. }
  582. // Implements the inproxy.BrokerDialCoordinator interface.
  583. func (b *InproxyBrokerClientInstance) OfferRetryDelay() time.Duration {
  584. return b.offerRetryDelay
  585. }
  586. // Implements the inproxy.BrokerDialCoordinator interface.
  587. func (b *InproxyBrokerClientInstance) OfferRetryJitter() float64 {
  588. return b.offerRetryJitter
  589. }
  590. // Implements the inproxy.BrokerDialCoordinator interface.
  591. func (b *InproxyBrokerClientInstance) RelayedPacketRequestTimeout() time.Duration {
  592. return b.relayedPacketRequestTimeout
  593. }
  594. // InproxyBrokerDialParameters represents a selected broker transport and dial
  595. // paramaters.
  596. //
  597. // InproxyBrokerDialParameters is used to configure dialers; as a persistent
  598. // record to store successful dial parameters for replay; and to report dial
  599. // stats in notices and Psiphon API calls.
  600. //
  601. // InproxyBrokerDialParameters is similar to tunnel DialParameters, but is
  602. // specific to the in-proxy broker dial phase.
  603. type InproxyBrokerDialParameters struct {
  604. brokerSpec *parameters.InproxyBrokerSpec `json:"-"`
  605. isReplay bool `json:"-"`
  606. LastUsedTimestamp time.Time
  607. LastUsedBrokerSpecHash []byte
  608. NetworkLatencyMultiplier float64
  609. BrokerTransport string
  610. DialAddress string
  611. FrontingProviderID string
  612. FrontingDialAddress string
  613. SNIServerName string
  614. TransformedHostName bool
  615. VerifyServerName string
  616. VerifyPins []string
  617. HostHeader string
  618. ResolvedIPAddress atomic.Value `json:"-"`
  619. TLSProfile string
  620. TLSVersion string
  621. RandomizedTLSProfileSeed *prng.Seed
  622. NoDefaultTLSSessionID bool
  623. TLSFragmentClientHello bool
  624. SelectedUserAgent bool
  625. UserAgent string
  626. BPFProgramName string
  627. BPFProgramInstructions []bpf.RawInstruction
  628. FragmentorSeed *prng.Seed
  629. ResolveParameters *resolver.ResolveParameters
  630. dialConfig *DialConfig `json:"-"`
  631. meekConfig *MeekConfig `json:"-"`
  632. }
  633. // MakeInproxyBrokerDialParameters creates a new InproxyBrokerDialParameters.
  634. func MakeInproxyBrokerDialParameters(
  635. config *Config,
  636. p parameters.ParametersAccessor,
  637. networkID string,
  638. brokerSpec *parameters.InproxyBrokerSpec) (*InproxyBrokerDialParameters, error) {
  639. // This function duplicates some code from MakeDialParameters and
  640. // makeFrontedHTTPClient. To simplify the logic, the Replay<Component>
  641. // tactic flags for individual dial components are ignored.
  642. //
  643. // TODO: merge common functionality?
  644. if config.UseUpstreamProxy() {
  645. return nil, errors.TraceNew("upstream proxy unsupported")
  646. }
  647. currentTimestamp := time.Now()
  648. var brokerDialParams *InproxyBrokerDialParameters
  649. // Select new broker dial parameters
  650. brokerDialParams = &InproxyBrokerDialParameters{
  651. brokerSpec: brokerSpec,
  652. LastUsedTimestamp: currentTimestamp,
  653. LastUsedBrokerSpecHash: hashBrokerSpec(brokerSpec),
  654. }
  655. // Network latency multiplier
  656. brokerDialParams.NetworkLatencyMultiplier = prng.ExpFloat64Range(
  657. p.Float(parameters.NetworkLatencyMultiplierMin),
  658. p.Float(parameters.NetworkLatencyMultiplierMax),
  659. p.Float(parameters.NetworkLatencyMultiplierLambda))
  660. // Select fronting configuration
  661. var err error
  662. brokerDialParams.FrontingProviderID,
  663. brokerDialParams.BrokerTransport,
  664. brokerDialParams.FrontingDialAddress,
  665. brokerDialParams.SNIServerName,
  666. brokerDialParams.VerifyServerName,
  667. brokerDialParams.VerifyPins,
  668. brokerDialParams.HostHeader,
  669. err = brokerDialParams.brokerSpec.BrokerFrontingSpecs.SelectParameters()
  670. if err != nil {
  671. return nil, errors.Trace(err)
  672. }
  673. // At this time, the broker client, the transport is limited to fronted
  674. // HTTPS.
  675. //
  676. // MeekModePlaintextRoundTrip currently disallows HTTP, as it must for
  677. // Conjure's request payloads, but the in-proxy broker session payload is
  678. // obfuscated. As a future enhancement, allow HTTP for the in-proxy
  679. // broker case, skip selecting TLS tactics and select HTTP tactics such
  680. // as HTTPTransformerParameters.
  681. if brokerDialParams.BrokerTransport == protocol.FRONTING_TRANSPORT_HTTP {
  682. return nil, errors.TraceNew("unsupported fronting transport")
  683. }
  684. // Determine and use the equivilent tunnel protocol for tactics
  685. // selections. For example, for the broker transport FRONTED-HTTPS, use
  686. // the tactics for FRONTED-MEEK-OSSH.
  687. equivilentTunnelProtocol, err := protocol.EquivilentTunnelProtocol(brokerDialParams.BrokerTransport)
  688. if err != nil {
  689. return nil, errors.Trace(err)
  690. }
  691. // FrontSpec.Addresses may include a port; default to 443 if none.
  692. if _, _, err := net.SplitHostPort(brokerDialParams.FrontingDialAddress); err == nil {
  693. brokerDialParams.DialAddress = brokerDialParams.FrontingDialAddress
  694. } else {
  695. brokerDialParams.DialAddress = net.JoinHostPort(brokerDialParams.FrontingDialAddress, "443")
  696. }
  697. // SNI configuration
  698. //
  699. // For a FrontingSpec, an SNI value of "" indicates to disable/omit SNI, so
  700. // never transform in that case.
  701. if brokerDialParams.SNIServerName != "" {
  702. if p.WeightedCoinFlip(parameters.TransformHostNameProbability) {
  703. brokerDialParams.SNIServerName = selectHostName(equivilentTunnelProtocol, p)
  704. brokerDialParams.TransformedHostName = true
  705. }
  706. }
  707. // TLS configuration
  708. //
  709. // The requireTLS13 flag is set to true in order to use only modern TLS
  710. // fingerprints which should support HTTP/2 in the ALPN.
  711. //
  712. // TODO: TLS padding, NoDefaultTLSSessionID
  713. brokerDialParams.TLSProfile,
  714. brokerDialParams.TLSVersion,
  715. brokerDialParams.RandomizedTLSProfileSeed,
  716. err = SelectTLSProfile(false, true, true, brokerDialParams.FrontingProviderID, p)
  717. brokerDialParams.NoDefaultTLSSessionID = p.WeightedCoinFlip(
  718. parameters.NoDefaultTLSSessionIDProbability)
  719. if brokerDialParams.SNIServerName != "" && net.ParseIP(brokerDialParams.SNIServerName) == nil {
  720. tlsFragmentorLimitProtocols := p.TunnelProtocols(parameters.TLSFragmentClientHelloLimitProtocols)
  721. if len(tlsFragmentorLimitProtocols) == 0 || common.Contains(tlsFragmentorLimitProtocols, equivilentTunnelProtocol) {
  722. brokerDialParams.TLSFragmentClientHello = p.WeightedCoinFlip(parameters.TLSFragmentClientHelloProbability)
  723. }
  724. }
  725. // User Agent configuration
  726. dialCustomHeaders := makeDialCustomHeaders(config, p)
  727. brokerDialParams.SelectedUserAgent, brokerDialParams.UserAgent = selectUserAgentIfUnset(p, dialCustomHeaders)
  728. // BPF configuration
  729. if ClientBPFEnabled() &&
  730. protocol.TunnelProtocolMayUseClientBPF(equivilentTunnelProtocol) {
  731. if p.WeightedCoinFlip(parameters.BPFClientTCPProbability) {
  732. brokerDialParams.BPFProgramName = ""
  733. brokerDialParams.BPFProgramInstructions = nil
  734. ok, name, rawInstructions := p.BPFProgram(parameters.BPFClientTCPProgram)
  735. if ok {
  736. brokerDialParams.BPFProgramName = name
  737. brokerDialParams.BPFProgramInstructions = rawInstructions
  738. }
  739. }
  740. }
  741. // Fragmentor configuration
  742. brokerDialParams.FragmentorSeed, err = prng.NewSeed()
  743. if err != nil {
  744. return nil, errors.Trace(err)
  745. }
  746. // Resolver configuration
  747. //
  748. // The custom resolcer is wired up only when there is a domain to be
  749. // resolved; GetMetrics will log resolver metrics when the resolver is set.
  750. if net.ParseIP(brokerDialParams.FrontingDialAddress) == nil {
  751. resolver := config.GetResolver()
  752. if resolver == nil {
  753. return nil, errors.TraceNew("missing resolver")
  754. }
  755. brokerDialParams.ResolveParameters, err = resolver.MakeResolveParameters(
  756. p, brokerDialParams.FrontingProviderID, brokerDialParams.FrontingDialAddress)
  757. if err != nil {
  758. return nil, errors.Trace(err)
  759. }
  760. }
  761. // Initialize Dial/MeekConfigs to be passed to the corresponding dialers.
  762. err = brokerDialParams.prepareDialConfigs(config, p, networkID, false, dialCustomHeaders)
  763. if err != nil {
  764. return nil, errors.Trace(err)
  765. }
  766. return brokerDialParams, nil
  767. }
  768. // prepareDialConfigs is called for both new and replayed broker dial parameters.
  769. func (brokerDialParams *InproxyBrokerDialParameters) prepareDialConfigs(
  770. config *Config,
  771. p parameters.ParametersAccessor,
  772. networkID string,
  773. isReplay bool,
  774. dialCustomHeaders http.Header) error {
  775. brokerDialParams.isReplay = isReplay
  776. equivilentTunnelProtocol, err := protocol.EquivilentTunnelProtocol(brokerDialParams.BrokerTransport)
  777. if err != nil {
  778. return errors.Trace(err)
  779. }
  780. // Custom headers and User Agent
  781. if dialCustomHeaders == nil {
  782. dialCustomHeaders = makeDialCustomHeaders(config, p)
  783. }
  784. if brokerDialParams.SelectedUserAgent {
  785. // Limitation: if config.CustomHeaders adds a User-Agent between
  786. // replays, it may be ignored due to replaying a selected User-Agent.
  787. dialCustomHeaders.Set("User-Agent", brokerDialParams.UserAgent)
  788. }
  789. // Fragmentor
  790. fragmentorConfig := fragmentor.NewUpstreamConfig(
  791. p, equivilentTunnelProtocol, brokerDialParams.FragmentorSeed)
  792. // Resolver
  793. var resolveIP func(ctx context.Context, hostname string) ([]net.IP, error)
  794. if net.ParseIP(brokerDialParams.FrontingDialAddress) == nil {
  795. resolver := config.GetResolver()
  796. if resolver == nil {
  797. return errors.TraceNew("missing resolver")
  798. }
  799. resolveIP = func(ctx context.Context, hostname string) ([]net.IP, error) {
  800. IPs, err := resolver.ResolveIP(
  801. ctx, networkID, brokerDialParams.ResolveParameters, hostname)
  802. return IPs, errors.Trace(err)
  803. }
  804. } else {
  805. resolveIP = func(ctx context.Context, hostname string) ([]net.IP, error) {
  806. return nil, errors.TraceNew("unexpected resolve")
  807. }
  808. }
  809. // DialConfig
  810. brokerDialParams.ResolvedIPAddress.Store("")
  811. brokerDialParams.dialConfig = &DialConfig{
  812. DiagnosticID: brokerDialParams.brokerSpec.BrokerPublicKey,
  813. CustomHeaders: dialCustomHeaders,
  814. BPFProgramInstructions: brokerDialParams.BPFProgramInstructions,
  815. DeviceBinder: config.deviceBinder,
  816. IPv6Synthesizer: config.IPv6Synthesizer,
  817. ResolveIP: resolveIP,
  818. TrustedCACertificatesFilename: config.TrustedCACertificatesFilename,
  819. FragmentorConfig: fragmentorConfig,
  820. ResolvedIPCallback: func(IPAddress string) {
  821. brokerDialParams.ResolvedIPAddress.Store(IPAddress)
  822. },
  823. }
  824. // MeekDialConfig
  825. //
  826. // The broker round trips use MeekModePlaintextRoundTrip without meek
  827. // cookies, so meek obfuscation is not configured. The in-proxy broker
  828. // session payloads have their own obfuscation layer.
  829. addPsiphonFrontingHeader := false
  830. if brokerDialParams.FrontingProviderID != "" {
  831. addPsiphonFrontingHeader = common.Contains(
  832. p.LabeledTunnelProtocols(
  833. parameters.AddFrontingProviderPsiphonFrontingHeader,
  834. brokerDialParams.FrontingProviderID),
  835. equivilentTunnelProtocol)
  836. }
  837. brokerDialParams.meekConfig = &MeekConfig{
  838. Mode: MeekModePlaintextRoundTrip,
  839. DiagnosticID: brokerDialParams.FrontingProviderID,
  840. Parameters: config.GetParameters(),
  841. DialAddress: brokerDialParams.DialAddress,
  842. TLSProfile: brokerDialParams.TLSProfile,
  843. NoDefaultTLSSessionID: brokerDialParams.NoDefaultTLSSessionID,
  844. RandomizedTLSProfileSeed: brokerDialParams.RandomizedTLSProfileSeed,
  845. SNIServerName: brokerDialParams.SNIServerName,
  846. AddPsiphonFrontingHeader: addPsiphonFrontingHeader,
  847. VerifyServerName: brokerDialParams.VerifyServerName,
  848. VerifyPins: brokerDialParams.VerifyPins,
  849. HostHeader: brokerDialParams.HostHeader,
  850. TransformedHostName: brokerDialParams.TransformedHostName,
  851. NetworkLatencyMultiplier: brokerDialParams.NetworkLatencyMultiplier,
  852. AdditionalHeaders: config.MeekAdditionalHeaders,
  853. }
  854. switch brokerDialParams.BrokerTransport {
  855. case protocol.FRONTING_TRANSPORT_HTTPS:
  856. brokerDialParams.meekConfig.UseHTTPS = true
  857. case protocol.FRONTING_TRANSPORT_QUIC:
  858. brokerDialParams.meekConfig.UseQUIC = true
  859. }
  860. return nil
  861. }
  862. // GetMetrics implements the common.MetricsSource interface and returns log
  863. // fields detailing the broker dial parameters.
  864. func (brokerDialParams *InproxyBrokerDialParameters) GetMetrics() common.LogFields {
  865. logFields := make(common.LogFields)
  866. logFields["inproxy_broker_transport"] = brokerDialParams.BrokerTransport
  867. isReplay := "0"
  868. if brokerDialParams.isReplay {
  869. isReplay = "1"
  870. }
  871. logFields["inproxy_broker_is_replay"] = isReplay
  872. // Note: as At the broker client transport is currently limited to domain
  873. // fronted HTTPS, the following related parameters are included
  874. // unconditionally.
  875. logFields["inproxy_broker_fronting_provider_id"] = brokerDialParams.FrontingProviderID
  876. logFields["inproxy_broker_dial_address"] = brokerDialParams.FrontingDialAddress
  877. resolvedIPAddress := brokerDialParams.ResolvedIPAddress.Load().(string)
  878. if resolvedIPAddress != "" {
  879. logFields["inproxy_broker_resolved_ip_address"] = resolvedIPAddress
  880. }
  881. if brokerDialParams.SNIServerName != "" {
  882. logFields["inproxy_broker_sni_server_name"] = brokerDialParams.SNIServerName
  883. }
  884. logFields["inproxy_broker_host_header"] = brokerDialParams.HostHeader
  885. transformedHostName := "0"
  886. if brokerDialParams.TransformedHostName {
  887. transformedHostName = "1"
  888. }
  889. logFields["inproxy_broker_transformed_host_name"] = transformedHostName
  890. if brokerDialParams.UserAgent != "" {
  891. logFields["inproxy_broker_user_agent"] = brokerDialParams.UserAgent
  892. }
  893. if brokerDialParams.BrokerTransport == protocol.FRONTING_TRANSPORT_HTTPS {
  894. if brokerDialParams.TLSProfile != "" {
  895. logFields["inproxy_broker_tls_profile"] = brokerDialParams.TLSProfile
  896. }
  897. logFields["inproxy_broker_tls_version"] = brokerDialParams.TLSVersion
  898. tlsFragmented := "0"
  899. if brokerDialParams.TLSFragmentClientHello {
  900. tlsFragmented = "1"
  901. }
  902. logFields["inproxy_broker_tls_fragmented"] = tlsFragmented
  903. }
  904. if brokerDialParams.BPFProgramName != "" {
  905. logFields["inproxy_broker_client_bpf"] = brokerDialParams.BPFProgramName
  906. }
  907. if brokerDialParams.ResolveParameters != nil {
  908. // See comment for dialParams.ResolveParameters handling in
  909. // getBaseAPIParameters.
  910. if brokerDialParams.ResolveParameters.PreresolvedIPAddress != "" {
  911. dialDomain, _, _ := net.SplitHostPort(brokerDialParams.DialAddress)
  912. if brokerDialParams.ResolveParameters.PreresolvedDomain == dialDomain {
  913. logFields["inproxy_broker_dns_preresolved"] = brokerDialParams.ResolveParameters.PreresolvedIPAddress
  914. }
  915. }
  916. if brokerDialParams.ResolveParameters.PreferAlternateDNSServer {
  917. logFields["inproxy_broker_dns_preferred"] = brokerDialParams.ResolveParameters.AlternateDNSServer
  918. }
  919. if brokerDialParams.ResolveParameters.ProtocolTransformName != "" {
  920. logFields["inproxy_broker_dns_transform"] = brokerDialParams.ResolveParameters.ProtocolTransformName
  921. }
  922. logFields["inproxy_broker_dns_attempt"] = strconv.Itoa(
  923. brokerDialParams.ResolveParameters.GetFirstAttemptWithAnswer())
  924. }
  925. // TODO: get fragmentor metrics, if any, from MeekConn.
  926. return logFields
  927. }
  928. // hashBrokerSpec hashes the broker spec. The hash is used to detect when
  929. // broker spec tactics have changed.
  930. func hashBrokerSpec(spec *parameters.InproxyBrokerSpec) []byte {
  931. var hash [8]byte
  932. binary.BigEndian.PutUint64(
  933. hash[:],
  934. uint64(xxhash.Sum64String(fmt.Sprintf("%+v", spec))))
  935. return hash[:]
  936. }
  937. // InproxyBrokerRoundTripper is a broker request round trip transport
  938. // implemented using MeekConn in MeekModePlaintextRoundTrip mode, utilizing
  939. // MeekConn's domain fronting capabilities and using persistent and
  940. // multiplexed connections, via HTTP/2, to support multiple concurrent
  941. // in-flight round trips.
  942. //
  943. // InproxyBrokerRoundTripper implements the inproxy.RoundTripper interface.
  944. type InproxyBrokerRoundTripper struct {
  945. brokerDialParams *InproxyBrokerDialParameters
  946. runCtx context.Context
  947. stopRunning context.CancelFunc
  948. dial int32
  949. dialCompleted chan struct{}
  950. dialErr error
  951. conn *MeekConn
  952. failureThreshold time.Duration
  953. }
  954. // NewInproxyBrokerRoundTripper creates a new InproxyBrokerRoundTripper. The
  955. // initial DialMeek is defered until the first call to RoundTrip, so
  956. // NewInproxyBrokerRoundTripper does not perform any network operations.
  957. //
  958. // The input brokerDialParams dial parameter and config fields must not
  959. // modifed after NewInproxyBrokerRoundTripper is called.
  960. func NewInproxyBrokerRoundTripper(
  961. p parameters.ParametersAccessor,
  962. brokerDialParams *InproxyBrokerDialParameters) *InproxyBrokerRoundTripper {
  963. runCtx, stopRunning := context.WithCancel(context.Background())
  964. return &InproxyBrokerRoundTripper{
  965. brokerDialParams: brokerDialParams,
  966. runCtx: runCtx,
  967. stopRunning: stopRunning,
  968. dialCompleted: make(chan struct{}),
  969. failureThreshold: p.Duration(
  970. parameters.InproxyBrokerRoundTripStatusCodeFailureThreshold),
  971. }
  972. }
  973. // Close interrupts any in-flight request and closes the underlying
  974. // MeekConn.
  975. func (rt *InproxyBrokerRoundTripper) Close() error {
  976. // Interrupt any DialMeek or RoundTrip.
  977. rt.stopRunning()
  978. if atomic.CompareAndSwapInt32(&rt.dial, 0, 1) {
  979. // RoundTrip has not yet been called or has not yet kicked off
  980. // DialMeek, so there is no MeekConn to close. Prevent any future
  981. // DialMeek by signaling dialCompleted and fail any future round trip
  982. // attempt by setting dialErr.
  983. rt.dialErr = errors.TraceNew("closed")
  984. close(rt.dialCompleted)
  985. } else {
  986. // Await any ongoing DialMeek or RoundTrip (stopRunning should
  987. // interrupt either one quickly).
  988. <-rt.dialCompleted
  989. if rt.conn != nil {
  990. _ = rt.conn.Close()
  991. }
  992. }
  993. // As with MeekConn.Close, any Close errors from underlying conns are not
  994. // propagated.
  995. return nil
  996. }
  997. // RoundTrip transports a request to the broker endpoint and returns a
  998. // response.
  999. func (rt *InproxyBrokerRoundTripper) RoundTrip(
  1000. ctx context.Context,
  1001. roundTripDelay time.Duration,
  1002. roundTripTimeout time.Duration,
  1003. requestPayload []byte) (_ []byte, retErr error) {
  1004. defer func() {
  1005. // Log any error which results in invoking BrokerClientRoundTripperFailed.
  1006. var failedError *inproxy.RoundTripperFailedError
  1007. if std_errors.As(retErr, &failedError) {
  1008. NoticeWarning("RoundTripperFailedError: %v", retErr)
  1009. }
  1010. }()
  1011. // Cancel DialMeek or MeekConn.RoundTrip when:
  1012. // - Close is called
  1013. // - the input context is done
  1014. ctx, cancelFunc := common.MergeContextCancel(ctx, rt.runCtx)
  1015. defer cancelFunc()
  1016. // Apply any round trip delay. Currently, this is used to apply an
  1017. // announce request delay post-waitToShareSession, pre-network round
  1018. // trip, and cancelable by the above merged context.
  1019. if roundTripDelay > 0 {
  1020. common.SleepWithContext(ctx, roundTripDelay)
  1021. }
  1022. // Apply the round trip timeout after any delay is complete.
  1023. //
  1024. // This timeout includes any TLS handshake network round trips, as
  1025. // performed by the initial DialMeek and may be performed subsequently by
  1026. // net/http via MeekConn.RoundTrip. These extra round trips should be
  1027. // accounted for in the in the difference between client-side request
  1028. // timeouts, such as InproxyProxyAnswerRequestTimeout, and broker-side
  1029. // handler timeouts, such as InproxyBrokerProxyAnnounceTimeout, with the
  1030. // former allowing more time for network round trips.
  1031. requestCtx := ctx
  1032. if roundTripTimeout > 0 {
  1033. var requestCancelFunc context.CancelFunc
  1034. requestCtx, requestCancelFunc = context.WithTimeout(ctx, roundTripTimeout)
  1035. defer requestCancelFunc()
  1036. }
  1037. // The first RoundTrip caller will perform the DialMeek step, which
  1038. // establishes the TLS trasport connection to the fronted endpoint.
  1039. // Following callers will await that DialMeek or share an established
  1040. // connection.
  1041. //
  1042. // To accomodate using custom utls fingerprints, with varying ALPNs, with
  1043. // net/http, DialMeek completes a full TLS handshake before instantiating
  1044. // the appropriate http.Transport or http2.Transport. Until that first
  1045. // DialMeek completes, and unlike standard net/http round trips,
  1046. // InproxyBrokerRoundTripper won't spawn distinct TLS persistent
  1047. // connections for concurrent round trips. After DialMeek, concurrent
  1048. // round trips over HTTP/2 connections may simply share the one TLS
  1049. // connection, while concurrent round trips over HTTP connections may
  1050. // spawn additional TLS persistent connections.
  1051. //
  1052. // There is no retry here if DialMeek fails, as higher levels will invoke
  1053. // BrokerClientRoundTripperFailed on failure, clear any replay, select
  1054. // new dial parameters, and retry.
  1055. if atomic.CompareAndSwapInt32(&rt.dial, 0, 1) {
  1056. // DialMeek hasn't been called yet.
  1057. conn, err := DialMeek(
  1058. requestCtx,
  1059. rt.brokerDialParams.meekConfig,
  1060. rt.brokerDialParams.dialConfig)
  1061. if err != nil && ctx.Err() != context.Canceled {
  1062. // DialMeek performs an initial TLS handshake. DialMeek errors,
  1063. // excluding a cancelled context as happens on shutdown, are
  1064. // classified as as RoundTripperFailedErrors, which will invoke
  1065. // BrokerClientRoundTripperFailed, resetting the round tripper
  1066. // and clearing replay parameters.
  1067. err = inproxy.NewRoundTripperFailedError(err)
  1068. }
  1069. rt.conn = conn
  1070. rt.dialErr = err
  1071. close(rt.dialCompleted)
  1072. if err != nil {
  1073. return nil, errors.Trace(rt.dialErr)
  1074. }
  1075. } else {
  1076. // Await any ongoing DialMeek run by a concurrent RoundTrip caller.
  1077. select {
  1078. case <-rt.dialCompleted:
  1079. case <-ctx.Done():
  1080. return nil, errors.Trace(ctx.Err())
  1081. }
  1082. if rt.dialErr != nil {
  1083. // There is no NewRoundTripperFailedError wrapping here, as the
  1084. // DialMeek caller will wrap its error and
  1085. // BrokerClientRoundTripperFailed will be invoked already.
  1086. return nil, errors.Trace(rt.dialErr)
  1087. }
  1088. }
  1089. // At this point, rt.conn is an established MeekConn.
  1090. // Note that the network address portion of the URL will be ignored by
  1091. // MeekConn in favor of the MeekDialConfig, while the path will be used.
  1092. url := fmt.Sprintf(
  1093. "https://%s/%s",
  1094. rt.brokerDialParams.DialAddress,
  1095. inproxy.BrokerEndPointName)
  1096. request, err := http.NewRequestWithContext(
  1097. requestCtx, "POST", url, bytes.NewBuffer(requestPayload))
  1098. if err != nil {
  1099. return nil, errors.Trace(err)
  1100. }
  1101. startTime := time.Now()
  1102. response, err := rt.conn.RoundTrip(request)
  1103. roundTripDuration := time.Since(startTime)
  1104. if err == nil {
  1105. defer response.Body.Close()
  1106. if response.StatusCode != http.StatusOK {
  1107. err = fmt.Errorf(
  1108. "unexpected response status code %d after %v",
  1109. response.StatusCode,
  1110. roundTripDuration)
  1111. // Depending on the round trip duration, this case is treated as a
  1112. // temporary round tripper failure, since we received a response
  1113. // from the CDN, secured with TLS and VerifyPins, or from broker
  1114. // itself. One common scenario is the CDN returning a temporary
  1115. // timeout error, as can happen when CDN timeouts and broker
  1116. // timeouts are misaligned, especially for long-polling requests.
  1117. //
  1118. // In this scenario, we can reuse the existing round tripper and
  1119. // it may be counterproductive to return a RoundTripperFailedError
  1120. // which will trigger a clearing of any broker dial replay
  1121. // parameters as well as reseting the round tripper.
  1122. //
  1123. // When the round trip duration is sufficiently short, much
  1124. // shorter than expected round trip timeouts, this is still
  1125. // classified as a RoundTripperFailedError error, as it is more
  1126. // likely due to a more serious issue between the CDN and broker.
  1127. if rt.failureThreshold > 0 &&
  1128. roundTripDuration <= rt.failureThreshold {
  1129. err = inproxy.NewRoundTripperFailedError(err)
  1130. }
  1131. }
  1132. } else if ctx.Err() != context.Canceled {
  1133. // Other round trip errors, including TLS failures and client-side
  1134. // timeouts, but excluding a cancelled context as happens on
  1135. // shutdown, are classified as RoundTripperFailedErrors.
  1136. err = inproxy.NewRoundTripperFailedError(err)
  1137. }
  1138. if err != nil {
  1139. return nil, errors.Trace(err)
  1140. }
  1141. responsePayload, err := io.ReadAll(response.Body)
  1142. if err != nil {
  1143. err = inproxy.NewRoundTripperFailedError(err)
  1144. return nil, errors.Trace(err)
  1145. }
  1146. return responsePayload, nil
  1147. }
  1148. // InproxyWebRTCDialInstance is the network state and dial parameters for a
  1149. // single WebRTC client or proxy connection.
  1150. //
  1151. // InproxyWebRTCDialInstance implements the inproxy.WebRTCDialCoordinator
  1152. // interface, which provides the WebRTC dial configuration and support to the
  1153. // in-proxy package.
  1154. type InproxyWebRTCDialInstance struct {
  1155. config *Config
  1156. networkID string
  1157. natStateManager *InproxyNATStateManager
  1158. stunDialParameters *InproxySTUNDialParameters
  1159. webRTCDialParameters *InproxyWebRTCDialParameters
  1160. discoverNAT bool
  1161. disableSTUN bool
  1162. disablePortMapping bool
  1163. disableInboundForMobileNetworks bool
  1164. disableIPv6ICECandidates bool
  1165. discoverNATTimeout time.Duration
  1166. webRTCAnswerTimeout time.Duration
  1167. awaitDataChannelTimeout time.Duration
  1168. proxyDestinationDialTimeout time.Duration
  1169. }
  1170. // NewInproxyWebRTCDialInstance creates a new InproxyWebRTCDialInstance.
  1171. //
  1172. // The caller provides STUN and WebRTC dial parameters that are either newly
  1173. // generated or replayed. Proxies may optionally pass in nil for either
  1174. // stunDialParameters or webRTCDialParameters, and new parameters will be
  1175. // generated.
  1176. func NewInproxyWebRTCDialInstance(
  1177. config *Config,
  1178. networkID string,
  1179. isProxy bool,
  1180. natStateManager *InproxyNATStateManager,
  1181. stunDialParameters *InproxySTUNDialParameters,
  1182. webRTCDialParameters *InproxyWebRTCDialParameters) (*InproxyWebRTCDialInstance, error) {
  1183. p := config.GetParameters().Get()
  1184. defer p.Close()
  1185. if isProxy && stunDialParameters == nil {
  1186. // Auto-generate STUN dial parameters. There's no replay in this case.
  1187. var err error
  1188. stunDialParameters, err = MakeInproxySTUNDialParameters(config, p, isProxy)
  1189. if err != nil {
  1190. return nil, errors.Trace(err)
  1191. }
  1192. }
  1193. if isProxy && webRTCDialParameters == nil {
  1194. // Auto-generate STUN dial parameters. There's no replay in this case.
  1195. var err error
  1196. webRTCDialParameters, err = MakeInproxyWebRTCDialParameters(p)
  1197. if err != nil {
  1198. return nil, errors.Trace(err)
  1199. }
  1200. }
  1201. var awaitDataChannelTimeout time.Duration
  1202. if isProxy {
  1203. awaitDataChannelTimeout = p.Duration(parameters.InproxyProxyWebRTCAwaitDataChannelTimeout)
  1204. } else {
  1205. awaitDataChannelTimeout = p.Duration(parameters.InproxyClientWebRTCAwaitDataChannelTimeout)
  1206. }
  1207. // Parameters such as disabling certain operations and operation timeouts
  1208. // are not replayed, but snapshots are stored in the
  1209. // InproxyWebRTCDialInstance for efficient lookup.
  1210. return &InproxyWebRTCDialInstance{
  1211. config: config,
  1212. networkID: networkID,
  1213. natStateManager: natStateManager,
  1214. stunDialParameters: stunDialParameters,
  1215. webRTCDialParameters: webRTCDialParameters,
  1216. discoverNAT: p.WeightedCoinFlip(parameters.InproxyClientDiscoverNATProbability),
  1217. disableSTUN: p.Bool(parameters.InproxyDisableSTUN),
  1218. disablePortMapping: p.Bool(parameters.InproxyDisablePortMapping),
  1219. disableInboundForMobileNetworks: p.Bool(parameters.InproxyDisableInboundForMobileNetworks),
  1220. disableIPv6ICECandidates: p.Bool(parameters.InproxyDisableIPv6ICECandidates),
  1221. discoverNATTimeout: p.Duration(parameters.InproxyDiscoverNATTimeout),
  1222. webRTCAnswerTimeout: p.Duration(parameters.InproxyWebRTCAnswerTimeout),
  1223. awaitDataChannelTimeout: awaitDataChannelTimeout,
  1224. proxyDestinationDialTimeout: p.Duration(parameters.InproxyProxyDestinationDialTimeout),
  1225. }, nil
  1226. }
  1227. // Implements the inproxy.WebRTCDialCoordinator interface.
  1228. func (w *InproxyWebRTCDialInstance) NetworkID() string {
  1229. return w.networkID
  1230. }
  1231. // Implements the inproxy.WebRTCDialCoordinator interface.
  1232. func (w *InproxyWebRTCDialInstance) NetworkType() inproxy.NetworkType {
  1233. return getInproxyNetworkType(GetNetworkType(w.networkID))
  1234. }
  1235. // Implements the inproxy.WebRTCDialCoordinator interface.
  1236. func (w *InproxyWebRTCDialInstance) ClientRootObfuscationSecret() inproxy.ObfuscationSecret {
  1237. return w.webRTCDialParameters.RootObfuscationSecret
  1238. }
  1239. // Implements the inproxy.WebRTCDialCoordinator interface.
  1240. func (w *InproxyWebRTCDialInstance) DoDTLSRandomization() bool {
  1241. return w.webRTCDialParameters.DoDTLSRandomization
  1242. }
  1243. // Implements the inproxy.WebRTCDialCoordinator interface.
  1244. func (w *InproxyWebRTCDialInstance) DataChannelTrafficShapingParameters() *inproxy.DataChannelTrafficShapingParameters {
  1245. return w.webRTCDialParameters.DataChannelTrafficShapingParameters
  1246. }
  1247. // Implements the inproxy.WebRTCDialCoordinator interface.
  1248. func (w *InproxyWebRTCDialInstance) STUNServerAddress(RFC5780 bool) string {
  1249. if RFC5780 {
  1250. return w.stunDialParameters.STUNServerAddressRFC5780
  1251. } else {
  1252. return w.stunDialParameters.STUNServerAddress
  1253. }
  1254. }
  1255. // Implements the inproxy.WebRTCDialCoordinator interface.
  1256. func (w *InproxyWebRTCDialInstance) STUNServerAddressResolved(RFC5780 bool) string {
  1257. if RFC5780 {
  1258. return w.stunDialParameters.STUNServerAddressRFC5780
  1259. } else {
  1260. return w.stunDialParameters.STUNServerAddress
  1261. }
  1262. }
  1263. // Implements the inproxy.WebRTCDialCoordinator interface.
  1264. func (w *InproxyWebRTCDialInstance) STUNServerAddressSucceeded(RFC5780 bool, address string) {
  1265. // Currently, for client tunnel dials, STUN dial parameter replay is
  1266. // managed by DialParameters and DialParameters.InproxySTUNDialParameters
  1267. // are replayed only when the entire dial succeeds.
  1268. //
  1269. // Note that, for a client tunnel dial, even if the STUN step fails and
  1270. // there are no STUN ICE candidates, the subsequent WebRTC connection may
  1271. // still proceed and be successful. In this case, the failed STUN dial
  1272. // parameters may be replayed.
  1273. //
  1274. // For proxies, there is no STUN dial parameter replay.
  1275. //
  1276. // As a future enhancement, consider independent and shared replay of
  1277. // working STUN servers, similar to how broker client dial parameters are
  1278. // replayed independent of overall dials and proxy relays, and shared
  1279. // between local client and proxy instances.
  1280. // Verify/extend the resolver cache entry for any resolved domain after a
  1281. // success.
  1282. resolver := w.config.GetResolver()
  1283. if resolver != nil {
  1284. resolver.VerifyCacheExtension(address)
  1285. }
  1286. }
  1287. // Implements the inproxy.WebRTCDialCoordinator interface.
  1288. func (w *InproxyWebRTCDialInstance) STUNServerAddressFailed(RFC5780 bool, address string) {
  1289. // Currently there is no independent replay for STUN dial parameters. See
  1290. // comment in STUNServerAddressSucceeded.
  1291. }
  1292. // Implements the inproxy.WebRTCDialCoordinator interface.
  1293. func (w *InproxyWebRTCDialInstance) DiscoverNAT() bool {
  1294. return w.discoverNAT
  1295. }
  1296. // Implements the inproxy.WebRTCDialCoordinator interface.
  1297. func (w *InproxyWebRTCDialInstance) DisableSTUN() bool {
  1298. return w.disableSTUN
  1299. }
  1300. // Implements the inproxy.WebRTCDialCoordinator interface.
  1301. func (w *InproxyWebRTCDialInstance) DisablePortMapping() bool {
  1302. return w.disablePortMapping
  1303. }
  1304. // Implements the inproxy.WebRTCDialCoordinator interface.
  1305. func (w *InproxyWebRTCDialInstance) DisableInboundForMobileNetworks() bool {
  1306. return w.disableInboundForMobileNetworks
  1307. }
  1308. // Implements the inproxy.WebRTCDialCoordinator interface.
  1309. func (w *InproxyWebRTCDialInstance) DisableIPv6ICECandidates() bool {
  1310. return w.disableIPv6ICECandidates
  1311. }
  1312. // Implements the inproxy.WebRTCDialCoordinator interface.
  1313. func (w *InproxyWebRTCDialInstance) NATType() inproxy.NATType {
  1314. return w.natStateManager.getNATType(w.networkID)
  1315. }
  1316. // Implements the inproxy.WebRTCDialCoordinator interface.
  1317. func (w *InproxyWebRTCDialInstance) SetNATType(natType inproxy.NATType) {
  1318. w.natStateManager.setNATType(w.networkID, natType)
  1319. }
  1320. // Implements the inproxy.WebRTCDialCoordinator interface.
  1321. func (w *InproxyWebRTCDialInstance) PortMappingTypes() inproxy.PortMappingTypes {
  1322. return w.natStateManager.getPortMappingTypes(w.networkID)
  1323. }
  1324. // Implements the inproxy.WebRTCDialCoordinator interface.
  1325. func (w *InproxyWebRTCDialInstance) SetPortMappingTypes(portMappingTypes inproxy.PortMappingTypes) {
  1326. w.natStateManager.setPortMappingTypes(w.networkID, portMappingTypes)
  1327. }
  1328. // Implements the inproxy.WebRTCDialCoordinator interface.
  1329. func (w *InproxyWebRTCDialInstance) ResolveAddress(ctx context.Context, network, address string) (string, error) {
  1330. // Use the Psiphon resolver to resolve addresses.
  1331. r := w.config.GetResolver()
  1332. if r == nil {
  1333. return "", errors.TraceNew("missing resolver")
  1334. }
  1335. // Identify when the address to be resolved is one of the configured STUN
  1336. // servers, and, in those cases, use/replay any STUN dial parameters
  1337. // ResolveParameters; and record the resolved IP address for metrics.
  1338. //
  1339. // In the in-proxy proxy case, ResolveAddress is invoked for the upstream,
  1340. // 2nd hop dial as well as for STUN server addresses.
  1341. //
  1342. // Limitation: there's no ResolveParameters, including no preresolved DNS
  1343. // tactics, for 2nd hop dials.
  1344. isSTUNServerAddress := address == w.stunDialParameters.STUNServerAddress
  1345. isSTUNServerAddressRFC5780 := address == w.stunDialParameters.STUNServerAddressRFC5780
  1346. var resolveParams *resolver.ResolveParameters
  1347. if isSTUNServerAddress || isSTUNServerAddressRFC5780 {
  1348. resolveParams = w.stunDialParameters.ResolveParameters
  1349. }
  1350. resolved, err := r.ResolveAddress(
  1351. ctx, w.networkID, resolveParams, network, address)
  1352. if err != nil {
  1353. return "", errors.Trace(err)
  1354. }
  1355. // Invoke the resolved IP callbacks only when the input is not the
  1356. // resolved IP address (this differs from the meek
  1357. // DialConfig.ResolvedIPCallback case).
  1358. if resolved != address {
  1359. if isSTUNServerAddress {
  1360. w.stunDialParameters.STUNServerResolvedIPAddress.Store(resolved)
  1361. } else if isSTUNServerAddressRFC5780 {
  1362. w.stunDialParameters.STUNServerRFC5780ResolvedIPAddress.Store(resolved)
  1363. }
  1364. }
  1365. return resolved, nil
  1366. }
  1367. // Implements the inproxy.WebRTCDialCoordinator interface.
  1368. func (w *InproxyWebRTCDialInstance) UDPListen(ctx context.Context) (net.PacketConn, error) {
  1369. // Create a new inproxyUDPConn for use as the in-proxy STUN and/ord WebRTC
  1370. // UDP socket.
  1371. conn, err := newInproxyUDPConn(ctx, w.config)
  1372. if err != nil {
  1373. return nil, errors.Trace(err)
  1374. }
  1375. return conn, nil
  1376. }
  1377. // Implements the inproxy.WebRTCDialCoordinator interface.
  1378. func (w *InproxyWebRTCDialInstance) UDPConn(
  1379. ctx context.Context, network, remoteAddress string) (net.PacketConn, error) {
  1380. // Create a new UDPConn bound to the specified remote address. This UDP
  1381. // conn is used, by the inproxy package, to determine the local address
  1382. // of the active interface the OS will select for the specified remote
  1383. // destination.
  1384. //
  1385. // Only IP address destinations are supported. ResolveIP is wired up only
  1386. // because NewUDPConn requires a non-nil resolver.
  1387. dialConfig := &DialConfig{
  1388. DeviceBinder: w.config.deviceBinder,
  1389. IPv6Synthesizer: w.config.IPv6Synthesizer,
  1390. ResolveIP: func(_ context.Context, hostname string) ([]net.IP, error) {
  1391. IP := net.ParseIP(hostname)
  1392. if IP == nil {
  1393. return nil, errors.TraceNew("not supported")
  1394. }
  1395. return []net.IP{IP}, nil
  1396. },
  1397. }
  1398. conn, _, err := NewUDPConn(ctx, network, true, "", remoteAddress, dialConfig)
  1399. if err != nil {
  1400. return nil, errors.Trace(err)
  1401. }
  1402. return conn, nil
  1403. }
  1404. // Implements the inproxy.WebRTCDialCoordinator interface.
  1405. func (w *InproxyWebRTCDialInstance) BindToDevice(fileDescriptor int) error {
  1406. // Use config.deviceBinder, with wired up logging, not
  1407. // config.DeviceBinder; other tunnel-core dials do this indirectly via
  1408. // psiphon.DialConfig.
  1409. _, err := w.config.deviceBinder.BindToDevice(fileDescriptor)
  1410. return errors.Trace(err)
  1411. }
  1412. // Implements the inproxy.WebRTCDialCoordinator interface.
  1413. func (w *InproxyWebRTCDialInstance) DiscoverNATTimeout() time.Duration {
  1414. return w.discoverNATTimeout
  1415. }
  1416. // Implements the inproxy.WebRTCDialCoordinator interface.
  1417. func (w *InproxyWebRTCDialInstance) WebRTCAnswerTimeout() time.Duration {
  1418. return w.webRTCAnswerTimeout
  1419. }
  1420. // Implements the inproxy.WebRTCDialCoordinator interface.
  1421. func (w *InproxyWebRTCDialInstance) WebRTCAwaitDataChannelTimeout() time.Duration {
  1422. return w.awaitDataChannelTimeout
  1423. }
  1424. // Implements the inproxy.WebRTCDialCoordinator interface.
  1425. func (w *InproxyWebRTCDialInstance) ProxyDestinationDialTimeout() time.Duration {
  1426. return w.proxyDestinationDialTimeout
  1427. }
  1428. // InproxySTUNDialParameters is a set of STUN dial parameters.
  1429. // InproxySTUNDialParameters is compatible with DialParameters JSON
  1430. // marshaling. For client in-proxy tunnel dials, DialParameters will manage
  1431. // STUN dial parameter selection and replay.
  1432. //
  1433. // When an instance of InproxySTUNDialParameters is unmarshaled from JSON,
  1434. // Prepare must be called to initialize the instance for use.
  1435. type InproxySTUNDialParameters struct {
  1436. ResolveParameters *resolver.ResolveParameters
  1437. STUNServerAddress string
  1438. STUNServerAddressRFC5780 string
  1439. STUNServerResolvedIPAddress atomic.Value `json:"-"`
  1440. STUNServerRFC5780ResolvedIPAddress atomic.Value `json:"-"`
  1441. }
  1442. // MakeInproxySTUNDialParameters generates new STUN dial parameters from the
  1443. // given tactics parameters.
  1444. func MakeInproxySTUNDialParameters(
  1445. config *Config,
  1446. p parameters.ParametersAccessor,
  1447. isProxy bool) (*InproxySTUNDialParameters, error) {
  1448. var stunServerAddresses, stunServerAddressesRFC5780 []string
  1449. if isProxy {
  1450. stunServerAddresses = p.Strings(
  1451. parameters.InproxyProxySTUNServerAddresses, parameters.InproxySTUNServerAddresses)
  1452. stunServerAddressesRFC5780 = p.Strings(
  1453. parameters.InproxyProxySTUNServerAddressesRFC5780, parameters.InproxySTUNServerAddressesRFC5780)
  1454. } else {
  1455. stunServerAddresses = p.Strings(
  1456. parameters.InproxyClientSTUNServerAddresses, parameters.InproxySTUNServerAddresses)
  1457. stunServerAddressesRFC5780 = p.Strings(
  1458. parameters.InproxyClientSTUNServerAddressesRFC5780, parameters.InproxySTUNServerAddressesRFC5780)
  1459. }
  1460. // Empty STUN server address lists are not an error condition. When used
  1461. // for WebRTC, the STUN ICE candidate gathering will be skipped but the
  1462. // WebRTC connection may still be established via other candidate types.
  1463. var stunServerAddress, stunServerAddressRFC5780 string
  1464. if len(stunServerAddresses) > 0 {
  1465. stunServerAddress = stunServerAddresses[prng.Range(0, len(stunServerAddresses)-1)]
  1466. }
  1467. if len(stunServerAddressesRFC5780) > 0 {
  1468. stunServerAddressRFC5780 =
  1469. stunServerAddressesRFC5780[prng.Range(0, len(stunServerAddressesRFC5780)-1)]
  1470. }
  1471. // Create DNS resolver dial parameters to use when resolving STUN server
  1472. // domain addresses. Instantiate only when there is a domain to be
  1473. // resolved; when recording DNS fields, GetMetrics will assume that a nil
  1474. // InproxySTUNDialParameters.ResolveParameters implies no resolve was
  1475. // attempted.
  1476. var resolveParameters *resolver.ResolveParameters
  1477. if (stunServerAddress != "" && net.ParseIP(stunServerAddress) == nil) ||
  1478. (stunServerAddressRFC5780 != "" && net.ParseIP(stunServerAddressRFC5780) == nil) {
  1479. // No DNSResolverPreresolvedIPAddressCIDRs will be selected since no
  1480. // fronting provider ID is specified.
  1481. //
  1482. // It would be possible to overload the meaning of the fronting
  1483. // provider ID field by using a string derived from STUN server
  1484. // address as the key.
  1485. //
  1486. // However, preresolved STUN configuration can already be achieved
  1487. // with IP addresses in the STUNServerAddresses tactics parameters.
  1488. // This approach results in slightly different metrics log fields vs.
  1489. // preresolved.
  1490. var err error
  1491. resolveParameters, err = config.GetResolver().MakeResolveParameters(p, "", "")
  1492. if err != nil {
  1493. return nil, errors.Trace(err)
  1494. }
  1495. }
  1496. dialParams := &InproxySTUNDialParameters{
  1497. ResolveParameters: resolveParameters,
  1498. STUNServerAddress: stunServerAddress,
  1499. STUNServerAddressRFC5780: stunServerAddressRFC5780,
  1500. }
  1501. dialParams.Prepare()
  1502. return dialParams, nil
  1503. }
  1504. // Prepare initializes an InproxySTUNDialParameters for use. Prepare should be
  1505. // called for any InproxySTUNDialParameters instance unmarshaled from JSON.
  1506. func (dialParams *InproxySTUNDialParameters) Prepare() {
  1507. dialParams.STUNServerResolvedIPAddress.Store("")
  1508. dialParams.STUNServerRFC5780ResolvedIPAddress.Store("")
  1509. }
  1510. // IsValidClientReplay checks that the selected STUN servers remain configured
  1511. // STUN server candidates for in-proxy clients.
  1512. func (dialParams *InproxySTUNDialParameters) IsValidClientReplay(
  1513. p parameters.ParametersAccessor) bool {
  1514. return (dialParams.STUNServerAddress == "" ||
  1515. common.Contains(
  1516. p.Strings(parameters.InproxyClientSTUNServerAddresses),
  1517. dialParams.STUNServerAddress)) &&
  1518. (dialParams.STUNServerAddressRFC5780 == "" ||
  1519. common.Contains(
  1520. p.Strings(parameters.InproxyClientSTUNServerAddressesRFC5780),
  1521. dialParams.STUNServerAddressRFC5780))
  1522. }
  1523. // GetMetrics implements the common.MetricsSource interface and returns log
  1524. // fields detailing the STUN dial parameters.
  1525. func (dialParams *InproxySTUNDialParameters) GetMetrics() common.LogFields {
  1526. // There is no is_replay-type field added here; replay is handled at a
  1527. // higher level, and, for client in-proxy tunnel dials, is part of the
  1528. // main tunnel dial parameters.
  1529. logFields := make(common.LogFields)
  1530. logFields["inproxy_webrtc_stun_server"] = dialParams.STUNServerAddress
  1531. resolvedIPAddress := dialParams.STUNServerResolvedIPAddress.Load().(string)
  1532. if resolvedIPAddress != "" {
  1533. logFields["inproxy_webrtc_stun_server_resolved_ip_address"] = resolvedIPAddress
  1534. }
  1535. // TODO: log RFC5780 selection only if used?
  1536. logFields["inproxy_webrtc_stun_server_RFC5780"] = dialParams.STUNServerAddressRFC5780
  1537. resolvedIPAddress = dialParams.STUNServerRFC5780ResolvedIPAddress.Load().(string)
  1538. if resolvedIPAddress != "" {
  1539. logFields["inproxy_webrtc_stun_server_RFC5780_resolved_ip_address"] = resolvedIPAddress
  1540. }
  1541. if dialParams.ResolveParameters != nil {
  1542. // See comment in getBaseAPIParameters regarding
  1543. // dialParams.ResolveParameters handling. As noted in
  1544. // MakeInproxySTUNDialParameters, no preresolved parameters are set,
  1545. // so none are checked for logging.
  1546. //
  1547. // Limitation: the potential use of single ResolveParameters to
  1548. // resolve multiple, different STUN server domains can skew the
  1549. // meaning of GetFirstAttemptWithAnswer.
  1550. if dialParams.ResolveParameters.PreferAlternateDNSServer {
  1551. logFields["inproxy_webrtc_dns_preferred"] = dialParams.ResolveParameters.AlternateDNSServer
  1552. }
  1553. if dialParams.ResolveParameters.ProtocolTransformName != "" {
  1554. logFields["inproxy_webrtc_dns_transform"] = dialParams.ResolveParameters.ProtocolTransformName
  1555. }
  1556. logFields["inproxy_webrtc_dns_attempt"] = strconv.Itoa(
  1557. dialParams.ResolveParameters.GetFirstAttemptWithAnswer())
  1558. }
  1559. return logFields
  1560. }
  1561. // InproxyWebRTCDialParameters is a set of WebRTC obfuscation dial parameters.
  1562. // InproxyWebRTCDialParameters is compatible with DialParameters JSON
  1563. // marshaling. For client in-proxy tunnel dials, DialParameters will manage
  1564. // WebRTC dial parameter selection and replay.
  1565. type InproxyWebRTCDialParameters struct {
  1566. RootObfuscationSecret inproxy.ObfuscationSecret
  1567. DataChannelTrafficShapingParameters *inproxy.DataChannelTrafficShapingParameters
  1568. DoDTLSRandomization bool
  1569. }
  1570. // MakeInproxyWebRTCDialParameters generates new InproxyWebRTCDialParameters.
  1571. func MakeInproxyWebRTCDialParameters(
  1572. p parameters.ParametersAccessor) (*InproxyWebRTCDialParameters, error) {
  1573. rootObfuscationSecret, err := inproxy.GenerateRootObfuscationSecret()
  1574. if err != nil {
  1575. return nil, errors.Trace(err)
  1576. }
  1577. var trafficSharingParams inproxy.DataChannelTrafficShapingParameters
  1578. if p.WeightedCoinFlip(parameters.InproxyDataChannelTrafficShapingProbability) {
  1579. trafficSharingParams = inproxy.DataChannelTrafficShapingParameters(
  1580. p.InproxyDataChannelTrafficShapingParameters(
  1581. parameters.InproxyDataChannelTrafficShapingParameters))
  1582. }
  1583. doDTLSRandomization := p.WeightedCoinFlip(parameters.InproxyDTLSRandomizationProbability)
  1584. return &InproxyWebRTCDialParameters{
  1585. RootObfuscationSecret: rootObfuscationSecret,
  1586. DataChannelTrafficShapingParameters: &trafficSharingParams,
  1587. DoDTLSRandomization: doDTLSRandomization,
  1588. }, nil
  1589. }
  1590. // GetMetrics implements the common.MetricsSource interface.
  1591. func (dialParams *InproxyWebRTCDialParameters) GetMetrics() common.LogFields {
  1592. // There is no is_replay-type field added here; replay is handled at a
  1593. // higher level, and, for client in-proxy tunnel dials, is part of the
  1594. // main tunnel dial parameters.
  1595. // Currently, all WebRTC metrics are delivered via
  1596. // inproxy.ClientConn/WebRTCConn GetMetrics.
  1597. return common.LogFields{}
  1598. }
  1599. // InproxyNATStateManager manages the NAT-related network topology state for
  1600. // the current network, caching the discovered network NAT type and supported
  1601. // port mapping types, if any.
  1602. type InproxyNATStateManager struct {
  1603. config *Config
  1604. mutex sync.Mutex
  1605. networkID string
  1606. natType inproxy.NATType
  1607. portMappingTypes inproxy.PortMappingTypes
  1608. }
  1609. // NewInproxyNATStateManager creates a new InproxyNATStateManager.
  1610. func NewInproxyNATStateManager(config *Config) *InproxyNATStateManager {
  1611. s := &InproxyNATStateManager{
  1612. config: config,
  1613. natType: inproxy.NATTypeUnknown,
  1614. portMappingTypes: inproxy.PortMappingTypes{},
  1615. }
  1616. s.reset()
  1617. return s
  1618. }
  1619. // TacticsApplied implements the TacticsAppliedReceiver interface, and is
  1620. // called when tactics have changed, which triggers a cached NAT state reset
  1621. // in order to apply potentially changed parameters.
  1622. func (s *InproxyNATStateManager) TacticsApplied() error {
  1623. s.reset()
  1624. return nil
  1625. }
  1626. func (s *InproxyNATStateManager) reset() {
  1627. // Assumes s.mutex lock is held.
  1628. networkID := s.config.GetNetworkID()
  1629. s.networkID = networkID
  1630. s.natType = inproxy.NATTypeUnknown
  1631. s.portMappingTypes = inproxy.PortMappingTypes{}
  1632. }
  1633. func (s *InproxyNATStateManager) getNATType(
  1634. networkID string) inproxy.NATType {
  1635. s.mutex.Lock()
  1636. defer s.mutex.Unlock()
  1637. if s.networkID != networkID {
  1638. return inproxy.NATTypeUnknown
  1639. }
  1640. return s.natType
  1641. }
  1642. func (s *InproxyNATStateManager) setNATType(
  1643. networkID string, natType inproxy.NATType) {
  1644. s.mutex.Lock()
  1645. defer s.mutex.Unlock()
  1646. if s.networkID != networkID {
  1647. return
  1648. }
  1649. s.natType = natType
  1650. }
  1651. func (s *InproxyNATStateManager) getPortMappingTypes(
  1652. networkID string) inproxy.PortMappingTypes {
  1653. s.mutex.Lock()
  1654. defer s.mutex.Unlock()
  1655. if s.networkID != networkID {
  1656. return inproxy.PortMappingTypes{}
  1657. }
  1658. return s.portMappingTypes
  1659. }
  1660. func (s *InproxyNATStateManager) setPortMappingTypes(
  1661. networkID string, portMappingTypes inproxy.PortMappingTypes) {
  1662. s.mutex.Lock()
  1663. defer s.mutex.Unlock()
  1664. if s.networkID != networkID {
  1665. return
  1666. }
  1667. s.portMappingTypes = portMappingTypes
  1668. }
  1669. // inproxyUDPConn is based on NewUDPConn and includes the write timeout
  1670. // workaround from common.WriteTimeoutUDPConn.
  1671. //
  1672. // inproxyUDPConn expands the NewUDPConn IPv6Synthesizer to support many
  1673. // destination addresses, as the inproxyUDPConn will be used to send/receive
  1674. // packets between many remote destination addresses.
  1675. //
  1676. // inproxyUDPConn implements the net.PacketConn interface.
  1677. type inproxyUDPConn struct {
  1678. udpConn *net.UDPConn
  1679. ipv6Synthesizer IPv6Synthesizer
  1680. synthesizerMutex sync.Mutex
  1681. ipv4ToIPv6 map[netip.Addr]net.IP
  1682. ipv6ToIPv4 map[netip.Addr]net.IP
  1683. }
  1684. func newInproxyUDPConn(ctx context.Context, config *Config) (net.PacketConn, error) {
  1685. listen := &net.ListenConfig{
  1686. Control: func(_, _ string, c syscall.RawConn) error {
  1687. var controlErr error
  1688. err := c.Control(func(fd uintptr) {
  1689. socketFD := int(fd)
  1690. setAdditionalSocketOptions(socketFD)
  1691. // Use config.deviceBinder, with wired up logging, not
  1692. // config.DeviceBinder; other tunnel-core dials do this
  1693. // indirectly via psiphon.DialConfig.
  1694. if config.deviceBinder != nil {
  1695. _, err := config.deviceBinder.BindToDevice(socketFD)
  1696. if err != nil {
  1697. controlErr = errors.Tracef("BindToDevice failed: %s", err)
  1698. return
  1699. }
  1700. }
  1701. })
  1702. if controlErr != nil {
  1703. return errors.Trace(controlErr)
  1704. }
  1705. return errors.Trace(err)
  1706. },
  1707. }
  1708. // Create an "unconnected" UDP socket for use with WriteTo and listening
  1709. // on all interfaces. See the limitation comment in NewUDPConn regarding
  1710. // its equivilent mode.
  1711. packetConn, err := listen.ListenPacket(ctx, "udp", "")
  1712. if err != nil {
  1713. return nil, errors.Trace(err)
  1714. }
  1715. var ok bool
  1716. udpConn, ok := packetConn.(*net.UDPConn)
  1717. if !ok {
  1718. return nil, errors.Tracef("unexpected conn type: %T", packetConn)
  1719. }
  1720. conn := &inproxyUDPConn{
  1721. udpConn: udpConn,
  1722. ipv6Synthesizer: config.IPv6Synthesizer,
  1723. }
  1724. if conn.ipv6Synthesizer != nil {
  1725. conn.ipv4ToIPv6 = make(map[netip.Addr]net.IP)
  1726. conn.ipv6ToIPv4 = make(map[netip.Addr]net.IP)
  1727. }
  1728. return conn, nil
  1729. }
  1730. func inproxyUDPAddrFromAddrPort(addrPort netip.AddrPort) *net.UDPAddr {
  1731. return &net.UDPAddr{
  1732. IP: addrPort.Addr().AsSlice(),
  1733. Port: int(addrPort.Port()),
  1734. }
  1735. }
  1736. func (conn *inproxyUDPConn) ReadFrom(p []byte) (int, net.Addr, error) {
  1737. // net.UDPConn.ReadFrom currently allocates a &UDPAddr{} per call, and so
  1738. // the &net.UDPAddr{} allocations done in the following synthesizer code
  1739. // path are no more than the standard code path.
  1740. //
  1741. // TODO: avoid all address allocations in both ReadFrom and WriteTo by:
  1742. //
  1743. // - changing ipvXToIPvY to map[netip.AddrPort]*net.UDPAddr
  1744. // - using a similar lookup for the non-synthesizer code path
  1745. //
  1746. // Such a scheme would work only if the caller is guaranteed to not mutate
  1747. // the returned net.Addr.
  1748. if conn.ipv6Synthesizer == nil {
  1749. // Do not wrap any I/O err returned by UDPConn
  1750. return conn.udpConn.ReadFrom(p)
  1751. }
  1752. n, addrPort, err := conn.udpConn.ReadFromUDPAddrPort(p)
  1753. // Reverse any synthesized address before returning err.
  1754. // Reverse the IPv6 synthesizer, returning the original IPv4 address
  1755. // as expected by the caller, including pion/webrtc. This logic
  1756. // assumes that no synthesized IPv6 address will conflict with any
  1757. // real IPv6 address.
  1758. var IP net.IP
  1759. ipAddr := addrPort.Addr()
  1760. if ipAddr.Is6() {
  1761. conn.synthesizerMutex.Lock()
  1762. IP, _ = conn.ipv6ToIPv4[ipAddr]
  1763. conn.synthesizerMutex.Unlock()
  1764. }
  1765. if IP == nil {
  1766. IP = ipAddr.AsSlice()
  1767. }
  1768. // Do not wrap any I/O err returned by UDPConn
  1769. return n, &net.UDPAddr{IP: IP, Port: int(addrPort.Port())}, err
  1770. }
  1771. func (conn *inproxyUDPConn) WriteTo(b []byte, addr net.Addr) (int, error) {
  1772. // See common.WriteTimeoutUDPConn.
  1773. err := conn.udpConn.SetWriteDeadline(
  1774. time.Now().Add(common.UDP_PACKET_WRITE_TIMEOUT))
  1775. if err != nil {
  1776. return 0, errors.Trace(err)
  1777. }
  1778. if conn.ipv6Synthesizer == nil {
  1779. // Do not wrap any I/O err returned by UDPConn
  1780. return conn.udpConn.WriteTo(b, addr)
  1781. }
  1782. // When configured, attempt to synthesize IPv6 addresses from an IPv4
  1783. // addresses for compatibility on DNS64/NAT64 networks.
  1784. //
  1785. // Store any synthesized addresses in a lookup table and reuse for
  1786. // subsequent writes to the same destination as well as reversing the
  1787. // conversion on reads.
  1788. //
  1789. // If synthesize fails, fall back to trying the original address.
  1790. // The netip.Addr type is used as the map key and the input address is
  1791. // assumed to be of the type *net.UDPAddr. This allows for more efficient
  1792. // lookup operations vs. a string key and parsing the input address via
  1793. // addr.String()/net.SplitHostPort().
  1794. udpAddr, ok := addr.(*net.UDPAddr)
  1795. if !ok {
  1796. return 0, errors.Tracef("unexpected addr type: %T", addr)
  1797. }
  1798. // Stack allocate to avoid an extra heap allocation per write.
  1799. var synthesizedAddr net.UDPAddr
  1800. if udpAddr.IP.To4() != nil {
  1801. ip4Addr, ok := netip.AddrFromSlice(udpAddr.IP)
  1802. if !ok {
  1803. return 0, errors.Tracef("invalid addr")
  1804. }
  1805. conn.synthesizerMutex.Lock()
  1806. synthesizedIP, ok := conn.ipv4ToIPv6[ip4Addr]
  1807. conn.synthesizerMutex.Unlock()
  1808. if ok {
  1809. synthesizedAddr = net.UDPAddr{IP: synthesizedIP, Port: udpAddr.Port}
  1810. } else {
  1811. synthesized := conn.ipv6Synthesizer.IPv6Synthesize(udpAddr.IP.String())
  1812. if synthesized != "" {
  1813. synthesizedIP := net.ParseIP(synthesized)
  1814. if synthesizedIP != nil {
  1815. conn.synthesizerMutex.Lock()
  1816. conn.ipv4ToIPv6[ip4Addr] = synthesizedIP
  1817. ipv6Addr, _ := netip.AddrFromSlice(synthesizedIP)
  1818. conn.ipv6ToIPv4[ipv6Addr] = udpAddr.IP
  1819. conn.synthesizerMutex.Unlock()
  1820. synthesizedAddr = net.UDPAddr{IP: synthesizedIP, Port: udpAddr.Port}
  1821. }
  1822. }
  1823. }
  1824. }
  1825. if synthesizedAddr.IP == nil {
  1826. // Do not wrap any I/O err returned by UDPConn
  1827. return conn.udpConn.WriteTo(b, addr)
  1828. }
  1829. return conn.udpConn.WriteTo(b, &synthesizedAddr)
  1830. }
  1831. func (conn *inproxyUDPConn) Close() error {
  1832. // Do not wrap any I/O err returned by UDPConn
  1833. return conn.udpConn.Close()
  1834. }
  1835. func (conn *inproxyUDPConn) LocalAddr() net.Addr {
  1836. // Do not wrap any I/O err returned by UDPConn
  1837. return conn.udpConn.LocalAddr()
  1838. }
  1839. func (conn *inproxyUDPConn) SetDeadline(t time.Time) error {
  1840. // Do not wrap any I/O err returned by UDPConn
  1841. return conn.udpConn.SetDeadline(t)
  1842. }
  1843. func (conn *inproxyUDPConn) SetReadDeadline(t time.Time) error {
  1844. // Do not wrap any I/O err returned by UDPConn
  1845. return conn.udpConn.SetReadDeadline(t)
  1846. }
  1847. func (conn *inproxyUDPConn) SetWriteDeadline(t time.Time) error {
  1848. // Do not wrap any I/O err returned by UDPConn
  1849. return conn.udpConn.SetWriteDeadline(t)
  1850. }
  1851. // getInproxyNetworkType converts a legacy string network type to an inproxy
  1852. // package type.
  1853. func getInproxyNetworkType(networkType string) inproxy.NetworkType {
  1854. // There is no VPN type conversion; clients and proxies will skip/fail
  1855. // in-proxy operations on non-Psiphon VPN networks.
  1856. switch networkType {
  1857. case "WIFI":
  1858. return inproxy.NetworkTypeWiFi
  1859. case "MOBILE":
  1860. return inproxy.NetworkTypeMobile
  1861. }
  1862. return inproxy.NetworkTypeUnknown
  1863. }