config.go 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961
  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. "regexp"
  31. "strconv"
  32. "strings"
  33. "sync"
  34. "unicode"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  39. )
  40. const (
  41. TUNNEL_POOL_SIZE = 1
  42. // Psiphon data directory name, relative to config.DataRootDirectory.
  43. // See config.GetPsiphonDataDirectory().
  44. PsiphonDataDirectoryName = "ca.psiphon.PsiphonTunnel.tunnel-core"
  45. // Filename constants, all relative to config.GetPsiphonDataDirectory().
  46. HomepageFilename = "homepage"
  47. NoticesFilename = "notices"
  48. OldNoticesFilename = "notices.1"
  49. UpgradeDownloadFilename = "upgrade"
  50. )
  51. // Config is the Psiphon configuration specified by the application. This
  52. // configuration controls the behavior of the core tunnel functionality.
  53. //
  54. // To distinguish omitted timeout params from explicit 0 value timeout params,
  55. // corresponding fields are int pointers. nil means no value was supplied and
  56. // to use the default; a non-nil pointer to 0 means no timeout.
  57. type Config struct {
  58. // DataRootDirectory is the directory in which to store persistent files,
  59. // which contain information such as server entries. By default, current
  60. // working directory.
  61. //
  62. // Psiphon will assume full control of files under this directory. They may
  63. // be deleted, moved or overwritten.
  64. DataRootDirectory string
  65. // UseNoticeFiles configures notice files for writing. If set, homepages
  66. // will be written to a file created at config.GetHomePageFilename()
  67. // and notices will be written to a file created at
  68. // config.GetNoticesFilename().
  69. //
  70. // The homepage file may be read after the Tunnels notice with count of 1.
  71. //
  72. // The value of UseNoticeFiles sets the size and frequency at which the
  73. // notices file, config.GetNoticesFilename(), will be rotated. See the
  74. // comment for UseNoticeFiles for more details. One rotated older file,
  75. // config.GetOldNoticesFilename(), is retained.
  76. //
  77. // The notice files may be may be read at any time; and should be opened
  78. // read-only for reading. Diagnostic notices are omitted from the notice
  79. // files.
  80. //
  81. // See comment for setNoticeFiles in notice.go for further details.
  82. UseNoticeFiles *UseNoticeFiles
  83. // PropagationChannelId is a string identifier which indicates how the
  84. // Psiphon client was distributed. This parameter is required. This value
  85. // is supplied by and depends on the Psiphon Network, and is typically
  86. // embedded in the client binary.
  87. PropagationChannelId string
  88. // SponsorId is a string identifier which indicates who is sponsoring this
  89. // Psiphon client. One purpose of this value is to determine the home
  90. // pages for display. This parameter is required. This value is supplied
  91. // by and depends on the Psiphon Network, and is typically embedded in the
  92. // client binary.
  93. SponsorId string
  94. // ClientVersion is the client version number that the client reports to
  95. // the server. The version number refers to the host client application,
  96. // not the core tunnel library. One purpose of this value is to enable
  97. // automatic updates. This value is supplied by and depends on the Psiphon
  98. // Network, and is typically embedded in the client binary.
  99. //
  100. // Note that sending a ClientPlatform string which includes "windows"
  101. // (case insensitive) and a ClientVersion of <= 44 will cause an error in
  102. // processing the response to DoConnectedRequest calls.
  103. ClientVersion string
  104. // ClientPlatform is the client platform ("Windows", "Android", etc.) that
  105. // the client reports to the server.
  106. ClientPlatform string
  107. // TunnelWholeDevice is a flag that is passed through to the handshake
  108. // request for stats purposes. Set to 1 when the host application is
  109. // tunneling the whole device, 0 otherwise.
  110. TunnelWholeDevice int
  111. // EgressRegion is a ISO 3166-1 alpha-2 country code which indicates which
  112. // country to egress from. For the default, "", the best performing server
  113. // in any country is selected.
  114. EgressRegion string
  115. // ListenInterface specifies which interface to listen on. If no
  116. // interface is provided then listen on 127.0.0.1. If 'any' is provided
  117. // then use 0.0.0.0. If there are multiple IP addresses on an interface
  118. // use the first IPv4 address.
  119. ListenInterface string
  120. // DisableLocalSocksProxy disables running the local SOCKS proxy.
  121. DisableLocalSocksProxy bool
  122. // LocalSocksProxyPort specifies a port number for the local SOCKS proxy
  123. // running at 127.0.0.1. For the default value, 0, the system selects a
  124. // free port (a notice reporting the selected port is emitted).
  125. LocalSocksProxyPort int
  126. // LocalHttpProxyPort specifies a port number for the local HTTP proxy
  127. // running at 127.0.0.1. For the default value, 0, the system selects a
  128. // free port (a notice reporting the selected port is emitted).
  129. LocalHttpProxyPort int
  130. // DisableLocalHTTPProxy disables running the local HTTP proxy.
  131. DisableLocalHTTPProxy bool
  132. // NetworkLatencyMultiplier is a multiplier that is to be applied to
  133. // default network event timeouts. Set this to tune performance for
  134. // slow networks.
  135. // When set, must be >= 1.0.
  136. NetworkLatencyMultiplier float64
  137. // LimitTunnelProtocols indicates which protocols to use. Valid values
  138. // include:
  139. // "SSH", "OSSH", "UNFRONTED-MEEK-OSSH", "UNFRONTED-MEEK-HTTPS-OSSH",
  140. // "UNFRONTED-MEEK-SESSION-TICKET-OSSH", "FRONTED-MEEK-OSSH",
  141. // "FRONTED-MEEK-HTTP-OSSH", "QUIC-OSSH", "MARIONETTE-OSSH", and
  142. // "TAPDANCE-OSSH".
  143. // For the default, an empty list, all protocols are used.
  144. LimitTunnelProtocols []string
  145. // InitialLimitTunnelProtocols is an optional initial phase of limited
  146. // protocols for the first InitialLimitTunnelProtocolsCandidateCount
  147. // candidates; after these candidates, LimitTunnelProtocols applies.
  148. //
  149. // For the default, an empty list, InitialLimitTunnelProtocols is off.
  150. InitialLimitTunnelProtocols []string
  151. // InitialLimitTunnelProtocolsCandidateCount is the number of candidates
  152. // to which InitialLimitTunnelProtocols is applied instead of
  153. // LimitTunnelProtocols.
  154. //
  155. // For the default, 0, InitialLimitTunnelProtocols is off.
  156. InitialLimitTunnelProtocolsCandidateCount int
  157. // LimitTLSProfiles indicates which TLS profiles to select from. Valid
  158. // values are listed in protocols.SupportedTLSProfiles.
  159. // For the default, an empty list, all profiles are candidates for
  160. // selection.
  161. LimitTLSProfiles []string
  162. // LimitQUICVersions indicates which QUIC versions to select from. Valid
  163. // values are listed in protocols.SupportedQUICVersions.
  164. // For the default, an empty list, all versions are candidates for
  165. // selection.
  166. LimitQUICVersions []string
  167. // EstablishTunnelTimeoutSeconds specifies a time limit after which to
  168. // halt the core tunnel controller if no tunnel has been established. The
  169. // default is parameters.EstablishTunnelTimeout.
  170. EstablishTunnelTimeoutSeconds *int
  171. // EstablishTunnelPausePeriodSeconds specifies the delay between attempts
  172. // to establish tunnels. Briefly pausing allows for network conditions to
  173. // improve and for asynchronous operations such as fetch remote server
  174. // list to complete. If omitted, a default value is used. This value is
  175. // typical overridden for testing.
  176. EstablishTunnelPausePeriodSeconds *int
  177. // EstablishTunnelPausePeriodSeconds specifies the grace period, or head
  178. // start, provided to the affinity server candidate when establishing. The
  179. // affinity server is the server used for the last established tunnel.
  180. EstablishTunnelServerAffinityGracePeriodMilliseconds *int
  181. // ConnectionWorkerPoolSize specifies how many connection attempts to
  182. // attempt in parallel. If omitted of when 0, a default is used; this is
  183. // recommended.
  184. ConnectionWorkerPoolSize int
  185. // TunnelPoolSize specifies how many tunnels to run in parallel. Port
  186. // forwards are multiplexed over multiple tunnels. If omitted or when 0,
  187. // the default is TUNNEL_POOL_SIZE, which is recommended.
  188. TunnelPoolSize int
  189. // StaggerConnectionWorkersMilliseconds adds a specified delay before
  190. // making each server candidate available to connection workers. This
  191. // option is enabled when StaggerConnectionWorkersMilliseconds > 0.
  192. StaggerConnectionWorkersMilliseconds int
  193. // LimitIntensiveConnectionWorkers limits the number of concurrent
  194. // connection workers attempting connections with resource intensive
  195. // protocols. This option is enabled when LimitIntensiveConnectionWorkers
  196. // > 0.
  197. LimitIntensiveConnectionWorkers int
  198. // LimitMeekBufferSizes selects smaller buffers for meek protocols.
  199. LimitMeekBufferSizes bool
  200. // IgnoreHandshakeStatsRegexps skips compiling and using stats regexes.
  201. IgnoreHandshakeStatsRegexps bool
  202. // UpstreamProxyURL is a URL specifying an upstream proxy to use for all
  203. // outbound connections. The URL should include proxy type and
  204. // authentication information, as required. See example URLs here:
  205. // https://github.com/Psiphon-Labs/psiphon-tunnel-core/tree/master/psiphon/upstreamproxy
  206. UpstreamProxyURL string
  207. // CustomHeaders is a set of additional arbitrary HTTP headers that are
  208. // added to all plaintext HTTP requests and requests made through an HTTP
  209. // upstream proxy when specified by UpstreamProxyURL.
  210. CustomHeaders http.Header
  211. // NetworkConnectivityChecker is an interface that enables tunnel-core to
  212. // call into the host application to check for network connectivity. See:
  213. // NetworkConnectivityChecker doc.
  214. //
  215. // This parameter is only applicable to library deployments.
  216. NetworkConnectivityChecker NetworkConnectivityChecker
  217. // DeviceBinder is an interface that enables tunnel-core to call into the
  218. // host application to bind sockets to specific devices. See: DeviceBinder
  219. // doc.
  220. //
  221. // This parameter is only applicable to library deployments.
  222. DeviceBinder DeviceBinder
  223. // IPv6Synthesizer is an interface that allows tunnel-core to call into
  224. // the host application to synthesize IPv6 addresses. See: IPv6Synthesizer
  225. // doc.
  226. //
  227. // This parameter is only applicable to library deployments.
  228. IPv6Synthesizer IPv6Synthesizer
  229. // DnsServerGetter is an interface that enables tunnel-core to call into
  230. // the host application to discover the native network DNS server
  231. // settings. See: DnsServerGetter doc.
  232. //
  233. // This parameter is only applicable to library deployments.
  234. DnsServerGetter DnsServerGetter
  235. // NetworkIDGetter in an interface that enables tunnel-core to call into
  236. // the host application to get an identifier for the host's current active
  237. // network. See: NetworkIDGetter doc.
  238. //
  239. // This parameter is only applicable to library deployments.
  240. NetworkIDGetter NetworkIDGetter
  241. // NetworkID, when not blank, is used as the identifier for the host's
  242. // current active network.
  243. // NetworkID is ignored when NetworkIDGetter is set.
  244. NetworkID string
  245. // DisableTactics disables tactics operations including requests, payload
  246. // handling, and application of parameters.
  247. DisableTactics bool
  248. // DisableReplay causes any persisted dial parameters to be ignored when
  249. // they would otherwise be used for replay.
  250. DisableReplay bool
  251. // TargetServerEntry is an encoded server entry. When specified, this
  252. // server entry is used exclusively and all other known servers are
  253. // ignored; also, when set, ConnectionWorkerPoolSize is ignored and
  254. // the pool size is 1.
  255. TargetServerEntry string
  256. // DisableApi disables Psiphon server API calls including handshake,
  257. // connected, status, etc. This is used for special case temporary tunnels
  258. // (Windows VPN mode).
  259. DisableApi bool
  260. // TargetApiProtocol specifies whether to force use of "ssh" or "web" API
  261. // protocol. When blank, the default, the optimal API protocol is used.
  262. // Note that this capability check is not applied before the
  263. // "CandidateServers" count is emitted.
  264. //
  265. // This parameter is intended for testing and debugging only. Not all
  266. // parameters are supported in the legacy "web" API protocol, including
  267. // speed test samples.
  268. TargetApiProtocol string
  269. // RemoteServerListURLs is list of URLs which specify locations to fetch
  270. // out-of-band server entries. This facility is used when a tunnel cannot
  271. // be established to known servers. This value is supplied by and depends
  272. // on the Psiphon Network, and is typically embedded in the client binary.
  273. // All URLs must point to the same entity with the same ETag. At least one
  274. // TransferURL must have OnlyAfterAttempts = 0.
  275. RemoteServerListURLs parameters.TransferURLs
  276. // RemoteServerListSignaturePublicKey specifies a public key that's used
  277. // to authenticate the remote server list payload. This value is supplied
  278. // by and depends on the Psiphon Network, and is typically embedded in the
  279. // client binary.
  280. RemoteServerListSignaturePublicKey string
  281. // DisableRemoteServerListFetcher disables fetching remote server lists.
  282. // This is used for special case temporary tunnels.
  283. DisableRemoteServerListFetcher bool
  284. // FetchRemoteServerListRetryPeriodMilliseconds specifies the delay before
  285. // resuming a remote server list download after a failure. If omitted, a
  286. // default value is used. This value is typical overridden for testing.
  287. FetchRemoteServerListRetryPeriodMilliseconds *int
  288. // ObfuscatedServerListRootURLs is a list of URLs which specify root
  289. // locations from which to fetch obfuscated server list files. This value
  290. // is supplied by and depends on the Psiphon Network, and is typically
  291. // embedded in the client binary. All URLs must point to the same entity
  292. // with the same ETag. At least one DownloadURL must have
  293. // OnlyAfterAttempts = 0.
  294. ObfuscatedServerListRootURLs parameters.TransferURLs
  295. // SplitTunnelRoutesURLFormat is a URL which specifies the location of a
  296. // routes file to use for split tunnel mode. The URL must include a
  297. // placeholder for the client region to be supplied. Split tunnel mode
  298. // uses the routes file to classify port forward destinations as foreign
  299. // or domestic and does not tunnel domestic destinations. Split tunnel
  300. // mode is on when all the SplitTunnel parameters are supplied. This value
  301. // is supplied by and depends on the Psiphon Network, and is typically
  302. // embedded in the client binary.
  303. SplitTunnelRoutesURLFormat string
  304. // SplitTunnelRoutesSignaturePublicKey specifies a public key that's used
  305. // to authenticate the split tunnel routes payload. This value is supplied
  306. // by and depends on the Psiphon Network, and is typically embedded in the
  307. // client binary.
  308. SplitTunnelRoutesSignaturePublicKey string
  309. // SplitTunnelDNSServer specifies a DNS server to use when resolving port
  310. // forward target domain names to IP addresses for classification. The DNS
  311. // server must support TCP requests.
  312. SplitTunnelDNSServer string
  313. // UpgradeDownloadURLs is list of URLs which specify locations from which
  314. // to download a host client upgrade file, when one is available. The core
  315. // tunnel controller provides a resumable download facility which
  316. // downloads this resource and emits a notice when complete. This value is
  317. // supplied by and depends on the Psiphon Network, and is typically
  318. // embedded in the client binary. All URLs must point to the same entity
  319. // with the same ETag. At least one DownloadURL must have
  320. // OnlyAfterAttempts = 0.
  321. UpgradeDownloadURLs parameters.TransferURLs
  322. // UpgradeDownloadClientVersionHeader specifies the HTTP header name for
  323. // the entity at UpgradeDownloadURLs which specifies the client version
  324. // (an integer value). A HEAD request may be made to check the version
  325. // number available at UpgradeDownloadURLs.
  326. // UpgradeDownloadClientVersionHeader is required when UpgradeDownloadURLs
  327. // is specified.
  328. UpgradeDownloadClientVersionHeader string
  329. // FetchUpgradeRetryPeriodMilliseconds specifies the delay before resuming
  330. // a client upgrade download after a failure. If omitted, a default value
  331. // is used. This value is typical overridden for testing.
  332. FetchUpgradeRetryPeriodMilliseconds *int
  333. // TrustedCACertificatesFilename specifies a file containing trusted CA
  334. // certs. When set, this toggles use of the trusted CA certs, specified in
  335. // TrustedCACertificatesFilename, for tunneled TLS connections that expect
  336. // server certificates signed with public certificate authorities
  337. // (currently, only upgrade downloads). This option is used with stock Go
  338. // TLS in cases where Go may fail to obtain a list of root CAs from the
  339. // operating system.
  340. TrustedCACertificatesFilename string
  341. // DisablePeriodicSshKeepAlive indicates whether to send an SSH keepalive
  342. // every 1-2 minutes, when the tunnel is idle. If the SSH keepalive times
  343. // out, the tunnel is considered to have failed.
  344. DisablePeriodicSshKeepAlive bool
  345. // DeviceRegion is the optional, reported region the host device is
  346. // running in. This input value should be a ISO 3166-1 alpha-2 country
  347. // code. The device region is reported to the server in the connected
  348. // request and recorded for Psiphon stats.
  349. //
  350. // When provided, this value may be used, pre-connection, to select
  351. // performance or circumvention optimization strategies for the given
  352. // region.
  353. DeviceRegion string
  354. // EmitDiagnosticNotices indicates whether to output notices containing
  355. // detailed information about the Psiphon session. As these notices may
  356. // contain sensitive information, they should not be insecurely distributed
  357. // or displayed to users. Default is off.
  358. EmitDiagnosticNotices bool
  359. // EmitDiagnosticNetworkParameters indicates whether to include network
  360. // parameters in diagnostic notices. As these parameters are sensitive
  361. // circumvention network information, they should not be insecurely
  362. // distributed or displayed to users. Default is off.
  363. EmitDiagnosticNetworkParameters bool
  364. // EmitBytesTransferred indicates whether to emit periodic notices showing
  365. // bytes sent and received.
  366. EmitBytesTransferred bool
  367. // EmitSLOKs indicates whether to emit notices for each seeded SLOK. As
  368. // this could reveal user browsing activity, it's intended for debugging
  369. // and testing only.
  370. EmitSLOKs bool
  371. // EmitTapdanceLogs indicates whether to emit gotapdance log messages
  372. // to stdout. Note that gotapdance log messages do not conform to the
  373. // Notice format standard. Default is off.
  374. EmitTapdanceLogs bool
  375. // EmitServerAlerts indicates whether to emit notices for server alerts.
  376. EmitServerAlerts bool
  377. // RateLimits specify throttling configuration for the tunnel.
  378. RateLimits common.RateLimits
  379. // PacketTunnelTunDeviceFileDescriptor specifies a tun device file
  380. // descriptor to use for running a packet tunnel. When this value is > 0,
  381. // a packet tunnel is established through the server and packets are
  382. // relayed via the tun device file descriptor. The file descriptor is
  383. // duped in NewController. When PacketTunnelTunDeviceFileDescriptor is
  384. // set, TunnelPoolSize must be 1.
  385. PacketTunnelTunFileDescriptor int
  386. // SessionID specifies a client session ID to use in the Psiphon API. The
  387. // session ID should be a randomly generated value that is used only for a
  388. // single session, which is defined as the period between a user starting
  389. // a Psiphon client and stopping the client.
  390. //
  391. // A session ID must be 32 hex digits (lower case). When blank, a random
  392. // session ID is automatically generated. Supply a session ID when a
  393. // single client session will cross multiple Controller instances.
  394. SessionID string
  395. // Authorizations is a list of encoded, signed access control
  396. // authorizations that the client has obtained and will present to the
  397. // server.
  398. Authorizations []string
  399. // ServerEntrySignaturePublicKey is a base64-encoded, ed25519 public
  400. // key value used to verify individual server entry signatures. This value
  401. // is supplied by and depends on the Psiphon Network, and is typically
  402. // embedded in the client binary.
  403. ServerEntrySignaturePublicKey string
  404. // ExchangeObfuscationKey is a base64-encoded, NaCl secretbox key used to
  405. // obfuscate server info exchanges between clients.
  406. // Required for the exchange functionality.
  407. ExchangeObfuscationKey string
  408. // TransformHostNameProbability is for testing purposes.
  409. TransformHostNameProbability *float64
  410. // FragmentorProbability and associated Fragmentor fields are for testing
  411. // purposes.
  412. FragmentorProbability *float64
  413. FragmentorLimitProtocols []string
  414. FragmentorMinTotalBytes *int
  415. FragmentorMaxTotalBytes *int
  416. FragmentorMinWriteBytes *int
  417. FragmentorMaxWriteBytes *int
  418. FragmentorMinDelayMicroseconds *int
  419. FragmentorMaxDelayMicroseconds *int
  420. // MeekTrafficShapingProbability and associated fields are for testing
  421. // purposes.
  422. MeekTrafficShapingProbability *float64
  423. MeekTrafficShapingLimitProtocols []string
  424. MeekMinTLSPadding *int
  425. MeekMaxTLSPadding *int
  426. MeekMinLimitRequestPayloadLength *int
  427. MeekMaxLimitRequestPayloadLength *int
  428. MeekRedialTLSProbability *float64
  429. // ObfuscatedSSHAlgorithms and associated ObfuscatedSSH fields are for
  430. // testing purposes. If specified, ObfuscatedSSHAlgorithms must have 4 SSH
  431. // KEX elements in order: the kex algorithm, cipher, MAC, and server host
  432. // key algorithm.
  433. ObfuscatedSSHAlgorithms []string
  434. ObfuscatedSSHMinPadding *int
  435. ObfuscatedSSHMaxPadding *int
  436. // LivenessTestMinUpstreamBytes and other LivenessTest fields are for
  437. // testing purposes.
  438. LivenessTestMinUpstreamBytes *int
  439. LivenessTestMaxUpstreamBytes *int
  440. LivenessTestMinDownstreamBytes *int
  441. LivenessTestMaxDownstreamBytes *int
  442. // ReplayCandidateCount and other Replay fields are for testing purposes.
  443. ReplayCandidateCount *int
  444. ReplayDialParametersTTLSeconds *int
  445. ReplayTargetUpstreamBytes *int
  446. ReplayTargetDownstreamBytes *int
  447. ReplayTargetTunnelDurationSeconds *int
  448. ReplayLaterRoundMoveToFrontProbability *float64
  449. ReplayRetainFailedProbability *float64
  450. // NetworkLatencyMultiplierMin and other NetworkLatencyMultiplier fields are
  451. // for testing purposes.
  452. NetworkLatencyMultiplierMin float64
  453. NetworkLatencyMultiplierMax float64
  454. NetworkLatencyMultiplierLambda float64
  455. // UseOnlyCustomTLSProfiles and other TLS configuration fields are for
  456. // testing purposes.
  457. UseOnlyCustomTLSProfiles *bool
  458. CustomTLSProfiles protocol.CustomTLSProfiles
  459. SelectRandomizedTLSProfileProbability *float64
  460. NoDefaultTLSSessionIDProbability *float64
  461. // ApplicationParameters is for testing purposes.
  462. ApplicationParameters parameters.KeyValues
  463. // MigrateHomepageNoticesFilename migrates a homepage file from the path
  464. // previously configured with setNoticeFiles to the new path for homepage
  465. // files under the data root directory. The file specified by this config
  466. // value will be moved to config.GetHomePageFilename().
  467. //
  468. // Note: see comment for config.Commit() for a description of how file
  469. // migrations are performed.
  470. //
  471. // If not set, no migration operation will be performed.
  472. MigrateHomepageNoticesFilename string
  473. // MigrateRotatingNoticesFilename migrates notice files from the path
  474. // previously configured with setNoticeFiles to the new path for notice
  475. // files under the data root directory.
  476. //
  477. // MigrateRotatingNoticesFilename will be moved to
  478. // config.GetNoticesFilename().
  479. //
  480. // MigrateRotatingNoticesFilename.1 will be moved to
  481. // config.GetOldNoticesFilename().
  482. //
  483. // Note: see comment for config.Commit() for a description of how file
  484. // migrations are performed.
  485. //
  486. // If not set, no migration operation will be performed.
  487. MigrateRotatingNoticesFilename string
  488. // DataStoreDirectory is the directory in which to store the persistent
  489. // database, which contains information such as server entries. By
  490. // default, current working directory.
  491. //
  492. // Deprecated:
  493. // Use MigrateDataStoreDirectory. When MigrateDataStoreDirectory
  494. // is set, this parameter is ignored.
  495. //
  496. // DataStoreDirectory has been subsumed by the new data root directory,
  497. // which is configured with DataRootDirectory. If set, datastore files
  498. // found in the specified directory will be moved under the data root
  499. // directory.
  500. DataStoreDirectory string
  501. // MigrateDataStoreDirectory indicates the location of the datastore
  502. // directory, as previously configured with the deprecated
  503. // DataStoreDirectory config field. Datastore files found in the specified
  504. // directory will be moved under the data root directory.
  505. //
  506. // Note: see comment for config.Commit() for a description of how file
  507. // migrations are performed.
  508. MigrateDataStoreDirectory string
  509. // RemoteServerListDownloadFilename specifies a target filename for
  510. // storing the remote server list download. Data is stored in co-located
  511. // files (RemoteServerListDownloadFilename.part*) to allow for resumable
  512. // downloading.
  513. //
  514. // Deprecated:
  515. // Use MigrateRemoteServerListDownloadFilename. When
  516. // MigrateRemoteServerListDownloadFilename is set, this parameter is
  517. // ignored.
  518. //
  519. // If set, remote server list download files found at the specified path
  520. // will be moved under the data root directory.
  521. RemoteServerListDownloadFilename string
  522. // MigrateRemoteServerListDownloadFilename indicates the location of
  523. // remote server list download files. The remote server list files found at
  524. // the specified path will be moved under the data root directory.
  525. //
  526. // Note: see comment for config.Commit() for a description of how file
  527. // migrations are performed.
  528. MigrateRemoteServerListDownloadFilename string
  529. // ObfuscatedServerListDownloadDirectory specifies a target directory for
  530. // storing the obfuscated remote server list downloads. Data is stored in
  531. // co-located files (<OSL filename>.part*) to allow for resumable
  532. // downloading.
  533. //
  534. // Deprecated:
  535. // Use MigrateObfuscatedServerListDownloadDirectory. When
  536. // MigrateObfuscatedServerListDownloadDirectory is set, this parameter is
  537. // ignored.
  538. //
  539. // If set, obfuscated server list download files found at the specified path
  540. // will be moved under the data root directory.
  541. ObfuscatedServerListDownloadDirectory string
  542. // MigrateObfuscatedServerListDownloadDirectory indicates the location of
  543. // the obfuscated server list downloads directory, as previously configured
  544. // with ObfuscatedServerListDownloadDirectory. Obfuscated server list
  545. // download files found in the specified directory will be moved under the
  546. // data root directory.
  547. //
  548. // Warning: if the directory is empty after obfuscated server
  549. // list files are moved, then it will be deleted.
  550. //
  551. // Note: see comment for config.Commit() for a description of how file
  552. // migrations are performed.
  553. MigrateObfuscatedServerListDownloadDirectory string
  554. // UpgradeDownloadFilename is the local target filename for an upgrade
  555. // download. This parameter is required when UpgradeDownloadURLs (or
  556. // UpgradeDownloadUrl) is specified. Data is stored in co-located files
  557. // (UpgradeDownloadFilename.part*) to allow for resumable downloading.
  558. //
  559. // Deprecated:
  560. // Use MigrateUpgradeDownloadFilename. When MigrateUpgradeDownloadFilename
  561. // is set, this parameter is ignored.
  562. //
  563. // If set, upgrade download files found at the specified path will be moved
  564. // under the data root directory.
  565. UpgradeDownloadFilename string
  566. // MigrateUpgradeDownloadFilename indicates the location of downloaded
  567. // application upgrade files. Downloaded upgrade files found at the
  568. // specified path will be moved under the data root directory.
  569. //
  570. // Note: see comment for config.Commit() for a description of how file
  571. // migrations are performed.
  572. MigrateUpgradeDownloadFilename string
  573. // TunnelProtocol indicates which protocol to use. For the default, "",
  574. // all protocols are used.
  575. //
  576. // Deprecated: Use LimitTunnelProtocols. When LimitTunnelProtocols is not
  577. // nil, this parameter is ignored.
  578. TunnelProtocol string
  579. // Deprecated: Use CustomHeaders. When CustomHeaders is not nil, this
  580. // parameter is ignored.
  581. UpstreamProxyCustomHeaders http.Header
  582. // RemoteServerListUrl is a URL which specifies a location to fetch out-
  583. // of-band server entries. This facility is used when a tunnel cannot be
  584. // established to known servers. This value is supplied by and depends on
  585. // the Psiphon Network, and is typically embedded in the client binary.
  586. //
  587. // Deprecated: Use RemoteServerListURLs. When RemoteServerListURLs is not
  588. // nil, this parameter is ignored.
  589. RemoteServerListUrl string
  590. // ObfuscatedServerListRootURL is a URL which specifies the root location
  591. // from which to fetch obfuscated server list files. This value is
  592. // supplied by and depends on the Psiphon Network, and is typically
  593. // embedded in the client binary.
  594. //
  595. // Deprecated: Use ObfuscatedServerListRootURLs. When
  596. // ObfuscatedServerListRootURLs is not nil, this parameter is ignored.
  597. ObfuscatedServerListRootURL string
  598. // UpgradeDownloadUrl specifies a URL from which to download a host client
  599. // upgrade file, when one is available. The core tunnel controller
  600. // provides a resumable download facility which downloads this resource
  601. // and emits a notice when complete. This value is supplied by and depends
  602. // on the Psiphon Network, and is typically embedded in the client binary.
  603. //
  604. // Deprecated: Use UpgradeDownloadURLs. When UpgradeDownloadURLs is not
  605. // nil, this parameter is ignored.
  606. UpgradeDownloadUrl string
  607. // FeedbackUploadURLs is a list of SecureTransferURLs which specify
  608. // locations where feedback data can be uploaded, pairing with each
  609. // location a public key with which to encrypt the feedback data. This
  610. // value is supplied by and depends on the Psiphon Network, and is
  611. // typically embedded in the client binary. At least one TransferURL must
  612. // have OnlyAfterAttempts = 0.
  613. FeedbackUploadURLs parameters.TransferURLs
  614. // FeedbackEncryptionPublicKey is a default base64-encoded, RSA public key
  615. // value used to encrypt feedback data. Used when uploading feedback with a
  616. // TransferURL which has no public key value configured, i.e.
  617. // B64EncodedPublicKey = "".
  618. FeedbackEncryptionPublicKey string
  619. // clientParameters is the active ClientParameters with defaults, config
  620. // values, and, optionally, tactics applied.
  621. //
  622. // New tactics must be applied by calling Config.SetClientParameters;
  623. // calling clientParameters.Set directly will fail to add config values.
  624. clientParameters *parameters.ClientParameters
  625. dialParametersHash []byte
  626. dynamicConfigMutex sync.Mutex
  627. sponsorID string
  628. authorizations []string
  629. deviceBinder DeviceBinder
  630. networkIDGetter NetworkIDGetter
  631. committed bool
  632. loadTimestamp string
  633. }
  634. // Config field which specifies if notice files should be used and at which
  635. // frequency and size they should be rotated.
  636. //
  637. // If either RotatingFileSize or RotatingSyncFrequency are <= 0, default values
  638. // are used.
  639. //
  640. // See comment for setNoticeFiles in notice.go for further details.
  641. type UseNoticeFiles struct {
  642. RotatingFileSize int
  643. RotatingSyncFrequency int
  644. }
  645. // LoadConfig parses a JSON format Psiphon config JSON string and returns a
  646. // Config struct populated with config values.
  647. //
  648. // The Config struct may then be programmatically populated with additional
  649. // values, including callbacks such as DeviceBinder.
  650. //
  651. // Before using the Config, Commit must be called, which will perform further
  652. // validation and initialize internal data structures.
  653. func LoadConfig(configJson []byte) (*Config, error) {
  654. var config Config
  655. err := json.Unmarshal(configJson, &config)
  656. if err != nil {
  657. return nil, errors.Trace(err)
  658. }
  659. config.loadTimestamp = common.TruncateTimestampToHour(
  660. common.GetCurrentTimestamp())
  661. return &config, nil
  662. }
  663. // IsCommitted checks if Commit was called.
  664. func (config *Config) IsCommitted() bool {
  665. return config.committed
  666. }
  667. // Commit validates Config fields finalizes initialization.
  668. //
  669. // Config fields should not be set after calling Config, as any changes may
  670. // not be reflected in internal data structures.
  671. //
  672. // If migrateFromLegacyFields is set to true, then an attempt to migrate from
  673. // legacy fields is made.
  674. //
  675. // Migration from legacy fields:
  676. // Config fields of the naming Migrate* (e.g. MigrateDataStoreDirectory) specify
  677. // a file migration operation which should be performed. These fields correspond
  678. // to deprecated fields, which previously could be used to specify where Psiphon
  679. // stored different sets of persistent files (e.g. MigrateDataStoreDirectory
  680. // corresponds to the deprecated field DataStoreDirectory).
  681. //
  682. // Psiphon now stores all persistent data under the configurable
  683. // DataRootDirectory (see Config.DataRootDirectory). The deprecated fields, and
  684. // corresponding Migrate* fields, are now used to specify the file or directory
  685. // path where, or under which, persistent files and directories created by
  686. // previous versions of Psiphon exist, so they can be moved under the
  687. // DataRootDirectory.
  688. //
  689. // For each migration operation:
  690. // - In the case of directories that could have defaulted to the current working
  691. // directory, persistent files and directories created by Psiphon are
  692. // precisely targeted to avoid moving files which were not created by Psiphon.
  693. // - If no file is found at the specified path, or an error is encountered while
  694. // migrating the file, then an error is logged and execution continues
  695. // normally.
  696. //
  697. // A sentinel file which signals that file migration has been completed, and
  698. // should not be attempted again, is created under DataRootDirectory after one
  699. // full pass through Commit(), regardless of whether file migration succeeds or
  700. // fails. It is better to not endlessly retry file migrations on each Commit()
  701. // because file system errors are expected to be rare and persistent files will
  702. // be re-populated over time.
  703. func (config *Config) Commit(migrateFromLegacyFields bool) error {
  704. // Do SetEmitDiagnosticNotices first, to ensure config file errors are
  705. // emitted.
  706. if config.EmitDiagnosticNotices {
  707. SetEmitDiagnosticNotices(
  708. true, config.EmitDiagnosticNetworkParameters)
  709. }
  710. // Migrate and set notice files before any operations that may emit an
  711. // error. This is to ensure config file errors are written to file when
  712. // notice files are configured with config.UseNoticeFiles.
  713. //
  714. // Note:
  715. // Errors encountered while configuring the data directory cannot be written
  716. // to notice files. This is because notices files are created within the
  717. // data directory.
  718. if config.DataRootDirectory == "" {
  719. wd, err := os.Getwd()
  720. if err != nil {
  721. return errors.Trace(err)
  722. }
  723. config.DataRootDirectory = wd
  724. }
  725. // Create root directory
  726. dataDirectoryPath := config.GetPsiphonDataDirectory()
  727. if !common.FileExists(dataDirectoryPath) {
  728. err := os.Mkdir(dataDirectoryPath, os.ModePerm)
  729. if err != nil {
  730. return errors.Tracef("failed to create datastore directory %s with error: %s", dataDirectoryPath, err.Error())
  731. }
  732. }
  733. // Check if the migration from legacy config fields has already been
  734. // completed. See the Migrate* config fields for more details.
  735. migrationCompleteFilePath := filepath.Join(config.GetPsiphonDataDirectory(), "migration_complete")
  736. needMigration := !common.FileExists(migrationCompleteFilePath)
  737. // Collect notices to emit them after notice files are set
  738. var noticeMigrationAlertMsgs []string
  739. var noticeMigrationInfoMsgs []string
  740. // Migrate notices first to ensure notice files are used for notices if
  741. // UseNoticeFiles is set.
  742. homepageFilePath := config.GetHomePageFilename()
  743. noticesFilePath := config.GetNoticesFilename()
  744. if migrateFromLegacyFields {
  745. if needMigration {
  746. // Move notice files that exist at legacy file paths under the data root
  747. // directory.
  748. noticeMigrationInfoMsgs = append(noticeMigrationInfoMsgs, "Config migration: need migration")
  749. noticeMigrations := migrationsFromLegacyNoticeFilePaths(config)
  750. for _, migration := range noticeMigrations {
  751. err := common.DoFileMigration(migration)
  752. if err != nil {
  753. alertMsg := fmt.Sprintf("Config migration: %s", errors.Trace(err))
  754. noticeMigrationAlertMsgs = append(noticeMigrationAlertMsgs, alertMsg)
  755. } else {
  756. infoMsg := fmt.Sprintf("Config migration: moved %s to %s", migration.OldPath, migration.NewPath)
  757. noticeMigrationInfoMsgs = append(noticeMigrationInfoMsgs, infoMsg)
  758. }
  759. }
  760. } else {
  761. noticeMigrationInfoMsgs = append(noticeMigrationInfoMsgs, "Config migration: migration already completed")
  762. }
  763. }
  764. if config.UseNoticeFiles != nil {
  765. setNoticeFiles(
  766. homepageFilePath,
  767. noticesFilePath,
  768. config.UseNoticeFiles.RotatingFileSize,
  769. config.UseNoticeFiles.RotatingSyncFrequency)
  770. }
  771. // Emit notices now that notice files are set if configured
  772. for _, msg := range noticeMigrationAlertMsgs {
  773. NoticeWarning(msg)
  774. }
  775. for _, msg := range noticeMigrationInfoMsgs {
  776. NoticeInfo(msg)
  777. }
  778. // Promote legacy fields.
  779. if config.CustomHeaders == nil {
  780. config.CustomHeaders = config.UpstreamProxyCustomHeaders
  781. config.UpstreamProxyCustomHeaders = nil
  782. }
  783. if config.RemoteServerListUrl != "" && config.RemoteServerListURLs == nil {
  784. config.RemoteServerListURLs = promoteLegacyTransferURL(config.RemoteServerListUrl)
  785. }
  786. if config.ObfuscatedServerListRootURL != "" && config.ObfuscatedServerListRootURLs == nil {
  787. config.ObfuscatedServerListRootURLs = promoteLegacyTransferURL(config.ObfuscatedServerListRootURL)
  788. }
  789. if config.UpgradeDownloadUrl != "" && config.UpgradeDownloadURLs == nil {
  790. config.UpgradeDownloadURLs = promoteLegacyTransferURL(config.UpgradeDownloadUrl)
  791. }
  792. if config.TunnelProtocol != "" && len(config.LimitTunnelProtocols) == 0 {
  793. config.LimitTunnelProtocols = []string{config.TunnelProtocol}
  794. }
  795. if config.DataStoreDirectory != "" && config.MigrateDataStoreDirectory == "" {
  796. config.MigrateDataStoreDirectory = config.DataStoreDirectory
  797. }
  798. if config.RemoteServerListDownloadFilename != "" && config.MigrateRemoteServerListDownloadFilename == "" {
  799. config.MigrateRemoteServerListDownloadFilename = config.RemoteServerListDownloadFilename
  800. }
  801. if config.ObfuscatedServerListDownloadDirectory != "" && config.MigrateObfuscatedServerListDownloadDirectory == "" {
  802. config.MigrateObfuscatedServerListDownloadDirectory = config.ObfuscatedServerListDownloadDirectory
  803. }
  804. if config.UpgradeDownloadFilename != "" && config.MigrateUpgradeDownloadFilename == "" {
  805. config.MigrateUpgradeDownloadFilename = config.UpgradeDownloadFilename
  806. }
  807. // Supply default values.
  808. // Create datastore directory.
  809. dataStoreDirectoryPath := config.GetDataStoreDirectory()
  810. if !common.FileExists(dataStoreDirectoryPath) {
  811. err := os.Mkdir(dataStoreDirectoryPath, os.ModePerm)
  812. if err != nil {
  813. return errors.Tracef("failed to create datastore directory %s with error: %s", dataStoreDirectoryPath, err.Error())
  814. }
  815. }
  816. // Create OSL directory.
  817. oslDirectoryPath := config.GetObfuscatedServerListDownloadDirectory()
  818. if !common.FileExists(oslDirectoryPath) {
  819. err := os.Mkdir(oslDirectoryPath, os.ModePerm)
  820. if err != nil {
  821. return errors.Tracef("failed to create osl directory %s with error: %s", oslDirectoryPath, err.Error())
  822. }
  823. }
  824. // Create tapdance directory
  825. tapdanceDirectoryPath := config.GetTapdanceDirectory()
  826. if !common.FileExists(tapdanceDirectoryPath) {
  827. err := os.Mkdir(tapdanceDirectoryPath, os.ModePerm)
  828. if err != nil {
  829. return errors.Tracef("failed to create tapdance directory %s with error: %s", tapdanceDirectoryPath, err.Error())
  830. }
  831. }
  832. if config.ClientVersion == "" {
  833. config.ClientVersion = "0"
  834. }
  835. if config.TunnelPoolSize == 0 {
  836. config.TunnelPoolSize = TUNNEL_POOL_SIZE
  837. }
  838. // Validate config fields.
  839. if !common.FileExists(config.DataRootDirectory) {
  840. return errors.Tracef("DataRootDirectory does not exist: %s", config.DataRootDirectory)
  841. }
  842. if config.PropagationChannelId == "" {
  843. return errors.TraceNew("propagation channel ID is missing from the configuration file")
  844. }
  845. if config.SponsorId == "" {
  846. return errors.TraceNew("sponsor ID is missing from the configuration file")
  847. }
  848. _, err := strconv.Atoi(config.ClientVersion)
  849. if err != nil {
  850. return errors.Tracef("invalid client version: %s", err)
  851. }
  852. if !common.Contains(
  853. []string{"", protocol.PSIPHON_SSH_API_PROTOCOL, protocol.PSIPHON_WEB_API_PROTOCOL},
  854. config.TargetApiProtocol) {
  855. return errors.TraceNew("invalid TargetApiProtocol")
  856. }
  857. if !config.DisableRemoteServerListFetcher {
  858. if config.RemoteServerListURLs != nil {
  859. if config.RemoteServerListSignaturePublicKey == "" {
  860. return errors.TraceNew("missing RemoteServerListSignaturePublicKey")
  861. }
  862. }
  863. if config.ObfuscatedServerListRootURLs != nil {
  864. if config.RemoteServerListSignaturePublicKey == "" {
  865. return errors.TraceNew("missing RemoteServerListSignaturePublicKey")
  866. }
  867. }
  868. }
  869. if config.SplitTunnelRoutesURLFormat != "" {
  870. if config.SplitTunnelRoutesSignaturePublicKey == "" {
  871. return errors.TraceNew("missing SplitTunnelRoutesSignaturePublicKey")
  872. }
  873. if config.SplitTunnelDNSServer == "" {
  874. return errors.TraceNew("missing SplitTunnelDNSServer")
  875. }
  876. }
  877. if config.UpgradeDownloadURLs != nil {
  878. if config.UpgradeDownloadClientVersionHeader == "" {
  879. return errors.TraceNew("missing UpgradeDownloadClientVersionHeader")
  880. }
  881. }
  882. if config.FeedbackUploadURLs != nil {
  883. if config.FeedbackEncryptionPublicKey == "" {
  884. return errors.TraceNew("missing FeedbackEncryptionPublicKey")
  885. }
  886. }
  887. // This constraint is expected by logic in Controller.runTunnels().
  888. if config.PacketTunnelTunFileDescriptor > 0 && config.TunnelPoolSize != 1 {
  889. return errors.TraceNew("packet tunnel mode requires TunnelPoolSize to be 1")
  890. }
  891. // SessionID must be PSIPHON_API_CLIENT_SESSION_ID_LENGTH lowercase hex-encoded bytes.
  892. if config.SessionID == "" {
  893. sessionID, err := MakeSessionId()
  894. if err != nil {
  895. return errors.Trace(err)
  896. }
  897. config.SessionID = sessionID
  898. }
  899. if len(config.SessionID) != 2*protocol.PSIPHON_API_CLIENT_SESSION_ID_LENGTH ||
  900. -1 != strings.IndexFunc(config.SessionID, func(c rune) bool {
  901. return !unicode.Is(unicode.ASCII_Hex_Digit, c) || unicode.IsUpper(c)
  902. }) {
  903. return errors.TraceNew("invalid SessionID")
  904. }
  905. config.clientParameters, err = parameters.NewClientParameters(
  906. func(err error) {
  907. NoticeWarning("ClientParameters getValue failed: %s", err)
  908. })
  909. if err != nil {
  910. return errors.Trace(err)
  911. }
  912. if config.ObfuscatedSSHAlgorithms != nil &&
  913. len(config.ObfuscatedSSHAlgorithms) != 4 {
  914. // TODO: validate each algorithm?
  915. return errors.TraceNew("invalid ObfuscatedSSHAlgorithms")
  916. }
  917. // clientParameters.Set will validate the config fields applied to parameters.
  918. err = config.SetClientParameters("", false, nil)
  919. if err != nil {
  920. return errors.Trace(err)
  921. }
  922. // Calculate and set the dial parameters hash. After this point, related
  923. // config fields must not change.
  924. config.setDialParametersHash()
  925. // Set defaults for dynamic config fields.
  926. config.SetDynamicConfig(config.SponsorId, config.Authorizations)
  927. // Initialize config.deviceBinder and config.config.networkIDGetter. These
  928. // wrap config.DeviceBinder and config.NetworkIDGetter/NetworkID with
  929. // loggers.
  930. //
  931. // New variables are set to avoid mutating input config fields.
  932. // Internally, code must use config.deviceBinder and
  933. // config.networkIDGetter and not the input/exported fields.
  934. if config.DeviceBinder != nil {
  935. config.deviceBinder = newLoggingDeviceBinder(config.DeviceBinder)
  936. }
  937. networkIDGetter := config.NetworkIDGetter
  938. if networkIDGetter == nil {
  939. // Limitation: unlike NetworkIDGetter, which calls back to platform APIs
  940. // this method of network identification is not dynamic and will not reflect
  941. // network changes that occur while running.
  942. if config.NetworkID != "" {
  943. networkIDGetter = newStaticNetworkGetter(config.NetworkID)
  944. } else {
  945. networkIDGetter = newStaticNetworkGetter("UNKNOWN")
  946. }
  947. }
  948. config.networkIDGetter = newLoggingNetworkIDGetter(networkIDGetter)
  949. // Migrate from old config fields. This results in files being moved under
  950. // a config specified data root directory.
  951. if migrateFromLegacyFields && needMigration {
  952. // If unset, set MigrateDataStoreDirectory to the previous default value for
  953. // DataStoreDirectory to ensure that datastore files are migrated.
  954. if config.MigrateDataStoreDirectory == "" {
  955. wd, err := os.Getwd()
  956. if err != nil {
  957. return errors.Trace(err)
  958. }
  959. NoticeInfo("MigrateDataStoreDirectory unset, using working directory %s", wd)
  960. config.MigrateDataStoreDirectory = wd
  961. }
  962. // Move files that exist at legacy file paths under the data root
  963. // directory.
  964. migrations, err := migrationsFromLegacyFilePaths(config)
  965. if err != nil {
  966. return errors.Trace(err)
  967. }
  968. // Do migrations
  969. for _, migration := range migrations {
  970. err := common.DoFileMigration(migration)
  971. if err != nil {
  972. NoticeWarning("Config migration: %s", errors.Trace(err))
  973. } else {
  974. NoticeInfo("Config migration: moved %s to %s", migration.OldPath, migration.NewPath)
  975. }
  976. }
  977. // Remove OSL directory if empty
  978. if config.MigrateObfuscatedServerListDownloadDirectory != "" {
  979. files, err := ioutil.ReadDir(config.MigrateObfuscatedServerListDownloadDirectory)
  980. if err != nil {
  981. NoticeWarning("Error reading OSL directory %s: %s", config.MigrateObfuscatedServerListDownloadDirectory, errors.Trace(err))
  982. } else if len(files) == 0 {
  983. err := os.Remove(config.MigrateObfuscatedServerListDownloadDirectory)
  984. if err != nil {
  985. NoticeWarning("Error deleting empty OSL directory %s: %s", config.MigrateObfuscatedServerListDownloadDirectory, errors.Trace(err))
  986. }
  987. }
  988. }
  989. f, err := os.Create(migrationCompleteFilePath)
  990. if err != nil {
  991. NoticeWarning("Config migration: failed to create %s with error %s", migrationCompleteFilePath, errors.Trace(err))
  992. } else {
  993. NoticeInfo("Config migration: completed")
  994. f.Close()
  995. }
  996. }
  997. config.committed = true
  998. return nil
  999. }
  1000. // GetClientParameters returns the current client parameters.
  1001. func (config *Config) GetClientParameters() *parameters.ClientParameters {
  1002. return config.clientParameters
  1003. }
  1004. // SetClientParameters resets Config.clientParameters to the default values,
  1005. // applies any config file values, and then applies the input parameters (from
  1006. // tactics, etc.)
  1007. //
  1008. // Set skipOnError to false when initially applying only config values, as
  1009. // this will validate the values and should fail. Set skipOnError to true when
  1010. // applying tactics to ignore invalid or unknown parameter values from tactics.
  1011. //
  1012. // In the case of applying tactics, do not call Config.clientParameters.Set
  1013. // directly as this will not first apply config values.
  1014. //
  1015. // If there is an error, the existing Config.clientParameters are left
  1016. // entirely unmodified.
  1017. func (config *Config) SetClientParameters(tag string, skipOnError bool, applyParameters map[string]interface{}) error {
  1018. setParameters := []map[string]interface{}{config.makeConfigParameters()}
  1019. if applyParameters != nil {
  1020. setParameters = append(setParameters, applyParameters)
  1021. }
  1022. counts, err := config.clientParameters.Set(tag, skipOnError, setParameters...)
  1023. if err != nil {
  1024. return errors.Trace(err)
  1025. }
  1026. NoticeInfo("applied %v parameters with tag '%s'", counts, tag)
  1027. // Emit certain individual parameter values for quick reference in diagnostics.
  1028. p := config.clientParameters.Get()
  1029. NoticeInfo(
  1030. "NetworkLatencyMultiplier Min/Max/Lambda: %f/%f/%f",
  1031. p.Float(parameters.NetworkLatencyMultiplierMin),
  1032. p.Float(parameters.NetworkLatencyMultiplierMax),
  1033. p.Float(parameters.NetworkLatencyMultiplierLambda))
  1034. // Application Parameters are feature flags/config info, delivered as Client
  1035. // Parameters via tactics/etc., to be communicated to the outer application.
  1036. // Emit these now, as notices.
  1037. if p.WeightedCoinFlip(parameters.ApplicationParametersProbability) {
  1038. NoticeApplicationParameters(p.KeyValues(parameters.ApplicationParameters))
  1039. }
  1040. return nil
  1041. }
  1042. // SetDynamicConfig sets the current client sponsor ID and authorizations.
  1043. // Invalid values for sponsor ID are ignored. The caller must not modify the
  1044. // input authorizations slice.
  1045. func (config *Config) SetDynamicConfig(sponsorID string, authorizations []string) {
  1046. config.dynamicConfigMutex.Lock()
  1047. defer config.dynamicConfigMutex.Unlock()
  1048. if sponsorID != "" {
  1049. config.sponsorID = sponsorID
  1050. }
  1051. config.authorizations = authorizations
  1052. }
  1053. // GetSponsorID returns the current client sponsor ID.
  1054. func (config *Config) GetSponsorID() string {
  1055. config.dynamicConfigMutex.Lock()
  1056. defer config.dynamicConfigMutex.Unlock()
  1057. return config.sponsorID
  1058. }
  1059. // GetAuthorizations returns the current client authorizations.
  1060. // The caller must not modify the returned slice.
  1061. func (config *Config) GetAuthorizations() []string {
  1062. config.dynamicConfigMutex.Lock()
  1063. defer config.dynamicConfigMutex.Unlock()
  1064. return config.authorizations
  1065. }
  1066. // GetPsiphonDataDirectory returns the directory under which all persistent
  1067. // files should be stored. This directory is created under
  1068. // config.DataRootDirectory. The motivation for an additional directory is that
  1069. // config.DataRootDirectory defaults to the current working directory, which may
  1070. // include non-tunnel-core files that should be excluded from directory-spanning
  1071. // operations (e.g. excluding all tunnel-core files from backup).
  1072. func (config *Config) GetPsiphonDataDirectory() string {
  1073. return filepath.Join(config.DataRootDirectory, PsiphonDataDirectoryName)
  1074. }
  1075. // GetHomePageFilename the path where the homepage notices file will be created.
  1076. func (config *Config) GetHomePageFilename() string {
  1077. return filepath.Join(config.GetPsiphonDataDirectory(), HomepageFilename)
  1078. }
  1079. // GetNoticesFilename returns the path where the notices file will be created.
  1080. // When the file is rotated it will be moved to config.GetOldNoticesFilename().
  1081. func (config *Config) GetNoticesFilename() string {
  1082. return filepath.Join(config.GetPsiphonDataDirectory(), NoticesFilename)
  1083. }
  1084. // GetOldNoticeFilename returns the path where the rotated notices file will be
  1085. // created.
  1086. func (config *Config) GetOldNoticesFilename() string {
  1087. return filepath.Join(config.GetPsiphonDataDirectory(), OldNoticesFilename)
  1088. }
  1089. // GetDataStoreDirectory returns the directory in which the persistent database
  1090. // will be stored. Created in Config.Commit(). The persistent database contains
  1091. // information such as server entries.
  1092. func (config *Config) GetDataStoreDirectory() string {
  1093. return filepath.Join(config.GetPsiphonDataDirectory(), "datastore")
  1094. }
  1095. // GetObfuscatedServerListDownloadDirectory returns the directory in which
  1096. // obfuscated remote server list downloads will be stored. Created in
  1097. // Config.Commit().
  1098. func (config *Config) GetObfuscatedServerListDownloadDirectory() string {
  1099. return filepath.Join(config.GetPsiphonDataDirectory(), "osl")
  1100. }
  1101. // GetRemoteServerListDownloadFilename returns the filename where the remote
  1102. // server list download will be stored. Data is stored in co-located files
  1103. // (RemoteServerListDownloadFilename.part*) to allow for resumable downloading.
  1104. func (config *Config) GetRemoteServerListDownloadFilename() string {
  1105. return filepath.Join(config.GetPsiphonDataDirectory(), "remote_server_list")
  1106. }
  1107. // GetUpgradeDownloadFilename specifies the filename where upgrade downloads
  1108. // will be stored. This filename is valid when UpgradeDownloadURLs
  1109. // (or UpgradeDownloadUrl) is specified. Data is stored in co-located files
  1110. // (UpgradeDownloadFilename.part*) to allow for resumable downloading.
  1111. func (config *Config) GetUpgradeDownloadFilename() string {
  1112. return filepath.Join(config.GetPsiphonDataDirectory(), UpgradeDownloadFilename)
  1113. }
  1114. // GetTapdanceDirectory returns the directory under which tapdance will create
  1115. // and manage files.
  1116. func (config *Config) GetTapdanceDirectory() string {
  1117. return filepath.Join(config.GetPsiphonDataDirectory(), "tapdance")
  1118. }
  1119. // UseUpstreamProxy indicates if an upstream proxy has been
  1120. // configured.
  1121. func (config *Config) UseUpstreamProxy() bool {
  1122. return config.UpstreamProxyURL != ""
  1123. }
  1124. // GetNetworkID returns the current network ID. When NetworkIDGetter
  1125. // is set, this calls into the host application; otherwise, a default
  1126. // value is returned.
  1127. func (config *Config) GetNetworkID() string {
  1128. return config.networkIDGetter.GetNetworkID()
  1129. }
  1130. func (config *Config) makeConfigParameters() map[string]interface{} {
  1131. // Build set of config values to apply to parameters.
  1132. //
  1133. // Note: names of some config fields such as
  1134. // StaggerConnectionWorkersMilliseconds and LimitMeekBufferSizes have
  1135. // changed in the parameters. The existing config fields are retained for
  1136. // backwards compatibility.
  1137. applyParameters := make(map[string]interface{})
  1138. // To support platform clients that configure NetworkLatencyMultiplier, set
  1139. // the NetworkLatencyMultiplierMin/NetworkLatencyMultiplierMax range to the
  1140. // specified value. Also set the older NetworkLatencyMultiplier tactic, since
  1141. // that will be used in the case of replaying with dial parameters persisted
  1142. // by an older client version.
  1143. if config.NetworkLatencyMultiplier > 0.0 {
  1144. applyParameters[parameters.NetworkLatencyMultiplier] = config.NetworkLatencyMultiplier
  1145. applyParameters[parameters.NetworkLatencyMultiplierMin] = config.NetworkLatencyMultiplier
  1146. applyParameters[parameters.NetworkLatencyMultiplierMax] = config.NetworkLatencyMultiplier
  1147. }
  1148. if config.NetworkLatencyMultiplierMin > 0.0 {
  1149. applyParameters[parameters.NetworkLatencyMultiplierMin] = config.NetworkLatencyMultiplierMin
  1150. }
  1151. if config.NetworkLatencyMultiplierMax > 0.0 {
  1152. applyParameters[parameters.NetworkLatencyMultiplierMax] = config.NetworkLatencyMultiplierMax
  1153. }
  1154. if config.NetworkLatencyMultiplierLambda > 0.0 {
  1155. applyParameters[parameters.NetworkLatencyMultiplierLambda] = config.NetworkLatencyMultiplierLambda
  1156. }
  1157. if len(config.LimitTunnelProtocols) > 0 {
  1158. applyParameters[parameters.LimitTunnelProtocols] = protocol.TunnelProtocols(config.LimitTunnelProtocols)
  1159. }
  1160. if len(config.InitialLimitTunnelProtocols) > 0 && config.InitialLimitTunnelProtocolsCandidateCount > 0 {
  1161. applyParameters[parameters.InitialLimitTunnelProtocols] = protocol.TunnelProtocols(config.InitialLimitTunnelProtocols)
  1162. applyParameters[parameters.InitialLimitTunnelProtocolsCandidateCount] = config.InitialLimitTunnelProtocolsCandidateCount
  1163. }
  1164. if len(config.LimitTLSProfiles) > 0 {
  1165. applyParameters[parameters.LimitTLSProfiles] = protocol.TunnelProtocols(config.LimitTLSProfiles)
  1166. }
  1167. if len(config.LimitQUICVersions) > 0 {
  1168. applyParameters[parameters.LimitQUICVersions] = protocol.QUICVersions(config.LimitQUICVersions)
  1169. }
  1170. if config.EstablishTunnelTimeoutSeconds != nil {
  1171. applyParameters[parameters.EstablishTunnelTimeout] = fmt.Sprintf("%ds", *config.EstablishTunnelTimeoutSeconds)
  1172. }
  1173. if config.EstablishTunnelServerAffinityGracePeriodMilliseconds != nil {
  1174. applyParameters[parameters.EstablishTunnelServerAffinityGracePeriod] = fmt.Sprintf("%dms", *config.EstablishTunnelServerAffinityGracePeriodMilliseconds)
  1175. }
  1176. if config.EstablishTunnelPausePeriodSeconds != nil {
  1177. applyParameters[parameters.EstablishTunnelPausePeriod] = fmt.Sprintf("%ds", *config.EstablishTunnelPausePeriodSeconds)
  1178. }
  1179. if config.ConnectionWorkerPoolSize != 0 {
  1180. applyParameters[parameters.ConnectionWorkerPoolSize] = config.ConnectionWorkerPoolSize
  1181. }
  1182. if config.StaggerConnectionWorkersMilliseconds > 0 {
  1183. applyParameters[parameters.StaggerConnectionWorkersPeriod] = fmt.Sprintf("%dms", config.StaggerConnectionWorkersMilliseconds)
  1184. }
  1185. if config.LimitIntensiveConnectionWorkers > 0 {
  1186. applyParameters[parameters.LimitIntensiveConnectionWorkers] = config.LimitIntensiveConnectionWorkers
  1187. }
  1188. applyParameters[parameters.MeekLimitBufferSizes] = config.LimitMeekBufferSizes
  1189. applyParameters[parameters.IgnoreHandshakeStatsRegexps] = config.IgnoreHandshakeStatsRegexps
  1190. if config.EstablishTunnelTimeoutSeconds != nil {
  1191. applyParameters[parameters.EstablishTunnelTimeout] = fmt.Sprintf("%ds", *config.EstablishTunnelTimeoutSeconds)
  1192. }
  1193. if config.FetchRemoteServerListRetryPeriodMilliseconds != nil {
  1194. applyParameters[parameters.FetchRemoteServerListRetryPeriod] = fmt.Sprintf("%dms", *config.FetchRemoteServerListRetryPeriodMilliseconds)
  1195. }
  1196. if config.FetchUpgradeRetryPeriodMilliseconds != nil {
  1197. applyParameters[parameters.FetchUpgradeRetryPeriod] = fmt.Sprintf("%dms", *config.FetchUpgradeRetryPeriodMilliseconds)
  1198. }
  1199. if !config.DisableRemoteServerListFetcher {
  1200. if config.RemoteServerListURLs != nil {
  1201. applyParameters[parameters.RemoteServerListSignaturePublicKey] = config.RemoteServerListSignaturePublicKey
  1202. applyParameters[parameters.RemoteServerListURLs] = config.RemoteServerListURLs
  1203. }
  1204. if config.ObfuscatedServerListRootURLs != nil {
  1205. applyParameters[parameters.RemoteServerListSignaturePublicKey] = config.RemoteServerListSignaturePublicKey
  1206. applyParameters[parameters.ObfuscatedServerListRootURLs] = config.ObfuscatedServerListRootURLs
  1207. }
  1208. }
  1209. applyParameters[parameters.SplitTunnelRoutesURLFormat] = config.SplitTunnelRoutesURLFormat
  1210. applyParameters[parameters.SplitTunnelRoutesSignaturePublicKey] = config.SplitTunnelRoutesSignaturePublicKey
  1211. applyParameters[parameters.SplitTunnelDNSServer] = config.SplitTunnelDNSServer
  1212. if config.UpgradeDownloadURLs != nil {
  1213. applyParameters[parameters.UpgradeDownloadClientVersionHeader] = config.UpgradeDownloadClientVersionHeader
  1214. applyParameters[parameters.UpgradeDownloadURLs] = config.UpgradeDownloadURLs
  1215. }
  1216. applyParameters[parameters.TunnelRateLimits] = config.RateLimits
  1217. if config.TransformHostNameProbability != nil {
  1218. applyParameters[parameters.TransformHostNameProbability] = *config.TransformHostNameProbability
  1219. }
  1220. if config.FragmentorProbability != nil {
  1221. applyParameters[parameters.FragmentorProbability] = *config.FragmentorProbability
  1222. }
  1223. if len(config.FragmentorLimitProtocols) > 0 {
  1224. applyParameters[parameters.FragmentorLimitProtocols] = protocol.TunnelProtocols(config.FragmentorLimitProtocols)
  1225. }
  1226. if config.FragmentorMinTotalBytes != nil {
  1227. applyParameters[parameters.FragmentorMinTotalBytes] = *config.FragmentorMinTotalBytes
  1228. }
  1229. if config.FragmentorMaxTotalBytes != nil {
  1230. applyParameters[parameters.FragmentorMaxTotalBytes] = *config.FragmentorMaxTotalBytes
  1231. }
  1232. if config.FragmentorMinWriteBytes != nil {
  1233. applyParameters[parameters.FragmentorMinWriteBytes] = *config.FragmentorMinWriteBytes
  1234. }
  1235. if config.FragmentorMaxWriteBytes != nil {
  1236. applyParameters[parameters.FragmentorMaxWriteBytes] = *config.FragmentorMaxWriteBytes
  1237. }
  1238. if config.FragmentorMinDelayMicroseconds != nil {
  1239. applyParameters[parameters.FragmentorMinDelay] = fmt.Sprintf("%dus", *config.FragmentorMinDelayMicroseconds)
  1240. }
  1241. if config.FragmentorMaxDelayMicroseconds != nil {
  1242. applyParameters[parameters.FragmentorMaxDelay] = fmt.Sprintf("%dus", *config.FragmentorMaxDelayMicroseconds)
  1243. }
  1244. if config.MeekTrafficShapingProbability != nil {
  1245. applyParameters[parameters.MeekTrafficShapingProbability] = *config.MeekTrafficShapingProbability
  1246. }
  1247. if len(config.MeekTrafficShapingLimitProtocols) > 0 {
  1248. applyParameters[parameters.MeekTrafficShapingLimitProtocols] = protocol.TunnelProtocols(config.MeekTrafficShapingLimitProtocols)
  1249. }
  1250. if config.MeekMinTLSPadding != nil {
  1251. applyParameters[parameters.MeekMinTLSPadding] = *config.MeekMinTLSPadding
  1252. }
  1253. if config.MeekMaxTLSPadding != nil {
  1254. applyParameters[parameters.MeekMaxTLSPadding] = *config.MeekMaxTLSPadding
  1255. }
  1256. if config.MeekMinLimitRequestPayloadLength != nil {
  1257. applyParameters[parameters.MeekMinLimitRequestPayloadLength] = *config.MeekMinLimitRequestPayloadLength
  1258. }
  1259. if config.MeekMaxLimitRequestPayloadLength != nil {
  1260. applyParameters[parameters.MeekMaxLimitRequestPayloadLength] = *config.MeekMaxLimitRequestPayloadLength
  1261. }
  1262. if config.MeekRedialTLSProbability != nil {
  1263. applyParameters[parameters.MeekRedialTLSProbability] = *config.MeekRedialTLSProbability
  1264. }
  1265. if config.ObfuscatedSSHMinPadding != nil {
  1266. applyParameters[parameters.ObfuscatedSSHMinPadding] = *config.ObfuscatedSSHMinPadding
  1267. }
  1268. if config.ObfuscatedSSHMaxPadding != nil {
  1269. applyParameters[parameters.ObfuscatedSSHMaxPadding] = *config.ObfuscatedSSHMaxPadding
  1270. }
  1271. if config.LivenessTestMinUpstreamBytes != nil {
  1272. applyParameters[parameters.LivenessTestMinUpstreamBytes] = *config.LivenessTestMinUpstreamBytes
  1273. }
  1274. if config.LivenessTestMaxUpstreamBytes != nil {
  1275. applyParameters[parameters.LivenessTestMaxUpstreamBytes] = *config.LivenessTestMaxUpstreamBytes
  1276. }
  1277. if config.LivenessTestMinDownstreamBytes != nil {
  1278. applyParameters[parameters.LivenessTestMinDownstreamBytes] = *config.LivenessTestMinDownstreamBytes
  1279. }
  1280. if config.LivenessTestMaxDownstreamBytes != nil {
  1281. applyParameters[parameters.LivenessTestMaxDownstreamBytes] = *config.LivenessTestMaxDownstreamBytes
  1282. }
  1283. if config.ReplayCandidateCount != nil {
  1284. applyParameters[parameters.ReplayCandidateCount] = *config.ReplayCandidateCount
  1285. }
  1286. if config.ReplayDialParametersTTLSeconds != nil {
  1287. applyParameters[parameters.ReplayDialParametersTTL] = fmt.Sprintf("%ds", *config.ReplayDialParametersTTLSeconds)
  1288. }
  1289. if config.ReplayTargetUpstreamBytes != nil {
  1290. applyParameters[parameters.ReplayTargetUpstreamBytes] = *config.ReplayTargetUpstreamBytes
  1291. }
  1292. if config.ReplayTargetDownstreamBytes != nil {
  1293. applyParameters[parameters.ReplayTargetDownstreamBytes] = *config.ReplayTargetDownstreamBytes
  1294. }
  1295. if config.ReplayTargetTunnelDurationSeconds != nil {
  1296. applyParameters[parameters.ReplayTargetTunnelDuration] = fmt.Sprintf("%ds", *config.ReplayTargetTunnelDurationSeconds)
  1297. }
  1298. if config.ReplayLaterRoundMoveToFrontProbability != nil {
  1299. applyParameters[parameters.ReplayLaterRoundMoveToFrontProbability] = *config.ReplayLaterRoundMoveToFrontProbability
  1300. }
  1301. if config.ReplayRetainFailedProbability != nil {
  1302. applyParameters[parameters.ReplayRetainFailedProbability] = *config.ReplayRetainFailedProbability
  1303. }
  1304. if config.UseOnlyCustomTLSProfiles != nil {
  1305. applyParameters[parameters.UseOnlyCustomTLSProfiles] = *config.UseOnlyCustomTLSProfiles
  1306. }
  1307. if config.CustomTLSProfiles != nil {
  1308. applyParameters[parameters.CustomTLSProfiles] = config.CustomTLSProfiles
  1309. }
  1310. if config.SelectRandomizedTLSProfileProbability != nil {
  1311. applyParameters[parameters.SelectRandomizedTLSProfileProbability] = *config.SelectRandomizedTLSProfileProbability
  1312. }
  1313. if config.NoDefaultTLSSessionIDProbability != nil {
  1314. applyParameters[parameters.NoDefaultTLSSessionIDProbability] = *config.NoDefaultTLSSessionIDProbability
  1315. }
  1316. if config.ApplicationParameters != nil {
  1317. applyParameters[parameters.ApplicationParameters] = config.ApplicationParameters
  1318. }
  1319. if len(config.FeedbackUploadURLs) > 0 {
  1320. applyParameters[parameters.FeedbackUploadURLs] = config.FeedbackUploadURLs
  1321. }
  1322. if config.FeedbackEncryptionPublicKey != "" {
  1323. applyParameters[parameters.FeedbackEncryptionPublicKey] = config.FeedbackEncryptionPublicKey
  1324. }
  1325. return applyParameters
  1326. }
  1327. func (config *Config) setDialParametersHash() {
  1328. // Calculate and store a hash of the config values that may impact
  1329. // dial parameters. This hash is used as part of the dial parameters
  1330. // replay mechanism to detect when persisted dial parameters should
  1331. // be discarded due to conflicting config changes.
  1332. //
  1333. // MD5 hash is used solely as a data checksum and not for any security
  1334. // purpose; serialization is not strictly unambiguous.
  1335. hash := md5.New()
  1336. if len(config.LimitTunnelProtocols) > 0 {
  1337. for _, protocol := range config.LimitTunnelProtocols {
  1338. hash.Write([]byte(protocol))
  1339. }
  1340. }
  1341. if len(config.InitialLimitTunnelProtocols) > 0 && config.InitialLimitTunnelProtocolsCandidateCount > 0 {
  1342. for _, protocol := range config.InitialLimitTunnelProtocols {
  1343. hash.Write([]byte(protocol))
  1344. }
  1345. binary.Write(hash, binary.LittleEndian, int64(config.InitialLimitTunnelProtocolsCandidateCount))
  1346. }
  1347. if len(config.LimitTLSProfiles) > 0 {
  1348. for _, profile := range config.LimitTLSProfiles {
  1349. hash.Write([]byte(profile))
  1350. }
  1351. }
  1352. if len(config.LimitQUICVersions) > 0 {
  1353. for _, version := range config.LimitQUICVersions {
  1354. hash.Write([]byte(version))
  1355. }
  1356. }
  1357. // Whether a custom User-Agent is specified is a binary flag: when not set,
  1358. // the replay dial parameters value applies. When set, external
  1359. // considerations apply.
  1360. if _, ok := config.CustomHeaders["User-Agent"]; ok {
  1361. hash.Write([]byte{1})
  1362. }
  1363. if config.UpstreamProxyURL != "" {
  1364. hash.Write([]byte(config.UpstreamProxyURL))
  1365. }
  1366. if config.TransformHostNameProbability != nil {
  1367. binary.Write(hash, binary.LittleEndian, *config.TransformHostNameProbability)
  1368. }
  1369. if config.FragmentorProbability != nil {
  1370. binary.Write(hash, binary.LittleEndian, *config.FragmentorProbability)
  1371. }
  1372. if len(config.FragmentorLimitProtocols) > 0 {
  1373. for _, protocol := range config.FragmentorLimitProtocols {
  1374. hash.Write([]byte(protocol))
  1375. }
  1376. }
  1377. if config.FragmentorMinTotalBytes != nil {
  1378. binary.Write(hash, binary.LittleEndian, int64(*config.FragmentorMinTotalBytes))
  1379. }
  1380. if config.FragmentorMaxTotalBytes != nil {
  1381. binary.Write(hash, binary.LittleEndian, int64(*config.FragmentorMaxTotalBytes))
  1382. }
  1383. if config.FragmentorMinWriteBytes != nil {
  1384. binary.Write(hash, binary.LittleEndian, int64(*config.FragmentorMinWriteBytes))
  1385. }
  1386. if config.FragmentorMaxWriteBytes != nil {
  1387. binary.Write(hash, binary.LittleEndian, int64(*config.FragmentorMaxWriteBytes))
  1388. }
  1389. if config.FragmentorMinDelayMicroseconds != nil {
  1390. binary.Write(hash, binary.LittleEndian, int64(*config.FragmentorMinDelayMicroseconds))
  1391. }
  1392. if config.FragmentorMaxDelayMicroseconds != nil {
  1393. binary.Write(hash, binary.LittleEndian, int64(*config.FragmentorMaxDelayMicroseconds))
  1394. }
  1395. if config.MeekTrafficShapingProbability != nil {
  1396. binary.Write(hash, binary.LittleEndian, int64(*config.MeekTrafficShapingProbability))
  1397. }
  1398. if len(config.MeekTrafficShapingLimitProtocols) > 0 {
  1399. for _, protocol := range config.MeekTrafficShapingLimitProtocols {
  1400. hash.Write([]byte(protocol))
  1401. }
  1402. }
  1403. if config.MeekMinLimitRequestPayloadLength != nil {
  1404. binary.Write(hash, binary.LittleEndian, int64(*config.MeekMinLimitRequestPayloadLength))
  1405. }
  1406. if config.MeekMaxLimitRequestPayloadLength != nil {
  1407. binary.Write(hash, binary.LittleEndian, int64(*config.MeekMaxLimitRequestPayloadLength))
  1408. }
  1409. if config.MeekRedialTLSProbability != nil {
  1410. binary.Write(hash, binary.LittleEndian, *config.MeekRedialTLSProbability)
  1411. }
  1412. if config.ObfuscatedSSHMinPadding != nil {
  1413. binary.Write(hash, binary.LittleEndian, int64(*config.ObfuscatedSSHMinPadding))
  1414. }
  1415. if config.ObfuscatedSSHMaxPadding != nil {
  1416. binary.Write(hash, binary.LittleEndian, int64(*config.ObfuscatedSSHMaxPadding))
  1417. }
  1418. if config.LivenessTestMinUpstreamBytes != nil {
  1419. binary.Write(hash, binary.LittleEndian, int64(*config.LivenessTestMinUpstreamBytes))
  1420. }
  1421. if config.LivenessTestMaxUpstreamBytes != nil {
  1422. binary.Write(hash, binary.LittleEndian, int64(*config.LivenessTestMaxUpstreamBytes))
  1423. }
  1424. if config.LivenessTestMinDownstreamBytes != nil {
  1425. binary.Write(hash, binary.LittleEndian, int64(*config.LivenessTestMinDownstreamBytes))
  1426. }
  1427. if config.LivenessTestMaxDownstreamBytes != nil {
  1428. binary.Write(hash, binary.LittleEndian, int64(*config.LivenessTestMaxDownstreamBytes))
  1429. }
  1430. binary.Write(hash, binary.LittleEndian, config.NetworkLatencyMultiplierMin)
  1431. binary.Write(hash, binary.LittleEndian, config.NetworkLatencyMultiplierMax)
  1432. binary.Write(hash, binary.LittleEndian, config.NetworkLatencyMultiplierLambda)
  1433. if config.UseOnlyCustomTLSProfiles != nil {
  1434. binary.Write(hash, binary.LittleEndian, *config.UseOnlyCustomTLSProfiles)
  1435. }
  1436. for _, customTLSProfile := range config.CustomTLSProfiles {
  1437. // Assumes consistent definition for a given profile name
  1438. hash.Write([]byte(customTLSProfile.Name))
  1439. }
  1440. if config.SelectRandomizedTLSProfileProbability != nil {
  1441. binary.Write(hash, binary.LittleEndian, *config.SelectRandomizedTLSProfileProbability)
  1442. }
  1443. if config.NoDefaultTLSSessionIDProbability != nil {
  1444. binary.Write(hash, binary.LittleEndian, *config.NoDefaultTLSSessionIDProbability)
  1445. }
  1446. config.dialParametersHash = hash.Sum(nil)
  1447. }
  1448. func promoteLegacyTransferURL(URL string) parameters.TransferURLs {
  1449. transferURLs := make(parameters.TransferURLs, 1)
  1450. transferURLs[0] = &parameters.TransferURL{
  1451. URL: base64.StdEncoding.EncodeToString([]byte(URL)),
  1452. SkipVerify: false,
  1453. OnlyAfterAttempts: 0,
  1454. }
  1455. return transferURLs
  1456. }
  1457. type loggingDeviceBinder struct {
  1458. d DeviceBinder
  1459. }
  1460. func newLoggingDeviceBinder(d DeviceBinder) *loggingDeviceBinder {
  1461. return &loggingDeviceBinder{d: d}
  1462. }
  1463. func (d *loggingDeviceBinder) BindToDevice(fileDescriptor int) (string, error) {
  1464. deviceInfo, err := d.d.BindToDevice(fileDescriptor)
  1465. if err == nil && deviceInfo != "" {
  1466. NoticeBindToDevice(deviceInfo)
  1467. }
  1468. return deviceInfo, err
  1469. }
  1470. type staticNetworkGetter struct {
  1471. networkID string
  1472. }
  1473. func newStaticNetworkGetter(networkID string) *staticNetworkGetter {
  1474. return &staticNetworkGetter{networkID: networkID}
  1475. }
  1476. func (n *staticNetworkGetter) GetNetworkID() string {
  1477. return n.networkID
  1478. }
  1479. type loggingNetworkIDGetter struct {
  1480. n NetworkIDGetter
  1481. }
  1482. func newLoggingNetworkIDGetter(n NetworkIDGetter) *loggingNetworkIDGetter {
  1483. return &loggingNetworkIDGetter{n: n}
  1484. }
  1485. func (n *loggingNetworkIDGetter) GetNetworkID() string {
  1486. networkID := n.n.GetNetworkID()
  1487. // All PII must appear after the initial "-"
  1488. // See: https://godoc.org/github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon#NetworkIDGetter
  1489. logNetworkID := networkID
  1490. index := strings.Index(logNetworkID, "-")
  1491. if index != -1 {
  1492. logNetworkID = logNetworkID[:index]
  1493. }
  1494. if len(logNetworkID)+1 < len(networkID) {
  1495. // Indicate when additional network info was present after the first "-".
  1496. logNetworkID += "+[redacted]"
  1497. }
  1498. NoticeNetworkID(logNetworkID)
  1499. return networkID
  1500. }
  1501. // migrationsFromLegacyNoticeFilePaths returns the file migrations which must be
  1502. // performed to move notice files from legacy file paths, which were configured
  1503. // with the legacy config fields HomepageNoticesFilename and
  1504. // RotatingNoticesFilename, to the new file paths used by Psiphon which exist
  1505. // under the data root directory.
  1506. func migrationsFromLegacyNoticeFilePaths(config *Config) []common.FileMigration {
  1507. var noticeMigrations []common.FileMigration
  1508. if config.MigrateHomepageNoticesFilename != "" {
  1509. noticeMigrations = append(noticeMigrations, common.FileMigration{
  1510. OldPath: config.MigrateHomepageNoticesFilename,
  1511. NewPath: config.GetHomePageFilename(),
  1512. })
  1513. }
  1514. if config.MigrateRotatingNoticesFilename != "" {
  1515. migrations := []common.FileMigration{
  1516. {
  1517. OldPath: config.MigrateRotatingNoticesFilename,
  1518. NewPath: config.GetNoticesFilename(),
  1519. IsDir: false,
  1520. },
  1521. {
  1522. OldPath: config.MigrateRotatingNoticesFilename + ".1",
  1523. NewPath: config.GetNoticesFilename() + ".1",
  1524. },
  1525. }
  1526. noticeMigrations = append(noticeMigrations, migrations...)
  1527. }
  1528. return noticeMigrations
  1529. }
  1530. // migrationsFromLegacyFilePaths returns the file migrations which must be
  1531. // performed to move files from legacy file paths, which were configured with
  1532. // legacy config fields, to the new file paths used by Psiphon which exist
  1533. // under the data root directory.
  1534. func migrationsFromLegacyFilePaths(config *Config) ([]common.FileMigration, error) {
  1535. migrations := []common.FileMigration{
  1536. {
  1537. OldPath: filepath.Join(config.MigrateDataStoreDirectory, "psiphon.boltdb"),
  1538. NewPath: filepath.Join(config.GetDataStoreDirectory(), "psiphon.boltdb"),
  1539. },
  1540. {
  1541. OldPath: filepath.Join(config.MigrateDataStoreDirectory, "psiphon.boltdb.lock"),
  1542. NewPath: filepath.Join(config.GetDataStoreDirectory(), "psiphon.boltdb.lock"),
  1543. },
  1544. {
  1545. OldPath: filepath.Join(config.MigrateDataStoreDirectory, "tapdance"),
  1546. NewPath: filepath.Join(config.GetTapdanceDirectory(), "tapdance"),
  1547. IsDir: true,
  1548. },
  1549. }
  1550. if config.MigrateRemoteServerListDownloadFilename != "" {
  1551. // Migrate remote server list files
  1552. rslMigrations := []common.FileMigration{
  1553. {
  1554. OldPath: config.MigrateRemoteServerListDownloadFilename,
  1555. NewPath: config.GetRemoteServerListDownloadFilename(),
  1556. },
  1557. {
  1558. OldPath: config.MigrateRemoteServerListDownloadFilename + ".part",
  1559. NewPath: config.GetRemoteServerListDownloadFilename() + ".part",
  1560. },
  1561. {
  1562. OldPath: config.MigrateRemoteServerListDownloadFilename + ".part.etag",
  1563. NewPath: config.GetRemoteServerListDownloadFilename() + ".part.etag",
  1564. },
  1565. }
  1566. migrations = append(migrations, rslMigrations...)
  1567. }
  1568. if config.MigrateObfuscatedServerListDownloadDirectory != "" {
  1569. // Migrate OSL registry file and downloads
  1570. oslFileRegex, err := regexp.Compile(`^osl-.+$`)
  1571. if err != nil {
  1572. return nil, errors.TraceMsg(err, "failed to compile regex for osl files")
  1573. }
  1574. files, err := ioutil.ReadDir(config.MigrateObfuscatedServerListDownloadDirectory)
  1575. if err != nil {
  1576. NoticeWarning("Migration: failed to read directory %s with error %s", config.MigrateObfuscatedServerListDownloadDirectory, err)
  1577. } else {
  1578. for _, file := range files {
  1579. if oslFileRegex.MatchString(file.Name()) {
  1580. fileMigration := common.FileMigration{
  1581. OldPath: filepath.Join(config.MigrateObfuscatedServerListDownloadDirectory, file.Name()),
  1582. NewPath: filepath.Join(config.GetObfuscatedServerListDownloadDirectory(), file.Name()),
  1583. }
  1584. migrations = append(migrations, fileMigration)
  1585. }
  1586. }
  1587. }
  1588. }
  1589. if config.MigrateUpgradeDownloadFilename != "" {
  1590. // Migrate downloaded upgrade files
  1591. oldUpgradeDownloadFilename := filepath.Base(config.MigrateUpgradeDownloadFilename)
  1592. // Create regex for:
  1593. // <old_upgrade_download_filename>
  1594. // <old_upgrade_download_filename>.<client_version_number>
  1595. // <old_upgrade_download_filename>.<client_version_number>.part
  1596. // <old_upgrade_download_filename>.<client_version_number>.part.etag
  1597. upgradeDownloadFileRegex, err := regexp.Compile(`^` + oldUpgradeDownloadFilename + `(\.\d+(\.part(\.etag)?)?)?$`)
  1598. if err != nil {
  1599. return nil, errors.TraceMsg(err, "failed to compile regex for upgrade files")
  1600. }
  1601. upgradeDownloadDir := filepath.Dir(config.MigrateUpgradeDownloadFilename)
  1602. files, err := ioutil.ReadDir(upgradeDownloadDir)
  1603. if err != nil {
  1604. NoticeWarning("Migration: failed to read directory %s with error %s", upgradeDownloadDir, err)
  1605. } else {
  1606. for _, file := range files {
  1607. if upgradeDownloadFileRegex.MatchString(file.Name()) {
  1608. oldFileSuffix := strings.TrimPrefix(file.Name(), oldUpgradeDownloadFilename)
  1609. fileMigration := common.FileMigration{
  1610. OldPath: filepath.Join(upgradeDownloadDir, file.Name()),
  1611. NewPath: config.GetUpgradeDownloadFilename() + oldFileSuffix,
  1612. }
  1613. migrations = append(migrations, fileMigration)
  1614. }
  1615. }
  1616. }
  1617. }
  1618. return migrations, nil
  1619. }