dialParameters.go 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204
  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. QUICDisableObfuscatedPSK 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. // fronting provider ID. See the corresponding server-side enforcement
  425. // comments in server.MeekServer.getSessionOrEndpoint.
  426. //
  427. // RestrictFrontingProviderIDs applies only to fronted meek tunnels, where
  428. // all traffic is relayed through a fronting provider.
  429. if protocol.TunnelProtocolUsesFrontedMeek(dialParams.TunnelProtocol) &&
  430. common.Contains(
  431. p.Strings(parameters.RestrictFrontingProviderIDs),
  432. dialParams.ServerEntry.FrontingProviderID) {
  433. if p.WeightedCoinFlip(
  434. parameters.RestrictFrontingProviderIDsClientProbability) {
  435. // When skipping, return nil/nil as no error should be logged.
  436. // NoticeSkipServerEntry emits each skip reason, regardless
  437. // of server entry, at most once per session.
  438. NoticeSkipServerEntry(
  439. "restricted fronting provider ID: %s",
  440. dialParams.ServerEntry.FrontingProviderID)
  441. return nil, nil
  442. }
  443. }
  444. if config.UseUpstreamProxy() {
  445. // When UpstreamProxy is configured, ServerEntry.GetSupportedProtocols, when
  446. // called via selectProtocol, will filter out protocols such that will not
  447. // select a protocol incompatible with UpstreamProxy. This additional check
  448. // will catch cases where selectProtocol does not apply this filter.
  449. if !protocol.TunnelProtocolSupportsUpstreamProxy(dialParams.TunnelProtocol) {
  450. NoticeSkipServerEntry(
  451. "protocol does not support upstream proxy: %s",
  452. dialParams.TunnelProtocol)
  453. return nil, nil
  454. }
  455. // Skip this candidate when the server entry is not to be used with an
  456. // upstream proxy. By not exposing servers from sources that are
  457. // relatively hard to enumerate, this mechanism mitigates the risk of
  458. // a malicious upstream proxy enumerating Psiphon servers. Populate
  459. // the allowed sources with fronted servers to provide greater
  460. // blocking resistence for clients using upstream proxy clients that
  461. // are subject to blocking.
  462. source := dialParams.ServerEntry.LocalSource
  463. if !protocol.AllowServerEntrySourceWithUpstreamProxy(source) &&
  464. !p.Bool(parameters.UpstreamProxyAllowAllServerEntrySources) {
  465. NoticeSkipServerEntry(
  466. "server entry source disallowed with upstream proxy: %s",
  467. source)
  468. return nil, nil
  469. }
  470. }
  471. if (!isReplay || !replayBPF) &&
  472. ClientBPFEnabled() &&
  473. protocol.TunnelProtocolMayUseClientBPF(dialParams.TunnelProtocol) {
  474. if p.WeightedCoinFlip(parameters.BPFClientTCPProbability) {
  475. dialParams.BPFProgramName = ""
  476. dialParams.BPFProgramInstructions = nil
  477. ok, name, rawInstructions := p.BPFProgram(parameters.BPFClientTCPProgram)
  478. if ok {
  479. dialParams.BPFProgramName = name
  480. dialParams.BPFProgramInstructions = rawInstructions
  481. }
  482. }
  483. }
  484. if !isReplay || !replaySSH {
  485. dialParams.SelectedSSHClientVersion = true
  486. dialParams.SSHClientVersion = values.GetSSHClientVersion()
  487. dialParams.SSHKEXSeed, err = prng.NewSeed()
  488. if err != nil {
  489. return nil, errors.Trace(err)
  490. }
  491. }
  492. if !isReplay || !replayObfuscatorPadding {
  493. dialParams.ObfuscatorPaddingSeed, err = prng.NewSeed()
  494. if err != nil {
  495. return nil, errors.Trace(err)
  496. }
  497. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) {
  498. dialParams.MeekObfuscatorPaddingSeed, err = prng.NewSeed()
  499. if err != nil {
  500. return nil, errors.Trace(err)
  501. }
  502. } else if protocol.TunnelProtocolUsesTLSOSSH(dialParams.TunnelProtocol) {
  503. dialParams.TLSOSSHObfuscatorPaddingSeed, err = prng.NewSeed()
  504. if err != nil {
  505. return nil, errors.Trace(err)
  506. }
  507. }
  508. }
  509. if !isReplay || !replayFragmentor {
  510. dialParams.FragmentorSeed, err = prng.NewSeed()
  511. if err != nil {
  512. return nil, errors.Trace(err)
  513. }
  514. }
  515. if (!isReplay || !replayConjureRegistration) &&
  516. protocol.TunnelProtocolUsesConjure(dialParams.TunnelProtocol) {
  517. dialParams.ConjureCachedRegistrationTTL = p.Duration(parameters.ConjureCachedRegistrationTTL)
  518. apiURL := p.String(parameters.ConjureAPIRegistrarBidirectionalURL)
  519. decoyWidth := p.Int(parameters.ConjureDecoyRegistrarWidth)
  520. dialParams.ConjureAPIRegistration = apiURL != ""
  521. dialParams.ConjureDecoyRegistration = decoyWidth != 0
  522. // We select only one of API or decoy registration. When both are enabled,
  523. // ConjureDecoyRegistrarProbability determines the probability of using
  524. // decoy registration.
  525. //
  526. // In general, we disable retries in gotapdance and rely on Psiphon
  527. // establishment to try/retry different registration schemes. This allows us
  528. // to control the proportion of registration types attempted. And, in good
  529. // network conditions, individual candidates are most likely to be cancelled
  530. // before they exhaust their retry options.
  531. if dialParams.ConjureAPIRegistration && dialParams.ConjureDecoyRegistration {
  532. if p.WeightedCoinFlip(parameters.ConjureDecoyRegistrarProbability) {
  533. dialParams.ConjureAPIRegistration = false
  534. }
  535. }
  536. if dialParams.ConjureAPIRegistration {
  537. // While Conjure API registration uses MeekConn and specifies common meek
  538. // parameters, the meek address and SNI configuration is implemented in this
  539. // code block and not in common code blocks below. The exception is TLS
  540. // configuration.
  541. //
  542. // Accordingly, replayFronting/replayHostname have no effect on Conjure API
  543. // registration replay.
  544. dialParams.ConjureAPIRegistrarBidirectionalURL = apiURL
  545. frontingSpecs := p.FrontingSpecs(parameters.ConjureAPIRegistrarFrontingSpecs)
  546. var frontingTransport string
  547. dialParams.FrontingProviderID,
  548. frontingTransport,
  549. dialParams.MeekFrontingDialAddress,
  550. dialParams.MeekSNIServerName,
  551. dialParams.MeekVerifyServerName,
  552. dialParams.MeekVerifyPins,
  553. dialParams.MeekFrontingHost,
  554. err = frontingSpecs.SelectParameters()
  555. if err != nil {
  556. return nil, errors.Trace(err)
  557. }
  558. if frontingTransport != protocol.FRONTING_TRANSPORT_HTTPS {
  559. return nil, errors.TraceNew("unsupported fronting transport")
  560. }
  561. if config.DisableSystemRootCAs {
  562. return nil, errors.TraceNew("TLS certificates must be verified in Conjure API registration")
  563. }
  564. dialParams.MeekDialAddress = net.JoinHostPort(dialParams.MeekFrontingDialAddress, "443")
  565. dialParams.MeekHostHeader = dialParams.MeekFrontingHost
  566. // For a FrontingSpec, an SNI value of "" indicates to disable/omit SNI, so
  567. // never transform in that case.
  568. if dialParams.MeekSNIServerName != "" {
  569. if p.WeightedCoinFlip(parameters.TransformHostNameProbability) {
  570. dialParams.MeekSNIServerName = selectHostName(dialParams.TunnelProtocol, p)
  571. dialParams.MeekTransformedHostName = true
  572. }
  573. }
  574. // The minimum delay value is determined by the Conjure station, which
  575. // performs an asynchronous "liveness test" against the selected phantom
  576. // IPs. The min/max range allows us to introduce some jitter so that we
  577. // don't present a trivial inter-flow fingerprint: CDN connection, fixed
  578. // delay, phantom dial.
  579. minDelay := p.Duration(parameters.ConjureAPIRegistrarMinDelay)
  580. maxDelay := p.Duration(parameters.ConjureAPIRegistrarMaxDelay)
  581. dialParams.ConjureAPIRegistrarDelay = prng.Period(minDelay, maxDelay)
  582. } else if dialParams.ConjureDecoyRegistration {
  583. dialParams.ConjureDecoyRegistrarWidth = decoyWidth
  584. minDelay := p.Duration(parameters.ConjureDecoyRegistrarMinDelay)
  585. maxDelay := p.Duration(parameters.ConjureDecoyRegistrarMaxDelay)
  586. dialParams.ConjureAPIRegistrarDelay = prng.Period(minDelay, maxDelay)
  587. } else {
  588. return nil, errors.TraceNew("no Conjure registrar configured")
  589. }
  590. }
  591. if (!isReplay || !replayConjureTransport) &&
  592. protocol.TunnelProtocolUsesConjure(dialParams.TunnelProtocol) {
  593. // None of ConjureEnableIPv6Dials, ConjureEnablePortRandomization, or
  594. // ConjureEnableRegistrationOverrides are set here for replay. The
  595. // current value of these flag parameters is always applied.
  596. dialParams.ConjureTransport = selectConjureTransport(p)
  597. if protocol.ConjureTransportUsesSTUN(dialParams.ConjureTransport) {
  598. stunServerAddresses := p.Strings(parameters.ConjureSTUNServerAddresses)
  599. if len(stunServerAddresses) == 0 {
  600. return nil, errors.Tracef(
  601. "no Conjure STUN servers addresses configured for transport %s", dialParams.ConjureTransport)
  602. }
  603. dialParams.ConjureSTUNServerAddress = stunServerAddresses[prng.Intn(len(stunServerAddresses))]
  604. dialParams.ConjureDTLSEmptyInitialPacket = p.WeightedCoinFlip(
  605. parameters.ConjureDTLSEmptyInitialPacketProbability)
  606. }
  607. }
  608. usingTLS := protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol) ||
  609. protocol.TunnelProtocolUsesTLSOSSH(dialParams.TunnelProtocol) ||
  610. dialParams.ConjureAPIRegistration
  611. if tlsClientSessionCache != nil && usingTLS {
  612. sessionKey, err := serverEntry.GetTLSSessionCacheKeyAddress(dialParams.TunnelProtocol)
  613. if err != nil {
  614. return nil, errors.Trace(err)
  615. }
  616. dialParams.tlsClientSessionCache = common.WrapUtlsClientSessionCache(tlsClientSessionCache, sessionKey)
  617. if !isReplay {
  618. // Remove the cache entry to make a fresh dial when !isReplay.
  619. dialParams.tlsClientSessionCache.RemoveCacheEntry()
  620. }
  621. }
  622. if (!isReplay || !replayTLSProfile) && usingTLS {
  623. dialParams.SelectedTLSProfile = true
  624. requireTLS12SessionTickets := protocol.TunnelProtocolRequiresTLS12SessionTickets(
  625. dialParams.TunnelProtocol)
  626. requireTLS13Support := protocol.TunnelProtocolRequiresTLS13Support(dialParams.TunnelProtocol)
  627. isFronted := protocol.TunnelProtocolUsesFrontedMeek(dialParams.TunnelProtocol) ||
  628. dialParams.ConjureAPIRegistration
  629. dialParams.TLSProfile, dialParams.TLSVersion, dialParams.RandomizedTLSProfileSeed, err = SelectTLSProfile(
  630. requireTLS12SessionTickets, requireTLS13Support, isFronted, serverEntry.FrontingProviderID, p)
  631. if err != nil {
  632. return nil, errors.Trace(err)
  633. }
  634. if dialParams.TLSProfile == "" && (requireTLS12SessionTickets || requireTLS13Support) {
  635. return nil, errors.TraceNew("required TLS profile not found")
  636. }
  637. dialParams.NoDefaultTLSSessionID = p.WeightedCoinFlip(
  638. parameters.NoDefaultTLSSessionIDProbability)
  639. }
  640. if (!isReplay || !replayFronting) &&
  641. protocol.TunnelProtocolUsesFrontedMeek(dialParams.TunnelProtocol) {
  642. dialParams.FrontingProviderID = serverEntry.FrontingProviderID
  643. dialParams.MeekFrontingDialAddress, dialParams.MeekFrontingHost, err =
  644. selectFrontingParameters(serverEntry)
  645. if err != nil {
  646. return nil, errors.Trace(err)
  647. }
  648. }
  649. if !isReplay || !replayHostname {
  650. // Any MeekHostHeader selections made here will be overridden below,
  651. // as required, for fronting cases.
  652. if protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol) ||
  653. protocol.TunnelProtocolUsesFrontedMeekQUIC(dialParams.TunnelProtocol) {
  654. dialParams.MeekSNIServerName = ""
  655. hostname := ""
  656. if p.WeightedCoinFlip(parameters.TransformHostNameProbability) {
  657. dialParams.MeekSNIServerName = selectHostName(dialParams.TunnelProtocol, p)
  658. hostname = dialParams.MeekSNIServerName
  659. dialParams.MeekTransformedHostName = true
  660. } else {
  661. // Always select a hostname for the Host header in this case.
  662. // Unlike HTTP, the Host header isn't plaintext on the wire,
  663. // and so there's no anti-fingerprint benefit from presenting
  664. // the server IP address in the Host header. Omitting the
  665. // server IP here can prevent exposing it in certain
  666. // scenarios where the traffic is rerouted and arrives at a
  667. // different HTTPS server.
  668. hostname = selectHostName(dialParams.TunnelProtocol, p)
  669. }
  670. if serverEntry.MeekServerPort == 443 {
  671. dialParams.MeekHostHeader = hostname
  672. } else {
  673. dialParams.MeekHostHeader = net.JoinHostPort(
  674. hostname, strconv.Itoa(serverEntry.MeekServerPort))
  675. }
  676. } else if protocol.TunnelProtocolUsesTLSOSSH(dialParams.TunnelProtocol) {
  677. dialParams.TLSOSSHSNIServerName = ""
  678. if p.WeightedCoinFlip(parameters.TransformHostNameProbability) {
  679. dialParams.TLSOSSHSNIServerName = selectHostName(dialParams.TunnelProtocol, p)
  680. dialParams.TLSOSSHTransformedSNIServerName = true
  681. }
  682. } else if protocol.TunnelProtocolUsesMeekHTTP(dialParams.TunnelProtocol) {
  683. dialParams.MeekHostHeader = ""
  684. hostname := serverEntry.IpAddress
  685. if p.WeightedCoinFlip(parameters.TransformHostNameProbability) {
  686. hostname = selectHostName(dialParams.TunnelProtocol, p)
  687. dialParams.MeekTransformedHostName = true
  688. }
  689. if serverEntry.MeekServerPort == 80 {
  690. dialParams.MeekHostHeader = hostname
  691. } else {
  692. dialParams.MeekHostHeader = net.JoinHostPort(
  693. hostname, strconv.Itoa(serverEntry.MeekServerPort))
  694. }
  695. } else if protocol.TunnelProtocolUsesQUIC(dialParams.TunnelProtocol) {
  696. dialParams.QUICDialSNIAddress = selectHostName(dialParams.TunnelProtocol, p)
  697. }
  698. }
  699. if (!isReplay || !replayQUICVersion) &&
  700. protocol.TunnelProtocolUsesQUIC(dialParams.TunnelProtocol) {
  701. isFronted := protocol.TunnelProtocolUsesFrontedMeekQUIC(dialParams.TunnelProtocol)
  702. isInproxy := protocol.TunnelProtocolUsesInproxy(dialParams.TunnelProtocol)
  703. dialParams.QUICVersion = selectQUICVersion(isFronted, isInproxy, serverEntry, p)
  704. // Due to potential tactics configurations, it may be that no QUIC
  705. // version is selected. Abort immediately, with no error, as in the
  706. // selectProtocol case. quic.Dial and quic.NewQUICTransporter will
  707. // check for a missing QUIC version, but at that later stage an
  708. // unnecessary failed_tunnel can be logged in this scenario.
  709. if dialParams.QUICVersion == "" {
  710. return nil, nil
  711. }
  712. if protocol.QUICVersionHasRandomizedClientHello(dialParams.QUICVersion) {
  713. dialParams.QUICClientHelloSeed, err = prng.NewSeed()
  714. if err != nil {
  715. return nil, errors.Trace(err)
  716. }
  717. }
  718. if isFronted {
  719. dialParams.QUICDisableObfuscatedPSK = true
  720. } else {
  721. dialParams.QUICDisableObfuscatedPSK = p.Bool(parameters.QUICDisableObfuscatedPSK)
  722. }
  723. dialParams.QUICDialEarly = p.WeightedCoinFlip(parameters.QUICDialEarlyProbability)
  724. dialParams.QUICDisablePathMTUDiscovery =
  725. protocol.QUICVersionUsesPathMTUDiscovery(dialParams.QUICVersion) &&
  726. p.WeightedCoinFlip(parameters.QUICDisableClientPathMTUDiscoveryProbability)
  727. }
  728. if quicTLSClientSessionCache != nil && protocol.TunnelProtocolUsesQUIC(dialParams.TunnelProtocol) {
  729. sessionKey, err := serverEntry.GetTLSSessionCacheKeyAddress(dialParams.TunnelProtocol)
  730. if err != nil {
  731. return nil, errors.Trace(err)
  732. }
  733. dialParams.quicTLSClientSessionCache = common.WrapClientSessionCache(
  734. quicTLSClientSessionCache,
  735. sessionKey)
  736. if !isReplay {
  737. // Remove the cache entry to make a fresh dial when !isReplay.
  738. dialParams.quicTLSClientSessionCache.RemoveCacheEntry()
  739. }
  740. }
  741. if (!isReplay || !replayObfuscatedQUIC) &&
  742. protocol.QUICVersionIsObfuscated(dialParams.QUICVersion) {
  743. dialParams.ObfuscatedQUICPaddingSeed, err = prng.NewSeed()
  744. if err != nil {
  745. return nil, errors.Trace(err)
  746. }
  747. }
  748. if protocol.QUICVersionIsObfuscated(dialParams.QUICVersion) {
  749. if serverEntry.DisableObfuscatedQUICTransforms {
  750. dialParams.ObfuscatedQUICNonceTransformerParameters = nil
  751. } else if !isReplay || !replayObfuscatedQUICNonceTransformer {
  752. params, err := makeSeedTransformerParameters(
  753. p,
  754. parameters.ObfuscatedQUICNonceTransformProbability,
  755. parameters.ObfuscatedQUICNonceTransformSpecs,
  756. parameters.ObfuscatedQUICNonceTransformScopedSpecNames)
  757. if err != nil {
  758. return nil, errors.Trace(err)
  759. }
  760. if params.TransformSpec != nil {
  761. dialParams.ObfuscatedQUICNonceTransformerParameters = params
  762. } else {
  763. dialParams.ObfuscatedQUICNonceTransformerParameters = nil
  764. }
  765. }
  766. }
  767. if !isReplay || !replayLivenessTest {
  768. // TODO: initialize only when LivenessTestMaxUp/DownstreamBytes > 0?
  769. dialParams.LivenessTestSeed, err = prng.NewSeed()
  770. if err != nil {
  771. return nil, errors.Trace(err)
  772. }
  773. }
  774. if !isReplay || !replayAPIRequestPadding {
  775. dialParams.APIRequestPaddingSeed, err = prng.NewSeed()
  776. if err != nil {
  777. return nil, errors.Trace(err)
  778. }
  779. }
  780. // Initialize dialParams.ResolveParameters for dials that will resolve
  781. // domain names, which currently includes fronted meek and Conjure API
  782. // registration, where the dial address is not an IP address.
  783. //
  784. // dialParams.ResolveParameters must be nil when the dial address is an IP
  785. // address to ensure that no DNS dial parameters are reported in metrics
  786. // or diagnostics when when no domain is resolved.
  787. //
  788. // No resolve parameters are initialized for in-proxy dials; broker and
  789. // STUN domain resolves use distinct ResolveParameters; and the proxy,
  790. // not the client, resolves any 2nd hop dial address domain.
  791. //
  792. // Limitation: DNSResolverPreresolvedIPAddressCIDRs could be applied by
  793. // the in-proxy client, and relayed to the proxy, enabling a preresolved
  794. // dial by the proxy, but this is currently not compatible with broker
  795. // dial destination verification.
  796. useResolver := (protocol.TunnelProtocolUsesFrontedMeek(dialParams.TunnelProtocol) ||
  797. dialParams.ConjureAPIRegistration) &&
  798. !protocol.TunnelProtocolUsesInproxy(dialParams.TunnelProtocol) &&
  799. net.ParseIP(dialParams.MeekFrontingDialAddress) == nil
  800. if (!isReplay || !replayResolveParameters) && useResolver {
  801. dialParams.ResolveParameters, err = dialParams.resolver.MakeResolveParameters(
  802. p, dialParams.FrontingProviderID, dialParams.MeekFrontingDialAddress)
  803. if err != nil {
  804. return nil, errors.Trace(err)
  805. }
  806. }
  807. if !isReplay || !replayHoldOffTunnel {
  808. var holdOffTunnelDuration time.Duration
  809. var holdOffDirectTunnelDuration time.Duration
  810. if common.Contains(
  811. p.TunnelProtocols(parameters.HoldOffTunnelProtocols), dialParams.TunnelProtocol) ||
  812. (protocol.TunnelProtocolUsesFrontedMeek(dialParams.TunnelProtocol) &&
  813. common.Contains(
  814. p.Strings(parameters.HoldOffTunnelFrontingProviderIDs),
  815. dialParams.FrontingProviderID)) {
  816. if p.WeightedCoinFlip(parameters.HoldOffTunnelProbability) {
  817. holdOffTunnelDuration = prng.Period(
  818. p.Duration(parameters.HoldOffTunnelMinDuration),
  819. p.Duration(parameters.HoldOffTunnelMaxDuration))
  820. }
  821. }
  822. if protocol.TunnelProtocolIsDirect(dialParams.TunnelProtocol) &&
  823. common.ContainsAny(
  824. p.KeyStrings(parameters.HoldOffDirectTunnelProviderRegions, dialParams.ServerEntry.ProviderID), []string{"", serverEntry.Region}) {
  825. if p.WeightedCoinFlip(parameters.HoldOffDirectTunnelProbability) {
  826. holdOffDirectTunnelDuration = prng.Period(
  827. p.Duration(parameters.HoldOffDirectTunnelMinDuration),
  828. p.Duration(parameters.HoldOffDirectTunnelMaxDuration))
  829. }
  830. }
  831. // Use the longest hold off duration
  832. if holdOffTunnelDuration >= holdOffDirectTunnelDuration {
  833. dialParams.HoldOffTunnelDuration = holdOffTunnelDuration
  834. } else {
  835. dialParams.HoldOffTunnelDuration = holdOffDirectTunnelDuration
  836. }
  837. }
  838. // OSSH prefix and seed transform are applied only to the OSSH tunnel protocol,
  839. // and not to any other protocol layered over OSSH.
  840. if protocol.TunnelProtocolIsObfuscatedSSH(dialParams.TunnelProtocol) {
  841. // Limitation: in the case of in-proxy OSSH, the client will get and
  842. // apply tactics based on its geolocation, but any OSSH prefix is
  843. // visible on the wire only after the 2nd hop. Configuring an OSSH
  844. // prefix based on the in-proxy proxy geolocation would be preferable.
  845. if serverEntry.DisableOSSHTransforms {
  846. dialParams.OSSHObfuscatorSeedTransformerParameters = nil
  847. } else if !isReplay || !replayOSSHSeedTransformerParameters {
  848. params, err := makeSeedTransformerParameters(
  849. p,
  850. parameters.OSSHObfuscatorSeedTransformProbability,
  851. parameters.OSSHObfuscatorSeedTransformSpecs,
  852. parameters.OSSHObfuscatorSeedTransformScopedSpecNames)
  853. if err != nil {
  854. return nil, errors.Trace(err)
  855. }
  856. if params.TransformSpec != nil {
  857. dialParams.OSSHObfuscatorSeedTransformerParameters = params
  858. } else {
  859. dialParams.OSSHObfuscatorSeedTransformerParameters = nil
  860. }
  861. }
  862. if serverEntry.DisableOSSHPrefix {
  863. dialParams.OSSHPrefixSpec = nil
  864. dialParams.OSSHPrefixSplitConfig = nil
  865. } else if !isReplay || !replayOSSHPrefix {
  866. dialPortNumber, err := serverEntry.GetDialPortNumber(dialParams.TunnelProtocol)
  867. if err != nil {
  868. return nil, errors.Trace(err)
  869. }
  870. prefixSpec, err := makeOSSHPrefixSpecParameters(p, strconv.Itoa(dialPortNumber))
  871. if err != nil {
  872. return nil, errors.Trace(err)
  873. }
  874. splitConfig, err := makeOSSHPrefixSplitConfig(p)
  875. if err != nil {
  876. return nil, errors.Trace(err)
  877. }
  878. if prefixSpec.Spec != nil {
  879. dialParams.OSSHPrefixSpec = prefixSpec
  880. dialParams.OSSHPrefixSplitConfig = splitConfig
  881. } else {
  882. dialParams.OSSHPrefixSpec = nil
  883. dialParams.OSSHPrefixSplitConfig = nil
  884. }
  885. }
  886. // OSSHPrefix supersedes OSSHObfuscatorSeedTransform.
  887. // This ensures both tactics are not used simultaneously,
  888. // until OSSHObfuscatorSeedTransform is removed.
  889. if dialParams.OSSHPrefixSpec != nil {
  890. dialParams.OSSHObfuscatorSeedTransformerParameters = nil
  891. }
  892. }
  893. if protocol.TunnelProtocolUsesMeekHTTP(dialParams.TunnelProtocol) {
  894. if serverEntry.DisableHTTPTransforms {
  895. dialParams.HTTPTransformerParameters = nil
  896. } else if !isReplay || !replayHTTPTransformerParameters {
  897. isFronted := protocol.TunnelProtocolUsesFrontedMeek(dialParams.TunnelProtocol)
  898. params, err := makeHTTPTransformerParameters(
  899. config.GetParameters().Get(), serverEntry.FrontingProviderID, isFronted)
  900. if err != nil {
  901. return nil, errors.Trace(err)
  902. }
  903. if params.ProtocolTransformSpec != nil {
  904. dialParams.HTTPTransformerParameters = params
  905. } else {
  906. dialParams.HTTPTransformerParameters = nil
  907. }
  908. }
  909. }
  910. // In-proxy dial configuration
  911. // For untunneled tactics requests, meek servers running in-proxy tunnel
  912. // protocols may be used, but the actual in-proxy 1st hop dial is skipped
  913. // and the meek server is used directly.
  914. if !isTactics && protocol.TunnelProtocolUsesInproxy(dialParams.TunnelProtocol) {
  915. // Check for incompatible networks, such as running under a
  916. // non-Psiphon VPN. While this check could be made before calling
  917. // MakeDialParameters, such as in selectProtocol during iteration,
  918. // checking here uses the network ID obtained in MakeDialParameters,
  919. // and the logged warning is useful for diagnostics.
  920. if !IsInproxyCompatibleNetworkType(dialParams.NetworkID) {
  921. return nil, errors.TraceNew("inproxy protocols skipped on incompatible network")
  922. }
  923. // inproxyDialInitialized indicates that the inproxy dial was wired
  924. // up, and this isn't an untunneled tactics request (isTactics).
  925. dialParams.inproxyDialInitialized = true
  926. // Store a reference to the current, shared in-proxy broker client.
  927. //
  928. // The broker client has its own, independent replay scheme and its
  929. // own dial parameters which are reported for metrics.
  930. dialParams.inproxyBrokerClient,
  931. dialParams.inproxyBrokerDialParameters,
  932. err = inproxyClientBrokerClientManager.GetBrokerClient(networkID)
  933. if err != nil {
  934. return nil, errors.Trace(err)
  935. }
  936. // Load the signed server entry to be presented to the broker as proof
  937. // that the in-proxy destination is a Psiphon server. The original
  938. // JSON server entry fields are loaded from the local data store
  939. // (or from config.TargetServerEntry), since the signature may
  940. // include fields, added after this client version, which are in the
  941. // JSON but not in the protocol.ServerEntry.
  942. var serverEntryFields protocol.ServerEntryFields
  943. if serverEntry.LocalSource == protocol.SERVER_ENTRY_SOURCE_TARGET {
  944. serverEntryFields, err = protocol.DecodeServerEntryFields(
  945. config.TargetServerEntry, "", protocol.SERVER_ENTRY_SOURCE_TARGET)
  946. if err != nil {
  947. return nil, errors.Trace(err)
  948. }
  949. if serverEntryFields.GetIPAddress() != serverEntry.IpAddress {
  950. return nil, errors.TraceNew("unexpected TargetServerEntry")
  951. }
  952. err = serverEntryFields.ToSignedFields()
  953. if err != nil {
  954. return nil, errors.Trace(err)
  955. }
  956. } else {
  957. serverEntryFields, err = GetSignedServerEntryFields(serverEntry.IpAddress)
  958. if err != nil {
  959. return nil, errors.Trace(err)
  960. }
  961. }
  962. // Verify the server entry signature locally to avoid a doomed broker
  963. // round trip.
  964. //
  965. // Limitation: the broker still checks signatures, but it won't get to
  966. // log an error in this case.
  967. err = serverEntryFields.VerifySignature(config.ServerEntrySignaturePublicKey)
  968. if err != nil {
  969. return nil, errors.Trace(err)
  970. }
  971. packedServerEntryFields, err := protocol.EncodePackedServerEntryFields(serverEntryFields)
  972. if err != nil {
  973. return nil, errors.Trace(err)
  974. }
  975. dialParams.inproxyPackedSignedServerEntry, err = protocol.CBOREncoding.Marshal(packedServerEntryFields)
  976. if err != nil {
  977. return nil, errors.Trace(err)
  978. }
  979. dialParams.inproxyNATStateManager = inproxyClientNATStateManager
  980. if !isReplay || !replayInproxySTUN {
  981. isProxy := false
  982. dialParams.InproxySTUNDialParameters, err = MakeInproxySTUNDialParameters(config, p, isProxy)
  983. if err != nil {
  984. return nil, errors.Trace(err)
  985. }
  986. } else if dialParams.InproxySTUNDialParameters != nil {
  987. dialParams.InproxySTUNDialParameters.Prepare()
  988. }
  989. if !isReplay || !replayInproxyWebRTC {
  990. dialParams.InproxyWebRTCDialParameters, err = MakeInproxyWebRTCDialParameters(p)
  991. if err != nil {
  992. return nil, errors.Trace(err)
  993. }
  994. }
  995. // dialParams.inproxyConn is left uninitialized until after the dial,
  996. // and until then Load will return nil.
  997. }
  998. // Set dial address fields. This portion of configuration is
  999. // deterministic, given the parameters established or replayed so far.
  1000. dialPortNumber, err := serverEntry.GetDialPortNumber(dialParams.TunnelProtocol)
  1001. if err != nil {
  1002. return nil, errors.Trace(err)
  1003. }
  1004. dialParams.DialPortNumber = strconv.Itoa(dialPortNumber)
  1005. switch protocol.TunnelProtocolMinusInproxy(dialParams.TunnelProtocol) {
  1006. case protocol.TUNNEL_PROTOCOL_SSH,
  1007. protocol.TUNNEL_PROTOCOL_OBFUSCATED_SSH,
  1008. protocol.TUNNEL_PROTOCOL_TAPDANCE_OBFUSCATED_SSH,
  1009. protocol.TUNNEL_PROTOCOL_CONJURE_OBFUSCATED_SSH,
  1010. protocol.TUNNEL_PROTOCOL_QUIC_OBFUSCATED_SSH,
  1011. protocol.TUNNEL_PROTOCOL_TLS_OBFUSCATED_SSH:
  1012. dialParams.DirectDialAddress = net.JoinHostPort(serverEntry.IpAddress, dialParams.DialPortNumber)
  1013. case protocol.TUNNEL_PROTOCOL_FRONTED_MEEK,
  1014. protocol.TUNNEL_PROTOCOL_FRONTED_MEEK_QUIC_OBFUSCATED_SSH:
  1015. dialParams.MeekDialAddress = net.JoinHostPort(dialParams.MeekFrontingDialAddress, dialParams.DialPortNumber)
  1016. dialParams.MeekHostHeader = dialParams.MeekFrontingHost
  1017. if serverEntry.MeekFrontingDisableSNI {
  1018. dialParams.MeekSNIServerName = ""
  1019. // When SNI is omitted, the transformed host name is not used.
  1020. dialParams.MeekTransformedHostName = false
  1021. } else if !dialParams.MeekTransformedHostName {
  1022. dialParams.MeekSNIServerName = dialParams.MeekFrontingDialAddress
  1023. }
  1024. case protocol.TUNNEL_PROTOCOL_FRONTED_MEEK_HTTP:
  1025. dialParams.MeekDialAddress = net.JoinHostPort(dialParams.MeekFrontingDialAddress, dialParams.DialPortNumber)
  1026. dialParams.MeekHostHeader = dialParams.MeekFrontingHost
  1027. // For FRONTED HTTP, the Host header cannot be transformed.
  1028. dialParams.MeekTransformedHostName = false
  1029. case protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK:
  1030. dialParams.MeekDialAddress = net.JoinHostPort(serverEntry.IpAddress, dialParams.DialPortNumber)
  1031. case protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  1032. protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET:
  1033. dialParams.MeekDialAddress = net.JoinHostPort(serverEntry.IpAddress, dialParams.DialPortNumber)
  1034. if !dialParams.MeekTransformedHostName {
  1035. // Note: IP address in SNI field will be omitted.
  1036. dialParams.MeekSNIServerName = serverEntry.IpAddress
  1037. }
  1038. default:
  1039. return nil, errors.Tracef(
  1040. "unknown tunnel protocol: %s", dialParams.TunnelProtocol)
  1041. }
  1042. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) {
  1043. host, _, _ := net.SplitHostPort(dialParams.MeekDialAddress)
  1044. if p.Bool(parameters.MeekDialDomainsOnly) {
  1045. if net.ParseIP(host) != nil {
  1046. // No error, as this is a "not supported" case.
  1047. return nil, nil
  1048. }
  1049. }
  1050. // The underlying TLS implementation will automatically omit SNI for
  1051. // IP address server name values; we have this explicit check here so
  1052. // we record the correct value for stats.
  1053. if net.ParseIP(dialParams.MeekSNIServerName) != nil {
  1054. dialParams.MeekSNIServerName = ""
  1055. }
  1056. }
  1057. // TLS ClientHello fragmentation is applied only after the state
  1058. // of SNI is determined above.
  1059. if (!isReplay || !replayTLSFragmentClientHello) && usingTLS {
  1060. limitProtocols := p.TunnelProtocols(parameters.TLSFragmentClientHelloLimitProtocols)
  1061. if len(limitProtocols) == 0 || common.Contains(limitProtocols, dialParams.TunnelProtocol) {
  1062. // Note: The TLS stack automatically drops the SNI extension when
  1063. // the host is an IP address.
  1064. usingSNI := false
  1065. if dialParams.TLSOSSHSNIServerName != "" {
  1066. usingSNI = net.ParseIP(dialParams.TLSOSSHSNIServerName) == nil
  1067. } else if dialParams.MeekSNIServerName != "" {
  1068. usingSNI = net.ParseIP(dialParams.MeekSNIServerName) == nil
  1069. }
  1070. // TLS ClientHello fragmentor expects SNI to be present.
  1071. if usingSNI {
  1072. dialParams.TLSFragmentClientHello = p.WeightedCoinFlip(
  1073. parameters.TLSFragmentClientHelloProbability)
  1074. }
  1075. }
  1076. }
  1077. // Initialize upstream proxy.
  1078. if config.UseUpstreamProxy() {
  1079. // Note: UpstreamProxyURL will be validated in the dial
  1080. proxyURL, err := common.SafeParseURL(config.UpstreamProxyURL)
  1081. if err == nil {
  1082. dialParams.UpstreamProxyType = proxyURL.Scheme
  1083. }
  1084. }
  1085. // Initialize/replay User-Agent header for HTTP upstream proxy and meek protocols.
  1086. dialCustomHeaders := makeDialCustomHeaders(config, p)
  1087. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) ||
  1088. dialParams.UpstreamProxyType == "http" ||
  1089. dialParams.ConjureAPIRegistration {
  1090. if !isReplay || !replayUserAgent {
  1091. dialParams.SelectedUserAgent, dialParams.UserAgent = selectUserAgentIfUnset(p, dialCustomHeaders)
  1092. }
  1093. if dialParams.SelectedUserAgent {
  1094. // Limitation: if config.CustomHeaders adds a User-Agent between
  1095. // replays, it may be ignored due to replaying a selected User-Agent.
  1096. dialCustomHeaders.Set("User-Agent", dialParams.UserAgent)
  1097. }
  1098. }
  1099. // UpstreamProxyCustomHeaderNames is a reported metric. Just the names and
  1100. // not the values are reported, in case the values are identifying.
  1101. if len(config.CustomHeaders) > 0 {
  1102. dialParams.UpstreamProxyCustomHeaderNames = make([]string, 0)
  1103. for name := range dialCustomHeaders {
  1104. if name == "User-Agent" && dialParams.SelectedUserAgent {
  1105. continue
  1106. }
  1107. dialParams.UpstreamProxyCustomHeaderNames = append(dialParams.UpstreamProxyCustomHeaderNames, name)
  1108. }
  1109. }
  1110. // Initialize Dial/MeekConfigs to be passed to the corresponding dialers.
  1111. var resolveIP func(ctx context.Context, hostname string) ([]net.IP, error)
  1112. // Determine whether to use a steering IP, and whether to indicate that
  1113. // this dial remains a replay or not.
  1114. //
  1115. // Steering IPs are used only for fronted tunnels and not lower-traffic
  1116. // tactics requests and signalling steps such as Conjure registration.
  1117. //
  1118. // The scope of the steering IP, and the corresponding cache key, is the
  1119. // fronting provider, tunnel protocol, and the current network ID.
  1120. //
  1121. // Currently, steering IPs are obtained and cached in the Psiphon API
  1122. // handshake response. A modest TTL is applied to cache entries, and, in
  1123. // the case of a failed tunnel, any corresponding cached steering IP is
  1124. // removed.
  1125. //
  1126. // DialParameters.SteeringIP is set and persisted, but is not used to dial
  1127. // in a replay case; it's used to determine whether this dial should be
  1128. // classified as a replay or not. A replay dial remains classified as
  1129. // replay if a steering IP is not used and no steering IP was used
  1130. // before; or when a steering IP is used and the same steering IP was
  1131. // used before.
  1132. //
  1133. // When a steering IP is used and none was used before, or vice versa,
  1134. // DialParameters.IsReplay is cleared so that is_replay is reported as
  1135. // false, since the dial may be very different in nature: using a
  1136. // different POP; skipping DNS; etc. Even if DialParameters.IsReplay was
  1137. // true and is cleared, this MakeDialParameters will have wired up all
  1138. // other dial parameters with replay values, so the benefit of those
  1139. // values is not lost.
  1140. var previousSteeringIP, currentSteeringIP string
  1141. if isReplay {
  1142. previousSteeringIP = dialParams.SteeringIP
  1143. }
  1144. dialParams.SteeringIP = ""
  1145. if !isTactics &&
  1146. protocol.TunnelProtocolUsesFrontedMeek(dialParams.TunnelProtocol) &&
  1147. dialParams.ServerEntry.FrontingProviderID != "" {
  1148. dialParams.steeringIPCacheKey = fmt.Sprintf("%s %s %s",
  1149. dialParams.NetworkID,
  1150. dialParams.ServerEntry.FrontingProviderID,
  1151. dialParams.TunnelProtocol)
  1152. steeringIPValue, ok := dialParams.steeringIPCache.Get(
  1153. dialParams.steeringIPCacheKey)
  1154. if ok {
  1155. currentSteeringIP = steeringIPValue.(string)
  1156. }
  1157. // A steering IP probability is applied and may be used to gradually
  1158. // apply steering IPs. The coin flip is made only to decide to start
  1159. // using a steering IP, avoiding flip flopping between dials. For any
  1160. // probability > 0.0, a long enough continuous session will
  1161. // eventually flip to true and then keep using steering IPs as long
  1162. // as they remain in the cache.
  1163. if previousSteeringIP == "" && currentSteeringIP != "" &&
  1164. !p.WeightedCoinFlip(parameters.SteeringIPProbability) {
  1165. currentSteeringIP = ""
  1166. }
  1167. }
  1168. if currentSteeringIP != "" {
  1169. IP := net.ParseIP(currentSteeringIP)
  1170. if IP == nil {
  1171. return nil, errors.TraceNew("invalid steering IP")
  1172. }
  1173. // Since tcpDial and NewUDPConn invoke ResolveIP unconditionally, even
  1174. // when the hostname is an IP address, a steering IP will be applied
  1175. // even in that case.
  1176. resolveIP = func(ctx context.Context, hostname string) ([]net.IP, error) {
  1177. return []net.IP{IP}, nil
  1178. }
  1179. // dialParams.SteeringIP will be used as the "previous" steering IP in
  1180. // the next replay.
  1181. dialParams.SteeringIP = currentSteeringIP
  1182. }
  1183. if currentSteeringIP != previousSteeringIP {
  1184. dialParams.IsReplay = false
  1185. }
  1186. // Custom ResolveParameters are set only when useResolver is true, but
  1187. // DialConfig.ResolveIP is required and wired up unconditionally. Any
  1188. // misconfigured or miscoded domain dial cases will use default
  1189. // ResolveParameters.
  1190. //
  1191. // ResolveIP will use the networkID obtained above, as it will be used
  1192. // almost immediately, instead of incurring the overhead of calling
  1193. // GetNetworkID again.
  1194. if resolveIP == nil {
  1195. resolveIP = func(ctx context.Context, hostname string) ([]net.IP, error) {
  1196. IPs, err := dialParams.resolver.ResolveIP(
  1197. ctx,
  1198. networkID,
  1199. dialParams.ResolveParameters,
  1200. hostname)
  1201. if err != nil {
  1202. return nil, errors.Trace(err)
  1203. }
  1204. return IPs, nil
  1205. }
  1206. }
  1207. // Fragmentor configuration.
  1208. // Note: fragmentorConfig is nil if fragmentor is disabled for prefixed OSSH.
  1209. //
  1210. // Limitation: when replaying and with ReplayIgnoreChangedConfigState set,
  1211. // fragmentor.NewUpstreamConfig may select a config using newer tactics
  1212. // parameters.
  1213. fragmentorConfig := fragmentor.NewUpstreamConfig(p, dialParams.TunnelProtocol, dialParams.FragmentorSeed)
  1214. if !p.Bool(parameters.OSSHPrefixEnableFragmentor) && dialParams.OSSHPrefixSpec != nil {
  1215. fragmentorConfig = nil
  1216. }
  1217. dialParams.dialConfig = &DialConfig{
  1218. DiagnosticID: serverEntry.GetDiagnosticID(),
  1219. UpstreamProxyURL: config.UpstreamProxyURL,
  1220. CustomHeaders: dialCustomHeaders,
  1221. BPFProgramInstructions: dialParams.BPFProgramInstructions,
  1222. DeviceBinder: config.deviceBinder,
  1223. IPv6Synthesizer: config.IPv6Synthesizer,
  1224. ResolveIP: resolveIP,
  1225. TrustedCACertificatesFilename: config.TrustedCACertificatesFilename,
  1226. FragmentorConfig: fragmentorConfig,
  1227. UpstreamProxyErrorCallback: upstreamProxyErrorCallback,
  1228. }
  1229. // Unconditionally initialize MeekResolvedIPAddress, so a valid string can
  1230. // always be read.
  1231. dialParams.MeekResolvedIPAddress.Store("")
  1232. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) ||
  1233. dialParams.ConjureAPIRegistration {
  1234. // For tactics requests, AddPsiphonFrontingHeader is set when set for
  1235. // the related tunnel protocol. E.g., FRONTED-OSSH-MEEK for
  1236. // FRONTED-MEEK-TACTICS. AddPsiphonFrontingHeader is not replayed.
  1237. addPsiphonFrontingHeader := false
  1238. if dialParams.FrontingProviderID != "" {
  1239. addPsiphonFrontingHeader = common.Contains(
  1240. p.LabeledTunnelProtocols(
  1241. parameters.AddFrontingProviderPsiphonFrontingHeader, dialParams.FrontingProviderID),
  1242. dialParams.TunnelProtocol)
  1243. }
  1244. dialParams.meekConfig = &MeekConfig{
  1245. DiagnosticID: serverEntry.GetDiagnosticID(),
  1246. Parameters: config.GetParameters(),
  1247. DialAddress: dialParams.MeekDialAddress,
  1248. UseQUIC: protocol.TunnelProtocolUsesFrontedMeekQUIC(dialParams.TunnelProtocol),
  1249. QUICVersion: dialParams.QUICVersion,
  1250. QUICClientHelloSeed: dialParams.QUICClientHelloSeed,
  1251. QUICDialEarly: dialParams.QUICDialEarly,
  1252. QUICTLSClientSessionCache: dialParams.quicTLSClientSessionCache,
  1253. TLSClientSessionCache: dialParams.tlsClientSessionCache,
  1254. QUICDisablePathMTUDiscovery: dialParams.QUICDisablePathMTUDiscovery,
  1255. UseHTTPS: usingTLS,
  1256. TLSProfile: dialParams.TLSProfile,
  1257. TLSFragmentClientHello: dialParams.TLSFragmentClientHello,
  1258. LegacyPassthrough: serverEntry.ProtocolUsesLegacyPassthrough(dialParams.TunnelProtocol),
  1259. NoDefaultTLSSessionID: dialParams.NoDefaultTLSSessionID,
  1260. RandomizedTLSProfileSeed: dialParams.RandomizedTLSProfileSeed,
  1261. UseObfuscatedSessionTickets: dialParams.TunnelProtocol == protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET,
  1262. SNIServerName: dialParams.MeekSNIServerName,
  1263. AddPsiphonFrontingHeader: addPsiphonFrontingHeader,
  1264. VerifyServerName: dialParams.MeekVerifyServerName,
  1265. VerifyPins: dialParams.MeekVerifyPins,
  1266. DisableSystemRootCAs: config.DisableSystemRootCAs,
  1267. HostHeader: dialParams.MeekHostHeader,
  1268. TransformedHostName: dialParams.MeekTransformedHostName,
  1269. ClientTunnelProtocol: dialParams.TunnelProtocol,
  1270. MeekCookieEncryptionPublicKey: serverEntry.MeekCookieEncryptionPublicKey,
  1271. MeekObfuscatedKey: serverEntry.MeekObfuscatedKey,
  1272. MeekObfuscatorPaddingSeed: dialParams.MeekObfuscatorPaddingSeed,
  1273. NetworkLatencyMultiplier: dialParams.NetworkLatencyMultiplier,
  1274. HTTPTransformerParameters: dialParams.HTTPTransformerParameters,
  1275. AdditionalHeaders: config.MeekAdditionalHeaders,
  1276. }
  1277. // Use an asynchronous callback to record the resolved IP address when
  1278. // dialing a domain name. Note that DialMeek doesn't immediately
  1279. // establish any HTTP connections, so the resolved IP address won't be
  1280. // reported in all cases until after SSH traffic is relayed or a
  1281. // endpoint request is made over the meek connection.
  1282. dialParams.dialConfig.ResolvedIPCallback = func(IPAddress string) {
  1283. dialParams.MeekResolvedIPAddress.Store(IPAddress)
  1284. }
  1285. if isTactics {
  1286. dialParams.meekConfig.Mode = MeekModeObfuscatedRoundTrip
  1287. } else if dialParams.ConjureAPIRegistration {
  1288. dialParams.meekConfig.Mode = MeekModePlaintextRoundTrip
  1289. } else {
  1290. dialParams.meekConfig.Mode = MeekModeRelay
  1291. }
  1292. }
  1293. if !isTactics &&
  1294. protocol.TunnelProtocolUsesInproxy(dialParams.TunnelProtocol) &&
  1295. protocol.TunnelProtocolUsesTCP(dialParams.TunnelProtocol) {
  1296. // Set DialConfig.CustomDialer to redirect all underlying TCP dials to use
  1297. // in-proxy as a 1st hop. Since QUIC doesn't use DialConfig or have its
  1298. // own CustomDialer, QUIC is handled with an explicit special case in
  1299. // dialTunnel.
  1300. dialParams.dialConfig.CustomDialer = makeInproxyTCPDialer(config, dialParams)
  1301. }
  1302. return dialParams, nil
  1303. }
  1304. func (dialParams *DialParameters) GetDialConfig() *DialConfig {
  1305. return dialParams.dialConfig
  1306. }
  1307. func (dialParams *DialParameters) GetMeekConfig() *MeekConfig {
  1308. return dialParams.meekConfig
  1309. }
  1310. func (dialParams *DialParameters) GetTLSOSSHConfig(config *Config) *TLSTunnelConfig {
  1311. p := config.GetParameters().Get()
  1312. useObfuscatedPSK := p.WeightedCoinFlip(parameters.TLSTunnelObfuscatedPSKProbability)
  1313. // TLSTunnelConfig isn't pre-created in MakeDialParameters to avoid holding a long
  1314. // term reference to TLSTunnelConfig.Parameters.
  1315. return &TLSTunnelConfig{
  1316. CustomTLSConfig: &CustomTLSConfig{
  1317. Parameters: config.GetParameters(),
  1318. DialAddr: dialParams.DirectDialAddress,
  1319. SNIServerName: dialParams.TLSOSSHSNIServerName,
  1320. SkipVerify: true,
  1321. VerifyServerName: "",
  1322. VerifyPins: nil,
  1323. TLSProfile: dialParams.TLSProfile,
  1324. NoDefaultTLSSessionID: &dialParams.NoDefaultTLSSessionID,
  1325. RandomizedTLSProfileSeed: dialParams.RandomizedTLSProfileSeed,
  1326. FragmentClientHello: dialParams.TLSFragmentClientHello,
  1327. ClientSessionCache: dialParams.tlsClientSessionCache,
  1328. },
  1329. UseObfuscatedSessionTickets: useObfuscatedPSK,
  1330. // Meek obfuscated key used to allow clients with legacy unfronted
  1331. // meek-https server entries, that have the passthrough capability, to
  1332. // connect with TLS-OSSH to the servers corresponding to those server
  1333. // entries, which now support TLS-OSSH by demultiplexing meek-https and
  1334. // TLS-OSSH over the meek-https port.
  1335. ObfuscatedKey: dialParams.ServerEntry.MeekObfuscatedKey,
  1336. ObfuscatorPaddingSeed: dialParams.TLSOSSHObfuscatorPaddingSeed,
  1337. }
  1338. }
  1339. func (dialParams *DialParameters) GetNetworkType() string {
  1340. return GetNetworkType(dialParams.NetworkID)
  1341. }
  1342. func (dialParams *DialParameters) GetTLSVersionForMetrics() string {
  1343. return getTLSVersionForMetrics(dialParams.TLSVersion, dialParams.NoDefaultTLSSessionID)
  1344. }
  1345. func getTLSVersionForMetrics(tlsVersion string, noDefaultTLSSessionID bool) string {
  1346. version := tlsVersion
  1347. if noDefaultTLSSessionID {
  1348. version += "-no_def_id"
  1349. }
  1350. return version
  1351. }
  1352. func (dialParams *DialParameters) GetInproxyMetrics() common.LogFields {
  1353. inproxyMetrics := common.LogFields{}
  1354. if !dialParams.inproxyDialInitialized {
  1355. // This was an untunneled tactics request using an in-proxy meek
  1356. // server, no there was no in-proxy dial or dial parameters.
  1357. return inproxyMetrics
  1358. }
  1359. for _, metrics := range []common.LogFields{
  1360. dialParams.inproxyBrokerDialParameters.GetMetrics(),
  1361. dialParams.InproxySTUNDialParameters.GetMetrics(),
  1362. dialParams.InproxyWebRTCDialParameters.GetMetrics(),
  1363. } {
  1364. for name, value := range metrics {
  1365. inproxyMetrics[name] = value
  1366. }
  1367. }
  1368. return inproxyMetrics
  1369. }
  1370. func (dialParams *DialParameters) Succeeded() {
  1371. // When TTL is 0, don't store dial parameters.
  1372. if dialParams.LastUsedTimestamp.IsZero() {
  1373. return
  1374. }
  1375. NoticeInfo("Set dial parameters for %s", dialParams.ServerEntry.GetDiagnosticID())
  1376. err := SetDialParameters(dialParams.ServerEntry.IpAddress, dialParams.NetworkID, dialParams)
  1377. if err != nil {
  1378. NoticeWarning("SetDialParameters failed: %s", err)
  1379. }
  1380. }
  1381. func (dialParams *DialParameters) Failed(config *Config) {
  1382. // When a tunnel fails, and the dial is a replay, clear the stored dial
  1383. // parameters which are now presumed to be blocked, impaired or otherwise
  1384. // no longer effective.
  1385. //
  1386. // It may be the case that a dial is not using stored dial parameters
  1387. // (!IsReplay), and in this case we retain those dial parameters since they
  1388. // were not exercised and may still be effective.
  1389. //
  1390. // Failed tunnel dial parameters may be retained with a configurable
  1391. // probability; this is intended to help mitigate false positive failures due
  1392. // to, e.g., temporary network disruptions or server load limiting.
  1393. if dialParams.IsReplay &&
  1394. !config.GetParameters().Get().WeightedCoinFlip(
  1395. parameters.ReplayRetainFailedProbability) {
  1396. NoticeInfo("Delete dial parameters for %s", dialParams.ServerEntry.GetDiagnosticID())
  1397. err := DeleteDialParameters(dialParams.ServerEntry.IpAddress, dialParams.NetworkID)
  1398. if err != nil {
  1399. NoticeWarning("DeleteDialParameters failed: %s", err)
  1400. }
  1401. }
  1402. // When a failed tunnel dialed with steering IP, remove the corresponding
  1403. // cache entry to avoid continuously redialing a potentially blocked or
  1404. // degraded POP.
  1405. //
  1406. // TODO: don't remove, but reduce the TTL to allow for one more dial?
  1407. if dialParams.steeringIPCacheKey != "" {
  1408. dialParams.steeringIPCache.Delete(dialParams.steeringIPCacheKey)
  1409. }
  1410. // Clear the TLS client session cache to avoid (potentially) reusing failed sessions for
  1411. // Meek, TLS-OSSH and QUIC connections.
  1412. if dialParams.quicTLSClientSessionCache != nil {
  1413. dialParams.quicTLSClientSessionCache.RemoveCacheEntry()
  1414. }
  1415. if dialParams.tlsClientSessionCache != nil {
  1416. dialParams.tlsClientSessionCache.RemoveCacheEntry()
  1417. }
  1418. }
  1419. // ExchangedDialParameters represents the subset of DialParameters that is
  1420. // shared in a client-to-client exchange of server connection info.
  1421. //
  1422. // The purpose of client-to-client exchange if for one user that can connect
  1423. // to help another user that cannot connect by sharing their connected
  1424. // configuration, including the server entry and dial parameters.
  1425. //
  1426. // There are two concerns regarding which dial parameter fields are safe to
  1427. // exchange:
  1428. //
  1429. // - Unlike signed server entries, there's no independent trust anchor
  1430. // that can certify that the exchange data is valid.
  1431. //
  1432. // - While users should only perform the exchange with trusted peers,
  1433. // the user's trust in their peer may be misplaced.
  1434. //
  1435. // This presents the possibility of attack such as the peer sending dial
  1436. // parameters that could be used to trace/monitor/flag the importer; or
  1437. // sending dial parameters, including dial address and SNI, to cause the peer
  1438. // to appear to connect to a banned service.
  1439. //
  1440. // To mitigate these risks, only a subset of dial parameters are exchanged.
  1441. // When exchanged dial parameters and imported and used, all unexchanged
  1442. // parameters are generated locally. At this time, only the tunnel protocol is
  1443. // exchanged. We consider tunnel protocol selection one of the key connection
  1444. // success factors.
  1445. //
  1446. // In addition, the exchange peers may not be on the same network with the
  1447. // same blocking and circumvention characteristics, which is another reason
  1448. // to limit exchanged dial parameter values to broadly applicable fields.
  1449. //
  1450. // Unlike the exchanged (and otherwise acquired) server entry,
  1451. // ExchangedDialParameters does not use the ServerEntry_Fields_ representation
  1452. // which allows older clients to receive and store new, unknown fields. Such a
  1453. // facility is less useful in this case, since exchanged dial parameters and
  1454. // used immediately and have a short lifespan.
  1455. //
  1456. // TODO: exchange more dial parameters, such as TLS profile, QUIC version, etc.
  1457. type ExchangedDialParameters struct {
  1458. TunnelProtocol string
  1459. }
  1460. // NewExchangedDialParameters creates a new ExchangedDialParameters from a
  1461. // DialParameters, including only the exchanged values.
  1462. // NewExchangedDialParameters assumes the input DialParameters has been
  1463. // initialized and populated by MakeDialParameters.
  1464. func NewExchangedDialParameters(dialParams *DialParameters) *ExchangedDialParameters {
  1465. return &ExchangedDialParameters{
  1466. TunnelProtocol: dialParams.TunnelProtocol,
  1467. }
  1468. }
  1469. // Validate checks that the ExchangedDialParameters contains only valid values
  1470. // and is compatible with the specified server entry.
  1471. func (dialParams *ExchangedDialParameters) Validate(serverEntry *protocol.ServerEntry) error {
  1472. if !common.Contains(protocol.SupportedTunnelProtocols, dialParams.TunnelProtocol) {
  1473. return errors.Tracef("unknown tunnel protocol: %s", dialParams.TunnelProtocol)
  1474. }
  1475. if !serverEntry.SupportsProtocol(dialParams.TunnelProtocol) {
  1476. return errors.Tracef("unsupported tunnel protocol: %s", dialParams.TunnelProtocol)
  1477. }
  1478. return nil
  1479. }
  1480. // MakeDialParameters creates a new, partially intitialized DialParameters
  1481. // from the values in ExchangedDialParameters. The returned DialParameters
  1482. // must not be used directly for dialing. It is intended to be stored, and
  1483. // then later fully initialized by MakeDialParameters.
  1484. func (dialParams *ExchangedDialParameters) MakeDialParameters(
  1485. config *Config,
  1486. p parameters.ParametersAccessor,
  1487. serverEntry *protocol.ServerEntry) *DialParameters {
  1488. configStateHash, serverEntryHash := getDialStateHashes(config, p, serverEntry)
  1489. return &DialParameters{
  1490. IsExchanged: true,
  1491. LastUsedTimestamp: time.Now(),
  1492. LastUsedConfigStateHash: configStateHash,
  1493. LastUsedServerEntryHash: serverEntryHash,
  1494. TunnelProtocol: dialParams.TunnelProtocol,
  1495. }
  1496. }
  1497. // getDialStateHashes returns two hashes: the config state hash reflects the
  1498. // config dial parameters and tactics tag used for a dial; and the server
  1499. // entry hash relects the server entry used for a dial.
  1500. //
  1501. // These hashes change if the input values change in a way that invalidates
  1502. // any stored dial parameters.
  1503. func getDialStateHashes(
  1504. config *Config,
  1505. p parameters.ParametersAccessor,
  1506. serverEntry *protocol.ServerEntry) ([]byte, []byte) {
  1507. // MD5 hash is used solely as a data checksum and not for any security
  1508. // purpose.
  1509. hash := md5.New()
  1510. // Add a hash of relevant dial parameter config fields. Config fields
  1511. // that change due to user preference changes, such as selected egress
  1512. // region, are not to be included in config.dialParametersHash.
  1513. //
  1514. // Limitation: the config hash may change even when tactics will override the
  1515. // changed config field.
  1516. hash.Write(config.dialParametersHash)
  1517. // Add the active tactics tag.
  1518. hash.Write([]byte(p.Tag()))
  1519. clientStateHash := hash.Sum(nil)
  1520. hash = md5.New()
  1521. // Add the server entry version and local timestamp, both of which should
  1522. // change when the server entry contents change and/or a new local copy is
  1523. // imported.
  1524. // TODO: marshal entire server entry?
  1525. var serverEntryConfigurationVersion [8]byte
  1526. binary.BigEndian.PutUint64(
  1527. serverEntryConfigurationVersion[:],
  1528. uint64(serverEntry.ConfigurationVersion))
  1529. hash.Write(serverEntryConfigurationVersion[:])
  1530. hash.Write([]byte(serverEntry.LocalTimestamp))
  1531. serverEntryHash := hash.Sum(nil)
  1532. return clientStateHash, serverEntryHash
  1533. }
  1534. func selectFrontingParameters(
  1535. serverEntry *protocol.ServerEntry) (string, string, error) {
  1536. frontingDialHost := ""
  1537. frontingHost := ""
  1538. if len(serverEntry.MeekFrontingAddressesRegex) > 0 {
  1539. // Generate a front address based on the regex.
  1540. var err error
  1541. frontingDialHost, err = regen.GenerateString(serverEntry.MeekFrontingAddressesRegex)
  1542. if err != nil {
  1543. return "", "", errors.Trace(err)
  1544. }
  1545. } else {
  1546. // Randomly select, for this connection attempt, one front address for
  1547. // fronting-capable servers.
  1548. if len(serverEntry.MeekFrontingAddresses) == 0 {
  1549. return "", "", errors.TraceNew("MeekFrontingAddresses is empty")
  1550. }
  1551. index := prng.Intn(len(serverEntry.MeekFrontingAddresses))
  1552. frontingDialHost = serverEntry.MeekFrontingAddresses[index]
  1553. }
  1554. if len(serverEntry.MeekFrontingHosts) > 0 {
  1555. index := prng.Intn(len(serverEntry.MeekFrontingHosts))
  1556. frontingHost = serverEntry.MeekFrontingHosts[index]
  1557. } else {
  1558. // Backwards compatibility case
  1559. frontingHost = serverEntry.MeekFrontingHost
  1560. }
  1561. return frontingDialHost, frontingHost, nil
  1562. }
  1563. func selectQUICVersion(
  1564. isFronted bool,
  1565. isInproxy bool,
  1566. serverEntry *protocol.ServerEntry,
  1567. p parameters.ParametersAccessor) string {
  1568. limitQUICVersions := p.QUICVersions(parameters.LimitQUICVersions)
  1569. var disableQUICVersions protocol.QUICVersions
  1570. if isFronted {
  1571. if serverEntry.FrontingProviderID == "" {
  1572. // Legacy server entry case
  1573. disableQUICVersions = protocol.QUICVersions{
  1574. protocol.QUIC_VERSION_V1,
  1575. protocol.QUIC_VERSION_RANDOMIZED_V1,
  1576. protocol.QUIC_VERSION_OBFUSCATED_V1,
  1577. protocol.QUIC_VERSION_DECOY_V1,
  1578. }
  1579. } else {
  1580. disableQUICVersions = p.LabeledQUICVersions(
  1581. parameters.DisableFrontingProviderQUICVersions,
  1582. serverEntry.FrontingProviderID)
  1583. }
  1584. }
  1585. quicVersions := make([]string, 0)
  1586. // Don't use gQUIC versions when the server entry specifies QUICv1-only.
  1587. //
  1588. // SupportedQUICVersions is specific to QUIC-OSSH and does not apply to
  1589. // in-proxy variants; all in-proxy QUIC is QUICv1-only.
  1590. supportedQUICVersions := protocol.SupportedQUICVersions
  1591. if isInproxy || serverEntry.SupportsOnlyQUICv1() {
  1592. supportedQUICVersions = protocol.SupportedQUICv1Versions
  1593. }
  1594. for _, quicVersion := range supportedQUICVersions {
  1595. if len(limitQUICVersions) > 0 &&
  1596. !common.Contains(limitQUICVersions, quicVersion) {
  1597. continue
  1598. }
  1599. // Both tactics and the server entry can specify LimitQUICVersions. In
  1600. // tactics, the parameter is intended to direct certain clients to
  1601. // use a successful protocol variant. In the server entry, the
  1602. // parameter may be used to direct all clients to send
  1603. // consistent-looking protocol variants to a particular server; e.g.,
  1604. // only regular QUIC, or only obfuscated QUIC.
  1605. //
  1606. // The isFronted/QUICVersionIsObfuscated logic predates
  1607. // ServerEntry.LimitQUICVersions; ServerEntry.LimitQUICVersions could
  1608. // now be used to achieve a similar outcome.
  1609. if len(serverEntry.LimitQUICVersions) > 0 &&
  1610. !common.Contains(serverEntry.LimitQUICVersions, quicVersion) {
  1611. continue
  1612. }
  1613. if isFronted &&
  1614. protocol.QUICVersionIsObfuscated(quicVersion) {
  1615. continue
  1616. }
  1617. if common.Contains(disableQUICVersions, quicVersion) {
  1618. continue
  1619. }
  1620. quicVersions = append(quicVersions, quicVersion)
  1621. }
  1622. if len(quicVersions) == 0 {
  1623. return ""
  1624. }
  1625. choice := prng.Intn(len(quicVersions))
  1626. return quicVersions[choice]
  1627. }
  1628. // selectUserAgentIfUnset selects a User-Agent header if one is not set.
  1629. func selectUserAgentIfUnset(
  1630. p parameters.ParametersAccessor, headers http.Header) (bool, string) {
  1631. if _, ok := headers["User-Agent"]; !ok {
  1632. userAgent := ""
  1633. if p.WeightedCoinFlip(parameters.PickUserAgentProbability) {
  1634. userAgent = values.GetUserAgent()
  1635. }
  1636. return true, userAgent
  1637. }
  1638. return false, ""
  1639. }
  1640. func makeDialCustomHeaders(
  1641. config *Config,
  1642. p parameters.ParametersAccessor) http.Header {
  1643. dialCustomHeaders := make(http.Header)
  1644. if config.CustomHeaders != nil {
  1645. for k, v := range config.CustomHeaders {
  1646. dialCustomHeaders[k] = make([]string, len(v))
  1647. copy(dialCustomHeaders[k], v)
  1648. }
  1649. }
  1650. additionalCustomHeaders := p.HTTPHeaders(parameters.AdditionalCustomHeaders)
  1651. for k, v := range additionalCustomHeaders {
  1652. dialCustomHeaders[k] = make([]string, len(v))
  1653. copy(dialCustomHeaders[k], v)
  1654. }
  1655. return dialCustomHeaders
  1656. }
  1657. func selectHostName(
  1658. tunnelProtocol string, p parameters.ParametersAccessor) string {
  1659. limitProtocols := p.TunnelProtocols(parameters.CustomHostNameLimitProtocols)
  1660. if len(limitProtocols) > 0 && !common.Contains(limitProtocols, tunnelProtocol) {
  1661. return values.GetHostName()
  1662. }
  1663. if !p.WeightedCoinFlip(parameters.CustomHostNameProbability) {
  1664. return values.GetHostName()
  1665. }
  1666. regexStrings := p.RegexStrings(parameters.CustomHostNameRegexes)
  1667. if len(regexStrings) == 0 {
  1668. return values.GetHostName()
  1669. }
  1670. choice := prng.Intn(len(regexStrings))
  1671. hostName, err := regen.GenerateString(regexStrings[choice])
  1672. if err != nil {
  1673. NoticeWarning("selectHostName: regen.Generate failed: %v", errors.Trace(err))
  1674. return values.GetHostName()
  1675. }
  1676. return hostName
  1677. }
  1678. // makeHTTPTransformerParameters generates HTTPTransformerParameters using the
  1679. // input tactics parameters and optional frontingProviderID context.
  1680. func makeHTTPTransformerParameters(p parameters.ParametersAccessor,
  1681. frontingProviderID string, isFronted bool) (*transforms.HTTPTransformerParameters, error) {
  1682. params := transforms.HTTPTransformerParameters{}
  1683. // Select an HTTP transform. If the request is fronted, HTTP request
  1684. // transforms are "scoped" by fronting provider ID. Otherwise, a transform
  1685. // from the default scope (transforms.SCOPE_ANY == "") is selected.
  1686. var specsKey string
  1687. var scopedSpecsNamesKey string
  1688. useTransform := false
  1689. scope := transforms.SCOPE_ANY
  1690. if isFronted {
  1691. if p.WeightedCoinFlip(parameters.FrontedHTTPProtocolTransformProbability) {
  1692. useTransform = true
  1693. scope = frontingProviderID
  1694. specsKey = parameters.FrontedHTTPProtocolTransformSpecs
  1695. scopedSpecsNamesKey = parameters.FrontedHTTPProtocolTransformScopedSpecNames
  1696. }
  1697. } else {
  1698. // unfronted
  1699. if p.WeightedCoinFlip(parameters.DirectHTTPProtocolTransformProbability) {
  1700. useTransform = true
  1701. specsKey = parameters.DirectHTTPProtocolTransformSpecs
  1702. scopedSpecsNamesKey = parameters.DirectHTTPProtocolTransformScopedSpecNames
  1703. }
  1704. }
  1705. if useTransform {
  1706. specs := p.ProtocolTransformSpecs(
  1707. specsKey)
  1708. scopedSpecNames := p.ProtocolTransformScopedSpecNames(
  1709. scopedSpecsNamesKey)
  1710. name, spec := specs.Select(scope, scopedSpecNames)
  1711. if spec != nil {
  1712. params.ProtocolTransformName = name
  1713. params.ProtocolTransformSpec = spec
  1714. var err error
  1715. // transform seed generated
  1716. params.ProtocolTransformSeed, err = prng.NewSeed()
  1717. if err != nil {
  1718. return nil, errors.Trace(err)
  1719. }
  1720. }
  1721. }
  1722. return &params, nil
  1723. }
  1724. // makeSeedTransformerParameters generates ObfuscatorSeedTransformerParameters
  1725. // using the input tactics parameters.
  1726. func makeSeedTransformerParameters(p parameters.ParametersAccessor,
  1727. probabilityFieldName, specsKey, scopedSpecsKey string) (*transforms.ObfuscatorSeedTransformerParameters, error) {
  1728. if !p.WeightedCoinFlip(probabilityFieldName) {
  1729. return &transforms.ObfuscatorSeedTransformerParameters{}, nil
  1730. }
  1731. seed, err := prng.NewSeed()
  1732. if err != nil {
  1733. return nil, errors.Trace(err)
  1734. }
  1735. specs := p.ProtocolTransformSpecs(specsKey)
  1736. scopedSpecNames := p.ProtocolTransformScopedSpecNames(scopedSpecsKey)
  1737. name, spec := specs.Select(transforms.SCOPE_ANY, scopedSpecNames)
  1738. if spec == nil {
  1739. return &transforms.ObfuscatorSeedTransformerParameters{}, nil
  1740. } else {
  1741. return &transforms.ObfuscatorSeedTransformerParameters{
  1742. TransformName: name,
  1743. TransformSpec: spec,
  1744. TransformSeed: seed,
  1745. }, nil
  1746. }
  1747. }
  1748. func makeOSSHPrefixSpecParameters(
  1749. p parameters.ParametersAccessor,
  1750. dialPortNumber string) (*obfuscator.OSSHPrefixSpec, error) {
  1751. if !p.WeightedCoinFlip(parameters.OSSHPrefixProbability) {
  1752. return &obfuscator.OSSHPrefixSpec{}, nil
  1753. }
  1754. specs := p.ProtocolTransformSpecs(parameters.OSSHPrefixSpecs)
  1755. scopedSpecNames := p.ProtocolTransformScopedSpecNames(parameters.OSSHPrefixScopedSpecNames)
  1756. name, spec := specs.Select(dialPortNumber, scopedSpecNames)
  1757. if spec == nil {
  1758. return &obfuscator.OSSHPrefixSpec{}, nil
  1759. } else {
  1760. seed, err := prng.NewSeed()
  1761. if err != nil {
  1762. return nil, errors.Trace(err)
  1763. }
  1764. return &obfuscator.OSSHPrefixSpec{
  1765. Name: name,
  1766. Spec: spec,
  1767. Seed: seed,
  1768. }, nil
  1769. }
  1770. }
  1771. func makeOSSHPrefixSplitConfig(p parameters.ParametersAccessor) (*obfuscator.OSSHPrefixSplitConfig, error) {
  1772. minDelay := p.Duration(parameters.OSSHPrefixSplitMinDelay)
  1773. maxDelay := p.Duration(parameters.OSSHPrefixSplitMaxDelay)
  1774. seed, err := prng.NewSeed()
  1775. if err != nil {
  1776. return nil, errors.Trace(err)
  1777. }
  1778. return &obfuscator.OSSHPrefixSplitConfig{
  1779. Seed: seed,
  1780. MinDelay: minDelay,
  1781. MaxDelay: maxDelay,
  1782. }, nil
  1783. }
  1784. func selectConjureTransport(
  1785. p parameters.ParametersAccessor) string {
  1786. limitConjureTransports := p.ConjureTransports(parameters.ConjureLimitTransports)
  1787. transports := make([]string, 0)
  1788. for _, transport := range protocol.SupportedConjureTransports {
  1789. if len(limitConjureTransports) > 0 &&
  1790. !common.Contains(limitConjureTransports, transport) {
  1791. continue
  1792. }
  1793. transports = append(transports, transport)
  1794. }
  1795. if len(transports) == 0 {
  1796. return ""
  1797. }
  1798. choice := prng.Intn(len(transports))
  1799. return transports[choice]
  1800. }