inproxy.go 81 KB

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