dialParameters.go 85 KB

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