inproxy.go 80 KB

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