dialParameters.go 58 KB

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