dialParameters.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  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. regen "github.com/zach-klippenstein/goregen"
  37. )
  38. // DialParameters represents a selected protocol and all the related selected
  39. // protocol attributes, many chosen at random, for a tunnel dial attempt.
  40. //
  41. // DialParameters is used:
  42. // - to configure dialers
  43. // - as a persistent record to store successful dial parameters for replay
  44. // - to report dial stats in notices and Psiphon API calls.
  45. //
  46. // MeekResolvedIPAddress is set asynchronously, as it is not known until the
  47. // dial process has begun. The atomic.Value will contain a string, initialized
  48. // to "", and set to the resolved IP address once that part of the dial
  49. // process has completed.
  50. //
  51. // DialParameters is not safe for concurrent use.
  52. type DialParameters struct {
  53. ServerEntry *protocol.ServerEntry `json:"-"`
  54. NetworkID string `json:"-"`
  55. IsReplay bool `json:"-"`
  56. LastUsedTimestamp time.Time
  57. LastUsedConfigStateHash []byte
  58. TunnelProtocol string
  59. DirectDialAddress string
  60. DialPortNumber string
  61. UpstreamProxyType string `json:"-"`
  62. UpstreamProxyCustomHeaderNames []string `json:"-"`
  63. SelectedSSHClientVersion bool
  64. SSHClientVersion string
  65. SSHKEXSeed *prng.Seed
  66. ObfuscatorPaddingSeed *prng.Seed
  67. FragmentorSeed *prng.Seed
  68. MeekFrontingDialAddress string
  69. MeekFrontingHost string
  70. MeekDialAddress string
  71. MeekTransformedHostName bool
  72. MeekSNIServerName string
  73. MeekHostHeader string
  74. MeekObfuscatorPaddingSeed *prng.Seed
  75. MeekResolvedIPAddress atomic.Value `json:"-"`
  76. SelectedUserAgent bool
  77. UserAgent string
  78. SelectedTLSProfile bool
  79. TLSProfile string
  80. RandomizedTLSProfileSeed *prng.Seed
  81. QUICVersion string
  82. QUICDialSNIAddress string
  83. ObfuscatedQUICPaddingSeed *prng.Seed
  84. LivenessTestSeed *prng.Seed
  85. APIRequestPaddingSeed *prng.Seed
  86. DialConnMetrics common.MetricsSource `json:"-"`
  87. ObfuscatedSSHConnMetrics common.MetricsSource `json:"-"`
  88. dialConfig *DialConfig `json:"-"`
  89. meekConfig *MeekConfig `json:"-"`
  90. }
  91. // MakeDialParameters creates a new DialParameters for the candidate server
  92. // entry, including selecting a protocol and all the various protocol
  93. // attributes. The input selectProtocol is used to comply with any active
  94. // protocol selection constraints.
  95. //
  96. // When stored dial parameters are available and may be used,
  97. // MakeDialParameters may replay previous dial parameters in an effort to
  98. // leverage "known working" values instead of always chosing at random from a
  99. // large space.
  100. //
  101. // MakeDialParameters will return nil/nil in cases where the candidate server
  102. // entry should be skipped.
  103. //
  104. // To support replay, the caller must call DialParameters.Succeeded when a
  105. // successful tunnel is established with the returned DialParameters; and must
  106. // call DialParameters.Failed when a tunnel dial or activation fails, except
  107. // when establishment is cancelled.
  108. func MakeDialParameters(
  109. config *Config,
  110. canReplay func(serverEntry *protocol.ServerEntry, replayProtocol string) bool,
  111. selectProtocol func(serverEntry *protocol.ServerEntry) (string, bool),
  112. serverEntry *protocol.ServerEntry,
  113. isTactics bool) (*DialParameters, error) {
  114. networkID := config.GetNetworkID()
  115. p := config.clientParameters.Get()
  116. ttl := p.Duration(parameters.ReplayDialParametersTTL)
  117. replaySSH := p.Bool(parameters.ReplaySSH)
  118. replayObfuscatorPadding := p.Bool(parameters.ReplayObfuscatorPadding)
  119. replayFragmentor := p.Bool(parameters.ReplayFragmentor)
  120. replayTLSProfile := p.Bool(parameters.ReplayTLSProfile)
  121. replayRandomizedTLSProfile := p.Bool(parameters.ReplayRandomizedTLSProfile)
  122. replayFronting := p.Bool(parameters.ReplayFronting)
  123. replayHostname := p.Bool(parameters.ReplayHostname)
  124. replayQUICVersion := p.Bool(parameters.ReplayQUICVersion)
  125. replayObfuscatedQUIC := p.Bool(parameters.ReplayObfuscatedQUIC)
  126. replayLivenessTest := p.Bool(parameters.ReplayLivenessTest)
  127. replayUserAgent := p.Bool(parameters.ReplayUserAgent)
  128. replayAPIRequestPadding := p.Bool(parameters.ReplayAPIRequestPadding)
  129. // Check for existing dial parameters for this server/network ID.
  130. dialParams, err := GetDialParameters(serverEntry.IpAddress, networkID)
  131. if err != nil {
  132. NoticeAlert("GetDialParameters failed: %s", err)
  133. dialParams = nil
  134. // Proceed, without existing dial parameters.
  135. }
  136. // Check if replay is permitted:
  137. // - TTL must be > 0 and existing dial parameters must not have expired
  138. // as indicated by LastUsedTimestamp + TTL.
  139. // - Config/tactics/server entry values must be unchanged from when
  140. // previous dial parameters were established.
  141. // - The protocol selection constraints must permit replay, as indicated
  142. // by canReplay.
  143. //
  144. // When existing dial parameters don't meet these conditions, dialParams
  145. // is reset to nil and new dial parameters will be generated.
  146. var currentTimestamp time.Time
  147. var configStateHash []byte
  148. // When TTL is 0, replay is disabled; the timestamp remains 0 and the
  149. // output DialParameters will not be stored by Success.
  150. if ttl > 0 {
  151. currentTimestamp = time.Now()
  152. configStateHash = getConfigStateHash(config, p, serverEntry)
  153. }
  154. if dialParams != nil &&
  155. (ttl <= 0 ||
  156. dialParams.LastUsedTimestamp.Before(currentTimestamp.Add(-ttl)) ||
  157. bytes.Compare(dialParams.LastUsedConfigStateHash, configStateHash) != 0) {
  158. // In these cases, existing dial parameters are expired or no longer
  159. // match the config state and so are cleared to avoid rechecking them.
  160. err = DeleteDialParameters(serverEntry.IpAddress, networkID)
  161. if err != nil {
  162. NoticeAlert("DeleteDialParameters failed: %s", err)
  163. }
  164. dialParams = nil
  165. }
  166. if dialParams != nil {
  167. if !canReplay(serverEntry, dialParams.TunnelProtocol) {
  168. // In this ephemeral case, existing dial parameters may still be
  169. // valid and used in future establishment phases, and so are
  170. // retained.
  171. dialParams = nil
  172. }
  173. }
  174. isReplay := (dialParams != nil)
  175. if !isReplay {
  176. dialParams = &DialParameters{}
  177. }
  178. dialParams.ServerEntry = serverEntry
  179. dialParams.NetworkID = networkID
  180. dialParams.IsReplay = isReplay
  181. // Even when replaying, LastUsedTimestamp is updated to extend the TTL of
  182. // replayed dial parameters which will be updated in the datastore upon
  183. // success.
  184. dialParams.LastUsedTimestamp = currentTimestamp
  185. dialParams.LastUsedConfigStateHash = configStateHash
  186. // Initialize dial parameters.
  187. //
  188. // When not replaying, all required parameters are initialized. When
  189. // replaying, existing parameters are retaing, subject to the replay-X
  190. // tactics flags.
  191. if !isReplay {
  192. // TODO: should there be a pre-check of selectProtocol before incurring
  193. // overhead of unmarshaling dial parameters? In may be that a server entry
  194. // is fully incapable of satisfying the current protocol selection
  195. // constraints.
  196. selectedProtocol, ok := selectProtocol(serverEntry)
  197. if !ok {
  198. return nil, nil
  199. }
  200. dialParams.TunnelProtocol = selectedProtocol
  201. }
  202. if !isReplay || !replaySSH {
  203. dialParams.SelectedSSHClientVersion = true
  204. dialParams.SSHClientVersion = pickSSHClientVersion()
  205. dialParams.SSHKEXSeed, err = prng.NewSeed()
  206. if err != nil {
  207. return nil, common.ContextError(err)
  208. }
  209. }
  210. if !isReplay || !replayObfuscatorPadding {
  211. dialParams.ObfuscatorPaddingSeed, err = prng.NewSeed()
  212. if err != nil {
  213. return nil, common.ContextError(err)
  214. }
  215. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) {
  216. dialParams.MeekObfuscatorPaddingSeed, err = prng.NewSeed()
  217. if err != nil {
  218. return nil, common.ContextError(err)
  219. }
  220. }
  221. }
  222. if !isReplay || !replayFragmentor {
  223. dialParams.FragmentorSeed, err = prng.NewSeed()
  224. if err != nil {
  225. return nil, common.ContextError(err)
  226. }
  227. }
  228. if (!isReplay || !replayTLSProfile) &&
  229. protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol) {
  230. dialParams.TLSProfile = SelectTLSProfile(p)
  231. }
  232. if (!isReplay || !replayRandomizedTLSProfile) &&
  233. protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol) &&
  234. protocol.TLSProfileIsRandomized(dialParams.TLSProfile) {
  235. dialParams.RandomizedTLSProfileSeed, err = prng.NewSeed()
  236. if err != nil {
  237. return nil, common.ContextError(err)
  238. }
  239. }
  240. if (!isReplay || !replayFronting) &&
  241. protocol.TunnelProtocolUsesFrontedMeek(dialParams.TunnelProtocol) {
  242. dialParams.MeekFrontingDialAddress, dialParams.MeekFrontingHost, err =
  243. selectFrontingParameters(serverEntry)
  244. if err != nil {
  245. return nil, common.ContextError(err)
  246. }
  247. }
  248. if !isReplay || !replayHostname {
  249. if protocol.TunnelProtocolUsesQUIC(dialParams.TunnelProtocol) {
  250. dialParams.QUICDialSNIAddress = fmt.Sprintf("%s:%d", common.GenerateHostName(), serverEntry.SshObfuscatedQUICPort)
  251. } else if protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol) {
  252. dialParams.MeekSNIServerName = ""
  253. if p.WeightedCoinFlip(parameters.TransformHostNameProbability) {
  254. dialParams.MeekSNIServerName = common.GenerateHostName()
  255. dialParams.MeekTransformedHostName = true
  256. }
  257. } else if protocol.TunnelProtocolUsesMeekHTTP(dialParams.TunnelProtocol) {
  258. dialParams.MeekHostHeader = ""
  259. hostname := serverEntry.IpAddress
  260. if p.WeightedCoinFlip(parameters.TransformHostNameProbability) {
  261. hostname = common.GenerateHostName()
  262. dialParams.MeekTransformedHostName = true
  263. }
  264. if serverEntry.MeekServerPort == 80 {
  265. dialParams.MeekHostHeader = hostname
  266. } else {
  267. dialParams.MeekHostHeader = fmt.Sprintf("%s:%d", hostname, serverEntry.MeekServerPort)
  268. }
  269. }
  270. }
  271. if (!isReplay || !replayQUICVersion) &&
  272. protocol.TunnelProtocolUsesQUIC(dialParams.TunnelProtocol) {
  273. dialParams.QUICVersion = selectQUICVersion(p)
  274. }
  275. if (!isReplay || !replayObfuscatedQUIC) &&
  276. protocol.QUICVersionIsObfuscated(dialParams.QUICVersion) {
  277. dialParams.ObfuscatedQUICPaddingSeed, err = prng.NewSeed()
  278. if err != nil {
  279. return nil, common.ContextError(err)
  280. }
  281. }
  282. if !isReplay || !replayLivenessTest {
  283. // TODO: initialize only when LivenessTestMaxUp/DownstreamBytes > 0?
  284. dialParams.LivenessTestSeed, err = prng.NewSeed()
  285. if err != nil {
  286. return nil, common.ContextError(err)
  287. }
  288. }
  289. if !isReplay || !replayAPIRequestPadding {
  290. dialParams.APIRequestPaddingSeed, err = prng.NewSeed()
  291. if err != nil {
  292. return nil, common.ContextError(err)
  293. }
  294. }
  295. // Set dial address fields. This portion of configuration is
  296. // deterministic, given the parameters established or replayed so far.
  297. switch dialParams.TunnelProtocol {
  298. case protocol.TUNNEL_PROTOCOL_SSH:
  299. dialParams.DirectDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.SshPort)
  300. case protocol.TUNNEL_PROTOCOL_OBFUSCATED_SSH:
  301. dialParams.DirectDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.SshObfuscatedPort)
  302. case protocol.TUNNEL_PROTOCOL_TAPDANCE_OBFUSCATED_SSH:
  303. dialParams.DirectDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.SshObfuscatedTapdancePort)
  304. case protocol.TUNNEL_PROTOCOL_QUIC_OBFUSCATED_SSH:
  305. dialParams.DirectDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.SshObfuscatedQUICPort)
  306. case protocol.TUNNEL_PROTOCOL_MARIONETTE_OBFUSCATED_SSH:
  307. // Note: port comes from marionnete "format"
  308. dialParams.DirectDialAddress = serverEntry.IpAddress
  309. case protocol.TUNNEL_PROTOCOL_FRONTED_MEEK:
  310. dialParams.MeekDialAddress = fmt.Sprintf("%s:443", dialParams.MeekFrontingDialAddress)
  311. dialParams.MeekHostHeader = dialParams.MeekFrontingHost
  312. if serverEntry.MeekFrontingDisableSNI {
  313. dialParams.MeekSNIServerName = ""
  314. } else if !dialParams.MeekTransformedHostName {
  315. dialParams.MeekSNIServerName = dialParams.MeekFrontingDialAddress
  316. }
  317. case protocol.TUNNEL_PROTOCOL_FRONTED_MEEK_HTTP:
  318. dialParams.MeekDialAddress = fmt.Sprintf("%s:80", dialParams.MeekFrontingDialAddress)
  319. dialParams.MeekHostHeader = dialParams.MeekFrontingHost
  320. case protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK:
  321. dialParams.MeekDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.MeekServerPort)
  322. if !dialParams.MeekTransformedHostName {
  323. if serverEntry.MeekServerPort == 80 {
  324. dialParams.MeekHostHeader = serverEntry.IpAddress
  325. } else {
  326. dialParams.MeekHostHeader = dialParams.MeekDialAddress
  327. }
  328. }
  329. case protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  330. protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET:
  331. dialParams.MeekDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.MeekServerPort)
  332. if !dialParams.MeekTransformedHostName {
  333. // Note: IP address in SNI field will be omitted.
  334. dialParams.MeekSNIServerName = serverEntry.IpAddress
  335. }
  336. if serverEntry.MeekServerPort == 443 {
  337. dialParams.MeekHostHeader = serverEntry.IpAddress
  338. } else {
  339. dialParams.MeekHostHeader = dialParams.MeekDialAddress
  340. }
  341. default:
  342. return nil, common.ContextError(
  343. fmt.Errorf("unknown tunnel protocol: %s", dialParams.TunnelProtocol))
  344. }
  345. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) {
  346. host, port, _ := net.SplitHostPort(dialParams.MeekDialAddress)
  347. if p.Bool(parameters.MeekDialDomainsOnly) {
  348. if net.ParseIP(host) != nil {
  349. // No error, as this is a "not supported" case.
  350. return nil, nil
  351. }
  352. }
  353. dialParams.DialPortNumber = port
  354. // The underlying TLS will automatically disable SNI for IP address server name
  355. // values; we have this explicit check here so we record the correct value for stats.
  356. if net.ParseIP(dialParams.MeekSNIServerName) != nil {
  357. dialParams.MeekSNIServerName = ""
  358. }
  359. } else {
  360. _, dialParams.DialPortNumber, _ = net.SplitHostPort(dialParams.DirectDialAddress)
  361. }
  362. // Initialize/replay User-Agent header for HTTP upstream proxy and meek protocols.
  363. if config.UseUpstreamProxy() {
  364. // Note: UpstreamProxyURL will be validated in the dial
  365. proxyURL, err := url.Parse(config.UpstreamProxyURL)
  366. if err == nil {
  367. dialParams.UpstreamProxyType = proxyURL.Scheme
  368. }
  369. }
  370. dialCustomHeaders := makeDialCustomHeaders(config, p)
  371. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) || dialParams.UpstreamProxyType == "http" {
  372. if !isReplay || !replayUserAgent {
  373. dialParams.SelectedUserAgent, dialParams.UserAgent = PickUserAgentIfUnset(p, dialCustomHeaders)
  374. }
  375. if dialParams.SelectedUserAgent {
  376. dialCustomHeaders.Set("User-Agent", dialParams.UserAgent)
  377. }
  378. }
  379. // UpstreamProxyCustomHeaderNames is a reported metric. Just the names and
  380. // not the values are reported, in case the values are identifying.
  381. if len(config.CustomHeaders) > 0 {
  382. dialParams.UpstreamProxyCustomHeaderNames = make([]string, 0)
  383. for name := range dialCustomHeaders {
  384. if name == "User-Agent" && dialParams.SelectedUserAgent {
  385. continue
  386. }
  387. dialParams.UpstreamProxyCustomHeaderNames = append(dialParams.UpstreamProxyCustomHeaderNames, name)
  388. }
  389. }
  390. // Initialize Dial/MeekConfigs to be passed to the corresponding dialers.
  391. dialParams.dialConfig = &DialConfig{
  392. UpstreamProxyURL: config.UpstreamProxyURL,
  393. CustomHeaders: dialCustomHeaders,
  394. DeviceBinder: config.deviceBinder,
  395. DnsServerGetter: config.DnsServerGetter,
  396. IPv6Synthesizer: config.IPv6Synthesizer,
  397. TrustedCACertificatesFilename: config.TrustedCACertificatesFilename,
  398. FragmentorConfig: fragmentor.NewUpstreamConfig(p, dialParams.TunnelProtocol, dialParams.FragmentorSeed),
  399. }
  400. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) {
  401. dialParams.meekConfig = &MeekConfig{
  402. ClientParameters: config.clientParameters,
  403. DialAddress: dialParams.MeekDialAddress,
  404. UseHTTPS: protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol),
  405. TLSProfile: dialParams.TLSProfile,
  406. RandomizedTLSProfileSeed: dialParams.RandomizedTLSProfileSeed,
  407. UseObfuscatedSessionTickets: dialParams.TunnelProtocol == protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET,
  408. SNIServerName: dialParams.MeekSNIServerName,
  409. HostHeader: dialParams.MeekHostHeader,
  410. TransformedHostName: dialParams.MeekTransformedHostName,
  411. ClientTunnelProtocol: dialParams.TunnelProtocol,
  412. MeekCookieEncryptionPublicKey: serverEntry.MeekCookieEncryptionPublicKey,
  413. MeekObfuscatedKey: serverEntry.MeekObfuscatedKey,
  414. MeekObfuscatorPaddingSeed: dialParams.MeekObfuscatorPaddingSeed,
  415. }
  416. if isTactics {
  417. dialParams.meekConfig.RoundTripperOnly = true
  418. }
  419. }
  420. // Initialize MeekResolvedIPAddress, so a valid string can always be read.
  421. dialParams.MeekResolvedIPAddress.Store("")
  422. return dialParams, nil
  423. }
  424. func (dialParams *DialParameters) GetDialConfig() *DialConfig {
  425. return dialParams.dialConfig
  426. }
  427. func (dialParams *DialParameters) GetMeekConfig() *MeekConfig {
  428. return dialParams.meekConfig
  429. }
  430. func (dialParams *DialParameters) Succeeded() {
  431. // When TTL is 0, don't store dial parameters.
  432. if dialParams.LastUsedTimestamp.IsZero() {
  433. return
  434. }
  435. NoticeInfo("Set dial parameters for %s", dialParams.ServerEntry.IpAddress)
  436. err := SetDialParameters(dialParams.ServerEntry.IpAddress, dialParams.NetworkID, dialParams)
  437. if err != nil {
  438. NoticeAlert("SetDialParameters failed: %s", err)
  439. }
  440. }
  441. func (dialParams *DialParameters) Failed() {
  442. // When a tunnel fails, and the dial is a replay, clear the stored dial
  443. // parameters which are now presumed to be blocked, impaired or otherwise
  444. // no longer effective.
  445. //
  446. // It may be the case that a dial is not using stored dial parameters, and
  447. // in this case we retain those dial parameters since they were not
  448. // exercised and may still be efective.
  449. if dialParams.IsReplay {
  450. NoticeInfo("Delete dial parameters for %s", dialParams.ServerEntry.IpAddress)
  451. err := DeleteDialParameters(dialParams.ServerEntry.IpAddress, dialParams.NetworkID)
  452. if err != nil {
  453. NoticeAlert("DeleteDialParameters failed: %s", err)
  454. }
  455. }
  456. }
  457. func getConfigStateHash(
  458. config *Config,
  459. p *parameters.ClientParametersSnapshot,
  460. serverEntry *protocol.ServerEntry) []byte {
  461. // The config state hash should reflect config, tactics, and server entry
  462. // settings that impact the dial parameters. The hash should change if any
  463. // of these input values change in a way that invalidates any stored dial
  464. // parameters.
  465. // MD5 hash is used solely as a data checksum and not for any security purpose.
  466. hash := md5.New()
  467. hash.Write([]byte(p.Tag()))
  468. // TODO: marshal entire server entry?
  469. var serverEntryConfigurationVersion [8]byte
  470. binary.BigEndian.PutUint64(
  471. serverEntryConfigurationVersion[:],
  472. uint64(serverEntry.ConfigurationVersion))
  473. hash.Write(serverEntryConfigurationVersion[:])
  474. hash.Write([]byte(serverEntry.LocalTimestamp))
  475. // TODO: add config.CustomHeaders, which could impact User-Agent header?
  476. hash.Write([]byte(config.UpstreamProxyURL))
  477. return hash.Sum(nil)
  478. }
  479. func selectFrontingParameters(serverEntry *protocol.ServerEntry) (string, string, error) {
  480. frontingDialHost := ""
  481. frontingHost := ""
  482. if len(serverEntry.MeekFrontingAddressesRegex) > 0 {
  483. // Generate a front address based on the regex.
  484. var err error
  485. frontingDialHost, err = regen.Generate(serverEntry.MeekFrontingAddressesRegex)
  486. if err != nil {
  487. return "", "", common.ContextError(err)
  488. }
  489. } else {
  490. // Randomly select, for this connection attempt, one front address for
  491. // fronting-capable servers.
  492. if len(serverEntry.MeekFrontingAddresses) == 0 {
  493. return "", "", common.ContextError(errors.New("MeekFrontingAddresses is empty"))
  494. }
  495. index := prng.Intn(len(serverEntry.MeekFrontingAddresses))
  496. frontingDialHost = serverEntry.MeekFrontingAddresses[index]
  497. }
  498. if len(serverEntry.MeekFrontingHosts) > 0 {
  499. index := prng.Intn(len(serverEntry.MeekFrontingHosts))
  500. frontingHost = serverEntry.MeekFrontingHosts[index]
  501. } else {
  502. // Backwards compatibility case
  503. frontingHost = serverEntry.MeekFrontingHost
  504. }
  505. return frontingDialHost, frontingHost, nil
  506. }
  507. func selectQUICVersion(p *parameters.ClientParametersSnapshot) string {
  508. limitQUICVersions := p.QUICVersions(parameters.LimitQUICVersions)
  509. quicVersions := make([]string, 0)
  510. for _, quicVersion := range protocol.SupportedQUICVersions {
  511. if len(limitQUICVersions) > 0 &&
  512. !common.Contains(limitQUICVersions, quicVersion) {
  513. continue
  514. }
  515. quicVersions = append(quicVersions, quicVersion)
  516. }
  517. if len(quicVersions) == 0 {
  518. return ""
  519. }
  520. choice := prng.Intn(len(quicVersions))
  521. return quicVersions[choice]
  522. }
  523. func makeDialCustomHeaders(
  524. config *Config,
  525. p *parameters.ClientParametersSnapshot) http.Header {
  526. dialCustomHeaders := make(http.Header)
  527. if config.CustomHeaders != nil {
  528. for k, v := range config.CustomHeaders {
  529. dialCustomHeaders[k] = make([]string, len(v))
  530. copy(dialCustomHeaders[k], v)
  531. }
  532. }
  533. additionalCustomHeaders := p.HTTPHeaders(parameters.AdditionalCustomHeaders)
  534. if additionalCustomHeaders != nil {
  535. for k, v := range additionalCustomHeaders {
  536. dialCustomHeaders[k] = make([]string, len(v))
  537. copy(dialCustomHeaders[k], v)
  538. }
  539. }
  540. return dialCustomHeaders
  541. }