dialParameters.go 42 KB

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