dialParameters.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  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. "fmt"
  25. "net"
  26. "net/http"
  27. "net/url"
  28. "sync/atomic"
  29. "time"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  31. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  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. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/values"
  37. utls "github.com/refraction-networking/utls"
  38. regen "github.com/zach-klippenstein/goregen"
  39. "golang.org/x/net/bpf"
  40. )
  41. // DialParameters represents a selected protocol and all the related selected
  42. // protocol attributes, many chosen at random, for a tunnel dial attempt.
  43. //
  44. // DialParameters is used:
  45. // - to configure dialers
  46. // - as a persistent record to store successful dial parameters for replay
  47. // - to report dial stats in notices and Psiphon API calls.
  48. //
  49. // MeekResolvedIPAddress is set asynchronously, as it is not known until the
  50. // dial process has begun. The atomic.Value will contain a string, initialized
  51. // to "", and set to the resolved IP address once that part of the dial
  52. // process has completed.
  53. //
  54. // DialParameters is not safe for concurrent use.
  55. type DialParameters struct {
  56. ServerEntry *protocol.ServerEntry `json:"-"`
  57. NetworkID string `json:"-"`
  58. IsReplay bool `json:"-"`
  59. CandidateNumber int `json:"-"`
  60. IsExchanged bool
  61. LastUsedTimestamp time.Time
  62. LastUsedConfigStateHash []byte
  63. NetworkLatencyMultiplier float64
  64. TunnelProtocol string
  65. DirectDialAddress string
  66. DialPortNumber string
  67. UpstreamProxyType string `json:"-"`
  68. UpstreamProxyCustomHeaderNames []string `json:"-"`
  69. BPFProgramName string
  70. BPFProgramInstructions []bpf.RawInstruction
  71. SelectedSSHClientVersion bool
  72. SSHClientVersion string
  73. SSHKEXSeed *prng.Seed
  74. ObfuscatorPaddingSeed *prng.Seed
  75. FragmentorSeed *prng.Seed
  76. MeekFrontingDialAddress string
  77. MeekFrontingHost string
  78. MeekDialAddress string
  79. MeekTransformedHostName bool
  80. MeekSNIServerName string
  81. MeekHostHeader string
  82. MeekObfuscatorPaddingSeed *prng.Seed
  83. MeekTLSPaddingSize int
  84. MeekResolvedIPAddress atomic.Value `json:"-"`
  85. SelectedUserAgent bool
  86. UserAgent string
  87. SelectedTLSProfile bool
  88. TLSProfile string
  89. NoDefaultTLSSessionID bool
  90. TLSVersion string
  91. RandomizedTLSProfileSeed *prng.Seed
  92. QUICVersion string
  93. QUICDialSNIAddress string
  94. ObfuscatedQUICPaddingSeed *prng.Seed
  95. LivenessTestSeed *prng.Seed
  96. APIRequestPaddingSeed *prng.Seed
  97. DialConnMetrics common.MetricsSource `json:"-"`
  98. ObfuscatedSSHConnMetrics common.MetricsSource `json:"-"`
  99. DialDuration time.Duration `json:"-"`
  100. dialConfig *DialConfig
  101. meekConfig *MeekConfig
  102. }
  103. // MakeDialParameters creates a new DialParameters for the candidate server
  104. // entry, including selecting a protocol and all the various protocol
  105. // attributes. The input selectProtocol is used to comply with any active
  106. // protocol selection constraints.
  107. //
  108. // When stored dial parameters are available and may be used,
  109. // MakeDialParameters may replay previous dial parameters in an effort to
  110. // leverage "known working" values instead of always chosing at random from a
  111. // large space.
  112. //
  113. // MakeDialParameters will return nil/nil in cases where the candidate server
  114. // entry should be skipped.
  115. //
  116. // To support replay, the caller must call DialParameters.Succeeded when a
  117. // successful tunnel is established with the returned DialParameters; and must
  118. // call DialParameters.Failed when a tunnel dial or activation fails, except
  119. // when establishment is cancelled.
  120. func MakeDialParameters(
  121. config *Config,
  122. canReplay func(serverEntry *protocol.ServerEntry, replayProtocol string) bool,
  123. selectProtocol func(serverEntry *protocol.ServerEntry) (string, bool),
  124. serverEntry *protocol.ServerEntry,
  125. isTactics bool,
  126. candidateNumber int) (*DialParameters, error) {
  127. networkID := config.GetNetworkID()
  128. p := config.GetClientParameters().Get()
  129. ttl := p.Duration(parameters.ReplayDialParametersTTL)
  130. replayBPF := p.Bool(parameters.ReplayBPF)
  131. replaySSH := p.Bool(parameters.ReplaySSH)
  132. replayObfuscatorPadding := p.Bool(parameters.ReplayObfuscatorPadding)
  133. replayFragmentor := p.Bool(parameters.ReplayFragmentor)
  134. replayTLSProfile := p.Bool(parameters.ReplayTLSProfile)
  135. replayRandomizedTLSProfile := p.Bool(parameters.ReplayRandomizedTLSProfile)
  136. replayFronting := p.Bool(parameters.ReplayFronting)
  137. replayHostname := p.Bool(parameters.ReplayHostname)
  138. replayQUICVersion := p.Bool(parameters.ReplayQUICVersion)
  139. replayObfuscatedQUIC := p.Bool(parameters.ReplayObfuscatedQUIC)
  140. replayLivenessTest := p.Bool(parameters.ReplayLivenessTest)
  141. replayUserAgent := p.Bool(parameters.ReplayUserAgent)
  142. replayAPIRequestPadding := p.Bool(parameters.ReplayAPIRequestPadding)
  143. // Check for existing dial parameters for this server/network ID.
  144. dialParams, err := GetDialParameters(serverEntry.IpAddress, networkID)
  145. if err != nil {
  146. NoticeWarning("GetDialParameters failed: %s", err)
  147. dialParams = nil
  148. // Proceed, without existing dial parameters.
  149. }
  150. // Check if replay is permitted:
  151. // - TTL must be > 0 and existing dial parameters must not have expired
  152. // as indicated by LastUsedTimestamp + TTL.
  153. // - Config/tactics/server entry values must be unchanged from when
  154. // previous dial parameters were established.
  155. // - The protocol selection constraints must permit replay, as indicated
  156. // by canReplay.
  157. // - Must not be using an obsolete TLS profile that is no longer supported.
  158. //
  159. // When existing dial parameters don't meet these conditions, dialParams
  160. // is reset to nil and new dial parameters will be generated.
  161. var currentTimestamp time.Time
  162. var configStateHash []byte
  163. // When TTL is 0, replay is disabled; the timestamp remains 0 and the
  164. // output DialParameters will not be stored by Success.
  165. if ttl > 0 {
  166. currentTimestamp = time.Now()
  167. configStateHash = getConfigStateHash(config, p, serverEntry)
  168. }
  169. if dialParams != nil &&
  170. (ttl <= 0 ||
  171. dialParams.LastUsedTimestamp.Before(currentTimestamp.Add(-ttl)) ||
  172. !bytes.Equal(dialParams.LastUsedConfigStateHash, configStateHash) ||
  173. (dialParams.TLSProfile != "" &&
  174. !common.Contains(protocol.SupportedTLSProfiles, dialParams.TLSProfile)) ||
  175. (dialParams.QUICVersion != "" &&
  176. !common.Contains(protocol.SupportedQUICVersions, dialParams.QUICVersion))) {
  177. // In these cases, existing dial parameters are expired or no longer
  178. // match the config state and so are cleared to avoid rechecking them.
  179. err = DeleteDialParameters(serverEntry.IpAddress, networkID)
  180. if err != nil {
  181. NoticeWarning("DeleteDialParameters failed: %s", err)
  182. }
  183. dialParams = nil
  184. }
  185. if dialParams != nil {
  186. if config.DisableReplay ||
  187. !canReplay(serverEntry, dialParams.TunnelProtocol) {
  188. // In these ephemeral cases, existing dial parameters may still be valid
  189. // and used in future establishment phases, and so are retained.
  190. dialParams = nil
  191. }
  192. }
  193. // IsExchanged:
  194. //
  195. // Dial parameters received via client-to-client exchange are partially
  196. // initialized. Only the exchange fields are retained, and all other dial
  197. // parameters fields must be initialized. This is not considered or logged as
  198. // a replay. The exchange case is identified by the IsExchanged flag.
  199. //
  200. // When previously stored, IsExchanged dial parameters will have set the same
  201. // timestamp and state hash used for regular dial parameters and the same
  202. // logic above should invalidate expired or invalid exchanged dial
  203. // parameters.
  204. //
  205. // Limitation: metrics will indicate when an exchanged server entry is used
  206. // (source "EXCHANGED") but will not indicate when exchanged dial parameters
  207. // are used vs. a redial after discarding dial parameters.
  208. isReplay := (dialParams != nil)
  209. isExchanged := isReplay && dialParams.IsExchanged
  210. if !isReplay {
  211. dialParams = &DialParameters{}
  212. }
  213. if isExchanged {
  214. // Set isReplay to false to cause all non-exchanged values to be
  215. // initialized; this also causes the exchange case to not log as replay.
  216. isReplay = false
  217. }
  218. // Set IsExchanged so that full dial parameters are stored and replayed upon success.
  219. dialParams.IsExchanged = false
  220. dialParams.ServerEntry = serverEntry
  221. dialParams.NetworkID = networkID
  222. dialParams.IsReplay = isReplay
  223. dialParams.CandidateNumber = candidateNumber
  224. // Even when replaying, LastUsedTimestamp is updated to extend the TTL of
  225. // replayed dial parameters which will be updated in the datastore upon
  226. // success.
  227. dialParams.LastUsedTimestamp = currentTimestamp
  228. dialParams.LastUsedConfigStateHash = configStateHash
  229. // Initialize dial parameters.
  230. //
  231. // When not replaying, all required parameters are initialized. When
  232. // replaying, existing parameters are retaing, subject to the replay-X
  233. // tactics flags.
  234. // Select a network latency multiplier for this dial. This allows clients to
  235. // explore and discover timeout values appropriate for the current network.
  236. // The selection applies per tunnel, to avoid delaying all establishment
  237. // candidates due to excessive timeouts. The random selection is bounded by a
  238. // min/max set in tactics and an exponential distribution is used so as to
  239. // heavily favor values close to the min, which should be set to the
  240. // singleton NetworkLatencyMultiplier tactics value.
  241. //
  242. // Not all existing, persisted DialParameters will have a custom
  243. // NetworkLatencyMultiplier value. Its zero value will cause the singleton
  244. // NetworkLatencyMultiplier tactics value to be used instead, which is
  245. // consistent with the pre-custom multiplier behavior in the older client
  246. // version which persisted that DialParameters.
  247. networkLatencyMultiplierMin := p.Float(parameters.NetworkLatencyMultiplierMin)
  248. networkLatencyMultiplierMax := p.Float(parameters.NetworkLatencyMultiplierMax)
  249. if !isReplay ||
  250. // Was selected...
  251. (dialParams.NetworkLatencyMultiplier != 0.0 &&
  252. // But is now outside tactics range...
  253. (dialParams.NetworkLatencyMultiplier < networkLatencyMultiplierMin ||
  254. dialParams.NetworkLatencyMultiplier > networkLatencyMultiplierMax)) {
  255. dialParams.NetworkLatencyMultiplier = prng.ExpFloat64Range(
  256. networkLatencyMultiplierMin,
  257. networkLatencyMultiplierMax,
  258. p.Float(parameters.NetworkLatencyMultiplierLambda))
  259. }
  260. if !isReplay && !isExchanged {
  261. // TODO: should there be a pre-check of selectProtocol before incurring
  262. // overhead of unmarshaling dial parameters? In may be that a server entry
  263. // is fully incapable of satisfying the current protocol selection
  264. // constraints.
  265. selectedProtocol, ok := selectProtocol(serverEntry)
  266. if !ok {
  267. return nil, nil
  268. }
  269. dialParams.TunnelProtocol = selectedProtocol
  270. }
  271. if (!isReplay || !replayBPF) &&
  272. ClientBPFEnabled() &&
  273. protocol.TunnelProtocolUsesTCP(dialParams.TunnelProtocol) {
  274. if p.WeightedCoinFlip(parameters.BPFClientTCPProbability) {
  275. dialParams.BPFProgramName = ""
  276. dialParams.BPFProgramInstructions = nil
  277. ok, name, rawInstructions := p.BPFProgram(parameters.BPFClientTCPProgram)
  278. if ok {
  279. dialParams.BPFProgramName = name
  280. dialParams.BPFProgramInstructions = rawInstructions
  281. }
  282. }
  283. }
  284. if !isReplay || !replaySSH {
  285. dialParams.SelectedSSHClientVersion = true
  286. dialParams.SSHClientVersion = values.GetSSHClientVersion()
  287. dialParams.SSHKEXSeed, err = prng.NewSeed()
  288. if err != nil {
  289. return nil, errors.Trace(err)
  290. }
  291. }
  292. if !isReplay || !replayObfuscatorPadding {
  293. dialParams.ObfuscatorPaddingSeed, err = prng.NewSeed()
  294. if err != nil {
  295. return nil, errors.Trace(err)
  296. }
  297. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) {
  298. dialParams.MeekObfuscatorPaddingSeed, err = prng.NewSeed()
  299. if err != nil {
  300. return nil, errors.Trace(err)
  301. }
  302. }
  303. }
  304. if !isReplay || !replayFragmentor {
  305. dialParams.FragmentorSeed, err = prng.NewSeed()
  306. if err != nil {
  307. return nil, errors.Trace(err)
  308. }
  309. }
  310. if (!isReplay || !replayTLSProfile) &&
  311. protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol) {
  312. dialParams.SelectedTLSProfile = true
  313. dialParams.TLSProfile = SelectTLSProfile(p)
  314. dialParams.NoDefaultTLSSessionID = p.WeightedCoinFlip(
  315. parameters.NoDefaultTLSSessionIDProbability)
  316. }
  317. if (!isReplay || !replayRandomizedTLSProfile) &&
  318. protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol) &&
  319. protocol.TLSProfileIsRandomized(dialParams.TLSProfile) {
  320. dialParams.RandomizedTLSProfileSeed, err = prng.NewSeed()
  321. if err != nil {
  322. return nil, errors.Trace(err)
  323. }
  324. }
  325. if (!isReplay || !replayTLSProfile) &&
  326. protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol) {
  327. // Since "Randomized-v2"/CustomTLSProfiles may be TLS 1.2 or TLS 1.3,
  328. // construct the ClientHello to determine if it's TLS 1.3. This test also
  329. // covers non-randomized TLS 1.3 profiles. This check must come after
  330. // dialParams.TLSProfile and dialParams.RandomizedTLSProfileSeed are set. No
  331. // actual dial is made here.
  332. utlsClientHelloID, utlsClientHelloSpec, err := getUTLSClientHelloID(
  333. p, dialParams.TLSProfile)
  334. if err != nil {
  335. return nil, errors.Trace(err)
  336. }
  337. if protocol.TLSProfileIsRandomized(dialParams.TLSProfile) {
  338. utlsClientHelloID.Seed = new(utls.PRNGSeed)
  339. *utlsClientHelloID.Seed = [32]byte(*dialParams.RandomizedTLSProfileSeed)
  340. }
  341. dialParams.TLSVersion, err = getClientHelloVersion(
  342. utlsClientHelloID, utlsClientHelloSpec)
  343. if err != nil {
  344. return nil, errors.Trace(err)
  345. }
  346. }
  347. if (!isReplay || !replayFronting) &&
  348. protocol.TunnelProtocolUsesFrontedMeek(dialParams.TunnelProtocol) {
  349. dialParams.MeekFrontingDialAddress, dialParams.MeekFrontingHost, err =
  350. selectFrontingParameters(serverEntry)
  351. if err != nil {
  352. return nil, errors.Trace(err)
  353. }
  354. }
  355. if !isReplay || !replayHostname {
  356. if protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol) ||
  357. protocol.TunnelProtocolUsesFrontedMeekQUIC(dialParams.TunnelProtocol) {
  358. dialParams.MeekSNIServerName = ""
  359. if p.WeightedCoinFlip(parameters.TransformHostNameProbability) {
  360. dialParams.MeekSNIServerName = values.GetHostName()
  361. dialParams.MeekTransformedHostName = true
  362. }
  363. } else if protocol.TunnelProtocolUsesMeekHTTP(dialParams.TunnelProtocol) {
  364. dialParams.MeekHostHeader = ""
  365. hostname := serverEntry.IpAddress
  366. if p.WeightedCoinFlip(parameters.TransformHostNameProbability) {
  367. hostname = values.GetHostName()
  368. dialParams.MeekTransformedHostName = true
  369. }
  370. if serverEntry.MeekServerPort == 80 {
  371. dialParams.MeekHostHeader = hostname
  372. } else {
  373. dialParams.MeekHostHeader = fmt.Sprintf("%s:%d", hostname, serverEntry.MeekServerPort)
  374. }
  375. } else if protocol.TunnelProtocolUsesQUIC(dialParams.TunnelProtocol) {
  376. dialParams.QUICDialSNIAddress = fmt.Sprintf(
  377. "%s:%d", values.GetHostName(), serverEntry.SshObfuscatedQUICPort)
  378. }
  379. }
  380. if (!isReplay || !replayQUICVersion) &&
  381. protocol.TunnelProtocolUsesQUIC(dialParams.TunnelProtocol) {
  382. allowObfuscatedQUIC := !protocol.TunnelProtocolUsesFrontedMeekQUIC(dialParams.TunnelProtocol)
  383. dialParams.QUICVersion = selectQUICVersion(allowObfuscatedQUIC, p)
  384. }
  385. if (!isReplay || !replayObfuscatedQUIC) &&
  386. protocol.QUICVersionIsObfuscated(dialParams.QUICVersion) {
  387. dialParams.ObfuscatedQUICPaddingSeed, err = prng.NewSeed()
  388. if err != nil {
  389. return nil, errors.Trace(err)
  390. }
  391. }
  392. if !isReplay || !replayLivenessTest {
  393. // TODO: initialize only when LivenessTestMaxUp/DownstreamBytes > 0?
  394. dialParams.LivenessTestSeed, err = prng.NewSeed()
  395. if err != nil {
  396. return nil, errors.Trace(err)
  397. }
  398. }
  399. if !isReplay || !replayAPIRequestPadding {
  400. dialParams.APIRequestPaddingSeed, err = prng.NewSeed()
  401. if err != nil {
  402. return nil, errors.Trace(err)
  403. }
  404. }
  405. // Set dial address fields. This portion of configuration is
  406. // deterministic, given the parameters established or replayed so far.
  407. switch dialParams.TunnelProtocol {
  408. case protocol.TUNNEL_PROTOCOL_SSH:
  409. dialParams.DirectDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.SshPort)
  410. case protocol.TUNNEL_PROTOCOL_OBFUSCATED_SSH:
  411. dialParams.DirectDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.SshObfuscatedPort)
  412. case protocol.TUNNEL_PROTOCOL_TAPDANCE_OBFUSCATED_SSH:
  413. dialParams.DirectDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.SshObfuscatedTapdancePort)
  414. case protocol.TUNNEL_PROTOCOL_QUIC_OBFUSCATED_SSH:
  415. dialParams.DirectDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.SshObfuscatedQUICPort)
  416. case protocol.TUNNEL_PROTOCOL_FRONTED_MEEK_QUIC_OBFUSCATED_SSH:
  417. dialParams.MeekDialAddress = fmt.Sprintf("%s:443", dialParams.MeekFrontingDialAddress)
  418. dialParams.MeekHostHeader = dialParams.MeekFrontingHost
  419. if !dialParams.MeekTransformedHostName {
  420. dialParams.MeekSNIServerName = dialParams.MeekFrontingDialAddress
  421. }
  422. case protocol.TUNNEL_PROTOCOL_MARIONETTE_OBFUSCATED_SSH:
  423. // Note: port comes from marionnete "format"
  424. dialParams.DirectDialAddress = serverEntry.IpAddress
  425. case protocol.TUNNEL_PROTOCOL_FRONTED_MEEK:
  426. dialParams.MeekDialAddress = fmt.Sprintf("%s:443", dialParams.MeekFrontingDialAddress)
  427. dialParams.MeekHostHeader = dialParams.MeekFrontingHost
  428. if serverEntry.MeekFrontingDisableSNI {
  429. dialParams.MeekSNIServerName = ""
  430. } else if !dialParams.MeekTransformedHostName {
  431. dialParams.MeekSNIServerName = dialParams.MeekFrontingDialAddress
  432. }
  433. case protocol.TUNNEL_PROTOCOL_FRONTED_MEEK_HTTP:
  434. dialParams.MeekDialAddress = fmt.Sprintf("%s:80", dialParams.MeekFrontingDialAddress)
  435. dialParams.MeekHostHeader = dialParams.MeekFrontingHost
  436. case protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK:
  437. dialParams.MeekDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.MeekServerPort)
  438. if !dialParams.MeekTransformedHostName {
  439. if serverEntry.MeekServerPort == 80 {
  440. dialParams.MeekHostHeader = serverEntry.IpAddress
  441. } else {
  442. dialParams.MeekHostHeader = dialParams.MeekDialAddress
  443. }
  444. }
  445. case protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  446. protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET:
  447. dialParams.MeekDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.MeekServerPort)
  448. if !dialParams.MeekTransformedHostName {
  449. // Note: IP address in SNI field will be omitted.
  450. dialParams.MeekSNIServerName = serverEntry.IpAddress
  451. }
  452. if serverEntry.MeekServerPort == 443 {
  453. dialParams.MeekHostHeader = serverEntry.IpAddress
  454. } else {
  455. dialParams.MeekHostHeader = dialParams.MeekDialAddress
  456. }
  457. default:
  458. return nil, errors.Tracef(
  459. "unknown tunnel protocol: %s", dialParams.TunnelProtocol)
  460. }
  461. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) {
  462. host, port, _ := net.SplitHostPort(dialParams.MeekDialAddress)
  463. if p.Bool(parameters.MeekDialDomainsOnly) {
  464. if net.ParseIP(host) != nil {
  465. // No error, as this is a "not supported" case.
  466. return nil, nil
  467. }
  468. }
  469. dialParams.DialPortNumber = port
  470. // The underlying TLS will automatically disable SNI for IP address server name
  471. // values; we have this explicit check here so we record the correct value for stats.
  472. if net.ParseIP(dialParams.MeekSNIServerName) != nil {
  473. dialParams.MeekSNIServerName = ""
  474. }
  475. } else {
  476. _, dialParams.DialPortNumber, _ = net.SplitHostPort(dialParams.DirectDialAddress)
  477. }
  478. // Initialize/replay User-Agent header for HTTP upstream proxy and meek protocols.
  479. if config.UseUpstreamProxy() {
  480. // Note: UpstreamProxyURL will be validated in the dial
  481. proxyURL, err := url.Parse(config.UpstreamProxyURL)
  482. if err == nil {
  483. dialParams.UpstreamProxyType = proxyURL.Scheme
  484. }
  485. }
  486. dialCustomHeaders := makeDialCustomHeaders(config, p)
  487. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) || dialParams.UpstreamProxyType == "http" {
  488. if !isReplay || !replayUserAgent {
  489. dialParams.SelectedUserAgent, dialParams.UserAgent = selectUserAgentIfUnset(p, dialCustomHeaders)
  490. }
  491. if dialParams.SelectedUserAgent {
  492. dialCustomHeaders.Set("User-Agent", dialParams.UserAgent)
  493. }
  494. }
  495. // UpstreamProxyCustomHeaderNames is a reported metric. Just the names and
  496. // not the values are reported, in case the values are identifying.
  497. if len(config.CustomHeaders) > 0 {
  498. dialParams.UpstreamProxyCustomHeaderNames = make([]string, 0)
  499. for name := range dialCustomHeaders {
  500. if name == "User-Agent" && dialParams.SelectedUserAgent {
  501. continue
  502. }
  503. dialParams.UpstreamProxyCustomHeaderNames = append(dialParams.UpstreamProxyCustomHeaderNames, name)
  504. }
  505. }
  506. // Initialize Dial/MeekConfigs to be passed to the corresponding dialers.
  507. dialParams.dialConfig = &DialConfig{
  508. DiagnosticID: serverEntry.GetDiagnosticID(),
  509. UpstreamProxyURL: config.UpstreamProxyURL,
  510. CustomHeaders: dialCustomHeaders,
  511. BPFProgramInstructions: dialParams.BPFProgramInstructions,
  512. DeviceBinder: config.deviceBinder,
  513. DnsServerGetter: config.DnsServerGetter,
  514. IPv6Synthesizer: config.IPv6Synthesizer,
  515. TrustedCACertificatesFilename: config.TrustedCACertificatesFilename,
  516. FragmentorConfig: fragmentor.NewUpstreamConfig(p, dialParams.TunnelProtocol, dialParams.FragmentorSeed),
  517. }
  518. // Unconditionally initialize MeekResolvedIPAddress, so a valid string can
  519. // always be read.
  520. dialParams.MeekResolvedIPAddress.Store("")
  521. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) {
  522. dialParams.meekConfig = &MeekConfig{
  523. DiagnosticID: serverEntry.GetDiagnosticID(),
  524. ClientParameters: config.clientParameters,
  525. DialAddress: dialParams.MeekDialAddress,
  526. UseQUIC: protocol.TunnelProtocolUsesFrontedMeekQUIC(dialParams.TunnelProtocol),
  527. QUICVersion: dialParams.QUICVersion,
  528. UseHTTPS: protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol),
  529. TLSProfile: dialParams.TLSProfile,
  530. NoDefaultTLSSessionID: dialParams.NoDefaultTLSSessionID,
  531. RandomizedTLSProfileSeed: dialParams.RandomizedTLSProfileSeed,
  532. UseObfuscatedSessionTickets: dialParams.TunnelProtocol == protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET,
  533. SNIServerName: dialParams.MeekSNIServerName,
  534. HostHeader: dialParams.MeekHostHeader,
  535. TransformedHostName: dialParams.MeekTransformedHostName,
  536. ClientTunnelProtocol: dialParams.TunnelProtocol,
  537. MeekCookieEncryptionPublicKey: serverEntry.MeekCookieEncryptionPublicKey,
  538. MeekObfuscatedKey: serverEntry.MeekObfuscatedKey,
  539. MeekObfuscatorPaddingSeed: dialParams.MeekObfuscatorPaddingSeed,
  540. NetworkLatencyMultiplier: dialParams.NetworkLatencyMultiplier,
  541. }
  542. // Use an asynchronous callback to record the resolved IP address when
  543. // dialing a domain name. Note that DialMeek doesn't immediately
  544. // establish any HTTP connections, so the resolved IP address won't be
  545. // reported in all cases until after SSH traffic is relayed or a
  546. // endpoint request is made over the meek connection.
  547. dialParams.dialConfig.ResolvedIPCallback = func(IPAddress string) {
  548. dialParams.MeekResolvedIPAddress.Store(IPAddress)
  549. }
  550. if isTactics {
  551. dialParams.meekConfig.RoundTripperOnly = true
  552. }
  553. }
  554. return dialParams, nil
  555. }
  556. func (dialParams *DialParameters) GetDialConfig() *DialConfig {
  557. return dialParams.dialConfig
  558. }
  559. func (dialParams *DialParameters) GetMeekConfig() *MeekConfig {
  560. return dialParams.meekConfig
  561. }
  562. func (dialParams *DialParameters) Succeeded() {
  563. // When TTL is 0, don't store dial parameters.
  564. if dialParams.LastUsedTimestamp.IsZero() {
  565. return
  566. }
  567. NoticeInfo("Set dial parameters for %s", dialParams.ServerEntry.GetDiagnosticID())
  568. err := SetDialParameters(dialParams.ServerEntry.IpAddress, dialParams.NetworkID, dialParams)
  569. if err != nil {
  570. NoticeWarning("SetDialParameters failed: %s", err)
  571. }
  572. }
  573. func (dialParams *DialParameters) Failed(config *Config) {
  574. // When a tunnel fails, and the dial is a replay, clear the stored dial
  575. // parameters which are now presumed to be blocked, impaired or otherwise
  576. // no longer effective.
  577. //
  578. // It may be the case that a dial is not using stored dial parameters
  579. // (!IsReplay), and in this case we retain those dial parameters since they
  580. // were not exercised and may still be effective.
  581. //
  582. // Failed tunnel dial parameters may be retained with a configurable
  583. // probability; this is intended to help mitigate false positive failures due
  584. // to, e.g., temporary network disruptions or server load limiting.
  585. if dialParams.IsReplay &&
  586. !config.GetClientParameters().Get().WeightedCoinFlip(
  587. parameters.ReplayRetainFailedProbability) {
  588. NoticeInfo("Delete dial parameters for %s", dialParams.ServerEntry.GetDiagnosticID())
  589. err := DeleteDialParameters(dialParams.ServerEntry.IpAddress, dialParams.NetworkID)
  590. if err != nil {
  591. NoticeWarning("DeleteDialParameters failed: %s", err)
  592. }
  593. }
  594. }
  595. func (dialParams *DialParameters) GetTLSVersionForMetrics() string {
  596. tlsVersion := dialParams.TLSVersion
  597. if dialParams.NoDefaultTLSSessionID {
  598. tlsVersion += "-no_def_id"
  599. }
  600. return tlsVersion
  601. }
  602. // ExchangedDialParameters represents the subset of DialParameters that is
  603. // shared in a client-to-client exchange of server connection info.
  604. //
  605. // The purpose of client-to-client exchange if for one user that can connect
  606. // to help another user that cannot connect by sharing their connected
  607. // configuration, including the server entry and dial parameters.
  608. //
  609. // There are two concerns regarding which dial parameter fields are safe to
  610. // exchange:
  611. //
  612. // - Unlike signed server entries, there's no independent trust anchor
  613. // that can certify that the exchange data is valid.
  614. //
  615. // - While users should only perform the exchange with trusted peers,
  616. // the user's trust in their peer may be misplaced.
  617. //
  618. // This presents the possibility of attack such as the peer sending dial
  619. // parameters that could be used to trace/monitor/flag the importer; or
  620. // sending dial parameters, including dial address and SNI, to cause the peer
  621. // to appear to connect to a banned service.
  622. //
  623. // To mitigate these risks, only a subset of dial parameters are exchanged.
  624. // When exchanged dial parameters and imported and used, all unexchanged
  625. // parameters are generated locally. At this time, only the tunnel protocol is
  626. // exchanged. We consider tunnel protocol selection one of the key connection
  627. // success factors.
  628. //
  629. // In addition, the exchange peers may not be on the same network with the
  630. // same blocking and circumvention characteristics, which is another reason
  631. // to limit exchanged dial parameter values to broadly applicable fields.
  632. //
  633. // Unlike the exchanged (and otherwise acquired) server entry,
  634. // ExchangedDialParameters does not use the ServerEntry_Fields_ representation
  635. // which allows older clients to receive and store new, unknown fields. Such a
  636. // facility is less useful in this case, since exchanged dial parameters and
  637. // used immediately and have a short lifespan.
  638. //
  639. // TODO: exchange more dial parameters, such as TLS profile, QUIC version, etc.
  640. type ExchangedDialParameters struct {
  641. TunnelProtocol string
  642. }
  643. // NewExchangedDialParameters creates a new ExchangedDialParameters from a
  644. // DialParameters, including only the exchanged values.
  645. // NewExchangedDialParameters assumes the input DialParameters has been
  646. // initialized and populated by MakeDialParameters.
  647. func NewExchangedDialParameters(dialParams *DialParameters) *ExchangedDialParameters {
  648. return &ExchangedDialParameters{
  649. TunnelProtocol: dialParams.TunnelProtocol,
  650. }
  651. }
  652. // Validate checks that the ExchangedDialParameters contains only valid values
  653. // and is compatible with the specified server entry.
  654. func (dialParams *ExchangedDialParameters) Validate(serverEntry *protocol.ServerEntry) error {
  655. if !common.Contains(protocol.SupportedTunnelProtocols, dialParams.TunnelProtocol) {
  656. return errors.Tracef("unknown tunnel protocol: %s", dialParams.TunnelProtocol)
  657. }
  658. if !serverEntry.SupportsProtocol(dialParams.TunnelProtocol) {
  659. return errors.Tracef("unsupported tunnel protocol: %s", dialParams.TunnelProtocol)
  660. }
  661. return nil
  662. }
  663. // MakeDialParameters creates a new, partially intitialized DialParameters
  664. // from the values in ExchangedDialParameters. The returned DialParameters
  665. // must not be used directly for dialing. It is intended to be stored, and
  666. // then later fully initialized by MakeDialParameters.
  667. func (dialParams *ExchangedDialParameters) MakeDialParameters(
  668. config *Config,
  669. p parameters.ClientParametersAccessor,
  670. serverEntry *protocol.ServerEntry) *DialParameters {
  671. return &DialParameters{
  672. IsExchanged: true,
  673. LastUsedTimestamp: time.Now(),
  674. LastUsedConfigStateHash: getConfigStateHash(config, p, serverEntry),
  675. TunnelProtocol: dialParams.TunnelProtocol,
  676. }
  677. }
  678. func getConfigStateHash(
  679. config *Config,
  680. p parameters.ClientParametersAccessor,
  681. serverEntry *protocol.ServerEntry) []byte {
  682. // The config state hash should reflect config, tactics, and server entry
  683. // settings that impact the dial parameters. The hash should change if any
  684. // of these input values change in a way that invalidates any stored dial
  685. // parameters.
  686. // MD5 hash is used solely as a data checksum and not for any security
  687. // purpose.
  688. hash := md5.New()
  689. // Add a hash of relevant config fields.
  690. // Limitation: the config hash may change even when tactics will override the
  691. // changed config field.
  692. hash.Write(config.dialParametersHash)
  693. // Add the active tactics tag.
  694. hash.Write([]byte(p.Tag()))
  695. // Add the server entry version and local timestamp, both of which should
  696. // change when the server entry contents change and/or a new local copy is
  697. // imported.
  698. // TODO: marshal entire server entry?
  699. var serverEntryConfigurationVersion [8]byte
  700. binary.BigEndian.PutUint64(
  701. serverEntryConfigurationVersion[:],
  702. uint64(serverEntry.ConfigurationVersion))
  703. hash.Write(serverEntryConfigurationVersion[:])
  704. hash.Write([]byte(serverEntry.LocalTimestamp))
  705. return hash.Sum(nil)
  706. }
  707. func selectFrontingParameters(serverEntry *protocol.ServerEntry) (string, string, error) {
  708. frontingDialHost := ""
  709. frontingHost := ""
  710. if len(serverEntry.MeekFrontingAddressesRegex) > 0 {
  711. // Generate a front address based on the regex.
  712. var err error
  713. frontingDialHost, err = regen.Generate(serverEntry.MeekFrontingAddressesRegex)
  714. if err != nil {
  715. return "", "", errors.Trace(err)
  716. }
  717. } else {
  718. // Randomly select, for this connection attempt, one front address for
  719. // fronting-capable servers.
  720. if len(serverEntry.MeekFrontingAddresses) == 0 {
  721. return "", "", errors.TraceNew("MeekFrontingAddresses is empty")
  722. }
  723. index := prng.Intn(len(serverEntry.MeekFrontingAddresses))
  724. frontingDialHost = serverEntry.MeekFrontingAddresses[index]
  725. }
  726. if len(serverEntry.MeekFrontingHosts) > 0 {
  727. index := prng.Intn(len(serverEntry.MeekFrontingHosts))
  728. frontingHost = serverEntry.MeekFrontingHosts[index]
  729. } else {
  730. // Backwards compatibility case
  731. frontingHost = serverEntry.MeekFrontingHost
  732. }
  733. return frontingDialHost, frontingHost, nil
  734. }
  735. func selectQUICVersion(allowObfuscatedQUIC bool, p parameters.ClientParametersAccessor) string {
  736. limitQUICVersions := p.QUICVersions(parameters.LimitQUICVersions)
  737. quicVersions := make([]string, 0)
  738. for _, quicVersion := range protocol.SupportedQUICVersions {
  739. if len(limitQUICVersions) > 0 &&
  740. !common.Contains(limitQUICVersions, quicVersion) {
  741. continue
  742. }
  743. if !allowObfuscatedQUIC &&
  744. protocol.QUICVersionIsObfuscated(quicVersion) {
  745. continue
  746. }
  747. // Temporary: disallow IETF QUIC where OBFUSCATED is disallowed.
  748. if !allowObfuscatedQUIC &&
  749. quicVersion == protocol.QUIC_VERSION_IETF_DRAFT24 {
  750. continue
  751. }
  752. quicVersions = append(quicVersions, quicVersion)
  753. }
  754. if len(quicVersions) == 0 {
  755. return ""
  756. }
  757. choice := prng.Intn(len(quicVersions))
  758. return quicVersions[choice]
  759. }
  760. // selectUserAgentIfUnset selects a User-Agent header if one is not set.
  761. func selectUserAgentIfUnset(
  762. p parameters.ClientParametersAccessor, headers http.Header) (bool, string) {
  763. if _, ok := headers["User-Agent"]; !ok {
  764. userAgent := ""
  765. if p.WeightedCoinFlip(parameters.PickUserAgentProbability) {
  766. userAgent = values.GetUserAgent()
  767. }
  768. return true, userAgent
  769. }
  770. return false, ""
  771. }
  772. func makeDialCustomHeaders(
  773. config *Config,
  774. p parameters.ClientParametersAccessor) http.Header {
  775. dialCustomHeaders := make(http.Header)
  776. if config.CustomHeaders != nil {
  777. for k, v := range config.CustomHeaders {
  778. dialCustomHeaders[k] = make([]string, len(v))
  779. copy(dialCustomHeaders[k], v)
  780. }
  781. }
  782. additionalCustomHeaders := p.HTTPHeaders(parameters.AdditionalCustomHeaders)
  783. for k, v := range additionalCustomHeaders {
  784. dialCustomHeaders[k] = make([]string, len(v))
  785. copy(dialCustomHeaders[k], v)
  786. }
  787. return dialCustomHeaders
  788. }