dialParameters.go 60 KB

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