dialParameters.go 62 KB

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