dialParameters.go 42 KB

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