dialParameters.go 57 KB

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