inproxy.go 91 KB

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