dialParameters.go 80 KB

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