inproxy.go 85 KB

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