dialParameters.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  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. DiagnosticID: serverEntry.GetDiagnosticID(),
  455. UpstreamProxyURL: config.UpstreamProxyURL,
  456. CustomHeaders: dialCustomHeaders,
  457. DeviceBinder: config.deviceBinder,
  458. DnsServerGetter: config.DnsServerGetter,
  459. IPv6Synthesizer: config.IPv6Synthesizer,
  460. TrustedCACertificatesFilename: config.TrustedCACertificatesFilename,
  461. FragmentorConfig: fragmentor.NewUpstreamConfig(p, dialParams.TunnelProtocol, dialParams.FragmentorSeed),
  462. }
  463. // Unconditionally initialize MeekResolvedIPAddress, so a valid string can
  464. // always be read.
  465. dialParams.MeekResolvedIPAddress.Store("")
  466. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) {
  467. dialParams.meekConfig = &MeekConfig{
  468. DiagnosticID: serverEntry.GetDiagnosticID(),
  469. ClientParameters: config.clientParameters,
  470. DialAddress: dialParams.MeekDialAddress,
  471. UseQUIC: protocol.TunnelProtocolUsesFrontedMeekQUIC(dialParams.TunnelProtocol),
  472. QUICVersion: dialParams.QUICVersion,
  473. UseHTTPS: protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol),
  474. TLSProfile: dialParams.TLSProfile,
  475. RandomizedTLSProfileSeed: dialParams.RandomizedTLSProfileSeed,
  476. UseObfuscatedSessionTickets: dialParams.TunnelProtocol == protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET,
  477. SNIServerName: dialParams.MeekSNIServerName,
  478. HostHeader: dialParams.MeekHostHeader,
  479. TransformedHostName: dialParams.MeekTransformedHostName,
  480. ClientTunnelProtocol: dialParams.TunnelProtocol,
  481. MeekCookieEncryptionPublicKey: serverEntry.MeekCookieEncryptionPublicKey,
  482. MeekObfuscatedKey: serverEntry.MeekObfuscatedKey,
  483. MeekObfuscatorPaddingSeed: dialParams.MeekObfuscatorPaddingSeed,
  484. }
  485. // Use an asynchronous callback to record the resolved IP address when
  486. // dialing a domain name. Note that DialMeek doesn't immediately
  487. // establish any HTTP connections, so the resolved IP address won't be
  488. // reported in all cases until after SSH traffic is relayed or a
  489. // endpoint request is made over the meek connection.
  490. dialParams.dialConfig.ResolvedIPCallback = func(IPAddress string) {
  491. dialParams.MeekResolvedIPAddress.Store(IPAddress)
  492. }
  493. if isTactics {
  494. dialParams.meekConfig.RoundTripperOnly = true
  495. }
  496. }
  497. return dialParams, nil
  498. }
  499. func (dialParams *DialParameters) GetDialConfig() *DialConfig {
  500. return dialParams.dialConfig
  501. }
  502. func (dialParams *DialParameters) GetMeekConfig() *MeekConfig {
  503. return dialParams.meekConfig
  504. }
  505. func (dialParams *DialParameters) Succeeded() {
  506. // When TTL is 0, don't store dial parameters.
  507. if dialParams.LastUsedTimestamp.IsZero() {
  508. return
  509. }
  510. NoticeInfo("Set dial parameters for %s", dialParams.ServerEntry.GetDiagnosticID())
  511. err := SetDialParameters(dialParams.ServerEntry.IpAddress, dialParams.NetworkID, dialParams)
  512. if err != nil {
  513. NoticeAlert("SetDialParameters failed: %s", err)
  514. }
  515. }
  516. func (dialParams *DialParameters) Failed(config *Config) {
  517. // When a tunnel fails, and the dial is a replay, clear the stored dial
  518. // parameters which are now presumed to be blocked, impaired or otherwise
  519. // no longer effective.
  520. //
  521. // It may be the case that a dial is not using stored dial parameters
  522. // (!IsReplay), and in this case we retain those dial parameters since they
  523. // were not exercised and may still be effective.
  524. //
  525. // Failed tunnel dial parameters may be retained with a configurable
  526. // probability; this is intended to help mitigate false positive failures due
  527. // to, e.g., temporary network disruptions or server load limiting.
  528. if dialParams.IsReplay &&
  529. !config.GetClientParametersSnapshot().WeightedCoinFlip(
  530. parameters.ReplayRetainFailedProbability) {
  531. NoticeInfo("Delete dial parameters for %s", dialParams.ServerEntry.GetDiagnosticID())
  532. err := DeleteDialParameters(dialParams.ServerEntry.IpAddress, dialParams.NetworkID)
  533. if err != nil {
  534. NoticeAlert("DeleteDialParameters failed: %s", err)
  535. }
  536. }
  537. }
  538. // ExchangedDialParameters represents the subset of DialParameters that is
  539. // shared in a client-to-client exchange of server connection info.
  540. //
  541. // The purpose of client-to-client exchange if for one user that can connect
  542. // to help another user that cannot connect by sharing their connected
  543. // configuration, including the server entry and dial parameters.
  544. //
  545. // There are two concerns regarding which dial parameter fields are safe to
  546. // exchange:
  547. //
  548. // - Unlike signed server entries, there's no independent trust anchor
  549. // that can certify that the exchange data is valid.
  550. //
  551. // - While users should only perform the exchange with trusted peers,
  552. // the user's trust in their peer may be misplaced.
  553. //
  554. // This presents the possibility of attack such as the peer sending dial
  555. // parameters that could be used to trace/monitor/flag the importer; or
  556. // sending dial parameters, including dial address and SNI, to cause the peer
  557. // to appear to connect to a banned service.
  558. //
  559. // To mitigate these risks, only a subset of dial parameters are exchanged.
  560. // When exchanged dial parameters and imported and used, all unexchanged
  561. // parameters are generated locally. At this time, only the tunnel protocol is
  562. // exchanged. We consider tunnel protocol selection one of the key connection
  563. // success factors.
  564. //
  565. // In addition, the exchange peers may not be on the same network with the
  566. // same blocking and circumvention characteristics, which is another reason
  567. // to limit exchanged dial parameter values to broadly applicable fields.
  568. //
  569. // Unlike the exchanged (and otherwise acquired) server entry,
  570. // ExchangedDialParameters does not use the ServerEntry_Fields_ representation
  571. // which allows older clients to receive and store new, unknown fields. Such a
  572. // facility is less useful in this case, since exchanged dial parameters and
  573. // used immediately and have a short lifespan.
  574. //
  575. // TODO: exchange more dial parameters, such as TLS profile, QUIC version, etc.
  576. type ExchangedDialParameters struct {
  577. TunnelProtocol string
  578. }
  579. // NewExchangedDialParameters creates a new ExchangedDialParameters from a
  580. // DialParameters, including only the exchanged values.
  581. // NewExchangedDialParameters assumes the input DialParameters has been
  582. // initialized and populated by MakeDialParameters.
  583. func NewExchangedDialParameters(dialParams *DialParameters) *ExchangedDialParameters {
  584. return &ExchangedDialParameters{
  585. TunnelProtocol: dialParams.TunnelProtocol,
  586. }
  587. }
  588. // Validate checks that the ExchangedDialParameters contains only valid values
  589. // and is compatible with the specified server entry.
  590. func (dialParams *ExchangedDialParameters) Validate(serverEntry *protocol.ServerEntry) error {
  591. if !common.Contains(protocol.SupportedTunnelProtocols, dialParams.TunnelProtocol) {
  592. return common.ContextError(fmt.Errorf("unknown tunnel protocol: %s", dialParams.TunnelProtocol))
  593. }
  594. if !serverEntry.SupportsProtocol(dialParams.TunnelProtocol) {
  595. return common.ContextError(fmt.Errorf("unsupported tunnel protocol: %s", dialParams.TunnelProtocol))
  596. }
  597. return nil
  598. }
  599. // MakeDialParameters creates a new, partially intitialized DialParameters
  600. // from the values in ExchangedDialParameters. The returned DialParameters
  601. // must not be used directly for dialing. It is intended to be stored, and
  602. // then later fully initialized by MakeDialParameters.
  603. func (dialParams *ExchangedDialParameters) MakeDialParameters(
  604. config *Config,
  605. p *parameters.ClientParametersSnapshot,
  606. serverEntry *protocol.ServerEntry) *DialParameters {
  607. return &DialParameters{
  608. IsExchanged: true,
  609. LastUsedTimestamp: time.Now(),
  610. LastUsedConfigStateHash: getConfigStateHash(config, p, serverEntry),
  611. TunnelProtocol: dialParams.TunnelProtocol,
  612. }
  613. }
  614. func getConfigStateHash(
  615. config *Config,
  616. p *parameters.ClientParametersSnapshot,
  617. serverEntry *protocol.ServerEntry) []byte {
  618. // The config state hash should reflect config, tactics, and server entry
  619. // settings that impact the dial parameters. The hash should change if any
  620. // of these input values change in a way that invalidates any stored dial
  621. // parameters.
  622. // MD5 hash is used solely as a data checksum and not for any security
  623. // purpose.
  624. hash := md5.New()
  625. // Add a hash of relevant config fields.
  626. // Limitation: the config hash may change even when tactics will override the
  627. // changed config field.
  628. hash.Write(config.dialParametersHash)
  629. // Add the active tactics tag.
  630. hash.Write([]byte(p.Tag()))
  631. // Add the server entry version and local timestamp, both of which should
  632. // change when the server entry contents change and/or a new local copy is
  633. // imported.
  634. // TODO: marshal entire server entry?
  635. var serverEntryConfigurationVersion [8]byte
  636. binary.BigEndian.PutUint64(
  637. serverEntryConfigurationVersion[:],
  638. uint64(serverEntry.ConfigurationVersion))
  639. hash.Write(serverEntryConfigurationVersion[:])
  640. hash.Write([]byte(serverEntry.LocalTimestamp))
  641. return hash.Sum(nil)
  642. }
  643. func selectFrontingParameters(serverEntry *protocol.ServerEntry) (string, string, error) {
  644. frontingDialHost := ""
  645. frontingHost := ""
  646. if len(serverEntry.MeekFrontingAddressesRegex) > 0 {
  647. // Generate a front address based on the regex.
  648. var err error
  649. frontingDialHost, err = regen.Generate(serverEntry.MeekFrontingAddressesRegex)
  650. if err != nil {
  651. return "", "", common.ContextError(err)
  652. }
  653. } else {
  654. // Randomly select, for this connection attempt, one front address for
  655. // fronting-capable servers.
  656. if len(serverEntry.MeekFrontingAddresses) == 0 {
  657. return "", "", common.ContextError(errors.New("MeekFrontingAddresses is empty"))
  658. }
  659. index := prng.Intn(len(serverEntry.MeekFrontingAddresses))
  660. frontingDialHost = serverEntry.MeekFrontingAddresses[index]
  661. }
  662. if len(serverEntry.MeekFrontingHosts) > 0 {
  663. index := prng.Intn(len(serverEntry.MeekFrontingHosts))
  664. frontingHost = serverEntry.MeekFrontingHosts[index]
  665. } else {
  666. // Backwards compatibility case
  667. frontingHost = serverEntry.MeekFrontingHost
  668. }
  669. return frontingDialHost, frontingHost, nil
  670. }
  671. func selectQUICVersion(allowObfuscatedQUIC bool, p *parameters.ClientParametersSnapshot) string {
  672. limitQUICVersions := p.QUICVersions(parameters.LimitQUICVersions)
  673. quicVersions := make([]string, 0)
  674. for _, quicVersion := range protocol.SupportedQUICVersions {
  675. if len(limitQUICVersions) > 0 &&
  676. !common.Contains(limitQUICVersions, quicVersion) {
  677. continue
  678. }
  679. if !allowObfuscatedQUIC &&
  680. protocol.QUICVersionIsObfuscated(quicVersion) {
  681. continue
  682. }
  683. quicVersions = append(quicVersions, quicVersion)
  684. }
  685. if len(quicVersions) == 0 {
  686. return ""
  687. }
  688. choice := prng.Intn(len(quicVersions))
  689. return quicVersions[choice]
  690. }
  691. func makeDialCustomHeaders(
  692. config *Config,
  693. p *parameters.ClientParametersSnapshot) http.Header {
  694. dialCustomHeaders := make(http.Header)
  695. if config.CustomHeaders != nil {
  696. for k, v := range config.CustomHeaders {
  697. dialCustomHeaders[k] = make([]string, len(v))
  698. copy(dialCustomHeaders[k], v)
  699. }
  700. }
  701. additionalCustomHeaders := p.HTTPHeaders(parameters.AdditionalCustomHeaders)
  702. if additionalCustomHeaders != nil {
  703. for k, v := range additionalCustomHeaders {
  704. dialCustomHeaders[k] = make([]string, len(v))
  705. copy(dialCustomHeaders[k], v)
  706. }
  707. }
  708. return dialCustomHeaders
  709. }