dialParameters.go 51 KB

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