dialParameters.go 86 KB

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