dialParameters.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  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.SelectedTLSProfile = true
  235. dialParams.TLSProfile = SelectTLSProfile(p)
  236. }
  237. if (!isReplay || !replayRandomizedTLSProfile) &&
  238. protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol) &&
  239. protocol.TLSProfileIsRandomized(dialParams.TLSProfile) {
  240. dialParams.RandomizedTLSProfileSeed, err = prng.NewSeed()
  241. if err != nil {
  242. return nil, common.ContextError(err)
  243. }
  244. }
  245. if (!isReplay || !replayFronting) &&
  246. protocol.TunnelProtocolUsesFrontedMeek(dialParams.TunnelProtocol) {
  247. dialParams.MeekFrontingDialAddress, dialParams.MeekFrontingHost, err =
  248. selectFrontingParameters(serverEntry)
  249. if err != nil {
  250. return nil, common.ContextError(err)
  251. }
  252. }
  253. if !isReplay || !replayHostname {
  254. if protocol.TunnelProtocolUsesQUIC(dialParams.TunnelProtocol) {
  255. dialParams.QUICDialSNIAddress = fmt.Sprintf("%s:%d", common.GenerateHostName(), serverEntry.SshObfuscatedQUICPort)
  256. } else if protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol) {
  257. dialParams.MeekSNIServerName = ""
  258. if p.WeightedCoinFlip(parameters.TransformHostNameProbability) {
  259. dialParams.MeekSNIServerName = common.GenerateHostName()
  260. dialParams.MeekTransformedHostName = true
  261. }
  262. } else if protocol.TunnelProtocolUsesMeekHTTP(dialParams.TunnelProtocol) {
  263. dialParams.MeekHostHeader = ""
  264. hostname := serverEntry.IpAddress
  265. if p.WeightedCoinFlip(parameters.TransformHostNameProbability) {
  266. hostname = common.GenerateHostName()
  267. dialParams.MeekTransformedHostName = true
  268. }
  269. if serverEntry.MeekServerPort == 80 {
  270. dialParams.MeekHostHeader = hostname
  271. } else {
  272. dialParams.MeekHostHeader = fmt.Sprintf("%s:%d", hostname, serverEntry.MeekServerPort)
  273. }
  274. }
  275. }
  276. if (!isReplay || !replayQUICVersion) &&
  277. protocol.TunnelProtocolUsesQUIC(dialParams.TunnelProtocol) {
  278. dialParams.QUICVersion = selectQUICVersion(p)
  279. }
  280. if (!isReplay || !replayObfuscatedQUIC) &&
  281. protocol.QUICVersionIsObfuscated(dialParams.QUICVersion) {
  282. dialParams.ObfuscatedQUICPaddingSeed, err = prng.NewSeed()
  283. if err != nil {
  284. return nil, common.ContextError(err)
  285. }
  286. }
  287. if !isReplay || !replayLivenessTest {
  288. // TODO: initialize only when LivenessTestMaxUp/DownstreamBytes > 0?
  289. dialParams.LivenessTestSeed, err = prng.NewSeed()
  290. if err != nil {
  291. return nil, common.ContextError(err)
  292. }
  293. }
  294. if !isReplay || !replayAPIRequestPadding {
  295. dialParams.APIRequestPaddingSeed, err = prng.NewSeed()
  296. if err != nil {
  297. return nil, common.ContextError(err)
  298. }
  299. }
  300. // Set dial address fields. This portion of configuration is
  301. // deterministic, given the parameters established or replayed so far.
  302. switch dialParams.TunnelProtocol {
  303. case protocol.TUNNEL_PROTOCOL_SSH:
  304. dialParams.DirectDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.SshPort)
  305. case protocol.TUNNEL_PROTOCOL_OBFUSCATED_SSH:
  306. dialParams.DirectDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.SshObfuscatedPort)
  307. case protocol.TUNNEL_PROTOCOL_TAPDANCE_OBFUSCATED_SSH:
  308. dialParams.DirectDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.SshObfuscatedTapdancePort)
  309. case protocol.TUNNEL_PROTOCOL_QUIC_OBFUSCATED_SSH:
  310. dialParams.DirectDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.SshObfuscatedQUICPort)
  311. case protocol.TUNNEL_PROTOCOL_MARIONETTE_OBFUSCATED_SSH:
  312. // Note: port comes from marionnete "format"
  313. dialParams.DirectDialAddress = serverEntry.IpAddress
  314. case protocol.TUNNEL_PROTOCOL_FRONTED_MEEK:
  315. dialParams.MeekDialAddress = fmt.Sprintf("%s:443", dialParams.MeekFrontingDialAddress)
  316. dialParams.MeekHostHeader = dialParams.MeekFrontingHost
  317. if serverEntry.MeekFrontingDisableSNI {
  318. dialParams.MeekSNIServerName = ""
  319. } else if !dialParams.MeekTransformedHostName {
  320. dialParams.MeekSNIServerName = dialParams.MeekFrontingDialAddress
  321. }
  322. case protocol.TUNNEL_PROTOCOL_FRONTED_MEEK_HTTP:
  323. dialParams.MeekDialAddress = fmt.Sprintf("%s:80", dialParams.MeekFrontingDialAddress)
  324. dialParams.MeekHostHeader = dialParams.MeekFrontingHost
  325. case protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK:
  326. dialParams.MeekDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.MeekServerPort)
  327. if !dialParams.MeekTransformedHostName {
  328. if serverEntry.MeekServerPort == 80 {
  329. dialParams.MeekHostHeader = serverEntry.IpAddress
  330. } else {
  331. dialParams.MeekHostHeader = dialParams.MeekDialAddress
  332. }
  333. }
  334. case protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  335. protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET:
  336. dialParams.MeekDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.MeekServerPort)
  337. if !dialParams.MeekTransformedHostName {
  338. // Note: IP address in SNI field will be omitted.
  339. dialParams.MeekSNIServerName = serverEntry.IpAddress
  340. }
  341. if serverEntry.MeekServerPort == 443 {
  342. dialParams.MeekHostHeader = serverEntry.IpAddress
  343. } else {
  344. dialParams.MeekHostHeader = dialParams.MeekDialAddress
  345. }
  346. default:
  347. return nil, common.ContextError(
  348. fmt.Errorf("unknown tunnel protocol: %s", dialParams.TunnelProtocol))
  349. }
  350. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) {
  351. host, port, _ := net.SplitHostPort(dialParams.MeekDialAddress)
  352. if p.Bool(parameters.MeekDialDomainsOnly) {
  353. if net.ParseIP(host) != nil {
  354. // No error, as this is a "not supported" case.
  355. return nil, nil
  356. }
  357. }
  358. dialParams.DialPortNumber = port
  359. // The underlying TLS will automatically disable SNI for IP address server name
  360. // values; we have this explicit check here so we record the correct value for stats.
  361. if net.ParseIP(dialParams.MeekSNIServerName) != nil {
  362. dialParams.MeekSNIServerName = ""
  363. }
  364. } else {
  365. _, dialParams.DialPortNumber, _ = net.SplitHostPort(dialParams.DirectDialAddress)
  366. }
  367. // Initialize/replay User-Agent header for HTTP upstream proxy and meek protocols.
  368. if config.UseUpstreamProxy() {
  369. // Note: UpstreamProxyURL will be validated in the dial
  370. proxyURL, err := url.Parse(config.UpstreamProxyURL)
  371. if err == nil {
  372. dialParams.UpstreamProxyType = proxyURL.Scheme
  373. }
  374. }
  375. dialCustomHeaders := makeDialCustomHeaders(config, p)
  376. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) || dialParams.UpstreamProxyType == "http" {
  377. if !isReplay || !replayUserAgent {
  378. dialParams.SelectedUserAgent, dialParams.UserAgent = PickUserAgentIfUnset(p, dialCustomHeaders)
  379. }
  380. if dialParams.SelectedUserAgent {
  381. dialCustomHeaders.Set("User-Agent", dialParams.UserAgent)
  382. }
  383. }
  384. // UpstreamProxyCustomHeaderNames is a reported metric. Just the names and
  385. // not the values are reported, in case the values are identifying.
  386. if len(config.CustomHeaders) > 0 {
  387. dialParams.UpstreamProxyCustomHeaderNames = make([]string, 0)
  388. for name := range dialCustomHeaders {
  389. if name == "User-Agent" && dialParams.SelectedUserAgent {
  390. continue
  391. }
  392. dialParams.UpstreamProxyCustomHeaderNames = append(dialParams.UpstreamProxyCustomHeaderNames, name)
  393. }
  394. }
  395. // Initialize Dial/MeekConfigs to be passed to the corresponding dialers.
  396. dialParams.dialConfig = &DialConfig{
  397. UpstreamProxyURL: config.UpstreamProxyURL,
  398. CustomHeaders: dialCustomHeaders,
  399. DeviceBinder: config.deviceBinder,
  400. DnsServerGetter: config.DnsServerGetter,
  401. IPv6Synthesizer: config.IPv6Synthesizer,
  402. TrustedCACertificatesFilename: config.TrustedCACertificatesFilename,
  403. FragmentorConfig: fragmentor.NewUpstreamConfig(p, dialParams.TunnelProtocol, dialParams.FragmentorSeed),
  404. }
  405. // Unconditionally initialize MeekResolvedIPAddress, so a valid string can
  406. // always be read.
  407. dialParams.MeekResolvedIPAddress.Store("")
  408. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) {
  409. dialParams.meekConfig = &MeekConfig{
  410. ClientParameters: config.clientParameters,
  411. DialAddress: dialParams.MeekDialAddress,
  412. UseHTTPS: protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol),
  413. TLSProfile: dialParams.TLSProfile,
  414. RandomizedTLSProfileSeed: dialParams.RandomizedTLSProfileSeed,
  415. UseObfuscatedSessionTickets: dialParams.TunnelProtocol == protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET,
  416. SNIServerName: dialParams.MeekSNIServerName,
  417. HostHeader: dialParams.MeekHostHeader,
  418. TransformedHostName: dialParams.MeekTransformedHostName,
  419. ClientTunnelProtocol: dialParams.TunnelProtocol,
  420. MeekCookieEncryptionPublicKey: serverEntry.MeekCookieEncryptionPublicKey,
  421. MeekObfuscatedKey: serverEntry.MeekObfuscatedKey,
  422. MeekObfuscatorPaddingSeed: dialParams.MeekObfuscatorPaddingSeed,
  423. }
  424. // Use an asynchronous callback to record the resolved IP address when
  425. // dialing a domain name. Note that DialMeek doesn't immediately
  426. // establish any HTTP connections, so the resolved IP address won't be
  427. // reported in all cases until after SSH traffic is relayed or a
  428. // endpoint request is made over the meek connection.
  429. dialParams.dialConfig.ResolvedIPCallback = func(IPAddress string) {
  430. dialParams.MeekResolvedIPAddress.Store(IPAddress)
  431. }
  432. if isTactics {
  433. dialParams.meekConfig.RoundTripperOnly = true
  434. }
  435. }
  436. return dialParams, nil
  437. }
  438. func (dialParams *DialParameters) GetDialConfig() *DialConfig {
  439. return dialParams.dialConfig
  440. }
  441. func (dialParams *DialParameters) GetMeekConfig() *MeekConfig {
  442. return dialParams.meekConfig
  443. }
  444. func (dialParams *DialParameters) Succeeded() {
  445. // When TTL is 0, don't store dial parameters.
  446. if dialParams.LastUsedTimestamp.IsZero() {
  447. return
  448. }
  449. NoticeInfo("Set dial parameters for %s", dialParams.ServerEntry.IpAddress)
  450. err := SetDialParameters(dialParams.ServerEntry.IpAddress, dialParams.NetworkID, dialParams)
  451. if err != nil {
  452. NoticeAlert("SetDialParameters failed: %s", err)
  453. }
  454. }
  455. func (dialParams *DialParameters) Failed() {
  456. // When a tunnel fails, and the dial is a replay, clear the stored dial
  457. // parameters which are now presumed to be blocked, impaired or otherwise
  458. // no longer effective.
  459. //
  460. // It may be the case that a dial is not using stored dial parameters, and
  461. // in this case we retain those dial parameters since they were not
  462. // exercised and may still be efective.
  463. if dialParams.IsReplay {
  464. NoticeInfo("Delete dial parameters for %s", dialParams.ServerEntry.IpAddress)
  465. err := DeleteDialParameters(dialParams.ServerEntry.IpAddress, dialParams.NetworkID)
  466. if err != nil {
  467. NoticeAlert("DeleteDialParameters failed: %s", err)
  468. }
  469. }
  470. }
  471. func getConfigStateHash(
  472. config *Config,
  473. p *parameters.ClientParametersSnapshot,
  474. serverEntry *protocol.ServerEntry) []byte {
  475. // The config state hash should reflect config, tactics, and server entry
  476. // settings that impact the dial parameters. The hash should change if any
  477. // of these input values change in a way that invalidates any stored dial
  478. // parameters.
  479. // MD5 hash is used solely as a data checksum and not for any security purpose.
  480. hash := md5.New()
  481. hash.Write([]byte(p.Tag()))
  482. // TODO: marshal entire server entry?
  483. var serverEntryConfigurationVersion [8]byte
  484. binary.BigEndian.PutUint64(
  485. serverEntryConfigurationVersion[:],
  486. uint64(serverEntry.ConfigurationVersion))
  487. hash.Write(serverEntryConfigurationVersion[:])
  488. hash.Write([]byte(serverEntry.LocalTimestamp))
  489. // TODO: add config.CustomHeaders, which could impact User-Agent header?
  490. hash.Write([]byte(config.UpstreamProxyURL))
  491. return hash.Sum(nil)
  492. }
  493. func selectFrontingParameters(serverEntry *protocol.ServerEntry) (string, string, error) {
  494. frontingDialHost := ""
  495. frontingHost := ""
  496. if len(serverEntry.MeekFrontingAddressesRegex) > 0 {
  497. // Generate a front address based on the regex.
  498. var err error
  499. frontingDialHost, err = regen.Generate(serverEntry.MeekFrontingAddressesRegex)
  500. if err != nil {
  501. return "", "", common.ContextError(err)
  502. }
  503. } else {
  504. // Randomly select, for this connection attempt, one front address for
  505. // fronting-capable servers.
  506. if len(serverEntry.MeekFrontingAddresses) == 0 {
  507. return "", "", common.ContextError(errors.New("MeekFrontingAddresses is empty"))
  508. }
  509. index := prng.Intn(len(serverEntry.MeekFrontingAddresses))
  510. frontingDialHost = serverEntry.MeekFrontingAddresses[index]
  511. }
  512. if len(serverEntry.MeekFrontingHosts) > 0 {
  513. index := prng.Intn(len(serverEntry.MeekFrontingHosts))
  514. frontingHost = serverEntry.MeekFrontingHosts[index]
  515. } else {
  516. // Backwards compatibility case
  517. frontingHost = serverEntry.MeekFrontingHost
  518. }
  519. return frontingDialHost, frontingHost, nil
  520. }
  521. func selectQUICVersion(p *parameters.ClientParametersSnapshot) string {
  522. limitQUICVersions := p.QUICVersions(parameters.LimitQUICVersions)
  523. quicVersions := make([]string, 0)
  524. for _, quicVersion := range protocol.SupportedQUICVersions {
  525. if len(limitQUICVersions) > 0 &&
  526. !common.Contains(limitQUICVersions, quicVersion) {
  527. continue
  528. }
  529. quicVersions = append(quicVersions, quicVersion)
  530. }
  531. if len(quicVersions) == 0 {
  532. return ""
  533. }
  534. choice := prng.Intn(len(quicVersions))
  535. return quicVersions[choice]
  536. }
  537. func makeDialCustomHeaders(
  538. config *Config,
  539. p *parameters.ClientParametersSnapshot) http.Header {
  540. dialCustomHeaders := make(http.Header)
  541. if config.CustomHeaders != nil {
  542. for k, v := range config.CustomHeaders {
  543. dialCustomHeaders[k] = make([]string, len(v))
  544. copy(dialCustomHeaders[k], v)
  545. }
  546. }
  547. additionalCustomHeaders := p.HTTPHeaders(parameters.AdditionalCustomHeaders)
  548. if additionalCustomHeaders != nil {
  549. for k, v := range additionalCustomHeaders {
  550. dialCustomHeaders[k] = make([]string, len(v))
  551. copy(dialCustomHeaders[k], v)
  552. }
  553. }
  554. return dialCustomHeaders
  555. }