dialParameters.go 43 KB

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