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