dialParameters.go 70 KB

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