dialParameters.go 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712
  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. dialParams.MeekDialAddress = net.JoinHostPort(dialParams.MeekFrontingDialAddress, "443")
  488. dialParams.MeekHostHeader = dialParams.MeekFrontingHost
  489. // For a FrontingSpec, an SNI value of "" indicates to disable/omit SNI, so
  490. // never transform in that case.
  491. if dialParams.MeekSNIServerName != "" {
  492. if p.WeightedCoinFlip(parameters.TransformHostNameProbability) {
  493. dialParams.MeekSNIServerName = selectHostName(dialParams.TunnelProtocol, p)
  494. dialParams.MeekTransformedHostName = true
  495. }
  496. }
  497. // The minimum delay value is determined by the Conjure station, which
  498. // performs an asynchronous "liveness test" against the selected phantom
  499. // IPs. The min/max range allows us to introduce some jitter so that we
  500. // don't present a trivial inter-flow fingerprint: CDN connection, fixed
  501. // delay, phantom dial.
  502. minDelay := p.Duration(parameters.ConjureAPIRegistrarMinDelay)
  503. maxDelay := p.Duration(parameters.ConjureAPIRegistrarMaxDelay)
  504. dialParams.ConjureAPIRegistrarDelay = prng.Period(minDelay, maxDelay)
  505. } else if dialParams.ConjureDecoyRegistration {
  506. dialParams.ConjureDecoyRegistrarWidth = decoyWidth
  507. minDelay := p.Duration(parameters.ConjureDecoyRegistrarMinDelay)
  508. maxDelay := p.Duration(parameters.ConjureDecoyRegistrarMaxDelay)
  509. dialParams.ConjureAPIRegistrarDelay = prng.Period(minDelay, maxDelay)
  510. } else {
  511. return nil, errors.TraceNew("no Conjure registrar configured")
  512. }
  513. }
  514. if (!isReplay || !replayConjureTransport) &&
  515. protocol.TunnelProtocolUsesConjure(dialParams.TunnelProtocol) {
  516. dialParams.ConjureTransport = protocol.CONJURE_TRANSPORT_MIN_OSSH
  517. if p.WeightedCoinFlip(
  518. parameters.ConjureTransportObfs4Probability) {
  519. dialParams.ConjureTransport = protocol.CONJURE_TRANSPORT_OBFS4_OSSH
  520. }
  521. }
  522. usingTLS := protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol) ||
  523. protocol.TunnelProtocolUsesTLSOSSH(dialParams.TunnelProtocol) ||
  524. dialParams.ConjureAPIRegistration
  525. if (!isReplay || !replayTLSProfile) && usingTLS {
  526. dialParams.SelectedTLSProfile = true
  527. requireTLS12SessionTickets := protocol.TunnelProtocolRequiresTLS12SessionTickets(
  528. dialParams.TunnelProtocol)
  529. requireTLS13Support := protocol.TunnelProtocolRequiresTLS13Support(dialParams.TunnelProtocol)
  530. isFronted := protocol.TunnelProtocolUsesFrontedMeek(dialParams.TunnelProtocol) ||
  531. dialParams.ConjureAPIRegistration
  532. dialParams.TLSProfile, dialParams.TLSVersion, dialParams.RandomizedTLSProfileSeed, err = SelectTLSProfile(
  533. requireTLS12SessionTickets, requireTLS13Support, isFronted, serverEntry.FrontingProviderID, p)
  534. if err != nil {
  535. return nil, errors.Trace(err)
  536. }
  537. if dialParams.TLSProfile == "" && (requireTLS12SessionTickets || requireTLS13Support) {
  538. return nil, errors.TraceNew("required TLS profile not found")
  539. }
  540. dialParams.NoDefaultTLSSessionID = p.WeightedCoinFlip(
  541. parameters.NoDefaultTLSSessionIDProbability)
  542. }
  543. if (!isReplay || !replayFronting) &&
  544. protocol.TunnelProtocolUsesFrontedMeek(dialParams.TunnelProtocol) {
  545. dialParams.FrontingProviderID = serverEntry.FrontingProviderID
  546. dialParams.MeekFrontingDialAddress, dialParams.MeekFrontingHost, err =
  547. selectFrontingParameters(serverEntry)
  548. if err != nil {
  549. return nil, errors.Trace(err)
  550. }
  551. }
  552. if !isReplay || !replayHostname {
  553. // Any MeekHostHeader selections made here will be overridden below,
  554. // as required, for fronting cases.
  555. if protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol) ||
  556. protocol.TunnelProtocolUsesFrontedMeekQUIC(dialParams.TunnelProtocol) {
  557. dialParams.MeekSNIServerName = ""
  558. hostname := ""
  559. if p.WeightedCoinFlip(parameters.TransformHostNameProbability) {
  560. dialParams.MeekSNIServerName = selectHostName(dialParams.TunnelProtocol, p)
  561. hostname = dialParams.MeekSNIServerName
  562. dialParams.MeekTransformedHostName = true
  563. } else {
  564. // Always select a hostname for the Host header in this case.
  565. // Unlike HTTP, the Host header isn't plaintext on the wire,
  566. // and so there's no anti-fingerprint benefit from presenting
  567. // the server IP address in the Host header. Omitting the
  568. // server IP here can prevent exposing it in certain
  569. // scenarios where the traffic is rerouted and arrives at a
  570. // different HTTPS server.
  571. hostname = selectHostName(dialParams.TunnelProtocol, p)
  572. }
  573. if serverEntry.MeekServerPort == 443 {
  574. dialParams.MeekHostHeader = hostname
  575. } else {
  576. dialParams.MeekHostHeader = net.JoinHostPort(
  577. hostname, strconv.Itoa(serverEntry.MeekServerPort))
  578. }
  579. } else if protocol.TunnelProtocolUsesTLSOSSH(dialParams.TunnelProtocol) {
  580. dialParams.TLSOSSHSNIServerName = ""
  581. if p.WeightedCoinFlip(parameters.TransformHostNameProbability) {
  582. dialParams.TLSOSSHSNIServerName = selectHostName(dialParams.TunnelProtocol, p)
  583. dialParams.TLSOSSHTransformedSNIServerName = true
  584. }
  585. } else if protocol.TunnelProtocolUsesMeekHTTP(dialParams.TunnelProtocol) {
  586. dialParams.MeekHostHeader = ""
  587. hostname := serverEntry.IpAddress
  588. if p.WeightedCoinFlip(parameters.TransformHostNameProbability) {
  589. hostname = selectHostName(dialParams.TunnelProtocol, p)
  590. dialParams.MeekTransformedHostName = true
  591. }
  592. if serverEntry.MeekServerPort == 80 {
  593. dialParams.MeekHostHeader = hostname
  594. } else {
  595. dialParams.MeekHostHeader = net.JoinHostPort(
  596. hostname, strconv.Itoa(serverEntry.MeekServerPort))
  597. }
  598. } else if protocol.TunnelProtocolUsesQUIC(dialParams.TunnelProtocol) {
  599. dialParams.QUICDialSNIAddress = selectHostName(dialParams.TunnelProtocol, p)
  600. }
  601. }
  602. if (!isReplay || !replayQUICVersion) &&
  603. protocol.TunnelProtocolUsesQUIC(dialParams.TunnelProtocol) {
  604. isFronted := protocol.TunnelProtocolUsesFrontedMeekQUIC(dialParams.TunnelProtocol)
  605. dialParams.QUICVersion = selectQUICVersion(isFronted, serverEntry, p)
  606. // Due to potential tactics configurations, it may be that no QUIC
  607. // version is selected. Abort immediately, with no error, as in the
  608. // selectProtocol case. quic.Dial and quic.NewQUICTransporter will
  609. // check for a missing QUIC version, but at that later stage an
  610. // unnecessary failed_tunnel can be logged in this scenario.
  611. if dialParams.QUICVersion == "" {
  612. return nil, nil
  613. }
  614. if protocol.QUICVersionHasRandomizedClientHello(dialParams.QUICVersion) {
  615. dialParams.QUICClientHelloSeed, err = prng.NewSeed()
  616. if err != nil {
  617. return nil, errors.Trace(err)
  618. }
  619. }
  620. dialParams.QUICDisablePathMTUDiscovery =
  621. protocol.QUICVersionUsesPathMTUDiscovery(dialParams.QUICVersion) &&
  622. p.WeightedCoinFlip(parameters.QUICDisableClientPathMTUDiscoveryProbability)
  623. }
  624. if (!isReplay || !replayObfuscatedQUIC) &&
  625. protocol.QUICVersionIsObfuscated(dialParams.QUICVersion) {
  626. dialParams.ObfuscatedQUICPaddingSeed, err = prng.NewSeed()
  627. if err != nil {
  628. return nil, errors.Trace(err)
  629. }
  630. }
  631. if protocol.QUICVersionIsObfuscated(dialParams.QUICVersion) {
  632. if serverEntry.DisableObfuscatedQUICTransforms {
  633. dialParams.ObfuscatedQUICNonceTransformerParameters = nil
  634. } else if !isReplay || !replayObfuscatedQUICNonceTransformer {
  635. params, err := makeSeedTransformerParameters(
  636. p,
  637. parameters.ObfuscatedQUICNonceTransformProbability,
  638. parameters.ObfuscatedQUICNonceTransformSpecs,
  639. parameters.ObfuscatedQUICNonceTransformScopedSpecNames)
  640. if err != nil {
  641. return nil, errors.Trace(err)
  642. }
  643. if params.TransformSpec != nil {
  644. dialParams.ObfuscatedQUICNonceTransformerParameters = params
  645. } else {
  646. dialParams.ObfuscatedQUICNonceTransformerParameters = nil
  647. }
  648. }
  649. }
  650. if !isReplay || !replayLivenessTest {
  651. // TODO: initialize only when LivenessTestMaxUp/DownstreamBytes > 0?
  652. dialParams.LivenessTestSeed, err = prng.NewSeed()
  653. if err != nil {
  654. return nil, errors.Trace(err)
  655. }
  656. }
  657. if !isReplay || !replayAPIRequestPadding {
  658. dialParams.APIRequestPaddingSeed, err = prng.NewSeed()
  659. if err != nil {
  660. return nil, errors.Trace(err)
  661. }
  662. }
  663. // Initialize dialParams.ResolveParameters for dials that will resolve
  664. // domain names, which currently includes fronted meek and Conjure API
  665. // registration, where the dial address is not an IP address.
  666. //
  667. // dialParams.ResolveParameters must be nil when the dial address is an IP
  668. // address to ensure that no DNS dial parameters are reported in metrics
  669. // or diagnostics when when no domain is resolved.
  670. useResolver := (protocol.TunnelProtocolUsesFrontedMeek(dialParams.TunnelProtocol) ||
  671. dialParams.ConjureAPIRegistration) &&
  672. net.ParseIP(dialParams.MeekFrontingDialAddress) == nil
  673. if (!isReplay || !replayResolveParameters) && useResolver {
  674. dialParams.ResolveParameters, err = dialParams.resolver.MakeResolveParameters(
  675. p, dialParams.FrontingProviderID)
  676. if err != nil {
  677. return nil, errors.Trace(err)
  678. }
  679. }
  680. if !isReplay || !replayHoldOffTunnel {
  681. if common.Contains(
  682. p.TunnelProtocols(parameters.HoldOffTunnelProtocols), dialParams.TunnelProtocol) ||
  683. (protocol.TunnelProtocolUsesFrontedMeek(dialParams.TunnelProtocol) &&
  684. common.Contains(
  685. p.Strings(parameters.HoldOffTunnelFrontingProviderIDs),
  686. dialParams.FrontingProviderID)) {
  687. if p.WeightedCoinFlip(parameters.HoldOffTunnelProbability) {
  688. dialParams.HoldOffTunnelDuration = prng.Period(
  689. p.Duration(parameters.HoldOffTunnelMinDuration),
  690. p.Duration(parameters.HoldOffTunnelMaxDuration))
  691. }
  692. }
  693. }
  694. // OSSH prefix and seed transform are applied only to the OSSH tunnel protocol,
  695. // and not to any other protocol layered over OSSH.
  696. if dialParams.TunnelProtocol == protocol.TUNNEL_PROTOCOL_OBFUSCATED_SSH {
  697. if serverEntry.DisableOSSHTransforms {
  698. dialParams.OSSHObfuscatorSeedTransformerParameters = nil
  699. } else if !isReplay || !replayOSSHSeedTransformerParameters {
  700. params, err := makeSeedTransformerParameters(
  701. p,
  702. parameters.OSSHObfuscatorSeedTransformProbability,
  703. parameters.OSSHObfuscatorSeedTransformSpecs,
  704. parameters.OSSHObfuscatorSeedTransformScopedSpecNames)
  705. if err != nil {
  706. return nil, errors.Trace(err)
  707. }
  708. if params.TransformSpec != nil {
  709. dialParams.OSSHObfuscatorSeedTransformerParameters = params
  710. } else {
  711. dialParams.OSSHObfuscatorSeedTransformerParameters = nil
  712. }
  713. }
  714. if serverEntry.DisableOSSHPrefix {
  715. dialParams.OSSHPrefixSpec = nil
  716. dialParams.OSSHPrefixSplitConfig = nil
  717. } else if !isReplay || !replayOSSHPrefix {
  718. dialPortNumber, err := serverEntry.GetDialPortNumber(dialParams.TunnelProtocol)
  719. if err != nil {
  720. return nil, errors.Trace(err)
  721. }
  722. prefixSpec, err := makeOSSHPrefixSpecParameters(p, strconv.Itoa(dialPortNumber))
  723. if err != nil {
  724. return nil, errors.Trace(err)
  725. }
  726. splitConfig, err := makeOSSHPrefixSplitConfig(p)
  727. if err != nil {
  728. return nil, errors.Trace(err)
  729. }
  730. if prefixSpec.Spec != nil {
  731. dialParams.OSSHPrefixSpec = prefixSpec
  732. dialParams.OSSHPrefixSplitConfig = splitConfig
  733. } else {
  734. dialParams.OSSHPrefixSpec = nil
  735. dialParams.OSSHPrefixSplitConfig = 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. protocol.TUNNEL_PROTOCOL_TLS_OBFUSCATED_SSH:
  775. dialParams.DirectDialAddress = net.JoinHostPort(serverEntry.IpAddress, dialParams.DialPortNumber)
  776. case protocol.TUNNEL_PROTOCOL_FRONTED_MEEK,
  777. protocol.TUNNEL_PROTOCOL_FRONTED_MEEK_QUIC_OBFUSCATED_SSH:
  778. dialParams.MeekDialAddress = net.JoinHostPort(dialParams.MeekFrontingDialAddress, dialParams.DialPortNumber)
  779. dialParams.MeekHostHeader = dialParams.MeekFrontingHost
  780. if serverEntry.MeekFrontingDisableSNI {
  781. dialParams.MeekSNIServerName = ""
  782. // When SNI is omitted, the transformed host name is not used.
  783. dialParams.MeekTransformedHostName = false
  784. } else if !dialParams.MeekTransformedHostName {
  785. dialParams.MeekSNIServerName = dialParams.MeekFrontingDialAddress
  786. }
  787. case protocol.TUNNEL_PROTOCOL_FRONTED_MEEK_HTTP:
  788. dialParams.MeekDialAddress = net.JoinHostPort(dialParams.MeekFrontingDialAddress, dialParams.DialPortNumber)
  789. dialParams.MeekHostHeader = dialParams.MeekFrontingHost
  790. // For FRONTED HTTP, the Host header cannot be transformed.
  791. dialParams.MeekTransformedHostName = false
  792. case protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK:
  793. dialParams.MeekDialAddress = net.JoinHostPort(serverEntry.IpAddress, dialParams.DialPortNumber)
  794. case protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  795. protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET:
  796. dialParams.MeekDialAddress = net.JoinHostPort(serverEntry.IpAddress, dialParams.DialPortNumber)
  797. if !dialParams.MeekTransformedHostName {
  798. // Note: IP address in SNI field will be omitted.
  799. dialParams.MeekSNIServerName = serverEntry.IpAddress
  800. }
  801. default:
  802. return nil, errors.Tracef(
  803. "unknown tunnel protocol: %s", dialParams.TunnelProtocol)
  804. }
  805. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) {
  806. host, _, _ := net.SplitHostPort(dialParams.MeekDialAddress)
  807. if p.Bool(parameters.MeekDialDomainsOnly) {
  808. if net.ParseIP(host) != nil {
  809. // No error, as this is a "not supported" case.
  810. return nil, nil
  811. }
  812. }
  813. // The underlying TLS implementation will automatically omit SNI for
  814. // IP address server name values; we have this explicit check here so
  815. // we record the correct value for stats.
  816. if net.ParseIP(dialParams.MeekSNIServerName) != nil {
  817. dialParams.MeekSNIServerName = ""
  818. }
  819. }
  820. // Initialize/replay User-Agent header for HTTP upstream proxy and meek protocols.
  821. if config.UseUpstreamProxy() {
  822. // Note: UpstreamProxyURL will be validated in the dial
  823. proxyURL, err := common.SafeParseURL(config.UpstreamProxyURL)
  824. if err == nil {
  825. dialParams.UpstreamProxyType = proxyURL.Scheme
  826. }
  827. }
  828. dialCustomHeaders := makeDialCustomHeaders(config, p)
  829. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) ||
  830. dialParams.UpstreamProxyType == "http" ||
  831. dialParams.ConjureAPIRegistration {
  832. if !isReplay || !replayUserAgent {
  833. dialParams.SelectedUserAgent, dialParams.UserAgent = selectUserAgentIfUnset(p, dialCustomHeaders)
  834. }
  835. if dialParams.SelectedUserAgent {
  836. dialCustomHeaders.Set("User-Agent", dialParams.UserAgent)
  837. }
  838. }
  839. // UpstreamProxyCustomHeaderNames is a reported metric. Just the names and
  840. // not the values are reported, in case the values are identifying.
  841. if len(config.CustomHeaders) > 0 {
  842. dialParams.UpstreamProxyCustomHeaderNames = make([]string, 0)
  843. for name := range dialCustomHeaders {
  844. if name == "User-Agent" && dialParams.SelectedUserAgent {
  845. continue
  846. }
  847. dialParams.UpstreamProxyCustomHeaderNames = append(dialParams.UpstreamProxyCustomHeaderNames, name)
  848. }
  849. }
  850. // Initialize Dial/MeekConfigs to be passed to the corresponding dialers.
  851. // Custom ResolveParameters are set only when useResolver is true, but
  852. // DialConfig.ResolveIP is required and wired up unconditionally. Any
  853. // misconfigured or miscoded domain dial cases will use default
  854. // ResolveParameters.
  855. //
  856. // ResolveIP will use the networkID obtained above, as it will be used
  857. // almost immediately, instead of incurring the overhead of calling
  858. // GetNetworkID again.
  859. resolveIP := func(ctx context.Context, hostname string) ([]net.IP, error) {
  860. IPs, err := dialParams.resolver.ResolveIP(
  861. ctx,
  862. networkID,
  863. dialParams.ResolveParameters,
  864. hostname)
  865. if err != nil {
  866. return nil, errors.Trace(err)
  867. }
  868. return IPs, nil
  869. }
  870. // Fragmentor configuration.
  871. // Note: fragmentorConfig is nil if fragmentor is disabled for prefixed OSSH.
  872. //
  873. // Limitation: when replaying and with ReplayIgnoreChangedConfigState set,
  874. // fragmentor.NewUpstreamConfig may select a config using newer tactics
  875. // parameters.
  876. fragmentorConfig := fragmentor.NewUpstreamConfig(p, dialParams.TunnelProtocol, dialParams.FragmentorSeed)
  877. if !p.Bool(parameters.OSSHPrefixEnableFragmentor) && dialParams.OSSHPrefixSpec != nil {
  878. fragmentorConfig = nil
  879. }
  880. dialParams.dialConfig = &DialConfig{
  881. DiagnosticID: serverEntry.GetDiagnosticID(),
  882. UpstreamProxyURL: config.UpstreamProxyURL,
  883. CustomHeaders: dialCustomHeaders,
  884. BPFProgramInstructions: dialParams.BPFProgramInstructions,
  885. DeviceBinder: config.deviceBinder,
  886. IPv6Synthesizer: config.IPv6Synthesizer,
  887. ResolveIP: resolveIP,
  888. TrustedCACertificatesFilename: config.TrustedCACertificatesFilename,
  889. FragmentorConfig: fragmentorConfig,
  890. UpstreamProxyErrorCallback: upstreamProxyErrorCallback,
  891. }
  892. // Unconditionally initialize MeekResolvedIPAddress, so a valid string can
  893. // always be read.
  894. dialParams.MeekResolvedIPAddress.Store("")
  895. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) ||
  896. dialParams.ConjureAPIRegistration {
  897. // For tactics requests, AddPsiphonFrontingHeader is set when set for
  898. // the related tunnel protocol. E.g., FRONTED-OSSH-MEEK for
  899. // FRONTED-MEEK-TACTICS. AddPsiphonFrontingHeader is not replayed.
  900. addPsiphonFrontingHeader := false
  901. if dialParams.FrontingProviderID != "" {
  902. addPsiphonFrontingHeader = common.Contains(
  903. p.LabeledTunnelProtocols(
  904. parameters.AddFrontingProviderPsiphonFrontingHeader, dialParams.FrontingProviderID),
  905. dialParams.TunnelProtocol)
  906. }
  907. dialParams.meekConfig = &MeekConfig{
  908. DiagnosticID: serverEntry.GetDiagnosticID(),
  909. Parameters: config.GetParameters(),
  910. DialAddress: dialParams.MeekDialAddress,
  911. UseQUIC: protocol.TunnelProtocolUsesFrontedMeekQUIC(dialParams.TunnelProtocol),
  912. QUICVersion: dialParams.QUICVersion,
  913. QUICClientHelloSeed: dialParams.QUICClientHelloSeed,
  914. QUICDisablePathMTUDiscovery: dialParams.QUICDisablePathMTUDiscovery,
  915. UseHTTPS: usingTLS,
  916. TLSProfile: dialParams.TLSProfile,
  917. LegacyPassthrough: serverEntry.ProtocolUsesLegacyPassthrough(dialParams.TunnelProtocol),
  918. NoDefaultTLSSessionID: dialParams.NoDefaultTLSSessionID,
  919. RandomizedTLSProfileSeed: dialParams.RandomizedTLSProfileSeed,
  920. UseObfuscatedSessionTickets: dialParams.TunnelProtocol == protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET,
  921. SNIServerName: dialParams.MeekSNIServerName,
  922. AddPsiphonFrontingHeader: addPsiphonFrontingHeader,
  923. VerifyServerName: dialParams.MeekVerifyServerName,
  924. VerifyPins: dialParams.MeekVerifyPins,
  925. HostHeader: dialParams.MeekHostHeader,
  926. TransformedHostName: dialParams.MeekTransformedHostName,
  927. ClientTunnelProtocol: dialParams.TunnelProtocol,
  928. MeekCookieEncryptionPublicKey: serverEntry.MeekCookieEncryptionPublicKey,
  929. MeekObfuscatedKey: serverEntry.MeekObfuscatedKey,
  930. MeekObfuscatorPaddingSeed: dialParams.MeekObfuscatorPaddingSeed,
  931. NetworkLatencyMultiplier: dialParams.NetworkLatencyMultiplier,
  932. HTTPTransformerParameters: dialParams.HTTPTransformerParameters,
  933. }
  934. // Use an asynchronous callback to record the resolved IP address when
  935. // dialing a domain name. Note that DialMeek doesn't immediately
  936. // establish any HTTP connections, so the resolved IP address won't be
  937. // reported in all cases until after SSH traffic is relayed or a
  938. // endpoint request is made over the meek connection.
  939. dialParams.dialConfig.ResolvedIPCallback = func(IPAddress string) {
  940. dialParams.MeekResolvedIPAddress.Store(IPAddress)
  941. }
  942. if isTactics {
  943. dialParams.meekConfig.Mode = MeekModeObfuscatedRoundTrip
  944. } else if dialParams.ConjureAPIRegistration {
  945. dialParams.meekConfig.Mode = MeekModePlaintextRoundTrip
  946. } else {
  947. dialParams.meekConfig.Mode = MeekModeRelay
  948. }
  949. }
  950. return dialParams, nil
  951. }
  952. func (dialParams *DialParameters) GetDialConfig() *DialConfig {
  953. return dialParams.dialConfig
  954. }
  955. func (dialParams *DialParameters) GetTLSOSSHConfig(config *Config) *TLSTunnelConfig {
  956. return &TLSTunnelConfig{
  957. CustomTLSConfig: &CustomTLSConfig{
  958. Parameters: config.GetParameters(),
  959. DialAddr: dialParams.DirectDialAddress,
  960. SNIServerName: dialParams.TLSOSSHSNIServerName,
  961. SkipVerify: true,
  962. VerifyServerName: "",
  963. VerifyPins: nil,
  964. TLSProfile: dialParams.TLSProfile,
  965. NoDefaultTLSSessionID: &dialParams.NoDefaultTLSSessionID,
  966. RandomizedTLSProfileSeed: dialParams.RandomizedTLSProfileSeed,
  967. },
  968. // Obfuscated session tickets are not used because TLS-OSSH uses TLS 1.3.
  969. UseObfuscatedSessionTickets: false,
  970. // Meek obfuscated key used to allow clients with legacy unfronted
  971. // meek-https server entries, that have the passthrough capability, to
  972. // connect with TLS-OSSH to the servers corresponding to those server
  973. // entries, which now support TLS-OSSH by demultiplexing meek-https and
  974. // TLS-OSSH over the meek-https port.
  975. ObfuscatedKey: dialParams.ServerEntry.MeekObfuscatedKey,
  976. ObfuscatorPaddingSeed: dialParams.TLSOSSHObfuscatorPaddingSeed,
  977. }
  978. }
  979. func (dialParams *DialParameters) GetMeekConfig() *MeekConfig {
  980. return dialParams.meekConfig
  981. }
  982. // GetNetworkType returns a network type name, suitable for metrics, which is
  983. // derived from the network ID.
  984. func (dialParams *DialParameters) GetNetworkType() string {
  985. // Unlike the logic in loggingNetworkIDGetter.GetNetworkID, we don't take the
  986. // arbitrary text before the first "-" since some platforms without network
  987. // detection support stub in random values to enable tactics. Instead we
  988. // check for and use the common network type prefixes currently used in
  989. // NetworkIDGetter implementations.
  990. if strings.HasPrefix(dialParams.NetworkID, "VPN") {
  991. return "VPN"
  992. }
  993. if strings.HasPrefix(dialParams.NetworkID, "WIFI") {
  994. return "WIFI"
  995. }
  996. if strings.HasPrefix(dialParams.NetworkID, "MOBILE") {
  997. return "MOBILE"
  998. }
  999. return "UNKNOWN"
  1000. }
  1001. func (dialParams *DialParameters) Succeeded() {
  1002. // When TTL is 0, don't store dial parameters.
  1003. if dialParams.LastUsedTimestamp.IsZero() {
  1004. return
  1005. }
  1006. NoticeInfo("Set dial parameters for %s", dialParams.ServerEntry.GetDiagnosticID())
  1007. err := SetDialParameters(dialParams.ServerEntry.IpAddress, dialParams.NetworkID, dialParams)
  1008. if err != nil {
  1009. NoticeWarning("SetDialParameters failed: %s", err)
  1010. }
  1011. }
  1012. func (dialParams *DialParameters) Failed(config *Config) {
  1013. // When a tunnel fails, and the dial is a replay, clear the stored dial
  1014. // parameters which are now presumed to be blocked, impaired or otherwise
  1015. // no longer effective.
  1016. //
  1017. // It may be the case that a dial is not using stored dial parameters
  1018. // (!IsReplay), and in this case we retain those dial parameters since they
  1019. // were not exercised and may still be effective.
  1020. //
  1021. // Failed tunnel dial parameters may be retained with a configurable
  1022. // probability; this is intended to help mitigate false positive failures due
  1023. // to, e.g., temporary network disruptions or server load limiting.
  1024. if dialParams.IsReplay &&
  1025. !config.GetParameters().Get().WeightedCoinFlip(
  1026. parameters.ReplayRetainFailedProbability) {
  1027. NoticeInfo("Delete dial parameters for %s", dialParams.ServerEntry.GetDiagnosticID())
  1028. err := DeleteDialParameters(dialParams.ServerEntry.IpAddress, dialParams.NetworkID)
  1029. if err != nil {
  1030. NoticeWarning("DeleteDialParameters failed: %s", err)
  1031. }
  1032. }
  1033. }
  1034. func (dialParams *DialParameters) GetTLSVersionForMetrics() string {
  1035. tlsVersion := dialParams.TLSVersion
  1036. if dialParams.NoDefaultTLSSessionID {
  1037. tlsVersion += "-no_def_id"
  1038. }
  1039. return tlsVersion
  1040. }
  1041. // ExchangedDialParameters represents the subset of DialParameters that is
  1042. // shared in a client-to-client exchange of server connection info.
  1043. //
  1044. // The purpose of client-to-client exchange if for one user that can connect
  1045. // to help another user that cannot connect by sharing their connected
  1046. // configuration, including the server entry and dial parameters.
  1047. //
  1048. // There are two concerns regarding which dial parameter fields are safe to
  1049. // exchange:
  1050. //
  1051. // - Unlike signed server entries, there's no independent trust anchor
  1052. // that can certify that the exchange data is valid.
  1053. //
  1054. // - While users should only perform the exchange with trusted peers,
  1055. // the user's trust in their peer may be misplaced.
  1056. //
  1057. // This presents the possibility of attack such as the peer sending dial
  1058. // parameters that could be used to trace/monitor/flag the importer; or
  1059. // sending dial parameters, including dial address and SNI, to cause the peer
  1060. // to appear to connect to a banned service.
  1061. //
  1062. // To mitigate these risks, only a subset of dial parameters are exchanged.
  1063. // When exchanged dial parameters and imported and used, all unexchanged
  1064. // parameters are generated locally. At this time, only the tunnel protocol is
  1065. // exchanged. We consider tunnel protocol selection one of the key connection
  1066. // success factors.
  1067. //
  1068. // In addition, the exchange peers may not be on the same network with the
  1069. // same blocking and circumvention characteristics, which is another reason
  1070. // to limit exchanged dial parameter values to broadly applicable fields.
  1071. //
  1072. // Unlike the exchanged (and otherwise acquired) server entry,
  1073. // ExchangedDialParameters does not use the ServerEntry_Fields_ representation
  1074. // which allows older clients to receive and store new, unknown fields. Such a
  1075. // facility is less useful in this case, since exchanged dial parameters and
  1076. // used immediately and have a short lifespan.
  1077. //
  1078. // TODO: exchange more dial parameters, such as TLS profile, QUIC version, etc.
  1079. type ExchangedDialParameters struct {
  1080. TunnelProtocol string
  1081. }
  1082. // NewExchangedDialParameters creates a new ExchangedDialParameters from a
  1083. // DialParameters, including only the exchanged values.
  1084. // NewExchangedDialParameters assumes the input DialParameters has been
  1085. // initialized and populated by MakeDialParameters.
  1086. func NewExchangedDialParameters(dialParams *DialParameters) *ExchangedDialParameters {
  1087. return &ExchangedDialParameters{
  1088. TunnelProtocol: dialParams.TunnelProtocol,
  1089. }
  1090. }
  1091. // Validate checks that the ExchangedDialParameters contains only valid values
  1092. // and is compatible with the specified server entry.
  1093. func (dialParams *ExchangedDialParameters) Validate(serverEntry *protocol.ServerEntry) error {
  1094. if !common.Contains(protocol.SupportedTunnelProtocols, dialParams.TunnelProtocol) {
  1095. return errors.Tracef("unknown tunnel protocol: %s", dialParams.TunnelProtocol)
  1096. }
  1097. if !serverEntry.SupportsProtocol(dialParams.TunnelProtocol) {
  1098. return errors.Tracef("unsupported tunnel protocol: %s", dialParams.TunnelProtocol)
  1099. }
  1100. return nil
  1101. }
  1102. // MakeDialParameters creates a new, partially intitialized DialParameters
  1103. // from the values in ExchangedDialParameters. The returned DialParameters
  1104. // must not be used directly for dialing. It is intended to be stored, and
  1105. // then later fully initialized by MakeDialParameters.
  1106. func (dialParams *ExchangedDialParameters) MakeDialParameters(
  1107. config *Config,
  1108. p parameters.ParametersAccessor,
  1109. serverEntry *protocol.ServerEntry) *DialParameters {
  1110. configStateHash, serverEntryHash := getDialStateHashes(config, p, serverEntry)
  1111. return &DialParameters{
  1112. IsExchanged: true,
  1113. LastUsedTimestamp: time.Now(),
  1114. LastUsedConfigStateHash: configStateHash,
  1115. LastUsedServerEntryHash: serverEntryHash,
  1116. TunnelProtocol: dialParams.TunnelProtocol,
  1117. }
  1118. }
  1119. // getDialStateHashes returns two hashes: the config state hash reflects the
  1120. // config dial parameters and tactics tag used for a dial; and the server
  1121. // entry hash relects the server entry used for a dial.
  1122. //
  1123. // These hashes change if the input values change in a way that invalidates
  1124. // any stored dial parameters.
  1125. func getDialStateHashes(
  1126. config *Config,
  1127. p parameters.ParametersAccessor,
  1128. serverEntry *protocol.ServerEntry) ([]byte, []byte) {
  1129. // MD5 hash is used solely as a data checksum and not for any security
  1130. // purpose.
  1131. hash := md5.New()
  1132. // Add a hash of relevant dial parameter config fields. Config fields
  1133. // that change due to user preference changes, such as selected egress
  1134. // region, are not to be included in config.dialParametersHash.
  1135. //
  1136. // Limitation: the config hash may change even when tactics will override the
  1137. // changed config field.
  1138. hash.Write(config.dialParametersHash)
  1139. // Add the active tactics tag.
  1140. hash.Write([]byte(p.Tag()))
  1141. clientStateHash := hash.Sum(nil)
  1142. hash = md5.New()
  1143. // Add the server entry version and local timestamp, both of which should
  1144. // change when the server entry contents change and/or a new local copy is
  1145. // imported.
  1146. // TODO: marshal entire server entry?
  1147. var serverEntryConfigurationVersion [8]byte
  1148. binary.BigEndian.PutUint64(
  1149. serverEntryConfigurationVersion[:],
  1150. uint64(serverEntry.ConfigurationVersion))
  1151. hash.Write(serverEntryConfigurationVersion[:])
  1152. hash.Write([]byte(serverEntry.LocalTimestamp))
  1153. serverEntryHash := hash.Sum(nil)
  1154. return clientStateHash, serverEntryHash
  1155. }
  1156. func selectFrontingParameters(
  1157. serverEntry *protocol.ServerEntry) (string, string, error) {
  1158. frontingDialHost := ""
  1159. frontingHost := ""
  1160. if len(serverEntry.MeekFrontingAddressesRegex) > 0 {
  1161. // Generate a front address based on the regex.
  1162. var err error
  1163. frontingDialHost, err = regen.GenerateString(serverEntry.MeekFrontingAddressesRegex)
  1164. if err != nil {
  1165. return "", "", errors.Trace(err)
  1166. }
  1167. } else {
  1168. // Randomly select, for this connection attempt, one front address for
  1169. // fronting-capable servers.
  1170. if len(serverEntry.MeekFrontingAddresses) == 0 {
  1171. return "", "", errors.TraceNew("MeekFrontingAddresses is empty")
  1172. }
  1173. index := prng.Intn(len(serverEntry.MeekFrontingAddresses))
  1174. frontingDialHost = serverEntry.MeekFrontingAddresses[index]
  1175. }
  1176. if len(serverEntry.MeekFrontingHosts) > 0 {
  1177. index := prng.Intn(len(serverEntry.MeekFrontingHosts))
  1178. frontingHost = serverEntry.MeekFrontingHosts[index]
  1179. } else {
  1180. // Backwards compatibility case
  1181. frontingHost = serverEntry.MeekFrontingHost
  1182. }
  1183. return frontingDialHost, frontingHost, nil
  1184. }
  1185. func selectQUICVersion(
  1186. isFronted bool,
  1187. serverEntry *protocol.ServerEntry,
  1188. p parameters.ParametersAccessor) string {
  1189. limitQUICVersions := p.QUICVersions(parameters.LimitQUICVersions)
  1190. var disableQUICVersions protocol.QUICVersions
  1191. if isFronted {
  1192. if serverEntry.FrontingProviderID == "" {
  1193. // Legacy server entry case
  1194. disableQUICVersions = protocol.QUICVersions{
  1195. protocol.QUIC_VERSION_V1,
  1196. protocol.QUIC_VERSION_RANDOMIZED_V1,
  1197. protocol.QUIC_VERSION_OBFUSCATED_V1,
  1198. protocol.QUIC_VERSION_DECOY_V1,
  1199. }
  1200. } else {
  1201. disableQUICVersions = p.LabeledQUICVersions(
  1202. parameters.DisableFrontingProviderQUICVersions,
  1203. serverEntry.FrontingProviderID)
  1204. }
  1205. }
  1206. quicVersions := make([]string, 0)
  1207. // Don't use gQUIC versions when the server entry specifies QUICv1-only.
  1208. supportedQUICVersions := protocol.SupportedQUICVersions
  1209. if serverEntry.SupportsOnlyQUICv1() {
  1210. supportedQUICVersions = protocol.SupportedQUICv1Versions
  1211. }
  1212. for _, quicVersion := range supportedQUICVersions {
  1213. if len(limitQUICVersions) > 0 &&
  1214. !common.Contains(limitQUICVersions, quicVersion) {
  1215. continue
  1216. }
  1217. // Both tactics and the server entry can specify LimitQUICVersions. In
  1218. // tactics, the parameter is intended to direct certain clients to
  1219. // use a successful protocol variant. In the server entry, the
  1220. // parameter may be used to direct all clients to send
  1221. // consistent-looking protocol variants to a particular server; e.g.,
  1222. // only regular QUIC, or only obfuscated QUIC.
  1223. //
  1224. // The isFronted/QUICVersionIsObfuscated logic predates
  1225. // ServerEntry.LimitQUICVersions; ServerEntry.LimitQUICVersions could
  1226. // now be used to achieve a similar outcome.
  1227. if len(serverEntry.LimitQUICVersions) > 0 &&
  1228. !common.Contains(serverEntry.LimitQUICVersions, quicVersion) {
  1229. continue
  1230. }
  1231. if isFronted &&
  1232. protocol.QUICVersionIsObfuscated(quicVersion) {
  1233. continue
  1234. }
  1235. if common.Contains(disableQUICVersions, quicVersion) {
  1236. continue
  1237. }
  1238. quicVersions = append(quicVersions, quicVersion)
  1239. }
  1240. if len(quicVersions) == 0 {
  1241. return ""
  1242. }
  1243. choice := prng.Intn(len(quicVersions))
  1244. return quicVersions[choice]
  1245. }
  1246. // selectUserAgentIfUnset selects a User-Agent header if one is not set.
  1247. func selectUserAgentIfUnset(
  1248. p parameters.ParametersAccessor, headers http.Header) (bool, string) {
  1249. if _, ok := headers["User-Agent"]; !ok {
  1250. userAgent := ""
  1251. if p.WeightedCoinFlip(parameters.PickUserAgentProbability) {
  1252. userAgent = values.GetUserAgent()
  1253. }
  1254. return true, userAgent
  1255. }
  1256. return false, ""
  1257. }
  1258. func makeDialCustomHeaders(
  1259. config *Config,
  1260. p parameters.ParametersAccessor) http.Header {
  1261. dialCustomHeaders := make(http.Header)
  1262. if config.CustomHeaders != nil {
  1263. for k, v := range config.CustomHeaders {
  1264. dialCustomHeaders[k] = make([]string, len(v))
  1265. copy(dialCustomHeaders[k], v)
  1266. }
  1267. }
  1268. additionalCustomHeaders := p.HTTPHeaders(parameters.AdditionalCustomHeaders)
  1269. for k, v := range additionalCustomHeaders {
  1270. dialCustomHeaders[k] = make([]string, len(v))
  1271. copy(dialCustomHeaders[k], v)
  1272. }
  1273. return dialCustomHeaders
  1274. }
  1275. func selectHostName(
  1276. tunnelProtocol string, p parameters.ParametersAccessor) string {
  1277. limitProtocols := p.TunnelProtocols(parameters.CustomHostNameLimitProtocols)
  1278. if len(limitProtocols) > 0 && !common.Contains(limitProtocols, tunnelProtocol) {
  1279. return values.GetHostName()
  1280. }
  1281. if !p.WeightedCoinFlip(parameters.CustomHostNameProbability) {
  1282. return values.GetHostName()
  1283. }
  1284. regexStrings := p.RegexStrings(parameters.CustomHostNameRegexes)
  1285. if len(regexStrings) == 0 {
  1286. return values.GetHostName()
  1287. }
  1288. choice := prng.Intn(len(regexStrings))
  1289. hostName, err := regen.GenerateString(regexStrings[choice])
  1290. if err != nil {
  1291. NoticeWarning("selectHostName: regen.Generate failed: %v", errors.Trace(err))
  1292. return values.GetHostName()
  1293. }
  1294. return hostName
  1295. }
  1296. // makeHTTPTransformerParameters generates HTTPTransformerParameters using the
  1297. // input tactics parameters and optional frontingProviderID context.
  1298. func makeHTTPTransformerParameters(p parameters.ParametersAccessor,
  1299. frontingProviderID string, isFronted bool) (*transforms.HTTPTransformerParameters, error) {
  1300. params := transforms.HTTPTransformerParameters{}
  1301. // Select an HTTP transform. If the request is fronted, HTTP request
  1302. // transforms are "scoped" by fronting provider ID. Otherwise, a transform
  1303. // from the default scope (transforms.SCOPE_ANY == "") is selected.
  1304. var specsKey string
  1305. var scopedSpecsNamesKey string
  1306. useTransform := false
  1307. scope := transforms.SCOPE_ANY
  1308. if isFronted {
  1309. if p.WeightedCoinFlip(parameters.FrontedHTTPProtocolTransformProbability) {
  1310. useTransform = true
  1311. scope = frontingProviderID
  1312. specsKey = parameters.FrontedHTTPProtocolTransformSpecs
  1313. scopedSpecsNamesKey = parameters.FrontedHTTPProtocolTransformScopedSpecNames
  1314. }
  1315. } else {
  1316. // unfronted
  1317. if p.WeightedCoinFlip(parameters.DirectHTTPProtocolTransformProbability) {
  1318. useTransform = true
  1319. specsKey = parameters.DirectHTTPProtocolTransformSpecs
  1320. scopedSpecsNamesKey = parameters.DirectHTTPProtocolTransformScopedSpecNames
  1321. }
  1322. }
  1323. if useTransform {
  1324. specs := p.ProtocolTransformSpecs(
  1325. specsKey)
  1326. scopedSpecNames := p.ProtocolTransformScopedSpecNames(
  1327. scopedSpecsNamesKey)
  1328. name, spec := specs.Select(scope, scopedSpecNames)
  1329. if spec != nil {
  1330. params.ProtocolTransformName = name
  1331. params.ProtocolTransformSpec = spec
  1332. var err error
  1333. // transform seed generated
  1334. params.ProtocolTransformSeed, err = prng.NewSeed()
  1335. if err != nil {
  1336. return nil, errors.Trace(err)
  1337. }
  1338. }
  1339. }
  1340. return &params, nil
  1341. }
  1342. // makeSeedTransformerParameters generates ObfuscatorSeedTransformerParameters
  1343. // using the input tactics parameters.
  1344. func makeSeedTransformerParameters(p parameters.ParametersAccessor,
  1345. probabilityFieldName, specsKey, scopedSpecsKey string) (*transforms.ObfuscatorSeedTransformerParameters, error) {
  1346. if !p.WeightedCoinFlip(probabilityFieldName) {
  1347. return &transforms.ObfuscatorSeedTransformerParameters{}, nil
  1348. }
  1349. seed, err := prng.NewSeed()
  1350. if err != nil {
  1351. return nil, errors.Trace(err)
  1352. }
  1353. specs := p.ProtocolTransformSpecs(specsKey)
  1354. scopedSpecNames := p.ProtocolTransformScopedSpecNames(scopedSpecsKey)
  1355. name, spec := specs.Select(transforms.SCOPE_ANY, scopedSpecNames)
  1356. if spec == nil {
  1357. return &transforms.ObfuscatorSeedTransformerParameters{}, nil
  1358. } else {
  1359. return &transforms.ObfuscatorSeedTransformerParameters{
  1360. TransformName: name,
  1361. TransformSpec: spec,
  1362. TransformSeed: seed,
  1363. }, nil
  1364. }
  1365. }
  1366. func makeOSSHPrefixSpecParameters(
  1367. p parameters.ParametersAccessor,
  1368. dialPortNumber string) (*obfuscator.OSSHPrefixSpec, error) {
  1369. if !p.WeightedCoinFlip(parameters.OSSHPrefixProbability) {
  1370. return &obfuscator.OSSHPrefixSpec{}, nil
  1371. }
  1372. specs := p.ProtocolTransformSpecs(parameters.OSSHPrefixSpecs)
  1373. scopedSpecNames := p.ProtocolTransformScopedSpecNames(parameters.OSSHPrefixScopedSpecNames)
  1374. name, spec := specs.Select(dialPortNumber, scopedSpecNames)
  1375. if spec == nil {
  1376. return &obfuscator.OSSHPrefixSpec{}, nil
  1377. } else {
  1378. seed, err := prng.NewSeed()
  1379. if err != nil {
  1380. return nil, errors.Trace(err)
  1381. }
  1382. return &obfuscator.OSSHPrefixSpec{
  1383. Name: name,
  1384. Spec: spec,
  1385. Seed: seed,
  1386. }, nil
  1387. }
  1388. }
  1389. func makeOSSHPrefixSplitConfig(p parameters.ParametersAccessor) (*obfuscator.OSSHPrefixSplitConfig, error) {
  1390. minDelay := p.Duration(parameters.OSSHPrefixSplitMinDelay)
  1391. maxDelay := p.Duration(parameters.OSSHPrefixSplitMaxDelay)
  1392. seed, err := prng.NewSeed()
  1393. if err != nil {
  1394. return nil, errors.Trace(err)
  1395. }
  1396. return &obfuscator.OSSHPrefixSplitConfig{
  1397. Seed: seed,
  1398. MinDelay: minDelay,
  1399. MaxDelay: maxDelay,
  1400. }, nil
  1401. }