dialParameters.go 51 KB

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