dialParameters.go 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347
  1. /*
  2. * Copyright (c) 2018, 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. "crypto/md5"
  24. "encoding/binary"
  25. "net"
  26. "net/http"
  27. "strconv"
  28. "strings"
  29. "sync/atomic"
  30. "time"
  31. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/fragmentor"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/resolver"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/values"
  39. utls "github.com/refraction-networking/utls"
  40. regen "github.com/zach-klippenstein/goregen"
  41. "golang.org/x/net/bpf"
  42. )
  43. // DialParameters represents a selected protocol and all the related selected
  44. // protocol attributes, many chosen at random, for a tunnel dial attempt.
  45. //
  46. // DialParameters is used:
  47. // - to configure dialers
  48. // - as a persistent record to store successful dial parameters for replay
  49. // - to report dial stats in notices and Psiphon API calls.
  50. //
  51. // MeekResolvedIPAddress is set asynchronously, as it is not known until the
  52. // dial process has begun. The atomic.Value will contain a string, initialized
  53. // to "", and set to the resolved IP address once that part of the dial
  54. // process has completed.
  55. //
  56. // DialParameters is not safe for concurrent use.
  57. type DialParameters struct {
  58. ServerEntry *protocol.ServerEntry `json:"-"`
  59. NetworkID string `json:"-"`
  60. IsReplay bool `json:"-"`
  61. CandidateNumber int `json:"-"`
  62. EstablishedTunnelsCount int `json:"-"`
  63. IsExchanged bool
  64. LastUsedTimestamp time.Time
  65. LastUsedConfigStateHash []byte
  66. NetworkLatencyMultiplier float64
  67. TunnelProtocol string
  68. DirectDialAddress string
  69. DialPortNumber string
  70. UpstreamProxyType string `json:"-"`
  71. UpstreamProxyCustomHeaderNames []string `json:"-"`
  72. BPFProgramName string
  73. BPFProgramInstructions []bpf.RawInstruction
  74. SelectedSSHClientVersion bool
  75. SSHClientVersion string
  76. SSHKEXSeed *prng.Seed
  77. ObfuscatorPaddingSeed *prng.Seed
  78. FragmentorSeed *prng.Seed
  79. FrontingProviderID string
  80. MeekFrontingDialAddress string
  81. MeekFrontingHost string
  82. MeekDialAddress string
  83. MeekTransformedHostName bool
  84. MeekSNIServerName string
  85. MeekVerifyServerName string
  86. MeekVerifyPins []string
  87. MeekHostHeader string
  88. MeekObfuscatorPaddingSeed *prng.Seed
  89. MeekTLSPaddingSize int
  90. MeekResolvedIPAddress atomic.Value `json:"-"`
  91. SelectedUserAgent bool
  92. UserAgent string
  93. SelectedTLSProfile bool
  94. TLSProfile string
  95. NoDefaultTLSSessionID bool
  96. TLSVersion string
  97. RandomizedTLSProfileSeed *prng.Seed
  98. QUICVersion string
  99. QUICDialSNIAddress string
  100. QUICClientHelloSeed *prng.Seed
  101. ObfuscatedQUICPaddingSeed *prng.Seed
  102. QUICDisablePathMTUDiscovery bool
  103. ConjureCachedRegistrationTTL time.Duration
  104. ConjureAPIRegistration bool
  105. ConjureAPIRegistrarBidirectionalURL string
  106. ConjureAPIRegistrarDelay time.Duration
  107. ConjureDecoyRegistration bool
  108. ConjureDecoyRegistrarDelay time.Duration
  109. ConjureDecoyRegistrarWidth int
  110. ConjureTransport string
  111. LivenessTestSeed *prng.Seed
  112. APIRequestPaddingSeed *prng.Seed
  113. HoldOffTunnelDuration time.Duration
  114. DialConnMetrics common.MetricsSource `json:"-"`
  115. ObfuscatedSSHConnMetrics common.MetricsSource `json:"-"`
  116. DialDuration time.Duration `json:"-"`
  117. resolver *resolver.Resolver `json:"-"`
  118. ResolveParameters *resolver.ResolveParameters
  119. dialConfig *DialConfig `json:"-"`
  120. meekConfig *MeekConfig `json:"-"`
  121. }
  122. // MakeDialParameters creates a new DialParameters for the candidate server
  123. // entry, including selecting a protocol and all the various protocol
  124. // attributes. The input selectProtocol is used to comply with any active
  125. // protocol selection constraints.
  126. //
  127. // When stored dial parameters are available and may be used,
  128. // MakeDialParameters may replay previous dial parameters in an effort to
  129. // leverage "known working" values instead of always chosing at random from a
  130. // large space.
  131. //
  132. // MakeDialParameters will return nil/nil in cases where the candidate server
  133. // entry should be skipped.
  134. //
  135. // To support replay, the caller must call DialParameters.Succeeded when a
  136. // successful tunnel is established with the returned DialParameters; and must
  137. // call DialParameters.Failed when a tunnel dial or activation fails, except
  138. // when establishment is cancelled.
  139. func MakeDialParameters(
  140. config *Config,
  141. upstreamProxyErrorCallback func(error),
  142. canReplay func(serverEntry *protocol.ServerEntry, replayProtocol string) bool,
  143. selectProtocol func(serverEntry *protocol.ServerEntry) (string, bool),
  144. serverEntry *protocol.ServerEntry,
  145. isTactics bool,
  146. candidateNumber int,
  147. establishedTunnelsCount int) (*DialParameters, error) {
  148. networkID := config.GetNetworkID()
  149. p := config.GetParameters().Get()
  150. ttl := p.Duration(parameters.ReplayDialParametersTTL)
  151. replayBPF := p.Bool(parameters.ReplayBPF)
  152. replaySSH := p.Bool(parameters.ReplaySSH)
  153. replayObfuscatorPadding := p.Bool(parameters.ReplayObfuscatorPadding)
  154. replayFragmentor := p.Bool(parameters.ReplayFragmentor)
  155. replayTLSProfile := p.Bool(parameters.ReplayTLSProfile)
  156. replayRandomizedTLSProfile := p.Bool(parameters.ReplayRandomizedTLSProfile)
  157. replayFronting := p.Bool(parameters.ReplayFronting)
  158. replayHostname := p.Bool(parameters.ReplayHostname)
  159. replayQUICVersion := p.Bool(parameters.ReplayQUICVersion)
  160. replayObfuscatedQUIC := p.Bool(parameters.ReplayObfuscatedQUIC)
  161. replayConjureRegistration := p.Bool(parameters.ReplayConjureRegistration)
  162. replayConjureTransport := p.Bool(parameters.ReplayConjureTransport)
  163. replayLivenessTest := p.Bool(parameters.ReplayLivenessTest)
  164. replayUserAgent := p.Bool(parameters.ReplayUserAgent)
  165. replayAPIRequestPadding := p.Bool(parameters.ReplayAPIRequestPadding)
  166. replayHoldOffTunnel := p.Bool(parameters.ReplayHoldOffTunnel)
  167. replayResolveParameters := p.Bool(parameters.ReplayResolveParameters)
  168. // Check for existing dial parameters for this server/network ID.
  169. dialParams, err := GetDialParameters(
  170. config, serverEntry.IpAddress, networkID)
  171. if err != nil {
  172. NoticeWarning("GetDialParameters failed: %s", err)
  173. dialParams = nil
  174. // Proceed, without existing dial parameters.
  175. }
  176. // Check if replay is permitted:
  177. // - TTL must be > 0 and existing dial parameters must not have expired
  178. // as indicated by LastUsedTimestamp + TTL.
  179. // - Config/tactics/server entry values must be unchanged from when
  180. // previous dial parameters were established.
  181. // - The protocol selection constraints must permit replay, as indicated
  182. // by canReplay.
  183. // - Must not be using an obsolete TLS profile that is no longer supported.
  184. // - Must be using the latest Conjure API URL.
  185. //
  186. // When existing dial parameters don't meet these conditions, dialParams
  187. // is reset to nil and new dial parameters will be generated.
  188. var currentTimestamp time.Time
  189. var configStateHash []byte
  190. // When TTL is 0, replay is disabled; the timestamp remains 0 and the
  191. // output DialParameters will not be stored by Success.
  192. if ttl > 0 {
  193. currentTimestamp = time.Now()
  194. configStateHash = getConfigStateHash(config, p, serverEntry)
  195. }
  196. if dialParams != nil &&
  197. (ttl <= 0 ||
  198. dialParams.LastUsedTimestamp.Before(currentTimestamp.Add(-ttl)) ||
  199. !bytes.Equal(dialParams.LastUsedConfigStateHash, configStateHash) ||
  200. (dialParams.TLSProfile != "" &&
  201. !common.Contains(protocol.SupportedTLSProfiles, dialParams.TLSProfile)) ||
  202. (dialParams.QUICVersion != "" &&
  203. !common.Contains(protocol.SupportedQUICVersions, dialParams.QUICVersion)) ||
  204. // Legacy clients use ConjureAPIRegistrarURL with
  205. // gotapdance.tapdance.APIRegistrar and new clients use
  206. // ConjureAPIRegistrarBidirectionalURL with
  207. // gotapdance.tapdance.APIRegistrarBidirectional. Updated clients
  208. // may have replay dial parameters with the old
  209. // ConjureAPIRegistrarURL field, which is now ignored. In this
  210. // case, ConjureAPIRegistrarBidirectionalURL will be blank. Reset
  211. // this replay.
  212. (dialParams.ConjureAPIRegistration && dialParams.ConjureAPIRegistrarBidirectionalURL == "")) {
  213. // In these cases, existing dial parameters are expired or no longer
  214. // match the config state and so are cleared to avoid rechecking them.
  215. err = DeleteDialParameters(serverEntry.IpAddress, networkID)
  216. if err != nil {
  217. NoticeWarning("DeleteDialParameters failed: %s", err)
  218. }
  219. dialParams = nil
  220. }
  221. if dialParams != nil {
  222. if config.DisableReplay ||
  223. !canReplay(serverEntry, dialParams.TunnelProtocol) {
  224. // In these ephemeral cases, existing dial parameters may still be valid
  225. // and used in future establishment phases, and so are retained.
  226. dialParams = nil
  227. }
  228. }
  229. // IsExchanged:
  230. //
  231. // Dial parameters received via client-to-client exchange are partially
  232. // initialized. Only the exchange fields are retained, and all other dial
  233. // parameters fields must be initialized. This is not considered or logged as
  234. // a replay. The exchange case is identified by the IsExchanged flag.
  235. //
  236. // When previously stored, IsExchanged dial parameters will have set the same
  237. // timestamp and state hash used for regular dial parameters and the same
  238. // logic above should invalidate expired or invalid exchanged dial
  239. // parameters.
  240. //
  241. // Limitation: metrics will indicate when an exchanged server entry is used
  242. // (source "EXCHANGED") but will not indicate when exchanged dial parameters
  243. // are used vs. a redial after discarding dial parameters.
  244. isReplay := (dialParams != nil)
  245. isExchanged := isReplay && dialParams.IsExchanged
  246. if !isReplay {
  247. dialParams = &DialParameters{}
  248. }
  249. // Point to the current resolver to be used in dials.
  250. dialParams.resolver = config.GetResolver()
  251. if dialParams.resolver == nil {
  252. return nil, errors.TraceNew("missing resolver")
  253. }
  254. if isExchanged {
  255. // Set isReplay to false to cause all non-exchanged values to be
  256. // initialized; this also causes the exchange case to not log as replay.
  257. isReplay = false
  258. }
  259. // Set IsExchanged such that full dial parameters are stored and replayed
  260. // upon success.
  261. dialParams.IsExchanged = false
  262. dialParams.ServerEntry = serverEntry
  263. dialParams.NetworkID = networkID
  264. dialParams.IsReplay = isReplay
  265. dialParams.CandidateNumber = candidateNumber
  266. dialParams.EstablishedTunnelsCount = establishedTunnelsCount
  267. // Even when replaying, LastUsedTimestamp is updated to extend the TTL of
  268. // replayed dial parameters which will be updated in the datastore upon
  269. // success.
  270. dialParams.LastUsedTimestamp = currentTimestamp
  271. dialParams.LastUsedConfigStateHash = configStateHash
  272. // Initialize dial parameters.
  273. //
  274. // When not replaying, all required parameters are initialized. When
  275. // replaying, existing parameters are retaing, subject to the replay-X
  276. // tactics flags.
  277. // Select a network latency multiplier for this dial. This allows clients to
  278. // explore and discover timeout values appropriate for the current network.
  279. // The selection applies per tunnel, to avoid delaying all establishment
  280. // candidates due to excessive timeouts. The random selection is bounded by a
  281. // min/max set in tactics and an exponential distribution is used so as to
  282. // heavily favor values close to the min, which should be set to the
  283. // singleton NetworkLatencyMultiplier tactics value.
  284. //
  285. // For NetworkLatencyMultiplierLambda close to 2.0, values near min are
  286. // very approximately 10x more likely to be selected than values near
  287. // max, while for NetworkLatencyMultiplierLambda close to 0.1, the
  288. // distribution is close to uniform.
  289. //
  290. // Not all existing, persisted DialParameters will have a custom
  291. // NetworkLatencyMultiplier value. Its zero value will cause the singleton
  292. // NetworkLatencyMultiplier tactics value to be used instead, which is
  293. // consistent with the pre-custom multiplier behavior in the older client
  294. // version which persisted that DialParameters.
  295. networkLatencyMultiplierMin := p.Float(parameters.NetworkLatencyMultiplierMin)
  296. networkLatencyMultiplierMax := p.Float(parameters.NetworkLatencyMultiplierMax)
  297. if !isReplay ||
  298. // Was selected...
  299. (dialParams.NetworkLatencyMultiplier != 0.0 &&
  300. // But is now outside tactics range...
  301. (dialParams.NetworkLatencyMultiplier < networkLatencyMultiplierMin ||
  302. dialParams.NetworkLatencyMultiplier > networkLatencyMultiplierMax)) {
  303. dialParams.NetworkLatencyMultiplier = prng.ExpFloat64Range(
  304. networkLatencyMultiplierMin,
  305. networkLatencyMultiplierMax,
  306. p.Float(parameters.NetworkLatencyMultiplierLambda))
  307. }
  308. // After this point, any tactics parameters that apply the network latency
  309. // multiplier will use this selected value.
  310. p = config.GetParameters().GetCustom(dialParams.NetworkLatencyMultiplier)
  311. if !isReplay && !isExchanged {
  312. // TODO: should there be a pre-check of selectProtocol before incurring
  313. // overhead of unmarshaling dial parameters? In may be that a server entry
  314. // is fully incapable of satisfying the current protocol selection
  315. // constraints.
  316. selectedProtocol, ok := selectProtocol(serverEntry)
  317. if !ok {
  318. return nil, nil
  319. }
  320. dialParams.TunnelProtocol = selectedProtocol
  321. }
  322. // Skip this candidate when the clients tactics restrict usage of the
  323. // fronting provider ID. See the corresponding server-side enforcement
  324. // comments in server.TacticsListener.accept.
  325. if protocol.TunnelProtocolUsesFrontedMeek(dialParams.TunnelProtocol) &&
  326. common.Contains(
  327. p.Strings(parameters.RestrictFrontingProviderIDs),
  328. dialParams.ServerEntry.FrontingProviderID) {
  329. if p.WeightedCoinFlip(
  330. parameters.RestrictFrontingProviderIDsClientProbability) {
  331. // When skipping, return nil/nil as no error should be logged.
  332. // NoticeSkipServerEntry emits each skip reason, regardless
  333. // of server entry, at most once per session.
  334. NoticeSkipServerEntry(
  335. "restricted fronting provider ID: %s",
  336. dialParams.ServerEntry.FrontingProviderID)
  337. return nil, nil
  338. }
  339. }
  340. if config.UseUpstreamProxy() {
  341. // When UpstreamProxy is configured, ServerEntry.GetSupportedProtocols, when
  342. // called via selectProtocol, will filter out protocols such that will not
  343. // select a protocol incompatible with UpstreamProxy. This additional check
  344. // will catch cases where selectProtocol does not apply this filter.
  345. if !protocol.TunnelProtocolSupportsUpstreamProxy(dialParams.TunnelProtocol) {
  346. NoticeSkipServerEntry(
  347. "protocol does not support upstream proxy: %s",
  348. dialParams.TunnelProtocol)
  349. return nil, nil
  350. }
  351. // Skip this candidate when the server entry is not to be used with an
  352. // upstream proxy. By not exposing servers from sources that are
  353. // relatively hard to enumerate, this mechanism mitigates the risk of
  354. // a malicious upstream proxy enumerating Psiphon servers. Populate
  355. // the allowed sources with fronted servers to provide greater
  356. // blocking resistence for clients using upstream proxy clients that
  357. // are subject to blocking.
  358. source := dialParams.ServerEntry.LocalSource
  359. if !protocol.AllowServerEntrySourceWithUpstreamProxy(source) &&
  360. !p.Bool(parameters.UpstreamProxyAllowAllServerEntrySources) {
  361. NoticeSkipServerEntry(
  362. "server entry source disallowed with upstream proxy: %s",
  363. source)
  364. return nil, nil
  365. }
  366. }
  367. if (!isReplay || !replayBPF) &&
  368. ClientBPFEnabled() &&
  369. protocol.TunnelProtocolUsesTCP(dialParams.TunnelProtocol) {
  370. if p.WeightedCoinFlip(parameters.BPFClientTCPProbability) {
  371. dialParams.BPFProgramName = ""
  372. dialParams.BPFProgramInstructions = nil
  373. ok, name, rawInstructions := p.BPFProgram(parameters.BPFClientTCPProgram)
  374. if ok {
  375. dialParams.BPFProgramName = name
  376. dialParams.BPFProgramInstructions = rawInstructions
  377. }
  378. }
  379. }
  380. if !isReplay || !replaySSH {
  381. dialParams.SelectedSSHClientVersion = true
  382. dialParams.SSHClientVersion = values.GetSSHClientVersion()
  383. dialParams.SSHKEXSeed, err = prng.NewSeed()
  384. if err != nil {
  385. return nil, errors.Trace(err)
  386. }
  387. }
  388. if !isReplay || !replayObfuscatorPadding {
  389. dialParams.ObfuscatorPaddingSeed, err = prng.NewSeed()
  390. if err != nil {
  391. return nil, errors.Trace(err)
  392. }
  393. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) {
  394. dialParams.MeekObfuscatorPaddingSeed, err = prng.NewSeed()
  395. if err != nil {
  396. return nil, errors.Trace(err)
  397. }
  398. }
  399. }
  400. if !isReplay || !replayFragmentor {
  401. dialParams.FragmentorSeed, err = prng.NewSeed()
  402. if err != nil {
  403. return nil, errors.Trace(err)
  404. }
  405. }
  406. if (!isReplay || !replayConjureRegistration) &&
  407. protocol.TunnelProtocolUsesConjure(dialParams.TunnelProtocol) {
  408. dialParams.ConjureCachedRegistrationTTL = p.Duration(parameters.ConjureCachedRegistrationTTL)
  409. apiURL := p.String(parameters.ConjureAPIRegistrarBidirectionalURL)
  410. decoyWidth := p.Int(parameters.ConjureDecoyRegistrarWidth)
  411. dialParams.ConjureAPIRegistration = apiURL != ""
  412. dialParams.ConjureDecoyRegistration = decoyWidth != 0
  413. // We select only one of API or decoy registration. When both are enabled,
  414. // ConjureDecoyRegistrarProbability determines the probability of using
  415. // decoy registration.
  416. //
  417. // In general, we disable retries in gotapdance and rely on Psiphon
  418. // establishment to try/retry different registration schemes. This allows us
  419. // to control the proportion of registration types attempted. And, in good
  420. // network conditions, individual candidates are most likely to be cancelled
  421. // before they exhaust their retry options.
  422. if dialParams.ConjureAPIRegistration && dialParams.ConjureDecoyRegistration {
  423. if p.WeightedCoinFlip(parameters.ConjureDecoyRegistrarProbability) {
  424. dialParams.ConjureAPIRegistration = false
  425. }
  426. }
  427. if dialParams.ConjureAPIRegistration {
  428. // While Conjure API registration uses MeekConn and specifies common meek
  429. // parameters, the meek address and SNI configuration is implemented in this
  430. // code block and not in common code blocks below. The exception is TLS
  431. // configuration.
  432. //
  433. // Accordingly, replayFronting/replayHostname have no effect on Conjure API
  434. // registration replay.
  435. dialParams.ConjureAPIRegistrarBidirectionalURL = apiURL
  436. frontingSpecs := p.FrontingSpecs(parameters.ConjureAPIRegistrarFrontingSpecs)
  437. dialParams.FrontingProviderID,
  438. dialParams.MeekFrontingDialAddress,
  439. dialParams.MeekSNIServerName,
  440. dialParams.MeekVerifyServerName,
  441. dialParams.MeekVerifyPins,
  442. dialParams.MeekFrontingHost,
  443. err = frontingSpecs.SelectParameters()
  444. if err != nil {
  445. return nil, errors.Trace(err)
  446. }
  447. dialParams.MeekDialAddress = net.JoinHostPort(dialParams.MeekFrontingDialAddress, "443")
  448. dialParams.MeekHostHeader = dialParams.MeekFrontingHost
  449. // For a FrontingSpec, an SNI value of "" indicates to disable/omit SNI, so
  450. // never transform in that case.
  451. if dialParams.MeekSNIServerName != "" {
  452. if p.WeightedCoinFlip(parameters.TransformHostNameProbability) {
  453. dialParams.MeekSNIServerName = selectHostName(dialParams.TunnelProtocol, p)
  454. dialParams.MeekTransformedHostName = true
  455. }
  456. }
  457. // The minimum delay value is determined by the Conjure station, which
  458. // performs an asynchronous "liveness test" against the selected phantom
  459. // IPs. The min/max range allows us to introduce some jitter so that we
  460. // don't present a trivial inter-flow fingerprint: CDN connection, fixed
  461. // delay, phantom dial.
  462. minDelay := p.Duration(parameters.ConjureAPIRegistrarMinDelay)
  463. maxDelay := p.Duration(parameters.ConjureAPIRegistrarMaxDelay)
  464. dialParams.ConjureAPIRegistrarDelay = prng.Period(minDelay, maxDelay)
  465. } else if dialParams.ConjureDecoyRegistration {
  466. dialParams.ConjureDecoyRegistrarWidth = decoyWidth
  467. minDelay := p.Duration(parameters.ConjureDecoyRegistrarMinDelay)
  468. maxDelay := p.Duration(parameters.ConjureDecoyRegistrarMaxDelay)
  469. dialParams.ConjureAPIRegistrarDelay = prng.Period(minDelay, maxDelay)
  470. } else {
  471. return nil, errors.TraceNew("no Conjure registrar configured")
  472. }
  473. }
  474. if (!isReplay || !replayConjureTransport) &&
  475. protocol.TunnelProtocolUsesConjure(dialParams.TunnelProtocol) {
  476. dialParams.ConjureTransport = protocol.CONJURE_TRANSPORT_MIN_OSSH
  477. if p.WeightedCoinFlip(
  478. parameters.ConjureTransportObfs4Probability) {
  479. dialParams.ConjureTransport = protocol.CONJURE_TRANSPORT_OBFS4_OSSH
  480. }
  481. }
  482. usingTLS := protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol) ||
  483. dialParams.ConjureAPIRegistration
  484. if (!isReplay || !replayTLSProfile) && usingTLS {
  485. dialParams.SelectedTLSProfile = true
  486. requireTLS12SessionTickets := protocol.TunnelProtocolRequiresTLS12SessionTickets(
  487. dialParams.TunnelProtocol)
  488. isFronted := protocol.TunnelProtocolUsesFrontedMeek(dialParams.TunnelProtocol) ||
  489. dialParams.ConjureAPIRegistration
  490. dialParams.TLSProfile = SelectTLSProfile(
  491. requireTLS12SessionTickets, isFronted, serverEntry.FrontingProviderID, p)
  492. dialParams.NoDefaultTLSSessionID = p.WeightedCoinFlip(
  493. parameters.NoDefaultTLSSessionIDProbability)
  494. }
  495. if (!isReplay || !replayRandomizedTLSProfile) && usingTLS &&
  496. protocol.TLSProfileIsRandomized(dialParams.TLSProfile) {
  497. dialParams.RandomizedTLSProfileSeed, err = prng.NewSeed()
  498. if err != nil {
  499. return nil, errors.Trace(err)
  500. }
  501. }
  502. if (!isReplay || !replayTLSProfile) && usingTLS {
  503. // Since "Randomized-v2"/CustomTLSProfiles may be TLS 1.2 or TLS 1.3,
  504. // construct the ClientHello to determine if it's TLS 1.3. This test also
  505. // covers non-randomized TLS 1.3 profiles. This check must come after
  506. // dialParams.TLSProfile and dialParams.RandomizedTLSProfileSeed are set. No
  507. // actual dial is made here.
  508. utlsClientHelloID, utlsClientHelloSpec, err := getUTLSClientHelloID(
  509. p, dialParams.TLSProfile)
  510. if err != nil {
  511. return nil, errors.Trace(err)
  512. }
  513. if protocol.TLSProfileIsRandomized(dialParams.TLSProfile) {
  514. utlsClientHelloID.Seed = new(utls.PRNGSeed)
  515. *utlsClientHelloID.Seed = [32]byte(*dialParams.RandomizedTLSProfileSeed)
  516. }
  517. dialParams.TLSVersion, err = getClientHelloVersion(
  518. utlsClientHelloID, utlsClientHelloSpec)
  519. if err != nil {
  520. return nil, errors.Trace(err)
  521. }
  522. }
  523. if (!isReplay || !replayFronting) &&
  524. protocol.TunnelProtocolUsesFrontedMeek(dialParams.TunnelProtocol) {
  525. dialParams.FrontingProviderID = serverEntry.FrontingProviderID
  526. dialParams.MeekFrontingDialAddress, dialParams.MeekFrontingHost, err =
  527. selectFrontingParameters(serverEntry)
  528. if err != nil {
  529. return nil, errors.Trace(err)
  530. }
  531. }
  532. if !isReplay || !replayHostname {
  533. if protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol) ||
  534. protocol.TunnelProtocolUsesFrontedMeekQUIC(dialParams.TunnelProtocol) {
  535. dialParams.MeekSNIServerName = ""
  536. if p.WeightedCoinFlip(parameters.TransformHostNameProbability) {
  537. dialParams.MeekSNIServerName = selectHostName(dialParams.TunnelProtocol, p)
  538. dialParams.MeekTransformedHostName = true
  539. }
  540. } else if protocol.TunnelProtocolUsesMeekHTTP(dialParams.TunnelProtocol) {
  541. dialParams.MeekHostHeader = ""
  542. hostname := serverEntry.IpAddress
  543. if p.WeightedCoinFlip(parameters.TransformHostNameProbability) {
  544. hostname = selectHostName(dialParams.TunnelProtocol, p)
  545. dialParams.MeekTransformedHostName = true
  546. }
  547. if serverEntry.MeekServerPort == 80 {
  548. dialParams.MeekHostHeader = hostname
  549. } else {
  550. dialParams.MeekHostHeader = net.JoinHostPort(
  551. hostname, strconv.Itoa(serverEntry.MeekServerPort))
  552. }
  553. } else if protocol.TunnelProtocolUsesQUIC(dialParams.TunnelProtocol) {
  554. dialParams.QUICDialSNIAddress = net.JoinHostPort(
  555. selectHostName(dialParams.TunnelProtocol, p),
  556. strconv.Itoa(serverEntry.SshObfuscatedQUICPort))
  557. }
  558. }
  559. if (!isReplay || !replayQUICVersion) &&
  560. protocol.TunnelProtocolUsesQUIC(dialParams.TunnelProtocol) {
  561. isFronted := protocol.TunnelProtocolUsesFrontedMeekQUIC(dialParams.TunnelProtocol)
  562. dialParams.QUICVersion = selectQUICVersion(isFronted, serverEntry, p)
  563. if protocol.QUICVersionHasRandomizedClientHello(dialParams.QUICVersion) {
  564. dialParams.QUICClientHelloSeed, err = prng.NewSeed()
  565. if err != nil {
  566. return nil, errors.Trace(err)
  567. }
  568. }
  569. dialParams.QUICDisablePathMTUDiscovery =
  570. protocol.QUICVersionUsesPathMTUDiscovery(dialParams.QUICVersion) &&
  571. p.WeightedCoinFlip(parameters.QUICDisableClientPathMTUDiscoveryProbability)
  572. }
  573. if (!isReplay || !replayObfuscatedQUIC) &&
  574. protocol.QUICVersionIsObfuscated(dialParams.QUICVersion) {
  575. dialParams.ObfuscatedQUICPaddingSeed, err = prng.NewSeed()
  576. if err != nil {
  577. return nil, errors.Trace(err)
  578. }
  579. }
  580. if !isReplay || !replayLivenessTest {
  581. // TODO: initialize only when LivenessTestMaxUp/DownstreamBytes > 0?
  582. dialParams.LivenessTestSeed, err = prng.NewSeed()
  583. if err != nil {
  584. return nil, errors.Trace(err)
  585. }
  586. }
  587. if !isReplay || !replayAPIRequestPadding {
  588. dialParams.APIRequestPaddingSeed, err = prng.NewSeed()
  589. if err != nil {
  590. return nil, errors.Trace(err)
  591. }
  592. }
  593. useResolver := protocol.TunnelProtocolUsesFrontedMeek(dialParams.TunnelProtocol) ||
  594. dialParams.ConjureAPIRegistration
  595. if (!isReplay || !replayResolveParameters) && useResolver {
  596. dialParams.ResolveParameters, err = dialParams.resolver.MakeResolveParameters(
  597. p, dialParams.FrontingProviderID)
  598. if err != nil {
  599. return nil, errors.Trace(err)
  600. }
  601. }
  602. if !isReplay || !replayHoldOffTunnel {
  603. if common.Contains(
  604. p.TunnelProtocols(parameters.HoldOffTunnelProtocols), dialParams.TunnelProtocol) ||
  605. (protocol.TunnelProtocolUsesFrontedMeek(dialParams.TunnelProtocol) &&
  606. common.Contains(
  607. p.Strings(parameters.HoldOffTunnelFrontingProviderIDs),
  608. dialParams.FrontingProviderID)) {
  609. if p.WeightedCoinFlip(parameters.HoldOffTunnelProbability) {
  610. dialParams.HoldOffTunnelDuration = prng.Period(
  611. p.Duration(parameters.HoldOffTunnelMinDuration),
  612. p.Duration(parameters.HoldOffTunnelMaxDuration))
  613. }
  614. }
  615. }
  616. // Set dial address fields. This portion of configuration is
  617. // deterministic, given the parameters established or replayed so far.
  618. dialPortNumber, err := serverEntry.GetDialPortNumber(dialParams.TunnelProtocol)
  619. if err != nil {
  620. return nil, errors.Trace(err)
  621. }
  622. dialParams.DialPortNumber = strconv.Itoa(dialPortNumber)
  623. switch dialParams.TunnelProtocol {
  624. case protocol.TUNNEL_PROTOCOL_SSH,
  625. protocol.TUNNEL_PROTOCOL_OBFUSCATED_SSH,
  626. protocol.TUNNEL_PROTOCOL_TAPDANCE_OBFUSCATED_SSH,
  627. protocol.TUNNEL_PROTOCOL_CONJURE_OBFUSCATED_SSH,
  628. protocol.TUNNEL_PROTOCOL_QUIC_OBFUSCATED_SSH:
  629. dialParams.DirectDialAddress = net.JoinHostPort(serverEntry.IpAddress, dialParams.DialPortNumber)
  630. case protocol.TUNNEL_PROTOCOL_FRONTED_MEEK,
  631. protocol.TUNNEL_PROTOCOL_FRONTED_MEEK_QUIC_OBFUSCATED_SSH:
  632. dialParams.MeekDialAddress = net.JoinHostPort(dialParams.MeekFrontingDialAddress, dialParams.DialPortNumber)
  633. dialParams.MeekHostHeader = dialParams.MeekFrontingHost
  634. if serverEntry.MeekFrontingDisableSNI {
  635. dialParams.MeekSNIServerName = ""
  636. // When SNI is omitted, the transformed host name is not used.
  637. dialParams.MeekTransformedHostName = false
  638. } else if !dialParams.MeekTransformedHostName {
  639. dialParams.MeekSNIServerName = dialParams.MeekFrontingDialAddress
  640. }
  641. case protocol.TUNNEL_PROTOCOL_FRONTED_MEEK_HTTP:
  642. dialParams.MeekDialAddress = net.JoinHostPort(dialParams.MeekFrontingDialAddress, dialParams.DialPortNumber)
  643. dialParams.MeekHostHeader = dialParams.MeekFrontingHost
  644. // For FRONTED HTTP, the Host header cannot be transformed.
  645. dialParams.MeekTransformedHostName = false
  646. case protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK:
  647. dialParams.MeekDialAddress = net.JoinHostPort(serverEntry.IpAddress, dialParams.DialPortNumber)
  648. if !dialParams.MeekTransformedHostName {
  649. if dialPortNumber == 80 {
  650. dialParams.MeekHostHeader = serverEntry.IpAddress
  651. } else {
  652. dialParams.MeekHostHeader = dialParams.MeekDialAddress
  653. }
  654. }
  655. case protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  656. protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET:
  657. dialParams.MeekDialAddress = net.JoinHostPort(serverEntry.IpAddress, dialParams.DialPortNumber)
  658. if !dialParams.MeekTransformedHostName {
  659. // Note: IP address in SNI field will be omitted.
  660. dialParams.MeekSNIServerName = serverEntry.IpAddress
  661. }
  662. if dialPortNumber == 443 {
  663. dialParams.MeekHostHeader = serverEntry.IpAddress
  664. } else {
  665. dialParams.MeekHostHeader = dialParams.MeekDialAddress
  666. }
  667. default:
  668. return nil, errors.Tracef(
  669. "unknown tunnel protocol: %s", dialParams.TunnelProtocol)
  670. }
  671. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) {
  672. host, _, _ := net.SplitHostPort(dialParams.MeekDialAddress)
  673. if p.Bool(parameters.MeekDialDomainsOnly) {
  674. if net.ParseIP(host) != nil {
  675. // No error, as this is a "not supported" case.
  676. return nil, nil
  677. }
  678. }
  679. // The underlying TLS implementation will automatically omit SNI for
  680. // IP address server name values; we have this explicit check here so
  681. // we record the correct value for stats.
  682. if net.ParseIP(dialParams.MeekSNIServerName) != nil {
  683. dialParams.MeekSNIServerName = ""
  684. }
  685. }
  686. // Initialize/replay User-Agent header for HTTP upstream proxy and meek protocols.
  687. if config.UseUpstreamProxy() {
  688. // Note: UpstreamProxyURL will be validated in the dial
  689. proxyURL, err := common.SafeParseURL(config.UpstreamProxyURL)
  690. if err == nil {
  691. dialParams.UpstreamProxyType = proxyURL.Scheme
  692. }
  693. }
  694. dialCustomHeaders := makeDialCustomHeaders(config, p)
  695. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) ||
  696. dialParams.UpstreamProxyType == "http" ||
  697. dialParams.ConjureAPIRegistration {
  698. if !isReplay || !replayUserAgent {
  699. dialParams.SelectedUserAgent, dialParams.UserAgent = selectUserAgentIfUnset(p, dialCustomHeaders)
  700. }
  701. if dialParams.SelectedUserAgent {
  702. dialCustomHeaders.Set("User-Agent", dialParams.UserAgent)
  703. }
  704. }
  705. // UpstreamProxyCustomHeaderNames is a reported metric. Just the names and
  706. // not the values are reported, in case the values are identifying.
  707. if len(config.CustomHeaders) > 0 {
  708. dialParams.UpstreamProxyCustomHeaderNames = make([]string, 0)
  709. for name := range dialCustomHeaders {
  710. if name == "User-Agent" && dialParams.SelectedUserAgent {
  711. continue
  712. }
  713. dialParams.UpstreamProxyCustomHeaderNames = append(dialParams.UpstreamProxyCustomHeaderNames, name)
  714. }
  715. }
  716. // Initialize Dial/MeekConfigs to be passed to the corresponding dialers.
  717. // Custom ResolveParameters are set only when useResolver is true, but
  718. // DialConfig.ResolveIP is wired up unconditionally, so that we fail over
  719. // to resolving, but without custom parameters, in case of a
  720. // misconfigured or miscoded case.
  721. //
  722. // ResolveIP will use the networkID obtained above, as it will be used
  723. // almost immediately, instead of incurring the overhead of calling
  724. // GetNetworkID again.
  725. resolveIP := func(ctx context.Context, hostname string) ([]net.IP, error) {
  726. IPs, err := dialParams.resolver.ResolveIP(
  727. ctx,
  728. networkID,
  729. dialParams.ResolveParameters,
  730. hostname)
  731. if err != nil {
  732. return nil, errors.Trace(err)
  733. }
  734. return IPs, nil
  735. }
  736. dialParams.dialConfig = &DialConfig{
  737. DiagnosticID: serverEntry.GetDiagnosticID(),
  738. UpstreamProxyURL: config.UpstreamProxyURL,
  739. CustomHeaders: dialCustomHeaders,
  740. BPFProgramInstructions: dialParams.BPFProgramInstructions,
  741. DeviceBinder: config.deviceBinder,
  742. IPv6Synthesizer: config.IPv6Synthesizer,
  743. ResolveIP: resolveIP,
  744. TrustedCACertificatesFilename: config.TrustedCACertificatesFilename,
  745. FragmentorConfig: fragmentor.NewUpstreamConfig(p, dialParams.TunnelProtocol, dialParams.FragmentorSeed),
  746. UpstreamProxyErrorCallback: upstreamProxyErrorCallback,
  747. }
  748. // Unconditionally initialize MeekResolvedIPAddress, so a valid string can
  749. // always be read.
  750. dialParams.MeekResolvedIPAddress.Store("")
  751. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) ||
  752. dialParams.ConjureAPIRegistration {
  753. dialParams.meekConfig = &MeekConfig{
  754. DiagnosticID: serverEntry.GetDiagnosticID(),
  755. Parameters: config.GetParameters(),
  756. DialAddress: dialParams.MeekDialAddress,
  757. UseQUIC: protocol.TunnelProtocolUsesFrontedMeekQUIC(dialParams.TunnelProtocol),
  758. QUICVersion: dialParams.QUICVersion,
  759. QUICClientHelloSeed: dialParams.QUICClientHelloSeed,
  760. QUICDisablePathMTUDiscovery: dialParams.QUICDisablePathMTUDiscovery,
  761. UseHTTPS: usingTLS,
  762. TLSProfile: dialParams.TLSProfile,
  763. LegacyPassthrough: serverEntry.ProtocolUsesLegacyPassthrough(dialParams.TunnelProtocol),
  764. NoDefaultTLSSessionID: dialParams.NoDefaultTLSSessionID,
  765. RandomizedTLSProfileSeed: dialParams.RandomizedTLSProfileSeed,
  766. UseObfuscatedSessionTickets: dialParams.TunnelProtocol == protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET,
  767. SNIServerName: dialParams.MeekSNIServerName,
  768. VerifyServerName: dialParams.MeekVerifyServerName,
  769. VerifyPins: dialParams.MeekVerifyPins,
  770. HostHeader: dialParams.MeekHostHeader,
  771. TransformedHostName: dialParams.MeekTransformedHostName,
  772. ClientTunnelProtocol: dialParams.TunnelProtocol,
  773. MeekCookieEncryptionPublicKey: serverEntry.MeekCookieEncryptionPublicKey,
  774. MeekObfuscatedKey: serverEntry.MeekObfuscatedKey,
  775. MeekObfuscatorPaddingSeed: dialParams.MeekObfuscatorPaddingSeed,
  776. NetworkLatencyMultiplier: dialParams.NetworkLatencyMultiplier,
  777. }
  778. // Use an asynchronous callback to record the resolved IP address when
  779. // dialing a domain name. Note that DialMeek doesn't immediately
  780. // establish any HTTP connections, so the resolved IP address won't be
  781. // reported in all cases until after SSH traffic is relayed or a
  782. // endpoint request is made over the meek connection.
  783. dialParams.dialConfig.ResolvedIPCallback = func(IPAddress string) {
  784. dialParams.MeekResolvedIPAddress.Store(IPAddress)
  785. }
  786. if isTactics {
  787. dialParams.meekConfig.Mode = MeekModeObfuscatedRoundTrip
  788. } else if dialParams.ConjureAPIRegistration {
  789. dialParams.meekConfig.Mode = MeekModePlaintextRoundTrip
  790. } else {
  791. dialParams.meekConfig.Mode = MeekModeRelay
  792. }
  793. }
  794. return dialParams, nil
  795. }
  796. func (dialParams *DialParameters) GetDialConfig() *DialConfig {
  797. return dialParams.dialConfig
  798. }
  799. func (dialParams *DialParameters) GetMeekConfig() *MeekConfig {
  800. return dialParams.meekConfig
  801. }
  802. // GetNetworkType returns a network type name, suitable for metrics, which is
  803. // derived from the network ID.
  804. func (dialParams *DialParameters) GetNetworkType() string {
  805. // Unlike the logic in loggingNetworkIDGetter.GetNetworkID, we don't take the
  806. // arbitrary text before the first "-" since some platforms without network
  807. // detection support stub in random values to enable tactics. Instead we
  808. // check for and use the common network type prefixes currently used in
  809. // NetworkIDGetter implementations.
  810. if strings.HasPrefix(dialParams.NetworkID, "WIFI") {
  811. return "WIFI"
  812. }
  813. if strings.HasPrefix(dialParams.NetworkID, "MOBILE") {
  814. return "MOBILE"
  815. }
  816. return "UNKNOWN"
  817. }
  818. func (dialParams *DialParameters) Succeeded() {
  819. // When TTL is 0, don't store dial parameters.
  820. if dialParams.LastUsedTimestamp.IsZero() {
  821. return
  822. }
  823. NoticeInfo("Set dial parameters for %s", dialParams.ServerEntry.GetDiagnosticID())
  824. err := SetDialParameters(dialParams.ServerEntry.IpAddress, dialParams.NetworkID, dialParams)
  825. if err != nil {
  826. NoticeWarning("SetDialParameters failed: %s", err)
  827. }
  828. }
  829. func (dialParams *DialParameters) Failed(config *Config) {
  830. // When a tunnel fails, and the dial is a replay, clear the stored dial
  831. // parameters which are now presumed to be blocked, impaired or otherwise
  832. // no longer effective.
  833. //
  834. // It may be the case that a dial is not using stored dial parameters
  835. // (!IsReplay), and in this case we retain those dial parameters since they
  836. // were not exercised and may still be effective.
  837. //
  838. // Failed tunnel dial parameters may be retained with a configurable
  839. // probability; this is intended to help mitigate false positive failures due
  840. // to, e.g., temporary network disruptions or server load limiting.
  841. if dialParams.IsReplay &&
  842. !config.GetParameters().Get().WeightedCoinFlip(
  843. parameters.ReplayRetainFailedProbability) {
  844. NoticeInfo("Delete dial parameters for %s", dialParams.ServerEntry.GetDiagnosticID())
  845. err := DeleteDialParameters(dialParams.ServerEntry.IpAddress, dialParams.NetworkID)
  846. if err != nil {
  847. NoticeWarning("DeleteDialParameters failed: %s", err)
  848. }
  849. }
  850. }
  851. func (dialParams *DialParameters) GetTLSVersionForMetrics() string {
  852. tlsVersion := dialParams.TLSVersion
  853. if dialParams.NoDefaultTLSSessionID {
  854. tlsVersion += "-no_def_id"
  855. }
  856. return tlsVersion
  857. }
  858. // ExchangedDialParameters represents the subset of DialParameters that is
  859. // shared in a client-to-client exchange of server connection info.
  860. //
  861. // The purpose of client-to-client exchange if for one user that can connect
  862. // to help another user that cannot connect by sharing their connected
  863. // configuration, including the server entry and dial parameters.
  864. //
  865. // There are two concerns regarding which dial parameter fields are safe to
  866. // exchange:
  867. //
  868. // - Unlike signed server entries, there's no independent trust anchor
  869. // that can certify that the exchange data is valid.
  870. //
  871. // - While users should only perform the exchange with trusted peers,
  872. // the user's trust in their peer may be misplaced.
  873. //
  874. // This presents the possibility of attack such as the peer sending dial
  875. // parameters that could be used to trace/monitor/flag the importer; or
  876. // sending dial parameters, including dial address and SNI, to cause the peer
  877. // to appear to connect to a banned service.
  878. //
  879. // To mitigate these risks, only a subset of dial parameters are exchanged.
  880. // When exchanged dial parameters and imported and used, all unexchanged
  881. // parameters are generated locally. At this time, only the tunnel protocol is
  882. // exchanged. We consider tunnel protocol selection one of the key connection
  883. // success factors.
  884. //
  885. // In addition, the exchange peers may not be on the same network with the
  886. // same blocking and circumvention characteristics, which is another reason
  887. // to limit exchanged dial parameter values to broadly applicable fields.
  888. //
  889. // Unlike the exchanged (and otherwise acquired) server entry,
  890. // ExchangedDialParameters does not use the ServerEntry_Fields_ representation
  891. // which allows older clients to receive and store new, unknown fields. Such a
  892. // facility is less useful in this case, since exchanged dial parameters and
  893. // used immediately and have a short lifespan.
  894. //
  895. // TODO: exchange more dial parameters, such as TLS profile, QUIC version, etc.
  896. type ExchangedDialParameters struct {
  897. TunnelProtocol string
  898. }
  899. // NewExchangedDialParameters creates a new ExchangedDialParameters from a
  900. // DialParameters, including only the exchanged values.
  901. // NewExchangedDialParameters assumes the input DialParameters has been
  902. // initialized and populated by MakeDialParameters.
  903. func NewExchangedDialParameters(dialParams *DialParameters) *ExchangedDialParameters {
  904. return &ExchangedDialParameters{
  905. TunnelProtocol: dialParams.TunnelProtocol,
  906. }
  907. }
  908. // Validate checks that the ExchangedDialParameters contains only valid values
  909. // and is compatible with the specified server entry.
  910. func (dialParams *ExchangedDialParameters) Validate(serverEntry *protocol.ServerEntry) error {
  911. if !common.Contains(protocol.SupportedTunnelProtocols, dialParams.TunnelProtocol) {
  912. return errors.Tracef("unknown tunnel protocol: %s", dialParams.TunnelProtocol)
  913. }
  914. if !serverEntry.SupportsProtocol(dialParams.TunnelProtocol) {
  915. return errors.Tracef("unsupported tunnel protocol: %s", dialParams.TunnelProtocol)
  916. }
  917. return nil
  918. }
  919. // MakeDialParameters creates a new, partially intitialized DialParameters
  920. // from the values in ExchangedDialParameters. The returned DialParameters
  921. // must not be used directly for dialing. It is intended to be stored, and
  922. // then later fully initialized by MakeDialParameters.
  923. func (dialParams *ExchangedDialParameters) MakeDialParameters(
  924. config *Config,
  925. p parameters.ParametersAccessor,
  926. serverEntry *protocol.ServerEntry) *DialParameters {
  927. return &DialParameters{
  928. IsExchanged: true,
  929. LastUsedTimestamp: time.Now(),
  930. LastUsedConfigStateHash: getConfigStateHash(config, p, serverEntry),
  931. TunnelProtocol: dialParams.TunnelProtocol,
  932. }
  933. }
  934. func getConfigStateHash(
  935. config *Config,
  936. p parameters.ParametersAccessor,
  937. serverEntry *protocol.ServerEntry) []byte {
  938. // The config state hash should reflect config, tactics, and server entry
  939. // settings that impact the dial parameters. The hash should change if any
  940. // of these input values change in a way that invalidates any stored dial
  941. // parameters.
  942. // MD5 hash is used solely as a data checksum and not for any security
  943. // purpose.
  944. hash := md5.New()
  945. // Add a hash of relevant config fields.
  946. // Limitation: the config hash may change even when tactics will override the
  947. // changed config field.
  948. hash.Write(config.dialParametersHash)
  949. // Add the active tactics tag.
  950. hash.Write([]byte(p.Tag()))
  951. // Add the server entry version and local timestamp, both of which should
  952. // change when the server entry contents change and/or a new local copy is
  953. // imported.
  954. // TODO: marshal entire server entry?
  955. var serverEntryConfigurationVersion [8]byte
  956. binary.BigEndian.PutUint64(
  957. serverEntryConfigurationVersion[:],
  958. uint64(serverEntry.ConfigurationVersion))
  959. hash.Write(serverEntryConfigurationVersion[:])
  960. hash.Write([]byte(serverEntry.LocalTimestamp))
  961. return hash.Sum(nil)
  962. }
  963. func selectFrontingParameters(
  964. serverEntry *protocol.ServerEntry) (string, string, error) {
  965. frontingDialHost := ""
  966. frontingHost := ""
  967. if len(serverEntry.MeekFrontingAddressesRegex) > 0 {
  968. // Generate a front address based on the regex.
  969. var err error
  970. frontingDialHost, err = regen.Generate(serverEntry.MeekFrontingAddressesRegex)
  971. if err != nil {
  972. return "", "", errors.Trace(err)
  973. }
  974. } else {
  975. // Randomly select, for this connection attempt, one front address for
  976. // fronting-capable servers.
  977. if len(serverEntry.MeekFrontingAddresses) == 0 {
  978. return "", "", errors.TraceNew("MeekFrontingAddresses is empty")
  979. }
  980. index := prng.Intn(len(serverEntry.MeekFrontingAddresses))
  981. frontingDialHost = serverEntry.MeekFrontingAddresses[index]
  982. }
  983. if len(serverEntry.MeekFrontingHosts) > 0 {
  984. index := prng.Intn(len(serverEntry.MeekFrontingHosts))
  985. frontingHost = serverEntry.MeekFrontingHosts[index]
  986. } else {
  987. // Backwards compatibility case
  988. frontingHost = serverEntry.MeekFrontingHost
  989. }
  990. return frontingDialHost, frontingHost, nil
  991. }
  992. func selectQUICVersion(
  993. isFronted bool,
  994. serverEntry *protocol.ServerEntry,
  995. p parameters.ParametersAccessor) string {
  996. limitQUICVersions := p.QUICVersions(parameters.LimitQUICVersions)
  997. var disableQUICVersions protocol.QUICVersions
  998. if isFronted {
  999. if serverEntry.FrontingProviderID == "" {
  1000. // Legacy server entry case
  1001. disableQUICVersions = protocol.QUICVersions{
  1002. protocol.QUIC_VERSION_V1,
  1003. protocol.QUIC_VERSION_RANDOMIZED_V1,
  1004. protocol.QUIC_VERSION_OBFUSCATED_V1,
  1005. protocol.QUIC_VERSION_DECOY_V1,
  1006. }
  1007. } else {
  1008. disableQUICVersions = p.LabeledQUICVersions(
  1009. parameters.DisableFrontingProviderQUICVersions,
  1010. serverEntry.FrontingProviderID)
  1011. }
  1012. }
  1013. quicVersions := make([]string, 0)
  1014. // Don't use gQUIC versions when the server entry specifies QUICv1-only.
  1015. supportedQUICVersions := protocol.SupportedQUICVersions
  1016. if serverEntry.SupportsOnlyQUICv1() {
  1017. supportedQUICVersions = protocol.SupportedQUICv1Versions
  1018. }
  1019. for _, quicVersion := range supportedQUICVersions {
  1020. if len(limitQUICVersions) > 0 &&
  1021. !common.Contains(limitQUICVersions, quicVersion) {
  1022. continue
  1023. }
  1024. // Both tactics and the server entry can specify LimitQUICVersions. In
  1025. // tactics, the parameter is intended to direct certain clients to
  1026. // use a successful protocol variant. In the server entry, the
  1027. // parameter may be used to direct all clients to send
  1028. // consistent-looking protocol variants to a particular server; e.g.,
  1029. // only regular QUIC, or only obfuscated QUIC.
  1030. //
  1031. // The isFronted/QUICVersionIsObfuscated logic predates
  1032. // ServerEntry.LimitQUICVersions; ServerEntry.LimitQUICVersions could
  1033. // now be used to achieve a similar outcome.
  1034. if len(serverEntry.LimitQUICVersions) > 0 &&
  1035. !common.Contains(serverEntry.LimitQUICVersions, quicVersion) {
  1036. continue
  1037. }
  1038. if isFronted &&
  1039. protocol.QUICVersionIsObfuscated(quicVersion) {
  1040. continue
  1041. }
  1042. if common.Contains(disableQUICVersions, quicVersion) {
  1043. continue
  1044. }
  1045. quicVersions = append(quicVersions, quicVersion)
  1046. }
  1047. if len(quicVersions) == 0 {
  1048. return ""
  1049. }
  1050. choice := prng.Intn(len(quicVersions))
  1051. return quicVersions[choice]
  1052. }
  1053. // selectUserAgentIfUnset selects a User-Agent header if one is not set.
  1054. func selectUserAgentIfUnset(
  1055. p parameters.ParametersAccessor, headers http.Header) (bool, string) {
  1056. if _, ok := headers["User-Agent"]; !ok {
  1057. userAgent := ""
  1058. if p.WeightedCoinFlip(parameters.PickUserAgentProbability) {
  1059. userAgent = values.GetUserAgent()
  1060. }
  1061. return true, userAgent
  1062. }
  1063. return false, ""
  1064. }
  1065. func makeDialCustomHeaders(
  1066. config *Config,
  1067. p parameters.ParametersAccessor) http.Header {
  1068. dialCustomHeaders := make(http.Header)
  1069. if config.CustomHeaders != nil {
  1070. for k, v := range config.CustomHeaders {
  1071. dialCustomHeaders[k] = make([]string, len(v))
  1072. copy(dialCustomHeaders[k], v)
  1073. }
  1074. }
  1075. additionalCustomHeaders := p.HTTPHeaders(parameters.AdditionalCustomHeaders)
  1076. for k, v := range additionalCustomHeaders {
  1077. dialCustomHeaders[k] = make([]string, len(v))
  1078. copy(dialCustomHeaders[k], v)
  1079. }
  1080. return dialCustomHeaders
  1081. }
  1082. func selectHostName(
  1083. tunnelProtocol string, p parameters.ParametersAccessor) string {
  1084. limitProtocols := p.TunnelProtocols(parameters.CustomHostNameLimitProtocols)
  1085. if len(limitProtocols) > 0 && !common.Contains(limitProtocols, tunnelProtocol) {
  1086. return values.GetHostName()
  1087. }
  1088. if !p.WeightedCoinFlip(parameters.CustomHostNameProbability) {
  1089. return values.GetHostName()
  1090. }
  1091. regexStrings := p.RegexStrings(parameters.CustomHostNameRegexes)
  1092. if len(regexStrings) == 0 {
  1093. return values.GetHostName()
  1094. }
  1095. choice := prng.Intn(len(regexStrings))
  1096. hostName, err := regen.Generate(regexStrings[choice])
  1097. if err != nil {
  1098. NoticeWarning("selectHostName: regen.Generate failed: %v", errors.Trace(err))
  1099. return values.GetHostName()
  1100. }
  1101. return hostName
  1102. }