dialParameters.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  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.GetClientParametersSnapshot()
  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. (dialParams.QUICVersion != "" &&
  167. !common.Contains(protocol.SupportedQUICVersions, dialParams.QUICVersion))) {
  168. // In these cases, existing dial parameters are expired or no longer
  169. // match the config state and so are cleared to avoid rechecking them.
  170. err = DeleteDialParameters(serverEntry.IpAddress, networkID)
  171. if err != nil {
  172. NoticeAlert("DeleteDialParameters failed: %s", err)
  173. }
  174. dialParams = nil
  175. }
  176. if dialParams != nil {
  177. if config.DisableReplay ||
  178. !canReplay(serverEntry, dialParams.TunnelProtocol) {
  179. // In these ephemeral cases, existing dial parameters may still be valid
  180. // and used in future establishment phases, and so are retained.
  181. dialParams = nil
  182. }
  183. }
  184. isReplay := (dialParams != nil)
  185. if !isReplay {
  186. dialParams = &DialParameters{}
  187. }
  188. dialParams.ServerEntry = serverEntry
  189. dialParams.NetworkID = networkID
  190. dialParams.IsReplay = isReplay
  191. dialParams.CandidateNumber = candidateNumber
  192. // Even when replaying, LastUsedTimestamp is updated to extend the TTL of
  193. // replayed dial parameters which will be updated in the datastore upon
  194. // success.
  195. dialParams.LastUsedTimestamp = currentTimestamp
  196. dialParams.LastUsedConfigStateHash = configStateHash
  197. // Initialize dial parameters.
  198. //
  199. // When not replaying, all required parameters are initialized. When
  200. // replaying, existing parameters are retaing, subject to the replay-X
  201. // tactics flags.
  202. if !isReplay {
  203. // TODO: should there be a pre-check of selectProtocol before incurring
  204. // overhead of unmarshaling dial parameters? In may be that a server entry
  205. // is fully incapable of satisfying the current protocol selection
  206. // constraints.
  207. selectedProtocol, ok := selectProtocol(serverEntry)
  208. if !ok {
  209. return nil, nil
  210. }
  211. dialParams.TunnelProtocol = selectedProtocol
  212. }
  213. if !isReplay || !replaySSH {
  214. dialParams.SelectedSSHClientVersion = true
  215. dialParams.SSHClientVersion = pickSSHClientVersion()
  216. dialParams.SSHKEXSeed, err = prng.NewSeed()
  217. if err != nil {
  218. return nil, common.ContextError(err)
  219. }
  220. }
  221. if !isReplay || !replayObfuscatorPadding {
  222. dialParams.ObfuscatorPaddingSeed, err = prng.NewSeed()
  223. if err != nil {
  224. return nil, common.ContextError(err)
  225. }
  226. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) {
  227. dialParams.MeekObfuscatorPaddingSeed, err = prng.NewSeed()
  228. if err != nil {
  229. return nil, common.ContextError(err)
  230. }
  231. }
  232. }
  233. if !isReplay || !replayFragmentor {
  234. dialParams.FragmentorSeed, err = prng.NewSeed()
  235. if err != nil {
  236. return nil, common.ContextError(err)
  237. }
  238. }
  239. if (!isReplay || !replayTLSProfile) &&
  240. protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol) {
  241. dialParams.SelectedTLSProfile = true
  242. dialParams.TLSProfile = SelectTLSProfile(p)
  243. }
  244. if (!isReplay || !replayRandomizedTLSProfile) &&
  245. protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol) &&
  246. protocol.TLSProfileIsRandomized(dialParams.TLSProfile) {
  247. dialParams.RandomizedTLSProfileSeed, err = prng.NewSeed()
  248. if err != nil {
  249. return nil, common.ContextError(err)
  250. }
  251. }
  252. if (!isReplay || !replayTLSProfile) &&
  253. protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol) {
  254. // Since "Randomized-v2" may be TLS 1.2 or TLS 1.3, construct the
  255. // ClientHello to determine if it's TLS 1.3. This test also covers
  256. // non-randomized TLS 1.3 profiles. This check must come after
  257. // dialParams.TLSProfile and dialParams.RandomizedTLSProfileSeed are set.
  258. // No actual dial is made here.
  259. utlsClientHelloID := getUTLSClientHelloID(dialParams.TLSProfile)
  260. if protocol.TLSProfileIsRandomized(dialParams.TLSProfile) {
  261. utlsClientHelloID.Seed = new(utls.PRNGSeed)
  262. *utlsClientHelloID.Seed = [32]byte(*dialParams.RandomizedTLSProfileSeed)
  263. }
  264. dialParams.TLSVersion, err = getClientHelloVersion(utlsClientHelloID)
  265. if err != nil {
  266. return nil, common.ContextError(err)
  267. }
  268. }
  269. if (!isReplay || !replayFronting) &&
  270. protocol.TunnelProtocolUsesFrontedMeek(dialParams.TunnelProtocol) {
  271. dialParams.MeekFrontingDialAddress, dialParams.MeekFrontingHost, err =
  272. selectFrontingParameters(serverEntry)
  273. if err != nil {
  274. return nil, common.ContextError(err)
  275. }
  276. }
  277. if !isReplay || !replayHostname {
  278. if protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol) ||
  279. protocol.TunnelProtocolUsesFrontedMeekQUIC(dialParams.TunnelProtocol) {
  280. dialParams.MeekSNIServerName = ""
  281. if p.WeightedCoinFlip(parameters.TransformHostNameProbability) {
  282. dialParams.MeekSNIServerName = common.GenerateHostName()
  283. dialParams.MeekTransformedHostName = true
  284. }
  285. } else if protocol.TunnelProtocolUsesMeekHTTP(dialParams.TunnelProtocol) {
  286. dialParams.MeekHostHeader = ""
  287. hostname := serverEntry.IpAddress
  288. if p.WeightedCoinFlip(parameters.TransformHostNameProbability) {
  289. hostname = common.GenerateHostName()
  290. dialParams.MeekTransformedHostName = true
  291. }
  292. if serverEntry.MeekServerPort == 80 {
  293. dialParams.MeekHostHeader = hostname
  294. } else {
  295. dialParams.MeekHostHeader = fmt.Sprintf("%s:%d", hostname, serverEntry.MeekServerPort)
  296. }
  297. } else if protocol.TunnelProtocolUsesQUIC(dialParams.TunnelProtocol) {
  298. dialParams.QUICDialSNIAddress = fmt.Sprintf(
  299. "%s:%d", common.GenerateHostName(), serverEntry.SshObfuscatedQUICPort)
  300. }
  301. }
  302. if (!isReplay || !replayQUICVersion) &&
  303. protocol.TunnelProtocolUsesQUIC(dialParams.TunnelProtocol) {
  304. allowObfuscatedQUIC := !protocol.TunnelProtocolUsesFrontedMeekQUIC(dialParams.TunnelProtocol)
  305. dialParams.QUICVersion = selectQUICVersion(allowObfuscatedQUIC, p)
  306. }
  307. if (!isReplay || !replayObfuscatedQUIC) &&
  308. protocol.QUICVersionIsObfuscated(dialParams.QUICVersion) {
  309. dialParams.ObfuscatedQUICPaddingSeed, err = prng.NewSeed()
  310. if err != nil {
  311. return nil, common.ContextError(err)
  312. }
  313. }
  314. if !isReplay || !replayLivenessTest {
  315. // TODO: initialize only when LivenessTestMaxUp/DownstreamBytes > 0?
  316. dialParams.LivenessTestSeed, err = prng.NewSeed()
  317. if err != nil {
  318. return nil, common.ContextError(err)
  319. }
  320. }
  321. if !isReplay || !replayAPIRequestPadding {
  322. dialParams.APIRequestPaddingSeed, err = prng.NewSeed()
  323. if err != nil {
  324. return nil, common.ContextError(err)
  325. }
  326. }
  327. // Set dial address fields. This portion of configuration is
  328. // deterministic, given the parameters established or replayed so far.
  329. switch dialParams.TunnelProtocol {
  330. case protocol.TUNNEL_PROTOCOL_SSH:
  331. dialParams.DirectDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.SshPort)
  332. case protocol.TUNNEL_PROTOCOL_OBFUSCATED_SSH:
  333. dialParams.DirectDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.SshObfuscatedPort)
  334. case protocol.TUNNEL_PROTOCOL_TAPDANCE_OBFUSCATED_SSH:
  335. dialParams.DirectDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.SshObfuscatedTapdancePort)
  336. case protocol.TUNNEL_PROTOCOL_QUIC_OBFUSCATED_SSH:
  337. dialParams.DirectDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.SshObfuscatedQUICPort)
  338. case protocol.TUNNEL_PROTOCOL_FRONTED_MEEK_QUIC_OBFUSCATED_SSH:
  339. dialParams.MeekDialAddress = fmt.Sprintf("%s:443", dialParams.MeekFrontingDialAddress)
  340. dialParams.MeekHostHeader = dialParams.MeekFrontingHost
  341. if !dialParams.MeekTransformedHostName {
  342. dialParams.MeekSNIServerName = dialParams.MeekFrontingDialAddress
  343. }
  344. case protocol.TUNNEL_PROTOCOL_MARIONETTE_OBFUSCATED_SSH:
  345. // Note: port comes from marionnete "format"
  346. dialParams.DirectDialAddress = serverEntry.IpAddress
  347. case protocol.TUNNEL_PROTOCOL_FRONTED_MEEK:
  348. dialParams.MeekDialAddress = fmt.Sprintf("%s:443", dialParams.MeekFrontingDialAddress)
  349. dialParams.MeekHostHeader = dialParams.MeekFrontingHost
  350. if serverEntry.MeekFrontingDisableSNI {
  351. dialParams.MeekSNIServerName = ""
  352. } else if !dialParams.MeekTransformedHostName {
  353. dialParams.MeekSNIServerName = dialParams.MeekFrontingDialAddress
  354. }
  355. case protocol.TUNNEL_PROTOCOL_FRONTED_MEEK_HTTP:
  356. dialParams.MeekDialAddress = fmt.Sprintf("%s:80", dialParams.MeekFrontingDialAddress)
  357. dialParams.MeekHostHeader = dialParams.MeekFrontingHost
  358. case protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK:
  359. dialParams.MeekDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.MeekServerPort)
  360. if !dialParams.MeekTransformedHostName {
  361. if serverEntry.MeekServerPort == 80 {
  362. dialParams.MeekHostHeader = serverEntry.IpAddress
  363. } else {
  364. dialParams.MeekHostHeader = dialParams.MeekDialAddress
  365. }
  366. }
  367. case protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  368. protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET:
  369. dialParams.MeekDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.MeekServerPort)
  370. if !dialParams.MeekTransformedHostName {
  371. // Note: IP address in SNI field will be omitted.
  372. dialParams.MeekSNIServerName = serverEntry.IpAddress
  373. }
  374. if serverEntry.MeekServerPort == 443 {
  375. dialParams.MeekHostHeader = serverEntry.IpAddress
  376. } else {
  377. dialParams.MeekHostHeader = dialParams.MeekDialAddress
  378. }
  379. default:
  380. return nil, common.ContextError(
  381. fmt.Errorf("unknown tunnel protocol: %s", dialParams.TunnelProtocol))
  382. }
  383. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) {
  384. host, port, _ := net.SplitHostPort(dialParams.MeekDialAddress)
  385. if p.Bool(parameters.MeekDialDomainsOnly) {
  386. if net.ParseIP(host) != nil {
  387. // No error, as this is a "not supported" case.
  388. return nil, nil
  389. }
  390. }
  391. dialParams.DialPortNumber = port
  392. // The underlying TLS will automatically disable SNI for IP address server name
  393. // values; we have this explicit check here so we record the correct value for stats.
  394. if net.ParseIP(dialParams.MeekSNIServerName) != nil {
  395. dialParams.MeekSNIServerName = ""
  396. }
  397. } else {
  398. _, dialParams.DialPortNumber, _ = net.SplitHostPort(dialParams.DirectDialAddress)
  399. }
  400. // Initialize/replay User-Agent header for HTTP upstream proxy and meek protocols.
  401. if config.UseUpstreamProxy() {
  402. // Note: UpstreamProxyURL will be validated in the dial
  403. proxyURL, err := url.Parse(config.UpstreamProxyURL)
  404. if err == nil {
  405. dialParams.UpstreamProxyType = proxyURL.Scheme
  406. }
  407. }
  408. dialCustomHeaders := makeDialCustomHeaders(config, p)
  409. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) || dialParams.UpstreamProxyType == "http" {
  410. if !isReplay || !replayUserAgent {
  411. dialParams.SelectedUserAgent, dialParams.UserAgent = PickUserAgentIfUnset(p, dialCustomHeaders)
  412. }
  413. if dialParams.SelectedUserAgent {
  414. dialCustomHeaders.Set("User-Agent", dialParams.UserAgent)
  415. }
  416. }
  417. // UpstreamProxyCustomHeaderNames is a reported metric. Just the names and
  418. // not the values are reported, in case the values are identifying.
  419. if len(config.CustomHeaders) > 0 {
  420. dialParams.UpstreamProxyCustomHeaderNames = make([]string, 0)
  421. for name := range dialCustomHeaders {
  422. if name == "User-Agent" && dialParams.SelectedUserAgent {
  423. continue
  424. }
  425. dialParams.UpstreamProxyCustomHeaderNames = append(dialParams.UpstreamProxyCustomHeaderNames, name)
  426. }
  427. }
  428. // Initialize Dial/MeekConfigs to be passed to the corresponding dialers.
  429. dialParams.dialConfig = &DialConfig{
  430. UpstreamProxyURL: config.UpstreamProxyURL,
  431. CustomHeaders: dialCustomHeaders,
  432. DeviceBinder: config.deviceBinder,
  433. DnsServerGetter: config.DnsServerGetter,
  434. IPv6Synthesizer: config.IPv6Synthesizer,
  435. TrustedCACertificatesFilename: config.TrustedCACertificatesFilename,
  436. FragmentorConfig: fragmentor.NewUpstreamConfig(p, dialParams.TunnelProtocol, dialParams.FragmentorSeed),
  437. }
  438. // Unconditionally initialize MeekResolvedIPAddress, so a valid string can
  439. // always be read.
  440. dialParams.MeekResolvedIPAddress.Store("")
  441. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) {
  442. dialParams.meekConfig = &MeekConfig{
  443. ClientParameters: config.clientParameters,
  444. DialAddress: dialParams.MeekDialAddress,
  445. UseQUIC: protocol.TunnelProtocolUsesFrontedMeekQUIC(dialParams.TunnelProtocol),
  446. QUICVersion: dialParams.QUICVersion,
  447. UseHTTPS: protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol),
  448. TLSProfile: dialParams.TLSProfile,
  449. RandomizedTLSProfileSeed: dialParams.RandomizedTLSProfileSeed,
  450. UseObfuscatedSessionTickets: dialParams.TunnelProtocol == protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET,
  451. SNIServerName: dialParams.MeekSNIServerName,
  452. HostHeader: dialParams.MeekHostHeader,
  453. TransformedHostName: dialParams.MeekTransformedHostName,
  454. ClientTunnelProtocol: dialParams.TunnelProtocol,
  455. MeekCookieEncryptionPublicKey: serverEntry.MeekCookieEncryptionPublicKey,
  456. MeekObfuscatedKey: serverEntry.MeekObfuscatedKey,
  457. MeekObfuscatorPaddingSeed: dialParams.MeekObfuscatorPaddingSeed,
  458. }
  459. // Use an asynchronous callback to record the resolved IP address when
  460. // dialing a domain name. Note that DialMeek doesn't immediately
  461. // establish any HTTP connections, so the resolved IP address won't be
  462. // reported in all cases until after SSH traffic is relayed or a
  463. // endpoint request is made over the meek connection.
  464. dialParams.dialConfig.ResolvedIPCallback = func(IPAddress string) {
  465. dialParams.MeekResolvedIPAddress.Store(IPAddress)
  466. }
  467. if isTactics {
  468. dialParams.meekConfig.RoundTripperOnly = true
  469. }
  470. }
  471. return dialParams, nil
  472. }
  473. func (dialParams *DialParameters) GetDialConfig() *DialConfig {
  474. return dialParams.dialConfig
  475. }
  476. func (dialParams *DialParameters) GetMeekConfig() *MeekConfig {
  477. return dialParams.meekConfig
  478. }
  479. func (dialParams *DialParameters) Succeeded() {
  480. // When TTL is 0, don't store dial parameters.
  481. if dialParams.LastUsedTimestamp.IsZero() {
  482. return
  483. }
  484. NoticeInfo("Set dial parameters for %s", dialParams.ServerEntry.IpAddress)
  485. err := SetDialParameters(dialParams.ServerEntry.IpAddress, dialParams.NetworkID, dialParams)
  486. if err != nil {
  487. NoticeAlert("SetDialParameters failed: %s", err)
  488. }
  489. }
  490. func (dialParams *DialParameters) Failed(config *Config) {
  491. // When a tunnel fails, and the dial is a replay, clear the stored dial
  492. // parameters which are now presumed to be blocked, impaired or otherwise
  493. // no longer effective.
  494. //
  495. // It may be the case that a dial is not using stored dial parameters
  496. // (!IsReplay), and in this case we retain those dial parameters since they
  497. // were not exercised and may still be effective.
  498. //
  499. // Failed tunnel dial parameters may be retained with a configurable
  500. // probability; this is intended to help mitigate false positive failures due
  501. // to, e.g., temporary network disruptions or server load limiting.
  502. if dialParams.IsReplay &&
  503. !config.GetClientParametersSnapshot().WeightedCoinFlip(
  504. parameters.ReplayRetainFailedProbability) {
  505. NoticeInfo("Delete dial parameters for %s", dialParams.ServerEntry.IpAddress)
  506. err := DeleteDialParameters(dialParams.ServerEntry.IpAddress, dialParams.NetworkID)
  507. if err != nil {
  508. NoticeAlert("DeleteDialParameters failed: %s", err)
  509. }
  510. }
  511. }
  512. func getConfigStateHash(
  513. config *Config,
  514. p *parameters.ClientParametersSnapshot,
  515. serverEntry *protocol.ServerEntry) []byte {
  516. // The config state hash should reflect config, tactics, and server entry
  517. // settings that impact the dial parameters. The hash should change if any
  518. // of these input values change in a way that invalidates any stored dial
  519. // parameters.
  520. // MD5 hash is used solely as a data checksum and not for any security
  521. // purpose.
  522. hash := md5.New()
  523. // Add a hash of relevant config fields.
  524. // Limitation: the config hash may change even when tactics will override the
  525. // changed config field.
  526. hash.Write(config.dialParametersHash)
  527. // Add the active tactics tag.
  528. hash.Write([]byte(p.Tag()))
  529. // Add the server entry version and local timestamp, both of which should
  530. // change when the server entry contents change and/or a new local copy is
  531. // imported.
  532. // TODO: marshal entire server entry?
  533. var serverEntryConfigurationVersion [8]byte
  534. binary.BigEndian.PutUint64(
  535. serverEntryConfigurationVersion[:],
  536. uint64(serverEntry.ConfigurationVersion))
  537. hash.Write(serverEntryConfigurationVersion[:])
  538. hash.Write([]byte(serverEntry.LocalTimestamp))
  539. return hash.Sum(nil)
  540. }
  541. func selectFrontingParameters(serverEntry *protocol.ServerEntry) (string, string, error) {
  542. frontingDialHost := ""
  543. frontingHost := ""
  544. if len(serverEntry.MeekFrontingAddressesRegex) > 0 {
  545. // Generate a front address based on the regex.
  546. var err error
  547. frontingDialHost, err = regen.Generate(serverEntry.MeekFrontingAddressesRegex)
  548. if err != nil {
  549. return "", "", common.ContextError(err)
  550. }
  551. } else {
  552. // Randomly select, for this connection attempt, one front address for
  553. // fronting-capable servers.
  554. if len(serverEntry.MeekFrontingAddresses) == 0 {
  555. return "", "", common.ContextError(errors.New("MeekFrontingAddresses is empty"))
  556. }
  557. index := prng.Intn(len(serverEntry.MeekFrontingAddresses))
  558. frontingDialHost = serverEntry.MeekFrontingAddresses[index]
  559. }
  560. if len(serverEntry.MeekFrontingHosts) > 0 {
  561. index := prng.Intn(len(serverEntry.MeekFrontingHosts))
  562. frontingHost = serverEntry.MeekFrontingHosts[index]
  563. } else {
  564. // Backwards compatibility case
  565. frontingHost = serverEntry.MeekFrontingHost
  566. }
  567. return frontingDialHost, frontingHost, nil
  568. }
  569. func selectQUICVersion(allowObfuscatedQUIC bool, p *parameters.ClientParametersSnapshot) string {
  570. limitQUICVersions := p.QUICVersions(parameters.LimitQUICVersions)
  571. quicVersions := make([]string, 0)
  572. for _, quicVersion := range protocol.SupportedQUICVersions {
  573. if len(limitQUICVersions) > 0 &&
  574. !common.Contains(limitQUICVersions, quicVersion) {
  575. continue
  576. }
  577. if !allowObfuscatedQUIC &&
  578. protocol.QUICVersionIsObfuscated(quicVersion) {
  579. continue
  580. }
  581. quicVersions = append(quicVersions, quicVersion)
  582. }
  583. if len(quicVersions) == 0 {
  584. return ""
  585. }
  586. choice := prng.Intn(len(quicVersions))
  587. return quicVersions[choice]
  588. }
  589. func makeDialCustomHeaders(
  590. config *Config,
  591. p *parameters.ClientParametersSnapshot) http.Header {
  592. dialCustomHeaders := make(http.Header)
  593. if config.CustomHeaders != nil {
  594. for k, v := range config.CustomHeaders {
  595. dialCustomHeaders[k] = make([]string, len(v))
  596. copy(dialCustomHeaders[k], v)
  597. }
  598. }
  599. additionalCustomHeaders := p.HTTPHeaders(parameters.AdditionalCustomHeaders)
  600. if additionalCustomHeaders != nil {
  601. for k, v := range additionalCustomHeaders {
  602. dialCustomHeaders[k] = make([]string, len(v))
  603. copy(dialCustomHeaders[k], v)
  604. }
  605. }
  606. return dialCustomHeaders
  607. }