dialParameters.go 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010
  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 !dialParams.MeekTransformedHostName {
  430. dialParams.MeekSNIServerName = dialParams.MeekFrontingDialAddress
  431. }
  432. case protocol.TUNNEL_PROTOCOL_MARIONETTE_OBFUSCATED_SSH:
  433. // Note: port comes from marionnete "format"
  434. dialParams.DirectDialAddress = serverEntry.IpAddress
  435. case protocol.TUNNEL_PROTOCOL_FRONTED_MEEK:
  436. dialParams.MeekDialAddress = fmt.Sprintf("%s:443", dialParams.MeekFrontingDialAddress)
  437. dialParams.MeekHostHeader = dialParams.MeekFrontingHost
  438. if serverEntry.MeekFrontingDisableSNI {
  439. dialParams.MeekSNIServerName = ""
  440. } else if !dialParams.MeekTransformedHostName {
  441. dialParams.MeekSNIServerName = dialParams.MeekFrontingDialAddress
  442. }
  443. case protocol.TUNNEL_PROTOCOL_FRONTED_MEEK_HTTP:
  444. dialParams.MeekDialAddress = fmt.Sprintf("%s:80", dialParams.MeekFrontingDialAddress)
  445. dialParams.MeekHostHeader = dialParams.MeekFrontingHost
  446. case protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK:
  447. dialParams.MeekDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.MeekServerPort)
  448. if !dialParams.MeekTransformedHostName {
  449. if serverEntry.MeekServerPort == 80 {
  450. dialParams.MeekHostHeader = serverEntry.IpAddress
  451. } else {
  452. dialParams.MeekHostHeader = dialParams.MeekDialAddress
  453. }
  454. }
  455. case protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  456. protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET:
  457. dialParams.MeekDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.MeekServerPort)
  458. if !dialParams.MeekTransformedHostName {
  459. // Note: IP address in SNI field will be omitted.
  460. dialParams.MeekSNIServerName = serverEntry.IpAddress
  461. }
  462. if serverEntry.MeekServerPort == 443 {
  463. dialParams.MeekHostHeader = serverEntry.IpAddress
  464. } else {
  465. dialParams.MeekHostHeader = dialParams.MeekDialAddress
  466. }
  467. default:
  468. return nil, errors.Tracef(
  469. "unknown tunnel protocol: %s", dialParams.TunnelProtocol)
  470. }
  471. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) {
  472. host, port, _ := net.SplitHostPort(dialParams.MeekDialAddress)
  473. if p.Bool(parameters.MeekDialDomainsOnly) {
  474. if net.ParseIP(host) != nil {
  475. // No error, as this is a "not supported" case.
  476. return nil, nil
  477. }
  478. }
  479. dialParams.DialPortNumber = port
  480. // The underlying TLS will automatically disable SNI for IP address server name
  481. // values; we have this explicit check here so we record the correct value for stats.
  482. if net.ParseIP(dialParams.MeekSNIServerName) != nil {
  483. dialParams.MeekSNIServerName = ""
  484. }
  485. } else {
  486. _, dialParams.DialPortNumber, _ = net.SplitHostPort(dialParams.DirectDialAddress)
  487. }
  488. // Initialize/replay User-Agent header for HTTP upstream proxy and meek protocols.
  489. if config.UseUpstreamProxy() {
  490. // Note: UpstreamProxyURL will be validated in the dial
  491. proxyURL, err := url.Parse(config.UpstreamProxyURL)
  492. if err == nil {
  493. dialParams.UpstreamProxyType = proxyURL.Scheme
  494. }
  495. }
  496. dialCustomHeaders := makeDialCustomHeaders(config, p)
  497. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) || dialParams.UpstreamProxyType == "http" {
  498. if !isReplay || !replayUserAgent {
  499. dialParams.SelectedUserAgent, dialParams.UserAgent = selectUserAgentIfUnset(p, dialCustomHeaders)
  500. }
  501. if dialParams.SelectedUserAgent {
  502. dialCustomHeaders.Set("User-Agent", dialParams.UserAgent)
  503. }
  504. }
  505. // UpstreamProxyCustomHeaderNames is a reported metric. Just the names and
  506. // not the values are reported, in case the values are identifying.
  507. if len(config.CustomHeaders) > 0 {
  508. dialParams.UpstreamProxyCustomHeaderNames = make([]string, 0)
  509. for name := range dialCustomHeaders {
  510. if name == "User-Agent" && dialParams.SelectedUserAgent {
  511. continue
  512. }
  513. dialParams.UpstreamProxyCustomHeaderNames = append(dialParams.UpstreamProxyCustomHeaderNames, name)
  514. }
  515. }
  516. // Initialize Dial/MeekConfigs to be passed to the corresponding dialers.
  517. dialParams.dialConfig = &DialConfig{
  518. DiagnosticID: serverEntry.GetDiagnosticID(),
  519. UpstreamProxyURL: config.UpstreamProxyURL,
  520. CustomHeaders: dialCustomHeaders,
  521. BPFProgramInstructions: dialParams.BPFProgramInstructions,
  522. DeviceBinder: config.deviceBinder,
  523. DnsServerGetter: config.DnsServerGetter,
  524. IPv6Synthesizer: config.IPv6Synthesizer,
  525. TrustedCACertificatesFilename: config.TrustedCACertificatesFilename,
  526. FragmentorConfig: fragmentor.NewUpstreamConfig(p, dialParams.TunnelProtocol, dialParams.FragmentorSeed),
  527. }
  528. // Unconditionally initialize MeekResolvedIPAddress, so a valid string can
  529. // always be read.
  530. dialParams.MeekResolvedIPAddress.Store("")
  531. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) {
  532. dialParams.meekConfig = &MeekConfig{
  533. DiagnosticID: serverEntry.GetDiagnosticID(),
  534. ClientParameters: config.clientParameters,
  535. DialAddress: dialParams.MeekDialAddress,
  536. UseQUIC: protocol.TunnelProtocolUsesFrontedMeekQUIC(dialParams.TunnelProtocol),
  537. QUICVersion: dialParams.QUICVersion,
  538. UseHTTPS: protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol),
  539. TLSProfile: dialParams.TLSProfile,
  540. NoDefaultTLSSessionID: dialParams.NoDefaultTLSSessionID,
  541. RandomizedTLSProfileSeed: dialParams.RandomizedTLSProfileSeed,
  542. UseObfuscatedSessionTickets: dialParams.TunnelProtocol == protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET,
  543. SNIServerName: dialParams.MeekSNIServerName,
  544. HostHeader: dialParams.MeekHostHeader,
  545. TransformedHostName: dialParams.MeekTransformedHostName,
  546. ClientTunnelProtocol: dialParams.TunnelProtocol,
  547. MeekCookieEncryptionPublicKey: serverEntry.MeekCookieEncryptionPublicKey,
  548. MeekObfuscatedKey: serverEntry.MeekObfuscatedKey,
  549. MeekObfuscatorPaddingSeed: dialParams.MeekObfuscatorPaddingSeed,
  550. NetworkLatencyMultiplier: dialParams.NetworkLatencyMultiplier,
  551. }
  552. // Use an asynchronous callback to record the resolved IP address when
  553. // dialing a domain name. Note that DialMeek doesn't immediately
  554. // establish any HTTP connections, so the resolved IP address won't be
  555. // reported in all cases until after SSH traffic is relayed or a
  556. // endpoint request is made over the meek connection.
  557. dialParams.dialConfig.ResolvedIPCallback = func(IPAddress string) {
  558. dialParams.MeekResolvedIPAddress.Store(IPAddress)
  559. }
  560. if isTactics {
  561. dialParams.meekConfig.RoundTripperOnly = true
  562. }
  563. }
  564. return dialParams, nil
  565. }
  566. func (dialParams *DialParameters) GetDialConfig() *DialConfig {
  567. return dialParams.dialConfig
  568. }
  569. func (dialParams *DialParameters) GetMeekConfig() *MeekConfig {
  570. return dialParams.meekConfig
  571. }
  572. // GetNetworkType returns a network type name, suitable for metrics, which is
  573. // derived from the network ID.
  574. func (dialParams *DialParameters) GetNetworkType() string {
  575. // Unlike the logic in loggingNetworkIDGetter.GetNetworkID, we don't take the
  576. // arbitrary text before the first "-" since some platforms without network
  577. // detection support stub in random values to enable tactics. Instead we
  578. // check for and use the common network type prefixes currently used in
  579. // NetworkIDGetter implementations.
  580. if strings.HasPrefix(dialParams.NetworkID, "WIFI") {
  581. return "WIFI"
  582. }
  583. if strings.HasPrefix(dialParams.NetworkID, "MOBILE") {
  584. return "MOBILE"
  585. }
  586. return "UNKNOWN"
  587. }
  588. func (dialParams *DialParameters) Succeeded() {
  589. // When TTL is 0, don't store dial parameters.
  590. if dialParams.LastUsedTimestamp.IsZero() {
  591. return
  592. }
  593. NoticeInfo("Set dial parameters for %s", dialParams.ServerEntry.GetDiagnosticID())
  594. err := SetDialParameters(dialParams.ServerEntry.IpAddress, dialParams.NetworkID, dialParams)
  595. if err != nil {
  596. NoticeWarning("SetDialParameters failed: %s", err)
  597. }
  598. }
  599. func (dialParams *DialParameters) Failed(config *Config) {
  600. // When a tunnel fails, and the dial is a replay, clear the stored dial
  601. // parameters which are now presumed to be blocked, impaired or otherwise
  602. // no longer effective.
  603. //
  604. // It may be the case that a dial is not using stored dial parameters
  605. // (!IsReplay), and in this case we retain those dial parameters since they
  606. // were not exercised and may still be effective.
  607. //
  608. // Failed tunnel dial parameters may be retained with a configurable
  609. // probability; this is intended to help mitigate false positive failures due
  610. // to, e.g., temporary network disruptions or server load limiting.
  611. if dialParams.IsReplay &&
  612. !config.GetClientParameters().Get().WeightedCoinFlip(
  613. parameters.ReplayRetainFailedProbability) {
  614. NoticeInfo("Delete dial parameters for %s", dialParams.ServerEntry.GetDiagnosticID())
  615. err := DeleteDialParameters(dialParams.ServerEntry.IpAddress, dialParams.NetworkID)
  616. if err != nil {
  617. NoticeWarning("DeleteDialParameters failed: %s", err)
  618. }
  619. }
  620. }
  621. func (dialParams *DialParameters) GetTLSVersionForMetrics() string {
  622. tlsVersion := dialParams.TLSVersion
  623. if dialParams.NoDefaultTLSSessionID {
  624. tlsVersion += "-no_def_id"
  625. }
  626. return tlsVersion
  627. }
  628. // ExchangedDialParameters represents the subset of DialParameters that is
  629. // shared in a client-to-client exchange of server connection info.
  630. //
  631. // The purpose of client-to-client exchange if for one user that can connect
  632. // to help another user that cannot connect by sharing their connected
  633. // configuration, including the server entry and dial parameters.
  634. //
  635. // There are two concerns regarding which dial parameter fields are safe to
  636. // exchange:
  637. //
  638. // - Unlike signed server entries, there's no independent trust anchor
  639. // that can certify that the exchange data is valid.
  640. //
  641. // - While users should only perform the exchange with trusted peers,
  642. // the user's trust in their peer may be misplaced.
  643. //
  644. // This presents the possibility of attack such as the peer sending dial
  645. // parameters that could be used to trace/monitor/flag the importer; or
  646. // sending dial parameters, including dial address and SNI, to cause the peer
  647. // to appear to connect to a banned service.
  648. //
  649. // To mitigate these risks, only a subset of dial parameters are exchanged.
  650. // When exchanged dial parameters and imported and used, all unexchanged
  651. // parameters are generated locally. At this time, only the tunnel protocol is
  652. // exchanged. We consider tunnel protocol selection one of the key connection
  653. // success factors.
  654. //
  655. // In addition, the exchange peers may not be on the same network with the
  656. // same blocking and circumvention characteristics, which is another reason
  657. // to limit exchanged dial parameter values to broadly applicable fields.
  658. //
  659. // Unlike the exchanged (and otherwise acquired) server entry,
  660. // ExchangedDialParameters does not use the ServerEntry_Fields_ representation
  661. // which allows older clients to receive and store new, unknown fields. Such a
  662. // facility is less useful in this case, since exchanged dial parameters and
  663. // used immediately and have a short lifespan.
  664. //
  665. // TODO: exchange more dial parameters, such as TLS profile, QUIC version, etc.
  666. type ExchangedDialParameters struct {
  667. TunnelProtocol string
  668. }
  669. // NewExchangedDialParameters creates a new ExchangedDialParameters from a
  670. // DialParameters, including only the exchanged values.
  671. // NewExchangedDialParameters assumes the input DialParameters has been
  672. // initialized and populated by MakeDialParameters.
  673. func NewExchangedDialParameters(dialParams *DialParameters) *ExchangedDialParameters {
  674. return &ExchangedDialParameters{
  675. TunnelProtocol: dialParams.TunnelProtocol,
  676. }
  677. }
  678. // Validate checks that the ExchangedDialParameters contains only valid values
  679. // and is compatible with the specified server entry.
  680. func (dialParams *ExchangedDialParameters) Validate(serverEntry *protocol.ServerEntry) error {
  681. if !common.Contains(protocol.SupportedTunnelProtocols, dialParams.TunnelProtocol) {
  682. return errors.Tracef("unknown tunnel protocol: %s", dialParams.TunnelProtocol)
  683. }
  684. if !serverEntry.SupportsProtocol(dialParams.TunnelProtocol) {
  685. return errors.Tracef("unsupported tunnel protocol: %s", dialParams.TunnelProtocol)
  686. }
  687. return nil
  688. }
  689. // MakeDialParameters creates a new, partially intitialized DialParameters
  690. // from the values in ExchangedDialParameters. The returned DialParameters
  691. // must not be used directly for dialing. It is intended to be stored, and
  692. // then later fully initialized by MakeDialParameters.
  693. func (dialParams *ExchangedDialParameters) MakeDialParameters(
  694. config *Config,
  695. p parameters.ClientParametersAccessor,
  696. serverEntry *protocol.ServerEntry) *DialParameters {
  697. return &DialParameters{
  698. IsExchanged: true,
  699. LastUsedTimestamp: time.Now(),
  700. LastUsedConfigStateHash: getConfigStateHash(config, p, serverEntry),
  701. TunnelProtocol: dialParams.TunnelProtocol,
  702. }
  703. }
  704. func getConfigStateHash(
  705. config *Config,
  706. p parameters.ClientParametersAccessor,
  707. serverEntry *protocol.ServerEntry) []byte {
  708. // The config state hash should reflect config, tactics, and server entry
  709. // settings that impact the dial parameters. The hash should change if any
  710. // of these input values change in a way that invalidates any stored dial
  711. // parameters.
  712. // MD5 hash is used solely as a data checksum and not for any security
  713. // purpose.
  714. hash := md5.New()
  715. // Add a hash of relevant config fields.
  716. // Limitation: the config hash may change even when tactics will override the
  717. // changed config field.
  718. hash.Write(config.dialParametersHash)
  719. // Add the active tactics tag.
  720. hash.Write([]byte(p.Tag()))
  721. // Add the server entry version and local timestamp, both of which should
  722. // change when the server entry contents change and/or a new local copy is
  723. // imported.
  724. // TODO: marshal entire server entry?
  725. var serverEntryConfigurationVersion [8]byte
  726. binary.BigEndian.PutUint64(
  727. serverEntryConfigurationVersion[:],
  728. uint64(serverEntry.ConfigurationVersion))
  729. hash.Write(serverEntryConfigurationVersion[:])
  730. hash.Write([]byte(serverEntry.LocalTimestamp))
  731. return hash.Sum(nil)
  732. }
  733. func selectFrontingParameters(serverEntry *protocol.ServerEntry) (string, string, error) {
  734. frontingDialHost := ""
  735. frontingHost := ""
  736. if len(serverEntry.MeekFrontingAddressesRegex) > 0 {
  737. // Generate a front address based on the regex.
  738. var err error
  739. frontingDialHost, err = regen.Generate(serverEntry.MeekFrontingAddressesRegex)
  740. if err != nil {
  741. return "", "", errors.Trace(err)
  742. }
  743. } else {
  744. // Randomly select, for this connection attempt, one front address for
  745. // fronting-capable servers.
  746. if len(serverEntry.MeekFrontingAddresses) == 0 {
  747. return "", "", errors.TraceNew("MeekFrontingAddresses is empty")
  748. }
  749. index := prng.Intn(len(serverEntry.MeekFrontingAddresses))
  750. frontingDialHost = serverEntry.MeekFrontingAddresses[index]
  751. }
  752. if len(serverEntry.MeekFrontingHosts) > 0 {
  753. index := prng.Intn(len(serverEntry.MeekFrontingHosts))
  754. frontingHost = serverEntry.MeekFrontingHosts[index]
  755. } else {
  756. // Backwards compatibility case
  757. frontingHost = serverEntry.MeekFrontingHost
  758. }
  759. return frontingDialHost, frontingHost, nil
  760. }
  761. func selectQUICVersion(
  762. isFronted bool,
  763. frontingProviderID string,
  764. p parameters.ClientParametersAccessor) string {
  765. limitQUICVersions := p.QUICVersions(parameters.LimitQUICVersions)
  766. var disableQUICVersions protocol.QUICVersions
  767. if isFronted {
  768. if frontingProviderID == "" {
  769. // Legacy server entry case
  770. disableQUICVersions = protocol.QUICVersions{protocol.QUIC_VERSION_IETF_DRAFT24}
  771. } else {
  772. disableQUICVersions = p.LabeledQUICVersions(
  773. parameters.DisableFrontingProviderQUICVersions, frontingProviderID)
  774. }
  775. }
  776. quicVersions := make([]string, 0)
  777. for _, quicVersion := range protocol.SupportedQUICVersions {
  778. if len(limitQUICVersions) > 0 &&
  779. !common.Contains(limitQUICVersions, quicVersion) {
  780. continue
  781. }
  782. if isFronted &&
  783. protocol.QUICVersionIsObfuscated(quicVersion) {
  784. continue
  785. }
  786. if common.Contains(disableQUICVersions, quicVersion) {
  787. continue
  788. }
  789. quicVersions = append(quicVersions, quicVersion)
  790. }
  791. if len(quicVersions) == 0 {
  792. return ""
  793. }
  794. choice := prng.Intn(len(quicVersions))
  795. return quicVersions[choice]
  796. }
  797. // selectUserAgentIfUnset selects a User-Agent header if one is not set.
  798. func selectUserAgentIfUnset(
  799. p parameters.ClientParametersAccessor, headers http.Header) (bool, string) {
  800. if _, ok := headers["User-Agent"]; !ok {
  801. userAgent := ""
  802. if p.WeightedCoinFlip(parameters.PickUserAgentProbability) {
  803. userAgent = values.GetUserAgent()
  804. }
  805. return true, userAgent
  806. }
  807. return false, ""
  808. }
  809. func makeDialCustomHeaders(
  810. config *Config,
  811. p parameters.ClientParametersAccessor) http.Header {
  812. dialCustomHeaders := make(http.Header)
  813. if config.CustomHeaders != nil {
  814. for k, v := range config.CustomHeaders {
  815. dialCustomHeaders[k] = make([]string, len(v))
  816. copy(dialCustomHeaders[k], v)
  817. }
  818. }
  819. additionalCustomHeaders := p.HTTPHeaders(parameters.AdditionalCustomHeaders)
  820. for k, v := range additionalCustomHeaders {
  821. dialCustomHeaders[k] = make([]string, len(v))
  822. copy(dialCustomHeaders[k], v)
  823. }
  824. return dialCustomHeaders
  825. }