dialParameters.go 43 KB

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