inproxy.go 79 KB

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