dialParameters.go 36 KB

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