config.go 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  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. "encoding/base64"
  22. "encoding/json"
  23. "errors"
  24. "fmt"
  25. "net/http"
  26. "os"
  27. "strconv"
  28. "strings"
  29. "sync"
  30. "unicode"
  31. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  34. )
  35. const (
  36. TUNNEL_POOL_SIZE = 1
  37. )
  38. // Config is the Psiphon configuration specified by the application. This
  39. // configuration controls the behavior of the core tunnel functionality.
  40. //
  41. // To distinguish omitted timeout params from explicit 0 value timeout params,
  42. // corresponding fieldss are int pointers. nil means no value was supplied and
  43. // to use the default; a non-nil pointer to 0 means no timeout.
  44. type Config struct {
  45. // DataStoreDirectory is the directory in which to store the persistent
  46. // database, which contains information such as server entries. By
  47. // default, current working directory.
  48. //
  49. // Warning: If the datastore file, DataStoreDirectory/DATA_STORE_FILENAME,
  50. // exists but fails to open for any reason (checksum error, unexpected
  51. // file format, etc.) it will be deleted in order to pave a new datastore
  52. // and continue running.
  53. DataStoreDirectory string
  54. // PropagationChannelId is a string identifier which indicates how the
  55. // Psiphon client was distributed. This parameter is required. This value
  56. // is supplied by and depends on the Psiphon Network, and is typically
  57. // embedded in the client binary.
  58. PropagationChannelId string
  59. // SponsorId is a string identifier which indicates who is sponsoring this
  60. // Psiphon client. One purpose of this value is to determine the home
  61. // pages for display. This parameter is required. This value is supplied
  62. // by and depends on the Psiphon Network, and is typically embedded in the
  63. // client binary.
  64. SponsorId string
  65. // ClientVersion is the client version number that the client reports to
  66. // the server. The version number refers to the host client application,
  67. // not the core tunnel library. One purpose of this value is to enable
  68. // automatic updates. This value is supplied by and depends on the Psiphon
  69. // Network, and is typically embedded in the client binary.
  70. //
  71. // Note that sending a ClientPlatform string which includes "windows"
  72. // (case insensitive) and a ClientVersion of <= 44 will cause an error in
  73. // processing the response to DoConnectedRequest calls.
  74. ClientVersion string
  75. // ClientPlatform is the client platform ("Windows", "Android", etc.) that
  76. // the client reports to the server.
  77. ClientPlatform string
  78. // TunnelWholeDevice is a flag that is passed through to the handshake
  79. // request for stats purposes. Set to 1 when the host application is
  80. // tunneling the whole device, 0 otherwise.
  81. TunnelWholeDevice int
  82. // EgressRegion is a ISO 3166-1 alpha-2 country code which indicates which
  83. // country to egress from. For the default, "", the best performing server
  84. // in any country is selected.
  85. EgressRegion string
  86. // ListenInterface specifies which interface to listen on. If no
  87. // interface is provided then listen on 127.0.0.1. If 'any' is provided
  88. // then use 0.0.0.0. If there are multiple IP addresses on an interface
  89. // use the first IPv4 address.
  90. ListenInterface string
  91. // DisableLocalSocksProxy disables running the local SOCKS proxy.
  92. DisableLocalSocksProxy bool
  93. // LocalSocksProxyPort specifies a port number for the local SOCKS proxy
  94. // running at 127.0.0.1. For the default value, 0, the system selects a
  95. // free port (a notice reporting the selected port is emitted).
  96. LocalSocksProxyPort int
  97. // LocalHttpProxyPort specifies a port number for the local HTTP proxy
  98. // running at 127.0.0.1. For the default value, 0, the system selects a
  99. // free port (a notice reporting the selected port is emitted).
  100. LocalHttpProxyPort int
  101. // DisableLocalHTTPProxy disables running the local HTTP proxy.
  102. DisableLocalHTTPProxy bool
  103. // NetworkLatencyMultiplier is a multiplier that is to be applied to
  104. // default network event timeouts. Set this to tune performance for
  105. // slow networks.
  106. // When set, must be >= 1.0.
  107. NetworkLatencyMultiplier float64
  108. // TunnelProtocol indicates which protocol to use. For the default, "",
  109. // all protocols are used.
  110. //
  111. // Deprecated: Use LimitTunnelProtocols. When LimitTunnelProtocols is not
  112. // nil, this parameter is ignored.
  113. TunnelProtocol string
  114. // LimitTunnelProtocols indicates which protocols to use. Valid values
  115. // include:
  116. // "SSH", "OSSH", "UNFRONTED-MEEK-OSSH", "UNFRONTED-MEEK-HTTPS-OSSH",
  117. // "UNFRONTED-MEEK-SESSION-TICKET-OSSH", "FRONTED-MEEK-OSSH",
  118. // "FRONTED-MEEK-HTTP-OSSH", "QUIC-OSSH", "MARIONETTE-OSSH", and
  119. // "TAPDANCE-OSSH".
  120. // For the default, an empty list, all protocols are used.
  121. LimitTunnelProtocols []string
  122. // InitialLimitTunnelProtocols is an optional initial phase of limited
  123. // protocols for the first InitialLimitTunnelProtocolsCandidateCount
  124. // candidates; after these candidates, LimitTunnelProtocols applies.
  125. //
  126. // For the default, an empty list, InitialLimitTunnelProtocols is off.
  127. InitialLimitTunnelProtocols []string
  128. // InitialLimitTunnelProtocolsCandidateCount is the number of candidates
  129. // to which InitialLimitTunnelProtocols is applied instead of
  130. // LimitTunnelProtocols.
  131. //
  132. // For the default, 0, InitialLimitTunnelProtocols is off.
  133. InitialLimitTunnelProtocolsCandidateCount int
  134. // LimitTLSProfiles indicates which TLS profiles to select from. Valid
  135. // values are listed in protocols.SupportedTLSProfiles.
  136. // For the default, an empty list, all profiles are candidates for
  137. // selection.
  138. LimitTLSProfiles []string
  139. // LimitQUICVersions indicates which QUIC versions to select from. Valid
  140. // values are listed in protocols.SupportedQUICVersions.
  141. // For the default, an empty list, all versions are candidates for
  142. // selection.
  143. LimitQUICVersions []string
  144. // EstablishTunnelTimeoutSeconds specifies a time limit after which to
  145. // halt the core tunnel controller if no tunnel has been established. The
  146. // default is parameters.EstablishTunnelTimeoutSeconds.
  147. EstablishTunnelTimeoutSeconds *int
  148. // EstablishTunnelPausePeriodSeconds specifies the delay between attempts
  149. // to establish tunnels. Briefly pausing allows for network conditions to
  150. // improve and for asynchronous operations such as fetch remote server
  151. // list to complete. If omitted, a default value is used. This value is
  152. // typical overridden for testing.
  153. EstablishTunnelPausePeriodSeconds *int
  154. // ConnectionWorkerPoolSize specifies how many connection attempts to
  155. // attempt in parallel. If omitted of when 0, a default is used; this is
  156. // recommended.
  157. ConnectionWorkerPoolSize int
  158. // TunnelPoolSize specifies how many tunnels to run in parallel. Port
  159. // forwards are multiplexed over multiple tunnels. If omitted or when 0,
  160. // the default is TUNNEL_POOL_SIZE, which is recommended.
  161. TunnelPoolSize int
  162. // StaggerConnectionWorkersMilliseconds adds a specified delay before
  163. // making each server candidate available to connection workers. This
  164. // option is enabled when StaggerConnectionWorkersMilliseconds > 0.
  165. StaggerConnectionWorkersMilliseconds int
  166. // LimitIntensiveConnectionWorkers limits the number of concurrent
  167. // connection workers attempting connections with resource intensive
  168. // protocols. This option is enabled when LimitIntensiveConnectionWorkers
  169. // > 0.
  170. LimitIntensiveConnectionWorkers int
  171. // LimitMeekBufferSizes selects smaller buffers for meek protocols.
  172. LimitMeekBufferSizes bool
  173. // IgnoreHandshakeStatsRegexps skips compiling and using stats regexes.
  174. IgnoreHandshakeStatsRegexps bool
  175. // UpstreamProxyURL is a URL specifying an upstream proxy to use for all
  176. // outbound connections. The URL should include proxy type and
  177. // authentication information, as required. See example URLs here:
  178. // https://github.com/Psiphon-Labs/psiphon-tunnel-core/tree/master/psiphon/upstreamproxy
  179. UpstreamProxyURL string
  180. // CustomHeaders is a set of additional arbitrary HTTP headers that are
  181. // added to all plaintext HTTP requests and requests made through an HTTP
  182. // upstream proxy when specified by UpstreamProxyURL.
  183. CustomHeaders http.Header
  184. // Deprecated: Use CustomHeaders. When CustomHeaders is not nil, this
  185. // parameter is ignored.
  186. UpstreamProxyCustomHeaders http.Header
  187. // NetworkConnectivityChecker is an interface that enables tunnel-core to
  188. // call into the host application to check for network connectivity. See:
  189. // NetworkConnectivityChecker doc.
  190. //
  191. // This parameter is only applicable to library deployments.
  192. NetworkConnectivityChecker NetworkConnectivityChecker
  193. // DeviceBinder is an interface that enables tunnel-core to call into the
  194. // host application to bind sockets to specific devices. See: DeviceBinder
  195. // doc.
  196. //
  197. // This parameter is only applicable to library deployments.
  198. DeviceBinder DeviceBinder
  199. // IPv6Synthesizer is an interface that allows tunnel-core to call into
  200. // the host application to synthesize IPv6 addresses. See: IPv6Synthesizer
  201. // doc.
  202. //
  203. // This parameter is only applicable to library deployments.
  204. IPv6Synthesizer IPv6Synthesizer
  205. // DnsServerGetter is an interface that enables tunnel-core to call into
  206. // the host application to discover the native network DNS server
  207. // settings. See: DnsServerGetter doc.
  208. //
  209. // This parameter is only applicable to library deployments.
  210. DnsServerGetter DnsServerGetter
  211. // NetworkIDGetter in an interface that enables tunnel-core to call into
  212. // the host application to get an identifier for the host's current active
  213. // network. See: NetworkIDGetter doc.
  214. //
  215. // This parameter is only applicable to library deployments.
  216. NetworkIDGetter NetworkIDGetter
  217. // NetworkID, when not blank, is used as the identifier for the host's
  218. // current active network.
  219. // NetworkID is ignored when NetworkIDGetter is set.
  220. NetworkID string
  221. // DisableTactics disables tactics operations including requests, payload
  222. // handling, and application of parameters.
  223. DisableTactics bool
  224. // TransformHostNames specifies whether to use hostname transformation
  225. // circumvention strategies. Set to "always" to always transform, "never"
  226. // to never transform, and "", the default, for the default transformation
  227. // strategy.
  228. TransformHostNames string
  229. // TargetServerEntry is an encoded server entry. When specified, this
  230. // server entry is used exclusively and all other known servers are
  231. // ignored.
  232. TargetServerEntry string
  233. // DisableApi disables Psiphon server API calls including handshake,
  234. // connected, status, etc. This is used for special case temporary tunnels
  235. // (Windows VPN mode).
  236. DisableApi bool
  237. // TargetApiProtocol specifies whether to force use of "ssh" or "web" API
  238. // protocol. When blank, the default, the optimal API protocol is used.
  239. // Note that this capability check is not applied before the
  240. // "CandidateServers" count is emitted.
  241. //
  242. // This parameter is intended for testing and debugging only. Not all
  243. // parameters are supported in the legacy "web" API protocol, including
  244. // speed test samples.
  245. TargetApiProtocol string
  246. // RemoteServerListUrl is a URL which specifies a location to fetch out-
  247. // of-band server entries. This facility is used when a tunnel cannot be
  248. // established to known servers. This value is supplied by and depends on
  249. // the Psiphon Network, and is typically embedded in the client binary.
  250. //
  251. // Deprecated: Use RemoteServerListURLs. When RemoteServerListURLs is not
  252. // nil, this parameter is ignored.
  253. RemoteServerListUrl string
  254. // RemoteServerListURLs is list of URLs which specify locations to fetch
  255. // out-of-band server entries. This facility is used when a tunnel cannot
  256. // be established to known servers. This value is supplied by and depends
  257. // on the Psiphon Network, and is typically embedded in the client binary.
  258. // All URLs must point to the same entity with the same ETag. At least one
  259. // DownloadURL must have OnlyAfterAttempts = 0.
  260. RemoteServerListURLs parameters.DownloadURLs
  261. // RemoteServerListDownloadFilename specifies a target filename for
  262. // storing the remote server list download. Data is stored in co-located
  263. // files (RemoteServerListDownloadFilename.part*) to allow for resumable
  264. // downloading.
  265. RemoteServerListDownloadFilename string
  266. // RemoteServerListSignaturePublicKey specifies a public key that's used
  267. // to authenticate the remote server list payload. This value is supplied
  268. // by and depends on the Psiphon Network, and is typically embedded in the
  269. // client binary.
  270. RemoteServerListSignaturePublicKey string
  271. // DisableRemoteServerListFetcher disables fetching remote server lists.
  272. // This is used for special case temporary tunnels.
  273. DisableRemoteServerListFetcher bool
  274. // FetchRemoteServerListRetryPeriodMilliseconds specifies the delay before
  275. // resuming a remote server list download after a failure. If omitted, a
  276. // default value is used. This value is typical overridden for testing.
  277. FetchRemoteServerListRetryPeriodMilliseconds *int
  278. // ObfuscatedServerListRootURL is a URL which specifies the root location
  279. // from which to fetch obfuscated server list files. This value is
  280. // supplied by and depends on the Psiphon Network, and is typically
  281. // embedded in the client binary.
  282. //
  283. // Deprecated: Use ObfuscatedServerListRootURLs. When
  284. // ObfuscatedServerListRootURLs is not nil, this parameter is ignored.
  285. ObfuscatedServerListRootURL string
  286. // ObfuscatedServerListRootURLs is a list of URLs which specify root
  287. // locations from which to fetch obfuscated server list files. This value
  288. // is supplied by and depends on the Psiphon Network, and is typically
  289. // embedded in the client binary. All URLs must point to the same entity
  290. // with the same ETag. At least one DownloadURL must have
  291. // OnlyAfterAttempts = 0.
  292. ObfuscatedServerListRootURLs parameters.DownloadURLs
  293. // ObfuscatedServerListDownloadDirectory specifies a target directory for
  294. // storing the obfuscated remote server list downloads. Data is stored in
  295. // co-located files (<OSL filename>.part*) to allow for resumable
  296. // downloading.
  297. ObfuscatedServerListDownloadDirectory string
  298. // SplitTunnelRoutesURLFormat is a URL which specifies the location of a
  299. // routes file to use for split tunnel mode. The URL must include a
  300. // placeholder for the client region to be supplied. Split tunnel mode
  301. // uses the routes file to classify port forward destinations as foreign
  302. // or domestic and does not tunnel domestic destinations. Split tunnel
  303. // mode is on when all the SplitTunnel parameters are supplied. This value
  304. // is supplied by and depends on the Psiphon Network, and is typically
  305. // embedded in the client binary.
  306. SplitTunnelRoutesURLFormat string
  307. // SplitTunnelRoutesSignaturePublicKey specifies a public key that's used
  308. // to authenticate the split tunnel routes payload. This value is supplied
  309. // by and depends on the Psiphon Network, and is typically embedded in the
  310. // client binary.
  311. SplitTunnelRoutesSignaturePublicKey string
  312. // SplitTunnelDNSServer specifies a DNS server to use when resolving port
  313. // forward target domain names to IP addresses for classification. The DNS
  314. // server must support TCP requests.
  315. SplitTunnelDNSServer string
  316. // UpgradeDownloadUrl specifies a URL from which to download a host client
  317. // upgrade file, when one is available. The core tunnel controller
  318. // provides a resumable download facility which downloads this resource
  319. // and emits a notice when complete. This value is supplied by and depends
  320. // on the Psiphon Network, and is typically embedded in the client binary.
  321. //
  322. // Deprecated: Use UpgradeDownloadURLs. When UpgradeDownloadURLs is not
  323. // nil, this parameter is ignored.
  324. UpgradeDownloadUrl string
  325. // UpgradeDownloadURLs is list of URLs which specify locations from which
  326. // to download a host client upgrade file, when one is available. The core
  327. // tunnel controller provides a resumable download facility which
  328. // downloads this resource and emits a notice when complete. This value is
  329. // supplied by and depends on the Psiphon Network, and is typically
  330. // embedded in the client binary. All URLs must point to the same entity
  331. // with the same ETag. At least one DownloadURL must have
  332. // OnlyAfterAttempts = 0.
  333. UpgradeDownloadURLs parameters.DownloadURLs
  334. // UpgradeDownloadClientVersionHeader specifies the HTTP header name for
  335. // the entity at UpgradeDownloadURLs which specifies the client version
  336. // (an integer value). A HEAD request may be made to check the version
  337. // number available at UpgradeDownloadURLs.
  338. // UpgradeDownloadClientVersionHeader is required when UpgradeDownloadURLs
  339. // is specified.
  340. UpgradeDownloadClientVersionHeader string
  341. // UpgradeDownloadFilename is the local target filename for an upgrade
  342. // download. This parameter is required when UpgradeDownloadURLs (or
  343. // UpgradeDownloadUrl) is specified. Data is stored in co-located files
  344. // (UpgradeDownloadFilename.part*) to allow for resumable downloading.
  345. UpgradeDownloadFilename string
  346. // FetchUpgradeRetryPeriodMilliseconds specifies the delay before resuming
  347. // a client upgrade download after a failure. If omitted, a default value
  348. // is used. This value is typical overridden for testing.
  349. FetchUpgradeRetryPeriodMilliseconds *int
  350. // EmitBytesTransferred indicates whether to emit periodic notices showing
  351. // bytes sent and received.
  352. EmitBytesTransferred bool
  353. // TrustedCACertificatesFilename specifies a file containing trusted CA
  354. // certs. When set, this toggles use of the trusted CA certs, specified in
  355. // TrustedCACertificatesFilename, for tunneled TLS connections that expect
  356. // server certificates signed with public certificate authorities
  357. // (currently, only upgrade downloads). This option is used with stock Go
  358. // TLS in cases where Go may fail to obtain a list of root CAs from the
  359. // operating system.
  360. TrustedCACertificatesFilename string
  361. // DisablePeriodicSshKeepAlive indicates whether to send an SSH keepalive
  362. // every 1-2 minutes, when the tunnel is idle. If the SSH keepalive times
  363. // out, the tunnel is considered to have failed.
  364. DisablePeriodicSshKeepAlive bool
  365. // DeviceRegion is the optional, reported region the host device is
  366. // running in. This input value should be a ISO 3166-1 alpha-2 country
  367. // code. The device region is reported to the server in the connected
  368. // request and recorded for Psiphon stats.
  369. //
  370. // When provided, this value may be used, pre-connection, to select
  371. // performance or circumvention optimization strategies for the given
  372. // region.
  373. DeviceRegion string
  374. // EmitDiagnosticNotices indicates whether to output notices containing
  375. // detailed information about the Psiphon session. As these notices may
  376. // contain sensitive network information, they should not be insecurely
  377. // distributed or displayed to users. Default is off.
  378. EmitDiagnosticNotices bool
  379. // RateLimits specify throttling configuration for the tunnel.
  380. RateLimits common.RateLimits
  381. // EmitSLOKs indicates whether to emit notices for each seeded SLOK. As
  382. // this could reveal user browsing activity, it's intended for debugging
  383. // and testing only.
  384. EmitSLOKs bool
  385. // PacketTunnelTunDeviceFileDescriptor specifies a tun device file
  386. // descriptor to use for running a packet tunnel. When this value is > 0,
  387. // a packet tunnel is established through the server and packets are
  388. // relayed via the tun device file descriptor. The file descriptor is
  389. // duped in NewController. When PacketTunnelTunDeviceFileDescriptor is
  390. // set, TunnelPoolSize must be 1.
  391. PacketTunnelTunFileDescriptor int
  392. // SessionID specifies a client session ID to use in the Psiphon API. The
  393. // session ID should be a randomly generated value that is used only for a
  394. // single session, which is defined as the period between a user starting
  395. // a Psiphon client and stopping the client.
  396. //
  397. // A session ID must be 32 hex digits (lower case). When blank, a random
  398. // session ID is automatically generated. Supply a session ID when a
  399. // single client session will cross multiple Controller instances.
  400. SessionID string
  401. // Authorizations is a list of encoded, signed access control
  402. // authorizations that the client has obtained and will present to the
  403. // server.
  404. Authorizations []string
  405. // UseFragmentor and associated Fragmentor fields are for testing
  406. // purposes.
  407. UseFragmentor string
  408. FragmentorMinTotalBytes *int
  409. FragmentorMaxTotalBytes *int
  410. FragmentorMinWriteBytes *int
  411. FragmentorMaxWriteBytes *int
  412. FragmentorMinDelayMicroseconds *int
  413. FragmentorMaxDelayMicroseconds *int
  414. // ObfuscatedSSHAlgorithms and associated ObfuscatedSSH fields are for
  415. // testing purposes. If specified, ObfuscatedSSHAlgorithms must have 4 SSH
  416. // KEX elements in order: the kex algorithm, cipher, MAC, and server host
  417. // key algorithm.
  418. ObfuscatedSSHAlgorithms []string
  419. ObfuscatedSSHMinPadding *int
  420. ObfuscatedSSHMaxPadding *int
  421. // LivenessTestMinUpstreamBytes and other LivenessTest fields are for
  422. // testing purposes.
  423. LivenessTestMinUpstreamBytes *int
  424. LivenessTestMaxUpstreamBytes *int
  425. LivenessTestMinDownstreamBytes *int
  426. LivenessTestMaxDownstreamBytes *int
  427. // clientParameters is the active ClientParameters with defaults, config
  428. // values, and, optionally, tactics applied.
  429. //
  430. // New tactics must be applied by calling Config.SetClientParameters;
  431. // calling clientParameters.Set directly will fail to add config values.
  432. clientParameters *parameters.ClientParameters
  433. dynamicConfigMutex sync.Mutex
  434. sponsorID string
  435. authorizations []string
  436. deviceBinder DeviceBinder
  437. networkIDGetter NetworkIDGetter
  438. committed bool
  439. }
  440. // LoadConfig parses a JSON format Psiphon config JSON string and returns a
  441. // Config struct populated with config values.
  442. //
  443. // The Config struct may then be programmatically populated with additional
  444. // values, including callbacks such as DeviceBinder.
  445. //
  446. // Before using the Config, Commit must be called, which will perform further
  447. // validation and initialize internal data structures.
  448. func LoadConfig(configJson []byte) (*Config, error) {
  449. var config Config
  450. err := json.Unmarshal(configJson, &config)
  451. if err != nil {
  452. return nil, common.ContextError(err)
  453. }
  454. return &config, nil
  455. }
  456. // IsCommitted checks if Commit was called.
  457. func (config *Config) IsCommitted() bool {
  458. return config.committed
  459. }
  460. // Commit validates Config fields finalizes initialization.
  461. //
  462. // Config fields should not be set after calling Config, as any changes may
  463. // not be reflected in internal data structures.
  464. func (config *Config) Commit() error {
  465. // Do SetEmitDiagnosticNotices first, to ensure config file errors are emitted.
  466. if config.EmitDiagnosticNotices {
  467. SetEmitDiagnosticNotices(true)
  468. }
  469. // Promote legacy fields.
  470. if config.CustomHeaders == nil {
  471. config.CustomHeaders = config.UpstreamProxyCustomHeaders
  472. config.UpstreamProxyCustomHeaders = nil
  473. }
  474. if config.RemoteServerListUrl != "" && config.RemoteServerListURLs == nil {
  475. config.RemoteServerListURLs = promoteLegacyDownloadURL(config.RemoteServerListUrl)
  476. }
  477. if config.ObfuscatedServerListRootURL != "" && config.ObfuscatedServerListRootURLs == nil {
  478. config.ObfuscatedServerListRootURLs = promoteLegacyDownloadURL(config.ObfuscatedServerListRootURL)
  479. }
  480. if config.UpgradeDownloadUrl != "" && config.UpgradeDownloadURLs == nil {
  481. config.UpgradeDownloadURLs = promoteLegacyDownloadURL(config.UpgradeDownloadUrl)
  482. }
  483. // Supply default values.
  484. if config.DataStoreDirectory == "" {
  485. wd, err := os.Getwd()
  486. if err != nil {
  487. return common.ContextError(err)
  488. }
  489. config.DataStoreDirectory = wd
  490. }
  491. if config.ClientVersion == "" {
  492. config.ClientVersion = "0"
  493. }
  494. if config.TunnelPoolSize == 0 {
  495. config.TunnelPoolSize = TUNNEL_POOL_SIZE
  496. }
  497. // Validate config fields.
  498. if config.PropagationChannelId == "" {
  499. return common.ContextError(
  500. errors.New("propagation channel ID is missing from the configuration file"))
  501. }
  502. if config.SponsorId == "" {
  503. return common.ContextError(
  504. errors.New("sponsor ID is missing from the configuration file"))
  505. }
  506. _, err := strconv.Atoi(config.ClientVersion)
  507. if err != nil {
  508. return common.ContextError(
  509. fmt.Errorf("invalid client version: %s", err))
  510. }
  511. if !common.Contains(
  512. []string{"", protocol.PSIPHON_SSH_API_PROTOCOL, protocol.PSIPHON_WEB_API_PROTOCOL},
  513. config.TargetApiProtocol) {
  514. return common.ContextError(
  515. errors.New("invalid TargetApiProtocol"))
  516. }
  517. if !config.DisableRemoteServerListFetcher {
  518. if config.RemoteServerListURLs != nil {
  519. if config.RemoteServerListSignaturePublicKey == "" {
  520. return common.ContextError(errors.New("missing RemoteServerListSignaturePublicKey"))
  521. }
  522. if config.RemoteServerListDownloadFilename == "" {
  523. return common.ContextError(errors.New("missing RemoteServerListDownloadFilename"))
  524. }
  525. }
  526. if config.ObfuscatedServerListRootURLs != nil {
  527. if config.RemoteServerListSignaturePublicKey == "" {
  528. return common.ContextError(errors.New("missing RemoteServerListSignaturePublicKey"))
  529. }
  530. if config.ObfuscatedServerListDownloadDirectory == "" {
  531. return common.ContextError(errors.New("missing ObfuscatedServerListDownloadDirectory"))
  532. }
  533. }
  534. }
  535. if config.SplitTunnelRoutesURLFormat != "" {
  536. if config.SplitTunnelRoutesSignaturePublicKey == "" {
  537. return common.ContextError(errors.New("missing SplitTunnelRoutesSignaturePublicKey"))
  538. }
  539. if config.SplitTunnelDNSServer == "" {
  540. return common.ContextError(errors.New("missing SplitTunnelDNSServer"))
  541. }
  542. }
  543. if config.UpgradeDownloadURLs != nil {
  544. if config.UpgradeDownloadClientVersionHeader == "" {
  545. return common.ContextError(errors.New("missing UpgradeDownloadClientVersionHeader"))
  546. }
  547. if config.UpgradeDownloadFilename == "" {
  548. return common.ContextError(errors.New("missing UpgradeDownloadFilename"))
  549. }
  550. }
  551. // This constraint is expected by logic in Controller.runTunnels().
  552. if config.PacketTunnelTunFileDescriptor > 0 && config.TunnelPoolSize != 1 {
  553. return common.ContextError(errors.New("packet tunnel mode requires TunnelPoolSize to be 1"))
  554. }
  555. // SessionID must be PSIPHON_API_CLIENT_SESSION_ID_LENGTH lowercase hex-encoded bytes.
  556. if config.SessionID == "" {
  557. sessionID, err := MakeSessionId()
  558. if err != nil {
  559. return common.ContextError(err)
  560. }
  561. config.SessionID = sessionID
  562. }
  563. if len(config.SessionID) != 2*protocol.PSIPHON_API_CLIENT_SESSION_ID_LENGTH ||
  564. -1 != strings.IndexFunc(config.SessionID, func(c rune) bool {
  565. return !unicode.Is(unicode.ASCII_Hex_Digit, c) || unicode.IsUpper(c)
  566. }) {
  567. return common.ContextError(errors.New("invalid SessionID"))
  568. }
  569. config.clientParameters, err = parameters.NewClientParameters(
  570. func(err error) {
  571. NoticeAlert("ClientParameters getValue failed: %s", err)
  572. })
  573. if err != nil {
  574. return common.ContextError(err)
  575. }
  576. if config.ObfuscatedSSHAlgorithms != nil &&
  577. len(config.ObfuscatedSSHAlgorithms) != 4 {
  578. // TODO: validate each algorithm?
  579. return common.ContextError(errors.New("invalid ObfuscatedSSHAlgorithms"))
  580. }
  581. // clientParameters.Set will validate the config fields applied to parameters.
  582. err = config.SetClientParameters("", false, nil)
  583. if err != nil {
  584. return common.ContextError(err)
  585. }
  586. // Set defaults for dynamic config fields.
  587. config.SetDynamicConfig(config.SponsorId, config.Authorizations)
  588. // Initialize config.deviceBinder and config.config.networkIDGetter. These
  589. // wrap config.DeviceBinder and config.NetworkIDGetter/NetworkID with
  590. // loggers.
  591. //
  592. // New variables are set to avoid mutating input config fields.
  593. // Internally, code must use config.deviceBinder and
  594. // config.networkIDGetter and not the input/exported fields.
  595. if config.DeviceBinder != nil {
  596. config.deviceBinder = &loggingDeviceBinder{config.DeviceBinder}
  597. }
  598. networkIDGetter := config.NetworkIDGetter
  599. if networkIDGetter == nil && config.NetworkID != "" {
  600. // Enable tactics when a NetworkID is specified
  601. //
  602. // Limitation: unlike NetworkIDGetter, which calls back to platform APIs
  603. // this method of network identification is not dynamic and will not reflect
  604. // network changes that occur while running.
  605. networkIDGetter = newStaticNetworkGetter(config.NetworkID)
  606. }
  607. if networkIDGetter != nil {
  608. config.networkIDGetter = &loggingNetworkIDGetter{networkIDGetter}
  609. }
  610. config.committed = true
  611. return nil
  612. }
  613. // GetClientParameters returns a snapshot of the current client parameters.
  614. func (config *Config) GetClientParameters() *parameters.ClientParametersSnapshot {
  615. return config.clientParameters.Get()
  616. }
  617. // SetClientParameters resets Config.clientParameters to the default values,
  618. // applies any config file values, and then applies the input parameters (from
  619. // tactics, etc.)
  620. //
  621. // Set skipOnError to false when initially applying only config values, as
  622. // this will validate the values and should fail. Set skipOnError to true when
  623. // applying tactics to ignore invalid or unknown parameter values from tactics.
  624. //
  625. // In the case of applying tactics, do not call Config.clientParameters.Set
  626. // directly as this will not first apply config values.
  627. //
  628. // If there is an error, the existing Config.clientParameters are left
  629. // entirely unmodified.
  630. func (config *Config) SetClientParameters(tag string, skipOnError bool, applyParameters map[string]interface{}) error {
  631. setParameters := []map[string]interface{}{config.makeConfigParameters()}
  632. if applyParameters != nil {
  633. setParameters = append(setParameters, applyParameters)
  634. }
  635. counts, err := config.clientParameters.Set(tag, skipOnError, setParameters...)
  636. if err != nil {
  637. return common.ContextError(err)
  638. }
  639. NoticeInfo("applied %v parameters with tag '%s'", counts, tag)
  640. // Emit certain individual parameter values for quick reference in diagnostics.
  641. networkLatencyMultiplier := config.clientParameters.Get().Float(parameters.NetworkLatencyMultiplier)
  642. if networkLatencyMultiplier != 0.0 {
  643. NoticeInfo(
  644. "NetworkLatencyMultiplier: %f",
  645. config.clientParameters.Get().Float(parameters.NetworkLatencyMultiplier))
  646. }
  647. return nil
  648. }
  649. // SetDynamicConfig sets the current client sponsor ID and authorizations.
  650. // Invalid values for sponsor ID are ignored. The caller must not modify the
  651. // input authorizations slice.
  652. func (config *Config) SetDynamicConfig(sponsorID string, authorizations []string) {
  653. config.dynamicConfigMutex.Lock()
  654. defer config.dynamicConfigMutex.Unlock()
  655. if sponsorID != "" {
  656. config.sponsorID = sponsorID
  657. }
  658. config.authorizations = authorizations
  659. }
  660. // GetSponsorID returns the current client sponsor ID.
  661. func (config *Config) GetSponsorID() string {
  662. config.dynamicConfigMutex.Lock()
  663. defer config.dynamicConfigMutex.Unlock()
  664. return config.sponsorID
  665. }
  666. // GetAuthorizations returns the current client authorizations.
  667. // The caller must not modify the returned slice.
  668. func (config *Config) GetAuthorizations() []string {
  669. config.dynamicConfigMutex.Lock()
  670. defer config.dynamicConfigMutex.Unlock()
  671. return config.authorizations
  672. }
  673. func (config *Config) UseUpstreamProxy() bool {
  674. return config.UpstreamProxyURL != ""
  675. }
  676. func (config *Config) makeConfigParameters() map[string]interface{} {
  677. // Build set of config values to apply to parameters.
  678. //
  679. // Note: names of some config fields such as
  680. // StaggerConnectionWorkersMilliseconds and LimitMeekBufferSizes have
  681. // changed in the parameters. The existing config fields are retained for
  682. // backwards compatibility.
  683. applyParameters := make(map[string]interface{})
  684. if config.NetworkLatencyMultiplier > 0.0 {
  685. applyParameters[parameters.NetworkLatencyMultiplier] = config.NetworkLatencyMultiplier
  686. }
  687. if len(config.LimitTunnelProtocols) > 0 {
  688. applyParameters[parameters.LimitTunnelProtocols] = protocol.TunnelProtocols(config.LimitTunnelProtocols)
  689. } else if config.TunnelProtocol != "" {
  690. applyParameters[parameters.LimitTunnelProtocols] = protocol.TunnelProtocols{config.TunnelProtocol}
  691. }
  692. if len(config.InitialLimitTunnelProtocols) > 0 && config.InitialLimitTunnelProtocolsCandidateCount > 0 {
  693. applyParameters[parameters.InitialLimitTunnelProtocols] = protocol.TunnelProtocols(config.InitialLimitTunnelProtocols)
  694. applyParameters[parameters.InitialLimitTunnelProtocolsCandidateCount] = config.InitialLimitTunnelProtocolsCandidateCount
  695. }
  696. if len(config.LimitTLSProfiles) > 0 {
  697. applyParameters[parameters.LimitTLSProfiles] = protocol.TunnelProtocols(config.LimitTLSProfiles)
  698. }
  699. if len(config.LimitQUICVersions) > 0 {
  700. applyParameters[parameters.LimitQUICVersions] = protocol.QUICVersions(config.LimitQUICVersions)
  701. }
  702. if config.EstablishTunnelTimeoutSeconds != nil {
  703. applyParameters[parameters.EstablishTunnelTimeout] = fmt.Sprintf("%ds", *config.EstablishTunnelTimeoutSeconds)
  704. }
  705. if config.EstablishTunnelPausePeriodSeconds != nil {
  706. applyParameters[parameters.EstablishTunnelPausePeriod] = fmt.Sprintf("%ds", *config.EstablishTunnelPausePeriodSeconds)
  707. }
  708. if config.ConnectionWorkerPoolSize != 0 {
  709. applyParameters[parameters.ConnectionWorkerPoolSize] = config.ConnectionWorkerPoolSize
  710. }
  711. if config.StaggerConnectionWorkersMilliseconds > 0 {
  712. applyParameters[parameters.StaggerConnectionWorkersPeriod] = fmt.Sprintf("%dms", config.StaggerConnectionWorkersMilliseconds)
  713. }
  714. if config.LimitIntensiveConnectionWorkers > 0 {
  715. applyParameters[parameters.LimitIntensiveConnectionWorkers] = config.LimitIntensiveConnectionWorkers
  716. }
  717. applyParameters[parameters.MeekLimitBufferSizes] = config.LimitMeekBufferSizes
  718. applyParameters[parameters.IgnoreHandshakeStatsRegexps] = config.IgnoreHandshakeStatsRegexps
  719. if config.EstablishTunnelTimeoutSeconds != nil {
  720. applyParameters[parameters.EstablishTunnelTimeout] = fmt.Sprintf("%ds", *config.EstablishTunnelTimeoutSeconds)
  721. }
  722. if config.FetchRemoteServerListRetryPeriodMilliseconds != nil {
  723. applyParameters[parameters.FetchRemoteServerListRetryPeriod] = fmt.Sprintf("%dms", *config.FetchRemoteServerListRetryPeriodMilliseconds)
  724. }
  725. if config.FetchUpgradeRetryPeriodMilliseconds != nil {
  726. applyParameters[parameters.FetchUpgradeRetryPeriod] = fmt.Sprintf("%dms", *config.FetchUpgradeRetryPeriodMilliseconds)
  727. }
  728. switch config.TransformHostNames {
  729. case "always":
  730. applyParameters[parameters.TransformHostNameProbability] = 1.0
  731. case "never":
  732. applyParameters[parameters.TransformHostNameProbability] = 0.0
  733. }
  734. if !config.DisableRemoteServerListFetcher {
  735. if config.RemoteServerListURLs != nil {
  736. applyParameters[parameters.RemoteServerListSignaturePublicKey] = config.RemoteServerListSignaturePublicKey
  737. applyParameters[parameters.RemoteServerListURLs] = config.RemoteServerListURLs
  738. }
  739. if config.ObfuscatedServerListRootURLs != nil {
  740. applyParameters[parameters.RemoteServerListSignaturePublicKey] = config.RemoteServerListSignaturePublicKey
  741. applyParameters[parameters.ObfuscatedServerListRootURLs] = config.ObfuscatedServerListRootURLs
  742. }
  743. }
  744. applyParameters[parameters.SplitTunnelRoutesURLFormat] = config.SplitTunnelRoutesURLFormat
  745. applyParameters[parameters.SplitTunnelRoutesSignaturePublicKey] = config.SplitTunnelRoutesSignaturePublicKey
  746. applyParameters[parameters.SplitTunnelDNSServer] = config.SplitTunnelDNSServer
  747. if config.UpgradeDownloadURLs != nil {
  748. applyParameters[parameters.UpgradeDownloadClientVersionHeader] = config.UpgradeDownloadClientVersionHeader
  749. applyParameters[parameters.UpgradeDownloadURLs] = config.UpgradeDownloadURLs
  750. }
  751. applyParameters[parameters.TunnelRateLimits] = config.RateLimits
  752. switch config.UseFragmentor {
  753. case "always":
  754. applyParameters[parameters.FragmentorProbability] = 1.0
  755. case "never":
  756. applyParameters[parameters.FragmentorProbability] = 0.0
  757. }
  758. if config.FragmentorMinTotalBytes != nil {
  759. applyParameters[parameters.FragmentorMinTotalBytes] = *config.FragmentorMinTotalBytes
  760. }
  761. if config.FragmentorMaxTotalBytes != nil {
  762. applyParameters[parameters.FragmentorMaxTotalBytes] = *config.FragmentorMaxTotalBytes
  763. }
  764. if config.FragmentorMinWriteBytes != nil {
  765. applyParameters[parameters.FragmentorMinWriteBytes] = *config.FragmentorMinWriteBytes
  766. }
  767. if config.FragmentorMaxWriteBytes != nil {
  768. applyParameters[parameters.FragmentorMaxWriteBytes] = *config.FragmentorMaxWriteBytes
  769. }
  770. if config.FragmentorMinDelayMicroseconds != nil {
  771. applyParameters[parameters.FragmentorMinDelay] = fmt.Sprintf("%dus", *config.FragmentorMinDelayMicroseconds)
  772. }
  773. if config.FragmentorMaxDelayMicroseconds != nil {
  774. applyParameters[parameters.FragmentorMaxDelay] = fmt.Sprintf("%dus", *config.FragmentorMaxDelayMicroseconds)
  775. }
  776. if config.ObfuscatedSSHMinPadding != nil {
  777. applyParameters[parameters.ObfuscatedSSHMinPadding] = *config.ObfuscatedSSHMinPadding
  778. }
  779. if config.ObfuscatedSSHMaxPadding != nil {
  780. applyParameters[parameters.ObfuscatedSSHMaxPadding] = *config.ObfuscatedSSHMaxPadding
  781. }
  782. if config.LivenessTestMinUpstreamBytes != nil {
  783. applyParameters[parameters.LivenessTestMinUpstreamBytes] = *config.LivenessTestMinUpstreamBytes
  784. }
  785. if config.LivenessTestMaxUpstreamBytes != nil {
  786. applyParameters[parameters.LivenessTestMaxUpstreamBytes] = *config.LivenessTestMaxUpstreamBytes
  787. }
  788. if config.LivenessTestMinDownstreamBytes != nil {
  789. applyParameters[parameters.LivenessTestMinDownstreamBytes] = *config.LivenessTestMinDownstreamBytes
  790. }
  791. if config.LivenessTestMaxDownstreamBytes != nil {
  792. applyParameters[parameters.LivenessTestMaxDownstreamBytes] = *config.LivenessTestMaxDownstreamBytes
  793. }
  794. return applyParameters
  795. }
  796. func promoteLegacyDownloadURL(URL string) parameters.DownloadURLs {
  797. downloadURLs := make(parameters.DownloadURLs, 1)
  798. downloadURLs[0] = &parameters.DownloadURL{
  799. URL: base64.StdEncoding.EncodeToString([]byte(URL)),
  800. SkipVerify: false,
  801. OnlyAfterAttempts: 0,
  802. }
  803. return downloadURLs
  804. }
  805. type loggingDeviceBinder struct {
  806. d DeviceBinder
  807. }
  808. func newLoggingDeviceBinder(d DeviceBinder) *loggingDeviceBinder {
  809. return &loggingDeviceBinder{d: d}
  810. }
  811. func (d *loggingDeviceBinder) BindToDevice(fileDescriptor int) (string, error) {
  812. deviceInfo, err := d.d.BindToDevice(fileDescriptor)
  813. if err == nil && deviceInfo != "" {
  814. NoticeBindToDevice(deviceInfo)
  815. }
  816. return deviceInfo, err
  817. }
  818. type staticNetworkGetter struct {
  819. networkID string
  820. }
  821. func newStaticNetworkGetter(networkID string) *staticNetworkGetter {
  822. return &staticNetworkGetter{networkID: networkID}
  823. }
  824. func (n *staticNetworkGetter) GetNetworkID() string {
  825. return n.networkID
  826. }
  827. type loggingNetworkIDGetter struct {
  828. n NetworkIDGetter
  829. }
  830. func newLoggingNetworkIDGetter(n NetworkIDGetter) *loggingNetworkIDGetter {
  831. return &loggingNetworkIDGetter{n: n}
  832. }
  833. func (n *loggingNetworkIDGetter) GetNetworkID() string {
  834. networkID := n.n.GetNetworkID()
  835. // All PII must appear after the initial "-"
  836. // See: https://godoc.org/github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon#NetworkIDGetter
  837. logNetworkID := networkID
  838. index := strings.Index(logNetworkID, "-")
  839. if index != -1 {
  840. logNetworkID = logNetworkID[:index]
  841. }
  842. if len(logNetworkID)+1 < len(networkID) {
  843. // Indicate when additional network info was present after the first "-".
  844. logNetworkID += "+<network info>"
  845. }
  846. NoticeNetworkID(logNetworkID)
  847. return networkID
  848. }