inproxy.go 88 KB

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