dialParameters.go 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297
  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. "fmt"
  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/values"
  38. utls "github.com/refraction-networking/utls"
  39. regen "github.com/zach-klippenstein/goregen"
  40. "golang.org/x/net/bpf"
  41. )
  42. // DialParameters represents a selected protocol and all the related selected
  43. // protocol attributes, many chosen at random, for a tunnel dial attempt.
  44. //
  45. // DialParameters is used:
  46. // - to configure dialers
  47. // - as a persistent record to store successful dial parameters for replay
  48. // - to report dial stats in notices and Psiphon API calls.
  49. //
  50. // MeekResolvedIPAddress is set asynchronously, as it is not known until the
  51. // dial process has begun. The atomic.Value will contain a string, initialized
  52. // to "", and set to the resolved IP address once that part of the dial
  53. // process has completed.
  54. //
  55. // DialParameters is not safe for concurrent use.
  56. type DialParameters struct {
  57. ServerEntry *protocol.ServerEntry `json:"-"`
  58. NetworkID string `json:"-"`
  59. IsReplay bool `json:"-"`
  60. CandidateNumber int `json:"-"`
  61. EstablishedTunnelsCount int `json:"-"`
  62. IsExchanged bool
  63. LastUsedTimestamp time.Time
  64. LastUsedConfigStateHash []byte
  65. NetworkLatencyMultiplier float64
  66. TunnelProtocol string
  67. DirectDialAddress string
  68. DialPortNumber string
  69. UpstreamProxyType string `json:"-"`
  70. UpstreamProxyCustomHeaderNames []string `json:"-"`
  71. BPFProgramName string
  72. BPFProgramInstructions []bpf.RawInstruction
  73. SelectedSSHClientVersion bool
  74. SSHClientVersion string
  75. SSHKEXSeed *prng.Seed
  76. ObfuscatorPaddingSeed *prng.Seed
  77. FragmentorSeed *prng.Seed
  78. FrontingProviderID string
  79. MeekFrontingDialAddress string
  80. MeekFrontingHost string
  81. MeekDialAddress string
  82. MeekTransformedHostName bool
  83. MeekSNIServerName string
  84. MeekVerifyServerName string
  85. MeekVerifyPins []string
  86. MeekHostHeader string
  87. MeekObfuscatorPaddingSeed *prng.Seed
  88. MeekTLSPaddingSize int
  89. MeekResolvedIPAddress atomic.Value `json:"-"`
  90. SelectedUserAgent bool
  91. UserAgent string
  92. SelectedTLSProfile bool
  93. TLSProfile string
  94. NoDefaultTLSSessionID bool
  95. TLSVersion string
  96. RandomizedTLSProfileSeed *prng.Seed
  97. QUICVersion string
  98. QUICDialSNIAddress string
  99. QUICClientHelloSeed *prng.Seed
  100. ObfuscatedQUICPaddingSeed *prng.Seed
  101. QUICDisablePathMTUDiscovery bool
  102. ConjureCachedRegistrationTTL time.Duration
  103. ConjureAPIRegistration bool
  104. ConjureAPIRegistrarBidirectionalURL string
  105. ConjureAPIRegistrarDelay time.Duration
  106. ConjureDecoyRegistration bool
  107. ConjureDecoyRegistrarDelay time.Duration
  108. ConjureDecoyRegistrarWidth int
  109. ConjureTransport string
  110. LivenessTestSeed *prng.Seed
  111. APIRequestPaddingSeed *prng.Seed
  112. HoldOffTunnelDuration time.Duration
  113. DialConnMetrics common.MetricsSource `json:"-"`
  114. ObfuscatedSSHConnMetrics common.MetricsSource `json:"-"`
  115. DialDuration time.Duration `json:"-"`
  116. dialConfig *DialConfig
  117. meekConfig *MeekConfig
  118. }
  119. // MakeDialParameters creates a new DialParameters for the candidate server
  120. // entry, including selecting a protocol and all the various protocol
  121. // attributes. The input selectProtocol is used to comply with any active
  122. // protocol selection constraints.
  123. //
  124. // When stored dial parameters are available and may be used,
  125. // MakeDialParameters may replay previous dial parameters in an effort to
  126. // leverage "known working" values instead of always chosing at random from a
  127. // large space.
  128. //
  129. // MakeDialParameters will return nil/nil in cases where the candidate server
  130. // entry should be skipped.
  131. //
  132. // To support replay, the caller must call DialParameters.Succeeded when a
  133. // successful tunnel is established with the returned DialParameters; and must
  134. // call DialParameters.Failed when a tunnel dial or activation fails, except
  135. // when establishment is cancelled.
  136. func MakeDialParameters(
  137. config *Config,
  138. upstreamProxyErrorCallback func(error),
  139. canReplay func(serverEntry *protocol.ServerEntry, replayProtocol string) bool,
  140. selectProtocol func(serverEntry *protocol.ServerEntry) (string, bool),
  141. serverEntry *protocol.ServerEntry,
  142. isTactics bool,
  143. candidateNumber int,
  144. establishedTunnelsCount int) (*DialParameters, error) {
  145. networkID := config.GetNetworkID()
  146. p := config.GetParameters().Get()
  147. ttl := p.Duration(parameters.ReplayDialParametersTTL)
  148. replayBPF := p.Bool(parameters.ReplayBPF)
  149. replaySSH := p.Bool(parameters.ReplaySSH)
  150. replayObfuscatorPadding := p.Bool(parameters.ReplayObfuscatorPadding)
  151. replayFragmentor := p.Bool(parameters.ReplayFragmentor)
  152. replayTLSProfile := p.Bool(parameters.ReplayTLSProfile)
  153. replayRandomizedTLSProfile := p.Bool(parameters.ReplayRandomizedTLSProfile)
  154. replayFronting := p.Bool(parameters.ReplayFronting)
  155. replayHostname := p.Bool(parameters.ReplayHostname)
  156. replayQUICVersion := p.Bool(parameters.ReplayQUICVersion)
  157. replayObfuscatedQUIC := p.Bool(parameters.ReplayObfuscatedQUIC)
  158. replayConjureRegistration := p.Bool(parameters.ReplayConjureRegistration)
  159. replayConjureTransport := p.Bool(parameters.ReplayConjureTransport)
  160. replayLivenessTest := p.Bool(parameters.ReplayLivenessTest)
  161. replayUserAgent := p.Bool(parameters.ReplayUserAgent)
  162. replayAPIRequestPadding := p.Bool(parameters.ReplayAPIRequestPadding)
  163. replayHoldOffTunnel := p.Bool(parameters.ReplayHoldOffTunnel)
  164. // Check for existing dial parameters for this server/network ID.
  165. dialParams, err := GetDialParameters(
  166. config, serverEntry.IpAddress, networkID)
  167. if err != nil {
  168. NoticeWarning("GetDialParameters failed: %s", err)
  169. dialParams = nil
  170. // Proceed, without existing dial parameters.
  171. }
  172. // Check if replay is permitted:
  173. // - TTL must be > 0 and existing dial parameters must not have expired
  174. // as indicated by LastUsedTimestamp + TTL.
  175. // - Config/tactics/server entry values must be unchanged from when
  176. // previous dial parameters were established.
  177. // - The protocol selection constraints must permit replay, as indicated
  178. // by canReplay.
  179. // - Must not be using an obsolete TLS profile that is no longer supported.
  180. // - Must be using the latest Conjure API URL.
  181. //
  182. // When existing dial parameters don't meet these conditions, dialParams
  183. // is reset to nil and new dial parameters will be generated.
  184. var currentTimestamp time.Time
  185. var configStateHash []byte
  186. // When TTL is 0, replay is disabled; the timestamp remains 0 and the
  187. // output DialParameters will not be stored by Success.
  188. if ttl > 0 {
  189. currentTimestamp = time.Now()
  190. configStateHash = getConfigStateHash(config, p, serverEntry)
  191. }
  192. if dialParams != nil &&
  193. (ttl <= 0 ||
  194. dialParams.LastUsedTimestamp.Before(currentTimestamp.Add(-ttl)) ||
  195. !bytes.Equal(dialParams.LastUsedConfigStateHash, configStateHash) ||
  196. (dialParams.TLSProfile != "" &&
  197. !common.Contains(protocol.SupportedTLSProfiles, dialParams.TLSProfile)) ||
  198. (dialParams.QUICVersion != "" &&
  199. !common.Contains(protocol.SupportedQUICVersions, dialParams.QUICVersion)) ||
  200. // Legacy clients use ConjureAPIRegistrarURL with
  201. // gotapdance.tapdance.APIRegistrar and new clients use
  202. // ConjureAPIRegistrarBidirectionalURL with
  203. // gotapdance.tapdance.APIRegistrarBidirectional. Updated clients
  204. // may have replay dial parameters with the old
  205. // ConjureAPIRegistrarURL field, which is now ignored. In this
  206. // case, ConjureAPIRegistrarBidirectionalURL will be blank. Reset
  207. // this replay.
  208. (dialParams.ConjureAPIRegistration && dialParams.ConjureAPIRegistrarBidirectionalURL == "")) {
  209. // In these cases, existing dial parameters are expired or no longer
  210. // match the config state and so are cleared to avoid rechecking them.
  211. err = DeleteDialParameters(serverEntry.IpAddress, networkID)
  212. if err != nil {
  213. NoticeWarning("DeleteDialParameters failed: %s", err)
  214. }
  215. dialParams = nil
  216. }
  217. if dialParams != nil {
  218. if config.DisableReplay ||
  219. !canReplay(serverEntry, dialParams.TunnelProtocol) {
  220. // In these ephemeral cases, existing dial parameters may still be valid
  221. // and used in future establishment phases, and so are retained.
  222. dialParams = nil
  223. }
  224. }
  225. // IsExchanged:
  226. //
  227. // Dial parameters received via client-to-client exchange are partially
  228. // initialized. Only the exchange fields are retained, and all other dial
  229. // parameters fields must be initialized. This is not considered or logged as
  230. // a replay. The exchange case is identified by the IsExchanged flag.
  231. //
  232. // When previously stored, IsExchanged dial parameters will have set the same
  233. // timestamp and state hash used for regular dial parameters and the same
  234. // logic above should invalidate expired or invalid exchanged dial
  235. // parameters.
  236. //
  237. // Limitation: metrics will indicate when an exchanged server entry is used
  238. // (source "EXCHANGED") but will not indicate when exchanged dial parameters
  239. // are used vs. a redial after discarding dial parameters.
  240. isReplay := (dialParams != nil)
  241. isExchanged := isReplay && dialParams.IsExchanged
  242. if !isReplay {
  243. dialParams = &DialParameters{}
  244. }
  245. if isExchanged {
  246. // Set isReplay to false to cause all non-exchanged values to be
  247. // initialized; this also causes the exchange case to not log as replay.
  248. isReplay = false
  249. }
  250. // Set IsExchanged such that full dial parameters are stored and replayed
  251. // upon success.
  252. dialParams.IsExchanged = false
  253. dialParams.ServerEntry = serverEntry
  254. dialParams.NetworkID = networkID
  255. dialParams.IsReplay = isReplay
  256. dialParams.CandidateNumber = candidateNumber
  257. dialParams.EstablishedTunnelsCount = establishedTunnelsCount
  258. // Even when replaying, LastUsedTimestamp is updated to extend the TTL of
  259. // replayed dial parameters which will be updated in the datastore upon
  260. // success.
  261. dialParams.LastUsedTimestamp = currentTimestamp
  262. dialParams.LastUsedConfigStateHash = configStateHash
  263. // Initialize dial parameters.
  264. //
  265. // When not replaying, all required parameters are initialized. When
  266. // replaying, existing parameters are retaing, subject to the replay-X
  267. // tactics flags.
  268. // Select a network latency multiplier for this dial. This allows clients to
  269. // explore and discover timeout values appropriate for the current network.
  270. // The selection applies per tunnel, to avoid delaying all establishment
  271. // candidates due to excessive timeouts. The random selection is bounded by a
  272. // min/max set in tactics and an exponential distribution is used so as to
  273. // heavily favor values close to the min, which should be set to the
  274. // singleton NetworkLatencyMultiplier tactics value.
  275. //
  276. // For NetworkLatencyMultiplierLambda close to 2.0, values near min are
  277. // very approximately 10x more likely to be selected than values near
  278. // max, while for NetworkLatencyMultiplierLambda close to 0.1, the
  279. // distribution is close to uniform.
  280. //
  281. // Not all existing, persisted DialParameters will have a custom
  282. // NetworkLatencyMultiplier value. Its zero value will cause the singleton
  283. // NetworkLatencyMultiplier tactics value to be used instead, which is
  284. // consistent with the pre-custom multiplier behavior in the older client
  285. // version which persisted that DialParameters.
  286. networkLatencyMultiplierMin := p.Float(parameters.NetworkLatencyMultiplierMin)
  287. networkLatencyMultiplierMax := p.Float(parameters.NetworkLatencyMultiplierMax)
  288. if !isReplay ||
  289. // Was selected...
  290. (dialParams.NetworkLatencyMultiplier != 0.0 &&
  291. // But is now outside tactics range...
  292. (dialParams.NetworkLatencyMultiplier < networkLatencyMultiplierMin ||
  293. dialParams.NetworkLatencyMultiplier > networkLatencyMultiplierMax)) {
  294. dialParams.NetworkLatencyMultiplier = prng.ExpFloat64Range(
  295. networkLatencyMultiplierMin,
  296. networkLatencyMultiplierMax,
  297. p.Float(parameters.NetworkLatencyMultiplierLambda))
  298. }
  299. // After this point, any tactics parameters that apply the network latency
  300. // multiplier will use this selected value.
  301. p = config.GetParameters().GetCustom(dialParams.NetworkLatencyMultiplier)
  302. if !isReplay && !isExchanged {
  303. // TODO: should there be a pre-check of selectProtocol before incurring
  304. // overhead of unmarshaling dial parameters? In may be that a server entry
  305. // is fully incapable of satisfying the current protocol selection
  306. // constraints.
  307. selectedProtocol, ok := selectProtocol(serverEntry)
  308. if !ok {
  309. return nil, nil
  310. }
  311. dialParams.TunnelProtocol = selectedProtocol
  312. }
  313. // Skip this candidate when the clients tactics restrict usage of the
  314. // fronting provider ID. See the corresponding server-side enforcement
  315. // comments in server.TacticsListener.accept.
  316. if protocol.TunnelProtocolUsesFrontedMeek(dialParams.TunnelProtocol) &&
  317. common.Contains(
  318. p.Strings(parameters.RestrictFrontingProviderIDs),
  319. dialParams.ServerEntry.FrontingProviderID) {
  320. if p.WeightedCoinFlip(
  321. parameters.RestrictFrontingProviderIDsClientProbability) {
  322. // When skipping, return nil/nil as no error should be logged.
  323. // NoticeSkipServerEntry emits each skip reason, regardless
  324. // of server entry, at most once per session.
  325. NoticeSkipServerEntry(
  326. "restricted fronting provider ID: %s",
  327. dialParams.ServerEntry.FrontingProviderID)
  328. return nil, nil
  329. }
  330. }
  331. if config.UseUpstreamProxy() {
  332. // When UpstreamProxy is configured, ServerEntry.GetSupportedProtocols, when
  333. // called via selectProtocol, will filter out protocols such that will not
  334. // select a protocol incompatible with UpstreamProxy. This additional check
  335. // will catch cases where selectProtocol does not apply this filter.
  336. if !protocol.TunnelProtocolSupportsUpstreamProxy(dialParams.TunnelProtocol) {
  337. NoticeSkipServerEntry(
  338. "protocol does not support upstream proxy: %s",
  339. dialParams.TunnelProtocol)
  340. return nil, nil
  341. }
  342. // Skip this candidate when the server entry is not to be used with an
  343. // upstream proxy. By not exposing servers from sources that are
  344. // relatively hard to enumerate, this mechanism mitigates the risk of
  345. // a malicious upstream proxy enumerating Psiphon servers. Populate
  346. // the allowed sources with fronted servers to provide greater
  347. // blocking resistence for clients using upstream proxy clients that
  348. // are subject to blocking.
  349. source := dialParams.ServerEntry.LocalSource
  350. if !protocol.AllowServerEntrySourceWithUpstreamProxy(source) &&
  351. !p.Bool(parameters.UpstreamProxyAllowAllServerEntrySources) {
  352. NoticeSkipServerEntry(
  353. "server entry source disallowed with upstream proxy: %s",
  354. source)
  355. return nil, nil
  356. }
  357. }
  358. if (!isReplay || !replayBPF) &&
  359. ClientBPFEnabled() &&
  360. protocol.TunnelProtocolUsesTCP(dialParams.TunnelProtocol) {
  361. if p.WeightedCoinFlip(parameters.BPFClientTCPProbability) {
  362. dialParams.BPFProgramName = ""
  363. dialParams.BPFProgramInstructions = nil
  364. ok, name, rawInstructions := p.BPFProgram(parameters.BPFClientTCPProgram)
  365. if ok {
  366. dialParams.BPFProgramName = name
  367. dialParams.BPFProgramInstructions = rawInstructions
  368. }
  369. }
  370. }
  371. if !isReplay || !replaySSH {
  372. dialParams.SelectedSSHClientVersion = true
  373. dialParams.SSHClientVersion = values.GetSSHClientVersion()
  374. dialParams.SSHKEXSeed, err = prng.NewSeed()
  375. if err != nil {
  376. return nil, errors.Trace(err)
  377. }
  378. }
  379. if !isReplay || !replayObfuscatorPadding {
  380. dialParams.ObfuscatorPaddingSeed, err = prng.NewSeed()
  381. if err != nil {
  382. return nil, errors.Trace(err)
  383. }
  384. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) {
  385. dialParams.MeekObfuscatorPaddingSeed, err = prng.NewSeed()
  386. if err != nil {
  387. return nil, errors.Trace(err)
  388. }
  389. }
  390. }
  391. if !isReplay || !replayFragmentor {
  392. dialParams.FragmentorSeed, err = prng.NewSeed()
  393. if err != nil {
  394. return nil, errors.Trace(err)
  395. }
  396. }
  397. if (!isReplay || !replayConjureRegistration) &&
  398. protocol.TunnelProtocolUsesConjure(dialParams.TunnelProtocol) {
  399. dialParams.ConjureCachedRegistrationTTL = p.Duration(parameters.ConjureCachedRegistrationTTL)
  400. apiURL := p.String(parameters.ConjureAPIRegistrarBidirectionalURL)
  401. decoyWidth := p.Int(parameters.ConjureDecoyRegistrarWidth)
  402. dialParams.ConjureAPIRegistration = apiURL != ""
  403. dialParams.ConjureDecoyRegistration = decoyWidth != 0
  404. // We select only one of API or decoy registration. When both are enabled,
  405. // ConjureDecoyRegistrarProbability determines the probability of using
  406. // decoy registration.
  407. //
  408. // In general, we disable retries in gotapdance and rely on Psiphon
  409. // establishment to try/retry different registration schemes. This allows us
  410. // to control the proportion of registration types attempted. And, in good
  411. // network conditions, individual candidates are most likely to be cancelled
  412. // before they exhaust their retry options.
  413. if dialParams.ConjureAPIRegistration && dialParams.ConjureDecoyRegistration {
  414. if p.WeightedCoinFlip(parameters.ConjureDecoyRegistrarProbability) {
  415. dialParams.ConjureAPIRegistration = false
  416. }
  417. }
  418. if dialParams.ConjureAPIRegistration {
  419. // While Conjure API registration uses MeekConn and specifies common meek
  420. // parameters, the meek address and SNI configuration is implemented in this
  421. // code block and not in common code blocks below. The exception is TLS
  422. // configuration.
  423. //
  424. // Accordingly, replayFronting/replayHostname have no effect on Conjure API
  425. // registration replay.
  426. dialParams.ConjureAPIRegistrarBidirectionalURL = apiURL
  427. frontingSpecs := p.FrontingSpecs(parameters.ConjureAPIRegistrarFrontingSpecs)
  428. dialParams.FrontingProviderID,
  429. dialParams.MeekFrontingDialAddress,
  430. dialParams.MeekSNIServerName,
  431. dialParams.MeekVerifyServerName,
  432. dialParams.MeekVerifyPins,
  433. dialParams.MeekFrontingHost,
  434. err = frontingSpecs.SelectParameters()
  435. if err != nil {
  436. return nil, errors.Trace(err)
  437. }
  438. dialParams.MeekDialAddress = fmt.Sprintf("%s:443", dialParams.MeekFrontingDialAddress)
  439. dialParams.MeekHostHeader = dialParams.MeekFrontingHost
  440. // For a FrontingSpec, an SNI value of "" indicates to disable/omit SNI, so
  441. // never transform in that case.
  442. if dialParams.MeekSNIServerName != "" {
  443. if p.WeightedCoinFlip(parameters.TransformHostNameProbability) {
  444. dialParams.MeekSNIServerName = selectHostName(dialParams.TunnelProtocol, p)
  445. dialParams.MeekTransformedHostName = true
  446. }
  447. }
  448. // The minimum delay value is determined by the Conjure station, which
  449. // performs an asynchronous "liveness test" against the selected phantom
  450. // IPs. The min/max range allows us to introduce some jitter so that we
  451. // don't present a trivial inter-flow fingerprint: CDN connection, fixed
  452. // delay, phantom dial.
  453. minDelay := p.Duration(parameters.ConjureAPIRegistrarMinDelay)
  454. maxDelay := p.Duration(parameters.ConjureAPIRegistrarMaxDelay)
  455. dialParams.ConjureAPIRegistrarDelay = prng.Period(minDelay, maxDelay)
  456. } else if dialParams.ConjureDecoyRegistration {
  457. dialParams.ConjureDecoyRegistrarWidth = decoyWidth
  458. minDelay := p.Duration(parameters.ConjureDecoyRegistrarMinDelay)
  459. maxDelay := p.Duration(parameters.ConjureDecoyRegistrarMaxDelay)
  460. dialParams.ConjureAPIRegistrarDelay = prng.Period(minDelay, maxDelay)
  461. } else {
  462. return nil, errors.TraceNew("no Conjure registrar configured")
  463. }
  464. }
  465. if (!isReplay || !replayConjureTransport) &&
  466. protocol.TunnelProtocolUsesConjure(dialParams.TunnelProtocol) {
  467. dialParams.ConjureTransport = protocol.CONJURE_TRANSPORT_MIN_OSSH
  468. if p.WeightedCoinFlip(
  469. parameters.ConjureTransportObfs4Probability) {
  470. dialParams.ConjureTransport = protocol.CONJURE_TRANSPORT_OBFS4_OSSH
  471. }
  472. }
  473. usingTLS := protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol) ||
  474. dialParams.ConjureAPIRegistration
  475. if (!isReplay || !replayTLSProfile) && usingTLS {
  476. dialParams.SelectedTLSProfile = true
  477. requireTLS12SessionTickets := protocol.TunnelProtocolRequiresTLS12SessionTickets(
  478. dialParams.TunnelProtocol)
  479. isFronted := protocol.TunnelProtocolUsesFrontedMeek(dialParams.TunnelProtocol) ||
  480. dialParams.ConjureAPIRegistration
  481. dialParams.TLSProfile = SelectTLSProfile(
  482. requireTLS12SessionTickets, isFronted, serverEntry.FrontingProviderID, p)
  483. dialParams.NoDefaultTLSSessionID = p.WeightedCoinFlip(
  484. parameters.NoDefaultTLSSessionIDProbability)
  485. }
  486. if (!isReplay || !replayRandomizedTLSProfile) && usingTLS &&
  487. protocol.TLSProfileIsRandomized(dialParams.TLSProfile) {
  488. dialParams.RandomizedTLSProfileSeed, err = prng.NewSeed()
  489. if err != nil {
  490. return nil, errors.Trace(err)
  491. }
  492. }
  493. if (!isReplay || !replayTLSProfile) && usingTLS {
  494. // Since "Randomized-v2"/CustomTLSProfiles may be TLS 1.2 or TLS 1.3,
  495. // construct the ClientHello to determine if it's TLS 1.3. This test also
  496. // covers non-randomized TLS 1.3 profiles. This check must come after
  497. // dialParams.TLSProfile and dialParams.RandomizedTLSProfileSeed are set. No
  498. // actual dial is made here.
  499. utlsClientHelloID, utlsClientHelloSpec, err := getUTLSClientHelloID(
  500. p, dialParams.TLSProfile)
  501. if err != nil {
  502. return nil, errors.Trace(err)
  503. }
  504. if protocol.TLSProfileIsRandomized(dialParams.TLSProfile) {
  505. utlsClientHelloID.Seed = new(utls.PRNGSeed)
  506. *utlsClientHelloID.Seed = [32]byte(*dialParams.RandomizedTLSProfileSeed)
  507. }
  508. dialParams.TLSVersion, err = getClientHelloVersion(
  509. utlsClientHelloID, utlsClientHelloSpec)
  510. if err != nil {
  511. return nil, errors.Trace(err)
  512. }
  513. }
  514. if (!isReplay || !replayFronting) &&
  515. protocol.TunnelProtocolUsesFrontedMeek(dialParams.TunnelProtocol) {
  516. dialParams.FrontingProviderID = serverEntry.FrontingProviderID
  517. dialParams.MeekFrontingDialAddress, dialParams.MeekFrontingHost, err =
  518. selectFrontingParameters(serverEntry)
  519. if err != nil {
  520. return nil, errors.Trace(err)
  521. }
  522. }
  523. if !isReplay || !replayHostname {
  524. if protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol) ||
  525. protocol.TunnelProtocolUsesFrontedMeekQUIC(dialParams.TunnelProtocol) {
  526. dialParams.MeekSNIServerName = ""
  527. if p.WeightedCoinFlip(parameters.TransformHostNameProbability) {
  528. dialParams.MeekSNIServerName = selectHostName(dialParams.TunnelProtocol, p)
  529. dialParams.MeekTransformedHostName = true
  530. }
  531. } else if protocol.TunnelProtocolUsesMeekHTTP(dialParams.TunnelProtocol) {
  532. dialParams.MeekHostHeader = ""
  533. hostname := serverEntry.IpAddress
  534. if p.WeightedCoinFlip(parameters.TransformHostNameProbability) {
  535. hostname = selectHostName(dialParams.TunnelProtocol, p)
  536. dialParams.MeekTransformedHostName = true
  537. }
  538. if serverEntry.MeekServerPort == 80 {
  539. dialParams.MeekHostHeader = hostname
  540. } else {
  541. dialParams.MeekHostHeader = fmt.Sprintf("%s:%d", hostname, serverEntry.MeekServerPort)
  542. }
  543. } else if protocol.TunnelProtocolUsesQUIC(dialParams.TunnelProtocol) {
  544. dialParams.QUICDialSNIAddress = fmt.Sprintf(
  545. "%s:%d",
  546. selectHostName(dialParams.TunnelProtocol, p),
  547. serverEntry.SshObfuscatedQUICPort)
  548. }
  549. }
  550. if (!isReplay || !replayQUICVersion) &&
  551. protocol.TunnelProtocolUsesQUIC(dialParams.TunnelProtocol) {
  552. isFronted := protocol.TunnelProtocolUsesFrontedMeekQUIC(dialParams.TunnelProtocol)
  553. dialParams.QUICVersion = selectQUICVersion(isFronted, serverEntry, p)
  554. if protocol.QUICVersionHasRandomizedClientHello(dialParams.QUICVersion) {
  555. dialParams.QUICClientHelloSeed, err = prng.NewSeed()
  556. if err != nil {
  557. return nil, errors.Trace(err)
  558. }
  559. }
  560. dialParams.QUICDisablePathMTUDiscovery =
  561. protocol.QUICVersionUsesPathMTUDiscovery(dialParams.QUICVersion) &&
  562. p.WeightedCoinFlip(parameters.QUICDisableClientPathMTUDiscoveryProbability)
  563. }
  564. if (!isReplay || !replayObfuscatedQUIC) &&
  565. protocol.QUICVersionIsObfuscated(dialParams.QUICVersion) {
  566. dialParams.ObfuscatedQUICPaddingSeed, err = prng.NewSeed()
  567. if err != nil {
  568. return nil, errors.Trace(err)
  569. }
  570. }
  571. if !isReplay || !replayLivenessTest {
  572. // TODO: initialize only when LivenessTestMaxUp/DownstreamBytes > 0?
  573. dialParams.LivenessTestSeed, err = prng.NewSeed()
  574. if err != nil {
  575. return nil, errors.Trace(err)
  576. }
  577. }
  578. if !isReplay || !replayAPIRequestPadding {
  579. dialParams.APIRequestPaddingSeed, err = prng.NewSeed()
  580. if err != nil {
  581. return nil, errors.Trace(err)
  582. }
  583. }
  584. if !isReplay || !replayHoldOffTunnel {
  585. if common.Contains(
  586. p.TunnelProtocols(parameters.HoldOffTunnelProtocols), dialParams.TunnelProtocol) ||
  587. (protocol.TunnelProtocolUsesFrontedMeek(dialParams.TunnelProtocol) &&
  588. common.Contains(
  589. p.Strings(parameters.HoldOffTunnelFrontingProviderIDs),
  590. dialParams.FrontingProviderID)) {
  591. if p.WeightedCoinFlip(parameters.HoldOffTunnelProbability) {
  592. dialParams.HoldOffTunnelDuration = prng.Period(
  593. p.Duration(parameters.HoldOffTunnelMinDuration),
  594. p.Duration(parameters.HoldOffTunnelMaxDuration))
  595. }
  596. }
  597. }
  598. // Set dial address fields. This portion of configuration is
  599. // deterministic, given the parameters established or replayed so far.
  600. dialPortNumber, err := serverEntry.GetDialPortNumber(dialParams.TunnelProtocol)
  601. if err != nil {
  602. return nil, errors.Trace(err)
  603. }
  604. dialParams.DialPortNumber = strconv.Itoa(dialPortNumber)
  605. switch dialParams.TunnelProtocol {
  606. case protocol.TUNNEL_PROTOCOL_SSH,
  607. protocol.TUNNEL_PROTOCOL_OBFUSCATED_SSH,
  608. protocol.TUNNEL_PROTOCOL_TAPDANCE_OBFUSCATED_SSH,
  609. protocol.TUNNEL_PROTOCOL_CONJURE_OBFUSCATED_SSH,
  610. protocol.TUNNEL_PROTOCOL_QUIC_OBFUSCATED_SSH:
  611. dialParams.DirectDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, dialPortNumber)
  612. case protocol.TUNNEL_PROTOCOL_FRONTED_MEEK,
  613. protocol.TUNNEL_PROTOCOL_FRONTED_MEEK_QUIC_OBFUSCATED_SSH:
  614. dialParams.MeekDialAddress = fmt.Sprintf("%s:%d", dialParams.MeekFrontingDialAddress, dialPortNumber)
  615. dialParams.MeekHostHeader = dialParams.MeekFrontingHost
  616. if serverEntry.MeekFrontingDisableSNI {
  617. dialParams.MeekSNIServerName = ""
  618. // When SNI is omitted, the transformed host name is not used.
  619. dialParams.MeekTransformedHostName = false
  620. } else if !dialParams.MeekTransformedHostName {
  621. dialParams.MeekSNIServerName = dialParams.MeekFrontingDialAddress
  622. }
  623. case protocol.TUNNEL_PROTOCOL_FRONTED_MEEK_HTTP:
  624. dialParams.MeekDialAddress = fmt.Sprintf("%s:%d", dialParams.MeekFrontingDialAddress, dialPortNumber)
  625. dialParams.MeekHostHeader = dialParams.MeekFrontingHost
  626. // For FRONTED HTTP, the Host header cannot be transformed.
  627. dialParams.MeekTransformedHostName = false
  628. case protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK:
  629. dialParams.MeekDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, dialPortNumber)
  630. if !dialParams.MeekTransformedHostName {
  631. if dialPortNumber == 80 {
  632. dialParams.MeekHostHeader = serverEntry.IpAddress
  633. } else {
  634. dialParams.MeekHostHeader = dialParams.MeekDialAddress
  635. }
  636. }
  637. case protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  638. protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET:
  639. dialParams.MeekDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, dialPortNumber)
  640. if !dialParams.MeekTransformedHostName {
  641. // Note: IP address in SNI field will be omitted.
  642. dialParams.MeekSNIServerName = serverEntry.IpAddress
  643. }
  644. if dialPortNumber == 443 {
  645. dialParams.MeekHostHeader = serverEntry.IpAddress
  646. } else {
  647. dialParams.MeekHostHeader = dialParams.MeekDialAddress
  648. }
  649. default:
  650. return nil, errors.Tracef(
  651. "unknown tunnel protocol: %s", dialParams.TunnelProtocol)
  652. }
  653. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) {
  654. host, _, _ := net.SplitHostPort(dialParams.MeekDialAddress)
  655. if p.Bool(parameters.MeekDialDomainsOnly) {
  656. if net.ParseIP(host) != nil {
  657. // No error, as this is a "not supported" case.
  658. return nil, nil
  659. }
  660. }
  661. // The underlying TLS will automatically disable SNI for IP address server name
  662. // values; we have this explicit check here so 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. for _, quicVersion := range protocol.SupportedQUICVersions {
  977. if len(limitQUICVersions) > 0 &&
  978. !common.Contains(limitQUICVersions, quicVersion) {
  979. continue
  980. }
  981. // Both tactics and the server entry can specify LimitQUICVersions. In
  982. // tactics, the parameter is intended to direct certain clients to
  983. // use a successful protocol variant. In the server entry, the
  984. // parameter may be used to direct all clients to send
  985. // consistent-looking protocol variants to a particular server; e.g.,
  986. // only regular QUIC, or only obfuscated QUIC.
  987. //
  988. // The isFronted/QUICVersionIsObfuscated logic predates
  989. // ServerEntry.LimitQUICVersions; ServerEntry.LimitQUICVersions could
  990. // now be used to achieve a similar outcome.
  991. if len(serverEntry.LimitQUICVersions) > 0 &&
  992. !common.Contains(serverEntry.LimitQUICVersions, quicVersion) {
  993. continue
  994. }
  995. if isFronted &&
  996. protocol.QUICVersionIsObfuscated(quicVersion) {
  997. continue
  998. }
  999. if common.Contains(disableQUICVersions, quicVersion) {
  1000. continue
  1001. }
  1002. quicVersions = append(quicVersions, quicVersion)
  1003. }
  1004. if len(quicVersions) == 0 {
  1005. return ""
  1006. }
  1007. choice := prng.Intn(len(quicVersions))
  1008. return quicVersions[choice]
  1009. }
  1010. // selectUserAgentIfUnset selects a User-Agent header if one is not set.
  1011. func selectUserAgentIfUnset(
  1012. p parameters.ParametersAccessor, headers http.Header) (bool, string) {
  1013. if _, ok := headers["User-Agent"]; !ok {
  1014. userAgent := ""
  1015. if p.WeightedCoinFlip(parameters.PickUserAgentProbability) {
  1016. userAgent = values.GetUserAgent()
  1017. }
  1018. return true, userAgent
  1019. }
  1020. return false, ""
  1021. }
  1022. func makeDialCustomHeaders(
  1023. config *Config,
  1024. p parameters.ParametersAccessor) http.Header {
  1025. dialCustomHeaders := make(http.Header)
  1026. if config.CustomHeaders != nil {
  1027. for k, v := range config.CustomHeaders {
  1028. dialCustomHeaders[k] = make([]string, len(v))
  1029. copy(dialCustomHeaders[k], v)
  1030. }
  1031. }
  1032. additionalCustomHeaders := p.HTTPHeaders(parameters.AdditionalCustomHeaders)
  1033. for k, v := range additionalCustomHeaders {
  1034. dialCustomHeaders[k] = make([]string, len(v))
  1035. copy(dialCustomHeaders[k], v)
  1036. }
  1037. return dialCustomHeaders
  1038. }
  1039. func selectHostName(
  1040. tunnelProtocol string, p parameters.ParametersAccessor) string {
  1041. limitProtocols := p.TunnelProtocols(parameters.CustomHostNameLimitProtocols)
  1042. if len(limitProtocols) > 0 && !common.Contains(limitProtocols, tunnelProtocol) {
  1043. return values.GetHostName()
  1044. }
  1045. if !p.WeightedCoinFlip(parameters.CustomHostNameProbability) {
  1046. return values.GetHostName()
  1047. }
  1048. regexStrings := p.RegexStrings(parameters.CustomHostNameRegexes)
  1049. if len(regexStrings) == 0 {
  1050. return values.GetHostName()
  1051. }
  1052. choice := prng.Intn(len(regexStrings))
  1053. hostName, err := regen.Generate(regexStrings[choice])
  1054. if err != nil {
  1055. NoticeWarning("selectHostName: regen.Generate failed: %v", errors.Trace(err))
  1056. return values.GetHostName()
  1057. }
  1058. return hostName
  1059. }