dialParameters.go 36 KB

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