inproxy.go 80 KB

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