inproxy.go 85 KB

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