dialParameters.go 37 KB

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