dialParameters.go 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435
  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 retaing, 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. if protocol.QUICVersionHasRandomizedClientHello(dialParams.QUICVersion) {
  568. dialParams.QUICClientHelloSeed, err = prng.NewSeed()
  569. if err != nil {
  570. return nil, errors.Trace(err)
  571. }
  572. }
  573. dialParams.QUICDisablePathMTUDiscovery =
  574. protocol.QUICVersionUsesPathMTUDiscovery(dialParams.QUICVersion) &&
  575. p.WeightedCoinFlip(parameters.QUICDisableClientPathMTUDiscoveryProbability)
  576. }
  577. if (!isReplay || !replayObfuscatedQUIC) &&
  578. protocol.QUICVersionIsObfuscated(dialParams.QUICVersion) {
  579. dialParams.ObfuscatedQUICPaddingSeed, err = prng.NewSeed()
  580. if err != nil {
  581. return nil, errors.Trace(err)
  582. }
  583. }
  584. if !isReplay || !replayLivenessTest {
  585. // TODO: initialize only when LivenessTestMaxUp/DownstreamBytes > 0?
  586. dialParams.LivenessTestSeed, err = prng.NewSeed()
  587. if err != nil {
  588. return nil, errors.Trace(err)
  589. }
  590. }
  591. if !isReplay || !replayAPIRequestPadding {
  592. dialParams.APIRequestPaddingSeed, err = prng.NewSeed()
  593. if err != nil {
  594. return nil, errors.Trace(err)
  595. }
  596. }
  597. // Initialize dialParams.ResolveParameters for dials that will resolve
  598. // domain names, which currently includes fronted meek and Conjure API
  599. // registration, where the dial address is not an IP address.
  600. //
  601. // dialParams.ResolveParameters must be nil when the dial address is an IP
  602. // address to ensure that no DNS dial parameters are reported in metrics
  603. // or diagnostics when when no domain is resolved.
  604. useResolver := (protocol.TunnelProtocolUsesFrontedMeek(dialParams.TunnelProtocol) ||
  605. dialParams.ConjureAPIRegistration) &&
  606. net.ParseIP(dialParams.MeekFrontingDialAddress) == nil
  607. if (!isReplay || !replayResolveParameters) && useResolver {
  608. dialParams.ResolveParameters, err = dialParams.resolver.MakeResolveParameters(
  609. p, dialParams.FrontingProviderID)
  610. if err != nil {
  611. return nil, errors.Trace(err)
  612. }
  613. }
  614. if !isReplay || !replayHoldOffTunnel {
  615. if common.Contains(
  616. p.TunnelProtocols(parameters.HoldOffTunnelProtocols), dialParams.TunnelProtocol) ||
  617. (protocol.TunnelProtocolUsesFrontedMeek(dialParams.TunnelProtocol) &&
  618. common.Contains(
  619. p.Strings(parameters.HoldOffTunnelFrontingProviderIDs),
  620. dialParams.FrontingProviderID)) {
  621. if p.WeightedCoinFlip(parameters.HoldOffTunnelProbability) {
  622. dialParams.HoldOffTunnelDuration = prng.Period(
  623. p.Duration(parameters.HoldOffTunnelMinDuration),
  624. p.Duration(parameters.HoldOffTunnelMaxDuration))
  625. }
  626. }
  627. }
  628. if (!isReplay || !replayHTTPTransformerParameters) && protocol.TunnelProtocolUsesMeekHTTP(dialParams.TunnelProtocol) {
  629. isFronted := protocol.TunnelProtocolUsesFrontedMeek(dialParams.TunnelProtocol)
  630. params, err := makeHTTPTransformerParameters(config.GetParameters().Get(), serverEntry.FrontingProviderID, isFronted)
  631. if err != nil {
  632. return nil, errors.Trace(err)
  633. }
  634. if params.ProtocolTransformSpec != nil {
  635. dialParams.HTTPTransformerParameters = params
  636. } else {
  637. dialParams.HTTPTransformerParameters = nil
  638. }
  639. }
  640. // Set dial address fields. This portion of configuration is
  641. // deterministic, given the parameters established or replayed so far.
  642. dialPortNumber, err := serverEntry.GetDialPortNumber(dialParams.TunnelProtocol)
  643. if err != nil {
  644. return nil, errors.Trace(err)
  645. }
  646. dialParams.DialPortNumber = strconv.Itoa(dialPortNumber)
  647. switch dialParams.TunnelProtocol {
  648. case protocol.TUNNEL_PROTOCOL_SSH,
  649. protocol.TUNNEL_PROTOCOL_OBFUSCATED_SSH,
  650. protocol.TUNNEL_PROTOCOL_TAPDANCE_OBFUSCATED_SSH,
  651. protocol.TUNNEL_PROTOCOL_CONJURE_OBFUSCATED_SSH,
  652. protocol.TUNNEL_PROTOCOL_QUIC_OBFUSCATED_SSH:
  653. dialParams.DirectDialAddress = net.JoinHostPort(serverEntry.IpAddress, dialParams.DialPortNumber)
  654. case protocol.TUNNEL_PROTOCOL_FRONTED_MEEK,
  655. protocol.TUNNEL_PROTOCOL_FRONTED_MEEK_QUIC_OBFUSCATED_SSH:
  656. dialParams.MeekDialAddress = net.JoinHostPort(dialParams.MeekFrontingDialAddress, dialParams.DialPortNumber)
  657. dialParams.MeekHostHeader = dialParams.MeekFrontingHost
  658. if serverEntry.MeekFrontingDisableSNI {
  659. dialParams.MeekSNIServerName = ""
  660. // When SNI is omitted, the transformed host name is not used.
  661. dialParams.MeekTransformedHostName = false
  662. } else if !dialParams.MeekTransformedHostName {
  663. dialParams.MeekSNIServerName = dialParams.MeekFrontingDialAddress
  664. }
  665. case protocol.TUNNEL_PROTOCOL_FRONTED_MEEK_HTTP:
  666. dialParams.MeekDialAddress = net.JoinHostPort(dialParams.MeekFrontingDialAddress, dialParams.DialPortNumber)
  667. dialParams.MeekHostHeader = dialParams.MeekFrontingHost
  668. // For FRONTED HTTP, the Host header cannot be transformed.
  669. dialParams.MeekTransformedHostName = false
  670. case protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK:
  671. dialParams.MeekDialAddress = net.JoinHostPort(serverEntry.IpAddress, dialParams.DialPortNumber)
  672. if !dialParams.MeekTransformedHostName {
  673. if dialPortNumber == 80 {
  674. dialParams.MeekHostHeader = serverEntry.IpAddress
  675. } else {
  676. dialParams.MeekHostHeader = dialParams.MeekDialAddress
  677. }
  678. }
  679. case protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  680. protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET:
  681. dialParams.MeekDialAddress = net.JoinHostPort(serverEntry.IpAddress, dialParams.DialPortNumber)
  682. if !dialParams.MeekTransformedHostName {
  683. // Note: IP address in SNI field will be omitted.
  684. dialParams.MeekSNIServerName = serverEntry.IpAddress
  685. }
  686. if dialPortNumber == 443 {
  687. dialParams.MeekHostHeader = serverEntry.IpAddress
  688. } else {
  689. dialParams.MeekHostHeader = dialParams.MeekDialAddress
  690. }
  691. default:
  692. return nil, errors.Tracef(
  693. "unknown tunnel protocol: %s", dialParams.TunnelProtocol)
  694. }
  695. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) {
  696. host, _, _ := net.SplitHostPort(dialParams.MeekDialAddress)
  697. if p.Bool(parameters.MeekDialDomainsOnly) {
  698. if net.ParseIP(host) != nil {
  699. // No error, as this is a "not supported" case.
  700. return nil, nil
  701. }
  702. }
  703. // The underlying TLS implementation will automatically omit SNI for
  704. // IP address server name values; we have this explicit check here so
  705. // we record the correct value for stats.
  706. if net.ParseIP(dialParams.MeekSNIServerName) != nil {
  707. dialParams.MeekSNIServerName = ""
  708. }
  709. }
  710. // Initialize/replay User-Agent header for HTTP upstream proxy and meek protocols.
  711. if config.UseUpstreamProxy() {
  712. // Note: UpstreamProxyURL will be validated in the dial
  713. proxyURL, err := common.SafeParseURL(config.UpstreamProxyURL)
  714. if err == nil {
  715. dialParams.UpstreamProxyType = proxyURL.Scheme
  716. }
  717. }
  718. dialCustomHeaders := makeDialCustomHeaders(config, p)
  719. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) ||
  720. dialParams.UpstreamProxyType == "http" ||
  721. dialParams.ConjureAPIRegistration {
  722. if !isReplay || !replayUserAgent {
  723. dialParams.SelectedUserAgent, dialParams.UserAgent = selectUserAgentIfUnset(p, dialCustomHeaders)
  724. }
  725. if dialParams.SelectedUserAgent {
  726. dialCustomHeaders.Set("User-Agent", dialParams.UserAgent)
  727. }
  728. }
  729. // UpstreamProxyCustomHeaderNames is a reported metric. Just the names and
  730. // not the values are reported, in case the values are identifying.
  731. if len(config.CustomHeaders) > 0 {
  732. dialParams.UpstreamProxyCustomHeaderNames = make([]string, 0)
  733. for name := range dialCustomHeaders {
  734. if name == "User-Agent" && dialParams.SelectedUserAgent {
  735. continue
  736. }
  737. dialParams.UpstreamProxyCustomHeaderNames = append(dialParams.UpstreamProxyCustomHeaderNames, name)
  738. }
  739. }
  740. // Initialize Dial/MeekConfigs to be passed to the corresponding dialers.
  741. // Custom ResolveParameters are set only when useResolver is true, but
  742. // DialConfig.ResolveIP is required and wired up unconditionally. Any
  743. // misconfigured or miscoded domain dial cases will use default
  744. // ResolveParameters.
  745. //
  746. // ResolveIP will use the networkID obtained above, as it will be used
  747. // almost immediately, instead of incurring the overhead of calling
  748. // GetNetworkID again.
  749. resolveIP := func(ctx context.Context, hostname string) ([]net.IP, error) {
  750. IPs, err := dialParams.resolver.ResolveIP(
  751. ctx,
  752. networkID,
  753. dialParams.ResolveParameters,
  754. hostname)
  755. if err != nil {
  756. return nil, errors.Trace(err)
  757. }
  758. return IPs, nil
  759. }
  760. dialParams.dialConfig = &DialConfig{
  761. DiagnosticID: serverEntry.GetDiagnosticID(),
  762. UpstreamProxyURL: config.UpstreamProxyURL,
  763. CustomHeaders: dialCustomHeaders,
  764. BPFProgramInstructions: dialParams.BPFProgramInstructions,
  765. DeviceBinder: config.deviceBinder,
  766. IPv6Synthesizer: config.IPv6Synthesizer,
  767. ResolveIP: resolveIP,
  768. TrustedCACertificatesFilename: config.TrustedCACertificatesFilename,
  769. FragmentorConfig: fragmentor.NewUpstreamConfig(p, dialParams.TunnelProtocol, dialParams.FragmentorSeed),
  770. UpstreamProxyErrorCallback: upstreamProxyErrorCallback,
  771. }
  772. // Unconditionally initialize MeekResolvedIPAddress, so a valid string can
  773. // always be read.
  774. dialParams.MeekResolvedIPAddress.Store("")
  775. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) ||
  776. dialParams.ConjureAPIRegistration {
  777. dialParams.meekConfig = &MeekConfig{
  778. DiagnosticID: serverEntry.GetDiagnosticID(),
  779. Parameters: config.GetParameters(),
  780. DialAddress: dialParams.MeekDialAddress,
  781. UseQUIC: protocol.TunnelProtocolUsesFrontedMeekQUIC(dialParams.TunnelProtocol),
  782. QUICVersion: dialParams.QUICVersion,
  783. QUICClientHelloSeed: dialParams.QUICClientHelloSeed,
  784. QUICDisablePathMTUDiscovery: dialParams.QUICDisablePathMTUDiscovery,
  785. UseHTTPS: usingTLS,
  786. TLSProfile: dialParams.TLSProfile,
  787. LegacyPassthrough: serverEntry.ProtocolUsesLegacyPassthrough(dialParams.TunnelProtocol),
  788. NoDefaultTLSSessionID: dialParams.NoDefaultTLSSessionID,
  789. RandomizedTLSProfileSeed: dialParams.RandomizedTLSProfileSeed,
  790. UseObfuscatedSessionTickets: dialParams.TunnelProtocol == protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET,
  791. SNIServerName: dialParams.MeekSNIServerName,
  792. VerifyServerName: dialParams.MeekVerifyServerName,
  793. VerifyPins: dialParams.MeekVerifyPins,
  794. HostHeader: dialParams.MeekHostHeader,
  795. TransformedHostName: dialParams.MeekTransformedHostName,
  796. ClientTunnelProtocol: dialParams.TunnelProtocol,
  797. MeekCookieEncryptionPublicKey: serverEntry.MeekCookieEncryptionPublicKey,
  798. MeekObfuscatedKey: serverEntry.MeekObfuscatedKey,
  799. MeekObfuscatorPaddingSeed: dialParams.MeekObfuscatorPaddingSeed,
  800. NetworkLatencyMultiplier: dialParams.NetworkLatencyMultiplier,
  801. HTTPTransformerParameters: dialParams.HTTPTransformerParameters,
  802. }
  803. // Use an asynchronous callback to record the resolved IP address when
  804. // dialing a domain name. Note that DialMeek doesn't immediately
  805. // establish any HTTP connections, so the resolved IP address won't be
  806. // reported in all cases until after SSH traffic is relayed or a
  807. // endpoint request is made over the meek connection.
  808. dialParams.dialConfig.ResolvedIPCallback = func(IPAddress string) {
  809. dialParams.MeekResolvedIPAddress.Store(IPAddress)
  810. }
  811. if isTactics {
  812. dialParams.meekConfig.Mode = MeekModeObfuscatedRoundTrip
  813. } else if dialParams.ConjureAPIRegistration {
  814. dialParams.meekConfig.Mode = MeekModePlaintextRoundTrip
  815. } else {
  816. dialParams.meekConfig.Mode = MeekModeRelay
  817. }
  818. }
  819. return dialParams, nil
  820. }
  821. func (dialParams *DialParameters) GetDialConfig() *DialConfig {
  822. return dialParams.dialConfig
  823. }
  824. func (dialParams *DialParameters) GetMeekConfig() *MeekConfig {
  825. return dialParams.meekConfig
  826. }
  827. // GetNetworkType returns a network type name, suitable for metrics, which is
  828. // derived from the network ID.
  829. func (dialParams *DialParameters) GetNetworkType() string {
  830. // Unlike the logic in loggingNetworkIDGetter.GetNetworkID, we don't take the
  831. // arbitrary text before the first "-" since some platforms without network
  832. // detection support stub in random values to enable tactics. Instead we
  833. // check for and use the common network type prefixes currently used in
  834. // NetworkIDGetter implementations.
  835. if strings.HasPrefix(dialParams.NetworkID, "WIFI") {
  836. return "WIFI"
  837. }
  838. if strings.HasPrefix(dialParams.NetworkID, "MOBILE") {
  839. return "MOBILE"
  840. }
  841. return "UNKNOWN"
  842. }
  843. func (dialParams *DialParameters) Succeeded() {
  844. // When TTL is 0, don't store dial parameters.
  845. if dialParams.LastUsedTimestamp.IsZero() {
  846. return
  847. }
  848. NoticeInfo("Set dial parameters for %s", dialParams.ServerEntry.GetDiagnosticID())
  849. err := SetDialParameters(dialParams.ServerEntry.IpAddress, dialParams.NetworkID, dialParams)
  850. if err != nil {
  851. NoticeWarning("SetDialParameters failed: %s", err)
  852. }
  853. }
  854. func (dialParams *DialParameters) Failed(config *Config) {
  855. // When a tunnel fails, and the dial is a replay, clear the stored dial
  856. // parameters which are now presumed to be blocked, impaired or otherwise
  857. // no longer effective.
  858. //
  859. // It may be the case that a dial is not using stored dial parameters
  860. // (!IsReplay), and in this case we retain those dial parameters since they
  861. // were not exercised and may still be effective.
  862. //
  863. // Failed tunnel dial parameters may be retained with a configurable
  864. // probability; this is intended to help mitigate false positive failures due
  865. // to, e.g., temporary network disruptions or server load limiting.
  866. if dialParams.IsReplay &&
  867. !config.GetParameters().Get().WeightedCoinFlip(
  868. parameters.ReplayRetainFailedProbability) {
  869. NoticeInfo("Delete dial parameters for %s", dialParams.ServerEntry.GetDiagnosticID())
  870. err := DeleteDialParameters(dialParams.ServerEntry.IpAddress, dialParams.NetworkID)
  871. if err != nil {
  872. NoticeWarning("DeleteDialParameters failed: %s", err)
  873. }
  874. }
  875. }
  876. func (dialParams *DialParameters) GetTLSVersionForMetrics() string {
  877. tlsVersion := dialParams.TLSVersion
  878. if dialParams.NoDefaultTLSSessionID {
  879. tlsVersion += "-no_def_id"
  880. }
  881. return tlsVersion
  882. }
  883. // ExchangedDialParameters represents the subset of DialParameters that is
  884. // shared in a client-to-client exchange of server connection info.
  885. //
  886. // The purpose of client-to-client exchange if for one user that can connect
  887. // to help another user that cannot connect by sharing their connected
  888. // configuration, including the server entry and dial parameters.
  889. //
  890. // There are two concerns regarding which dial parameter fields are safe to
  891. // exchange:
  892. //
  893. // - Unlike signed server entries, there's no independent trust anchor
  894. // that can certify that the exchange data is valid.
  895. //
  896. // - While users should only perform the exchange with trusted peers,
  897. // the user's trust in their peer may be misplaced.
  898. //
  899. // This presents the possibility of attack such as the peer sending dial
  900. // parameters that could be used to trace/monitor/flag the importer; or
  901. // sending dial parameters, including dial address and SNI, to cause the peer
  902. // to appear to connect to a banned service.
  903. //
  904. // To mitigate these risks, only a subset of dial parameters are exchanged.
  905. // When exchanged dial parameters and imported and used, all unexchanged
  906. // parameters are generated locally. At this time, only the tunnel protocol is
  907. // exchanged. We consider tunnel protocol selection one of the key connection
  908. // success factors.
  909. //
  910. // In addition, the exchange peers may not be on the same network with the
  911. // same blocking and circumvention characteristics, which is another reason
  912. // to limit exchanged dial parameter values to broadly applicable fields.
  913. //
  914. // Unlike the exchanged (and otherwise acquired) server entry,
  915. // ExchangedDialParameters does not use the ServerEntry_Fields_ representation
  916. // which allows older clients to receive and store new, unknown fields. Such a
  917. // facility is less useful in this case, since exchanged dial parameters and
  918. // used immediately and have a short lifespan.
  919. //
  920. // TODO: exchange more dial parameters, such as TLS profile, QUIC version, etc.
  921. type ExchangedDialParameters struct {
  922. TunnelProtocol string
  923. }
  924. // NewExchangedDialParameters creates a new ExchangedDialParameters from a
  925. // DialParameters, including only the exchanged values.
  926. // NewExchangedDialParameters assumes the input DialParameters has been
  927. // initialized and populated by MakeDialParameters.
  928. func NewExchangedDialParameters(dialParams *DialParameters) *ExchangedDialParameters {
  929. return &ExchangedDialParameters{
  930. TunnelProtocol: dialParams.TunnelProtocol,
  931. }
  932. }
  933. // Validate checks that the ExchangedDialParameters contains only valid values
  934. // and is compatible with the specified server entry.
  935. func (dialParams *ExchangedDialParameters) Validate(serverEntry *protocol.ServerEntry) error {
  936. if !common.Contains(protocol.SupportedTunnelProtocols, dialParams.TunnelProtocol) {
  937. return errors.Tracef("unknown tunnel protocol: %s", dialParams.TunnelProtocol)
  938. }
  939. if !serverEntry.SupportsProtocol(dialParams.TunnelProtocol) {
  940. return errors.Tracef("unsupported tunnel protocol: %s", dialParams.TunnelProtocol)
  941. }
  942. return nil
  943. }
  944. // MakeDialParameters creates a new, partially intitialized DialParameters
  945. // from the values in ExchangedDialParameters. The returned DialParameters
  946. // must not be used directly for dialing. It is intended to be stored, and
  947. // then later fully initialized by MakeDialParameters.
  948. func (dialParams *ExchangedDialParameters) MakeDialParameters(
  949. config *Config,
  950. p parameters.ParametersAccessor,
  951. serverEntry *protocol.ServerEntry) *DialParameters {
  952. return &DialParameters{
  953. IsExchanged: true,
  954. LastUsedTimestamp: time.Now(),
  955. LastUsedConfigStateHash: getConfigStateHash(config, p, serverEntry),
  956. TunnelProtocol: dialParams.TunnelProtocol,
  957. }
  958. }
  959. func getConfigStateHash(
  960. config *Config,
  961. p parameters.ParametersAccessor,
  962. serverEntry *protocol.ServerEntry) []byte {
  963. // The config state hash should reflect config, tactics, and server entry
  964. // settings that impact the dial parameters. The hash should change if any
  965. // of these input values change in a way that invalidates any stored dial
  966. // parameters.
  967. // MD5 hash is used solely as a data checksum and not for any security
  968. // purpose.
  969. hash := md5.New()
  970. // Add a hash of relevant config fields.
  971. // Limitation: the config hash may change even when tactics will override the
  972. // changed config field.
  973. hash.Write(config.dialParametersHash)
  974. // Add the active tactics tag.
  975. hash.Write([]byte(p.Tag()))
  976. // Add the server entry version and local timestamp, both of which should
  977. // change when the server entry contents change and/or a new local copy is
  978. // imported.
  979. // TODO: marshal entire server entry?
  980. var serverEntryConfigurationVersion [8]byte
  981. binary.BigEndian.PutUint64(
  982. serverEntryConfigurationVersion[:],
  983. uint64(serverEntry.ConfigurationVersion))
  984. hash.Write(serverEntryConfigurationVersion[:])
  985. hash.Write([]byte(serverEntry.LocalTimestamp))
  986. return hash.Sum(nil)
  987. }
  988. func selectFrontingParameters(
  989. serverEntry *protocol.ServerEntry) (string, string, error) {
  990. frontingDialHost := ""
  991. frontingHost := ""
  992. if len(serverEntry.MeekFrontingAddressesRegex) > 0 {
  993. // Generate a front address based on the regex.
  994. var err error
  995. frontingDialHost, err = regen.Generate(serverEntry.MeekFrontingAddressesRegex)
  996. if err != nil {
  997. return "", "", errors.Trace(err)
  998. }
  999. } else {
  1000. // Randomly select, for this connection attempt, one front address for
  1001. // fronting-capable servers.
  1002. if len(serverEntry.MeekFrontingAddresses) == 0 {
  1003. return "", "", errors.TraceNew("MeekFrontingAddresses is empty")
  1004. }
  1005. index := prng.Intn(len(serverEntry.MeekFrontingAddresses))
  1006. frontingDialHost = serverEntry.MeekFrontingAddresses[index]
  1007. }
  1008. if len(serverEntry.MeekFrontingHosts) > 0 {
  1009. index := prng.Intn(len(serverEntry.MeekFrontingHosts))
  1010. frontingHost = serverEntry.MeekFrontingHosts[index]
  1011. } else {
  1012. // Backwards compatibility case
  1013. frontingHost = serverEntry.MeekFrontingHost
  1014. }
  1015. return frontingDialHost, frontingHost, nil
  1016. }
  1017. func selectQUICVersion(
  1018. isFronted bool,
  1019. serverEntry *protocol.ServerEntry,
  1020. p parameters.ParametersAccessor) string {
  1021. limitQUICVersions := p.QUICVersions(parameters.LimitQUICVersions)
  1022. var disableQUICVersions protocol.QUICVersions
  1023. if isFronted {
  1024. if serverEntry.FrontingProviderID == "" {
  1025. // Legacy server entry case
  1026. disableQUICVersions = protocol.QUICVersions{
  1027. protocol.QUIC_VERSION_V1,
  1028. protocol.QUIC_VERSION_RANDOMIZED_V1,
  1029. protocol.QUIC_VERSION_OBFUSCATED_V1,
  1030. protocol.QUIC_VERSION_DECOY_V1,
  1031. }
  1032. } else {
  1033. disableQUICVersions = p.LabeledQUICVersions(
  1034. parameters.DisableFrontingProviderQUICVersions,
  1035. serverEntry.FrontingProviderID)
  1036. }
  1037. }
  1038. quicVersions := make([]string, 0)
  1039. // Don't use gQUIC versions when the server entry specifies QUICv1-only.
  1040. supportedQUICVersions := protocol.SupportedQUICVersions
  1041. if serverEntry.SupportsOnlyQUICv1() {
  1042. supportedQUICVersions = protocol.SupportedQUICv1Versions
  1043. }
  1044. for _, quicVersion := range supportedQUICVersions {
  1045. if len(limitQUICVersions) > 0 &&
  1046. !common.Contains(limitQUICVersions, quicVersion) {
  1047. continue
  1048. }
  1049. // Both tactics and the server entry can specify LimitQUICVersions. In
  1050. // tactics, the parameter is intended to direct certain clients to
  1051. // use a successful protocol variant. In the server entry, the
  1052. // parameter may be used to direct all clients to send
  1053. // consistent-looking protocol variants to a particular server; e.g.,
  1054. // only regular QUIC, or only obfuscated QUIC.
  1055. //
  1056. // The isFronted/QUICVersionIsObfuscated logic predates
  1057. // ServerEntry.LimitQUICVersions; ServerEntry.LimitQUICVersions could
  1058. // now be used to achieve a similar outcome.
  1059. if len(serverEntry.LimitQUICVersions) > 0 &&
  1060. !common.Contains(serverEntry.LimitQUICVersions, quicVersion) {
  1061. continue
  1062. }
  1063. if isFronted &&
  1064. protocol.QUICVersionIsObfuscated(quicVersion) {
  1065. continue
  1066. }
  1067. if common.Contains(disableQUICVersions, quicVersion) {
  1068. continue
  1069. }
  1070. quicVersions = append(quicVersions, quicVersion)
  1071. }
  1072. if len(quicVersions) == 0 {
  1073. return ""
  1074. }
  1075. choice := prng.Intn(len(quicVersions))
  1076. return quicVersions[choice]
  1077. }
  1078. // selectUserAgentIfUnset selects a User-Agent header if one is not set.
  1079. func selectUserAgentIfUnset(
  1080. p parameters.ParametersAccessor, headers http.Header) (bool, string) {
  1081. if _, ok := headers["User-Agent"]; !ok {
  1082. userAgent := ""
  1083. if p.WeightedCoinFlip(parameters.PickUserAgentProbability) {
  1084. userAgent = values.GetUserAgent()
  1085. }
  1086. return true, userAgent
  1087. }
  1088. return false, ""
  1089. }
  1090. func makeDialCustomHeaders(
  1091. config *Config,
  1092. p parameters.ParametersAccessor) http.Header {
  1093. dialCustomHeaders := make(http.Header)
  1094. if config.CustomHeaders != nil {
  1095. for k, v := range config.CustomHeaders {
  1096. dialCustomHeaders[k] = make([]string, len(v))
  1097. copy(dialCustomHeaders[k], v)
  1098. }
  1099. }
  1100. additionalCustomHeaders := p.HTTPHeaders(parameters.AdditionalCustomHeaders)
  1101. for k, v := range additionalCustomHeaders {
  1102. dialCustomHeaders[k] = make([]string, len(v))
  1103. copy(dialCustomHeaders[k], v)
  1104. }
  1105. return dialCustomHeaders
  1106. }
  1107. func selectHostName(
  1108. tunnelProtocol string, p parameters.ParametersAccessor) string {
  1109. limitProtocols := p.TunnelProtocols(parameters.CustomHostNameLimitProtocols)
  1110. if len(limitProtocols) > 0 && !common.Contains(limitProtocols, tunnelProtocol) {
  1111. return values.GetHostName()
  1112. }
  1113. if !p.WeightedCoinFlip(parameters.CustomHostNameProbability) {
  1114. return values.GetHostName()
  1115. }
  1116. regexStrings := p.RegexStrings(parameters.CustomHostNameRegexes)
  1117. if len(regexStrings) == 0 {
  1118. return values.GetHostName()
  1119. }
  1120. choice := prng.Intn(len(regexStrings))
  1121. hostName, err := regen.Generate(regexStrings[choice])
  1122. if err != nil {
  1123. NoticeWarning("selectHostName: regen.Generate failed: %v", errors.Trace(err))
  1124. return values.GetHostName()
  1125. }
  1126. return hostName
  1127. }
  1128. // makeHTTPTransformerParameters generates HTTPTransformerParameters using the
  1129. // input tactics parameters and optional frontingProviderID context.
  1130. func makeHTTPTransformerParameters(p parameters.ParametersAccessor,
  1131. frontingProviderID string, isFronted bool) (*transforms.HTTPTransformerParameters, error) {
  1132. params := transforms.HTTPTransformerParameters{}
  1133. // Select an HTTP transform. If the request is fronted, HTTP request
  1134. // transforms are "scoped" by fronting provider ID. Otherwise, a transform
  1135. // from the default scope (transforms.SCOPE_ANY == "") is selected.
  1136. var specsKey string
  1137. var scopedSpecsNamesKey string
  1138. useTransform := false
  1139. scope := transforms.SCOPE_ANY
  1140. if isFronted {
  1141. if p.WeightedCoinFlip(parameters.FrontedHTTPProtocolTransformProbability) {
  1142. useTransform = true
  1143. scope = frontingProviderID
  1144. specsKey = parameters.FrontedHTTPProtocolTransformSpecs
  1145. scopedSpecsNamesKey = parameters.FrontedHTTPProtocolTransformScopedSpecNames
  1146. }
  1147. } else {
  1148. // unfronted
  1149. if p.WeightedCoinFlip(parameters.DirectHTTPProtocolTransformProbability) {
  1150. useTransform = true
  1151. specsKey = parameters.DirectHTTPProtocolTransformSpecs
  1152. scopedSpecsNamesKey = parameters.DirectHTTPProtocolTransformScopedSpecNames
  1153. }
  1154. }
  1155. if useTransform {
  1156. specs := p.ProtocolTransformSpecs(
  1157. specsKey)
  1158. scopedSpecNames := p.ProtocolTransformScopedSpecNames(
  1159. scopedSpecsNamesKey)
  1160. name, spec := specs.Select(scope, scopedSpecNames)
  1161. if spec != nil {
  1162. params.ProtocolTransformName = name
  1163. params.ProtocolTransformSpec = spec
  1164. var err error
  1165. // transform seed generated
  1166. params.ProtocolTransformSeed, err = prng.NewSeed()
  1167. if err != nil {
  1168. return nil, errors.Trace(err)
  1169. }
  1170. }
  1171. }
  1172. return &params, nil
  1173. }