dialParameters.go 41 KB

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