inproxy.go 85 KB

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