dialParameters.go 25 KB

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