dialParameters.go 55 KB

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