dialParameters.go 44 KB

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