dialParameters.go 32 KB

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