dialParameters.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  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. "net/url"
  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. IsExchanged bool
  61. LastUsedTimestamp time.Time
  62. LastUsedConfigStateHash []byte
  63. NetworkLatencyMultiplier float64
  64. TunnelProtocol string
  65. DirectDialAddress string
  66. DialPortNumber string
  67. UpstreamProxyType string `json:"-"`
  68. UpstreamProxyCustomHeaderNames []string `json:"-"`
  69. BPFProgramName string
  70. BPFProgramInstructions []bpf.RawInstruction
  71. SelectedSSHClientVersion bool
  72. SSHClientVersion string
  73. SSHKEXSeed *prng.Seed
  74. ObfuscatorPaddingSeed *prng.Seed
  75. FragmentorSeed *prng.Seed
  76. FrontingProviderID string
  77. MeekFrontingDialAddress string
  78. MeekFrontingHost string
  79. MeekDialAddress string
  80. MeekTransformedHostName bool
  81. MeekSNIServerName string
  82. MeekHostHeader string
  83. MeekObfuscatorPaddingSeed *prng.Seed
  84. MeekTLSPaddingSize int
  85. MeekResolvedIPAddress atomic.Value `json:"-"`
  86. SelectedUserAgent bool
  87. UserAgent string
  88. SelectedTLSProfile bool
  89. TLSProfile string
  90. NoDefaultTLSSessionID bool
  91. TLSVersion string
  92. RandomizedTLSProfileSeed *prng.Seed
  93. QUICVersion string
  94. QUICDialSNIAddress string
  95. ObfuscatedQUICPaddingSeed *prng.Seed
  96. LivenessTestSeed *prng.Seed
  97. APIRequestPaddingSeed *prng.Seed
  98. DialConnMetrics common.MetricsSource `json:"-"`
  99. ObfuscatedSSHConnMetrics common.MetricsSource `json:"-"`
  100. DialDuration time.Duration `json:"-"`
  101. dialConfig *DialConfig
  102. meekConfig *MeekConfig
  103. }
  104. // MakeDialParameters creates a new DialParameters for the candidate server
  105. // entry, including selecting a protocol and all the various protocol
  106. // attributes. The input selectProtocol is used to comply with any active
  107. // protocol selection constraints.
  108. //
  109. // When stored dial parameters are available and may be used,
  110. // MakeDialParameters may replay previous dial parameters in an effort to
  111. // leverage "known working" values instead of always chosing at random from a
  112. // large space.
  113. //
  114. // MakeDialParameters will return nil/nil in cases where the candidate server
  115. // entry should be skipped.
  116. //
  117. // To support replay, the caller must call DialParameters.Succeeded when a
  118. // successful tunnel is established with the returned DialParameters; and must
  119. // call DialParameters.Failed when a tunnel dial or activation fails, except
  120. // when establishment is cancelled.
  121. func MakeDialParameters(
  122. config *Config,
  123. canReplay func(serverEntry *protocol.ServerEntry, replayProtocol string) bool,
  124. selectProtocol func(serverEntry *protocol.ServerEntry) (string, bool),
  125. serverEntry *protocol.ServerEntry,
  126. isTactics bool,
  127. candidateNumber int) (*DialParameters, error) {
  128. networkID := config.GetNetworkID()
  129. p := config.GetClientParameters().Get()
  130. ttl := p.Duration(parameters.ReplayDialParametersTTL)
  131. replayBPF := p.Bool(parameters.ReplayBPF)
  132. replaySSH := p.Bool(parameters.ReplaySSH)
  133. replayObfuscatorPadding := p.Bool(parameters.ReplayObfuscatorPadding)
  134. replayFragmentor := p.Bool(parameters.ReplayFragmentor)
  135. replayTLSProfile := p.Bool(parameters.ReplayTLSProfile)
  136. replayRandomizedTLSProfile := p.Bool(parameters.ReplayRandomizedTLSProfile)
  137. replayFronting := p.Bool(parameters.ReplayFronting)
  138. replayHostname := p.Bool(parameters.ReplayHostname)
  139. replayQUICVersion := p.Bool(parameters.ReplayQUICVersion)
  140. replayObfuscatedQUIC := p.Bool(parameters.ReplayObfuscatedQUIC)
  141. replayLivenessTest := p.Bool(parameters.ReplayLivenessTest)
  142. replayUserAgent := p.Bool(parameters.ReplayUserAgent)
  143. replayAPIRequestPadding := p.Bool(parameters.ReplayAPIRequestPadding)
  144. // Check for existing dial parameters for this server/network ID.
  145. dialParams, err := GetDialParameters(serverEntry.IpAddress, networkID)
  146. if err != nil {
  147. NoticeWarning("GetDialParameters failed: %s", err)
  148. dialParams = nil
  149. // Proceed, without existing dial parameters.
  150. }
  151. // Check if replay is permitted:
  152. // - TTL must be > 0 and existing dial parameters must not have expired
  153. // as indicated by LastUsedTimestamp + TTL.
  154. // - Config/tactics/server entry values must be unchanged from when
  155. // previous dial parameters were established.
  156. // - The protocol selection constraints must permit replay, as indicated
  157. // by canReplay.
  158. // - Must not be using an obsolete TLS profile that is no longer supported.
  159. //
  160. // When existing dial parameters don't meet these conditions, dialParams
  161. // is reset to nil and new dial parameters will be generated.
  162. var currentTimestamp time.Time
  163. var configStateHash []byte
  164. // When TTL is 0, replay is disabled; the timestamp remains 0 and the
  165. // output DialParameters will not be stored by Success.
  166. if ttl > 0 {
  167. currentTimestamp = time.Now()
  168. configStateHash = getConfigStateHash(config, p, serverEntry)
  169. }
  170. if dialParams != nil &&
  171. (ttl <= 0 ||
  172. dialParams.LastUsedTimestamp.Before(currentTimestamp.Add(-ttl)) ||
  173. !bytes.Equal(dialParams.LastUsedConfigStateHash, configStateHash) ||
  174. (dialParams.TLSProfile != "" &&
  175. !common.Contains(protocol.SupportedTLSProfiles, dialParams.TLSProfile)) ||
  176. (dialParams.QUICVersion != "" &&
  177. !common.Contains(protocol.SupportedQUICVersions, dialParams.QUICVersion))) {
  178. // In these cases, existing dial parameters are expired or no longer
  179. // match the config state and so are cleared to avoid rechecking them.
  180. err = DeleteDialParameters(serverEntry.IpAddress, networkID)
  181. if err != nil {
  182. NoticeWarning("DeleteDialParameters failed: %s", err)
  183. }
  184. dialParams = nil
  185. }
  186. if dialParams != nil {
  187. if config.DisableReplay ||
  188. !canReplay(serverEntry, dialParams.TunnelProtocol) {
  189. // In these ephemeral cases, existing dial parameters may still be valid
  190. // and used in future establishment phases, and so are retained.
  191. dialParams = nil
  192. }
  193. }
  194. // IsExchanged:
  195. //
  196. // Dial parameters received via client-to-client exchange are partially
  197. // initialized. Only the exchange fields are retained, and all other dial
  198. // parameters fields must be initialized. This is not considered or logged as
  199. // a replay. The exchange case is identified by the IsExchanged flag.
  200. //
  201. // When previously stored, IsExchanged dial parameters will have set the same
  202. // timestamp and state hash used for regular dial parameters and the same
  203. // logic above should invalidate expired or invalid exchanged dial
  204. // parameters.
  205. //
  206. // Limitation: metrics will indicate when an exchanged server entry is used
  207. // (source "EXCHANGED") but will not indicate when exchanged dial parameters
  208. // are used vs. a redial after discarding dial parameters.
  209. isReplay := (dialParams != nil)
  210. isExchanged := isReplay && dialParams.IsExchanged
  211. if !isReplay {
  212. dialParams = &DialParameters{}
  213. }
  214. if isExchanged {
  215. // Set isReplay to false to cause all non-exchanged values to be
  216. // initialized; this also causes the exchange case to not log as replay.
  217. isReplay = false
  218. }
  219. // Set IsExchanged so that full dial parameters are stored and replayed upon success.
  220. dialParams.IsExchanged = false
  221. dialParams.ServerEntry = serverEntry
  222. dialParams.NetworkID = networkID
  223. dialParams.IsReplay = isReplay
  224. dialParams.CandidateNumber = candidateNumber
  225. // Even when replaying, LastUsedTimestamp is updated to extend the TTL of
  226. // replayed dial parameters which will be updated in the datastore upon
  227. // success.
  228. dialParams.LastUsedTimestamp = currentTimestamp
  229. dialParams.LastUsedConfigStateHash = configStateHash
  230. // Initialize dial parameters.
  231. //
  232. // When not replaying, all required parameters are initialized. When
  233. // replaying, existing parameters are retaing, subject to the replay-X
  234. // tactics flags.
  235. // Select a network latency multiplier for this dial. This allows clients to
  236. // explore and discover timeout values appropriate for the current network.
  237. // The selection applies per tunnel, to avoid delaying all establishment
  238. // candidates due to excessive timeouts. The random selection is bounded by a
  239. // min/max set in tactics and an exponential distribution is used so as to
  240. // heavily favor values close to the min, which should be set to the
  241. // singleton NetworkLatencyMultiplier tactics value.
  242. //
  243. // Not all existing, persisted DialParameters will have a custom
  244. // NetworkLatencyMultiplier value. Its zero value will cause the singleton
  245. // NetworkLatencyMultiplier tactics value to be used instead, which is
  246. // consistent with the pre-custom multiplier behavior in the older client
  247. // version which persisted that DialParameters.
  248. networkLatencyMultiplierMin := p.Float(parameters.NetworkLatencyMultiplierMin)
  249. networkLatencyMultiplierMax := p.Float(parameters.NetworkLatencyMultiplierMax)
  250. if !isReplay ||
  251. // Was selected...
  252. (dialParams.NetworkLatencyMultiplier != 0.0 &&
  253. // But is now outside tactics range...
  254. (dialParams.NetworkLatencyMultiplier < networkLatencyMultiplierMin ||
  255. dialParams.NetworkLatencyMultiplier > networkLatencyMultiplierMax)) {
  256. dialParams.NetworkLatencyMultiplier = prng.ExpFloat64Range(
  257. networkLatencyMultiplierMin,
  258. networkLatencyMultiplierMax,
  259. p.Float(parameters.NetworkLatencyMultiplierLambda))
  260. }
  261. if !isReplay && !isExchanged {
  262. // TODO: should there be a pre-check of selectProtocol before incurring
  263. // overhead of unmarshaling dial parameters? In may be that a server entry
  264. // is fully incapable of satisfying the current protocol selection
  265. // constraints.
  266. selectedProtocol, ok := selectProtocol(serverEntry)
  267. if !ok {
  268. return nil, nil
  269. }
  270. dialParams.TunnelProtocol = selectedProtocol
  271. }
  272. if (!isReplay || !replayBPF) &&
  273. ClientBPFEnabled() &&
  274. protocol.TunnelProtocolUsesTCP(dialParams.TunnelProtocol) {
  275. if p.WeightedCoinFlip(parameters.BPFClientTCPProbability) {
  276. dialParams.BPFProgramName = ""
  277. dialParams.BPFProgramInstructions = nil
  278. ok, name, rawInstructions := p.BPFProgram(parameters.BPFClientTCPProgram)
  279. if ok {
  280. dialParams.BPFProgramName = name
  281. dialParams.BPFProgramInstructions = rawInstructions
  282. }
  283. }
  284. }
  285. if !isReplay || !replaySSH {
  286. dialParams.SelectedSSHClientVersion = true
  287. dialParams.SSHClientVersion = values.GetSSHClientVersion()
  288. dialParams.SSHKEXSeed, err = prng.NewSeed()
  289. if err != nil {
  290. return nil, errors.Trace(err)
  291. }
  292. }
  293. if !isReplay || !replayObfuscatorPadding {
  294. dialParams.ObfuscatorPaddingSeed, err = prng.NewSeed()
  295. if err != nil {
  296. return nil, errors.Trace(err)
  297. }
  298. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) {
  299. dialParams.MeekObfuscatorPaddingSeed, err = prng.NewSeed()
  300. if err != nil {
  301. return nil, errors.Trace(err)
  302. }
  303. }
  304. }
  305. if !isReplay || !replayFragmentor {
  306. dialParams.FragmentorSeed, err = prng.NewSeed()
  307. if err != nil {
  308. return nil, errors.Trace(err)
  309. }
  310. }
  311. if (!isReplay || !replayTLSProfile) &&
  312. protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol) {
  313. isFronted := protocol.TunnelProtocolUsesFrontedMeek(dialParams.TunnelProtocol)
  314. dialParams.SelectedTLSProfile = true
  315. dialParams.TLSProfile = SelectTLSProfile(isFronted, serverEntry.FrontingProviderID, p)
  316. dialParams.NoDefaultTLSSessionID = p.WeightedCoinFlip(
  317. parameters.NoDefaultTLSSessionIDProbability)
  318. }
  319. if (!isReplay || !replayRandomizedTLSProfile) &&
  320. protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol) &&
  321. protocol.TLSProfileIsRandomized(dialParams.TLSProfile) {
  322. dialParams.RandomizedTLSProfileSeed, err = prng.NewSeed()
  323. if err != nil {
  324. return nil, errors.Trace(err)
  325. }
  326. }
  327. if (!isReplay || !replayTLSProfile) &&
  328. protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol) {
  329. // Since "Randomized-v2"/CustomTLSProfiles may be TLS 1.2 or TLS 1.3,
  330. // construct the ClientHello to determine if it's TLS 1.3. This test also
  331. // covers non-randomized TLS 1.3 profiles. This check must come after
  332. // dialParams.TLSProfile and dialParams.RandomizedTLSProfileSeed are set. No
  333. // actual dial is made here.
  334. utlsClientHelloID, utlsClientHelloSpec, err := getUTLSClientHelloID(
  335. p, dialParams.TLSProfile)
  336. if err != nil {
  337. return nil, errors.Trace(err)
  338. }
  339. if protocol.TLSProfileIsRandomized(dialParams.TLSProfile) {
  340. utlsClientHelloID.Seed = new(utls.PRNGSeed)
  341. *utlsClientHelloID.Seed = [32]byte(*dialParams.RandomizedTLSProfileSeed)
  342. }
  343. dialParams.TLSVersion, err = getClientHelloVersion(
  344. utlsClientHelloID, utlsClientHelloSpec)
  345. if err != nil {
  346. return nil, errors.Trace(err)
  347. }
  348. }
  349. if (!isReplay || !replayFronting) &&
  350. protocol.TunnelProtocolUsesFrontedMeek(dialParams.TunnelProtocol) {
  351. dialParams.FrontingProviderID = serverEntry.FrontingProviderID
  352. dialParams.MeekFrontingDialAddress, dialParams.MeekFrontingHost, err =
  353. selectFrontingParameters(serverEntry)
  354. if err != nil {
  355. return nil, errors.Trace(err)
  356. }
  357. }
  358. if !isReplay || !replayHostname {
  359. if protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol) ||
  360. protocol.TunnelProtocolUsesFrontedMeekQUIC(dialParams.TunnelProtocol) {
  361. dialParams.MeekSNIServerName = ""
  362. if p.WeightedCoinFlip(parameters.TransformHostNameProbability) {
  363. dialParams.MeekSNIServerName = values.GetHostName()
  364. dialParams.MeekTransformedHostName = true
  365. }
  366. } else if protocol.TunnelProtocolUsesMeekHTTP(dialParams.TunnelProtocol) {
  367. dialParams.MeekHostHeader = ""
  368. hostname := serverEntry.IpAddress
  369. if p.WeightedCoinFlip(parameters.TransformHostNameProbability) {
  370. hostname = values.GetHostName()
  371. dialParams.MeekTransformedHostName = true
  372. }
  373. if serverEntry.MeekServerPort == 80 {
  374. dialParams.MeekHostHeader = hostname
  375. } else {
  376. dialParams.MeekHostHeader = fmt.Sprintf("%s:%d", hostname, serverEntry.MeekServerPort)
  377. }
  378. } else if protocol.TunnelProtocolUsesQUIC(dialParams.TunnelProtocol) {
  379. dialParams.QUICDialSNIAddress = fmt.Sprintf(
  380. "%s:%d", values.GetHostName(), serverEntry.SshObfuscatedQUICPort)
  381. }
  382. }
  383. if (!isReplay || !replayQUICVersion) &&
  384. protocol.TunnelProtocolUsesQUIC(dialParams.TunnelProtocol) {
  385. isFronted := protocol.TunnelProtocolUsesFrontedMeekQUIC(dialParams.TunnelProtocol)
  386. dialParams.QUICVersion = selectQUICVersion(isFronted, serverEntry.FrontingProviderID, p)
  387. }
  388. if (!isReplay || !replayObfuscatedQUIC) &&
  389. protocol.QUICVersionIsObfuscated(dialParams.QUICVersion) {
  390. dialParams.ObfuscatedQUICPaddingSeed, err = prng.NewSeed()
  391. if err != nil {
  392. return nil, errors.Trace(err)
  393. }
  394. }
  395. if !isReplay || !replayLivenessTest {
  396. // TODO: initialize only when LivenessTestMaxUp/DownstreamBytes > 0?
  397. dialParams.LivenessTestSeed, err = prng.NewSeed()
  398. if err != nil {
  399. return nil, errors.Trace(err)
  400. }
  401. }
  402. if !isReplay || !replayAPIRequestPadding {
  403. dialParams.APIRequestPaddingSeed, err = prng.NewSeed()
  404. if err != nil {
  405. return nil, errors.Trace(err)
  406. }
  407. }
  408. // Set dial address fields. This portion of configuration is
  409. // deterministic, given the parameters established or replayed so far.
  410. switch dialParams.TunnelProtocol {
  411. case protocol.TUNNEL_PROTOCOL_SSH:
  412. dialParams.DirectDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.SshPort)
  413. case protocol.TUNNEL_PROTOCOL_OBFUSCATED_SSH:
  414. dialParams.DirectDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.SshObfuscatedPort)
  415. case protocol.TUNNEL_PROTOCOL_TAPDANCE_OBFUSCATED_SSH:
  416. dialParams.DirectDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.SshObfuscatedTapdancePort)
  417. case protocol.TUNNEL_PROTOCOL_QUIC_OBFUSCATED_SSH:
  418. dialParams.DirectDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.SshObfuscatedQUICPort)
  419. case protocol.TUNNEL_PROTOCOL_FRONTED_MEEK_QUIC_OBFUSCATED_SSH:
  420. dialParams.MeekDialAddress = fmt.Sprintf("%s:443", dialParams.MeekFrontingDialAddress)
  421. dialParams.MeekHostHeader = dialParams.MeekFrontingHost
  422. if !dialParams.MeekTransformedHostName {
  423. dialParams.MeekSNIServerName = dialParams.MeekFrontingDialAddress
  424. }
  425. case protocol.TUNNEL_PROTOCOL_MARIONETTE_OBFUSCATED_SSH:
  426. // Note: port comes from marionnete "format"
  427. dialParams.DirectDialAddress = serverEntry.IpAddress
  428. case protocol.TUNNEL_PROTOCOL_FRONTED_MEEK:
  429. dialParams.MeekDialAddress = fmt.Sprintf("%s:443", dialParams.MeekFrontingDialAddress)
  430. dialParams.MeekHostHeader = dialParams.MeekFrontingHost
  431. if serverEntry.MeekFrontingDisableSNI {
  432. dialParams.MeekSNIServerName = ""
  433. } else if !dialParams.MeekTransformedHostName {
  434. dialParams.MeekSNIServerName = dialParams.MeekFrontingDialAddress
  435. }
  436. case protocol.TUNNEL_PROTOCOL_FRONTED_MEEK_HTTP:
  437. dialParams.MeekDialAddress = fmt.Sprintf("%s:80", dialParams.MeekFrontingDialAddress)
  438. dialParams.MeekHostHeader = dialParams.MeekFrontingHost
  439. case protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK:
  440. dialParams.MeekDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.MeekServerPort)
  441. if !dialParams.MeekTransformedHostName {
  442. if serverEntry.MeekServerPort == 80 {
  443. dialParams.MeekHostHeader = serverEntry.IpAddress
  444. } else {
  445. dialParams.MeekHostHeader = dialParams.MeekDialAddress
  446. }
  447. }
  448. case protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  449. protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET:
  450. dialParams.MeekDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.MeekServerPort)
  451. if !dialParams.MeekTransformedHostName {
  452. // Note: IP address in SNI field will be omitted.
  453. dialParams.MeekSNIServerName = serverEntry.IpAddress
  454. }
  455. if serverEntry.MeekServerPort == 443 {
  456. dialParams.MeekHostHeader = serverEntry.IpAddress
  457. } else {
  458. dialParams.MeekHostHeader = dialParams.MeekDialAddress
  459. }
  460. default:
  461. return nil, errors.Tracef(
  462. "unknown tunnel protocol: %s", dialParams.TunnelProtocol)
  463. }
  464. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) {
  465. host, port, _ := net.SplitHostPort(dialParams.MeekDialAddress)
  466. if p.Bool(parameters.MeekDialDomainsOnly) {
  467. if net.ParseIP(host) != nil {
  468. // No error, as this is a "not supported" case.
  469. return nil, nil
  470. }
  471. }
  472. dialParams.DialPortNumber = port
  473. // The underlying TLS will automatically disable SNI for IP address server name
  474. // values; we have this explicit check here so we record the correct value for stats.
  475. if net.ParseIP(dialParams.MeekSNIServerName) != nil {
  476. dialParams.MeekSNIServerName = ""
  477. }
  478. } else {
  479. _, dialParams.DialPortNumber, _ = net.SplitHostPort(dialParams.DirectDialAddress)
  480. }
  481. // Initialize/replay User-Agent header for HTTP upstream proxy and meek protocols.
  482. if config.UseUpstreamProxy() {
  483. // Note: UpstreamProxyURL will be validated in the dial
  484. proxyURL, err := url.Parse(config.UpstreamProxyURL)
  485. if err == nil {
  486. dialParams.UpstreamProxyType = proxyURL.Scheme
  487. }
  488. }
  489. dialCustomHeaders := makeDialCustomHeaders(config, p)
  490. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) || dialParams.UpstreamProxyType == "http" {
  491. if !isReplay || !replayUserAgent {
  492. dialParams.SelectedUserAgent, dialParams.UserAgent = selectUserAgentIfUnset(p, dialCustomHeaders)
  493. }
  494. if dialParams.SelectedUserAgent {
  495. dialCustomHeaders.Set("User-Agent", dialParams.UserAgent)
  496. }
  497. }
  498. // UpstreamProxyCustomHeaderNames is a reported metric. Just the names and
  499. // not the values are reported, in case the values are identifying.
  500. if len(config.CustomHeaders) > 0 {
  501. dialParams.UpstreamProxyCustomHeaderNames = make([]string, 0)
  502. for name := range dialCustomHeaders {
  503. if name == "User-Agent" && dialParams.SelectedUserAgent {
  504. continue
  505. }
  506. dialParams.UpstreamProxyCustomHeaderNames = append(dialParams.UpstreamProxyCustomHeaderNames, name)
  507. }
  508. }
  509. // Initialize Dial/MeekConfigs to be passed to the corresponding dialers.
  510. dialParams.dialConfig = &DialConfig{
  511. DiagnosticID: serverEntry.GetDiagnosticID(),
  512. UpstreamProxyURL: config.UpstreamProxyURL,
  513. CustomHeaders: dialCustomHeaders,
  514. BPFProgramInstructions: dialParams.BPFProgramInstructions,
  515. DeviceBinder: config.deviceBinder,
  516. DnsServerGetter: config.DnsServerGetter,
  517. IPv6Synthesizer: config.IPv6Synthesizer,
  518. TrustedCACertificatesFilename: config.TrustedCACertificatesFilename,
  519. FragmentorConfig: fragmentor.NewUpstreamConfig(p, dialParams.TunnelProtocol, dialParams.FragmentorSeed),
  520. }
  521. // Unconditionally initialize MeekResolvedIPAddress, so a valid string can
  522. // always be read.
  523. dialParams.MeekResolvedIPAddress.Store("")
  524. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) {
  525. dialParams.meekConfig = &MeekConfig{
  526. DiagnosticID: serverEntry.GetDiagnosticID(),
  527. ClientParameters: config.clientParameters,
  528. DialAddress: dialParams.MeekDialAddress,
  529. UseQUIC: protocol.TunnelProtocolUsesFrontedMeekQUIC(dialParams.TunnelProtocol),
  530. QUICVersion: dialParams.QUICVersion,
  531. UseHTTPS: protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol),
  532. TLSProfile: dialParams.TLSProfile,
  533. NoDefaultTLSSessionID: dialParams.NoDefaultTLSSessionID,
  534. RandomizedTLSProfileSeed: dialParams.RandomizedTLSProfileSeed,
  535. UseObfuscatedSessionTickets: dialParams.TunnelProtocol == protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET,
  536. SNIServerName: dialParams.MeekSNIServerName,
  537. HostHeader: dialParams.MeekHostHeader,
  538. TransformedHostName: dialParams.MeekTransformedHostName,
  539. ClientTunnelProtocol: dialParams.TunnelProtocol,
  540. MeekCookieEncryptionPublicKey: serverEntry.MeekCookieEncryptionPublicKey,
  541. MeekObfuscatedKey: serverEntry.MeekObfuscatedKey,
  542. MeekObfuscatorPaddingSeed: dialParams.MeekObfuscatorPaddingSeed,
  543. NetworkLatencyMultiplier: dialParams.NetworkLatencyMultiplier,
  544. }
  545. // Use an asynchronous callback to record the resolved IP address when
  546. // dialing a domain name. Note that DialMeek doesn't immediately
  547. // establish any HTTP connections, so the resolved IP address won't be
  548. // reported in all cases until after SSH traffic is relayed or a
  549. // endpoint request is made over the meek connection.
  550. dialParams.dialConfig.ResolvedIPCallback = func(IPAddress string) {
  551. dialParams.MeekResolvedIPAddress.Store(IPAddress)
  552. }
  553. if isTactics {
  554. dialParams.meekConfig.RoundTripperOnly = true
  555. }
  556. }
  557. return dialParams, nil
  558. }
  559. func (dialParams *DialParameters) GetDialConfig() *DialConfig {
  560. return dialParams.dialConfig
  561. }
  562. func (dialParams *DialParameters) GetMeekConfig() *MeekConfig {
  563. return dialParams.meekConfig
  564. }
  565. func (dialParams *DialParameters) Succeeded() {
  566. // When TTL is 0, don't store dial parameters.
  567. if dialParams.LastUsedTimestamp.IsZero() {
  568. return
  569. }
  570. NoticeInfo("Set dial parameters for %s", dialParams.ServerEntry.GetDiagnosticID())
  571. err := SetDialParameters(dialParams.ServerEntry.IpAddress, dialParams.NetworkID, dialParams)
  572. if err != nil {
  573. NoticeWarning("SetDialParameters failed: %s", err)
  574. }
  575. }
  576. func (dialParams *DialParameters) Failed(config *Config) {
  577. // When a tunnel fails, and the dial is a replay, clear the stored dial
  578. // parameters which are now presumed to be blocked, impaired or otherwise
  579. // no longer effective.
  580. //
  581. // It may be the case that a dial is not using stored dial parameters
  582. // (!IsReplay), and in this case we retain those dial parameters since they
  583. // were not exercised and may still be effective.
  584. //
  585. // Failed tunnel dial parameters may be retained with a configurable
  586. // probability; this is intended to help mitigate false positive failures due
  587. // to, e.g., temporary network disruptions or server load limiting.
  588. if dialParams.IsReplay &&
  589. !config.GetClientParameters().Get().WeightedCoinFlip(
  590. parameters.ReplayRetainFailedProbability) {
  591. NoticeInfo("Delete dial parameters for %s", dialParams.ServerEntry.GetDiagnosticID())
  592. err := DeleteDialParameters(dialParams.ServerEntry.IpAddress, dialParams.NetworkID)
  593. if err != nil {
  594. NoticeWarning("DeleteDialParameters failed: %s", err)
  595. }
  596. }
  597. }
  598. func (dialParams *DialParameters) GetTLSVersionForMetrics() string {
  599. tlsVersion := dialParams.TLSVersion
  600. if dialParams.NoDefaultTLSSessionID {
  601. tlsVersion += "-no_def_id"
  602. }
  603. return tlsVersion
  604. }
  605. // ExchangedDialParameters represents the subset of DialParameters that is
  606. // shared in a client-to-client exchange of server connection info.
  607. //
  608. // The purpose of client-to-client exchange if for one user that can connect
  609. // to help another user that cannot connect by sharing their connected
  610. // configuration, including the server entry and dial parameters.
  611. //
  612. // There are two concerns regarding which dial parameter fields are safe to
  613. // exchange:
  614. //
  615. // - Unlike signed server entries, there's no independent trust anchor
  616. // that can certify that the exchange data is valid.
  617. //
  618. // - While users should only perform the exchange with trusted peers,
  619. // the user's trust in their peer may be misplaced.
  620. //
  621. // This presents the possibility of attack such as the peer sending dial
  622. // parameters that could be used to trace/monitor/flag the importer; or
  623. // sending dial parameters, including dial address and SNI, to cause the peer
  624. // to appear to connect to a banned service.
  625. //
  626. // To mitigate these risks, only a subset of dial parameters are exchanged.
  627. // When exchanged dial parameters and imported and used, all unexchanged
  628. // parameters are generated locally. At this time, only the tunnel protocol is
  629. // exchanged. We consider tunnel protocol selection one of the key connection
  630. // success factors.
  631. //
  632. // In addition, the exchange peers may not be on the same network with the
  633. // same blocking and circumvention characteristics, which is another reason
  634. // to limit exchanged dial parameter values to broadly applicable fields.
  635. //
  636. // Unlike the exchanged (and otherwise acquired) server entry,
  637. // ExchangedDialParameters does not use the ServerEntry_Fields_ representation
  638. // which allows older clients to receive and store new, unknown fields. Such a
  639. // facility is less useful in this case, since exchanged dial parameters and
  640. // used immediately and have a short lifespan.
  641. //
  642. // TODO: exchange more dial parameters, such as TLS profile, QUIC version, etc.
  643. type ExchangedDialParameters struct {
  644. TunnelProtocol string
  645. }
  646. // NewExchangedDialParameters creates a new ExchangedDialParameters from a
  647. // DialParameters, including only the exchanged values.
  648. // NewExchangedDialParameters assumes the input DialParameters has been
  649. // initialized and populated by MakeDialParameters.
  650. func NewExchangedDialParameters(dialParams *DialParameters) *ExchangedDialParameters {
  651. return &ExchangedDialParameters{
  652. TunnelProtocol: dialParams.TunnelProtocol,
  653. }
  654. }
  655. // Validate checks that the ExchangedDialParameters contains only valid values
  656. // and is compatible with the specified server entry.
  657. func (dialParams *ExchangedDialParameters) Validate(serverEntry *protocol.ServerEntry) error {
  658. if !common.Contains(protocol.SupportedTunnelProtocols, dialParams.TunnelProtocol) {
  659. return errors.Tracef("unknown tunnel protocol: %s", dialParams.TunnelProtocol)
  660. }
  661. if !serverEntry.SupportsProtocol(dialParams.TunnelProtocol) {
  662. return errors.Tracef("unsupported tunnel protocol: %s", dialParams.TunnelProtocol)
  663. }
  664. return nil
  665. }
  666. // MakeDialParameters creates a new, partially intitialized DialParameters
  667. // from the values in ExchangedDialParameters. The returned DialParameters
  668. // must not be used directly for dialing. It is intended to be stored, and
  669. // then later fully initialized by MakeDialParameters.
  670. func (dialParams *ExchangedDialParameters) MakeDialParameters(
  671. config *Config,
  672. p parameters.ClientParametersAccessor,
  673. serverEntry *protocol.ServerEntry) *DialParameters {
  674. return &DialParameters{
  675. IsExchanged: true,
  676. LastUsedTimestamp: time.Now(),
  677. LastUsedConfigStateHash: getConfigStateHash(config, p, serverEntry),
  678. TunnelProtocol: dialParams.TunnelProtocol,
  679. }
  680. }
  681. func getConfigStateHash(
  682. config *Config,
  683. p parameters.ClientParametersAccessor,
  684. serverEntry *protocol.ServerEntry) []byte {
  685. // The config state hash should reflect config, tactics, and server entry
  686. // settings that impact the dial parameters. The hash should change if any
  687. // of these input values change in a way that invalidates any stored dial
  688. // parameters.
  689. // MD5 hash is used solely as a data checksum and not for any security
  690. // purpose.
  691. hash := md5.New()
  692. // Add a hash of relevant config fields.
  693. // Limitation: the config hash may change even when tactics will override the
  694. // changed config field.
  695. hash.Write(config.dialParametersHash)
  696. // Add the active tactics tag.
  697. hash.Write([]byte(p.Tag()))
  698. // Add the server entry version and local timestamp, both of which should
  699. // change when the server entry contents change and/or a new local copy is
  700. // imported.
  701. // TODO: marshal entire server entry?
  702. var serverEntryConfigurationVersion [8]byte
  703. binary.BigEndian.PutUint64(
  704. serverEntryConfigurationVersion[:],
  705. uint64(serverEntry.ConfigurationVersion))
  706. hash.Write(serverEntryConfigurationVersion[:])
  707. hash.Write([]byte(serverEntry.LocalTimestamp))
  708. return hash.Sum(nil)
  709. }
  710. func selectFrontingParameters(serverEntry *protocol.ServerEntry) (string, string, error) {
  711. frontingDialHost := ""
  712. frontingHost := ""
  713. if len(serverEntry.MeekFrontingAddressesRegex) > 0 {
  714. // Generate a front address based on the regex.
  715. var err error
  716. frontingDialHost, err = regen.Generate(serverEntry.MeekFrontingAddressesRegex)
  717. if err != nil {
  718. return "", "", errors.Trace(err)
  719. }
  720. } else {
  721. // Randomly select, for this connection attempt, one front address for
  722. // fronting-capable servers.
  723. if len(serverEntry.MeekFrontingAddresses) == 0 {
  724. return "", "", errors.TraceNew("MeekFrontingAddresses is empty")
  725. }
  726. index := prng.Intn(len(serverEntry.MeekFrontingAddresses))
  727. frontingDialHost = serverEntry.MeekFrontingAddresses[index]
  728. }
  729. if len(serverEntry.MeekFrontingHosts) > 0 {
  730. index := prng.Intn(len(serverEntry.MeekFrontingHosts))
  731. frontingHost = serverEntry.MeekFrontingHosts[index]
  732. } else {
  733. // Backwards compatibility case
  734. frontingHost = serverEntry.MeekFrontingHost
  735. }
  736. return frontingDialHost, frontingHost, nil
  737. }
  738. func selectQUICVersion(
  739. isFronted bool,
  740. frontingProviderID string,
  741. p parameters.ClientParametersAccessor) string {
  742. limitQUICVersions := p.QUICVersions(parameters.LimitQUICVersions)
  743. var disableQUICVersions protocol.QUICVersions
  744. if isFronted {
  745. if frontingProviderID == "" {
  746. // Legacy server entry case
  747. disableQUICVersions = protocol.QUICVersions{protocol.QUIC_VERSION_IETF_DRAFT24}
  748. } else {
  749. disableQUICVersions = p.LabeledQUICVersions(
  750. parameters.DisableFrontingProviderQUICVersions, frontingProviderID)
  751. }
  752. }
  753. quicVersions := make([]string, 0)
  754. for _, quicVersion := range protocol.SupportedQUICVersions {
  755. if len(limitQUICVersions) > 0 &&
  756. !common.Contains(limitQUICVersions, quicVersion) {
  757. continue
  758. }
  759. if isFronted &&
  760. protocol.QUICVersionIsObfuscated(quicVersion) {
  761. continue
  762. }
  763. if common.Contains(disableQUICVersions, quicVersion) {
  764. continue
  765. }
  766. quicVersions = append(quicVersions, quicVersion)
  767. }
  768. if len(quicVersions) == 0 {
  769. return ""
  770. }
  771. choice := prng.Intn(len(quicVersions))
  772. return quicVersions[choice]
  773. }
  774. // selectUserAgentIfUnset selects a User-Agent header if one is not set.
  775. func selectUserAgentIfUnset(
  776. p parameters.ClientParametersAccessor, headers http.Header) (bool, string) {
  777. if _, ok := headers["User-Agent"]; !ok {
  778. userAgent := ""
  779. if p.WeightedCoinFlip(parameters.PickUserAgentProbability) {
  780. userAgent = values.GetUserAgent()
  781. }
  782. return true, userAgent
  783. }
  784. return false, ""
  785. }
  786. func makeDialCustomHeaders(
  787. config *Config,
  788. p parameters.ClientParametersAccessor) http.Header {
  789. dialCustomHeaders := make(http.Header)
  790. if config.CustomHeaders != nil {
  791. for k, v := range config.CustomHeaders {
  792. dialCustomHeaders[k] = make([]string, len(v))
  793. copy(dialCustomHeaders[k], v)
  794. }
  795. }
  796. additionalCustomHeaders := p.HTTPHeaders(parameters.AdditionalCustomHeaders)
  797. for k, v := range additionalCustomHeaders {
  798. dialCustomHeaders[k] = make([]string, len(v))
  799. copy(dialCustomHeaders[k], v)
  800. }
  801. return dialCustomHeaders
  802. }