dialParameters.go 94 KB

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