dialParameters.go 22 KB

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