inproxy.go 90 KB

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