dialParameters.go 30 KB

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