inproxy.go 85 KB

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