dialParameters.go 75 KB

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