dialParameters.go 45 KB

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