dialParameters.go 55 KB

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