inproxy.go 90 KB

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