dialParameters.go 47 KB

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