dialParameters.go 31 KB

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