dialParameters.go 77 KB

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