dialParameters.go 47 KB

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