dialParameters.go 45 KB

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