dialParameters.go 36 KB

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