dialParameters.go 32 KB

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