dialParameters.go 86 KB

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