dialParameters.go 24 KB

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