dialParameters.go 22 KB

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