config.go 117 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059
  1. /*
  2. * Copyright (c) 2015, 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. "crypto/md5"
  22. "encoding/base64"
  23. "encoding/binary"
  24. "encoding/json"
  25. "fmt"
  26. "io/ioutil"
  27. "net/http"
  28. "os"
  29. "path/filepath"
  30. "reflect"
  31. "regexp"
  32. "strconv"
  33. "strings"
  34. "sync"
  35. "unicode"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  40. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/resolver"
  41. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/transforms"
  42. "golang.org/x/crypto/nacl/secretbox"
  43. )
  44. const (
  45. TUNNEL_POOL_SIZE = 1
  46. MAX_TUNNEL_POOL_SIZE = 32
  47. // Psiphon data directory name, relative to config.DataRootDirectory.
  48. // See config.GetPsiphonDataDirectory().
  49. PsiphonDataDirectoryName = "ca.psiphon.PsiphonTunnel.tunnel-core"
  50. // Filename constants, all relative to config.GetPsiphonDataDirectory().
  51. HomepageFilename = "homepage"
  52. NoticesFilename = "notices"
  53. OldNoticesFilename = "notices.1"
  54. UpgradeDownloadFilename = "upgrade"
  55. )
  56. // Config is the Psiphon configuration specified by the application. This
  57. // configuration controls the behavior of the core tunnel functionality.
  58. //
  59. // To distinguish omitted timeout params from explicit 0 value timeout params,
  60. // corresponding fields are int pointers. nil means no value was supplied and
  61. // to use the default; a non-nil pointer to 0 means no timeout.
  62. type Config struct {
  63. // DataRootDirectory is the directory in which to store persistent files,
  64. // which contain information such as server entries. By default, current
  65. // working directory.
  66. //
  67. // Psiphon will assume full control of files under this directory. They may
  68. // be deleted, moved or overwritten.
  69. DataRootDirectory string
  70. // UseNoticeFiles configures notice files for writing. If set, homepages
  71. // will be written to a file created at config.GetHomePageFilename()
  72. // and notices will be written to a file created at
  73. // config.GetNoticesFilename().
  74. //
  75. // The homepage file may be read after the Tunnels notice with count of 1.
  76. //
  77. // The value of UseNoticeFiles sets the size and frequency at which the
  78. // notices file, config.GetNoticesFilename(), will be rotated. See the
  79. // comment for UseNoticeFiles for more details. One rotated older file,
  80. // config.GetOldNoticesFilename(), is retained.
  81. //
  82. // The notice files may be may be read at any time; and should be opened
  83. // read-only for reading. Diagnostic notices are omitted from the notice
  84. // files.
  85. //
  86. // See comment for setNoticeFiles in notice.go for further details.
  87. UseNoticeFiles *UseNoticeFiles
  88. // PropagationChannelId is a string identifier which indicates how the
  89. // Psiphon client was distributed. This parameter is required. This value
  90. // is supplied by and depends on the Psiphon Network, and is typically
  91. // embedded in the client binary.
  92. PropagationChannelId string
  93. // SponsorId is a string identifier which indicates who is sponsoring this
  94. // Psiphon client. One purpose of this value is to determine the home
  95. // pages for display. This parameter is required. This value is supplied
  96. // by and depends on the Psiphon Network, and is typically embedded in the
  97. // client binary.
  98. SponsorId string
  99. // ClientVersion is the client version number that the client reports to
  100. // the server. The version number refers to the host client application,
  101. // not the core tunnel library. One purpose of this value is to enable
  102. // automatic updates. This value is supplied by and depends on the Psiphon
  103. // Network, and is typically embedded in the client binary.
  104. //
  105. // Note that sending a ClientPlatform string which includes "windows"
  106. // (case insensitive) and a ClientVersion of <= 44 will cause an error in
  107. // processing the response to DoConnectedRequest calls.
  108. ClientVersion string
  109. // ClientPlatform is the client platform ("Windows", "Android", etc.) that
  110. // the client reports to the server.
  111. ClientPlatform string
  112. // ClientFeatures is a list of feature names denoting enabled application
  113. // features. Clients report enabled features to the server for stats
  114. // purposes.
  115. ClientFeatures []string
  116. // EgressRegion is a ISO 3166-1 alpha-2 country code which indicates which
  117. // country to egress from. For the default, "", the best performing server
  118. // in any country is selected.
  119. EgressRegion string
  120. // SplitTunnelOwnRegion enables split tunnel mode for the client's own
  121. // country. When enabled, TCP port forward destinations that resolve to
  122. // the same GeoIP country as the client are connected to directly,
  123. // untunneled.
  124. SplitTunnelOwnRegion bool
  125. // SplitTunnelRegions enables selected split tunnel mode in which the
  126. // client specifies a list of ISO 3166-1 alpha-2 country codes for which
  127. // traffic should be untunneled. TCP port forwards destined to any
  128. // country specified in SplitTunnelRegions will be untunneled, regardless
  129. // of whether SplitTunnelOwnRegion is on or off.
  130. SplitTunnelRegions []string
  131. // ListenInterface specifies which interface to listen on. If no
  132. // interface is provided then listen on 127.0.0.1. If 'any' is provided
  133. // then use 0.0.0.0. If there are multiple IP addresses on an interface
  134. // use the first IPv4 address.
  135. ListenInterface string
  136. // DisableLocalSocksProxy disables running the local SOCKS proxy.
  137. DisableLocalSocksProxy bool
  138. // LocalSocksProxyPort specifies a port number for the local SOCKS proxy
  139. // running at 127.0.0.1. For the default value, 0, the system selects a
  140. // free port (a notice reporting the selected port is emitted).
  141. LocalSocksProxyPort int
  142. // LocalHttpProxyPort specifies a port number for the local HTTP proxy
  143. // running at 127.0.0.1. For the default value, 0, the system selects a
  144. // free port (a notice reporting the selected port is emitted).
  145. LocalHttpProxyPort int
  146. // DisableLocalHTTPProxy disables running the local HTTP proxy.
  147. DisableLocalHTTPProxy bool
  148. // NetworkLatencyMultiplier is a multiplier that is to be applied to
  149. // default network event timeouts. Set this to tune performance for
  150. // slow networks.
  151. // When set, must be >= 1.0.
  152. NetworkLatencyMultiplier float64
  153. // LimitTunnelProtocols indicates which protocols to use. Valid values
  154. // include: "SSH", "OSSH", "TLS-OSSH", "UNFRONTED-MEEK-OSSH",
  155. // "UNFRONTED-MEEK-HTTPS-OSSH", "UNFRONTED-MEEK-SESSION-TICKET-OSSH",
  156. // "FRONTED-MEEK-OSSH", "FRONTED-MEEK-HTTP-OSSH", "QUIC-OSSH",
  157. // "FRONTED-MEEK-QUIC-OSSH", "TAPDANCE-OSSH", and "CONJURE-OSSH".
  158. // For the default, an empty list, all protocols are used.
  159. LimitTunnelProtocols []string
  160. // InitialLimitTunnelProtocols is an optional initial phase of limited
  161. // protocols for the first InitialLimitTunnelProtocolsCandidateCount
  162. // candidates; after these candidates, LimitTunnelProtocols applies.
  163. //
  164. // For the default, an empty list, InitialLimitTunnelProtocols is off.
  165. InitialLimitTunnelProtocols []string
  166. // InitialLimitTunnelProtocolsCandidateCount is the number of candidates
  167. // to which InitialLimitTunnelProtocols is applied instead of
  168. // LimitTunnelProtocols.
  169. //
  170. // For the default, 0, InitialLimitTunnelProtocols is off.
  171. InitialLimitTunnelProtocolsCandidateCount int
  172. // LimitTLSProfiles indicates which TLS profiles to select from. Valid
  173. // values are listed in protocols.SupportedTLSProfiles.
  174. // For the default, an empty list, all profiles are candidates for
  175. // selection.
  176. LimitTLSProfiles []string
  177. // LimitQUICVersions indicates which QUIC versions to select from. Valid
  178. // values are listed in protocols.SupportedQUICVersions.
  179. // For the default, an empty list, all versions are candidates for
  180. // selection.
  181. LimitQUICVersions []string
  182. // EstablishTunnelTimeoutSeconds specifies a time limit after which to
  183. // halt the core tunnel controller if no tunnel has been established. The
  184. // default is parameters.EstablishTunnelTimeout.
  185. EstablishTunnelTimeoutSeconds *int
  186. // EstablishTunnelPausePeriodSeconds specifies the delay between attempts
  187. // to establish tunnels. Briefly pausing allows for network conditions to
  188. // improve and for asynchronous operations such as fetch remote server
  189. // list to complete. If omitted, a default value is used. This value is
  190. // typical overridden for testing.
  191. EstablishTunnelPausePeriodSeconds *int
  192. // EstablishTunnelPausePeriodSeconds specifies the grace period, or head
  193. // start, provided to the affinity server candidate when establishing. The
  194. // affinity server is the server used for the last established tunnel.
  195. EstablishTunnelServerAffinityGracePeriodMilliseconds *int
  196. // ConnectionWorkerPoolSize specifies how many connection attempts to
  197. // attempt in parallel. If omitted of when 0, a default is used; this is
  198. // recommended.
  199. ConnectionWorkerPoolSize int
  200. // TunnelPoolSize specifies how many tunnels to run in parallel. Port
  201. // forwards are multiplexed over multiple tunnels. If omitted or when 0,
  202. // the default is TUNNEL_POOL_SIZE, which is recommended. Any value over
  203. // MAX_TUNNEL_POOL_SIZE is treated as MAX_TUNNEL_POOL_SIZE.
  204. TunnelPoolSize int
  205. // StaggerConnectionWorkersMilliseconds adds a specified delay before
  206. // making each server candidate available to connection workers. This
  207. // option is enabled when StaggerConnectionWorkersMilliseconds > 0.
  208. StaggerConnectionWorkersMilliseconds int
  209. // LimitIntensiveConnectionWorkers limits the number of concurrent
  210. // connection workers attempting connections with resource intensive
  211. // protocols. This option is enabled when LimitIntensiveConnectionWorkers
  212. // > 0.
  213. LimitIntensiveConnectionWorkers int
  214. // LimitMeekBufferSizes selects smaller buffers for meek protocols.
  215. LimitMeekBufferSizes bool
  216. // LimitCPUThreads minimizes the number of CPU threads -- and associated
  217. // overhead -- the are used.
  218. LimitCPUThreads bool
  219. // LimitRelayBufferSizes selects smaller buffers for port forward relaying.
  220. LimitRelayBufferSizes bool
  221. // IgnoreHandshakeStatsRegexps skips compiling and using stats regexes.
  222. IgnoreHandshakeStatsRegexps bool
  223. // UpstreamProxyURL is a URL specifying an upstream proxy to use for all
  224. // outbound connections. The URL should include proxy type and
  225. // authentication information, as required. See example URLs here:
  226. // https://github.com/Psiphon-Labs/psiphon-tunnel-core/tree/master/psiphon/upstreamproxy
  227. UpstreamProxyURL string
  228. // CustomHeaders is a set of additional arbitrary HTTP headers that are
  229. // added to all plaintext HTTP requests and requests made through an HTTP
  230. // upstream proxy when specified by UpstreamProxyURL.
  231. CustomHeaders http.Header
  232. // MeekAdditionalHeaders is a set of additional arbitrary HTTP headers
  233. // that are added to all meek HTTP requests. An additional header is
  234. // ignored when the header name is already present in a meek request.
  235. MeekAdditionalHeaders http.Header
  236. // NetworkConnectivityChecker is an interface that enables tunnel-core to
  237. // call into the host application to check for network connectivity. See:
  238. // NetworkConnectivityChecker doc.
  239. NetworkConnectivityChecker NetworkConnectivityChecker
  240. // DeviceBinder is an interface that enables tunnel-core to call into the
  241. // host application to bind sockets to specific devices. See: DeviceBinder
  242. // doc.
  243. //
  244. // When DeviceBinder is set, the "VPN" feature name is automatically added
  245. // when reporting ClientFeatures.
  246. DeviceBinder DeviceBinder
  247. // AllowDefaultDNSResolverWithBindToDevice indicates that it's safe to use
  248. // the default resolver when DeviceBinder is configured, as the host OS
  249. // will automatically exclude DNS requests from the VPN.
  250. AllowDefaultDNSResolverWithBindToDevice bool
  251. // IPv6Synthesizer is an interface that allows tunnel-core to call into
  252. // the host application to synthesize IPv6 addresses. See: IPv6Synthesizer
  253. // doc.
  254. IPv6Synthesizer IPv6Synthesizer
  255. // HasIPv6RouteGetter is an interface that allows tunnel-core to call into
  256. // the host application to determine if the host has an IPv6 route. See:
  257. // HasIPv6RouteGetter doc.
  258. HasIPv6RouteGetter HasIPv6RouteGetter
  259. // DNSServerGetter is an interface that enables tunnel-core to call into
  260. // the host application to discover the native network DNS server
  261. // settings. See: DNSServerGetter doc.
  262. DNSServerGetter DNSServerGetter
  263. // NetworkIDGetter in an interface that enables tunnel-core to call into
  264. // the host application to get an identifier for the host's current active
  265. // network. See: NetworkIDGetter doc.
  266. NetworkIDGetter NetworkIDGetter
  267. // NetworkID, when not blank, is used as the identifier for the host's
  268. // current active network.
  269. // NetworkID is ignored when NetworkIDGetter is set.
  270. NetworkID string
  271. // DisableTactics disables tactics operations including requests, payload
  272. // handling, and application of parameters.
  273. DisableTactics bool
  274. // DisableReplay causes any persisted dial parameters to be ignored when
  275. // they would otherwise be used for replay.
  276. DisableReplay bool
  277. // TargetServerEntry is an encoded server entry. When specified, this
  278. // server entry is used exclusively and all other known servers are
  279. // ignored; also, when set, ConnectionWorkerPoolSize is ignored and
  280. // the pool size is 1.
  281. TargetServerEntry string
  282. // DisableApi disables Psiphon server API calls including handshake,
  283. // connected, status, etc. This is used for special case temporary tunnels
  284. // (Windows VPN mode).
  285. DisableApi bool
  286. // TargetApiProtocol specifies whether to force use of "ssh" or "web" API
  287. // protocol. When blank, the default, the optimal API protocol is used.
  288. // Note that this capability check is not applied before the
  289. // "CandidateServers" count is emitted.
  290. //
  291. // This parameter is intended for testing and debugging only. Not all
  292. // parameters are supported in the legacy "web" API protocol, including
  293. // speed test samples.
  294. TargetApiProtocol string
  295. // RemoteServerListURLs is list of URLs which specify locations to fetch
  296. // out-of-band server entries. This facility is used when a tunnel cannot
  297. // be established to known servers. This value is supplied by and depends
  298. // on the Psiphon Network, and is typically embedded in the client binary.
  299. // All URLs must point to the same entity with the same ETag. At least one
  300. // TransferURL must have OnlyAfterAttempts = 0.
  301. RemoteServerListURLs parameters.TransferURLs
  302. // RemoteServerListSignaturePublicKey specifies a public key that's used
  303. // to authenticate the remote server list payload. This value is supplied
  304. // by and depends on the Psiphon Network, and is typically embedded in the
  305. // client binary.
  306. RemoteServerListSignaturePublicKey string
  307. // DisableRemoteServerListFetcher disables fetching remote server lists.
  308. // This is used for special case temporary tunnels.
  309. DisableRemoteServerListFetcher bool
  310. // FetchRemoteServerListRetryPeriodMilliseconds specifies the delay before
  311. // resuming a remote server list download after a failure. If omitted, a
  312. // default value is used. This value is typical overridden for testing.
  313. FetchRemoteServerListRetryPeriodMilliseconds *int
  314. // ObfuscatedServerListRootURLs is a list of URLs which specify root
  315. // locations from which to fetch obfuscated server list files. This value
  316. // is supplied by and depends on the Psiphon Network, and is typically
  317. // embedded in the client binary. All URLs must point to the same entity
  318. // with the same ETag. At least one DownloadURL must have
  319. // OnlyAfterAttempts = 0.
  320. ObfuscatedServerListRootURLs parameters.TransferURLs
  321. // EnableUpgradeDownload indicates whether to check for and download
  322. // upgrades. When set, UpgradeDownloadURLs and
  323. // UpgradeDownloadClientVersionHeader must also be set. ClientPlatform
  324. // and ClientVersion should also be set.
  325. EnableUpgradeDownload bool
  326. // UpgradeDownloadURLs is list of URLs which specify locations from which
  327. // to download a host client upgrade file, when one is available. The core
  328. // tunnel controller provides a resumable download facility which
  329. // downloads this resource and emits a notice when complete. This value is
  330. // supplied by and depends on the Psiphon Network, and is typically
  331. // embedded in the client binary. All URLs must point to the same entity
  332. // with the same ETag. At least one DownloadURL must have
  333. // OnlyAfterAttempts = 0.
  334. UpgradeDownloadURLs parameters.TransferURLs
  335. // UpgradeDownloadClientVersionHeader specifies the HTTP header name for
  336. // the entity at UpgradeDownloadURLs which specifies the client version
  337. // (an integer value). A HEAD request may be made to check the version
  338. // number available at UpgradeDownloadURLs.
  339. // UpgradeDownloadClientVersionHeader is required when UpgradeDownloadURLs
  340. // is specified.
  341. UpgradeDownloadClientVersionHeader string
  342. // FetchUpgradeRetryPeriodMilliseconds specifies the delay before resuming
  343. // a client upgrade download after a failure. If omitted, a default value
  344. // is used. This value is typical overridden for testing.
  345. FetchUpgradeRetryPeriodMilliseconds *int
  346. // EnableFeedbackUpload indicates whether to enable uploading feedback
  347. // data. When set, FeedbackUploadURLs and FeedbackEncryptionPublicKey
  348. // must also be set.
  349. EnableFeedbackUpload bool
  350. // FeedbackUploadURLs is a list of SecureTransferURLs which specify
  351. // locations where feedback data can be uploaded, pairing with each
  352. // location a public key with which to encrypt the feedback data. This
  353. // value is supplied by and depends on the Psiphon Network, and is
  354. // typically embedded in the client binary. At least one TransferURL must
  355. // have OnlyAfterAttempts = 0.
  356. FeedbackUploadURLs parameters.TransferURLs
  357. // FeedbackEncryptionPublicKey is a default base64-encoded, RSA public key
  358. // value used to encrypt feedback data. Used when uploading feedback with a
  359. // TransferURL which has no public key value configured, i.e.
  360. // B64EncodedPublicKey = "".
  361. FeedbackEncryptionPublicKey string
  362. // TrustedCACertificatesFilename specifies a file containing trusted CA
  363. // certs. When set, this toggles use of the trusted CA certs, specified in
  364. // TrustedCACertificatesFilename, for tunneled TLS connections that expect
  365. // server certificates signed with public certificate authorities
  366. // (currently, only upgrade downloads). This option is used with stock Go
  367. // TLS in cases where Go may fail to obtain a list of root CAs from the
  368. // operating system.
  369. TrustedCACertificatesFilename string
  370. // DisableSystemRootCAs, when true, disables loading system root CAs when
  371. // verifying TLS certificates for all remote server list downloads, upgrade
  372. // downloads, and feedback uploads. Each of these transfers has additional
  373. // security at the payload level. Verifying TLS certificates is preferred,
  374. // as an additional security and circumvention layer; set
  375. // DisableSystemRootCAs only in cases where system root CAs cannot be
  376. // loaded; for example, if unsupported (iOS < 12) or insufficient memory
  377. // (VPN extension on iOS < 15).
  378. DisableSystemRootCAs bool
  379. // DisablePeriodicSshKeepAlive indicates whether to send an SSH keepalive
  380. // every 1-2 minutes, when the tunnel is idle. If the SSH keepalive times
  381. // out, the tunnel is considered to have failed.
  382. DisablePeriodicSshKeepAlive bool
  383. // DeviceLocation is the optional, reported location the host device is
  384. // running in. This input value should be a string representing location
  385. // geohash. The device location is reported to the server in the connected
  386. // request and recorded for Psiphon stats.
  387. DeviceLocation string
  388. // DeviceRegion is the optional, reported region the host device is
  389. // running in. This input value should be a ISO 3166-1 alpha-2 country
  390. // code. The device region is reported to the server in the connected
  391. // request and recorded for Psiphon stats.
  392. //
  393. // When provided, this value may be used, pre-connection, to select
  394. // performance or circumvention optimization strategies for the given
  395. // region.
  396. DeviceRegion string
  397. // EmitDiagnosticNotices indicates whether to output notices containing
  398. // detailed information about the Psiphon session. As these notices may
  399. // contain sensitive information, they should not be insecurely distributed
  400. // or displayed to users. Default is off.
  401. EmitDiagnosticNotices bool
  402. // EmitDiagnosticNetworkParameters indicates whether to include network
  403. // parameters in diagnostic notices. As these parameters are sensitive
  404. // circumvention network information, they should not be insecurely
  405. // distributed or displayed to users. Default is off.
  406. EmitDiagnosticNetworkParameters bool
  407. // EmitBytesTransferred indicates whether to emit periodic notices showing
  408. // bytes sent and received.
  409. EmitBytesTransferred bool
  410. // EmitSLOKs indicates whether to emit notices for each seeded SLOK. As
  411. // this could reveal user browsing activity, it's intended for debugging
  412. // and testing only.
  413. EmitSLOKs bool
  414. // EmitRefractionNetworkingLogs indicates whether to emit gotapdance log
  415. // messages to stdout. Note that gotapdance log messages do not conform to
  416. // the Notice format standard. Default is off.
  417. EmitRefractionNetworkingLogs bool
  418. // EmitServerAlerts indicates whether to emit notices for server alerts.
  419. EmitServerAlerts bool
  420. // EmitClientAddress indicates whether to emit the client's public network
  421. // address, IP and port, as seen by the server.
  422. EmitClientAddress bool
  423. // RateLimits specify throttling configuration for the tunnel.
  424. RateLimits common.RateLimits
  425. // PacketTunnelTunDeviceFileDescriptor specifies a tun device file
  426. // descriptor to use for running a packet tunnel. When this value is > 0,
  427. // a packet tunnel is established through the server and packets are
  428. // relayed via the tun device file descriptor. The file descriptor is
  429. // duped in NewController. When PacketTunnelTunDeviceFileDescriptor is
  430. // set, TunnelPoolSize must be 1.
  431. PacketTunnelTunFileDescriptor int
  432. // PacketTunnelTransparentDNSIPv4Address is the IPv4 address of the DNS
  433. // server configured by a VPN using a packet tunnel. All DNS packets
  434. // destined to this DNS server are transparently redirected to the
  435. // Psiphon server DNS.
  436. PacketTunnelTransparentDNSIPv4Address string
  437. // PacketTunnelTransparentDNSIPv6Address is the IPv6 address of the DNS
  438. // server configured by a VPN using a packet tunnel. All DNS packets
  439. // destined to this DNS server are transparently redirected to the
  440. // Psiphon server DNS.
  441. PacketTunnelTransparentDNSIPv6Address string
  442. // SessionID specifies a client session ID to use in the Psiphon API. The
  443. // session ID should be a randomly generated value that is used only for a
  444. // single session, which is defined as the period between a user starting
  445. // a Psiphon client and stopping the client.
  446. //
  447. // A session ID must be 32 hex digits (lower case). When blank, a random
  448. // session ID is automatically generated. Supply a session ID when a
  449. // single client session will cross multiple Controller instances.
  450. SessionID string
  451. // Authorizations is a list of encoded, signed access control
  452. // authorizations that the client has obtained and will present to the
  453. // server.
  454. Authorizations []string
  455. // ServerEntrySignaturePublicKey is a base64-encoded, ed25519 public
  456. // key value used to verify individual server entry signatures. This value
  457. // is supplied by and depends on the Psiphon Network, and is typically
  458. // embedded in the client binary.
  459. ServerEntrySignaturePublicKey string
  460. // ExchangeObfuscationKey is a base64-encoded, NaCl secretbox key used to
  461. // obfuscate server info exchanges between clients.
  462. // Required for the exchange functionality.
  463. ExchangeObfuscationKey string
  464. // MigrateHomepageNoticesFilename migrates a homepage file from the path
  465. // previously configured with setNoticeFiles to the new path for homepage
  466. // files under the data root directory. The file specified by this config
  467. // value will be moved to config.GetHomePageFilename().
  468. //
  469. // Note: see comment for config.Commit() for a description of how file
  470. // migrations are performed.
  471. //
  472. // If not set, no migration operation will be performed.
  473. MigrateHomepageNoticesFilename string
  474. // MigrateRotatingNoticesFilename migrates notice files from the path
  475. // previously configured with setNoticeFiles to the new path for notice
  476. // files under the data root directory.
  477. //
  478. // MigrateRotatingNoticesFilename will be moved to
  479. // config.GetNoticesFilename().
  480. //
  481. // MigrateRotatingNoticesFilename.1 will be moved to
  482. // config.GetOldNoticesFilename().
  483. //
  484. // Note: see comment for config.Commit() for a description of how file
  485. // migrations are performed.
  486. //
  487. // If not set, no migration operation will be performed.
  488. MigrateRotatingNoticesFilename string
  489. // MigrateDataStoreDirectory indicates the location of the datastore
  490. // directory, as previously configured with the deprecated
  491. // DataStoreDirectory config field. Datastore files found in the specified
  492. // directory will be moved under the data root directory.
  493. //
  494. // Note: see comment for config.Commit() for a description of how file
  495. // migrations are performed.
  496. MigrateDataStoreDirectory string
  497. // MigrateRemoteServerListDownloadFilename indicates the location of
  498. // remote server list download files. The remote server list files found at
  499. // the specified path will be moved under the data root directory.
  500. //
  501. // Note: see comment for config.Commit() for a description of how file
  502. // migrations are performed.
  503. MigrateRemoteServerListDownloadFilename string
  504. // MigrateObfuscatedServerListDownloadDirectory indicates the location of
  505. // the obfuscated server list downloads directory, as previously configured
  506. // with ObfuscatedServerListDownloadDirectory. Obfuscated server list
  507. // download files found in the specified directory will be moved under the
  508. // data root directory.
  509. //
  510. // Warning: if the directory is empty after obfuscated server
  511. // list files are moved, then it will be deleted.
  512. //
  513. // Note: see comment for config.Commit() for a description of how file
  514. // migrations are performed.
  515. MigrateObfuscatedServerListDownloadDirectory string
  516. // MigrateUpgradeDownloadFilename indicates the location of downloaded
  517. // application upgrade files. Downloaded upgrade files found at the
  518. // specified path will be moved under the data root directory.
  519. //
  520. // Note: see comment for config.Commit() for a description of how file
  521. // migrations are performed.
  522. MigrateUpgradeDownloadFilename string
  523. //
  524. // The following parameters are deprecated.
  525. //
  526. // DataStoreDirectory is the directory in which to store the persistent
  527. // database, which contains information such as server entries. By
  528. // default, current working directory.
  529. //
  530. // Deprecated:
  531. // Use MigrateDataStoreDirectory. When MigrateDataStoreDirectory
  532. // is set, this parameter is ignored.
  533. //
  534. // DataStoreDirectory has been subsumed by the new data root directory,
  535. // which is configured with DataRootDirectory. If set, datastore files
  536. // found in the specified directory will be moved under the data root
  537. // directory.
  538. DataStoreDirectory string
  539. // RemoteServerListDownloadFilename specifies a target filename for
  540. // storing the remote server list download. Data is stored in co-located
  541. // files (RemoteServerListDownloadFilename.part*) to allow for resumable
  542. // downloading.
  543. //
  544. // Deprecated:
  545. // Use MigrateRemoteServerListDownloadFilename. When
  546. // MigrateRemoteServerListDownloadFilename is set, this parameter is
  547. // ignored.
  548. //
  549. // If set, remote server list download files found at the specified path
  550. // will be moved under the data root directory.
  551. RemoteServerListDownloadFilename string
  552. // ObfuscatedServerListDownloadDirectory specifies a target directory for
  553. // storing the obfuscated remote server list downloads. Data is stored in
  554. // co-located files (<OSL filename>.part*) to allow for resumable
  555. // downloading.
  556. //
  557. // Deprecated:
  558. // Use MigrateObfuscatedServerListDownloadDirectory. When
  559. // MigrateObfuscatedServerListDownloadDirectory is set, this parameter is
  560. // ignored.
  561. //
  562. // If set, obfuscated server list download files found at the specified path
  563. // will be moved under the data root directory.
  564. ObfuscatedServerListDownloadDirectory string
  565. // UpgradeDownloadFilename is the local target filename for an upgrade
  566. // download. This parameter is required when UpgradeDownloadURLs (or
  567. // UpgradeDownloadUrl) is specified. Data is stored in co-located files
  568. // (UpgradeDownloadFilename.part*) to allow for resumable downloading.
  569. //
  570. // Deprecated:
  571. // Use MigrateUpgradeDownloadFilename. When MigrateUpgradeDownloadFilename
  572. // is set, this parameter is ignored.
  573. //
  574. // If set, upgrade download files found at the specified path will be moved
  575. // under the data root directory.
  576. UpgradeDownloadFilename string
  577. // TunnelProtocol indicates which protocol to use. For the default, "",
  578. // all protocols are used.
  579. //
  580. // Deprecated: Use LimitTunnelProtocols. When LimitTunnelProtocols is not
  581. // nil, this parameter is ignored.
  582. TunnelProtocol string
  583. // Deprecated: Use CustomHeaders. When CustomHeaders is not nil, this
  584. // parameter is ignored.
  585. UpstreamProxyCustomHeaders http.Header
  586. // RemoteServerListUrl is a URL which specifies a location to fetch out-
  587. // of-band server entries. This facility is used when a tunnel cannot be
  588. // established to known servers. This value is supplied by and depends on
  589. // the Psiphon Network, and is typically embedded in the client binary.
  590. //
  591. // Deprecated: Use RemoteServerListURLs. When RemoteServerListURLs is not
  592. // nil, this parameter is ignored.
  593. RemoteServerListUrl string
  594. // ObfuscatedServerListRootURL is a URL which specifies the root location
  595. // from which to fetch obfuscated server list files. This value is
  596. // supplied by and depends on the Psiphon Network, and is typically
  597. // embedded in the client binary.
  598. //
  599. // Deprecated: Use ObfuscatedServerListRootURLs. When
  600. // ObfuscatedServerListRootURLs is not nil, this parameter is ignored.
  601. ObfuscatedServerListRootURL string
  602. // UpgradeDownloadUrl specifies a URL from which to download a host client
  603. // upgrade file, when one is available. The core tunnel controller
  604. // provides a resumable download facility which downloads this resource
  605. // and emits a notice when complete. This value is supplied by and depends
  606. // on the Psiphon Network, and is typically embedded in the client binary.
  607. //
  608. // Deprecated: Use UpgradeDownloadURLs. When UpgradeDownloadURLs is not
  609. // nil, this parameter is ignored.
  610. UpgradeDownloadUrl string
  611. //
  612. // The following parameters are for testing purposes.
  613. //
  614. // TransformHostNameProbability is for testing purposes.
  615. TransformHostNameProbability *float64
  616. // FragmentorProbability and associated Fragmentor fields are for testing
  617. // purposes.
  618. FragmentorProbability *float64
  619. FragmentorLimitProtocols []string
  620. FragmentorMinTotalBytes *int
  621. FragmentorMaxTotalBytes *int
  622. FragmentorMinWriteBytes *int
  623. FragmentorMaxWriteBytes *int
  624. FragmentorMinDelayMicroseconds *int
  625. FragmentorMaxDelayMicroseconds *int
  626. // MeekTrafficShapingProbability and associated fields are for testing
  627. // purposes.
  628. MeekTrafficShapingProbability *float64
  629. MeekTrafficShapingLimitProtocols []string
  630. MeekMinTLSPadding *int
  631. MeekMaxTLSPadding *int
  632. MeekMinLimitRequestPayloadLength *int
  633. MeekMaxLimitRequestPayloadLength *int
  634. MeekRedialTLSProbability *float64
  635. MeekAlternateCookieNameProbability *float64
  636. MeekAlternateContentTypeProbability *float64
  637. // ObfuscatedSSHAlgorithms and associated ObfuscatedSSH fields are for
  638. // testing purposes. If specified, ObfuscatedSSHAlgorithms must have 4 SSH
  639. // KEX elements in order: the kex algorithm, cipher, MAC, and server host
  640. // key algorithm.
  641. ObfuscatedSSHAlgorithms []string
  642. ObfuscatedSSHMinPadding *int
  643. ObfuscatedSSHMaxPadding *int
  644. // LivenessTestMinUpstreamBytes and other LivenessTest fields are for
  645. // testing purposes.
  646. LivenessTestMinUpstreamBytes *int
  647. LivenessTestMaxUpstreamBytes *int
  648. LivenessTestMinDownstreamBytes *int
  649. LivenessTestMaxDownstreamBytes *int
  650. // ReplayCandidateCount and other Replay fields are for testing purposes.
  651. ReplayCandidateCount *int
  652. ReplayDialParametersTTLSeconds *int
  653. ReplayTargetUpstreamBytes *int
  654. ReplayTargetDownstreamBytes *int
  655. ReplayTargetTunnelDurationSeconds *int
  656. ReplayLaterRoundMoveToFrontProbability *float64
  657. ReplayRetainFailedProbability *float64
  658. ReplayIgnoreChangedConfigState *bool
  659. // NetworkLatencyMultiplierMin and other NetworkLatencyMultiplier fields are
  660. // for testing purposes.
  661. NetworkLatencyMultiplierMin float64
  662. NetworkLatencyMultiplierMax float64
  663. NetworkLatencyMultiplierLambda float64
  664. // UseOnlyCustomTLSProfiles and other TLS configuration fields are for
  665. // testing purposes.
  666. UseOnlyCustomTLSProfiles *bool
  667. CustomTLSProfiles protocol.CustomTLSProfiles
  668. SelectRandomizedTLSProfileProbability *float64
  669. NoDefaultTLSSessionIDProbability *float64
  670. DisableFrontingProviderTLSProfiles protocol.LabeledTLSProfiles
  671. // ClientBurstUpstreamTargetBytes and other burst metric fields are for
  672. // testing purposes.
  673. ClientBurstUpstreamTargetBytes *int
  674. ClientBurstUpstreamDeadlineMilliseconds *int
  675. ClientBurstDownstreamTargetBytes *int
  676. ClientBurstDownstreamDeadlineMilliseconds *int
  677. // ApplicationParameters is for testing purposes.
  678. ApplicationParameters parameters.KeyValues
  679. // CustomHostNameRegexes and other custom host name fields are for testing
  680. // purposes.
  681. CustomHostNameRegexes []string
  682. CustomHostNameProbability *float64
  683. CustomHostNameLimitProtocols []string
  684. // ConjureCachedRegistrationTTLSeconds and other Conjure fields are for
  685. // testing purposes.
  686. ConjureCachedRegistrationTTLSeconds *int
  687. ConjureAPIRegistrarBidirectionalURL string
  688. ConjureAPIRegistrarFrontingSpecs parameters.FrontingSpecs
  689. ConjureAPIRegistrarMinDelayMilliseconds *int
  690. ConjureAPIRegistrarMaxDelayMilliseconds *int
  691. ConjureDecoyRegistrarProbability *float64
  692. ConjureDecoyRegistrarWidth *int
  693. ConjureDecoyRegistrarMinDelayMilliseconds *int
  694. ConjureDecoyRegistrarMaxDelayMilliseconds *int
  695. ConjureEnableIPv6Dials *bool
  696. ConjureEnablePortRandomization *bool
  697. ConjureEnableRegistrationOverrides *bool
  698. ConjureLimitTransports protocol.ConjureTransports
  699. ConjureSTUNServerAddresses []string
  700. ConjureDTLSEmptyInitialPacketProbability *float64
  701. // HoldOffTunnelMinDurationMilliseconds and other HoldOffTunnel fields are
  702. // for testing purposes.
  703. HoldOffTunnelMinDurationMilliseconds *int
  704. HoldOffTunnelMaxDurationMilliseconds *int
  705. HoldOffTunnelProtocols []string
  706. HoldOffTunnelFrontingProviderIDs []string
  707. HoldOffTunnelProbability *float64
  708. // HoldOffDirectTunnelMinDurationMilliseconds and other HoldOffDirect
  709. // fields are for testing purposes.
  710. HoldOffDirectTunnelMinDurationMilliseconds *int
  711. HoldOffDirectTunnelMaxDurationMilliseconds *int
  712. HoldOffDirectServerEntryRegions []string
  713. HoldOffDirectServerEntryProviderRegions map[string][]string
  714. HoldOffDirectTunnelProbability *float64
  715. // RestrictDirectProviderIDs and other RestrictDirect fields are for
  716. // testing purposes.
  717. RestrictDirectProviderIDs []string
  718. RestrictDirectProviderRegions map[string][]string
  719. RestrictDirectProviderIDsClientProbability *float64
  720. // RestrictFrontingProviderIDs and other RestrictFrontingProviderIDs fields
  721. // are for testing purposes.
  722. RestrictFrontingProviderIDs []string
  723. RestrictFrontingProviderIDsClientProbability *float64
  724. // UpstreamProxyAllowAllServerEntrySources is for testing purposes.
  725. UpstreamProxyAllowAllServerEntrySources *bool
  726. // LimitTunnelDialPortNumbers is for testing purposes.
  727. LimitTunnelDialPortNumbers parameters.TunnelProtocolPortLists
  728. // QUICDisablePathMTUDiscoveryProbability is for testing purposes.
  729. QUICDisablePathMTUDiscoveryProbability *float64
  730. // DNSResolverAttemptsPerServer and other DNSResolver fields are for
  731. // testing purposes.
  732. DNSResolverAttemptsPerServer *int
  733. DNSResolverAttemptsPerPreferredServer *int
  734. DNSResolverRequestTimeoutMilliseconds *int
  735. DNSResolverAwaitTimeoutMilliseconds *int
  736. DNSResolverPreresolvedIPAddressCIDRs parameters.LabeledCIDRs
  737. DNSResolverPreresolvedIPAddressProbability *float64
  738. DNSResolverAlternateServers []string
  739. DNSResolverPreferredAlternateServers []string
  740. DNSResolverPreferAlternateServerProbability *float64
  741. DNSResolverProtocolTransformSpecs transforms.Specs
  742. DNSResolverProtocolTransformScopedSpecNames transforms.ScopedSpecNames
  743. DNSResolverProtocolTransformProbability *float64
  744. DNSResolverIncludeEDNS0Probability *float64
  745. DNSResolverCacheExtensionInitialTTLMilliseconds *int
  746. DNSResolverCacheExtensionVerifiedTTLMilliseconds *int
  747. DirectHTTPProtocolTransformSpecs transforms.Specs
  748. DirectHTTPProtocolTransformScopedSpecNames transforms.ScopedSpecNames
  749. DirectHTTPProtocolTransformProbability *float64
  750. FrontedHTTPProtocolTransformSpecs transforms.Specs
  751. FrontedHTTPProtocolTransformScopedSpecNames transforms.ScopedSpecNames
  752. FrontedHTTPProtocolTransformProbability *float64
  753. OSSHObfuscatorSeedTransformSpecs transforms.Specs
  754. OSSHObfuscatorSeedTransformScopedSpecNames transforms.ScopedSpecNames
  755. OSSHObfuscatorSeedTransformProbability *float64
  756. ObfuscatedQUICNonceTransformSpecs transforms.Specs
  757. ObfuscatedQUICNonceTransformScopedSpecNames transforms.ScopedSpecNames
  758. ObfuscatedQUICNonceTransformProbability *float64
  759. // OSSHPrefix parameters are for testing purposes only.
  760. OSSHPrefixSpecs transforms.Specs
  761. OSSHPrefixScopedSpecNames transforms.ScopedSpecNames
  762. OSSHPrefixProbability *float64
  763. OSSHPrefixSplitMinDelayMilliseconds *int
  764. OSSHPrefixSplitMaxDelayMilliseconds *int
  765. OSSHPrefixEnableFragmentor *bool
  766. // TLSTunnelTrafficShapingProbability and associated fields are for testing.
  767. TLSTunnelTrafficShapingProbability *float64
  768. TLSTunnelMinTLSPadding *int
  769. TLSTunnelMaxTLSPadding *int
  770. // TLSFragmentClientHello fields are for testing purposes only.
  771. TLSFragmentClientHelloProbability *float64
  772. TLSFragmentClientHelloLimitProtocols []string
  773. // AdditionalParameters is used for testing.
  774. AdditionalParameters string
  775. // SteeringIP fields are for testing purposes only.
  776. SteeringIPCacheTTLSeconds *int
  777. SteeringIPCacheMaxEntries *int
  778. SteeringIPProbability *float64
  779. // params is the active parameters.Parameters with defaults, config values,
  780. // and, optionally, tactics applied.
  781. //
  782. // New tactics must be applied by calling Config.SetParameters; calling
  783. // params.Set directly will fail to add config values.
  784. params *parameters.Parameters
  785. dialParametersHash []byte
  786. dynamicConfigMutex sync.Mutex
  787. sponsorID string
  788. authorizations []string
  789. deviceBinder DeviceBinder
  790. networkIDGetter NetworkIDGetter
  791. clientFeatures []string
  792. resolverMutex sync.Mutex
  793. resolver *resolver.Resolver
  794. committed bool
  795. loadTimestamp string
  796. }
  797. // Config field which specifies if notice files should be used and at which
  798. // frequency and size they should be rotated.
  799. //
  800. // If either RotatingFileSize or RotatingSyncFrequency are <= 0, default values
  801. // are used.
  802. //
  803. // See comment for setNoticeFiles in notice.go for further details.
  804. type UseNoticeFiles struct {
  805. RotatingFileSize int
  806. RotatingSyncFrequency int
  807. }
  808. // LoadConfig parses a JSON format Psiphon config JSON string and returns a
  809. // Config struct populated with config values.
  810. //
  811. // The Config struct may then be programmatically populated with additional
  812. // values, including callbacks such as DeviceBinder.
  813. //
  814. // Before using the Config, Commit must be called, which will perform further
  815. // validation and initialize internal data structures.
  816. func LoadConfig(configJson []byte) (*Config, error) {
  817. var config Config
  818. err := json.Unmarshal(configJson, &config)
  819. if err != nil {
  820. return nil, errors.Trace(err)
  821. }
  822. config.loadTimestamp = common.TruncateTimestampToHour(
  823. common.GetCurrentTimestamp())
  824. return &config, nil
  825. }
  826. // IsCommitted checks if Commit was called.
  827. func (config *Config) IsCommitted() bool {
  828. return config.committed
  829. }
  830. // Commit validates Config fields finalizes initialization.
  831. //
  832. // Config fields should not be set after calling Config, as any changes may
  833. // not be reflected in internal data structures.
  834. //
  835. // If migrateFromLegacyFields is set to true, then an attempt to migrate from
  836. // legacy fields is made.
  837. //
  838. // Migration from legacy fields:
  839. // Config fields of the naming Migrate* (e.g. MigrateDataStoreDirectory) specify
  840. // a file migration operation which should be performed. These fields correspond
  841. // to deprecated fields, which previously could be used to specify where Psiphon
  842. // stored different sets of persistent files (e.g. MigrateDataStoreDirectory
  843. // corresponds to the deprecated field DataStoreDirectory).
  844. //
  845. // Psiphon now stores all persistent data under the configurable
  846. // DataRootDirectory (see Config.DataRootDirectory). The deprecated fields, and
  847. // corresponding Migrate* fields, are now used to specify the file or directory
  848. // path where, or under which, persistent files and directories created by
  849. // previous versions of Psiphon exist, so they can be moved under the
  850. // DataRootDirectory.
  851. //
  852. // For each migration operation:
  853. // - In the case of directories that could have defaulted to the current working
  854. // directory, persistent files and directories created by Psiphon are
  855. // precisely targeted to avoid moving files which were not created by Psiphon.
  856. // - If no file is found at the specified path, or an error is encountered while
  857. // migrating the file, then an error is logged and execution continues
  858. // normally.
  859. //
  860. // A sentinel file which signals that file migration has been completed, and
  861. // should not be attempted again, is created under DataRootDirectory after one
  862. // full pass through Commit(), regardless of whether file migration succeeds or
  863. // fails. It is better to not endlessly retry file migrations on each Commit()
  864. // because file system errors are expected to be rare and persistent files will
  865. // be re-populated over time.
  866. func (config *Config) Commit(migrateFromLegacyFields bool) error {
  867. // Apply any additional parameters first
  868. additionalParametersInfoMsgs, err := config.applyAdditionalParameters()
  869. if err != nil {
  870. return errors.TraceMsg(err, "failed to apply additional parameters")
  871. }
  872. // Do SetEmitDiagnosticNotices first, to ensure config file errors are
  873. // emitted.
  874. if config.EmitDiagnosticNotices {
  875. SetEmitDiagnosticNotices(
  876. true, config.EmitDiagnosticNetworkParameters)
  877. }
  878. // Migrate and set notice files before any operations that may emit an
  879. // error. This is to ensure config file errors are written to file when
  880. // notice files are configured with config.UseNoticeFiles.
  881. //
  882. // Note:
  883. // Errors encountered while configuring the data directory cannot be written
  884. // to notice files. This is because notices files are created within the
  885. // data directory.
  886. if config.DataRootDirectory == "" {
  887. wd, err := os.Getwd()
  888. if err != nil {
  889. return errors.Trace(common.RedactFilePathsError(err))
  890. }
  891. config.DataRootDirectory = wd
  892. }
  893. // Create root directory
  894. dataDirectoryPath := config.GetPsiphonDataDirectory()
  895. if !common.FileExists(dataDirectoryPath) {
  896. err := os.Mkdir(dataDirectoryPath, os.ModePerm)
  897. if err != nil {
  898. return errors.Tracef(
  899. "failed to create datastore directory with error: %s",
  900. common.RedactFilePathsError(err, dataDirectoryPath))
  901. }
  902. }
  903. // Check if the migration from legacy config fields has already been
  904. // completed. See the Migrate* config fields for more details.
  905. migrationCompleteFilePath := filepath.Join(config.GetPsiphonDataDirectory(), "migration_complete")
  906. needMigration := !common.FileExists(migrationCompleteFilePath)
  907. // Collect notices to emit them after notice files are set
  908. var noticeMigrationAlertMsgs []string
  909. var noticeMigrationInfoMsgs []string
  910. // Migrate notices first to ensure notice files are used for notices if
  911. // UseNoticeFiles is set.
  912. homepageFilePath := config.GetHomePageFilename()
  913. noticesFilePath := config.GetNoticesFilename()
  914. if migrateFromLegacyFields {
  915. if needMigration {
  916. // Move notice files that exist at legacy file paths under the data root
  917. // directory.
  918. noticeMigrationInfoMsgs = append(noticeMigrationInfoMsgs, "Config migration: need migration")
  919. noticeMigrations := migrationsFromLegacyNoticeFilePaths(config)
  920. successfulMigrations := 0
  921. for _, migration := range noticeMigrations {
  922. err := DoFileMigration(migration)
  923. if err != nil {
  924. alertMsg := fmt.Sprintf("Config migration: %s", errors.Trace(err))
  925. noticeMigrationAlertMsgs = append(noticeMigrationAlertMsgs, alertMsg)
  926. } else {
  927. successfulMigrations += 1
  928. }
  929. }
  930. infoMsg := fmt.Sprintf("Config migration: %d/%d notice files successfully migrated", successfulMigrations, len(noticeMigrations))
  931. noticeMigrationInfoMsgs = append(noticeMigrationInfoMsgs, infoMsg)
  932. } else {
  933. noticeMigrationInfoMsgs = append(noticeMigrationInfoMsgs, "Config migration: migration already completed")
  934. }
  935. }
  936. if config.UseNoticeFiles != nil {
  937. setNoticeFiles(
  938. homepageFilePath,
  939. noticesFilePath,
  940. config.UseNoticeFiles.RotatingFileSize,
  941. config.UseNoticeFiles.RotatingSyncFrequency)
  942. }
  943. // Emit notices now that notice files are set if configured
  944. for _, msg := range additionalParametersInfoMsgs {
  945. NoticeInfo(msg)
  946. }
  947. for _, msg := range noticeMigrationAlertMsgs {
  948. NoticeWarning(msg)
  949. }
  950. for _, msg := range noticeMigrationInfoMsgs {
  951. NoticeInfo(msg)
  952. }
  953. // Promote legacy fields.
  954. if config.CustomHeaders == nil {
  955. config.CustomHeaders = config.UpstreamProxyCustomHeaders
  956. config.UpstreamProxyCustomHeaders = nil
  957. }
  958. if config.RemoteServerListUrl != "" && config.RemoteServerListURLs == nil {
  959. config.RemoteServerListURLs = promoteLegacyTransferURL(config.RemoteServerListUrl)
  960. }
  961. if config.ObfuscatedServerListRootURL != "" && config.ObfuscatedServerListRootURLs == nil {
  962. config.ObfuscatedServerListRootURLs = promoteLegacyTransferURL(config.ObfuscatedServerListRootURL)
  963. }
  964. if config.UpgradeDownloadUrl != "" && config.UpgradeDownloadURLs == nil {
  965. config.UpgradeDownloadURLs = promoteLegacyTransferURL(config.UpgradeDownloadUrl)
  966. }
  967. if config.TunnelProtocol != "" && len(config.LimitTunnelProtocols) == 0 {
  968. config.LimitTunnelProtocols = []string{config.TunnelProtocol}
  969. }
  970. if config.DataStoreDirectory != "" && config.MigrateDataStoreDirectory == "" {
  971. config.MigrateDataStoreDirectory = config.DataStoreDirectory
  972. }
  973. if config.RemoteServerListDownloadFilename != "" && config.MigrateRemoteServerListDownloadFilename == "" {
  974. config.MigrateRemoteServerListDownloadFilename = config.RemoteServerListDownloadFilename
  975. }
  976. if config.ObfuscatedServerListDownloadDirectory != "" && config.MigrateObfuscatedServerListDownloadDirectory == "" {
  977. config.MigrateObfuscatedServerListDownloadDirectory = config.ObfuscatedServerListDownloadDirectory
  978. }
  979. if config.UpgradeDownloadFilename != "" && config.MigrateUpgradeDownloadFilename == "" {
  980. config.MigrateUpgradeDownloadFilename = config.UpgradeDownloadFilename
  981. }
  982. // Supply default values.
  983. // Create datastore directory.
  984. dataStoreDirectoryPath := config.GetDataStoreDirectory()
  985. if !common.FileExists(dataStoreDirectoryPath) {
  986. err := os.Mkdir(dataStoreDirectoryPath, os.ModePerm)
  987. if err != nil {
  988. return errors.Tracef(
  989. "failed to create datastore directory with error: %s",
  990. common.RedactFilePathsError(err, dataStoreDirectoryPath))
  991. }
  992. }
  993. // Create OSL directory.
  994. oslDirectoryPath := config.GetObfuscatedServerListDownloadDirectory()
  995. if !common.FileExists(oslDirectoryPath) {
  996. err := os.Mkdir(oslDirectoryPath, os.ModePerm)
  997. if err != nil {
  998. return errors.Tracef(
  999. "failed to create osl directory with error: %s",
  1000. common.RedactFilePathsError(err, oslDirectoryPath))
  1001. }
  1002. }
  1003. if config.ClientVersion == "" {
  1004. config.ClientVersion = "0"
  1005. }
  1006. if config.TunnelPoolSize == 0 {
  1007. config.TunnelPoolSize = TUNNEL_POOL_SIZE
  1008. }
  1009. // Validate config fields.
  1010. if !common.FileExists(config.DataRootDirectory) {
  1011. return errors.TraceNew("DataRootDirectory does not exist")
  1012. }
  1013. if config.PropagationChannelId == "" {
  1014. return errors.TraceNew("propagation channel ID is missing from the configuration file")
  1015. }
  1016. if config.SponsorId == "" {
  1017. return errors.TraceNew("sponsor ID is missing from the configuration file")
  1018. }
  1019. _, err = strconv.Atoi(config.ClientVersion)
  1020. if err != nil {
  1021. return errors.Tracef("invalid client version: %s", err)
  1022. }
  1023. if !common.Contains(
  1024. []string{"", protocol.PSIPHON_SSH_API_PROTOCOL, protocol.PSIPHON_WEB_API_PROTOCOL},
  1025. config.TargetApiProtocol) {
  1026. return errors.TraceNew("invalid TargetApiProtocol")
  1027. }
  1028. if !config.DisableRemoteServerListFetcher {
  1029. if config.RemoteServerListURLs != nil {
  1030. if config.RemoteServerListSignaturePublicKey == "" {
  1031. return errors.TraceNew("missing RemoteServerListSignaturePublicKey")
  1032. }
  1033. }
  1034. if config.ObfuscatedServerListRootURLs != nil {
  1035. if config.RemoteServerListSignaturePublicKey == "" {
  1036. return errors.TraceNew("missing RemoteServerListSignaturePublicKey")
  1037. }
  1038. }
  1039. }
  1040. if config.EnableUpgradeDownload {
  1041. if len(config.UpgradeDownloadURLs) == 0 {
  1042. return errors.TraceNew("missing UpgradeDownloadURLs")
  1043. }
  1044. if config.UpgradeDownloadClientVersionHeader == "" {
  1045. return errors.TraceNew("missing UpgradeDownloadClientVersionHeader")
  1046. }
  1047. }
  1048. if config.EnableFeedbackUpload {
  1049. if len(config.FeedbackUploadURLs) == 0 {
  1050. return errors.TraceNew("missing FeedbackUploadURLs")
  1051. }
  1052. if config.FeedbackEncryptionPublicKey == "" {
  1053. return errors.TraceNew("missing FeedbackEncryptionPublicKey")
  1054. }
  1055. }
  1056. // This constraint is expected by logic in Controller.runTunnels().
  1057. if config.PacketTunnelTunFileDescriptor > 0 && config.TunnelPoolSize != 1 {
  1058. return errors.TraceNew("packet tunnel mode requires TunnelPoolSize to be 1")
  1059. }
  1060. // SessionID must be PSIPHON_API_CLIENT_SESSION_ID_LENGTH lowercase hex-encoded bytes.
  1061. if config.SessionID == "" {
  1062. sessionID, err := MakeSessionId()
  1063. if err != nil {
  1064. return errors.Trace(err)
  1065. }
  1066. config.SessionID = sessionID
  1067. }
  1068. if len(config.SessionID) != 2*protocol.PSIPHON_API_CLIENT_SESSION_ID_LENGTH ||
  1069. -1 != strings.IndexFunc(config.SessionID, func(c rune) bool {
  1070. return !unicode.Is(unicode.ASCII_Hex_Digit, c) || unicode.IsUpper(c)
  1071. }) {
  1072. return errors.TraceNew("invalid SessionID")
  1073. }
  1074. config.params, err = parameters.NewParameters(
  1075. func(err error) {
  1076. NoticeWarning("Parameters getValue failed: %s", err)
  1077. })
  1078. if err != nil {
  1079. return errors.Trace(err)
  1080. }
  1081. if config.ObfuscatedSSHAlgorithms != nil &&
  1082. len(config.ObfuscatedSSHAlgorithms) != 4 {
  1083. // TODO: validate each algorithm?
  1084. return errors.TraceNew("invalid ObfuscatedSSHAlgorithms")
  1085. }
  1086. // parametersParameters.Set will validate the config fields applied to
  1087. // parametersParameters.
  1088. err = config.SetParameters("", false, nil)
  1089. if err != nil {
  1090. return errors.Trace(err)
  1091. }
  1092. // Calculate and set the dial parameters hash. After this point, related
  1093. // config fields must not change.
  1094. config.setDialParametersHash()
  1095. // Set defaults for dynamic config fields.
  1096. config.SetDynamicConfig(config.SponsorId, config.Authorizations)
  1097. // Initialize config.deviceBinder and config.config.networkIDGetter. These
  1098. // wrap config.DeviceBinder and config.NetworkIDGetter/NetworkID with
  1099. // loggers.
  1100. //
  1101. // New variables are set to avoid mutating input config fields.
  1102. // Internally, code must use config.deviceBinder and
  1103. // config.networkIDGetter and not the input/exported fields.
  1104. if config.DeviceBinder != nil {
  1105. config.deviceBinder = newLoggingDeviceBinder(config.DeviceBinder)
  1106. }
  1107. networkIDGetter := config.NetworkIDGetter
  1108. if networkIDGetter == nil {
  1109. // Limitation: unlike NetworkIDGetter, which calls back to platform APIs
  1110. // this method of network identification is not dynamic and will not reflect
  1111. // network changes that occur while running.
  1112. if config.NetworkID != "" {
  1113. networkIDGetter = newStaticNetworkGetter(config.NetworkID)
  1114. } else {
  1115. networkIDGetter = newStaticNetworkGetter("UNKNOWN")
  1116. }
  1117. }
  1118. config.networkIDGetter = newLoggingNetworkIDGetter(networkIDGetter)
  1119. // Initialize config.clientFeatures, which adds feature names on top of
  1120. // those specified by the host application in config.ClientFeatures.
  1121. config.clientFeatures = config.ClientFeatures
  1122. feature := "VPN"
  1123. if config.DeviceBinder != nil && !common.Contains(config.clientFeatures, feature) {
  1124. config.clientFeatures = append(config.clientFeatures, feature)
  1125. }
  1126. // Migrate from old config fields. This results in files being moved under
  1127. // a config specified data root directory.
  1128. if migrateFromLegacyFields && needMigration {
  1129. // If unset, set MigrateDataStoreDirectory to the previous default value for
  1130. // DataStoreDirectory to ensure that datastore files are migrated.
  1131. if config.MigrateDataStoreDirectory == "" {
  1132. wd, err := os.Getwd()
  1133. if err != nil {
  1134. return errors.Trace(err)
  1135. }
  1136. NoticeInfo("MigrateDataStoreDirectory unset, using working directory")
  1137. config.MigrateDataStoreDirectory = wd
  1138. }
  1139. // Move files that exist at legacy file paths under the data root
  1140. // directory.
  1141. migrations, err := migrationsFromLegacyFilePaths(config)
  1142. if err != nil {
  1143. return errors.Trace(err)
  1144. }
  1145. // Do migrations
  1146. successfulMigrations := 0
  1147. for _, migration := range migrations {
  1148. err := DoFileMigration(migration)
  1149. if err != nil {
  1150. NoticeWarning("Config migration: %s", errors.Trace(err))
  1151. } else {
  1152. successfulMigrations += 1
  1153. }
  1154. }
  1155. NoticeInfo(fmt.Sprintf(
  1156. "Config migration: %d/%d legacy files successfully migrated",
  1157. successfulMigrations, len(migrations)))
  1158. // Remove OSL directory if empty
  1159. if config.MigrateObfuscatedServerListDownloadDirectory != "" {
  1160. files, err := ioutil.ReadDir(config.MigrateObfuscatedServerListDownloadDirectory)
  1161. if err != nil {
  1162. NoticeWarning(
  1163. "Error reading OSL directory: %s",
  1164. errors.Trace(common.RedactFilePathsError(err, config.MigrateObfuscatedServerListDownloadDirectory)))
  1165. } else if len(files) == 0 {
  1166. err := os.Remove(config.MigrateObfuscatedServerListDownloadDirectory)
  1167. if err != nil {
  1168. NoticeWarning(
  1169. "Error deleting empty OSL directory: %s",
  1170. errors.Trace(common.RedactFilePathsError(err, config.MigrateObfuscatedServerListDownloadDirectory)))
  1171. }
  1172. }
  1173. }
  1174. f, err := os.Create(migrationCompleteFilePath)
  1175. if err != nil {
  1176. NoticeWarning(
  1177. "Config migration: failed to create migration completed file with error %s",
  1178. errors.Trace(common.RedactFilePathsError(err, migrationCompleteFilePath)))
  1179. } else {
  1180. NoticeInfo("Config migration: completed")
  1181. f.Close()
  1182. }
  1183. }
  1184. config.committed = true
  1185. return nil
  1186. }
  1187. // GetParameters returns the current parameters.Parameters.
  1188. func (config *Config) GetParameters() *parameters.Parameters {
  1189. return config.params
  1190. }
  1191. // SetParameters resets the parameters.Parameters to the default values,
  1192. // applies any config file values, and then applies the input parameters (from
  1193. // tactics, etc.)
  1194. //
  1195. // Set skipOnError to false when initially applying only config values, as
  1196. // this will validate the values and should fail. Set skipOnError to true when
  1197. // applying tactics to ignore invalid or unknown parameter values from tactics.
  1198. //
  1199. // In the case of applying tactics, do not call Config.parameters.Set
  1200. // directly as this will not first apply config values.
  1201. //
  1202. // If there is an error, the existing Config.parameters are left
  1203. // entirely unmodified.
  1204. func (config *Config) SetParameters(tag string, skipOnError bool, applyParameters map[string]interface{}) error {
  1205. setParameters := []map[string]interface{}{config.makeConfigParameters()}
  1206. if applyParameters != nil {
  1207. setParameters = append(setParameters, applyParameters)
  1208. }
  1209. counts, err := config.params.Set(tag, skipOnError, setParameters...)
  1210. if err != nil {
  1211. return errors.Trace(err)
  1212. }
  1213. NoticeInfo("applied %v parameters with tag '%s'", counts, tag)
  1214. // Emit certain individual parameter values for quick reference in diagnostics.
  1215. p := config.params.Get()
  1216. NoticeInfo(
  1217. "NetworkLatencyMultiplier Min/Max/Lambda: %f/%f/%f",
  1218. p.Float(parameters.NetworkLatencyMultiplierMin),
  1219. p.Float(parameters.NetworkLatencyMultiplierMax),
  1220. p.Float(parameters.NetworkLatencyMultiplierLambda))
  1221. // Application Parameters are feature flags/config info, delivered as Client
  1222. // Parameters via tactics/etc., to be communicated to the outer application.
  1223. // Emit these now, as notices.
  1224. if p.WeightedCoinFlip(parameters.ApplicationParametersProbability) {
  1225. NoticeApplicationParameters(p.KeyValues(parameters.ApplicationParameters))
  1226. }
  1227. return nil
  1228. }
  1229. // SetResolver sets the current resolver.
  1230. func (config *Config) SetResolver(resolver *resolver.Resolver) {
  1231. config.resolverMutex.Lock()
  1232. defer config.resolverMutex.Unlock()
  1233. config.resolver = resolver
  1234. }
  1235. // GetResolver returns the current resolver. May return nil.
  1236. func (config *Config) GetResolver() *resolver.Resolver {
  1237. config.resolverMutex.Lock()
  1238. defer config.resolverMutex.Unlock()
  1239. return config.resolver
  1240. }
  1241. // SetDynamicConfig sets the current client sponsor ID and authorizations.
  1242. // Invalid values for sponsor ID are ignored. The caller must not modify the
  1243. // input authorizations slice.
  1244. func (config *Config) SetDynamicConfig(sponsorID string, authorizations []string) {
  1245. config.dynamicConfigMutex.Lock()
  1246. defer config.dynamicConfigMutex.Unlock()
  1247. if sponsorID != "" {
  1248. config.sponsorID = sponsorID
  1249. }
  1250. config.authorizations = authorizations
  1251. }
  1252. // GetSponsorID returns the current client sponsor ID.
  1253. func (config *Config) GetSponsorID() string {
  1254. config.dynamicConfigMutex.Lock()
  1255. defer config.dynamicConfigMutex.Unlock()
  1256. return config.sponsorID
  1257. }
  1258. // IsSplitTunnelEnabled indicates if split tunnel mode is enabled, either for
  1259. // the client's own country, a specified list of countries, or both.
  1260. func (config *Config) IsSplitTunnelEnabled() bool {
  1261. return config.SplitTunnelOwnRegion || len(config.SplitTunnelRegions) > 0
  1262. }
  1263. // GetAuthorizations returns the current client authorizations.
  1264. // The caller must not modify the returned slice.
  1265. func (config *Config) GetAuthorizations() []string {
  1266. config.dynamicConfigMutex.Lock()
  1267. defer config.dynamicConfigMutex.Unlock()
  1268. return config.authorizations
  1269. }
  1270. // GetPsiphonDataDirectory returns the directory under which all persistent
  1271. // files should be stored. This directory is created under
  1272. // config.DataRootDirectory. The motivation for an additional directory is that
  1273. // config.DataRootDirectory defaults to the current working directory, which may
  1274. // include non-tunnel-core files that should be excluded from directory-spanning
  1275. // operations (e.g. excluding all tunnel-core files from backup).
  1276. func (config *Config) GetPsiphonDataDirectory() string {
  1277. return filepath.Join(config.DataRootDirectory, PsiphonDataDirectoryName)
  1278. }
  1279. // GetHomePageFilename the path where the homepage notices file will be created.
  1280. func (config *Config) GetHomePageFilename() string {
  1281. return filepath.Join(config.GetPsiphonDataDirectory(), HomepageFilename)
  1282. }
  1283. // GetNoticesFilename returns the path where the notices file will be created.
  1284. // When the file is rotated it will be moved to config.GetOldNoticesFilename().
  1285. func (config *Config) GetNoticesFilename() string {
  1286. return filepath.Join(config.GetPsiphonDataDirectory(), NoticesFilename)
  1287. }
  1288. // GetOldNoticeFilename returns the path where the rotated notices file will be
  1289. // created.
  1290. func (config *Config) GetOldNoticesFilename() string {
  1291. return filepath.Join(config.GetPsiphonDataDirectory(), OldNoticesFilename)
  1292. }
  1293. // GetDataStoreDirectory returns the directory in which the persistent database
  1294. // will be stored. Created in Config.Commit(). The persistent database contains
  1295. // information such as server entries.
  1296. func (config *Config) GetDataStoreDirectory() string {
  1297. return filepath.Join(config.GetPsiphonDataDirectory(), "datastore")
  1298. }
  1299. // GetObfuscatedServerListDownloadDirectory returns the directory in which
  1300. // obfuscated remote server list downloads will be stored. Created in
  1301. // Config.Commit().
  1302. func (config *Config) GetObfuscatedServerListDownloadDirectory() string {
  1303. return filepath.Join(config.GetPsiphonDataDirectory(), "osl")
  1304. }
  1305. // GetRemoteServerListDownloadFilename returns the filename where the remote
  1306. // server list download will be stored. Data is stored in co-located files
  1307. // (RemoteServerListDownloadFilename.part*) to allow for resumable downloading.
  1308. func (config *Config) GetRemoteServerListDownloadFilename() string {
  1309. return filepath.Join(config.GetPsiphonDataDirectory(), "remote_server_list")
  1310. }
  1311. // GetUpgradeDownloadFilename specifies the filename where upgrade downloads
  1312. // will be stored. This filename is valid when UpgradeDownloadURLs
  1313. // (or UpgradeDownloadUrl) is specified. Data is stored in co-located files
  1314. // (UpgradeDownloadFilename.part*) to allow for resumable downloading.
  1315. func (config *Config) GetUpgradeDownloadFilename() string {
  1316. return filepath.Join(config.GetPsiphonDataDirectory(), UpgradeDownloadFilename)
  1317. }
  1318. // UseUpstreamProxy indicates if an upstream proxy has been
  1319. // configured.
  1320. func (config *Config) UseUpstreamProxy() bool {
  1321. return config.UpstreamProxyURL != ""
  1322. }
  1323. // GetNetworkID returns the current network ID. When NetworkIDGetter
  1324. // is set, this calls into the host application; otherwise, a default
  1325. // value is returned.
  1326. func (config *Config) GetNetworkID() string {
  1327. return config.networkIDGetter.GetNetworkID()
  1328. }
  1329. func (config *Config) makeConfigParameters() map[string]interface{} {
  1330. // Build set of config values to apply to parameters.
  1331. //
  1332. // Note: names of some config fields such as
  1333. // StaggerConnectionWorkersMilliseconds and LimitMeekBufferSizes have
  1334. // changed in the parameters. The existing config fields are retained for
  1335. // backwards compatibility.
  1336. applyParameters := make(map[string]interface{})
  1337. // To support platform clients that configure NetworkLatencyMultiplier, set
  1338. // the NetworkLatencyMultiplierMin/NetworkLatencyMultiplierMax range to the
  1339. // specified value. Also set the older NetworkLatencyMultiplier tactic, since
  1340. // that will be used in the case of replaying with dial parameters persisted
  1341. // by an older client version.
  1342. if config.NetworkLatencyMultiplier > 0.0 {
  1343. applyParameters[parameters.NetworkLatencyMultiplier] = config.NetworkLatencyMultiplier
  1344. applyParameters[parameters.NetworkLatencyMultiplierMin] = config.NetworkLatencyMultiplier
  1345. applyParameters[parameters.NetworkLatencyMultiplierMax] = config.NetworkLatencyMultiplier
  1346. }
  1347. if config.NetworkLatencyMultiplierMin > 0.0 {
  1348. applyParameters[parameters.NetworkLatencyMultiplierMin] = config.NetworkLatencyMultiplierMin
  1349. }
  1350. if config.NetworkLatencyMultiplierMax > 0.0 {
  1351. applyParameters[parameters.NetworkLatencyMultiplierMax] = config.NetworkLatencyMultiplierMax
  1352. }
  1353. if config.NetworkLatencyMultiplierLambda > 0.0 {
  1354. applyParameters[parameters.NetworkLatencyMultiplierLambda] = config.NetworkLatencyMultiplierLambda
  1355. }
  1356. if len(config.LimitTunnelProtocols) > 0 {
  1357. applyParameters[parameters.LimitTunnelProtocols] = protocol.TunnelProtocols(config.LimitTunnelProtocols)
  1358. }
  1359. if len(config.InitialLimitTunnelProtocols) > 0 && config.InitialLimitTunnelProtocolsCandidateCount > 0 {
  1360. applyParameters[parameters.InitialLimitTunnelProtocols] = protocol.TunnelProtocols(config.InitialLimitTunnelProtocols)
  1361. applyParameters[parameters.InitialLimitTunnelProtocolsCandidateCount] = config.InitialLimitTunnelProtocolsCandidateCount
  1362. }
  1363. if len(config.LimitTLSProfiles) > 0 {
  1364. applyParameters[parameters.LimitTLSProfiles] = protocol.TunnelProtocols(config.LimitTLSProfiles)
  1365. }
  1366. if len(config.LimitQUICVersions) > 0 {
  1367. applyParameters[parameters.LimitQUICVersions] = protocol.QUICVersions(config.LimitQUICVersions)
  1368. }
  1369. if config.EstablishTunnelTimeoutSeconds != nil {
  1370. applyParameters[parameters.EstablishTunnelTimeout] = fmt.Sprintf("%ds", *config.EstablishTunnelTimeoutSeconds)
  1371. }
  1372. if config.EstablishTunnelServerAffinityGracePeriodMilliseconds != nil {
  1373. applyParameters[parameters.EstablishTunnelServerAffinityGracePeriod] = fmt.Sprintf("%dms", *config.EstablishTunnelServerAffinityGracePeriodMilliseconds)
  1374. }
  1375. if config.EstablishTunnelPausePeriodSeconds != nil {
  1376. applyParameters[parameters.EstablishTunnelPausePeriod] = fmt.Sprintf("%ds", *config.EstablishTunnelPausePeriodSeconds)
  1377. }
  1378. if config.ConnectionWorkerPoolSize != 0 {
  1379. applyParameters[parameters.ConnectionWorkerPoolSize] = config.ConnectionWorkerPoolSize
  1380. }
  1381. if config.TunnelPoolSize != 0 {
  1382. applyParameters[parameters.TunnelPoolSize] = config.TunnelPoolSize
  1383. }
  1384. if config.StaggerConnectionWorkersMilliseconds > 0 {
  1385. applyParameters[parameters.StaggerConnectionWorkersPeriod] = fmt.Sprintf("%dms", config.StaggerConnectionWorkersMilliseconds)
  1386. }
  1387. if config.LimitIntensiveConnectionWorkers > 0 {
  1388. applyParameters[parameters.LimitIntensiveConnectionWorkers] = config.LimitIntensiveConnectionWorkers
  1389. }
  1390. applyParameters[parameters.MeekLimitBufferSizes] = config.LimitMeekBufferSizes
  1391. applyParameters[parameters.IgnoreHandshakeStatsRegexps] = config.IgnoreHandshakeStatsRegexps
  1392. if config.EstablishTunnelTimeoutSeconds != nil {
  1393. applyParameters[parameters.EstablishTunnelTimeout] = fmt.Sprintf("%ds", *config.EstablishTunnelTimeoutSeconds)
  1394. }
  1395. if config.FetchRemoteServerListRetryPeriodMilliseconds != nil {
  1396. applyParameters[parameters.FetchRemoteServerListRetryPeriod] = fmt.Sprintf("%dms", *config.FetchRemoteServerListRetryPeriodMilliseconds)
  1397. }
  1398. if config.FetchUpgradeRetryPeriodMilliseconds != nil {
  1399. applyParameters[parameters.FetchUpgradeRetryPeriod] = fmt.Sprintf("%dms", *config.FetchUpgradeRetryPeriodMilliseconds)
  1400. }
  1401. if !config.DisableRemoteServerListFetcher {
  1402. if config.RemoteServerListURLs != nil {
  1403. applyParameters[parameters.RemoteServerListSignaturePublicKey] = config.RemoteServerListSignaturePublicKey
  1404. applyParameters[parameters.RemoteServerListURLs] = config.RemoteServerListURLs
  1405. }
  1406. if config.ObfuscatedServerListRootURLs != nil {
  1407. applyParameters[parameters.RemoteServerListSignaturePublicKey] = config.RemoteServerListSignaturePublicKey
  1408. applyParameters[parameters.ObfuscatedServerListRootURLs] = config.ObfuscatedServerListRootURLs
  1409. }
  1410. }
  1411. if config.EnableUpgradeDownload {
  1412. applyParameters[parameters.UpgradeDownloadURLs] = config.UpgradeDownloadURLs
  1413. applyParameters[parameters.UpgradeDownloadClientVersionHeader] = config.UpgradeDownloadClientVersionHeader
  1414. }
  1415. if config.EnableFeedbackUpload {
  1416. applyParameters[parameters.FeedbackUploadURLs] = config.FeedbackUploadURLs
  1417. applyParameters[parameters.FeedbackEncryptionPublicKey] = config.FeedbackEncryptionPublicKey
  1418. }
  1419. applyParameters[parameters.TunnelRateLimits] = config.RateLimits
  1420. if config.TransformHostNameProbability != nil {
  1421. applyParameters[parameters.TransformHostNameProbability] = *config.TransformHostNameProbability
  1422. }
  1423. if config.FragmentorProbability != nil {
  1424. applyParameters[parameters.FragmentorProbability] = *config.FragmentorProbability
  1425. }
  1426. if len(config.FragmentorLimitProtocols) > 0 {
  1427. applyParameters[parameters.FragmentorLimitProtocols] = protocol.TunnelProtocols(config.FragmentorLimitProtocols)
  1428. }
  1429. if config.FragmentorMinTotalBytes != nil {
  1430. applyParameters[parameters.FragmentorMinTotalBytes] = *config.FragmentorMinTotalBytes
  1431. }
  1432. if config.FragmentorMaxTotalBytes != nil {
  1433. applyParameters[parameters.FragmentorMaxTotalBytes] = *config.FragmentorMaxTotalBytes
  1434. }
  1435. if config.FragmentorMinWriteBytes != nil {
  1436. applyParameters[parameters.FragmentorMinWriteBytes] = *config.FragmentorMinWriteBytes
  1437. }
  1438. if config.FragmentorMaxWriteBytes != nil {
  1439. applyParameters[parameters.FragmentorMaxWriteBytes] = *config.FragmentorMaxWriteBytes
  1440. }
  1441. if config.FragmentorMinDelayMicroseconds != nil {
  1442. applyParameters[parameters.FragmentorMinDelay] = fmt.Sprintf("%dus", *config.FragmentorMinDelayMicroseconds)
  1443. }
  1444. if config.FragmentorMaxDelayMicroseconds != nil {
  1445. applyParameters[parameters.FragmentorMaxDelay] = fmt.Sprintf("%dus", *config.FragmentorMaxDelayMicroseconds)
  1446. }
  1447. if config.MeekTrafficShapingProbability != nil {
  1448. applyParameters[parameters.MeekTrafficShapingProbability] = *config.MeekTrafficShapingProbability
  1449. }
  1450. if len(config.MeekTrafficShapingLimitProtocols) > 0 {
  1451. applyParameters[parameters.MeekTrafficShapingLimitProtocols] = protocol.TunnelProtocols(config.MeekTrafficShapingLimitProtocols)
  1452. }
  1453. if config.MeekMinTLSPadding != nil {
  1454. applyParameters[parameters.MeekMinTLSPadding] = *config.MeekMinTLSPadding
  1455. }
  1456. if config.MeekMaxTLSPadding != nil {
  1457. applyParameters[parameters.MeekMaxTLSPadding] = *config.MeekMaxTLSPadding
  1458. }
  1459. if config.MeekMinLimitRequestPayloadLength != nil {
  1460. applyParameters[parameters.MeekMinLimitRequestPayloadLength] = *config.MeekMinLimitRequestPayloadLength
  1461. }
  1462. if config.MeekMaxLimitRequestPayloadLength != nil {
  1463. applyParameters[parameters.MeekMaxLimitRequestPayloadLength] = *config.MeekMaxLimitRequestPayloadLength
  1464. }
  1465. if config.MeekRedialTLSProbability != nil {
  1466. applyParameters[parameters.MeekRedialTLSProbability] = *config.MeekRedialTLSProbability
  1467. }
  1468. if config.MeekAlternateCookieNameProbability != nil {
  1469. applyParameters[parameters.MeekAlternateCookieNameProbability] = *config.MeekAlternateCookieNameProbability
  1470. }
  1471. if config.MeekAlternateContentTypeProbability != nil {
  1472. applyParameters[parameters.MeekAlternateContentTypeProbability] = *config.MeekAlternateContentTypeProbability
  1473. }
  1474. if config.ObfuscatedSSHMinPadding != nil {
  1475. applyParameters[parameters.ObfuscatedSSHMinPadding] = *config.ObfuscatedSSHMinPadding
  1476. }
  1477. if config.ObfuscatedSSHMaxPadding != nil {
  1478. applyParameters[parameters.ObfuscatedSSHMaxPadding] = *config.ObfuscatedSSHMaxPadding
  1479. }
  1480. if config.LivenessTestMinUpstreamBytes != nil {
  1481. applyParameters[parameters.LivenessTestMinUpstreamBytes] = *config.LivenessTestMinUpstreamBytes
  1482. }
  1483. if config.LivenessTestMaxUpstreamBytes != nil {
  1484. applyParameters[parameters.LivenessTestMaxUpstreamBytes] = *config.LivenessTestMaxUpstreamBytes
  1485. }
  1486. if config.LivenessTestMinDownstreamBytes != nil {
  1487. applyParameters[parameters.LivenessTestMinDownstreamBytes] = *config.LivenessTestMinDownstreamBytes
  1488. }
  1489. if config.LivenessTestMaxDownstreamBytes != nil {
  1490. applyParameters[parameters.LivenessTestMaxDownstreamBytes] = *config.LivenessTestMaxDownstreamBytes
  1491. }
  1492. if config.ReplayCandidateCount != nil {
  1493. applyParameters[parameters.ReplayCandidateCount] = *config.ReplayCandidateCount
  1494. }
  1495. if config.ReplayDialParametersTTLSeconds != nil {
  1496. applyParameters[parameters.ReplayDialParametersTTL] = fmt.Sprintf("%ds", *config.ReplayDialParametersTTLSeconds)
  1497. }
  1498. if config.ReplayTargetUpstreamBytes != nil {
  1499. applyParameters[parameters.ReplayTargetUpstreamBytes] = *config.ReplayTargetUpstreamBytes
  1500. }
  1501. if config.ReplayTargetDownstreamBytes != nil {
  1502. applyParameters[parameters.ReplayTargetDownstreamBytes] = *config.ReplayTargetDownstreamBytes
  1503. }
  1504. if config.ReplayTargetTunnelDurationSeconds != nil {
  1505. applyParameters[parameters.ReplayTargetTunnelDuration] = fmt.Sprintf("%ds", *config.ReplayTargetTunnelDurationSeconds)
  1506. }
  1507. if config.ReplayLaterRoundMoveToFrontProbability != nil {
  1508. applyParameters[parameters.ReplayLaterRoundMoveToFrontProbability] = *config.ReplayLaterRoundMoveToFrontProbability
  1509. }
  1510. if config.ReplayRetainFailedProbability != nil {
  1511. applyParameters[parameters.ReplayRetainFailedProbability] = *config.ReplayRetainFailedProbability
  1512. }
  1513. if config.ReplayIgnoreChangedConfigState != nil {
  1514. applyParameters[parameters.ReplayIgnoreChangedConfigState] = *config.ReplayIgnoreChangedConfigState
  1515. }
  1516. if config.UseOnlyCustomTLSProfiles != nil {
  1517. applyParameters[parameters.UseOnlyCustomTLSProfiles] = *config.UseOnlyCustomTLSProfiles
  1518. }
  1519. if len(config.CustomTLSProfiles) > 0 {
  1520. applyParameters[parameters.CustomTLSProfiles] = config.CustomTLSProfiles
  1521. }
  1522. if config.SelectRandomizedTLSProfileProbability != nil {
  1523. applyParameters[parameters.SelectRandomizedTLSProfileProbability] = *config.SelectRandomizedTLSProfileProbability
  1524. }
  1525. if config.NoDefaultTLSSessionIDProbability != nil {
  1526. applyParameters[parameters.NoDefaultTLSSessionIDProbability] = *config.NoDefaultTLSSessionIDProbability
  1527. }
  1528. if len(config.DisableFrontingProviderTLSProfiles) > 0 {
  1529. applyParameters[parameters.DisableFrontingProviderTLSProfiles] = config.DisableFrontingProviderTLSProfiles
  1530. }
  1531. if config.ClientBurstUpstreamTargetBytes != nil {
  1532. applyParameters[parameters.ClientBurstUpstreamTargetBytes] = *config.ClientBurstUpstreamTargetBytes
  1533. }
  1534. if config.ClientBurstUpstreamDeadlineMilliseconds != nil {
  1535. applyParameters[parameters.ClientBurstUpstreamDeadline] = fmt.Sprintf("%dms", *config.ClientBurstUpstreamDeadlineMilliseconds)
  1536. }
  1537. if config.ClientBurstDownstreamTargetBytes != nil {
  1538. applyParameters[parameters.ClientBurstDownstreamTargetBytes] = *config.ClientBurstDownstreamTargetBytes
  1539. }
  1540. if config.ClientBurstDownstreamDeadlineMilliseconds != nil {
  1541. applyParameters[parameters.ClientBurstDownstreamDeadline] = fmt.Sprintf("%dms", *config.ClientBurstDownstreamDeadlineMilliseconds)
  1542. }
  1543. if config.ApplicationParameters != nil {
  1544. applyParameters[parameters.ApplicationParameters] = config.ApplicationParameters
  1545. }
  1546. if config.CustomHostNameRegexes != nil {
  1547. applyParameters[parameters.CustomHostNameRegexes] = parameters.RegexStrings(config.CustomHostNameRegexes)
  1548. }
  1549. if config.CustomHostNameProbability != nil {
  1550. applyParameters[parameters.CustomHostNameProbability] = *config.CustomHostNameProbability
  1551. }
  1552. if config.CustomHostNameLimitProtocols != nil {
  1553. applyParameters[parameters.CustomHostNameLimitProtocols] = protocol.TunnelProtocols(config.CustomHostNameLimitProtocols)
  1554. }
  1555. if config.ConjureCachedRegistrationTTLSeconds != nil {
  1556. applyParameters[parameters.ConjureCachedRegistrationTTL] = fmt.Sprintf("%ds", *config.ConjureCachedRegistrationTTLSeconds)
  1557. }
  1558. if config.ConjureAPIRegistrarBidirectionalURL != "" {
  1559. applyParameters[parameters.ConjureAPIRegistrarBidirectionalURL] = config.ConjureAPIRegistrarBidirectionalURL
  1560. }
  1561. if len(config.ConjureAPIRegistrarFrontingSpecs) > 0 {
  1562. applyParameters[parameters.ConjureAPIRegistrarFrontingSpecs] = config.ConjureAPIRegistrarFrontingSpecs
  1563. }
  1564. if config.ConjureAPIRegistrarMinDelayMilliseconds != nil {
  1565. applyParameters[parameters.ConjureAPIRegistrarMinDelay] = fmt.Sprintf("%dms", *config.ConjureAPIRegistrarMinDelayMilliseconds)
  1566. }
  1567. if config.ConjureAPIRegistrarMaxDelayMilliseconds != nil {
  1568. applyParameters[parameters.ConjureAPIRegistrarMaxDelay] = fmt.Sprintf("%dms", *config.ConjureAPIRegistrarMaxDelayMilliseconds)
  1569. }
  1570. if config.ConjureDecoyRegistrarProbability != nil {
  1571. applyParameters[parameters.ConjureDecoyRegistrarProbability] = *config.ConjureDecoyRegistrarProbability
  1572. }
  1573. if config.ConjureDecoyRegistrarWidth != nil {
  1574. applyParameters[parameters.ConjureDecoyRegistrarWidth] = *config.ConjureDecoyRegistrarWidth
  1575. }
  1576. if config.ConjureDecoyRegistrarMinDelayMilliseconds != nil {
  1577. applyParameters[parameters.ConjureDecoyRegistrarMinDelay] = fmt.Sprintf("%dms", *config.ConjureDecoyRegistrarMinDelayMilliseconds)
  1578. }
  1579. if config.ConjureDecoyRegistrarMaxDelayMilliseconds != nil {
  1580. applyParameters[parameters.ConjureDecoyRegistrarMaxDelay] = fmt.Sprintf("%dms", *config.ConjureDecoyRegistrarMaxDelayMilliseconds)
  1581. }
  1582. if config.ConjureEnableIPv6Dials != nil {
  1583. applyParameters[parameters.ConjureEnableIPv6Dials] = *config.ConjureEnableIPv6Dials
  1584. }
  1585. if config.ConjureEnablePortRandomization != nil {
  1586. applyParameters[parameters.ConjureEnablePortRandomization] = *config.ConjureEnablePortRandomization
  1587. }
  1588. if config.ConjureEnableRegistrationOverrides != nil {
  1589. applyParameters[parameters.ConjureEnableRegistrationOverrides] = *config.ConjureEnableRegistrationOverrides
  1590. }
  1591. if config.ConjureLimitTransports != nil {
  1592. applyParameters[parameters.ConjureLimitTransports] = config.ConjureLimitTransports
  1593. }
  1594. if config.ConjureSTUNServerAddresses != nil {
  1595. applyParameters[parameters.ConjureSTUNServerAddresses] = config.ConjureSTUNServerAddresses
  1596. }
  1597. if config.ConjureDTLSEmptyInitialPacketProbability != nil {
  1598. applyParameters[parameters.ConjureDTLSEmptyInitialPacketProbability] = *config.ConjureDTLSEmptyInitialPacketProbability
  1599. }
  1600. if config.HoldOffTunnelMinDurationMilliseconds != nil {
  1601. applyParameters[parameters.HoldOffTunnelMinDuration] = fmt.Sprintf("%dms", *config.HoldOffTunnelMinDurationMilliseconds)
  1602. }
  1603. if config.HoldOffTunnelMaxDurationMilliseconds != nil {
  1604. applyParameters[parameters.HoldOffTunnelMaxDuration] = fmt.Sprintf("%dms", *config.HoldOffTunnelMaxDurationMilliseconds)
  1605. }
  1606. if len(config.HoldOffTunnelProtocols) > 0 {
  1607. applyParameters[parameters.HoldOffTunnelProtocols] = protocol.TunnelProtocols(config.HoldOffTunnelProtocols)
  1608. }
  1609. if len(config.HoldOffTunnelFrontingProviderIDs) > 0 {
  1610. applyParameters[parameters.HoldOffTunnelFrontingProviderIDs] = config.HoldOffTunnelFrontingProviderIDs
  1611. }
  1612. if config.HoldOffTunnelProbability != nil {
  1613. applyParameters[parameters.HoldOffTunnelProbability] = *config.HoldOffTunnelProbability
  1614. }
  1615. if config.HoldOffDirectTunnelMinDurationMilliseconds != nil {
  1616. applyParameters[parameters.HoldOffDirectTunnelMinDuration] = fmt.Sprintf("%dms", *config.HoldOffDirectTunnelMinDurationMilliseconds)
  1617. }
  1618. if config.HoldOffDirectTunnelMaxDurationMilliseconds != nil {
  1619. applyParameters[parameters.HoldOffDirectTunnelMaxDuration] = fmt.Sprintf("%dms", *config.HoldOffDirectTunnelMaxDurationMilliseconds)
  1620. }
  1621. if len(config.HoldOffDirectServerEntryRegions) > 0 {
  1622. applyParameters[parameters.HoldOffDirectServerEntryRegions] = config.HoldOffDirectServerEntryRegions
  1623. }
  1624. if len(config.HoldOffDirectServerEntryProviderRegions) > 0 {
  1625. applyParameters[parameters.HoldOffDirectServerEntryProviderRegions] = parameters.KeyStrings(config.HoldOffDirectServerEntryProviderRegions)
  1626. }
  1627. if config.HoldOffDirectTunnelProbability != nil {
  1628. applyParameters[parameters.HoldOffDirectTunnelProbability] = *config.HoldOffDirectTunnelProbability
  1629. }
  1630. if len(config.RestrictDirectProviderIDs) > 0 {
  1631. applyParameters[parameters.RestrictDirectProviderIDs] = config.RestrictDirectProviderIDs
  1632. }
  1633. if len(config.RestrictDirectProviderRegions) > 0 {
  1634. applyParameters[parameters.RestrictDirectProviderRegions] = parameters.KeyStrings(config.RestrictDirectProviderRegions)
  1635. }
  1636. if config.RestrictDirectProviderIDsClientProbability != nil {
  1637. applyParameters[parameters.RestrictDirectProviderIDsClientProbability] = *config.RestrictDirectProviderIDsClientProbability
  1638. }
  1639. if len(config.RestrictFrontingProviderIDs) > 0 {
  1640. applyParameters[parameters.RestrictFrontingProviderIDs] = config.RestrictFrontingProviderIDs
  1641. }
  1642. if config.RestrictFrontingProviderIDsClientProbability != nil {
  1643. applyParameters[parameters.RestrictFrontingProviderIDsClientProbability] = *config.RestrictFrontingProviderIDsClientProbability
  1644. }
  1645. if config.UpstreamProxyAllowAllServerEntrySources != nil {
  1646. applyParameters[parameters.UpstreamProxyAllowAllServerEntrySources] = *config.UpstreamProxyAllowAllServerEntrySources
  1647. }
  1648. if len(config.LimitTunnelDialPortNumbers) > 0 {
  1649. applyParameters[parameters.LimitTunnelDialPortNumbers] = config.LimitTunnelDialPortNumbers
  1650. }
  1651. if config.QUICDisablePathMTUDiscoveryProbability != nil {
  1652. applyParameters[parameters.QUICDisableClientPathMTUDiscoveryProbability] = *config.QUICDisablePathMTUDiscoveryProbability
  1653. }
  1654. if config.DNSResolverAttemptsPerServer != nil {
  1655. applyParameters[parameters.DNSResolverAttemptsPerServer] = *config.DNSResolverAttemptsPerServer
  1656. }
  1657. if config.DNSResolverAttemptsPerPreferredServer != nil {
  1658. applyParameters[parameters.DNSResolverAttemptsPerPreferredServer] = *config.DNSResolverAttemptsPerPreferredServer
  1659. }
  1660. if config.DNSResolverRequestTimeoutMilliseconds != nil {
  1661. applyParameters[parameters.DNSResolverRequestTimeout] = fmt.Sprintf("%dms", *config.DNSResolverRequestTimeoutMilliseconds)
  1662. }
  1663. if config.DNSResolverAwaitTimeoutMilliseconds != nil {
  1664. applyParameters[parameters.DNSResolverAwaitTimeout] = fmt.Sprintf("%dms", *config.DNSResolverAwaitTimeoutMilliseconds)
  1665. }
  1666. if config.DNSResolverPreresolvedIPAddressProbability != nil {
  1667. applyParameters[parameters.DNSResolverPreresolvedIPAddressProbability] = *config.DNSResolverPreresolvedIPAddressProbability
  1668. }
  1669. if config.DNSResolverPreresolvedIPAddressCIDRs != nil {
  1670. applyParameters[parameters.DNSResolverPreresolvedIPAddressCIDRs] = config.DNSResolverPreresolvedIPAddressCIDRs
  1671. }
  1672. if config.DNSResolverAlternateServers != nil {
  1673. applyParameters[parameters.DNSResolverAlternateServers] = config.DNSResolverAlternateServers
  1674. }
  1675. if config.DNSResolverPreferredAlternateServers != nil {
  1676. applyParameters[parameters.DNSResolverPreferredAlternateServers] = config.DNSResolverPreferredAlternateServers
  1677. }
  1678. if config.DNSResolverPreferAlternateServerProbability != nil {
  1679. applyParameters[parameters.DNSResolverPreferAlternateServerProbability] = *config.DNSResolverPreferAlternateServerProbability
  1680. }
  1681. if config.DNSResolverProtocolTransformSpecs != nil {
  1682. applyParameters[parameters.DNSResolverProtocolTransformSpecs] = config.DNSResolverProtocolTransformSpecs
  1683. }
  1684. if config.DNSResolverProtocolTransformScopedSpecNames != nil {
  1685. applyParameters[parameters.DNSResolverProtocolTransformScopedSpecNames] = config.DNSResolverProtocolTransformScopedSpecNames
  1686. }
  1687. if config.DNSResolverProtocolTransformProbability != nil {
  1688. applyParameters[parameters.DNSResolverProtocolTransformProbability] = *config.DNSResolverProtocolTransformProbability
  1689. }
  1690. if config.DNSResolverIncludeEDNS0Probability != nil {
  1691. applyParameters[parameters.DNSResolverIncludeEDNS0Probability] = *config.DNSResolverIncludeEDNS0Probability
  1692. }
  1693. if config.DNSResolverCacheExtensionInitialTTLMilliseconds != nil {
  1694. applyParameters[parameters.DNSResolverCacheExtensionInitialTTL] = fmt.Sprintf("%dms", *config.DNSResolverCacheExtensionInitialTTLMilliseconds)
  1695. }
  1696. if config.DNSResolverCacheExtensionVerifiedTTLMilliseconds != nil {
  1697. applyParameters[parameters.DNSResolverCacheExtensionVerifiedTTL] = fmt.Sprintf("%dms", *config.DNSResolverCacheExtensionVerifiedTTLMilliseconds)
  1698. }
  1699. if config.DirectHTTPProtocolTransformSpecs != nil {
  1700. applyParameters[parameters.DirectHTTPProtocolTransformSpecs] = config.DirectHTTPProtocolTransformSpecs
  1701. }
  1702. if config.DirectHTTPProtocolTransformScopedSpecNames != nil {
  1703. applyParameters[parameters.DirectHTTPProtocolTransformScopedSpecNames] = config.DirectHTTPProtocolTransformScopedSpecNames
  1704. }
  1705. if config.DirectHTTPProtocolTransformProbability != nil {
  1706. applyParameters[parameters.DirectHTTPProtocolTransformProbability] = *config.DirectHTTPProtocolTransformProbability
  1707. }
  1708. if config.FrontedHTTPProtocolTransformSpecs != nil {
  1709. applyParameters[parameters.FrontedHTTPProtocolTransformSpecs] = config.FrontedHTTPProtocolTransformSpecs
  1710. }
  1711. if config.FrontedHTTPProtocolTransformScopedSpecNames != nil {
  1712. applyParameters[parameters.FrontedHTTPProtocolTransformScopedSpecNames] = config.FrontedHTTPProtocolTransformScopedSpecNames
  1713. }
  1714. if config.FrontedHTTPProtocolTransformProbability != nil {
  1715. applyParameters[parameters.FrontedHTTPProtocolTransformProbability] = *config.FrontedHTTPProtocolTransformProbability
  1716. }
  1717. if config.OSSHObfuscatorSeedTransformSpecs != nil {
  1718. applyParameters[parameters.OSSHObfuscatorSeedTransformSpecs] = config.OSSHObfuscatorSeedTransformSpecs
  1719. }
  1720. if config.OSSHObfuscatorSeedTransformScopedSpecNames != nil {
  1721. applyParameters[parameters.OSSHObfuscatorSeedTransformScopedSpecNames] = config.OSSHObfuscatorSeedTransformScopedSpecNames
  1722. }
  1723. if config.OSSHObfuscatorSeedTransformProbability != nil {
  1724. applyParameters[parameters.OSSHObfuscatorSeedTransformProbability] = *config.OSSHObfuscatorSeedTransformProbability
  1725. }
  1726. if config.ObfuscatedQUICNonceTransformSpecs != nil {
  1727. applyParameters[parameters.ObfuscatedQUICNonceTransformSpecs] = config.ObfuscatedQUICNonceTransformSpecs
  1728. }
  1729. if config.ObfuscatedQUICNonceTransformScopedSpecNames != nil {
  1730. applyParameters[parameters.ObfuscatedQUICNonceTransformScopedSpecNames] = config.ObfuscatedQUICNonceTransformScopedSpecNames
  1731. }
  1732. if config.ObfuscatedQUICNonceTransformProbability != nil {
  1733. applyParameters[parameters.ObfuscatedQUICNonceTransformProbability] = *config.ObfuscatedQUICNonceTransformProbability
  1734. }
  1735. if config.OSSHPrefixSpecs != nil {
  1736. applyParameters[parameters.OSSHPrefixSpecs] = config.OSSHPrefixSpecs
  1737. }
  1738. if config.OSSHPrefixScopedSpecNames != nil {
  1739. applyParameters[parameters.OSSHPrefixScopedSpecNames] = config.OSSHPrefixScopedSpecNames
  1740. }
  1741. if config.OSSHPrefixProbability != nil {
  1742. applyParameters[parameters.OSSHPrefixProbability] = *config.OSSHPrefixProbability
  1743. }
  1744. if config.OSSHPrefixSplitMinDelayMilliseconds != nil {
  1745. applyParameters[parameters.OSSHPrefixSplitMinDelay] = fmt.Sprintf("%dms", *config.OSSHPrefixSplitMinDelayMilliseconds)
  1746. }
  1747. if config.OSSHPrefixSplitMaxDelayMilliseconds != nil {
  1748. applyParameters[parameters.OSSHPrefixSplitMaxDelay] = fmt.Sprintf("%dms", *config.OSSHPrefixSplitMaxDelayMilliseconds)
  1749. }
  1750. if config.OSSHPrefixEnableFragmentor != nil {
  1751. applyParameters[parameters.OSSHPrefixEnableFragmentor] = *config.OSSHPrefixEnableFragmentor
  1752. }
  1753. if config.TLSTunnelTrafficShapingProbability != nil {
  1754. applyParameters[parameters.TLSTunnelTrafficShapingProbability] = *config.TLSTunnelTrafficShapingProbability
  1755. }
  1756. if config.TLSTunnelMinTLSPadding != nil {
  1757. applyParameters[parameters.TLSTunnelMinTLSPadding] = *config.TLSTunnelMinTLSPadding
  1758. }
  1759. if config.TLSTunnelMaxTLSPadding != nil {
  1760. applyParameters[parameters.TLSTunnelMaxTLSPadding] = *config.TLSTunnelMaxTLSPadding
  1761. }
  1762. if config.TLSFragmentClientHelloProbability != nil {
  1763. applyParameters[parameters.TLSFragmentClientHelloProbability] = *config.TLSFragmentClientHelloProbability
  1764. }
  1765. if len(config.TLSFragmentClientHelloLimitProtocols) > 0 {
  1766. applyParameters[parameters.TLSFragmentClientHelloLimitProtocols] = protocol.TunnelProtocols(config.TLSFragmentClientHelloLimitProtocols)
  1767. }
  1768. if config.SteeringIPCacheTTLSeconds != nil {
  1769. applyParameters[parameters.SteeringIPCacheTTL] = fmt.Sprintf("%ds", *config.SteeringIPCacheTTLSeconds)
  1770. }
  1771. if config.SteeringIPCacheMaxEntries != nil {
  1772. applyParameters[parameters.SteeringIPCacheMaxEntries] = *config.SteeringIPCacheMaxEntries
  1773. }
  1774. if config.SteeringIPProbability != nil {
  1775. applyParameters[parameters.SteeringIPProbability] = *config.SteeringIPProbability
  1776. }
  1777. // When adding new config dial parameters that may override tactics, also
  1778. // update setDialParametersHash.
  1779. return applyParameters
  1780. }
  1781. func (config *Config) setDialParametersHash() {
  1782. // Calculate and store a hash of the config values that may impact
  1783. // dial parameters. This hash is used as part of the dial parameters
  1784. // replay mechanism to detect when persisted dial parameters should
  1785. // be discarded due to conflicting config changes.
  1786. //
  1787. // With a couple of minor exceptions, configuring dial parameters via the
  1788. // config is intended for testing only, and so these parameters are expected
  1789. // to be present in test runs only. It remains an important case to discard
  1790. // replay dial parameters when test config parameters are varied.
  1791. //
  1792. // Hashing the parameter names detects some ambiguous hash cases, such as two
  1793. // consecutive int64 parameters, one omitted and one not, that are flipped.
  1794. // The serialization is not completely unambiguous, and the format is
  1795. // currently limited by legacy cases (not invalidating replay dial parameters
  1796. // for production clients is more important than invalidating for test runs).
  1797. // We cannot hash the entire config JSON as it contains non-dial parameter
  1798. // fields which may frequently change across runs.
  1799. //
  1800. // MD5 hash is used solely as a data checksum and not for any security
  1801. // purpose.
  1802. hash := md5.New()
  1803. if len(config.LimitTunnelProtocols) > 0 {
  1804. hash.Write([]byte("LimitTunnelProtocols"))
  1805. for _, protocol := range config.LimitTunnelProtocols {
  1806. hash.Write([]byte(protocol))
  1807. }
  1808. }
  1809. if len(config.InitialLimitTunnelProtocols) > 0 && config.InitialLimitTunnelProtocolsCandidateCount > 0 {
  1810. hash.Write([]byte("InitialLimitTunnelProtocols"))
  1811. for _, protocol := range config.InitialLimitTunnelProtocols {
  1812. hash.Write([]byte(protocol))
  1813. }
  1814. binary.Write(hash, binary.LittleEndian, int64(config.InitialLimitTunnelProtocolsCandidateCount))
  1815. }
  1816. if len(config.LimitTLSProfiles) > 0 {
  1817. hash.Write([]byte("LimitTLSProfiles"))
  1818. for _, profile := range config.LimitTLSProfiles {
  1819. hash.Write([]byte(profile))
  1820. }
  1821. }
  1822. if len(config.LimitQUICVersions) > 0 {
  1823. hash.Write([]byte("LimitQUICVersions"))
  1824. for _, version := range config.LimitQUICVersions {
  1825. hash.Write([]byte(version))
  1826. }
  1827. }
  1828. // Whether a custom User-Agent is specified is a binary flag: when not set,
  1829. // the replay dial parameters value applies. When set, external
  1830. // considerations apply.
  1831. if _, ok := config.CustomHeaders["User-Agent"]; ok {
  1832. hash.Write([]byte("CustomHeaders User-Agent"))
  1833. hash.Write([]byte{1})
  1834. }
  1835. if config.UpstreamProxyURL != "" {
  1836. hash.Write([]byte("UpstreamProxyURL"))
  1837. hash.Write([]byte(config.UpstreamProxyURL))
  1838. }
  1839. if config.TransformHostNameProbability != nil {
  1840. hash.Write([]byte("TransformHostNameProbability"))
  1841. binary.Write(hash, binary.LittleEndian, *config.TransformHostNameProbability)
  1842. }
  1843. if config.FragmentorProbability != nil {
  1844. hash.Write([]byte("FragmentorProbability"))
  1845. binary.Write(hash, binary.LittleEndian, *config.FragmentorProbability)
  1846. }
  1847. if len(config.FragmentorLimitProtocols) > 0 {
  1848. hash.Write([]byte("FragmentorLimitProtocols"))
  1849. for _, protocol := range config.FragmentorLimitProtocols {
  1850. hash.Write([]byte(protocol))
  1851. }
  1852. }
  1853. if config.FragmentorMinTotalBytes != nil {
  1854. hash.Write([]byte("FragmentorMinTotalBytes"))
  1855. binary.Write(hash, binary.LittleEndian, int64(*config.FragmentorMinTotalBytes))
  1856. }
  1857. if config.FragmentorMaxTotalBytes != nil {
  1858. hash.Write([]byte("FragmentorMaxTotalBytes"))
  1859. binary.Write(hash, binary.LittleEndian, int64(*config.FragmentorMaxTotalBytes))
  1860. }
  1861. if config.FragmentorMinWriteBytes != nil {
  1862. hash.Write([]byte("FragmentorMinWriteBytes"))
  1863. binary.Write(hash, binary.LittleEndian, int64(*config.FragmentorMinWriteBytes))
  1864. }
  1865. if config.FragmentorMaxWriteBytes != nil {
  1866. hash.Write([]byte("FragmentorMaxWriteBytes"))
  1867. binary.Write(hash, binary.LittleEndian, int64(*config.FragmentorMaxWriteBytes))
  1868. }
  1869. if config.FragmentorMinDelayMicroseconds != nil {
  1870. hash.Write([]byte("FragmentorMinDelayMicroseconds"))
  1871. binary.Write(hash, binary.LittleEndian, int64(*config.FragmentorMinDelayMicroseconds))
  1872. }
  1873. if config.FragmentorMaxDelayMicroseconds != nil {
  1874. hash.Write([]byte("FragmentorMaxDelayMicroseconds"))
  1875. binary.Write(hash, binary.LittleEndian, int64(*config.FragmentorMaxDelayMicroseconds))
  1876. }
  1877. if config.MeekTrafficShapingProbability != nil {
  1878. hash.Write([]byte("MeekTrafficShapingProbability"))
  1879. binary.Write(hash, binary.LittleEndian, *config.MeekTrafficShapingProbability)
  1880. }
  1881. if len(config.MeekTrafficShapingLimitProtocols) > 0 {
  1882. hash.Write([]byte("MeekTrafficShapingLimitProtocols"))
  1883. for _, protocol := range config.MeekTrafficShapingLimitProtocols {
  1884. hash.Write([]byte(protocol))
  1885. }
  1886. }
  1887. if config.MeekMinLimitRequestPayloadLength != nil {
  1888. hash.Write([]byte("MeekMinLimitRequestPayloadLength"))
  1889. binary.Write(hash, binary.LittleEndian, int64(*config.MeekMinLimitRequestPayloadLength))
  1890. }
  1891. if config.MeekMaxLimitRequestPayloadLength != nil {
  1892. hash.Write([]byte("MeekMaxLimitRequestPayloadLength"))
  1893. binary.Write(hash, binary.LittleEndian, int64(*config.MeekMaxLimitRequestPayloadLength))
  1894. }
  1895. if config.MeekRedialTLSProbability != nil {
  1896. hash.Write([]byte("MeekRedialTLSProbability"))
  1897. binary.Write(hash, binary.LittleEndian, *config.MeekRedialTLSProbability)
  1898. }
  1899. if config.ObfuscatedSSHMinPadding != nil {
  1900. hash.Write([]byte("ObfuscatedSSHMinPadding"))
  1901. binary.Write(hash, binary.LittleEndian, int64(*config.ObfuscatedSSHMinPadding))
  1902. }
  1903. if config.ObfuscatedSSHMaxPadding != nil {
  1904. hash.Write([]byte("ObfuscatedSSHMaxPadding"))
  1905. binary.Write(hash, binary.LittleEndian, int64(*config.ObfuscatedSSHMaxPadding))
  1906. }
  1907. if config.LivenessTestMinUpstreamBytes != nil {
  1908. hash.Write([]byte("LivenessTestMinUpstreamBytes"))
  1909. binary.Write(hash, binary.LittleEndian, int64(*config.LivenessTestMinUpstreamBytes))
  1910. }
  1911. if config.LivenessTestMaxUpstreamBytes != nil {
  1912. hash.Write([]byte("LivenessTestMaxUpstreamBytes"))
  1913. binary.Write(hash, binary.LittleEndian, int64(*config.LivenessTestMaxUpstreamBytes))
  1914. }
  1915. if config.LivenessTestMinDownstreamBytes != nil {
  1916. hash.Write([]byte("LivenessTestMinDownstreamBytes"))
  1917. binary.Write(hash, binary.LittleEndian, int64(*config.LivenessTestMinDownstreamBytes))
  1918. }
  1919. if config.LivenessTestMaxDownstreamBytes != nil {
  1920. hash.Write([]byte("LivenessTestMaxDownstreamBytes"))
  1921. binary.Write(hash, binary.LittleEndian, int64(*config.LivenessTestMaxDownstreamBytes))
  1922. }
  1923. // Legacy case: these parameters are included in the hash unconditionally,
  1924. // and so will impact almost all production clients. These parameter names
  1925. // are not hashed since that would invalidate all replay dial parameters for
  1926. // existing clients whose hashes predate the inclusion of parameter names.
  1927. binary.Write(hash, binary.LittleEndian, config.NetworkLatencyMultiplierMin)
  1928. binary.Write(hash, binary.LittleEndian, config.NetworkLatencyMultiplierMax)
  1929. binary.Write(hash, binary.LittleEndian, config.NetworkLatencyMultiplierLambda)
  1930. if config.UseOnlyCustomTLSProfiles != nil {
  1931. hash.Write([]byte("UseOnlyCustomTLSProfiles"))
  1932. binary.Write(hash, binary.LittleEndian, *config.UseOnlyCustomTLSProfiles)
  1933. }
  1934. if len(config.CustomTLSProfiles) > 0 {
  1935. hash.Write([]byte("CustomTLSProfiles"))
  1936. for _, customTLSProfile := range config.CustomTLSProfiles {
  1937. encodedCustomTLSProofile, _ := json.Marshal(customTLSProfile)
  1938. hash.Write(encodedCustomTLSProofile)
  1939. }
  1940. }
  1941. if config.SelectRandomizedTLSProfileProbability != nil {
  1942. hash.Write([]byte("SelectRandomizedTLSProfileProbability"))
  1943. binary.Write(hash, binary.LittleEndian, *config.SelectRandomizedTLSProfileProbability)
  1944. }
  1945. if config.NoDefaultTLSSessionIDProbability != nil {
  1946. hash.Write([]byte("NoDefaultTLSSessionIDProbability"))
  1947. binary.Write(hash, binary.LittleEndian, *config.NoDefaultTLSSessionIDProbability)
  1948. }
  1949. if len(config.DisableFrontingProviderTLSProfiles) > 0 {
  1950. hash.Write([]byte("DisableFrontingProviderTLSProfiles"))
  1951. encodedDisableFrontingProviderTLSProfiles, _ :=
  1952. json.Marshal(config.DisableFrontingProviderTLSProfiles)
  1953. hash.Write(encodedDisableFrontingProviderTLSProfiles)
  1954. }
  1955. if len(config.CustomHostNameRegexes) > 0 {
  1956. hash.Write([]byte("CustomHostNameRegexes"))
  1957. for _, customHostNameRegex := range config.CustomHostNameRegexes {
  1958. hash.Write([]byte(customHostNameRegex))
  1959. }
  1960. }
  1961. if config.CustomHostNameProbability != nil {
  1962. hash.Write([]byte("CustomHostNameProbability"))
  1963. binary.Write(hash, binary.LittleEndian, *config.CustomHostNameProbability)
  1964. }
  1965. if len(config.CustomHostNameLimitProtocols) > 0 {
  1966. hash.Write([]byte("CustomHostNameLimitProtocols"))
  1967. for _, protocol := range config.CustomHostNameLimitProtocols {
  1968. hash.Write([]byte(protocol))
  1969. }
  1970. }
  1971. if config.ConjureCachedRegistrationTTLSeconds != nil {
  1972. hash.Write([]byte("ConjureCachedRegistrationTTLSeconds"))
  1973. binary.Write(hash, binary.LittleEndian, int64(*config.ConjureCachedRegistrationTTLSeconds))
  1974. }
  1975. if config.ConjureAPIRegistrarBidirectionalURL != "" {
  1976. hash.Write([]byte("ConjureAPIRegistrarBidirectionalURL"))
  1977. hash.Write([]byte(config.ConjureAPIRegistrarBidirectionalURL))
  1978. }
  1979. if len(config.ConjureAPIRegistrarFrontingSpecs) > 0 {
  1980. hash.Write([]byte("ConjureAPIRegistrarFrontingSpecs"))
  1981. for _, frontingSpec := range config.ConjureAPIRegistrarFrontingSpecs {
  1982. encodedFrontSpec, _ := json.Marshal(frontingSpec)
  1983. hash.Write(encodedFrontSpec)
  1984. }
  1985. }
  1986. if config.ConjureAPIRegistrarMinDelayMilliseconds != nil {
  1987. hash.Write([]byte("ConjureAPIRegistrarMinDelayMilliseconds"))
  1988. binary.Write(hash, binary.LittleEndian, int64(*config.ConjureAPIRegistrarMinDelayMilliseconds))
  1989. }
  1990. if config.ConjureAPIRegistrarMaxDelayMilliseconds != nil {
  1991. hash.Write([]byte("ConjureAPIRegistrarMaxDelayMilliseconds"))
  1992. binary.Write(hash, binary.LittleEndian, int64(*config.ConjureAPIRegistrarMaxDelayMilliseconds))
  1993. }
  1994. if config.ConjureDecoyRegistrarWidth != nil {
  1995. hash.Write([]byte("ConjureDecoyRegistrarWidth"))
  1996. binary.Write(hash, binary.LittleEndian, int64(*config.ConjureDecoyRegistrarWidth))
  1997. }
  1998. if config.ConjureDecoyRegistrarMinDelayMilliseconds != nil {
  1999. hash.Write([]byte("ConjureDecoyRegistrarMinDelayMilliseconds"))
  2000. binary.Write(hash, binary.LittleEndian, int64(*config.ConjureDecoyRegistrarMinDelayMilliseconds))
  2001. }
  2002. if config.ConjureDecoyRegistrarMaxDelayMilliseconds != nil {
  2003. hash.Write([]byte("ConjureDecoyRegistrarMaxDelayMilliseconds"))
  2004. binary.Write(hash, binary.LittleEndian, int64(*config.ConjureDecoyRegistrarMaxDelayMilliseconds))
  2005. }
  2006. if config.ConjureLimitTransports != nil {
  2007. hash.Write([]byte("ConjureLimitTransports"))
  2008. for _, transport := range config.ConjureLimitTransports {
  2009. hash.Write([]byte(transport))
  2010. }
  2011. }
  2012. if config.ConjureSTUNServerAddresses != nil {
  2013. hash.Write([]byte("ConjureSTUNServerAddresses"))
  2014. for _, address := range config.ConjureSTUNServerAddresses {
  2015. hash.Write([]byte(address))
  2016. }
  2017. }
  2018. if config.HoldOffTunnelMinDurationMilliseconds != nil {
  2019. hash.Write([]byte("HoldOffTunnelMinDurationMilliseconds"))
  2020. binary.Write(hash, binary.LittleEndian, int64(*config.HoldOffTunnelMinDurationMilliseconds))
  2021. }
  2022. if config.HoldOffTunnelMaxDurationMilliseconds != nil {
  2023. hash.Write([]byte("HoldOffTunnelMaxDurationMilliseconds"))
  2024. binary.Write(hash, binary.LittleEndian, int64(*config.HoldOffTunnelMaxDurationMilliseconds))
  2025. }
  2026. if len(config.HoldOffTunnelProtocols) > 0 {
  2027. hash.Write([]byte("HoldOffTunnelProtocols"))
  2028. for _, protocol := range config.HoldOffTunnelProtocols {
  2029. hash.Write([]byte(protocol))
  2030. }
  2031. }
  2032. if len(config.HoldOffTunnelFrontingProviderIDs) > 0 {
  2033. hash.Write([]byte("HoldOffTunnelFrontingProviderIDs"))
  2034. for _, providerID := range config.HoldOffTunnelFrontingProviderIDs {
  2035. hash.Write([]byte(providerID))
  2036. }
  2037. }
  2038. if config.HoldOffDirectTunnelProbability != nil {
  2039. hash.Write([]byte("HoldOffDirectTunnelProbability"))
  2040. binary.Write(hash, binary.LittleEndian, *config.HoldOffDirectTunnelProbability)
  2041. }
  2042. if config.HoldOffDirectTunnelMinDurationMilliseconds != nil {
  2043. hash.Write([]byte("HoldOffDirectTunnelMinDurationMilliseconds"))
  2044. binary.Write(hash, binary.LittleEndian, int64(*config.HoldOffDirectTunnelMinDurationMilliseconds))
  2045. }
  2046. if config.HoldOffDirectTunnelMaxDurationMilliseconds != nil {
  2047. hash.Write([]byte("HoldOffDirectTunnelMaxDurationMilliseconds"))
  2048. binary.Write(hash, binary.LittleEndian, int64(*config.HoldOffDirectTunnelMaxDurationMilliseconds))
  2049. }
  2050. if len(config.HoldOffDirectServerEntryRegions) > 0 {
  2051. hash.Write([]byte("HoldOffDirectServerEntryRegions"))
  2052. for _, region := range config.HoldOffDirectServerEntryRegions {
  2053. hash.Write([]byte(region))
  2054. }
  2055. }
  2056. if len(config.HoldOffDirectServerEntryProviderRegions) > 0 {
  2057. hash.Write([]byte("HoldOffDirectServerEntryProviderRegions"))
  2058. for providerID, regions := range config.HoldOffDirectServerEntryProviderRegions {
  2059. hash.Write([]byte(providerID))
  2060. for _, region := range regions {
  2061. hash.Write([]byte(region))
  2062. }
  2063. }
  2064. }
  2065. if config.HoldOffTunnelProbability != nil {
  2066. hash.Write([]byte("HoldOffTunnelProbability"))
  2067. binary.Write(hash, binary.LittleEndian, *config.HoldOffTunnelProbability)
  2068. }
  2069. if len(config.RestrictDirectProviderIDs) > 0 {
  2070. hash.Write([]byte("RestrictDirectProviderIDs"))
  2071. for _, providerID := range config.RestrictDirectProviderIDs {
  2072. hash.Write([]byte(providerID))
  2073. }
  2074. }
  2075. if len(config.RestrictDirectProviderRegions) > 0 {
  2076. hash.Write([]byte("RestrictDirectProviderRegions"))
  2077. for providerID, regions := range config.RestrictDirectProviderRegions {
  2078. hash.Write([]byte(providerID))
  2079. for _, region := range regions {
  2080. hash.Write([]byte(region))
  2081. }
  2082. }
  2083. }
  2084. if config.RestrictDirectProviderIDsClientProbability != nil {
  2085. hash.Write([]byte("RestrictDirectProviderIDsClientProbability"))
  2086. binary.Write(hash, binary.LittleEndian, *config.RestrictDirectProviderIDsClientProbability)
  2087. }
  2088. if len(config.RestrictFrontingProviderIDs) > 0 {
  2089. hash.Write([]byte("RestrictFrontingProviderIDs"))
  2090. for _, providerID := range config.RestrictFrontingProviderIDs {
  2091. hash.Write([]byte(providerID))
  2092. }
  2093. }
  2094. if config.RestrictFrontingProviderIDsClientProbability != nil {
  2095. hash.Write([]byte("RestrictFrontingProviderIDsClientProbability"))
  2096. binary.Write(hash, binary.LittleEndian, *config.RestrictFrontingProviderIDsClientProbability)
  2097. }
  2098. if config.UpstreamProxyAllowAllServerEntrySources != nil {
  2099. hash.Write([]byte("UpstreamProxyAllowAllServerEntrySources"))
  2100. binary.Write(hash, binary.LittleEndian, *config.UpstreamProxyAllowAllServerEntrySources)
  2101. }
  2102. if len(config.LimitTunnelDialPortNumbers) > 0 {
  2103. hash.Write([]byte("LimitTunnelDialPortNumbers"))
  2104. encodedLimitTunnelDialPortNumbers, _ :=
  2105. json.Marshal(config.LimitTunnelDialPortNumbers)
  2106. hash.Write(encodedLimitTunnelDialPortNumbers)
  2107. }
  2108. if config.QUICDisablePathMTUDiscoveryProbability != nil {
  2109. hash.Write([]byte("QUICDisablePathMTUDiscoveryProbability"))
  2110. binary.Write(hash, binary.LittleEndian, *config.QUICDisablePathMTUDiscoveryProbability)
  2111. }
  2112. if config.DNSResolverAttemptsPerServer != nil {
  2113. hash.Write([]byte("DNSResolverAttemptsPerServer"))
  2114. binary.Write(hash, binary.LittleEndian, int64(*config.DNSResolverAttemptsPerServer))
  2115. }
  2116. if config.DNSResolverRequestTimeoutMilliseconds != nil {
  2117. hash.Write([]byte("DNSResolverRequestTimeoutMilliseconds"))
  2118. binary.Write(hash, binary.LittleEndian, int64(*config.DNSResolverRequestTimeoutMilliseconds))
  2119. }
  2120. if config.DNSResolverAwaitTimeoutMilliseconds != nil {
  2121. hash.Write([]byte("DNSResolverAwaitTimeoutMilliseconds"))
  2122. binary.Write(hash, binary.LittleEndian, int64(*config.DNSResolverAwaitTimeoutMilliseconds))
  2123. }
  2124. if config.DNSResolverPreresolvedIPAddressCIDRs != nil {
  2125. hash.Write([]byte("DNSResolverPreresolvedIPAddressCIDRs"))
  2126. encodedDNSResolverPreresolvedIPAddressCIDRs, _ :=
  2127. json.Marshal(config.DNSResolverPreresolvedIPAddressCIDRs)
  2128. hash.Write(encodedDNSResolverPreresolvedIPAddressCIDRs)
  2129. }
  2130. if config.DNSResolverPreresolvedIPAddressProbability != nil {
  2131. hash.Write([]byte("DNSResolverPreresolvedIPAddressProbability"))
  2132. binary.Write(hash, binary.LittleEndian, *config.DNSResolverPreresolvedIPAddressProbability)
  2133. }
  2134. if config.DNSResolverAlternateServers != nil {
  2135. hash.Write([]byte("DNSResolverAlternateServers"))
  2136. for _, server := range config.DNSResolverAlternateServers {
  2137. hash.Write([]byte(server))
  2138. }
  2139. }
  2140. if config.DNSResolverPreferAlternateServerProbability != nil {
  2141. hash.Write([]byte("DNSResolverPreferAlternateServerProbability"))
  2142. binary.Write(hash, binary.LittleEndian, *config.DNSResolverPreferAlternateServerProbability)
  2143. }
  2144. if config.DNSResolverProtocolTransformSpecs != nil {
  2145. hash.Write([]byte("DNSResolverProtocolTransformSpecs"))
  2146. encodedDNSResolverProtocolTransformSpecs, _ :=
  2147. json.Marshal(config.DNSResolverProtocolTransformSpecs)
  2148. hash.Write(encodedDNSResolverProtocolTransformSpecs)
  2149. }
  2150. if config.DNSResolverProtocolTransformScopedSpecNames != nil {
  2151. hash.Write([]byte("DNSResolverProtocolTransformScopedSpecNames"))
  2152. encodedDNSResolverProtocolTransformScopedSpecNames, _ :=
  2153. json.Marshal(config.DNSResolverProtocolTransformScopedSpecNames)
  2154. hash.Write(encodedDNSResolverProtocolTransformScopedSpecNames)
  2155. }
  2156. if config.DNSResolverProtocolTransformProbability != nil {
  2157. hash.Write([]byte("DNSResolverProtocolTransformProbability"))
  2158. binary.Write(hash, binary.LittleEndian, *config.DNSResolverProtocolTransformProbability)
  2159. }
  2160. if config.DNSResolverIncludeEDNS0Probability != nil {
  2161. hash.Write([]byte("DNSResolverIncludeEDNS0Probability"))
  2162. binary.Write(hash, binary.LittleEndian, *config.DNSResolverIncludeEDNS0Probability)
  2163. }
  2164. if config.DNSResolverCacheExtensionInitialTTLMilliseconds != nil {
  2165. hash.Write([]byte("DNSResolverCacheExtensionInitialTTLMilliseconds"))
  2166. binary.Write(hash, binary.LittleEndian, int64(*config.DNSResolverCacheExtensionInitialTTLMilliseconds))
  2167. }
  2168. if config.DNSResolverCacheExtensionVerifiedTTLMilliseconds != nil {
  2169. hash.Write([]byte("DNSResolverCacheExtensionVerifiedTTLMilliseconds"))
  2170. binary.Write(hash, binary.LittleEndian, int64(*config.DNSResolverCacheExtensionVerifiedTTLMilliseconds))
  2171. }
  2172. if config.DirectHTTPProtocolTransformSpecs != nil {
  2173. hash.Write([]byte("DirectHTTPProtocolTransformSpecs"))
  2174. encodedDirectHTTPProtocolTransformSpecs, _ :=
  2175. json.Marshal(config.DirectHTTPProtocolTransformSpecs)
  2176. hash.Write(encodedDirectHTTPProtocolTransformSpecs)
  2177. }
  2178. if config.DirectHTTPProtocolTransformScopedSpecNames != nil {
  2179. hash.Write([]byte("DirectHTTPProtocolTransformScopedSpecNames"))
  2180. encodedDirectHTTPProtocolTransformScopedSpecNames, _ :=
  2181. json.Marshal(config.DirectHTTPProtocolTransformScopedSpecNames)
  2182. hash.Write(encodedDirectHTTPProtocolTransformScopedSpecNames)
  2183. }
  2184. if config.DirectHTTPProtocolTransformProbability != nil {
  2185. hash.Write([]byte("DirectHTTPProtocolTransformProbability"))
  2186. binary.Write(hash, binary.LittleEndian, *config.DirectHTTPProtocolTransformProbability)
  2187. }
  2188. if config.FrontedHTTPProtocolTransformSpecs != nil {
  2189. hash.Write([]byte("FrontedHTTPProtocolTransformSpecs"))
  2190. encodedFrontedHTTPProtocolTransformSpecs, _ :=
  2191. json.Marshal(config.FrontedHTTPProtocolTransformSpecs)
  2192. hash.Write(encodedFrontedHTTPProtocolTransformSpecs)
  2193. }
  2194. if config.FrontedHTTPProtocolTransformScopedSpecNames != nil {
  2195. hash.Write([]byte("FrontedHTTPProtocolTransformScopedSpecNames"))
  2196. encodedFrontedHTTPProtocolTransformScopedSpecNames, _ :=
  2197. json.Marshal(config.FrontedHTTPProtocolTransformScopedSpecNames)
  2198. hash.Write(encodedFrontedHTTPProtocolTransformScopedSpecNames)
  2199. }
  2200. if config.FrontedHTTPProtocolTransformProbability != nil {
  2201. hash.Write([]byte("FrontedHTTPProtocolTransformProbability"))
  2202. binary.Write(hash, binary.LittleEndian, *config.FrontedHTTPProtocolTransformProbability)
  2203. }
  2204. if config.OSSHObfuscatorSeedTransformSpecs != nil {
  2205. hash.Write([]byte("OSSHObfuscatorSeedTransformSpecs"))
  2206. encodedOSSHObfuscatorSeedTransformSpecs, _ :=
  2207. json.Marshal(config.OSSHObfuscatorSeedTransformSpecs)
  2208. hash.Write(encodedOSSHObfuscatorSeedTransformSpecs)
  2209. }
  2210. if config.OSSHObfuscatorSeedTransformScopedSpecNames != nil {
  2211. hash.Write([]byte("OSSHObfuscatorSeedTransformScopedSpecNames"))
  2212. encodedOSSHObfuscatorSeedTransformScopedSpecNames, _ :=
  2213. json.Marshal(config.OSSHObfuscatorSeedTransformScopedSpecNames)
  2214. hash.Write(encodedOSSHObfuscatorSeedTransformScopedSpecNames)
  2215. }
  2216. if config.OSSHObfuscatorSeedTransformProbability != nil {
  2217. hash.Write([]byte("OSSHObfuscatorSeedTransformProbability"))
  2218. binary.Write(hash, binary.LittleEndian, *config.OSSHObfuscatorSeedTransformProbability)
  2219. }
  2220. if config.ObfuscatedQUICNonceTransformSpecs != nil {
  2221. hash.Write([]byte("ObfuscatedQUICNonceTransformSpecs"))
  2222. encodedObfuscatedQUICNonceTransformSpecs, _ :=
  2223. json.Marshal(config.ObfuscatedQUICNonceTransformSpecs)
  2224. hash.Write(encodedObfuscatedQUICNonceTransformSpecs)
  2225. }
  2226. if config.ObfuscatedQUICNonceTransformScopedSpecNames != nil {
  2227. hash.Write([]byte("ObfuscatedQUICNonceTransformScopedSpecNames"))
  2228. encodedObfuscatedQUICNonceTransformScopedSpecNames, _ :=
  2229. json.Marshal(config.ObfuscatedQUICNonceTransformScopedSpecNames)
  2230. hash.Write(encodedObfuscatedQUICNonceTransformScopedSpecNames)
  2231. }
  2232. if config.ObfuscatedQUICNonceTransformProbability != nil {
  2233. hash.Write([]byte("ObfuscatedQUICNonceTransformProbability"))
  2234. binary.Write(hash, binary.LittleEndian, *config.ObfuscatedQUICNonceTransformProbability)
  2235. }
  2236. if config.OSSHPrefixSpecs != nil {
  2237. hash.Write([]byte("OSSHPrefixSpecs"))
  2238. encodedOSSHPrefixSpecs, _ := json.Marshal(config.OSSHPrefixSpecs)
  2239. hash.Write(encodedOSSHPrefixSpecs)
  2240. }
  2241. if config.OSSHPrefixScopedSpecNames != nil {
  2242. hash.Write([]byte("OSSHPrefixScopedSpecNames"))
  2243. encodedOSSHPrefixScopedSpecNames, _ := json.Marshal(config.OSSHPrefixScopedSpecNames)
  2244. hash.Write(encodedOSSHPrefixScopedSpecNames)
  2245. }
  2246. if config.OSSHPrefixProbability != nil {
  2247. hash.Write([]byte("OSSHPrefixProbability"))
  2248. binary.Write(hash, binary.LittleEndian, *config.OSSHPrefixProbability)
  2249. }
  2250. if config.OSSHPrefixSplitMinDelayMilliseconds != nil {
  2251. hash.Write([]byte("OSSHPrefixSplitMinDelayMilliseconds"))
  2252. binary.Write(hash, binary.LittleEndian, int64(*config.OSSHPrefixSplitMinDelayMilliseconds))
  2253. }
  2254. if config.OSSHPrefixSplitMaxDelayMilliseconds != nil {
  2255. hash.Write([]byte("OSSHPrefixSplitMaxDelayMilliseconds"))
  2256. binary.Write(hash, binary.LittleEndian, int64(*config.OSSHPrefixSplitMaxDelayMilliseconds))
  2257. }
  2258. if config.OSSHPrefixEnableFragmentor != nil {
  2259. hash.Write([]byte("OSSHPrefixEnableFragmentor"))
  2260. binary.Write(hash, binary.LittleEndian, *config.OSSHPrefixEnableFragmentor)
  2261. }
  2262. if config.TLSTunnelTrafficShapingProbability != nil {
  2263. hash.Write([]byte("TLSTunnelTrafficShapingProbability"))
  2264. binary.Write(hash, binary.LittleEndian, *config.TLSTunnelTrafficShapingProbability)
  2265. }
  2266. if config.TLSTunnelMinTLSPadding != nil {
  2267. hash.Write([]byte("TLSTunnelMinTLSPadding"))
  2268. binary.Write(hash, binary.LittleEndian, int64(*config.TLSTunnelMinTLSPadding))
  2269. }
  2270. if config.TLSTunnelMaxTLSPadding != nil {
  2271. hash.Write([]byte("TLSTunnelMaxTLSPadding"))
  2272. binary.Write(hash, binary.LittleEndian, int64(*config.TLSTunnelMaxTLSPadding))
  2273. }
  2274. if config.TLSFragmentClientHelloProbability != nil {
  2275. hash.Write([]byte("TLSFragmentClientHelloProbability"))
  2276. binary.Write(hash, binary.LittleEndian, *config.TLSFragmentClientHelloProbability)
  2277. }
  2278. if len(config.TLSFragmentClientHelloLimitProtocols) > 0 {
  2279. hash.Write([]byte("TLSFragmentClientHelloLimitProtocols"))
  2280. for _, protocol := range config.TLSFragmentClientHelloLimitProtocols {
  2281. hash.Write([]byte(protocol))
  2282. }
  2283. }
  2284. // Steering IPs are ephemeral and not replayed, so steering IP parameters
  2285. // are excluded here.
  2286. config.dialParametersHash = hash.Sum(nil)
  2287. }
  2288. // applyAdditionalParameters decodes and applies any additional parameters
  2289. // stored in config.AdditionalParameter to the Config and returns an array
  2290. // of notices which should be logged at the info level. If there is no error,
  2291. // then config.AdditionalParameter is set to "" to conserve memory and further
  2292. // calls will do nothing. This function should only be called once.
  2293. //
  2294. // If there is an error, the existing Config is left entirely unmodified.
  2295. func (config *Config) applyAdditionalParameters() ([]string, error) {
  2296. if config.AdditionalParameters == "" {
  2297. return nil, nil
  2298. }
  2299. b, err := base64.StdEncoding.DecodeString(config.AdditionalParameters)
  2300. if err != nil {
  2301. return nil, errors.Trace(err)
  2302. }
  2303. if len(b) < 32 {
  2304. return nil, errors.Tracef("invalid length, len(b) == %d", len(b))
  2305. }
  2306. var key [32]byte
  2307. copy(key[:], b[:32])
  2308. decrypted, ok := secretbox.Open(nil, b[32:], &[24]byte{}, &key)
  2309. if !ok {
  2310. return nil, errors.TraceNew("secretbox.Open failed")
  2311. }
  2312. var additionalParameters Config
  2313. err = json.Unmarshal(decrypted, &additionalParameters)
  2314. if err != nil {
  2315. return nil, errors.Trace(err)
  2316. }
  2317. src := reflect.ValueOf(&additionalParameters).Elem()
  2318. dest := reflect.ValueOf(config).Elem()
  2319. var infoNotices []string
  2320. for i := 0; i < src.NumField(); i++ {
  2321. if !src.Field(i).IsZero() {
  2322. dest.Field(i).Set(src.Field(i))
  2323. infoNotice := fmt.Sprintf("%s overridden by AdditionalParameters", dest.Type().Field(i).Name)
  2324. infoNotices = append(infoNotices, infoNotice)
  2325. }
  2326. }
  2327. // Reset field to conserve memory since this is a one-time operation.
  2328. config.AdditionalParameters = ""
  2329. return infoNotices, nil
  2330. }
  2331. func promoteLegacyTransferURL(URL string) parameters.TransferURLs {
  2332. transferURLs := make(parameters.TransferURLs, 1)
  2333. transferURLs[0] = &parameters.TransferURL{
  2334. URL: base64.StdEncoding.EncodeToString([]byte(URL)),
  2335. SkipVerify: false,
  2336. OnlyAfterAttempts: 0,
  2337. }
  2338. return transferURLs
  2339. }
  2340. type loggingDeviceBinder struct {
  2341. d DeviceBinder
  2342. }
  2343. func newLoggingDeviceBinder(d DeviceBinder) *loggingDeviceBinder {
  2344. return &loggingDeviceBinder{d: d}
  2345. }
  2346. func (d *loggingDeviceBinder) BindToDevice(fileDescriptor int) (string, error) {
  2347. deviceInfo, err := d.d.BindToDevice(fileDescriptor)
  2348. if err == nil && deviceInfo != "" {
  2349. NoticeBindToDevice(deviceInfo)
  2350. }
  2351. return deviceInfo, err
  2352. }
  2353. type staticNetworkGetter struct {
  2354. networkID string
  2355. }
  2356. func newStaticNetworkGetter(networkID string) *staticNetworkGetter {
  2357. return &staticNetworkGetter{networkID: networkID}
  2358. }
  2359. func (n *staticNetworkGetter) GetNetworkID() string {
  2360. return n.networkID
  2361. }
  2362. type loggingNetworkIDGetter struct {
  2363. n NetworkIDGetter
  2364. }
  2365. func newLoggingNetworkIDGetter(n NetworkIDGetter) *loggingNetworkIDGetter {
  2366. return &loggingNetworkIDGetter{n: n}
  2367. }
  2368. func (n *loggingNetworkIDGetter) GetNetworkID() string {
  2369. networkID := n.n.GetNetworkID()
  2370. // All PII must appear after the initial "-"
  2371. // See: https://godoc.org/github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon#NetworkIDGetter
  2372. logNetworkID := networkID
  2373. index := strings.Index(logNetworkID, "-")
  2374. if index != -1 {
  2375. logNetworkID = logNetworkID[:index]
  2376. }
  2377. if len(logNetworkID)+1 < len(networkID) {
  2378. // Indicate when additional network info was present after the first "-".
  2379. logNetworkID += "+[redacted]"
  2380. }
  2381. NoticeNetworkID(logNetworkID)
  2382. return networkID
  2383. }
  2384. // migrationsFromLegacyNoticeFilePaths returns the file migrations which must be
  2385. // performed to move notice files from legacy file paths, which were configured
  2386. // with the legacy config fields HomepageNoticesFilename and
  2387. // RotatingNoticesFilename, to the new file paths used by Psiphon which exist
  2388. // under the data root directory.
  2389. func migrationsFromLegacyNoticeFilePaths(config *Config) []FileMigration {
  2390. var noticeMigrations []FileMigration
  2391. if config.MigrateHomepageNoticesFilename != "" {
  2392. noticeMigrations = append(noticeMigrations, FileMigration{
  2393. Name: "hompage",
  2394. OldPath: config.MigrateHomepageNoticesFilename,
  2395. NewPath: config.GetHomePageFilename(),
  2396. })
  2397. }
  2398. if config.MigrateRotatingNoticesFilename != "" {
  2399. migrations := []FileMigration{
  2400. {
  2401. Name: "notices",
  2402. OldPath: config.MigrateRotatingNoticesFilename,
  2403. NewPath: config.GetNoticesFilename(),
  2404. IsDir: false,
  2405. },
  2406. {
  2407. Name: "notices.1",
  2408. OldPath: config.MigrateRotatingNoticesFilename + ".1",
  2409. NewPath: config.GetNoticesFilename() + ".1",
  2410. },
  2411. }
  2412. noticeMigrations = append(noticeMigrations, migrations...)
  2413. }
  2414. return noticeMigrations
  2415. }
  2416. // migrationsFromLegacyFilePaths returns the file migrations which must be
  2417. // performed to move files from legacy file paths, which were configured with
  2418. // legacy config fields, to the new file paths used by Psiphon which exist
  2419. // under the data root directory.
  2420. // Note: an attempt is made to redact any file paths from the returned error.
  2421. func migrationsFromLegacyFilePaths(config *Config) ([]FileMigration, error) {
  2422. migrations := []FileMigration{
  2423. {
  2424. Name: "psiphon.boltdb",
  2425. OldPath: filepath.Join(config.MigrateDataStoreDirectory, "psiphon.boltdb"),
  2426. NewPath: filepath.Join(config.GetDataStoreDirectory(), "psiphon.boltdb"),
  2427. },
  2428. {
  2429. Name: "psiphon.boltdb.lock",
  2430. OldPath: filepath.Join(config.MigrateDataStoreDirectory, "psiphon.boltdb.lock"),
  2431. NewPath: filepath.Join(config.GetDataStoreDirectory(), "psiphon.boltdb.lock"),
  2432. },
  2433. }
  2434. if config.MigrateRemoteServerListDownloadFilename != "" {
  2435. // Migrate remote server list files
  2436. rslMigrations := []FileMigration{
  2437. {
  2438. Name: "remote_server_list",
  2439. OldPath: config.MigrateRemoteServerListDownloadFilename,
  2440. NewPath: config.GetRemoteServerListDownloadFilename(),
  2441. },
  2442. {
  2443. Name: "remote_server_list.part",
  2444. OldPath: config.MigrateRemoteServerListDownloadFilename + ".part",
  2445. NewPath: config.GetRemoteServerListDownloadFilename() + ".part",
  2446. },
  2447. {
  2448. Name: "remote_server_list.part.etag",
  2449. OldPath: config.MigrateRemoteServerListDownloadFilename + ".part.etag",
  2450. NewPath: config.GetRemoteServerListDownloadFilename() + ".part.etag",
  2451. },
  2452. }
  2453. migrations = append(migrations, rslMigrations...)
  2454. }
  2455. if config.MigrateObfuscatedServerListDownloadDirectory != "" {
  2456. // Migrate OSL registry file and downloads
  2457. oslFileRegex, err := regexp.Compile(`^osl-.+$`)
  2458. if err != nil {
  2459. return nil, errors.TraceMsg(err, "failed to compile regex for osl files")
  2460. }
  2461. files, err := ioutil.ReadDir(config.MigrateObfuscatedServerListDownloadDirectory)
  2462. if err != nil {
  2463. NoticeWarning(
  2464. "Migration: failed to read OSL download directory with error %s",
  2465. common.RedactFilePathsError(err, config.MigrateObfuscatedServerListDownloadDirectory))
  2466. } else {
  2467. for _, file := range files {
  2468. if oslFileRegex.MatchString(file.Name()) {
  2469. fileMigration := FileMigration{
  2470. Name: "osl",
  2471. OldPath: filepath.Join(config.MigrateObfuscatedServerListDownloadDirectory, file.Name()),
  2472. NewPath: filepath.Join(config.GetObfuscatedServerListDownloadDirectory(), file.Name()),
  2473. }
  2474. migrations = append(migrations, fileMigration)
  2475. }
  2476. }
  2477. }
  2478. }
  2479. if config.MigrateUpgradeDownloadFilename != "" {
  2480. // Migrate downloaded upgrade files
  2481. oldUpgradeDownloadFilename := filepath.Base(config.MigrateUpgradeDownloadFilename)
  2482. // Create regex for:
  2483. // <old_upgrade_download_filename>
  2484. // <old_upgrade_download_filename>.<client_version_number>
  2485. // <old_upgrade_download_filename>.<client_version_number>.part
  2486. // <old_upgrade_download_filename>.<client_version_number>.part.etag
  2487. upgradeDownloadFileRegex, err := regexp.Compile(`^` + oldUpgradeDownloadFilename + `(\.\d+(\.part(\.etag)?)?)?$`)
  2488. if err != nil {
  2489. return nil, errors.TraceMsg(err, "failed to compile regex for upgrade files")
  2490. }
  2491. upgradeDownloadDir := filepath.Dir(config.MigrateUpgradeDownloadFilename)
  2492. files, err := ioutil.ReadDir(upgradeDownloadDir)
  2493. if err != nil {
  2494. NoticeWarning(
  2495. "Migration: failed to read upgrade download directory with error %s",
  2496. common.RedactFilePathsError(err, upgradeDownloadDir))
  2497. } else {
  2498. for _, file := range files {
  2499. if upgradeDownloadFileRegex.MatchString(file.Name()) {
  2500. oldFileSuffix := strings.TrimPrefix(file.Name(), oldUpgradeDownloadFilename)
  2501. fileMigration := FileMigration{
  2502. Name: "upgrade",
  2503. OldPath: filepath.Join(upgradeDownloadDir, file.Name()),
  2504. NewPath: config.GetUpgradeDownloadFilename() + oldFileSuffix,
  2505. }
  2506. migrations = append(migrations, fileMigration)
  2507. }
  2508. }
  2509. }
  2510. }
  2511. return migrations, nil
  2512. }