dialParameters.go 37 KB

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