dialParameters.go 36 KB

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