dialParameters.go 35 KB

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